1use anyhow::ensure;
11use async_stream::{stream, try_stream};
12use differential_dataflow::difference::Monoid;
13use mz_persist::metrics::ColumnarMetrics;
14use proptest::prelude::{Arbitrary, Strategy};
15use std::borrow::Cow;
16use std::cmp::Ordering;
17use std::collections::BTreeMap;
18use std::fmt::{Debug, Formatter};
19use std::marker::PhantomData;
20use std::ops::ControlFlow::{self, Break, Continue};
21use std::ops::{Deref, DerefMut};
22use std::time::Duration;
23
24use arrow::array::{Array, ArrayData, make_array};
25use arrow::datatypes::DataType;
26use bytes::Bytes;
27use differential_dataflow::Hashable;
28use differential_dataflow::lattice::Lattice;
29use differential_dataflow::trace::Description;
30use differential_dataflow::trace::implementations::BatchContainer;
31use futures::Stream;
32use futures_util::StreamExt;
33use itertools::Itertools;
34use mz_dyncfg::{Config, ParameterScope};
35use mz_ore::cast::CastFrom;
36use mz_ore::now::EpochMillis;
37use mz_ore::soft_panic_or_log;
38use mz_ore::vec::PartialOrdVecExt;
39use mz_persist::indexed::encoding::{BatchColumnarFormat, BlobTraceUpdates};
40use mz_persist::location::{Blob, SeqNo};
41use mz_persist_types::arrow::{ArrayBound, ProtoArrayData};
42use mz_persist_types::columnar::{ColumnEncoder, Schema};
43use mz_persist_types::schema::{SchemaId, backward_compatible};
44use mz_persist_types::{Codec, Codec64};
45use mz_proto::ProtoType;
46use mz_proto::RustType;
47use proptest_derive::Arbitrary;
48use semver::Version;
49use serde::ser::SerializeStruct;
50use serde::{Serialize, Serializer};
51use timely::PartialOrder;
52use timely::order::TotalOrder;
53use timely::progress::{Antichain, Timestamp};
54use tracing::info;
55use uuid::Uuid;
56
57use crate::critical::{CriticalReaderId, Opaque};
58use crate::error::InvalidUsage;
59use crate::internal::encoding::{
60 LazyInlineBatchPart, LazyPartStats, LazyProto, MetadataKey, MetadataMap, parse_id,
61};
62use crate::internal::gc::GcReq;
63use crate::internal::machine::retry_external;
64use crate::internal::paths::{BlobKey, PartId, PartialBatchKey, PartialRollupKey, WriterKey};
65use crate::internal::trace::{
66 ActiveCompaction, ApplyMergeResult, FueledMergeReq, FueledMergeRes, Trace,
67};
68use crate::metrics::Metrics;
69use crate::read::LeasedReaderId;
70use crate::schema::CaESchema;
71use crate::write::WriterId;
72use crate::{PersistConfig, ShardId};
73
74include!(concat!(
75 env!("OUT_DIR"),
76 "/mz_persist_client.internal.state.rs"
77));
78
79include!(concat!(
80 env!("OUT_DIR"),
81 "/mz_persist_client.internal.diff.rs"
82));
83
84pub(crate) const ROLLUP_THRESHOLD: Config<usize> = Config::new(
92 "persist_rollup_threshold",
93 128,
94 "The number of seqnos between rollups.",
95 ParameterScope::Environment,
96);
97
98pub(crate) const ROLLUP_FALLBACK_THRESHOLD_MS: Config<usize> = Config::new(
101 "persist_rollup_fallback_threshold_ms",
102 5000,
103 "The number of milliseconds before a worker claims an already claimed rollup.",
104 ParameterScope::Environment,
105);
106
107pub(crate) const ROLLUP_USE_ACTIVE_ROLLUP: Config<bool> = Config::new(
110 "persist_rollup_use_active_rollup",
111 true,
112 "Whether to use the new active rollup tracking mechanism.",
113 ParameterScope::Environment,
114);
115
116pub(crate) const GC_FALLBACK_THRESHOLD_MS: Config<usize> = Config::new(
119 "persist_gc_fallback_threshold_ms",
120 900000,
121 "The number of milliseconds before a worker claims an already claimed GC.",
122 ParameterScope::Environment,
123);
124
125pub(crate) const GC_MIN_VERSIONS: Config<usize> = Config::new(
127 "persist_gc_min_versions",
128 32,
129 "The number of un-GCd versions that may exist in state before we'll trigger a GC.",
130 ParameterScope::Environment,
131);
132
133pub(crate) const GC_MAX_VERSIONS: Config<usize> = Config::new(
135 "persist_gc_max_versions",
136 128_000,
137 "The maximum number of versions to GC in a single GC run.",
138 ParameterScope::Environment,
139);
140
141pub(crate) const GC_USE_ACTIVE_GC: Config<bool> = Config::new(
144 "persist_gc_use_active_gc",
145 false,
146 "Whether to use the new active GC tracking mechanism.",
147 ParameterScope::Environment,
148);
149
150pub(crate) const ENABLE_INCREMENTAL_COMPACTION: Config<bool> = Config::new(
151 "persist_enable_incremental_compaction",
152 false,
153 "Whether to enable incremental compaction.",
154 ParameterScope::Environment,
155);
156
157#[derive(Arbitrary, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
160#[serde(into = "String")]
161pub struct IdempotencyToken(pub(crate) [u8; 16]);
162
163impl std::fmt::Display for IdempotencyToken {
164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 write!(f, "i{}", Uuid::from_bytes(self.0))
166 }
167}
168
169impl std::fmt::Debug for IdempotencyToken {
170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 write!(f, "IdempotencyToken({})", Uuid::from_bytes(self.0))
172 }
173}
174
175impl std::str::FromStr for IdempotencyToken {
176 type Err = String;
177
178 fn from_str(s: &str) -> Result<Self, Self::Err> {
179 parse_id("i", "IdempotencyToken", s).map(IdempotencyToken)
180 }
181}
182
183impl From<IdempotencyToken> for String {
184 fn from(x: IdempotencyToken) -> Self {
185 x.to_string()
186 }
187}
188
189impl IdempotencyToken {
190 pub(crate) fn new() -> Self {
191 IdempotencyToken(*Uuid::new_v4().as_bytes())
192 }
193 pub(crate) const SENTINEL: IdempotencyToken = IdempotencyToken([17u8; 16]);
194}
195
196#[derive(Clone, Debug, PartialEq, Serialize)]
197pub struct LeasedReaderState<T> {
198 pub seqno: SeqNo,
200 pub since: Antichain<T>,
202 pub last_heartbeat_timestamp_ms: u64,
204 pub lease_duration_ms: u64,
207 pub debug: HandleDebugState,
209}
210
211#[derive(Clone, Debug, PartialEq, Serialize)]
212pub struct CriticalReaderState<T> {
213 pub since: Antichain<T>,
215 pub opaque: Opaque,
217 pub debug: HandleDebugState,
219}
220
221#[derive(Clone, Debug, PartialEq, Serialize)]
222pub struct WriterState<T> {
223 pub last_heartbeat_timestamp_ms: u64,
225 pub lease_duration_ms: u64,
228 pub most_recent_write_token: IdempotencyToken,
231 pub most_recent_write_upper: Antichain<T>,
234 pub debug: HandleDebugState,
236}
237
238#[derive(Arbitrary, Clone, Debug, Default, PartialEq, Serialize)]
240pub struct HandleDebugState {
241 pub hostname: String,
244 pub purpose: String,
246}
247
248#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
252#[serde(tag = "type")]
253pub enum BatchPart<T> {
254 Hollow(HollowBatchPart<T>),
255 Inline {
256 updates: LazyInlineBatchPart,
257 ts_rewrite: Option<Antichain<T>>,
258 schema_id: Option<SchemaId>,
259
260 deprecated_schema_id: Option<SchemaId>,
262 },
263}
264
265fn decode_structured_lower(lower: &LazyProto<ProtoArrayData>) -> Option<ArrayBound> {
266 let try_decode = |lower: &LazyProto<ProtoArrayData>| {
267 let proto = lower.decode()?;
268 let data = ArrayData::from_proto(proto)?;
269 ensure!(data.len() == 1);
270 Ok(ArrayBound::new(make_array(data), 0))
271 };
272
273 let decoded: anyhow::Result<ArrayBound> = try_decode(lower);
274
275 match decoded {
276 Ok(bound) => Some(bound),
277 Err(e) => {
278 soft_panic_or_log!("failed to decode bound: {e:#?}");
279 None
280 }
281 }
282}
283
284impl<T> BatchPart<T> {
285 pub fn hollow_bytes(&self) -> usize {
286 match self {
287 BatchPart::Hollow(x) => x.encoded_size_bytes,
288 BatchPart::Inline { .. } => 0,
289 }
290 }
291
292 pub fn is_inline(&self) -> bool {
293 matches!(self, BatchPart::Inline { .. })
294 }
295
296 pub fn inline_bytes(&self) -> usize {
297 match self {
298 BatchPart::Hollow(_) => 0,
299 BatchPart::Inline { updates, .. } => updates.encoded_size_bytes(),
300 }
301 }
302
303 pub fn writer_key(&self) -> Option<WriterKey> {
304 match self {
305 BatchPart::Hollow(x) => x.key.split().map(|(writer, _part)| writer),
306 BatchPart::Inline { .. } => None,
307 }
308 }
309
310 pub fn encoded_size_bytes(&self) -> usize {
311 match self {
312 BatchPart::Hollow(x) => x.encoded_size_bytes,
313 BatchPart::Inline { updates, .. } => updates.encoded_size_bytes(),
314 }
315 }
316
317 pub fn printable_name(&self) -> &str {
320 match self {
321 BatchPart::Hollow(x) => x.key.0.as_str(),
322 BatchPart::Inline { .. } => "<inline>",
323 }
324 }
325
326 pub fn stats(&self) -> Option<&LazyPartStats> {
327 match self {
328 BatchPart::Hollow(x) => x.stats.as_ref(),
329 BatchPart::Inline { .. } => None,
330 }
331 }
332
333 pub fn key_lower(&self) -> &[u8] {
334 match self {
335 BatchPart::Hollow(x) => x.key_lower.as_slice(),
336 BatchPart::Inline { .. } => &[],
343 }
344 }
345
346 pub fn structured_key_lower(&self) -> Option<ArrayBound> {
347 let part = match self {
348 BatchPart::Hollow(part) => part,
349 BatchPart::Inline { .. } => return None,
350 };
351
352 decode_structured_lower(part.structured_key_lower.as_ref()?)
353 }
354
355 pub fn ts_rewrite(&self) -> Option<&Antichain<T>> {
356 match self {
357 BatchPart::Hollow(x) => x.ts_rewrite.as_ref(),
358 BatchPart::Inline { ts_rewrite, .. } => ts_rewrite.as_ref(),
359 }
360 }
361
362 pub fn schema_id(&self) -> Option<SchemaId> {
363 match self {
364 BatchPart::Hollow(x) => x.schema_id,
365 BatchPart::Inline { schema_id, .. } => *schema_id,
366 }
367 }
368
369 pub fn deprecated_schema_id(&self) -> Option<SchemaId> {
370 match self {
371 BatchPart::Hollow(x) => x.deprecated_schema_id,
372 BatchPart::Inline {
373 deprecated_schema_id,
374 ..
375 } => *deprecated_schema_id,
376 }
377 }
378}
379
380impl<T: Timestamp + Codec64> BatchPart<T> {
381 pub fn is_structured_only(&self, metrics: &ColumnarMetrics) -> bool {
382 match self {
383 BatchPart::Hollow(x) => matches!(x.format, Some(BatchColumnarFormat::Structured)),
384 BatchPart::Inline { updates, .. } => {
385 let inline_part = updates.decode::<T>(metrics).expect("valid inline part");
386 matches!(inline_part.updates, BlobTraceUpdates::Structured { .. })
387 }
388 }
389 }
390
391 pub fn diffs_sum<D: Codec64 + Monoid>(&self, metrics: &ColumnarMetrics) -> Option<D> {
392 match self {
393 BatchPart::Hollow(x) => x.diffs_sum.map(D::decode),
394 BatchPart::Inline { updates, .. } => Some(
395 updates
396 .decode::<T>(metrics)
397 .expect("valid inline part")
398 .updates
399 .diffs_sum(),
400 ),
401 }
402 }
403}
404
405#[derive(Debug, Clone)]
407pub struct HollowRun<T> {
408 pub(crate) parts: Vec<RunPart<T>>,
410}
411
412#[derive(Debug, Eq, PartialEq, Clone, Serialize)]
415pub struct HollowRunRef<T> {
416 pub key: PartialBatchKey,
417
418 pub hollow_bytes: usize,
420
421 pub max_part_bytes: usize,
423
424 pub key_lower: Vec<u8>,
426
427 pub structured_key_lower: Option<LazyProto<ProtoArrayData>>,
429
430 pub diffs_sum: Option<[u8; 8]>,
431
432 pub(crate) _phantom_data: PhantomData<T>,
433}
434impl<T: Eq> PartialOrd<Self> for HollowRunRef<T> {
435 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
436 Some(self.cmp(other))
437 }
438}
439
440impl<T: Eq> Ord for HollowRunRef<T> {
441 fn cmp(&self, other: &Self) -> Ordering {
442 self.key.cmp(&other.key)
443 }
444}
445
446impl<T> HollowRunRef<T> {
447 pub fn writer_key(&self) -> Option<WriterKey> {
448 Some(self.key.split()?.0)
449 }
450}
451
452impl<T: Timestamp + Codec64> HollowRunRef<T> {
453 pub async fn set<D: Codec64 + Monoid>(
455 shard_id: ShardId,
456 blob: &dyn Blob,
457 writer: &WriterKey,
458 data: HollowRun<T>,
459 metrics: &Metrics,
460 ) -> Self {
461 let hollow_bytes = data.parts.iter().map(|p| p.hollow_bytes()).sum();
462 let max_part_bytes = data
463 .parts
464 .iter()
465 .map(|p| p.max_part_bytes())
466 .max()
467 .unwrap_or(0);
468 let key_lower = data
469 .parts
470 .first()
471 .map_or(vec![], |p| p.key_lower().to_vec());
472 let structured_key_lower = match data.parts.first() {
473 Some(RunPart::Many(r)) => r.structured_key_lower.clone(),
474 Some(RunPart::Single(BatchPart::Hollow(p))) => p.structured_key_lower.clone(),
475 Some(RunPart::Single(BatchPart::Inline { .. })) | None => None,
476 };
477 let diffs_sum = data
478 .parts
479 .iter()
480 .map(|p| {
481 p.diffs_sum::<D>(&metrics.columnar)
482 .expect("valid diffs sum")
483 })
484 .reduce(|mut a, b| {
485 a.plus_equals(&b);
486 a
487 })
488 .expect("valid diffs sum")
489 .encode();
490
491 let key = PartialBatchKey::new(writer, &PartId::new());
492 let blob_key = key.complete(&shard_id);
493 let bytes = Bytes::from(prost::Message::encode_to_vec(&data.into_proto()));
494 let () = retry_external(&metrics.retries.external.hollow_run_set, || {
495 blob.set(&blob_key, bytes.clone())
496 })
497 .await;
498 Self {
499 key,
500 hollow_bytes,
501 max_part_bytes,
502 key_lower,
503 structured_key_lower,
504 diffs_sum: Some(diffs_sum),
505 _phantom_data: Default::default(),
506 }
507 }
508
509 pub async fn get(
513 &self,
514 shard_id: ShardId,
515 blob: &dyn Blob,
516 metrics: &Metrics,
517 ) -> Option<HollowRun<T>> {
518 let blob_key = self.key.complete(&shard_id);
519 let mut bytes = retry_external(&metrics.retries.external.hollow_run_get, || {
520 blob.get(&blob_key)
521 })
522 .await?;
523 let proto_runs: ProtoHollowRun =
524 prost::Message::decode(&mut bytes).expect("illegal state: invalid proto bytes");
525 let runs = proto_runs
526 .into_rust()
527 .expect("illegal state: invalid encoded runs proto");
528 Some(runs)
529 }
530}
531
532#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
536#[serde(untagged)]
537pub enum RunPart<T> {
538 Single(BatchPart<T>),
539 Many(HollowRunRef<T>),
540}
541
542impl<T: Ord> PartialOrd<Self> for RunPart<T> {
543 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
544 Some(self.cmp(other))
545 }
546}
547
548impl<T: Ord> Ord for RunPart<T> {
549 fn cmp(&self, other: &Self) -> Ordering {
550 match (self, other) {
551 (RunPart::Single(a), RunPart::Single(b)) => a.cmp(b),
552 (RunPart::Single(_), RunPart::Many(_)) => Ordering::Less,
553 (RunPart::Many(_), RunPart::Single(_)) => Ordering::Greater,
554 (RunPart::Many(a), RunPart::Many(b)) => a.cmp(b),
555 }
556 }
557}
558
559impl<T> RunPart<T> {
560 #[cfg(test)]
561 pub fn expect_hollow_part(&self) -> &HollowBatchPart<T> {
562 match self {
563 RunPart::Single(BatchPart::Hollow(hollow)) => hollow,
564 _ => panic!("expected hollow part!"),
565 }
566 }
567
568 pub fn hollow_bytes(&self) -> usize {
569 match self {
570 Self::Single(p) => p.hollow_bytes(),
571 Self::Many(r) => r.hollow_bytes,
572 }
573 }
574
575 pub fn is_inline(&self) -> bool {
576 match self {
577 Self::Single(p) => p.is_inline(),
578 Self::Many(_) => false,
579 }
580 }
581
582 pub fn inline_bytes(&self) -> usize {
583 match self {
584 Self::Single(p) => p.inline_bytes(),
585 Self::Many(_) => 0,
586 }
587 }
588
589 pub fn max_part_bytes(&self) -> usize {
590 match self {
591 Self::Single(p) => p.encoded_size_bytes(),
592 Self::Many(r) => r.max_part_bytes,
593 }
594 }
595
596 pub fn writer_key(&self) -> Option<WriterKey> {
597 match self {
598 Self::Single(p) => p.writer_key(),
599 Self::Many(r) => r.writer_key(),
600 }
601 }
602
603 pub fn encoded_size_bytes(&self) -> usize {
604 match self {
605 Self::Single(p) => p.encoded_size_bytes(),
606 Self::Many(r) => r.hollow_bytes,
607 }
608 }
609
610 pub fn schema_id(&self) -> Option<SchemaId> {
611 match self {
612 Self::Single(p) => p.schema_id(),
613 Self::Many(_) => None,
614 }
615 }
616
617 pub fn printable_name(&self) -> &str {
620 match self {
621 Self::Single(p) => p.printable_name(),
622 Self::Many(r) => r.key.0.as_str(),
623 }
624 }
625
626 pub fn stats(&self) -> Option<&LazyPartStats> {
627 match self {
628 Self::Single(p) => p.stats(),
629 Self::Many(_) => None,
631 }
632 }
633
634 pub fn key_lower(&self) -> &[u8] {
635 match self {
636 Self::Single(p) => p.key_lower(),
637 Self::Many(r) => r.key_lower.as_slice(),
638 }
639 }
640
641 pub fn structured_key_lower(&self) -> Option<ArrayBound> {
642 match self {
643 Self::Single(p) => p.structured_key_lower(),
644 Self::Many(_) => None,
645 }
646 }
647
648 pub fn ts_rewrite(&self) -> Option<&Antichain<T>> {
649 match self {
650 Self::Single(p) => p.ts_rewrite(),
651 Self::Many(_) => None,
652 }
653 }
654}
655
656impl<T> RunPart<T>
657where
658 T: Timestamp + Codec64,
659{
660 pub fn diffs_sum<D: Codec64 + Monoid>(&self, metrics: &ColumnarMetrics) -> Option<D> {
661 match self {
662 Self::Single(p) => p.diffs_sum(metrics),
663 Self::Many(hollow_run) => hollow_run.diffs_sum.map(D::decode),
664 }
665 }
666}
667
668#[derive(Clone, Debug)]
670pub struct MissingBlob(BlobKey);
671
672impl std::fmt::Display for MissingBlob {
673 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
674 write!(f, "unexpectedly missing key: {}", self.0)
675 }
676}
677
678impl std::error::Error for MissingBlob {}
679
680impl<T: Timestamp + Codec64 + Sync> RunPart<T> {
681 pub fn part_stream<'a>(
682 &'a self,
683 shard_id: ShardId,
684 blob: &'a dyn Blob,
685 metrics: &'a Metrics,
686 ) -> impl Stream<Item = Result<Cow<'a, BatchPart<T>>, MissingBlob>> + Send + 'a {
687 try_stream! {
688 match self {
689 RunPart::Single(p) => {
690 yield Cow::Borrowed(p);
691 }
692 RunPart::Many(r) => {
693 let fetched = r.get(shard_id, blob, metrics).await
694 .ok_or_else(|| MissingBlob(r.key.complete(&shard_id)))?;
695 for run_part in fetched.parts {
696 for await batch_part in
697 run_part.part_stream(shard_id, blob, metrics).boxed()
698 {
699 yield Cow::Owned(batch_part?.into_owned());
700 }
701 }
702 }
703 }
704 }
705 }
706}
707
708impl<T: Ord> PartialOrd for BatchPart<T> {
709 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
710 Some(self.cmp(other))
711 }
712}
713
714impl<T: Ord> Ord for BatchPart<T> {
715 fn cmp(&self, other: &Self) -> Ordering {
716 match (self, other) {
717 (BatchPart::Hollow(s), BatchPart::Hollow(o)) => s.cmp(o),
718 (
719 BatchPart::Inline {
720 updates: s_updates,
721 ts_rewrite: s_ts_rewrite,
722 schema_id: s_schema_id,
723 deprecated_schema_id: s_deprecated_schema_id,
724 },
725 BatchPart::Inline {
726 updates: o_updates,
727 ts_rewrite: o_ts_rewrite,
728 schema_id: o_schema_id,
729 deprecated_schema_id: o_deprecated_schema_id,
730 },
731 ) => (
732 s_updates,
733 s_ts_rewrite.as_ref().map(|x| x.elements()),
734 s_schema_id,
735 s_deprecated_schema_id,
736 )
737 .cmp(&(
738 o_updates,
739 o_ts_rewrite.as_ref().map(|x| x.elements()),
740 o_schema_id,
741 o_deprecated_schema_id,
742 )),
743 (BatchPart::Hollow(_), BatchPart::Inline { .. }) => Ordering::Less,
744 (BatchPart::Inline { .. }, BatchPart::Hollow(_)) => Ordering::Greater,
745 }
746 }
747}
748
749#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd, Serialize)]
751pub(crate) enum RunOrder {
752 Unordered,
754 Codec,
756 Structured,
758}
759
760#[derive(Clone, PartialEq, Eq, Ord, PartialOrd, Serialize, Copy, Hash)]
761pub struct RunId(pub(crate) [u8; 16]);
762
763impl std::fmt::Display for RunId {
764 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
765 write!(f, "ri{}", Uuid::from_bytes(self.0))
766 }
767}
768
769impl std::fmt::Debug for RunId {
770 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
771 write!(f, "RunId({})", Uuid::from_bytes(self.0))
772 }
773}
774
775impl std::str::FromStr for RunId {
776 type Err = String;
777
778 fn from_str(s: &str) -> Result<Self, Self::Err> {
779 parse_id("ri", "RunId", s).map(RunId)
780 }
781}
782
783impl From<RunId> for String {
784 fn from(x: RunId) -> Self {
785 x.to_string()
786 }
787}
788
789impl RunId {
790 pub(crate) fn new() -> Self {
791 RunId(*Uuid::new_v4().as_bytes())
792 }
793}
794
795impl Arbitrary for RunId {
796 type Parameters = ();
797 type Strategy = proptest::strategy::BoxedStrategy<Self>;
798 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
799 Strategy::prop_map(proptest::prelude::any::<u128>(), |n| {
800 RunId(*Uuid::from_u128(n).as_bytes())
801 })
802 .boxed()
803 }
804}
805
806#[derive(Clone, Debug, Default, PartialEq, Eq, Ord, PartialOrd, Serialize)]
808pub struct RunMeta {
809 pub(crate) order: Option<RunOrder>,
811 pub(crate) schema: Option<SchemaId>,
813
814 pub(crate) deprecated_schema: Option<SchemaId>,
816
817 pub(crate) id: Option<RunId>,
819
820 pub(crate) len: Option<usize>,
822
823 #[serde(skip_serializing_if = "MetadataMap::is_empty")]
825 pub(crate) meta: MetadataMap,
826}
827
828const RUN_META_BOUNDS_TRUNCATED: MetadataKey<bool> = MetadataKey::new("truncated");
830
831impl RunMeta {
832 pub(crate) fn bounds_truncated(&self) -> bool {
842 self.meta.get(RUN_META_BOUNDS_TRUNCATED).unwrap_or(false)
843 }
844
845 pub(crate) fn set_bounds_truncated(&mut self) {
848 self.meta.set(RUN_META_BOUNDS_TRUNCATED, true);
849 }
850}
851
852#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
854pub struct HollowBatchPart<T> {
855 pub key: PartialBatchKey,
857 #[serde(skip_serializing_if = "MetadataMap::is_empty")]
859 pub meta: MetadataMap,
860 pub encoded_size_bytes: usize,
862 #[serde(serialize_with = "serialize_part_bytes")]
865 pub key_lower: Vec<u8>,
866 #[serde(serialize_with = "serialize_lazy_proto")]
868 pub structured_key_lower: Option<LazyProto<ProtoArrayData>>,
869 #[serde(serialize_with = "serialize_part_stats")]
871 pub stats: Option<LazyPartStats>,
872 pub ts_rewrite: Option<Antichain<T>>,
880 #[serde(serialize_with = "serialize_diffs_sum")]
888 pub diffs_sum: Option<[u8; 8]>,
889 pub format: Option<BatchColumnarFormat>,
894 pub schema_id: Option<SchemaId>,
899
900 pub deprecated_schema_id: Option<SchemaId>,
902}
903
904#[derive(Clone, PartialEq, Eq)]
908pub struct HollowBatch<T> {
909 pub desc: Description<T>,
911 pub len: usize,
913 pub(crate) parts: Vec<RunPart<T>>,
915 pub(crate) run_splits: Vec<usize>,
923 pub(crate) run_meta: Vec<RunMeta>,
926}
927
928impl<T: Debug> Debug for HollowBatch<T> {
929 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
930 let HollowBatch {
931 desc,
932 parts,
933 len,
934 run_splits: runs,
935 run_meta,
936 } = self;
937 f.debug_struct("HollowBatch")
938 .field(
939 "desc",
940 &(
941 desc.lower().elements(),
942 desc.upper().elements(),
943 desc.since().elements(),
944 ),
945 )
946 .field("parts", &parts)
947 .field("len", &len)
948 .field("runs", &runs)
949 .field("run_meta", &run_meta)
950 .finish()
951 }
952}
953
954impl<T: Serialize> serde::Serialize for HollowBatch<T> {
955 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
956 let HollowBatch {
957 desc,
958 len,
959 parts: _,
961 run_splits: _,
962 run_meta: _,
963 } = self;
964 let mut s = s.serialize_struct("HollowBatch", 5)?;
965 let () = s.serialize_field("lower", &desc.lower().elements())?;
966 let () = s.serialize_field("upper", &desc.upper().elements())?;
967 let () = s.serialize_field("since", &desc.since().elements())?;
968 let () = s.serialize_field("len", len)?;
969 let () = s.serialize_field("part_runs", &self.runs().collect::<Vec<_>>())?;
970 s.end()
971 }
972}
973
974impl<T: Ord> PartialOrd for HollowBatch<T> {
975 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
976 Some(self.cmp(other))
977 }
978}
979
980impl<T: Ord> Ord for HollowBatch<T> {
981 fn cmp(&self, other: &Self) -> Ordering {
982 let HollowBatch {
985 desc: self_desc,
986 parts: self_parts,
987 len: self_len,
988 run_splits: self_runs,
989 run_meta: self_run_meta,
990 } = self;
991 let HollowBatch {
992 desc: other_desc,
993 parts: other_parts,
994 len: other_len,
995 run_splits: other_runs,
996 run_meta: other_run_meta,
997 } = other;
998 (
999 self_desc.lower().elements(),
1000 self_desc.upper().elements(),
1001 self_desc.since().elements(),
1002 self_parts,
1003 self_len,
1004 self_runs,
1005 self_run_meta,
1006 )
1007 .cmp(&(
1008 other_desc.lower().elements(),
1009 other_desc.upper().elements(),
1010 other_desc.since().elements(),
1011 other_parts,
1012 other_len,
1013 other_runs,
1014 other_run_meta,
1015 ))
1016 }
1017}
1018
1019impl<T: Timestamp + Codec64 + Sync> HollowBatch<T> {
1020 pub(crate) fn part_stream<'a>(
1021 &'a self,
1022 shard_id: ShardId,
1023 blob: &'a dyn Blob,
1024 metrics: &'a Metrics,
1025 ) -> impl Stream<Item = Result<Cow<'a, BatchPart<T>>, MissingBlob>> + 'a {
1026 stream! {
1027 for part in &self.parts {
1028 for await part in part.part_stream(shard_id, blob, metrics) {
1029 yield part;
1030 }
1031 }
1032 }
1033 }
1034}
1035impl<T> HollowBatch<T> {
1036 pub(crate) fn new(
1043 desc: Description<T>,
1044 parts: Vec<RunPart<T>>,
1045 len: usize,
1046 run_meta: Vec<RunMeta>,
1047 run_splits: Vec<usize>,
1048 ) -> Self {
1049 debug_assert!(
1050 run_splits.is_strictly_sorted(),
1051 "run indices should be strictly increasing"
1052 );
1053 mz_ore::soft_assert_no_log!(
1054 run_splits.first().map_or(true, |i| *i > 0),
1055 "run indices should be positive"
1056 );
1057 mz_ore::soft_assert_no_log!(
1058 run_splits.last().map_or(true, |i| *i < parts.len()),
1059 "run indices should be valid indices into parts"
1060 );
1061 mz_ore::soft_assert_no_log!(
1062 parts.is_empty() || run_meta.len() == run_splits.len() + 1,
1063 "all metadata should correspond to a run"
1064 );
1065
1066 Self {
1067 desc,
1068 len,
1069 parts,
1070 run_splits,
1071 run_meta,
1072 }
1073 }
1074
1075 pub(crate) fn new_run(desc: Description<T>, parts: Vec<RunPart<T>>, len: usize) -> Self {
1077 let run_meta = if parts.is_empty() {
1078 vec![]
1079 } else {
1080 vec![RunMeta::default()]
1081 };
1082 Self {
1083 desc,
1084 len,
1085 parts,
1086 run_splits: vec![],
1087 run_meta,
1088 }
1089 }
1090
1091 #[cfg(test)]
1092 pub(crate) fn new_run_for_test(
1093 desc: Description<T>,
1094 parts: Vec<RunPart<T>>,
1095 len: usize,
1096 run_id: RunId,
1097 ) -> Self {
1098 let run_meta = if parts.is_empty() {
1099 vec![]
1100 } else {
1101 let mut meta = RunMeta::default();
1102 meta.id = Some(run_id);
1103 vec![meta]
1104 };
1105 Self {
1106 desc,
1107 len,
1108 parts,
1109 run_splits: vec![],
1110 run_meta,
1111 }
1112 }
1113
1114 pub(crate) fn empty(desc: Description<T>) -> Self {
1116 Self {
1117 desc,
1118 len: 0,
1119 parts: vec![],
1120 run_splits: vec![],
1121 run_meta: vec![],
1122 }
1123 }
1124
1125 pub(crate) fn runs(&self) -> impl Iterator<Item = (&RunMeta, &[RunPart<T>])> {
1126 let run_ends = self
1127 .run_splits
1128 .iter()
1129 .copied()
1130 .chain(std::iter::once(self.parts.len()));
1131 let run_metas = self.run_meta.iter();
1132 let run_parts = run_ends
1133 .scan(0, |start, end| {
1134 let range = *start..end;
1135 *start = end;
1136 Some(range)
1137 })
1138 .filter(|range| !range.is_empty())
1139 .map(|range| &self.parts[range]);
1140 run_metas.zip_eq(run_parts)
1141 }
1142
1143 pub(crate) fn inline_bytes(&self) -> usize {
1144 self.parts.iter().map(|x| x.inline_bytes()).sum()
1145 }
1146
1147 pub(crate) fn is_empty(&self) -> bool {
1148 self.parts.is_empty()
1149 }
1150
1151 pub(crate) fn part_count(&self) -> usize {
1152 self.parts.len()
1153 }
1154
1155 pub fn encoded_size_bytes(&self) -> usize {
1157 self.parts.iter().map(|p| p.encoded_size_bytes()).sum()
1158 }
1159}
1160
1161impl<T: Timestamp + TotalOrder> HollowBatch<T> {
1163 pub(crate) fn rewrite_ts(
1164 &mut self,
1165 frontier: &Antichain<T>,
1166 new_upper: Antichain<T>,
1167 ) -> Result<(), String> {
1168 if !PartialOrder::less_than(frontier, &new_upper) {
1169 return Err(format!(
1170 "rewrite frontier {:?} !< rewrite upper {:?}",
1171 frontier.elements(),
1172 new_upper.elements(),
1173 ));
1174 }
1175 if PartialOrder::less_than(&new_upper, self.desc.upper()) {
1176 return Err(format!(
1177 "rewrite upper {:?} < batch upper {:?}",
1178 new_upper.elements(),
1179 self.desc.upper().elements(),
1180 ));
1181 }
1182
1183 if PartialOrder::less_than(frontier, self.desc.lower()) {
1186 return Err(format!(
1187 "rewrite frontier {:?} < batch lower {:?}",
1188 frontier.elements(),
1189 self.desc.lower().elements(),
1190 ));
1191 }
1192 if self.desc.since() != &Antichain::from_elem(T::minimum()) {
1193 return Err(format!(
1194 "batch since {:?} != minimum antichain {:?}",
1195 self.desc.since().elements(),
1196 [T::minimum()],
1197 ));
1198 }
1199 for part in self.parts.iter() {
1200 let Some(ts_rewrite) = part.ts_rewrite() else {
1201 continue;
1202 };
1203 if PartialOrder::less_than(frontier, ts_rewrite) {
1204 return Err(format!(
1205 "rewrite frontier {:?} < batch rewrite {:?}",
1206 frontier.elements(),
1207 ts_rewrite.elements(),
1208 ));
1209 }
1210 }
1211
1212 self.desc = Description::new(
1213 self.desc.lower().clone(),
1214 new_upper,
1215 self.desc.since().clone(),
1216 );
1217 for part in &mut self.parts {
1218 match part {
1219 RunPart::Single(BatchPart::Hollow(part)) => {
1220 part.ts_rewrite = Some(frontier.clone())
1221 }
1222 RunPart::Single(BatchPart::Inline { ts_rewrite, .. }) => {
1223 *ts_rewrite = Some(frontier.clone())
1224 }
1225 RunPart::Many(runs) => {
1226 panic!("unexpected rewrite of a hollow runs ref: {runs:?}");
1229 }
1230 }
1231 }
1232 Ok(())
1233 }
1234}
1235
1236impl<T: Ord> PartialOrd for HollowBatchPart<T> {
1237 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1238 Some(self.cmp(other))
1239 }
1240}
1241
1242impl<T: Ord> Ord for HollowBatchPart<T> {
1243 fn cmp(&self, other: &Self) -> Ordering {
1244 let HollowBatchPart {
1247 key: self_key,
1248 meta: self_meta,
1249 encoded_size_bytes: self_encoded_size_bytes,
1250 key_lower: self_key_lower,
1251 structured_key_lower: self_structured_key_lower,
1252 stats: self_stats,
1253 ts_rewrite: self_ts_rewrite,
1254 diffs_sum: self_diffs_sum,
1255 format: self_format,
1256 schema_id: self_schema_id,
1257 deprecated_schema_id: self_deprecated_schema_id,
1258 } = self;
1259 let HollowBatchPart {
1260 key: other_key,
1261 meta: other_meta,
1262 encoded_size_bytes: other_encoded_size_bytes,
1263 key_lower: other_key_lower,
1264 structured_key_lower: other_structured_key_lower,
1265 stats: other_stats,
1266 ts_rewrite: other_ts_rewrite,
1267 diffs_sum: other_diffs_sum,
1268 format: other_format,
1269 schema_id: other_schema_id,
1270 deprecated_schema_id: other_deprecated_schema_id,
1271 } = other;
1272 (
1273 self_key,
1274 self_meta,
1275 self_encoded_size_bytes,
1276 self_key_lower,
1277 self_structured_key_lower,
1278 self_stats,
1279 self_ts_rewrite.as_ref().map(|x| x.elements()),
1280 self_diffs_sum,
1281 self_format,
1282 self_schema_id,
1283 self_deprecated_schema_id,
1284 )
1285 .cmp(&(
1286 other_key,
1287 other_meta,
1288 other_encoded_size_bytes,
1289 other_key_lower,
1290 other_structured_key_lower,
1291 other_stats,
1292 other_ts_rewrite.as_ref().map(|x| x.elements()),
1293 other_diffs_sum,
1294 other_format,
1295 other_schema_id,
1296 other_deprecated_schema_id,
1297 ))
1298 }
1299}
1300
1301#[derive(Arbitrary, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
1303pub struct HollowRollup {
1304 pub key: PartialRollupKey,
1306 pub encoded_size_bytes: Option<usize>,
1308}
1309
1310#[derive(Debug)]
1312pub enum HollowBlobRef<'a, T> {
1313 Batch(&'a HollowBatch<T>),
1314 Rollup(&'a HollowRollup),
1315}
1316
1317#[derive(
1319 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Arbitrary, Serialize
1320)]
1321pub struct ActiveRollup {
1322 pub seqno: SeqNo,
1323 pub start_ms: u64,
1324}
1325
1326#[derive(
1328 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Arbitrary, Serialize
1329)]
1330pub struct ActiveGc {
1331 pub seqno: SeqNo,
1332 pub start_ms: u64,
1333}
1334
1335#[derive(Debug)]
1340#[cfg_attr(any(test, debug_assertions), derive(PartialEq))]
1341pub struct NoOpStateTransition<T>(pub T);
1342
1343#[derive(Debug, Clone)]
1345#[cfg_attr(any(test, debug_assertions), derive(PartialEq))]
1346pub struct StateCollections<T> {
1347 pub(crate) version: Version,
1351
1352 pub(crate) last_gc_req: SeqNo,
1355
1356 pub(crate) rollups: BTreeMap<SeqNo, HollowRollup>,
1358
1359 pub(crate) active_rollup: Option<ActiveRollup>,
1361 pub(crate) active_gc: Option<ActiveGc>,
1363
1364 pub(crate) leased_readers: BTreeMap<LeasedReaderId, LeasedReaderState<T>>,
1365 pub(crate) critical_readers: BTreeMap<CriticalReaderId, CriticalReaderState<T>>,
1366 pub(crate) writers: BTreeMap<WriterId, WriterState<T>>,
1367 pub(crate) schemas: BTreeMap<SchemaId, EncodedSchemas>,
1368
1369 pub(crate) trace: Trace<T>,
1374}
1375
1376#[derive(Debug, Clone, Serialize, PartialEq)]
1392pub struct EncodedSchemas {
1393 pub key: Bytes,
1395 pub key_data_type: Bytes,
1398 pub val: Bytes,
1400 pub val_data_type: Bytes,
1403}
1404
1405impl EncodedSchemas {
1406 pub(crate) fn decode_data_type(buf: &[u8]) -> DataType {
1407 let proto = prost::Message::decode(buf).expect("valid ProtoDataType");
1408 DataType::from_proto(proto).expect("valid DataType")
1409 }
1410}
1411
1412#[derive(Debug)]
1413#[cfg_attr(test, derive(PartialEq))]
1414pub enum CompareAndAppendBreak<T> {
1415 AlreadyCommitted,
1416 Upper {
1417 shard_upper: Antichain<T>,
1418 writer_upper: Antichain<T>,
1419 },
1420 InvalidUsage(InvalidUsage<T>),
1421 InlineBackpressure,
1422}
1423
1424#[derive(Debug)]
1425#[cfg_attr(test, derive(PartialEq))]
1426pub enum SnapshotErr<T> {
1427 AsOfNotYetAvailable(SeqNo, Upper<T>),
1428 AsOfHistoricalDistinctionsLost(Since<T>),
1429}
1430
1431impl<T> StateCollections<T>
1432where
1433 T: Timestamp + Lattice + Codec64,
1434{
1435 pub fn add_rollup(
1436 &mut self,
1437 add_rollup: (SeqNo, &HollowRollup),
1438 ) -> ControlFlow<NoOpStateTransition<bool>, bool> {
1439 let (rollup_seqno, rollup) = add_rollup;
1440 let applied = match self.rollups.get(&rollup_seqno) {
1441 Some(x) => x.key == rollup.key,
1442 None => {
1443 if let Some(min_kept) = self.rollups.keys().next() {
1464 if rollup_seqno < *min_kept {
1465 return Continue(false);
1466 }
1467 }
1468 self.active_rollup = None;
1469 self.rollups.insert(rollup_seqno, rollup.to_owned());
1470 true
1471 }
1472 };
1473 Continue(applied)
1477 }
1478
1479 pub fn remove_rollups(
1480 &mut self,
1481 remove_rollups: &[(SeqNo, PartialRollupKey)],
1482 ) -> ControlFlow<NoOpStateTransition<Vec<SeqNo>>, Vec<SeqNo>> {
1483 if self.is_tombstone() {
1484 return Break(NoOpStateTransition(vec![]));
1485 }
1486
1487 let active_gc_was_set = self.active_gc.take().is_some();
1490
1491 if remove_rollups.is_empty() {
1492 return if active_gc_was_set {
1493 Continue(vec![])
1494 } else {
1495 Break(NoOpStateTransition(vec![]))
1496 };
1497 }
1498
1499 let mut removed = vec![];
1500 for (seqno, key) in remove_rollups {
1501 let removed_key = self.rollups.remove(seqno);
1502 mz_ore::soft_assert_no_log!(
1503 removed_key.as_ref().map_or(true, |x| &x.key == key),
1504 "rollup at {} to be removed has key {:?} in state, but GC asked to remove {}",
1505 seqno,
1506 removed_key,
1507 key
1508 );
1509
1510 if removed_key.is_some() {
1511 removed.push(*seqno);
1512 }
1513 }
1514
1515 Continue(removed)
1516 }
1517
1518 pub fn register_leased_reader(
1519 &mut self,
1520 hostname: &str,
1521 reader_id: &LeasedReaderId,
1522 purpose: &str,
1523 seqno: SeqNo,
1524 lease_duration: Duration,
1525 heartbeat_timestamp_ms: u64,
1526 use_critical_since: bool,
1527 ) -> ControlFlow<
1528 NoOpStateTransition<(LeasedReaderState<T>, SeqNo)>,
1529 (LeasedReaderState<T>, SeqNo),
1530 > {
1531 let since = if use_critical_since {
1532 self.critical_since()
1533 .unwrap_or_else(|| self.trace.since().clone())
1534 } else {
1535 self.trace.since().clone()
1536 };
1537 let reader_state = LeasedReaderState {
1538 debug: HandleDebugState {
1539 hostname: hostname.to_owned(),
1540 purpose: purpose.to_owned(),
1541 },
1542 seqno,
1543 since,
1544 last_heartbeat_timestamp_ms: heartbeat_timestamp_ms,
1545 lease_duration_ms: u64::try_from(lease_duration.as_millis())
1546 .expect("lease duration as millis should fit within u64"),
1547 };
1548
1549 if self.is_tombstone() {
1554 return Break(NoOpStateTransition((reader_state, self.seqno_since(seqno))));
1555 }
1556
1557 self.leased_readers
1559 .insert(reader_id.clone(), reader_state.clone());
1560 Continue((reader_state, self.seqno_since(seqno)))
1561 }
1562
1563 pub fn register_critical_reader(
1564 &mut self,
1565 hostname: &str,
1566 reader_id: &CriticalReaderId,
1567 opaque: Opaque,
1568 purpose: &str,
1569 ) -> ControlFlow<NoOpStateTransition<CriticalReaderState<T>>, CriticalReaderState<T>> {
1570 let state = CriticalReaderState {
1571 debug: HandleDebugState {
1572 hostname: hostname.to_owned(),
1573 purpose: purpose.to_owned(),
1574 },
1575 since: self.trace.since().clone(),
1576 opaque,
1577 };
1578
1579 if self.is_tombstone() {
1584 return Break(NoOpStateTransition(state));
1585 }
1586
1587 let state = match self.critical_readers.get_mut(reader_id) {
1588 Some(existing_state) => {
1589 existing_state.debug = state.debug;
1590 existing_state.clone()
1591 }
1592 None => {
1593 self.critical_readers
1594 .insert(reader_id.clone(), state.clone());
1595 state
1596 }
1597 };
1598 Continue(state)
1599 }
1600
1601 pub fn register_schema<K: Codec, V: Codec>(
1602 &mut self,
1603 key_schema: &K::Schema,
1604 val_schema: &V::Schema,
1605 ) -> ControlFlow<NoOpStateTransition<Option<SchemaId>>, Option<SchemaId>> {
1606 fn encode_data_type(data_type: &DataType) -> Bytes {
1607 let proto = data_type.into_proto();
1608 prost::Message::encode_to_vec(&proto).into()
1609 }
1610
1611 let existing_id = self.schemas.iter().rev().find(|(_, x)| {
1623 K::decode_schema(&x.key) == *key_schema && V::decode_schema(&x.val) == *val_schema
1624 });
1625 match existing_id {
1626 Some((schema_id, _)) => {
1627 Break(NoOpStateTransition(Some(*schema_id)))
1632 }
1633 None if self.is_tombstone() => {
1634 Break(NoOpStateTransition(None))
1636 }
1637 None if self.schemas.is_empty() => {
1638 let id = SchemaId(self.schemas.len());
1642 let key_data_type = mz_persist_types::columnar::data_type::<K>(key_schema)
1643 .expect("valid key schema");
1644 let val_data_type = mz_persist_types::columnar::data_type::<V>(val_schema)
1645 .expect("valid val schema");
1646 let prev = self.schemas.insert(
1647 id,
1648 EncodedSchemas {
1649 key: K::encode_schema(key_schema),
1650 key_data_type: encode_data_type(&key_data_type),
1651 val: V::encode_schema(val_schema),
1652 val_data_type: encode_data_type(&val_data_type),
1653 },
1654 );
1655 assert_eq!(prev, None);
1656 Continue(Some(id))
1657 }
1658 None => {
1659 info!(
1660 "register_schemas got {:?} expected {:?}",
1661 key_schema,
1662 self.schemas
1663 .iter()
1664 .map(|(id, x)| (id, K::decode_schema(&x.key)))
1665 .collect::<Vec<_>>()
1666 );
1667 Break(NoOpStateTransition(None))
1670 }
1671 }
1672 }
1673
1674 pub fn compare_and_evolve_schema<K: Codec, V: Codec>(
1675 &mut self,
1676 expected: SchemaId,
1677 key_schema: &K::Schema,
1678 val_schema: &V::Schema,
1679 ) -> ControlFlow<NoOpStateTransition<CaESchema<K, V>>, CaESchema<K, V>> {
1680 fn data_type<T>(schema: &impl Schema<T>) -> DataType {
1681 let array = Schema::encoder(schema).expect("valid schema").finish();
1685 Array::data_type(&array).clone()
1686 }
1687
1688 let (current_id, current) = self
1689 .schemas
1690 .last_key_value()
1691 .expect("all shards have a schema");
1692
1693 let current_key = K::decode_schema(¤t.key);
1694 let current_key_dt = EncodedSchemas::decode_data_type(¤t.key_data_type);
1695 let current_val = V::decode_schema(¤t.val);
1696 let current_val_dt = EncodedSchemas::decode_data_type(¤t.val_data_type);
1697
1698 let key_dt = data_type(key_schema);
1699 let val_dt = data_type(val_schema);
1700
1701 if current_key == *key_schema
1711 && current_key_dt == key_dt
1712 && current_val == *val_schema
1713 && current_val_dt == val_dt
1714 {
1715 return Break(NoOpStateTransition(CaESchema::Ok(*current_id)));
1716 }
1717
1718 if *current_id != expected {
1719 return Break(NoOpStateTransition(CaESchema::ExpectedMismatch {
1720 schema_id: *current_id,
1721 key: current_key,
1722 val: current_val,
1723 }));
1724 }
1725
1726 let key_fn = backward_compatible(¤t_key_dt, &key_dt);
1727 let val_fn = backward_compatible(¤t_val_dt, &val_dt);
1728 let (Some(key_fn), Some(val_fn)) = (key_fn, val_fn) else {
1729 return Break(NoOpStateTransition(CaESchema::Incompatible));
1730 };
1731 if key_fn.contains_drop() || val_fn.contains_drop() {
1735 return Break(NoOpStateTransition(CaESchema::Incompatible));
1736 }
1737
1738 let id = SchemaId(self.schemas.len());
1742 self.schemas.insert(
1743 id,
1744 EncodedSchemas {
1745 key: K::encode_schema(key_schema),
1746 key_data_type: prost::Message::encode_to_vec(&key_dt.into_proto()).into(),
1747 val: V::encode_schema(val_schema),
1748 val_data_type: prost::Message::encode_to_vec(&val_dt.into_proto()).into(),
1749 },
1750 );
1751 Continue(CaESchema::Ok(id))
1752 }
1753
1754 pub fn compare_and_append(
1755 &mut self,
1756 batch: &HollowBatch<T>,
1757 writer_id: &WriterId,
1758 heartbeat_timestamp_ms: u64,
1759 lease_duration_ms: u64,
1760 idempotency_token: &IdempotencyToken,
1761 debug_info: &HandleDebugState,
1762 inline_writes_total_max_bytes: usize,
1763 claim_compaction_percent: usize,
1764 claim_compaction_min_version: Option<&Version>,
1765 ) -> ControlFlow<CompareAndAppendBreak<T>, Vec<FueledMergeReq<T>>> {
1766 if self.is_tombstone() {
1771 assert_eq!(self.trace.upper(), &Antichain::new());
1772 return Break(CompareAndAppendBreak::Upper {
1773 shard_upper: Antichain::new(),
1774 writer_upper: Antichain::new(),
1779 });
1780 }
1781
1782 let writer_state = self
1783 .writers
1784 .entry(writer_id.clone())
1785 .or_insert_with(|| WriterState {
1786 last_heartbeat_timestamp_ms: heartbeat_timestamp_ms,
1787 lease_duration_ms,
1788 most_recent_write_token: IdempotencyToken::SENTINEL,
1789 most_recent_write_upper: Antichain::from_elem(T::minimum()),
1790 debug: debug_info.clone(),
1791 });
1792
1793 if PartialOrder::less_than(batch.desc.upper(), batch.desc.lower()) {
1794 return Break(CompareAndAppendBreak::InvalidUsage(
1795 InvalidUsage::InvalidBounds {
1796 lower: batch.desc.lower().clone(),
1797 upper: batch.desc.upper().clone(),
1798 },
1799 ));
1800 }
1801
1802 if batch.desc.upper() == batch.desc.lower() && !batch.is_empty() {
1805 return Break(CompareAndAppendBreak::InvalidUsage(
1806 InvalidUsage::InvalidEmptyTimeInterval {
1807 lower: batch.desc.lower().clone(),
1808 upper: batch.desc.upper().clone(),
1809 keys: batch
1810 .parts
1811 .iter()
1812 .map(|x| x.printable_name().to_owned())
1813 .collect(),
1814 },
1815 ));
1816 }
1817
1818 if idempotency_token == &writer_state.most_recent_write_token {
1819 assert_eq!(batch.desc.upper(), &writer_state.most_recent_write_upper);
1824 assert!(
1825 PartialOrder::less_equal(batch.desc.upper(), self.trace.upper()),
1826 "{:?} vs {:?}",
1827 batch.desc.upper(),
1828 self.trace.upper()
1829 );
1830 return Break(CompareAndAppendBreak::AlreadyCommitted);
1831 }
1832
1833 let shard_upper = self.trace.upper();
1834 if shard_upper != batch.desc.lower() {
1835 return Break(CompareAndAppendBreak::Upper {
1836 shard_upper: shard_upper.clone(),
1837 writer_upper: writer_state.most_recent_write_upper.clone(),
1838 });
1839 }
1840
1841 let new_inline_bytes = batch.inline_bytes();
1842 if new_inline_bytes > 0 {
1843 let mut existing_inline_bytes = 0;
1844 self.trace
1845 .map_batches(|x| existing_inline_bytes += x.inline_bytes());
1846 if existing_inline_bytes + new_inline_bytes >= inline_writes_total_max_bytes {
1850 return Break(CompareAndAppendBreak::InlineBackpressure);
1851 }
1852 }
1853
1854 let mut merge_reqs = if batch.desc.upper() != batch.desc.lower() {
1855 self.trace.push_batch(batch.clone())
1856 } else {
1857 Vec::new()
1858 };
1859
1860 let all_empty_reqs = merge_reqs
1863 .iter()
1864 .all(|req| req.inputs.iter().all(|b| b.batch.is_empty()));
1865 if all_empty_reqs && !batch.is_empty() {
1866 let mut reqs_to_take = claim_compaction_percent / 100;
1867 if (usize::cast_from(idempotency_token.hashed()) % 100)
1868 < (claim_compaction_percent % 100)
1869 {
1870 reqs_to_take += 1;
1871 }
1872 let threshold_ms = heartbeat_timestamp_ms.saturating_sub(lease_duration_ms);
1873 let min_writer = claim_compaction_min_version.map(WriterKey::for_version);
1874 merge_reqs.extend(
1875 self.trace
1878 .fueled_merge_reqs_before_ms(threshold_ms, min_writer)
1879 .take(reqs_to_take),
1880 )
1881 }
1882
1883 for req in &merge_reqs {
1884 self.trace.claim_compaction(
1885 req.id,
1886 ActiveCompaction {
1887 start_ms: heartbeat_timestamp_ms,
1888 },
1889 )
1890 }
1891
1892 mz_ore::soft_assert_eq_no_log!(self.trace.upper(), batch.desc.upper());
1893 writer_state.most_recent_write_token = idempotency_token.clone();
1894 assert!(
1896 PartialOrder::less_equal(&writer_state.most_recent_write_upper, batch.desc.upper()),
1897 "{:?} vs {:?}",
1898 writer_state.most_recent_write_upper,
1899 batch.desc.upper()
1900 );
1901 writer_state
1902 .most_recent_write_upper
1903 .clone_from(batch.desc.upper());
1904
1905 writer_state.last_heartbeat_timestamp_ms = std::cmp::max(
1907 heartbeat_timestamp_ms,
1908 writer_state.last_heartbeat_timestamp_ms,
1909 );
1910
1911 Continue(merge_reqs)
1912 }
1913
1914 pub fn apply_merge_res<D: Codec64 + Monoid + PartialEq>(
1915 &mut self,
1916 res: &FueledMergeRes<T>,
1917 metrics: &ColumnarMetrics,
1918 ) -> ControlFlow<NoOpStateTransition<ApplyMergeResult>, ApplyMergeResult> {
1919 if self.is_tombstone() {
1924 return Break(NoOpStateTransition(ApplyMergeResult::NotAppliedNoMatch));
1925 }
1926
1927 let apply_merge_result = self.trace.apply_merge_res_checked::<D>(res, metrics);
1928 Continue(apply_merge_result)
1929 }
1930
1931 pub fn spine_exert(
1932 &mut self,
1933 fuel: usize,
1934 ) -> ControlFlow<NoOpStateTransition<Vec<FueledMergeReq<T>>>, Vec<FueledMergeReq<T>>> {
1935 let (merge_reqs, did_work) = self.trace.exert(fuel);
1936 if did_work {
1937 Continue(merge_reqs)
1938 } else {
1939 assert!(merge_reqs.is_empty());
1940 Break(NoOpStateTransition(Vec::new()))
1943 }
1944 }
1945
1946 pub fn downgrade_since(
1947 &mut self,
1948 reader_id: &LeasedReaderId,
1949 seqno: SeqNo,
1950 outstanding_seqno: SeqNo,
1951 new_since: &Antichain<T>,
1952 heartbeat_timestamp_ms: u64,
1953 ) -> ControlFlow<NoOpStateTransition<Since<T>>, Since<T>> {
1954 if self.is_tombstone() {
1959 return Break(NoOpStateTransition(Since(Antichain::new())));
1960 }
1961
1962 let Some(reader_state) = self.leased_reader(reader_id) else {
1965 tracing::warn!(
1966 "Leased reader {reader_id} was expired due to inactivity. Did the machine go to sleep?",
1967 );
1968 return Break(NoOpStateTransition(Since(Antichain::new())));
1969 };
1970
1971 reader_state.last_heartbeat_timestamp_ms = std::cmp::max(
1974 heartbeat_timestamp_ms,
1975 reader_state.last_heartbeat_timestamp_ms,
1976 );
1977
1978 let seqno = {
1979 assert!(
1980 outstanding_seqno >= reader_state.seqno,
1981 "SeqNos cannot go backward; however, oldest leased SeqNo ({:?}) \
1982 is behind current reader_state ({:?})",
1983 outstanding_seqno,
1984 reader_state.seqno,
1985 );
1986 std::cmp::min(outstanding_seqno, seqno)
1987 };
1988
1989 reader_state.seqno = seqno;
1990
1991 let reader_current_since = if PartialOrder::less_than(&reader_state.since, new_since) {
1992 reader_state.since.clone_from(new_since);
1993 self.update_since();
1994 new_since.clone()
1995 } else {
1996 reader_state.since.clone()
1999 };
2000
2001 Continue(Since(reader_current_since))
2002 }
2003
2004 pub fn compare_and_downgrade_since(
2005 &mut self,
2006 reader_id: &CriticalReaderId,
2007 expected_opaque: &Opaque,
2008 (new_opaque, new_since): (&Opaque, &Antichain<T>),
2009 ) -> ControlFlow<
2010 NoOpStateTransition<Result<Since<T>, (Opaque, Since<T>)>>,
2011 Result<Since<T>, (Opaque, Since<T>)>,
2012 > {
2013 if self.is_tombstone() {
2018 return Break(NoOpStateTransition(Ok(Since(Antichain::new()))));
2022 }
2023
2024 let reader_state = self.critical_reader(reader_id);
2025
2026 if reader_state.opaque != *expected_opaque {
2027 return Continue(Err((
2030 reader_state.opaque.clone(),
2031 Since(reader_state.since.clone()),
2032 )));
2033 }
2034
2035 reader_state.opaque = new_opaque.clone();
2036 if PartialOrder::less_equal(&reader_state.since, new_since) {
2037 reader_state.since.clone_from(new_since);
2038 self.update_since();
2039 Continue(Ok(Since(new_since.clone())))
2040 } else {
2041 Continue(Ok(Since(reader_state.since.clone())))
2045 }
2046 }
2047
2048 pub fn expire_leased_reader(
2049 &mut self,
2050 reader_id: &LeasedReaderId,
2051 ) -> ControlFlow<NoOpStateTransition<bool>, bool> {
2052 if self.is_tombstone() {
2057 return Break(NoOpStateTransition(false));
2058 }
2059
2060 let existed = self.leased_readers.remove(reader_id).is_some();
2061 if existed {
2062 }
2076 Continue(existed)
2079 }
2080
2081 pub fn expire_critical_reader(
2082 &mut self,
2083 reader_id: &CriticalReaderId,
2084 ) -> ControlFlow<NoOpStateTransition<bool>, bool> {
2085 if self.is_tombstone() {
2090 return Break(NoOpStateTransition(false));
2091 }
2092
2093 let existed = self.critical_readers.remove(reader_id).is_some();
2094 if existed {
2095 }
2109 Continue(existed)
2113 }
2114
2115 pub fn expire_writer(
2116 &mut self,
2117 writer_id: &WriterId,
2118 ) -> ControlFlow<NoOpStateTransition<bool>, bool> {
2119 if self.is_tombstone() {
2124 return Break(NoOpStateTransition(false));
2125 }
2126
2127 let existed = self.writers.remove(writer_id).is_some();
2128 Continue(existed)
2132 }
2133
2134 fn leased_reader(&mut self, id: &LeasedReaderId) -> Option<&mut LeasedReaderState<T>> {
2135 self.leased_readers.get_mut(id)
2136 }
2137
2138 fn critical_reader(&mut self, id: &CriticalReaderId) -> &mut CriticalReaderState<T> {
2139 self.critical_readers
2140 .get_mut(id)
2141 .unwrap_or_else(|| {
2142 panic!(
2143 "Unknown CriticalReaderId({}). It was either never registered, or has been manually expired.",
2144 id
2145 )
2146 })
2147 }
2148
2149 fn critical_since(&self) -> Option<Antichain<T>> {
2150 let mut critical_sinces = self.critical_readers.values().map(|r| &r.since);
2151 let mut since = critical_sinces.next().cloned()?;
2152 for s in critical_sinces {
2153 since.meet_assign(s);
2154 }
2155 Some(since)
2156 }
2157
2158 fn update_since(&mut self) {
2159 let mut sinces_iter = self
2160 .leased_readers
2161 .values()
2162 .map(|x| &x.since)
2163 .chain(self.critical_readers.values().map(|x| &x.since));
2164 let mut since = match sinces_iter.next() {
2165 Some(since) => since.clone(),
2166 None => {
2167 return;
2170 }
2171 };
2172 while let Some(s) = sinces_iter.next() {
2173 since.meet_assign(s);
2174 }
2175 self.trace.downgrade_since(&since);
2176 }
2177
2178 fn seqno_since(&self, seqno: SeqNo) -> SeqNo {
2179 let mut seqno_since = seqno;
2180 for cap in self.leased_readers.values() {
2181 seqno_since = std::cmp::min(seqno_since, cap.seqno);
2182 }
2183 seqno_since
2185 }
2186
2187 fn tombstone_batch() -> HollowBatch<T> {
2188 HollowBatch::empty(Description::new(
2189 Antichain::from_elem(T::minimum()),
2190 Antichain::new(),
2191 Antichain::new(),
2192 ))
2193 }
2194
2195 pub(crate) fn is_tombstone(&self) -> bool {
2196 self.trace.upper().is_empty()
2197 && self.trace.since().is_empty()
2198 && self.writers.is_empty()
2199 && self.leased_readers.is_empty()
2200 && self.critical_readers.is_empty()
2201 }
2202
2203 pub(crate) fn is_single_empty_batch(&self) -> bool {
2204 let mut batch_count = 0;
2205 let mut is_empty = true;
2206 self.trace.map_batches(|b| {
2207 batch_count += 1;
2208 is_empty &= b.is_empty()
2209 });
2210 batch_count <= 1 && is_empty
2211 }
2212
2213 pub fn become_tombstone_and_shrink(&mut self) -> ControlFlow<NoOpStateTransition<()>, ()> {
2214 assert_eq!(self.trace.upper(), &Antichain::new());
2215 assert_eq!(self.trace.since(), &Antichain::new());
2216
2217 let was_tombstone = self.is_tombstone();
2220
2221 self.writers.clear();
2223 self.leased_readers.clear();
2224 self.critical_readers.clear();
2225
2226 mz_ore::soft_assert_no_log!(self.is_tombstone());
2227
2228 let mut to_replace = None;
2237 let mut batch_count = 0;
2238 self.trace.map_batches(|b| {
2239 batch_count += 1;
2240 if !b.is_empty() && to_replace.is_none() {
2241 to_replace = Some(b.desc.clone());
2242 }
2243 });
2244 if let Some(desc) = to_replace {
2245 let result = self.trace.apply_tombstone_merge(&desc);
2249 assert!(
2250 result.matched(),
2251 "merge with a matching desc should always match"
2252 );
2253 Continue(())
2254 } else if batch_count > 1 {
2255 let mut new_trace = Trace::default();
2260 new_trace.downgrade_since(&Antichain::new());
2261 let merge_reqs = new_trace.push_batch(Self::tombstone_batch());
2262 assert_eq!(merge_reqs, Vec::new());
2263 self.trace = new_trace;
2264 Continue(())
2265 } else if !was_tombstone {
2266 Continue(())
2269 } else {
2270 Break(NoOpStateTransition(()))
2273 }
2274 }
2275}
2276
2277#[derive(Debug)]
2279#[cfg_attr(any(test, debug_assertions), derive(Clone, PartialEq))]
2280pub struct State<T> {
2281 pub(crate) shard_id: ShardId,
2282
2283 pub(crate) seqno: SeqNo,
2284 pub(crate) walltime_ms: u64,
2287 pub(crate) hostname: String,
2290 pub(crate) collections: StateCollections<T>,
2291}
2292
2293pub struct TypedState<K, V, T, D> {
2296 pub(crate) state: State<T>,
2297
2298 pub(crate) _phantom: PhantomData<fn() -> (K, V, D)>,
2306}
2307
2308impl<K, V, T: Clone, D> TypedState<K, V, T, D> {
2309 #[cfg(any(test, debug_assertions))]
2310 pub(crate) fn clone(&self, hostname: String) -> Self {
2311 TypedState {
2312 state: State {
2313 shard_id: self.shard_id.clone(),
2314 seqno: self.seqno.clone(),
2315 walltime_ms: self.walltime_ms,
2316 hostname,
2317 collections: self.collections.clone(),
2318 },
2319 _phantom: PhantomData,
2320 }
2321 }
2322
2323 pub(crate) fn clone_for_rollup(&self) -> Self {
2324 TypedState {
2325 state: State {
2326 shard_id: self.shard_id.clone(),
2327 seqno: self.seqno.clone(),
2328 walltime_ms: self.walltime_ms,
2329 hostname: self.hostname.clone(),
2330 collections: self.collections.clone(),
2331 },
2332 _phantom: PhantomData,
2333 }
2334 }
2335}
2336
2337impl<K, V, T: Debug, D> Debug for TypedState<K, V, T, D> {
2338 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2339 let TypedState { state, _phantom } = self;
2342 f.debug_struct("TypedState").field("state", state).finish()
2343 }
2344}
2345
2346#[cfg(any(test, debug_assertions))]
2348impl<K, V, T: PartialEq, D> PartialEq for TypedState<K, V, T, D> {
2349 fn eq(&self, other: &Self) -> bool {
2350 let TypedState {
2353 state: self_state,
2354 _phantom,
2355 } = self;
2356 let TypedState {
2357 state: other_state,
2358 _phantom,
2359 } = other;
2360 self_state == other_state
2361 }
2362}
2363
2364impl<K, V, T, D> Deref for TypedState<K, V, T, D> {
2365 type Target = State<T>;
2366
2367 fn deref(&self) -> &Self::Target {
2368 &self.state
2369 }
2370}
2371
2372impl<K, V, T, D> DerefMut for TypedState<K, V, T, D> {
2373 fn deref_mut(&mut self) -> &mut Self::Target {
2374 &mut self.state
2375 }
2376}
2377
2378impl<K, V, T, D> TypedState<K, V, T, D>
2379where
2380 K: Codec,
2381 V: Codec,
2382 T: Timestamp + Lattice + Codec64,
2383 D: Codec64,
2384{
2385 pub fn new(
2386 applier_version: Version,
2387 shard_id: ShardId,
2388 hostname: String,
2389 walltime_ms: u64,
2390 ) -> Self {
2391 let state = State {
2392 shard_id,
2393 seqno: SeqNo::minimum(),
2394 walltime_ms,
2395 hostname,
2396 collections: StateCollections {
2397 version: applier_version,
2398 last_gc_req: SeqNo::minimum(),
2399 rollups: BTreeMap::new(),
2400 active_rollup: None,
2401 active_gc: None,
2402 leased_readers: BTreeMap::new(),
2403 critical_readers: BTreeMap::new(),
2404 writers: BTreeMap::new(),
2405 schemas: BTreeMap::new(),
2406 trace: Trace::default(),
2407 },
2408 };
2409 TypedState {
2410 state,
2411 _phantom: PhantomData,
2412 }
2413 }
2414
2415 pub fn clone_apply<R, E, WorkFn>(
2416 &self,
2417 cfg: &PersistConfig,
2418 work_fn: &mut WorkFn,
2419 ) -> ControlFlow<E, (R, Self)>
2420 where
2421 WorkFn: FnMut(SeqNo, &PersistConfig, &mut StateCollections<T>) -> ControlFlow<E, R>,
2422 {
2423 let mut new_state = State {
2425 shard_id: self.shard_id,
2426 seqno: self.seqno.next(),
2427 walltime_ms: (cfg.now)(),
2428 hostname: cfg.hostname.clone(),
2429 collections: self.collections.clone(),
2430 };
2431
2432 if new_state.walltime_ms <= self.walltime_ms {
2435 new_state.walltime_ms = self.walltime_ms + 1;
2436 }
2437
2438 let work_ret = work_fn(new_state.seqno, cfg, &mut new_state.collections)?;
2439 let new_state = TypedState {
2440 state: new_state,
2441 _phantom: PhantomData,
2442 };
2443 Continue((work_ret, new_state))
2444 }
2445}
2446
2447#[derive(Copy, Clone, Debug)]
2448pub struct GcConfig {
2449 pub use_active_gc: bool,
2450 pub fallback_threshold_ms: u64,
2451 pub min_versions: usize,
2452 pub max_versions: usize,
2453}
2454
2455impl<T> State<T>
2456where
2457 T: Timestamp + Lattice + Codec64,
2458{
2459 pub fn shard_id(&self) -> ShardId {
2460 self.shard_id
2461 }
2462
2463 pub fn seqno(&self) -> SeqNo {
2464 self.seqno
2465 }
2466
2467 pub fn since(&self) -> &Antichain<T> {
2468 self.collections.trace.since()
2469 }
2470
2471 pub fn upper(&self) -> &Antichain<T> {
2472 self.collections.trace.upper()
2473 }
2474
2475 pub fn spine_batch_count(&self) -> usize {
2476 self.collections.trace.num_spine_batches()
2477 }
2478
2479 pub fn size_metrics(&self) -> StateSizeMetrics {
2480 let mut ret = StateSizeMetrics::default();
2481 self.blobs().for_each(|x| match x {
2482 HollowBlobRef::Batch(x) => {
2483 ret.hollow_batch_count += 1;
2484 ret.batch_part_count += x.part_count();
2485 ret.num_updates += x.len;
2486
2487 let batch_size = x.encoded_size_bytes();
2488 for x in x.parts.iter() {
2489 if x.is_inline() {
2490 ret.inline_part_count += 1;
2491 }
2492 }
2493 ret.largest_batch_bytes = std::cmp::max(ret.largest_batch_bytes, batch_size);
2494 ret.state_batches_bytes += batch_size;
2495 }
2496 HollowBlobRef::Rollup(x) => {
2497 ret.state_rollup_count += 1;
2498 ret.state_rollups_bytes += x.encoded_size_bytes.unwrap_or_default()
2499 }
2500 });
2501 ret
2502 }
2503
2504 pub fn latest_rollup(&self) -> (&SeqNo, &HollowRollup) {
2505 self.collections
2508 .rollups
2509 .iter()
2510 .rev()
2511 .next()
2512 .expect("State should have at least one rollup if seqno > minimum")
2513 }
2514
2515 pub(crate) fn seqno_since(&self) -> SeqNo {
2516 self.collections.seqno_since(self.seqno)
2517 }
2518
2519 pub fn maybe_gc(&mut self, is_write: bool, now: u64, cfg: GcConfig) -> Option<GcReq> {
2531 let GcConfig {
2532 use_active_gc,
2533 fallback_threshold_ms,
2534 min_versions,
2535 max_versions,
2536 } = cfg;
2537 let gc_threshold = if use_active_gc {
2541 u64::cast_from(min_versions)
2542 } else {
2543 std::cmp::max(
2544 1,
2545 u64::cast_from(self.seqno.0.next_power_of_two().trailing_zeros()),
2546 )
2547 };
2548 let new_seqno_since = self.seqno_since();
2549 let gc_until_seqno = new_seqno_since.min(SeqNo(
2552 self.collections
2553 .last_gc_req
2554 .0
2555 .saturating_add(u64::cast_from(max_versions)),
2556 ));
2557 let should_gc = new_seqno_since
2558 .0
2559 .saturating_sub(self.collections.last_gc_req.0)
2560 >= gc_threshold;
2561
2562 let should_gc = if use_active_gc && !should_gc {
2565 match self.collections.active_gc {
2566 Some(active_gc) => now.saturating_sub(active_gc.start_ms) > fallback_threshold_ms,
2567 None => false,
2568 }
2569 } else {
2570 should_gc
2571 };
2572 let should_gc = should_gc && (is_write || self.collections.writers.is_empty());
2575 let tombstone_needs_gc = self.collections.is_tombstone();
2580 let should_gc = should_gc || tombstone_needs_gc;
2581 let should_gc = if use_active_gc {
2582 should_gc
2586 && match self.collections.active_gc {
2587 Some(active) => now.saturating_sub(active.start_ms) > fallback_threshold_ms,
2588 None => true,
2589 }
2590 } else {
2591 should_gc
2592 };
2593 if should_gc {
2594 self.collections.last_gc_req = gc_until_seqno;
2595 Some(GcReq {
2596 shard_id: self.shard_id,
2597 new_seqno_since: gc_until_seqno,
2598 })
2599 } else {
2600 None
2601 }
2602 }
2603
2604 pub fn seqnos_held(&self) -> usize {
2606 usize::cast_from(self.seqno.0.saturating_sub(self.seqno_since().0))
2607 }
2608
2609 pub fn expire_at(&mut self, walltime_ms: EpochMillis) -> ExpiryMetrics {
2611 let mut metrics = ExpiryMetrics::default();
2612 let shard_id = self.shard_id();
2613 self.collections.leased_readers.retain(|id, state| {
2614 let retain = state.last_heartbeat_timestamp_ms + state.lease_duration_ms >= walltime_ms;
2615 if !retain {
2616 info!(
2617 "Force expiring reader {id} ({}) of shard {shard_id} due to inactivity",
2618 state.debug.purpose
2619 );
2620 metrics.readers_expired += 1;
2621 }
2622 retain
2623 });
2624 self.collections.writers.retain(|id, state| {
2626 let retain =
2627 (state.last_heartbeat_timestamp_ms + state.lease_duration_ms) >= walltime_ms;
2628 if !retain {
2629 info!(
2630 "Force expiring writer {id} ({}) of shard {shard_id} due to inactivity",
2631 state.debug.purpose
2632 );
2633 metrics.writers_expired += 1;
2634 }
2635 retain
2636 });
2637 metrics
2638 }
2639
2640 pub fn snapshot(&self, as_of: &Antichain<T>) -> Result<Vec<HollowBatch<T>>, SnapshotErr<T>> {
2644 if PartialOrder::less_than(as_of, self.collections.trace.since()) {
2645 return Err(SnapshotErr::AsOfHistoricalDistinctionsLost(Since(
2646 self.collections.trace.since().clone(),
2647 )));
2648 }
2649 let upper = self.collections.trace.upper();
2650 if PartialOrder::less_equal(upper, as_of) {
2651 return Err(SnapshotErr::AsOfNotYetAvailable(
2652 self.seqno,
2653 Upper(upper.clone()),
2654 ));
2655 }
2656
2657 let batches = self
2658 .collections
2659 .trace
2660 .batches()
2661 .filter(|b| !PartialOrder::less_than(as_of, b.desc.lower()))
2662 .cloned()
2663 .collect();
2664 Ok(batches)
2665 }
2666
2667 pub fn verify_listen(&self, as_of: &Antichain<T>) -> Result<(), Since<T>> {
2669 if PartialOrder::less_than(as_of, self.collections.trace.since()) {
2670 return Err(Since(self.collections.trace.since().clone()));
2671 }
2672 Ok(())
2673 }
2674
2675 pub fn next_listen_batch(&self, frontier: &Antichain<T>) -> Result<HollowBatch<T>, SeqNo> {
2676 self.collections
2679 .trace
2680 .batches()
2681 .find(|b| {
2682 PartialOrder::less_equal(b.desc.lower(), frontier)
2683 && PartialOrder::less_than(frontier, b.desc.upper())
2684 })
2685 .cloned()
2686 .ok_or(self.seqno)
2687 }
2688
2689 pub fn active_rollup(&self) -> Option<ActiveRollup> {
2690 self.collections.active_rollup
2691 }
2692
2693 pub fn need_rollup(
2694 &self,
2695 threshold: usize,
2696 use_active_rollup: bool,
2697 fallback_threshold_ms: u64,
2698 now: u64,
2699 ) -> Option<SeqNo> {
2700 let (latest_rollup_seqno, _) = self.latest_rollup();
2701
2702 if self.collections.is_tombstone() && latest_rollup_seqno.next() < self.seqno {
2708 return Some(self.seqno);
2709 }
2710
2711 let seqnos_since_last_rollup = self.seqno.0.saturating_sub(latest_rollup_seqno.0);
2712
2713 if use_active_rollup {
2714 if seqnos_since_last_rollup > u64::cast_from(threshold) {
2720 match self.active_rollup() {
2721 Some(active_rollup) => {
2722 if now.saturating_sub(active_rollup.start_ms) > fallback_threshold_ms {
2723 return Some(self.seqno);
2724 }
2725 }
2726 None => {
2727 return Some(self.seqno);
2728 }
2729 }
2730 }
2731 } else {
2732 if seqnos_since_last_rollup > 0
2736 && seqnos_since_last_rollup % u64::cast_from(threshold) == 0
2737 {
2738 return Some(self.seqno);
2739 }
2740
2741 if seqnos_since_last_rollup
2744 > u64::cast_from(
2745 threshold * PersistConfig::DEFAULT_FALLBACK_ROLLUP_THRESHOLD_MULTIPLIER,
2746 )
2747 {
2748 return Some(self.seqno);
2749 }
2750 }
2751
2752 None
2753 }
2754
2755 pub(crate) fn blobs(&self) -> impl Iterator<Item = HollowBlobRef<'_, T>> {
2756 let batches = self.collections.trace.batches().map(HollowBlobRef::Batch);
2757 let rollups = self.collections.rollups.values().map(HollowBlobRef::Rollup);
2758 batches.chain(rollups)
2759 }
2760}
2761
2762fn serialize_part_bytes<S: Serializer>(val: &[u8], s: S) -> Result<S::Ok, S::Error> {
2763 let val = hex::encode(val);
2764 val.serialize(s)
2765}
2766
2767fn serialize_lazy_proto<S: Serializer, T: prost::Message + Default>(
2768 val: &Option<LazyProto<T>>,
2769 s: S,
2770) -> Result<S::Ok, S::Error> {
2771 val.as_ref()
2772 .map(|lazy| hex::encode(&lazy.into_proto()))
2773 .serialize(s)
2774}
2775
2776fn serialize_part_stats<S: Serializer>(
2777 val: &Option<LazyPartStats>,
2778 s: S,
2779) -> Result<S::Ok, S::Error> {
2780 let stats = val.as_ref().and_then(|x| match x.try_decode() {
2786 Ok(stats) => Some(stats.key),
2787 Err(err) => {
2788 tracing::warn!("undecodable part stats, reporting as absent: {err}");
2789 None
2790 }
2791 });
2792 stats.serialize(s)
2793}
2794
2795fn serialize_diffs_sum<S: Serializer>(val: &Option<[u8; 8]>, s: S) -> Result<S::Ok, S::Error> {
2796 let val = val.map(i64::decode);
2798 val.serialize(s)
2799}
2800
2801impl<T: Serialize + Timestamp + Lattice> Serialize for State<T> {
2807 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2808 let State {
2809 shard_id,
2810 seqno,
2811 walltime_ms,
2812 hostname,
2813 collections:
2814 StateCollections {
2815 version: applier_version,
2816 last_gc_req,
2817 rollups,
2818 active_rollup,
2819 active_gc,
2820 leased_readers,
2821 critical_readers,
2822 writers,
2823 schemas,
2824 trace,
2825 },
2826 } = self;
2827 let mut s = s.serialize_struct("State", 13)?;
2828 let () = s.serialize_field("applier_version", &applier_version.to_string())?;
2829 let () = s.serialize_field("shard_id", shard_id)?;
2830 let () = s.serialize_field("seqno", seqno)?;
2831 let () = s.serialize_field("walltime_ms", walltime_ms)?;
2832 let () = s.serialize_field("hostname", hostname)?;
2833 let () = s.serialize_field("last_gc_req", last_gc_req)?;
2834 let () = s.serialize_field("rollups", rollups)?;
2835 let () = s.serialize_field("active_rollup", active_rollup)?;
2836 let () = s.serialize_field("active_gc", active_gc)?;
2837 let () = s.serialize_field("leased_readers", leased_readers)?;
2838 let () = s.serialize_field("critical_readers", critical_readers)?;
2839 let () = s.serialize_field("writers", writers)?;
2840 let () = s.serialize_field("schemas", schemas)?;
2841 let () = s.serialize_field("since", &trace.since().elements())?;
2842 let () = s.serialize_field("upper", &trace.upper().elements())?;
2843 let trace = trace.flatten();
2844 let () = s.serialize_field("batches", &trace.legacy_batches.keys().collect::<Vec<_>>())?;
2845 let () = s.serialize_field("hollow_batches", &trace.hollow_batches)?;
2846 let () = s.serialize_field("spine_batches", &trace.spine_batches)?;
2847 let () = s.serialize_field("merges", &trace.merges)?;
2848 s.end()
2849 }
2850}
2851
2852#[derive(Debug, Default)]
2853pub struct StateSizeMetrics {
2854 pub hollow_batch_count: usize,
2855 pub batch_part_count: usize,
2856 pub num_updates: usize,
2857 pub largest_batch_bytes: usize,
2858 pub state_batches_bytes: usize,
2859 pub state_rollups_bytes: usize,
2860 pub state_rollup_count: usize,
2861 pub inline_part_count: usize,
2862}
2863
2864#[derive(Default)]
2865pub struct ExpiryMetrics {
2866 pub(crate) readers_expired: usize,
2867 pub(crate) writers_expired: usize,
2868}
2869
2870#[derive(Debug, Clone, PartialEq)]
2872pub struct Since<T>(pub Antichain<T>);
2873
2874#[derive(Debug, PartialEq)]
2876pub struct Upper<T>(pub Antichain<T>);
2877
2878#[cfg(test)]
2879pub(crate) mod tests {
2880 use std::ops::Range;
2881 use std::str::FromStr;
2882
2883 use bytes::Bytes;
2884 use mz_build_info::DUMMY_BUILD_INFO;
2885 use mz_dyncfg::ConfigUpdates;
2886 use mz_ore::now::SYSTEM_TIME;
2887 use mz_ore::{assert_none, assert_ok};
2888 use mz_proto::RustType;
2889 use proptest::prelude::*;
2890 use proptest::strategy::ValueTree;
2891
2892 use crate::InvalidUsage::{InvalidBounds, InvalidEmptyTimeInterval};
2893 use crate::cache::PersistClientCache;
2894 use crate::internal::encoding::any_some_lazy_part_stats;
2895 use crate::internal::paths::RollupId;
2896 use crate::internal::trace::tests::any_trace;
2897 use crate::tests::new_test_client_cache;
2898 use crate::{Diagnostics, PersistLocation};
2899
2900 use super::*;
2901
2902 const LEASE_DURATION_MS: u64 = 900 * 1000;
2903 fn debug_state() -> HandleDebugState {
2904 HandleDebugState {
2905 hostname: "debug".to_owned(),
2906 purpose: "finding the bugs".to_owned(),
2907 }
2908 }
2909
2910 pub fn any_hollow_batch_with_exact_runs<T: Arbitrary + Timestamp>(
2911 num_runs: usize,
2912 ) -> impl Strategy<Value = HollowBatch<T>> {
2913 (
2914 any::<T>(),
2915 any::<T>(),
2916 any::<T>(),
2917 proptest::collection::vec(any_run_part::<T>(), num_runs + 1..20),
2918 any::<usize>(),
2919 )
2920 .prop_map(move |(t0, t1, since, parts, len)| {
2921 let (lower, upper) = if t0 <= t1 {
2922 (Antichain::from_elem(t0), Antichain::from_elem(t1))
2923 } else {
2924 (Antichain::from_elem(t1), Antichain::from_elem(t0))
2925 };
2926 let since = Antichain::from_elem(since);
2927
2928 let run_splits = (1..num_runs)
2929 .map(|i| i * parts.len() / num_runs)
2930 .collect::<Vec<_>>();
2931
2932 let run_meta = (0..num_runs)
2933 .map(|_| {
2934 let mut meta = RunMeta::default();
2935 meta.id = Some(RunId::new());
2936 meta
2937 })
2938 .collect::<Vec<_>>();
2939
2940 HollowBatch::new(
2941 Description::new(lower, upper, since),
2942 parts,
2943 len % 10,
2944 run_meta,
2945 run_splits,
2946 )
2947 })
2948 }
2949
2950 pub fn any_hollow_batch<T: Arbitrary + Timestamp>() -> impl Strategy<Value = HollowBatch<T>> {
2951 Strategy::prop_map(
2952 (
2953 any::<T>(),
2954 any::<T>(),
2955 any::<T>(),
2956 proptest::collection::vec(any_run_part::<T>(), 0..20),
2957 any::<usize>(),
2958 0..=10usize,
2959 proptest::collection::vec(any::<RunId>(), 10),
2960 ),
2961 |(t0, t1, since, parts, len, num_runs, run_ids)| {
2962 let (lower, upper) = if t0 <= t1 {
2963 (Antichain::from_elem(t0), Antichain::from_elem(t1))
2964 } else {
2965 (Antichain::from_elem(t1), Antichain::from_elem(t0))
2966 };
2967 let since = Antichain::from_elem(since);
2968 if num_runs > 0 && parts.len() > 2 && num_runs < parts.len() {
2969 let run_splits = (1..num_runs)
2970 .map(|i| i * parts.len() / num_runs)
2971 .collect::<Vec<_>>();
2972
2973 let run_meta = (0..num_runs)
2974 .enumerate()
2975 .map(|(i, _)| {
2976 let mut meta = RunMeta::default();
2977 meta.id = Some(run_ids[i]);
2978 meta
2979 })
2980 .collect::<Vec<_>>();
2981
2982 HollowBatch::new(
2983 Description::new(lower, upper, since),
2984 parts,
2985 len % 10,
2986 run_meta,
2987 run_splits,
2988 )
2989 } else {
2990 HollowBatch::new_run_for_test(
2991 Description::new(lower, upper, since),
2992 parts,
2993 len % 10,
2994 run_ids[0],
2995 )
2996 }
2997 },
2998 )
2999 }
3000
3001 pub fn any_batch_part<T: Arbitrary + Timestamp>() -> impl Strategy<Value = BatchPart<T>> {
3002 Strategy::prop_map(
3003 (
3004 any::<bool>(),
3005 any_hollow_batch_part(),
3006 any::<Option<T>>(),
3007 any::<Option<SchemaId>>(),
3008 any::<Option<SchemaId>>(),
3009 ),
3010 |(is_hollow, hollow, ts_rewrite, schema_id, deprecated_schema_id)| {
3011 if is_hollow {
3012 BatchPart::Hollow(hollow)
3013 } else {
3014 let updates = LazyInlineBatchPart::from_proto(Bytes::new()).unwrap();
3015 let ts_rewrite = ts_rewrite.map(Antichain::from_elem);
3016 BatchPart::Inline {
3017 updates,
3018 ts_rewrite,
3019 schema_id,
3020 deprecated_schema_id,
3021 }
3022 }
3023 },
3024 )
3025 }
3026
3027 pub fn any_run_part<T: Arbitrary + Timestamp>() -> impl Strategy<Value = RunPart<T>> {
3028 Strategy::prop_map(any_batch_part(), |part| RunPart::Single(part))
3029 }
3030
3031 pub fn any_hollow_batch_part<T: Arbitrary + Timestamp>()
3032 -> impl Strategy<Value = HollowBatchPart<T>> {
3033 Strategy::prop_map(
3034 (
3035 any::<PartialBatchKey>(),
3036 any::<usize>(),
3037 any::<Vec<u8>>(),
3038 any_some_lazy_part_stats(),
3039 any::<Option<T>>(),
3040 any::<[u8; 8]>(),
3041 any::<Option<BatchColumnarFormat>>(),
3042 any::<Option<SchemaId>>(),
3043 any::<Option<SchemaId>>(),
3044 ),
3045 |(
3046 key,
3047 encoded_size_bytes,
3048 key_lower,
3049 stats,
3050 ts_rewrite,
3051 diffs_sum,
3052 format,
3053 schema_id,
3054 deprecated_schema_id,
3055 )| {
3056 HollowBatchPart {
3057 key,
3058 meta: Default::default(),
3059 encoded_size_bytes,
3060 key_lower,
3061 structured_key_lower: None,
3062 stats,
3063 ts_rewrite: ts_rewrite.map(Antichain::from_elem),
3064 diffs_sum: Some(diffs_sum),
3065 format,
3066 schema_id,
3067 deprecated_schema_id,
3068 }
3069 },
3070 )
3071 }
3072
3073 pub fn any_leased_reader_state<T: Arbitrary>() -> impl Strategy<Value = LeasedReaderState<T>> {
3074 Strategy::prop_map(
3075 (
3076 any::<SeqNo>(),
3077 any::<Option<T>>(),
3078 any::<u64>(),
3079 any::<u64>(),
3080 any::<HandleDebugState>(),
3081 ),
3082 |(seqno, since, last_heartbeat_timestamp_ms, mut lease_duration_ms, debug)| {
3083 if lease_duration_ms == 0 {
3087 lease_duration_ms += 1;
3088 }
3089 LeasedReaderState {
3090 seqno,
3091 since: since.map_or_else(Antichain::new, Antichain::from_elem),
3092 last_heartbeat_timestamp_ms,
3093 lease_duration_ms,
3094 debug,
3095 }
3096 },
3097 )
3098 }
3099
3100 pub fn any_critical_reader_state<T>() -> impl Strategy<Value = CriticalReaderState<T>>
3101 where
3102 T: Arbitrary,
3103 {
3104 Strategy::prop_map(
3105 (
3106 any::<Option<T>>(),
3107 any::<Opaque>(),
3108 any::<HandleDebugState>(),
3109 ),
3110 |(since, opaque, debug)| CriticalReaderState {
3111 since: since.map_or_else(Antichain::new, Antichain::from_elem),
3112 opaque,
3113 debug,
3114 },
3115 )
3116 }
3117
3118 pub fn any_writer_state<T: Arbitrary>() -> impl Strategy<Value = WriterState<T>> {
3119 Strategy::prop_map(
3120 (
3121 any::<u64>(),
3122 any::<u64>(),
3123 any::<IdempotencyToken>(),
3124 any::<Option<T>>(),
3125 any::<HandleDebugState>(),
3126 ),
3127 |(
3128 last_heartbeat_timestamp_ms,
3129 lease_duration_ms,
3130 most_recent_write_token,
3131 most_recent_write_upper,
3132 debug,
3133 )| WriterState {
3134 last_heartbeat_timestamp_ms,
3135 lease_duration_ms,
3136 most_recent_write_token,
3137 most_recent_write_upper: most_recent_write_upper
3138 .map_or_else(Antichain::new, Antichain::from_elem),
3139 debug,
3140 },
3141 )
3142 }
3143
3144 pub fn any_encoded_schemas() -> impl Strategy<Value = EncodedSchemas> {
3145 Strategy::prop_map(
3146 (
3147 any::<Vec<u8>>(),
3148 any::<Vec<u8>>(),
3149 any::<Vec<u8>>(),
3150 any::<Vec<u8>>(),
3151 ),
3152 |(key, key_data_type, val, val_data_type)| EncodedSchemas {
3153 key: Bytes::from(key),
3154 key_data_type: Bytes::from(key_data_type),
3155 val: Bytes::from(val),
3156 val_data_type: Bytes::from(val_data_type),
3157 },
3158 )
3159 }
3160
3161 pub fn any_state<T: Arbitrary + Timestamp + Lattice>(
3162 num_trace_batches: Range<usize>,
3163 ) -> impl Strategy<Value = State<T>> {
3164 let part1 = (
3165 any::<ShardId>(),
3166 any::<SeqNo>(),
3167 any::<u64>(),
3168 any::<String>(),
3169 any::<SeqNo>(),
3170 proptest::collection::btree_map(any::<SeqNo>(), any::<HollowRollup>(), 1..3),
3171 proptest::option::of(any::<ActiveRollup>()),
3172 );
3173
3174 let part2 = (
3175 proptest::option::of(any::<ActiveGc>()),
3176 proptest::collection::btree_map(
3177 any::<LeasedReaderId>(),
3178 any_leased_reader_state::<T>(),
3179 1..3,
3180 ),
3181 proptest::collection::btree_map(
3182 any::<CriticalReaderId>(),
3183 any_critical_reader_state::<T>(),
3184 1..3,
3185 ),
3186 proptest::collection::btree_map(any::<WriterId>(), any_writer_state::<T>(), 0..3),
3187 proptest::collection::btree_map(any::<SchemaId>(), any_encoded_schemas(), 0..3),
3188 any_trace::<T>(num_trace_batches),
3189 );
3190
3191 (part1, part2).prop_map(
3192 |(
3193 (shard_id, seqno, walltime_ms, hostname, last_gc_req, rollups, active_rollup),
3194 (active_gc, leased_readers, critical_readers, writers, schemas, trace),
3195 )| State {
3196 shard_id,
3197 seqno,
3198 walltime_ms,
3199 hostname,
3200 collections: StateCollections {
3201 version: Version::new(1, 2, 3),
3202 last_gc_req,
3203 rollups,
3204 active_rollup,
3205 active_gc,
3206 leased_readers,
3207 critical_readers,
3208 writers,
3209 schemas,
3210 trace,
3211 },
3212 },
3213 )
3214 }
3215
3216 pub(crate) fn hollow<T: Timestamp>(
3217 lower: T,
3218 upper: T,
3219 keys: &[&str],
3220 len: usize,
3221 ) -> HollowBatch<T> {
3222 HollowBatch::new_run(
3223 Description::new(
3224 Antichain::from_elem(lower),
3225 Antichain::from_elem(upper),
3226 Antichain::from_elem(T::minimum()),
3227 ),
3228 keys.iter()
3229 .map(|x| {
3230 RunPart::Single(BatchPart::Hollow(HollowBatchPart {
3231 key: PartialBatchKey((*x).to_owned()),
3232 meta: Default::default(),
3233 encoded_size_bytes: 0,
3234 key_lower: vec![],
3235 structured_key_lower: None,
3236 stats: None,
3237 ts_rewrite: None,
3238 diffs_sum: None,
3239 format: None,
3240 schema_id: None,
3241 deprecated_schema_id: None,
3242 }))
3243 })
3244 .collect(),
3245 len,
3246 )
3247 }
3248
3249 #[mz_ore::test]
3250 fn downgrade_since() {
3251 let mut state = TypedState::<(), (), u64, i64>::new(
3252 DUMMY_BUILD_INFO.semver_version(),
3253 ShardId::new(),
3254 "".to_owned(),
3255 0,
3256 );
3257 let reader = LeasedReaderId::new();
3258 let seqno = SeqNo::minimum();
3259 let now = SYSTEM_TIME.clone();
3260 let _ = state.collections.register_leased_reader(
3261 "",
3262 &reader,
3263 "",
3264 seqno,
3265 Duration::from_secs(10),
3266 now(),
3267 false,
3268 );
3269
3270 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(0));
3272
3273 assert_eq!(
3275 state.collections.downgrade_since(
3276 &reader,
3277 seqno,
3278 seqno,
3279 &Antichain::from_elem(2),
3280 now()
3281 ),
3282 Continue(Since(Antichain::from_elem(2)))
3283 );
3284 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3285 assert_eq!(
3287 state.collections.downgrade_since(
3288 &reader,
3289 seqno,
3290 seqno,
3291 &Antichain::from_elem(2),
3292 now()
3293 ),
3294 Continue(Since(Antichain::from_elem(2)))
3295 );
3296 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3297 assert_eq!(
3299 state.collections.downgrade_since(
3300 &reader,
3301 seqno,
3302 seqno,
3303 &Antichain::from_elem(1),
3304 now()
3305 ),
3306 Continue(Since(Antichain::from_elem(2)))
3307 );
3308 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3309
3310 let reader2 = LeasedReaderId::new();
3312 let _ = state.collections.register_leased_reader(
3313 "",
3314 &reader2,
3315 "",
3316 seqno,
3317 Duration::from_secs(10),
3318 now(),
3319 false,
3320 );
3321
3322 assert_eq!(
3324 state.collections.downgrade_since(
3325 &reader2,
3326 seqno,
3327 seqno,
3328 &Antichain::from_elem(3),
3329 now()
3330 ),
3331 Continue(Since(Antichain::from_elem(3)))
3332 );
3333 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3334 assert_eq!(
3336 state.collections.downgrade_since(
3337 &reader,
3338 seqno,
3339 seqno,
3340 &Antichain::from_elem(5),
3341 now()
3342 ),
3343 Continue(Since(Antichain::from_elem(5)))
3344 );
3345 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(3));
3346
3347 assert_eq!(
3349 state.collections.expire_leased_reader(&reader),
3350 Continue(true)
3351 );
3352 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(3));
3353
3354 let reader3 = LeasedReaderId::new();
3356 let _ = state.collections.register_leased_reader(
3357 "",
3358 &reader3,
3359 "",
3360 seqno,
3361 Duration::from_secs(10),
3362 now(),
3363 false,
3364 );
3365
3366 assert_eq!(
3368 state.collections.downgrade_since(
3369 &reader3,
3370 seqno,
3371 seqno,
3372 &Antichain::from_elem(10),
3373 now()
3374 ),
3375 Continue(Since(Antichain::from_elem(10)))
3376 );
3377 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(3));
3378
3379 assert_eq!(
3381 state.collections.expire_leased_reader(&reader2),
3382 Continue(true)
3383 );
3384 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(3));
3389
3390 assert_eq!(
3392 state.collections.expire_leased_reader(&reader3),
3393 Continue(true)
3394 );
3395 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(3));
3400 }
3401
3402 #[mz_ore::test]
3403 fn compare_and_downgrade_since() {
3404 let mut state = TypedState::<(), (), u64, i64>::new(
3405 DUMMY_BUILD_INFO.semver_version(),
3406 ShardId::new(),
3407 "".to_owned(),
3408 0,
3409 );
3410 let reader = CriticalReaderId::new();
3411 let _ = state
3412 .collections
3413 .register_critical_reader("", &reader, Opaque::encode(&0u64), "");
3414
3415 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(0));
3417 assert_eq!(
3419 state
3420 .collections
3421 .critical_reader(&reader)
3422 .opaque
3423 .decode::<u64>(),
3424 u64::MIN
3425 );
3426
3427 assert_eq!(
3429 state.collections.compare_and_downgrade_since(
3430 &reader,
3431 &Opaque::encode(&0u64),
3432 (&Opaque::encode(&1u64), &Antichain::from_elem(2)),
3433 ),
3434 Continue(Ok(Since(Antichain::from_elem(2))))
3435 );
3436 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3437 assert_eq!(
3438 state
3439 .collections
3440 .critical_reader(&reader)
3441 .opaque
3442 .decode::<u64>(),
3443 1
3444 );
3445 assert_eq!(
3447 state.collections.compare_and_downgrade_since(
3448 &reader,
3449 &Opaque::encode(&1u64),
3450 (&Opaque::encode(&2u64), &Antichain::from_elem(2)),
3451 ),
3452 Continue(Ok(Since(Antichain::from_elem(2))))
3453 );
3454 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3455 assert_eq!(
3456 state
3457 .collections
3458 .critical_reader(&reader)
3459 .opaque
3460 .decode::<u64>(),
3461 2
3462 );
3463 assert_eq!(
3465 state.collections.compare_and_downgrade_since(
3466 &reader,
3467 &Opaque::encode(&2u64),
3468 (&Opaque::encode(&3u64), &Antichain::from_elem(1)),
3469 ),
3470 Continue(Ok(Since(Antichain::from_elem(2))))
3471 );
3472 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3473 assert_eq!(
3474 state
3475 .collections
3476 .critical_reader(&reader)
3477 .opaque
3478 .decode::<u64>(),
3479 3
3480 );
3481 }
3482
3483 #[mz_ore::test]
3484 fn compare_and_append() {
3485 let state = &mut TypedState::<String, String, u64, i64>::new(
3486 DUMMY_BUILD_INFO.semver_version(),
3487 ShardId::new(),
3488 "".to_owned(),
3489 0,
3490 )
3491 .collections;
3492
3493 let writer_id = WriterId::new();
3494 let now = SYSTEM_TIME.clone();
3495
3496 assert_eq!(state.trace.num_spine_batches(), 0);
3498 assert_eq!(state.trace.num_hollow_batches(), 0);
3499 assert_eq!(state.trace.num_updates(), 0);
3500
3501 assert_eq!(
3503 state.compare_and_append(
3504 &hollow(1, 2, &["key1"], 1),
3505 &writer_id,
3506 now(),
3507 LEASE_DURATION_MS,
3508 &IdempotencyToken::new(),
3509 &debug_state(),
3510 0,
3511 100,
3512 None
3513 ),
3514 Break(CompareAndAppendBreak::Upper {
3515 shard_upper: Antichain::from_elem(0),
3516 writer_upper: Antichain::from_elem(0)
3517 })
3518 );
3519
3520 assert!(
3522 state
3523 .compare_and_append(
3524 &hollow(0, 5, &[], 0),
3525 &writer_id,
3526 now(),
3527 LEASE_DURATION_MS,
3528 &IdempotencyToken::new(),
3529 &debug_state(),
3530 0,
3531 100,
3532 None
3533 )
3534 .is_continue()
3535 );
3536
3537 assert_eq!(
3539 state.compare_and_append(
3540 &hollow(5, 4, &["key1"], 1),
3541 &writer_id,
3542 now(),
3543 LEASE_DURATION_MS,
3544 &IdempotencyToken::new(),
3545 &debug_state(),
3546 0,
3547 100,
3548 None
3549 ),
3550 Break(CompareAndAppendBreak::InvalidUsage(InvalidBounds {
3551 lower: Antichain::from_elem(5),
3552 upper: Antichain::from_elem(4)
3553 }))
3554 );
3555
3556 assert_eq!(
3558 state.compare_and_append(
3559 &hollow(5, 5, &["key1"], 1),
3560 &writer_id,
3561 now(),
3562 LEASE_DURATION_MS,
3563 &IdempotencyToken::new(),
3564 &debug_state(),
3565 0,
3566 100,
3567 None
3568 ),
3569 Break(CompareAndAppendBreak::InvalidUsage(
3570 InvalidEmptyTimeInterval {
3571 lower: Antichain::from_elem(5),
3572 upper: Antichain::from_elem(5),
3573 keys: vec!["key1".to_owned()],
3574 }
3575 ))
3576 );
3577
3578 assert!(
3580 state
3581 .compare_and_append(
3582 &hollow(5, 5, &[], 0),
3583 &writer_id,
3584 now(),
3585 LEASE_DURATION_MS,
3586 &IdempotencyToken::new(),
3587 &debug_state(),
3588 0,
3589 100,
3590 None
3591 )
3592 .is_continue()
3593 );
3594 }
3595
3596 #[mz_ore::test]
3597 fn snapshot() {
3598 let now = SYSTEM_TIME.clone();
3599
3600 let mut state = TypedState::<String, String, u64, i64>::new(
3601 DUMMY_BUILD_INFO.semver_version(),
3602 ShardId::new(),
3603 "".to_owned(),
3604 0,
3605 );
3606 assert_eq!(
3608 state.snapshot(&Antichain::from_elem(0)),
3609 Err(SnapshotErr::AsOfNotYetAvailable(
3610 SeqNo(0),
3611 Upper(Antichain::from_elem(0))
3612 ))
3613 );
3614
3615 assert_eq!(
3617 state.snapshot(&Antichain::from_elem(5)),
3618 Err(SnapshotErr::AsOfNotYetAvailable(
3619 SeqNo(0),
3620 Upper(Antichain::from_elem(0))
3621 ))
3622 );
3623
3624 let writer_id = WriterId::new();
3625
3626 assert!(
3628 state
3629 .collections
3630 .compare_and_append(
3631 &hollow(0, 5, &["key1"], 1),
3632 &writer_id,
3633 now(),
3634 LEASE_DURATION_MS,
3635 &IdempotencyToken::new(),
3636 &debug_state(),
3637 0,
3638 100,
3639 None
3640 )
3641 .is_continue()
3642 );
3643
3644 assert_eq!(
3646 state.snapshot(&Antichain::from_elem(0)),
3647 Ok(vec![hollow(0, 5, &["key1"], 1)])
3648 );
3649
3650 assert_eq!(
3652 state.snapshot(&Antichain::from_elem(4)),
3653 Ok(vec![hollow(0, 5, &["key1"], 1)])
3654 );
3655
3656 assert_eq!(
3658 state.snapshot(&Antichain::from_elem(5)),
3659 Err(SnapshotErr::AsOfNotYetAvailable(
3660 SeqNo(0),
3661 Upper(Antichain::from_elem(5))
3662 ))
3663 );
3664 assert_eq!(
3665 state.snapshot(&Antichain::from_elem(6)),
3666 Err(SnapshotErr::AsOfNotYetAvailable(
3667 SeqNo(0),
3668 Upper(Antichain::from_elem(5))
3669 ))
3670 );
3671
3672 let reader = LeasedReaderId::new();
3673 let _ = state.collections.register_leased_reader(
3675 "",
3676 &reader,
3677 "",
3678 SeqNo::minimum(),
3679 Duration::from_secs(10),
3680 now(),
3681 false,
3682 );
3683 assert_eq!(
3684 state.collections.downgrade_since(
3685 &reader,
3686 SeqNo::minimum(),
3687 SeqNo::minimum(),
3688 &Antichain::from_elem(2),
3689 now()
3690 ),
3691 Continue(Since(Antichain::from_elem(2)))
3692 );
3693 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3694 assert_eq!(
3696 state.snapshot(&Antichain::from_elem(1)),
3697 Err(SnapshotErr::AsOfHistoricalDistinctionsLost(Since(
3698 Antichain::from_elem(2)
3699 )))
3700 );
3701
3702 assert!(
3704 state
3705 .collections
3706 .compare_and_append(
3707 &hollow(5, 10, &[], 0),
3708 &writer_id,
3709 now(),
3710 LEASE_DURATION_MS,
3711 &IdempotencyToken::new(),
3712 &debug_state(),
3713 0,
3714 100,
3715 None
3716 )
3717 .is_continue()
3718 );
3719
3720 assert_eq!(
3722 state.snapshot(&Antichain::from_elem(7)),
3723 Ok(vec![hollow(0, 5, &["key1"], 1), hollow(5, 10, &[], 0)])
3724 );
3725
3726 assert_eq!(
3728 state.snapshot(&Antichain::from_elem(10)),
3729 Err(SnapshotErr::AsOfNotYetAvailable(
3730 SeqNo(0),
3731 Upper(Antichain::from_elem(10))
3732 ))
3733 );
3734
3735 assert!(
3737 state
3738 .collections
3739 .compare_and_append(
3740 &hollow(10, 15, &["key2"], 1),
3741 &writer_id,
3742 now(),
3743 LEASE_DURATION_MS,
3744 &IdempotencyToken::new(),
3745 &debug_state(),
3746 0,
3747 100,
3748 None
3749 )
3750 .is_continue()
3751 );
3752
3753 assert_eq!(
3756 state.snapshot(&Antichain::from_elem(9)),
3757 Ok(vec![hollow(0, 5, &["key1"], 1), hollow(5, 10, &[], 0)])
3758 );
3759
3760 assert_eq!(
3762 state.snapshot(&Antichain::from_elem(10)),
3763 Ok(vec![
3764 hollow(0, 5, &["key1"], 1),
3765 hollow(5, 10, &[], 0),
3766 hollow(10, 15, &["key2"], 1)
3767 ])
3768 );
3769
3770 assert_eq!(
3771 state.snapshot(&Antichain::from_elem(11)),
3772 Ok(vec![
3773 hollow(0, 5, &["key1"], 1),
3774 hollow(5, 10, &[], 0),
3775 hollow(10, 15, &["key2"], 1)
3776 ])
3777 );
3778 }
3779
3780 #[mz_ore::test]
3781 fn next_listen_batch() {
3782 let mut state = TypedState::<String, String, u64, i64>::new(
3783 DUMMY_BUILD_INFO.semver_version(),
3784 ShardId::new(),
3785 "".to_owned(),
3786 0,
3787 );
3788
3789 assert_eq!(
3792 state.next_listen_batch(&Antichain::from_elem(0)),
3793 Err(SeqNo(0))
3794 );
3795 assert_eq!(state.next_listen_batch(&Antichain::new()), Err(SeqNo(0)));
3796
3797 let writer_id = WriterId::new();
3798 let now = SYSTEM_TIME.clone();
3799
3800 assert!(
3802 state
3803 .collections
3804 .compare_and_append(
3805 &hollow(0, 5, &["key1"], 1),
3806 &writer_id,
3807 now(),
3808 LEASE_DURATION_MS,
3809 &IdempotencyToken::new(),
3810 &debug_state(),
3811 0,
3812 100,
3813 None
3814 )
3815 .is_continue()
3816 );
3817 assert!(
3818 state
3819 .collections
3820 .compare_and_append(
3821 &hollow(5, 10, &["key2"], 1),
3822 &writer_id,
3823 now(),
3824 LEASE_DURATION_MS,
3825 &IdempotencyToken::new(),
3826 &debug_state(),
3827 0,
3828 100,
3829 None
3830 )
3831 .is_continue()
3832 );
3833
3834 for t in 0..=4 {
3836 assert_eq!(
3837 state.next_listen_batch(&Antichain::from_elem(t)),
3838 Ok(hollow(0, 5, &["key1"], 1))
3839 );
3840 }
3841
3842 for t in 5..=9 {
3844 assert_eq!(
3845 state.next_listen_batch(&Antichain::from_elem(t)),
3846 Ok(hollow(5, 10, &["key2"], 1))
3847 );
3848 }
3849
3850 assert_eq!(
3852 state.next_listen_batch(&Antichain::from_elem(10)),
3853 Err(SeqNo(0))
3854 );
3855
3856 assert_eq!(state.next_listen_batch(&Antichain::new()), Err(SeqNo(0)));
3859 }
3860
3861 #[mz_ore::test]
3862 fn expire_writer() {
3863 let mut state = TypedState::<String, String, u64, i64>::new(
3864 DUMMY_BUILD_INFO.semver_version(),
3865 ShardId::new(),
3866 "".to_owned(),
3867 0,
3868 );
3869 let now = SYSTEM_TIME.clone();
3870
3871 let writer_id_one = WriterId::new();
3872
3873 let writer_id_two = WriterId::new();
3874
3875 assert!(
3877 state
3878 .collections
3879 .compare_and_append(
3880 &hollow(0, 2, &["key1"], 1),
3881 &writer_id_one,
3882 now(),
3883 LEASE_DURATION_MS,
3884 &IdempotencyToken::new(),
3885 &debug_state(),
3886 0,
3887 100,
3888 None
3889 )
3890 .is_continue()
3891 );
3892
3893 assert!(
3894 state
3895 .collections
3896 .expire_writer(&writer_id_one)
3897 .is_continue()
3898 );
3899
3900 assert!(
3902 state
3903 .collections
3904 .compare_and_append(
3905 &hollow(2, 5, &["key2"], 1),
3906 &writer_id_two,
3907 now(),
3908 LEASE_DURATION_MS,
3909 &IdempotencyToken::new(),
3910 &debug_state(),
3911 0,
3912 100,
3913 None
3914 )
3915 .is_continue()
3916 );
3917 }
3918
3919 #[mz_ore::test]
3920 fn maybe_gc_active_gc() {
3921 const GC_CONFIG: GcConfig = GcConfig {
3922 use_active_gc: true,
3923 fallback_threshold_ms: 5000,
3924 min_versions: 99,
3925 max_versions: 500,
3926 };
3927 let now_fn = SYSTEM_TIME.clone();
3928
3929 let mut state = TypedState::<String, String, u64, i64>::new(
3930 DUMMY_BUILD_INFO.semver_version(),
3931 ShardId::new(),
3932 "".to_owned(),
3933 0,
3934 );
3935
3936 let now = now_fn();
3937 assert_eq!(state.maybe_gc(true, now, GC_CONFIG), None);
3939 assert_eq!(state.maybe_gc(false, now, GC_CONFIG), None);
3940
3941 state.seqno = SeqNo(100);
3944 assert_eq!(state.seqno_since(), SeqNo(100));
3945
3946 let writer_id = WriterId::new();
3948 let _ = state.collections.compare_and_append(
3949 &hollow(1, 2, &["key1"], 1),
3950 &writer_id,
3951 now,
3952 LEASE_DURATION_MS,
3953 &IdempotencyToken::new(),
3954 &debug_state(),
3955 0,
3956 100,
3957 None,
3958 );
3959 assert_eq!(state.maybe_gc(false, now, GC_CONFIG), None);
3960
3961 assert_eq!(
3963 state.maybe_gc(true, now, GC_CONFIG),
3964 Some(GcReq {
3965 shard_id: state.shard_id,
3966 new_seqno_since: SeqNo(100)
3967 })
3968 );
3969
3970 state.collections.active_gc = Some(ActiveGc {
3972 seqno: state.seqno,
3973 start_ms: now,
3974 });
3975
3976 state.seqno = SeqNo(200);
3977 assert_eq!(state.seqno_since(), SeqNo(200));
3978
3979 assert_eq!(state.maybe_gc(true, now, GC_CONFIG), None);
3980
3981 state.seqno = SeqNo(300);
3982 assert_eq!(state.seqno_since(), SeqNo(300));
3983 let new_now = now + GC_CONFIG.fallback_threshold_ms + 1;
3985 assert_eq!(
3986 state.maybe_gc(true, new_now, GC_CONFIG),
3987 Some(GcReq {
3988 shard_id: state.shard_id,
3989 new_seqno_since: SeqNo(300)
3990 })
3991 );
3992
3993 state.seqno = SeqNo(301);
3997 assert_eq!(state.seqno_since(), SeqNo(301));
3998 assert_eq!(
3999 state.maybe_gc(true, new_now, GC_CONFIG),
4000 Some(GcReq {
4001 shard_id: state.shard_id,
4002 new_seqno_since: SeqNo(301)
4003 })
4004 );
4005
4006 state.collections.active_gc = None;
4007
4008 state.seqno = SeqNo(400);
4011 assert_eq!(state.seqno_since(), SeqNo(400));
4012
4013 let now = now_fn();
4014
4015 let _ = state.collections.expire_writer(&writer_id);
4017 assert_eq!(
4018 state.maybe_gc(false, now, GC_CONFIG),
4019 Some(GcReq {
4020 shard_id: state.shard_id,
4021 new_seqno_since: SeqNo(400)
4022 })
4023 );
4024
4025 let previous_seqno = state.seqno;
4027 state.seqno = SeqNo(10_000);
4028 assert_eq!(state.seqno_since(), SeqNo(10_000));
4029
4030 let now = now_fn();
4031 assert_eq!(
4032 state.maybe_gc(true, now, GC_CONFIG),
4033 Some(GcReq {
4034 shard_id: state.shard_id,
4035 new_seqno_since: SeqNo(previous_seqno.0 + u64::cast_from(GC_CONFIG.max_versions))
4036 })
4037 );
4038 }
4039
4040 #[mz_ore::test]
4041 fn maybe_gc_classic() {
4042 const GC_CONFIG: GcConfig = GcConfig {
4043 use_active_gc: false,
4044 fallback_threshold_ms: 5000,
4045 min_versions: 16,
4046 max_versions: 128,
4047 };
4048 const NOW_MS: u64 = 0;
4049
4050 let mut state = TypedState::<String, String, u64, i64>::new(
4051 DUMMY_BUILD_INFO.semver_version(),
4052 ShardId::new(),
4053 "".to_owned(),
4054 0,
4055 );
4056
4057 assert_eq!(state.maybe_gc(true, NOW_MS, GC_CONFIG), None);
4059 assert_eq!(state.maybe_gc(false, NOW_MS, GC_CONFIG), None);
4060
4061 state.seqno = SeqNo(100);
4064 assert_eq!(state.seqno_since(), SeqNo(100));
4065
4066 let writer_id = WriterId::new();
4068 let now = SYSTEM_TIME.clone();
4069 let _ = state.collections.compare_and_append(
4070 &hollow(1, 2, &["key1"], 1),
4071 &writer_id,
4072 now(),
4073 LEASE_DURATION_MS,
4074 &IdempotencyToken::new(),
4075 &debug_state(),
4076 0,
4077 100,
4078 None,
4079 );
4080 assert_eq!(state.maybe_gc(false, NOW_MS, GC_CONFIG), None);
4081
4082 assert_eq!(
4084 state.maybe_gc(true, NOW_MS, GC_CONFIG),
4085 Some(GcReq {
4086 shard_id: state.shard_id,
4087 new_seqno_since: SeqNo(100)
4088 })
4089 );
4090
4091 state.seqno = SeqNo(200);
4094 assert_eq!(state.seqno_since(), SeqNo(200));
4095
4096 let _ = state.collections.expire_writer(&writer_id);
4098 assert_eq!(
4099 state.maybe_gc(false, NOW_MS, GC_CONFIG),
4100 Some(GcReq {
4101 shard_id: state.shard_id,
4102 new_seqno_since: SeqNo(200)
4103 })
4104 );
4105 }
4106
4107 #[mz_ore::test]
4108 fn need_rollup_active_rollup() {
4109 const ROLLUP_THRESHOLD: usize = 3;
4110 const ROLLUP_USE_ACTIVE_ROLLUP: bool = true;
4111 const ROLLUP_FALLBACK_THRESHOLD_MS: u64 = 5000;
4112 let now = SYSTEM_TIME.clone();
4113
4114 mz_ore::test::init_logging();
4115 let mut state = TypedState::<String, String, u64, i64>::new(
4116 DUMMY_BUILD_INFO.semver_version(),
4117 ShardId::new(),
4118 "".to_owned(),
4119 0,
4120 );
4121
4122 let rollup_seqno = SeqNo(5);
4123 let rollup = HollowRollup {
4124 key: PartialRollupKey::new(rollup_seqno, &RollupId::new()),
4125 encoded_size_bytes: None,
4126 };
4127
4128 assert!(
4129 state
4130 .collections
4131 .add_rollup((rollup_seqno, &rollup))
4132 .is_continue()
4133 );
4134
4135 state.seqno = SeqNo(5);
4137 assert_none!(state.need_rollup(
4138 ROLLUP_THRESHOLD,
4139 ROLLUP_USE_ACTIVE_ROLLUP,
4140 ROLLUP_FALLBACK_THRESHOLD_MS,
4141 now()
4142 ));
4143
4144 state.seqno = SeqNo(6);
4146 assert_none!(state.need_rollup(
4147 ROLLUP_THRESHOLD,
4148 ROLLUP_USE_ACTIVE_ROLLUP,
4149 ROLLUP_FALLBACK_THRESHOLD_MS,
4150 now()
4151 ));
4152 state.seqno = SeqNo(7);
4153 assert_none!(state.need_rollup(
4154 ROLLUP_THRESHOLD,
4155 ROLLUP_USE_ACTIVE_ROLLUP,
4156 ROLLUP_FALLBACK_THRESHOLD_MS,
4157 now()
4158 ));
4159 state.seqno = SeqNo(8);
4160 assert_none!(state.need_rollup(
4161 ROLLUP_THRESHOLD,
4162 ROLLUP_USE_ACTIVE_ROLLUP,
4163 ROLLUP_FALLBACK_THRESHOLD_MS,
4164 now()
4165 ));
4166
4167 let mut current_time = now();
4168 state.seqno = SeqNo(9);
4170 assert_eq!(
4171 state
4172 .need_rollup(
4173 ROLLUP_THRESHOLD,
4174 ROLLUP_USE_ACTIVE_ROLLUP,
4175 ROLLUP_FALLBACK_THRESHOLD_MS,
4176 current_time
4177 )
4178 .expect("rollup"),
4179 SeqNo(9)
4180 );
4181
4182 state.collections.active_rollup = Some(ActiveRollup {
4183 seqno: SeqNo(9),
4184 start_ms: current_time,
4185 });
4186
4187 assert_none!(state.need_rollup(
4189 ROLLUP_THRESHOLD,
4190 ROLLUP_USE_ACTIVE_ROLLUP,
4191 ROLLUP_FALLBACK_THRESHOLD_MS,
4192 current_time
4193 ));
4194
4195 state.seqno = SeqNo(10);
4196 assert_none!(state.need_rollup(
4199 ROLLUP_THRESHOLD,
4200 ROLLUP_USE_ACTIVE_ROLLUP,
4201 ROLLUP_FALLBACK_THRESHOLD_MS,
4202 current_time
4203 ));
4204
4205 current_time += u64::cast_from(ROLLUP_FALLBACK_THRESHOLD_MS) + 1;
4207 assert_eq!(
4208 state
4209 .need_rollup(
4210 ROLLUP_THRESHOLD,
4211 ROLLUP_USE_ACTIVE_ROLLUP,
4212 ROLLUP_FALLBACK_THRESHOLD_MS,
4213 current_time
4214 )
4215 .expect("rollup"),
4216 SeqNo(10)
4217 );
4218
4219 state.seqno = SeqNo(9);
4220 state.collections.active_rollup = None;
4222 let rollup_seqno = SeqNo(9);
4223 let rollup = HollowRollup {
4224 key: PartialRollupKey::new(rollup_seqno, &RollupId::new()),
4225 encoded_size_bytes: None,
4226 };
4227 assert!(
4228 state
4229 .collections
4230 .add_rollup((rollup_seqno, &rollup))
4231 .is_continue()
4232 );
4233
4234 state.seqno = SeqNo(11);
4235 assert_none!(state.need_rollup(
4237 ROLLUP_THRESHOLD,
4238 ROLLUP_USE_ACTIVE_ROLLUP,
4239 ROLLUP_FALLBACK_THRESHOLD_MS,
4240 current_time
4241 ));
4242 state.seqno = SeqNo(13);
4244 assert_eq!(
4245 state
4246 .need_rollup(
4247 ROLLUP_THRESHOLD,
4248 ROLLUP_USE_ACTIVE_ROLLUP,
4249 ROLLUP_FALLBACK_THRESHOLD_MS,
4250 current_time
4251 )
4252 .expect("rollup"),
4253 SeqNo(13)
4254 );
4255 }
4256
4257 #[mz_ore::test]
4258 fn need_rollup_classic() {
4259 const ROLLUP_THRESHOLD: usize = 3;
4260 const ROLLUP_USE_ACTIVE_ROLLUP: bool = false;
4261 const ROLLUP_FALLBACK_THRESHOLD_MS: u64 = 0;
4262 const NOW: u64 = 0;
4263
4264 mz_ore::test::init_logging();
4265 let mut state = TypedState::<String, String, u64, i64>::new(
4266 DUMMY_BUILD_INFO.semver_version(),
4267 ShardId::new(),
4268 "".to_owned(),
4269 0,
4270 );
4271
4272 let rollup_seqno = SeqNo(5);
4273 let rollup = HollowRollup {
4274 key: PartialRollupKey::new(rollup_seqno, &RollupId::new()),
4275 encoded_size_bytes: None,
4276 };
4277
4278 assert!(
4279 state
4280 .collections
4281 .add_rollup((rollup_seqno, &rollup))
4282 .is_continue()
4283 );
4284
4285 state.seqno = SeqNo(5);
4287 assert_none!(state.need_rollup(
4288 ROLLUP_THRESHOLD,
4289 ROLLUP_USE_ACTIVE_ROLLUP,
4290 ROLLUP_FALLBACK_THRESHOLD_MS,
4291 NOW
4292 ));
4293
4294 state.seqno = SeqNo(6);
4296 assert_none!(state.need_rollup(
4297 ROLLUP_THRESHOLD,
4298 ROLLUP_USE_ACTIVE_ROLLUP,
4299 ROLLUP_FALLBACK_THRESHOLD_MS,
4300 NOW
4301 ));
4302 state.seqno = SeqNo(7);
4303 assert_none!(state.need_rollup(
4304 ROLLUP_THRESHOLD,
4305 ROLLUP_USE_ACTIVE_ROLLUP,
4306 ROLLUP_FALLBACK_THRESHOLD_MS,
4307 NOW
4308 ));
4309
4310 state.seqno = SeqNo(8);
4312 assert_eq!(
4313 state
4314 .need_rollup(
4315 ROLLUP_THRESHOLD,
4316 ROLLUP_USE_ACTIVE_ROLLUP,
4317 ROLLUP_FALLBACK_THRESHOLD_MS,
4318 NOW
4319 )
4320 .expect("rollup"),
4321 SeqNo(8)
4322 );
4323
4324 state.seqno = SeqNo(9);
4326 assert_none!(state.need_rollup(
4327 ROLLUP_THRESHOLD,
4328 ROLLUP_USE_ACTIVE_ROLLUP,
4329 ROLLUP_FALLBACK_THRESHOLD_MS,
4330 NOW
4331 ));
4332
4333 state.seqno = SeqNo(11);
4335 assert_eq!(
4336 state
4337 .need_rollup(
4338 ROLLUP_THRESHOLD,
4339 ROLLUP_USE_ACTIVE_ROLLUP,
4340 ROLLUP_FALLBACK_THRESHOLD_MS,
4341 NOW
4342 )
4343 .expect("rollup"),
4344 SeqNo(11)
4345 );
4346
4347 let rollup_seqno = SeqNo(6);
4349 let rollup = HollowRollup {
4350 key: PartialRollupKey::new(rollup_seqno, &RollupId::new()),
4351 encoded_size_bytes: None,
4352 };
4353 assert!(
4354 state
4355 .collections
4356 .add_rollup((rollup_seqno, &rollup))
4357 .is_continue()
4358 );
4359
4360 state.seqno = SeqNo(8);
4361 assert_none!(state.need_rollup(
4362 ROLLUP_THRESHOLD,
4363 ROLLUP_USE_ACTIVE_ROLLUP,
4364 ROLLUP_FALLBACK_THRESHOLD_MS,
4365 NOW
4366 ));
4367 state.seqno = SeqNo(9);
4368 assert_eq!(
4369 state
4370 .need_rollup(
4371 ROLLUP_THRESHOLD,
4372 ROLLUP_USE_ACTIVE_ROLLUP,
4373 ROLLUP_FALLBACK_THRESHOLD_MS,
4374 NOW
4375 )
4376 .expect("rollup"),
4377 SeqNo(9)
4378 );
4379
4380 let fallback_seqno = SeqNo(
4382 rollup_seqno.0
4383 * u64::cast_from(PersistConfig::DEFAULT_FALLBACK_ROLLUP_THRESHOLD_MULTIPLIER),
4384 );
4385 state.seqno = fallback_seqno;
4386 assert_eq!(
4387 state
4388 .need_rollup(
4389 ROLLUP_THRESHOLD,
4390 ROLLUP_USE_ACTIVE_ROLLUP,
4391 ROLLUP_FALLBACK_THRESHOLD_MS,
4392 NOW
4393 )
4394 .expect("rollup"),
4395 fallback_seqno
4396 );
4397 state.seqno = fallback_seqno.next();
4398 assert_eq!(
4399 state
4400 .need_rollup(
4401 ROLLUP_THRESHOLD,
4402 ROLLUP_USE_ACTIVE_ROLLUP,
4403 ROLLUP_FALLBACK_THRESHOLD_MS,
4404 NOW
4405 )
4406 .expect("rollup"),
4407 fallback_seqno.next()
4408 );
4409 }
4410
4411 #[mz_ore::test]
4412 fn idempotency_token_sentinel() {
4413 assert_eq!(
4414 IdempotencyToken::SENTINEL.to_string(),
4415 "i11111111-1111-1111-1111-111111111111"
4416 );
4417 }
4418
4419 #[mz_ore::test]
4428 #[cfg_attr(miri, ignore)] fn state_inspect_serde_json() {
4430 const STATE_SERDE_JSON: &str = include_str!("state_serde.json");
4431 let mut runner = proptest::test_runner::TestRunner::deterministic();
4432 let tree = any_state::<u64>(6..8).new_tree(&mut runner).unwrap();
4433 let json = serde_json::to_string_pretty(&tree.current()).unwrap();
4434 assert_eq!(
4435 json.trim(),
4436 STATE_SERDE_JSON.trim(),
4437 "\n\nNEW GOLDEN\n{}\n",
4438 json
4439 );
4440 }
4441
4442 #[mz_persist_proc::test(tokio::test)]
4443 #[cfg_attr(miri, ignore)] async fn sneaky_downgrades(dyncfgs: ConfigUpdates) {
4445 let mut clients = new_test_client_cache(&dyncfgs);
4446 let shard_id = ShardId::new();
4447
4448 async fn open_and_write(
4449 clients: &mut PersistClientCache,
4450 version: semver::Version,
4451 shard_id: ShardId,
4452 ) -> Result<(), tokio::task::JoinError> {
4453 clients.cfg.build_version = version.clone();
4454 clients.clear_state_cache();
4455 let client = clients.open(PersistLocation::new_in_mem()).await.unwrap();
4456 mz_ore::task::spawn(|| version.to_string(), async move {
4458 let () = client
4459 .upgrade_version::<String, (), u64, i64>(shard_id, Diagnostics::for_tests())
4460 .await
4461 .expect("valid usage");
4462 let (mut write, _) = client.expect_open::<String, (), u64, i64>(shard_id).await;
4463 let current = *write.upper().as_option().unwrap();
4464 write
4466 .expect_compare_and_append_batch(&mut [], current, current + 1)
4467 .await;
4468 })
4469 .into_tokio_handle()
4470 .await
4471 }
4472
4473 let res = open_and_write(&mut clients, Version::new(0, 10, 0), shard_id).await;
4475 assert_ok!(res);
4476
4477 let res = open_and_write(&mut clients, Version::new(0, 11, 0), shard_id).await;
4479 assert_ok!(res);
4480
4481 let res = open_and_write(&mut clients, Version::new(0, 10, 0), shard_id).await;
4483 assert!(res.unwrap_err().is_panic());
4484
4485 let res = open_and_write(&mut clients, Version::new(0, 9, 0), shard_id).await;
4487 assert!(res.unwrap_err().is_panic());
4488 }
4489
4490 #[mz_ore::test]
4491 fn runid_roundtrip() {
4492 proptest!(|(runid: RunId)| {
4493 let runid_str = runid.to_string();
4494 let parsed = RunId::from_str(&runid_str);
4495 prop_assert_eq!(parsed, Ok(runid));
4496 });
4497 }
4498
4499 #[mz_ore::test]
4515 fn add_rollup_idempotent_across_gc_removal() {
4516 let mut state = TypedState::<String, String, u64, i64>::new(
4517 DUMMY_BUILD_INFO.semver_version(),
4518 ShardId::new(),
4519 "".to_owned(),
4520 0,
4521 );
4522
4523 let older_seqno = SeqNo(10);
4524 let older = HollowRollup {
4525 key: PartialRollupKey::new(older_seqno, &RollupId::new()),
4526 encoded_size_bytes: None,
4527 };
4528 let newer_seqno = SeqNo(20);
4529 let newer = HollowRollup {
4530 key: PartialRollupKey::new(newer_seqno, &RollupId::new()),
4531 encoded_size_bytes: None,
4532 };
4533 let add_older = |state: &mut StateCollections<u64>| state.add_rollup((older_seqno, &older));
4534
4535 assert_eq!(add_older(&mut state.collections), Continue(true));
4537 assert_eq!(add_older(&mut state.collections), Continue(true));
4540 assert_eq!(state.collections.rollups.len(), 1);
4541
4542 assert_eq!(
4546 state.collections.add_rollup((newer_seqno, &newer)),
4547 Continue(true),
4548 );
4549
4550 let _ = state
4554 .collections
4555 .remove_rollups(&[(older_seqno, older.key.clone())]);
4556 assert!(!state.collections.rollups.contains_key(&older_seqno));
4557 assert!(state.collections.rollups.contains_key(&newer_seqno));
4558
4559 assert_eq!(add_older(&mut state.collections), Continue(false));
4564 assert!(!state.collections.rollups.contains_key(&older_seqno));
4565 assert_eq!(state.collections.rollups.len(), 1);
4566 }
4567}