Skip to main content

mz_persist_client/internal/
state.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use 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
84/// Determines how often to write rollups, assigning a maintenance task after
85/// `rollup_threshold` seqnos have passed since the last rollup.
86///
87/// Tuning note: in the absence of a long reader seqno hold, and with
88/// incremental GC, this threshold will determine about how many live diffs are
89/// held in Consensus. Lowering this value decreases the live diff count at the
90/// cost of more maintenance work + blob writes.
91pub(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
98/// Determines how long to wait before an active rollup is considered
99/// "stuck" and a new rollup is started.
100pub(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
107/// Feature flag the new active rollup tracking mechanism.
108/// We musn't enable this until we are fully deployed on the new version.
109pub(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
116/// Determines how long to wait before an active GC is considered
117/// "stuck" and a new GC is started.
118pub(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
125/// See the config description string.
126pub(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
133/// See the config description string.
134pub(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
141/// Feature flag the new active GC tracking mechanism.
142/// We musn't enable this until we are fully deployed on the new version.
143pub(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/// A token to disambiguate state commands that could not otherwise be
158/// idempotent.
159#[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    /// The seqno capability of this reader.
199    pub seqno: SeqNo,
200    /// The since capability of this reader.
201    pub since: Antichain<T>,
202    /// UNIX_EPOCH timestamp (in millis) of this reader's most recent heartbeat
203    pub last_heartbeat_timestamp_ms: u64,
204    /// Duration (in millis) allowed after [Self::last_heartbeat_timestamp_ms]
205    /// after which this reader may be expired
206    pub lease_duration_ms: u64,
207    /// For debugging.
208    pub debug: HandleDebugState,
209}
210
211#[derive(Clone, Debug, PartialEq, Serialize)]
212pub struct CriticalReaderState<T> {
213    /// The since capability of this reader.
214    pub since: Antichain<T>,
215    /// An opaque token matched on by compare_and_downgrade_since.
216    pub opaque: Opaque,
217    /// For debugging.
218    pub debug: HandleDebugState,
219}
220
221#[derive(Clone, Debug, PartialEq, Serialize)]
222pub struct WriterState<T> {
223    /// UNIX_EPOCH timestamp (in millis) of this writer's most recent heartbeat
224    pub last_heartbeat_timestamp_ms: u64,
225    /// Duration (in millis) allowed after [Self::last_heartbeat_timestamp_ms]
226    /// after which this writer may be expired
227    pub lease_duration_ms: u64,
228    /// The idempotency token of the most recent successful compare_and_append
229    /// by this writer.
230    pub most_recent_write_token: IdempotencyToken,
231    /// The upper of the most recent successful compare_and_append by this
232    /// writer.
233    pub most_recent_write_upper: Antichain<T>,
234    /// For debugging.
235    pub debug: HandleDebugState,
236}
237
238/// Debugging info for a reader or writer.
239#[derive(Arbitrary, Clone, Debug, Default, PartialEq, Serialize)]
240pub struct HandleDebugState {
241    /// Hostname of the persist user that registered this writer or reader. For
242    /// critical readers, this is the _most recent_ registration.
243    pub hostname: String,
244    /// Plaintext description of this writer or reader's intent.
245    pub purpose: String,
246}
247
248/// Part of the updates in a Batch.
249///
250/// Either a pointer to ones stored in Blob or the updates themselves inlined.
251#[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        /// ID of a schema that has since been deprecated and exists only to cleanly roundtrip.
261        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    // A user-interpretable identifier or description of the part (for logs and
318    // such).
319    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            // We don't duplicate the lowest key because this can be
337            // considerable overhead for small parts.
338            //
339            // The empty key might not be a tight lower bound, but it is a valid
340            // lower bound. If a caller is interested in a tighter lower bound,
341            // the data is inline.
342            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/// An ordered list of parts, generally stored as part of a larger run.
406#[derive(Debug, Clone)]
407pub struct HollowRun<T> {
408    /// Pointers usable to retrieve the updates.
409    pub(crate) parts: Vec<RunPart<T>>,
410}
411
412/// A reference to a [HollowRun], including the key in the blob store and some denormalized
413/// metadata.
414#[derive(Debug, Eq, PartialEq, Clone, Serialize)]
415pub struct HollowRunRef<T> {
416    pub key: PartialBatchKey,
417
418    /// The size of the referenced run object, plus all of the hollow objects it contains.
419    pub hollow_bytes: usize,
420
421    /// The size of the largest individual part in the run; useful for sizing compaction.
422    pub max_part_bytes: usize,
423
424    /// The lower bound of the data in this part, ordered by the codec ordering.
425    pub key_lower: Vec<u8>,
426
427    /// The lower bound of the data in this part, ordered by the structured ordering.
428    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    /// Stores the given runs and returns a [HollowRunRef] that points to them.
454    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    /// Retrieve the [HollowRun] that this reference points to.
510    /// The caller is expected to ensure that this ref is the result of calling [HollowRunRef::set]
511    /// with the same shard id and backing store.
512    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/// Part of the updates in a run.
533///
534/// Either a pointer to ones stored in Blob or a single part stored inline.
535#[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    // A user-interpretable identifier or description of the part (for logs and
618    // such).
619    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            // TODO: if we kept stats we could avoid fetching the metadata here.
630            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/// A blob was missing!
669#[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/// What order are the parts in this run in?
750#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd, Serialize)]
751pub(crate) enum RunOrder {
752    /// They're in no particular order.
753    Unordered,
754    /// They're ordered based on the codec-encoded K/V bytes.
755    Codec,
756    /// They're ordered by the natural ordering of the structured data.
757    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/// Metadata shared across a run.
807#[derive(Clone, Debug, Default, PartialEq, Eq, Ord, PartialOrd, Serialize)]
808pub struct RunMeta {
809    /// If none, Persist should infer the order based on the proto metadata.
810    pub(crate) order: Option<RunOrder>,
811    /// All parts in a run should have the same schema.
812    pub(crate) schema: Option<SchemaId>,
813
814    /// ID of a schema that has since been deprecated and exists only to cleanly roundtrip.
815    pub(crate) deprecated_schema: Option<SchemaId>,
816
817    /// If set, a UUID that uniquely identifies this run.
818    pub(crate) id: Option<RunId>,
819
820    /// The number of updates in this run, or `None` if the number is unknown.
821    pub(crate) len: Option<usize>,
822
823    /// Additional unstructured metadata.
824    #[serde(skip_serializing_if = "MetadataMap::is_empty")]
825    pub(crate) meta: MetadataMap,
826}
827
828/// Metadata key for [RunMeta::bounds_truncated].
829const RUN_META_BOUNDS_TRUNCATED: MetadataKey<bool> = MetadataKey::new("truncated");
830
831impl RunMeta {
832    /// Whether this run's parts may hold updates outside the registered desc
833    /// of the batch that contains them.
834    ///
835    /// Set when a batch is appended under a desc narrower than the one it was
836    /// written with (truncation). Readers filter such updates out against the
837    /// registered desc, but per-part statistics like `diffs_sum` are computed
838    /// at write time over everything physically in the part, so accounting
839    /// that compares those statistics against data seen through a read must
840    /// skip runs with this bit set.
841    pub(crate) fn bounds_truncated(&self) -> bool {
842        self.meta.get(RUN_META_BOUNDS_TRUNCATED).unwrap_or(false)
843    }
844
845    /// Marks this run as possibly holding updates outside its batch's
846    /// registered desc. See [Self::bounds_truncated].
847    pub(crate) fn set_bounds_truncated(&mut self) {
848        self.meta.set(RUN_META_BOUNDS_TRUNCATED, true);
849    }
850}
851
852/// A subset of a [HollowBatch] corresponding 1:1 to a blob.
853#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
854pub struct HollowBatchPart<T> {
855    /// Pointer usable to retrieve the updates.
856    pub key: PartialBatchKey,
857    /// Miscellaneous metadata.
858    #[serde(skip_serializing_if = "MetadataMap::is_empty")]
859    pub meta: MetadataMap,
860    /// The encoded size of this part.
861    pub encoded_size_bytes: usize,
862    /// A lower bound on the keys in the part. (By default, this the minimum
863    /// possible key: `vec![]`.)
864    #[serde(serialize_with = "serialize_part_bytes")]
865    pub key_lower: Vec<u8>,
866    /// A lower bound on the keys in the part, stored as structured data.
867    #[serde(serialize_with = "serialize_lazy_proto")]
868    pub structured_key_lower: Option<LazyProto<ProtoArrayData>>,
869    /// Aggregate statistics about data contained in this part.
870    #[serde(serialize_with = "serialize_part_stats")]
871    pub stats: Option<LazyPartStats>,
872    /// A frontier to which timestamps in this part are advanced on read, if
873    /// set.
874    ///
875    /// A value of `Some([T::minimum()])` is functionally the same as `None`,
876    /// but we maintain the distinction between the two for some internal sanity
877    /// checking of invariants as well as metrics. If this ever becomes an
878    /// issue, everything still works with this as just `Antichain<T>`.
879    pub ts_rewrite: Option<Antichain<T>>,
880    /// A Codec64 encoded sum of all diffs in this part, if known.
881    ///
882    /// This is `None` if this part was written before we started storing this
883    /// information, or if it was written when the dyncfg was off.
884    ///
885    /// It could also make sense to model this as part of the pushdown stats, if
886    /// we later decide that's of some benefit.
887    #[serde(serialize_with = "serialize_diffs_sum")]
888    pub diffs_sum: Option<[u8; 8]>,
889    /// Columnar format that this batch was written in.
890    ///
891    /// This is `None` if this part was written before we started writing structured
892    /// columnar data.
893    pub format: Option<BatchColumnarFormat>,
894    /// The schemas used to encode the data in this batch part.
895    ///
896    /// Or None for historical data written before the schema registry was
897    /// added.
898    pub schema_id: Option<SchemaId>,
899
900    /// ID of a schema that has since been deprecated and exists only to cleanly roundtrip.
901    pub deprecated_schema_id: Option<SchemaId>,
902}
903
904/// A differential trace batch, but with the updates themselves stored externally.
905#[derive(Clone, PartialEq, Eq)]
906pub struct HollowBatch<T> {
907    /// Describes the times of the updates in the batch.
908    pub desc: Description<T>,
909    /// The number of updates in the batch.
910    pub len: usize,
911    /// Pointers usable to retrieve the updates.
912    pub(crate) parts: Vec<RunPart<T>>,
913    /// Runs of sequential sorted batch parts, stored as indices into `parts`.
914    /// ex.
915    /// ```text
916    ///     parts=[p1, p2, p3], runs=[]     --> run  is  [p1, p2, p2]
917    ///     parts=[p1, p2, p3], runs=[1]    --> runs are [p1] and [p2, p3]
918    ///     parts=[p1, p2, p3], runs=[1, 2] --> runs are [p1], [p2], [p3]
919    /// ```
920    pub(crate) run_splits: Vec<usize>,
921    /// Run-level metadata: the first entry has metadata for the first run, and so on.
922    /// If there's no corresponding entry for a particular run, it's assumed to be [RunMeta::default()].
923    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            // Both parts and runs are covered by the self.runs call.
958            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        // Deconstruct self and other so we get a compile failure if new fields
981        // are added.
982        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    /// Construct an in-memory hollow batch from the given metadata.
1035    ///
1036    /// This method checks that `runs` is a sequence of valid indices into `parts`. The caller
1037    /// is responsible for ensuring that the defined runs are valid.
1038    ///
1039    /// `len` should represent the number of valid updates in the referenced parts.
1040    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    /// Construct a batch of a single run with default metadata. Mostly interesting for tests.
1074    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    /// An empty hollow batch, representing no updates over the given desc.
1113    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    /// The sum of the encoded sizes of all parts in the batch.
1154    pub fn encoded_size_bytes(&self) -> usize {
1155        self.parts.iter().map(|p| p.encoded_size_bytes()).sum()
1156    }
1157}
1158
1159// See the comment on [Batch::rewrite_ts] for why this is TotalOrder.
1160impl<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        // The following are things that it seems like we could support, but
1182        // initially we don't because we don't have a use case for them.
1183        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            // A hollow run's parts live in a separate blob this rewrite can't edit.
1200            // `WriteHandle::rewritable_builder` never makes one.
1201            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        // Deconstruct self and other so we get a compile failure if new fields
1240        // are added.
1241        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/// A pointer to a rollup stored externally.
1297#[derive(Arbitrary, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
1298pub struct HollowRollup {
1299    /// Pointer usable to retrieve the rollup.
1300    pub key: PartialRollupKey,
1301    /// The encoded size of this rollup, if known.
1302    pub encoded_size_bytes: Option<usize>,
1303    /// Whether the state this rolls up is finalized, recorded only while
1304    /// `persist_gc_remove_finalized_rollups` is on. GC keeps these.
1305    pub finalized: bool,
1306}
1307
1308/// A pointer to a blob stored externally.
1309#[derive(Debug)]
1310pub enum HollowBlobRef<'a, T> {
1311    Batch(&'a HollowBatch<T>),
1312    Rollup(&'a HollowRollup),
1313}
1314
1315/// A rollup that is currently being computed.
1316#[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/// A garbage collection request that is currently being computed.
1325#[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/// A sentinel for a state transition that was a no-op.
1334///
1335/// Critically, this also indicates that the no-op state transition was not
1336/// committed through compare_and_append and thus is _not linearized_.
1337#[derive(Debug)]
1338#[cfg_attr(any(test, debug_assertions), derive(PartialEq))]
1339pub struct NoOpStateTransition<T>(pub T);
1340
1341// TODO: Document invariants.
1342#[derive(Debug, Clone)]
1343#[cfg_attr(any(test, debug_assertions), derive(PartialEq))]
1344pub struct StateCollections<T> {
1345    /// The version of this state. This is typically identical to the version of the code
1346    /// that wrote it, but may diverge during 0dt upgrades and similar operations when a
1347    /// new version of code is intentionally interoperating with an older state format.
1348    pub(crate) version: Version,
1349
1350    // - Invariant: `<= all reader.since`
1351    // - Invariant: Doesn't regress across state versions.
1352    pub(crate) last_gc_req: SeqNo,
1353
1354    // - Invariant: There is a rollup with `seqno <= self.seqno_since`.
1355    pub(crate) rollups: BTreeMap<SeqNo, HollowRollup>,
1356
1357    /// The rollup that is currently being computed.
1358    pub(crate) active_rollup: Option<ActiveRollup>,
1359    /// The gc request that is currently being computed.
1360    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    // - Invariant: `trace.since == meet(all reader.since)`
1368    // - Invariant: `trace.since` doesn't regress across state versions.
1369    // - Invariant: `trace.upper` doesn't regress across state versions.
1370    // - Invariant: `trace` upholds its own invariants.
1371    pub(crate) trace: Trace<T>,
1372}
1373
1374/// A key and val [Codec::Schema] encoded via [Codec::encode_schema].
1375///
1376/// This strategy of directly serializing the schema objects requires that
1377/// persist users do the right thing. Specifically, that an encoded schema
1378/// doesn't in some later version of mz decode to an in-mem object that acts
1379/// differently. In a sense, the current system (before the introduction of the
1380/// schema registry) where schemas are passed in unchecked to reader and writer
1381/// registration calls also has the same defect, so seems fine.
1382///
1383/// An alternative is to write down here some persist-specific representation of
1384/// the schema (e.g. the arrow DataType). This is a lot more work and also has
1385/// the potential to lead down a similar failure mode to the mz_persist_types
1386/// `Data` trait, where the boilerplate isn't worth the safety. Given that we
1387/// can always migrate later by rehydrating these, seems fine to start with the
1388/// easy thing.
1389#[derive(Debug, Clone, Serialize, PartialEq)]
1390pub struct EncodedSchemas {
1391    /// A full in-mem `K::Schema` impl encoded via [Codec::encode_schema].
1392    pub key: Bytes,
1393    /// The arrow `DataType` produced by this `K::Schema` at the time it was
1394    /// registered, encoded as a `ProtoDataType`.
1395    pub key_data_type: Bytes,
1396    /// A full in-mem `V::Schema` impl encoded via [Codec::encode_schema].
1397    pub val: Bytes,
1398    /// The arrow `DataType` produced by this `V::Schema` at the time it was
1399    /// registered, encoded as a `ProtoDataType`.
1400    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                // PER-16: refuse to insert a rollup at a seqno that GC has
1442                // already physically removed. `apply_unbatched_idempotent_cmd`
1443                // replays the captured `(rollup_seqno, rollup)` tuple on
1444                // every retry. If the original CAS committed indeterminately
1445                // and a concurrent GC then removed the rollup, the retry
1446                // would otherwise observe an empty map entry and re-insert
1447                // the same `PartialRollupKey` at the same seqno, producing
1448                // a second Insert (and, later, a second Delete) for that
1449                // key in the diff stream and tripping the `assert!` in
1450                // `find_removable_blobs`.
1451                //
1452                // We use the smallest seqno currently in `self.rollups` as
1453                // the GC watermark. GC's `remove_rollups` always keeps the
1454                // latest rollup `<= seqno_since` and removes the older
1455                // ones, so the surviving minimum is strictly above every
1456                // seqno that has been removed. (Unlike `last_gc_req`, this
1457                // is only advanced by an actual physical removal, not by
1458                // `maybe_gc` deciding to *request* one — `last_gc_req` runs
1459                // ahead of removals and would falsely reject legitimate
1460                // late `add_rollup` calls for older seqnos.)
1461                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        // This state transition is a no-op if applied is false but we
1472        // still commit the state change so that this gets linearized
1473        // (maybe we're looking at old state).
1474        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        // This state transition is called at the end of the GC process, so we
1490        // need to unset the `active_gc` field.
1491        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    /// Removes only rollups written before the shard was finalized. Each
1521    /// removal asks for a new rollup, so removing those too would loop.
1522    ///
1523    /// NOTE: A no-op must not commit, even just to clear `active_gc`. See the
1524    /// soft assert in `compute_next_state_locked`.
1525    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            // Misses are expected when GC replays a committed removal.
1537            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 the shard-global upper and since are both the empty antichain,
1585        // then no further writes can ever commit and no further reads can be
1586        // served. Optimize this by no-op-ing reader registration so that we can
1587        // settle the shard into a final unchanging tombstone state.
1588        if self.is_tombstone() {
1589            return Break(NoOpStateTransition((reader_state, self.seqno_since(seqno))));
1590        }
1591
1592        // TODO: Handle if the reader or writer already exists.
1593        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        // We expire all readers if the upper and since both advance to the
1615        // empty antichain. Gracefully handle this. At the same time,
1616        // short-circuit the cmd application so we don't needlessly create new
1617        // SeqNos.
1618        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        // Look for an existing registered SchemaId for these schemas.
1647        //
1648        // The common case is that this should be a recent one, so as a minor
1649        // optimization, do this search in reverse order.
1650        //
1651        // TODO: Note that this impl is `O(schemas)`. Combined with the
1652        // possibility of cmd retries, it's possible but unlikely for this to
1653        // get expensive. We could maintain a reverse map to speed this up in
1654        // necessary. This would either need to work on the encoded
1655        // representation (which, we'd have to fall back to the linear scan) or
1656        // we'd need to add a Hash/Ord bound to Schema.
1657        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                // TODO: Validate that the decoded schemas still produce records
1663                // of the recorded DataType, to detect shenanigans. Probably
1664                // best to wait until we've turned on Schema2 in prod and thus
1665                // committed to the current mappings.
1666                Break(NoOpStateTransition(Some(*schema_id)))
1667            }
1668            None if self.is_tombstone() => {
1669                // TODO: Is this right?
1670                Break(NoOpStateTransition(None))
1671            }
1672            None if self.schemas.is_empty() => {
1673                // We'll have to do something more sophisticated here to
1674                // generate the next id if/when we start supporting the removal
1675                // of schemas.
1676                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                // This state may predate the schema's registration, see
1703                // `Machine::register_schema`.
1704                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            // To be defensive, create an empty batch and inspect the resulting
1717            // data type (as opposed to something like allowing the `Schema` to
1718            // declare the DataType).
1719            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(&current.key);
1729        let current_key_dt = EncodedSchemas::decode_data_type(&current.key_data_type);
1730        let current_val = V::decode_schema(&current.val);
1731        let current_val_dt = EncodedSchemas::decode_data_type(&current.val_data_type);
1732
1733        let key_dt = data_type(key_schema);
1734        let val_dt = data_type(val_schema);
1735
1736        // If the schema is exactly the same as the current one, no-op. NOTE:
1737        // this check has to come before the `expected` one, otherwise the
1738        // command is not idempotent: `apply_unbatched_idempotent_cmd` retries
1739        // indeterminate errors, so a CaS that committed but lost its response
1740        // gets re-run against state that already carries its own evolution.
1741        //
1742        // Returning Ok when `*current_id != expected` is safe: register_schema
1743        // never mints two ids for the same content, so a content match is the
1744        // current schema and a stale `expected` just lags the committed retry.
1745        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(&current_key_dt, &key_dt);
1762        let val_fn = backward_compatible(&current_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        // Persist initially disallows dropping columns. This would require a
1767        // bunch more work (e.g. not safe to use the latest schema in
1768        // compaction) and isn't initially necessary in mz.
1769        if key_fn.contains_drop() || val_fn.contains_drop() {
1770            return Break(NoOpStateTransition(CaESchema::Incompatible));
1771        }
1772
1773        // We'll have to do something more sophisticated here to
1774        // generate the next id if/when we start supporting the removal
1775        // of schemas.
1776        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        // We expire all writers if the upper and since both advance to the
1802        // empty antichain. Gracefully handle this. At the same time,
1803        // short-circuit the cmd application so we don't needlessly create new
1804        // SeqNos.
1805        if self.is_tombstone() {
1806            assert_eq!(self.trace.upper(), &Antichain::new());
1807            return Break(CompareAndAppendBreak::Upper {
1808                shard_upper: Antichain::new(),
1809                // This writer might have been registered before the shard upper
1810                // was advanced, which would make this pessimistic in the
1811                // Indeterminate handling of compare_and_append at the machine
1812                // level, but that's fine.
1813                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 the time interval is empty, the list of updates must also be
1838        // empty.
1839        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            // If the last write had the same idempotency_token, then this must
1855            // have already committed. Sanity check that the most recent write
1856            // upper matches and that the shard upper is at least the write
1857            // upper, if it's not something very suspect is going on.
1858            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            // TODO: For very small batches, it may actually _increase_ the size
1882            // of state to flush them out. Consider another threshold under
1883            // which an inline part can be appended no matter what.
1884            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        // NB: we don't claim unclaimed compactions when the recording flag is off, even if we'd
1896        // otherwise be allowed to, to avoid triggering the same compactions in every writer.
1897        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                // We keep the oldest `reqs_to_take` batches, under the theory that they're least
1911                // likely to be compacted soon for other reasons.
1912                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        // The writer's most recent upper should only go forward.
1930        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        // Heartbeat the writer state to keep our idempotency token alive.
1941        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        // We expire all writers if the upper and since both advance to the
1955        // empty antichain. Gracefully handle this. At the same time,
1956        // short-circuit the cmd application so we don't needlessly create new
1957        // SeqNos.
1958        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 if we have nothing useful to do to save the seqno (and
1976            // resulting crdb traffic)
1977            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        // We expire all readers if the upper and since both advance to the
1990        // empty antichain. Gracefully handle this. At the same time,
1991        // short-circuit the cmd application so we don't needlessly create new
1992        // SeqNos.
1993        if self.is_tombstone() {
1994            return Break(NoOpStateTransition(Since(Antichain::new())));
1995        }
1996
1997        // The only way to have a missing reader in state is if it's been expired... and in that
1998        // case, we behave the same as though that reader had been downgraded to the empty antichain.
1999        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        // Also use this as an opportunity to heartbeat the reader and downgrade
2007        // the seqno capability.
2008        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            // No-op, but still commit the state change so that this gets
2032            // linearized.
2033            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        // We expire all readers if the upper and since both advance to the
2049        // empty antichain. Gracefully handle this. At the same time,
2050        // short-circuit the cmd application so we don't needlessly create new
2051        // SeqNos.
2052        if self.is_tombstone() {
2053            // Match the idempotence behavior below of ignoring the token if
2054            // since is already advanced enough (in this case, because it's a
2055            // tombstone, we know it's the empty antichain).
2056            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            // No-op, but still commit the state change so that this gets
2063            // linearized.
2064            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            // no work to be done -- the reader state's `since` is already sufficiently
2077            // advanced. we may someday need to revisit this branch when it's possible
2078            // for two `since` frontiers to be incomparable.
2079            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        // We expire all readers if the upper and since both advance to the
2088        // empty antichain. Gracefully handle this. At the same time,
2089        // short-circuit the cmd application so we don't needlessly create new
2090        // SeqNos.
2091        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            // TODO(database-issues#6885): Re-enable this
2098            //
2099            // Temporarily disabling this because we think it might be the cause
2100            // of the remap since bug. Specifically, a clusterd process has a
2101            // ReadHandle for maintaining the once and one inside a Listen. If
2102            // we crash and stay down for longer than the read lease duration,
2103            // it's possible that an expiry of them both in quick succession
2104            // jumps the since forward to the Listen one.
2105            //
2106            // Don't forget to update the downgrade_since when this gets
2107            // switched back on.
2108            //
2109            // self.update_since();
2110        }
2111        // No-op if existed is false, but still commit the state change so that
2112        // this gets linearized.
2113        Continue(existed)
2114    }
2115
2116    pub fn expire_critical_reader(
2117        &mut self,
2118        reader_id: &CriticalReaderId,
2119    ) -> ControlFlow<NoOpStateTransition<bool>, bool> {
2120        // We expire all readers if the upper and since both advance to the
2121        // empty antichain. Gracefully handle this. At the same time,
2122        // short-circuit the cmd application so we don't needlessly create new
2123        // SeqNos.
2124        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            // TODO(database-issues#6885): Re-enable this
2131            //
2132            // Temporarily disabling this because we think it might be the cause
2133            // of the remap since bug. Specifically, a clusterd process has a
2134            // ReadHandle for maintaining the once and one inside a Listen. If
2135            // we crash and stay down for longer than the read lease duration,
2136            // it's possible that an expiry of them both in quick succession
2137            // jumps the since forward to the Listen one.
2138            //
2139            // Don't forget to update the downgrade_since when this gets
2140            // switched back on.
2141            //
2142            // self.update_since();
2143        }
2144        // This state transition is a no-op if existed is false, but we still
2145        // commit the state change so that this gets linearized (maybe we're
2146        // looking at old state).
2147        Continue(existed)
2148    }
2149
2150    pub fn expire_writer(
2151        &mut self,
2152        writer_id: &WriterId,
2153    ) -> ControlFlow<NoOpStateTransition<bool>, bool> {
2154        // We expire all writers if the upper and since both advance to the
2155        // empty antichain. Gracefully handle this. At the same time,
2156        // short-circuit the cmd application so we don't needlessly create new
2157        // SeqNos.
2158        if self.is_tombstone() {
2159            return Break(NoOpStateTransition(false));
2160        }
2161
2162        let existed = self.writers.remove(writer_id).is_some();
2163        // This state transition is a no-op if existed is false, but we still
2164        // commit the state change so that this gets linearized (maybe we're
2165        // looking at old state).
2166        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                // If there are no current readers, leave `since` unchanged so
2203                // it doesn't regress.
2204                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        // critical_readers don't hold a seqno capability.
2219        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    /// A tombstone that has shrunk to a single empty batch.
2239    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        // Remember our current state, so we can decide whether we have to
2258        // record a transition in durable state.
2259        let was_tombstone = self.is_tombstone();
2260
2261        // Enter the "tombstone" state, if we're not in it already.
2262        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        // Now that we're in a "tombstone" state -- ie. nobody can read the data from a shard or write to
2269        // it -- the actual contents of our batches no longer matter.
2270        // This method progressively replaces batches in our state with simpler versions, to allow
2271        // freeing up resources and to reduce the state size. (Since the state is unreadable, this
2272        // is not visible to clients.) We do this a little bit at a time to avoid really large state
2273        // transitions... most operations happen incrementally, and large single writes can overwhelm
2274        // a backing store. See comments for why we believe the relevant diffs are reasonably small.
2275
2276        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            // We have a nonempty batch: replace it with an empty batch and return.
2286            // This should not produce an excessively large diff: if it did, we wouldn't have been
2287            // able to append that batch in the first place.
2288            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            // All our batches are empty, but we have more than one of them. Replace the whole set
2296            // with a new single-batch trace.
2297            // This produces a diff with a size proportional to the number of batches, but since
2298            // Spine keeps a logarithmic number of batches this should never be excessively large.
2299            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            // We were not tombstoned before, so have to make sure this state
2307            // transition is recorded.
2308            Continue(())
2309        } else {
2310            // All our batches are empty, and there's only one... there's no shrinking this
2311            // tombstone further.
2312            Break(NoOpStateTransition(()))
2313        }
2314    }
2315}
2316
2317// TODO: Document invariants.
2318#[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    /// A strictly increasing wall time of when this state was written, in
2325    /// milliseconds since the unix epoch.
2326    pub(crate) walltime_ms: u64,
2327    /// Hostname of the persist user that created this version of state. For
2328    /// debugging.
2329    pub(crate) hostname: String,
2330    pub(crate) collections: StateCollections<T>,
2331}
2332
2333/// A newtype wrapper of State that guarantees the K, V, and D codecs match the
2334/// ones in durable storage.
2335pub struct TypedState<K, V, T, D> {
2336    pub(crate) state: State<T>,
2337
2338    // According to the docs, PhantomData is to "mark things that act like they
2339    // own a T". State doesn't actually own K, V, or D, just the ability to
2340    // produce them. Using the `fn() -> T` pattern gets us the same variance as
2341    // T [1], but also allows State to correctly derive Send+Sync.
2342    //
2343    // [1]:
2344    //     https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns
2345    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        // Deconstruct self so we get a compile failure if new fields
2380        // are added.
2381        let TypedState { state, _phantom } = self;
2382        f.debug_struct("TypedState").field("state", state).finish()
2383    }
2384}
2385
2386// Impl PartialEq regardless of the type params.
2387#[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        // Deconstruct self and other so we get a compile failure if new fields
2391        // are added.
2392        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        // We do not increment the version by default, though work_fn can if it chooses to.
2464        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        // Make sure walltime_ms is strictly increasing, in case clocks are
2473        // offset.
2474        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/// See [State::finalized_gc_step].
2488#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2489pub(crate) enum FinalizedGcStep {
2490    WriteRollup,
2491    /// GC through this seqno.
2492    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    /// Mirrors `persist_gc_remove_finalized_rollups`.
2502    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        // We maintain the invariant that every version of state has at least
2556        // one rollup.
2557        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    /// Whether a tombstone has committed anything after linking its latest
2570    /// rollup. A rollup of seqno X is linked at X+1, so a settled tombstone
2571    /// has exactly those two live diffs.
2572    fn tombstone_needs_rollup(&self) -> bool {
2573        let (latest, _) = self.latest_rollup();
2574        self.collections.is_tombstone() && latest.next() < self.seqno
2575    }
2576
2577    /// The next step toward finishing GC on a finalized shard, or `None` when
2578    /// it's done. `earliest_live` is the earliest live diff's seqno in
2579    /// consensus, which state doesn't record.
2580    ///
2581    /// Each pass that removes old rollups adds one rollup of finalized state,
2582    /// which is kept, so a shard GC'd in several passes keeps one per pass.
2583    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        // GC can only delete what a commit after the latest rollup removed
2590        // (shrinking batches, or old rollups) by truncating to a later rollup.
2591        if self.tombstone_needs_rollup() {
2592            return Some(FinalizedGcStep::WriteRollup);
2593        }
2594        let (latest, _) = self.latest_rollup();
2595        // GC keeps the newest rollup <= new_seqno_since and truncates to it. With
2596        // only one rollup in range it removes and truncates nothing, so cap the
2597        // versions one pass fetches at max_versions, but extend to the next rollup
2598        // so every pass makes progress.
2599        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        // A rollup older than `latest` is still live in consensus, so there's one
2604        // to truncate away.
2605        if earliest_live < *latest {
2606            return Some(FinalizedGcStep::Gc(new_seqno_since));
2607        }
2608        // Consensus is already truncated to `latest`, but state can still list older
2609        // rollups: a prior GC died after truncating but before removing them from
2610        // state, or ran with remove_finalized_rollups off.
2611        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    // Returns whether the cmd proposing this state has been selected to perform
2619    // background garbage collection work.
2620    //
2621    // If it was selected, this information is recorded in the state itself for
2622    // commit along with the cmd's state transition. This helps us to avoid
2623    // redundant work.
2624    //
2625    // Correctness does not depend on a gc assignment being executed, nor on
2626    // them being executed in the order they are given. But it is expected that
2627    // gc assignments are best-effort respected. In practice, cmds like
2628    // register_foo or expire_foo, where it would be awkward, ignore gc.
2629    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        // This is an arbitrary-ish threshold that scales with seqno, but never
2638        // gets particularly big. It probably could be much bigger and certainly
2639        // could use a tuning pass at some point.
2640        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        // Collect until the new seqno since... or the old since plus the max number of versions,
2650        // whatever is less.
2651        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        // If we wouldn't otherwise gc, check if we have an active gc. If we do, and
2663        // it's been a while since it started, we should gc.
2664        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        // Assign GC traffic preferentially to writers, falling back to anyone
2673        // generating new state versions if there are no writers.
2674        let should_gc = should_gc && (is_write || self.collections.writers.is_empty());
2675        // Always assign GC work to a tombstoned shard to have the chance to
2676        // clean up any residual blobs. This is safe (won't cause excess gc)
2677        // as a tombstone only commits a few rollups and, once finalized, the
2678        // `remove_rollups` that drop the older ones.
2679        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            // If we have an active gc, we should only gc if the active gc is
2683            // sufficiently old. This is to avoid doing more gc work than
2684            // necessary.
2685            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        // A no-op GC on a tombstone leaves `active_gc` set, which would block
2694        // GC on the final `add_rollup`. Nothing commits after that, so the old
2695        // rollups would leak.
2696        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    /// Return the number of gc-ineligible state versions.
2709    pub fn seqnos_held(&self) -> usize {
2710        usize::cast_from(self.seqno.0.saturating_sub(self.seqno_since().0))
2711    }
2712
2713    /// Expire all readers and writers up to the given walltime_ms.
2714    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        // critical_readers don't need forced expiration. (In fact, that's the point!)
2729        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    /// Returns the batches that contain updates up to (and including) the given `as_of`. The
2745    /// result `Vec` contains blob keys, along with a [`Description`] of what updates in the
2746    /// referenced parts are valid to read.
2747    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    // NB: Unlike the other methods here, this one is read-only.
2772    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        // TODO: Avoid the O(n^2) here: `next_listen_batch` is called once per
2781        // batch and this iterates through all batches to find the next one.
2782        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        // Tombstoned shards require one final rollup. However, because we
2807        // write a rollup as of SeqNo X and then link it in using a state
2808        // transition (in this case from X to X+1), the minimum number of
2809        // live diffs is actually two. Detect when we're in this minimal
2810        // two diff state and stop the (otherwise) infinite iteration.
2811        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 sequnos_since_last_rollup>threshold, and there is no existing rollup in progress,
2819            // we should start a new rollup.
2820            // If there is an active rollup, we should check if it has been running too long.
2821            // If it has, we should start a new rollup.
2822            // This is to guard against a worker dying/taking too long/etc.
2823            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            // every `threshold` seqnos since the latest rollup, assign rollup maintenance.
2837            // we avoid assigning rollups to every seqno past the threshold to avoid handles
2838            // racing / performing redundant work.
2839            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            // however, since maintenance is best-effort and could fail, do assign rollup
2846            // work to every seqno after a fallback threshold to ensure one is written.
2847            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    // These bytes come from blob and are never validated on the way in, so a
2885    // malformed or newer-version encoding reaches here intact. Report it as
2886    // absent rather than panicking, and keep the field's shape stable for
2887    // consumers of the inspect-state output by logging the failure instead of
2888    // serializing a differently typed value in its place.
2889    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    // This is only used for debugging, so hack to assume that D is i64.
2901    let val = val.map(i64::decode);
2902    val.serialize(s)
2903}
2904
2905// This Serialize impl is used for debugging/testing and exposed via SQL. It's
2906// intentionally gated from users, so not strictly subject to our backward
2907// compatibility guarantees, but still probably best to be thoughtful about
2908// making unnecessary changes. Additionally, it's nice to make the output as
2909// nice to use as possible without tying our hands for the actual code usages.
2910impl<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/// Wrapper for Antichain that represents a Since
2975#[derive(Debug, Clone, PartialEq)]
2976pub struct Since<T>(pub Antichain<T>);
2977
2978/// Wrapper for Antichain that represents an Upper
2979#[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                // lease_duration_ms of 0 means this state was written by an old
3188                // version of code, which means we'll migrate it in the decode
3189                // path. Avoid.
3190                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        // The shard global since == 0 initially.
3394        assert_eq!(state.collections.trace.since(), &Antichain::from_elem(0));
3395
3396        // Greater
3397        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        // Equal (no-op)
3409        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        // Less (no-op)
3421        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        // Create a second reader.
3434        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        // Shard since doesn't change until the meet (min) of all reader sinces changes.
3446        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        // Shard since == 3 when all readers have since >= 3.
3458        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        // Shard since unaffected readers with since > shard since expiring.
3471        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        // Create a third reader.
3478        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        // Shard since doesn't change until the meet (min) of all reader sinces changes.
3490        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        // Shard since advances when reader with the minimal since expires.
3503        assert_eq!(
3504            state.collections.expire_leased_reader(&reader2),
3505            Continue(true)
3506        );
3507        // TODO(database-issues#6885): expiry temporarily doesn't advance since
3508        // Switch this assertion back when we re-enable this.
3509        //
3510        // assert_eq!(state.collections.trace.since(), &Antichain::from_elem(10));
3511        assert_eq!(state.collections.trace.since(), &Antichain::from_elem(3));
3512
3513        // Shard since unaffected when all readers are expired.
3514        assert_eq!(
3515            state.collections.expire_leased_reader(&reader3),
3516            Continue(true)
3517        );
3518        // TODO(database-issues#6885): expiry temporarily doesn't advance since
3519        // Switch this assertion back when we re-enable this.
3520        //
3521        // assert_eq!(state.collections.trace.since(), &Antichain::from_elem(10));
3522        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        // The shard global since == 0 initially.
3539        assert_eq!(state.collections.trace.since(), &Antichain::from_elem(0));
3540        // The initial opaque value should be set.
3541        assert_eq!(
3542            state
3543                .collections
3544                .critical_reader(&reader)
3545                .opaque
3546                .decode::<u64>(),
3547            u64::MIN
3548        );
3549
3550        // Greater
3551        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        // Equal (no-op)
3569        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        // Less (no-op)
3587        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        // State is initially empty.
3620        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        // Cannot insert a batch with a lower != current shard upper.
3625        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        // Insert an empty batch with an upper > lower..
3644        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        // Cannot insert a batch with a upper less than the lower.
3661        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        // Cannot insert a nonempty batch with an upper equal to lower.
3680        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        // Can insert an empty batch with an upper equal to lower.
3702        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        // Cannot take a snapshot with as_of == shard upper.
3730        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        // Cannot take a snapshot with as_of > shard upper.
3739        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        // Advance upper to 5.
3750        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        // Can take a snapshot with as_of < upper.
3768        assert_eq!(
3769            state.snapshot(&Antichain::from_elem(0)),
3770            Ok(vec![hollow(0, 5, &["key1"], 1)])
3771        );
3772
3773        // Can take a snapshot with as_of >= shard since, as long as as_of < shard_upper.
3774        assert_eq!(
3775            state.snapshot(&Antichain::from_elem(4)),
3776            Ok(vec![hollow(0, 5, &["key1"], 1)])
3777        );
3778
3779        // Cannot take a snapshot with as_of >= upper.
3780        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        // Advance the since to 2.
3797        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        // Cannot take a snapshot with as_of < shard_since.
3818        assert_eq!(
3819            state.snapshot(&Antichain::from_elem(1)),
3820            Err(SnapshotErr::AsOfHistoricalDistinctionsLost(Since(
3821                Antichain::from_elem(2)
3822            )))
3823        );
3824
3825        // Advance the upper to 10 via an empty batch.
3826        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        // Can still take snapshots at times < upper.
3844        assert_eq!(
3845            state.snapshot(&Antichain::from_elem(7)),
3846            Ok(vec![hollow(0, 5, &["key1"], 1), hollow(5, 10, &[], 0)])
3847        );
3848
3849        // Cannot take snapshots with as_of >= upper.
3850        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        // Advance upper to 15.
3859        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        // Filter out batches whose lowers are less than the requested as of (the
3877        // batches that are too far in the future for the requested as_of).
3878        assert_eq!(
3879            state.snapshot(&Antichain::from_elem(9)),
3880            Ok(vec![hollow(0, 5, &["key1"], 1), hollow(5, 10, &[], 0)])
3881        );
3882
3883        // Don't filter out batches whose lowers are <= the requested as_of.
3884        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        // Empty collection never has any batches to listen for, regardless of the
3913        // current frontier.
3914        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        // Add two batches of data, one from [0, 5) and then another from [5, 10).
3924        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        // All frontiers in [0, 5) return the first batch.
3958        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        // All frontiers in [5, 10) return the second batch.
3966        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        // There is no batch currently available for t = 10.
3974        assert_eq!(
3975            state.next_listen_batch(&Antichain::from_elem(10)),
3976            Err(SeqNo(0))
3977        );
3978
3979        // By definition, there is no frontier ever at the empty antichain which
3980        // is the time after all possible times.
3981        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        // Writer is eligible to write
3999        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        // Other writers should still be able to write
4024        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        // Empty state doesn't need gc, regardless of is_write.
4062        assert_eq!(state.maybe_gc(true, now, GC_CONFIG), None);
4063        assert_eq!(state.maybe_gc(false, now, GC_CONFIG), None);
4064
4065        // Artificially advance the seqno so the seqno_since advances past our
4066        // internal gc_threshold.
4067        state.seqno = SeqNo(100);
4068        assert_eq!(state.seqno_since(), SeqNo(100));
4069
4070        // When a writer is present, non-writes don't gc.
4071        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        // A write will gc though.
4086        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        // But if we write down an active gc, we won't gc.
4095        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        // But if we advance the time past the threshold, we will gc.
4108        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        // Even if the sequence number doesn't pass the threshold, if the
4118        // active gc is expired, we will gc.
4119
4120        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        // Artificially advance the seqno (again) so the seqno_since advances
4133        // past our internal gc_threshold (again).
4134        state.seqno = SeqNo(400);
4135        assert_eq!(state.seqno_since(), SeqNo(400));
4136
4137        let now = now_fn();
4138
4139        // If there are no writers, even a non-write will gc.
4140        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        // Upper-bound the number of seqnos we'll attempt to collect in one go.
4150        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        // Empty state doesn't need gc, regardless of is_write.
4183        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        // Artificially advance the seqno so the seqno_since advances past our
4187        // internal gc_threshold.
4188        state.seqno = SeqNo(100);
4189        assert_eq!(state.seqno_since(), SeqNo(100));
4190
4191        // When a writer is present, non-writes don't gc.
4192        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        // A write will gc though.
4208        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        // Artificially advance the seqno (again) so the seqno_since advances
4217        // past our internal gc_threshold (again).
4218        state.seqno = SeqNo(200);
4219        assert_eq!(state.seqno_since(), SeqNo(200));
4220
4221        // If there are no writers, even a non-write will gc.
4222        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        // shouldn't need a rollup at the seqno of the rollup
4262        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        // shouldn't need a rollup at seqnos less than our threshold
4271        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        // hit our threshold! we should need a rollup
4295        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        // There is now an active rollup, so we shouldn't need a rollup.
4314        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        // We still don't need a rollup, even though the seqno is greater than
4323        // the rollup threshold.
4324        assert_none!(state.need_rollup(
4325            ROLLUP_THRESHOLD,
4326            ROLLUP_USE_ACTIVE_ROLLUP,
4327            ROLLUP_FALLBACK_THRESHOLD_MS,
4328            current_time
4329        ));
4330
4331        // But if we wait long enough, we should need a rollup again.
4332        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        // Clear the active rollup and ensure we need a rollup again.
4347        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        // We shouldn't need a rollup at seqnos less than our threshold
4363        assert_none!(state.need_rollup(
4364            ROLLUP_THRESHOLD,
4365            ROLLUP_USE_ACTIVE_ROLLUP,
4366            ROLLUP_FALLBACK_THRESHOLD_MS,
4367            current_time
4368        ));
4369        // hit our threshold! we should need a rollup
4370        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        // shouldn't need a rollup at the seqno of the rollup
4414        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        // shouldn't need a rollup at seqnos less than our threshold
4423        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        // hit our threshold! we should need a rollup
4439        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        // but we don't need rollups for every seqno > the threshold
4453        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        // we only need a rollup each `ROLLUP_THRESHOLD` beyond our current seqno
4462        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        // add another rollup and ensure we're always picking the latest
4476        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        // and ensure that after a fallback point, we assign every seqno work
4510        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    /// This test generates an "arbitrary" State, but uses a fixed seed for the
4549    /// randomness, so that it's deterministic. This lets us assert the
4550    /// serialization of that State against a golden file that's committed,
4551    /// making it easy to see what the serialization (used in an upcoming
4552    /// INSPECT feature) looks like.
4553    ///
4554    /// This golden will have to be updated each time we change State, but
4555    /// that's a feature, not a bug.
4556    #[mz_ore::test]
4557    #[cfg_attr(miri, ignore)] // too slow
4558    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)] // too slow
4573    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            // Run in a task so we can catch the panic.
4586            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                // Do a write so that we tag the state with the version.
4594                write
4595                    .expect_compare_and_append_batch(&mut [], current, current + 1)
4596                    .await;
4597            })
4598            .into_tokio_handle()
4599            .await
4600        }
4601
4602        // Start at v0.10.0.
4603        let res = open_and_write(&mut clients, Version::new(0, 10, 0), shard_id).await;
4604        assert_ok!(res);
4605
4606        // Upgrade to v0.11.0 is allowed.
4607        let res = open_and_write(&mut clients, Version::new(0, 11, 0), shard_id).await;
4608        assert_ok!(res);
4609
4610        // Downgrade to v0.10.0 is no longer allowed.
4611        let res = open_and_write(&mut clients, Version::new(0, 10, 0), shard_id).await;
4612        assert!(res.unwrap_err().is_panic());
4613
4614        // Downgrade to v0.9.0 is _NOT_ allowed.
4615        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    /// Regression for PER-16. `add_rollup` must refuse to (re-)insert a
4629    /// rollup at a seqno that GC has already physically removed.
4630    /// Without this guard, an `apply_unbatched_idempotent_cmd` retry of
4631    /// `add_rollup` that runs after a concurrent GC removed the rollup's
4632    /// original map entry will re-insert it under the same key, producing
4633    /// duplicate Insert events in the diff stream and (later) duplicate
4634    /// Delete events that trip the `assert!` in `gc.rs`'s
4635    /// `find_removable_blobs`.
4636    ///
4637    /// This test reaches the bug state via the public
4638    /// `add_rollup` → `add_rollup` (newer) → `remove_rollups` (the older
4639    /// one) → `add_rollup` (retry of the older one) sequence, mirroring
4640    /// how a delayed retry of an indeterminate add_rollup commit can race
4641    /// a concurrent GC pass that has since added a newer rollup and
4642    /// removed the older one.
4643    #[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        // First attempt commits the older rollup.
4667        assert_eq!(add_older(&mut state.collections), Continue(true));
4668        // A repeat at the same seqno with the same key is the pre-existing
4669        // idempotent no-op and should report applied=true.
4670        assert_eq!(add_older(&mut state.collections), Continue(true));
4671        assert_eq!(state.collections.rollups.len(), 1);
4672
4673        // The shard keeps making progress and a later command commits a
4674        // newer rollup. This is what gives GC something to keep when it
4675        // later removes the older entry.
4676        assert_eq!(
4677            state.collections.add_rollup((newer_seqno, &newer)),
4678            Continue(true),
4679        );
4680
4681        // The GC worker, having found a kept rollup at `newer_seqno`,
4682        // commits the removal of the older one. State.rollups now only
4683        // contains the kept rollup; the older entry is gone.
4684        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        // The retry replays the same captured `(older_seqno, older)`
4691        // tuple. Even though no entry references the key anymore,
4692        // re-inserting it must be refused: `older_seqno` falls below the
4693        // smallest live rollup seqno, which is the GC watermark.
4694        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        // The final rollup at v5 is added at v6, and GC's removal of v1 at v7
4729        // asks for one more.
4730        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}