mz_storage/upsert_continual_feedback.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 feedback UPSERT operator and associated helpers. See
11//! [`upsert_inner`] for a description of how the operator works and why.
12
13use std::cmp::Reverse;
14use std::fmt::Debug;
15use std::sync::Arc;
16
17use differential_dataflow::hashable::Hashable;
18use differential_dataflow::{AsCollection, VecCollection};
19use indexmap::map::Entry;
20use itertools::Itertools;
21use mz_repr::{Diff, GlobalId, Row};
22use mz_storage_types::errors::{DataflowError, EnvelopeError};
23use mz_timely_util::builder_async::{
24 Event as AsyncEvent, OperatorBuilder as AsyncOperatorBuilder, PressOnDropButton,
25};
26use std::convert::Infallible;
27use timely::container::CapacityContainerBuilder;
28use timely::dataflow::channels::pact::Exchange;
29use timely::dataflow::operators::{Capability, CapabilitySet};
30use timely::dataflow::{Scope, Stream};
31use timely::order::{PartialOrder, TotalOrder};
32use timely::progress::timestamp::Refines;
33use timely::progress::{Antichain, Timestamp};
34
35use crate::healthcheck::HealthStatusUpdate;
36use crate::metrics::upsert::UpsertMetrics;
37use crate::upsert::UpsertConfig;
38use crate::upsert::UpsertErrorEmitter;
39use crate::upsert::UpsertKey;
40use crate::upsert::UpsertValue;
41use crate::upsert::types::UpsertValueAndSize;
42use crate::upsert::types::{self as upsert_types, ValueMetadata};
43use crate::upsert::types::{StateValue, UpsertState, UpsertStateBackend};
44
45/// An operator that transforms an input stream of upserts (updates to key-value
46/// pairs), which represents an imaginary key-value state, into a differential
47/// collection. It keeps an internal map-like state which keeps the latest value
48/// for each key, such that it can emit the retractions and additions implied by
49/// a new update for a given key.
50///
51/// This operator is intended to be used in an ingestion pipeline that reads
52/// from an external source, and the output of this operator is eventually
53/// written to persist.
54///
55/// The operator has two inputs: a) the source input, of upserts, and b) a
56/// persist input that feeds back the upsert state to the operator. Below, there
57/// is a section for each input that describes how and why we process updates
58/// from each input.
59///
60/// An important property of this operator is that it does _not_ update the
61/// map-like state that it keeps for translating the stream of upserts into a
62/// differential collection when it processes source input. It _only_ updates
63/// the map-like state based on updates from the persist (feedback) input. We do
64/// this because the operator is expected to be used in cases where there are
65/// multiple concurrent instances of the same ingestion pipeline, and the
66/// different instances might see different input because of concurrency and
67/// non-determinism. All instances of the upsert operator must produce output
68/// that is consistent with the current state of the output (that all instances
69/// produce "collaboratively"). This global state is what the operator
70/// continually learns about via updates from the persist input.
71///
72/// ## Processing the Source Input
73///
74/// Updates on the source input are stashed/staged until they can be processed.
75/// Whether or not an update can be processed depends both on the upper frontier
76/// of the source input and on the upper frontier of the persist input:
77///
78/// - Input updates are only processed once their timestamp is "done", that is
79/// the input upper is no longer `less_equal` their timestamp.
80///
81/// - Input updates are only processed once they are at the persist upper, that
82/// is we have emitted and written down updates for all previous times and we
83/// have updated our map-like state to the latest global state of the output of
84/// the ingestion pipeline. We know this is the case when the persist upper is
85/// no longer `less_than` their timestamp.
86///
87/// As an optimization, we allow processing input updates when they are right at
88/// the input frontier. This is called _partial emission_ because we are
89/// emitting updates that might be retracted when processing more updates from
90/// the same timestamp. In order to be able to process these updates we keep
91/// _provisional values_ in our upsert state. These will be overwritten when we
92/// get the final upsert values on the persist input.
93///
94/// ## Processing the Persist Input
95///
96/// We continually ingest updates from the persist input into our state using
97/// `UpsertState::consolidate_chunk`. We might be ingesting updates from the
98/// initial snapshot (when starting the operator) that are not consolidated or
99/// we might be ingesting updates from a partial emission (see above). In either
100/// case, our input might not be consolidated and `consolidate_chunk` is able to
101/// handle that.
102pub fn upsert_inner<G: Scope, FromTime, F, Fut, US>(
103 input: &VecCollection<G, (UpsertKey, Option<UpsertValue>, FromTime), Diff>,
104 key_indices: Vec<usize>,
105 resume_upper: Antichain<G::Timestamp>,
106 persist_input: VecCollection<G, Result<Row, DataflowError>, Diff>,
107 mut persist_token: Option<Vec<PressOnDropButton>>,
108 upsert_metrics: UpsertMetrics,
109 source_config: crate::source::SourceExportCreationConfig,
110 state_fn: F,
111 upsert_config: UpsertConfig,
112 prevent_snapshot_buffering: bool,
113 snapshot_buffering_max: Option<usize>,
114) -> (
115 VecCollection<G, Result<Row, DataflowError>, Diff>,
116 Stream<G, (Option<GlobalId>, HealthStatusUpdate)>,
117 Stream<G, Infallible>,
118 PressOnDropButton,
119)
120where
121 G::Timestamp: Refines<mz_repr::Timestamp> + TotalOrder + Sync,
122 F: FnOnce() -> Fut + 'static,
123 Fut: std::future::Future<Output = US>,
124 US: UpsertStateBackend<G::Timestamp, FromTime>,
125 FromTime: Debug + timely::ExchangeData + Ord + Sync,
126{
127 let mut builder = AsyncOperatorBuilder::new("Upsert".to_string(), input.scope());
128
129 // We only care about UpsertValueError since this is the only error that we can retract
130 let persist_input = persist_input.flat_map(move |result| {
131 let value = match result {
132 Ok(ok) => Ok(ok),
133 Err(DataflowError::EnvelopeError(err)) => match *err {
134 EnvelopeError::Upsert(err) => Err(Box::new(err)),
135 _ => return None,
136 },
137 Err(_) => return None,
138 };
139 let value_ref = match value {
140 Ok(ref row) => Ok(row),
141 Err(ref err) => Err(&**err),
142 };
143 Some((UpsertKey::from_value(value_ref, &key_indices), value))
144 });
145 let (output_handle, output) = builder.new_output::<CapacityContainerBuilder<_>>();
146
147 // An output that just reports progress of the snapshot consolidation process upstream to the
148 // persist source to ensure that backpressure is applied
149 let (_snapshot_handle, snapshot_stream) =
150 builder.new_output::<CapacityContainerBuilder<Vec<Infallible>>>();
151
152 let (mut health_output, health_stream) = builder.new_output();
153 let mut input = builder.new_input_for(
154 &input.inner,
155 Exchange::new(move |((key, _, _), _, _)| UpsertKey::hashed(key)),
156 &output_handle,
157 );
158
159 let mut persist_input = builder.new_disconnected_input(
160 &persist_input.inner,
161 Exchange::new(|((key, _), _, _)| UpsertKey::hashed(key)),
162 );
163
164 let upsert_shared_metrics = Arc::clone(&upsert_metrics.shared);
165
166 let shutdown_button = builder.build(move |caps| async move {
167 let [output_cap, snapshot_cap, health_cap]: [_; 3] = caps.try_into().unwrap();
168 drop(output_cap);
169 let mut snapshot_cap = CapabilitySet::from_elem(snapshot_cap);
170
171 let mut state = UpsertState::<_, G::Timestamp, FromTime>::new(
172 state_fn().await,
173 upsert_shared_metrics,
174 &upsert_metrics,
175 source_config.source_statistics.clone(),
176 upsert_config.shrink_upsert_unused_buffers_by_ratio,
177 );
178
179 // True while we're still reading the initial "snapshot" (a whole bunch
180 // of updates, all at the same initial timestamp) from our persist
181 // input or while we're reading the initial snapshot from the upstream
182 // source.
183 let mut hydrating = true;
184
185 // A re-usable buffer of changes, per key. This is an `IndexMap`
186 // because it has to be `drain`-able and have a consistent iteration
187 // order.
188 let mut commands_state: indexmap::IndexMap<
189 _,
190 upsert_types::UpsertValueAndSize<G::Timestamp, FromTime>,
191 > = indexmap::IndexMap::new();
192 let mut multi_get_scratch = Vec::new();
193
194 // For stashing source input while it's not eligible for processing.
195 let mut stash = vec![];
196 // A capability suitable for emitting any updates based on stash. No capability is held
197 // when the stash is empty.
198 let mut stash_cap: Option<Capability<G::Timestamp>> = None;
199 let mut input_upper = Antichain::from_elem(Timestamp::minimum());
200 let mut partial_drain_time = None;
201
202 // For our persist/feedback input, both of these.
203 let mut persist_stash = vec![];
204 let mut persist_upper = Antichain::from_elem(Timestamp::minimum());
205
206 // We keep track of the largest timestamp seen on the persist input so
207 // that we can block processing source input while that timestamp is
208 // beyond the persist frontier. While ingesting updates of a timestamp,
209 // our upsert state is in a consolidating state, and trying to read it
210 // at that time would yield a panic.
211 //
212 // NOTE(aljoscha): You would think that it cannot happen that we even
213 // attempt to process source updates while the state is in a
214 // consolidating state, because we always wait until the persist
215 // frontier "catches up" with the timestamp of the source input. If
216 // there is only this here UPSERT operator and no concurrent instances,
217 // this is true. But with concurrent instances it can happen that an
218 // operator that is faster than us makes it so updates get written to
219 // persist. And we would then be ingesting them.
220 let mut largest_seen_persist_ts: Option<G::Timestamp> = None;
221
222 // A buffer for our output.
223 let mut output_updates = vec![];
224
225 let mut error_emitter = (&mut health_output, &health_cap);
226
227 loop {
228 tokio::select! {
229 _ = persist_input.ready() => {
230 // Read away as much input as we can.
231 while let Some(persist_event) = persist_input.next_sync() {
232 match persist_event {
233 AsyncEvent::Data(time, data) => {
234 tracing::trace!(
235 worker_id = %source_config.worker_id,
236 source_id = %source_config.id,
237 time=?time,
238 updates=%data.len(),
239 "received persist data");
240
241 persist_stash.extend(data.into_iter().map(
242 |((key, value), ts, diff)| {
243 largest_seen_persist_ts =
244 std::cmp::max(
245 largest_seen_persist_ts
246 .clone(),
247 Some(ts.clone()),
248 );
249 (key, value, ts, diff)
250 },
251 ));
252 }
253 AsyncEvent::Progress(upper) => {
254 tracing::trace!(
255 worker_id = %source_config.worker_id,
256 source_id = %source_config.id,
257 ?upper,
258 "received persist progress");
259 persist_upper = upper;
260 }
261 }
262 }
263
264 let last_rehydration_chunk =
265 hydrating && PartialOrder::less_equal(&resume_upper, &persist_upper);
266
267 tracing::debug!(
268 worker_id = %source_config.worker_id,
269 source_id = %source_config.id,
270 persist_stash = %persist_stash.len(),
271 %hydrating,
272 %last_rehydration_chunk,
273 ?resume_upper,
274 ?persist_upper,
275 "ingesting persist snapshot chunk");
276
277 let persist_stash_iter = persist_stash
278 .drain(..)
279 .map(|(key, val, _ts, diff)| (key, val, diff));
280
281 match state
282 .consolidate_chunk(
283 persist_stash_iter,
284 last_rehydration_chunk,
285 )
286 .await
287 {
288 Ok(_) => {}
289 Err(e) => {
290 // Make sure our persist source can shut down.
291 persist_token.take();
292 snapshot_cap.downgrade(&[]);
293 UpsertErrorEmitter::<G>::emit(
294 &mut error_emitter,
295 "Failed to rehydrate state".to_string(),
296 e,
297 )
298 .await;
299 }
300 }
301
302 tracing::debug!(
303 worker_id = %source_config.worker_id,
304 source_id = %source_config.id,
305 ?resume_upper,
306 ?persist_upper,
307 "downgrading snapshot cap",
308 );
309
310 // Only downgrade this _after_ ingesting the data, because
311 // that can actually take quite some time, and we don't want
312 // to announce that we're done ingesting the initial
313 // snapshot too early.
314 //
315 // When we finish ingesting our initial persist snapshot,
316 // during "re-hydration", we downgrade this to the empty
317 // frontier, so we need to be lenient to this failing from
318 // then on.
319 let _ = snapshot_cap.try_downgrade(persist_upper.iter());
320
321
322
323 if last_rehydration_chunk {
324 hydrating = false;
325
326 tracing::info!(
327 worker_id = %source_config.worker_id,
328 source_id = %source_config.id,
329 "upsert source finished rehydration",
330 );
331
332 snapshot_cap.downgrade(&[]);
333 }
334
335 }
336 _ = input.ready() => {
337 let mut events_processed = 0;
338 while let Some(event) = input.next_sync() {
339 match event {
340 AsyncEvent::Data(cap, mut data) => {
341 tracing::trace!(
342 worker_id = %source_config.worker_id,
343 source_id = %source_config.id,
344 time=?cap.time(),
345 updates=%data.len(),
346 "received data");
347
348 let event_time = cap.time().clone();
349
350 stage_input(
351 &mut stash,
352 &mut data,
353 &input_upper,
354 &resume_upper,
355 );
356 if !stash.is_empty() {
357 // Update the stashed capability to the minimum
358 stash_cap = match stash_cap {
359 Some(stash_cap) => {
360 if cap.time() < stash_cap.time() {
361 Some(cap)
362 } else {
363 Some(stash_cap)
364 }
365 }
366 None => Some(cap)
367 };
368 }
369
370 if prevent_snapshot_buffering
371 && input_upper.as_option()
372 == Some(&event_time)
373 {
374 tracing::debug!(
375 worker_id = %source_config.worker_id,
376 source_id = %source_config.id,
377 ?event_time,
378 ?resume_upper,
379 ?input_upper,
380 "allowing partial drain");
381 partial_drain_time = Some(event_time.clone());
382 } else {
383 tracing::debug!(
384 worker_id = %source_config.worker_id,
385 source_id = %source_config.id,
386 %prevent_snapshot_buffering,
387 ?event_time,
388 ?resume_upper,
389 ?input_upper,
390 "not allowing partial drain");
391 }
392 }
393 AsyncEvent::Progress(upper) => {
394 tracing::trace!(
395 worker_id = %source_config.worker_id,
396 source_id = %source_config.id,
397 ?upper,
398 "received progress");
399
400 // Ignore progress updates before the `resume_upper`, which is our initial
401 // capability post-snapshotting.
402 if PartialOrder::less_than(&upper, &resume_upper) {
403 tracing::trace!(
404 worker_id = %source_config.worker_id,
405 source_id = %source_config.id,
406 ?upper,
407 ?resume_upper,
408 "ignoring progress updates before resume_upper");
409 continue;
410 }
411
412 // Disable partial drain, because this progress
413 // update has moved the frontier. We might allow
414 // it again once we receive data right at the
415 // frontier again.
416 partial_drain_time = None;
417 input_upper = upper;
418 }
419 }
420
421 events_processed += 1;
422 if let Some(max) = snapshot_buffering_max {
423 if events_processed >= max {
424 break;
425 }
426 }
427 }
428 }
429 };
430
431 // While we have partially ingested updates of a timestamp our state
432 // is in an inconsistent/consolidating state and accessing it would
433 // panic.
434 if let Some(largest_seen_persist_ts) = largest_seen_persist_ts.as_ref() {
435 let largest_seen_outer_persist_ts = largest_seen_persist_ts.clone().to_outer();
436 let outer_persist_upper = persist_upper.iter().map(|ts| ts.clone().to_outer());
437 let outer_persist_upper = Antichain::from_iter(outer_persist_upper);
438 if outer_persist_upper.less_equal(&largest_seen_outer_persist_ts) {
439 continue;
440 }
441 }
442
443 // We try and drain from our stash every time we go through the
444 // loop. More of our stash can become eligible for draining both
445 // when the source-input frontier advances or when the persist
446 // frontier advances.
447 if !stash.is_empty() {
448 let cap = stash_cap
449 .as_mut()
450 .expect("missing capability for non-empty stash");
451
452 tracing::trace!(
453 worker_id = %source_config.worker_id,
454 source_id = %source_config.id,
455 ?cap,
456 ?stash,
457 "stashed updates");
458
459 let mut min_remaining_time = drain_staged_input::<_, G, _, _, _>(
460 &mut stash,
461 &mut commands_state,
462 &mut output_updates,
463 &mut multi_get_scratch,
464 DrainStyle::ToUpper {
465 input_upper: &input_upper,
466 persist_upper: &persist_upper,
467 },
468 &mut error_emitter,
469 &mut state,
470 &source_config,
471 )
472 .await;
473
474 tracing::trace!(
475 worker_id = %source_config.worker_id,
476 source_id = %source_config.id,
477 output_updates = %output_updates.len(),
478 "output updates for complete timestamp");
479
480 for (update, ts, diff) in output_updates.drain(..) {
481 output_handle.give(cap, (update, ts, diff));
482 }
483
484 if !stash.is_empty() {
485 let min_remaining_time = min_remaining_time
486 .take()
487 .expect("we still have updates left");
488 cap.downgrade(&min_remaining_time);
489 } else {
490 stash_cap = None;
491 }
492 }
493
494 if input_upper.is_empty() {
495 tracing::debug!(
496 worker_id = %source_config.worker_id,
497 source_id = %source_config.id,
498 "input exhausted, shutting down");
499 break;
500 };
501
502 // If there were staged events that occurred at the capability time, drain
503 // them. This is safe because out-of-order updates to the same key that are
504 // drained in separate calls to `drain_staged_input` are correctly ordered by
505 // their `FromTime` in `drain_staged_input`.
506 //
507 // Note also that this may result in more updates in the output collection than
508 // the minimum. However, because the frontier only advances on `Progress` updates,
509 // the collection always accumulates correctly for all keys.
510 if let Some(partial_drain_time) = &partial_drain_time {
511 if !stash.is_empty() {
512 let cap = stash_cap
513 .as_mut()
514 .expect("missing capability for non-empty stash");
515
516 tracing::trace!(
517 worker_id = %source_config.worker_id,
518 source_id = %source_config.id,
519 ?cap,
520 ?stash,
521 "stashed updates");
522
523 let mut min_remaining_time = drain_staged_input::<_, G, _, _, _>(
524 &mut stash,
525 &mut commands_state,
526 &mut output_updates,
527 &mut multi_get_scratch,
528 DrainStyle::AtTime {
529 time: partial_drain_time.clone(),
530 persist_upper: &persist_upper,
531 },
532 &mut error_emitter,
533 &mut state,
534 &source_config,
535 )
536 .await;
537
538 tracing::trace!(
539 worker_id = %source_config.worker_id,
540 source_id = %source_config.id,
541 output_updates = %output_updates.len(),
542 "output updates for partial timestamp");
543
544 for (update, ts, diff) in output_updates.drain(..) {
545 output_handle.give(cap, (update, ts, diff));
546 }
547
548 if !stash.is_empty() {
549 let min_remaining_time = min_remaining_time
550 .take()
551 .expect("we still have updates left");
552 cap.downgrade(&min_remaining_time);
553 } else {
554 stash_cap = None;
555 }
556 }
557 }
558 }
559 });
560
561 (
562 output
563 .as_collection()
564 .map(|result: UpsertValue| match result {
565 Ok(ok) => Ok(ok),
566 Err(err) => Err(DataflowError::from(EnvelopeError::Upsert(*err))),
567 }),
568 health_stream,
569 snapshot_stream,
570 shutdown_button.press_on_drop(),
571 )
572}
573
574/// Helper method for [`upsert_inner`] used to stage `data` updates
575/// from the input/source timely edge.
576#[allow(clippy::disallowed_types)]
577fn stage_input<T, FromTime>(
578 stash: &mut Vec<(T, UpsertKey, Reverse<FromTime>, Option<UpsertValue>)>,
579 data: &mut Vec<((UpsertKey, Option<UpsertValue>, FromTime), T, Diff)>,
580 input_upper: &Antichain<T>,
581 resume_upper: &Antichain<T>,
582) where
583 T: PartialOrder + timely::progress::Timestamp,
584 FromTime: Ord,
585{
586 if PartialOrder::less_equal(input_upper, resume_upper) {
587 data.retain(|(_, ts, _)| resume_upper.less_equal(ts));
588 }
589
590 stash.extend(data.drain(..).map(|((key, value, order), time, diff)| {
591 assert!(diff.is_positive(), "invalid upsert input");
592 (time, key, Reverse(order), value)
593 }));
594}
595
596/// The style of drain we are performing on the stash. `AtTime`-drains cannot
597/// assume that all values have been seen, and must leave tombstones behind for deleted values.
598#[derive(Debug)]
599enum DrainStyle<'a, T> {
600 ToUpper {
601 input_upper: &'a Antichain<T>,
602 persist_upper: &'a Antichain<T>,
603 },
604 // For partial draining when taking the source snapshot.
605 AtTime {
606 time: T,
607 persist_upper: &'a Antichain<T>,
608 },
609}
610
611/// Helper method for [`upsert_inner`] used to stage `data` updates
612/// from the input timely edge.
613///
614/// Returns the minimum observed time across the updates that remain in the
615/// stash or `None` if none are left.
616///
617/// ## Correctness
618///
619/// It is safe to call this function multiple times with the same `persist_upper` provided that the
620/// drain style is `AtTime`, which updates the state such that past actions are remembered and can
621/// be undone in subsequent calls.
622///
623/// It is *not* safe to call this function more than once with the same `persist_upper` and a
624/// `ToUpper` drain style. Doing so causes all calls except the first one to base their work on
625/// stale state, since in this drain style no modifications to the state are made.
626async fn drain_staged_input<S, G, T, FromTime, E>(
627 stash: &mut Vec<(T, UpsertKey, Reverse<FromTime>, Option<UpsertValue>)>,
628 commands_state: &mut indexmap::IndexMap<UpsertKey, UpsertValueAndSize<T, FromTime>>,
629 output_updates: &mut Vec<(UpsertValue, T, Diff)>,
630 multi_get_scratch: &mut Vec<UpsertKey>,
631 drain_style: DrainStyle<'_, T>,
632 error_emitter: &mut E,
633 state: &mut UpsertState<'_, S, T, FromTime>,
634 source_config: &crate::source::SourceExportCreationConfig,
635) -> Option<T>
636where
637 S: UpsertStateBackend<T, FromTime>,
638 G: Scope,
639 T: TotalOrder + timely::ExchangeData + Debug + Ord + Sync,
640 FromTime: timely::ExchangeData + Ord + Sync,
641 E: UpsertErrorEmitter<G>,
642{
643 let mut min_remaining_time = Antichain::new();
644
645 let mut eligible_updates = stash
646 .extract_if(.., |(ts, _, _, _)| {
647 let eligible = match &drain_style {
648 DrainStyle::ToUpper {
649 input_upper,
650 persist_upper,
651 } => {
652 // We make sure that a) we only process updates when we know their
653 // timestamp is complete, that is there will be no more updates for
654 // that timestamp, and b) that "previous" times in the persist
655 // input are complete. The latter makes sure that we emit updates
656 // for the next timestamp that are consistent with the global state
657 // in the output persist shard, which also serves as a persistent
658 // copy of our in-memory/on-disk upsert state.
659 !input_upper.less_equal(ts) && !persist_upper.less_than(ts)
660 }
661 DrainStyle::AtTime {
662 time,
663 persist_upper,
664 } => {
665 // Even when emitting partial updates, we still need to wait
666 // until "previous" times in the persist input are complete.
667 *ts <= *time && !persist_upper.less_than(ts)
668 }
669 };
670
671 if !eligible {
672 min_remaining_time.insert(ts.clone());
673 }
674
675 eligible
676 })
677 .filter(|(ts, _, _, _)| {
678 let persist_upper = match &drain_style {
679 DrainStyle::ToUpper {
680 input_upper: _,
681 persist_upper,
682 } => persist_upper,
683 DrainStyle::AtTime {
684 time: _,
685 persist_upper,
686 } => persist_upper,
687 };
688
689 // Any update that is "in the past" of the persist upper is not
690 // relevant anymore. We _can_ emit changes for it, but the
691 // downstream persist_sink would filter these updates out because
692 // the shard upper is already further ahead.
693 //
694 // Plus, our upsert state is up-to-date to the persist_upper, so we
695 // wouldn't be able to emit correct retractions for incoming
696 // commands whose `ts` is in the past of that.
697 let relevant = persist_upper.less_equal(ts);
698 relevant
699 })
700 .collect_vec();
701
702 tracing::debug!(
703 worker_id = %source_config.worker_id,
704 source_id = %source_config.id,
705 ?drain_style,
706 remaining = %stash.len(),
707 eligible = eligible_updates.len(),
708 "draining stash");
709
710 // Sort the eligible updates by (key, time, Reverse(from_time)) so that
711 // deduping by (key, time) gives the latest change for that key.
712 eligible_updates.sort_unstable_by(|a, b| {
713 let (ts1, key1, from_ts1, val1) = a;
714 let (ts2, key2, from_ts2, val2) = b;
715 Ord::cmp(&(ts1, key1, from_ts1, val1), &(ts2, key2, from_ts2, val2))
716 });
717
718 // Read the previous values _per key_ out of `state`, recording it
719 // along with the value with the _latest timestamp for that key_.
720 commands_state.clear();
721 for (_, key, _, _) in eligible_updates.iter() {
722 commands_state.entry(*key).or_default();
723 }
724
725 // These iterators iterate in the same order because `commands_state`
726 // is an `IndexMap`.
727 multi_get_scratch.clear();
728 multi_get_scratch.extend(commands_state.iter().map(|(k, _)| *k));
729 match state
730 .multi_get(multi_get_scratch.drain(..), commands_state.values_mut())
731 .await
732 {
733 Ok(_) => {}
734 Err(e) => {
735 error_emitter
736 .emit("Failed to fetch records from state".to_string(), e)
737 .await;
738 }
739 }
740
741 // From the prefix that can be emitted we can deduplicate based on (ts, key) in
742 // order to only process the command with the maximum order within the (ts,
743 // key) group. This is achieved by wrapping order in `Reverse(FromTime)` above.;
744 let mut commands = eligible_updates.into_iter().dedup_by(|a, b| {
745 let ((a_ts, a_key, _, _), (b_ts, b_key, _, _)) = (a, b);
746 a_ts == b_ts && a_key == b_key
747 });
748
749 let bincode_opts = upsert_types::upsert_bincode_opts();
750 // Upsert the values into `commands_state`, by recording the latest
751 // value (or deletion). These will be synced at the end to the `state`.
752 //
753 // Note that we are effectively doing "mini-upsert" here, using
754 // `command_state`. This "mini-upsert" is seeded with data from `state`, using
755 // a single `multi_get` above, and the final state is written out into
756 // `state` using a single `multi_put`. This simplifies `UpsertStateBackend`
757 // implementations, and reduces the number of reads and write we need to do.
758 //
759 // This "mini-upsert" technique is actually useful in `UpsertState`'s
760 // `consolidate_snapshot_read_write_inner` implementation, minimizing gets and puts on
761 // the `UpsertStateBackend` implementations. In some sense, its "upsert all the way down".
762 while let Some((ts, key, from_time, value)) = commands.next() {
763 let mut command_state = if let Entry::Occupied(command_state) = commands_state.entry(key) {
764 command_state
765 } else {
766 panic!("key missing from commands_state");
767 };
768
769 let existing_state_cell = &mut command_state.get_mut().value;
770
771 if let Some(cs) = existing_state_cell.as_mut() {
772 cs.ensure_decoded(bincode_opts, source_config.id);
773 }
774
775 // Skip this command if its order key is below the one in the upsert state.
776 // Note that the existing order key may be `None` if the existing value
777 // is from snapshotting, which always sorts below new values/deletes.
778 let existing_order = existing_state_cell
779 .as_ref()
780 .and_then(|cs| cs.provisional_order(&ts));
781 if existing_order >= Some(&from_time.0) {
782 // Skip this update. If no later updates adjust this key, then we just
783 // end up writing the same value back to state. If there
784 // is nothing in the state, `existing_order` is `None`, and this
785 // does not occur.
786 continue;
787 }
788
789 match value {
790 Some(value) => {
791 if let Some(old_value) = existing_state_cell.as_ref() {
792 if let Some(old_value) = old_value.provisional_value_ref(&ts) {
793 output_updates.push((old_value.clone(), ts.clone(), Diff::MINUS_ONE));
794 }
795 }
796
797 match &drain_style {
798 DrainStyle::AtTime { .. } => {
799 let existing_value = existing_state_cell.take();
800
801 let new_value = match existing_value {
802 Some(existing_value) => existing_value.clone().into_provisional_value(
803 value.clone(),
804 ts.clone(),
805 from_time.0.clone(),
806 ),
807 None => StateValue::new_provisional_value(
808 value.clone(),
809 ts.clone(),
810 from_time.0.clone(),
811 ),
812 };
813
814 existing_state_cell.replace(new_value);
815 }
816 DrainStyle::ToUpper { .. } => {
817 // Not writing down provisional values, or anything.
818 }
819 };
820
821 output_updates.push((value, ts, Diff::ONE));
822 }
823 None => {
824 if let Some(old_value) = existing_state_cell.as_ref() {
825 if let Some(old_value) = old_value.provisional_value_ref(&ts) {
826 output_updates.push((old_value.clone(), ts.clone(), Diff::MINUS_ONE));
827 }
828 }
829
830 match &drain_style {
831 DrainStyle::AtTime { .. } => {
832 let existing_value = existing_state_cell.take();
833
834 let new_value = match existing_value {
835 Some(existing_value) => existing_value
836 .into_provisional_tombstone(ts.clone(), from_time.0.clone()),
837 None => StateValue::new_provisional_tombstone(
838 ts.clone(),
839 from_time.0.clone(),
840 ),
841 };
842
843 existing_state_cell.replace(new_value);
844 }
845 DrainStyle::ToUpper { .. } => {
846 // Not writing down provisional values, or anything.
847 }
848 }
849 }
850 }
851 }
852
853 match &drain_style {
854 DrainStyle::AtTime { .. } => {
855 match state
856 .multi_put(
857 // We don't want to update per-record stats, like size of
858 // records indexed or count of records indexed.
859 //
860 // We only add provisional values and these will be
861 // overwritten once we receive updates for state from the
862 // persist input. And the merge functionality cannot know
863 // what was in state before merging, so it cannot correctly
864 // retract/update stats added here.
865 //
866 // Mostly, the merge functionality can't update those stats
867 // because merging happens in a function that we pass to
868 // rocksdb which doesn't have access to any external
869 // context. And in general, with rocksdb we do blind writes
870 // rather than inspect what was there before when
871 // updating/inserting.
872 false,
873 commands_state.drain(..).map(|(k, cv)| {
874 (
875 k,
876 upsert_types::PutValue {
877 value: cv.value.map(|cv| cv.into_decoded()),
878 previous_value_metadata: cv.metadata.map(|v| ValueMetadata {
879 size: v.size.try_into().expect("less than i64 size"),
880 is_tombstone: v.is_tombstone,
881 }),
882 },
883 )
884 }),
885 )
886 .await
887 {
888 Ok(_) => {}
889 Err(e) => {
890 error_emitter
891 .emit("Failed to update records in state".to_string(), e)
892 .await;
893 }
894 }
895 }
896 style => {
897 tracing::trace!(
898 worker_id = %source_config.worker_id,
899 source_id = %source_config.id,
900 "not doing state update for drain style {:?}", style);
901 }
902 }
903
904 min_remaining_time.into_option()
905}
906
907#[cfg(test)]
908mod test {
909 use std::sync::mpsc;
910
911 use mz_ore::metrics::MetricsRegistry;
912 use mz_persist_types::ShardId;
913 use mz_repr::{Datum, Timestamp as MzTimestamp};
914 use mz_rocksdb::{RocksDBConfig, ValueIterator};
915 use mz_storage_operators::persist_source::Subtime;
916 use mz_storage_types::sources::SourceEnvelope;
917 use mz_storage_types::sources::envelope::{KeyEnvelope, UpsertEnvelope, UpsertStyle};
918 use rocksdb::Env;
919 use timely::dataflow::operators::capture::Extract;
920 use timely::dataflow::operators::{Capture, Input, Probe};
921 use timely::progress::Timestamp;
922
923 use crate::metrics::StorageMetrics;
924 use crate::metrics::upsert::UpsertMetricDefs;
925 use crate::source::SourceExportCreationConfig;
926 use crate::statistics::{SourceStatistics, SourceStatisticsMetricDefs};
927 use crate::upsert::memory::InMemoryHashMap;
928 use crate::upsert::types::{BincodeOpts, consolidating_merge_function, upsert_bincode_opts};
929
930 use super::*;
931
932 #[mz_ore::test]
933 #[cfg_attr(miri, ignore)]
934 fn gh_9160_repro() {
935 // Helper to wrap timestamps in the appropriate types
936 let new_ts = |ts| (MzTimestamp::new(ts), Subtime::minimum());
937
938 let output_handle = timely::execute_directly(move |worker| {
939 let (mut input_handle, mut persist_handle, output_handle) = worker
940 .dataflow::<MzTimestamp, _, _>(|scope| {
941 // Enter a subscope since the upsert operator expects to work a backpressure
942 // enabled scope.
943 scope.scoped::<(MzTimestamp, Subtime), _, _>("upsert", |scope| {
944 let (input_handle, input) = scope.new_input();
945 let (persist_handle, persist_input) = scope.new_input();
946 let upsert_config = UpsertConfig {
947 shrink_upsert_unused_buffers_by_ratio: 0,
948 };
949 let source_id = GlobalId::User(0);
950 let metrics_registry = MetricsRegistry::new();
951 let upsert_metrics_defs =
952 UpsertMetricDefs::register_with(&metrics_registry);
953 let upsert_metrics =
954 UpsertMetrics::new(&upsert_metrics_defs, source_id, 0, None);
955
956 let metrics_registry = MetricsRegistry::new();
957 let storage_metrics = StorageMetrics::register_with(&metrics_registry);
958
959 let metrics_registry = MetricsRegistry::new();
960 let source_statistics_defs =
961 SourceStatisticsMetricDefs::register_with(&metrics_registry);
962 let envelope = SourceEnvelope::Upsert(UpsertEnvelope {
963 source_arity: 2,
964 style: UpsertStyle::Default(KeyEnvelope::Flattened),
965 key_indices: vec![0],
966 });
967 let source_statistics = SourceStatistics::new(
968 source_id,
969 0,
970 &source_statistics_defs,
971 source_id,
972 &ShardId::new(),
973 envelope,
974 Antichain::from_elem(Timestamp::minimum()),
975 );
976
977 let source_config = SourceExportCreationConfig {
978 id: GlobalId::User(0),
979 worker_id: 0,
980 metrics: storage_metrics,
981 source_statistics,
982 };
983
984 let (output, _, _, button) = upsert_inner(
985 &input.as_collection(),
986 vec![0],
987 Antichain::from_elem(Timestamp::minimum()),
988 persist_input.as_collection(),
989 None,
990 upsert_metrics,
991 source_config,
992 || async { InMemoryHashMap::default() },
993 upsert_config,
994 true,
995 None,
996 );
997 std::mem::forget(button);
998
999 (input_handle, persist_handle, output.inner.capture())
1000 })
1001 });
1002
1003 // We work with a hypothetical schema of (key int, value int).
1004
1005 // The input will contain records for two keys, 0 and 1.
1006 let key0 = UpsertKey::from_key(Ok(&Row::pack_slice(&[Datum::Int64(0)])));
1007 let key1 = UpsertKey::from_key(Ok(&Row::pack_slice(&[Datum::Int64(1)])));
1008
1009 // We will assume that the kafka topic contains the following messages with their
1010 // associated reclocked timestamp:
1011 // 1. {offset=1, key=0, value=0} @ mz_time = 0
1012 // 2. {offset=2, key=1, value=NULL} @ mz_time = 2 // <- deletion of unrelated key. Causes the operator
1013 // // to maintain the associated cap to time 2
1014 // 3. {offset=3, key=0, value=1} @ mz_time = 3
1015 // 4. {offset=4, key=0, value=2} @ mz_time = 3 // <- messages 2 and 3 are reclocked to time 3
1016 let value1 = Row::pack_slice(&[Datum::Int64(0), Datum::Int64(0)]);
1017 let value3 = Row::pack_slice(&[Datum::Int64(0), Datum::Int64(1)]);
1018 let value4 = Row::pack_slice(&[Datum::Int64(0), Datum::Int64(2)]);
1019 let msg1 = (key0, Some(Ok(value1.clone())), 1);
1020 let msg2 = (key1, None, 2);
1021 let msg3 = (key0, Some(Ok(value3)), 3);
1022 let msg4 = (key0, Some(Ok(value4)), 4);
1023
1024 // The first message will initialize the upsert state such that key 0 has value 0 and
1025 // produce an output update to that effect.
1026 input_handle.send((msg1, new_ts(0), Diff::ONE));
1027 input_handle.advance_to(new_ts(2));
1028 worker.step();
1029
1030 // We assume this worker succesfully CAAs the update to the shard so we send it back
1031 // through the persist_input
1032 persist_handle.send((Ok(value1), new_ts(0), Diff::ONE));
1033 persist_handle.advance_to(new_ts(1));
1034 worker.step();
1035
1036 // Then, messages 2 and 3 are sent as one batch with capability = 2
1037 input_handle.send_batch(&mut vec![
1038 (msg2, new_ts(2), Diff::ONE),
1039 (msg3, new_ts(3), Diff::ONE),
1040 ]);
1041 // Advance our capability to 3
1042 input_handle.advance_to(new_ts(3));
1043 // Message 4 is sent with capability 3
1044 input_handle.send_batch(&mut vec![(msg4, new_ts(3), Diff::ONE)]);
1045 // Advance our capability to 4
1046 input_handle.advance_to(new_ts(4));
1047 // We now step the worker so that the pending data is received. This causes the
1048 // operator to store internally the following map from capabilities to updates:
1049 // cap=2 => [ msg2, msg3 ]
1050 // cap=3 => [ msg4 ]
1051 worker.step();
1052
1053 // We now assume that another replica raced us and processed msg1 at time 2, which in
1054 // this test is a no-op so the persist frontier advances to time 3 without new data.
1055 persist_handle.advance_to(new_ts(3));
1056 // We now step this worker again, which will notice that the persist upper is {3} and
1057 // wlil attempt to process msg3 and msg4 *separately*, causing it to produce a double
1058 // retraction.
1059 worker.step();
1060
1061 output_handle
1062 });
1063
1064 let mut actual_output = output_handle
1065 .extract()
1066 .into_iter()
1067 .flat_map(|(_cap, container)| container)
1068 .collect();
1069 differential_dataflow::consolidation::consolidate_updates(&mut actual_output);
1070
1071 // The expected consolidated output contains only updates for key 0 which has the value 0
1072 // at timestamp 0 and the value 2 at timestamp 3
1073 let value1 = Row::pack_slice(&[Datum::Int64(0), Datum::Int64(0)]);
1074 let value4 = Row::pack_slice(&[Datum::Int64(0), Datum::Int64(2)]);
1075 let expected_output: Vec<(Result<Row, DataflowError>, _, _)> = vec![
1076 (Ok(value1.clone()), new_ts(0), Diff::ONE),
1077 (Ok(value1), new_ts(3), Diff::MINUS_ONE),
1078 (Ok(value4), new_ts(3), Diff::ONE),
1079 ];
1080 assert_eq!(actual_output, expected_output);
1081 }
1082
1083 #[mz_ore::test]
1084 #[cfg_attr(miri, ignore)]
1085 fn gh_9540_repro() {
1086 // Helper to wrap timestamps in the appropriate types
1087 let mz_ts = |ts| (MzTimestamp::new(ts), Subtime::minimum());
1088 let (tx, rx) = mpsc::channel::<std::thread::JoinHandle<()>>();
1089
1090 let rocksdb_dir = tempfile::tempdir().unwrap();
1091 let output_handle = timely::execute_directly(move |worker| {
1092 let tx = tx.clone();
1093 let (mut input_handle, mut persist_handle, output_probe, output_handle) =
1094 worker.dataflow::<MzTimestamp, _, _>(|scope| {
1095 // Enter a subscope since the upsert operator expects to work a backpressure
1096 // enabled scope.
1097 scope.scoped::<(MzTimestamp, Subtime), _, _>("upsert", |scope| {
1098 let (input_handle, input) = scope.new_input();
1099 let (persist_handle, persist_input) = scope.new_input();
1100 let upsert_config = UpsertConfig {
1101 shrink_upsert_unused_buffers_by_ratio: 0,
1102 };
1103 let source_id = GlobalId::User(0);
1104 let metrics_registry = MetricsRegistry::new();
1105 let upsert_metrics_defs =
1106 UpsertMetricDefs::register_with(&metrics_registry);
1107 let upsert_metrics =
1108 UpsertMetrics::new(&upsert_metrics_defs, source_id, 0, None);
1109 let rocksdb_shared_metrics = Arc::clone(&upsert_metrics.rocksdb_shared);
1110 let rocksdb_instance_metrics =
1111 Arc::clone(&upsert_metrics.rocksdb_instance_metrics);
1112
1113 let metrics_registry = MetricsRegistry::new();
1114 let storage_metrics = StorageMetrics::register_with(&metrics_registry);
1115
1116 let metrics_registry = MetricsRegistry::new();
1117 let source_statistics_defs =
1118 SourceStatisticsMetricDefs::register_with(&metrics_registry);
1119 let envelope = SourceEnvelope::Upsert(UpsertEnvelope {
1120 source_arity: 2,
1121 style: UpsertStyle::Default(KeyEnvelope::Flattened),
1122 key_indices: vec![0],
1123 });
1124 let source_statistics = SourceStatistics::new(
1125 source_id,
1126 0,
1127 &source_statistics_defs,
1128 source_id,
1129 &ShardId::new(),
1130 envelope,
1131 Antichain::from_elem(Timestamp::minimum()),
1132 );
1133
1134 let source_config = SourceExportCreationConfig {
1135 id: GlobalId::User(0),
1136 worker_id: 0,
1137 metrics: storage_metrics,
1138 source_statistics,
1139 };
1140
1141 // A closure that will initialize and return a configured RocksDB instance
1142 let rocksdb_init_fn = move || async move {
1143 let merge_operator = Some((
1144 "upsert_state_snapshot_merge_v1".to_string(),
1145 |a: &[u8],
1146 b: ValueIterator<
1147 BincodeOpts,
1148 StateValue<(MzTimestamp, Subtime), u64>,
1149 >| {
1150 consolidating_merge_function::<(MzTimestamp, Subtime), u64>(
1151 a.into(),
1152 b,
1153 )
1154 },
1155 ));
1156 let rocksdb_cleanup_tries = 5;
1157 let tuning = RocksDBConfig::new(Default::default(), None);
1158 let mut rocksdb_inst = mz_rocksdb::RocksDBInstance::new(
1159 rocksdb_dir.path(),
1160 mz_rocksdb::InstanceOptions::new(
1161 Env::mem_env().unwrap(),
1162 rocksdb_cleanup_tries,
1163 merge_operator,
1164 // For now, just use the same config as the one used for
1165 // merging snapshots.
1166 upsert_bincode_opts(),
1167 ),
1168 tuning,
1169 rocksdb_shared_metrics,
1170 rocksdb_instance_metrics,
1171 )
1172 .unwrap();
1173
1174 let handle = rocksdb_inst.take_core_loop_handle().expect("join handle");
1175 tx.send(handle).expect("sent joinhandle");
1176 crate::upsert::rocksdb::RocksDB::new(rocksdb_inst)
1177 };
1178
1179 let (output, _, _, button) = upsert_inner(
1180 &input.as_collection(),
1181 vec![0],
1182 Antichain::from_elem(Timestamp::minimum()),
1183 persist_input.as_collection(),
1184 None,
1185 upsert_metrics,
1186 source_config,
1187 rocksdb_init_fn,
1188 upsert_config,
1189 true,
1190 None,
1191 );
1192 std::mem::forget(button);
1193
1194 (
1195 input_handle,
1196 persist_handle,
1197 output.inner.probe(),
1198 output.inner.capture(),
1199 )
1200 })
1201 });
1202
1203 // We work with a hypothetical schema of (key int, value int).
1204
1205 // The input will contain records for two keys, 0 and 1.
1206 let key0 = UpsertKey::from_key(Ok(&Row::pack_slice(&[Datum::Int64(0)])));
1207
1208 // We will assume that the kafka topic contains the following messages with their
1209 // associated reclocked timestamp:
1210 // 1. {offset=1, key=0, value=0} @ mz_time = 0
1211 // 2. {offset=2, key=0, value=NULL} @ mz_time = 1
1212 // 3. {offset=3, key=0, value=0} @ mz_time = 2
1213 // 4. {offset=4, key=0, value=NULL} @ mz_time = 2 // <- messages 3 and 4 are *BOTH* reclocked to time 2
1214 let value1 = Row::pack_slice(&[Datum::Int64(0), Datum::Int64(0)]);
1215 let msg1 = ((key0, Some(Ok(value1.clone())), 1), mz_ts(0), Diff::ONE);
1216 let msg2 = ((key0, None, 2), mz_ts(1), Diff::ONE);
1217 let msg3 = ((key0, Some(Ok(value1.clone())), 3), mz_ts(2), Diff::ONE);
1218 let msg4 = ((key0, None, 4), mz_ts(2), Diff::ONE);
1219
1220 // The first message will initialize the upsert state such that key 0 has value 0 and
1221 // produce an output update to that effect.
1222 input_handle.send(msg1);
1223 input_handle.advance_to(mz_ts(1));
1224 while output_probe.less_than(&mz_ts(1)) {
1225 worker.step_or_park(None);
1226 }
1227 // Feedback the produced output..
1228 persist_handle.send((Ok(value1.clone()), mz_ts(0), Diff::ONE));
1229 persist_handle.advance_to(mz_ts(1));
1230 // ..and send the next upsert command that deletes the key.
1231 input_handle.send(msg2);
1232 input_handle.advance_to(mz_ts(2));
1233 while output_probe.less_than(&mz_ts(2)) {
1234 worker.step_or_park(None);
1235 }
1236
1237 // Feedback the produced output..
1238 persist_handle.send((Ok(value1), mz_ts(1), Diff::MINUS_ONE));
1239 persist_handle.advance_to(mz_ts(2));
1240 // ..and send the next *out of order* upsert command that deletes the key. Here msg4
1241 // happens at offset 4 and the operator should rememeber that.
1242 input_handle.send(msg4);
1243 input_handle.flush();
1244 // Run the worker for enough steps to process these events. We can't guide the
1245 // execution with the probe here since the frontier does not advance, only provisional
1246 // updates are produced.
1247 for _ in 0..5 {
1248 worker.step();
1249 }
1250
1251 // Send the missing message that will now confuse the operator because it has lost
1252 // track that for key 0 it has already seen a command for offset 4, and therefore msg3
1253 // should be skipped.
1254 input_handle.send(msg3);
1255 input_handle.flush();
1256 input_handle.advance_to(mz_ts(3));
1257
1258 output_handle
1259 });
1260
1261 let mut actual_output = output_handle
1262 .extract()
1263 .into_iter()
1264 .flat_map(|(_cap, container)| container)
1265 .collect();
1266 differential_dataflow::consolidation::consolidate_updates(&mut actual_output);
1267
1268 // The expected consolidated output contains only updates for key 0 which has the value 0
1269 // at timestamp 0 and the value 2 at timestamp 3
1270 let value1 = Row::pack_slice(&[Datum::Int64(0), Datum::Int64(0)]);
1271 let expected_output: Vec<(Result<Row, DataflowError>, _, _)> = vec![
1272 (Ok(value1.clone()), mz_ts(0), Diff::ONE),
1273 (Ok(value1), mz_ts(1), Diff::MINUS_ONE),
1274 ];
1275 assert_eq!(actual_output, expected_output);
1276
1277 while let Ok(handle) = rx.recv() {
1278 handle.join().expect("threads completed successfully");
1279 }
1280 }
1281}