1use 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#[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 state: Arc<LockingTypedState<K, V, T, D>>,
71}
72
73impl<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 pub fn watch(&self) -> StateWatch<K, V, T, D> {
130 StateWatch::new(Arc::clone(&self.state), Arc::clone(&self.metrics))
131 }
132
133 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 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 #[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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 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 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 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 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 let diff = StateDiff::from_diff(&state.state, &new_state);
627 #[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 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 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 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 if seqno_before < new_seqno {
717 self.metrics.state.update_state_fast_path.inc();
718 return;
719 }
720
721 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}