1use async_stream::stream;
13use std::collections::BTreeMap;
14use std::fmt::Debug;
15use std::future::Future;
16use std::sync::Arc;
17use std::time::{Duration, Instant};
18
19use differential_dataflow::Hashable;
20use differential_dataflow::consolidation::consolidate_updates;
21use differential_dataflow::difference::Monoid;
22use differential_dataflow::lattice::Lattice;
23use futures::Stream;
24use futures_util::{StreamExt, stream};
25use mz_dyncfg::{Config, ParameterScope};
26use mz_ore::cast::CastLossy;
27use mz_ore::halt;
28use mz_ore::instrument;
29use mz_ore::process::halt_with_code;
30use mz_ore::task::JoinHandle;
31use mz_persist::location::{Blob, SeqNo};
32use mz_persist_types::columnar::{ColumnDecoder, Schema};
33use mz_persist_types::{Codec, Codec64};
34use proptest_derive::Arbitrary;
35use serde::{Deserialize, Serialize};
36use timely::PartialOrder;
37use timely::order::TotalOrder;
38use timely::progress::{Antichain, Timestamp};
39use tracing::warn;
40use uuid::Uuid;
41
42use crate::batch::BLOB_TARGET_SIZE;
43use crate::cfg::{COMPACTION_MEMORY_BOUND_BYTES, RetryParameters};
44use crate::fetch::FetchConfig;
45use crate::fetch::{FetchBatchFilter, FetchedPart, Lease, LeasedBatchPart, fetch_leased_part};
46use crate::internal::encoding::Schemas;
47use crate::internal::machine::{Machine, next_listen_batch_retry_params};
48use crate::internal::metrics::{Metrics, ReadMetrics, ShardMetrics};
49use crate::internal::state::{HollowBatch, LeasedReaderState, SnapshotErr};
50use crate::internal::watch::{AwaitableState, StateWatch};
51use crate::iter::{Consolidator, StructuredSort};
52use crate::schema::SchemaCache;
53use crate::stats::{SnapshotPartStats, SnapshotPartsStats, SnapshotStats};
54use crate::{GarbageCollector, PersistConfig, ShardId, parse_id};
55
56pub use crate::internal::encoding::LazyPartStats;
57pub use crate::internal::state::Since;
58
59#[derive(
61 Arbitrary,
62 Clone,
63 PartialEq,
64 Eq,
65 PartialOrd,
66 Ord,
67 Hash,
68 Serialize,
69 Deserialize
70)]
71#[serde(try_from = "String", into = "String")]
72pub struct LeasedReaderId(pub(crate) [u8; 16]);
73
74impl std::fmt::Display for LeasedReaderId {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 write!(f, "r{}", Uuid::from_bytes(self.0))
77 }
78}
79
80impl std::fmt::Debug for LeasedReaderId {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 write!(f, "LeasedReaderId({})", Uuid::from_bytes(self.0))
83 }
84}
85
86impl std::str::FromStr for LeasedReaderId {
87 type Err = String;
88
89 fn from_str(s: &str) -> Result<Self, Self::Err> {
90 parse_id("r", "LeasedReaderId", s).map(LeasedReaderId)
91 }
92}
93
94impl From<LeasedReaderId> for String {
95 fn from(reader_id: LeasedReaderId) -> Self {
96 reader_id.to_string()
97 }
98}
99
100impl TryFrom<String> for LeasedReaderId {
101 type Error = String;
102
103 fn try_from(s: String) -> Result<Self, Self::Error> {
104 s.parse()
105 }
106}
107
108impl LeasedReaderId {
109 pub(crate) fn new() -> Self {
110 LeasedReaderId(*Uuid::new_v4().as_bytes())
111 }
112}
113
114#[derive(Debug)]
119pub struct Subscribe<K: Codec, V: Codec, T, D> {
120 snapshot: Option<Vec<LeasedBatchPart<T>>>,
121 listen: Listen<K, V, T, D>,
122}
123
124impl<K, V, T, D> Subscribe<K, V, T, D>
125where
126 K: Debug + Codec,
127 V: Debug + Codec,
128 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
129 D: Monoid + Codec64 + Send + Sync,
130{
131 fn new(snapshot_parts: Vec<LeasedBatchPart<T>>, listen: Listen<K, V, T, D>) -> Self {
132 Subscribe {
133 snapshot: Some(snapshot_parts),
134 listen,
135 }
136 }
137
138 #[instrument(level = "debug", fields(shard = %self.listen.handle.machine.shard_id()))]
146 pub async fn next(
147 &mut self,
148 listen_retry: Option<RetryParameters>,
150 ) -> Vec<ListenEvent<T, LeasedBatchPart<T>>> {
151 match self.snapshot.take() {
152 Some(parts) => vec![ListenEvent::Updates(parts)],
153 None => {
154 let (parts, upper) = self.listen.next(listen_retry).await;
155 vec![ListenEvent::Updates(parts), ListenEvent::Progress(upper)]
156 }
157 }
158 }
159}
160
161impl<K, V, T, D> Subscribe<K, V, T, D>
162where
163 K: Debug + Codec,
164 V: Debug + Codec,
165 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
166 D: Monoid + Codec64 + Send + Sync,
167{
168 #[instrument(level = "debug", fields(shard = %self.listen.handle.machine.shard_id()))]
171 pub async fn fetch_next(&mut self) -> Vec<ListenEvent<T, ((K, V), T, D)>> {
172 let events = self.next(None).await;
173 let new_len = events
174 .iter()
175 .map(|event| match event {
176 ListenEvent::Updates(parts) => parts.len(),
177 ListenEvent::Progress(_) => 1,
178 })
179 .sum();
180 let mut ret = Vec::with_capacity(new_len);
181 for event in events {
182 match event {
183 ListenEvent::Updates(parts) => {
184 for part in parts {
185 let fetched_part = self.listen.fetch_batch_part(part).await;
186 let updates = fetched_part.collect::<Vec<_>>();
187 if !updates.is_empty() {
188 ret.push(ListenEvent::Updates(updates));
189 }
190 }
191 }
192 ListenEvent::Progress(progress) => ret.push(ListenEvent::Progress(progress)),
193 }
194 }
195 ret
196 }
197
198 pub async fn fetch_batch_part(&mut self, part: LeasedBatchPart<T>) -> FetchedPart<K, V, T, D> {
200 self.listen.fetch_batch_part(part).await
201 }
202
203 #[doc(hidden)]
206 pub async fn expire_lease_for_tests(&self) {
207 let handle = &self.listen.handle;
208 let _ = handle.machine.expire_leased_reader(&handle.reader_id).await;
209 }
210}
211
212impl<K, V, T, D> Subscribe<K, V, T, D>
213where
214 K: Debug + Codec,
215 V: Debug + Codec,
216 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
217 D: Monoid + Codec64 + Send + Sync,
218{
219 pub async fn expire(mut self) {
226 let _ = self.snapshot.take(); self.listen.expire().await;
228 }
229}
230
231#[derive(Debug, PartialEq)]
235pub enum ListenEvent<T, D> {
236 Progress(Antichain<T>),
238 Updates(Vec<D>),
240}
241
242#[derive(Debug)]
244pub struct Listen<K: Codec, V: Codec, T, D> {
245 handle: ReadHandle<K, V, T, D>,
246 as_of: Antichain<T>,
247 since: Antichain<T>,
248 frontier: Antichain<T>,
249}
250
251impl<K, V, T, D> Listen<K, V, T, D>
252where
253 K: Debug + Codec,
254 V: Debug + Codec,
255 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
256 D: Monoid + Codec64 + Send + Sync,
257{
258 async fn new(
259 mut handle: ReadHandle<K, V, T, D>,
260 as_of: Antichain<T>,
261 ) -> Result<Self, Since<T>> {
262 let () = handle.machine.verify_listen(&as_of)?;
263
264 let since = as_of.clone();
265 if !PartialOrder::less_equal(handle.since(), &since) {
266 return Err(Since(handle.since().clone()));
269 }
270 handle.downgrade_since(&since).await;
274 Ok(Listen {
275 handle,
276 since,
277 frontier: as_of.clone(),
278 as_of,
279 })
280 }
281
282 pub fn frontier(&self) -> &Antichain<T> {
284 &self.frontier
285 }
286
287 pub async fn next(
295 &mut self,
296 retry: Option<RetryParameters>,
298 ) -> (Vec<LeasedBatchPart<T>>, Antichain<T>) {
299 let retry = retry
301 .unwrap_or_else(|| next_listen_batch_retry_params(&self.handle.machine.applier.cfg));
302 self.handle
303 .machine
304 .wait_for_upper_past(
305 &self.frontier,
306 &mut self.handle.watch,
307 Some(&self.handle.reader_id),
308 &self.handle.metrics.retries.next_listen_batch,
309 retry,
310 )
311 .await;
312
313 let lease = self.handle.lease_seqno().await;
315 let batch = match self
316 .handle
317 .machine
318 .applier
319 .next_listen_batch(&self.frontier)
320 {
321 Ok(batch) => batch,
322 Err(seqno) => {
323 panic!(
324 "waited for upper past {frontier:?}, but no listen batch was available at {seqno:?}!",
325 frontier = self.frontier.elements()
326 );
327 }
328 };
329
330 let acceptable_desc = PartialOrder::less_than(batch.desc.since(), &self.frontier)
340 || (self.frontier == self.as_of
345 && PartialOrder::less_equal(batch.desc.since(), &self.frontier));
346 if !acceptable_desc {
347 let lease_state = self
348 .handle
349 .machine
350 .applier
351 .reader_lease(self.handle.reader_id.clone());
352 if let Some(lease) = lease_state {
353 panic!(
354 "Listen on {} received a batch {:?} advanced past the listen frontier {:?}, but the lease has not expired: {:?}",
355 self.handle.machine.shard_id(),
356 batch.desc,
357 self.frontier,
358 lease
359 )
360 } else if self.handle.machine.applier.is_tombstone() {
361 halt!(
363 "Listen on {} received a batch {:?} advanced past the listen frontier {:?} after the shard was tombstoned",
364 self.handle.machine.shard_id(),
365 batch.desc,
366 self.frontier
367 )
368 } else {
369 halt_with_code(
372 READER_LEASE_EXPIRED_EXIT_CODE,
373 format_args!(
374 "Listen on {} received a batch {:?} advanced past the listen frontier {:?} after the reader has expired. \
375 This can happen in exceptional cases: a machine goes to sleep or is running out of memory or CPU, for example.",
376 self.handle.machine.shard_id(),
377 batch.desc,
378 self.frontier
379 ),
380 )
381 }
382 }
383
384 let new_frontier = batch.desc.upper().clone();
385
386 for x in self.frontier.elements().iter() {
409 let less_than_upper = batch.desc.upper().elements().iter().any(|u| x.less_than(u));
410 if less_than_upper {
411 self.since.join_assign(&Antichain::from_elem(x.clone()));
412 }
413 }
414
415 let filter = FetchBatchFilter::Listen {
420 as_of: self.as_of.clone(),
421 lower: self.frontier.clone(),
422 };
423 let parts = self
424 .handle
425 .lease_batch_parts(lease, batch, filter)
426 .collect()
427 .await;
428
429 self.handle.maybe_downgrade_since(&self.since).await;
430
431 self.frontier = new_frontier;
434
435 (parts, self.frontier.clone())
436 }
437}
438
439impl<K, V, T, D> Listen<K, V, T, D>
440where
441 K: Debug + Codec,
442 V: Debug + Codec,
443 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
444 D: Monoid + Codec64 + Send + Sync,
445{
446 #[instrument(level = "debug", name = "listen::next", fields(shard = %self.handle.machine.shard_id()))]
457 pub async fn fetch_next(&mut self) -> Vec<ListenEvent<T, ((K, V), T, D)>> {
458 let (parts, progress) = self.next(None).await;
459 let mut ret = Vec::with_capacity(parts.len() + 1);
460 for part in parts {
461 let fetched_part = self.fetch_batch_part(part).await;
462 let updates = fetched_part.collect::<Vec<_>>();
463 if !updates.is_empty() {
464 ret.push(ListenEvent::Updates(updates));
465 }
466 }
467 ret.push(ListenEvent::Progress(progress));
468 ret
469 }
470
471 pub fn into_stream(mut self) -> impl Stream<Item = ListenEvent<T, ((K, V), T, D)>> {
473 async_stream::stream!({
474 loop {
475 for msg in self.fetch_next().await {
476 yield msg;
477 }
478 }
479 })
480 }
481
482 #[cfg(test)]
486 #[track_caller]
487 pub async fn read_until(&mut self, ts: &T) -> (Vec<((K, V), T, D)>, Antichain<T>) {
488 let mut updates = Vec::new();
489 let mut frontier = Antichain::from_elem(T::minimum());
490 while self.frontier.less_than(ts) {
491 for event in self.fetch_next().await {
492 match event {
493 ListenEvent::Updates(mut x) => updates.append(&mut x),
494 ListenEvent::Progress(x) => frontier = x,
495 }
496 }
497 }
498 (updates, frontier)
501 }
502}
503
504impl<K, V, T, D> Listen<K, V, T, D>
505where
506 K: Debug + Codec,
507 V: Debug + Codec,
508 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
509 D: Monoid + Codec64 + Send + Sync,
510{
511 async fn fetch_batch_part(&mut self, part: LeasedBatchPart<T>) -> FetchedPart<K, V, T, D> {
516 let fetched_part = fetch_leased_part(
517 &self.handle.cfg,
518 &part,
519 self.handle.blob.as_ref(),
520 Arc::clone(&self.handle.metrics),
521 &self.handle.metrics.read.listen,
522 &self.handle.machine.applier.shard_metrics,
523 &self.handle.reader_id,
524 self.handle.read_schemas.clone(),
525 &mut self.handle.schema_cache,
526 )
527 .await;
528 fetched_part
529 }
530
531 pub async fn expire(self) {
538 self.handle.expire().await
539 }
540}
541
542#[derive(Debug)]
545pub(crate) struct ReadHolds<T> {
546 held_since: Antichain<T>,
548 applied_since: Antichain<T>,
551 recent_seqno: SeqNo,
553 leases: BTreeMap<SeqNo, Lease>,
556 expired: bool,
558 request_sync: bool,
561}
562
563impl<T> ReadHolds<T>
564where
565 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
566{
567 pub fn downgrade_since(&mut self, since: &Antichain<T>) {
568 self.held_since.join_assign(since);
569 }
570
571 pub fn observe_seqno(&mut self, seqno: SeqNo) {
572 self.recent_seqno = seqno.max(self.recent_seqno);
573 }
574
575 pub fn lease_seqno(&mut self) -> Lease {
576 let seqno = self.recent_seqno;
577 let lease = self
578 .leases
579 .entry(seqno)
580 .or_insert_with(|| Lease::new(seqno));
581 lease.clone()
582 }
583
584 pub fn outstanding_seqno(&mut self) -> SeqNo {
585 while let Some(first) = self.leases.first_entry() {
586 if first.get().count() <= 1 {
587 first.remove();
588 } else {
589 return *first.key();
590 }
591 }
592 self.recent_seqno
593 }
594}
595
596#[derive(Debug)]
617pub struct ReadHandle<K: Codec, V: Codec, T, D> {
618 pub(crate) cfg: PersistConfig,
619 pub(crate) metrics: Arc<Metrics>,
620 pub(crate) machine: Machine<K, V, T, D>,
621 pub(crate) gc: GarbageCollector<K, V, T, D>,
622 pub(crate) blob: Arc<dyn Blob>,
623 watch: StateWatch<K, V, T, D>,
624
625 pub(crate) reader_id: LeasedReaderId,
626 pub(crate) read_schemas: Schemas<K, V>,
627 pub(crate) schema_cache: SchemaCache<K, V, T, D>,
628
629 since: Antichain<T>,
630 pub(crate) hold_state: AwaitableState<ReadHolds<T>>,
631 pub(crate) unexpired_state: Option<UnexpiredReadHandleState>,
632}
633
634pub const READER_LEASE_EXPIRED_EXIT_CODE: i32 = 168;
640
641pub(crate) const READER_LEASE_DURATION: Config<Duration> = Config::new(
644 "persist_reader_lease_duration",
645 Duration::from_secs(60 * 15),
646 "The time after which we'll clean up stale read leases",
647 ParameterScope::Environment,
648);
649
650impl<K, V, T, D> ReadHandle<K, V, T, D>
651where
652 K: Debug + Codec,
653 V: Debug + Codec,
654 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
655 D: Monoid + Codec64 + Send + Sync,
656{
657 #[allow(clippy::unused_async)]
658 pub(crate) async fn new(
659 cfg: PersistConfig,
660 metrics: Arc<Metrics>,
661 machine: Machine<K, V, T, D>,
662 gc: GarbageCollector<K, V, T, D>,
663 blob: Arc<dyn Blob>,
664 reader_id: LeasedReaderId,
665 read_schemas: Schemas<K, V>,
666 state: LeasedReaderState<T>,
667 ) -> Self {
668 let schema_cache = machine.applier.schema_cache();
669 let hold_state = AwaitableState::new(ReadHolds {
670 held_since: state.since.clone(),
671 applied_since: state.since.clone(),
672 recent_seqno: state.seqno,
673 leases: Default::default(),
674 expired: false,
675 request_sync: false,
676 });
677 ReadHandle {
678 cfg,
679 metrics: Arc::clone(&metrics),
680 machine: machine.clone(),
681 gc: gc.clone(),
682 blob,
683 watch: machine.applier.watch(),
684 reader_id: reader_id.clone(),
685 read_schemas,
686 schema_cache,
687 since: state.since,
688 hold_state: hold_state.clone(),
689 unexpired_state: Some(UnexpiredReadHandleState {
690 heartbeat_task: Self::start_reader_heartbeat_task(
691 machine, reader_id, gc, hold_state,
692 ),
693 }),
694 }
695 }
696
697 fn start_reader_heartbeat_task(
698 machine: Machine<K, V, T, D>,
699 reader_id: LeasedReaderId,
700 gc: GarbageCollector<K, V, T, D>,
701 leased_seqnos: AwaitableState<ReadHolds<T>>,
702 ) -> JoinHandle<()> {
703 let metrics = Arc::clone(&machine.applier.metrics);
704 let name = format!(
705 "persist::heartbeat_read({},{})",
706 machine.shard_id(),
707 reader_id
708 );
709 mz_ore::task::spawn(|| name, {
710 metrics.tasks.heartbeat_read.instrument_task(async move {
711 Self::reader_heartbeat_task(machine, reader_id, gc, leased_seqnos).await
712 })
713 })
714 }
715
716 async fn reader_heartbeat_task(
717 machine: Machine<K, V, T, D>,
718 reader_id: LeasedReaderId,
719 gc: GarbageCollector<K, V, T, D>,
720 leased_seqnos: AwaitableState<ReadHolds<T>>,
721 ) {
722 let sleep_duration = READER_LEASE_DURATION.get(&machine.applier.cfg) / 4;
723 let jitter: f64 = f64::cast_lossy(reader_id.hashed()) / f64::cast_lossy(u64::MAX);
726 let mut interval = tokio::time::interval_at(
727 tokio::time::Instant::now() + sleep_duration.mul_f64(jitter),
728 sleep_duration,
729 );
730 let mut held_since = leased_seqnos.read(|s| s.held_since.clone());
731 loop {
732 let before_sleep = Instant::now();
733 let _woke_by_tick = tokio::select! {
734 _tick = interval.tick() => {
735 true
736 }
737 _whatever = leased_seqnos.wait_while(|s| !s.request_sync) => {
738 false
739 }
740 };
741
742 let elapsed_since_before_sleeping = before_sleep.elapsed();
743 if elapsed_since_before_sleeping > sleep_duration + Duration::from_secs(60) {
744 warn!(
745 "reader ({}) of shard ({}) went {}s between heartbeats",
746 reader_id,
747 machine.shard_id(),
748 elapsed_since_before_sleeping.as_secs_f64()
749 );
750 }
751
752 let before_heartbeat = Instant::now();
753 let current_seqno = machine.seqno();
754 let result = leased_seqnos.modify(|s| {
755 if s.expired {
756 Err(())
757 } else {
758 s.observe_seqno(current_seqno);
759 s.request_sync = false;
760 held_since.join_assign(&s.held_since);
761 Ok(s.outstanding_seqno())
762 }
763 });
764 let actual_since = match result {
765 Ok(held_seqno) => {
766 let (seqno, actual_since, maintenance) = machine
767 .downgrade_since(&reader_id, held_seqno, &held_since)
768 .await;
769 leased_seqnos.modify(|s| {
770 s.applied_since.clone_from(&actual_since.0);
771 s.observe_seqno(seqno)
772 });
773 maintenance.start_performing(&machine, &gc);
774 actual_since
775 }
776 Err(()) => {
777 let (seqno, maintenance) = machine.expire_leased_reader(&reader_id).await;
778 leased_seqnos.modify(|s| s.observe_seqno(seqno));
779 maintenance.start_performing(&machine, &gc);
780 break;
781 }
782 };
783
784 let elapsed_since_heartbeat = before_heartbeat.elapsed();
785 if elapsed_since_heartbeat > Duration::from_secs(60) {
786 warn!(
787 "reader ({}) of shard ({}) heartbeat call took {}s",
788 reader_id,
789 machine.shard_id(),
790 elapsed_since_heartbeat.as_secs_f64(),
791 );
792 }
793
794 if PartialOrder::less_than(&held_since, &actual_since.0) {
795 warn!(
803 "heartbeat task for reader ({}) of shard ({}) exiting due to expired lease \
804 while read handle is live",
805 reader_id,
806 machine.shard_id(),
807 );
808 return;
809 }
810 }
811 }
812
813 pub fn shard_id(&self) -> ShardId {
815 self.machine.shard_id()
816 }
817
818 pub fn since(&self) -> &Antichain<T> {
822 &self.since
823 }
824
825 pub fn shared_upper(&self) -> Antichain<T> {
831 self.machine.applier.clone_upper()
832 }
833
834 #[cfg(test)]
835 fn outstanding_seqno(&self) -> SeqNo {
836 let current_seqno = self.machine.seqno();
837 self.hold_state.modify(|s| {
838 s.observe_seqno(current_seqno);
839 s.outstanding_seqno()
840 })
841 }
842
843 #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
850 pub async fn downgrade_since(&mut self, new_since: &Antichain<T>) {
851 self.since = new_since.clone();
852 self.hold_state.modify(|s| {
853 s.downgrade_since(new_since);
854 s.request_sync = true;
855 });
856 self.hold_state
857 .wait_while(|s| PartialOrder::less_than(&s.applied_since, new_since))
858 .await;
859 }
860
861 #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
878 pub async fn listen(self, as_of: Antichain<T>) -> Result<Listen<K, V, T, D>, Since<T>> {
879 Listen::new(self, as_of).await
880 }
881
882 async fn snapshot_batches(
883 &mut self,
884 as_of: Antichain<T>,
885 ) -> Result<(Lease, Vec<HollowBatch<T>>), Since<T>> {
886 self.machine
887 .wait_for_upper_past(
888 &as_of,
889 &mut self.watch,
890 Some(&self.reader_id),
891 &self.metrics.retries.snapshot,
892 RetryParameters::persist_defaults(),
893 )
894 .await;
895 let lease = self.lease_seqno().await;
896 let batches = match self.machine.applier.snapshot(&as_of) {
897 Ok(data) => data,
898 Err(SnapshotErr::AsOfHistoricalDistinctionsLost(since)) => return Err(since),
899 Err(SnapshotErr::AsOfNotYetAvailable(seqno, upper)) => {
900 panic!(
901 "waited for upper past {as_of:?}, but at latest seqno {seqno:?} the frontier was only {upper:?}",
902 as_of = as_of.elements(),
903 upper = upper.0.elements(),
904 )
905 }
906 };
907 Ok((lease, batches))
908 }
909
910 #[instrument(level = "trace", fields(shard = %self.machine.shard_id()))]
924 pub async fn snapshot(
925 &mut self,
926 as_of: Antichain<T>,
927 ) -> Result<Vec<LeasedBatchPart<T>>, Since<T>> {
928 let (lease, batches) = self.snapshot_batches(as_of.clone()).await?;
929
930 if !PartialOrder::less_equal(self.since(), &as_of) {
931 return Err(Since(self.since().clone()));
932 }
933
934 let filter = FetchBatchFilter::Snapshot { as_of };
935 let mut leased_parts = Vec::new();
936 for batch in batches {
937 leased_parts.extend(
942 self.lease_batch_parts(lease.clone(), batch, filter.clone())
943 .collect::<Vec<_>>()
944 .await,
945 );
946 }
947 Ok(leased_parts)
948 }
949
950 #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
956 pub async fn subscribe(
957 mut self,
958 as_of: Antichain<T>,
959 ) -> Result<Subscribe<K, V, T, D>, Since<T>> {
960 let snapshot_parts = self.snapshot(as_of.clone()).await?;
961 let listen = self.listen(as_of.clone()).await?;
962 Ok(Subscribe::new(snapshot_parts, listen))
963 }
964
965 fn lease_batch_parts(
966 &mut self,
967 lease: Lease,
968 batch: HollowBatch<T>,
969 filter: FetchBatchFilter<T>,
970 ) -> impl Stream<Item = LeasedBatchPart<T>> + '_ {
971 stream! {
972 let blob = Arc::clone(&self.blob);
973 let metrics = Arc::clone(&self.metrics);
974 let desc = batch.desc.clone();
975 let bounds_truncated = batch.runs().any(|(meta, _)| meta.bounds_truncated());
976 for await part in batch.part_stream(self.shard_id(), &*blob, &*metrics) {
977 yield LeasedBatchPart {
978 metrics: Arc::clone(&self.metrics),
979 shard_id: self.machine.shard_id(),
980 filter: filter.clone(),
981 desc: desc.clone(),
982 part: part.expect("leased part").into_owned(),
983 lease: lease.clone(),
984 reader_id: self.reader_id.clone(),
985 filter_pushdown_audit: false,
986 bounds_truncated,
987 }
988 }
989 }
990 }
991
992 async fn lease_seqno(&mut self) -> Lease {
1002 let current_seqno = self.machine.seqno();
1003 let lease = self.hold_state.modify(|s| {
1004 s.observe_seqno(current_seqno);
1005 s.lease_seqno()
1006 });
1007 self.watch.wait_for_seqno_ge(lease.seqno()).await;
1012 lease
1013 }
1014
1015 #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
1018 pub async fn clone(&self, purpose: &str) -> Self {
1019 let new_reader_id = LeasedReaderId::new();
1020 let machine = self.machine.clone();
1021 let gc = self.gc.clone();
1022 let (reader_state, maintenance) = machine
1023 .register_leased_reader(
1024 &new_reader_id,
1025 purpose,
1026 READER_LEASE_DURATION.get(&self.cfg),
1027 false,
1028 )
1029 .await;
1030 maintenance.start_performing(&machine, &gc);
1031 assert!(PartialOrder::less_equal(&reader_state.since, &self.since));
1035 let new_reader = ReadHandle::new(
1036 self.cfg.clone(),
1037 Arc::clone(&self.metrics),
1038 machine,
1039 gc,
1040 Arc::clone(&self.blob),
1041 new_reader_id,
1042 self.read_schemas.clone(),
1043 reader_state,
1044 )
1045 .await;
1046 new_reader
1047 }
1048
1049 #[allow(clippy::unused_async)]
1054 pub async fn maybe_downgrade_since(&mut self, new_since: &Antichain<T>) {
1055 self.since = new_since.clone();
1056 self.hold_state.modify(|s| {
1057 s.downgrade_since(new_since);
1058 });
1059 }
1060
1061 #[instrument(level = "debug", fields(shard = %self.machine.shard_id()))]
1067 pub async fn expire(mut self) {
1068 self.hold_state.modify(|s| {
1069 s.expired = true;
1070 s.request_sync = true;
1071 });
1072 let Some(unexpired_state) = self.unexpired_state.take() else {
1073 return;
1074 };
1075 unexpired_state.heartbeat_task.await;
1076 }
1077
1078 #[cfg(test)]
1080 #[track_caller]
1081 pub async fn expect_listen(self, as_of: T) -> Listen<K, V, T, D> {
1082 self.listen(Antichain::from_elem(as_of))
1083 .await
1084 .expect("cannot serve requested as_of")
1085 }
1086}
1087
1088#[derive(Debug)]
1090pub(crate) struct UnexpiredReadHandleState {
1091 pub(crate) heartbeat_task: JoinHandle<()>,
1092}
1093
1094#[derive(Debug)]
1100pub struct Cursor<K: Codec, V: Codec, T: Timestamp + Codec64, D: Codec64, L = Lease> {
1101 consolidator: Consolidator<T, D, StructuredSort<K, V, T, D>>,
1102 max_len: usize,
1103 max_bytes: usize,
1104 _lease: L,
1105 read_schemas: Schemas<K, V>,
1106}
1107
1108impl<K: Codec, V: Codec, T: Timestamp + Codec64, D: Codec64, L> Cursor<K, V, T, D, L> {
1109 pub fn into_lease(self: Self) -> L {
1112 self._lease
1113 }
1114}
1115
1116impl<K, V, T, D, L> Cursor<K, V, T, D, L>
1117where
1118 K: Debug + Codec + Ord,
1119 V: Debug + Codec + Ord,
1120 T: Timestamp + Lattice + Codec64 + Sync,
1121 D: Monoid + Ord + Codec64 + Send + Sync,
1122{
1123 pub async fn next(&mut self) -> Option<impl Iterator<Item = ((K, V), T, D)> + '_> {
1125 let Self {
1126 consolidator,
1127 max_len,
1128 max_bytes,
1129 _lease,
1130 read_schemas: _,
1131 } = self;
1132
1133 let part = consolidator
1134 .next_chunk(*max_len, *max_bytes)
1135 .await
1136 .expect("fetching a leased part")?;
1137 let key_decoder = self
1138 .read_schemas
1139 .key
1140 .decoder_any(part.key.as_ref())
1141 .expect("ok");
1142 let val_decoder = self
1143 .read_schemas
1144 .val
1145 .decoder_any(part.val.as_ref())
1146 .expect("ok");
1147 let iter = (0..part.len()).map(move |i| {
1148 let mut k = K::default();
1149 let mut v = V::default();
1150 key_decoder.decode(i, &mut k);
1151 val_decoder.decode(i, &mut v);
1152 let t = T::decode(part.time.value(i).to_le_bytes());
1153 let d = D::decode(part.diff.value(i).to_le_bytes());
1154 ((k, v), t, d)
1155 });
1156
1157 Some(iter)
1158 }
1159}
1160
1161impl<K, V, T, D> ReadHandle<K, V, T, D>
1162where
1163 K: Debug + Codec + Ord,
1164 V: Debug + Codec + Ord,
1165 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
1166 D: Monoid + Ord + Codec64 + Send + Sync,
1167{
1168 pub async fn snapshot_and_fetch(
1182 &mut self,
1183 as_of: Antichain<T>,
1184 ) -> Result<Vec<((K, V), T, D)>, Since<T>> {
1185 let mut cursor = self.snapshot_cursor(as_of, |_| true).await?;
1186 let mut contents = Vec::new();
1187 while let Some(iter) = cursor.next().await {
1188 contents.extend(iter);
1189 }
1190
1191 let old_len = contents.len();
1194 consolidate_updates(&mut contents);
1195 if old_len != contents.len() {
1196 self.machine
1198 .applier
1199 .shard_metrics
1200 .unconsolidated_snapshot
1201 .inc();
1202 }
1203
1204 Ok(contents)
1205 }
1206
1207 pub async fn snapshot_cursor(
1214 &mut self,
1215 as_of: Antichain<T>,
1216 should_fetch_part: impl for<'a> Fn(Option<&'a LazyPartStats>) -> bool,
1217 ) -> Result<Cursor<K, V, T, D>, Since<T>> {
1218 let (lease, batches) = self.snapshot_batches(as_of.clone()).await?;
1219
1220 Self::read_batches_consolidated(
1221 &self.cfg,
1222 Arc::clone(&self.metrics),
1223 Arc::clone(&self.machine.applier.shard_metrics),
1224 self.metrics.read.snapshot.clone(),
1225 Arc::clone(&self.blob),
1226 self.shard_id(),
1227 as_of,
1228 self.read_schemas.clone(),
1229 &batches,
1230 lease,
1231 should_fetch_part,
1232 COMPACTION_MEMORY_BOUND_BYTES.get(&self.cfg),
1233 )
1234 }
1235
1236 pub(crate) fn read_batches_consolidated<L>(
1237 persist_cfg: &PersistConfig,
1238 metrics: Arc<Metrics>,
1239 shard_metrics: Arc<ShardMetrics>,
1240 read_metrics: ReadMetrics,
1241 blob: Arc<dyn Blob>,
1242 shard_id: ShardId,
1243 as_of: Antichain<T>,
1244 schemas: Schemas<K, V>,
1245 batches: &[HollowBatch<T>],
1246 lease: L,
1247 should_fetch_part: impl for<'a> Fn(Option<&'a LazyPartStats>) -> bool,
1248 memory_budget_bytes: usize,
1249 ) -> Result<Cursor<K, V, T, D, L>, Since<T>> {
1250 let context = format!("{}[as_of={:?}]", shard_id, as_of.elements());
1251 let filter = FetchBatchFilter::Snapshot {
1252 as_of: as_of.clone(),
1253 };
1254
1255 let mut consolidator = Consolidator::new(
1256 context,
1257 FetchConfig::from_persist_config(persist_cfg),
1258 shard_id,
1259 StructuredSort::new(schemas.clone()),
1260 blob,
1261 metrics,
1262 shard_metrics,
1263 read_metrics,
1264 filter,
1265 None,
1266 memory_budget_bytes,
1267 );
1268 for batch in batches {
1269 for (meta, run) in batch.runs() {
1270 consolidator.enqueue_run(
1271 &batch.desc,
1272 meta,
1273 run.into_iter()
1274 .filter(|p| should_fetch_part(p.stats()))
1275 .cloned(),
1276 );
1277 }
1278 }
1279 let max_len = persist_cfg.compaction_yield_after_n_updates;
1283 let max_bytes = BLOB_TARGET_SIZE.get(persist_cfg).max(1);
1284
1285 Ok(Cursor {
1286 consolidator,
1287 max_len,
1288 max_bytes,
1289 _lease: lease,
1290 read_schemas: schemas,
1291 })
1292 }
1293
1294 pub fn snapshot_stats(
1306 &self,
1307 as_of: Option<Antichain<T>>,
1308 ) -> impl Future<Output = Result<SnapshotStats, Since<T>>> + Send + 'static {
1309 let machine = self.machine.clone();
1310 async move {
1311 let batches = match as_of {
1312 Some(as_of) => machine.unleased_snapshot(&as_of).await?,
1313 None => machine.applier.all_batches(),
1314 };
1315 let num_updates = batches.iter().map(|b| b.len).sum();
1316 Ok(SnapshotStats {
1317 shard_id: machine.shard_id(),
1318 num_updates,
1319 })
1320 }
1321 }
1322
1323 pub async fn snapshot_parts_stats(
1334 &self,
1335 as_of: Antichain<T>,
1336 ) -> Result<SnapshotPartsStats, Since<T>> {
1337 let batches = self.machine.unleased_snapshot(&as_of).await?;
1338 let parts = stream::iter(&batches)
1339 .flat_map(|b| b.part_stream(self.shard_id(), &*self.blob, &*self.metrics))
1340 .map(|p| {
1341 let p = p.expect("live batch");
1342 SnapshotPartStats {
1343 encoded_size_bytes: p.encoded_size_bytes(),
1344 stats: p.stats().cloned(),
1345 }
1346 })
1347 .collect()
1348 .await;
1349 Ok(SnapshotPartsStats {
1350 metrics: Arc::clone(&self.machine.applier.metrics),
1351 shard_id: self.machine.shard_id(),
1352 parts,
1353 })
1354 }
1355}
1356
1357impl<K, V, T, D> ReadHandle<K, V, T, D>
1358where
1359 K: Debug + Codec + Ord,
1360 V: Debug + Codec + Ord,
1361 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
1362 D: Monoid + Codec64 + Send + Sync,
1363{
1364 pub async fn snapshot_and_stream(
1369 &mut self,
1370 as_of: Antichain<T>,
1371 ) -> Result<impl Stream<Item = ((K, V), T, D)> + use<K, V, T, D>, Since<T>> {
1372 let snap = self.snapshot(as_of).await?;
1373
1374 let blob = Arc::clone(&self.blob);
1375 let metrics = Arc::clone(&self.metrics);
1376 let snapshot_metrics = self.metrics.read.snapshot.clone();
1377 let shard_metrics = Arc::clone(&self.machine.applier.shard_metrics);
1378 let reader_id = self.reader_id.clone();
1379 let schemas = self.read_schemas.clone();
1380 let mut schema_cache = self.schema_cache.clone();
1381 let persist_cfg = self.cfg.clone();
1382 let stream = async_stream::stream! {
1383 for part in snap {
1384 let mut fetched_part = fetch_leased_part(
1385 &persist_cfg,
1386 &part,
1387 blob.as_ref(),
1388 Arc::clone(&metrics),
1389 &snapshot_metrics,
1390 &shard_metrics,
1391 &reader_id,
1392 schemas.clone(),
1393 &mut schema_cache,
1394 )
1395 .await;
1396
1397 while let Some(next) = fetched_part.next() {
1398 yield next;
1399 }
1400 }
1401 };
1402
1403 Ok(stream)
1404 }
1405}
1406
1407impl<K, V, T, D> ReadHandle<K, V, T, D>
1408where
1409 K: Debug + Codec + Ord,
1410 V: Debug + Codec + Ord,
1411 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
1412 D: Monoid + Ord + Codec64 + Send + Sync,
1413{
1414 #[cfg(test)]
1417 #[track_caller]
1418 pub async fn expect_snapshot_and_fetch(&mut self, as_of: T) -> Vec<((K, V), T, D)> {
1419 let mut ret = self
1420 .snapshot_and_fetch(Antichain::from_elem(as_of))
1421 .await
1422 .expect("cannot serve requested as_of");
1423
1424 ret.sort();
1425 ret
1426 }
1427}
1428
1429impl<K: Codec, V: Codec, T, D> Drop for ReadHandle<K, V, T, D> {
1430 fn drop(&mut self) {
1431 self.hold_state.modify(|s| {
1432 s.expired = true;
1433 s.request_sync = true;
1434 });
1435 }
1436}
1437
1438#[cfg(test)]
1439mod tests {
1440 use std::pin;
1441 use std::str::FromStr;
1442
1443 use mz_dyncfg::ConfigUpdates;
1444 use mz_ore::cast::CastFrom;
1445 use mz_ore::metrics::MetricsRegistry;
1446 use mz_persist::mem::{MemBlob, MemBlobConfig, MemConsensus};
1447 use mz_persist::unreliable::{UnreliableConsensus, UnreliableHandle};
1448 use serde::{Deserialize, Serialize};
1449 use serde_json::json;
1450 use tokio_stream::StreamExt;
1451
1452 use crate::async_runtime::IsolatedRuntime;
1453 use crate::batch::BLOB_TARGET_SIZE;
1454 use crate::cache::StateCache;
1455 use crate::internal::metrics::Metrics;
1456 use crate::rpc::NoopPubSubSender;
1457 use crate::tests::{all_ok, new_test_client};
1458 use crate::{Diagnostics, PersistClient, PersistConfig, ShardId};
1459
1460 use super::*;
1461
1462 #[mz_persist_proc::test(tokio::test)]
1464 #[cfg_attr(miri, ignore)] async fn drop_unused_subscribe(dyncfgs: ConfigUpdates) {
1466 let data = [
1467 (("0".to_owned(), "zero".to_owned()), 0, 1),
1468 (("1".to_owned(), "one".to_owned()), 1, 1),
1469 (("2".to_owned(), "two".to_owned()), 2, 1),
1470 ];
1471
1472 let (mut write, read) = new_test_client(&dyncfgs)
1473 .await
1474 .expect_open::<String, String, u64, i64>(crate::ShardId::new())
1475 .await;
1476
1477 write.expect_compare_and_append(&data[0..1], 0, 1).await;
1478 write.expect_compare_and_append(&data[1..2], 1, 2).await;
1479 write.expect_compare_and_append(&data[2..3], 2, 3).await;
1480
1481 let subscribe = read
1482 .subscribe(timely::progress::Antichain::from_elem(2))
1483 .await
1484 .unwrap();
1485 assert!(
1486 !subscribe.snapshot.as_ref().unwrap().is_empty(),
1487 "snapshot must have batches for test to be meaningful"
1488 );
1489 drop(subscribe);
1490 }
1491
1492 #[mz_ore::test(tokio::test)]
1497 #[cfg_attr(miri, ignore)] async fn maybe_optimize_ignores_truncated_batches() {
1499 use arrow::array::{ArrayRef, StringArray};
1500
1501 use crate::batch::{INLINE_WRITES_SINGLE_MAX_BYTES, INLINE_WRITES_TOTAL_MAX_BYTES};
1502 use crate::cache::PersistClientCache;
1503
1504 let mut cache = PersistClientCache::new_no_metrics();
1505 cache.cfg.compaction_enabled = false;
1508 cache.cfg.set_config(&INLINE_WRITES_SINGLE_MAX_BYTES, 0);
1510 cache.cfg.set_config(&INLINE_WRITES_TOTAL_MAX_BYTES, 0);
1511 let client = cache
1512 .open(crate::PersistLocation::new_in_mem())
1513 .await
1514 .expect("client construction failed");
1515 let (mut write, mut read) = client
1516 .expect_open::<String, String, u64, i64>(ShardId::new())
1517 .await;
1518
1519 write
1520 .expect_compare_and_append(&[(("0".to_owned(), "zero".to_owned()), 0, 1)], 0, 1)
1521 .await;
1522
1523 let mut batch = write
1526 .expect_batch(
1527 &[
1528 (("stale".to_owned(), "stale".to_owned()), 0, 1),
1529 (("1".to_owned(), "one".to_owned()), 1, 1),
1530 (("2".to_owned(), "two".to_owned()), 2, 1),
1531 ],
1532 0,
1533 3,
1534 )
1535 .await;
1536 write
1537 .compare_and_append_batch(
1538 &mut [&mut batch],
1539 Antichain::from_elem(1),
1540 Antichain::from_elem(3),
1541 true,
1542 )
1543 .await
1544 .expect("invalid usage")
1545 .expect("unexpected upper");
1546
1547 write
1549 .expect_compare_and_append(&[(("3".to_owned(), "three".to_owned()), 3, 1)], 3, 4)
1550 .await;
1551
1552 let parts = read
1553 .snapshot(Antichain::from_elem(3))
1554 .await
1555 .expect("as_of unavailable");
1556
1557 let mut faked = 0;
1558 let mut kept_truncated = 0;
1559 for mut part in parts {
1560 let key: ArrayRef = Arc::new(StringArray::from(vec!["k"]));
1561 let val: ArrayRef = Arc::new(StringArray::from(vec!["v"]));
1562 part.maybe_optimize(&cache.cfg, key, val);
1563 match part.desc.lower().elements() {
1564 [0] => {
1565 assert!(!part.bounds_truncated);
1568 assert!(part.part.is_inline(), "expected a faked part");
1569 faked += 1;
1570 }
1571 [1] => {
1572 assert!(part.bounds_truncated);
1575 assert!(
1576 !part.part.is_inline(),
1577 "must not substitute statistics for a truncated part"
1578 );
1579 kept_truncated += 1;
1580 }
1581 [3] => (),
1582 x => panic!("unexpected part lower {:?}", x),
1583 }
1584 }
1585 assert_eq!(faked, 1);
1586 assert_eq!(kept_truncated, 1);
1587 }
1588
1589 #[mz_persist_proc::test(tokio::test)]
1591 #[cfg_attr(miri, ignore)] async fn streaming_consolidate(dyncfgs: ConfigUpdates) {
1593 let data = &[
1594 (("k".to_owned(), "v".to_owned()), 0, 1),
1596 (("k".to_owned(), "v".to_owned()), 1, 1),
1597 (("k".to_owned(), "v".to_owned()), 2, 1),
1598 (("k2".to_owned(), "v".to_owned()), 0, 1),
1600 (("k2".to_owned(), "v".to_owned()), 1, -1),
1601 ];
1602
1603 let (mut write, read) = {
1604 let client = new_test_client(&dyncfgs).await;
1605 client.cfg.set_config(&BLOB_TARGET_SIZE, 1000); client
1607 .expect_open::<String, String, u64, i64>(crate::ShardId::new())
1608 .await
1609 };
1610
1611 write.expect_compare_and_append(data, 0, 5).await;
1612
1613 let mut snapshot = read
1614 .subscribe(timely::progress::Antichain::from_elem(4))
1615 .await
1616 .unwrap();
1617
1618 let mut updates = vec![];
1619 'outer: loop {
1620 for event in snapshot.fetch_next().await {
1621 match event {
1622 ListenEvent::Progress(t) => {
1623 if !t.less_than(&4) {
1624 break 'outer;
1625 }
1626 }
1627 ListenEvent::Updates(data) => {
1628 updates.extend(data);
1629 }
1630 }
1631 }
1632 }
1633 assert_eq!(updates, &[(("k".to_owned(), "v".to_owned()), 4u64, 3i64)],)
1634 }
1635
1636 #[mz_persist_proc::test(tokio::test)]
1637 #[cfg_attr(miri, ignore)] async fn snapshot_and_stream(dyncfgs: ConfigUpdates) {
1639 let data = &mut [
1640 (("k1".to_owned(), "v1".to_owned()), 0, 1),
1641 (("k2".to_owned(), "v2".to_owned()), 1, 1),
1642 (("k3".to_owned(), "v3".to_owned()), 2, 1),
1643 (("k4".to_owned(), "v4".to_owned()), 2, 1),
1644 (("k5".to_owned(), "v5".to_owned()), 3, 1),
1645 ];
1646
1647 let (mut write, mut read) = {
1648 let client = new_test_client(&dyncfgs).await;
1649 client.cfg.set_config(&BLOB_TARGET_SIZE, 0); client
1651 .expect_open::<String, String, u64, i64>(crate::ShardId::new())
1652 .await
1653 };
1654
1655 write.expect_compare_and_append(&data[0..2], 0, 2).await;
1656 write.expect_compare_and_append(&data[2..4], 2, 3).await;
1657 write.expect_compare_and_append(&data[4..], 3, 4).await;
1658
1659 let as_of = Antichain::from_elem(3);
1660 let mut snapshot = pin::pin!(read.snapshot_and_stream(as_of.clone()).await.unwrap());
1661
1662 let mut snapshot_rows = vec![];
1663 while let Some(((k, v), t, d)) = snapshot.next().await {
1664 snapshot_rows.push(((k, v), t, d));
1665 }
1666
1667 for ((_k, _v), t, _d) in data.as_mut_slice() {
1668 t.advance_by(as_of.borrow());
1669 }
1670
1671 assert_eq!(data.as_slice(), snapshot_rows.as_slice());
1672 }
1673
1674 #[mz_persist_proc::test(tokio::test)]
1676 #[cfg_attr(miri, ignore)] async fn seqno_leases(dyncfgs: ConfigUpdates) {
1678 let mut data = vec![];
1679 for i in 0..20 {
1680 data.push(((i.to_string(), i.to_string()), i, 1))
1681 }
1682
1683 let shard_id = ShardId::new();
1684
1685 let client = new_test_client(&dyncfgs).await;
1686 let (mut write, read) = client
1687 .expect_open::<String, String, u64, i64>(shard_id)
1688 .await;
1689
1690 let mut offset = 0;
1692 let mut width = 2;
1693
1694 for i in offset..offset + width {
1695 write
1696 .expect_compare_and_append(
1697 &data[i..i + 1],
1698 u64::cast_from(i),
1699 u64::cast_from(i) + 1,
1700 )
1701 .await;
1702 }
1703 offset += width;
1704
1705 let mut fetcher = client
1707 .create_batch_fetcher::<String, String, u64, i64>(
1708 shard_id,
1709 Default::default(),
1710 Default::default(),
1711 false,
1712 Diagnostics::for_tests(),
1713 )
1714 .await
1715 .unwrap();
1716
1717 let mut subscribe = read
1718 .subscribe(timely::progress::Antichain::from_elem(1))
1719 .await
1720 .expect("cannot serve requested as_of");
1721
1722 let original_seqno_since = subscribe.listen.handle.outstanding_seqno();
1724 if let Some(snapshot) = &subscribe.snapshot {
1725 for part in snapshot {
1726 assert!(
1727 part.lease.seqno() >= original_seqno_since,
1728 "our seqno hold must cover all parts"
1729 );
1730 }
1731 }
1732
1733 let mut parts = vec![];
1734
1735 width = 4;
1736 for i in offset..offset + width {
1738 for event in subscribe.next(None).await {
1739 if let ListenEvent::Updates(mut new_parts) = event {
1740 parts.append(&mut new_parts);
1741 subscribe
1744 .listen
1745 .handle
1746 .downgrade_since(&subscribe.listen.since)
1747 .await;
1748 }
1749 }
1750
1751 write
1752 .expect_compare_and_append(
1753 &data[i..i + 1],
1754 u64::cast_from(i),
1755 u64::cast_from(i) + 1,
1756 )
1757 .await;
1758
1759 assert_eq!(
1761 subscribe.listen.handle.machine.applier.seqno_since(),
1762 original_seqno_since
1763 );
1764 }
1765
1766 offset += width;
1767
1768 let mut seqno_since = subscribe.listen.handle.machine.applier.seqno_since();
1769
1770 assert_eq!(seqno_since, original_seqno_since);
1772
1773 let mut subsequent_parts = vec![];
1776
1777 let mut this_seqno = SeqNo::minimum();
1781
1782 for (mut i, part) in parts.into_iter().enumerate() {
1784 let part_seqno = part.lease.seqno();
1785 let last_seqno = this_seqno;
1786 this_seqno = part_seqno;
1787 assert!(this_seqno >= last_seqno);
1788
1789 let (part, lease) = part.into_exchangeable_part();
1790 let _ = fetcher.fetch_leased_part(part).await;
1791 drop(lease);
1792
1793 for event in subscribe.next(None).await {
1795 if let ListenEvent::Updates(parts) = event {
1796 for part in parts {
1797 let (_, lease) = part.into_exchangeable_part();
1798 subsequent_parts.push(lease);
1799 }
1800 }
1801 }
1802
1803 subscribe
1804 .listen
1805 .handle
1806 .downgrade_since(&subscribe.listen.since)
1807 .await;
1808
1809 i += offset;
1811 write
1812 .expect_compare_and_append(
1813 &data[i..i + 1],
1814 u64::cast_from(i),
1815 u64::cast_from(i) + 1,
1816 )
1817 .await;
1818
1819 let expect_downgrade = subscribe.listen.handle.outstanding_seqno() > part_seqno;
1822
1823 let new_seqno_since = subscribe.listen.handle.machine.applier.seqno_since();
1824 if expect_downgrade {
1825 assert!(new_seqno_since > seqno_since);
1826 } else {
1827 assert_eq!(new_seqno_since, seqno_since);
1828 }
1829 seqno_since = new_seqno_since;
1830 }
1831
1832 assert!(seqno_since > original_seqno_since);
1834
1835 drop(subsequent_parts);
1837 drop(subscribe);
1838 }
1839
1840 #[mz_ore::test]
1841 fn reader_id_human_readable_serde() {
1842 #[derive(Debug, Serialize, Deserialize)]
1843 struct Container {
1844 reader_id: LeasedReaderId,
1845 }
1846
1847 let id =
1849 LeasedReaderId::from_str("r00000000-1234-5678-0000-000000000000").expect("valid id");
1850 assert_eq!(
1851 id,
1852 serde_json::from_value(serde_json::to_value(id.clone()).expect("serializable"))
1853 .expect("deserializable")
1854 );
1855
1856 assert_eq!(
1858 id,
1859 serde_json::from_str("\"r00000000-1234-5678-0000-000000000000\"")
1860 .expect("deserializable")
1861 );
1862
1863 let json = json!({ "reader_id": id });
1865 assert_eq!(
1866 "{\"reader_id\":\"r00000000-1234-5678-0000-000000000000\"}",
1867 &json.to_string()
1868 );
1869 let container: Container = serde_json::from_value(json).expect("deserializable");
1870 assert_eq!(container.reader_id, id);
1871 }
1872
1873 #[mz_ore::test(tokio::test)]
1877 #[cfg_attr(miri, ignore)] async fn skip_consensus_fetch_optimization() {
1879 let data = vec![
1880 (("0".to_owned(), "zero".to_owned()), 0, 1),
1881 (("1".to_owned(), "one".to_owned()), 1, 1),
1882 (("2".to_owned(), "two".to_owned()), 2, 1),
1883 ];
1884
1885 let cfg = PersistConfig::new_for_tests();
1886 let blob = Arc::new(MemBlob::open(MemBlobConfig::default()));
1887 let consensus = Arc::new(MemConsensus::default());
1888 let unreliable = UnreliableHandle::default();
1889 unreliable.totally_available();
1890 let consensus = Arc::new(UnreliableConsensus::new(consensus, unreliable.clone()));
1891 let metrics = Arc::new(Metrics::new(&cfg, &MetricsRegistry::new()));
1892 let pubsub_sender = Arc::new(NoopPubSubSender);
1893 let (mut write, mut read) = PersistClient::new(
1894 cfg,
1895 blob,
1896 consensus,
1897 metrics,
1898 Arc::new(IsolatedRuntime::new_for_tests()),
1899 Arc::new(StateCache::new_no_metrics()),
1900 pubsub_sender,
1901 )
1902 .expect("client construction failed")
1903 .expect_open::<String, String, u64, i64>(ShardId::new())
1904 .await;
1905
1906 write.expect_compare_and_append(&data[0..1], 0, 1).await;
1907 write.expect_compare_and_append(&data[1..2], 1, 2).await;
1908 write.expect_compare_and_append(&data[2..3], 2, 3).await;
1909
1910 let snapshot = read.expect_snapshot_and_fetch(2).await;
1911 let mut listen = read.expect_listen(0).await;
1912
1913 let listen_actual = listen.fetch_next().await;
1918 let expected_events = vec![ListenEvent::Progress(Antichain::from_elem(1))];
1919 assert_eq!(listen_actual, expected_events);
1920
1921 unreliable.totally_unavailable();
1924 assert_eq!(snapshot, all_ok(&data, 2));
1925 assert_eq!(
1926 listen.read_until(&3).await,
1927 (all_ok(&data[1..], 1), Antichain::from_elem(3))
1928 );
1929 }
1930}