Skip to main content

mz_persist_client/internal/
apply.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 persist command application.
11
12use std::collections::BTreeMap;
13use std::fmt::Debug;
14use std::ops::ControlFlow::{self, Break, Continue};
15use std::sync::Arc;
16use std::time::Instant;
17
18use crate::cache::{LockingTypedState, StateCache};
19use crate::cfg::GC_REMOVE_FINALIZED_ROLLUPS;
20use crate::error::{CodecMismatch, InvalidUsage};
21use crate::internal::gc::GcReq;
22use crate::internal::maintenance::RoutineMaintenance;
23use crate::internal::metrics::{CmdMetrics, Metrics, ShardMetrics};
24use crate::internal::paths::{PartialRollupKey, RollupId};
25use crate::internal::state::{
26    ActiveGc, ActiveRollup, EncodedSchemas, ExpiryMetrics, GC_FALLBACK_THRESHOLD_MS,
27    GC_MAX_VERSIONS, GC_MIN_VERSIONS, GC_USE_ACTIVE_GC, GcConfig, HollowBatch, LeasedReaderState,
28    ROLLUP_FALLBACK_THRESHOLD_MS, ROLLUP_THRESHOLD, ROLLUP_USE_ACTIVE_ROLLUP, Since, SnapshotErr,
29    StateCollections, TypedState,
30};
31use crate::internal::state_diff::StateDiff;
32use crate::internal::state_versions::{EncodedRollup, StateVersions};
33use crate::internal::trace::FueledMergeReq;
34use crate::internal::watch::StateWatch;
35use crate::read::LeasedReaderId;
36use crate::rpc::{PUBSUB_PUSH_DIFF_ENABLED, PubSubSender};
37use crate::schema::SchemaCache;
38use crate::{Diagnostics, PersistConfig, ShardId, cfg};
39use differential_dataflow::difference::Monoid;
40use differential_dataflow::lattice::Lattice;
41use mz_ore::cast::CastFrom;
42use mz_ore::soft_assert_or_log;
43use mz_persist::location::{CaSResult, Indeterminate, SeqNo, VersionedData};
44use mz_persist_types::schema::SchemaId;
45use mz_persist_types::{Codec, Codec64};
46use timely::progress::{Antichain, Timestamp};
47use tracing::debug;
48
49/// An applier of persist commands.
50///
51/// This struct exists mainly to allow us to very narrowly bound the surface
52/// area that directly interacts with state.
53#[derive(Debug)]
54pub struct Applier<K, V, T, D> {
55    pub(crate) cfg: PersistConfig,
56    pub(crate) metrics: Arc<Metrics>,
57    pub(crate) shard_metrics: Arc<ShardMetrics>,
58    pub(crate) state_versions: Arc<StateVersions>,
59    pubsub_sender: Arc<dyn PubSubSender>,
60    pub(crate) shard_id: ShardId,
61
62    // Access to the shard's state, shared across all handles created by the same
63    // PersistClientCache. The state is wrapped in LockingTypedState, disallowing
64    // access across await points. Access should be always be kept brief, and it
65    // is expected that other handles may advance the state at any time this Applier
66    // is not holding the lock.
67    //
68    // NB: This is very intentionally not pub(crate) so that it's easy to reason
69    //     very locally about the duration of locks.
70    state: Arc<LockingTypedState<K, V, T, D>>,
71}
72
73// Impl Clone regardless of the type params.
74impl<K, V, T: Clone, D> Clone for Applier<K, V, T, D> {
75    fn clone(&self) -> Self {
76        Self {
77            cfg: self.cfg.clone(),
78            metrics: Arc::clone(&self.metrics),
79            shard_metrics: Arc::clone(&self.shard_metrics),
80            state_versions: Arc::clone(&self.state_versions),
81            pubsub_sender: Arc::clone(&self.pubsub_sender),
82            shard_id: self.shard_id,
83            state: Arc::clone(&self.state),
84        }
85    }
86}
87
88impl<K, V, T, D> Applier<K, V, T, D>
89where
90    K: Debug + Codec,
91    V: Debug + Codec,
92    T: Timestamp + Lattice + Codec64 + Sync,
93    D: Monoid + Codec64,
94{
95    pub async fn new(
96        cfg: PersistConfig,
97        shard_id: ShardId,
98        metrics: Arc<Metrics>,
99        state_versions: Arc<StateVersions>,
100        shared_states: Arc<StateCache>,
101        pubsub_sender: Arc<dyn PubSubSender>,
102        diagnostics: Diagnostics,
103    ) -> Result<Self, Box<CodecMismatch>> {
104        let shard_metrics = metrics.shards.shard(&shard_id, &diagnostics.shard_name);
105        let state = shared_states
106            .get::<K, V, T, D, _, _>(
107                shard_id,
108                || {
109                    metrics.cmds.init_state.run_cmd(&shard_metrics, || {
110                        state_versions.maybe_init_shard(&shard_metrics)
111                    })
112                },
113                &diagnostics,
114            )
115            .await?;
116        let ret = Applier {
117            cfg,
118            metrics,
119            shard_metrics,
120            state_versions,
121            pubsub_sender,
122            shard_id,
123            state,
124        };
125        Ok(ret)
126    }
127
128    /// Returns a new [StateWatch] for changes to this Applier's State.
129    pub fn watch(&self) -> StateWatch<K, V, T, D> {
130        StateWatch::new(Arc::clone(&self.state), Arc::clone(&self.metrics))
131    }
132
133    /// Fetches the latest state from Consensus and passes its `upper` to the provided closure.
134    pub async fn fetch_upper<R, F: FnMut(&Antichain<T>) -> R>(&self, mut f: F) -> R {
135        self.metrics.cmds.fetch_upper_count.inc();
136        self.fetch_and_update_state(None).await;
137        self.upper(|_seqno, upper| f(upper))
138    }
139
140    /// A point-in-time read/clone of `upper` from the current state.
141    ///
142    /// Due to sharing state with other handles, successive reads to this fn or any other may
143    /// see a different version of state, even if this Applier has not explicitly fetched and
144    /// updated to the latest state. Successive calls will always return values such that
145    /// `PartialOrder::less_equal(call1, call2)` hold true.
146    pub fn clone_upper(&self) -> Antichain<T> {
147        self.upper(|_seqno, upper| upper.clone())
148    }
149
150    pub(crate) fn upper<R, F: FnMut(SeqNo, &Antichain<T>) -> R>(&self, mut f: F) -> R {
151        self.state
152            .read_lock(&self.metrics.locks.applier_read_cacheable, move |state| {
153                f(state.seqno, state.upper())
154            })
155    }
156
157    pub(crate) fn schemas<R>(
158        &self,
159        mut f: impl FnMut(SeqNo, &BTreeMap<SchemaId, EncodedSchemas>) -> R,
160    ) -> R {
161        self.state
162            .read_lock(&self.metrics.locks.applier_read_cacheable, move |state| {
163                f(state.seqno, &state.collections.schemas)
164            })
165    }
166
167    pub(crate) fn schema_cache(&self) -> SchemaCache<K, V, T, D> {
168        SchemaCache::new(self.state.schema_cache(), self.clone())
169    }
170
171    /// A point-in-time read of `since` from the current state.
172    ///
173    /// Due to sharing state with other handles, successive reads to this fn or any other may
174    /// see a different version of state, even if this Applier has not explicitly fetched and
175    /// updated to the latest state. Successive calls will always return values such that
176    /// `PartialOrder::less_equal(call1, call2)` hold true.
177    #[cfg(test)]
178    pub fn since(&self) -> Antichain<T> {
179        self.state
180            .read_lock(&self.metrics.locks.applier_read_cacheable, |state| {
181                state.since().clone()
182            })
183    }
184
185    /// Does a lease for the provided reader exist in the current state?
186    ///
187    /// This is useful when we encounter a condition that should only be possible when the lease
188    /// has expired, so we can distinguish between scary bugs and expected-but-unusual cases.
189    /// This returns whatever lease is present in the latest version of state - so to avoid false
190    /// positives, this should be checked only after the surprising condition has occurred.
191    pub fn reader_lease(&self, id: LeasedReaderId) -> Option<LeasedReaderState<T>> {
192        self.state
193            .read_lock(&self.metrics.locks.applier_read_cacheable, |state| {
194                state.state.collections.leased_readers.get(&id).cloned()
195            })
196    }
197
198    /// A point-in-time read of `seqno` from the current state.
199    ///
200    /// Due to sharing state with other handles, successive reads to this fn or any other may
201    /// see a different version of state, even if this Applier has not explicitly fetched and
202    /// updated to the latest state. Successive calls will always return values such that
203    /// `call1 <= call2` hold true.
204    pub fn seqno(&self) -> SeqNo {
205        self.state
206            .read_lock(&self.metrics.locks.applier_read_cacheable, |state| {
207                state.seqno
208            })
209    }
210
211    /// A point-in-time read of `seqno_since` from the current state.
212    ///
213    /// Due to sharing state with other handles, successive reads to this fn or any other may
214    /// see a different version of state, even if this Applier has not explicitly fetched and
215    /// updated to the latest state. Successive calls will always return values such that
216    /// `call1 <= call2` hold true.
217    pub fn seqno_since(&self) -> SeqNo {
218        self.state
219            .read_lock(&self.metrics.locks.applier_read_cacheable, |state| {
220                state.seqno_since()
221            })
222    }
223
224    /// A point-in-time read from the current state. (We declare a shard 'finalized' if it's
225    /// both become an unreadable tombstone and the state itself is has been emptied out.)
226    ///
227    /// Due to sharing state with other handles, successive reads to this fn or any other may
228    /// see a different version of state, even if this Applier has not explicitly fetched and
229    /// updated to the latest state. Once this fn returns true, it will always return true.
230    pub fn is_finalized(&self) -> bool {
231        self.state
232            .read_lock(&self.metrics.locks.applier_read_cacheable, |state| {
233                state.collections.is_finalized()
234            })
235    }
236
237    pub(crate) fn finalized_gc_step(
238        &self,
239        earliest_live: SeqNo,
240    ) -> Option<crate::internal::state::FinalizedGcStep> {
241        let max_versions = GC_MAX_VERSIONS.get(&self.cfg);
242        let remove_finalized_rollups = GC_REMOVE_FINALIZED_ROLLUPS.get(&self.cfg);
243        self.state
244            .read_lock(&self.metrics.locks.applier_read_noncacheable, |state| {
245                state.finalized_gc_step(earliest_live, max_versions, remove_finalized_rollups)
246            })
247    }
248
249    /// Whether the shard is a tombstone, which has no readers or writers.
250    pub(crate) fn is_tombstone(&self) -> bool {
251        self.state
252            .read_lock(&self.metrics.locks.applier_read_cacheable, |state| {
253                state.collections.is_tombstone()
254            })
255    }
256
257    /// See [crate::PersistClient::get_schema].
258    pub fn get_schema(&self, schema_id: SchemaId) -> Option<(K::Schema, V::Schema)> {
259        self.state
260            .read_lock(&self.metrics.locks.applier_read_cacheable, |state| {
261                let x = state.collections.schemas.get(&schema_id)?;
262                Some((K::decode_schema(&x.key), V::decode_schema(&x.val)))
263            })
264    }
265
266    /// See [crate::PersistClient::latest_schema].
267    pub fn latest_schema(&self) -> Option<(SchemaId, K::Schema, V::Schema)> {
268        self.state
269            .read_lock(&self.metrics.locks.applier_read_cacheable, |state| {
270                let (id, x) = state.collections.schemas.last_key_value()?;
271                Some((*id, K::decode_schema(&x.key), V::decode_schema(&x.val)))
272            })
273    }
274
275    /// Returns the ID of the given schema, if known at the current state.
276    pub fn find_schema(&self, key_schema: &K::Schema, val_schema: &V::Schema) -> Option<SchemaId> {
277        self.state
278            .read_lock(&self.metrics.locks.applier_read_cacheable, |state| {
279                // The common case is that the requested schema is a recent one, so as a minor
280                // optimization, do this search in reverse order.
281                let mut schemas = state.collections.schemas.iter().rev();
282                schemas
283                    .find(|(_, x)| {
284                        K::decode_schema(&x.key) == *key_schema
285                            && V::decode_schema(&x.val) == *val_schema
286                    })
287                    .map(|(id, _)| *id)
288            })
289    }
290
291    /// Returns whether the current's state `since` and `upper` are both empty.
292    ///
293    /// Due to sharing state with other handles, successive reads to this fn or any other may
294    /// see a different version of state, even if this Applier has not explicitly fetched and
295    /// updated to the latest state. Once this fn returns true, it will always return true.
296    pub fn check_since_upper_both_empty(&self) -> Result<(), InvalidUsage<T>> {
297        self.state
298            .read_lock(&self.metrics.locks.applier_read_cacheable, |state| {
299                if state.since().is_empty() && state.upper().is_empty() {
300                    Ok(())
301                } else {
302                    Err(InvalidUsage::FinalizationError {
303                        since: state.since().clone(),
304                        upper: state.upper().clone(),
305                    })
306                }
307            })
308    }
309
310    /// Returns all rollups that are <= the given `seqno`.
311    ///
312    /// Due to sharing state with other handles, successive reads to this fn or any other may
313    /// see a different version of state, even if this Applier has not explicitly fetched and
314    /// updated to the latest state.
315    pub fn rollups_lte_seqno(&self, seqno: SeqNo) -> Vec<(SeqNo, PartialRollupKey)> {
316        self.state
317            .read_lock(&self.metrics.locks.applier_read_noncacheable, |state| {
318                state
319                    .collections
320                    .rollups
321                    .range(..=seqno)
322                    .map(|(seqno, rollup)| (*seqno, rollup.key.clone()))
323                    .collect::<Vec<(SeqNo, PartialRollupKey)>>()
324            })
325    }
326
327    pub fn all_fueled_merge_reqs(&self) -> Vec<FueledMergeReq<T>> {
328        self.state
329            .read_lock(&self.metrics.locks.applier_read_noncacheable, |state| {
330                state
331                    .collections
332                    .trace
333                    .fueled_merge_reqs_before_ms(u64::MAX, None)
334                    .collect()
335            })
336    }
337
338    pub fn snapshot(&self, as_of: &Antichain<T>) -> Result<Vec<HollowBatch<T>>, SnapshotErr<T>> {
339        self.state
340            .read_lock(&self.metrics.locks.applier_read_noncacheable, |state| {
341                state.snapshot(as_of)
342            })
343    }
344
345    pub fn all_batches(&self) -> Vec<HollowBatch<T>> {
346        self.state
347            .read_lock(&self.metrics.locks.applier_read_noncacheable, |state| {
348                state.state.collections.trace.batches().cloned().collect()
349            })
350    }
351
352    pub fn verify_listen(&self, as_of: &Antichain<T>) -> Result<(), Since<T>> {
353        self.state
354            .read_lock(&self.metrics.locks.applier_read_noncacheable, |state| {
355                state.verify_listen(as_of)
356            })
357    }
358
359    pub fn next_listen_batch(&self, frontier: &Antichain<T>) -> Result<HollowBatch<T>, SeqNo> {
360        self.state
361            .read_lock(&self.metrics.locks.applier_read_noncacheable, |state| {
362                state.next_listen_batch(frontier)
363            })
364    }
365
366    pub async fn write_rollup_for_state(&self) -> Option<EncodedRollup> {
367        let state = self
368            .state
369            .read_lock(&self.metrics.locks.applier_read_noncacheable, |state| {
370                state.clone_for_rollup()
371            });
372
373        self.state_versions
374            .write_rollup_for_state(self.shard_metrics.as_ref(), state, &RollupId::new())
375            .await
376    }
377
378    pub async fn apply_unbatched_cmd<
379        R,
380        E,
381        WorkFn: FnMut(SeqNo, &PersistConfig, &mut StateCollections<T>) -> ControlFlow<E, R>,
382    >(
383        &self,
384        cmd: &CmdMetrics,
385        mut work_fn: WorkFn,
386    ) -> Result<(SeqNo, Result<R, E>, RoutineMaintenance), Indeterminate> {
387        loop {
388            cmd.started.inc();
389            let now = Instant::now();
390            let ret = Self::apply_unbatched_cmd_locked(
391                &self.state,
392                cmd,
393                &mut work_fn,
394                &self.cfg,
395                &self.metrics,
396                &self.shard_metrics,
397                &self.state_versions,
398            )
399            .await;
400            cmd.seconds.inc_by(now.elapsed().as_secs_f64());
401
402            match ret {
403                ApplyCmdResult::Committed((diff, new_state, res, maintenance)) => {
404                    cmd.succeeded.inc();
405                    self.shard_metrics.cmd_succeeded.inc();
406                    self.update_state(new_state);
407                    if PUBSUB_PUSH_DIFF_ENABLED.get(&self.cfg) {
408                        self.pubsub_sender.push_diff(&self.shard_id, &diff);
409                    }
410                    return Ok((diff.seqno, Ok(res), maintenance));
411                }
412                ApplyCmdResult::SkippedStateTransition((seqno, err, maintenance)) => {
413                    cmd.succeeded.inc();
414                    self.shard_metrics.cmd_succeeded.inc();
415                    return Ok((seqno, Err(err), maintenance));
416                }
417                ApplyCmdResult::Indeterminate(err) => {
418                    cmd.failed.inc();
419                    return Err(err);
420                }
421                ApplyCmdResult::ExpectationMismatch(seqno) => {
422                    cmd.cas_mismatch.inc();
423                    self.fetch_and_update_state(Some(seqno)).await;
424                }
425            }
426        }
427    }
428
429    // work_fn fails to compile without mut, false positive
430    #[allow(clippy::needless_pass_by_ref_mut)]
431    async fn apply_unbatched_cmd_locked<
432        R,
433        E,
434        WorkFn: FnMut(SeqNo, &PersistConfig, &mut StateCollections<T>) -> ControlFlow<E, R>,
435    >(
436        state: &LockingTypedState<K, V, T, D>,
437        cmd: &CmdMetrics,
438        work_fn: &mut WorkFn,
439        cfg: &PersistConfig,
440        metrics: &Metrics,
441        shard_metrics: &ShardMetrics,
442        state_versions: &StateVersions,
443    ) -> ApplyCmdResult<K, V, T, D, R, E> {
444        // While it's safe for more than one cmd to try and update the state, only one of those
445        // concurrent requests could actually succeed. This call will wait until previous requests
446        // have completed or timed out, and holding the resulting permit will delay other cmds until
447        // this attempt completes or times out.
448        let _permit_opt = state.lease_for_update().await;
449
450        let computed_next_state = state
451            .read_lock(&metrics.locks.applier_read_noncacheable, |state| {
452                Self::compute_next_state_locked(state, work_fn, metrics, cmd, cfg)
453            });
454
455        let next_state = match computed_next_state {
456            Ok(x) => x,
457            Err((seqno, err)) => {
458                return ApplyCmdResult::SkippedStateTransition((
459                    seqno,
460                    err,
461                    RoutineMaintenance::default(),
462                ));
463            }
464        };
465
466        let NextState {
467            diff,
468            state,
469            expiry_metrics,
470            garbage_collection,
471            write_rollup,
472            work_ret,
473        } = next_state;
474
475        {
476            let build_version = &cfg.build_version;
477            let state_version = &state.state.collections.version;
478            soft_assert_or_log!(
479                cfg::code_can_write_data(build_version, state_version),
480                "current version {build_version} does not support state format {state_version}"
481            );
482        }
483
484        // SUBTLE! Unlike the other consensus and blob uses, we can't
485        // automatically retry indeterminate ExternalErrors here. However,
486        // if the state change itself is _idempotent_, then we're free to
487        // retry even indeterminate errors. See
488        // [Self::apply_unbatched_idempotent_cmd].
489        let cas_res = state_versions
490            .try_compare_and_set_current(&cmd.name, shard_metrics, &state, &diff)
491            .await;
492
493        match cas_res {
494            Ok((CaSResult::Committed, diff)) => {
495                metrics
496                    .lease
497                    .timeout_read
498                    .inc_by(u64::cast_from(expiry_metrics.readers_expired));
499
500                metrics
501                    .state
502                    .writer_removed
503                    .inc_by(u64::cast_from(expiry_metrics.writers_expired));
504
505                if let Some(gc) = garbage_collection.as_ref() {
506                    debug!("Assigned gc request: {:?}", gc);
507                }
508
509                let maintenance = RoutineMaintenance {
510                    garbage_collection,
511                    write_rollup,
512                };
513
514                ApplyCmdResult::Committed((diff, state, work_ret, maintenance))
515            }
516            Ok((CaSResult::ExpectationMismatch, _diff)) => {
517                ApplyCmdResult::ExpectationMismatch(state.seqno())
518            }
519            Err(err) => ApplyCmdResult::Indeterminate(err),
520        }
521    }
522
523    fn compute_next_state_locked<
524        R,
525        E,
526        WorkFn: FnMut(SeqNo, &PersistConfig, &mut StateCollections<T>) -> ControlFlow<E, R>,
527    >(
528        state: &TypedState<K, V, T, D>,
529        work_fn: &mut WorkFn,
530        metrics: &Metrics,
531        cmd: &CmdMetrics,
532        cfg: &PersistConfig,
533    ) -> Result<NextState<K, V, T, D, R>, (SeqNo, E)> {
534        let is_write = cmd.name == metrics.cmds.compare_and_append.name;
535        let is_rollup = cmd.name == metrics.cmds.add_rollup.name;
536        let is_become_tombstone = cmd.name == metrics.cmds.become_tombstone.name;
537        let is_remove_rollups = cmd.name == metrics.cmds.remove_rollups.name;
538
539        let gc_config = GcConfig {
540            use_active_gc: GC_USE_ACTIVE_GC.get(cfg),
541            fallback_threshold_ms: u64::cast_from(GC_FALLBACK_THRESHOLD_MS.get(cfg)),
542            min_versions: GC_MIN_VERSIONS.get(cfg),
543            max_versions: GC_MAX_VERSIONS.get(cfg),
544            remove_finalized_rollups: GC_REMOVE_FINALIZED_ROLLUPS.get(cfg),
545        };
546
547        let use_active_rollup = ROLLUP_USE_ACTIVE_ROLLUP.get(cfg);
548        let rollup_threshold = ROLLUP_THRESHOLD.get(cfg);
549        let rollup_fallback_threshold_ms = u64::cast_from(ROLLUP_FALLBACK_THRESHOLD_MS.get(cfg));
550
551        let expected = state.seqno;
552        let was_tombstone_before = state.collections.is_tombstone();
553
554        let (work_ret, mut new_state) = match state.clone_apply(cfg, work_fn) {
555            Continue(x) => x,
556            Break(err) => {
557                return Err((expected, err));
558            }
559        };
560        let expiry_metrics = new_state.expire_at((cfg.now)());
561        new_state.state.collections.trace.roundtrip_structure = true;
562
563        // Sanity check that all state transitions have special case for
564        // being a tombstone. The ones that do will return a Break and
565        // return out of this method above. The exceptions are adding the
566        // tombstone's final rollup and removing old rollups once finalized.
567        //
568        // NOTE: Even better would be to write the rollup in the
569        // tombstone transition so it's a single terminal state
570        // transition, but it'll be tricky to get right.
571        let is_finalized_removal = is_remove_rollups && new_state.collections.is_finalized();
572        if was_tombstone_before && !(is_rollup || is_become_tombstone || is_finalized_removal) {
573            panic!(
574                "cmd {} unexpectedly tried to commit a new state on a tombstone: {:?}",
575                cmd.name, state
576            );
577        }
578
579        // Every extra commit on a finalized shard triggers another rollup,
580        // which GC keeps.
581        if was_tombstone_before && is_remove_rollups {
582            soft_assert_or_log!(
583                new_state.collections.rollups.len() < state.collections.rollups.len(),
584                "remove_rollups committed on a tombstone without removing a rollup"
585            );
586        }
587
588        let now = (cfg.now)();
589        let write_rollup = new_state.need_rollup(
590            rollup_threshold,
591            use_active_rollup,
592            rollup_fallback_threshold_ms,
593            now,
594        );
595
596        if let Some(write_rollup_seqno) = write_rollup {
597            if new_state.collections.is_finalized() {
598                metrics.state.finalized_rollup_assigned.inc();
599            }
600            if use_active_rollup {
601                new_state.collections.active_rollup = Some(ActiveRollup {
602                    seqno: write_rollup_seqno,
603                    start_ms: now,
604                });
605            }
606        }
607
608        // Find out if this command has been selected to perform gc, so
609        // that it will fire off a background request to the
610        // GarbageCollector to delete eligible blobs and truncate the
611        // state history. This is dependant both on `maybe_gc` returning
612        // Some _and_ on this state being successfully compare_and_set.
613        let garbage_collection = new_state.maybe_gc(is_write, now, gc_config);
614
615        if let Some(gc) = garbage_collection.as_ref() {
616            if gc_config.use_active_gc {
617                new_state.collections.active_gc = Some(ActiveGc {
618                    seqno: gc.new_seqno_since,
619                    start_ms: now,
620                });
621            }
622        }
623
624        // Make sure `new_state` is not modified after this point!
625        // The new state and the diff must be consistent with each other for correctness.
626        let diff = StateDiff::from_diff(&state.state, &new_state);
627        // Sanity check that our diff logic roundtrips and adds back up
628        // correctly.
629        #[cfg(any(test, debug_assertions))]
630        {
631            if let Err(err) = StateDiff::validate_roundtrip(metrics, state, &diff, &new_state) {
632                panic!("validate_roundtrips failed: {}", err);
633            }
634        }
635
636        assert_eq!(
637            expected.next(),
638            new_state.seqno(),
639            "successive states should have successive seqnos"
640        );
641        Ok(NextState {
642            diff,
643            state: new_state,
644            expiry_metrics,
645            garbage_collection,
646            write_rollup,
647            work_ret,
648        })
649    }
650
651    pub fn update_state(&self, new_state: TypedState<K, V, T, D>) {
652        let (seqno_before, seqno_after) =
653            self.state
654                .write_lock(&self.metrics.locks.applier_write, |state| {
655                    let seqno_before = state.seqno;
656                    if seqno_before < new_state.seqno {
657                        *state = new_state;
658                    }
659                    let seqno_after = state.seqno;
660                    (seqno_before, seqno_after)
661                });
662
663        assert!(
664            seqno_before <= seqno_after,
665            "state seqno regressed: {} vs {}",
666            seqno_before,
667            seqno_after
668        );
669    }
670
671    /// Fetches and updates to the latest state. Uses an optional hint to early-out if
672    /// any more recent version of state is observed (e.g. updated by another handle),
673    /// without making any calls to Consensus or Blob.
674    pub async fn fetch_and_update_state(&self, seqno_hint: Option<SeqNo>) {
675        let current_seqno = self.seqno();
676        let seqno_before = match seqno_hint {
677            None => current_seqno,
678            Some(hint) => {
679                // state is already more recent than our hint due to
680                // advancement by another handle to the same shard.
681                if hint < current_seqno {
682                    self.metrics.state.update_state_noop_path.inc();
683                    return;
684                }
685                current_seqno
686            }
687        };
688
689        let diffs_to_current = self
690            .state_versions
691            .fetch_all_live_diffs_gt_seqno::<K, V, T, D>(&self.shard_id, seqno_before)
692            .await;
693
694        // no new diffs past our current seqno, nothing to do
695        if diffs_to_current.is_empty() {
696            self.metrics.state.update_state_empty_path.inc();
697            return;
698        }
699
700        let new_seqno = self
701            .state
702            .write_lock(&self.metrics.locks.applier_write, |state| {
703                state.apply_encoded_diffs(&self.cfg, &self.metrics, &diffs_to_current);
704                state.seqno
705            });
706
707        assert!(
708            seqno_before <= new_seqno,
709            "state seqno regressed: {} vs {}",
710            seqno_before,
711            new_seqno
712        );
713
714        // whether the seqno advanced from diffs and/or because another handle
715        // already updated it, we can assume it is now up-to-date
716        if seqno_before < new_seqno {
717            self.metrics.state.update_state_fast_path.inc();
718            return;
719        }
720
721        // our state is so old there aren't any diffs we can use to
722        // catch up directly. fall back to fully refetching state.
723        // we can reuse the recent diffs we already have as a hint.
724        let new_state = self
725            .state_versions
726            .fetch_current_state(&self.shard_id, diffs_to_current)
727            .await
728            .check_codecs::<K, V, D>(&self.shard_id)
729            .expect("shard codecs should not change");
730
731        let new_seqno = self
732            .state
733            .write_lock(&self.metrics.locks.applier_write, |state| {
734                if state.seqno < new_state.seqno {
735                    *state = new_state;
736                }
737                state.seqno
738            });
739
740        self.metrics.state.update_state_slow_path.inc();
741        assert!(
742            seqno_before <= new_seqno,
743            "state seqno regressed: {} vs {}",
744            seqno_before,
745            new_seqno
746        );
747    }
748}
749
750enum ApplyCmdResult<K, V, T, D, R, E> {
751    Committed((VersionedData, TypedState<K, V, T, D>, R, RoutineMaintenance)),
752    SkippedStateTransition((SeqNo, E, RoutineMaintenance)),
753    Indeterminate(Indeterminate),
754    ExpectationMismatch(SeqNo),
755}
756
757struct NextState<K, V, T, D, R> {
758    diff: StateDiff<T>,
759    state: TypedState<K, V, T, D>,
760    expiry_metrics: ExpiryMetrics,
761    write_rollup: Option<SeqNo>,
762    garbage_collection: Option<GcReq>,
763    work_ret: R,
764}