1use std::cell::RefCell;
11use std::cmp::Reverse;
12use std::convert::AsRef;
13use std::fmt::Debug;
14use std::hash::{Hash, Hasher};
15use std::path::PathBuf;
16use std::sync::Arc;
17
18use differential_dataflow::{AsCollection, VecCollection};
19use futures::StreamExt;
20#[cfg(feature = "fuzzing")]
21use indexmap::map::Entry;
22use itertools::Itertools;
23use mz_ore::error::ErrorExt;
24use mz_repr::{Datum, DatumVec, Diff, GlobalId, Row};
25use mz_rocksdb::ValueIterator;
26use mz_sql_server_util::cdc::Lsn;
27use mz_storage_types::configuration::StorageConfiguration;
28use mz_storage_types::dyncfgs;
29use mz_storage_types::errors::{DataflowError, EnvelopeError, UpsertError};
30use mz_storage_types::sources::MzOffset;
31use mz_storage_types::sources::envelope::UpsertEnvelope;
32use mz_storage_types::sources::kafka::{KafkaTimestamp, RangeBound};
33use mz_storage_types::sources::mysql::GtidPartition;
34use mz_timely_util::builder_async::{
35 AsyncOutputHandle, ButtonHandle, Event as AsyncEvent, OperatorBuilder as AsyncOperatorBuilder,
36 PressOnDropButton,
37};
38use serde::{Deserialize, Serialize};
39use sha2::{Digest, Sha256};
40use timely::dataflow::operators::{Capability, Operator};
41use timely::dataflow::{Scope, StreamVec};
42use timely::order::{PartialOrder, TotalOrder};
43use timely::progress::timestamp::Refines;
44use timely::progress::{Antichain, Timestamp};
45
46use crate::healthcheck::HealthStatusUpdate;
47use crate::metrics::upsert::UpsertBackpressureMetrics;
48use crate::storage_state::StorageInstanceContext;
49use crate::{upsert_continual_feedback, upsert_continual_feedback_v2};
50use types::{BincodeOpts, StateValue, consolidating_merge_function, upsert_bincode_opts};
51#[cfg(feature = "fuzzing")]
52use types::{UpsertState, UpsertStateBackend};
53
54#[cfg(any(test, feature = "fuzzing"))]
55pub mod memory;
56pub(crate) mod rocksdb;
57pub(crate) mod types;
59
60pub type UpsertValue = Result<Row, Box<UpsertError>>;
61
62#[derive(
63 Copy,
64 Clone,
65 Hash,
66 PartialEq,
67 Eq,
68 PartialOrd,
69 Ord,
70 Serialize,
71 Deserialize,
72 bytemuck::AnyBitPattern,
73 bytemuck::NoUninit
74)]
75#[repr(transparent)]
76pub struct UpsertKey([u8; 32]);
77
78impl columnation::Columnation for UpsertKey {
79 type InnerRegion = columnation::CopyRegion<UpsertKey>;
80}
81
82mod columnar_upsert_key {
94 use super::UpsertKey;
95 use columnar::Columnar;
96 use mz_ore::cast::CastFrom;
97 use std::ops::Range;
98
99 #[derive(Clone, Copy, Default, Debug)]
101 pub struct UpsertKeys<T>(T);
102 impl<D, T: columnar::Push<D>> columnar::Push<D> for UpsertKeys<T> {
103 #[inline(always)]
104 fn push(&mut self, item: D) {
105 self.0.push(item)
106 }
107 }
108 impl<T: columnar::Clear> columnar::Clear for UpsertKeys<T> {
109 #[inline(always)]
110 fn clear(&mut self) {
111 self.0.clear()
112 }
113 }
114 impl<T: columnar::Len> columnar::Len for UpsertKeys<T> {
115 #[inline(always)]
116 fn len(&self) -> usize {
117 self.0.len()
118 }
119 }
120 impl<'a> columnar::Index for UpsertKeys<&'a [UpsertKey]> {
121 type Ref = &'a UpsertKey;
122
123 #[inline(always)]
124 fn get(&self, index: usize) -> Self::Ref {
125 &self.0[index]
126 }
127 }
128
129 impl Columnar for UpsertKey {
130 #[inline(always)]
131 fn into_owned<'a>(other: columnar::Ref<'a, Self>) -> Self {
132 *other
133 }
134 type Container = UpsertKeys<Vec<UpsertKey>>;
135 #[inline(always)]
136 fn reborrow<'b, 'a: 'b>(thing: columnar::Ref<'a, Self>) -> columnar::Ref<'b, Self>
137 where
138 Self: 'a,
139 {
140 thing
141 }
142 }
143
144 impl columnar::Borrow for UpsertKeys<Vec<UpsertKey>> {
145 type Ref<'a> = &'a UpsertKey;
146 type Borrowed<'a>
147 = UpsertKeys<&'a [UpsertKey]>
148 where
149 Self: 'a;
150 #[inline(always)]
151 fn borrow<'a>(&'a self) -> Self::Borrowed<'a> {
152 UpsertKeys(self.0.as_slice())
153 }
154 #[inline(always)]
155 fn reborrow<'b, 'a: 'b>(item: Self::Borrowed<'a>) -> Self::Borrowed<'b>
156 where
157 Self: 'a,
158 {
159 UpsertKeys(item.0)
160 }
161 #[inline(always)]
162 fn reborrow_ref<'b, 'a: 'b>(item: Self::Ref<'a>) -> Self::Ref<'b>
163 where
164 Self: 'a,
165 {
166 item
167 }
168 }
169
170 impl columnar::Container for UpsertKeys<Vec<UpsertKey>> {
171 #[inline(always)]
172 fn extend_from_self(&mut self, other: Self::Borrowed<'_>, range: Range<usize>) {
173 self.0.extend_from_self(other.0, range)
174 }
175 #[inline(always)]
176 fn reserve_for<'a, I>(&mut self, selves: I)
177 where
178 Self: 'a,
179 I: Iterator<Item = Self::Borrowed<'a>> + Clone,
180 {
181 self.0.reserve_for(selves.map(|s| s.0));
182 }
183 }
184
185 impl<'a> columnar::AsBytes<'a> for UpsertKeys<&'a [UpsertKey]> {
186 const SLICE_COUNT: usize = 1;
187 #[inline(always)]
188 fn get_byte_slice(&self, index: usize) -> (u64, &'a [u8]) {
189 mz_ore::soft_assert_no_log!(index < Self::SLICE_COUNT);
190 (
191 u64::cast_from(align_of::<UpsertKey>()),
192 bytemuck::cast_slice(self.0),
193 )
194 }
195 #[inline(always)]
196 fn as_bytes(&self) -> impl Iterator<Item = (u64, &'a [u8])> {
197 std::iter::once((
198 u64::cast_from(align_of::<UpsertKey>()),
199 bytemuck::cast_slice(self.0),
200 ))
201 }
202 }
203 impl<'a> columnar::FromBytes<'a> for UpsertKeys<&'a [UpsertKey]> {
204 const SLICE_COUNT: usize = 1;
205 #[inline(always)]
206 fn from_bytes(bytes: &mut impl Iterator<Item = &'a [u8]>) -> Self {
207 UpsertKeys(bytemuck::cast_slice(
208 bytes.next().expect("Iterator exhausted prematurely"),
209 ))
210 }
211 }
212}
213
214pub trait UpsertSourceTime
230where
231 for<'a> columnar::Ref<'a, Self::Order>: Ord,
232{
233 type Order: mz_timely_util::columnar::chunk::PoolColumnar
236 + Clone
237 + Default
238 + Ord
239 + Send
240 + Sync
241 + 'static;
242 fn upsert_order(&self) -> Self::Order;
244}
245
246impl UpsertSourceTime for KafkaTimestamp {
247 type Order = (i64, u64);
253 fn upsert_order(&self) -> (i64, u64) {
254 let partition = match self.interval().lower {
255 RangeBound::NegInfinity => i64::MIN,
256 RangeBound::Elem(p, _) => i64::from(p),
257 RangeBound::PosInfinity => i64::MAX,
258 };
259 (partition, self.timestamp().offset)
260 }
261}
262
263impl UpsertSourceTime for MzOffset {
269 type Order = u64;
270 fn upsert_order(&self) -> u64 {
271 self.offset
272 }
273}
274
275macro_rules! upsert_source_time_unit {
282 ($($ty:ty),+ $(,)?) => {$(
283 impl UpsertSourceTime for $ty {
284 type Order = ();
285 fn upsert_order(&self) {
286 unreachable!(
287 "upsert source stash is not rendered for this source, but \
288 {} reached the projection",
289 std::any::type_name::<Self>(),
290 )
291 }
292 }
293 )+};
294}
295upsert_source_time_unit!(GtidPartition, Lsn);
296
297pub mod upsert_stash_spill {
305 pub fn set_enabled(enabled: bool) {
307 mz_timely_util::columnar::chunk::set_storage_spill_enabled(enabled);
308 }
309}
310
311impl Debug for UpsertKey {
312 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313 write!(f, "0x")?;
314 for byte in self.0 {
315 write!(f, "{:02x}", byte)?;
316 }
317 Ok(())
318 }
319}
320
321impl AsRef<[u8]> for UpsertKey {
322 #[inline(always)]
323 fn as_ref(&self) -> &[u8] {
327 &self.0
328 }
329}
330
331impl From<&[u8]> for UpsertKey {
332 fn from(bytes: &[u8]) -> Self {
333 UpsertKey(bytes.try_into().expect("invalid key length"))
334 }
335}
336
337type KeyHash = Sha256;
342
343impl UpsertKey {
344 pub fn from_key(key: Result<&Row, &UpsertError>) -> Self {
345 Self::from_iter(key.map(|r| r.iter()))
346 }
347
348 pub fn from_value(value: Result<&Row, &UpsertError>, key_indices: &[usize]) -> Self {
349 thread_local! {
350 static VALUE_DATUMS: RefCell<DatumVec> = RefCell::new(DatumVec::new());
352 }
353 VALUE_DATUMS.with(|value_datums| {
354 let mut value_datums = value_datums.borrow_mut();
355 let value = value.map(|v| value_datums.borrow_with(v));
356 let key = match value {
357 Ok(ref datums) => Ok(key_indices.iter().map(|&idx| datums[idx])),
358 Err(err) => Err(err),
359 };
360 Self::from_iter(key)
361 })
362 }
363
364 pub fn from_iter<'a, 'b>(
365 key: Result<impl Iterator<Item = Datum<'a>> + 'b, &UpsertError>,
366 ) -> Self {
367 thread_local! {
368 static KEY_DATUMS: RefCell<DatumVec> = RefCell::new(DatumVec::new());
370 }
371 KEY_DATUMS.with(|key_datums| {
372 let mut key_datums = key_datums.borrow_mut();
373 let mut key_datums = key_datums.borrow();
376 let key: Result<&[Datum], Datum> = match key {
377 Ok(key) => {
378 for datum in key {
379 key_datums.push(datum);
380 }
381 Ok(&*key_datums)
382 }
383 Err(UpsertError::Value(err)) => {
384 key_datums.extend(err.for_key.iter());
385 Ok(&*key_datums)
386 }
387 Err(UpsertError::KeyDecode(err)) => Err(Datum::Bytes(&err.raw)),
388 Err(UpsertError::NullKey(_)) => Err(Datum::Null),
389 };
390 let mut hasher = DigestHasher(KeyHash::new());
391 key.hash(&mut hasher);
392 Self(hasher.0.finalize().into())
393 })
394 }
395}
396
397struct DigestHasher<H: Digest>(H);
398
399impl<H: Digest> Hasher for DigestHasher<H> {
400 fn write(&mut self, bytes: &[u8]) {
401 self.0.update(bytes);
402 }
403
404 fn finish(&self) -> u64 {
405 panic!("digest wrapper used to produce a hash");
406 }
407}
408
409use std::convert::Infallible;
410use timely::container::CapacityContainerBuilder;
411use timely::dataflow::channels::pact::Pipeline;
412
413#[cfg(feature = "fuzzing")]
414use self::types::ValueMetadata;
415
416pub fn rehydration_finished<'scope, T: Timestamp>(
420 scope: Scope<'scope, T>,
421 source_config: &crate::source::RawSourceCreationConfig,
422 token: impl std::any::Any + 'static,
424 resume_upper: Antichain<T>,
425 input: StreamVec<'scope, T, Infallible>,
426) {
427 let worker_id = source_config.worker_id;
428 let id = source_config.id;
429 let mut builder = AsyncOperatorBuilder::new(format!("rehydration_finished({id}"), scope);
430 let mut input = builder.new_disconnected_input(input, Pipeline);
431
432 builder.build(move |_capabilities| async move {
433 let mut input_upper = Antichain::from_elem(Timestamp::minimum());
434 while !PartialOrder::less_equal(&resume_upper, &input_upper) {
436 let Some(event) = input.next().await else {
437 break;
438 };
439 if let AsyncEvent::Progress(upper) = event {
440 input_upper = upper;
441 }
442 }
443 tracing::info!(
444 %worker_id,
445 source_id = %id,
446 "upsert source has downgraded past the resume upper ({resume_upper:?}) across all workers",
447 );
448 drop(token);
449 });
450}
451
452pub(crate) fn key_persist_feedback<'scope, T>(
458 ok: VecCollection<'scope, T, Row, Diff>,
459 err: VecCollection<'scope, T, DataflowError, Diff>,
460 key_indices: Vec<usize>,
461) -> VecCollection<'scope, T, (UpsertKey, UpsertValue), Diff>
462where
463 T: Timestamp,
464{
465 let keyed_ok = {
466 let key_indices = key_indices.clone();
467 ok.map(move |row| {
468 let key = UpsertKey::from_value(Ok(&row), &key_indices);
469 (key, Ok(row))
470 })
471 };
472 let keyed_err = err.flat_map(move |err| {
473 let err = match err {
474 DataflowError::EnvelopeError(err) => match *err {
475 EnvelopeError::Upsert(err) => Box::new(err),
476 EnvelopeError::Flat(_) => return None,
477 },
478 _ => return None,
479 };
480 let key = UpsertKey::from_value(Err(&err), &key_indices);
481 Some((key, Err(err)))
482 });
483 keyed_ok.concat(keyed_err)
484}
485
486pub(crate) fn upsert<'scope, T, FromTime>(
492 input: VecCollection<'scope, T, (UpsertKey, Option<UpsertValue>, FromTime), Diff>,
493 upsert_envelope: UpsertEnvelope,
494 resume_upper: Antichain<T>,
495 previous_ok: VecCollection<'scope, T, Row, Diff>,
496 previous_err: VecCollection<'scope, T, DataflowError, Diff>,
497 previous_token: Option<Vec<PressOnDropButton>>,
498 source_config: crate::source::SourceExportCreationConfig,
499 instance_context: &StorageInstanceContext,
500 storage_configuration: &StorageConfiguration,
501 dataflow_paramters: &crate::internal_control::DataflowParameters,
502 backpressure_metrics: Option<UpsertBackpressureMetrics>,
503) -> (
504 VecCollection<'scope, T, Result<Row, DataflowError>, Diff>,
505 StreamVec<'scope, T, (Option<GlobalId>, HealthStatusUpdate)>,
506 StreamVec<'scope, T, Infallible>,
507 PressOnDropButton,
508)
509where
510 T: Timestamp + TotalOrder + Sync,
511 T: Refines<mz_repr::Timestamp> + TotalOrder + Sync,
512 FromTime: Timestamp + Clone + Sync,
513{
514 let upsert_metrics = source_config.metrics.get_upsert_metrics(
515 source_config.id,
516 source_config.worker_id,
517 backpressure_metrics,
518 );
519
520 let rocksdb_cleanup_tries =
521 dyncfgs::STORAGE_ROCKSDB_CLEANUP_TRIES.get(storage_configuration.config_set());
522
523 let prevent_snapshot_buffering =
526 dyncfgs::STORAGE_UPSERT_PREVENT_SNAPSHOT_BUFFERING.get(storage_configuration.config_set());
527 let snapshot_buffering_max = dyncfgs::STORAGE_UPSERT_MAX_SNAPSHOT_BATCH_BUFFERING
529 .get(storage_configuration.config_set());
530
531 let rocksdb_use_native_merge_operator =
534 dyncfgs::STORAGE_ROCKSDB_USE_MERGE_OPERATOR.get(storage_configuration.config_set());
535
536 let upsert_config = UpsertConfig {
537 shrink_upsert_unused_buffers_by_ratio: storage_configuration
538 .parameters
539 .shrink_upsert_unused_buffers_by_ratio,
540 };
541
542 let thin_input = upsert_thinning(input);
543
544 let tuning = dataflow_paramters.upsert_rocksdb_tuning_config.clone();
545
546 let rocksdb_dir = instance_context
551 .scratch_directory
552 .clone()
553 .unwrap_or_else(|| PathBuf::from("/tmp"))
554 .join("storage")
555 .join("upsert")
556 .join(source_config.id.to_string())
557 .join(source_config.worker_id.to_string());
558
559 tracing::info!(
560 worker_id = %source_config.worker_id,
561 source_id = %source_config.id,
562 ?rocksdb_dir,
563 ?tuning,
564 ?rocksdb_use_native_merge_operator,
565 "rendering upsert source"
566 );
567
568 let rocksdb_shared_metrics = Arc::clone(&upsert_metrics.rocksdb_shared);
569 let rocksdb_instance_metrics = Arc::clone(&upsert_metrics.rocksdb_instance_metrics);
570
571 let env = instance_context
572 .rocksdb_env()
573 .expect("failed to create rocksdb env");
574
575 let rocksdb_init_fn = move || async move {
577 let merge_operator = if rocksdb_use_native_merge_operator {
578 Some((
579 "upsert_state_snapshot_merge_v1".to_string(),
580 |a: &[u8], b: ValueIterator<BincodeOpts, StateValue<T, FromTime>>| {
581 consolidating_merge_function::<T, FromTime>(a.into(), b)
582 },
583 ))
584 } else {
585 None
586 };
587 rocksdb::RocksDB::new(
588 mz_rocksdb::RocksDBInstance::new(
589 &rocksdb_dir,
590 mz_rocksdb::InstanceOptions::new(
591 env,
592 rocksdb_cleanup_tries,
593 merge_operator,
594 upsert_bincode_opts(),
597 ),
598 tuning,
599 rocksdb_shared_metrics,
600 rocksdb_instance_metrics,
601 )
602 .unwrap(),
603 )
604 };
605
606 upsert_continual_feedback::upsert_inner(
607 thin_input,
608 upsert_envelope.key_indices,
609 resume_upper,
610 previous_ok,
611 previous_err,
612 previous_token,
613 upsert_metrics,
614 source_config,
615 rocksdb_init_fn,
616 upsert_config,
617 prevent_snapshot_buffering,
618 snapshot_buffering_max,
619 )
620}
621
622pub(crate) fn upsert_v2<'scope, T, FromTime>(
629 input: VecCollection<'scope, T, (UpsertKey, Option<UpsertValue>, FromTime), Diff>,
630 upsert_envelope: UpsertEnvelope,
631 resume_upper: Antichain<T>,
632 previous_ok: VecCollection<'scope, T, Row, Diff>,
633 previous_err: VecCollection<'scope, T, DataflowError, Diff>,
634 previous_token: Option<Vec<PressOnDropButton>>,
635 source_config: crate::source::SourceExportCreationConfig,
636 backpressure_metrics: Option<UpsertBackpressureMetrics>,
637 stats_shutdown: ButtonHandle,
638) -> (
639 VecCollection<'scope, T, Result<Row, DataflowError>, Diff>,
640 StreamVec<'scope, T, (Option<GlobalId>, HealthStatusUpdate)>,
641 StreamVec<'scope, T, Infallible>,
642 PressOnDropButton,
643)
644where
645 T: Timestamp + TotalOrder + Sync,
646 T: Refines<mz_repr::Timestamp> + differential_dataflow::lattice::Lattice,
647 T: columnation::Columnation,
648 T: mz_timely_util::columnar::chunk::PoolColumnar + Default,
649 for<'a> columnar::Ref<'a, T>: Copy + Ord,
650 FromTime: Timestamp + Clone + Sync,
651 FromTime: UpsertSourceTime,
652{
653 let upsert_metrics = source_config.metrics.get_upsert_metrics(
654 source_config.id,
655 source_config.worker_id,
656 backpressure_metrics,
657 );
658
659 let thin_input = upsert_thinning(input);
660
661 tracing::info!(
662 worker_id = %source_config.worker_id,
663 source_id = %source_config.id,
664 "rendering upsert source (btreemap backend)"
665 );
666
667 upsert_continual_feedback_v2::upsert_inner(
668 thin_input,
669 upsert_envelope.key_indices,
670 resume_upper,
671 previous_ok,
672 previous_err,
673 previous_token,
674 upsert_metrics,
675 source_config,
676 stats_shutdown,
677 )
678}
679
680fn upsert_thinning<'scope, T, K, V, FromTime>(
685 input: VecCollection<'scope, T, (K, V, FromTime), Diff>,
686) -> VecCollection<'scope, T, (K, V, FromTime), Diff>
687where
688 T: Timestamp + TotalOrder,
689 K: timely::ExchangeData + Clone + Eq + Ord,
690 V: timely::ExchangeData + Clone,
691 FromTime: Timestamp,
692{
693 input
694 .inner
695 .unary(Pipeline, "UpsertThinning", |_, _| {
696 let mut capability: Option<Capability<T>> = None;
698 let mut updates = Vec::new();
700 move |input, output| {
701 input.for_each(|cap, data| {
702 assert!(
703 data.iter().all(|(_, _, diff)| diff.is_positive()),
704 "invalid upsert input"
705 );
706 updates.append(data);
707 let cap = cap
710 .retain_least(0)
711 .expect("message stamped with no capabilities");
712 match capability.as_mut() {
713 Some(capability) => {
714 if cap.time() <= capability.time() {
715 *capability = cap;
716 }
717 }
718 None => capability = Some(cap),
719 }
720 });
721 if let Some(capability) = capability.take() {
722 updates.sort_unstable_by(|a, b| {
725 let ((key1, _, from_time1), time1, _) = a;
726 let ((key2, _, from_time2), time2, _) = b;
727 Ord::cmp(
728 &(key1, time1, Reverse(from_time1)),
729 &(key2, time2, Reverse(from_time2)),
730 )
731 });
732 let mut session = output.session(&capability);
733 session.give_iterator(updates.drain(..).dedup_by(|a, b| {
734 let ((key1, _, _), time1, _) = a;
735 let ((key2, _, _), time2, _) = b;
736 (key1, time1) == (key2, time2)
737 }))
738 }
739 }
740 })
741 .as_collection()
742}
743
744#[cfg(feature = "fuzzing")]
749async fn drain_staged_input<S, T, FromTime, E>(
750 stash: &mut Vec<(T, UpsertKey, Reverse<FromTime>, Option<UpsertValue>)>,
751 commands_state: &mut indexmap::IndexMap<UpsertKey, types::UpsertValueAndSize<T, FromTime>>,
752 output_updates: &mut Vec<(UpsertValue, T, Diff)>,
753 multi_get_scratch: &mut Vec<UpsertKey>,
754 upper: &Antichain<T>,
755 error_emitter: &mut E,
756 state: &mut UpsertState<'_, S, T, FromTime>,
757 source_config: &crate::source::SourceExportCreationConfig,
758) where
759 S: UpsertStateBackend<T, FromTime>,
760 T: PartialOrder + Ord + Clone + Send + Sync + Serialize + Debug + 'static,
761 FromTime: timely::ExchangeData + Clone + Ord + Sync,
762 E: UpsertErrorEmitter<T>,
763{
764 stash.sort_unstable();
765
766 let idx = stash.partition_point(|(ts, _, _, _)| !upper.less_equal(ts));
768
769 tracing::trace!(?upper, updates = idx, "draining stash in upsert");
770
771 commands_state.clear();
774 for (_, key, _, _) in stash.iter().take(idx) {
775 commands_state.entry(*key).or_default();
776 }
777
778 multi_get_scratch.clear();
781 multi_get_scratch.extend(commands_state.iter().map(|(k, _)| *k));
782 match state
783 .multi_get(multi_get_scratch.drain(..), commands_state.values_mut())
784 .await
785 {
786 Ok(_) => {}
787 Err(e) => {
788 error_emitter
789 .emit("Failed to fetch records from state".to_string(), e)
790 .await;
791 }
792 }
793
794 let mut commands = stash.drain(..idx).dedup_by(|a, b| {
798 let ((a_ts, a_key, _, _), (b_ts, b_key, _, _)) = (a, b);
799 a_ts == b_ts && a_key == b_key
800 });
801
802 let bincode_opts = types::upsert_bincode_opts();
803 while let Some((ts, key, from_time, value)) = commands.next() {
816 let mut command_state = if let Entry::Occupied(command_state) = commands_state.entry(key) {
817 command_state
818 } else {
819 panic!("key missing from commands_state");
820 };
821
822 let existing_value = &mut command_state.get_mut().value;
823
824 if let Some(cs) = existing_value.as_mut() {
825 cs.ensure_decoded(bincode_opts, source_config.id, Some(&key));
826 }
827
828 let existing_order = existing_value
832 .as_ref()
833 .and_then(|cs| cs.provisional_order(&ts));
834 if existing_order >= Some(&from_time.0) {
835 continue;
840 }
841
842 match value {
843 Some(value) => {
844 if let Some(old_value) =
845 existing_value.replace(StateValue::finalized_value(value.clone()))
846 {
847 if let Some(old_value) = old_value.into_decoded().finalized {
848 output_updates.push((old_value, ts.clone(), Diff::MINUS_ONE));
849 }
850 }
851 output_updates.push((value, ts, Diff::ONE));
852 }
853 None => {
854 if let Some(old_value) = existing_value.take() {
855 if let Some(old_value) = old_value.into_decoded().finalized {
856 output_updates.push((old_value, ts, Diff::MINUS_ONE));
857 }
858 }
859
860 *existing_value = Some(StateValue::tombstone());
862 }
863 }
864 }
865
866 match state
867 .multi_put(
868 true, commands_state.drain(..).map(|(k, cv)| {
870 (
871 k,
872 types::PutValue {
873 value: cv.value.map(|cv| cv.into_decoded()),
874 previous_value_metadata: cv.metadata.map(|v| ValueMetadata {
875 size: v.size.try_into().expect("less than i64 size"),
876 is_tombstone: v.is_tombstone,
877 }),
878 },
879 )
880 }),
881 )
882 .await
883 {
884 Ok(_) => {}
885 Err(e) => {
886 error_emitter
887 .emit("Failed to update records in state".to_string(), e)
888 .await;
889 }
890 }
891}
892
893#[cfg(feature = "fuzzing")]
897struct PanicErrorEmitter;
898
899#[cfg(feature = "fuzzing")]
900#[async_trait::async_trait(?Send)]
901impl<T> UpsertErrorEmitter<T> for PanicErrorEmitter {
902 async fn emit(&mut self, context: String, e: anyhow::Error) {
903 panic!("unexpected upsert state error during fuzzing: {context}: {e}");
904 }
905}
906
907#[cfg(feature = "fuzzing")]
914pub async fn fuzz_drain_staged_input(
915 parts: &types::FuzzUpsertParts,
916 source_config: &crate::source::SourceExportCreationConfig,
917 commands: Vec<(u64, UpsertKey, u64, Option<UpsertValue>)>,
918 drain_to: u64,
919 all_keys: &[UpsertKey],
920) -> (Vec<(UpsertValue, u64, Diff)>, Vec<Option<UpsertValue>>) {
921 let mut state = parts.state();
922 let mut stash: Vec<(u64, UpsertKey, Reverse<u64>, Option<UpsertValue>)> = commands
923 .into_iter()
924 .map(|(ts, key, order, value)| (ts, key, Reverse(order), value))
925 .collect();
926 let mut commands_state = indexmap::IndexMap::new();
927 let mut output = Vec::new();
928 let mut multi_get_scratch = Vec::new();
929 let mut emitter = PanicErrorEmitter;
930
931 drain_staged_input(
932 &mut stash,
933 &mut commands_state,
934 &mut output,
935 &mut multi_get_scratch,
936 &Antichain::from_elem(drain_to),
937 &mut emitter,
938 &mut state,
939 source_config,
940 )
941 .await;
942
943 let bincode_opts = types::upsert_bincode_opts();
944 let mut results = vec![types::UpsertValueAndSize::default(); all_keys.len()];
945 state
946 .multi_get(all_keys.iter().copied(), results.iter_mut())
947 .await
948 .expect("multi_get in fuzz hook should not error");
949 let final_state = results
950 .into_iter()
951 .map(|r| match r.value {
952 None => None,
953 Some(mut sv) => {
954 sv.ensure_decoded(bincode_opts, GlobalId::User(0), None);
955 sv.into_decoded().finalized
956 }
957 })
958 .collect();
959
960 (output, final_state)
961}
962
963pub(crate) struct UpsertConfig {
966 pub shrink_upsert_unused_buffers_by_ratio: usize,
967}
968
969#[async_trait::async_trait(?Send)]
970pub(crate) trait UpsertErrorEmitter<T> {
971 async fn emit(&mut self, context: String, e: anyhow::Error);
972}
973
974#[async_trait::async_trait(?Send)]
975impl<T: Timestamp> UpsertErrorEmitter<T>
976 for (
977 &mut AsyncOutputHandle<
978 T,
979 CapacityContainerBuilder<Vec<(Option<GlobalId>, HealthStatusUpdate)>>,
980 >,
981 &Capability<T>,
982 )
983{
984 async fn emit(&mut self, context: String, e: anyhow::Error) {
985 process_upsert_state_error::<T>(context, e, self.0, self.1).await
986 }
987}
988
989async fn process_upsert_state_error<T: Timestamp>(
991 context: String,
992 e: anyhow::Error,
993 health_output: &AsyncOutputHandle<
994 T,
995 CapacityContainerBuilder<Vec<(Option<GlobalId>, HealthStatusUpdate)>>,
996 >,
997 health_cap: &Capability<T>,
998) {
999 let update = HealthStatusUpdate::halting(e.context(context).to_string_with_causes(), None);
1000 health_output.give(health_cap, (None, update));
1001 std::future::pending::<()>().await;
1002 unreachable!("pending future never returns");
1003}