Skip to main content

mz_persist_client/internal/
machine.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
10//! Implementation of the persist state machine.
11
12use std::fmt::Debug;
13use std::ops::ControlFlow::{self, Break, Continue};
14use std::sync::Arc;
15use std::time::{Duration, Instant, SystemTime};
16
17use differential_dataflow::difference::Monoid;
18use differential_dataflow::lattice::Lattice;
19use futures::FutureExt;
20use futures::future::{self, BoxFuture};
21use mz_dyncfg::{Config, ConfigSet, ParameterScope};
22use mz_ore::cast::CastFrom;
23use mz_ore::error::ErrorExt;
24#[allow(unused_imports)] // False positive.
25use mz_ore::fmt::FormatBuffer;
26use mz_ore::{assert_none, soft_assert_no_log};
27use mz_persist::location::{ExternalError, Indeterminate, SeqNo};
28use mz_persist::retry::Retry;
29use mz_persist_types::schema::SchemaId;
30use mz_persist_types::{Codec, Codec64};
31use semver::Version;
32use timely::PartialOrder;
33use timely::progress::{Antichain, Timestamp};
34use tracing::{Instrument, debug, info, trace_span, warn};
35
36use crate::async_runtime::IsolatedRuntime;
37use crate::batch::INLINE_WRITES_TOTAL_MAX_BYTES;
38use crate::cache::StateCache;
39use crate::cfg::RetryParameters;
40use crate::critical::{CriticalReaderId, Opaque};
41use crate::error::{CodecMismatch, InvalidUsage};
42use crate::internal::apply::Applier;
43use crate::internal::compact::CompactReq;
44use crate::internal::gc::{GarbageCollector, GcCaller, GcReq};
45use crate::internal::maintenance::{RoutineMaintenance, WriterMaintenance};
46use crate::internal::metrics::{CmdMetrics, Metrics, MetricsRetryStream, RetryMetrics};
47use crate::internal::paths::PartialRollupKey;
48use crate::internal::state::{
49    CompareAndAppendBreak, CriticalReaderState, FinalizedGcStep, HandleDebugState, HollowBatch,
50    HollowRollup, IdempotencyToken, LeasedReaderState, NoOpStateTransition, Since, SnapshotErr,
51    StateCollections,
52};
53use crate::internal::state_versions::StateVersions;
54use crate::internal::trace::{ApplyMergeResult, FueledMergeRes};
55use crate::internal::watch::StateWatch;
56use crate::read::LeasedReaderId;
57use crate::rpc::PubSubSender;
58use crate::schema::CaESchema;
59use crate::write::WriterId;
60use crate::{Diagnostics, PersistConfig, ShardId};
61
62#[derive(Debug)]
63pub struct Machine<K, V, T, D> {
64    pub(crate) applier: Applier<K, V, T, D>,
65    pub(crate) isolated_runtime: Arc<IsolatedRuntime>,
66}
67
68// Impl Clone regardless of the type params.
69impl<K, V, T: Clone, D> Clone for Machine<K, V, T, D> {
70    fn clone(&self) -> Self {
71        Self {
72            applier: self.applier.clone(),
73            isolated_runtime: Arc::clone(&self.isolated_runtime),
74        }
75    }
76}
77
78pub(crate) const CLAIM_UNCLAIMED_COMPACTIONS: Config<bool> = Config::new(
79    "persist_claim_unclaimed_compactions",
80    false,
81    "If an append doesn't result in a compaction request, but there is some uncompacted batch \
82    in state, compact that instead.",
83    ParameterScope::Environment,
84);
85
86pub(crate) const CLAIM_COMPACTION_PERCENT: Config<usize> = Config::new(
87    "persist_claim_compaction_percent",
88    100,
89    "Claim a compaction with the given percent chance, if claiming compactions is enabled. \
90    (If over 100, we'll always claim at least one; for example, if set to 365, we'll claim at least \
91    three and have a 65% chance of claiming a fourth.)",
92    ParameterScope::Environment,
93);
94
95pub(crate) const CLAIM_COMPACTION_MIN_VERSION: Config<String> = Config::new(
96    "persist_claim_compaction_min_version",
97    String::new(),
98    "If set to a valid version string, compact away any earlier versions if possible.",
99    ParameterScope::Environment,
100);
101
102impl<K, V, T, D> Machine<K, V, T, D>
103where
104    K: Debug + Codec,
105    V: Debug + Codec,
106    T: Timestamp + Lattice + Codec64 + Sync,
107    D: Monoid + Codec64,
108{
109    pub async fn new(
110        cfg: PersistConfig,
111        shard_id: ShardId,
112        metrics: Arc<Metrics>,
113        state_versions: Arc<StateVersions>,
114        shared_states: Arc<StateCache>,
115        pubsub_sender: Arc<dyn PubSubSender>,
116        isolated_runtime: Arc<IsolatedRuntime>,
117        diagnostics: Diagnostics,
118    ) -> Result<Self, Box<CodecMismatch>> {
119        let applier = Applier::new(
120            cfg,
121            shard_id,
122            metrics,
123            state_versions,
124            shared_states,
125            pubsub_sender,
126            diagnostics,
127        )
128        .await?;
129        Ok(Machine {
130            applier,
131            isolated_runtime,
132        })
133    }
134
135    pub fn shard_id(&self) -> ShardId {
136        self.applier.shard_id
137    }
138
139    pub fn seqno(&self) -> SeqNo {
140        self.applier.seqno()
141    }
142
143    pub async fn add_rollup_for_current_seqno(&self) -> RoutineMaintenance {
144        let rollup = self.applier.write_rollup_for_state().await;
145        let Some(rollup) = rollup else {
146            return RoutineMaintenance::default();
147        };
148
149        let (applied, maintenance) = self.add_rollup((rollup.seqno, &rollup.to_hollow())).await;
150        if !applied {
151            // Someone else already wrote a rollup at this seqno, so ours didn't
152            // get added. Delete it.
153            self.applier
154                .state_versions
155                .delete_rollup(&rollup.shard_id, &rollup.key)
156                .await;
157        }
158        maintenance
159    }
160
161    pub async fn add_rollup(
162        &self,
163        add_rollup: (SeqNo, &HollowRollup),
164    ) -> (bool, RoutineMaintenance) {
165        // See the big SUBTLE comment in [Self::merge_res] for what's going on
166        // here.
167        let mut applied_ever_true = false;
168        let metrics = Arc::clone(&self.applier.metrics);
169        let (_seqno, _applied, maintenance) = self
170            .apply_unbatched_idempotent_cmd(&metrics.cmds.add_rollup, |_, _, state| {
171                let ret = state.add_rollup(add_rollup);
172                if let Continue(applied) = ret {
173                    applied_ever_true = applied_ever_true || applied;
174                }
175                ret
176            })
177            .await;
178        (applied_ever_true, maintenance)
179    }
180
181    pub async fn remove_rollups(
182        &self,
183        remove_rollups: &[(SeqNo, PartialRollupKey)],
184        remove_finalized: bool,
185    ) -> (Vec<SeqNo>, RoutineMaintenance) {
186        let metrics = Arc::clone(&self.applier.metrics);
187        let (_seqno, removed_rollup_seqnos, maintenance) = self
188            .apply_unbatched_idempotent_cmd(&metrics.cmds.remove_rollups, |_, _, state| {
189                state.remove_rollups(remove_rollups, remove_finalized)
190            })
191            .await;
192        (removed_rollup_seqnos, maintenance)
193    }
194
195    /// Attempt to upgrade the state to the latest version. If that's not possible, return the
196    /// actual data version of the shard.
197    pub async fn upgrade_version(&self) -> Result<RoutineMaintenance, Version> {
198        let metrics = Arc::clone(&self.applier.metrics);
199        let (_seqno, upgrade_result, maintenance) = self
200            .apply_unbatched_idempotent_cmd(&metrics.cmds.upgrade_version, |_, cfg, state| {
201                // A tombstone is terminal and version-inert, so treat the
202                // upgrade as trivially satisfied instead of committing a new
203                // state that `compute_next_state_locked` would reject.
204                if state.is_tombstone() {
205                    return Break(NoOpStateTransition(Ok(())));
206                }
207
208                if state.version <= cfg.build_version {
209                    // This would be the place to remove any deprecated items from state, now
210                    // that we're dropping compatibility with any previous versions.
211                    state.version = cfg.build_version.clone();
212                    Continue(Ok(()))
213                } else {
214                    Break(NoOpStateTransition(Err(state.version.clone())))
215                }
216            })
217            .await;
218
219        match upgrade_result {
220            Ok(()) => Ok(maintenance),
221            Err(version) => {
222                soft_assert_no_log!(
223                    maintenance.is_empty(),
224                    "should not generate maintenance on failed upgrade"
225                );
226                Err(version)
227            }
228        }
229    }
230
231    /// Registers a leased reader, returning its initial state.
232    pub async fn register_leased_reader(
233        &self,
234        reader_id: &LeasedReaderId,
235        purpose: &str,
236        lease_duration: Duration,
237        use_critical_since: bool,
238    ) -> (LeasedReaderState<T>, RoutineMaintenance) {
239        let metrics = Arc::clone(&self.applier.metrics);
240        let (_seqno, (reader_state, seqno_since), maintenance) = self
241            .apply_unbatched_idempotent_cmd(&metrics.cmds.register, |seqno, cfg, state| {
242                state.register_leased_reader(
243                    &cfg.hostname,
244                    reader_id,
245                    purpose,
246                    seqno,
247                    lease_duration,
248                    // NOTE: Sample the clock here rather than hoisting it out of the closure so
249                    // that a fresh value is used on every retry of this command.
250                    (cfg.now)(),
251                    use_critical_since,
252                )
253            })
254            .await;
255        // Usually, the reader gets an initial seqno hold of the seqno at which
256        // it was registered. However, on a tombstone shard the seqno hold
257        // happens to get computed as the tombstone seqno + 1
258        // (State::clone_apply provided seqno.next(), the non-no-op commit
259        // seqno, to the work fn and this is what register_reader uses for the
260        // seqno hold). The real invariant we want to protect here is that the
261        // hold is >= the seqno_since, so validate that instead of anything more
262        // specific.
263        mz_ore::soft_assert_no_log!(
264            reader_state.seqno >= seqno_since,
265            "leased reader {} registered with seqno hold {} below the shard's seqno_since {}",
266            reader_id,
267            reader_state.seqno,
268            seqno_since,
269        );
270        (reader_state, maintenance)
271    }
272
273    pub async fn register_critical_reader(
274        &self,
275        reader_id: &CriticalReaderId,
276        default_opaque: Opaque,
277        purpose: &str,
278    ) -> (CriticalReaderState<T>, RoutineMaintenance) {
279        let metrics = Arc::clone(&self.applier.metrics);
280        let (_seqno, state, maintenance) = self
281            .apply_unbatched_idempotent_cmd(&metrics.cmds.register, |_seqno, cfg, state| {
282                state.register_critical_reader(
283                    &cfg.hostname,
284                    reader_id,
285                    default_opaque.clone(),
286                    purpose,
287                )
288            })
289            .await;
290        (state, maintenance)
291    }
292
293    pub async fn register_schema(
294        &self,
295        key_schema: &K::Schema,
296        val_schema: &V::Schema,
297    ) -> (Option<SchemaId>, RoutineMaintenance) {
298        let metrics = Arc::clone(&self.applier.metrics);
299        let register = || {
300            self.apply_unbatched_idempotent_cmd(&metrics.cmds.register, |_seqno, _cfg, state| {
301                state.register_schema::<K, V>(key_schema, val_schema)
302            })
303        };
304        let (_seqno, mut schema_id, mut maintenance) = register().await;
305        // `None` is a no-op that never reaches consensus, so our cached state
306        // may lack a schema another process added with `compare_and_evolve_schema`.
307        // Refetching without a seqno hint always reads consensus, so one retry
308        // sees every schema registered before this call. A tombstone's `None`
309        // is final, because `Applier::compute_next_state_locked` rejects
310        // schema commits on tombstones.
311        if schema_id.is_none() && !self.applier.is_tombstone() {
312            self.applier.fetch_and_update_state(None).await;
313            (_, schema_id, maintenance) = register().await;
314        }
315        (schema_id, maintenance)
316    }
317
318    pub async fn spine_exert(&self, fuel: usize) -> (Vec<CompactReq<T>>, RoutineMaintenance) {
319        // Performance special case for no-ops, to avoid the State clones.
320        if fuel == 0 || self.applier.all_batches().len() < 2 {
321            return (Vec::new(), RoutineMaintenance::default());
322        }
323
324        let metrics = Arc::clone(&self.applier.metrics);
325        let (_seqno, reqs, maintenance) = self
326            .apply_unbatched_idempotent_cmd(&metrics.cmds.spine_exert, |_seqno, _cfg, state| {
327                state.spine_exert(fuel)
328            })
329            .await;
330        let reqs = reqs
331            .into_iter()
332            .map(|req| CompactReq {
333                shard_id: self.shard_id(),
334                desc: req.desc,
335                inputs: req.inputs,
336            })
337            .collect();
338        (reqs, maintenance)
339    }
340
341    /// Appends `batch` if the shard upper matches its lower.
342    pub async fn compare_and_append(
343        &self,
344        batch: &HollowBatch<T>,
345        writer_id: &WriterId,
346        debug_info: &HandleDebugState,
347    ) -> CompareAndAppendRes<T> {
348        let idempotency_token = IdempotencyToken::new();
349        loop {
350            let res = self
351                .compare_and_append_idempotent(
352                    batch,
353                    writer_id,
354                    &idempotency_token,
355                    debug_info,
356                    None,
357                )
358                .await;
359            match res {
360                CompareAndAppendRes::Success(seqno, maintenance) => {
361                    return CompareAndAppendRes::Success(seqno, maintenance);
362                }
363                CompareAndAppendRes::InvalidUsage(x) => {
364                    return CompareAndAppendRes::InvalidUsage(x);
365                }
366                CompareAndAppendRes::InlineBackpressure => {
367                    return CompareAndAppendRes::InlineBackpressure;
368                }
369                CompareAndAppendRes::UpperMismatch(seqno, _current_upper) => {
370                    // If the state machine thinks that the shard upper is not
371                    // far enough along, it could be because the caller of this
372                    // method has found out that it advanced via some some
373                    // side-channel that didn't update our local cache of the
374                    // machine state. So, fetch the latest state and try again
375                    // if we indeed get something different.
376                    self.applier.fetch_and_update_state(Some(seqno)).await;
377                    let (current_seqno, current_upper) =
378                        self.applier.upper(|seqno, upper| (seqno, upper.clone()));
379
380                    // We tried to to a compare_and_append with the wrong
381                    // expected upper, that won't work.
382                    if &current_upper != batch.desc.lower() {
383                        return CompareAndAppendRes::UpperMismatch(current_seqno, current_upper);
384                    } else {
385                        // The upper stored in state was outdated. Retry after
386                        // updating.
387                    }
388                }
389            }
390        }
391    }
392
393    async fn compare_and_append_idempotent(
394        &self,
395        batch: &HollowBatch<T>,
396        writer_id: &WriterId,
397        idempotency_token: &IdempotencyToken,
398        debug_info: &HandleDebugState,
399        // Only exposed for testing. In prod, this always starts as None, but
400        // making it a parameter allows us to simulate hitting an indeterminate
401        // error on the first attempt in tests.
402        mut indeterminate: Option<Indeterminate>,
403    ) -> CompareAndAppendRes<T> {
404        let metrics = Arc::clone(&self.applier.metrics);
405        let lease_duration_ms = self
406            .applier
407            .cfg
408            .writer_lease_duration
409            .as_millis()
410            .try_into()
411            .expect("reasonable duration");
412        // SUBTLE: Retries of compare_and_append with Indeterminate errors are
413        // tricky (more discussion of this in database-issues#3680):
414        //
415        // - (1) We compare_and_append and get an Indeterminate error back from
416        //   CRDB/Consensus. This means we don't know if it committed or not.
417        // - (2) We retry it.
418        // - (3) We get back an upper mismatch. The tricky bit is deciding if we
419        //   conflicted with some other writer OR if the write in (1) actually
420        //   went through and we're "conflicting" with ourself.
421        //
422        // A number of scenarios can be distinguished with per-writer
423        // idempotency tokens, so I'll jump straight to the hardest one:
424        //
425        // - (1) A compare_and_append is issued for e.g. `[5,7)`, the consensus
426        //   call makes it onto the network before the operation is cancelled
427        //   (by dropping the future).
428        // - (2) A compare_and_append is issued from the same WriteHandle for
429        //   `[3,5)`, it uses a different conn from the consensus pool and gets
430        //   an Indeterminate error.
431        // - (3) The call in (1) is received by consensus and commits.
432        // - (4) The retry of (2) receives an upper mismatch with an upper of 7.
433        //
434        // At this point, how do we determine whether (2) committed or not and
435        // thus whether we should return success or upper mismatch? Getting this
436        // right is very important for correctness (imagine this is a table
437        // write and we either return success or failure to the client).
438        //
439        // - If we use per-writer IdempotencyTokens but only store the latest
440        //   one in state, then the `[5,7)` one will have clobbered whatever our
441        //   `[3,5)` one was.
442        // - We could store every IdempotencyToken that ever committed, but that
443        //   would require unbounded storage in state (non-starter).
444        // - We could require that IdempotencyTokens are comparable and that
445        //   each call issued by a WriteHandle uses one that is strictly greater
446        //   than every call before it. A previous version of this PR tried this
447        //   and it's remarkably subtle. As a result, I (Dan) have developed
448        //   strong feels that our correctness protocol _should not depend on
449        //   WriteHandle, only Machine_.
450        // - We could require a new WriterId if a request is ever cancelled by
451        //   making `compare_and_append` take ownership of `self` and then
452        //   handing it back for any call polled to completion. The ergonomics
453        //   of this are quite awkward and, like the previous idea, it depends
454        //   on the WriteHandle impl for correctness.
455        // - Any ideas that involve reading back the data are foiled by a step
456        //   `(0) set the since to 100` (plus the latency and memory usage would
457        //   be too unpredictable).
458        //
459        // The technique used here derives from the following observations:
460        //
461        // - In practice, we don't use compare_and_append with the sort of
462        //   "regressing frontiers" described above.
463        // - In practice, Indeterminate errors are rare-ish. They happen enough
464        //   that we don't want to always panic on them, but this is still a
465        //   useful property to build on.
466        //
467        // At a high level, we do just enough to be able to distinguish the
468        // cases that we think will happen in practice and then leave the rest
469        // for a panic! that we think we'll never see. Concretely:
470        //
471        // - Run compare_and_append in a loop, retrying on Indeterminate errors
472        //   but noting if we've ever done that.
473        // - If we haven't seen an Indeterminate error (i.e. this is the first
474        //   time though the loop) then the result we got is guaranteed to be
475        //   correct, so pass it up.
476        // - Otherwise, any result other than an expected upper mismatch is
477        //   guaranteed to be correct, so just pass it up.
478        // - Otherwise examine the writer's most recent upper and break it into
479        //   two cases:
480        // - Case 1 `expected_upper.less_than(writer_most_recent_upper)`: it's
481        //   impossible that we committed on a previous iteration because the
482        //   overall upper of the shard is less_than what this call would have
483        //   advanced it to. Pass up the expectation mismatch.
484        // - Case 2 `!Case1`: First note that this means our IdempotencyToken
485        //   didn't match, otherwise we would have gotten `AlreadyCommitted`. It
486        //   also means some previous write from _this writer_ has committed an
487        //   upper that is beyond the one in this call, which is a weird usage
488        //   (NB can't be a future write because that would mean someone is
489        //   still polling us, but `&mut self` prevents that).
490        //
491        // TODO: If this technique works in practice (leads to zero panics),
492        // then commit to it and remove the Indeterminate from
493        // [WriteHandle::compare_and_append_batch].
494        let mut retry = self
495            .applier
496            .metrics
497            .retries
498            .compare_and_append_idempotent
499            .stream(Retry::persist_defaults(SystemTime::now()).into_retry_stream());
500        let mut writer_was_present = false;
501        loop {
502            let cmd_res = self
503                .applier
504                .apply_unbatched_cmd(&metrics.cmds.compare_and_append, |_, cfg, state| {
505                    writer_was_present = state.writers.contains_key(writer_id);
506                    state.compare_and_append(
507                        batch,
508                        writer_id,
509                        // NOTE: Sample the clock here rather than hoisting it out of the closure
510                        // so that a fresh value is used on every retry of this command.
511                        (cfg.now)(),
512                        lease_duration_ms,
513                        idempotency_token,
514                        debug_info,
515                        INLINE_WRITES_TOTAL_MAX_BYTES.get(cfg),
516                        if CLAIM_UNCLAIMED_COMPACTIONS.get(cfg) {
517                            CLAIM_COMPACTION_PERCENT.get(cfg)
518                        } else {
519                            0
520                        },
521                        Version::parse(&CLAIM_COMPACTION_MIN_VERSION.get(cfg))
522                            .ok()
523                            .as_ref(),
524                    )
525                })
526                .await;
527            let (seqno, res, routine) = match cmd_res {
528                Ok(x) => x,
529                Err(err) => {
530                    // These are rare and interesting enough that we always log
531                    // them at info!.
532                    info!(
533                        "compare_and_append received an indeterminate error, retrying in {:?}: {}",
534                        retry.next_sleep(),
535                        err.display_with_causes()
536                    );
537                    if indeterminate.is_none() {
538                        indeterminate = Some(err);
539                    }
540                    retry = retry.sleep().await;
541                    continue;
542                }
543            };
544            match res {
545                Ok(merge_reqs) => {
546                    // We got explicit confirmation that we succeeded, so
547                    // anything that happened in a previous retry is irrelevant.
548                    let mut compact_reqs = Vec::with_capacity(merge_reqs.len());
549                    for req in merge_reqs {
550                        let req = CompactReq {
551                            shard_id: self.shard_id(),
552                            desc: req.desc,
553                            inputs: req.inputs,
554                        };
555                        compact_reqs.push(req);
556                    }
557                    let writer_maintenance = WriterMaintenance {
558                        routine,
559                        compaction: compact_reqs,
560                    };
561
562                    if !writer_was_present {
563                        metrics.state.writer_added.inc();
564                    }
565                    for part in &batch.parts {
566                        if part.is_inline() {
567                            let bytes = u64::cast_from(part.inline_bytes());
568                            metrics.inline.part_commit_bytes.inc_by(bytes);
569                            metrics.inline.part_commit_count.inc();
570                        }
571                    }
572                    return CompareAndAppendRes::Success(seqno, writer_maintenance);
573                }
574                Err(CompareAndAppendBreak::AlreadyCommitted) => {
575                    // A previous iteration through this loop got an
576                    // Indeterminate error but was successful. Sanity check this
577                    // and pass along the good news.
578                    assert!(indeterminate.is_some());
579                    self.applier.metrics.cmds.compare_and_append_noop.inc();
580                    if !writer_was_present {
581                        metrics.state.writer_added.inc();
582                    }
583                    return CompareAndAppendRes::Success(seqno, WriterMaintenance::default());
584                }
585                Err(CompareAndAppendBreak::InvalidUsage(err)) => {
586                    // InvalidUsage is (or should be) a deterministic function
587                    // of the inputs and independent of anything in persist
588                    // state. It's handed back via a Break, so we never even try
589                    // to commit it. No network, no Indeterminate.
590                    assert_none!(indeterminate);
591                    return CompareAndAppendRes::InvalidUsage(err);
592                }
593                Err(CompareAndAppendBreak::InlineBackpressure) => {
594                    // We tried to write an inline part, but there was already
595                    // too much in state. Flush it out to s3 and try again.
596                    return CompareAndAppendRes::InlineBackpressure;
597                }
598                Err(CompareAndAppendBreak::Upper {
599                    shard_upper,
600                    writer_upper,
601                }) => {
602                    // NB the below intentionally compares to writer_upper
603                    // (because it gives a tighter bound on the bad case), but
604                    // returns shard_upper (what the persist caller cares
605                    // about).
606                    assert!(
607                        PartialOrder::less_equal(&writer_upper, &shard_upper),
608                        "{:?} vs {:?}",
609                        writer_upper,
610                        shard_upper
611                    );
612                    if PartialOrder::less_than(&writer_upper, batch.desc.upper()) {
613                        // No way this could have committed in some previous
614                        // attempt of this loop: the upper of the writer is
615                        // strictly less than the proposed new upper.
616                        return CompareAndAppendRes::UpperMismatch(seqno, shard_upper);
617                    }
618                    if indeterminate.is_none() {
619                        // No way this could have committed in some previous
620                        // attempt of this loop: we never saw an indeterminate
621                        // error (thus there was no previous iteration of the
622                        // loop).
623                        return CompareAndAppendRes::UpperMismatch(seqno, shard_upper);
624                    }
625                    // This is the bad case. We can't distinguish if some
626                    // previous attempt that got an Indeterminate error
627                    // succeeded or not. This should be sufficiently rare in
628                    // practice (hopefully ~never) that we give up and let
629                    // process restart fix things. See the big comment above for
630                    // more context.
631                    //
632                    // NB: This is intentionally not a halt! because it's quite
633                    // unexpected.
634                    panic!(
635                        concat!(
636                            "cannot distinguish compare_and_append success or failure ",
637                            "caa_lower={:?} caa_upper={:?} writer_upper={:?} shard_upper={:?} err={:?}"
638                        ),
639                        batch.desc.lower().elements(),
640                        batch.desc.upper().elements(),
641                        writer_upper.elements(),
642                        shard_upper.elements(),
643                        indeterminate,
644                    );
645                }
646            };
647        }
648    }
649
650    /// Downgrades the reader's since capability, also heartbeating its lease.
651    pub async fn downgrade_since(
652        &self,
653        reader_id: &LeasedReaderId,
654        outstanding_seqno: SeqNo,
655        new_since: &Antichain<T>,
656    ) -> (SeqNo, Since<T>, RoutineMaintenance) {
657        let metrics = Arc::clone(&self.applier.metrics);
658        self.apply_unbatched_idempotent_cmd(&metrics.cmds.downgrade_since, |seqno, cfg, state| {
659            // NOTE: Sample the clock here rather than hoisting it out of the closure so that a
660            // fresh value is used on every retry of this command.
661            state.downgrade_since(reader_id, seqno, outstanding_seqno, new_since, (cfg.now)())
662        })
663        .await
664    }
665
666    pub async fn compare_and_downgrade_since(
667        &self,
668        reader_id: &CriticalReaderId,
669        expected_opaque: &Opaque,
670        (new_opaque, new_since): (&Opaque, &Antichain<T>),
671    ) -> (Result<Since<T>, (Opaque, Since<T>)>, RoutineMaintenance) {
672        let metrics = Arc::clone(&self.applier.metrics);
673        let (_seqno, res, maintenance) = self
674            .apply_unbatched_idempotent_cmd(
675                &metrics.cmds.compare_and_downgrade_since,
676                |_seqno, _cfg, state| {
677                    state.compare_and_downgrade_since(
678                        reader_id,
679                        expected_opaque,
680                        (new_opaque, new_since),
681                    )
682                },
683            )
684            .await;
685
686        match res {
687            Ok(since) => (Ok(since), maintenance),
688            Err((opaque, since)) => (Err((opaque, since)), maintenance),
689        }
690    }
691
692    pub async fn expire_leased_reader(
693        &self,
694        reader_id: &LeasedReaderId,
695    ) -> (SeqNo, RoutineMaintenance) {
696        let metrics = Arc::clone(&self.applier.metrics);
697        let (seqno, _existed, maintenance) = self
698            .apply_unbatched_idempotent_cmd(&metrics.cmds.expire_reader, |_, _, state| {
699                state.expire_leased_reader(reader_id)
700            })
701            .await;
702        (seqno, maintenance)
703    }
704
705    #[allow(dead_code)] // TODO(bkirwi): remove this when since behaviour on expiry has settled
706    pub async fn expire_critical_reader(
707        &self,
708        reader_id: &CriticalReaderId,
709    ) -> (SeqNo, RoutineMaintenance) {
710        let metrics = Arc::clone(&self.applier.metrics);
711        let (seqno, _existed, maintenance) = self
712            .apply_unbatched_idempotent_cmd(&metrics.cmds.expire_reader, |_, _, state| {
713                state.expire_critical_reader(reader_id)
714            })
715            .await;
716        (seqno, maintenance)
717    }
718
719    pub async fn expire_writer(&self, writer_id: &WriterId) -> (SeqNo, RoutineMaintenance) {
720        let metrics = Arc::clone(&self.applier.metrics);
721        let (seqno, _existed, maintenance) = self
722            .apply_unbatched_idempotent_cmd(&metrics.cmds.expire_writer, |_, _, state| {
723                state.expire_writer(writer_id)
724            })
725            .await;
726        metrics.state.writer_removed.inc();
727        (seqno, maintenance)
728    }
729
730    pub fn is_finalized(&self) -> bool {
731        self.applier.is_finalized()
732    }
733
734    /// Reads the earliest live seqno from consensus and refreshes state, then
735    /// returns both with the next GC step. Callers use the seqno to track progress.
736    pub(crate) async fn fetch_finalized_gc_step(&self) -> (SeqNo, Option<FinalizedGcStep>) {
737        // Read consensus first, so state has the rollup it was truncated to.
738        let shard_id = self.shard_id();
739        let diffs = self
740            .applier
741            .state_versions
742            .fetch_live_diffs(&shard_id, SeqNo::minimum(), 1);
743        let earliest_live = diffs.await.first().expect("shard is initialized").seqno;
744        self.applier.fetch_and_update_state(None).await;
745        (earliest_live, self.applier.finalized_gc_step(earliest_live))
746    }
747
748    /// How many times [Self::finish_finalized_gc] backs off without progress
749    /// before giving up. With persist's default backoff (4ms, doubling) that's
750    /// about 16s.
751    const FINALIZED_GC_MAX_STALLED_RETRIES: usize = 12;
752
753    /// Runs GC on a finalized shard until it's done. GC normally runs as
754    /// maintenance after a write, and a finalized shard gets no more writes.
755    ///
756    /// A pass can make no progress for a while, e.g. on stale state behind a
757    /// concurrent GC, so it backs off and retries before giving up. Returns
758    /// whether GC finished.
759    pub(crate) async fn finish_finalized_gc(&self, gc: &GarbageCollector<K, V, T, D>) -> bool {
760        let new_retry = || Retry::persist_defaults(SystemTime::now()).into_retry_stream();
761        let mut retry = new_retry();
762        let mut last_progress = None;
763        loop {
764            let (earliest_live, Some(step)) = self.fetch_finalized_gc_step().await else {
765                return true;
766            };
767            // A commit or a truncation since the last pass is progress, so
768            // reset the backoff.
769            let progress = Some((self.seqno(), earliest_live));
770            if progress != last_progress {
771                retry = new_retry();
772            } else if retry.attempt() >= Self::FINALIZED_GC_MAX_STALLED_RETRIES {
773                mz_ore::soft_panic_or_log!(
774                    "GC of finalized shard {} stuck at {:?}: seqno {}, earliest live {}",
775                    self.shard_id(),
776                    step,
777                    self.seqno(),
778                    earliest_live,
779                );
780                return false;
781            } else {
782                retry = retry.sleep().await;
783            }
784            last_progress = progress;
785            match step {
786                FinalizedGcStep::WriteRollup => {
787                    let _ = self.add_rollup_for_current_seqno().await;
788                }
789                FinalizedGcStep::Gc(new_seqno_since) => {
790                    let shard_id = self.shard_id();
791                    let req = GcReq {
792                        shard_id,
793                        new_seqno_since,
794                    };
795                    if let Some(done) = gc.gc_and_truncate_background(req, GcCaller::Finalize) {
796                        let _ = done.await;
797                    }
798                }
799            }
800        }
801    }
802
803    /// See [crate::PersistClient::get_schema].
804    pub fn get_schema(&self, schema_id: SchemaId) -> Option<(K::Schema, V::Schema)> {
805        self.applier.get_schema(schema_id)
806    }
807
808    /// See [crate::PersistClient::latest_schema].
809    pub fn latest_schema(&self) -> Option<(SchemaId, K::Schema, V::Schema)> {
810        self.applier.latest_schema()
811    }
812
813    /// Returns the ID of the given schema, if known at the current state.
814    pub fn find_schema(&self, key_schema: &K::Schema, val_schema: &V::Schema) -> Option<SchemaId> {
815        self.applier.find_schema(key_schema, val_schema)
816    }
817
818    /// See [crate::PersistClient::compare_and_evolve_schema].
819    ///
820    /// TODO: Unify this with [Self::register_schema]?
821    pub async fn compare_and_evolve_schema(
822        &self,
823        expected: SchemaId,
824        key_schema: &K::Schema,
825        val_schema: &V::Schema,
826    ) -> (CaESchema<K, V>, RoutineMaintenance) {
827        let metrics = Arc::clone(&self.applier.metrics);
828        let (_seqno, state, maintenance) = self
829            .apply_unbatched_idempotent_cmd(
830                &metrics.cmds.compare_and_evolve_schema,
831                |_seqno, _cfg, state| {
832                    state.compare_and_evolve_schema::<K, V>(expected, key_schema, val_schema)
833                },
834            )
835            .await;
836        (state, maintenance)
837    }
838
839    async fn tombstone_step(&self) -> Result<(bool, RoutineMaintenance), InvalidUsage<T>> {
840        let metrics = Arc::clone(&self.applier.metrics);
841        let mut retry = self
842            .applier
843            .metrics
844            .retries
845            .idempotent_cmd
846            .stream(Retry::persist_defaults(SystemTime::now()).into_retry_stream());
847        loop {
848            let res = self
849                .applier
850                .apply_unbatched_cmd(&metrics.cmds.become_tombstone, |_, _, state| {
851                    state.become_tombstone_and_shrink()
852                })
853                .await;
854            let err = match res {
855                Ok((_seqno, Ok(()), maintenance)) => return Ok((true, maintenance)),
856                Ok((_seqno, Err(NoOpStateTransition(())), maintenance)) => {
857                    return Ok((false, maintenance));
858                }
859                Err(err) => err,
860            };
861            if retry.attempt() >= INFO_MIN_ATTEMPTS {
862                info!(
863                    "become_tombstone received an indeterminate error, retrying in {:?}: {}",
864                    retry.next_sleep(),
865                    err
866                );
867            } else {
868                debug!(
869                    "become_tombstone received an indeterminate error, retrying in {:?}: {}",
870                    retry.next_sleep(),
871                    err
872                );
873            }
874            retry = retry.sleep().await;
875        }
876    }
877
878    pub async fn become_tombstone(&self) -> Result<RoutineMaintenance, InvalidUsage<T>> {
879        self.applier.check_since_upper_both_empty()?;
880
881        let mut maintenance = RoutineMaintenance::default();
882
883        loop {
884            let (made_progress, more_maintenance) = self.tombstone_step().await?;
885            maintenance.merge(more_maintenance);
886            if !made_progress {
887                break;
888            }
889        }
890
891        Ok(maintenance)
892    }
893
894    /// Fetch a snapshot at the frontier without taking a lease on it. This may be useful for stats
895    /// or testing, but most callers will wish to wait for the frontier to advance and obtain the
896    /// snapshot separately.
897    pub async fn unleased_snapshot(
898        &self,
899        as_of: &Antichain<T>,
900    ) -> Result<Vec<HollowBatch<T>>, Since<T>> {
901        if let Ok(data) = self.applier.snapshot(as_of) {
902            return Ok(data);
903        }
904        let mut watch = self.applier.watch();
905        self.wait_for_upper_past(
906            as_of,
907            &mut watch,
908            None,
909            &self.applier.metrics.retries.snapshot,
910            RetryParameters::persist_defaults(),
911        )
912        .await;
913        match self.applier.snapshot(as_of) {
914            Ok(data) => Ok(data),
915            Err(SnapshotErr::AsOfHistoricalDistinctionsLost(since)) => Err(since),
916            Err(SnapshotErr::AsOfNotYetAvailable(seqno, upper)) => {
917                panic!(
918                    "waited for upper past {as_of:?}, but at latest seqno {seqno:?} the frontier was only {upper:?}",
919                    as_of = as_of.elements(),
920                    upper = upper.0.elements(),
921                )
922            }
923        }
924    }
925
926    // NB: Unlike the other methods here, this one is read-only.
927    pub fn verify_listen(&self, as_of: &Antichain<T>) -> Result<(), Since<T>> {
928        self.applier.verify_listen(as_of)
929    }
930
931    pub async fn wait_for_upper_past(
932        &self,
933        frontier: &Antichain<T>,
934        watch: &mut StateWatch<K, V, T, D>,
935        reader_id: Option<&LeasedReaderId>,
936        metrics: &RetryMetrics,
937        retry: RetryParameters,
938    ) {
939        let start = Instant::now();
940        let wait_for_seqno_past = self.applier.upper(|seqno, upper| {
941            if PartialOrder::less_than(frontier, upper) {
942                None
943            } else {
944                Some((seqno, upper.clone()))
945            }
946        });
947        let Some((mut seqno, mut upper)) = wait_for_seqno_past else {
948            // The current state's upper is already past the given frontier.
949            return;
950        };
951
952        // The latest state still doesn't have a new frontier for us:
953        // watch+sleep in a loop until it does.
954        let sleeps = metrics.stream(retry.into_retry(SystemTime::now()).into_retry_stream());
955
956        enum Wake<'a, K, V, T, D> {
957            Watch(&'a mut StateWatch<K, V, T, D>),
958            Sleep(MetricsRetryStream),
959        }
960        let mut watch_fut = std::pin::pin!(
961            watch
962                .wait_for_upper_past(frontier)
963                .map(Wake::Watch)
964                .instrument(trace_span!("snapshot::watch"))
965        );
966        let mut sleep_fut = std::pin::pin!(
967            sleeps
968                .sleep()
969                .map(Wake::Sleep)
970                .instrument(trace_span!("snapshot::sleep"))
971        );
972
973        // To reduce log spam, we log "not yet available" only once at info if
974        // it passes a certain threshold. Then, if it did one info log, we log
975        // again at info when it resolves.
976        let mut logged_at_info = false;
977        loop {
978            // Use a duration based threshold here instead of the usual
979            // INFO_MIN_ATTEMPTS because here we're waiting on an
980            // external thing to arrive.
981            if !logged_at_info
982                && start.elapsed() >= Duration::from_millis(1024)
983                && metrics.name.as_str() == "snapshot"
984            {
985                logged_at_info = true;
986                info!(
987                    shard_id =? self.shard_id(),
988                    shard_name =? self.applier.shard_metrics.name,
989                    reader_id =? reader_id,
990                    wait_frontier =? frontier.elements(),
991                    current_upper =? upper.elements(),
992                    current_seqno =? seqno,
993                    wait_for = &metrics.name,
994                    "desired upper not yet available",
995                );
996            } else {
997                debug!(
998                    shard_id =? self.shard_id(),
999                    shard_name =? self.applier.shard_metrics.name,
1000                    reader_id =? reader_id,
1001                    wait_frontier =? frontier.elements(),
1002                    current_upper =? upper.elements(),
1003                    current_seqno =? seqno,
1004                    wait_for = &metrics.name,
1005                    "desired upper not yet available",
1006                );
1007            }
1008
1009            let wake = match future::select(watch_fut.as_mut(), sleep_fut.as_mut()).await {
1010                future::Either::Left((wake, _)) => wake,
1011                future::Either::Right((wake, _)) => wake,
1012            };
1013            // Note that we don't need to fetch in the Watch case, because the
1014            // Watch wakeup is a signal that the shared state has already been
1015            // updated.
1016            match &wake {
1017                Wake::Watch(_) => self.applier.metrics.watch.wait_woken_via_watch.inc(),
1018                Wake::Sleep(_) => {
1019                    self.applier.metrics.watch.wait_woken_via_sleep.inc();
1020                    self.applier.fetch_and_update_state(Some(seqno)).await;
1021                }
1022            }
1023
1024            let wait_for_seqno_past = self.applier.upper(|seqno, upper| {
1025                if PartialOrder::less_than(frontier, upper) {
1026                    None
1027                } else {
1028                    Some((seqno, upper.clone()))
1029                }
1030            });
1031            match wait_for_seqno_past {
1032                None => {
1033                    match &wake {
1034                        Wake::Watch(_) => self.applier.metrics.watch.wait_resolved_via_watch.inc(),
1035                        Wake::Sleep(_) => self.applier.metrics.watch.wait_resolved_via_sleep.inc(),
1036                    }
1037                    return;
1038                }
1039                Some((s, u)) => {
1040                    seqno = s;
1041                    upper = u;
1042                }
1043            };
1044
1045            // Wait a bit and try again. Intentionally don't ever log
1046            // this at info level.
1047            match wake {
1048                Wake::Watch(watch) => {
1049                    watch_fut.set(
1050                        watch
1051                            .wait_for_upper_past(frontier)
1052                            .map(Wake::Watch)
1053                            .instrument(trace_span!("snapshot::watch")),
1054                    );
1055                }
1056                Wake::Sleep(sleeps) => {
1057                    debug!(
1058                        shard_id =? self.shard_id(),
1059                        shard_name =? self.applier.shard_metrics.name,
1060                        reader_id =? reader_id,
1061                        wait_frontier =? frontier.elements(),
1062                        current_upper =? upper.elements(),
1063                        current_seqno =? seqno,
1064                        wait_for = &metrics.name,
1065                        "didn't find new data, retrying in {:?}",
1066                        sleeps.next_sleep(),
1067                    );
1068                    sleep_fut.set(
1069                        sleeps
1070                            .sleep()
1071                            .map(Wake::Sleep)
1072                            .instrument(trace_span!("snapshot::sleep")),
1073                    );
1074                }
1075            }
1076        }
1077    }
1078
1079    async fn apply_unbatched_idempotent_cmd<
1080        R,
1081        WorkFn: FnMut(
1082            SeqNo,
1083            &PersistConfig,
1084            &mut StateCollections<T>,
1085        ) -> ControlFlow<NoOpStateTransition<R>, R>,
1086    >(
1087        &self,
1088        cmd: &CmdMetrics,
1089        mut work_fn: WorkFn,
1090    ) -> (SeqNo, R, RoutineMaintenance) {
1091        let mut retry = self
1092            .applier
1093            .metrics
1094            .retries
1095            .idempotent_cmd
1096            .stream(Retry::persist_defaults(SystemTime::now()).into_retry_stream());
1097        loop {
1098            match self.applier.apply_unbatched_cmd(cmd, &mut work_fn).await {
1099                Ok((seqno, x, maintenance)) => match x {
1100                    Ok(x) => {
1101                        return (seqno, x, maintenance);
1102                    }
1103                    Err(NoOpStateTransition(x)) => {
1104                        return (seqno, x, maintenance);
1105                    }
1106                },
1107                Err(err) => {
1108                    if retry.attempt() >= INFO_MIN_ATTEMPTS {
1109                        info!(
1110                            "apply_unbatched_idempotent_cmd {} received an indeterminate error, retrying in {:?}: {}",
1111                            cmd.name,
1112                            retry.next_sleep(),
1113                            err
1114                        );
1115                    } else {
1116                        debug!(
1117                            "apply_unbatched_idempotent_cmd {} received an indeterminate error, retrying in {:?}: {}",
1118                            cmd.name,
1119                            retry.next_sleep(),
1120                            err
1121                        );
1122                    }
1123                    retry = retry.sleep().await;
1124                    continue;
1125                }
1126            }
1127        }
1128    }
1129}
1130
1131impl<K, V, T, D> Machine<K, V, T, D>
1132where
1133    K: Debug + Codec,
1134    V: Debug + Codec,
1135    T: Timestamp + Lattice + Codec64 + Sync,
1136    D: Monoid + Codec64 + PartialEq,
1137{
1138    pub async fn merge_res(
1139        &self,
1140        res: &FueledMergeRes<T>,
1141    ) -> (ApplyMergeResult, RoutineMaintenance) {
1142        let metrics = Arc::clone(&self.applier.metrics);
1143
1144        // SUBTLE! If Machine::merge_res returns false, the blobs referenced in
1145        // compaction output are deleted so we don't leak them. Naively passing
1146        // back the value returned by State::apply_merge_res might give a false
1147        // negative in the presence of retries and Indeterminate errors.
1148        // Specifically, something like the following:
1149        //
1150        // - We try to apply_merge_res, it matches.
1151        // - When apply_unbatched_cmd goes to commit the new state, the
1152        //   Consensus::compare_and_set returns an Indeterminate error (but
1153        //   actually succeeds). The committed State now contains references to
1154        //   the compaction output blobs.
1155        // - Machine::apply_unbatched_idempotent_cmd retries the Indeterminate
1156        //   error. For whatever reason, this time though it doesn't match
1157        //   (maybe the batches simply get grouped difference when deserialized
1158        //   from state, or more unavoidably perhaps another compaction
1159        //   happens).
1160        // - This now bubbles up applied=false to the caller, which uses it as a
1161        //   signal that the blobs in the compaction output should be deleted so
1162        //   that we don't leak them.
1163        // - We now contain references in committed State to blobs that don't
1164        //   exist.
1165        //
1166        // The fix is to keep track of whether applied ever was true, even for a
1167        // compare_and_set that returned an Indeterminate error. This has the
1168        // chance of false positive (leaking a blob) but that's better than a
1169        // false negative (a blob we can never recover referenced by state). We
1170        // anyway need a mechanism to clean up leaked blobs because of process
1171        // crashes.
1172        let mut merge_result_ever_applied = ApplyMergeResult::NotAppliedNoMatch;
1173        let (_seqno, _apply_merge_result, maintenance) = self
1174            .apply_unbatched_idempotent_cmd(&metrics.cmds.merge_res, |_, _, state| {
1175                let ret = state.apply_merge_res::<D>(res, &Arc::clone(&metrics).columnar);
1176                if let Continue(result) = ret {
1177                    // record if we've ever applied the merge
1178                    if result.applied() {
1179                        merge_result_ever_applied = result;
1180                    }
1181                    // otherwise record the most granular reason for _not_
1182                    // applying the merge when there was a matching batch
1183                    if result.matched() && !result.applied() && !merge_result_ever_applied.applied()
1184                    {
1185                        merge_result_ever_applied = result;
1186                    }
1187                }
1188                ret
1189            })
1190            .await;
1191        (merge_result_ever_applied, maintenance)
1192    }
1193}
1194
1195pub(crate) struct ExpireFn(
1196    /// This is stored on WriteHandle and ReadHandle, which we require to be
1197    /// Send + Sync, but the Future is only Send and not Sync. Instead store a
1198    /// FnOnce that returns the Future. This could also be made an `IntoFuture`,
1199    /// once producing one of those is made easier.
1200    pub(crate) Box<dyn FnOnce() -> BoxFuture<'static, ()> + Send + Sync + 'static>,
1201);
1202
1203impl Debug for ExpireFn {
1204    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1205        f.debug_struct("ExpireFn").finish_non_exhaustive()
1206    }
1207}
1208
1209#[derive(Debug)]
1210pub(crate) enum CompareAndAppendRes<T> {
1211    Success(SeqNo, WriterMaintenance<T>),
1212    InvalidUsage(InvalidUsage<T>),
1213    UpperMismatch(SeqNo, Antichain<T>),
1214    InlineBackpressure,
1215}
1216
1217#[cfg(test)]
1218impl<T: Debug> CompareAndAppendRes<T> {
1219    #[track_caller]
1220    fn unwrap(self) -> (SeqNo, WriterMaintenance<T>) {
1221        match self {
1222            CompareAndAppendRes::Success(seqno, maintenance) => (seqno, maintenance),
1223            x => panic!("{:?}", x),
1224        }
1225    }
1226}
1227
1228pub(crate) const NEXT_LISTEN_BATCH_RETRYER_FIXED_SLEEP: Config<Duration> = Config::new(
1229    "persist_next_listen_batch_retryer_fixed_sleep",
1230    Duration::from_millis(1200), // pubsub is on by default!
1231    "\
1232    The fixed sleep when polling for new batches from a Listen or Subscribe. Skipped if zero.",
1233    ParameterScope::Environment,
1234);
1235
1236pub(crate) const NEXT_LISTEN_BATCH_RETRYER_INITIAL_BACKOFF: Config<Duration> = Config::new(
1237    "persist_next_listen_batch_retryer_initial_backoff",
1238    Duration::from_millis(100), // pubsub is on by default!
1239    "The initial backoff when polling for new batches from a Listen or Subscribe.",
1240    ParameterScope::Environment,
1241);
1242
1243pub(crate) const NEXT_LISTEN_BATCH_RETRYER_MULTIPLIER: Config<u32> = Config::new(
1244    "persist_next_listen_batch_retryer_multiplier",
1245    2,
1246    "The backoff multiplier when polling for new batches from a Listen or Subscribe.",
1247    ParameterScope::Environment,
1248);
1249
1250pub(crate) const NEXT_LISTEN_BATCH_RETRYER_CLAMP: Config<Duration> = Config::new(
1251    "persist_next_listen_batch_retryer_clamp",
1252    Duration::from_secs(16), // pubsub is on by default!
1253    "The backoff clamp duration when polling for new batches from a Listen or Subscribe.",
1254    ParameterScope::Environment,
1255);
1256
1257pub(crate) fn next_listen_batch_retry_params(cfg: &ConfigSet) -> RetryParameters {
1258    RetryParameters {
1259        fixed_sleep: NEXT_LISTEN_BATCH_RETRYER_FIXED_SLEEP.get(cfg),
1260        initial_backoff: NEXT_LISTEN_BATCH_RETRYER_INITIAL_BACKOFF.get(cfg),
1261        multiplier: NEXT_LISTEN_BATCH_RETRYER_MULTIPLIER.get(cfg),
1262        clamp: NEXT_LISTEN_BATCH_RETRYER_CLAMP.get(cfg),
1263    }
1264}
1265
1266pub const INFO_MIN_ATTEMPTS: usize = 3;
1267
1268/// Attempts after which a still-failing retry loop escalates from INFO to WARN.
1269/// `retry_external` always uses the persist backoff (clamped at 16s), so this
1270/// is roughly five minutes of continuous failure: well past transient retries,
1271/// and a sign the operation (e.g. a blob whose GET never returns) is wedged.
1272pub const WARN_MIN_ATTEMPTS: usize = 30;
1273
1274pub async fn retry_external<R, F, WorkFn>(metrics: &RetryMetrics, mut work_fn: WorkFn) -> R
1275where
1276    F: std::future::Future<Output = Result<R, ExternalError>>,
1277    WorkFn: FnMut() -> F,
1278{
1279    let mut retry = metrics.stream(Retry::persist_defaults(SystemTime::now()).into_retry_stream());
1280    loop {
1281        match work_fn().await {
1282            Ok(x) => {
1283                if retry.attempt() > 0 {
1284                    debug!(
1285                        "external operation {} succeeded after failing at least once",
1286                        metrics.name,
1287                    );
1288                }
1289                return x;
1290            }
1291            Err(err) => {
1292                if retry.attempt() >= WARN_MIN_ATTEMPTS {
1293                    warn!(
1294                        "external operation {} has failed {} times, retrying in {:?}: {}",
1295                        metrics.name,
1296                        retry.attempt(),
1297                        retry.next_sleep(),
1298                        err.display_with_causes()
1299                    );
1300                } else if retry.attempt() >= INFO_MIN_ATTEMPTS {
1301                    info!(
1302                        "external operation {} failed, retrying in {:?}: {}",
1303                        metrics.name,
1304                        retry.next_sleep(),
1305                        err.display_with_causes()
1306                    );
1307                } else {
1308                    debug!(
1309                        "external operation {} failed, retrying in {:?}: {}",
1310                        metrics.name,
1311                        retry.next_sleep(),
1312                        err.display_with_causes()
1313                    );
1314                }
1315                retry = retry.sleep().await;
1316            }
1317        }
1318    }
1319}
1320
1321pub async fn retry_determinate<R, F, WorkFn>(
1322    metrics: &RetryMetrics,
1323    mut work_fn: WorkFn,
1324) -> Result<R, Indeterminate>
1325where
1326    F: std::future::Future<Output = Result<R, ExternalError>>,
1327    WorkFn: FnMut() -> F,
1328{
1329    let mut retry = metrics.stream(Retry::persist_defaults(SystemTime::now()).into_retry_stream());
1330    loop {
1331        match work_fn().await {
1332            Ok(x) => {
1333                if retry.attempt() > 0 {
1334                    debug!(
1335                        "external operation {} succeeded after failing at least once",
1336                        metrics.name,
1337                    );
1338                }
1339                return Ok(x);
1340            }
1341            Err(ExternalError::Determinate(err)) => {
1342                // The determinate "could not serialize access" errors
1343                // happen often enough in dev (which uses Postgres) that
1344                // it's impeding people's work. At the same time, it's been
1345                // a source of confusion for eng. The situation is much
1346                // better on CRDB and we have metrics coverage in prod, so
1347                // this is redundant enough that it's more hurtful than
1348                // helpful. As a result, this intentionally ignores
1349                // INFO_MIN_ATTEMPTS and always logs at debug.
1350                debug!(
1351                    "external operation {} failed, retrying in {:?}: {}",
1352                    metrics.name,
1353                    retry.next_sleep(),
1354                    err.display_with_causes()
1355                );
1356                retry = retry.sleep().await;
1357                continue;
1358            }
1359            Err(ExternalError::Indeterminate(x)) => return Err(x),
1360        }
1361    }
1362}
1363
1364#[cfg(test)]
1365pub mod datadriven {
1366    use std::collections::{BTreeMap, BTreeSet};
1367    use std::pin::pin;
1368    use std::sync::{Arc, LazyLock};
1369
1370    use anyhow::anyhow;
1371    use differential_dataflow::consolidation::consolidate_updates;
1372    use differential_dataflow::trace::Description;
1373    use futures::StreamExt;
1374    use mz_dyncfg::{ConfigUpdates, ConfigVal};
1375    use mz_persist::indexed::encoding::BlobTraceBatchPart;
1376    use mz_persist_types::codec_impls::{StringSchema, UnitSchema};
1377
1378    use crate::batch::{
1379        BLOB_TARGET_SIZE, Batch, BatchBuilder, BatchBuilderConfig, BatchBuilderInternal,
1380        BatchParts, validate_truncate_batch,
1381    };
1382    use crate::cfg::COMPACTION_MEMORY_BOUND_BYTES;
1383    use crate::fetch::{EncodedPart, FetchConfig};
1384    use crate::internal::compact::{CompactConfig, CompactReq, Compactor};
1385    use crate::internal::datadriven::DirectiveArgs;
1386    use crate::internal::encoding::Schemas;
1387    use crate::internal::gc::GcReq;
1388    use crate::internal::paths::{BlobKey, BlobKeyPrefix, PartialBlobKey};
1389    use crate::internal::state::{BatchPart, RunOrder, RunPart, Upper};
1390    use crate::internal::state_versions::EncodedRollup;
1391    use crate::internal::trace::{CompactionInput, IdHollowBatch, SpineId};
1392    use crate::read::{Listen, ListenEvent, READER_LEASE_DURATION};
1393    use crate::rpc::NoopPubSubSender;
1394    use crate::tests::new_test_client;
1395    use crate::write::COMBINE_INLINE_WRITES;
1396    use crate::{GarbageCollector, PersistClient};
1397
1398    use super::*;
1399
1400    static SCHEMAS: LazyLock<Schemas<String, ()>> = LazyLock::new(|| Schemas {
1401        id: Some(SchemaId(0)),
1402        key: Arc::new(StringSchema),
1403        val: Arc::new(UnitSchema),
1404    });
1405
1406    /// Shared state for a single [crate::internal::machine] [datadriven::TestFile].
1407    #[derive(Debug)]
1408    pub struct MachineState {
1409        pub client: PersistClient,
1410        pub shard_id: ShardId,
1411        pub state_versions: Arc<StateVersions>,
1412        pub machine: Machine<String, (), u64, i64>,
1413        pub batches: BTreeMap<String, IdHollowBatch<u64>>,
1414        pub next_id: usize,
1415        pub rollups: BTreeMap<String, EncodedRollup>,
1416        pub listens: BTreeMap<String, Listen<String, (), u64, i64>>,
1417        pub routine: Vec<RoutineMaintenance>,
1418        pub compactions: BTreeMap<String, CompactReq<u64>>,
1419    }
1420
1421    impl MachineState {
1422        pub async fn new(dyncfgs: &ConfigUpdates) -> Self {
1423            let shard_id = ShardId::new();
1424            let client = new_test_client(dyncfgs).await;
1425            // Reset blob_target_size. Individual batch writes and compactions
1426            // can override it with an arg.
1427            client
1428                .cfg
1429                .set_config(&BLOB_TARGET_SIZE, *BLOB_TARGET_SIZE.default());
1430            // Our structured compaction code uses slightly different estimates
1431            // for array size than the old path, which can affect the results of
1432            // some compaction tests.
1433            client.cfg.set_config(&COMBINE_INLINE_WRITES, false);
1434            let state_versions = Arc::new(StateVersions::new(
1435                client.cfg.clone(),
1436                Arc::clone(&client.consensus),
1437                Arc::clone(&client.blob),
1438                Arc::clone(&client.metrics),
1439            ));
1440            let machine = Machine::new(
1441                client.cfg.clone(),
1442                shard_id,
1443                Arc::clone(&client.metrics),
1444                Arc::clone(&state_versions),
1445                Arc::clone(&client.shared_states),
1446                Arc::new(NoopPubSubSender),
1447                Arc::clone(&client.isolated_runtime),
1448                Diagnostics::for_tests(),
1449            )
1450            .await
1451            .expect("codecs should match");
1452            MachineState {
1453                shard_id,
1454                client,
1455                state_versions,
1456                machine,
1457                batches: BTreeMap::default(),
1458                rollups: BTreeMap::default(),
1459                listens: BTreeMap::default(),
1460                routine: Vec::new(),
1461                compactions: BTreeMap::default(),
1462                next_id: 0,
1463            }
1464        }
1465
1466        fn to_batch(&self, hollow: HollowBatch<u64>) -> Batch<String, (), u64, i64> {
1467            Batch::new(
1468                true,
1469                Arc::clone(&self.client.metrics),
1470                Arc::clone(&self.client.blob),
1471                self.client.metrics.shards.shard(&self.shard_id, "test"),
1472                self.client.cfg.build_version.clone(),
1473                (
1474                    <String>::encode_schema(&*SCHEMAS.key),
1475                    <()>::encode_schema(&*SCHEMAS.val),
1476                ),
1477                hollow,
1478            )
1479        }
1480    }
1481
1482    /// Scans consensus and returns all states with their SeqNos
1483    /// and which batches they reference
1484    pub async fn consensus_scan(
1485        datadriven: &MachineState,
1486        args: DirectiveArgs<'_>,
1487    ) -> Result<String, anyhow::Error> {
1488        let from = args.expect("from_seqno");
1489
1490        let mut states = datadriven
1491            .state_versions
1492            .fetch_all_live_states::<u64>(datadriven.shard_id)
1493            .await
1494            .expect("should only be called on an initialized shard")
1495            .check_ts_codec()
1496            .expect("shard codecs should not change");
1497        let mut s = String::new();
1498        while let Some(x) = states.next(|_| {}) {
1499            if x.seqno < from {
1500                continue;
1501            }
1502            let rollups: Vec<_> = x
1503                .collections
1504                .rollups
1505                .keys()
1506                .map(|seqno| seqno.to_string())
1507                .collect();
1508            let batches: Vec<_> = x
1509                .collections
1510                .trace
1511                .batches()
1512                .filter(|b| !b.is_empty())
1513                .filter_map(|b| {
1514                    datadriven
1515                        .batches
1516                        .iter()
1517                        .find(|(_, original_batch)| original_batch.batch.parts == b.parts)
1518                        .map(|(batch_name, _)| batch_name.to_owned())
1519                })
1520                .collect();
1521            write!(
1522                s,
1523                "seqno={} batches={} rollups={}\n",
1524                x.seqno,
1525                batches.join(","),
1526                rollups.join(","),
1527            );
1528        }
1529        Ok(s)
1530    }
1531
1532    pub async fn consensus_truncate(
1533        datadriven: &MachineState,
1534        args: DirectiveArgs<'_>,
1535    ) -> Result<String, anyhow::Error> {
1536        let to = args.expect("to_seqno");
1537        let removed = datadriven
1538            .client
1539            .consensus
1540            .truncate(&datadriven.shard_id.to_string(), to)
1541            .await
1542            .expect("valid truncation");
1543        Ok(format!("{:?}\n", removed))
1544    }
1545
1546    pub async fn blob_scan_batches(
1547        datadriven: &MachineState,
1548        _args: DirectiveArgs<'_>,
1549    ) -> Result<String, anyhow::Error> {
1550        let key_prefix = BlobKeyPrefix::Shard(&datadriven.shard_id).to_string();
1551
1552        let mut s = String::new();
1553        let () = datadriven
1554            .state_versions
1555            .blob
1556            .list_keys_and_metadata(&key_prefix, &mut |x| {
1557                let (_, key) = BlobKey::parse_ids(x.key).expect("key should be valid");
1558                if let PartialBlobKey::Batch(_, _) = key {
1559                    write!(s, "{}: {}b\n", x.key, x.size_in_bytes);
1560                }
1561            })
1562            .await?;
1563        Ok(s)
1564    }
1565
1566    /// Lists the seqnos of rollups in blob, which can differ from those in
1567    /// state.
1568    pub async fn blob_scan_rollups(
1569        datadriven: &MachineState,
1570        _args: DirectiveArgs<'_>,
1571    ) -> Result<String, anyhow::Error> {
1572        let key_prefix = BlobKeyPrefix::Shard(&datadriven.shard_id).to_string();
1573
1574        // Keys include a random id, so print only seqnos.
1575        let mut seqnos = vec![];
1576        let () = datadriven
1577            .state_versions
1578            .blob
1579            .list_keys_and_metadata(&key_prefix, &mut |x| {
1580                let (_, key) = BlobKey::parse_ids(x.key).expect("key should be valid");
1581                if let PartialBlobKey::Rollup(seqno, _) = key {
1582                    seqnos.push(seqno);
1583                }
1584            })
1585            .await?;
1586        seqnos.sort();
1587        Ok(seqnos.iter().map(|seqno| format!("{seqno}\n")).collect())
1588    }
1589
1590    #[allow(clippy::unused_async)]
1591    pub async fn shard_desc(
1592        datadriven: &MachineState,
1593        _args: DirectiveArgs<'_>,
1594    ) -> Result<String, anyhow::Error> {
1595        Ok(format!(
1596            "since={:?} upper={:?}\n",
1597            datadriven.machine.applier.since().elements(),
1598            datadriven.machine.applier.clone_upper().elements()
1599        ))
1600    }
1601
1602    pub async fn downgrade_since(
1603        datadriven: &mut MachineState,
1604        args: DirectiveArgs<'_>,
1605    ) -> Result<String, anyhow::Error> {
1606        let since = args.expect_antichain("since");
1607        let seqno = args
1608            .optional("seqno")
1609            .unwrap_or_else(|| datadriven.machine.seqno());
1610        let reader_id = args.expect("reader_id");
1611        let (_, since, routine) = datadriven
1612            .machine
1613            .downgrade_since(&reader_id, seqno, &since)
1614            .await;
1615        datadriven.routine.push(routine);
1616        Ok(format!(
1617            "{} {:?}\n",
1618            datadriven.machine.seqno(),
1619            since.0.elements()
1620        ))
1621    }
1622
1623    #[allow(clippy::unused_async)]
1624    pub async fn dyncfg(
1625        datadriven: &MachineState,
1626        args: DirectiveArgs<'_>,
1627    ) -> Result<String, anyhow::Error> {
1628        let mut updates = ConfigUpdates::default();
1629        for x in args.input.trim().split('\n') {
1630            match x.split(' ').collect::<Vec<_>>().as_slice() {
1631                &[name, val] => {
1632                    let config = datadriven
1633                        .client
1634                        .cfg
1635                        .entries()
1636                        .find(|x| x.name() == name)
1637                        .ok_or_else(|| anyhow!("unknown dyncfg: {}", name))?;
1638                    match config.val() {
1639                        ConfigVal::Usize(_) => {
1640                            let val = val.parse().map_err(anyhow::Error::new)?;
1641                            updates.add_dynamic(name, ConfigVal::Usize(val));
1642                        }
1643                        ConfigVal::Bool(_) => {
1644                            let val = val.parse().map_err(anyhow::Error::new)?;
1645                            updates.add_dynamic(name, ConfigVal::Bool(val));
1646                        }
1647                        x => unimplemented!("dyncfg type: {:?}", x),
1648                    }
1649                }
1650                x => return Err(anyhow!("expected `name val` got: {:?}", x)),
1651            }
1652        }
1653        updates.apply(&datadriven.client.cfg);
1654
1655        Ok("ok\n".to_string())
1656    }
1657
1658    pub async fn compare_and_downgrade_since(
1659        datadriven: &mut MachineState,
1660        args: DirectiveArgs<'_>,
1661    ) -> Result<String, anyhow::Error> {
1662        let expected_opaque: u64 = args.expect("expect_opaque");
1663        let new_opaque: u64 = args.expect("opaque");
1664        let new_since = args.expect_antichain("since");
1665        let reader_id = args.expect("reader_id");
1666        let (res, routine) = datadriven
1667            .machine
1668            .compare_and_downgrade_since(
1669                &reader_id,
1670                &Opaque::encode(&expected_opaque),
1671                (&Opaque::encode(&new_opaque), &new_since),
1672            )
1673            .await;
1674        datadriven.routine.push(routine);
1675        let since = res.map_err(|(opaque, since)| {
1676            anyhow!(
1677                "mismatch: opaque={} since={:?}",
1678                opaque.decode::<u64>(),
1679                since.0.elements()
1680            )
1681        })?;
1682        Ok(format!(
1683            "{} {} {:?}\n",
1684            datadriven.machine.seqno(),
1685            new_opaque,
1686            since.0.elements()
1687        ))
1688    }
1689
1690    pub async fn write_rollup(
1691        datadriven: &mut MachineState,
1692        args: DirectiveArgs<'_>,
1693    ) -> Result<String, anyhow::Error> {
1694        let output = args.expect_str("output");
1695
1696        let rollup = datadriven
1697            .machine
1698            .applier
1699            .write_rollup_for_state()
1700            .await
1701            .expect("rollup");
1702
1703        datadriven
1704            .rollups
1705            .insert(output.to_string(), rollup.clone());
1706
1707        Ok(format!(
1708            "state={} diffs=[{}, {})\n",
1709            rollup.seqno,
1710            rollup._desc.lower().first().expect("seqno"),
1711            rollup._desc.upper().first().expect("seqno"),
1712        ))
1713    }
1714
1715    pub async fn add_rollup(
1716        datadriven: &mut MachineState,
1717        args: DirectiveArgs<'_>,
1718    ) -> Result<String, anyhow::Error> {
1719        let input = args.expect_str("input");
1720        let rollup = datadriven
1721            .rollups
1722            .get(input)
1723            .expect("unknown batch")
1724            .clone();
1725
1726        let (applied, maintenance) = datadriven
1727            .machine
1728            .add_rollup((rollup.seqno, &rollup.to_hollow()))
1729            .await;
1730
1731        if !applied {
1732            return Err(anyhow!("failed to apply rollup for: {}", rollup.seqno));
1733        }
1734
1735        datadriven.routine.push(maintenance);
1736        Ok(format!("{}\n", datadriven.machine.seqno()))
1737    }
1738
1739    pub async fn write_batch(
1740        datadriven: &mut MachineState,
1741        args: DirectiveArgs<'_>,
1742    ) -> Result<String, anyhow::Error> {
1743        let output = args.expect_str("output");
1744        let lower = args.expect_antichain("lower");
1745        let upper = args.expect_antichain("upper");
1746        assert!(PartialOrder::less_than(&lower, &upper));
1747        let since = args
1748            .optional_antichain("since")
1749            .unwrap_or_else(|| Antichain::from_elem(0));
1750        let target_size = args.optional("target_size");
1751        let parts_size_override = args.optional("parts_size_override");
1752        let consolidate = args.optional("consolidate").unwrap_or(true);
1753        let mut updates: Vec<_> = args
1754            .input
1755            .split('\n')
1756            .flat_map(DirectiveArgs::parse_update)
1757            .collect();
1758
1759        let mut cfg = BatchBuilderConfig::new(&datadriven.client.cfg, datadriven.shard_id);
1760        if let Some(target_size) = target_size {
1761            cfg.blob_target_size = target_size;
1762        };
1763        if consolidate {
1764            consolidate_updates(&mut updates);
1765        }
1766        let run_order = if consolidate {
1767            cfg.preferred_order
1768        } else {
1769            RunOrder::Unordered
1770        };
1771        let parts = BatchParts::new_ordered::<i64>(
1772            cfg.clone(),
1773            run_order,
1774            Arc::clone(&datadriven.client.metrics),
1775            Arc::clone(&datadriven.machine.applier.shard_metrics),
1776            datadriven.shard_id,
1777            Arc::clone(&datadriven.client.blob),
1778            Arc::clone(&datadriven.client.isolated_runtime),
1779            &datadriven.client.metrics.user,
1780        );
1781        let builder = BatchBuilderInternal::new(
1782            cfg.clone(),
1783            parts,
1784            Arc::clone(&datadriven.client.metrics),
1785            SCHEMAS.clone(),
1786            Arc::clone(&datadriven.client.blob),
1787            datadriven.shard_id.clone(),
1788            datadriven.client.cfg.build_version.clone(),
1789        );
1790        let mut builder = BatchBuilder::new(builder, Description::new(lower, upper.clone(), since));
1791        for ((k, ()), t, d) in updates {
1792            builder.add(&k, &(), &t, &d).await.expect("invalid batch");
1793        }
1794        let mut batch = builder.finish(upper).await?;
1795        // We can only reasonably use parts_size_override with hollow batches,
1796        // so if it's set, flush any inline batches out.
1797        if parts_size_override.is_some() {
1798            batch
1799                .flush_to_blob(
1800                    &cfg,
1801                    &datadriven.client.metrics.user,
1802                    &datadriven.client.isolated_runtime,
1803                    &SCHEMAS,
1804                )
1805                .await;
1806        }
1807        let batch = batch.into_hollow_batch();
1808        let batch = IdHollowBatch {
1809            batch: Arc::new(batch),
1810            id: SpineId(datadriven.next_id, datadriven.next_id + 1),
1811        };
1812        datadriven.next_id += 1;
1813
1814        if let Some(size) = parts_size_override {
1815            let mut batch = batch.clone();
1816            let mut hollow_batch = (*batch.batch).clone();
1817            for part in hollow_batch.parts.iter_mut() {
1818                match part {
1819                    RunPart::Many(run) => run.max_part_bytes = size,
1820                    RunPart::Single(BatchPart::Hollow(part)) => part.encoded_size_bytes = size,
1821                    RunPart::Single(BatchPart::Inline { .. }) => unreachable!("flushed out above"),
1822                }
1823            }
1824            batch.batch = Arc::new(hollow_batch);
1825            datadriven.batches.insert(output.to_owned(), batch);
1826        } else {
1827            datadriven.batches.insert(output.to_owned(), batch.clone());
1828        }
1829        Ok(format!(
1830            "parts={} len={}\n",
1831            batch.batch.part_count(),
1832            batch.batch.len
1833        ))
1834    }
1835
1836    pub async fn fetch_batch(
1837        datadriven: &MachineState,
1838        args: DirectiveArgs<'_>,
1839    ) -> Result<String, anyhow::Error> {
1840        let input = args.expect_str("input");
1841        let stats = args.optional_str("stats");
1842        let batch = datadriven.batches.get(input).expect("unknown batch");
1843
1844        let mut s = String::new();
1845        let mut stream = pin!(
1846            batch
1847                .batch
1848                .part_stream(
1849                    datadriven.shard_id,
1850                    &*datadriven.state_versions.blob,
1851                    &*datadriven.state_versions.metrics
1852                )
1853                .enumerate()
1854        );
1855        while let Some((idx, part)) = stream.next().await {
1856            let part = &*part?;
1857            write!(s, "<part {idx}>\n");
1858
1859            let lower = match part {
1860                BatchPart::Inline { updates, .. } => {
1861                    let updates: BlobTraceBatchPart<u64> =
1862                        updates.decode(&datadriven.client.metrics.columnar)?;
1863                    updates.structured_key_lower()
1864                }
1865                other @ BatchPart::Hollow(_) => other.structured_key_lower(),
1866            };
1867
1868            if let Some(lower) = lower {
1869                if stats == Some("lower") {
1870                    writeln!(s, "<key lower={}>", lower.get())
1871                }
1872            }
1873
1874            match part {
1875                BatchPart::Hollow(part) => {
1876                    let blob_batch = datadriven
1877                        .client
1878                        .blob
1879                        .get(&part.key.complete(&datadriven.shard_id))
1880                        .await;
1881                    match blob_batch {
1882                        Ok(Some(_)) | Err(_) => {}
1883                        // don't try to fetch/print the keys of the batch part
1884                        // if the blob store no longer has it
1885                        Ok(None) => {
1886                            s.push_str("<empty>\n");
1887                            continue;
1888                        }
1889                    };
1890                }
1891                BatchPart::Inline { .. } => {}
1892            };
1893            let part = EncodedPart::fetch(
1894                &FetchConfig::from_persist_config(&datadriven.client.cfg),
1895                &datadriven.shard_id,
1896                datadriven.client.blob.as_ref(),
1897                datadriven.client.metrics.as_ref(),
1898                datadriven.machine.applier.shard_metrics.as_ref(),
1899                &datadriven.client.metrics.read.batch_fetcher,
1900                &batch.batch.desc,
1901                part,
1902            )
1903            .await
1904            .expect("invalid batch part");
1905            let part = part
1906                .normalize(&datadriven.client.metrics.columnar)
1907                .into_part::<String, ()>(&*SCHEMAS.key, &*SCHEMAS.val);
1908
1909            for ((k, _v), t, d) in part
1910                .decode_iter::<_, _, u64, i64>(&*SCHEMAS.key, &*SCHEMAS.val)
1911                .expect("valid schemas")
1912            {
1913                writeln!(s, "{k} {t} {d}");
1914            }
1915        }
1916        if !s.is_empty() {
1917            for (idx, (_meta, run)) in batch.batch.runs().enumerate() {
1918                write!(s, "<run {idx}>\n");
1919                for part in run {
1920                    let part_idx = batch
1921                        .batch
1922                        .parts
1923                        .iter()
1924                        .position(|p| p == part)
1925                        .expect("part should exist");
1926                    write!(s, "part {part_idx}\n");
1927                }
1928            }
1929        }
1930        Ok(s)
1931    }
1932
1933    #[allow(clippy::unused_async)]
1934    pub async fn truncate_batch_desc(
1935        datadriven: &mut MachineState,
1936        args: DirectiveArgs<'_>,
1937    ) -> Result<String, anyhow::Error> {
1938        let input = args.expect_str("input");
1939        let output = args.expect_str("output");
1940        let lower = args.expect_antichain("lower");
1941        let upper = args.expect_antichain("upper");
1942
1943        let batch = datadriven
1944            .batches
1945            .get(input)
1946            .expect("unknown batch")
1947            .clone();
1948        let truncated_desc = Description::new(lower, upper, batch.batch.desc.since().clone());
1949        let bounds_truncated = validate_truncate_batch(&batch.batch, &truncated_desc, false, true)?;
1950        let mut new_hollow_batch = (*batch.batch).clone();
1951        if bounds_truncated {
1952            for run_meta in &mut new_hollow_batch.run_meta {
1953                run_meta.set_bounds_truncated();
1954            }
1955        }
1956        new_hollow_batch.desc = truncated_desc;
1957        let new_batch = IdHollowBatch {
1958            batch: Arc::new(new_hollow_batch),
1959            id: batch.id,
1960        };
1961        datadriven
1962            .batches
1963            .insert(output.to_owned(), new_batch.clone());
1964        Ok(format!(
1965            "parts={} len={}\n",
1966            batch.batch.part_count(),
1967            batch.batch.len
1968        ))
1969    }
1970
1971    #[allow(clippy::unused_async)]
1972    pub async fn set_batch_parts_size(
1973        datadriven: &mut MachineState,
1974        args: DirectiveArgs<'_>,
1975    ) -> Result<String, anyhow::Error> {
1976        let input = args.expect_str("input");
1977        let size = args.expect("size");
1978        let batch = datadriven.batches.get_mut(input).expect("unknown batch");
1979        let mut hollow_batch = (*batch.batch).clone();
1980        for part in hollow_batch.parts.iter_mut() {
1981            match part {
1982                RunPart::Single(BatchPart::Hollow(x)) => x.encoded_size_bytes = size,
1983                _ => {
1984                    panic!("set_batch_parts_size only supports hollow parts")
1985                }
1986            }
1987        }
1988        batch.batch = Arc::new(hollow_batch);
1989        Ok("ok\n".to_string())
1990    }
1991
1992    pub async fn compact(
1993        datadriven: &mut MachineState,
1994        args: DirectiveArgs<'_>,
1995    ) -> Result<String, anyhow::Error> {
1996        let output = args.expect_str("output");
1997        let lower = args.expect_antichain("lower");
1998        let upper = args.expect_antichain("upper");
1999        let since = args.expect_antichain("since");
2000        let target_size = args.optional("target_size");
2001        let memory_bound = args.optional("memory_bound");
2002
2003        let mut inputs = Vec::new();
2004        for input in args.args.get("inputs").expect("missing inputs") {
2005            inputs.push(
2006                datadriven
2007                    .batches
2008                    .get(input)
2009                    .expect("unknown batch")
2010                    .clone(),
2011            );
2012        }
2013
2014        let cfg = datadriven.client.cfg.clone();
2015        if let Some(target_size) = target_size {
2016            cfg.set_config(&BLOB_TARGET_SIZE, target_size);
2017        };
2018        if let Some(memory_bound) = memory_bound {
2019            cfg.set_config(&COMPACTION_MEMORY_BOUND_BYTES, memory_bound);
2020        }
2021        let req = CompactReq {
2022            shard_id: datadriven.shard_id,
2023            desc: Description::new(lower, upper, since),
2024            inputs: inputs.clone(),
2025        };
2026        datadriven
2027            .compactions
2028            .insert(output.to_owned(), req.clone());
2029        let spine_lower = inputs
2030            .first()
2031            .map_or_else(|| datadriven.next_id, |x| x.id.0);
2032        let spine_upper = inputs.last().map_or_else(
2033            || {
2034                datadriven.next_id += 1;
2035                datadriven.next_id
2036            },
2037            |x| x.id.1,
2038        );
2039        let new_spine_id = SpineId(spine_lower, spine_upper);
2040        let res = Compactor::<String, (), u64, i64>::compact(
2041            CompactConfig::new(&cfg, datadriven.shard_id),
2042            Arc::clone(&datadriven.client.blob),
2043            Arc::clone(&datadriven.client.metrics),
2044            Arc::clone(&datadriven.machine.applier.shard_metrics),
2045            Arc::clone(&datadriven.client.isolated_runtime),
2046            req,
2047            SCHEMAS.clone(),
2048        )
2049        .await?;
2050
2051        let batch = IdHollowBatch {
2052            batch: Arc::new(res.output.clone()),
2053            id: new_spine_id,
2054        };
2055
2056        datadriven.batches.insert(output.to_owned(), batch.clone());
2057        Ok(format!(
2058            "parts={} len={}\n",
2059            res.output.part_count(),
2060            res.output.len
2061        ))
2062    }
2063
2064    pub async fn clear_blob(
2065        datadriven: &MachineState,
2066        _args: DirectiveArgs<'_>,
2067    ) -> Result<String, anyhow::Error> {
2068        let mut to_delete = vec![];
2069        datadriven
2070            .client
2071            .blob
2072            .list_keys_and_metadata("", &mut |meta| {
2073                to_delete.push(meta.key.to_owned());
2074            })
2075            .await?;
2076        for blob in &to_delete {
2077            datadriven.client.blob.delete(blob).await?;
2078        }
2079        Ok(format!("deleted={}\n", to_delete.len()))
2080    }
2081
2082    pub async fn restore_blob(
2083        datadriven: &MachineState,
2084        _args: DirectiveArgs<'_>,
2085    ) -> Result<String, anyhow::Error> {
2086        let not_restored = crate::internal::restore::restore_blob(
2087            &datadriven.state_versions,
2088            datadriven.client.blob.as_ref(),
2089            &datadriven.client.cfg.build_version,
2090            datadriven.shard_id,
2091            &*datadriven.state_versions.metrics,
2092        )
2093        .await?;
2094        let mut out = String::new();
2095        for key in not_restored {
2096            writeln!(&mut out, "{key}");
2097        }
2098        Ok(out)
2099    }
2100
2101    #[allow(clippy::unused_async)]
2102    pub async fn rewrite_ts(
2103        datadriven: &mut MachineState,
2104        args: DirectiveArgs<'_>,
2105    ) -> Result<String, anyhow::Error> {
2106        let input = args.expect_str("input");
2107        let ts_rewrite = args.expect_antichain("frontier");
2108        let upper = args.expect_antichain("upper");
2109
2110        let batch = datadriven.batches.get_mut(input).expect("unknown batch");
2111        let mut hollow_batch = (*batch.batch).clone();
2112        let () = hollow_batch
2113            .rewrite_ts(&ts_rewrite, upper)
2114            .map_err(|err| anyhow!("invalid rewrite: {}", err))?;
2115        batch.batch = Arc::new(hollow_batch);
2116        Ok("ok\n".into())
2117    }
2118
2119    pub async fn gc(
2120        datadriven: &mut MachineState,
2121        args: DirectiveArgs<'_>,
2122    ) -> Result<String, anyhow::Error> {
2123        let new_seqno_since = args.expect("to_seqno");
2124
2125        let req = GcReq {
2126            shard_id: datadriven.shard_id,
2127            new_seqno_since,
2128        };
2129        let (maintenance, stats) =
2130            GarbageCollector::gc_and_truncate(&datadriven.machine, req).await;
2131        datadriven.routine.push(maintenance);
2132
2133        Ok(format!(
2134            "{} batch_parts={} rollups={} truncated={} state_rollups={}\n",
2135            datadriven.machine.seqno(),
2136            stats.batch_parts_deleted_from_blob,
2137            stats.rollups_deleted_from_blob,
2138            stats
2139                .truncated_consensus_to
2140                .iter()
2141                .map(|x| x.to_string())
2142                .collect::<Vec<_>>()
2143                .join(","),
2144            stats
2145                .rollups_removed_from_state
2146                .iter()
2147                .map(|x| x.to_string())
2148                .collect::<Vec<_>>()
2149                .join(","),
2150        ))
2151    }
2152
2153    pub async fn snapshot(
2154        datadriven: &MachineState,
2155        args: DirectiveArgs<'_>,
2156    ) -> Result<String, anyhow::Error> {
2157        let as_of = args.expect_antichain("as_of");
2158        let snapshot = datadriven
2159            .machine
2160            .unleased_snapshot(&as_of)
2161            .await
2162            .map_err(|err| anyhow!("{:?}", err))?;
2163
2164        let mut result = String::new();
2165
2166        for batch in snapshot {
2167            writeln!(
2168                result,
2169                "<batch {:?}-{:?}>",
2170                batch.desc.lower().elements(),
2171                batch.desc.upper().elements()
2172            );
2173            for (run, (_meta, parts)) in batch.runs().enumerate() {
2174                writeln!(result, "<run {run}>");
2175                let mut stream = pin!(
2176                    futures::stream::iter(parts)
2177                        .flat_map(|part| part.part_stream(
2178                            datadriven.shard_id,
2179                            &*datadriven.state_versions.blob,
2180                            &*datadriven.state_versions.metrics
2181                        ))
2182                        .enumerate()
2183                );
2184
2185                while let Some((idx, part)) = stream.next().await {
2186                    let part = &*part?;
2187                    writeln!(result, "<part {idx}>");
2188
2189                    let part = EncodedPart::fetch(
2190                        &FetchConfig::from_persist_config(&datadriven.client.cfg),
2191                        &datadriven.shard_id,
2192                        datadriven.client.blob.as_ref(),
2193                        datadriven.client.metrics.as_ref(),
2194                        datadriven.machine.applier.shard_metrics.as_ref(),
2195                        &datadriven.client.metrics.read.batch_fetcher,
2196                        &batch.desc,
2197                        part,
2198                    )
2199                    .await
2200                    .expect("invalid batch part");
2201                    let part = part
2202                        .normalize(&datadriven.client.metrics.columnar)
2203                        .into_part::<String, ()>(&*SCHEMAS.key, &*SCHEMAS.val);
2204
2205                    let mut updates = Vec::new();
2206
2207                    for ((k, _v), mut t, d) in part
2208                        .decode_iter::<_, _, u64, i64>(&*SCHEMAS.key, &*SCHEMAS.val)
2209                        .expect("valid schemas")
2210                    {
2211                        t.advance_by(as_of.borrow());
2212                        updates.push((k, t, d));
2213                    }
2214
2215                    consolidate_updates(&mut updates);
2216
2217                    for (k, t, d) in updates {
2218                        writeln!(result, "{k} {t} {d}");
2219                    }
2220                }
2221            }
2222        }
2223
2224        Ok(result)
2225    }
2226
2227    pub async fn register_listen(
2228        datadriven: &mut MachineState,
2229        args: DirectiveArgs<'_>,
2230    ) -> Result<String, anyhow::Error> {
2231        let output = args.expect_str("output");
2232        let as_of = args.expect_antichain("as_of");
2233        let read = datadriven
2234            .client
2235            .open_leased_reader::<String, (), u64, i64>(
2236                datadriven.shard_id,
2237                Arc::new(StringSchema),
2238                Arc::new(UnitSchema),
2239                Diagnostics::for_tests(),
2240                true,
2241            )
2242            .await
2243            .expect("invalid shard types");
2244        let listen = read
2245            .listen(as_of)
2246            .await
2247            .map_err(|err| anyhow!("{:?}", err))?;
2248        datadriven.listens.insert(output.to_owned(), listen);
2249        Ok("ok\n".into())
2250    }
2251
2252    pub async fn listen_through(
2253        datadriven: &mut MachineState,
2254        args: DirectiveArgs<'_>,
2255    ) -> Result<String, anyhow::Error> {
2256        let input = args.expect_str("input");
2257        // It's not possible to listen _through_ the empty antichain, so this is
2258        // intentionally `expect` instead of `expect_antichain`.
2259        let frontier = args.expect("frontier");
2260        let listen = datadriven.listens.get_mut(input).expect("unknown listener");
2261        let mut s = String::new();
2262        loop {
2263            for event in listen.fetch_next().await {
2264                match event {
2265                    ListenEvent::Updates(x) => {
2266                        for ((k, _v), t, d) in x.iter() {
2267                            write!(s, "{} {} {}\n", k, t, d);
2268                        }
2269                    }
2270                    ListenEvent::Progress(x) => {
2271                        if !x.less_than(&frontier) {
2272                            return Ok(s);
2273                        }
2274                    }
2275                }
2276            }
2277        }
2278    }
2279
2280    pub async fn register_critical_reader(
2281        datadriven: &mut MachineState,
2282        args: DirectiveArgs<'_>,
2283    ) -> Result<String, anyhow::Error> {
2284        let reader_id = args.expect("reader_id");
2285        let (state, maintenance) = datadriven
2286            .machine
2287            .register_critical_reader(&reader_id, Opaque::encode(&0u64), "tests")
2288            .await;
2289        datadriven.routine.push(maintenance);
2290        Ok(format!(
2291            "{} {:?}\n",
2292            datadriven.machine.seqno(),
2293            state.since.elements(),
2294        ))
2295    }
2296
2297    pub async fn register_leased_reader(
2298        datadriven: &mut MachineState,
2299        args: DirectiveArgs<'_>,
2300    ) -> Result<String, anyhow::Error> {
2301        let reader_id = args.expect("reader_id");
2302        let (reader_state, maintenance) = datadriven
2303            .machine
2304            .register_leased_reader(
2305                &reader_id,
2306                "tests",
2307                READER_LEASE_DURATION.get(&datadriven.client.cfg),
2308                false,
2309            )
2310            .await;
2311        datadriven.routine.push(maintenance);
2312        Ok(format!(
2313            "{} {:?}\n",
2314            datadriven.machine.seqno(),
2315            reader_state.since.elements(),
2316        ))
2317    }
2318
2319    pub async fn expire_critical_reader(
2320        datadriven: &mut MachineState,
2321        args: DirectiveArgs<'_>,
2322    ) -> Result<String, anyhow::Error> {
2323        let reader_id = args.expect("reader_id");
2324        let (_, maintenance) = datadriven.machine.expire_critical_reader(&reader_id).await;
2325        datadriven.routine.push(maintenance);
2326        Ok(format!("{} ok\n", datadriven.machine.seqno()))
2327    }
2328
2329    pub async fn expire_leased_reader(
2330        datadriven: &mut MachineState,
2331        args: DirectiveArgs<'_>,
2332    ) -> Result<String, anyhow::Error> {
2333        let reader_id = args.expect("reader_id");
2334        let (_, maintenance) = datadriven.machine.expire_leased_reader(&reader_id).await;
2335        datadriven.routine.push(maintenance);
2336        Ok(format!("{} ok\n", datadriven.machine.seqno()))
2337    }
2338
2339    pub async fn compare_and_append_batches(
2340        datadriven: &MachineState,
2341        args: DirectiveArgs<'_>,
2342    ) -> Result<String, anyhow::Error> {
2343        let expected_upper = args.expect_antichain("expected_upper");
2344        let new_upper = args.expect_antichain("new_upper");
2345
2346        let mut batches: Vec<Batch<String, (), u64, i64>> = args
2347            .args
2348            .get("batches")
2349            .expect("missing batches")
2350            .into_iter()
2351            .map(|batch| {
2352                let hollow = (*datadriven
2353                    .batches
2354                    .get(batch)
2355                    .expect("unknown batch")
2356                    .clone()
2357                    .batch)
2358                    .clone();
2359                datadriven.to_batch(hollow)
2360            })
2361            .collect();
2362
2363        let mut writer = datadriven
2364            .client
2365            .open_writer(
2366                datadriven.shard_id,
2367                Arc::new(StringSchema),
2368                Arc::new(UnitSchema),
2369                Diagnostics::for_tests(),
2370            )
2371            .await?;
2372
2373        let mut batch_refs: Vec<_> = batches.iter_mut().collect();
2374
2375        let () = writer
2376            .compare_and_append_batch(batch_refs.as_mut_slice(), expected_upper, new_upper, true)
2377            .await?
2378            .map_err(|err| anyhow!("upper mismatch: {:?}", err))?;
2379
2380        writer.expire().await;
2381
2382        Ok("ok\n".into())
2383    }
2384
2385    pub async fn expire_writer(
2386        datadriven: &mut MachineState,
2387        args: DirectiveArgs<'_>,
2388    ) -> Result<String, anyhow::Error> {
2389        let writer_id = args.expect("writer_id");
2390        let (_, maintenance) = datadriven.machine.expire_writer(&writer_id).await;
2391        datadriven.routine.push(maintenance);
2392        Ok(format!("{} ok\n", datadriven.machine.seqno()))
2393    }
2394
2395    pub(crate) async fn finalize(
2396        datadriven: &mut MachineState,
2397        _args: DirectiveArgs<'_>,
2398    ) -> anyhow::Result<String> {
2399        let maintenance = datadriven.machine.become_tombstone().await?;
2400        datadriven.routine.push(maintenance);
2401        Ok(format!("{} ok\n", datadriven.machine.seqno()))
2402    }
2403
2404    pub(crate) fn is_finalized(
2405        datadriven: &MachineState,
2406        _args: DirectiveArgs<'_>,
2407    ) -> anyhow::Result<String> {
2408        let seqno = datadriven.machine.seqno();
2409        let tombstone = datadriven.machine.is_finalized();
2410        Ok(format!("{seqno} {tombstone}\n"))
2411    }
2412
2413    pub async fn compare_and_append(
2414        datadriven: &mut MachineState,
2415        args: DirectiveArgs<'_>,
2416    ) -> Result<String, anyhow::Error> {
2417        let input = args.expect_str("input");
2418        let writer_id = args.expect("writer_id");
2419        let mut batch = datadriven
2420            .batches
2421            .get(input)
2422            .expect("unknown batch")
2423            .clone();
2424        let token = args.optional("token").unwrap_or_else(IdempotencyToken::new);
2425
2426        let (id, maintenance) = datadriven
2427            .machine
2428            .register_schema(&*SCHEMAS.key, &*SCHEMAS.val)
2429            .await;
2430        assert_eq!(id, SCHEMAS.id);
2431        datadriven.routine.push(maintenance);
2432        let maintenance = loop {
2433            let indeterminate = args
2434                .optional::<String>("prev_indeterminate")
2435                .map(|x| Indeterminate::new(anyhow::Error::msg(x)));
2436            let res = datadriven
2437                .machine
2438                .compare_and_append_idempotent(
2439                    &batch.batch,
2440                    &writer_id,
2441                    &token,
2442                    &HandleDebugState::default(),
2443                    indeterminate,
2444                )
2445                .await;
2446            match res {
2447                CompareAndAppendRes::Success(_, x) => break x,
2448                CompareAndAppendRes::UpperMismatch(_seqno, upper) => {
2449                    return Err(anyhow!("{:?}", Upper(upper)));
2450                }
2451                CompareAndAppendRes::InlineBackpressure => {
2452                    let hollow_batch = (*batch.batch).clone();
2453                    let mut b = datadriven.to_batch(hollow_batch);
2454                    let cfg = BatchBuilderConfig::new(&datadriven.client.cfg, datadriven.shard_id);
2455                    b.flush_to_blob(
2456                        &cfg,
2457                        &datadriven.client.metrics.user,
2458                        &datadriven.client.isolated_runtime,
2459                        &*SCHEMAS,
2460                    )
2461                    .await;
2462                    batch.batch = Arc::new(b.into_hollow_batch());
2463                    continue;
2464                }
2465                CompareAndAppendRes::InvalidUsage(_) => panic!("{:?}", res),
2466            };
2467        };
2468        // TODO: Don't throw away writer maintenance. It's slightly tricky
2469        // because we need a WriterId for Compactor.
2470        datadriven.routine.push(maintenance.routine);
2471        Ok(format!(
2472            "{} {:?}\n",
2473            datadriven.machine.seqno(),
2474            datadriven.machine.applier.clone_upper().elements(),
2475        ))
2476    }
2477
2478    pub async fn apply_merge_res(
2479        datadriven: &mut MachineState,
2480        args: DirectiveArgs<'_>,
2481    ) -> Result<String, anyhow::Error> {
2482        let input = args.expect_str("input");
2483        let legacy = args.optional("legacy").unwrap_or(false);
2484        let batch = datadriven
2485            .batches
2486            .get(input)
2487            .expect("unknown batch")
2488            .clone();
2489        let compaction_input = if legacy {
2490            CompactionInput::Legacy
2491        } else {
2492            let compact_req = datadriven
2493                .compactions
2494                .get(input)
2495                .expect("unknown compact req")
2496                .clone();
2497            let input_batches = compact_req
2498                .inputs
2499                .iter()
2500                .map(|x| x.id)
2501                .collect::<BTreeSet<_>>();
2502            let lower_spine_bound = input_batches
2503                .first()
2504                .map(|id| id.0)
2505                .expect("at least one batch must be present");
2506            let upper_spine_bound = input_batches
2507                .last()
2508                .map(|id| id.1)
2509                .expect("at least one batch must be present");
2510            CompactionInput::IdRange(SpineId(lower_spine_bound, upper_spine_bound))
2511        };
2512        let hollow_batch = (*batch.batch).clone();
2513
2514        let (merge_res, maintenance) = datadriven
2515            .machine
2516            .merge_res(&FueledMergeRes {
2517                output: hollow_batch,
2518                input: compaction_input,
2519                new_active_compaction: None,
2520            })
2521            .await;
2522        datadriven.routine.push(maintenance);
2523        Ok(format!(
2524            "{} {}\n",
2525            datadriven.machine.seqno(),
2526            merge_res.applied()
2527        ))
2528    }
2529
2530    pub async fn perform_maintenance(
2531        datadriven: &mut MachineState,
2532        _args: DirectiveArgs<'_>,
2533    ) -> Result<String, anyhow::Error> {
2534        let mut s = String::new();
2535        for maintenance in datadriven.routine.drain(..) {
2536            // One step at a time, rollup before GC, so the output doesn't
2537            // depend on which wins a race.
2538            let mut pending = vec![maintenance];
2539            while let Some(m) = pending.pop() {
2540                if m.write_rollup.is_some() {
2541                    pending.push(datadriven.machine.add_rollup_for_current_seqno().await);
2542                }
2543                if let Some(req) = m.garbage_collection {
2544                    let machine = &datadriven.machine;
2545                    pending.push(GarbageCollector::gc_and_truncate(machine, req).await.0);
2546                }
2547            }
2548            let () = datadriven
2549                .machine
2550                .applier
2551                .fetch_and_update_state(None)
2552                .await;
2553            write!(s, "{} ok\n", datadriven.machine.seqno());
2554        }
2555        Ok(s)
2556    }
2557}
2558
2559#[cfg(test)]
2560pub mod tests {
2561    use std::collections::BTreeSet;
2562    use std::sync::Arc;
2563    use std::sync::atomic::{AtomicBool, Ordering};
2564
2565    use mz_dyncfg::ConfigUpdates;
2566    use mz_ore::cast::CastFrom;
2567    use mz_ore::metrics::MetricsRegistry;
2568    use mz_ore::task::spawn;
2569    use mz_persist::intercept::{InterceptBlob, InterceptHandle};
2570    use mz_persist::location::{BlobMetadata, SeqNo};
2571    use mz_persist::mem::{MemBlob, MemBlobConfig, MemConsensus};
2572    use mz_persist_types::PersistLocation;
2573    use semver::Version;
2574    use timely::progress::Antichain;
2575
2576    use crate::async_runtime::IsolatedRuntime;
2577    use crate::batch::{BatchBuilderConfig, INLINE_WRITES_SINGLE_MAX_BYTES};
2578    use crate::cache::StateCache;
2579    use crate::cfg::GC_REMOVE_FINALIZED_ROLLUPS;
2580    use crate::internal::gc::{GarbageCollector, GcCaller, GcReq, GcResults};
2581    use crate::internal::machine::Machine;
2582    use crate::internal::metrics::Metrics;
2583    use crate::internal::paths::{BlobKey, BlobKeyPrefix, PartialBlobKey};
2584    use crate::internal::state::{
2585        GC_MAX_VERSIONS, GC_USE_ACTIVE_GC, HandleDebugState, ROLLUP_THRESHOLD,
2586    };
2587    use crate::rpc::NoopPubSubSender;
2588    use crate::tests::{LoseOneCasResponse, new_test_client, new_test_client_cache};
2589    use crate::{Diagnostics, PersistClient, PersistConfig, ShardId};
2590
2591    #[mz_persist_proc::test(tokio::test(flavor = "multi_thread"))]
2592    #[cfg_attr(miri, ignore)] // error: unsupported operation: integer-to-pointer casts and `ptr::from_exposed_addr` are not supported with `-Zmiri-strict-provenance`
2593    async fn apply_unbatched_cmd_truncate(dyncfgs: ConfigUpdates) {
2594        mz_ore::test::init_logging();
2595
2596        let client = new_test_client(&dyncfgs).await;
2597        // set a low rollup threshold so GC/truncation is more aggressive
2598        client.cfg.set_config(&ROLLUP_THRESHOLD, 5);
2599        let (mut write, read) = client
2600            .expect_open::<String, (), u64, i64>(ShardId::new())
2601            .await;
2602
2603        // Ensure the reader is not holding back the since.
2604        read.expire().await;
2605
2606        // Write a bunch of batches. This should result in a bounded number of
2607        // live entries in consensus.
2608        const NUM_BATCHES: u64 = 100;
2609        for idx in 0..NUM_BATCHES {
2610            let mut batch = write
2611                .expect_batch(&[((idx.to_string(), ()), idx, 1)], idx, idx + 1)
2612                .await;
2613            // Flush this batch out so the CaA doesn't get inline writes
2614            // backpressure.
2615            let cfg = BatchBuilderConfig::new(&client.cfg, write.shard_id());
2616            batch
2617                .flush_to_blob(
2618                    &cfg,
2619                    &client.metrics.user,
2620                    &client.isolated_runtime,
2621                    &write.write_schemas,
2622                )
2623                .await;
2624            let (_, writer_maintenance) = write
2625                .machine
2626                .compare_and_append(
2627                    &batch.into_hollow_batch(),
2628                    &write.writer_id,
2629                    &HandleDebugState::default(),
2630                )
2631                .await
2632                .unwrap();
2633            writer_maintenance
2634                .perform(&write.machine, &write.gc, write.compact.as_ref())
2635                .await;
2636        }
2637        let live_diffs = write
2638            .machine
2639            .applier
2640            .state_versions
2641            .fetch_all_live_diffs(&write.machine.shard_id())
2642            .await;
2643        // Make sure we constructed the key correctly.
2644        assert!(live_diffs.len() > 0);
2645        // Make sure the number of entries is bounded. (I think we could work
2646        // out a tighter bound than this, but the point is only that it's
2647        // bounded).
2648        let max_live_diffs = 2 * usize::cast_from(NUM_BATCHES.next_power_of_two().trailing_zeros());
2649        assert!(
2650            live_diffs.len() <= max_live_diffs,
2651            "{} vs {}",
2652            live_diffs.len(),
2653            max_live_diffs
2654        );
2655    }
2656
2657    // A regression test for database-issues#4206, where a bug in gc led to an incremental
2658    // state invariant being violated which resulted in gc being permanently
2659    // wedged for the shard.
2660    #[mz_persist_proc::test(tokio::test(flavor = "multi_thread"))]
2661    #[cfg_attr(miri, ignore)] // error: unsupported operation: integer-to-pointer casts and `ptr::from_exposed_addr` are not supported with `-Zmiri-strict-provenance`
2662    async fn regression_gc_skipped_req_and_interrupted(dyncfgs: ConfigUpdates) {
2663        let mut client = new_test_client(&dyncfgs).await;
2664        let intercept = InterceptHandle::default();
2665        client.blob = Arc::new(InterceptBlob::new(
2666            Arc::clone(&client.blob),
2667            intercept.clone(),
2668        ));
2669        let (_, mut read) = client
2670            .expect_open::<String, String, u64, i64>(ShardId::new())
2671            .await;
2672
2673        // Create a new SeqNo
2674        read.downgrade_since(&Antichain::from_elem(1)).await;
2675        let new_seqno_since = read.machine.applier.seqno_since();
2676
2677        // Start a GC in the background for some SeqNo range that is not
2678        // contiguous compared to the last gc req (in this case, n/a) and then
2679        // crash when it gets to the blob deletes. In the regression case, this
2680        // renders the shard permanently un-gc-able.
2681        assert!(new_seqno_since > SeqNo::minimum());
2682        intercept.set_post_delete(Some(Arc::new(|_, _| panic!("boom"))));
2683        let machine = read.machine.clone();
2684        // Run this in a spawn so we can catch the boom panic
2685        let gc = spawn(|| "", async move {
2686            let req = GcReq {
2687                shard_id: machine.shard_id(),
2688                new_seqno_since,
2689            };
2690            GarbageCollector::gc_and_truncate(&machine, req).await
2691        });
2692        // Wait for gc to either panic (regression case) or finish (good case)
2693        // because it happens to not call blob delete.
2694        let _ = gc.await;
2695
2696        // Allow blob deletes to go through and try GC again. In the regression
2697        // case, this hangs.
2698        intercept.set_post_delete(None);
2699        let req = GcReq {
2700            shard_id: read.machine.shard_id(),
2701            new_seqno_since,
2702        };
2703        let _ = GarbageCollector::gc_and_truncate(&read.machine, req.clone()).await;
2704    }
2705
2706    // A regression test for materialize#20776, where a bug meant that compare_and_append
2707    // would not fetch the latest state after an upper mismatch. This meant that
2708    // a write that could succeed if retried on the latest state would instead
2709    // return an UpperMismatch.
2710    #[mz_persist_proc::test(tokio::test(flavor = "multi_thread"))]
2711    #[cfg_attr(miri, ignore)] // error: unsupported operation: integer-to-pointer casts and `ptr::from_exposed_addr` are not supported with `-Zmiri-strict-provenance`
2712    async fn regression_update_state_after_upper_mismatch(dyncfgs: ConfigUpdates) {
2713        let client = new_test_client(&dyncfgs).await;
2714        let mut client2 = client.clone();
2715
2716        // The bug can only happen if the two WriteHandles have separate copies
2717        // of state, so make sure that each is given its own StateCache.
2718        let new_state_cache = Arc::new(StateCache::new_no_metrics());
2719        client2.shared_states = new_state_cache;
2720
2721        let shard_id = ShardId::new();
2722        let (mut write1, _) = client.expect_open::<String, (), u64, i64>(shard_id).await;
2723        let (mut write2, _) = client2.expect_open::<String, (), u64, i64>(shard_id).await;
2724
2725        let data = [
2726            (("1".to_owned(), ()), 1, 1),
2727            (("2".to_owned(), ()), 2, 1),
2728            (("3".to_owned(), ()), 3, 1),
2729            (("4".to_owned(), ()), 4, 1),
2730            (("5".to_owned(), ()), 5, 1),
2731        ];
2732
2733        write1.expect_compare_and_append(&data[..1], 0, 2).await;
2734
2735        // this handle's upper now lags behind. if compare_and_append fails to update
2736        // state after an upper mismatch then this call would (incorrectly) fail
2737        write2.expect_compare_and_append(&data[1..2], 2, 3).await;
2738    }
2739
2740    #[mz_persist_proc::test(tokio::test(flavor = "multi_thread"))]
2741    #[cfg_attr(miri, ignore)]
2742    async fn version_upgrade(dyncfgs: ConfigUpdates) {
2743        let mut cache = new_test_client_cache(&dyncfgs);
2744        cache.cfg.build_version = Version::new(26, 1, 0);
2745        let shard_id = ShardId::new();
2746
2747        async fn fetch_catalog_upgrade_shard_version(
2748            persist_client: &PersistClient,
2749            upgrade_shard_id: ShardId,
2750        ) -> Option<semver::Version> {
2751            let shard_state = persist_client
2752                .inspect_shard::<u64>(&upgrade_shard_id)
2753                .await
2754                .ok()?;
2755            let json_state = serde_json::to_value(shard_state).expect("state serialization error");
2756            let upgrade_version = json_state
2757                .get("applier_version")
2758                .cloned()
2759                .expect("missing applier_version");
2760            let upgrade_version =
2761                serde_json::from_value(upgrade_version).expect("version deserialization error");
2762            Some(upgrade_version)
2763        }
2764
2765        cache.cfg.build_version = Version::new(26, 1, 0);
2766        let client = cache.open(PersistLocation::new_in_mem()).await.unwrap();
2767        let (write, mut reader) = client.expect_open::<String, (), u64, i64>(shard_id).await;
2768        reader.downgrade_since(&Antichain::from_elem(1)).await;
2769        assert_eq!(
2770            fetch_catalog_upgrade_shard_version(&client, shard_id).await,
2771            Some(Version::new(26, 1, 0)),
2772        );
2773
2774        // Expire the old-version handles before bumping the build version. They
2775        // share the in-mem state cache, and if their background tasks (reader
2776        // heartbeat / writer expiry) are left to linger they can observe the
2777        // upgraded 27.1.0 state below and panic on the version mismatch
2778        // (apply.rs `code_can_write_data` / encoding.rs `assert_code_can_read_data`),
2779        // poisoning the shared state lock and flaking the test. `expire` does
2780        // the final cleanup at the current version and awaits the background
2781        // task, so nothing at 26.1.0 outlives the upgrade.
2782        write.expire().await;
2783        reader.expire().await;
2784
2785        // Merely opening and operating on the shard at a new version doesn't bump version...
2786        cache.cfg.build_version = Version::new(27, 1, 0);
2787        let client = cache.open(PersistLocation::new_in_mem()).await.unwrap();
2788        let (write, mut reader) = client.expect_open::<String, (), u64, i64>(shard_id).await;
2789        reader.downgrade_since(&Antichain::from_elem(2)).await;
2790        assert_eq!(
2791            fetch_catalog_upgrade_shard_version(&client, shard_id).await,
2792            Some(Version::new(26, 1, 0)),
2793        );
2794
2795        // ...but an explicit call will.
2796        client
2797            .upgrade_version::<String, (), u64, i64>(shard_id, Diagnostics::for_tests())
2798            .await
2799            .unwrap();
2800        assert_eq!(
2801            fetch_catalog_upgrade_shard_version(&client, shard_id).await,
2802            Some(Version::new(27, 1, 0)),
2803        );
2804
2805        write.expire().await;
2806        reader.expire().await;
2807    }
2808
2809    /// Regression test for a panic where `upgrade_version` tried to commit a
2810    /// new state on a tombstone shard. Upgrading a tombstone must be a no-op:
2811    /// the shard stays finalized and its recorded version stays unchanged.
2812    #[mz_persist_proc::test(tokio::test)]
2813    #[cfg_attr(miri, ignore)] // too slow
2814    async fn version_upgrade_tombstone(dyncfgs: ConfigUpdates) {
2815        async fn shard_version(
2816            persist_client: &PersistClient,
2817            shard_id: ShardId,
2818        ) -> Option<semver::Version> {
2819            let shard_state = persist_client.inspect_shard::<u64>(&shard_id).await.ok()?;
2820            let json_state = serde_json::to_value(shard_state).expect("state serialization error");
2821            let version = json_state
2822                .get("applier_version")
2823                .cloned()
2824                .expect("missing applier_version");
2825            Some(serde_json::from_value(version).expect("version deserialization error"))
2826        }
2827
2828        let mut cache = new_test_client_cache(&dyncfgs);
2829        cache.cfg.build_version = Version::new(26, 1, 0);
2830        let client = cache.open(PersistLocation::new_in_mem()).await.unwrap();
2831        let shard_id = ShardId::new();
2832
2833        // Advance since and upper to the empty antichain and finalize the
2834        // shard into a tombstone.
2835        let (mut write, mut read) = client.expect_open::<String, (), u64, i64>(shard_id).await;
2836        read.downgrade_since(&Antichain::new()).await;
2837        write.advance_upper(&Antichain::new()).await;
2838        // Expiring the last handle here would start a background rollup that
2839        // could commit after finalize_shard finishes GC.
2840        client
2841            .finalize_shard::<String, (), u64, i64>(shard_id, Diagnostics::for_tests())
2842            .await
2843            .expect("finalization must succeed");
2844        write.expire().await;
2845        read.expire().await;
2846
2847        // Upgrading at the version that wrote the tombstone must not panic or
2848        // commit a new state.
2849        client
2850            .upgrade_version::<String, (), u64, i64>(shard_id, Diagnostics::for_tests())
2851            .await
2852            .expect("upgrade on tombstone must succeed");
2853
2854        // Same for upgrading at a newer build version.
2855        cache.cfg.build_version = Version::new(27, 1, 0);
2856        let client = cache.open(PersistLocation::new_in_mem()).await.unwrap();
2857        client
2858            .upgrade_version::<String, (), u64, i64>(shard_id, Diagnostics::for_tests())
2859            .await
2860            .expect("upgrade on tombstone must succeed");
2861
2862        assert_eq!(
2863            shard_version(&client, shard_id).await,
2864            Some(Version::new(26, 1, 0)),
2865        );
2866        let is_finalized = client
2867            .is_finalized::<String, (), u64, i64>(shard_id, Diagnostics::for_tests())
2868            .await
2869            .expect("invalid persist usage");
2870        assert!(is_finalized, "shard must still be finalized");
2871    }
2872
2873    /// A machine with its own state cache, as after a restart.
2874    async fn cold_machine(
2875        client: &PersistClient,
2876        shard_id: ShardId,
2877    ) -> Machine<String, (), u64, i64> {
2878        let mut client = client.clone();
2879        client.shared_states = Arc::new(StateCache::new_no_metrics());
2880        client
2881            .make_machine(shard_id, Diagnostics::for_tests())
2882            .await
2883            .expect("codecs match")
2884    }
2885
2886    async fn gc(machine: &Machine<String, (), u64, i64>) -> GcResults {
2887        let req = GcReq {
2888            shard_id: machine.shard_id(),
2889            new_seqno_since: machine.applier.seqno_since(),
2890        };
2891        GarbageCollector::gc_and_truncate(machine, req).await.1
2892    }
2893
2894    /// GC removes a finalized shard's old rollups from state and blob, and a
2895    /// later GC finishes one interrupted before or after its commit. GC from
2896    /// stale state skips the shard.
2897    #[mz_persist_proc::test(tokio::test(flavor = "multi_thread"))]
2898    #[cfg_attr(miri, ignore)] // too slow
2899    async fn finalized_gc_removes_old_rollups(dyncfgs: ConfigUpdates) {
2900        let client = new_test_client(&dyncfgs).await;
2901        // Only active GC fetches diffs through `seqno_since`, which the stale
2902        // GC at the end needs.
2903        client.cfg.set_config(&GC_USE_ACTIVE_GC, true);
2904        let shard_id = ShardId::new();
2905        let (mut write, mut read) = client.expect_open::<String, (), u64, i64>(shard_id).await;
2906        read.downgrade_since(&Antichain::new()).await;
2907        write.advance_upper(&Antichain::new()).await;
2908        let machine = write.machine.clone();
2909
2910        // Finalize by hand. Expiring the last handle would write the final
2911        // rollup from a background task that races the GCs below. GC requests
2912        // are dropped, so the test runs each GC itself.
2913        let mut maintenance = machine
2914            .become_tombstone()
2915            .await
2916            .expect("since and upper are empty");
2917        while maintenance.write_rollup.is_some() {
2918            maintenance = machine.add_rollup_for_current_seqno().await;
2919        }
2920        assert!(machine.is_finalized());
2921        let stale = cold_machine(&client, shard_id).await;
2922
2923        let mut rollups = machine
2924            .applier
2925            .rollups_lte_seqno(machine.applier.seqno_since());
2926        let (kept_seqno, kept) = rollups.pop().expect("tombstone has a rollup");
2927        assert!(!rollups.is_empty(), "need an old rollup to delete");
2928        let old_keys: Vec<String> = rollups
2929            .iter()
2930            .map(|(_, key)| key.complete(&shard_id).to_string())
2931            .collect();
2932        let head_seqno = || async {
2933            client
2934                .consensus
2935                .head(&shard_id.to_string())
2936                .await
2937                .expect("head")
2938                .expect("shard is initialized")
2939                .seqno
2940        };
2941        let listed_rollups = || async {
2942            cold_machine(&client, shard_id)
2943                .await
2944                .applier
2945                .rollups_lte_seqno(SeqNo::maximum())
2946        };
2947        let old_blobs = || async {
2948            let mut n = 0;
2949            for key in &old_keys {
2950                n += usize::from(client.blob.get(key).await.expect("get").is_some());
2951            }
2952            n
2953        };
2954        let rollups_assigned = || client.metrics.state.finalized_rollup_assigned.get();
2955        let assigned = rollups_assigned();
2956
2957        // Crash after truncation, before the commit: with the kill switch off,
2958        // GC stops right there.
2959        client.cfg.set_config(&GC_REMOVE_FINALIZED_ROLLUPS, false);
2960        let seqno = head_seqno().await;
2961        gc(&cold_machine(&client, shard_id).await).await;
2962        client.cfg.set_config(&GC_REMOVE_FINALIZED_ROLLUPS, true);
2963        let live_diffs = machine
2964            .applier
2965            .state_versions
2966            .fetch_all_live_diffs(&shard_id)
2967            .await;
2968        assert_eq!(live_diffs.first().map(|x| x.seqno), Some(kept_seqno));
2969        assert_eq!(
2970            head_seqno().await,
2971            seqno,
2972            "kill switch off but gc committed"
2973        );
2974        assert_eq!(listed_rollups().await.len(), old_keys.len() + 1);
2975        assert_eq!(old_blobs().await, old_keys.len());
2976
2977        // Crash after the commit, before the deletes: run only GC's commit.
2978        let _ = cold_machine(&client, shard_id)
2979            .await
2980            .remove_rollups(&rollups, true)
2981            .await;
2982        let committed = head_seqno().await;
2983        assert_eq!(committed, seqno.next(), "gc should commit one removal");
2984        assert_eq!(listed_rollups().await, vec![(kept_seqno, kept.clone())]);
2985        assert_eq!(old_blobs().await, old_keys.len());
2986
2987        // The removal asks for one more rollup, which lets a later GC truncate
2988        // past it. That GC finishes the deletes without committing, and
2989        // further GCs are no-ops.
2990        let _ = cold_machine(&client, shard_id)
2991            .await
2992            .add_rollup_for_current_seqno()
2993            .await;
2994        let committed = head_seqno().await;
2995        let kept = listed_rollups().await;
2996        for i in 0..3 {
2997            let results = gc(&cold_machine(&client, shard_id).await).await;
2998            let expected_deleted = if i == 0 { old_keys.len() } else { 0 };
2999            assert_eq!(results.rollups_deleted_from_blob, expected_deleted);
3000            assert_eq!(old_blobs().await, 0, "old rollups still in blob");
3001            assert_eq!(
3002                head_seqno().await,
3003                committed,
3004                "gc at the fixed point committed"
3005            );
3006        }
3007        assert_eq!(listed_rollups().await, kept);
3008
3009        // GC from state older than the truncation is a no-op.
3010        let results = gc(&stale).await;
3011        assert!(results.truncated_consensus_to.is_empty());
3012        assert_eq!(results.rollups_deleted_from_blob, 0);
3013        assert_eq!(
3014            rollups_assigned(),
3015            assigned + 1,
3016            "rollup assigned after finalizing"
3017        );
3018
3019        write.expire().await;
3020        read.expire().await;
3021    }
3022
3023    /// A retried finalize finishes the GC that a crash cut short, with or
3024    /// without removing old rollups, however far behind GC was.
3025    #[mz_persist_proc::test(tokio::test(flavor = "multi_thread"))]
3026    #[cfg_attr(miri, ignore)] // too slow
3027    async fn finalize_retry_finishes_gc(dyncfgs: ConfigUpdates) {
3028        for remove_finalized_rollups in [false, true] {
3029            let mut client = new_test_client(&dyncfgs).await;
3030            // Background compaction writes and deletes its own parts, which
3031            // would race the part count below.
3032            client.cfg.compaction_enabled = false;
3033            client
3034                .cfg
3035                .set_config(&GC_REMOVE_FINALIZED_ROLLUPS, remove_finalized_rollups);
3036            // Write parts to blob, and cap each GC below the rollup spacing.
3037            client.cfg.set_config(&INLINE_WRITES_SINGLE_MAX_BYTES, 0);
3038            client.cfg.set_config(&ROLLUP_THRESHOLD, 3);
3039            client.cfg.set_config(&GC_MAX_VERSIONS, 1);
3040            let shard_id = ShardId::new();
3041            let (mut write, mut read) = client.expect_open::<String, (), u64, i64>(shard_id).await;
3042            for ts in 0..10 {
3043                let updates = [((ts.to_string(), ()), ts, 1)];
3044                write.expect_compare_and_append(&updates, ts, ts + 1).await;
3045            }
3046            read.downgrade_since(&Antichain::new()).await;
3047            write.advance_upper(&Antichain::new()).await;
3048            let parts = || async {
3049                let mut n = 0;
3050                let prefix = BlobKeyPrefix::Shard(&shard_id).to_string();
3051                let mut count = |x: BlobMetadata<'_>| {
3052                    if let Ok((_, PartialBlobKey::Batch(..))) = BlobKey::parse_ids(x.key) {
3053                        n += 1;
3054                    }
3055                };
3056                let list = client.blob.list_keys_and_metadata(&prefix, &mut count);
3057                list.await.expect("list");
3058                n
3059            };
3060            assert!(parts().await > 0);
3061
3062            read.expire().await;
3063            let deleted = |caller| client.metrics.gc.tombstone_deleted_blobs(caller);
3064            // Rollup maintenance from the writes above can still link a rollup
3065            // during the loop below, so compare keys rather than counts.
3066            let (_, rollups_before) = rollup_keys(&client, shard_id).await;
3067            // Every rollup seen in state, for the final check.
3068            let mut linked = rollups_before.clone();
3069            // The second GC deletes the rollup blobs that the first GC removed
3070            // from state.
3071            for _ in 0..2 {
3072                let _ = write.machine.add_rollup_for_current_seqno().await;
3073                let req = GcReq {
3074                    shard_id,
3075                    new_seqno_since: write.machine.applier.seqno_since(),
3076                };
3077                let done = write
3078                    .gc
3079                    .gc_and_truncate_background(req, GcCaller::Maintenance);
3080                let _ = done.expect("gc running").await;
3081                linked.extend(rollup_keys(&client, shard_id).await.1);
3082            }
3083            let (rollups_after, _) = rollup_keys(&client, shard_id).await;
3084            assert!(
3085                rollups_before.is_disjoint(&rollups_after),
3086                "live GC left rollups in blob"
3087            );
3088            assert_eq!(deleted("maintenance"), 0, "counted a live shard");
3089
3090            // Crash after the tombstone commit, before its GC.
3091            let _ = write
3092                .machine
3093                .become_tombstone()
3094                .await
3095                .expect("since and upper are empty");
3096            linked.extend(rollup_keys(&client, shard_id).await.1);
3097            let is_finalized = || async {
3098                let shard =
3099                    client.is_finalized::<String, (), u64, i64>(shard_id, Diagnostics::for_tests());
3100                shard.await.expect("valid usage")
3101            };
3102            assert!(!is_finalized().await, "finalized before GC ran");
3103
3104            let finalize =
3105                client.finalize_shard::<String, (), u64, i64>(shard_id, Diagnostics::for_tests());
3106            assert!(finalize.await.expect("valid usage"));
3107            assert!(is_finalized().await);
3108            assert_eq!(parts().await, 0, "retry left parts in blob");
3109            assert!(deleted("finalize") > 0, "retry's deletes not counted");
3110            let (blob, state) = rollup_keys(&client, shard_id).await;
3111            assert!(state.is_subset(&blob), "state references deleted rollups");
3112            // `Machine::add_rollup` reports a rollup as applied if any attempt
3113            // matched, so a background rollup write that loses a race to link
3114            // it leaks its blob. Check only the rollups seen in state.
3115            let removed: BTreeSet<_> = linked.difference(&state).cloned().collect();
3116            assert!(removed.is_disjoint(&blob), "retry left rollups in blob");
3117        }
3118    }
3119
3120    /// The rollup keys in blob, and in the latest state.
3121    async fn rollup_keys(
3122        client: &PersistClient,
3123        shard_id: ShardId,
3124    ) -> (BTreeSet<String>, BTreeSet<String>) {
3125        // Read state first: a rollup that background maintenance links between
3126        // the two reads would otherwise be in state but not in the listing.
3127        let machine = client
3128            .make_machine::<String, (), u64, i64>(shard_id, Diagnostics::for_tests())
3129            .await
3130            .expect("valid usage");
3131        machine.applier.fetch_and_update_state(None).await;
3132        let state = machine.applier.rollups_lte_seqno(SeqNo::maximum());
3133        let state = state.iter().map(|(_, x)| x.complete(&shard_id).to_string());
3134        let mut blob = BTreeSet::new();
3135        let prefix = BlobKeyPrefix::Shard(&shard_id).to_string();
3136        let mut collect = |x: BlobMetadata<'_>| {
3137            if let Ok((_, PartialBlobKey::Rollup(..))) = BlobKey::parse_ids(x.key) {
3138                blob.insert(x.key.to_owned());
3139            }
3140        };
3141        let list = client.blob.list_keys_and_metadata(&prefix, &mut collect);
3142        list.await.expect("list");
3143        (blob, state.collect())
3144    }
3145
3146    /// A `remove_rollups` on a finalized shard that commits but loses its
3147    /// response retries into a no-op, which asks for no rollup, so nothing
3148    /// truncates past the removal. A retried finalize still writes that rollup
3149    /// and deletes the removed blobs.
3150    #[mz_persist_proc::test(tokio::test(flavor = "multi_thread"))]
3151    #[cfg_attr(miri, ignore)] // too slow
3152    async fn finalize_retry_after_lost_remove_rollups(dyncfgs: ConfigUpdates) {
3153        let armed = Arc::new(AtomicBool::new(false));
3154        let consensus = LoseOneCasResponse {
3155            inner: Arc::new(MemConsensus::default()),
3156            armed: Arc::clone(&armed),
3157        };
3158        let mut cfg = PersistConfig::new_for_tests();
3159        dyncfgs.apply(&cfg);
3160        // Setup maintenance must not race the lost-response assertions below.
3161        cfg.compaction_enabled = false;
3162        cfg.set_config(&INLINE_WRITES_SINGLE_MAX_BYTES, 0);
3163        cfg.set_config(&ROLLUP_THRESHOLD, 100);
3164        // Finalize keeping old rollups, so turning this on leaves a removal.
3165        cfg.set_config(&GC_REMOVE_FINALIZED_ROLLUPS, false);
3166        let metrics = Arc::new(Metrics::new(&cfg, &MetricsRegistry::new()));
3167        let client = PersistClient::new(
3168            cfg,
3169            Arc::new(MemBlob::open(MemBlobConfig::default())),
3170            Arc::new(consensus),
3171            metrics,
3172            Arc::new(IsolatedRuntime::new_for_tests()),
3173            Arc::new(StateCache::new_no_metrics()),
3174            Arc::new(NoopPubSubSender),
3175        )
3176        .expect("client construction failed");
3177        let shard_id = ShardId::new();
3178        let (mut write, mut read) = client.expect_open::<String, (), u64, i64>(shard_id).await;
3179        for ts in 0..10 {
3180            let updates = [((ts.to_string(), ()), ts, 1)];
3181            write.expect_compare_and_append(&updates, ts, ts + 1).await;
3182        }
3183        read.downgrade_since(&Antichain::new()).await;
3184        write.advance_upper(&Antichain::new()).await;
3185        let finalize = || async {
3186            let finalize =
3187                client.finalize_shard::<String, (), u64, i64>(shard_id, Diagnostics::for_tests());
3188            finalize.await.expect("valid usage");
3189        };
3190        let is_finalized = || async {
3191            let shard =
3192                client.is_finalized::<String, (), u64, i64>(shard_id, Diagnostics::for_tests());
3193            shard.await.expect("valid usage")
3194        };
3195        finalize().await;
3196        assert!(is_finalized().await);
3197
3198        // GC's `remove_rollups` commits, but its response is lost.
3199        client.cfg.set_config(&GC_REMOVE_FINALIZED_ROLLUPS, true);
3200        let machine = client
3201            .make_machine::<String, (), u64, i64>(shard_id, Diagnostics::for_tests())
3202            .await
3203            .expect("valid usage");
3204        let new_seqno_since = machine.seqno();
3205        armed.store(true, Ordering::SeqCst);
3206        let req = GcReq {
3207            shard_id,
3208            new_seqno_since,
3209        };
3210        let (maintenance, _) = GarbageCollector::gc_and_truncate(&machine, req).await;
3211        assert!(!armed.load(Ordering::SeqCst), "no CaS lost its response");
3212        assert!(maintenance.is_empty(), "the retry asked for maintenance");
3213        let (blob, state) = rollup_keys(&client, shard_id).await;
3214        assert!(blob.len() > state.len(), "the removal deleted its blobs");
3215        assert!(!is_finalized().await);
3216
3217        finalize().await;
3218        assert!(is_finalized().await);
3219        let (blob, state) = rollup_keys(&client, shard_id).await;
3220        assert_eq!(blob, state, "retry left rollups in blob");
3221    }
3222}