mz_storage/upsert_continual_feedback_v2/stash.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//! The upsert-v2 source stash: the consolidating diff, the stash batcher
11//! types, and the [`UpsertStashArm`].
12
13use differential_dataflow::batcher::Extract;
14use differential_dataflow::difference::{IsZero, Semigroup};
15use differential_dataflow::lattice::Lattice;
16use differential_dataflow::operators::arrange::agent::TraceAgent;
17use differential_dataflow::trace::TraceReader;
18use differential_dataflow::trace::chunk::ChunkMerger;
19use differential_dataflow::trace::implementations::spine_fueled::SpineBatch;
20use mz_repr::{GlobalId, Row};
21use mz_timely_util::columnar::Column;
22use mz_timely_util::columnar::batcher::ColumnChunker;
23use mz_timely_util::columnar::chunk::{ChunkChunker, ColumnChunk, StorageSpill};
24use mz_timely_util::operator::ConsolidatingBatcher;
25use timely::container::{ContainerBuilder, PushInto};
26use timely::dataflow::operators::Capability;
27use timely::order::TotalOrder;
28use timely::progress::frontier::AntichainRef;
29use timely::progress::timestamp::Refines;
30use timely::progress::{Antichain, Timestamp};
31
32use super::UpsertOutputHandle;
33use super::drain::{DrainStats, drain_sealed_input_chunked};
34use super::feedback::FeedbackSpine;
35use crate::upsert::UpsertKey;
36
37// The source stash carries the upsert payload in a custom diff type so the
38// merge batcher consolidates by (key, time), keeping the update with the
39// highest `FromTime` (latest source offset) per group. The diff is `Columnar`
40// so the stash batcher can store it in a `Column` chunk.
41//
42// The value is a tag-encoded `Row` (see `upsert_value_to_row`) rather than an
43// `UpsertValue`: folding both the `Ok` and `Err` arms into one `Row` lets the
44// value share a single columnar byte container, and `Row` already implements
45// `Columnar`. `None` is a deletion tombstone.
46
47// Derive ordering on the generated `UpsertDiffReference` too: the stash
48// batcher requires `Ref: Ord` to sort the `(key, time, diff)` columns it
49// consolidates. The derived order (by `from_time`, then `value`) is fine —
50// "max FromTime wins" can tie only between equal `from_time`s, and a source
51// never emits two distinct values for the same `(key, time, from_time)`, so
52// the consolidated result doesn't depend on the fold order of equal
53// `(key, time)` runs.
54#[derive(Clone, Debug, Default, columnar::Columnar)]
55#[columnar(derive(PartialEq, Eq, PartialOrd, Ord))]
56pub(super) struct UpsertDiff<O> {
57 pub(super) from_time: O,
58 pub(super) value: Option<Row>,
59}
60
61impl<O> IsZero for UpsertDiff<O> {
62 fn is_zero(&self) -> bool {
63 false
64 }
65}
66
67impl<O: Ord + Clone> Semigroup for UpsertDiff<O> {
68 fn plus_equals(&mut self, rhs: &Self) {
69 if rhs.from_time > self.from_time {
70 *self = rhs.clone();
71 }
72 }
73}
74
75// Accumulate a borrowed columnar reference: the stash batcher consolidates
76// `Column`-resident diffs through this path on every fold of an equal
77// `(key, time)` run. Materialize only the order key to decide the "max FromTime
78// wins" comparison — copying the value `Row` out of the column solely when `rhs`
79// wins. Losing folds (the common case for a repeatedly-updated key) then pay no
80// `Row` copy at all.
81impl<'a, O> Semigroup<columnar::Ref<'a, UpsertDiff<O>>> for UpsertDiff<O>
82where
83 O: columnar::Columnar + Ord + Clone,
84{
85 fn plus_equals(&mut self, rhs: &columnar::Ref<'a, UpsertDiff<O>>) {
86 let rhs_from_time = <O as columnar::Columnar>::into_owned(rhs.from_time);
87 if rhs_from_time > self.from_time {
88 self.from_time = rhs_from_time;
89 self.value = <Option<Row> as columnar::Columnar>::into_owned(rhs.value);
90 }
91 }
92}
93
94/// One source-stash update: a key, its dataflow time, and the payload diff.
95/// `O` is the columnar order key projected from the source `FromTime` (see
96/// [`UpsertSourceTime`](crate::upsert::UpsertSourceTime)).
97pub(super) type UpsertUpdate<T, O> = (UpsertKey, T, UpsertDiff<O>);
98
99/// One chunked-flavor stash update: [`UpsertUpdate`] with the time copied
100/// into the data, so the batcher sorts by `(time, key)`.
101///
102/// A seal at an upper then cuts a prefix of the batcher's chains. Its extract
103/// passes chunks wholly on either side of the upper through by their time
104/// bounds, so it rewrites only the chunk the upper splits. Its merges pass
105/// chunks through when their data ranges are disjoint, which holds between
106/// chains at different times, so data at a later time does not rewrite the
107/// stashed backlog; data at the same time merges as in any batcher (see
108/// [`ChunkedArm`] for what a pass-through still costs). Sorted by key, every
109/// chunk spans the stash's whole time range, so each seal would load and
110/// rewrite every chunk, which makes catching up on a tail of `n` timestamps
111/// quadratic in the tail. Within one time, entries stay sorted by key, which
112/// the drain's monotone probes rely on.
113pub(super) type TimeMajorUpdate<T, O> = ((T, UpsertKey), T, UpsertDiff<O>);
114
115/// One chunked-flavor stash chunk: a sorted, consolidated run of time-major
116/// updates, resident or spilled to the buffer pool.
117type UpsertChunk<T, O> = ColumnChunk<(T, UpsertKey), T, UpsertDiff<O>, StorageSpill>;
118
119/// The chunked flavor's stash: differential's chunk merge batcher over
120/// `ColumnChunk`s. Data is pushed in unsorted. The batcher maintains
121/// geometrically-sized sorted chains and consolidates via the UpsertDiff
122/// Semigroup automatically. Committed chunks spill their bodies to the
123/// process buffer pool (see `mz_timely_util::columnar::chunk`), so the
124/// not-yet-eligible backlog (the snapshot / persist-lag window) pages out of
125/// RSS instead of growing it.
126type UpsertChunkBatcher<T, O> = ConsolidatingBatcher<
127 ChunkChunker<(T, UpsertKey), T, UpsertDiff<O>, StorageSpill>,
128 ChunkMerger<UpsertChunk<T, O>>,
129>;
130
131/// The chunker that sorts and consolidates raw input into the time-major
132/// `Column` chunks the stash batcher consumes.
133type TimeMajorChunker<T, O> = ColumnChunker<TimeMajorUpdate<T, O>>;
134
135/// The start of the `mz_repr::Timestamp` after `persist_upper`'s, capped at
136/// `input_upper` so no unfinalized time is extracted.
137///
138/// Only entries at `persist_upper` are eligible in a round, and the drain
139/// returns every extracted entry past `persist_upper` as a resident `Vec`,
140/// outside the buffer pool budget, to be re-pushed through the chunker.
141/// Sealing at `input_upper` instead would do that for the whole backlog
142/// between the two frontiers once per persist round trip, which is the entire
143/// source tail while the operator catches up from behind.
144pub(super) fn seal_upper<T>(
145 persist_upper: &Antichain<T>,
146 input_upper: &Antichain<T>,
147) -> Antichain<T>
148where
149 T: Timestamp + TotalOrder + Refines<mz_repr::Timestamp>,
150{
151 match persist_upper.as_option().and_then(next_outer) {
152 Some(next) if !input_upper.less_equal(&next) => Antichain::from_elem(next),
153 _ => input_upper.clone(),
154 }
155}
156
157/// The least time past every time sharing `ts`'s `mz_repr::Timestamp`, or
158/// `None` when that timestamp is the maximum.
159fn next_outer<T: Refines<mz_repr::Timestamp>>(ts: &T) -> Option<T> {
160 ts.clone().to_outer().try_step_forward().map(T::to_inner)
161}
162
163/// The pieces of the upsert-v2 operator that depend on the stash
164/// representation: the stash batcher, the feedback arrangement's spine, and
165/// how the drain reads prior state.
166/// [`build_upsert_operator`](super::build_upsert_operator) holds the operator
167/// loop and calls through this trait at those points.
168pub(super) trait UpsertStashArm<T, O>
169where
170 T: Timestamp + Lattice + mz_timely_util::columnar::chunk::PoolColumnar + Default,
171 for<'a> columnar::Ref<'a, T>: Copy + Ord,
172 O: mz_timely_util::columnar::chunk::PoolColumnar
173 + Default
174 + Ord
175 + Clone
176 + Send
177 + Sync
178 + 'static,
179 for<'a> columnar::Ref<'a, O>: Ord + Copy,
180{
181 /// The feedback arrangement's spine. `'static` because the operator
182 /// future owns a trace agent for it.
183 type Spine: TraceReader<Time = T, Batch: SpineBatch> + 'static;
184 /// The source-stash batcher. `'static` because the operator future owns
185 /// it.
186 type Batcher: 'static;
187 /// The chunk representation the stash batcher accumulates into.
188 type Chunk;
189
190 /// Sorts and consolidates raw updates into the batcher's chunks.
191 type Chunker: Default + 'static;
192
193 /// A new stash batcher for one source dataflow.
194 fn new_batcher() -> Self::Batcher;
195
196 /// Carve the chain of updates `upper` unblocks out of the stash.
197 ///
198 /// Returns the chunks and a lower bound on the times of what stays behind. The stash keeps
199 /// the chunks as they are: a caller that wanted a trace batch would have to take it apart
200 /// again.
201 fn extract(
202 batcher: &mut Self::Batcher,
203 upper: AntichainRef<T>,
204 ) -> (Vec<Self::Chunk>, Antichain<T>);
205
206 /// Consolidate `updates` through `chunker` into chunks and push them into
207 /// `batcher`, emptying `updates` (keeping its capacity). The chunker
208 /// readies a fully-consolidated chunk per `push_into`, so nothing stays
209 /// pending in it between calls.
210 fn flush(
211 updates: &mut Vec<UpsertUpdate<T, O>>,
212 chunker: &mut Self::Chunker,
213 batcher: &mut Self::Batcher,
214 );
215
216 /// Classify one sealed stash against `persist_upper` and emit eligible
217 /// output; see [`DrainStats`].
218 async fn drain(
219 sealed: Vec<Self::Chunk>,
220 ineligible: &mut Vec<UpsertUpdate<T, O>>,
221 output_handle: &UpsertOutputHandle<T>,
222 output_cap: &Capability<T>,
223 persist_upper: &Antichain<T>,
224 trace: &mut TraceAgent<Self::Spine>,
225 worker_id: usize,
226 source_id: GlobalId,
227 ) -> DrainStats;
228}
229
230/// The shared body of the arms' `flush`: writes each update into a raw
231/// column through `record`, consolidates it through `chunker`, and hands each
232/// readied chunk to `push`.
233fn flush_through<T, O, U, C>(
234 updates: &mut Vec<UpsertUpdate<T, O>>,
235 chunker: &mut C,
236 mut record: impl FnMut(UpsertUpdate<T, O>, &mut Column<U>),
237 mut push: impl FnMut(C::Container),
238) where
239 U: columnar::Columnar,
240 C: ContainerBuilder + for<'a> PushInto<&'a mut Column<U>>,
241 C::Container: Default,
242{
243 if updates.is_empty() {
244 return;
245 }
246 let mut raw: Column<U> = Default::default();
247 for update in updates.drain(..) {
248 record(update, &mut raw);
249 }
250 chunker.push_into(&mut raw);
251 while let Some(chunk) = chunker.extract() {
252 push(std::mem::take(chunk));
253 }
254}
255
256/// The chunked flavor: time-major [`UpsertChunkBatcher`] stash,
257/// [`FeedbackSpine`] feedback arrangement, bulk-probe drain.
258///
259/// NOTE: the seal's chain merge loads the bodies of the chunks it actually
260/// merges. Chunks whose data ranges are disjoint pass through, and the
261/// partition against the upper passes chunks wholly on one side of it
262/// through, so only chunks the upper splits are rewritten (see
263/// [`TimeMajorUpdate`]). Two costs remain per seal. A spilled body that ages
264/// to `compress_min_depth` through a pass-through is loaded once and
265/// re-spilled compressed. A resident chunk's time bounds are recomputed by
266/// scanning its time column, so with spilling off a seal still reads every
267/// stashed time. The drain then loads sealed chunks one at a time, so a large
268/// drain (a frontier advance releasing a snapshot's worth of stash at once)
269/// holds at most one chunk resident rather than the whole backlog.
270pub(super) struct ChunkedArm;
271
272impl<T, O> UpsertStashArm<T, O> for ChunkedArm
273where
274 T: Timestamp + TotalOrder + Lattice + Sync,
275 T: columnation::Columnation + mz_timely_util::columnar::chunk::PoolColumnar + Default,
276 for<'a> columnar::Ref<'a, T>: Copy + Ord,
277 O: mz_timely_util::columnar::chunk::PoolColumnar
278 + Default
279 + Ord
280 + Clone
281 + Send
282 + Sync
283 + 'static,
284 for<'a> columnar::Ref<'a, O>: Ord + Copy,
285{
286 type Spine = FeedbackSpine<T>;
287 type Batcher = UpsertChunkBatcher<T, O>;
288 type Chunk = UpsertChunk<T, O>;
289 type Chunker = TimeMajorChunker<T, O>;
290
291 fn new_batcher() -> Self::Batcher {
292 ConsolidatingBatcher::new(None, 0)
293 }
294
295 fn extract(
296 batcher: &mut Self::Batcher,
297 upper: AntichainRef<T>,
298 ) -> (Vec<Self::Chunk>, Antichain<T>) {
299 let (chain, frontier) = batcher.extract(upper);
300 (chain.unwrap_or_default(), frontier.to_owned())
301 }
302
303 fn flush(
304 updates: &mut Vec<UpsertUpdate<T, O>>,
305 chunker: &mut Self::Chunker,
306 batcher: &mut Self::Batcher,
307 ) {
308 flush_through(
309 updates,
310 chunker,
311 |(key, ts, diff), raw| raw.push_into(&((ts.clone(), key), ts, diff)),
312 |chunk| batcher.push_chunk(ColumnChunk::from_body(chunk)),
313 );
314 }
315
316 async fn drain(
317 sealed: Vec<UpsertChunk<T, O>>,
318 ineligible: &mut Vec<UpsertUpdate<T, O>>,
319 output_handle: &UpsertOutputHandle<T>,
320 output_cap: &Capability<T>,
321 persist_upper: &Antichain<T>,
322 trace: &mut TraceAgent<Self::Spine>,
323 worker_id: usize,
324 source_id: GlobalId,
325 ) -> DrainStats {
326 drain_sealed_input_chunked(
327 sealed.into_iter().map(ColumnChunk::into_body),
328 ineligible,
329 output_handle,
330 output_cap,
331 persist_upper,
332 trace,
333 worker_id,
334 source_id,
335 )
336 .await
337 }
338}