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 true,
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)]
906pub struct HollowBatch<T> {
907 pub desc: Description<T>,
909 pub len: usize,
911 pub(crate) parts: Vec<RunPart<T>>,
913 pub(crate) run_splits: Vec<usize>,
921 pub(crate) run_meta: Vec<RunMeta>,
924}
925
926impl<T: Debug> Debug for HollowBatch<T> {
927 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
928 let HollowBatch {
929 desc,
930 parts,
931 len,
932 run_splits: runs,
933 run_meta,
934 } = self;
935 f.debug_struct("HollowBatch")
936 .field(
937 "desc",
938 &(
939 desc.lower().elements(),
940 desc.upper().elements(),
941 desc.since().elements(),
942 ),
943 )
944 .field("parts", &parts)
945 .field("len", &len)
946 .field("runs", &runs)
947 .field("run_meta", &run_meta)
948 .finish()
949 }
950}
951
952impl<T: Serialize> serde::Serialize for HollowBatch<T> {
953 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
954 let HollowBatch {
955 desc,
956 len,
957 parts: _,
959 run_splits: _,
960 run_meta: _,
961 } = self;
962 let mut s = s.serialize_struct("HollowBatch", 5)?;
963 let () = s.serialize_field("lower", &desc.lower().elements())?;
964 let () = s.serialize_field("upper", &desc.upper().elements())?;
965 let () = s.serialize_field("since", &desc.since().elements())?;
966 let () = s.serialize_field("len", len)?;
967 let () = s.serialize_field("part_runs", &self.runs().collect::<Vec<_>>())?;
968 s.end()
969 }
970}
971
972impl<T: Ord> PartialOrd for HollowBatch<T> {
973 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
974 Some(self.cmp(other))
975 }
976}
977
978impl<T: Ord> Ord for HollowBatch<T> {
979 fn cmp(&self, other: &Self) -> Ordering {
980 let HollowBatch {
983 desc: self_desc,
984 parts: self_parts,
985 len: self_len,
986 run_splits: self_runs,
987 run_meta: self_run_meta,
988 } = self;
989 let HollowBatch {
990 desc: other_desc,
991 parts: other_parts,
992 len: other_len,
993 run_splits: other_runs,
994 run_meta: other_run_meta,
995 } = other;
996 (
997 self_desc.lower().elements(),
998 self_desc.upper().elements(),
999 self_desc.since().elements(),
1000 self_parts,
1001 self_len,
1002 self_runs,
1003 self_run_meta,
1004 )
1005 .cmp(&(
1006 other_desc.lower().elements(),
1007 other_desc.upper().elements(),
1008 other_desc.since().elements(),
1009 other_parts,
1010 other_len,
1011 other_runs,
1012 other_run_meta,
1013 ))
1014 }
1015}
1016
1017impl<T: Timestamp + Codec64 + Sync> HollowBatch<T> {
1018 pub(crate) fn part_stream<'a>(
1019 &'a self,
1020 shard_id: ShardId,
1021 blob: &'a dyn Blob,
1022 metrics: &'a Metrics,
1023 ) -> impl Stream<Item = Result<Cow<'a, BatchPart<T>>, MissingBlob>> + 'a {
1024 stream! {
1025 for part in &self.parts {
1026 for await part in part.part_stream(shard_id, blob, metrics) {
1027 yield part;
1028 }
1029 }
1030 }
1031 }
1032}
1033impl<T> HollowBatch<T> {
1034 pub(crate) fn new(
1041 desc: Description<T>,
1042 parts: Vec<RunPart<T>>,
1043 len: usize,
1044 run_meta: Vec<RunMeta>,
1045 run_splits: Vec<usize>,
1046 ) -> Self {
1047 debug_assert!(
1048 run_splits.is_strictly_sorted(),
1049 "run indices should be strictly increasing"
1050 );
1051 mz_ore::soft_assert_no_log!(
1052 run_splits.first().map_or(true, |i| *i > 0),
1053 "run indices should be positive"
1054 );
1055 mz_ore::soft_assert_no_log!(
1056 run_splits.last().map_or(true, |i| *i < parts.len()),
1057 "run indices should be valid indices into parts"
1058 );
1059 mz_ore::soft_assert_no_log!(
1060 parts.is_empty() || run_meta.len() == run_splits.len() + 1,
1061 "all metadata should correspond to a run"
1062 );
1063
1064 Self {
1065 desc,
1066 len,
1067 parts,
1068 run_splits,
1069 run_meta,
1070 }
1071 }
1072
1073 pub(crate) fn new_run(desc: Description<T>, parts: Vec<RunPart<T>>, len: usize) -> Self {
1075 let run_meta = if parts.is_empty() {
1076 vec![]
1077 } else {
1078 vec![RunMeta::default()]
1079 };
1080 Self {
1081 desc,
1082 len,
1083 parts,
1084 run_splits: vec![],
1085 run_meta,
1086 }
1087 }
1088
1089 #[cfg(test)]
1090 pub(crate) fn new_run_for_test(
1091 desc: Description<T>,
1092 parts: Vec<RunPart<T>>,
1093 len: usize,
1094 run_id: RunId,
1095 ) -> Self {
1096 let run_meta = if parts.is_empty() {
1097 vec![]
1098 } else {
1099 let mut meta = RunMeta::default();
1100 meta.id = Some(run_id);
1101 vec![meta]
1102 };
1103 Self {
1104 desc,
1105 len,
1106 parts,
1107 run_splits: vec![],
1108 run_meta,
1109 }
1110 }
1111
1112 pub(crate) fn empty(desc: Description<T>) -> Self {
1114 Self {
1115 desc,
1116 len: 0,
1117 parts: vec![],
1118 run_splits: vec![],
1119 run_meta: vec![],
1120 }
1121 }
1122
1123 pub(crate) fn runs(&self) -> impl Iterator<Item = (&RunMeta, &[RunPart<T>])> {
1124 let run_ends = self
1125 .run_splits
1126 .iter()
1127 .copied()
1128 .chain(std::iter::once(self.parts.len()));
1129 let run_metas = self.run_meta.iter();
1130 let run_parts = run_ends
1131 .scan(0, |start, end| {
1132 let range = *start..end;
1133 *start = end;
1134 Some(range)
1135 })
1136 .filter(|range| !range.is_empty())
1137 .map(|range| &self.parts[range]);
1138 run_metas.zip_eq(run_parts)
1139 }
1140
1141 pub(crate) fn inline_bytes(&self) -> usize {
1142 self.parts.iter().map(|x| x.inline_bytes()).sum()
1143 }
1144
1145 pub(crate) fn is_empty(&self) -> bool {
1146 self.parts.is_empty()
1147 }
1148
1149 pub(crate) fn part_count(&self) -> usize {
1150 self.parts.len()
1151 }
1152
1153 pub fn encoded_size_bytes(&self) -> usize {
1155 self.parts.iter().map(|p| p.encoded_size_bytes()).sum()
1156 }
1157}
1158
1159impl<T: Timestamp + TotalOrder> HollowBatch<T> {
1161 pub(crate) fn rewrite_ts(
1162 &mut self,
1163 frontier: &Antichain<T>,
1164 new_upper: Antichain<T>,
1165 ) -> Result<(), String> {
1166 if !PartialOrder::less_than(frontier, &new_upper) {
1167 return Err(format!(
1168 "rewrite frontier {:?} !< rewrite upper {:?}",
1169 frontier.elements(),
1170 new_upper.elements(),
1171 ));
1172 }
1173 if PartialOrder::less_than(&new_upper, self.desc.upper()) {
1174 return Err(format!(
1175 "rewrite upper {:?} < batch upper {:?}",
1176 new_upper.elements(),
1177 self.desc.upper().elements(),
1178 ));
1179 }
1180
1181 if PartialOrder::less_than(frontier, self.desc.lower()) {
1184 return Err(format!(
1185 "rewrite frontier {:?} < batch lower {:?}",
1186 frontier.elements(),
1187 self.desc.lower().elements(),
1188 ));
1189 }
1190 if self.desc.since() != &Antichain::from_elem(T::minimum()) {
1191 return Err(format!(
1192 "batch since {:?} != minimum antichain {:?}",
1193 self.desc.since().elements(),
1194 [T::minimum()],
1195 ));
1196 }
1197 let mut parts = Vec::with_capacity(self.parts.len());
1198 for part in self.parts.iter_mut() {
1199 let RunPart::Single(part) = &mut *part else {
1202 return Err(format!("unexpected rewrite of a hollow run: {part:?}"));
1203 };
1204 if let Some(ts_rewrite) = part.ts_rewrite()
1205 && PartialOrder::less_than(frontier, ts_rewrite)
1206 {
1207 return Err(format!(
1208 "rewrite frontier {:?} < batch rewrite {:?}",
1209 frontier.elements(),
1210 ts_rewrite.elements(),
1211 ));
1212 }
1213 parts.push(part);
1214 }
1215
1216 self.desc = Description::new(
1217 self.desc.lower().clone(),
1218 new_upper,
1219 self.desc.since().clone(),
1220 );
1221 for part in parts {
1222 match part {
1223 BatchPart::Hollow(part) => part.ts_rewrite = Some(frontier.clone()),
1224 BatchPart::Inline { ts_rewrite, .. } => *ts_rewrite = Some(frontier.clone()),
1225 }
1226 }
1227 Ok(())
1228 }
1229}
1230
1231impl<T: Ord> PartialOrd for HollowBatchPart<T> {
1232 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1233 Some(self.cmp(other))
1234 }
1235}
1236
1237impl<T: Ord> Ord for HollowBatchPart<T> {
1238 fn cmp(&self, other: &Self) -> Ordering {
1239 let HollowBatchPart {
1242 key: self_key,
1243 meta: self_meta,
1244 encoded_size_bytes: self_encoded_size_bytes,
1245 key_lower: self_key_lower,
1246 structured_key_lower: self_structured_key_lower,
1247 stats: self_stats,
1248 ts_rewrite: self_ts_rewrite,
1249 diffs_sum: self_diffs_sum,
1250 format: self_format,
1251 schema_id: self_schema_id,
1252 deprecated_schema_id: self_deprecated_schema_id,
1253 } = self;
1254 let HollowBatchPart {
1255 key: other_key,
1256 meta: other_meta,
1257 encoded_size_bytes: other_encoded_size_bytes,
1258 key_lower: other_key_lower,
1259 structured_key_lower: other_structured_key_lower,
1260 stats: other_stats,
1261 ts_rewrite: other_ts_rewrite,
1262 diffs_sum: other_diffs_sum,
1263 format: other_format,
1264 schema_id: other_schema_id,
1265 deprecated_schema_id: other_deprecated_schema_id,
1266 } = other;
1267 (
1268 self_key,
1269 self_meta,
1270 self_encoded_size_bytes,
1271 self_key_lower,
1272 self_structured_key_lower,
1273 self_stats,
1274 self_ts_rewrite.as_ref().map(|x| x.elements()),
1275 self_diffs_sum,
1276 self_format,
1277 self_schema_id,
1278 self_deprecated_schema_id,
1279 )
1280 .cmp(&(
1281 other_key,
1282 other_meta,
1283 other_encoded_size_bytes,
1284 other_key_lower,
1285 other_structured_key_lower,
1286 other_stats,
1287 other_ts_rewrite.as_ref().map(|x| x.elements()),
1288 other_diffs_sum,
1289 other_format,
1290 other_schema_id,
1291 other_deprecated_schema_id,
1292 ))
1293 }
1294}
1295
1296#[derive(Arbitrary, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
1298pub struct HollowRollup {
1299 pub key: PartialRollupKey,
1301 pub encoded_size_bytes: Option<usize>,
1303 pub finalized: bool,
1306}
1307
1308#[derive(Debug)]
1310pub enum HollowBlobRef<'a, T> {
1311 Batch(&'a HollowBatch<T>),
1312 Rollup(&'a HollowRollup),
1313}
1314
1315#[derive(
1317 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Arbitrary, Serialize
1318)]
1319pub struct ActiveRollup {
1320 pub seqno: SeqNo,
1321 pub start_ms: u64,
1322}
1323
1324#[derive(
1326 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Arbitrary, Serialize
1327)]
1328pub struct ActiveGc {
1329 pub seqno: SeqNo,
1330 pub start_ms: u64,
1331}
1332
1333#[derive(Debug)]
1338#[cfg_attr(any(test, debug_assertions), derive(PartialEq))]
1339pub struct NoOpStateTransition<T>(pub T);
1340
1341#[derive(Debug, Clone)]
1343#[cfg_attr(any(test, debug_assertions), derive(PartialEq))]
1344pub struct StateCollections<T> {
1345 pub(crate) version: Version,
1349
1350 pub(crate) last_gc_req: SeqNo,
1353
1354 pub(crate) rollups: BTreeMap<SeqNo, HollowRollup>,
1356
1357 pub(crate) active_rollup: Option<ActiveRollup>,
1359 pub(crate) active_gc: Option<ActiveGc>,
1361
1362 pub(crate) leased_readers: BTreeMap<LeasedReaderId, LeasedReaderState<T>>,
1363 pub(crate) critical_readers: BTreeMap<CriticalReaderId, CriticalReaderState<T>>,
1364 pub(crate) writers: BTreeMap<WriterId, WriterState<T>>,
1365 pub(crate) schemas: BTreeMap<SchemaId, EncodedSchemas>,
1366
1367 pub(crate) trace: Trace<T>,
1372}
1373
1374#[derive(Debug, Clone, Serialize, PartialEq)]
1390pub struct EncodedSchemas {
1391 pub key: Bytes,
1393 pub key_data_type: Bytes,
1396 pub val: Bytes,
1398 pub val_data_type: Bytes,
1401}
1402
1403impl EncodedSchemas {
1404 pub(crate) fn decode_data_type(buf: &[u8]) -> DataType {
1405 let proto = prost::Message::decode(buf).expect("valid ProtoDataType");
1406 DataType::from_proto(proto).expect("valid DataType")
1407 }
1408}
1409
1410#[derive(Debug)]
1411#[cfg_attr(test, derive(PartialEq))]
1412pub enum CompareAndAppendBreak<T> {
1413 AlreadyCommitted,
1414 Upper {
1415 shard_upper: Antichain<T>,
1416 writer_upper: Antichain<T>,
1417 },
1418 InvalidUsage(InvalidUsage<T>),
1419 InlineBackpressure,
1420}
1421
1422#[derive(Debug)]
1423#[cfg_attr(test, derive(PartialEq))]
1424pub enum SnapshotErr<T> {
1425 AsOfNotYetAvailable(SeqNo, Upper<T>),
1426 AsOfHistoricalDistinctionsLost(Since<T>),
1427}
1428
1429impl<T> StateCollections<T>
1430where
1431 T: Timestamp + Lattice + Codec64,
1432{
1433 pub fn add_rollup(
1434 &mut self,
1435 add_rollup: (SeqNo, &HollowRollup),
1436 ) -> ControlFlow<NoOpStateTransition<bool>, bool> {
1437 let (rollup_seqno, rollup) = add_rollup;
1438 let applied = match self.rollups.get(&rollup_seqno) {
1439 Some(x) => x.key == rollup.key,
1440 None => {
1441 if let Some(min_kept) = self.rollups.keys().next() {
1462 if rollup_seqno < *min_kept {
1463 return Continue(false);
1464 }
1465 }
1466 self.active_rollup = None;
1467 self.rollups.insert(rollup_seqno, rollup.to_owned());
1468 true
1469 }
1470 };
1471 Continue(applied)
1475 }
1476
1477 pub fn remove_rollups(
1478 &mut self,
1479 remove_rollups: &[(SeqNo, PartialRollupKey)],
1480 remove_finalized: bool,
1481 ) -> ControlFlow<NoOpStateTransition<Vec<SeqNo>>, Vec<SeqNo>> {
1482 if self.is_tombstone() {
1483 if !remove_finalized || !self.is_finalized() {
1484 return Break(NoOpStateTransition(vec![]));
1485 }
1486 return self.remove_finalized_rollups(remove_rollups);
1487 }
1488
1489 let active_gc_was_set = self.active_gc.take().is_some();
1492
1493 if remove_rollups.is_empty() {
1494 return if active_gc_was_set {
1495 Continue(vec![])
1496 } else {
1497 Break(NoOpStateTransition(vec![]))
1498 };
1499 }
1500
1501 let mut removed = vec![];
1502 for (seqno, key) in remove_rollups {
1503 let removed_key = self.rollups.remove(seqno);
1504 mz_ore::soft_assert_no_log!(
1505 removed_key.as_ref().map_or(true, |x| &x.key == key),
1506 "rollup at {} to be removed has key {:?} in state, but GC asked to remove {}",
1507 seqno,
1508 removed_key,
1509 key
1510 );
1511
1512 if removed_key.is_some() {
1513 removed.push(*seqno);
1514 }
1515 }
1516
1517 Continue(removed)
1518 }
1519
1520 fn remove_finalized_rollups(
1526 &mut self,
1527 remove_rollups: &[(SeqNo, PartialRollupKey)],
1528 ) -> ControlFlow<NoOpStateTransition<Vec<SeqNo>>, Vec<SeqNo>> {
1529 let latest = self.rollups.keys().next_back().copied();
1530 let mut removed = vec![];
1531 for (seqno, key) in remove_rollups {
1532 if Some(*seqno) == latest {
1533 mz_ore::soft_panic_or_log!("GC asked to remove a finalized shard's latest rollup");
1534 continue;
1535 }
1536 if self
1538 .rollups
1539 .get(seqno)
1540 .is_some_and(|x| &x.key == key && !x.finalized)
1541 {
1542 self.rollups.remove(seqno);
1543 removed.push(*seqno);
1544 }
1545 }
1546 if removed.is_empty() {
1547 return Break(NoOpStateTransition(vec![]));
1548 }
1549 self.active_gc = None;
1550 Continue(removed)
1551 }
1552
1553 pub fn register_leased_reader(
1554 &mut self,
1555 hostname: &str,
1556 reader_id: &LeasedReaderId,
1557 purpose: &str,
1558 seqno: SeqNo,
1559 lease_duration: Duration,
1560 heartbeat_timestamp_ms: u64,
1561 use_critical_since: bool,
1562 ) -> ControlFlow<
1563 NoOpStateTransition<(LeasedReaderState<T>, SeqNo)>,
1564 (LeasedReaderState<T>, SeqNo),
1565 > {
1566 let since = if use_critical_since {
1567 self.critical_since()
1568 .unwrap_or_else(|| self.trace.since().clone())
1569 } else {
1570 self.trace.since().clone()
1571 };
1572 let reader_state = LeasedReaderState {
1573 debug: HandleDebugState {
1574 hostname: hostname.to_owned(),
1575 purpose: purpose.to_owned(),
1576 },
1577 seqno,
1578 since,
1579 last_heartbeat_timestamp_ms: heartbeat_timestamp_ms,
1580 lease_duration_ms: u64::try_from(lease_duration.as_millis())
1581 .expect("lease duration as millis should fit within u64"),
1582 };
1583
1584 if self.is_tombstone() {
1589 return Break(NoOpStateTransition((reader_state, self.seqno_since(seqno))));
1590 }
1591
1592 self.leased_readers
1594 .insert(reader_id.clone(), reader_state.clone());
1595 Continue((reader_state, self.seqno_since(seqno)))
1596 }
1597
1598 pub fn register_critical_reader(
1599 &mut self,
1600 hostname: &str,
1601 reader_id: &CriticalReaderId,
1602 opaque: Opaque,
1603 purpose: &str,
1604 ) -> ControlFlow<NoOpStateTransition<CriticalReaderState<T>>, CriticalReaderState<T>> {
1605 let state = CriticalReaderState {
1606 debug: HandleDebugState {
1607 hostname: hostname.to_owned(),
1608 purpose: purpose.to_owned(),
1609 },
1610 since: self.trace.since().clone(),
1611 opaque,
1612 };
1613
1614 if self.is_tombstone() {
1619 return Break(NoOpStateTransition(state));
1620 }
1621
1622 let state = match self.critical_readers.get_mut(reader_id) {
1623 Some(existing_state) => {
1624 existing_state.debug = state.debug;
1625 existing_state.clone()
1626 }
1627 None => {
1628 self.critical_readers
1629 .insert(reader_id.clone(), state.clone());
1630 state
1631 }
1632 };
1633 Continue(state)
1634 }
1635
1636 pub fn register_schema<K: Codec, V: Codec>(
1637 &mut self,
1638 key_schema: &K::Schema,
1639 val_schema: &V::Schema,
1640 ) -> ControlFlow<NoOpStateTransition<Option<SchemaId>>, Option<SchemaId>> {
1641 fn encode_data_type(data_type: &DataType) -> Bytes {
1642 let proto = data_type.into_proto();
1643 prost::Message::encode_to_vec(&proto).into()
1644 }
1645
1646 let existing_id = self.schemas.iter().rev().find(|(_, x)| {
1658 K::decode_schema(&x.key) == *key_schema && V::decode_schema(&x.val) == *val_schema
1659 });
1660 match existing_id {
1661 Some((schema_id, _)) => {
1662 Break(NoOpStateTransition(Some(*schema_id)))
1667 }
1668 None if self.is_tombstone() => {
1669 Break(NoOpStateTransition(None))
1671 }
1672 None if self.schemas.is_empty() => {
1673 let id = SchemaId(self.schemas.len());
1677 let key_data_type = mz_persist_types::columnar::data_type::<K>(key_schema)
1678 .expect("valid key schema");
1679 let val_data_type = mz_persist_types::columnar::data_type::<V>(val_schema)
1680 .expect("valid val schema");
1681 let prev = self.schemas.insert(
1682 id,
1683 EncodedSchemas {
1684 key: K::encode_schema(key_schema),
1685 key_data_type: encode_data_type(&key_data_type),
1686 val: V::encode_schema(val_schema),
1687 val_data_type: encode_data_type(&val_data_type),
1688 },
1689 );
1690 assert_eq!(prev, None);
1691 Continue(Some(id))
1692 }
1693 None => {
1694 info!(
1695 "register_schemas got {:?} expected {:?}",
1696 key_schema,
1697 self.schemas
1698 .iter()
1699 .map(|(id, x)| (id, K::decode_schema(&x.key)))
1700 .collect::<Vec<_>>()
1701 );
1702 Break(NoOpStateTransition(None))
1705 }
1706 }
1707 }
1708
1709 pub fn compare_and_evolve_schema<K: Codec, V: Codec>(
1710 &mut self,
1711 expected: SchemaId,
1712 key_schema: &K::Schema,
1713 val_schema: &V::Schema,
1714 ) -> ControlFlow<NoOpStateTransition<CaESchema<K, V>>, CaESchema<K, V>> {
1715 fn data_type<T>(schema: &impl Schema<T>) -> DataType {
1716 let array = Schema::encoder(schema).expect("valid schema").finish();
1720 Array::data_type(&array).clone()
1721 }
1722
1723 let (current_id, current) = self
1724 .schemas
1725 .last_key_value()
1726 .expect("all shards have a schema");
1727
1728 let current_key = K::decode_schema(¤t.key);
1729 let current_key_dt = EncodedSchemas::decode_data_type(¤t.key_data_type);
1730 let current_val = V::decode_schema(¤t.val);
1731 let current_val_dt = EncodedSchemas::decode_data_type(¤t.val_data_type);
1732
1733 let key_dt = data_type(key_schema);
1734 let val_dt = data_type(val_schema);
1735
1736 if current_key == *key_schema
1746 && current_key_dt == key_dt
1747 && current_val == *val_schema
1748 && current_val_dt == val_dt
1749 {
1750 return Break(NoOpStateTransition(CaESchema::Ok(*current_id)));
1751 }
1752
1753 if *current_id != expected {
1754 return Break(NoOpStateTransition(CaESchema::ExpectedMismatch {
1755 schema_id: *current_id,
1756 key: current_key,
1757 val: current_val,
1758 }));
1759 }
1760
1761 let key_fn = backward_compatible(¤t_key_dt, &key_dt);
1762 let val_fn = backward_compatible(¤t_val_dt, &val_dt);
1763 let (Some(key_fn), Some(val_fn)) = (key_fn, val_fn) else {
1764 return Break(NoOpStateTransition(CaESchema::Incompatible));
1765 };
1766 if key_fn.contains_drop() || val_fn.contains_drop() {
1770 return Break(NoOpStateTransition(CaESchema::Incompatible));
1771 }
1772
1773 let id = SchemaId(self.schemas.len());
1777 self.schemas.insert(
1778 id,
1779 EncodedSchemas {
1780 key: K::encode_schema(key_schema),
1781 key_data_type: prost::Message::encode_to_vec(&key_dt.into_proto()).into(),
1782 val: V::encode_schema(val_schema),
1783 val_data_type: prost::Message::encode_to_vec(&val_dt.into_proto()).into(),
1784 },
1785 );
1786 Continue(CaESchema::Ok(id))
1787 }
1788
1789 pub fn compare_and_append(
1790 &mut self,
1791 batch: &HollowBatch<T>,
1792 writer_id: &WriterId,
1793 heartbeat_timestamp_ms: u64,
1794 lease_duration_ms: u64,
1795 idempotency_token: &IdempotencyToken,
1796 debug_info: &HandleDebugState,
1797 inline_writes_total_max_bytes: usize,
1798 claim_compaction_percent: usize,
1799 claim_compaction_min_version: Option<&Version>,
1800 ) -> ControlFlow<CompareAndAppendBreak<T>, Vec<FueledMergeReq<T>>> {
1801 if self.is_tombstone() {
1806 assert_eq!(self.trace.upper(), &Antichain::new());
1807 return Break(CompareAndAppendBreak::Upper {
1808 shard_upper: Antichain::new(),
1809 writer_upper: Antichain::new(),
1814 });
1815 }
1816
1817 let writer_state = self
1818 .writers
1819 .entry(writer_id.clone())
1820 .or_insert_with(|| WriterState {
1821 last_heartbeat_timestamp_ms: heartbeat_timestamp_ms,
1822 lease_duration_ms,
1823 most_recent_write_token: IdempotencyToken::SENTINEL,
1824 most_recent_write_upper: Antichain::from_elem(T::minimum()),
1825 debug: debug_info.clone(),
1826 });
1827
1828 if PartialOrder::less_than(batch.desc.upper(), batch.desc.lower()) {
1829 return Break(CompareAndAppendBreak::InvalidUsage(
1830 InvalidUsage::InvalidBounds {
1831 lower: batch.desc.lower().clone(),
1832 upper: batch.desc.upper().clone(),
1833 },
1834 ));
1835 }
1836
1837 if batch.desc.upper() == batch.desc.lower() && !batch.is_empty() {
1840 return Break(CompareAndAppendBreak::InvalidUsage(
1841 InvalidUsage::InvalidEmptyTimeInterval {
1842 lower: batch.desc.lower().clone(),
1843 upper: batch.desc.upper().clone(),
1844 keys: batch
1845 .parts
1846 .iter()
1847 .map(|x| x.printable_name().to_owned())
1848 .collect(),
1849 },
1850 ));
1851 }
1852
1853 if idempotency_token == &writer_state.most_recent_write_token {
1854 assert_eq!(batch.desc.upper(), &writer_state.most_recent_write_upper);
1859 assert!(
1860 PartialOrder::less_equal(batch.desc.upper(), self.trace.upper()),
1861 "{:?} vs {:?}",
1862 batch.desc.upper(),
1863 self.trace.upper()
1864 );
1865 return Break(CompareAndAppendBreak::AlreadyCommitted);
1866 }
1867
1868 let shard_upper = self.trace.upper();
1869 if shard_upper != batch.desc.lower() {
1870 return Break(CompareAndAppendBreak::Upper {
1871 shard_upper: shard_upper.clone(),
1872 writer_upper: writer_state.most_recent_write_upper.clone(),
1873 });
1874 }
1875
1876 let new_inline_bytes = batch.inline_bytes();
1877 if new_inline_bytes > 0 {
1878 let mut existing_inline_bytes = 0;
1879 self.trace
1880 .map_batches(|x| existing_inline_bytes += x.inline_bytes());
1881 if existing_inline_bytes + new_inline_bytes >= inline_writes_total_max_bytes {
1885 return Break(CompareAndAppendBreak::InlineBackpressure);
1886 }
1887 }
1888
1889 let mut merge_reqs = if batch.desc.upper() != batch.desc.lower() {
1890 self.trace.push_batch(batch.clone())
1891 } else {
1892 Vec::new()
1893 };
1894
1895 let all_empty_reqs = merge_reqs
1898 .iter()
1899 .all(|req| req.inputs.iter().all(|b| b.batch.is_empty()));
1900 if all_empty_reqs && !batch.is_empty() {
1901 let mut reqs_to_take = claim_compaction_percent / 100;
1902 if (usize::cast_from(idempotency_token.hashed()) % 100)
1903 < (claim_compaction_percent % 100)
1904 {
1905 reqs_to_take += 1;
1906 }
1907 let threshold_ms = heartbeat_timestamp_ms.saturating_sub(lease_duration_ms);
1908 let min_writer = claim_compaction_min_version.map(WriterKey::for_version);
1909 merge_reqs.extend(
1910 self.trace
1913 .fueled_merge_reqs_before_ms(threshold_ms, min_writer)
1914 .take(reqs_to_take),
1915 )
1916 }
1917
1918 for req in &merge_reqs {
1919 self.trace.claim_compaction(
1920 req.id,
1921 ActiveCompaction {
1922 start_ms: heartbeat_timestamp_ms,
1923 },
1924 )
1925 }
1926
1927 mz_ore::soft_assert_eq_no_log!(self.trace.upper(), batch.desc.upper());
1928 writer_state.most_recent_write_token = idempotency_token.clone();
1929 assert!(
1931 PartialOrder::less_equal(&writer_state.most_recent_write_upper, batch.desc.upper()),
1932 "{:?} vs {:?}",
1933 writer_state.most_recent_write_upper,
1934 batch.desc.upper()
1935 );
1936 writer_state
1937 .most_recent_write_upper
1938 .clone_from(batch.desc.upper());
1939
1940 writer_state.last_heartbeat_timestamp_ms = std::cmp::max(
1942 heartbeat_timestamp_ms,
1943 writer_state.last_heartbeat_timestamp_ms,
1944 );
1945
1946 Continue(merge_reqs)
1947 }
1948
1949 pub fn apply_merge_res<D: Codec64 + Monoid + PartialEq>(
1950 &mut self,
1951 res: &FueledMergeRes<T>,
1952 metrics: &ColumnarMetrics,
1953 ) -> ControlFlow<NoOpStateTransition<ApplyMergeResult>, ApplyMergeResult> {
1954 if self.is_tombstone() {
1959 return Break(NoOpStateTransition(ApplyMergeResult::NotAppliedNoMatch));
1960 }
1961
1962 let apply_merge_result = self.trace.apply_merge_res_checked::<D>(res, metrics);
1963 Continue(apply_merge_result)
1964 }
1965
1966 pub fn spine_exert(
1967 &mut self,
1968 fuel: usize,
1969 ) -> ControlFlow<NoOpStateTransition<Vec<FueledMergeReq<T>>>, Vec<FueledMergeReq<T>>> {
1970 let (merge_reqs, did_work) = self.trace.exert(fuel);
1971 if did_work {
1972 Continue(merge_reqs)
1973 } else {
1974 assert!(merge_reqs.is_empty());
1975 Break(NoOpStateTransition(Vec::new()))
1978 }
1979 }
1980
1981 pub fn downgrade_since(
1982 &mut self,
1983 reader_id: &LeasedReaderId,
1984 seqno: SeqNo,
1985 outstanding_seqno: SeqNo,
1986 new_since: &Antichain<T>,
1987 heartbeat_timestamp_ms: u64,
1988 ) -> ControlFlow<NoOpStateTransition<Since<T>>, Since<T>> {
1989 if self.is_tombstone() {
1994 return Break(NoOpStateTransition(Since(Antichain::new())));
1995 }
1996
1997 let Some(reader_state) = self.leased_reader(reader_id) else {
2000 tracing::warn!(
2001 "Leased reader {reader_id} was expired due to inactivity. Did the machine go to sleep?",
2002 );
2003 return Break(NoOpStateTransition(Since(Antichain::new())));
2004 };
2005
2006 reader_state.last_heartbeat_timestamp_ms = std::cmp::max(
2009 heartbeat_timestamp_ms,
2010 reader_state.last_heartbeat_timestamp_ms,
2011 );
2012
2013 let seqno = {
2014 assert!(
2015 outstanding_seqno >= reader_state.seqno,
2016 "SeqNos cannot go backward; however, oldest leased SeqNo ({:?}) \
2017 is behind current reader_state ({:?})",
2018 outstanding_seqno,
2019 reader_state.seqno,
2020 );
2021 std::cmp::min(outstanding_seqno, seqno)
2022 };
2023
2024 reader_state.seqno = seqno;
2025
2026 let reader_current_since = if PartialOrder::less_than(&reader_state.since, new_since) {
2027 reader_state.since.clone_from(new_since);
2028 self.update_since();
2029 new_since.clone()
2030 } else {
2031 reader_state.since.clone()
2034 };
2035
2036 Continue(Since(reader_current_since))
2037 }
2038
2039 pub fn compare_and_downgrade_since(
2040 &mut self,
2041 reader_id: &CriticalReaderId,
2042 expected_opaque: &Opaque,
2043 (new_opaque, new_since): (&Opaque, &Antichain<T>),
2044 ) -> ControlFlow<
2045 NoOpStateTransition<Result<Since<T>, (Opaque, Since<T>)>>,
2046 Result<Since<T>, (Opaque, Since<T>)>,
2047 > {
2048 if self.is_tombstone() {
2053 return Break(NoOpStateTransition(Ok(Since(Antichain::new()))));
2057 }
2058
2059 let reader_state = self.critical_reader(reader_id);
2060
2061 if reader_state.opaque != *expected_opaque {
2062 return Continue(Err((
2065 reader_state.opaque.clone(),
2066 Since(reader_state.since.clone()),
2067 )));
2068 }
2069
2070 reader_state.opaque = new_opaque.clone();
2071 if PartialOrder::less_equal(&reader_state.since, new_since) {
2072 reader_state.since.clone_from(new_since);
2073 self.update_since();
2074 Continue(Ok(Since(new_since.clone())))
2075 } else {
2076 Continue(Ok(Since(reader_state.since.clone())))
2080 }
2081 }
2082
2083 pub fn expire_leased_reader(
2084 &mut self,
2085 reader_id: &LeasedReaderId,
2086 ) -> ControlFlow<NoOpStateTransition<bool>, bool> {
2087 if self.is_tombstone() {
2092 return Break(NoOpStateTransition(false));
2093 }
2094
2095 let existed = self.leased_readers.remove(reader_id).is_some();
2096 if existed {
2097 }
2111 Continue(existed)
2114 }
2115
2116 pub fn expire_critical_reader(
2117 &mut self,
2118 reader_id: &CriticalReaderId,
2119 ) -> ControlFlow<NoOpStateTransition<bool>, bool> {
2120 if self.is_tombstone() {
2125 return Break(NoOpStateTransition(false));
2126 }
2127
2128 let existed = self.critical_readers.remove(reader_id).is_some();
2129 if existed {
2130 }
2144 Continue(existed)
2148 }
2149
2150 pub fn expire_writer(
2151 &mut self,
2152 writer_id: &WriterId,
2153 ) -> ControlFlow<NoOpStateTransition<bool>, bool> {
2154 if self.is_tombstone() {
2159 return Break(NoOpStateTransition(false));
2160 }
2161
2162 let existed = self.writers.remove(writer_id).is_some();
2163 Continue(existed)
2167 }
2168
2169 fn leased_reader(&mut self, id: &LeasedReaderId) -> Option<&mut LeasedReaderState<T>> {
2170 self.leased_readers.get_mut(id)
2171 }
2172
2173 fn critical_reader(&mut self, id: &CriticalReaderId) -> &mut CriticalReaderState<T> {
2174 self.critical_readers
2175 .get_mut(id)
2176 .unwrap_or_else(|| {
2177 panic!(
2178 "Unknown CriticalReaderId({}). It was either never registered, or has been manually expired.",
2179 id
2180 )
2181 })
2182 }
2183
2184 fn critical_since(&self) -> Option<Antichain<T>> {
2185 let mut critical_sinces = self.critical_readers.values().map(|r| &r.since);
2186 let mut since = critical_sinces.next().cloned()?;
2187 for s in critical_sinces {
2188 since.meet_assign(s);
2189 }
2190 Some(since)
2191 }
2192
2193 fn update_since(&mut self) {
2194 let mut sinces_iter = self
2195 .leased_readers
2196 .values()
2197 .map(|x| &x.since)
2198 .chain(self.critical_readers.values().map(|x| &x.since));
2199 let mut since = match sinces_iter.next() {
2200 Some(since) => since.clone(),
2201 None => {
2202 return;
2205 }
2206 };
2207 while let Some(s) = sinces_iter.next() {
2208 since.meet_assign(s);
2209 }
2210 self.trace.downgrade_since(&since);
2211 }
2212
2213 fn seqno_since(&self, seqno: SeqNo) -> SeqNo {
2214 let mut seqno_since = seqno;
2215 for cap in self.leased_readers.values() {
2216 seqno_since = std::cmp::min(seqno_since, cap.seqno);
2217 }
2218 seqno_since
2220 }
2221
2222 fn tombstone_batch() -> HollowBatch<T> {
2223 HollowBatch::empty(Description::new(
2224 Antichain::from_elem(T::minimum()),
2225 Antichain::new(),
2226 Antichain::new(),
2227 ))
2228 }
2229
2230 pub(crate) fn is_tombstone(&self) -> bool {
2231 self.trace.upper().is_empty()
2232 && self.trace.since().is_empty()
2233 && self.writers.is_empty()
2234 && self.leased_readers.is_empty()
2235 && self.critical_readers.is_empty()
2236 }
2237
2238 pub(crate) fn is_finalized(&self) -> bool {
2240 self.is_tombstone() && self.is_single_empty_batch()
2241 }
2242
2243 pub(crate) fn is_single_empty_batch(&self) -> bool {
2244 let mut batch_count = 0;
2245 let mut is_empty = true;
2246 self.trace.map_batches(|b| {
2247 batch_count += 1;
2248 is_empty &= b.is_empty()
2249 });
2250 batch_count <= 1 && is_empty
2251 }
2252
2253 pub fn become_tombstone_and_shrink(&mut self) -> ControlFlow<NoOpStateTransition<()>, ()> {
2254 assert_eq!(self.trace.upper(), &Antichain::new());
2255 assert_eq!(self.trace.since(), &Antichain::new());
2256
2257 let was_tombstone = self.is_tombstone();
2260
2261 self.writers.clear();
2263 self.leased_readers.clear();
2264 self.critical_readers.clear();
2265
2266 mz_ore::soft_assert_no_log!(self.is_tombstone());
2267
2268 let mut to_replace = None;
2277 let mut batch_count = 0;
2278 self.trace.map_batches(|b| {
2279 batch_count += 1;
2280 if !b.is_empty() && to_replace.is_none() {
2281 to_replace = Some(b.desc.clone());
2282 }
2283 });
2284 if let Some(desc) = to_replace {
2285 let result = self.trace.apply_tombstone_merge(&desc);
2289 assert!(
2290 result.matched(),
2291 "merge with a matching desc should always match"
2292 );
2293 Continue(())
2294 } else if batch_count > 1 {
2295 let mut new_trace = Trace::default();
2300 new_trace.downgrade_since(&Antichain::new());
2301 let merge_reqs = new_trace.push_batch(Self::tombstone_batch());
2302 assert_eq!(merge_reqs, Vec::new());
2303 self.trace = new_trace;
2304 Continue(())
2305 } else if !was_tombstone {
2306 Continue(())
2309 } else {
2310 Break(NoOpStateTransition(()))
2313 }
2314 }
2315}
2316
2317#[derive(Debug)]
2319#[cfg_attr(any(test, debug_assertions), derive(Clone, PartialEq))]
2320pub struct State<T> {
2321 pub(crate) shard_id: ShardId,
2322
2323 pub(crate) seqno: SeqNo,
2324 pub(crate) walltime_ms: u64,
2327 pub(crate) hostname: String,
2330 pub(crate) collections: StateCollections<T>,
2331}
2332
2333pub struct TypedState<K, V, T, D> {
2336 pub(crate) state: State<T>,
2337
2338 pub(crate) _phantom: PhantomData<fn() -> (K, V, D)>,
2346}
2347
2348impl<K, V, T: Clone, D> TypedState<K, V, T, D> {
2349 #[cfg(any(test, debug_assertions))]
2350 pub(crate) fn clone(&self, hostname: String) -> Self {
2351 TypedState {
2352 state: State {
2353 shard_id: self.shard_id.clone(),
2354 seqno: self.seqno.clone(),
2355 walltime_ms: self.walltime_ms,
2356 hostname,
2357 collections: self.collections.clone(),
2358 },
2359 _phantom: PhantomData,
2360 }
2361 }
2362
2363 pub(crate) fn clone_for_rollup(&self) -> Self {
2364 TypedState {
2365 state: State {
2366 shard_id: self.shard_id.clone(),
2367 seqno: self.seqno.clone(),
2368 walltime_ms: self.walltime_ms,
2369 hostname: self.hostname.clone(),
2370 collections: self.collections.clone(),
2371 },
2372 _phantom: PhantomData,
2373 }
2374 }
2375}
2376
2377impl<K, V, T: Debug, D> Debug for TypedState<K, V, T, D> {
2378 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2379 let TypedState { state, _phantom } = self;
2382 f.debug_struct("TypedState").field("state", state).finish()
2383 }
2384}
2385
2386#[cfg(any(test, debug_assertions))]
2388impl<K, V, T: PartialEq, D> PartialEq for TypedState<K, V, T, D> {
2389 fn eq(&self, other: &Self) -> bool {
2390 let TypedState {
2393 state: self_state,
2394 _phantom,
2395 } = self;
2396 let TypedState {
2397 state: other_state,
2398 _phantom,
2399 } = other;
2400 self_state == other_state
2401 }
2402}
2403
2404impl<K, V, T, D> Deref for TypedState<K, V, T, D> {
2405 type Target = State<T>;
2406
2407 fn deref(&self) -> &Self::Target {
2408 &self.state
2409 }
2410}
2411
2412impl<K, V, T, D> DerefMut for TypedState<K, V, T, D> {
2413 fn deref_mut(&mut self) -> &mut Self::Target {
2414 &mut self.state
2415 }
2416}
2417
2418impl<K, V, T, D> TypedState<K, V, T, D>
2419where
2420 K: Codec,
2421 V: Codec,
2422 T: Timestamp + Lattice + Codec64,
2423 D: Codec64,
2424{
2425 pub fn new(
2426 applier_version: Version,
2427 shard_id: ShardId,
2428 hostname: String,
2429 walltime_ms: u64,
2430 ) -> Self {
2431 let state = State {
2432 shard_id,
2433 seqno: SeqNo::minimum(),
2434 walltime_ms,
2435 hostname,
2436 collections: StateCollections {
2437 version: applier_version,
2438 last_gc_req: SeqNo::minimum(),
2439 rollups: BTreeMap::new(),
2440 active_rollup: None,
2441 active_gc: None,
2442 leased_readers: BTreeMap::new(),
2443 critical_readers: BTreeMap::new(),
2444 writers: BTreeMap::new(),
2445 schemas: BTreeMap::new(),
2446 trace: Trace::default(),
2447 },
2448 };
2449 TypedState {
2450 state,
2451 _phantom: PhantomData,
2452 }
2453 }
2454
2455 pub fn clone_apply<R, E, WorkFn>(
2456 &self,
2457 cfg: &PersistConfig,
2458 work_fn: &mut WorkFn,
2459 ) -> ControlFlow<E, (R, Self)>
2460 where
2461 WorkFn: FnMut(SeqNo, &PersistConfig, &mut StateCollections<T>) -> ControlFlow<E, R>,
2462 {
2463 let mut new_state = State {
2465 shard_id: self.shard_id,
2466 seqno: self.seqno.next(),
2467 walltime_ms: (cfg.now)(),
2468 hostname: cfg.hostname.clone(),
2469 collections: self.collections.clone(),
2470 };
2471
2472 if new_state.walltime_ms <= self.walltime_ms {
2475 new_state.walltime_ms = self.walltime_ms + 1;
2476 }
2477
2478 let work_ret = work_fn(new_state.seqno, cfg, &mut new_state.collections)?;
2479 let new_state = TypedState {
2480 state: new_state,
2481 _phantom: PhantomData,
2482 };
2483 Continue((work_ret, new_state))
2484 }
2485}
2486
2487#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2489pub(crate) enum FinalizedGcStep {
2490 WriteRollup,
2491 Gc(SeqNo),
2493}
2494
2495#[derive(Copy, Clone, Debug)]
2496pub struct GcConfig {
2497 pub use_active_gc: bool,
2498 pub fallback_threshold_ms: u64,
2499 pub min_versions: usize,
2500 pub max_versions: usize,
2501 pub remove_finalized_rollups: bool,
2503}
2504
2505impl<T> State<T>
2506where
2507 T: Timestamp + Lattice + Codec64,
2508{
2509 pub fn shard_id(&self) -> ShardId {
2510 self.shard_id
2511 }
2512
2513 pub fn seqno(&self) -> SeqNo {
2514 self.seqno
2515 }
2516
2517 pub fn since(&self) -> &Antichain<T> {
2518 self.collections.trace.since()
2519 }
2520
2521 pub fn upper(&self) -> &Antichain<T> {
2522 self.collections.trace.upper()
2523 }
2524
2525 pub fn spine_batch_count(&self) -> usize {
2526 self.collections.trace.num_spine_batches()
2527 }
2528
2529 pub fn size_metrics(&self) -> StateSizeMetrics {
2530 let mut ret = StateSizeMetrics::default();
2531 self.blobs().for_each(|x| match x {
2532 HollowBlobRef::Batch(x) => {
2533 ret.hollow_batch_count += 1;
2534 ret.batch_part_count += x.part_count();
2535 ret.num_updates += x.len;
2536
2537 let batch_size = x.encoded_size_bytes();
2538 for x in x.parts.iter() {
2539 if x.is_inline() {
2540 ret.inline_part_count += 1;
2541 }
2542 }
2543 ret.largest_batch_bytes = std::cmp::max(ret.largest_batch_bytes, batch_size);
2544 ret.state_batches_bytes += batch_size;
2545 }
2546 HollowBlobRef::Rollup(x) => {
2547 ret.state_rollup_count += 1;
2548 ret.state_rollups_bytes += x.encoded_size_bytes.unwrap_or_default()
2549 }
2550 });
2551 ret
2552 }
2553
2554 pub fn latest_rollup(&self) -> (&SeqNo, &HollowRollup) {
2555 self.collections
2558 .rollups
2559 .iter()
2560 .rev()
2561 .next()
2562 .expect("State should have at least one rollup if seqno > minimum")
2563 }
2564
2565 pub(crate) fn seqno_since(&self) -> SeqNo {
2566 self.collections.seqno_since(self.seqno)
2567 }
2568
2569 fn tombstone_needs_rollup(&self) -> bool {
2573 let (latest, _) = self.latest_rollup();
2574 self.collections.is_tombstone() && latest.next() < self.seqno
2575 }
2576
2577 pub(crate) fn finalized_gc_step(
2584 &self,
2585 earliest_live: SeqNo,
2586 max_versions: usize,
2587 remove_finalized_rollups: bool,
2588 ) -> Option<FinalizedGcStep> {
2589 if self.tombstone_needs_rollup() {
2592 return Some(FinalizedGcStep::WriteRollup);
2593 }
2594 let (latest, _) = self.latest_rollup();
2595 let mut later_rollups = self.collections.rollups.range(earliest_live.next()..);
2600 let next_rollup = later_rollups.next().map(|(seqno, _)| *seqno);
2601 let capped = SeqNo(earliest_live.0.saturating_add(u64::cast_from(max_versions)));
2602 let new_seqno_since = self.seqno.min(capped.max(next_rollup.unwrap_or(capped)));
2603 if earliest_live < *latest {
2606 return Some(FinalizedGcStep::Gc(new_seqno_since));
2607 }
2608 let mut old_rollups = self.collections.rollups.values().rev().skip(1);
2612 if remove_finalized_rollups && old_rollups.any(|x| !x.finalized) {
2613 return Some(FinalizedGcStep::Gc(new_seqno_since));
2614 }
2615 None
2616 }
2617
2618 pub fn maybe_gc(&mut self, is_write: bool, now: u64, cfg: GcConfig) -> Option<GcReq> {
2630 let GcConfig {
2631 use_active_gc,
2632 fallback_threshold_ms,
2633 min_versions,
2634 max_versions,
2635 remove_finalized_rollups,
2636 } = cfg;
2637 let gc_threshold = if use_active_gc {
2641 u64::cast_from(min_versions)
2642 } else {
2643 std::cmp::max(
2644 1,
2645 u64::cast_from(self.seqno.0.next_power_of_two().trailing_zeros()),
2646 )
2647 };
2648 let new_seqno_since = self.seqno_since();
2649 let gc_until_seqno = new_seqno_since.min(SeqNo(
2652 self.collections
2653 .last_gc_req
2654 .0
2655 .saturating_add(u64::cast_from(max_versions)),
2656 ));
2657 let should_gc = new_seqno_since
2658 .0
2659 .saturating_sub(self.collections.last_gc_req.0)
2660 >= gc_threshold;
2661
2662 let should_gc = if use_active_gc && !should_gc {
2665 match self.collections.active_gc {
2666 Some(active_gc) => now.saturating_sub(active_gc.start_ms) > fallback_threshold_ms,
2667 None => false,
2668 }
2669 } else {
2670 should_gc
2671 };
2672 let should_gc = should_gc && (is_write || self.collections.writers.is_empty());
2675 let tombstone_needs_gc = self.collections.is_tombstone();
2680 let should_gc = should_gc || (tombstone_needs_gc && !remove_finalized_rollups);
2681 let should_gc = if use_active_gc {
2682 should_gc
2686 && match self.collections.active_gc {
2687 Some(active) => now.saturating_sub(active.start_ms) > fallback_threshold_ms,
2688 None => true,
2689 }
2690 } else {
2691 should_gc
2692 };
2693 let should_gc = should_gc || (tombstone_needs_gc && remove_finalized_rollups);
2697 if should_gc {
2698 self.collections.last_gc_req = gc_until_seqno;
2699 Some(GcReq {
2700 shard_id: self.shard_id,
2701 new_seqno_since: gc_until_seqno,
2702 })
2703 } else {
2704 None
2705 }
2706 }
2707
2708 pub fn seqnos_held(&self) -> usize {
2710 usize::cast_from(self.seqno.0.saturating_sub(self.seqno_since().0))
2711 }
2712
2713 pub fn expire_at(&mut self, walltime_ms: EpochMillis) -> ExpiryMetrics {
2715 let mut metrics = ExpiryMetrics::default();
2716 let shard_id = self.shard_id();
2717 self.collections.leased_readers.retain(|id, state| {
2718 let retain = state.last_heartbeat_timestamp_ms + state.lease_duration_ms >= walltime_ms;
2719 if !retain {
2720 info!(
2721 "Force expiring reader {id} ({}) of shard {shard_id} due to inactivity",
2722 state.debug.purpose
2723 );
2724 metrics.readers_expired += 1;
2725 }
2726 retain
2727 });
2728 self.collections.writers.retain(|id, state| {
2730 let retain =
2731 (state.last_heartbeat_timestamp_ms + state.lease_duration_ms) >= walltime_ms;
2732 if !retain {
2733 info!(
2734 "Force expiring writer {id} ({}) of shard {shard_id} due to inactivity",
2735 state.debug.purpose
2736 );
2737 metrics.writers_expired += 1;
2738 }
2739 retain
2740 });
2741 metrics
2742 }
2743
2744 pub fn snapshot(&self, as_of: &Antichain<T>) -> Result<Vec<HollowBatch<T>>, SnapshotErr<T>> {
2748 if PartialOrder::less_than(as_of, self.collections.trace.since()) {
2749 return Err(SnapshotErr::AsOfHistoricalDistinctionsLost(Since(
2750 self.collections.trace.since().clone(),
2751 )));
2752 }
2753 let upper = self.collections.trace.upper();
2754 if PartialOrder::less_equal(upper, as_of) {
2755 return Err(SnapshotErr::AsOfNotYetAvailable(
2756 self.seqno,
2757 Upper(upper.clone()),
2758 ));
2759 }
2760
2761 let batches = self
2762 .collections
2763 .trace
2764 .batches()
2765 .filter(|b| !PartialOrder::less_than(as_of, b.desc.lower()))
2766 .cloned()
2767 .collect();
2768 Ok(batches)
2769 }
2770
2771 pub fn verify_listen(&self, as_of: &Antichain<T>) -> Result<(), Since<T>> {
2773 if PartialOrder::less_than(as_of, self.collections.trace.since()) {
2774 return Err(Since(self.collections.trace.since().clone()));
2775 }
2776 Ok(())
2777 }
2778
2779 pub fn next_listen_batch(&self, frontier: &Antichain<T>) -> Result<HollowBatch<T>, SeqNo> {
2780 self.collections
2783 .trace
2784 .batches()
2785 .find(|b| {
2786 PartialOrder::less_equal(b.desc.lower(), frontier)
2787 && PartialOrder::less_than(frontier, b.desc.upper())
2788 })
2789 .cloned()
2790 .ok_or(self.seqno)
2791 }
2792
2793 pub fn active_rollup(&self) -> Option<ActiveRollup> {
2794 self.collections.active_rollup
2795 }
2796
2797 pub fn need_rollup(
2798 &self,
2799 threshold: usize,
2800 use_active_rollup: bool,
2801 fallback_threshold_ms: u64,
2802 now: u64,
2803 ) -> Option<SeqNo> {
2804 let (latest_rollup_seqno, _) = self.latest_rollup();
2805
2806 if self.tombstone_needs_rollup() {
2812 return Some(self.seqno);
2813 }
2814
2815 let seqnos_since_last_rollup = self.seqno.0.saturating_sub(latest_rollup_seqno.0);
2816
2817 if use_active_rollup {
2818 if seqnos_since_last_rollup > u64::cast_from(threshold) {
2824 match self.active_rollup() {
2825 Some(active_rollup) => {
2826 if now.saturating_sub(active_rollup.start_ms) > fallback_threshold_ms {
2827 return Some(self.seqno);
2828 }
2829 }
2830 None => {
2831 return Some(self.seqno);
2832 }
2833 }
2834 }
2835 } else {
2836 if seqnos_since_last_rollup > 0
2840 && seqnos_since_last_rollup % u64::cast_from(threshold) == 0
2841 {
2842 return Some(self.seqno);
2843 }
2844
2845 if seqnos_since_last_rollup
2848 > u64::cast_from(
2849 threshold * PersistConfig::DEFAULT_FALLBACK_ROLLUP_THRESHOLD_MULTIPLIER,
2850 )
2851 {
2852 return Some(self.seqno);
2853 }
2854 }
2855
2856 None
2857 }
2858
2859 pub(crate) fn blobs(&self) -> impl Iterator<Item = HollowBlobRef<'_, T>> {
2860 let batches = self.collections.trace.batches().map(HollowBlobRef::Batch);
2861 let rollups = self.collections.rollups.values().map(HollowBlobRef::Rollup);
2862 batches.chain(rollups)
2863 }
2864}
2865
2866fn serialize_part_bytes<S: Serializer>(val: &[u8], s: S) -> Result<S::Ok, S::Error> {
2867 let val = hex::encode(val);
2868 val.serialize(s)
2869}
2870
2871fn serialize_lazy_proto<S: Serializer, T: prost::Message + Default>(
2872 val: &Option<LazyProto<T>>,
2873 s: S,
2874) -> Result<S::Ok, S::Error> {
2875 val.as_ref()
2876 .map(|lazy| hex::encode(&lazy.into_proto()))
2877 .serialize(s)
2878}
2879
2880fn serialize_part_stats<S: Serializer>(
2881 val: &Option<LazyPartStats>,
2882 s: S,
2883) -> Result<S::Ok, S::Error> {
2884 let stats = val.as_ref().and_then(|x| match x.try_decode() {
2890 Ok(stats) => Some(stats.key),
2891 Err(err) => {
2892 tracing::warn!("undecodable part stats, reporting as absent: {err}");
2893 None
2894 }
2895 });
2896 stats.serialize(s)
2897}
2898
2899fn serialize_diffs_sum<S: Serializer>(val: &Option<[u8; 8]>, s: S) -> Result<S::Ok, S::Error> {
2900 let val = val.map(i64::decode);
2902 val.serialize(s)
2903}
2904
2905impl<T: Serialize + Timestamp + Lattice> Serialize for State<T> {
2911 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2912 let State {
2913 shard_id,
2914 seqno,
2915 walltime_ms,
2916 hostname,
2917 collections:
2918 StateCollections {
2919 version: applier_version,
2920 last_gc_req,
2921 rollups,
2922 active_rollup,
2923 active_gc,
2924 leased_readers,
2925 critical_readers,
2926 writers,
2927 schemas,
2928 trace,
2929 },
2930 } = self;
2931 let mut s = s.serialize_struct("State", 13)?;
2932 let () = s.serialize_field("applier_version", &applier_version.to_string())?;
2933 let () = s.serialize_field("shard_id", shard_id)?;
2934 let () = s.serialize_field("seqno", seqno)?;
2935 let () = s.serialize_field("walltime_ms", walltime_ms)?;
2936 let () = s.serialize_field("hostname", hostname)?;
2937 let () = s.serialize_field("last_gc_req", last_gc_req)?;
2938 let () = s.serialize_field("rollups", rollups)?;
2939 let () = s.serialize_field("active_rollup", active_rollup)?;
2940 let () = s.serialize_field("active_gc", active_gc)?;
2941 let () = s.serialize_field("leased_readers", leased_readers)?;
2942 let () = s.serialize_field("critical_readers", critical_readers)?;
2943 let () = s.serialize_field("writers", writers)?;
2944 let () = s.serialize_field("schemas", schemas)?;
2945 let () = s.serialize_field("since", &trace.since().elements())?;
2946 let () = s.serialize_field("upper", &trace.upper().elements())?;
2947 let trace = trace.flatten();
2948 let () = s.serialize_field("batches", &trace.legacy_batches.keys().collect::<Vec<_>>())?;
2949 let () = s.serialize_field("hollow_batches", &trace.hollow_batches)?;
2950 let () = s.serialize_field("spine_batches", &trace.spine_batches)?;
2951 let () = s.serialize_field("merges", &trace.merges)?;
2952 s.end()
2953 }
2954}
2955
2956#[derive(Debug, Default)]
2957pub struct StateSizeMetrics {
2958 pub hollow_batch_count: usize,
2959 pub batch_part_count: usize,
2960 pub num_updates: usize,
2961 pub largest_batch_bytes: usize,
2962 pub state_batches_bytes: usize,
2963 pub state_rollups_bytes: usize,
2964 pub state_rollup_count: usize,
2965 pub inline_part_count: usize,
2966}
2967
2968#[derive(Default)]
2969pub struct ExpiryMetrics {
2970 pub(crate) readers_expired: usize,
2971 pub(crate) writers_expired: usize,
2972}
2973
2974#[derive(Debug, Clone, PartialEq)]
2976pub struct Since<T>(pub Antichain<T>);
2977
2978#[derive(Debug, PartialEq)]
2980pub struct Upper<T>(pub Antichain<T>);
2981
2982#[cfg(test)]
2983pub(crate) mod tests {
2984 use std::ops::Range;
2985 use std::str::FromStr;
2986
2987 use bytes::Bytes;
2988 use mz_build_info::DUMMY_BUILD_INFO;
2989 use mz_dyncfg::ConfigUpdates;
2990 use mz_ore::now::SYSTEM_TIME;
2991 use mz_ore::{assert_err, assert_none, assert_ok};
2992 use mz_proto::RustType;
2993 use proptest::prelude::*;
2994 use proptest::strategy::ValueTree;
2995
2996 use crate::InvalidUsage::{InvalidBounds, InvalidEmptyTimeInterval};
2997 use crate::cache::PersistClientCache;
2998 use crate::internal::encoding::any_some_lazy_part_stats;
2999 use crate::internal::paths::RollupId;
3000 use crate::internal::trace::tests::any_trace;
3001 use crate::tests::new_test_client_cache;
3002 use crate::{Diagnostics, PersistLocation};
3003
3004 use super::*;
3005
3006 const LEASE_DURATION_MS: u64 = 900 * 1000;
3007 fn debug_state() -> HandleDebugState {
3008 HandleDebugState {
3009 hostname: "debug".to_owned(),
3010 purpose: "finding the bugs".to_owned(),
3011 }
3012 }
3013
3014 pub fn any_hollow_batch_with_exact_runs<T: Arbitrary + Timestamp>(
3015 num_runs: usize,
3016 ) -> impl Strategy<Value = HollowBatch<T>> {
3017 (
3018 any::<T>(),
3019 any::<T>(),
3020 any::<T>(),
3021 proptest::collection::vec(any_run_part::<T>(), num_runs + 1..20),
3022 any::<usize>(),
3023 )
3024 .prop_map(move |(t0, t1, since, parts, len)| {
3025 let (lower, upper) = if t0 <= t1 {
3026 (Antichain::from_elem(t0), Antichain::from_elem(t1))
3027 } else {
3028 (Antichain::from_elem(t1), Antichain::from_elem(t0))
3029 };
3030 let since = Antichain::from_elem(since);
3031
3032 let run_splits = (1..num_runs)
3033 .map(|i| i * parts.len() / num_runs)
3034 .collect::<Vec<_>>();
3035
3036 let run_meta = (0..num_runs)
3037 .map(|_| {
3038 let mut meta = RunMeta::default();
3039 meta.id = Some(RunId::new());
3040 meta
3041 })
3042 .collect::<Vec<_>>();
3043
3044 HollowBatch::new(
3045 Description::new(lower, upper, since),
3046 parts,
3047 len % 10,
3048 run_meta,
3049 run_splits,
3050 )
3051 })
3052 }
3053
3054 pub fn any_hollow_batch<T: Arbitrary + Timestamp>() -> impl Strategy<Value = HollowBatch<T>> {
3055 Strategy::prop_map(
3056 (
3057 any::<T>(),
3058 any::<T>(),
3059 any::<T>(),
3060 proptest::collection::vec(any_run_part::<T>(), 0..20),
3061 any::<usize>(),
3062 0..=10usize,
3063 proptest::collection::vec(any::<RunId>(), 10),
3064 ),
3065 |(t0, t1, since, parts, len, num_runs, run_ids)| {
3066 let (lower, upper) = if t0 <= t1 {
3067 (Antichain::from_elem(t0), Antichain::from_elem(t1))
3068 } else {
3069 (Antichain::from_elem(t1), Antichain::from_elem(t0))
3070 };
3071 let since = Antichain::from_elem(since);
3072 if num_runs > 0 && parts.len() > 2 && num_runs < parts.len() {
3073 let run_splits = (1..num_runs)
3074 .map(|i| i * parts.len() / num_runs)
3075 .collect::<Vec<_>>();
3076
3077 let run_meta = (0..num_runs)
3078 .enumerate()
3079 .map(|(i, _)| {
3080 let mut meta = RunMeta::default();
3081 meta.id = Some(run_ids[i]);
3082 meta
3083 })
3084 .collect::<Vec<_>>();
3085
3086 HollowBatch::new(
3087 Description::new(lower, upper, since),
3088 parts,
3089 len % 10,
3090 run_meta,
3091 run_splits,
3092 )
3093 } else {
3094 HollowBatch::new_run_for_test(
3095 Description::new(lower, upper, since),
3096 parts,
3097 len % 10,
3098 run_ids[0],
3099 )
3100 }
3101 },
3102 )
3103 }
3104
3105 pub fn any_batch_part<T: Arbitrary + Timestamp>() -> impl Strategy<Value = BatchPart<T>> {
3106 Strategy::prop_map(
3107 (
3108 any::<bool>(),
3109 any_hollow_batch_part(),
3110 any::<Option<T>>(),
3111 any::<Option<SchemaId>>(),
3112 any::<Option<SchemaId>>(),
3113 ),
3114 |(is_hollow, hollow, ts_rewrite, schema_id, deprecated_schema_id)| {
3115 if is_hollow {
3116 BatchPart::Hollow(hollow)
3117 } else {
3118 let updates = LazyInlineBatchPart::from_proto(Bytes::new()).unwrap();
3119 let ts_rewrite = ts_rewrite.map(Antichain::from_elem);
3120 BatchPart::Inline {
3121 updates,
3122 ts_rewrite,
3123 schema_id,
3124 deprecated_schema_id,
3125 }
3126 }
3127 },
3128 )
3129 }
3130
3131 pub fn any_run_part<T: Arbitrary + Timestamp>() -> impl Strategy<Value = RunPart<T>> {
3132 Strategy::prop_map(any_batch_part(), |part| RunPart::Single(part))
3133 }
3134
3135 pub fn any_hollow_batch_part<T: Arbitrary + Timestamp>()
3136 -> impl Strategy<Value = HollowBatchPart<T>> {
3137 Strategy::prop_map(
3138 (
3139 any::<PartialBatchKey>(),
3140 any::<usize>(),
3141 any::<Vec<u8>>(),
3142 any_some_lazy_part_stats(),
3143 any::<Option<T>>(),
3144 any::<[u8; 8]>(),
3145 any::<Option<BatchColumnarFormat>>(),
3146 any::<Option<SchemaId>>(),
3147 any::<Option<SchemaId>>(),
3148 ),
3149 |(
3150 key,
3151 encoded_size_bytes,
3152 key_lower,
3153 stats,
3154 ts_rewrite,
3155 diffs_sum,
3156 format,
3157 schema_id,
3158 deprecated_schema_id,
3159 )| {
3160 HollowBatchPart {
3161 key,
3162 meta: Default::default(),
3163 encoded_size_bytes,
3164 key_lower,
3165 structured_key_lower: None,
3166 stats,
3167 ts_rewrite: ts_rewrite.map(Antichain::from_elem),
3168 diffs_sum: Some(diffs_sum),
3169 format,
3170 schema_id,
3171 deprecated_schema_id,
3172 }
3173 },
3174 )
3175 }
3176
3177 pub fn any_leased_reader_state<T: Arbitrary>() -> impl Strategy<Value = LeasedReaderState<T>> {
3178 Strategy::prop_map(
3179 (
3180 any::<SeqNo>(),
3181 any::<Option<T>>(),
3182 any::<u64>(),
3183 any::<u64>(),
3184 any::<HandleDebugState>(),
3185 ),
3186 |(seqno, since, last_heartbeat_timestamp_ms, mut lease_duration_ms, debug)| {
3187 if lease_duration_ms == 0 {
3191 lease_duration_ms += 1;
3192 }
3193 LeasedReaderState {
3194 seqno,
3195 since: since.map_or_else(Antichain::new, Antichain::from_elem),
3196 last_heartbeat_timestamp_ms,
3197 lease_duration_ms,
3198 debug,
3199 }
3200 },
3201 )
3202 }
3203
3204 pub fn any_critical_reader_state<T>() -> impl Strategy<Value = CriticalReaderState<T>>
3205 where
3206 T: Arbitrary,
3207 {
3208 Strategy::prop_map(
3209 (
3210 any::<Option<T>>(),
3211 any::<Opaque>(),
3212 any::<HandleDebugState>(),
3213 ),
3214 |(since, opaque, debug)| CriticalReaderState {
3215 since: since.map_or_else(Antichain::new, Antichain::from_elem),
3216 opaque,
3217 debug,
3218 },
3219 )
3220 }
3221
3222 pub fn any_writer_state<T: Arbitrary>() -> impl Strategy<Value = WriterState<T>> {
3223 Strategy::prop_map(
3224 (
3225 any::<u64>(),
3226 any::<u64>(),
3227 any::<IdempotencyToken>(),
3228 any::<Option<T>>(),
3229 any::<HandleDebugState>(),
3230 ),
3231 |(
3232 last_heartbeat_timestamp_ms,
3233 lease_duration_ms,
3234 most_recent_write_token,
3235 most_recent_write_upper,
3236 debug,
3237 )| WriterState {
3238 last_heartbeat_timestamp_ms,
3239 lease_duration_ms,
3240 most_recent_write_token,
3241 most_recent_write_upper: most_recent_write_upper
3242 .map_or_else(Antichain::new, Antichain::from_elem),
3243 debug,
3244 },
3245 )
3246 }
3247
3248 pub fn any_encoded_schemas() -> impl Strategy<Value = EncodedSchemas> {
3249 Strategy::prop_map(
3250 (
3251 any::<Vec<u8>>(),
3252 any::<Vec<u8>>(),
3253 any::<Vec<u8>>(),
3254 any::<Vec<u8>>(),
3255 ),
3256 |(key, key_data_type, val, val_data_type)| EncodedSchemas {
3257 key: Bytes::from(key),
3258 key_data_type: Bytes::from(key_data_type),
3259 val: Bytes::from(val),
3260 val_data_type: Bytes::from(val_data_type),
3261 },
3262 )
3263 }
3264
3265 pub fn any_state<T: Arbitrary + Timestamp + Lattice>(
3266 num_trace_batches: Range<usize>,
3267 ) -> impl Strategy<Value = State<T>> {
3268 let part1 = (
3269 any::<ShardId>(),
3270 any::<SeqNo>(),
3271 any::<u64>(),
3272 any::<String>(),
3273 any::<SeqNo>(),
3274 proptest::collection::btree_map(any::<SeqNo>(), any::<HollowRollup>(), 1..3),
3275 proptest::option::of(any::<ActiveRollup>()),
3276 );
3277
3278 let part2 = (
3279 proptest::option::of(any::<ActiveGc>()),
3280 proptest::collection::btree_map(
3281 any::<LeasedReaderId>(),
3282 any_leased_reader_state::<T>(),
3283 1..3,
3284 ),
3285 proptest::collection::btree_map(
3286 any::<CriticalReaderId>(),
3287 any_critical_reader_state::<T>(),
3288 1..3,
3289 ),
3290 proptest::collection::btree_map(any::<WriterId>(), any_writer_state::<T>(), 0..3),
3291 proptest::collection::btree_map(any::<SchemaId>(), any_encoded_schemas(), 0..3),
3292 any_trace::<T>(num_trace_batches),
3293 );
3294
3295 (part1, part2).prop_map(
3296 |(
3297 (shard_id, seqno, walltime_ms, hostname, last_gc_req, rollups, active_rollup),
3298 (active_gc, leased_readers, critical_readers, writers, schemas, trace),
3299 )| State {
3300 shard_id,
3301 seqno,
3302 walltime_ms,
3303 hostname,
3304 collections: StateCollections {
3305 version: Version::new(1, 2, 3),
3306 last_gc_req,
3307 rollups,
3308 active_rollup,
3309 active_gc,
3310 leased_readers,
3311 critical_readers,
3312 writers,
3313 schemas,
3314 trace,
3315 },
3316 },
3317 )
3318 }
3319
3320 pub(crate) fn hollow<T: Timestamp>(
3321 lower: T,
3322 upper: T,
3323 keys: &[&str],
3324 len: usize,
3325 ) -> HollowBatch<T> {
3326 HollowBatch::new_run(
3327 Description::new(
3328 Antichain::from_elem(lower),
3329 Antichain::from_elem(upper),
3330 Antichain::from_elem(T::minimum()),
3331 ),
3332 keys.iter()
3333 .map(|x| {
3334 RunPart::Single(BatchPart::Hollow(HollowBatchPart {
3335 key: PartialBatchKey((*x).to_owned()),
3336 meta: Default::default(),
3337 encoded_size_bytes: 0,
3338 key_lower: vec![],
3339 structured_key_lower: None,
3340 stats: None,
3341 ts_rewrite: None,
3342 diffs_sum: None,
3343 format: None,
3344 schema_id: None,
3345 deprecated_schema_id: None,
3346 }))
3347 })
3348 .collect(),
3349 len,
3350 )
3351 }
3352
3353 #[mz_ore::test]
3354 fn rewrite_ts_hollow_run() {
3355 let mut batch = hollow(0u64, 1, &["a"], 2);
3356 batch.parts.push(RunPart::Many(HollowRunRef {
3357 key: PartialBatchKey("b".to_owned()),
3358 hollow_bytes: 0,
3359 max_part_bytes: 0,
3360 key_lower: vec![],
3361 structured_key_lower: None,
3362 diffs_sum: None,
3363 _phantom_data: PhantomData,
3364 }));
3365 let before = batch.clone();
3366
3367 let res = batch.rewrite_ts(&Antichain::from_elem(2), Antichain::from_elem(3));
3368 assert_err!(res);
3369 assert_eq!(batch, before);
3370 }
3371
3372 #[mz_ore::test]
3373 fn downgrade_since() {
3374 let mut state = TypedState::<(), (), u64, i64>::new(
3375 DUMMY_BUILD_INFO.semver_version(),
3376 ShardId::new(),
3377 "".to_owned(),
3378 0,
3379 );
3380 let reader = LeasedReaderId::new();
3381 let seqno = SeqNo::minimum();
3382 let now = SYSTEM_TIME.clone();
3383 let _ = state.collections.register_leased_reader(
3384 "",
3385 &reader,
3386 "",
3387 seqno,
3388 Duration::from_secs(10),
3389 now(),
3390 false,
3391 );
3392
3393 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(0));
3395
3396 assert_eq!(
3398 state.collections.downgrade_since(
3399 &reader,
3400 seqno,
3401 seqno,
3402 &Antichain::from_elem(2),
3403 now()
3404 ),
3405 Continue(Since(Antichain::from_elem(2)))
3406 );
3407 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3408 assert_eq!(
3410 state.collections.downgrade_since(
3411 &reader,
3412 seqno,
3413 seqno,
3414 &Antichain::from_elem(2),
3415 now()
3416 ),
3417 Continue(Since(Antichain::from_elem(2)))
3418 );
3419 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3420 assert_eq!(
3422 state.collections.downgrade_since(
3423 &reader,
3424 seqno,
3425 seqno,
3426 &Antichain::from_elem(1),
3427 now()
3428 ),
3429 Continue(Since(Antichain::from_elem(2)))
3430 );
3431 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3432
3433 let reader2 = LeasedReaderId::new();
3435 let _ = state.collections.register_leased_reader(
3436 "",
3437 &reader2,
3438 "",
3439 seqno,
3440 Duration::from_secs(10),
3441 now(),
3442 false,
3443 );
3444
3445 assert_eq!(
3447 state.collections.downgrade_since(
3448 &reader2,
3449 seqno,
3450 seqno,
3451 &Antichain::from_elem(3),
3452 now()
3453 ),
3454 Continue(Since(Antichain::from_elem(3)))
3455 );
3456 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3457 assert_eq!(
3459 state.collections.downgrade_since(
3460 &reader,
3461 seqno,
3462 seqno,
3463 &Antichain::from_elem(5),
3464 now()
3465 ),
3466 Continue(Since(Antichain::from_elem(5)))
3467 );
3468 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(3));
3469
3470 assert_eq!(
3472 state.collections.expire_leased_reader(&reader),
3473 Continue(true)
3474 );
3475 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(3));
3476
3477 let reader3 = LeasedReaderId::new();
3479 let _ = state.collections.register_leased_reader(
3480 "",
3481 &reader3,
3482 "",
3483 seqno,
3484 Duration::from_secs(10),
3485 now(),
3486 false,
3487 );
3488
3489 assert_eq!(
3491 state.collections.downgrade_since(
3492 &reader3,
3493 seqno,
3494 seqno,
3495 &Antichain::from_elem(10),
3496 now()
3497 ),
3498 Continue(Since(Antichain::from_elem(10)))
3499 );
3500 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(3));
3501
3502 assert_eq!(
3504 state.collections.expire_leased_reader(&reader2),
3505 Continue(true)
3506 );
3507 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(3));
3512
3513 assert_eq!(
3515 state.collections.expire_leased_reader(&reader3),
3516 Continue(true)
3517 );
3518 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(3));
3523 }
3524
3525 #[mz_ore::test]
3526 fn compare_and_downgrade_since() {
3527 let mut state = TypedState::<(), (), u64, i64>::new(
3528 DUMMY_BUILD_INFO.semver_version(),
3529 ShardId::new(),
3530 "".to_owned(),
3531 0,
3532 );
3533 let reader = CriticalReaderId::new();
3534 let _ = state
3535 .collections
3536 .register_critical_reader("", &reader, Opaque::encode(&0u64), "");
3537
3538 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(0));
3540 assert_eq!(
3542 state
3543 .collections
3544 .critical_reader(&reader)
3545 .opaque
3546 .decode::<u64>(),
3547 u64::MIN
3548 );
3549
3550 assert_eq!(
3552 state.collections.compare_and_downgrade_since(
3553 &reader,
3554 &Opaque::encode(&0u64),
3555 (&Opaque::encode(&1u64), &Antichain::from_elem(2)),
3556 ),
3557 Continue(Ok(Since(Antichain::from_elem(2))))
3558 );
3559 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3560 assert_eq!(
3561 state
3562 .collections
3563 .critical_reader(&reader)
3564 .opaque
3565 .decode::<u64>(),
3566 1
3567 );
3568 assert_eq!(
3570 state.collections.compare_and_downgrade_since(
3571 &reader,
3572 &Opaque::encode(&1u64),
3573 (&Opaque::encode(&2u64), &Antichain::from_elem(2)),
3574 ),
3575 Continue(Ok(Since(Antichain::from_elem(2))))
3576 );
3577 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3578 assert_eq!(
3579 state
3580 .collections
3581 .critical_reader(&reader)
3582 .opaque
3583 .decode::<u64>(),
3584 2
3585 );
3586 assert_eq!(
3588 state.collections.compare_and_downgrade_since(
3589 &reader,
3590 &Opaque::encode(&2u64),
3591 (&Opaque::encode(&3u64), &Antichain::from_elem(1)),
3592 ),
3593 Continue(Ok(Since(Antichain::from_elem(2))))
3594 );
3595 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3596 assert_eq!(
3597 state
3598 .collections
3599 .critical_reader(&reader)
3600 .opaque
3601 .decode::<u64>(),
3602 3
3603 );
3604 }
3605
3606 #[mz_ore::test]
3607 fn compare_and_append() {
3608 let state = &mut TypedState::<String, String, u64, i64>::new(
3609 DUMMY_BUILD_INFO.semver_version(),
3610 ShardId::new(),
3611 "".to_owned(),
3612 0,
3613 )
3614 .collections;
3615
3616 let writer_id = WriterId::new();
3617 let now = SYSTEM_TIME.clone();
3618
3619 assert_eq!(state.trace.num_spine_batches(), 0);
3621 assert_eq!(state.trace.num_hollow_batches(), 0);
3622 assert_eq!(state.trace.num_updates(), 0);
3623
3624 assert_eq!(
3626 state.compare_and_append(
3627 &hollow(1, 2, &["key1"], 1),
3628 &writer_id,
3629 now(),
3630 LEASE_DURATION_MS,
3631 &IdempotencyToken::new(),
3632 &debug_state(),
3633 0,
3634 100,
3635 None
3636 ),
3637 Break(CompareAndAppendBreak::Upper {
3638 shard_upper: Antichain::from_elem(0),
3639 writer_upper: Antichain::from_elem(0)
3640 })
3641 );
3642
3643 assert!(
3645 state
3646 .compare_and_append(
3647 &hollow(0, 5, &[], 0),
3648 &writer_id,
3649 now(),
3650 LEASE_DURATION_MS,
3651 &IdempotencyToken::new(),
3652 &debug_state(),
3653 0,
3654 100,
3655 None
3656 )
3657 .is_continue()
3658 );
3659
3660 assert_eq!(
3662 state.compare_and_append(
3663 &hollow(5, 4, &["key1"], 1),
3664 &writer_id,
3665 now(),
3666 LEASE_DURATION_MS,
3667 &IdempotencyToken::new(),
3668 &debug_state(),
3669 0,
3670 100,
3671 None
3672 ),
3673 Break(CompareAndAppendBreak::InvalidUsage(InvalidBounds {
3674 lower: Antichain::from_elem(5),
3675 upper: Antichain::from_elem(4)
3676 }))
3677 );
3678
3679 assert_eq!(
3681 state.compare_and_append(
3682 &hollow(5, 5, &["key1"], 1),
3683 &writer_id,
3684 now(),
3685 LEASE_DURATION_MS,
3686 &IdempotencyToken::new(),
3687 &debug_state(),
3688 0,
3689 100,
3690 None
3691 ),
3692 Break(CompareAndAppendBreak::InvalidUsage(
3693 InvalidEmptyTimeInterval {
3694 lower: Antichain::from_elem(5),
3695 upper: Antichain::from_elem(5),
3696 keys: vec!["key1".to_owned()],
3697 }
3698 ))
3699 );
3700
3701 assert!(
3703 state
3704 .compare_and_append(
3705 &hollow(5, 5, &[], 0),
3706 &writer_id,
3707 now(),
3708 LEASE_DURATION_MS,
3709 &IdempotencyToken::new(),
3710 &debug_state(),
3711 0,
3712 100,
3713 None
3714 )
3715 .is_continue()
3716 );
3717 }
3718
3719 #[mz_ore::test]
3720 fn snapshot() {
3721 let now = SYSTEM_TIME.clone();
3722
3723 let mut state = TypedState::<String, String, u64, i64>::new(
3724 DUMMY_BUILD_INFO.semver_version(),
3725 ShardId::new(),
3726 "".to_owned(),
3727 0,
3728 );
3729 assert_eq!(
3731 state.snapshot(&Antichain::from_elem(0)),
3732 Err(SnapshotErr::AsOfNotYetAvailable(
3733 SeqNo(0),
3734 Upper(Antichain::from_elem(0))
3735 ))
3736 );
3737
3738 assert_eq!(
3740 state.snapshot(&Antichain::from_elem(5)),
3741 Err(SnapshotErr::AsOfNotYetAvailable(
3742 SeqNo(0),
3743 Upper(Antichain::from_elem(0))
3744 ))
3745 );
3746
3747 let writer_id = WriterId::new();
3748
3749 assert!(
3751 state
3752 .collections
3753 .compare_and_append(
3754 &hollow(0, 5, &["key1"], 1),
3755 &writer_id,
3756 now(),
3757 LEASE_DURATION_MS,
3758 &IdempotencyToken::new(),
3759 &debug_state(),
3760 0,
3761 100,
3762 None
3763 )
3764 .is_continue()
3765 );
3766
3767 assert_eq!(
3769 state.snapshot(&Antichain::from_elem(0)),
3770 Ok(vec![hollow(0, 5, &["key1"], 1)])
3771 );
3772
3773 assert_eq!(
3775 state.snapshot(&Antichain::from_elem(4)),
3776 Ok(vec![hollow(0, 5, &["key1"], 1)])
3777 );
3778
3779 assert_eq!(
3781 state.snapshot(&Antichain::from_elem(5)),
3782 Err(SnapshotErr::AsOfNotYetAvailable(
3783 SeqNo(0),
3784 Upper(Antichain::from_elem(5))
3785 ))
3786 );
3787 assert_eq!(
3788 state.snapshot(&Antichain::from_elem(6)),
3789 Err(SnapshotErr::AsOfNotYetAvailable(
3790 SeqNo(0),
3791 Upper(Antichain::from_elem(5))
3792 ))
3793 );
3794
3795 let reader = LeasedReaderId::new();
3796 let _ = state.collections.register_leased_reader(
3798 "",
3799 &reader,
3800 "",
3801 SeqNo::minimum(),
3802 Duration::from_secs(10),
3803 now(),
3804 false,
3805 );
3806 assert_eq!(
3807 state.collections.downgrade_since(
3808 &reader,
3809 SeqNo::minimum(),
3810 SeqNo::minimum(),
3811 &Antichain::from_elem(2),
3812 now()
3813 ),
3814 Continue(Since(Antichain::from_elem(2)))
3815 );
3816 assert_eq!(state.collections.trace.since(), &Antichain::from_elem(2));
3817 assert_eq!(
3819 state.snapshot(&Antichain::from_elem(1)),
3820 Err(SnapshotErr::AsOfHistoricalDistinctionsLost(Since(
3821 Antichain::from_elem(2)
3822 )))
3823 );
3824
3825 assert!(
3827 state
3828 .collections
3829 .compare_and_append(
3830 &hollow(5, 10, &[], 0),
3831 &writer_id,
3832 now(),
3833 LEASE_DURATION_MS,
3834 &IdempotencyToken::new(),
3835 &debug_state(),
3836 0,
3837 100,
3838 None
3839 )
3840 .is_continue()
3841 );
3842
3843 assert_eq!(
3845 state.snapshot(&Antichain::from_elem(7)),
3846 Ok(vec![hollow(0, 5, &["key1"], 1), hollow(5, 10, &[], 0)])
3847 );
3848
3849 assert_eq!(
3851 state.snapshot(&Antichain::from_elem(10)),
3852 Err(SnapshotErr::AsOfNotYetAvailable(
3853 SeqNo(0),
3854 Upper(Antichain::from_elem(10))
3855 ))
3856 );
3857
3858 assert!(
3860 state
3861 .collections
3862 .compare_and_append(
3863 &hollow(10, 15, &["key2"], 1),
3864 &writer_id,
3865 now(),
3866 LEASE_DURATION_MS,
3867 &IdempotencyToken::new(),
3868 &debug_state(),
3869 0,
3870 100,
3871 None
3872 )
3873 .is_continue()
3874 );
3875
3876 assert_eq!(
3879 state.snapshot(&Antichain::from_elem(9)),
3880 Ok(vec![hollow(0, 5, &["key1"], 1), hollow(5, 10, &[], 0)])
3881 );
3882
3883 assert_eq!(
3885 state.snapshot(&Antichain::from_elem(10)),
3886 Ok(vec![
3887 hollow(0, 5, &["key1"], 1),
3888 hollow(5, 10, &[], 0),
3889 hollow(10, 15, &["key2"], 1)
3890 ])
3891 );
3892
3893 assert_eq!(
3894 state.snapshot(&Antichain::from_elem(11)),
3895 Ok(vec![
3896 hollow(0, 5, &["key1"], 1),
3897 hollow(5, 10, &[], 0),
3898 hollow(10, 15, &["key2"], 1)
3899 ])
3900 );
3901 }
3902
3903 #[mz_ore::test]
3904 fn next_listen_batch() {
3905 let mut state = TypedState::<String, String, u64, i64>::new(
3906 DUMMY_BUILD_INFO.semver_version(),
3907 ShardId::new(),
3908 "".to_owned(),
3909 0,
3910 );
3911
3912 assert_eq!(
3915 state.next_listen_batch(&Antichain::from_elem(0)),
3916 Err(SeqNo(0))
3917 );
3918 assert_eq!(state.next_listen_batch(&Antichain::new()), Err(SeqNo(0)));
3919
3920 let writer_id = WriterId::new();
3921 let now = SYSTEM_TIME.clone();
3922
3923 assert!(
3925 state
3926 .collections
3927 .compare_and_append(
3928 &hollow(0, 5, &["key1"], 1),
3929 &writer_id,
3930 now(),
3931 LEASE_DURATION_MS,
3932 &IdempotencyToken::new(),
3933 &debug_state(),
3934 0,
3935 100,
3936 None
3937 )
3938 .is_continue()
3939 );
3940 assert!(
3941 state
3942 .collections
3943 .compare_and_append(
3944 &hollow(5, 10, &["key2"], 1),
3945 &writer_id,
3946 now(),
3947 LEASE_DURATION_MS,
3948 &IdempotencyToken::new(),
3949 &debug_state(),
3950 0,
3951 100,
3952 None
3953 )
3954 .is_continue()
3955 );
3956
3957 for t in 0..=4 {
3959 assert_eq!(
3960 state.next_listen_batch(&Antichain::from_elem(t)),
3961 Ok(hollow(0, 5, &["key1"], 1))
3962 );
3963 }
3964
3965 for t in 5..=9 {
3967 assert_eq!(
3968 state.next_listen_batch(&Antichain::from_elem(t)),
3969 Ok(hollow(5, 10, &["key2"], 1))
3970 );
3971 }
3972
3973 assert_eq!(
3975 state.next_listen_batch(&Antichain::from_elem(10)),
3976 Err(SeqNo(0))
3977 );
3978
3979 assert_eq!(state.next_listen_batch(&Antichain::new()), Err(SeqNo(0)));
3982 }
3983
3984 #[mz_ore::test]
3985 fn expire_writer() {
3986 let mut state = TypedState::<String, String, u64, i64>::new(
3987 DUMMY_BUILD_INFO.semver_version(),
3988 ShardId::new(),
3989 "".to_owned(),
3990 0,
3991 );
3992 let now = SYSTEM_TIME.clone();
3993
3994 let writer_id_one = WriterId::new();
3995
3996 let writer_id_two = WriterId::new();
3997
3998 assert!(
4000 state
4001 .collections
4002 .compare_and_append(
4003 &hollow(0, 2, &["key1"], 1),
4004 &writer_id_one,
4005 now(),
4006 LEASE_DURATION_MS,
4007 &IdempotencyToken::new(),
4008 &debug_state(),
4009 0,
4010 100,
4011 None
4012 )
4013 .is_continue()
4014 );
4015
4016 assert!(
4017 state
4018 .collections
4019 .expire_writer(&writer_id_one)
4020 .is_continue()
4021 );
4022
4023 assert!(
4025 state
4026 .collections
4027 .compare_and_append(
4028 &hollow(2, 5, &["key2"], 1),
4029 &writer_id_two,
4030 now(),
4031 LEASE_DURATION_MS,
4032 &IdempotencyToken::new(),
4033 &debug_state(),
4034 0,
4035 100,
4036 None
4037 )
4038 .is_continue()
4039 );
4040 }
4041
4042 #[mz_ore::test]
4043 fn maybe_gc_active_gc() {
4044 const GC_CONFIG: GcConfig = GcConfig {
4045 use_active_gc: true,
4046 fallback_threshold_ms: 5000,
4047 min_versions: 99,
4048 max_versions: 500,
4049 remove_finalized_rollups: true,
4050 };
4051 let now_fn = SYSTEM_TIME.clone();
4052
4053 let mut state = TypedState::<String, String, u64, i64>::new(
4054 DUMMY_BUILD_INFO.semver_version(),
4055 ShardId::new(),
4056 "".to_owned(),
4057 0,
4058 );
4059
4060 let now = now_fn();
4061 assert_eq!(state.maybe_gc(true, now, GC_CONFIG), None);
4063 assert_eq!(state.maybe_gc(false, now, GC_CONFIG), None);
4064
4065 state.seqno = SeqNo(100);
4068 assert_eq!(state.seqno_since(), SeqNo(100));
4069
4070 let writer_id = WriterId::new();
4072 let _ = state.collections.compare_and_append(
4073 &hollow(1, 2, &["key1"], 1),
4074 &writer_id,
4075 now,
4076 LEASE_DURATION_MS,
4077 &IdempotencyToken::new(),
4078 &debug_state(),
4079 0,
4080 100,
4081 None,
4082 );
4083 assert_eq!(state.maybe_gc(false, now, GC_CONFIG), None);
4084
4085 assert_eq!(
4087 state.maybe_gc(true, now, GC_CONFIG),
4088 Some(GcReq {
4089 shard_id: state.shard_id,
4090 new_seqno_since: SeqNo(100)
4091 })
4092 );
4093
4094 state.collections.active_gc = Some(ActiveGc {
4096 seqno: state.seqno,
4097 start_ms: now,
4098 });
4099
4100 state.seqno = SeqNo(200);
4101 assert_eq!(state.seqno_since(), SeqNo(200));
4102
4103 assert_eq!(state.maybe_gc(true, now, GC_CONFIG), None);
4104
4105 state.seqno = SeqNo(300);
4106 assert_eq!(state.seqno_since(), SeqNo(300));
4107 let new_now = now + GC_CONFIG.fallback_threshold_ms + 1;
4109 assert_eq!(
4110 state.maybe_gc(true, new_now, GC_CONFIG),
4111 Some(GcReq {
4112 shard_id: state.shard_id,
4113 new_seqno_since: SeqNo(300)
4114 })
4115 );
4116
4117 state.seqno = SeqNo(301);
4121 assert_eq!(state.seqno_since(), SeqNo(301));
4122 assert_eq!(
4123 state.maybe_gc(true, new_now, GC_CONFIG),
4124 Some(GcReq {
4125 shard_id: state.shard_id,
4126 new_seqno_since: SeqNo(301)
4127 })
4128 );
4129
4130 state.collections.active_gc = None;
4131
4132 state.seqno = SeqNo(400);
4135 assert_eq!(state.seqno_since(), SeqNo(400));
4136
4137 let now = now_fn();
4138
4139 let _ = state.collections.expire_writer(&writer_id);
4141 assert_eq!(
4142 state.maybe_gc(false, now, GC_CONFIG),
4143 Some(GcReq {
4144 shard_id: state.shard_id,
4145 new_seqno_since: SeqNo(400)
4146 })
4147 );
4148
4149 let previous_seqno = state.seqno;
4151 state.seqno = SeqNo(10_000);
4152 assert_eq!(state.seqno_since(), SeqNo(10_000));
4153
4154 let now = now_fn();
4155 assert_eq!(
4156 state.maybe_gc(true, now, GC_CONFIG),
4157 Some(GcReq {
4158 shard_id: state.shard_id,
4159 new_seqno_since: SeqNo(previous_seqno.0 + u64::cast_from(GC_CONFIG.max_versions))
4160 })
4161 );
4162 }
4163
4164 #[mz_ore::test]
4165 fn maybe_gc_classic() {
4166 const GC_CONFIG: GcConfig = GcConfig {
4167 use_active_gc: false,
4168 fallback_threshold_ms: 5000,
4169 min_versions: 16,
4170 max_versions: 128,
4171 remove_finalized_rollups: true,
4172 };
4173 const NOW_MS: u64 = 0;
4174
4175 let mut state = TypedState::<String, String, u64, i64>::new(
4176 DUMMY_BUILD_INFO.semver_version(),
4177 ShardId::new(),
4178 "".to_owned(),
4179 0,
4180 );
4181
4182 assert_eq!(state.maybe_gc(true, NOW_MS, GC_CONFIG), None);
4184 assert_eq!(state.maybe_gc(false, NOW_MS, GC_CONFIG), None);
4185
4186 state.seqno = SeqNo(100);
4189 assert_eq!(state.seqno_since(), SeqNo(100));
4190
4191 let writer_id = WriterId::new();
4193 let now = SYSTEM_TIME.clone();
4194 let _ = state.collections.compare_and_append(
4195 &hollow(1, 2, &["key1"], 1),
4196 &writer_id,
4197 now(),
4198 LEASE_DURATION_MS,
4199 &IdempotencyToken::new(),
4200 &debug_state(),
4201 0,
4202 100,
4203 None,
4204 );
4205 assert_eq!(state.maybe_gc(false, NOW_MS, GC_CONFIG), None);
4206
4207 assert_eq!(
4209 state.maybe_gc(true, NOW_MS, GC_CONFIG),
4210 Some(GcReq {
4211 shard_id: state.shard_id,
4212 new_seqno_since: SeqNo(100)
4213 })
4214 );
4215
4216 state.seqno = SeqNo(200);
4219 assert_eq!(state.seqno_since(), SeqNo(200));
4220
4221 let _ = state.collections.expire_writer(&writer_id);
4223 assert_eq!(
4224 state.maybe_gc(false, NOW_MS, GC_CONFIG),
4225 Some(GcReq {
4226 shard_id: state.shard_id,
4227 new_seqno_since: SeqNo(200)
4228 })
4229 );
4230 }
4231
4232 #[mz_ore::test]
4233 fn need_rollup_active_rollup() {
4234 const ROLLUP_THRESHOLD: usize = 3;
4235 const ROLLUP_USE_ACTIVE_ROLLUP: bool = true;
4236 const ROLLUP_FALLBACK_THRESHOLD_MS: u64 = 5000;
4237 let now = SYSTEM_TIME.clone();
4238
4239 mz_ore::test::init_logging();
4240 let mut state = TypedState::<String, String, u64, i64>::new(
4241 DUMMY_BUILD_INFO.semver_version(),
4242 ShardId::new(),
4243 "".to_owned(),
4244 0,
4245 );
4246
4247 let rollup_seqno = SeqNo(5);
4248 let rollup = HollowRollup {
4249 key: PartialRollupKey::new(rollup_seqno, &RollupId::new()),
4250 encoded_size_bytes: None,
4251 finalized: false,
4252 };
4253
4254 assert!(
4255 state
4256 .collections
4257 .add_rollup((rollup_seqno, &rollup))
4258 .is_continue()
4259 );
4260
4261 state.seqno = SeqNo(5);
4263 assert_none!(state.need_rollup(
4264 ROLLUP_THRESHOLD,
4265 ROLLUP_USE_ACTIVE_ROLLUP,
4266 ROLLUP_FALLBACK_THRESHOLD_MS,
4267 now()
4268 ));
4269
4270 state.seqno = SeqNo(6);
4272 assert_none!(state.need_rollup(
4273 ROLLUP_THRESHOLD,
4274 ROLLUP_USE_ACTIVE_ROLLUP,
4275 ROLLUP_FALLBACK_THRESHOLD_MS,
4276 now()
4277 ));
4278 state.seqno = SeqNo(7);
4279 assert_none!(state.need_rollup(
4280 ROLLUP_THRESHOLD,
4281 ROLLUP_USE_ACTIVE_ROLLUP,
4282 ROLLUP_FALLBACK_THRESHOLD_MS,
4283 now()
4284 ));
4285 state.seqno = SeqNo(8);
4286 assert_none!(state.need_rollup(
4287 ROLLUP_THRESHOLD,
4288 ROLLUP_USE_ACTIVE_ROLLUP,
4289 ROLLUP_FALLBACK_THRESHOLD_MS,
4290 now()
4291 ));
4292
4293 let mut current_time = now();
4294 state.seqno = SeqNo(9);
4296 assert_eq!(
4297 state
4298 .need_rollup(
4299 ROLLUP_THRESHOLD,
4300 ROLLUP_USE_ACTIVE_ROLLUP,
4301 ROLLUP_FALLBACK_THRESHOLD_MS,
4302 current_time
4303 )
4304 .expect("rollup"),
4305 SeqNo(9)
4306 );
4307
4308 state.collections.active_rollup = Some(ActiveRollup {
4309 seqno: SeqNo(9),
4310 start_ms: current_time,
4311 });
4312
4313 assert_none!(state.need_rollup(
4315 ROLLUP_THRESHOLD,
4316 ROLLUP_USE_ACTIVE_ROLLUP,
4317 ROLLUP_FALLBACK_THRESHOLD_MS,
4318 current_time
4319 ));
4320
4321 state.seqno = SeqNo(10);
4322 assert_none!(state.need_rollup(
4325 ROLLUP_THRESHOLD,
4326 ROLLUP_USE_ACTIVE_ROLLUP,
4327 ROLLUP_FALLBACK_THRESHOLD_MS,
4328 current_time
4329 ));
4330
4331 current_time += u64::cast_from(ROLLUP_FALLBACK_THRESHOLD_MS) + 1;
4333 assert_eq!(
4334 state
4335 .need_rollup(
4336 ROLLUP_THRESHOLD,
4337 ROLLUP_USE_ACTIVE_ROLLUP,
4338 ROLLUP_FALLBACK_THRESHOLD_MS,
4339 current_time
4340 )
4341 .expect("rollup"),
4342 SeqNo(10)
4343 );
4344
4345 state.seqno = SeqNo(9);
4346 state.collections.active_rollup = None;
4348 let rollup_seqno = SeqNo(9);
4349 let rollup = HollowRollup {
4350 key: PartialRollupKey::new(rollup_seqno, &RollupId::new()),
4351 encoded_size_bytes: None,
4352 finalized: false,
4353 };
4354 assert!(
4355 state
4356 .collections
4357 .add_rollup((rollup_seqno, &rollup))
4358 .is_continue()
4359 );
4360
4361 state.seqno = SeqNo(11);
4362 assert_none!(state.need_rollup(
4364 ROLLUP_THRESHOLD,
4365 ROLLUP_USE_ACTIVE_ROLLUP,
4366 ROLLUP_FALLBACK_THRESHOLD_MS,
4367 current_time
4368 ));
4369 state.seqno = SeqNo(13);
4371 assert_eq!(
4372 state
4373 .need_rollup(
4374 ROLLUP_THRESHOLD,
4375 ROLLUP_USE_ACTIVE_ROLLUP,
4376 ROLLUP_FALLBACK_THRESHOLD_MS,
4377 current_time
4378 )
4379 .expect("rollup"),
4380 SeqNo(13)
4381 );
4382 }
4383
4384 #[mz_ore::test]
4385 fn need_rollup_classic() {
4386 const ROLLUP_THRESHOLD: usize = 3;
4387 const ROLLUP_USE_ACTIVE_ROLLUP: bool = false;
4388 const ROLLUP_FALLBACK_THRESHOLD_MS: u64 = 0;
4389 const NOW: u64 = 0;
4390
4391 mz_ore::test::init_logging();
4392 let mut state = TypedState::<String, String, u64, i64>::new(
4393 DUMMY_BUILD_INFO.semver_version(),
4394 ShardId::new(),
4395 "".to_owned(),
4396 0,
4397 );
4398
4399 let rollup_seqno = SeqNo(5);
4400 let rollup = HollowRollup {
4401 key: PartialRollupKey::new(rollup_seqno, &RollupId::new()),
4402 encoded_size_bytes: None,
4403 finalized: false,
4404 };
4405
4406 assert!(
4407 state
4408 .collections
4409 .add_rollup((rollup_seqno, &rollup))
4410 .is_continue()
4411 );
4412
4413 state.seqno = SeqNo(5);
4415 assert_none!(state.need_rollup(
4416 ROLLUP_THRESHOLD,
4417 ROLLUP_USE_ACTIVE_ROLLUP,
4418 ROLLUP_FALLBACK_THRESHOLD_MS,
4419 NOW
4420 ));
4421
4422 state.seqno = SeqNo(6);
4424 assert_none!(state.need_rollup(
4425 ROLLUP_THRESHOLD,
4426 ROLLUP_USE_ACTIVE_ROLLUP,
4427 ROLLUP_FALLBACK_THRESHOLD_MS,
4428 NOW
4429 ));
4430 state.seqno = SeqNo(7);
4431 assert_none!(state.need_rollup(
4432 ROLLUP_THRESHOLD,
4433 ROLLUP_USE_ACTIVE_ROLLUP,
4434 ROLLUP_FALLBACK_THRESHOLD_MS,
4435 NOW
4436 ));
4437
4438 state.seqno = SeqNo(8);
4440 assert_eq!(
4441 state
4442 .need_rollup(
4443 ROLLUP_THRESHOLD,
4444 ROLLUP_USE_ACTIVE_ROLLUP,
4445 ROLLUP_FALLBACK_THRESHOLD_MS,
4446 NOW
4447 )
4448 .expect("rollup"),
4449 SeqNo(8)
4450 );
4451
4452 state.seqno = SeqNo(9);
4454 assert_none!(state.need_rollup(
4455 ROLLUP_THRESHOLD,
4456 ROLLUP_USE_ACTIVE_ROLLUP,
4457 ROLLUP_FALLBACK_THRESHOLD_MS,
4458 NOW
4459 ));
4460
4461 state.seqno = SeqNo(11);
4463 assert_eq!(
4464 state
4465 .need_rollup(
4466 ROLLUP_THRESHOLD,
4467 ROLLUP_USE_ACTIVE_ROLLUP,
4468 ROLLUP_FALLBACK_THRESHOLD_MS,
4469 NOW
4470 )
4471 .expect("rollup"),
4472 SeqNo(11)
4473 );
4474
4475 let rollup_seqno = SeqNo(6);
4477 let rollup = HollowRollup {
4478 key: PartialRollupKey::new(rollup_seqno, &RollupId::new()),
4479 encoded_size_bytes: None,
4480 finalized: false,
4481 };
4482 assert!(
4483 state
4484 .collections
4485 .add_rollup((rollup_seqno, &rollup))
4486 .is_continue()
4487 );
4488
4489 state.seqno = SeqNo(8);
4490 assert_none!(state.need_rollup(
4491 ROLLUP_THRESHOLD,
4492 ROLLUP_USE_ACTIVE_ROLLUP,
4493 ROLLUP_FALLBACK_THRESHOLD_MS,
4494 NOW
4495 ));
4496 state.seqno = SeqNo(9);
4497 assert_eq!(
4498 state
4499 .need_rollup(
4500 ROLLUP_THRESHOLD,
4501 ROLLUP_USE_ACTIVE_ROLLUP,
4502 ROLLUP_FALLBACK_THRESHOLD_MS,
4503 NOW
4504 )
4505 .expect("rollup"),
4506 SeqNo(9)
4507 );
4508
4509 let fallback_seqno = SeqNo(
4511 rollup_seqno.0
4512 * u64::cast_from(PersistConfig::DEFAULT_FALLBACK_ROLLUP_THRESHOLD_MULTIPLIER),
4513 );
4514 state.seqno = fallback_seqno;
4515 assert_eq!(
4516 state
4517 .need_rollup(
4518 ROLLUP_THRESHOLD,
4519 ROLLUP_USE_ACTIVE_ROLLUP,
4520 ROLLUP_FALLBACK_THRESHOLD_MS,
4521 NOW
4522 )
4523 .expect("rollup"),
4524 fallback_seqno
4525 );
4526 state.seqno = fallback_seqno.next();
4527 assert_eq!(
4528 state
4529 .need_rollup(
4530 ROLLUP_THRESHOLD,
4531 ROLLUP_USE_ACTIVE_ROLLUP,
4532 ROLLUP_FALLBACK_THRESHOLD_MS,
4533 NOW
4534 )
4535 .expect("rollup"),
4536 fallback_seqno.next()
4537 );
4538 }
4539
4540 #[mz_ore::test]
4541 fn idempotency_token_sentinel() {
4542 assert_eq!(
4543 IdempotencyToken::SENTINEL.to_string(),
4544 "i11111111-1111-1111-1111-111111111111"
4545 );
4546 }
4547
4548 #[mz_ore::test]
4557 #[cfg_attr(miri, ignore)] fn state_inspect_serde_json() {
4559 const STATE_SERDE_JSON: &str = include_str!("state_serde.json");
4560 let mut runner = proptest::test_runner::TestRunner::deterministic();
4561 let tree = any_state::<u64>(6..8).new_tree(&mut runner).unwrap();
4562 let json = serde_json::to_string_pretty(&tree.current()).unwrap();
4563 assert_eq!(
4564 json.trim(),
4565 STATE_SERDE_JSON.trim(),
4566 "\n\nNEW GOLDEN\n{}\n",
4567 json
4568 );
4569 }
4570
4571 #[mz_persist_proc::test(tokio::test)]
4572 #[cfg_attr(miri, ignore)] async fn sneaky_downgrades(dyncfgs: ConfigUpdates) {
4574 let mut clients = new_test_client_cache(&dyncfgs);
4575 let shard_id = ShardId::new();
4576
4577 async fn open_and_write(
4578 clients: &mut PersistClientCache,
4579 version: semver::Version,
4580 shard_id: ShardId,
4581 ) -> Result<(), tokio::task::JoinError> {
4582 clients.cfg.build_version = version.clone();
4583 clients.clear_state_cache();
4584 let client = clients.open(PersistLocation::new_in_mem()).await.unwrap();
4585 mz_ore::task::spawn(|| version.to_string(), async move {
4587 let () = client
4588 .upgrade_version::<String, (), u64, i64>(shard_id, Diagnostics::for_tests())
4589 .await
4590 .expect("valid usage");
4591 let (mut write, _) = client.expect_open::<String, (), u64, i64>(shard_id).await;
4592 let current = *write.upper().as_option().unwrap();
4593 write
4595 .expect_compare_and_append_batch(&mut [], current, current + 1)
4596 .await;
4597 })
4598 .into_tokio_handle()
4599 .await
4600 }
4601
4602 let res = open_and_write(&mut clients, Version::new(0, 10, 0), shard_id).await;
4604 assert_ok!(res);
4605
4606 let res = open_and_write(&mut clients, Version::new(0, 11, 0), shard_id).await;
4608 assert_ok!(res);
4609
4610 let res = open_and_write(&mut clients, Version::new(0, 10, 0), shard_id).await;
4612 assert!(res.unwrap_err().is_panic());
4613
4614 let res = open_and_write(&mut clients, Version::new(0, 9, 0), shard_id).await;
4616 assert!(res.unwrap_err().is_panic());
4617 }
4618
4619 #[mz_ore::test]
4620 fn runid_roundtrip() {
4621 proptest!(|(runid: RunId)| {
4622 let runid_str = runid.to_string();
4623 let parsed = RunId::from_str(&runid_str);
4624 prop_assert_eq!(parsed, Ok(runid));
4625 });
4626 }
4627
4628 #[mz_ore::test]
4644 fn add_rollup_idempotent_across_gc_removal() {
4645 let mut state = TypedState::<String, String, u64, i64>::new(
4646 DUMMY_BUILD_INFO.semver_version(),
4647 ShardId::new(),
4648 "".to_owned(),
4649 0,
4650 );
4651
4652 let older_seqno = SeqNo(10);
4653 let older = HollowRollup {
4654 key: PartialRollupKey::new(older_seqno, &RollupId::new()),
4655 encoded_size_bytes: None,
4656 finalized: false,
4657 };
4658 let newer_seqno = SeqNo(20);
4659 let newer = HollowRollup {
4660 key: PartialRollupKey::new(newer_seqno, &RollupId::new()),
4661 encoded_size_bytes: None,
4662 finalized: false,
4663 };
4664 let add_older = |state: &mut StateCollections<u64>| state.add_rollup((older_seqno, &older));
4665
4666 assert_eq!(add_older(&mut state.collections), Continue(true));
4668 assert_eq!(add_older(&mut state.collections), Continue(true));
4671 assert_eq!(state.collections.rollups.len(), 1);
4672
4673 assert_eq!(
4677 state.collections.add_rollup((newer_seqno, &newer)),
4678 Continue(true),
4679 );
4680
4681 let _ = state
4685 .collections
4686 .remove_rollups(&[(older_seqno, older.key.clone())], false);
4687 assert!(!state.collections.rollups.contains_key(&older_seqno));
4688 assert!(state.collections.rollups.contains_key(&newer_seqno));
4689
4690 assert_eq!(add_older(&mut state.collections), Continue(false));
4695 assert!(!state.collections.rollups.contains_key(&older_seqno));
4696 assert_eq!(state.collections.rollups.len(), 1);
4697 }
4698
4699 #[mz_ore::test]
4700 fn finalized_rollups() {
4701 let mut state = TypedState::<String, String, u64, i64>::new(
4702 DUMMY_BUILD_INFO.semver_version(),
4703 ShardId::new(),
4704 "".to_owned(),
4705 0,
4706 );
4707 state.collections.trace.downgrade_since(&Antichain::new());
4708 let _ = state
4709 .collections
4710 .trace
4711 .push_batch(StateCollections::tombstone_batch());
4712 assert!(state.collections.is_finalized());
4713
4714 let rollup = |seqno, finalized| HollowRollup {
4715 key: PartialRollupKey::new(SeqNo(seqno), &RollupId::new()),
4716 encoded_size_bytes: None,
4717 finalized,
4718 };
4719 let (old, kept, latest) = (rollup(1, false), rollup(3, true), rollup(5, true));
4720 for (seqno, rollup) in [(1, &old), (3, &kept), (5, &latest)] {
4721 assert_eq!(
4722 state.collections.add_rollup((SeqNo(seqno), rollup)),
4723 Continue(true)
4724 );
4725 }
4726 let remove_old = [(SeqNo(1), old.key.clone()), (SeqNo(3), kept.key.clone())];
4727
4728 for (seqno, need) in [(6, None), (7, Some(SeqNo(7)))] {
4731 state.seqno = SeqNo(seqno);
4732 assert_eq!(state.need_rollup(3, false, 0, 0), need);
4733 }
4734
4735 let noop = Break(NoOpStateTransition(vec![]));
4736 assert_eq!(
4737 state.collections.remove_rollups(&remove_old, false),
4738 noop,
4739 "kill switch off"
4740 );
4741
4742 state.collections.active_gc = Some(ActiveGc {
4743 seqno: SeqNo(6),
4744 start_ms: 0,
4745 });
4746 assert_eq!(state.collections.remove_rollups(&[], true), noop);
4747 assert!(
4748 state.collections.active_gc.is_some(),
4749 "a no-op must not commit to clear active_gc"
4750 );
4751
4752 assert_eq!(
4753 state.collections.remove_rollups(&remove_old, true),
4754 Continue(vec![SeqNo(1)])
4755 );
4756 assert_eq!(state.collections.active_gc, None);
4757 assert_eq!(
4758 state.collections.rollups.keys().collect::<Vec<_>>(),
4759 vec![&SeqNo(3), &SeqNo(5)]
4760 );
4761 assert_eq!(
4762 state.collections.remove_rollups(&remove_old, true),
4763 noop,
4764 "replayed removal"
4765 );
4766 }
4767}