Skip to main content

mz_persist_client/
fetch.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//! Fetching batches of data from persist's backing store
11
12use std::fmt::{self, Debug};
13use std::marker::PhantomData;
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17use anyhow::anyhow;
18use arrow::array::{Array, ArrayRef, AsArray, BooleanArray, Int64Array};
19use arrow::compute::FilterBuilder;
20use differential_dataflow::difference::Monoid;
21use differential_dataflow::lattice::Lattice;
22use differential_dataflow::trace::Description;
23use itertools::EitherOrBoth;
24use mz_dyncfg::{Config, ConfigSet, ConfigValHandle, ParameterScope};
25use mz_ore::bytes::SegmentedBytes;
26use mz_ore::cast::CastFrom;
27use mz_ore::halt;
28use mz_ore::metrics::IntCounter;
29use mz_ore::process::halt_with_code;
30use mz_ore::{soft_assert_or_log, soft_panic_no_log, soft_panic_or_log};
31use mz_persist::indexed::columnar::arrow::{realloc_any, realloc_array};
32use mz_persist::indexed::columnar::parquet::BlobTraceBatchPartReader;
33use mz_persist::indexed::columnar::{ColumnarRecords, ColumnarRecordsStructuredExt};
34use mz_persist::indexed::encoding::{BlobTraceBatchPart, BlobTraceUpdates};
35use mz_persist::location::{Blob, SeqNo};
36use mz_persist::metrics::ColumnarMetrics;
37use mz_persist_types::arrow::ArrayOrd;
38use mz_persist_types::columnar::{ColumnDecoder, Schema, data_type};
39use mz_persist_types::part::Codec64Mut;
40use mz_persist_types::schema::backward_compatible;
41use mz_persist_types::stats::PartStats;
42use mz_persist_types::{Codec, Codec64};
43use mz_proto::RustType;
44use serde::{Deserialize, Serialize};
45use timely::PartialOrder;
46use timely::progress::frontier::AntichainRef;
47use timely::progress::{Antichain, Timestamp};
48use tracing::{Instrument, debug, debug_span, trace_span};
49
50use crate::ShardId;
51use crate::cfg::PersistConfig;
52use crate::error::InvalidUsage;
53use crate::internal::apply::Applier;
54use crate::internal::encoding::{LazyInlineBatchPart, LazyPartStats, LazyProto, Schemas};
55use crate::internal::machine::retry_external;
56use crate::internal::metrics::{Metrics, MetricsPermits, ReadMetrics, ShardMetrics};
57use crate::internal::paths::BlobKey;
58use crate::internal::state::{
59    BatchPart, HollowBatchPart, ProtoHollowBatchPart, ProtoInlineBatchPart,
60};
61use crate::read::{LeasedReaderId, READER_LEASE_EXPIRED_EXIT_CODE};
62use crate::schema::{PartMigration, SchemaCache};
63
64pub(crate) const FETCH_SEMAPHORE_COST_ADJUSTMENT: Config<f64> = Config::new(
65    "persist_fetch_semaphore_cost_adjustment",
66    // We use `encoded_size_bytes` as the number of permits, but the parsed size
67    // is larger than the encoded one, so adjust it. This default value is from
68    // eyeballing graphs in experiments that were run on tpch loadgen data.
69    1.2,
70    "\
71    An adjustment multiplied by encoded_size_bytes to approximate an upper \
72    bound on the size in lgalloc, which includes the decoded version.",
73    ParameterScope::Environment,
74);
75
76pub(crate) const FETCH_SEMAPHORE_PERMIT_ADJUSTMENT: Config<f64> = Config::new(
77    "persist_fetch_semaphore_permit_adjustment",
78    1.0,
79    "\
80    A limit on the number of outstanding persist bytes being fetched and \
81    parsed, expressed as a multiplier of the process's memory limit. This data \
82    all spills to lgalloc, so values > 1.0 are safe. Only applied to cc \
83    replicas.",
84    ParameterScope::Environment,
85);
86
87pub(crate) const PART_DECODE_FORMAT: Config<&'static str> = Config::new(
88    "persist_part_decode_format",
89    PartDecodeFormat::default().as_str(),
90    "\
91    Format we'll use to decode a Persist Part, either 'row', \
92    'row_with_validate', or 'arrow' (Materialize).",
93    ParameterScope::Environment,
94);
95
96pub(crate) const PART_DECODE_BATCH_ROWS: Config<Option<usize>> = Config::new(
97    "persist_part_decode_batch_rows",
98    Some(16384),
99    "\
100    Maximum number of rows of a fetched blob part that a reader decodes at \
101    once. Unset decodes the whole part at once.",
102    ParameterScope::Environment,
103);
104
105pub(crate) const OPTIMIZE_IGNORED_DATA_FETCH: Config<bool> = Config::new(
106    "persist_optimize_ignored_data_fetch",
107    true,
108    "CYA to allow opt-out of a performance optimization to skip fetching ignored data",
109    ParameterScope::Environment,
110);
111
112pub(crate) const VALIDATE_PART_BOUNDS_ON_READ: Config<bool> = Config::new(
113    "persist_validate_part_bounds_on_read",
114    false,
115    "Validate the part lower <= the batch lower and the part upper <= batch upper,\
116    for the batch containing that part",
117    ParameterScope::Environment,
118);
119
120#[derive(Debug, Clone)]
121pub(crate) struct FetchConfig {
122    pub(crate) validate_bounds_on_read: bool,
123    /// See [`PART_DECODE_BATCH_ROWS`]. Only consulted by readers that decode
124    /// through [`FetchedPart`].
125    pub(crate) part_decode_batch_rows: Option<usize>,
126}
127
128impl FetchConfig {
129    pub fn from_persist_config(cfg: &PersistConfig) -> Self {
130        Self {
131            validate_bounds_on_read: VALIDATE_PART_BOUNDS_ON_READ.get(cfg),
132            part_decode_batch_rows: PART_DECODE_BATCH_ROWS.get(cfg),
133        }
134    }
135}
136
137#[derive(Debug, Clone)]
138pub(crate) struct BatchFetcherConfig {
139    pub(crate) part_decode_format: ConfigValHandle<String>,
140    pub(crate) validate_bounds_on_read: ConfigValHandle<bool>,
141    pub(crate) part_decode_batch_rows: ConfigValHandle<Option<usize>>,
142}
143
144impl BatchFetcherConfig {
145    pub fn new(value: &PersistConfig) -> Self {
146        Self {
147            part_decode_format: PART_DECODE_FORMAT.handle(value),
148            validate_bounds_on_read: VALIDATE_PART_BOUNDS_ON_READ.handle(value),
149            part_decode_batch_rows: PART_DECODE_BATCH_ROWS.handle(value),
150        }
151    }
152
153    pub fn part_decode_format(&self) -> PartDecodeFormat {
154        PartDecodeFormat::from_str(self.part_decode_format.get().as_str())
155    }
156
157    /// The [`FetchConfig`] with values read at call time.
158    pub fn fetch_config(&self) -> FetchConfig {
159        FetchConfig {
160            validate_bounds_on_read: self.validate_bounds_on_read.get(),
161            part_decode_batch_rows: self.part_decode_batch_rows.get(),
162        }
163    }
164}
165
166/// Capable of fetching [`LeasedBatchPart`] while not holding any capabilities.
167#[derive(Debug)]
168pub struct BatchFetcher<K, V, T, D>
169where
170    T: Timestamp + Lattice + Codec64,
171    // These are only here so we can use them in the auto-expiring `Drop` impl.
172    K: Debug + Codec,
173    V: Debug + Codec,
174    D: Monoid + Codec64 + Send + Sync,
175{
176    pub(crate) cfg: BatchFetcherConfig,
177    pub(crate) blob: Arc<dyn Blob>,
178    pub(crate) metrics: Arc<Metrics>,
179    pub(crate) shard_metrics: Arc<ShardMetrics>,
180    pub(crate) shard_id: ShardId,
181    pub(crate) read_schemas: Schemas<K, V>,
182    pub(crate) schema_cache: SchemaCache<K, V, T, D>,
183    pub(crate) is_transient: bool,
184
185    // Ensures that `BatchFetcher` is of the same type as the `ReadHandle` it's
186    // derived from.
187    pub(crate) _phantom: PhantomData<fn() -> (K, V, T, D)>,
188}
189
190// Hand-written (rather than derived) so cloning does not require `K: Clone`
191// etc.: every field is an `Arc` or independently `Clone`. The `schema_cache`
192// clone shares the schema-lookup maps and applier, so clones reuse cached
193// schema fetches and only duplicate a small per-clone migration memo. Used to
194// run several `fetch_leased_part` calls concurrently, each on its own clone.
195impl<K, V, T, D> Clone for BatchFetcher<K, V, T, D>
196where
197    T: Timestamp + Lattice + Codec64,
198    K: Debug + Codec,
199    V: Debug + Codec,
200    D: Monoid + Codec64 + Send + Sync,
201{
202    fn clone(&self) -> Self {
203        Self {
204            cfg: self.cfg.clone(),
205            blob: Arc::clone(&self.blob),
206            metrics: Arc::clone(&self.metrics),
207            shard_metrics: Arc::clone(&self.shard_metrics),
208            shard_id: self.shard_id.clone(),
209            read_schemas: self.read_schemas.clone(),
210            schema_cache: self.schema_cache.clone(),
211            is_transient: self.is_transient,
212            _phantom: PhantomData,
213        }
214    }
215}
216
217impl<K, V, T, D> BatchFetcher<K, V, T, D>
218where
219    K: Debug + Codec,
220    V: Debug + Codec,
221    T: Timestamp + Lattice + Codec64 + Sync,
222    D: Monoid + Codec64 + Send + Sync,
223{
224    /// Trade in an exchange-able [LeasedBatchPart] for the data it represents.
225    ///
226    /// Note to check the `LeasedBatchPart` documentation for how to handle the
227    /// returned value.
228    pub async fn fetch_leased_part(
229        &mut self,
230        part: ExchangeableBatchPart<T>,
231    ) -> Result<Result<FetchedBlob<K, V, T, D>, BlobKey>, InvalidUsage<T>> {
232        let ExchangeableBatchPart {
233            shard_id,
234            encoded_size_bytes: _,
235            desc,
236            filter,
237            filter_pushdown_audit,
238            part,
239            reader_id: _,
240        } = part;
241        let part: BatchPart<T> = part.decode_to().expect("valid part");
242        if shard_id != self.shard_id {
243            return Err(InvalidUsage::BatchNotFromThisShard {
244                batch_shard: shard_id,
245                handle_shard: self.shard_id.clone(),
246            });
247        }
248
249        let migration =
250            PartMigration::new(&part, self.read_schemas.clone(), &mut self.schema_cache)
251                .await
252                .unwrap_or_else(|read_schemas| {
253                    panic!(
254                        "could not decode part {:?} with schema: {:?}",
255                        part.schema_id(),
256                        read_schemas
257                    )
258                });
259
260        let (buf, fetch_permit) = match &part {
261            BatchPart::Hollow(x) => {
262                let fetch_permit = self
263                    .metrics
264                    .semaphore
265                    .acquire_fetch_permits(x.encoded_size_bytes)
266                    .await;
267                let read_metrics = if self.is_transient {
268                    &self.metrics.read.unindexed
269                } else {
270                    &self.metrics.read.batch_fetcher
271                };
272                let buf = fetch_batch_part_blob(
273                    &shard_id,
274                    self.blob.as_ref(),
275                    &self.metrics,
276                    &self.shard_metrics,
277                    read_metrics,
278                    x,
279                )
280                .await;
281                let buf = match buf {
282                    Ok(buf) => buf,
283                    Err(key) => return Ok(Err(key)),
284                };
285                let buf = FetchedBlobBuf::Hollow {
286                    buf,
287                    part: x.clone(),
288                };
289                (buf, Some(Arc::new(fetch_permit)))
290            }
291            BatchPart::Inline {
292                updates,
293                ts_rewrite,
294                ..
295            } => {
296                let buf = FetchedBlobBuf::Inline {
297                    desc: desc.clone(),
298                    updates: updates.clone(),
299                    ts_rewrite: ts_rewrite.clone(),
300                };
301                (buf, None)
302            }
303        };
304        let fetched_blob = FetchedBlob {
305            metrics: Arc::clone(&self.metrics),
306            read_metrics: self.metrics.read.batch_fetcher.clone(),
307            buf,
308            registered_desc: desc.clone(),
309            migration,
310            filter: filter.clone(),
311            filter_pushdown_audit,
312            structured_part_audit: self.cfg.part_decode_format(),
313            fetch_permit,
314            _phantom: PhantomData,
315            fetch_config: self.cfg.fetch_config(),
316        };
317        Ok(Ok(fetched_blob))
318    }
319
320    /// Diagnoses a missing-blob fetch failure for a part leased by the given
321    /// reader. See the free function `missing_blob_diagnostics`.
322    pub async fn missing_blob_diagnostics(
323        &self,
324        reader_id: &LeasedReaderId,
325    ) -> MissingBlobDiagnosis {
326        missing_blob_diagnostics(self.schema_cache.applier(), reader_id.clone()).await
327    }
328}
329
330/// How long [missing_blob_diagnostics] waits to refresh state.
331const MISSING_BLOB_DIAGNOSIS_TIMEOUT: Duration = Duration::from_secs(30);
332
333/// The result of [BatchFetcher::missing_blob_diagnostics].
334#[derive(Debug)]
335pub enum MissingBlobDiagnosis {
336    /// The reader has been expired out of state, so its lease was lost.
337    LeaseExpired {
338        /// The reader that leased the part.
339        reader_id: LeasedReaderId,
340    },
341    /// The shard was tombstoned, which removes every reader. Not a lost lease.
342    ShardTombstoned {
343        /// The reader that leased the part.
344        reader_id: LeasedReaderId,
345    },
346    /// The reader is still in state, so its hold did not protect the blob.
347    LeasePresent {
348        /// The reader that leased the part.
349        reader_id: LeasedReaderId,
350        /// The reader's lease state, for the error message.
351        lease_state: String,
352    },
353    /// State could not be refreshed in time to tell.
354    Unknown {
355        /// The reader that leased the part.
356        reader_id: LeasedReaderId,
357    },
358}
359
360/// How a fetch that found its part's blob missing should fail.
361#[derive(Debug)]
362pub(crate) enum MissingBlobExit {
363    /// Halt with [READER_LEASE_EXPIRED_EXIT_CODE].
364    LeaseExpired,
365    /// Halt: the shard was tombstoned.
366    Halt,
367    /// Panic: a GC or lease bug, so it reaches Sentry.
368    Panic,
369}
370
371impl MissingBlobDiagnosis {
372    /// Classifies this diagnosis. Counts a lost lease in `expired_live_read`.
373    pub(crate) fn exit(&self, expired_live_read: &IntCounter) -> MissingBlobExit {
374        match self {
375            MissingBlobDiagnosis::LeaseExpired { .. } => {
376                expired_live_read.inc();
377                MissingBlobExit::LeaseExpired
378            }
379            MissingBlobDiagnosis::ShardTombstoned { .. } => MissingBlobExit::Halt,
380            // `Unknown` means the state refresh timed out, for example because this
381            // process is partitioned from consensus. That can also cost the lease,
382            // but we can't confirm it here, so it is classed as a bug.
383            MissingBlobDiagnosis::LeasePresent { .. } | MissingBlobDiagnosis::Unknown { .. } => {
384                MissingBlobExit::Panic
385            }
386        }
387    }
388}
389
390impl fmt::Display for MissingBlobDiagnosis {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        match self {
393            MissingBlobDiagnosis::LeaseExpired { reader_id } => write!(
394                f,
395                "reader {reader_id} has been expired out of state; \
396                 the process likely failed to heartbeat it within the lease duration \
397                 (machine sleep, CPU/memory starvation, or a partition from consensus?)"
398            ),
399            MissingBlobDiagnosis::ShardTombstoned { reader_id } => write!(
400                f,
401                "reader {reader_id}: the shard has been tombstoned, which removes every reader"
402            ),
403            MissingBlobDiagnosis::LeasePresent {
404                reader_id,
405                lease_state,
406            } => write!(
407                f,
408                "reader {reader_id} is still present in state ({lease_state}); \
409                 a missing blob despite a live lease indicates a GC bug"
410            ),
411            MissingBlobDiagnosis::Unknown { reader_id } => write!(
412                f,
413                "reader {reader_id}: could not refresh state within {}s to diagnose the lease; \
414                 partitioned from consensus?",
415                MISSING_BLOB_DIAGNOSIS_TIMEOUT.as_secs()
416            ),
417        }
418    }
419}
420
421/// Diagnoses a missing-blob fetch failure: refreshes the shard state and
422/// reports whether the reader that leased the part is still present in it.
423///
424/// A missing blob means garbage collection deleted a blob that the part's
425/// lease (a seqno hold in shard state) should have protected. See
426/// [MissingBlobDiagnosis] for what each outcome means.
427pub(crate) async fn missing_blob_diagnostics<K, V, T, D>(
428    applier: &Applier<K, V, T, D>,
429    reader_id: LeasedReaderId,
430) -> MissingBlobDiagnosis
431where
432    K: Debug + Codec,
433    V: Debug + Codec,
434    T: Timestamp + Lattice + Codec64 + Sync,
435    D: Monoid + Codec64,
436{
437    // Refreshing state talks to consensus; this runs on an already-fatal path
438    // and a partition from consensus may be the very reason the lease was
439    // lost, so don't let the diagnosis block the restart indefinitely.
440    let refresh = applier.fetch_and_update_state(None);
441    if tokio::time::timeout(MISSING_BLOB_DIAGNOSIS_TIMEOUT, refresh)
442        .await
443        .is_err()
444    {
445        return MissingBlobDiagnosis::Unknown { reader_id };
446    }
447    if applier.is_tombstone() {
448        return MissingBlobDiagnosis::ShardTombstoned { reader_id };
449    }
450    match applier.reader_lease(reader_id.clone()) {
451        Some(lease_state) => MissingBlobDiagnosis::LeasePresent {
452            reader_id,
453            lease_state: format!("{lease_state:?}"),
454        },
455        None => MissingBlobDiagnosis::LeaseExpired { reader_id },
456    }
457}
458
459#[derive(Debug, Clone, Serialize, Deserialize)]
460pub(crate) enum FetchBatchFilter<T> {
461    Snapshot {
462        as_of: Antichain<T>,
463    },
464    Listen {
465        as_of: Antichain<T>,
466        lower: Antichain<T>,
467    },
468    Compaction {
469        since: Antichain<T>,
470    },
471}
472
473impl<T: Timestamp + Lattice> FetchBatchFilter<T> {
474    pub(crate) fn filter_ts(&self, t: &mut T) -> bool {
475        match self {
476            FetchBatchFilter::Snapshot { as_of } => {
477                // This time is covered by a listen
478                if as_of.less_than(t) {
479                    return false;
480                }
481                t.advance_by(as_of.borrow());
482                true
483            }
484            FetchBatchFilter::Listen { as_of, lower } => {
485                // This time is covered by a snapshot
486                if !as_of.less_than(t) {
487                    return false;
488                }
489
490                // Because of compaction, the next batch we get might also
491                // contain updates we've already emitted. For example, we
492                // emitted `[1, 2)` and then compaction combined that batch with
493                // a `[2, 3)` batch into a new `[1, 3)` batch. If this happens,
494                // we just need to filter out anything < the frontier. This
495                // frontier was the upper of the last batch (and thus exclusive)
496                // so for the == case, we still emit.
497                if !lower.less_equal(t) {
498                    return false;
499                }
500                true
501            }
502            FetchBatchFilter::Compaction { since } => {
503                t.advance_by(since.borrow());
504                true
505            }
506        }
507    }
508}
509
510/// Trade in an exchange-able [LeasedBatchPart] for the data it represents.
511///
512/// Note to check the `LeasedBatchPart` documentation for how to handle the
513/// returned value.
514pub(crate) async fn fetch_leased_part<K, V, T, D>(
515    cfg: &PersistConfig,
516    part: &LeasedBatchPart<T>,
517    blob: &dyn Blob,
518    metrics: Arc<Metrics>,
519    read_metrics: &ReadMetrics,
520    shard_metrics: &ShardMetrics,
521    reader_id: &LeasedReaderId,
522    read_schemas: Schemas<K, V>,
523    schema_cache: &mut SchemaCache<K, V, T, D>,
524) -> FetchedPart<K, V, T, D>
525where
526    K: Debug + Codec,
527    V: Debug + Codec,
528    T: Timestamp + Lattice + Codec64 + Sync,
529    D: Monoid + Codec64 + Send + Sync,
530{
531    let fetch_config = FetchConfig::from_persist_config(cfg);
532    let fetched = match &part.part {
533        BatchPart::Hollow(x) => fetch_batch_part_blob(
534            &part.shard_id,
535            blob,
536            &metrics,
537            shard_metrics,
538            read_metrics,
539            x,
540        )
541        .await
542        .map(|buf| {
543            PartSource::from_hollow_blob(
544                &fetch_config,
545                &metrics,
546                read_metrics,
547                part.desc.clone(),
548                x,
549                &buf,
550            )
551        }),
552        BatchPart::Inline {
553            updates,
554            ts_rewrite,
555            ..
556        } => Ok(PartSource::Whole(EncodedPart::from_inline(
557            &fetch_config,
558            &metrics,
559            read_metrics.clone(),
560            part.desc.clone(),
561            updates,
562            ts_rewrite.as_ref(),
563        ))),
564    };
565    let source = match fetched {
566        Ok(x) => x,
567        Err(blob_key) => {
568            // Ideally, readers should never encounter a missing blob. They place a seqno
569            // hold as they consume their snapshot/listen, preventing any blobs they need
570            // from being deleted by garbage collection, and all blob implementations are
571            // linearizable so there should be no possibility of stale reads.
572            //
573            // So a missing blob means a lost lease or a bug. Callers have no error channel, so exit.
574            let diagnosis =
575                missing_blob_diagnostics(schema_cache.applier(), reader_id.clone()).await;
576            let message = format_args!("could not fetch batch part {blob_key}: {diagnosis}");
577            match diagnosis.exit(&metrics.lease.expired_live_read) {
578                MissingBlobExit::LeaseExpired => {
579                    halt_with_code(READER_LEASE_EXPIRED_EXIT_CODE, message)
580                }
581                MissingBlobExit::Halt => halt!("{message}"),
582                MissingBlobExit::Panic => panic!("{message}"),
583            }
584        }
585    };
586    let part_cfg = BatchFetcherConfig::new(cfg);
587    let migration = PartMigration::new(&part.part, read_schemas, schema_cache)
588        .await
589        .unwrap_or_else(|read_schemas| {
590            panic!(
591                "could not decode part {:?} with schema: {:?}",
592                part.part.schema_id(),
593                read_schemas
594            )
595        });
596    FetchedPart::new(
597        metrics,
598        source,
599        migration,
600        part.filter.clone(),
601        part.filter_pushdown_audit,
602        part_cfg.part_decode_format(),
603        part.part.stats(),
604    )
605}
606
607pub(crate) async fn fetch_batch_part_blob<T>(
608    shard_id: &ShardId,
609    blob: &dyn Blob,
610    metrics: &Metrics,
611    shard_metrics: &ShardMetrics,
612    read_metrics: &ReadMetrics,
613    part: &HollowBatchPart<T>,
614) -> Result<SegmentedBytes, BlobKey> {
615    let now = Instant::now();
616    let get_span = debug_span!("fetch_batch::get");
617    let blob_key = part.key.complete(shard_id);
618    let value = retry_external(&metrics.retries.external.fetch_batch_get, || async {
619        shard_metrics.blob_gets.inc();
620        // Name the blob in the error. A GET stuck retrying forever surfaces only in the retry log
621        // (see `retry_external`), which prints the error, so without this the log cannot say which
622        // blob, and thus which shard, is wedged.
623        blob.get(&blob_key)
624            .await
625            .map_err(|err| err.context(format!("blob {blob_key}")))
626    })
627    .instrument(get_span.clone())
628    .await
629    .ok_or(blob_key)?;
630
631    drop(get_span);
632
633    read_metrics.part_count.inc();
634    read_metrics.part_bytes.inc_by(u64::cast_from(value.len()));
635    read_metrics.seconds.inc_by(now.elapsed().as_secs_f64());
636
637    Ok(value)
638}
639
640pub(crate) fn decode_batch_part_blob<T>(
641    cfg: &FetchConfig,
642    metrics: &Metrics,
643    read_metrics: &ReadMetrics,
644    registered_desc: Description<T>,
645    part: &HollowBatchPart<T>,
646    buf: &SegmentedBytes,
647) -> EncodedPart<T>
648where
649    T: Timestamp + Lattice + Codec64,
650{
651    trace_span!("fetch_batch::decode").in_scope(|| {
652        let parsed = metrics
653            .codecs
654            .batch
655            .decode(|| BlobTraceBatchPart::decode(buf, &metrics.columnar))
656            .map_err(|err| anyhow!("couldn't decode batch at key {}: {}", part.key, err))
657            // We received a State that we couldn't decode. This could happen if
658            // persist messes up backward/forward compatibility, if the durable
659            // data was corrupted, or if operations messes up deployment. In any
660            // case, fail loudly.
661            .expect("internal error: invalid encoded state");
662        read_metrics
663            .part_goodbytes
664            .inc_by(u64::cast_from(parsed.updates.goodbytes()));
665        EncodedPart::from_hollow(cfg, read_metrics.clone(), registered_desc, part, parsed)
666    })
667}
668
669pub(crate) async fn fetch_batch_part<T>(
670    cfg: &FetchConfig,
671    shard_id: &ShardId,
672    blob: &dyn Blob,
673    metrics: &Metrics,
674    shard_metrics: &ShardMetrics,
675    read_metrics: &ReadMetrics,
676    registered_desc: &Description<T>,
677    part: &HollowBatchPart<T>,
678) -> Result<EncodedPart<T>, BlobKey>
679where
680    T: Timestamp + Lattice + Codec64,
681{
682    let buf =
683        fetch_batch_part_blob(shard_id, blob, metrics, shard_metrics, read_metrics, part).await?;
684    let part = decode_batch_part_blob(
685        cfg,
686        metrics,
687        read_metrics,
688        registered_desc.clone(),
689        part,
690        &buf,
691    );
692    Ok(part)
693}
694
695/// This represents the lease of a seqno. It's generally paired with some external state,
696/// like a hollow part: holding this lease indicates that we may still want to fetch that part,
697/// and should hold back GC to keep it around.
698///
699/// Generally the state and lease are bundled together, as in [LeasedBatchPart]... but sometimes
700/// it's necessary to handle them separately, so this struct is exposed as well. Handle with care.
701#[derive(Clone, Debug)]
702pub struct Lease(Arc<SeqNo>);
703
704impl Lease {
705    /// Creates a new [Lease] that holds the given [SeqNo].
706    pub fn new(seqno: SeqNo) -> Self {
707        Self(Arc::new(seqno))
708    }
709
710    /// Returns the inner [SeqNo] of this [Lease].
711    pub fn seqno(&self) -> SeqNo {
712        *self.0
713    }
714
715    /// Returns the number of live copies of this lease, including this one.
716    pub fn count(&self) -> usize {
717        Arc::strong_count(&self.0)
718    }
719}
720
721/// A token representing one fetch-able batch part.
722///
723/// It is tradeable via `crate::fetch::fetch_batch` for the resulting data
724/// stored in the part.
725///
726/// # Exchange
727///
728/// You can exchange `LeasedBatchPart`:
729/// - If `leased_seqno.is_none()`
730/// - By converting it to [`ExchangeableBatchPart`] through
731///   `Self::into_exchangeable_part`. [`ExchangeableBatchPart`] is exchangeable,
732///   including over the network.
733///
734/// n.b. `Self::into_exchangeable_part` is known to be equivalent to
735/// `SerdeLeasedBatchPart::from(self)`, but we want the additional warning message to
736/// be visible and sufficiently scary.
737///
738/// # Panics
739/// `LeasedBatchPart` panics when dropped unless a very strict set of invariants are
740/// held:
741///
742/// `LeasedBatchPart` may only be dropped if it:
743/// - Does not have a leased `SeqNo (i.e. `self.leased_seqno.is_none()`)
744///
745/// In any other circumstance, dropping `LeasedBatchPart` panics.
746#[derive(Debug)]
747pub struct LeasedBatchPart<T> {
748    pub(crate) metrics: Arc<Metrics>,
749    pub(crate) shard_id: ShardId,
750    pub(crate) filter: FetchBatchFilter<T>,
751    pub(crate) desc: Description<T>,
752    pub(crate) part: BatchPart<T>,
753    /// The lease that prevents this part from being GCed. Code should ensure that this lease
754    /// lives as long as the part is needed.
755    pub(crate) lease: Lease,
756    /// The id of the reader that leased this part, for diagnostics: if the
757    /// blob backing the part goes missing, knowing whether this reader is
758    /// still present in state distinguishes a lost lease from a GC bug.
759    pub(crate) reader_id: LeasedReaderId,
760    pub(crate) filter_pushdown_audit: bool,
761    /// Whether the containing batch has a run that may hold updates outside
762    /// the registered desc (see `RunMeta::bounds_truncated`). A fetch filters
763    /// those updates out, but write-time part statistics count them, so
764    /// optimizations that substitute statistics for a fetch must not fire.
765    pub(crate) bounds_truncated: bool,
766}
767
768impl<T> LeasedBatchPart<T>
769where
770    T: Timestamp + Codec64,
771{
772    /// Takes `self` into a [`ExchangeableBatchPart`], which allows `self` to be
773    /// exchanged (potentially across the network).
774    ///
775    /// !!!WARNING!!!
776    ///
777    /// This method also returns the [Lease] associated with the given part, since
778    /// that can't travel across process boundaries. The caller is responsible for
779    /// ensuring that the lease is held for as long as the batch part may be in use:
780    /// dropping it too early may cause a fetch to fail.
781    pub(crate) fn into_exchangeable_part(self) -> (ExchangeableBatchPart<T>, Lease) {
782        // If `x` has a lease, we've effectively transferred it to `r`.
783        let lease = self.lease.clone();
784        let part = ExchangeableBatchPart {
785            shard_id: self.shard_id,
786            encoded_size_bytes: self.part.encoded_size_bytes(),
787            desc: self.desc.clone(),
788            filter: self.filter.clone(),
789            part: LazyProto::from(&self.part.into_proto()),
790            reader_id: self.reader_id.clone(),
791            filter_pushdown_audit: self.filter_pushdown_audit,
792        };
793        (part, lease)
794    }
795
796    /// The encoded size of this part in bytes
797    pub fn encoded_size_bytes(&self) -> usize {
798        self.part.encoded_size_bytes()
799    }
800
801    /// The filter has indicated we don't need this part, we can verify the
802    /// ongoing end-to-end correctness of corner cases via "audit". This means
803    /// we fetch the part like normal and if the MFP keeps anything from it,
804    /// then something has gone horribly wrong.
805    pub fn request_filter_pushdown_audit(&mut self) {
806        self.filter_pushdown_audit = true;
807    }
808
809    /// Returns the pushdown stats for this part.
810    ///
811    /// Stats written by a newer version may not decode; those return `None`,
812    /// the same as a part that carries no stats.
813    pub fn stats(&self) -> Option<PartStats> {
814        self.part.stats().and_then(|x| x.try_decode().ok())
815    }
816
817    /// Apply any relevant projection pushdown optimizations, assuming that the data in the part
818    /// is equivalent to the provided key and value.
819    pub fn maybe_optimize(&mut self, cfg: &ConfigSet, key: ArrayRef, val: ArrayRef) {
820        assert_eq!(key.len(), 1, "expect a single-row key array");
821        assert_eq!(val.len(), 1, "expect a single-row val array");
822        let as_of = match &self.filter {
823            FetchBatchFilter::Snapshot { as_of } => as_of,
824            FetchBatchFilter::Listen { .. } | FetchBatchFilter::Compaction { .. } => return,
825        };
826        if !OPTIMIZE_IGNORED_DATA_FETCH.get(cfg) {
827            return;
828        }
829        // A truncated batch's parts may physically hold updates outside the
830        // registered desc. A fetch filters those out, but the write-time
831        // diffs_sum counts them, so substituting it would fabricate data.
832        if self.bounds_truncated {
833            return;
834        }
835        let (diffs_sum, _stats) = match &self.part {
836            BatchPart::Hollow(x) => (x.diffs_sum, x.stats.as_ref()),
837            BatchPart::Inline { .. } => return,
838        };
839        debug!(
840            "try_optimize_ignored_data_fetch diffs_sum={:?} as_of={:?} lower={:?} upper={:?}",
841            // This is only used for debugging, so hack to assume that D is i64.
842            diffs_sum.map(i64::decode),
843            as_of.elements(),
844            self.desc.lower().elements(),
845            self.desc.upper().elements()
846        );
847        let as_of = match &as_of.elements() {
848            &[as_of] => as_of,
849            _ => return,
850        };
851        // NOTE: `diffs_sum` sums every row physically in the blob, while
852        // reads truncate rows outside the registered desc. Substituting it is
853        // sound only while no writer registers a batch with tighter bounds
854        // than the blob holds (none does today, and rewritten batches prove
855        // it), which nothing here can re-check without fetching the blob.
856        let eligible = self.desc.upper().less_equal(as_of) && self.desc.since().less_equal(as_of);
857        if !eligible {
858            return;
859        }
860        let Some(diffs_sum) = diffs_sum else {
861            return;
862        };
863
864        debug!(
865            "try_optimize_ignored_data_fetch faked {:?} diffs at ts {:?} skipping fetch of {} bytes",
866            // This is only used for debugging, so hack to assume that D is i64.
867            i64::decode(diffs_sum),
868            as_of,
869            self.part.encoded_size_bytes(),
870        );
871        self.metrics.pushdown.parts_faked_count.inc();
872        self.metrics
873            .pushdown
874            .parts_faked_bytes
875            .inc_by(u64::cast_from(self.part.encoded_size_bytes()));
876        let timestamps = {
877            let mut col = Codec64Mut::with_capacity(1);
878            col.push(as_of);
879            col.finish()
880        };
881        let diffs = {
882            let mut col = Codec64Mut::with_capacity(1);
883            col.push_raw(diffs_sum);
884            col.finish()
885        };
886        let updates = BlobTraceUpdates::Structured {
887            key_values: ColumnarRecordsStructuredExt { key, val },
888            timestamps,
889            diffs,
890        };
891        let faked_data = LazyInlineBatchPart::from(&ProtoInlineBatchPart {
892            desc: Some(self.desc.into_proto()),
893            index: 0,
894            updates: Some(updates.into_proto()),
895        });
896        self.part = BatchPart::Inline {
897            updates: faked_data,
898            ts_rewrite: None,
899            schema_id: None,
900            deprecated_schema_id: None,
901        };
902    }
903}
904
905impl<T> Drop for LeasedBatchPart<T> {
906    /// For details, see [`LeasedBatchPart`].
907    fn drop(&mut self) {
908        self.metrics.lease.dropped_part.inc()
909    }
910}
911
912/// A [Blob] object that has been fetched, but not at all decoded.
913///
914/// In contrast to [FetchedPart], this representation hasn't yet done parquet
915/// decoding.
916#[derive(Debug)]
917pub struct FetchedBlob<K: Codec, V: Codec, T, D> {
918    metrics: Arc<Metrics>,
919    read_metrics: ReadMetrics,
920    buf: FetchedBlobBuf<T>,
921    registered_desc: Description<T>,
922    migration: PartMigration<K, V>,
923    filter: FetchBatchFilter<T>,
924    filter_pushdown_audit: bool,
925    structured_part_audit: PartDecodeFormat,
926    fetch_permit: Option<Arc<MetricsPermits>>,
927    fetch_config: FetchConfig,
928    _phantom: PhantomData<fn() -> D>,
929}
930
931#[derive(Debug, Clone)]
932enum FetchedBlobBuf<T> {
933    Hollow {
934        buf: SegmentedBytes,
935        part: HollowBatchPart<T>,
936    },
937    Inline {
938        desc: Description<T>,
939        updates: LazyInlineBatchPart,
940        ts_rewrite: Option<Antichain<T>>,
941    },
942}
943
944impl<K: Codec, V: Codec, T: Clone, D> Clone for FetchedBlob<K, V, T, D> {
945    fn clone(&self) -> Self {
946        Self {
947            metrics: Arc::clone(&self.metrics),
948            read_metrics: self.read_metrics.clone(),
949            buf: self.buf.clone(),
950            registered_desc: self.registered_desc.clone(),
951            migration: self.migration.clone(),
952            filter: self.filter.clone(),
953            filter_pushdown_audit: self.filter_pushdown_audit.clone(),
954            fetch_permit: self.fetch_permit.clone(),
955            structured_part_audit: self.structured_part_audit.clone(),
956            fetch_config: self.fetch_config.clone(),
957            _phantom: self._phantom.clone(),
958        }
959    }
960}
961
962/// [FetchedPart] but with an accompanying permit from the fetch mem/disk
963/// semaphore.
964pub struct ShardSourcePart<K: Codec, V: Codec, T, D> {
965    /// The underlying [FetchedPart].
966    pub part: FetchedPart<K, V, T, D>,
967    fetch_permit: Option<Arc<MetricsPermits>>,
968}
969
970impl<K, V, T: Debug, D: Debug> Debug for ShardSourcePart<K, V, T, D>
971where
972    K: Codec + Debug,
973    <K as Codec>::Storage: Debug,
974    V: Codec + Debug,
975    <V as Codec>::Storage: Debug,
976{
977    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
978        let ShardSourcePart { part, fetch_permit } = self;
979        f.debug_struct("ShardSourcePart")
980            .field("part", part)
981            .field("fetch_permit", fetch_permit)
982            .finish()
983    }
984}
985
986impl<K: Codec, V: Codec, T: Timestamp + Lattice + Codec64, D> FetchedBlob<K, V, T, D> {
987    /// Partially decodes this blob into a [FetchedPart].
988    pub fn parse(&self) -> ShardSourcePart<K, V, T, D> {
989        self.parse_internal(&self.fetch_config)
990    }
991
992    /// Partially decodes this blob into a [FetchedPart].
993    pub(crate) fn parse_internal(&self, cfg: &FetchConfig) -> ShardSourcePart<K, V, T, D> {
994        let (part, stats) = match &self.buf {
995            FetchedBlobBuf::Hollow { buf, part } => {
996                let source = PartSource::from_hollow_blob(
997                    cfg,
998                    &self.metrics,
999                    &self.read_metrics,
1000                    self.registered_desc.clone(),
1001                    part,
1002                    buf,
1003                );
1004                (source, part.stats.as_ref())
1005            }
1006            FetchedBlobBuf::Inline {
1007                desc,
1008                updates,
1009                ts_rewrite,
1010            } => {
1011                let parsed = EncodedPart::from_inline(
1012                    cfg,
1013                    &self.metrics,
1014                    self.read_metrics.clone(),
1015                    desc.clone(),
1016                    updates,
1017                    ts_rewrite.as_ref(),
1018                );
1019                (PartSource::Whole(parsed), None)
1020            }
1021        };
1022        let part = FetchedPart::new(
1023            Arc::clone(&self.metrics),
1024            part,
1025            self.migration.clone(),
1026            self.filter.clone(),
1027            self.filter_pushdown_audit,
1028            self.structured_part_audit,
1029            stats,
1030        );
1031        ShardSourcePart {
1032            part,
1033            fetch_permit: self.fetch_permit.clone(),
1034        }
1035    }
1036
1037    /// Decodes and returns the pushdown stats for this part, if known.
1038    ///
1039    /// Stats written by a newer version may not decode; those return `None`,
1040    /// the same as a part that carries no stats.
1041    pub fn stats(&self) -> Option<PartStats> {
1042        match &self.buf {
1043            FetchedBlobBuf::Hollow { part, .. } => {
1044                part.stats.as_ref().and_then(|x| x.try_decode().ok())
1045            }
1046            FetchedBlobBuf::Inline { .. } => None,
1047        }
1048    }
1049}
1050
1051/// A [Blob] object that has been fetched, but not yet fully decoded.
1052///
1053/// In contrast to [FetchedBlob], this representation has already done parquet
1054/// decoding.
1055#[derive(Debug)]
1056pub struct FetchedPart<K: Codec, V: Codec, T, D> {
1057    metrics: Arc<Metrics>,
1058    ts_filter: FetchBatchFilter<T>,
1059    // The decoded rows of the whole part, or of the current batch of
1060    // `batches`. `None` before the first batch and after the last.
1061    rows: Option<DecodedRows<K, V>>,
1062    // Batches not yet decoded into `rows`, if the part is decoded in batches.
1063    batches: Option<EncodedPartBatches<T>>,
1064    part_decode_format: PartDecodeFormat,
1065    // Row count of the whole part before normalization.
1066    part_rows: usize,
1067    migration: PartMigration<K, V>,
1068    filter_pushdown_audit: Option<LazyPartStats>,
1069    peek_stash: Option<((K, V), T, D)>,
1070    key_storage: Option<K::Storage>,
1071    val_storage: Option<V::Storage>,
1072
1073    _phantom: PhantomData<fn() -> D>,
1074}
1075
1076/// Decoded rows of a [`FetchedPart`] and the cursor into them.
1077#[derive(Debug)]
1078struct DecodedRows<K: Codec, V: Codec> {
1079    // If migration is Either, then the columnar one will have already been
1080    // applied here on the structured data only.
1081    part: EitherOrBoth<
1082        ColumnarRecords,
1083        (
1084            <K::Schema as Schema<K>>::Decoder,
1085            <V::Schema as Schema<V>>::Decoder,
1086        ),
1087    >,
1088    timestamps: Int64Array,
1089    diffs: Int64Array,
1090    cursor: usize,
1091}
1092
1093impl<K: Codec, V: Codec, T: Timestamp + Lattice + Codec64, D> FetchedPart<K, V, T, D> {
1094    pub(crate) fn new(
1095        metrics: Arc<Metrics>,
1096        source: PartSource<T>,
1097        migration: PartMigration<K, V>,
1098        ts_filter: FetchBatchFilter<T>,
1099        filter_pushdown_audit: bool,
1100        part_decode_format: PartDecodeFormat,
1101        stats: Option<&LazyPartStats>,
1102    ) -> Self {
1103        let (updates, batches, part_rows) = match source {
1104            PartSource::Whole(part) => {
1105                let part_rows = part.updates().len();
1106                (Some(part.normalize(&metrics.columnar)), None, part_rows)
1107            }
1108            PartSource::Batched(batches) => {
1109                let part_rows = batches.reader.num_rows();
1110                (None, Some(batches), part_rows)
1111            }
1112        };
1113        let part_len = u64::cast_from(part_rows);
1114        match &migration {
1115            PartMigration::SameSchema { .. } => metrics.schema.migration_count_same.inc(),
1116            PartMigration::Schemaless { .. } => {
1117                metrics.schema.migration_count_codec.inc();
1118                metrics.schema.migration_len_legacy_codec.inc_by(part_len);
1119            }
1120            PartMigration::Either { .. } => {
1121                metrics.schema.migration_count_either.inc();
1122                match part_decode_format {
1123                    PartDecodeFormat::Row {
1124                        validate_structured: false,
1125                    } => metrics.schema.migration_len_either_codec.inc_by(part_len),
1126                    PartDecodeFormat::Row {
1127                        validate_structured: true,
1128                    } => {
1129                        metrics.schema.migration_len_either_codec.inc_by(part_len);
1130                        metrics.schema.migration_len_either_arrow.inc_by(part_len);
1131                    }
1132                    PartDecodeFormat::Arrow => {
1133                        metrics.schema.migration_len_either_arrow.inc_by(part_len)
1134                    }
1135                }
1136            }
1137        }
1138
1139        let filter_pushdown_audit = if filter_pushdown_audit {
1140            stats.cloned()
1141        } else {
1142            None
1143        };
1144
1145        let mut ret = FetchedPart {
1146            metrics,
1147            ts_filter,
1148            rows: None,
1149            peek_stash: None,
1150            batches,
1151            part_decode_format,
1152            part_rows,
1153            migration,
1154            filter_pushdown_audit,
1155            key_storage: None,
1156            val_storage: None,
1157            _phantom: PhantomData,
1158        };
1159        ret.rows = updates.map(|updates| ret.decode_rows(updates));
1160        ret
1161    }
1162
1163    /// Replaces the current decoded rows with the next batch, if any.
1164    ///
1165    /// Returns false once all batches have been decoded, or if the part was
1166    /// decoded whole.
1167    fn next_batch(&mut self) -> bool {
1168        let Some(batches) = self.batches.as_mut() else {
1169            return false;
1170        };
1171        // Release the current batch before decoding the next, so at most one
1172        // decoded batch is alive.
1173        self.rows = None;
1174        match batches.next_updates(&self.metrics) {
1175            Some(updates) => {
1176                self.rows = Some(self.decode_rows(updates));
1177                true
1178            }
1179            None => {
1180                self.batches = None;
1181                false
1182            }
1183        }
1184    }
1185
1186    /// Builds decoders over normalized `updates`.
1187    fn decode_rows(&self, updates: BlobTraceUpdates) -> DecodedRows<K, V> {
1188        let metrics = &*self.metrics;
1189        let migration = &self.migration;
1190        let downcast_structured = |structured: ColumnarRecordsStructuredExt,
1191                                   structured_only: bool| {
1192            let key_size_before = ArrayOrd::new(&structured.key).goodbytes();
1193
1194            let structured = match migration {
1195                PartMigration::SameSchema { .. } => structured,
1196                PartMigration::Schemaless { read } if structured_only => {
1197                    // We don't know the source schema, but we do know the source datatype; migrate it directly.
1198                    let start = Instant::now();
1199                    let read_key = data_type::<K>(&*read.key).ok()?;
1200                    let read_val = data_type::<V>(&*read.val).ok()?;
1201                    let key_migration = backward_compatible(structured.key.data_type(), &read_key)?;
1202                    let val_migration = backward_compatible(structured.val.data_type(), &read_val)?;
1203                    let key = key_migration.migrate(structured.key);
1204                    let val = val_migration.migrate(structured.val);
1205                    metrics
1206                        .schema
1207                        .migration_migrate_seconds
1208                        .inc_by(start.elapsed().as_secs_f64());
1209                    ColumnarRecordsStructuredExt { key, val }
1210                }
1211                PartMigration::Schemaless { .. } => return None,
1212                PartMigration::Either {
1213                    write: _,
1214                    read: _,
1215                    key_migration,
1216                    val_migration,
1217                } => {
1218                    let start = Instant::now();
1219                    let key = key_migration.migrate(structured.key);
1220                    let val = val_migration.migrate(structured.val);
1221                    metrics
1222                        .schema
1223                        .migration_migrate_seconds
1224                        .inc_by(start.elapsed().as_secs_f64());
1225                    ColumnarRecordsStructuredExt { key, val }
1226                }
1227            };
1228
1229            let read_schema = migration.codec_read();
1230            let key = K::Schema::decoder_any(&*read_schema.key, &*structured.key);
1231            let val = V::Schema::decoder_any(&*read_schema.val, &*structured.val);
1232
1233            match &key {
1234                Ok(key_decoder) => {
1235                    let key_size_after = key_decoder.goodbytes();
1236                    let key_diff = key_size_before.saturating_sub(key_size_after);
1237                    metrics
1238                        .pushdown
1239                        .parts_projection_trimmed_bytes
1240                        .inc_by(u64::cast_from(key_diff));
1241                }
1242                Err(e) => {
1243                    soft_panic_or_log!("failed to create decoder: {e:#?}");
1244                }
1245            }
1246
1247            Some((key.ok()?, val.ok()?))
1248        };
1249
1250        let timestamps = updates.timestamps().clone();
1251        let diffs = updates.diffs().clone();
1252        let part = match updates {
1253            // If only one encoding is available, decode via that encoding.
1254            BlobTraceUpdates::Row(records) => EitherOrBoth::Left(records),
1255            BlobTraceUpdates::Structured { key_values, .. } => EitherOrBoth::Right(
1256                // The structured-only data format was added after schema ids were recorded everywhere,
1257                // so we expect this data to be present.
1258                downcast_structured(key_values, true).expect("valid schemas for structured data"),
1259            ),
1260            // If both are available, respect the specified part decode format.
1261            BlobTraceUpdates::Both(records, ext) => match self.part_decode_format {
1262                PartDecodeFormat::Row {
1263                    validate_structured: false,
1264                } => EitherOrBoth::Left(records),
1265                PartDecodeFormat::Row {
1266                    validate_structured: true,
1267                } => match downcast_structured(ext, false) {
1268                    Some(decoders) => EitherOrBoth::Both(records, decoders),
1269                    None => EitherOrBoth::Left(records),
1270                },
1271                PartDecodeFormat::Arrow => match downcast_structured(ext, false) {
1272                    Some(decoders) => EitherOrBoth::Right(decoders),
1273                    None => EitherOrBoth::Left(records),
1274                },
1275            },
1276        };
1277
1278        DecodedRows {
1279            part,
1280            timestamps,
1281            diffs,
1282            cursor: 0,
1283        }
1284    }
1285
1286    /// Returns Some if this part was only fetched as part of a filter pushdown
1287    /// audit. See [LeasedBatchPart::request_filter_pushdown_audit].
1288    ///
1289    /// If set, the value in the Option is for debugging and should be included
1290    /// in any error messages.
1291    pub fn is_filter_pushdown_audit(&self) -> Option<impl std::fmt::Debug + use<K, V, T, D>> {
1292        self.filter_pushdown_audit.clone()
1293    }
1294}
1295
1296/// A [Blob] object that has been fetched, but has no associated decoding
1297/// logic.
1298#[derive(Debug)]
1299pub(crate) struct EncodedPart<T> {
1300    part: BlobTraceBatchPart<T>,
1301    normalization: PartNormalization<T>,
1302}
1303
1304/// The updates [`FetchedPart`] reads: a part decoded whole, or one decoded
1305/// in bounded batches on demand.
1306///
1307/// Readers decode hollow parts in batches when
1308/// [`FetchConfig::part_decode_batch_rows`] is set. Inline parts, and
1309/// all parts read through [`EncodedPart`] directly (compaction, consolidating
1310/// iteration, inspect), are decoded whole.
1311#[derive(Debug)]
1312pub(crate) enum PartSource<T> {
1313    Whole(EncodedPart<T>),
1314    Batched(EncodedPartBatches<T>),
1315}
1316
1317impl<T: Timestamp + Lattice + Codec64> PartSource<T> {
1318    /// Decodes the fetched blob `buf` of the hollow `part`, in batches if
1319    /// [`FetchConfig::part_decode_batch_rows`] is set.
1320    pub(crate) fn from_hollow_blob(
1321        cfg: &FetchConfig,
1322        metrics: &Metrics,
1323        read_metrics: &ReadMetrics,
1324        registered_desc: Description<T>,
1325        part: &HollowBatchPart<T>,
1326        buf: &SegmentedBytes,
1327    ) -> Self {
1328        match cfg.part_decode_batch_rows {
1329            None => PartSource::Whole(decode_batch_part_blob(
1330                cfg,
1331                metrics,
1332                read_metrics,
1333                registered_desc,
1334                part,
1335                buf,
1336            )),
1337            Some(batch_rows) => PartSource::Batched(EncodedPartBatches::new(
1338                cfg,
1339                batch_rows,
1340                metrics,
1341                read_metrics.clone(),
1342                registered_desc,
1343                part,
1344                buf.clone(),
1345            )),
1346        }
1347    }
1348}
1349
1350/// The normalization of a fetched part's updates to its registered
1351/// description: truncation to the registered bounds and `ts_rewrite`.
1352#[derive(Debug)]
1353struct PartNormalization<T> {
1354    metrics: ReadMetrics,
1355    registered_desc: Description<T>,
1356    needs_truncation: bool,
1357    ts_rewrite: Option<Antichain<T>>,
1358}
1359
1360/// A hollow part decoded into normalized updates in batches of at most
1361/// `batch_rows` rows.
1362///
1363/// Holds the encoded bytes until the last batch is decoded.
1364#[derive(Debug)]
1365pub(crate) struct EncodedPartBatches<T> {
1366    reader: BlobTraceBatchPartReader<T>,
1367    normalization: PartNormalization<T>,
1368}
1369
1370impl<T: Timestamp + Lattice + Codec64> EncodedPartBatches<T> {
1371    pub(crate) fn new(
1372        cfg: &FetchConfig,
1373        batch_rows: usize,
1374        metrics: &Metrics,
1375        read_metrics: ReadMetrics,
1376        registered_desc: Description<T>,
1377        part: &HollowBatchPart<T>,
1378        buf: SegmentedBytes,
1379    ) -> Self {
1380        let reader = metrics
1381            .codecs
1382            .batch
1383            .decode(|| BlobTraceBatchPartReader::new(buf, batch_rows))
1384            .map_err(|err| anyhow!("couldn't decode batch at key {}: {}", part.key, err))
1385            // Same as `decode_batch_part_blob`: undecodable durable data is
1386            // not recoverable.
1387            .expect("internal error: invalid encoded state");
1388        let normalization = PartNormalization::new(
1389            cfg,
1390            read_metrics,
1391            registered_desc,
1392            &part.key.0,
1393            part.ts_rewrite.as_ref(),
1394            reader.desc(),
1395        );
1396        EncodedPartBatches {
1397            reader,
1398            normalization,
1399        }
1400    }
1401
1402    /// Decodes and normalizes the next batch, or returns `None` once all rows
1403    /// have been returned.
1404    fn next_updates(&mut self, metrics: &Metrics) -> Option<BlobTraceUpdates> {
1405        let start = Instant::now();
1406        let updates = self
1407            .reader
1408            .next_updates(&metrics.columnar)?
1409            .expect("internal error: invalid encoded state");
1410        // Counts parts, not batches, so only the open in `new` increments
1411        // `decode_count`.
1412        metrics
1413            .codecs
1414            .batch
1415            .decode_seconds
1416            .inc_by(start.elapsed().as_secs_f64());
1417        self.normalization
1418            .metrics
1419            .part_goodbytes
1420            .inc_by(u64::cast_from(updates.goodbytes()));
1421        Some(self.normalization.normalize(&updates, &metrics.columnar))
1422    }
1423}
1424
1425impl<K, V, T, D> FetchedPart<K, V, T, D>
1426where
1427    K: Debug + Codec,
1428    V: Debug + Codec,
1429    T: Timestamp + Lattice + Codec64,
1430    D: Monoid + Codec64 + Send + Sync,
1431{
1432    /// [Self::next] but optionally providing a `K` and `V` for alloc reuse.
1433    ///
1434    /// When `result_override` is specified, return it instead of decoding data.
1435    /// This is used when we know the decoded result will be ignored.
1436    pub fn next_with_storage(
1437        &mut self,
1438        key: &mut Option<K>,
1439        val: &mut Option<V>,
1440    ) -> Option<((K, V), T, D)> {
1441        let mut consolidated = self.peek_stash.take();
1442        loop {
1443            // Fetch and decode the next tuple in the sequence. (Or break if there is none.)
1444            let row = match &mut self.rows {
1445                Some(rows) if rows.cursor < rows.timestamps.len() => {
1446                    let idx = rows.cursor;
1447                    rows.cursor += 1;
1448                    Some((idx, rows.timestamps.values()[idx], rows.diffs.values()[idx]))
1449                }
1450                _ => None,
1451            };
1452            let next = if let Some((next_idx, t, d)) = row {
1453                // These `to_le_bytes` calls were previously encapsulated by `ColumnarRecords`.
1454                // TODO(structured): re-encapsulate these once we've finished the structured migration.
1455                let mut t = T::decode(t.to_le_bytes());
1456                if !self.ts_filter.filter_ts(&mut t) {
1457                    continue;
1458                }
1459                let d = D::decode(d.to_le_bytes());
1460                if d.is_zero() {
1461                    continue;
1462                }
1463                let kv = self.decode_kv(next_idx, key, val);
1464                (kv, t, d)
1465            } else if self.next_batch() {
1466                // `consolidated` and `peek_stash` are owned, so consolidation
1467                // continues across the batch boundary.
1468                continue;
1469            } else {
1470                break;
1471            };
1472
1473            // Attempt to consolidate in the next tuple, stashing it if that's not possible.
1474            if let Some((kv, t, d)) = &mut consolidated {
1475                let (kv_next, t_next, d_next) = &next;
1476                if kv == kv_next && t == t_next {
1477                    d.plus_equals(d_next);
1478                    if d.is_zero() {
1479                        consolidated = None;
1480                    }
1481                } else {
1482                    self.peek_stash = Some(next);
1483                    break;
1484                }
1485            } else {
1486                consolidated = Some(next);
1487            }
1488        }
1489
1490        let (kv, t, d) = consolidated?;
1491
1492        Some((kv, t, d))
1493    }
1494
1495    fn decode_kv(&mut self, index: usize, key: &mut Option<K>, val: &mut Option<V>) -> (K, V) {
1496        let decoded = self
1497            .rows
1498            .as_ref()
1499            .expect("decoded rows present while the cursor is in bounds")
1500            .part
1501            .as_ref()
1502            .map_left(|codec| {
1503                let ((ck, cv), _, _) = codec.get(index).expect("valid index");
1504                let (k, v) = Self::decode_codec(
1505                    &*self.metrics,
1506                    self.migration.codec_read(),
1507                    ck,
1508                    cv,
1509                    key,
1510                    val,
1511                    &mut self.key_storage,
1512                    &mut self.val_storage,
1513                );
1514                (k.expect("valid legacy key"), v.expect("valid legacy value"))
1515            })
1516            .map_right(|(structured_key, structured_val)| {
1517                self.decode_structured(index, structured_key, structured_val, key, val)
1518            });
1519
1520        match decoded {
1521            EitherOrBoth::Both((k, v), (k_s, v_s)) => {
1522                // Purposefully do not trace to prevent blowing up Sentry.
1523                let is_valid = self
1524                    .metrics
1525                    .columnar
1526                    .arrow()
1527                    .key()
1528                    .report_valid(|| k_s == k);
1529                if !is_valid {
1530                    soft_panic_no_log!("structured key did not match, {k_s:?} != {k:?}");
1531                }
1532                // Purposefully do not trace to prevent blowing up Sentry.
1533                let is_valid = self
1534                    .metrics
1535                    .columnar
1536                    .arrow()
1537                    .val()
1538                    .report_valid(|| v_s == v);
1539                if !is_valid {
1540                    soft_panic_no_log!("structured val did not match, {v_s:?} != {v:?}");
1541                }
1542
1543                (k, v)
1544            }
1545            EitherOrBoth::Left(kv) => kv,
1546            EitherOrBoth::Right(kv) => kv,
1547        }
1548    }
1549
1550    fn decode_codec(
1551        metrics: &Metrics,
1552        read_schemas: &Schemas<K, V>,
1553        key_buf: &[u8],
1554        val_buf: &[u8],
1555        key: &mut Option<K>,
1556        val: &mut Option<V>,
1557        key_storage: &mut Option<K::Storage>,
1558        val_storage: &mut Option<V::Storage>,
1559    ) -> (Result<K, String>, Result<V, String>) {
1560        let k = metrics.codecs.key.decode(|| match key.take() {
1561            Some(mut key) => {
1562                match K::decode_from(&mut key, key_buf, key_storage, &read_schemas.key) {
1563                    Ok(()) => Ok(key),
1564                    Err(err) => Err(err),
1565                }
1566            }
1567            None => K::decode(key_buf, &read_schemas.key),
1568        });
1569        let v = metrics.codecs.val.decode(|| match val.take() {
1570            Some(mut val) => {
1571                match V::decode_from(&mut val, val_buf, val_storage, &read_schemas.val) {
1572                    Ok(()) => Ok(val),
1573                    Err(err) => Err(err),
1574                }
1575            }
1576            None => V::decode(val_buf, &read_schemas.val),
1577        });
1578        (k, v)
1579    }
1580
1581    fn decode_structured(
1582        &self,
1583        idx: usize,
1584        keys: &<K::Schema as Schema<K>>::Decoder,
1585        vals: &<V::Schema as Schema<V>>::Decoder,
1586        key: &mut Option<K>,
1587        val: &mut Option<V>,
1588    ) -> (K, V) {
1589        let mut key = key.take().unwrap_or_default();
1590        keys.decode(idx, &mut key);
1591
1592        let mut val = val.take().unwrap_or_default();
1593        vals.decode(idx, &mut val);
1594
1595        (key, val)
1596    }
1597}
1598
1599impl<K, V, T, D> Iterator for FetchedPart<K, V, T, D>
1600where
1601    K: Debug + Codec,
1602    V: Debug + Codec,
1603    T: Timestamp + Lattice + Codec64,
1604    D: Monoid + Codec64 + Send + Sync,
1605{
1606    type Item = ((K, V), T, D);
1607
1608    fn next(&mut self) -> Option<Self::Item> {
1609        self.next_with_storage(&mut None, &mut None)
1610    }
1611
1612    fn size_hint(&self) -> (usize, Option<usize>) {
1613        // We don't know in advance how restrictive the filter will be.
1614        let max_len = self.part_rows;
1615        (0, Some(max_len))
1616    }
1617}
1618
1619impl<T> EncodedPart<T>
1620where
1621    T: Timestamp + Lattice + Codec64,
1622{
1623    pub async fn fetch(
1624        cfg: &FetchConfig,
1625        shard_id: &ShardId,
1626        blob: &dyn Blob,
1627        metrics: &Metrics,
1628        shard_metrics: &ShardMetrics,
1629        read_metrics: &ReadMetrics,
1630        registered_desc: &Description<T>,
1631        part: &BatchPart<T>,
1632    ) -> Result<Self, BlobKey> {
1633        match part {
1634            BatchPart::Hollow(x) => {
1635                fetch_batch_part(
1636                    cfg,
1637                    shard_id,
1638                    blob,
1639                    metrics,
1640                    shard_metrics,
1641                    read_metrics,
1642                    registered_desc,
1643                    x,
1644                )
1645                .await
1646            }
1647            BatchPart::Inline {
1648                updates,
1649                ts_rewrite,
1650                ..
1651            } => Ok(EncodedPart::from_inline(
1652                cfg,
1653                metrics,
1654                read_metrics.clone(),
1655                registered_desc.clone(),
1656                updates,
1657                ts_rewrite.as_ref(),
1658            )),
1659        }
1660    }
1661
1662    pub(crate) fn from_inline(
1663        cfg: &FetchConfig,
1664        metrics: &Metrics,
1665        read_metrics: ReadMetrics,
1666        desc: Description<T>,
1667        x: &LazyInlineBatchPart,
1668        ts_rewrite: Option<&Antichain<T>>,
1669    ) -> Self {
1670        let parsed = x.decode(&metrics.columnar).expect("valid inline part");
1671        Self::new(cfg, read_metrics, desc, "inline", ts_rewrite, parsed)
1672    }
1673
1674    pub(crate) fn from_hollow(
1675        cfg: &FetchConfig,
1676        metrics: ReadMetrics,
1677        registered_desc: Description<T>,
1678        part: &HollowBatchPart<T>,
1679        parsed: BlobTraceBatchPart<T>,
1680    ) -> Self {
1681        Self::new(
1682            cfg,
1683            metrics,
1684            registered_desc,
1685            &part.key.0,
1686            part.ts_rewrite.as_ref(),
1687            parsed,
1688        )
1689    }
1690
1691    pub(crate) fn new(
1692        cfg: &FetchConfig,
1693        metrics: ReadMetrics,
1694        registered_desc: Description<T>,
1695        printable_name: &str,
1696        ts_rewrite: Option<&Antichain<T>>,
1697        parsed: BlobTraceBatchPart<T>,
1698    ) -> Self {
1699        let normalization = PartNormalization::new(
1700            cfg,
1701            metrics,
1702            registered_desc,
1703            printable_name,
1704            ts_rewrite,
1705            &parsed.desc,
1706        );
1707        EncodedPart {
1708            part: parsed,
1709            normalization,
1710        }
1711    }
1712
1713    pub(crate) fn maybe_unconsolidated(&self) -> bool {
1714        // At time of writing, only user parts may be unconsolidated, and they are always
1715        // written with a since of [T::minimum()].
1716        self.part.desc.since().borrow() == AntichainRef::new(&[T::minimum()])
1717    }
1718
1719    pub(crate) fn updates(&self) -> &BlobTraceUpdates {
1720        &self.part.updates
1721    }
1722
1723    /// Returns the updates with all truncation / timestamp rewriting applied.
1724    pub(crate) fn normalize(&self, metrics: &ColumnarMetrics) -> BlobTraceUpdates {
1725        self.normalization.normalize(&self.part.updates, metrics)
1726    }
1727}
1728
1729impl<T: Timestamp + Lattice + Codec64> PartNormalization<T> {
1730    fn new(
1731        cfg: &FetchConfig,
1732        metrics: ReadMetrics,
1733        registered_desc: Description<T>,
1734        printable_name: &str,
1735        ts_rewrite: Option<&Antichain<T>>,
1736        inline_desc: &Description<T>,
1737    ) -> Self {
1738        // There are two types of batches in persist:
1739        // - Batches written by a persist user (either directly or indirectly
1740        //   via BatchBuilder). These always have a since of the minimum
1741        //   timestamp and may be registered in persist state with a tighter set
1742        //   of bounds than are inline in the batch (truncation). To read one of
1743        //   these batches, all data physically in the batch but outside of the
1744        //   truncated bounds must be ignored. Not every user batch is
1745        //   truncated.
1746        // - Batches written by compaction. These always have an inline desc
1747        //   lower and upper that matches the registered desc lower and upper,
1748        //   and a since that is less than or equal to the registered desc.
1749        //   The inline since may be less than the registered desc since,
1750        //   this is because of incremental compaction, where we might rewrite
1751        //   certain runs in a batch but not others.
1752        let needs_truncation = inline_desc.lower() != registered_desc.lower()
1753            || inline_desc.upper() != registered_desc.upper();
1754        if needs_truncation {
1755            if cfg.validate_bounds_on_read {
1756                soft_assert_or_log!(
1757                    PartialOrder::less_equal(inline_desc.lower(), registered_desc.lower()),
1758                    "key={} inline={:?} registered={:?}",
1759                    printable_name,
1760                    inline_desc,
1761                    registered_desc
1762                );
1763
1764                if ts_rewrite.is_none() {
1765                    // The ts rewrite feature allows us to advance the registered
1766                    // upper of a batch that's already been staged (the inline
1767                    // upper), so if it's been used, then there's no useful
1768                    // invariant that we can assert here.
1769                    soft_assert_or_log!(
1770                        PartialOrder::less_equal(registered_desc.upper(), inline_desc.upper()),
1771                        "key={} inline={:?} registered={:?}",
1772                        printable_name,
1773                        inline_desc,
1774                        registered_desc
1775                    );
1776                }
1777            }
1778            // As mentioned above, batches that needs truncation will always have a
1779            // since of the minimum timestamp. Technically we could truncate any
1780            // batch where the since is less_than the output_desc's lower, but we're
1781            // strict here so we don't get any surprises.
1782            assert_eq!(
1783                inline_desc.since(),
1784                &Antichain::from_elem(T::minimum()),
1785                "key={} inline={:?} registered={:?}",
1786                printable_name,
1787                inline_desc,
1788                registered_desc
1789            );
1790        } else {
1791            soft_assert_or_log!(
1792                PartialOrder::less_equal(inline_desc.since(), registered_desc.since()),
1793                "key={} inline={:?} registered={:?}",
1794                printable_name,
1795                inline_desc,
1796                registered_desc
1797            );
1798            assert_eq!(
1799                inline_desc.lower(),
1800                registered_desc.lower(),
1801                "key={} inline={:?} registered={:?}",
1802                printable_name,
1803                inline_desc,
1804                registered_desc
1805            );
1806            assert_eq!(
1807                inline_desc.upper(),
1808                registered_desc.upper(),
1809                "key={} inline={:?} registered={:?}",
1810                printable_name,
1811                inline_desc,
1812                registered_desc
1813            );
1814        }
1815
1816        PartNormalization {
1817            metrics,
1818            registered_desc,
1819            needs_truncation,
1820            ts_rewrite: ts_rewrite.cloned(),
1821        }
1822    }
1823
1824    /// Returns `updates` with all truncation / timestamp rewriting applied.
1825    fn normalize(&self, updates: &BlobTraceUpdates, metrics: &ColumnarMetrics) -> BlobTraceUpdates {
1826        let updates = updates.clone();
1827        if !self.needs_truncation && self.ts_rewrite.is_none() {
1828            return updates;
1829        }
1830
1831        let mut codec = updates
1832            .records()
1833            .map(|r| (r.keys().clone(), r.vals().clone()));
1834        let mut structured = updates.structured().cloned();
1835        let mut timestamps = updates.timestamps().clone();
1836        let mut diffs = updates.diffs().clone();
1837
1838        if let Some(rewrite) = self.ts_rewrite.as_ref() {
1839            timestamps = arrow::compute::unary(&timestamps, |i: i64| {
1840                let mut t = T::decode(i.to_le_bytes());
1841                t.advance_by(rewrite.borrow());
1842                i64::from_le_bytes(T::encode(&t))
1843            });
1844        }
1845
1846        let reallocated = if self.needs_truncation {
1847            let filter = BooleanArray::from_unary(&timestamps, |i| {
1848                let t = T::decode(i.to_le_bytes());
1849                let truncate_t = {
1850                    !self.registered_desc.lower().less_equal(&t)
1851                        || self.registered_desc.upper().less_equal(&t)
1852                };
1853                !truncate_t
1854            });
1855            if filter.false_count() == 0 {
1856                // If we're not filtering anything in practice, skip filtering and reallocating.
1857                false
1858            } else {
1859                let filter = FilterBuilder::new(&filter).optimize().build();
1860                let do_filter = |array: &dyn Array| filter.filter(array).expect("valid filter len");
1861                if let Some((keys, vals)) = codec {
1862                    codec = Some((
1863                        realloc_array(do_filter(&keys).as_binary(), metrics),
1864                        realloc_array(do_filter(&vals).as_binary(), metrics),
1865                    ));
1866                }
1867                if let Some(ext) = structured {
1868                    structured = Some(ColumnarRecordsStructuredExt {
1869                        key: realloc_any(do_filter(&*ext.key), metrics),
1870                        val: realloc_any(do_filter(&*ext.val), metrics),
1871                    });
1872                }
1873                timestamps = realloc_array(do_filter(&timestamps).as_primitive(), metrics);
1874                diffs = realloc_array(do_filter(&diffs).as_primitive(), metrics);
1875                true
1876            }
1877        } else {
1878            false
1879        };
1880
1881        if self.ts_rewrite.is_some() && !reallocated {
1882            timestamps = realloc_array(&timestamps, metrics);
1883        }
1884
1885        if self.ts_rewrite.is_some() {
1886            self.metrics
1887                .ts_rewrite
1888                .inc_by(u64::cast_from(timestamps.len()));
1889        }
1890
1891        match (codec, structured) {
1892            (Some((key, value)), None) => {
1893                BlobTraceUpdates::Row(ColumnarRecords::new(key, value, timestamps, diffs))
1894            }
1895            (Some((key, value)), Some(ext)) => {
1896                BlobTraceUpdates::Both(ColumnarRecords::new(key, value, timestamps, diffs), ext)
1897            }
1898            (None, Some(ext)) => BlobTraceUpdates::Structured {
1899                key_values: ext,
1900                timestamps,
1901                diffs,
1902            },
1903            (None, None) => unreachable!(),
1904        }
1905    }
1906}
1907
1908/// This represents the serde encoding for [`LeasedBatchPart`]. We expose the struct
1909/// itself (unlike other encodable structs) to attempt to provide stricter drop
1910/// semantics on `LeasedBatchPart`, i.e. `SerdeLeasedBatchPart` is exchangeable
1911/// (including over the network), where `LeasedBatchPart` is not.
1912///
1913/// For more details see documentation and comments on:
1914/// - [`LeasedBatchPart`]
1915/// - `From<SerdeLeasedBatchPart>` for `LeasedBatchPart<T>`
1916#[derive(Debug, Serialize, Deserialize, Clone)]
1917pub struct ExchangeableBatchPart<T> {
1918    shard_id: ShardId,
1919    // Duplicated with the one serialized in the proto for use in backpressure.
1920    encoded_size_bytes: usize,
1921    desc: Description<T>,
1922    filter: FetchBatchFilter<T>,
1923    part: LazyProto<ProtoHollowBatchPart>,
1924    /// The id of the reader that leased this part. See the corresponding field
1925    /// on [LeasedBatchPart].
1926    reader_id: LeasedReaderId,
1927    filter_pushdown_audit: bool,
1928}
1929
1930impl<T> ExchangeableBatchPart<T> {
1931    /// Returns the encoded size of the given part.
1932    pub fn encoded_size_bytes(&self) -> usize {
1933        self.encoded_size_bytes
1934    }
1935
1936    /// Returns the id of the reader that leased this part.
1937    pub fn reader_id(&self) -> &LeasedReaderId {
1938        &self.reader_id
1939    }
1940}
1941
1942/// Format we'll use when decoding a [`Part`].
1943///
1944/// [`Part`]: mz_persist_types::part::Part
1945#[derive(Debug, Copy, Clone)]
1946pub enum PartDecodeFormat {
1947    /// Decode from opaque `Codec` data.
1948    Row {
1949        /// Will also decode the structured data, and validate it matches.
1950        validate_structured: bool,
1951    },
1952    /// Decode from arrow data
1953    Arrow,
1954}
1955
1956impl PartDecodeFormat {
1957    /// Returns a default value for [`PartDecodeFormat`].
1958    pub const fn default() -> Self {
1959        PartDecodeFormat::Arrow
1960    }
1961
1962    /// Parses a [`PartDecodeFormat`] from the provided string, falling back to the default if the
1963    /// provided value is unrecognized.
1964    pub fn from_str(s: &str) -> Self {
1965        match s {
1966            "row" => PartDecodeFormat::Row {
1967                validate_structured: false,
1968            },
1969            "row_with_validate" => PartDecodeFormat::Row {
1970                validate_structured: true,
1971            },
1972            "arrow" => PartDecodeFormat::Arrow,
1973            x => {
1974                let default = PartDecodeFormat::default();
1975                soft_panic_or_log!("Invalid part decode format: '{x}', falling back to {default}");
1976                default
1977            }
1978        }
1979    }
1980
1981    /// Returns a string representation of [`PartDecodeFormat`].
1982    pub const fn as_str(&self) -> &'static str {
1983        match self {
1984            PartDecodeFormat::Row {
1985                validate_structured: false,
1986            } => "row",
1987            PartDecodeFormat::Row {
1988                validate_structured: true,
1989            } => "row_with_validate",
1990            PartDecodeFormat::Arrow => "arrow",
1991        }
1992    }
1993}
1994
1995impl fmt::Display for PartDecodeFormat {
1996    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1997        f.write_str(self.as_str())
1998    }
1999}
2000
2001#[mz_ore::test]
2002fn client_exchange_data() {
2003    // The whole point of SerdeLeasedBatchPart is that it can be exchanged
2004    // between timely workers, including over the network. Enforce then that it
2005    // implements ExchangeData.
2006    fn is_exchange_data<T: timely::ExchangeData>() {}
2007    is_exchange_data::<ExchangeableBatchPart<u64>>();
2008    is_exchange_data::<ExchangeableBatchPart<u64>>();
2009}
2010
2011#[cfg(test)]
2012mod tests;