Skip to main content

mz_storage/
upsert.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use 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;
57// TODO(aljoscha): Move next to upsert module, rename to upsert_types.
58pub(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
82/// Columnar (the `columnar` crate, distinct from `columnation`) support for
83/// `UpsertKey`, so the upsert-v2 source stash can use a columnar merge
84/// batcher keyed natively by `UpsertKey` (no `Row` packing). `UpsertKey` is a
85/// POD `[u8; 32]` newtype, so the container is a fixed-stride byte column.
86///
87/// This is hand-rolled rather than `#[derive(Columnar)]`d for one load-bearing
88/// reason: the reference type must be `&UpsertKey`. `&UpsertKey` is `Copy + Ord`
89/// (the lexicographic `[u8; 32]` order the persist-feedback trace is keyed on),
90/// which satisfies the merge batcher's `Ref: Copy + Ord` requirement. A derived
91/// impl would yield a generated `UpsertKeyReference` and route `[u8; 32]`
92/// through the generic, non-fixed-stride array container.
93mod columnar_upsert_key {
94    use super::UpsertKey;
95    use columnar::Columnar;
96    use mz_ore::cast::CastFrom;
97    use std::ops::Range;
98
99    /// A newtype wrapper for a vector of `UpsertKey` values.
100    #[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
214/// Projects a source's native `FromTime` to a columnar, totally-ordered key
215/// used by the upsert source stash to keep the latest update per `(key, time)`.
216///
217/// The upsert stash is a columnar merge batcher; its diff carries this
218/// projection rather than the raw `FromTime`, so the only columnar type the
219/// stash needs is `Order` — never the (possibly structurally complex) source
220/// timestamp. This is what keeps the columnar requirement off the generic
221/// source-render path: that path only ever needs `FromTime: UpsertSourceTime`.
222/// Only the relative order matters; the value is never read back.
223///
224/// The upsert envelope is rendered for Kafka and the KEY VALUE load generator,
225/// so those source times (`KafkaTimestamp`, `MzOffset`) project to a real order
226/// key. The remaining source times implement the trait only for coherence on
227/// the generic render path — their sources never render upsert — so their
228/// projection is a panicking guard rather than a real key.
229pub trait UpsertSourceTime
230where
231    for<'a> columnar::Ref<'a, Self::Order>: Ord,
232{
233    /// Columnar order key. Must order consistently with the source time it is
234    /// projected from.
235    type Order: mz_timely_util::columnar::chunk::PoolColumnar
236        + Clone
237        + Default
238        + Ord
239        + Send
240        + Sync
241        + 'static;
242    /// Project the source time onto its order key.
243    fn upsert_order(&self) -> Self::Order;
244}
245
246impl UpsertSourceTime for KafkaTimestamp {
247    /// Per-record Kafka source times are exact singletons (a single partition
248    /// at a single offset; see the source reader), and `KafkaTimestamp`'s
249    /// derived `Ord` is lexicographic on `(partition, offset)`, so this flat
250    /// projection is order-preserving. `RangeBound`'s infinities map to the
251    /// `i64` extrema to remain order-consistent for any non-singleton bound.
252    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
263/// Load-generator (and Postgres) source time. The KEY VALUE load generator is
264/// the one non-Kafka source that renders the upsert envelope (see
265/// `apply_source_envelope_encoding` in the planner), so this projects to the
266/// record offset: offsets increase with each update, so "max order wins" is
267/// exactly "latest update wins" for dedup.
268impl UpsertSourceTime for MzOffset {
269    type Order = u64;
270    fn upsert_order(&self) -> u64 {
271        self.offset
272    }
273}
274
275/// Source times whose sources never render the upsert envelope (MySQL and SQL
276/// Server CDC). `Order = ()` keeps the generic render path free of any columnar
277/// requirement on the source time. The projection panics rather than returning:
278/// `()` would collapse every `from_time` to equal, silently breaking "latest
279/// offset wins" dedup, so if such a source ever reaches the upsert path we want
280/// a loud failure, not arbitrary per-key output.
281macro_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
297/// The storage spill gate ([`mz_timely_util::columnar::chunk::StorageSpill`]).
298///
299/// The upsert-v2 source stash and feedback arrangement spill through the
300/// process buffer pool: committed chunk bodies land in the pool once compute's
301/// config handler has installed and budgeted it (storage and compute run in
302/// the same `clusterd` process). The gate is consulted at every chunk commit,
303/// so flips apply to running dataflows.
304pub mod upsert_stash_spill {
305    /// Enable or disable spilling of upsert chunk bodies to the buffer pool.
306    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    // Note we do 1 `multi_get` and 1 `multi_put` while processing a _batch of updates_. Within the
324    // batch, we effectively consolidate each key, before persisting that consolidated value.
325    // Easy!!
326    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
337/// The hash function used to map upsert keys. It is important that this hash is a cryptographic
338/// hash so that there is no risk of collisions. Collisions on SHA256 have a probability of 2^128
339/// which is many orders of magnitude smaller than many other events that we don't even think about
340/// (e.g bit flips). In short, we can safely assume that sha256(a) == sha256(b) iff a == b.
341type 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            /// A thread-local datum cache used to calculate hashes
351            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            /// A thread-local datum cache used to calculate hashes
369            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            // Borrowing the DatumVec gives us a temporary buffer to store datums in that will be
374            // automatically cleared on Drop. See the DatumVec docs for more details.
375            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
416/// This leaf operator drops `token` after the input reaches the `resume_upper`.
417/// This is useful to take coordinated actions across all workers, after the `upsert`
418/// operator has rehydrated.
419pub fn rehydration_finished<'scope, T: Timestamp>(
420    scope: Scope<'scope, T>,
421    source_config: &crate::source::RawSourceCreationConfig,
422    // A token that we can drop to signal we are finished rehydrating.
423    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        // Ensure this operator finishes if the resume upper is `[0]`
435        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
452/// Keys this operator's previous output, read back from persist, for retraction.
453///
454/// Only [`UpsertError`] survives the error side. It is the one error this operator can have
455/// written, and therefore the one it can retract; anything else entered the shard from
456/// elsewhere and is not ours to take back.
457pub(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
486/// Resumes an upsert computation at `resume_upper` given as inputs a collection of upsert commands
487/// and the collection of the previous output of this operator.
488/// Returns a tuple of
489/// - A collection of the computed upsert operator and,
490/// - A health update stream to propagate errors
491pub(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    // Whether or not to partially drain the input buffer
524    // to prevent buffering of the _upstream_ snapshot.
525    let prevent_snapshot_buffering =
526        dyncfgs::STORAGE_UPSERT_PREVENT_SNAPSHOT_BUFFERING.get(storage_configuration.config_set());
527    // If the above is true, the number of timely batches to process at once.
528    let snapshot_buffering_max = dyncfgs::STORAGE_UPSERT_MAX_SNAPSHOT_BATCH_BUFFERING
529        .get(storage_configuration.config_set());
530
531    // Whether we should provide the upsert state merge operator to the RocksDB instance
532    // (for faster performance during snapshot hydration).
533    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    // When running RocksDB in memory, the file system is emulated. However, we still need to
547    // pick a path that exists because RocksDB will attempt to create the working directory
548    // (see https://github.com/rust-rocksdb/rust-rocksdb/issues/1015) and write a lock file,
549    // so we need to ensure the directory is unique per worker.
550    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    // A closure that will initialize and return a configured RocksDB instance
576    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                    // For now, just use the same config as the one used for
595                    // merging snapshots.
596                    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
622/// An experimental upsert implementation loosely described in this doc:
623/// [Upsert V2 Much Simpler Boogaloo](https://www.notion.so/materialize/Upsert-V2-Much-Simpler-Boogaloo-31913f48d37b807fa88bdeafc27c02d9?source=copy_link)
624///
625/// Instead of using rocksdb as a state backend, this implementation uses a differential dataflow collection to hold the key state,
626/// and performs consolidation of updates with matching keys and MZ timestamps, using max FromTime to choose winners,
627/// resulting in only one record per key per time.
628pub(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
680/// Renders an operator that discards updates that are known to not affect the outcome of upsert in
681/// a streaming fashion. For each distinct (key, time) in the input it emits the value with the
682/// highest from_time. Its purpose is to thin out data as much as possible before exchanging them
683/// across workers.
684fn 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            // A capability suitable to emit all updates in `updates`, if any.
697            let mut capability: Option<Capability<T>> = None;
698            // A batch of received updates
699            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                    // `T: TotalOrder`, so the message's stamp has a least element, and holding
708                    // that one capability suffices to emit every update in the message.
709                    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                    // Sort by (key, time, Reverse(from_time)) so that deduping by (key, time) gives
723                    // the latest change for that key.
724                    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/// Drains the updates in `stash` that are not beyond `upper` into `state`.
745///
746/// NOTE: Only the `upsert_runtime` fuzz target runs this. The upsert operator
747/// drains its stash with `upsert_continual_feedback::drain_staged_input`.
748#[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    // Find the prefix that we can emit
767    let idx = stash.partition_point(|(ts, _, _, _)| !upper.less_equal(ts));
768
769    tracing::trace!(?upper, updates = idx, "draining stash in upsert");
770
771    // Read the previous values _per key_ out of `state`, recording it
772    // along with the value with the _latest timestamp for that key_.
773    commands_state.clear();
774    for (_, key, _, _) in stash.iter().take(idx) {
775        commands_state.entry(*key).or_default();
776    }
777
778    // These iterators iterate in the same order because `commands_state`
779    // is an `IndexMap`.
780    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    // From the prefix that can be emitted we can deduplicate based on (ts, key) in
795    // order to only process the command with the maximum order within the (ts,
796    // key) group. This is achieved by wrapping order in `Reverse(FromTime)` above.;
797    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    // Upsert the values into `commands_state`, by recording the latest
804    // value (or deletion). These will be synced at the end to the `state`.
805    //
806    // Note that we are effectively doing "mini-upsert" here, using
807    // `command_state`. This "mini-upsert" is seeded with data from `state`, using
808    // a single `multi_get` above, and the final state is written out into
809    // `state` using a single `multi_put`. This simplifies `UpsertStateBackend`
810    // implementations, and reduces the number of reads and write we need to do.
811    //
812    // This "mini-upsert" technique is actually useful in `UpsertState`'s
813    // `consolidate_snapshot_read_write_inner` implementation, minimizing gets and puts on
814    // the `UpsertStateBackend` implementations. In some sense, its "upsert all the way down".
815    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        // Skip this command if its order key is below the one in the upsert state.
829        // Note that the existing order key may be `None` if the existing value
830        // is from snapshotting, which always sorts below new values/deletes.
831        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            // Skip this update. If no later updates adjust this key, then we just
836            // end up writing the same value back to state. If there
837            // is nothing in the state, `existing_order` is `None`, and this
838            // does not occur.
839            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                // Record a tombstone for deletes.
861                *existing_value = Some(StateValue::tombstone());
862            }
863        }
864    }
865
866    match state
867        .multi_put(
868            true, // Do update per-update stats.
869            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/// A no-op-ish error emitter for the fuzzing hook. With the in-memory backend
894/// and the well-formed inputs the fuzzer builds, `multi_get`/`multi_put` never
895/// error, so reaching this is itself a finding.
896#[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/// Fuzzing hook: run a single `drain_staged_input` over `commands` (each a
908/// `(timestamp, key, order, value)`, where `value == None` is a delete) against
909/// a fresh empty in-memory state, draining everything strictly below
910/// `drain_to`. Returns the emitted output updates and the final finalized value
911/// of each key in `all_keys`. Exposed only for fuzzing. Not a stable public
912/// API.
913#[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
963// Created a struct to hold the configs for upserts.
964// So that new configs don't require a new method parameter.
965pub(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
989/// Emit the given error, and stall till the dataflow is restarted.
990async 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}