1#![cfg_attr(
16 not(feature = "fuzzing"),
17 warn(missing_docs, missing_debug_implementations)
18)]
19#![allow(ungated_async_fn_track_caller)]
23
24use std::fmt::Debug;
25use std::marker::PhantomData;
26use std::sync::Arc;
27
28use differential_dataflow::difference::Monoid;
29use differential_dataflow::lattice::Lattice;
30use itertools::Itertools;
31use mz_build_info::{BuildInfo, build_info};
32use mz_dyncfg::ConfigSet;
33use mz_ore::instrument;
34use mz_persist::location::{Blob, Consensus, ExternalError};
35use mz_persist_types::schema::SchemaId;
36use mz_persist_types::{Codec, Codec64};
37use mz_proto::{IntoRustIfSome, ProtoType};
38use semver::Version;
39use timely::order::TotalOrder;
40use timely::progress::{Antichain, Timestamp};
41
42use crate::async_runtime::IsolatedRuntime;
43use crate::batch::{BATCH_DELETE_ENABLED, Batch, BatchBuilder, ProtoBatch};
44use crate::cache::{PersistClientCache, StateCache};
45use crate::cfg::PersistConfig;
46use crate::critical::{CriticalReaderId, Opaque, SinceHandle};
47use crate::error::InvalidUsage;
48use crate::fetch::{BatchFetcher, BatchFetcherConfig};
49use crate::internal::compact::{CompactConfig, Compactor};
50use crate::internal::encoding::parse_id;
51use crate::internal::gc::GarbageCollector;
52use crate::internal::machine::{Machine, retry_external};
53use crate::internal::state_versions::StateVersions;
54use crate::metrics::Metrics;
55use crate::read::{
56 Cursor, LazyPartStats, LeasedReaderId, READER_LEASE_DURATION, ReadHandle, Since,
57};
58use crate::rpc::PubSubSender;
59use crate::schema::CaESchema;
60use crate::write::{WriteHandle, WriterId};
61
62pub mod async_runtime;
63pub mod batch;
64pub mod cache;
65pub mod cfg;
66pub mod cli {
67 pub mod admin;
69 pub mod args;
70 pub mod bench;
71 pub mod inspect;
72}
73pub mod critical;
74pub mod error;
75pub mod fetch;
76pub mod internals_bench;
77pub mod iter;
78pub mod metrics {
79 pub use crate::internal::metrics::{
81 BackpressureMetrics, Metrics, SinkMetrics, SinkWorkerMetrics, UpdateDelta, encode_ts_metric,
82 };
83}
84pub mod operators {
85 use mz_dyncfg::{Config, ParameterScope};
88
89 pub mod shard_source;
90
91 pub(crate) const STORAGE_SOURCE_DECODE_FUEL: Config<usize> = Config::new(
93 "storage_source_decode_fuel",
94 100_000,
95 "\
96 The maximum amount of work to do in the persist_source mfp_and_decode \
97 operator before yielding.",
98 ParameterScope::Environment,
99 );
100}
101pub mod read;
102pub mod rpc;
103pub mod schema;
104pub mod stats;
105pub mod usage;
106pub mod write;
107
108#[cfg(feature = "fuzzing")]
113pub mod fuzz_exports {
114 pub use crate::internal::encoding::Rollup;
115 pub use crate::internal::state::{ProtoRollup, ProtoStateDiff};
116 pub use crate::internal::state_diff::StateDiff;
117}
118
119mod internal {
121 pub mod apply;
122 pub mod cache;
123 pub mod compact;
124 pub mod encoding;
125 pub mod gc;
126 pub mod machine;
127 pub mod maintenance;
128 pub mod merge;
129 pub mod metrics;
130 pub mod paths;
131 pub mod restore;
132 pub mod service;
133 pub mod state;
134 pub mod state_diff;
135 pub mod state_versions;
136 pub mod trace;
137 pub mod watch;
138
139 #[cfg(test)]
140 pub mod datadriven;
141}
142
143pub const BUILD_INFO: BuildInfo = build_info!();
145
146pub use mz_persist_types::{PersistLocation, ShardId};
148
149pub use crate::internal::encoding::Schemas;
150
151#[derive(Clone, Debug)]
154pub struct Diagnostics {
155 pub shard_name: String,
157 pub handle_purpose: String,
159}
160
161impl Diagnostics {
162 pub fn from_purpose(handle_purpose: &str) -> Self {
164 Self {
165 shard_name: "unknown".to_string(),
166 handle_purpose: handle_purpose.to_string(),
167 }
168 }
169
170 pub fn for_tests() -> Self {
172 Self {
173 shard_name: "test-shard-name".to_string(),
174 handle_purpose: "test-purpose".to_string(),
175 }
176 }
177}
178
179#[derive(Debug, Clone)]
200pub struct PersistClient {
201 cfg: PersistConfig,
202 blob: Arc<dyn Blob>,
203 consensus: Arc<dyn Consensus>,
204 metrics: Arc<Metrics>,
205 isolated_runtime: Arc<IsolatedRuntime>,
206 shared_states: Arc<StateCache>,
207 pubsub_sender: Arc<dyn PubSubSender>,
208}
209
210impl PersistClient {
211 pub fn new(
217 cfg: PersistConfig,
218 blob: Arc<dyn Blob>,
219 consensus: Arc<dyn Consensus>,
220 metrics: Arc<Metrics>,
221 isolated_runtime: Arc<IsolatedRuntime>,
222 shared_states: Arc<StateCache>,
223 pubsub_sender: Arc<dyn PubSubSender>,
224 ) -> Result<Self, ExternalError> {
225 Ok(PersistClient {
228 cfg,
229 blob,
230 consensus,
231 metrics,
232 isolated_runtime,
233 shared_states,
234 pubsub_sender,
235 })
236 }
237
238 pub async fn new_for_tests() -> Self {
240 let cache = PersistClientCache::new_no_metrics();
241 cache
242 .open(PersistLocation::new_in_mem())
243 .await
244 .expect("in-mem location is valid")
245 }
246
247 pub fn dyncfgs(&self) -> &ConfigSet {
249 &self.cfg.configs
250 }
251
252 async fn make_machine<K, V, T, D>(
253 &self,
254 shard_id: ShardId,
255 diagnostics: Diagnostics,
256 ) -> Result<Machine<K, V, T, D>, InvalidUsage<T>>
257 where
258 K: Debug + Codec,
259 V: Debug + Codec,
260 T: Timestamp + Lattice + Codec64 + Sync,
261 D: Monoid + Codec64 + Send + Sync,
262 {
263 let state_versions = StateVersions::new(
264 self.cfg.clone(),
265 Arc::clone(&self.consensus),
266 Arc::clone(&self.blob),
267 Arc::clone(&self.metrics),
268 );
269 let machine = Machine::<K, V, T, D>::new(
270 self.cfg.clone(),
271 shard_id,
272 Arc::clone(&self.metrics),
273 Arc::new(state_versions),
274 Arc::clone(&self.shared_states),
275 Arc::clone(&self.pubsub_sender),
276 Arc::clone(&self.isolated_runtime),
277 diagnostics.clone(),
278 )
279 .await?;
280 Ok(machine)
281 }
282
283 #[instrument(level = "debug", fields(shard = %shard_id))]
301 pub async fn open<K, V, T, D>(
302 &self,
303 shard_id: ShardId,
304 key_schema: Arc<K::Schema>,
305 val_schema: Arc<V::Schema>,
306 diagnostics: Diagnostics,
307 use_critical_since: bool,
308 ) -> Result<(WriteHandle<K, V, T, D>, ReadHandle<K, V, T, D>), InvalidUsage<T>>
309 where
310 K: Debug + Codec,
311 V: Debug + Codec,
312 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
313 D: Monoid + Ord + Codec64 + Send + Sync,
314 {
315 Ok((
316 self.open_writer(
317 shard_id,
318 Arc::clone(&key_schema),
319 Arc::clone(&val_schema),
320 diagnostics.clone(),
321 )
322 .await?,
323 self.open_leased_reader(
324 shard_id,
325 key_schema,
326 val_schema,
327 diagnostics,
328 use_critical_since,
329 )
330 .await?,
331 ))
332 }
333
334 #[instrument(level = "debug", fields(shard = %shard_id))]
343 pub async fn open_leased_reader<K, V, T, D>(
344 &self,
345 shard_id: ShardId,
346 key_schema: Arc<K::Schema>,
347 val_schema: Arc<V::Schema>,
348 diagnostics: Diagnostics,
349 use_critical_since: bool,
350 ) -> Result<ReadHandle<K, V, T, D>, InvalidUsage<T>>
351 where
352 K: Debug + Codec,
353 V: Debug + Codec,
354 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
355 D: Monoid + Codec64 + Send + Sync,
356 {
357 let machine = self.make_machine(shard_id, diagnostics.clone()).await?;
358 let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
359
360 let reader_id = LeasedReaderId::new();
361 let (reader_state, maintenance) = machine
362 .register_leased_reader(
363 &reader_id,
364 &diagnostics.handle_purpose,
365 READER_LEASE_DURATION.get(&self.cfg),
366 use_critical_since,
367 )
368 .await;
369 maintenance.start_performing(&machine, &gc);
370 let schemas = Schemas {
371 id: None,
372 key: key_schema,
373 val: val_schema,
374 };
375 let reader = ReadHandle::new(
376 self.cfg.clone(),
377 Arc::clone(&self.metrics),
378 machine,
379 gc,
380 Arc::clone(&self.blob),
381 reader_id,
382 schemas,
383 reader_state,
384 )
385 .await;
386
387 Ok(reader)
388 }
389
390 #[instrument(level = "debug", fields(shard = %shard_id))]
392 pub async fn create_batch_fetcher<K, V, T, D>(
393 &self,
394 shard_id: ShardId,
395 key_schema: Arc<K::Schema>,
396 val_schema: Arc<V::Schema>,
397 is_transient: bool,
398 diagnostics: Diagnostics,
399 ) -> Result<BatchFetcher<K, V, T, D>, InvalidUsage<T>>
400 where
401 K: Debug + Codec,
402 V: Debug + Codec,
403 T: Timestamp + Lattice + Codec64 + Sync,
404 D: Monoid + Codec64 + Send + Sync,
405 {
406 let machine = self.make_machine(shard_id, diagnostics.clone()).await?;
407 let read_schemas = Schemas {
408 id: None,
409 key: key_schema,
410 val: val_schema,
411 };
412 let schema_cache = machine.applier.schema_cache();
413 let fetcher = BatchFetcher {
414 cfg: BatchFetcherConfig::new(&self.cfg),
415 blob: Arc::clone(&self.blob),
416 metrics: Arc::clone(&self.metrics),
417 shard_metrics: Arc::clone(&machine.applier.shard_metrics),
418 shard_id,
419 read_schemas,
420 schema_cache,
421 is_transient,
422 _phantom: PhantomData,
423 };
424
425 Ok(fetcher)
426 }
427
428 pub const CONTROLLER_CRITICAL_SINCE: CriticalReaderId =
450 CriticalReaderId([0, 0, 0, 0, 17, 17, 34, 34, 51, 51, 68, 68, 68, 68, 68, 68]);
451
452 #[instrument(level = "debug", fields(shard = %shard_id))]
473 pub async fn open_critical_since<K, V, T, D>(
474 &self,
475 shard_id: ShardId,
476 reader_id: CriticalReaderId,
477 default_opaque: Opaque,
478 diagnostics: Diagnostics,
479 ) -> Result<SinceHandle<K, V, T, D>, InvalidUsage<T>>
480 where
481 K: Debug + Codec,
482 V: Debug + Codec,
483 T: Timestamp + Lattice + Codec64 + Sync,
484 D: Monoid + Codec64 + Send + Sync,
485 {
486 let machine = self.make_machine(shard_id, diagnostics.clone()).await?;
487 let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
488
489 let (state, maintenance) = machine
490 .register_critical_reader(&reader_id, default_opaque, &diagnostics.handle_purpose)
491 .await;
492 maintenance.start_performing(&machine, &gc);
493 let handle = SinceHandle::new(machine, gc, reader_id, state.since, state.opaque);
494
495 Ok(handle)
496 }
497
498 #[instrument(level = "debug", fields(shard = %shard_id))]
503 pub async fn open_writer<K, V, T, D>(
504 &self,
505 shard_id: ShardId,
506 key_schema: Arc<K::Schema>,
507 val_schema: Arc<V::Schema>,
508 diagnostics: Diagnostics,
509 ) -> Result<WriteHandle<K, V, T, D>, InvalidUsage<T>>
510 where
511 K: Debug + Codec,
512 V: Debug + Codec,
513 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
514 D: Monoid + Ord + Codec64 + Send + Sync,
515 {
516 let machine = self.make_machine(shard_id, diagnostics.clone()).await?;
517 let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
518
519 let schema_id = machine.find_schema(&*key_schema, &*val_schema);
524
525 let writer_id = WriterId::new();
526 let schemas = Schemas {
527 id: schema_id,
528 key: key_schema,
529 val: val_schema,
530 };
531 let writer = WriteHandle::new(
532 self.cfg.clone(),
533 Arc::clone(&self.metrics),
534 machine,
535 gc,
536 Arc::clone(&self.blob),
537 writer_id,
538 &diagnostics.handle_purpose,
539 schemas,
540 );
541 Ok(writer)
542 }
543
544 #[instrument(level = "debug", fields(shard = %shard_id))]
557 pub fn batch_builder<K, V, T, D>(
558 &self,
559 shard_id: ShardId,
560 shard_name: &str,
561 write_schemas: Schemas<K, V>,
562 lower: Antichain<T>,
563 max_runs: Option<usize>,
564 ) -> BatchBuilder<K, V, T, D>
565 where
566 K: Debug + Codec,
567 V: Debug + Codec,
568 T: Timestamp + Lattice + Codec64 + TotalOrder + Sync,
569 D: Monoid + Ord + Codec64 + Send + Sync,
570 {
571 let mut compact_cfg = CompactConfig::new(&self.cfg, shard_id);
572 if let Some(max_runs) = max_runs {
573 compact_cfg.batch.max_runs = Some(max_runs);
574 }
575 WriteHandle::builder_inner(
576 &self.cfg,
577 compact_cfg,
578 Arc::clone(&self.metrics),
579 self.metrics.shards.shard(&shard_id, shard_name),
580 &self.metrics.user,
581 Arc::clone(&self.isolated_runtime),
582 Arc::clone(&self.blob),
583 shard_id,
584 write_schemas,
585 lower,
586 )
587 }
588
589 pub fn batch_from_transmittable_batch<K, V, T, D>(
598 &self,
599 shard_id: &ShardId,
600 batch: ProtoBatch,
601 ) -> Batch<K, V, T, D>
602 where
603 K: Debug + Codec,
604 V: Debug + Codec,
605 T: Timestamp + Lattice + Codec64 + Sync,
606 D: Monoid + Ord + Codec64 + Send + Sync,
607 {
608 let batch_shard_id: ShardId = batch
609 .shard_id
610 .into_rust()
611 .expect("valid transmittable batch");
612 assert_eq!(&batch_shard_id, shard_id);
613
614 let shard_metrics = self.metrics.shards.shard(shard_id, "peek_stash");
615
616 let ret = Batch {
617 batch_delete_enabled: BATCH_DELETE_ENABLED.get(&self.cfg),
618 metrics: Arc::clone(&self.metrics),
619 shard_metrics,
620 version: Version::parse(&batch.version).expect("valid transmittable batch"),
621 schemas: (batch.key_schema, batch.val_schema),
622 batch: batch
623 .batch
624 .into_rust_if_some("ProtoBatch::batch")
625 .expect("valid transmittable batch"),
626 blob: Arc::clone(&self.blob),
627 _phantom: std::marker::PhantomData,
628 };
629
630 assert_eq!(&ret.shard_id(), shard_id);
631 ret
632 }
633
634 #[allow(clippy::unused_async)]
649 pub async fn read_batches_consolidated<K, V, T, D>(
650 &mut self,
651 shard_id: ShardId,
652 as_of: Antichain<T>,
653 read_schemas: Schemas<K, V>,
654 batches: Vec<Batch<K, V, T, D>>,
655 should_fetch_part: impl for<'a> Fn(Option<&'a LazyPartStats>) -> bool,
656 memory_budget_bytes: usize,
657 ) -> Result<Cursor<K, V, T, D, Vec<Batch<K, V, T, D>>>, Since<T>>
658 where
659 K: Debug + Codec + Ord,
660 V: Debug + Codec + Ord,
661 T: Timestamp + Lattice + Codec64 + TotalOrder + Sync,
662 D: Monoid + Ord + Codec64 + Send + Sync,
663 {
664 let shard_metrics = self.metrics.shards.shard(&shard_id, "peek_stash");
665
666 let hollow_batches = batches.iter().map(|b| b.batch.clone()).collect_vec();
667
668 ReadHandle::read_batches_consolidated(
669 &self.cfg,
670 Arc::clone(&self.metrics),
671 shard_metrics,
672 self.metrics.read.snapshot.clone(),
673 Arc::clone(&self.blob),
674 shard_id,
675 as_of,
676 read_schemas,
677 &hollow_batches,
678 batches,
679 should_fetch_part,
680 memory_budget_bytes,
681 )
682 }
683
684 pub async fn get_schema<K, V, T, D>(
686 &self,
687 shard_id: ShardId,
688 schema_id: SchemaId,
689 diagnostics: Diagnostics,
690 ) -> Result<Option<(K::Schema, V::Schema)>, InvalidUsage<T>>
691 where
692 K: Debug + Codec,
693 V: Debug + Codec,
694 T: Timestamp + Lattice + Codec64 + Sync,
695 D: Monoid + Codec64 + Send + Sync,
696 {
697 let machine = self
698 .make_machine::<K, V, T, D>(shard_id, diagnostics)
699 .await?;
700 Ok(machine.get_schema(schema_id))
701 }
702
703 pub async fn latest_schema<K, V, T, D>(
705 &self,
706 shard_id: ShardId,
707 diagnostics: Diagnostics,
708 ) -> Result<Option<(SchemaId, K::Schema, V::Schema)>, InvalidUsage<T>>
709 where
710 K: Debug + Codec,
711 V: Debug + Codec,
712 T: Timestamp + Lattice + Codec64 + Sync,
713 D: Monoid + Codec64 + Send + Sync,
714 {
715 let machine = self
716 .make_machine::<K, V, T, D>(shard_id, diagnostics)
717 .await?;
718 Ok(machine.latest_schema())
719 }
720
721 pub async fn recent_upper<K, V, T, D>(
732 &self,
733 shard_id: ShardId,
734 diagnostics: Diagnostics,
735 ) -> Result<Antichain<T>, InvalidUsage<T>>
736 where
737 K: Debug + Codec,
738 V: Debug + Codec,
739 T: Timestamp + Lattice + Codec64 + Sync,
740 D: Monoid + Codec64 + Send + Sync,
741 {
742 let machine = self
743 .make_machine::<K, V, T, D>(shard_id, diagnostics)
744 .await?;
745 Ok(machine.applier.fetch_upper(|upper| upper.clone()).await)
746 }
747
748 pub async fn register_schema<K, V, T, D>(
760 &self,
761 shard_id: ShardId,
762 key_schema: &K::Schema,
763 val_schema: &V::Schema,
764 diagnostics: Diagnostics,
765 ) -> Result<Option<SchemaId>, InvalidUsage<T>>
766 where
767 K: Debug + Codec,
768 V: Debug + Codec,
769 T: Timestamp + Lattice + Codec64 + Sync,
770 D: Monoid + Codec64 + Send + Sync,
771 {
772 let machine = self
773 .make_machine::<K, V, T, D>(shard_id, diagnostics)
774 .await?;
775 let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
776
777 let (schema_id, maintenance) = machine.register_schema(key_schema, val_schema).await;
778 maintenance.start_performing(&machine, &gc);
779
780 Ok(schema_id)
781 }
782
783 pub async fn compare_and_evolve_schema<K, V, T, D>(
797 &self,
798 shard_id: ShardId,
799 expected: SchemaId,
800 key_schema: &K::Schema,
801 val_schema: &V::Schema,
802 diagnostics: Diagnostics,
803 ) -> Result<CaESchema<K, V>, InvalidUsage<T>>
804 where
805 K: Debug + Codec,
806 V: Debug + Codec,
807 T: Timestamp + Lattice + Codec64 + Sync,
808 D: Monoid + Codec64 + Send + Sync,
809 {
810 let machine = self
811 .make_machine::<K, V, T, D>(shard_id, diagnostics)
812 .await?;
813 let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
814 let (res, maintenance) = machine
815 .compare_and_evolve_schema(expected, key_schema, val_schema)
816 .await;
817 maintenance.start_performing(&machine, &gc);
818 Ok(res)
819 }
820
821 pub async fn is_finalized<K, V, T, D>(
830 &self,
831 shard_id: ShardId,
832 diagnostics: Diagnostics,
833 ) -> Result<bool, InvalidUsage<T>>
834 where
835 K: Debug + Codec,
836 V: Debug + Codec,
837 T: Timestamp + Lattice + Codec64 + Sync,
838 D: Monoid + Codec64 + Send + Sync,
839 {
840 let machine = self
841 .make_machine::<K, V, T, D>(shard_id, diagnostics)
842 .await?;
843 Ok(machine.is_finalized() && machine.fetch_finalized_gc_step().await.1.is_none())
844 }
845
846 #[instrument(level = "debug", fields(shard = %shard_id))]
860 pub async fn finalize_shard<K, V, T, D>(
861 &self,
862 shard_id: ShardId,
863 diagnostics: Diagnostics,
864 ) -> Result<bool, InvalidUsage<T>>
865 where
866 K: Debug + Codec,
867 V: Debug + Codec,
868 T: Timestamp + Lattice + Codec64 + Sync,
869 D: Monoid + Codec64 + Send + Sync,
870 {
871 let machine = self
872 .make_machine::<K, V, T, D>(shard_id, diagnostics)
873 .await?;
874
875 let maintenance = machine.become_tombstone().await?;
876 let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
877
878 let () = maintenance.perform(&machine, &gc).await;
879 let gc_done = machine.finish_finalized_gc(&gc).await;
882
883 Ok(machine.is_finalized() && gc_done)
884 }
885
886 pub async fn upgrade_version<K, V, T, D>(
889 &self,
890 shard_id: ShardId,
891 diagnostics: Diagnostics,
892 ) -> Result<(), InvalidUsage<T>>
893 where
894 K: Debug + Codec,
895 V: Debug + Codec,
896 T: Timestamp + Lattice + Codec64 + Sync,
897 D: Monoid + Codec64 + Send + Sync,
898 {
899 let machine = self
900 .make_machine::<K, V, T, D>(shard_id, diagnostics)
901 .await?;
902
903 match machine.upgrade_version().await {
904 Ok(maintenance) => {
905 let gc = GarbageCollector::new(machine.clone(), Arc::clone(&self.isolated_runtime));
906 let () = maintenance.perform(&machine, &gc).await;
907 Ok(())
908 }
909 Err(version) => Err(InvalidUsage::IncompatibleVersion { version }),
910 }
911 }
912
913 pub async fn inspect_shard<T: Timestamp + Lattice + Codec64>(
919 &self,
920 shard_id: &ShardId,
921 ) -> Result<impl serde::Serialize, anyhow::Error> {
922 let state_versions = StateVersions::new(
923 self.cfg.clone(),
924 Arc::clone(&self.consensus),
925 Arc::clone(&self.blob),
926 Arc::clone(&self.metrics),
927 );
928 let versions = state_versions.fetch_all_live_diffs(shard_id).await;
932 if versions.is_empty() {
933 return Err(anyhow::anyhow!("{} does not exist", shard_id));
934 }
935 let state = state_versions
936 .fetch_current_state::<T>(shard_id, versions)
937 .await;
938 let state = state.check_ts_codec(shard_id)?;
939 Ok(state)
940 }
941
942 #[cfg(test)]
944 #[track_caller]
945 pub async fn expect_open<K, V, T, D>(
946 &self,
947 shard_id: ShardId,
948 ) -> (WriteHandle<K, V, T, D>, ReadHandle<K, V, T, D>)
949 where
950 K: Debug + Codec,
951 V: Debug + Codec,
952 T: Timestamp + TotalOrder + Lattice + Codec64 + Sync,
953 D: Monoid + Ord + Codec64 + Send + Sync,
954 K::Schema: Default,
955 V::Schema: Default,
956 {
957 self.open(
958 shard_id,
959 Arc::new(K::Schema::default()),
960 Arc::new(V::Schema::default()),
961 Diagnostics::for_tests(),
962 true,
963 )
964 .await
965 .expect("codec mismatch")
966 }
967
968 pub fn metrics(&self) -> &Arc<Metrics> {
972 &self.metrics
973 }
974}
975
976#[cfg(test)]
977mod tests {
978 use std::future::Future;
979 use std::pin::Pin;
980 use std::sync::atomic::{AtomicBool, Ordering};
981 use std::task::Context;
982 use std::time::{Duration, Instant};
983
984 use async_trait::async_trait;
985 use differential_dataflow::consolidation::consolidate_updates;
986 use differential_dataflow::lattice::Lattice;
987 use futures_task::noop_waker;
988 use mz_dyncfg::ConfigUpdates;
989 use mz_ore::assert_ok;
990 use mz_persist::indexed::encoding::BlobTraceBatchPart;
991 use mz_persist::location::{
992 CaSResult, Consensus, ExternalError, ResultStream, SeqNo, VersionedData,
993 };
994 use mz_persist::workload::DataGenerator;
995 use mz_persist_types::codec_impls::{StringSchema, VecU8Schema};
996 use mz_proto::protobuf_roundtrip;
997 use proptest::prelude::*;
998 use timely::order::PartialOrder;
999 use timely::progress::Antichain;
1000
1001 use crate::batch::BLOB_TARGET_SIZE;
1002 use crate::cache::PersistClientCache;
1003 use crate::cfg::{BATCH_BUILDER_MAX_OUTSTANDING_PARTS, GC_REMOVE_FINALIZED_ROLLUPS};
1004 use crate::critical::Opaque;
1005 use crate::error::{CodecConcreteType, CodecMismatch, UpperMismatch};
1006 use crate::internal::paths::BlobKey;
1007 use crate::read::ListenEvent;
1008
1009 use super::*;
1010
1011 pub fn new_test_client_cache(dyncfgs: &ConfigUpdates) -> PersistClientCache {
1012 let mut cache = PersistClientCache::new_no_metrics();
1015 cache.cfg.set_config(&BLOB_TARGET_SIZE, 10);
1016 cache
1017 .cfg
1018 .set_config(&BATCH_BUILDER_MAX_OUTSTANDING_PARTS, 1);
1019 cache.cfg.set_config(&GC_REMOVE_FINALIZED_ROLLUPS, true);
1021 dyncfgs.apply(cache.cfg());
1022
1023 cache.cfg.compaction_enabled = true;
1025 cache
1026 }
1027
1028 pub async fn new_test_client(dyncfgs: &ConfigUpdates) -> PersistClient {
1029 let cache = new_test_client_cache(dyncfgs);
1030 cache
1031 .open(PersistLocation::new_in_mem())
1032 .await
1033 .expect("client construction failed")
1034 }
1035
1036 #[derive(Debug)]
1045 pub(crate) struct LoseOneCasResponse {
1046 pub(crate) inner: Arc<dyn Consensus>,
1047 pub(crate) armed: Arc<AtomicBool>,
1048 }
1049
1050 #[async_trait]
1051 impl Consensus for LoseOneCasResponse {
1052 fn list_keys(&self) -> ResultStream<'_, String> {
1053 self.inner.list_keys()
1054 }
1055
1056 async fn head(&self, key: &str) -> Result<Option<VersionedData>, ExternalError> {
1057 self.inner.head(key).await
1058 }
1059
1060 async fn compare_and_set(
1061 &self,
1062 key: &str,
1063 new: VersionedData,
1064 ) -> Result<CaSResult, ExternalError> {
1065 let res = self.inner.compare_and_set(key, new).await;
1068 if self.armed.swap(false, Ordering::SeqCst) {
1069 return Err(ExternalError::new_timeout(Instant::now()));
1070 }
1071 res
1072 }
1073
1074 async fn scan(
1075 &self,
1076 key: &str,
1077 from: SeqNo,
1078 limit: usize,
1079 ) -> Result<Vec<VersionedData>, ExternalError> {
1080 self.inner.scan(key, from, limit).await
1081 }
1082
1083 async fn truncate(&self, key: &str, seqno: SeqNo) -> Result<Option<usize>, ExternalError> {
1084 self.inner.truncate(key, seqno).await
1085 }
1086 }
1087
1088 pub fn all_ok<'a, K, V, T, D, I>(iter: I, as_of: T) -> Vec<((K, V), T, D)>
1089 where
1090 K: Ord + Clone + 'a,
1091 V: Ord + Clone + 'a,
1092 T: Timestamp + Lattice + Clone + 'a,
1093 D: Monoid + Clone + 'a,
1094 I: IntoIterator<Item = &'a ((K, V), T, D)>,
1095 {
1096 let as_of = Antichain::from_elem(as_of);
1097 let mut ret = iter
1098 .into_iter()
1099 .map(|((k, v), t, d)| {
1100 let mut t = t.clone();
1101 t.advance_by(as_of.borrow());
1102 ((k.clone(), v.clone()), t, d.clone())
1103 })
1104 .collect();
1105 consolidate_updates(&mut ret);
1106 ret
1107 }
1108
1109 pub async fn expect_fetch_part<K, V, T, D>(
1110 blob: &dyn Blob,
1111 key: &BlobKey,
1112 metrics: &Metrics,
1113 read_schemas: &Schemas<K, V>,
1114 ) -> (BlobTraceBatchPart<T>, Vec<((K, V), T, D)>)
1115 where
1116 K: Codec + Clone,
1117 V: Codec + Clone,
1118 T: Timestamp + Codec64,
1119 D: Codec64,
1120 {
1121 let value = blob
1122 .get(key)
1123 .await
1124 .expect("failed to fetch part")
1125 .expect("missing part");
1126 let mut part =
1127 BlobTraceBatchPart::decode(&value, &metrics.columnar).expect("failed to decode part");
1128 let structured = part
1129 .updates
1130 .into_part::<K, V>(&*read_schemas.key, &*read_schemas.val);
1131 let updates = structured
1132 .decode_iter::<K, V, T, D>(&*read_schemas.key, &*read_schemas.val)
1133 .expect("structured data")
1134 .collect();
1135 (part, updates)
1136 }
1137
1138 #[mz_persist_proc::test(tokio::test)]
1139 #[cfg_attr(miri, ignore)] async fn sanity_check(dyncfgs: ConfigUpdates) {
1141 let data = [
1142 (("1".to_owned(), "one".to_owned()), 1, 1),
1143 (("2".to_owned(), "two".to_owned()), 2, 1),
1144 (("3".to_owned(), "three".to_owned()), 3, 1),
1145 ];
1146
1147 let (mut write, mut read) = new_test_client(&dyncfgs)
1148 .await
1149 .expect_open::<String, String, u64, i64>(ShardId::new())
1150 .await;
1151 assert_eq!(write.upper(), &Antichain::from_elem(u64::minimum()));
1152 assert_eq!(read.since(), &Antichain::from_elem(u64::minimum()));
1153
1154 write
1156 .expect_append(&data[..2], write.upper().clone(), vec![3])
1157 .await;
1158 assert_eq!(write.upper(), &Antichain::from_elem(3));
1159
1160 assert_eq!(
1162 read.expect_snapshot_and_fetch(1).await,
1163 all_ok(&data[..1], 1)
1164 );
1165
1166 let mut listen = read.clone("").await.expect_listen(1).await;
1167
1168 write
1170 .expect_append(&data[2..], write.upper().clone(), vec![4])
1171 .await;
1172 assert_eq!(write.upper(), &Antichain::from_elem(4));
1173
1174 assert_eq!(
1176 listen.read_until(&4).await,
1177 (all_ok(&data[1..], 1), Antichain::from_elem(4))
1178 );
1179
1180 read.downgrade_since(&Antichain::from_elem(2)).await;
1182 assert_eq!(read.since(), &Antichain::from_elem(2));
1183 }
1184
1185 #[mz_persist_proc::test(tokio::test)]
1187 #[cfg_attr(miri, ignore)] async fn open_reader_writer(dyncfgs: ConfigUpdates) {
1189 let data = vec![
1190 (("1".to_owned(), "one".to_owned()), 1, 1),
1191 (("2".to_owned(), "two".to_owned()), 2, 1),
1192 (("3".to_owned(), "three".to_owned()), 3, 1),
1193 ];
1194
1195 let shard_id = ShardId::new();
1196 let client = new_test_client(&dyncfgs).await;
1197 let mut write1 = client
1198 .open_writer::<String, String, u64, i64>(
1199 shard_id,
1200 Arc::new(StringSchema),
1201 Arc::new(StringSchema),
1202 Diagnostics::for_tests(),
1203 )
1204 .await
1205 .expect("codec mismatch");
1206 let mut read1 = client
1207 .open_leased_reader::<String, String, u64, i64>(
1208 shard_id,
1209 Arc::new(StringSchema),
1210 Arc::new(StringSchema),
1211 Diagnostics::for_tests(),
1212 true,
1213 )
1214 .await
1215 .expect("codec mismatch");
1216 let mut read2 = client
1217 .open_leased_reader::<String, String, u64, i64>(
1218 shard_id,
1219 Arc::new(StringSchema),
1220 Arc::new(StringSchema),
1221 Diagnostics::for_tests(),
1222 true,
1223 )
1224 .await
1225 .expect("codec mismatch");
1226 let mut write2 = client
1227 .open_writer::<String, String, u64, i64>(
1228 shard_id,
1229 Arc::new(StringSchema),
1230 Arc::new(StringSchema),
1231 Diagnostics::for_tests(),
1232 )
1233 .await
1234 .expect("codec mismatch");
1235
1236 write2.expect_compare_and_append(&data[..1], 0, 2).await;
1237 assert_eq!(
1238 read2.expect_snapshot_and_fetch(1).await,
1239 all_ok(&data[..1], 1)
1240 );
1241 write1.expect_compare_and_append(&data[1..], 2, 4).await;
1242 assert_eq!(read1.expect_snapshot_and_fetch(3).await, all_ok(&data, 3));
1243 }
1244
1245 #[mz_persist_proc::test(tokio::test)]
1246 #[cfg_attr(miri, ignore)] async fn invalid_usage(dyncfgs: ConfigUpdates) {
1248 let data = vec![
1249 (("1".to_owned(), "one".to_owned()), 1, 1),
1250 (("2".to_owned(), "two".to_owned()), 2, 1),
1251 (("3".to_owned(), "three".to_owned()), 3, 1),
1252 ];
1253
1254 let shard_id0 = "s00000000-0000-0000-0000-000000000000"
1255 .parse::<ShardId>()
1256 .expect("invalid shard id");
1257 let mut client = new_test_client(&dyncfgs).await;
1258
1259 let (mut write0, mut read0) = client
1260 .expect_open::<String, String, u64, i64>(shard_id0)
1261 .await;
1262
1263 write0.expect_compare_and_append(&data, 0, 4).await;
1264
1265 {
1267 fn codecs(
1268 k: &str,
1269 v: &str,
1270 t: &str,
1271 d: &str,
1272 ) -> (String, String, String, String, Option<CodecConcreteType>) {
1273 (k.to_owned(), v.to_owned(), t.to_owned(), d.to_owned(), None)
1274 }
1275
1276 client.shared_states = Arc::new(StateCache::new_no_metrics());
1277 assert_eq!(
1278 client
1279 .open::<Vec<u8>, String, u64, i64>(
1280 shard_id0,
1281 Arc::new(VecU8Schema),
1282 Arc::new(StringSchema),
1283 Diagnostics::for_tests(),
1284 true,
1285 )
1286 .await
1287 .unwrap_err(),
1288 InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1289 requested: codecs("Vec<u8>", "String", "u64", "i64"),
1290 actual: codecs("String", "String", "u64", "i64"),
1291 }))
1292 );
1293 assert_eq!(
1294 client
1295 .open::<String, Vec<u8>, u64, i64>(
1296 shard_id0,
1297 Arc::new(StringSchema),
1298 Arc::new(VecU8Schema),
1299 Diagnostics::for_tests(),
1300 true,
1301 )
1302 .await
1303 .unwrap_err(),
1304 InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1305 requested: codecs("String", "Vec<u8>", "u64", "i64"),
1306 actual: codecs("String", "String", "u64", "i64"),
1307 }))
1308 );
1309 assert_eq!(
1310 client
1311 .open::<String, String, i64, i64>(
1312 shard_id0,
1313 Arc::new(StringSchema),
1314 Arc::new(StringSchema),
1315 Diagnostics::for_tests(),
1316 true,
1317 )
1318 .await
1319 .unwrap_err(),
1320 InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1321 requested: codecs("String", "String", "i64", "i64"),
1322 actual: codecs("String", "String", "u64", "i64"),
1323 }))
1324 );
1325 assert_eq!(
1326 client
1327 .open::<String, String, u64, u64>(
1328 shard_id0,
1329 Arc::new(StringSchema),
1330 Arc::new(StringSchema),
1331 Diagnostics::for_tests(),
1332 true,
1333 )
1334 .await
1335 .unwrap_err(),
1336 InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1337 requested: codecs("String", "String", "u64", "u64"),
1338 actual: codecs("String", "String", "u64", "i64"),
1339 }))
1340 );
1341
1342 assert_eq!(
1346 client
1347 .open_leased_reader::<Vec<u8>, String, u64, i64>(
1348 shard_id0,
1349 Arc::new(VecU8Schema),
1350 Arc::new(StringSchema),
1351 Diagnostics::for_tests(),
1352 true,
1353 )
1354 .await
1355 .unwrap_err(),
1356 InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1357 requested: codecs("Vec<u8>", "String", "u64", "i64"),
1358 actual: codecs("String", "String", "u64", "i64"),
1359 }))
1360 );
1361 assert_eq!(
1362 client
1363 .open_writer::<Vec<u8>, String, u64, i64>(
1364 shard_id0,
1365 Arc::new(VecU8Schema),
1366 Arc::new(StringSchema),
1367 Diagnostics::for_tests(),
1368 )
1369 .await
1370 .unwrap_err(),
1371 InvalidUsage::CodecMismatch(Box::new(CodecMismatch {
1372 requested: codecs("Vec<u8>", "String", "u64", "i64"),
1373 actual: codecs("String", "String", "u64", "i64"),
1374 }))
1375 );
1376 }
1377
1378 {
1380 let snap = read0
1381 .snapshot(Antichain::from_elem(3))
1382 .await
1383 .expect("cannot serve requested as_of");
1384
1385 let shard_id1 = "s11111111-1111-1111-1111-111111111111"
1386 .parse::<ShardId>()
1387 .expect("invalid shard id");
1388 let mut fetcher1 = client
1389 .create_batch_fetcher::<String, String, u64, i64>(
1390 shard_id1,
1391 Default::default(),
1392 Default::default(),
1393 false,
1394 Diagnostics::for_tests(),
1395 )
1396 .await
1397 .unwrap();
1398 for part in snap {
1399 let (part, _lease) = part.into_exchangeable_part();
1400 let res = fetcher1.fetch_leased_part(part).await;
1401 assert_eq!(
1402 res.unwrap_err(),
1403 InvalidUsage::BatchNotFromThisShard {
1404 batch_shard: shard_id0,
1405 handle_shard: shard_id1,
1406 }
1407 );
1408 }
1409 }
1410
1411 {
1413 let ts3 = &data[2];
1414 assert_eq!(ts3.1, 3);
1415 let ts3 = vec![ts3.clone()];
1416
1417 assert_eq!(
1420 write0
1421 .append(&ts3, Antichain::from_elem(4), Antichain::from_elem(5))
1422 .await
1423 .unwrap_err(),
1424 InvalidUsage::UpdateNotBeyondLower {
1425 ts: 3,
1426 lower: Antichain::from_elem(4),
1427 },
1428 );
1429 assert_eq!(
1430 write0
1431 .append(&ts3, Antichain::from_elem(2), Antichain::from_elem(3))
1432 .await
1433 .unwrap_err(),
1434 InvalidUsage::UpdateBeyondUpper {
1435 ts: 3,
1436 expected_upper: Antichain::from_elem(3),
1437 },
1438 );
1439 assert_eq!(
1441 write0
1442 .append(&data[..0], Antichain::from_elem(3), Antichain::from_elem(2))
1443 .await
1444 .unwrap_err(),
1445 InvalidUsage::InvalidBounds {
1446 lower: Antichain::from_elem(3),
1447 upper: Antichain::from_elem(2),
1448 },
1449 );
1450
1451 assert_eq!(
1453 write0
1454 .builder(Antichain::from_elem(3))
1455 .finish(Antichain::from_elem(2))
1456 .await
1457 .unwrap_err(),
1458 InvalidUsage::InvalidBounds {
1459 lower: Antichain::from_elem(3),
1460 upper: Antichain::from_elem(2)
1461 },
1462 );
1463 let batch = write0
1464 .batch(&ts3, Antichain::from_elem(3), Antichain::from_elem(4))
1465 .await
1466 .expect("invalid usage");
1467 assert_eq!(
1468 write0
1469 .append_batch(batch, Antichain::from_elem(4), Antichain::from_elem(5))
1470 .await
1471 .unwrap_err(),
1472 InvalidUsage::InvalidBatchBounds {
1473 batch_lower: Antichain::from_elem(3),
1474 batch_upper: Antichain::from_elem(4),
1475 append_lower: Antichain::from_elem(4),
1476 append_upper: Antichain::from_elem(5),
1477 },
1478 );
1479 let batch = write0
1480 .batch(&ts3, Antichain::from_elem(3), Antichain::from_elem(4))
1481 .await
1482 .expect("invalid usage");
1483 assert_eq!(
1484 write0
1485 .append_batch(batch, Antichain::from_elem(2), Antichain::from_elem(3))
1486 .await
1487 .unwrap_err(),
1488 InvalidUsage::InvalidBatchBounds {
1489 batch_lower: Antichain::from_elem(3),
1490 batch_upper: Antichain::from_elem(4),
1491 append_lower: Antichain::from_elem(2),
1492 append_upper: Antichain::from_elem(3),
1493 },
1494 );
1495 let batch = write0
1496 .batch(&ts3, Antichain::from_elem(3), Antichain::from_elem(4))
1497 .await
1498 .expect("invalid usage");
1499 assert!(matches!(
1502 write0
1503 .append_batch(batch, Antichain::from_elem(3), Antichain::from_elem(3))
1504 .await
1505 .unwrap_err(),
1506 InvalidUsage::InvalidEmptyTimeInterval { .. }
1507 ));
1508 }
1509 }
1510
1511 #[mz_persist_proc::test(tokio::test)]
1512 #[cfg_attr(miri, ignore)] async fn multiple_shards(dyncfgs: ConfigUpdates) {
1514 let data1 = [
1515 (("1".to_owned(), "one".to_owned()), 1, 1),
1516 (("2".to_owned(), "two".to_owned()), 2, 1),
1517 ];
1518
1519 let data2 = [(("1".to_owned(), ()), 1, 1), (("2".to_owned(), ()), 2, 1)];
1520
1521 let client = new_test_client(&dyncfgs).await;
1522
1523 let (mut write1, mut read1) = client
1524 .expect_open::<String, String, u64, i64>(ShardId::new())
1525 .await;
1526
1527 let (mut write2, mut read2) = client
1530 .expect_open::<String, (), u64, i64>(ShardId::new())
1531 .await;
1532
1533 write1
1534 .expect_compare_and_append(&data1[..], u64::minimum(), 3)
1535 .await;
1536
1537 write2
1538 .expect_compare_and_append(&data2[..], u64::minimum(), 3)
1539 .await;
1540
1541 assert_eq!(
1542 read1.expect_snapshot_and_fetch(2).await,
1543 all_ok(&data1[..], 2)
1544 );
1545
1546 assert_eq!(
1547 read2.expect_snapshot_and_fetch(2).await,
1548 all_ok(&data2[..], 2)
1549 );
1550 }
1551
1552 #[mz_persist_proc::test(tokio::test)]
1553 #[cfg_attr(miri, ignore)] async fn fetch_upper(dyncfgs: ConfigUpdates) {
1555 let data = [
1556 (("1".to_owned(), "one".to_owned()), 1, 1),
1557 (("2".to_owned(), "two".to_owned()), 2, 1),
1558 ];
1559
1560 let client = new_test_client(&dyncfgs).await;
1561
1562 let shard_id = ShardId::new();
1563
1564 let (mut write1, _read1) = client
1565 .expect_open::<String, String, u64, i64>(shard_id)
1566 .await;
1567
1568 let (mut write2, _read2) = client
1569 .expect_open::<String, String, u64, i64>(shard_id)
1570 .await;
1571
1572 write1
1573 .expect_append(&data[..], write1.upper().clone(), vec![3])
1574 .await;
1575
1576 assert_eq!(write2.fetch_recent_upper().await, &Antichain::from_elem(3));
1578
1579 assert_eq!(write2.upper(), &Antichain::from_elem(3));
1582 }
1583
1584 #[mz_persist_proc::test(tokio::test)]
1585 #[cfg_attr(miri, ignore)] async fn append_with_invalid_upper(dyncfgs: ConfigUpdates) {
1587 let data = [
1588 (("1".to_owned(), "one".to_owned()), 1, 1),
1589 (("2".to_owned(), "two".to_owned()), 2, 1),
1590 ];
1591
1592 let client = new_test_client(&dyncfgs).await;
1593
1594 let shard_id = ShardId::new();
1595
1596 let (mut write, _read) = client
1597 .expect_open::<String, String, u64, i64>(shard_id)
1598 .await;
1599
1600 write
1601 .expect_append(&data[..], write.upper().clone(), vec![3])
1602 .await;
1603
1604 let data = [
1605 (("5".to_owned(), "fünf".to_owned()), 5, 1),
1606 (("6".to_owned(), "sechs".to_owned()), 6, 1),
1607 ];
1608 let res = write
1609 .append(
1610 data.iter(),
1611 Antichain::from_elem(5),
1612 Antichain::from_elem(7),
1613 )
1614 .await;
1615 assert_eq!(
1616 res,
1617 Ok(Err(UpperMismatch {
1618 expected: Antichain::from_elem(5),
1619 current: Antichain::from_elem(3)
1620 }))
1621 );
1622
1623 assert_eq!(write.upper(), &Antichain::from_elem(3));
1625 }
1626
1627 #[allow(unused)]
1630 async fn sync_send(dyncfgs: ConfigUpdates) {
1631 mz_ore::test::init_logging();
1632
1633 fn is_send_sync<T: Send + Sync>(_x: T) -> bool {
1634 true
1635 }
1636
1637 let client = new_test_client(&dyncfgs).await;
1638
1639 let (write, read) = client
1640 .expect_open::<String, String, u64, i64>(ShardId::new())
1641 .await;
1642
1643 assert!(is_send_sync(client));
1644 assert!(is_send_sync(write));
1645 assert!(is_send_sync(read));
1646 }
1647
1648 #[mz_persist_proc::test(tokio::test)]
1649 #[cfg_attr(miri, ignore)] async fn compare_and_append(dyncfgs: ConfigUpdates) {
1651 let data = vec![
1652 (("1".to_owned(), "one".to_owned()), 1, 1),
1653 (("2".to_owned(), "two".to_owned()), 2, 1),
1654 (("3".to_owned(), "three".to_owned()), 3, 1),
1655 ];
1656
1657 let id = ShardId::new();
1658 let client = new_test_client(&dyncfgs).await;
1659 let (mut write1, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1660
1661 let (mut write2, _read) = client.expect_open::<String, String, u64, i64>(id).await;
1662
1663 assert_eq!(write1.upper(), &Antichain::from_elem(u64::minimum()));
1664 assert_eq!(write2.upper(), &Antichain::from_elem(u64::minimum()));
1665 assert_eq!(read.since(), &Antichain::from_elem(u64::minimum()));
1666
1667 write1
1669 .expect_compare_and_append(&data[..2], u64::minimum(), 3)
1670 .await;
1671 assert_eq!(write1.upper(), &Antichain::from_elem(3));
1672
1673 assert_eq!(
1674 read.expect_snapshot_and_fetch(2).await,
1675 all_ok(&data[..2], 2)
1676 );
1677
1678 let res = write2
1680 .compare_and_append(
1681 &data[..2],
1682 Antichain::from_elem(u64::minimum()),
1683 Antichain::from_elem(3),
1684 )
1685 .await;
1686 assert_eq!(
1687 res,
1688 Ok(Err(UpperMismatch {
1689 expected: Antichain::from_elem(u64::minimum()),
1690 current: Antichain::from_elem(3)
1691 }))
1692 );
1693
1694 assert_eq!(write2.upper(), &Antichain::from_elem(3));
1696
1697 write2.expect_compare_and_append(&data[2..], 3, 4).await;
1699
1700 assert_eq!(write2.upper(), &Antichain::from_elem(4));
1701
1702 assert_eq!(read.expect_snapshot_and_fetch(3).await, all_ok(&data, 3));
1703 }
1704
1705 #[mz_persist_proc::test(tokio::test)]
1706 #[cfg_attr(miri, ignore)] async fn overlapping_append(dyncfgs: ConfigUpdates) {
1708 mz_ore::test::init_logging_default("info");
1709
1710 let data = vec![
1711 (("1".to_owned(), "one".to_owned()), 1, 1),
1712 (("2".to_owned(), "two".to_owned()), 2, 1),
1713 (("3".to_owned(), "three".to_owned()), 3, 1),
1714 (("4".to_owned(), "vier".to_owned()), 4, 1),
1715 (("5".to_owned(), "cinque".to_owned()), 5, 1),
1716 ];
1717
1718 let id = ShardId::new();
1719 let client = new_test_client(&dyncfgs).await;
1720
1721 let (mut write1, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1722
1723 let (mut write2, _read) = client.expect_open::<String, String, u64, i64>(id).await;
1724
1725 let mut listen = read.clone("").await.expect_listen(0).await;
1727
1728 write1
1730 .expect_append(&data[..2], write1.upper().clone(), vec![3])
1731 .await;
1732 assert_eq!(write1.upper(), &Antichain::from_elem(3));
1733
1734 write2
1736 .expect_append(&data[..4], write2.upper().clone(), vec![5])
1737 .await;
1738 assert_eq!(write2.upper(), &Antichain::from_elem(5));
1739
1740 write1
1742 .expect_append(&data[2..5], write1.upper().clone(), vec![6])
1743 .await;
1744 assert_eq!(write1.upper(), &Antichain::from_elem(6));
1745
1746 assert_eq!(read.expect_snapshot_and_fetch(5).await, all_ok(&data, 5));
1747
1748 assert_eq!(
1749 listen.read_until(&6).await,
1750 (all_ok(&data[..], 1), Antichain::from_elem(6))
1751 );
1752 }
1753
1754 #[mz_persist_proc::test(tokio::test)]
1757 #[cfg_attr(miri, ignore)] async fn contiguous_append(dyncfgs: ConfigUpdates) {
1759 let data = vec![
1760 (("1".to_owned(), "one".to_owned()), 1, 1),
1761 (("2".to_owned(), "two".to_owned()), 2, 1),
1762 (("3".to_owned(), "three".to_owned()), 3, 1),
1763 (("4".to_owned(), "vier".to_owned()), 4, 1),
1764 (("5".to_owned(), "cinque".to_owned()), 5, 1),
1765 ];
1766
1767 let id = ShardId::new();
1768 let client = new_test_client(&dyncfgs).await;
1769
1770 let (mut write, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1771
1772 write
1774 .expect_append(&data[..2], write.upper().clone(), vec![3])
1775 .await;
1776 assert_eq!(write.upper(), &Antichain::from_elem(3));
1777
1778 let result = write
1781 .append(
1782 &data[4..5],
1783 Antichain::from_elem(5),
1784 Antichain::from_elem(6),
1785 )
1786 .await;
1787 assert_eq!(
1788 result,
1789 Ok(Err(UpperMismatch {
1790 expected: Antichain::from_elem(5),
1791 current: Antichain::from_elem(3)
1792 }))
1793 );
1794
1795 write.expect_append(&data[2..5], vec![3], vec![6]).await;
1797 assert_eq!(write.upper(), &Antichain::from_elem(6));
1798
1799 assert_eq!(read.expect_snapshot_and_fetch(5).await, all_ok(&data, 5));
1800 }
1801
1802 #[mz_persist_proc::test(tokio::test)]
1805 #[cfg_attr(miri, ignore)] async fn noncontiguous_append_per_writer(dyncfgs: ConfigUpdates) {
1807 let data = vec![
1808 (("1".to_owned(), "one".to_owned()), 1, 1),
1809 (("2".to_owned(), "two".to_owned()), 2, 1),
1810 (("3".to_owned(), "three".to_owned()), 3, 1),
1811 (("4".to_owned(), "vier".to_owned()), 4, 1),
1812 (("5".to_owned(), "cinque".to_owned()), 5, 1),
1813 ];
1814
1815 let id = ShardId::new();
1816 let client = new_test_client(&dyncfgs).await;
1817
1818 let (mut write1, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1819
1820 let (mut write2, _read) = client.expect_open::<String, String, u64, i64>(id).await;
1821
1822 write1
1824 .expect_append(&data[..2], write1.upper().clone(), vec![3])
1825 .await;
1826 assert_eq!(write1.upper(), &Antichain::from_elem(3));
1827
1828 write2.upper = Antichain::from_elem(3);
1830 write2
1831 .expect_append(&data[2..4], write2.upper().clone(), vec![5])
1832 .await;
1833 assert_eq!(write2.upper(), &Antichain::from_elem(5));
1834
1835 write1.upper = Antichain::from_elem(5);
1837 write1
1838 .expect_append(&data[4..5], write1.upper().clone(), vec![6])
1839 .await;
1840 assert_eq!(write1.upper(), &Antichain::from_elem(6));
1841
1842 assert_eq!(read.expect_snapshot_and_fetch(5).await, all_ok(&data, 5));
1843 }
1844
1845 #[mz_persist_proc::test(tokio::test)]
1848 #[cfg_attr(miri, ignore)] async fn contiguous_compare_and_append(dyncfgs: ConfigUpdates) {
1850 let data = vec![
1851 (("1".to_owned(), "one".to_owned()), 1, 1),
1852 (("2".to_owned(), "two".to_owned()), 2, 1),
1853 (("3".to_owned(), "three".to_owned()), 3, 1),
1854 (("4".to_owned(), "vier".to_owned()), 4, 1),
1855 (("5".to_owned(), "cinque".to_owned()), 5, 1),
1856 ];
1857
1858 let id = ShardId::new();
1859 let client = new_test_client(&dyncfgs).await;
1860
1861 let (mut write, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1862
1863 write.expect_compare_and_append(&data[..2], 0, 3).await;
1865 assert_eq!(write.upper(), &Antichain::from_elem(3));
1866
1867 let result = write
1870 .compare_and_append(
1871 &data[4..5],
1872 Antichain::from_elem(5),
1873 Antichain::from_elem(6),
1874 )
1875 .await;
1876 assert_eq!(
1877 result,
1878 Ok(Err(UpperMismatch {
1879 expected: Antichain::from_elem(5),
1880 current: Antichain::from_elem(3)
1881 }))
1882 );
1883
1884 write.expect_compare_and_append(&data[2..5], 3, 6).await;
1887 assert_eq!(write.upper(), &Antichain::from_elem(6));
1888
1889 assert_eq!(read.expect_snapshot_and_fetch(5).await, all_ok(&data, 5));
1890 }
1891
1892 #[mz_persist_proc::test(tokio::test)]
1895 #[cfg_attr(miri, ignore)] async fn noncontiguous_compare_and_append_per_writer(dyncfgs: ConfigUpdates) {
1897 let data = vec![
1898 (("1".to_owned(), "one".to_owned()), 1, 1),
1899 (("2".to_owned(), "two".to_owned()), 2, 1),
1900 (("3".to_owned(), "three".to_owned()), 3, 1),
1901 (("4".to_owned(), "vier".to_owned()), 4, 1),
1902 (("5".to_owned(), "cinque".to_owned()), 5, 1),
1903 ];
1904
1905 let id = ShardId::new();
1906 let client = new_test_client(&dyncfgs).await;
1907
1908 let (mut write1, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
1909
1910 let (mut write2, _read) = client.expect_open::<String, String, u64, i64>(id).await;
1911
1912 write1.expect_compare_and_append(&data[..2], 0, 3).await;
1914 assert_eq!(write1.upper(), &Antichain::from_elem(3));
1915
1916 write2.expect_compare_and_append(&data[2..4], 3, 5).await;
1918 assert_eq!(write2.upper(), &Antichain::from_elem(5));
1919
1920 write1.expect_compare_and_append(&data[4..5], 5, 6).await;
1922 assert_eq!(write1.upper(), &Antichain::from_elem(6));
1923
1924 assert_eq!(read.expect_snapshot_and_fetch(5).await, all_ok(&data, 5));
1925 }
1926
1927 #[mz_ore::test]
1928 fn fmt_ids() {
1929 assert_eq!(
1930 format!("{}", LeasedReaderId([0u8; 16])),
1931 "r00000000-0000-0000-0000-000000000000"
1932 );
1933 assert_eq!(
1934 format!("{:?}", LeasedReaderId([0u8; 16])),
1935 "LeasedReaderId(00000000-0000-0000-0000-000000000000)"
1936 );
1937 }
1938
1939 #[mz_persist_proc::test(tokio::test(flavor = "multi_thread"))]
1940 #[cfg_attr(miri, ignore)] async fn concurrency(dyncfgs: ConfigUpdates) {
1942 let data = DataGenerator::small();
1943
1944 const NUM_WRITERS: usize = 2;
1945 let id = ShardId::new();
1946 let client = new_test_client(&dyncfgs).await;
1947 let mut handles = Vec::<mz_ore::task::JoinHandle<()>>::new();
1948 for idx in 0..NUM_WRITERS {
1949 let (data, client) = (data.clone(), client.clone());
1950
1951 let (batch_tx, mut batch_rx) = tokio::sync::mpsc::channel(1);
1952
1953 let client1 = client.clone();
1954 let handle = mz_ore::task::spawn(|| format!("writer-{}", idx), async move {
1955 let (write, _) = client1.expect_open::<Vec<u8>, Vec<u8>, u64, i64>(id).await;
1956 let mut current_upper = 0;
1957 for batch in data.batches() {
1958 let new_upper = match batch.get(batch.len() - 1) {
1959 Some((_, max_ts, _)) => u64::decode(max_ts) + 1,
1960 None => continue,
1961 };
1962 if PartialOrder::less_equal(&Antichain::from_elem(new_upper), write.upper()) {
1977 continue;
1978 }
1979
1980 let current_upper_chain = Antichain::from_elem(current_upper);
1981 current_upper = new_upper;
1982 let new_upper_chain = Antichain::from_elem(new_upper);
1983 let mut builder = write.builder(current_upper_chain);
1984
1985 for ((k, v), t, d) in batch.iter() {
1986 builder
1987 .add(&k.to_vec(), &v.to_vec(), &u64::decode(t), &i64::decode(d))
1988 .await
1989 .expect("invalid usage");
1990 }
1991
1992 let batch = builder
1993 .finish(new_upper_chain)
1994 .await
1995 .expect("invalid usage");
1996
1997 match batch_tx.send(batch).await {
1998 Ok(_) => (),
1999 Err(e) => panic!("send error: {}", e),
2000 }
2001 }
2002 });
2003 handles.push(handle);
2004
2005 let handle = mz_ore::task::spawn(|| format!("appender-{}", idx), async move {
2006 let (mut write, _) = client.expect_open::<Vec<u8>, Vec<u8>, u64, i64>(id).await;
2007
2008 while let Some(batch) = batch_rx.recv().await {
2009 let lower = batch.lower().clone();
2010 let upper = batch.upper().clone();
2011 write
2012 .append_batch(batch, lower, upper)
2013 .await
2014 .expect("invalid usage")
2015 .expect("unexpected upper");
2016 }
2017 });
2018 handles.push(handle);
2019 }
2020
2021 for handle in handles {
2022 let () = handle.await;
2023 }
2024
2025 let expected = data.records().collect::<Vec<_>>();
2026 let max_ts = expected.last().map(|(_, t, _)| *t).unwrap_or_default();
2027 let (_, mut read) = client.expect_open::<Vec<u8>, Vec<u8>, u64, i64>(id).await;
2028 assert_eq!(
2029 read.expect_snapshot_and_fetch(max_ts).await,
2030 all_ok(expected.iter(), max_ts)
2031 );
2032 }
2033
2034 #[mz_persist_proc::test(tokio::test)]
2038 #[cfg_attr(miri, ignore)] async fn regression_blocking_reads(dyncfgs: ConfigUpdates) {
2040 let waker = noop_waker();
2041 let mut cx = Context::from_waker(&waker);
2042
2043 let data = [
2044 (("1".to_owned(), "one".to_owned()), 1, 1),
2045 (("2".to_owned(), "two".to_owned()), 2, 1),
2046 (("3".to_owned(), "three".to_owned()), 3, 1),
2047 ];
2048
2049 let id = ShardId::new();
2050 let client = new_test_client(&dyncfgs).await;
2051 let (mut write, mut read) = client.expect_open::<String, String, u64, i64>(id).await;
2052
2053 let mut listen = read.clone("").await.expect_listen(1).await;
2055 let mut listen_next = Box::pin(listen.fetch_next());
2056 for _ in 0..100 {
2060 assert!(
2061 Pin::new(&mut listen_next).poll(&mut cx).is_pending(),
2062 "listen::next unexpectedly ready"
2063 );
2064 }
2065
2066 write
2068 .expect_compare_and_append(&data[..2], u64::minimum(), 3)
2069 .await;
2070
2071 assert_eq!(
2074 listen_next.await,
2075 vec![
2076 ListenEvent::Updates(vec![(("2".to_owned(), "two".to_owned()), 2, 1)]),
2077 ListenEvent::Progress(Antichain::from_elem(3)),
2078 ]
2079 );
2080
2081 let mut snap = Box::pin(read.expect_snapshot_and_fetch(3));
2095 for _ in 0..100 {
2096 assert!(
2097 Pin::new(&mut snap).poll(&mut cx).is_pending(),
2098 "snapshot unexpectedly ready"
2099 );
2100 }
2101
2102 write.expect_compare_and_append(&data[2..], 3, 4).await;
2104
2105 assert_eq!(snap.await, all_ok(&data[..], 3));
2107 }
2108
2109 #[mz_persist_proc::test(tokio::test)]
2110 #[cfg_attr(miri, ignore)] async fn heartbeat_task_shutdown(dyncfgs: ConfigUpdates) {
2112 let mut cache = new_test_client_cache(&dyncfgs);
2115 cache
2116 .cfg
2117 .set_config(&READER_LEASE_DURATION, Duration::from_millis(1));
2118 cache.cfg.writer_lease_duration = Duration::from_millis(1);
2119 let (_write, mut read) = cache
2120 .open(PersistLocation::new_in_mem())
2121 .await
2122 .expect("client construction failed")
2123 .expect_open::<(), (), u64, i64>(ShardId::new())
2124 .await;
2125 let read_unexpired_state = read
2126 .unexpired_state
2127 .take()
2128 .expect("handle should have unexpired state");
2129 read.expire().await;
2130 read_unexpired_state.heartbeat_task.await
2131 }
2132
2133 #[mz_persist_proc::test(tokio::test)]
2136 #[cfg_attr(miri, ignore)] async fn finalize_empty_shard(dyncfgs: ConfigUpdates) {
2138 let persist_client = new_test_client(&dyncfgs).await;
2139
2140 let shard_id = ShardId::new();
2141 pub const CRITICAL_SINCE: CriticalReaderId =
2142 CriticalReaderId([0, 0, 0, 0, 17, 17, 34, 34, 51, 51, 68, 68, 68, 68, 68, 68]);
2143
2144 let (mut write, mut read) = persist_client
2145 .expect_open::<(), (), u64, i64>(shard_id)
2146 .await;
2147
2148 let () = read.downgrade_since(&Antichain::new()).await;
2151 let () = write.advance_upper(&Antichain::new()).await;
2152
2153 let mut since_handle: SinceHandle<(), (), u64, i64> = persist_client
2154 .open_critical_since(
2155 shard_id,
2156 CRITICAL_SINCE,
2157 Opaque::encode(&0u64),
2158 Diagnostics::for_tests(),
2159 )
2160 .await
2161 .expect("invalid persist usage");
2162
2163 let epoch = since_handle.opaque().clone();
2164 let new_since = Antichain::new();
2165 let downgrade = since_handle
2166 .compare_and_downgrade_since(&epoch, (&epoch, &new_since))
2167 .await;
2168
2169 assert!(
2170 downgrade.is_ok(),
2171 "downgrade of critical handle must succeed"
2172 );
2173
2174 let finalize = persist_client
2175 .finalize_shard::<(), (), u64, i64>(shard_id, Diagnostics::for_tests())
2176 .await;
2177
2178 assert_ok!(finalize, "finalization must succeed");
2179
2180 let is_finalized = persist_client
2181 .is_finalized::<(), (), u64, i64>(shard_id, Diagnostics::for_tests())
2182 .await
2183 .expect("invalid persist usage");
2184 assert!(is_finalized, "shard must still be finalized");
2185 }
2186
2187 #[mz_persist_proc::test(tokio::test)]
2191 #[cfg_attr(miri, ignore)] async fn finalize_shard(dyncfgs: ConfigUpdates) {
2193 const DATA: &[(((), ()), u64, i64)] = &[(((), ()), 0, 1)];
2194 let persist_client = new_test_client(&dyncfgs).await;
2195
2196 let shard_id = ShardId::new();
2197 pub const CRITICAL_SINCE: CriticalReaderId =
2198 CriticalReaderId([0, 0, 0, 0, 17, 17, 34, 34, 51, 51, 68, 68, 68, 68, 68, 68]);
2199
2200 let (mut write, mut read) = persist_client
2201 .expect_open::<(), (), u64, i64>(shard_id)
2202 .await;
2203
2204 let () = write
2206 .compare_and_append(DATA, Antichain::from_elem(0), Antichain::from_elem(1))
2207 .await
2208 .expect("usage should be valid")
2209 .expect("upper should match");
2210
2211 let () = read.downgrade_since(&Antichain::new()).await;
2214 let () = write.advance_upper(&Antichain::new()).await;
2215
2216 let mut since_handle: SinceHandle<(), (), u64, i64> = persist_client
2217 .open_critical_since(
2218 shard_id,
2219 CRITICAL_SINCE,
2220 Opaque::encode(&0u64),
2221 Diagnostics::for_tests(),
2222 )
2223 .await
2224 .expect("invalid persist usage");
2225
2226 let epoch = since_handle.opaque().clone();
2227 let new_since = Antichain::new();
2228 let downgrade = since_handle
2229 .compare_and_downgrade_since(&epoch, (&epoch, &new_since))
2230 .await;
2231
2232 assert!(
2233 downgrade.is_ok(),
2234 "downgrade of critical handle must succeed"
2235 );
2236
2237 let finalize = persist_client
2238 .finalize_shard::<(), (), u64, i64>(shard_id, Diagnostics::for_tests())
2239 .await;
2240
2241 assert_ok!(finalize, "finalization must succeed");
2242
2243 let is_finalized = persist_client
2244 .is_finalized::<(), (), u64, i64>(shard_id, Diagnostics::for_tests())
2245 .await
2246 .expect("invalid persist usage");
2247 assert!(is_finalized, "shard must still be finalized");
2248 }
2249
2250 proptest! {
2251 #![proptest_config(ProptestConfig::with_cases(4096))]
2252
2253 #[mz_ore::test]
2254 #[cfg_attr(miri, ignore)] fn shard_id_protobuf_roundtrip(expect in any::<ShardId>() ) {
2256 let actual = protobuf_roundtrip::<_, String>(&expect);
2257 assert_ok!(actual);
2258 assert_eq!(actual.unwrap(), expect);
2259 }
2260 }
2261}