1use 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 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 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 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#[derive(Debug)]
168pub struct BatchFetcher<K, V, T, D>
169where
170 T: Timestamp + Lattice + Codec64,
171 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 pub(crate) _phantom: PhantomData<fn() -> (K, V, T, D)>,
188}
189
190impl<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 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 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
330const MISSING_BLOB_DIAGNOSIS_TIMEOUT: Duration = Duration::from_secs(30);
332
333#[derive(Debug)]
335pub enum MissingBlobDiagnosis {
336 LeaseExpired {
338 reader_id: LeasedReaderId,
340 },
341 ShardTombstoned {
343 reader_id: LeasedReaderId,
345 },
346 LeasePresent {
348 reader_id: LeasedReaderId,
350 lease_state: String,
352 },
353 Unknown {
355 reader_id: LeasedReaderId,
357 },
358}
359
360#[derive(Debug)]
362pub(crate) enum MissingBlobExit {
363 LeaseExpired,
365 Halt,
367 Panic,
369}
370
371impl MissingBlobDiagnosis {
372 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 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
421pub(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 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 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 if !as_of.less_than(t) {
487 return false;
488 }
489
490 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
510pub(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 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 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 .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#[derive(Clone, Debug)]
702pub struct Lease(Arc<SeqNo>);
703
704impl Lease {
705 pub fn new(seqno: SeqNo) -> Self {
707 Self(Arc::new(seqno))
708 }
709
710 pub fn seqno(&self) -> SeqNo {
712 *self.0
713 }
714
715 pub fn count(&self) -> usize {
717 Arc::strong_count(&self.0)
718 }
719}
720
721#[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 pub(crate) lease: Lease,
756 pub(crate) reader_id: LeasedReaderId,
760 pub(crate) filter_pushdown_audit: bool,
761 pub(crate) bounds_truncated: bool,
766}
767
768impl<T> LeasedBatchPart<T>
769where
770 T: Timestamp + Codec64,
771{
772 pub(crate) fn into_exchangeable_part(self) -> (ExchangeableBatchPart<T>, Lease) {
782 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 pub fn encoded_size_bytes(&self) -> usize {
798 self.part.encoded_size_bytes()
799 }
800
801 pub fn request_filter_pushdown_audit(&mut self) {
806 self.filter_pushdown_audit = true;
807 }
808
809 pub fn stats(&self) -> Option<PartStats> {
814 self.part.stats().and_then(|x| x.try_decode().ok())
815 }
816
817 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 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 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 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 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 fn drop(&mut self) {
908 self.metrics.lease.dropped_part.inc()
909 }
910}
911
912#[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
962pub struct ShardSourcePart<K: Codec, V: Codec, T, D> {
965 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 pub fn parse(&self) -> ShardSourcePart<K, V, T, D> {
989 self.parse_internal(&self.fetch_config)
990 }
991
992 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 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#[derive(Debug)]
1056pub struct FetchedPart<K: Codec, V: Codec, T, D> {
1057 metrics: Arc<Metrics>,
1058 ts_filter: FetchBatchFilter<T>,
1059 rows: Option<DecodedRows<K, V>>,
1062 batches: Option<EncodedPartBatches<T>>,
1064 part_decode_format: PartDecodeFormat,
1065 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#[derive(Debug)]
1078struct DecodedRows<K: Codec, V: Codec> {
1079 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 fn next_batch(&mut self) -> bool {
1168 let Some(batches) = self.batches.as_mut() else {
1169 return false;
1170 };
1171 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 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 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 BlobTraceUpdates::Row(records) => EitherOrBoth::Left(records),
1255 BlobTraceUpdates::Structured { key_values, .. } => EitherOrBoth::Right(
1256 downcast_structured(key_values, true).expect("valid schemas for structured data"),
1259 ),
1260 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 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#[derive(Debug)]
1299pub(crate) struct EncodedPart<T> {
1300 part: BlobTraceBatchPart<T>,
1301 normalization: PartNormalization<T>,
1302}
1303
1304#[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 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#[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#[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 .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 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 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 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 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 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 continue;
1469 } else {
1470 break;
1471 };
1472
1473 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 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 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 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 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 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 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 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 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 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(×tamps, |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(×tamps, |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 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(×tamps).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(×tamps, 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#[derive(Debug, Serialize, Deserialize, Clone)]
1917pub struct ExchangeableBatchPart<T> {
1918 shard_id: ShardId,
1919 encoded_size_bytes: usize,
1921 desc: Description<T>,
1922 filter: FetchBatchFilter<T>,
1923 part: LazyProto<ProtoHollowBatchPart>,
1924 reader_id: LeasedReaderId,
1927 filter_pushdown_audit: bool,
1928}
1929
1930impl<T> ExchangeableBatchPart<T> {
1931 pub fn encoded_size_bytes(&self) -> usize {
1933 self.encoded_size_bytes
1934 }
1935
1936 pub fn reader_id(&self) -> &LeasedReaderId {
1938 &self.reader_id
1939 }
1940}
1941
1942#[derive(Debug, Copy, Clone)]
1946pub enum PartDecodeFormat {
1947 Row {
1949 validate_structured: bool,
1951 },
1952 Arrow,
1954}
1955
1956impl PartDecodeFormat {
1957 pub const fn default() -> Self {
1959 PartDecodeFormat::Arrow
1960 }
1961
1962 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 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 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;