mz_storage/upsert_continual_feedback_v2.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 the feedback UPSERT operator.
11//!
12//! # Architecture
13//!
14//! The operator converts a stream of upsert commands `(key, Option<value>)` into
15//! a differential collection of `(key, value)` pairs, using a feedback loop
16//! through persist to maintain the "previous value" state needed for computing
17//! retractions.
18//!
19//! ## Dataflow topology
20//!
21//! ```text
22//! Source input ──► ┌──────────┐ ──► Output ──► Persist
23//! │ Upsert │
24//! Persist read ──► └──────────┘
25//! ▲ │
26//! └───────────── feedback ────────────────────┘
27//! ```
28//!
29//! ## Operator loop (each iteration)
30//!
31//! 1. **Ingest source data.** Read upsert commands from the source input,
32//! wrap each in an `UpsertDiff` (carrying a columnar order key projected
33//! from `FromTime` via [`UpsertSourceTime`] for dedup), and push into the
34//! source-stash batcher. The batcher consolidates entries for the same
35//! `(key, time)` via the `UpsertDiff` Semigroup, keeping the update with
36//! the highest order key (latest source offset), through amortized
37//! geometric merging as data is pushed in, and cold stash state leaves RSS
38//! through the buffer pool (see below). This bounds resident
39//! memory even during large source snapshots.
40//!
41//! 2. **Read persist frontier.** Check the probe on the persist arrangement
42//! to learn which times have been committed. When the persist frontier
43//! reaches the resume upper, rehydration is complete.
44//!
45//! 3. **Extract & drain.** Extract from the batcher just past the persist
46//! frontier (capped at the input frontier, see `seal_upper`) all
47//! source-finalized entries as sorted, consolidated chunks. Each entry is
48//! classified:
49//! - **Eligible** (at the persist frontier): the persist trace has the
50//! correct "before" state for this time. Look up the old value in the
51//! feedback arrangement, emit a retraction if present, and emit the new
52//! value.
53//! - **Ineligible** (above the persist frontier, below the extract upper):
54//! persist hasn't caught up yet. Push back into the batcher for the next
55//! iteration.
56//! - **Already persisted** (below the persist frontier): some writer has
57//! already advanced the shard past this time, so it is dropped. See the
58//! drain functions for why re-stashing it would strand the data and pin
59//! the output frontier below the shard upper.
60//!
61//! 4. **Capability management.** Downgrade the output capability to the
62//! minimum time of any remaining buffered data (in the batcher or pushed
63//! back as ineligible). Drop the capability entirely when the batcher is
64//! empty.
65//!
66//! ## Stash and feedback arrangement
67//!
68//! The stash is differential's chunk merge batcher over time-major
69//! `ColumnChunk`s and the feedback arrangement is a spine of chunk batches.
70//! Committed chunk bodies spill to the process buffer pool, gated by
71//! `enable_upsert_paged_spill`. The drain loads sealed chunks one at a time,
72//! and prior state comes back through bulk probes of the trace's batches.
73//!
74//! ## Eligibility condition (total order)
75//!
76//! For a total-order timestamp with `input_upper = {i}` and
77//! `persist_upper = {p}`, an entry at time `ts` is eligible when
78//! `ts == p < i` — the source has finalized it and persist is exactly at
79//! that time, so the feedback trace holds the correct prior state. An entry
80//! with `p < ts` is ineligible (persist hasn't caught up), and one with
81//! `ts < p` is already persisted and dropped.
82
83use std::fmt::Debug;
84
85use differential_dataflow::hashable::Hashable;
86use differential_dataflow::operators::arrange::agent::TraceAgent;
87use differential_dataflow::operators::arrange::arrangement::{Arranged, arrange_core};
88use differential_dataflow::trace::TraceReader;
89use differential_dataflow::trace::chunk::ChunkBatcher;
90use differential_dataflow::trace::implementations::merge_batcher::MergeBatcher;
91use differential_dataflow::trace::implementations::spine_fueled::SpineBatch;
92use differential_dataflow::{AsCollection, VecCollection};
93use mz_ore::cast::CastFrom;
94use mz_repr::{Diff, GlobalId, Row};
95use mz_storage_types::errors::{DataflowError, EnvelopeError};
96use mz_timely_util::builder_async::{
97 AsyncOutputHandle, ButtonHandle, Event as AsyncEvent, OperatorBuilder as AsyncOperatorBuilder,
98 PressOnDropButton, sole_capability,
99};
100use mz_timely_util::columnar::chunk::{ChunkChunker, StorageSpill};
101use mz_timely_util::containers::stack::FueledBuilder;
102use std::convert::Infallible;
103use timely::container::CapacityContainerBuilder;
104use timely::dataflow::StreamVec;
105use timely::dataflow::channels::pact::{Exchange, Pipeline};
106use timely::dataflow::operators::{Capability, CapabilitySet};
107use timely::order::{PartialOrder, TotalOrder};
108use timely::progress::timestamp::Refines;
109use timely::progress::{Antichain, Timestamp};
110
111use crate::healthcheck::HealthStatusUpdate;
112use crate::metrics::upsert::UpsertMetrics;
113use crate::upsert::UpsertKey;
114use crate::upsert::UpsertSourceTime;
115use crate::upsert::UpsertValue;
116
117use self::feedback::{FeedbackChunk, FeedbackSpine, encode_feedback};
118use self::stash::{ChunkedArm, UpsertDiff, UpsertStashArm, UpsertUpdate, seal_upper};
119
120#[cfg(feature = "fuzzing")]
121pub use self::feedback::datum_seq_to_upsert_value;
122pub use self::feedback::upsert_value_to_row;
123
124mod drain;
125mod feedback;
126mod stash;
127#[cfg(test)]
128mod tests;
129
130/// The operator's data-output handle. A fueled `Vec` builder so the drain can
131/// `give_fueled` each emitted update and yield to timely under large snapshot
132/// drains instead of monopolizing the worker.
133type UpsertOutputHandle<T> =
134 AsyncOutputHandle<T, FueledBuilder<CapacityContainerBuilder<Vec<(UpsertValue, T, Diff)>>>>;
135
136/// Transforms a stream of upserts (key-value updates) into a differential
137/// collection.
138///
139/// Persist feedback is arranged into a differential trace (DD manages the
140/// spine lifecycle). Source input is stashed with a custom `UpsertDiff`
141/// Semigroup that deduplicates by keeping the highest FromTime per (key, time).
142///
143/// Has two inputs:
144/// 1. **Source input** — upsert commands from the external source.
145/// 2. **Persist input** — feedback of the operator's own output, read back
146/// from persist. Arranged into a trace for prior-value lookups.
147///
148/// Source statistics stop once `stats_shutdown` reports its button pressed
149/// on this worker. The caller holds that button with the ingestion's tokens.
150#[allow(clippy::disallowed_methods)]
151pub fn upsert_inner<'scope, T, FromTime>(
152 input: VecCollection<'scope, T, (UpsertKey, Option<UpsertValue>, FromTime), Diff>,
153 key_indices: Vec<usize>,
154 resume_upper: Antichain<T>,
155 persist_ok: VecCollection<'scope, T, Row, Diff>,
156 persist_err: VecCollection<'scope, T, DataflowError, Diff>,
157 persist_token: Option<Vec<PressOnDropButton>>,
158 upsert_metrics: UpsertMetrics,
159 source_config: crate::source::SourceExportCreationConfig,
160 stats_shutdown: ButtonHandle,
161) -> (
162 VecCollection<'scope, T, Result<Row, DataflowError>, Diff>,
163 StreamVec<'scope, T, (Option<GlobalId>, HealthStatusUpdate)>,
164 StreamVec<'scope, T, Infallible>,
165 PressOnDropButton,
166)
167where
168 T: Timestamp + TotalOrder + Sync,
169 T: Refines<mz_repr::Timestamp> + differential_dataflow::lattice::Lattice,
170 T: columnation::Columnation,
171 T: mz_timely_util::columnar::chunk::PoolColumnar + Default,
172 for<'a> columnar::Ref<'a, T>: Copy + Ord,
173 FromTime: Debug + timely::ExchangeData + Clone + Ord + Sync,
174 FromTime: UpsertSourceTime,
175{
176 let encoded = encode_feedback(
177 persist_ok,
178 persist_err,
179 key_indices,
180 source_config.source_statistics.clone(),
181 stats_shutdown,
182 );
183 // Chains and sealed batches alike are `FeedbackChunk`s whose bodies spill
184 // to the buffer pool, behind the same storage spill gate as the source
185 // stash.
186 let persist_arranged = arrange_core::<
187 _,
188 _,
189 ChunkBatcher<ChunkChunker<(UpsertKey, Row), T, Diff, StorageSpill>, FeedbackChunk<T>>,
190 FeedbackSpine<T>,
191 >(encoded, Pipeline, "Persist feedback", MergeBatcher::new);
192 build_upsert_operator::<ChunkedArm, _, _>(
193 input,
194 resume_upper,
195 persist_arranged,
196 persist_token,
197 upsert_metrics,
198 source_config,
199 )
200}
201
202/// The upsert-v2 operator loop, generic over an [`UpsertStashArm`].
203///
204/// Consumes the source input and the arranged persist feedback (constructed
205/// by [`upsert_inner`]) and drives the ingest / seal / drain / capability
206/// loop described in the module docs, calling through the arm for the stash
207/// and the drain.
208#[allow(clippy::disallowed_methods)]
209fn build_upsert_operator<'scope, A, T, FromTime>(
210 input: VecCollection<'scope, T, (UpsertKey, Option<UpsertValue>, FromTime), Diff>,
211 resume_upper: Antichain<T>,
212 persist_arranged: Arranged<'scope, TraceAgent<A::Spine>>,
213 persist_token: Option<Vec<PressOnDropButton>>,
214 upsert_metrics: UpsertMetrics,
215 source_config: crate::source::SourceExportCreationConfig,
216) -> (
217 VecCollection<'scope, T, Result<Row, DataflowError>, Diff>,
218 StreamVec<'scope, T, (Option<GlobalId>, HealthStatusUpdate)>,
219 StreamVec<'scope, T, Infallible>,
220 PressOnDropButton,
221)
222where
223 A: UpsertStashArm<T, FromTime::Order>,
224 T: Timestamp + TotalOrder + Sync,
225 T: Refines<mz_repr::Timestamp> + differential_dataflow::lattice::Lattice,
226 T: columnation::Columnation,
227 T: mz_timely_util::columnar::chunk::PoolColumnar + Default,
228 for<'a> columnar::Ref<'a, T>: Copy + Ord,
229 FromTime: Debug + timely::ExchangeData + Clone + Ord + Sync,
230 FromTime: UpsertSourceTime,
231{
232 let mut persist_trace = persist_arranged.trace.clone();
233
234 // Probe the persist arrangement's stream for frontier tracking.
235 // This replaces receiving the batch stream as an input — we just
236 // read the probe frontier to know when persist has caught up.
237 use timely::dataflow::operators::Probe;
238 let (persist_probe, _persist_probe_stream) = persist_arranged.stream.probe();
239
240 // Build the async processing operator.
241 let mut builder = AsyncOperatorBuilder::new("Upsert V2".to_string(), input.scope());
242
243 let (output_handle, output) = builder
244 .new_output::<FueledBuilder<CapacityContainerBuilder<Vec<(UpsertValue, T, Diff)>>>>();
245 let (_snapshot_handle, snapshot_stream) =
246 builder.new_output::<CapacityContainerBuilder<Vec<Infallible>>>();
247 let (_health_output, health_stream) = builder
248 .new_output::<CapacityContainerBuilder<Vec<(Option<GlobalId>, HealthStatusUpdate)>>>();
249
250 let mut input = builder.new_input_for(
251 input.inner,
252 Exchange::new(move |((key, _, _), _, _)| UpsertKey::hashed(key)),
253 &output_handle,
254 );
255
256 // We still need the persist stream as an input so the operator wakes
257 // when the persist arrangement produces batches (frontier advances).
258 // We read the actual frontier from the probe though.
259 let mut persist_wakeup = builder.new_disconnected_input(_persist_probe_stream, Pipeline);
260
261 let shutdown_button = builder.build(move |caps| async move {
262 // Hold the persist source tokens for the operator's lifetime so the
263 // feedback shard stays open until shutdown.
264 let _persist_token = persist_token;
265
266 let [output_cap, snapshot_cap, _health_cap]: [_; 3] = caps.try_into().unwrap();
267 drop(output_cap);
268 let mut snapshot_cap = CapabilitySet::from_elem(snapshot_cap);
269
270 let mut hydrating = true;
271
272 // Source stash. The batcher maintains geometrically-sized sorted
273 // chains and consolidates via the UpsertDiff Semigroup as data is
274 // pushed in, bounding memory to O(unique key-time pairs) even during
275 // large initial snapshots.
276 let mut batcher = A::new_batcher();
277 // The chunker sorts and consolidates raw input into the chunks the
278 // batcher consumes.
279 let mut chunker = A::Chunker::default();
280 // Scratch buffer for accumulating source events before flushing to
281 // the batcher. Drained on each iteration via the chunker.
282 let mut push_buffer: Vec<UpsertUpdate<T, FromTime::Order>> = Vec::new();
283
284 // Capability held at the minimum time of any buffered data. When
285 // Some, the operator may still produce output; when None, the
286 // batcher is empty.
287 let mut stash_cap: Option<Capability<T>> = None;
288 let mut input_upper = Antichain::from_elem(Timestamp::minimum());
289
290 let snapshot_start = std::time::Instant::now();
291 let mut prev_persist_upper = Antichain::from_elem(Timestamp::minimum());
292
293 // Accumulators for rehydration metrics, set as gauges when rehydration completes.
294 let mut rehydration_total: u64 = 0;
295 let mut rehydration_updates: u64 = 0;
296
297 // Main operator loop. Each iteration performs four steps:
298 // Step 1: Ingest source data into the batcher.
299 // Step 2: Read the persist frontier and update rehydration state.
300 // Step 3: Extract from the batcher, drain eligible entries, push back the rest.
301 // Step 4: Manage the output capability.
302 loop {
303 // Block until woken by source input or a persist frontier advance.
304 tokio::select! {
305 _ = input.ready() => {}
306 _ = persist_wakeup.ready() => {
307 while let Some(event) = persist_wakeup.next_sync() {
308 if let AsyncEvent::Data(_, batches) = event {
309 for batch in batches {
310 mz_timely_util::columnar::chunk::metrics::record_batch(
311 batch.inner.as_ref().map_or(0, SpineBatch::len),
312 );
313 }
314 }
315 }
316 }
317 }
318
319 // Step 1: Ingest source data.
320 // Read all available source events, wrap each value in an
321 // UpsertDiff (carrying FromTime for dedup), and buffer them.
322 // Events before the resume_upper are dropped (already persisted).
323 while let Some(event) = input.next_sync() {
324 match event {
325 AsyncEvent::Data(cap, data) => {
326 let cap = sole_capability(&cap).clone();
327 let mut pushed_any = false;
328 for ((key, value, from_time), ts, diff) in data {
329 assert!(diff.is_positive(), "invalid upsert input");
330 if PartialOrder::less_equal(&input_upper, &resume_upper)
331 && !resume_upper.less_equal(&ts)
332 {
333 continue;
334 }
335 let value = value.as_ref().map(upsert_value_to_row);
336 let from_time = from_time.upsert_order();
337 push_buffer.push((key, ts, UpsertDiff { from_time, value }));
338 pushed_any = true;
339 }
340 // Track the minimum capability across all buffered data
341 // so we can emit output at the correct times.
342 if pushed_any {
343 stash_cap = Some(match stash_cap {
344 Some(prev) if cap.time() < prev.time() => cap,
345 Some(prev) => prev,
346 None => cap,
347 });
348 }
349 }
350 AsyncEvent::Progress(upper) => {
351 if PartialOrder::less_than(&upper, &resume_upper) {
352 continue;
353 }
354 input_upper = upper;
355 }
356 }
357 }
358
359 // Flush buffered events through the chunker into the batcher. This
360 // triggers the chunker + geometric chain merging, which consolidates
361 // entries for the same (key, time) via the UpsertDiff Semigroup.
362 A::flush(&mut push_buffer, &mut chunker, &mut batcher);
363
364 // Step 2: Read persist frontier.
365 // The persist probe tells us which output times have been
366 // committed back through the feedback loop. This determines:
367 // - Whether rehydration is complete (persist >= resume_upper).
368 // - Which source entries are eligible for processing (their
369 // time must equal persist_upper so the feedback trace holds
370 // the correct prior state).
371 // - How far to compact the persist trace.
372 let persist_upper = persist_probe.with_frontier(|f| f.to_owned());
373
374 if persist_upper != prev_persist_upper {
375 let last_rehydration_chunk =
376 hydrating && PartialOrder::less_equal(&resume_upper, &persist_upper);
377
378 if last_rehydration_chunk {
379 hydrating = false;
380 upsert_metrics
381 .rehydration_latency
382 .set(snapshot_start.elapsed().as_secs_f64());
383 upsert_metrics.rehydration_total.set(rehydration_total);
384 upsert_metrics.rehydration_updates.set(rehydration_updates);
385 tracing::info!(
386 worker_id = %source_config.worker_id,
387 source_id = %source_config.id,
388 "upsert finished rehydration",
389 );
390 snapshot_cap.downgrade(&[]);
391 }
392
393 let _ = snapshot_cap.try_downgrade(persist_upper.iter());
394
395 // Compact the trace so the spine can merge old batches.
396 persist_trace.set_logical_compaction(persist_upper.borrow());
397 persist_trace.set_physical_compaction(persist_upper.borrow());
398
399 prev_persist_upper = persist_upper.clone();
400 }
401
402 // Step 3: Extract & drain.
403 // Extract from the batcher at `seal_upper`, just past
404 // persist_upper and at most input_upper, all source-finalized
405 // entries as sorted, consolidated chunks. The extract merges all
406 // internal chains and splits by time: entries below the extract
407 // upper are extracted, the rest stay in the batcher.
408 //
409 // Extracted entries are partitioned into:
410 // - Eligible (ts == persist_upper): processed now via a
411 // prior-value lookup in the persist trace.
412 // - Ineligible (persist_upper < ts < extract upper): persist
413 // hasn't caught up yet, so pushed back into the batcher.
414 //
415 // We skip the extract entirely unless an eligible entry is at all
416 // possible. `extract` merges all chains regardless of how much it
417 // extracts, so calling it when nothing can be processed makes
418 // the operator quadratic in the number of wakeups (a real
419 // pathology during upstream snapshots and during rehydration
420 // when the source races ahead of persist).
421 //
422 // For an entry at `ts` to be eligible we need
423 // `ts == persist_upper && ts < input_upper`. The necessary
424 // preconditions, expressible without scanning the batcher:
425 // 1. `cap.time() <= persist_upper`. Since `cap.time()` is
426 // maintained as a lower bound on `min(ts in batcher)`, if
427 // `cap.time() > persist_upper` then every buffered ts is
428 // strictly above persist_upper and none can equal it.
429 // 2. `persist_upper < input_upper`. Otherwise no `ts` that
430 // satisfies `ts == persist_upper` can also satisfy
431 // `ts < input_upper`.
432 //
433 // This naturally covers both the post-hydration source-snapshot
434 // case (cap == persist == input → condition 2 fails) and the
435 // rehydration-with-source-ahead case (cap > persist → condition
436 // 1 fails). It also no-ops correctly when persist has shut down
437 // (empty persist_upper makes condition 2 vacuously false).
438 if let Some(cap) = stash_cap.as_mut()
439 && !persist_upper.less_than(cap.time())
440 && PartialOrder::less_than(&persist_upper, &input_upper)
441 {
442 // Step 1 already consolidated `push_buffer` through the chunker
443 // (which readies a complete chunk per `push_into`) and pushed
444 // those chunks into the batcher, so we can extract directly.
445 // `remaining_frontier` bounds the data left behind (ts >= the
446 // extract upper).
447 let (sealed, remaining_frontier) = A::extract(
448 &mut batcher,
449 seal_upper(&persist_upper, &input_upper).borrow(),
450 );
451
452 let mut ineligible = Vec::new();
453 // The drain emits eligible output directly through
454 // `output_handle` (fueled), so there is no intermediate
455 // output buffer to drain afterward.
456 let drain_stats = A::drain(
457 sealed,
458 &mut ineligible,
459 &output_handle,
460 &*cap,
461 &persist_upper,
462 &mut persist_trace,
463 source_config.worker_id,
464 source_config.id,
465 )
466 .await;
467
468 upsert_metrics.multi_get_size.inc_by(drain_stats.eligible);
469 upsert_metrics
470 .multi_get_result_count
471 .inc_by(drain_stats.result_count);
472 upsert_metrics
473 .multi_put_size
474 .inc_by(drain_stats.output_count);
475 upsert_metrics.upsert_inserts.inc_by(drain_stats.inserts);
476 upsert_metrics.upsert_updates.inc_by(drain_stats.updates);
477 upsert_metrics.upsert_deletes.inc_by(drain_stats.deletes);
478 upsert_metrics
479 .restashed
480 .inc_by(u64::cast_from(ineligible.len()));
481
482 if hydrating {
483 rehydration_total += drain_stats.inserts;
484 rehydration_updates += drain_stats.eligible;
485 }
486
487 // Step 4: Capability management.
488 // Downgrade the output capability to the minimum time of any
489 // remaining data: either entries still in the batcher (at or
490 // above the seal upper) or ineligible entries being pushed back.
491 let min_ineligible_ts = ineligible.iter().map(|(_, ts, _)| ts).min().cloned();
492 A::flush(&mut ineligible, &mut chunker, &mut batcher);
493
494 // `Option::min` alone would be wrong here, `None` sorts low.
495 // Chain the candidates and take the min over present ones.
496 let min_ts = remaining_frontier
497 .elements()
498 .first()
499 .into_iter()
500 .chain(min_ineligible_ts.as_ref())
501 .min();
502 match min_ts {
503 Some(min_ts) => cap.downgrade(min_ts),
504 // Batcher is completely empty. Drop the capability so
505 // downstream operators can make progress.
506 None => stash_cap = None,
507 }
508 }
509
510 if input_upper.is_empty() {
511 break;
512 }
513 }
514 });
515
516 (
517 output
518 .as_collection()
519 .map(|result: UpsertValue| match result {
520 Ok(ok) => Ok(ok),
521 Err(err) => Err(DataflowError::from(EnvelopeError::Upsert(*err))),
522 }),
523 health_stream,
524 snapshot_stream,
525 shutdown_button.press_on_drop(),
526 )
527}