Skip to main content

mz_storage/upsert_continual_feedback_v2/
drain.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//! Draining sealed stash chunks against the persist feedback.
11
12use differential_dataflow::lattice::Lattice;
13use differential_dataflow::operators::arrange::agent::TraceAgent;
14use differential_dataflow::trace::TraceReader;
15use mz_repr::{Diff, GlobalId};
16use mz_timely_util::columnar::body::ColumnBody;
17use mz_timely_util::columnar::unload::UnloadBatch;
18use timely::dataflow::operators::Capability;
19use timely::order::{PartialOrder, TotalOrder};
20use timely::progress::{Antichain, Timestamp};
21
22use super::UpsertOutputHandle;
23use super::feedback::{FeedbackSpine, FeedbackUpdate, decode_upsert_value, upsert_value_byte_len};
24use super::stash::{TimeMajorUpdate, UpsertDiff, UpsertUpdate};
25use crate::upsert::{UpsertKey, UpsertValue};
26
27/// Where a stashed entry's time falls relative to the feedback frontier.
28enum TimeClass {
29    /// `ts < persist_upper`: already persisted, dropped by the drain.
30    AlreadyPersisted,
31    /// `ts == persist_upper`: processed now.
32    Eligible,
33    /// `ts > persist_upper`: re-stashed until persist catches up.
34    Ineligible,
35}
36
37/// Classify `ts` against `persist_upper`: the single spelling of the drain's
38/// eligibility test. The chunked drain's probe-collection pass and its
39/// classification pass both call this, so the probe set and the
40/// classification cannot disagree. Under the
41/// operator's total order, `Eligible` means `ts` equals the frontier's one
42/// element.
43fn classify_time<T: PartialOrder>(persist_upper: &Antichain<T>, ts: &T) -> TimeClass {
44    if !persist_upper.less_equal(ts) {
45        TimeClass::AlreadyPersisted
46    } else if persist_upper.less_than(ts) {
47        TimeClass::Ineligible
48    } else {
49        TimeClass::Eligible
50    }
51}
52
53/// Counts from a single call to [`drain_sealed_input_chunked`], used to
54/// update metrics.
55pub(super) struct DrainStats {
56    /// Number of eligible entries probed against the feedback trace.
57    pub(super) eligible: u64,
58    /// Number of probed entries for which a prior value was found.
59    pub(super) result_count: u64,
60    /// New value written with no prior value (insert).
61    pub(super) inserts: u64,
62    /// New value written over an existing value (update).
63    pub(super) updates: u64,
64    /// Tombstone (None) applied to an existing value (delete).
65    pub(super) deletes: u64,
66    /// Total output records emitted (retractions + insertions).
67    pub(super) output_count: u64,
68}
69
70/// Process sealed chunks from the batcher, classifying each entry by its
71/// timestamp relative to `persist_upper`:
72///
73///   * `ts == persist_upper`: eligible for processing now (bulk probe of the
74///     feedback trace + output).
75///   * `ts >  persist_upper`: not yet processable. Returned in `ineligible`
76///     for re-stashing until the feedback frontier catches up to it.
77///   * `ts <  persist_upper`: already persisted by some writer and not
78///     relevant anymore, so DROPPED. The downstream persist_sink would filter
79///     such updates out anyway since the shard upper is further ahead, and
80///     our state is already up-to-date to `persist_upper` so we could not
81///     emit correct retractions for it. Re-stashing it would strand the data
82///     forever (`persist_upper` only advances, so `ts == persist_upper` can
83///     never again hold) and pin the operator's output frontier below the
84///     shard upper. This mirrors v1's `relevant = persist_upper.less_equal(ts)`.
85///
86/// The sealed chunks are already sorted and consolidated by the merge
87/// batcher, so each chunk's eligible keys form a sorted, deduplicated probe
88/// set, and the prior state comes back through one bulk `extract_into` pass
89/// per trace batch. Resident fence metadata selects the touched trace
90/// chunks, and only those bodies are read back, copy-out, per chunk probed.
91/// Sealed chunks are pulled from the iterator one at a time and dropped
92/// before the next is requested, so at most one loaded stash chunk (plus the
93/// probe hits for its keys) is resident regardless of drain size. Only the
94/// re-stashed ineligible set is materialized.
95pub(super) async fn drain_sealed_input_chunked<T, O>(
96    sealed: impl Iterator<Item = ColumnBody<TimeMajorUpdate<T, O>>>,
97    ineligible: &mut Vec<UpsertUpdate<T, O>>,
98    output_handle: &UpsertOutputHandle<T>,
99    output_cap: &Capability<T>,
100    persist_upper: &Antichain<T>,
101    trace: &mut TraceAgent<FeedbackSpine<T>>,
102    worker_id: usize,
103    source_id: GlobalId,
104) -> DrainStats
105where
106    T: Timestamp + TotalOrder + Lattice + Sync,
107    T: columnation::Columnation + mz_timely_util::columnar::chunk::PoolColumnar + Default,
108    for<'a> columnar::Ref<'a, T>: Copy + Ord,
109    O: mz_timely_util::columnar::chunk::PoolColumnar,
110{
111    let mut eligible_count: u64 = 0;
112    let mut result_count: u64 = 0;
113    let mut output_count: u64 = 0;
114    let mut inserts: u64 = 0;
115    let mut updates: u64 = 0;
116    let mut deletes: u64 = 0;
117
118    // The batches this drain reads against. `Rc` clones of the trace's
119    // sealed chunk batches: chunk bodies stay spilled and are read back
120    // copy-out, per probed chunk, inside `extract_into`.
121    let batches = trace
122        .batches_through(Antichain::new().borrow())
123        .expect("complete batch set for the feedback trace; is it closed?");
124
125    // Eligible keys are probed against the trace in windows of this many
126    // distinct keys, bounding what one pass stages resident: probe hits carry
127    // full values, so an unwindowed pass over a byte-graded chunk of small
128    // records could stage tens of thousands of values at once.
129    const PROBE_WINDOW: usize = 1024;
130
131    for chunk in sealed {
132        use columnar::{Index, Len};
133        let view = chunk.borrow();
134        let total = view.len();
135        let mut start = 0;
136        while start < total {
137            // Pass 1: this window's sorted, deduplicated probe keys. The
138            // chunk is sorted by (time, key) and eligible entries share one
139            // time, so they are contiguous and key-sorted: a window is a
140            // contiguous record range, probes come out sorted, and dedup is
141            // a neighbor test. The window closes where its PROBE_WINDOW + 1st
142            // distinct eligible key would begin.
143            let mut probe_col = <UpsertKey as columnar::Columnar>::Container::default();
144            let mut probe_count = 0usize;
145            let mut end = total;
146            {
147                use columnar::Push;
148                let mut last_probe: Option<&UpsertKey> = None;
149                for index in start..total {
150                    let ((_, key), ts, _diff) = view.get(index);
151                    let ts = <T as columnar::Columnar>::into_owned(ts);
152                    if matches!(classify_time(persist_upper, &ts), TimeClass::Eligible) {
153                        if last_probe != Some(key) {
154                            if probe_count == PROBE_WINDOW {
155                                end = index;
156                                break;
157                            }
158                            probe_col.push(key);
159                            probe_count += 1;
160                            last_probe = Some(key);
161                        }
162                    }
163                }
164            }
165
166            // Pass 2: bulk-probe the trace's batches through the chunk
167            // batches' `UnloadChunk` surface and consolidate the hits into
168            // the prior value per key. Hits arrive per batch, so equal
169            // `(key, val)` pairs from different batches are non-adjacent.
170            // Sort before folding.
171            let mut old_values: std::collections::BTreeMap<UpsertKey, UpsertValue> =
172                std::collections::BTreeMap::new();
173            if probe_count > 0 {
174                use columnar::Borrow;
175                let mut staging = <FeedbackUpdate<T> as columnar::Columnar>::Container::default();
176                for batch in &batches {
177                    batch.extract_into(probe_col.borrow(), &mut staging);
178                }
179                let staged = staging.borrow();
180                let mut hits: Vec<_> = (0..staged.len())
181                    .map(|i| {
182                        let ((key, val), _time, diff) = staged.get(i);
183                        (key, val, <Diff as columnar::Columnar>::into_owned(diff))
184                    })
185                    .collect();
186                hits.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));
187                let mut i = 0;
188                while i < hits.len() {
189                    let (key, val, _) = hits[i];
190                    let mut count = Diff::ZERO;
191                    let mut j = i;
192                    while j < hits.len() && hits[j].0 == key && hits[j].1 == val {
193                        count += hits[j].2;
194                        j += 1;
195                    }
196                    if count.is_positive() {
197                        assert!(
198                            count == 1.into(),
199                            "unexpected multiple entries for the same key in persist trace"
200                        );
201                        let prev = old_values.insert(*key, decode_upsert_value(val.iter()));
202                        assert!(
203                            prev.is_none(),
204                            "unexpected multiple values for the same key in persist trace"
205                        );
206                    }
207                    i = j;
208                }
209            }
210
211            // Pass 3: classify and emit this window's records.
212            for index in start..end {
213                let ((_, key), ts, diff) = view.get(index);
214                let ts = <T as columnar::Columnar>::into_owned(ts);
215                match classify_time(persist_upper, &ts) {
216                    TimeClass::AlreadyPersisted => continue,
217                    TimeClass::Ineligible => {
218                        // Re-stash for later (owned).
219                        ineligible.push((
220                            *key,
221                            ts,
222                            <UpsertDiff<O> as columnar::Columnar>::into_owned(diff),
223                        ));
224                        continue;
225                    }
226                    TimeClass::Eligible => {}
227                }
228
229                // ts == persist_upper: eligible. The chunk holds one entry per
230                // (key, time) and eligibility pins the time, so this key appears
231                // at most once and its prior value can move out of the map.
232                eligible_count += 1;
233                let old_value = old_values.remove(key);
234
235                if old_value.is_some() {
236                    result_count += 1;
237                }
238
239                match diff.value {
240                    Some(row) => {
241                        if let Some(old_val) = old_value {
242                            let size = upsert_value_byte_len(&old_val);
243                            output_handle
244                                .give_fueled(
245                                    output_cap,
246                                    (old_val, ts.clone(), Diff::MINUS_ONE),
247                                    size,
248                                )
249                                .await;
250                            output_count += 1;
251                            updates += 1;
252                        } else {
253                            inserts += 1;
254                        }
255                        let new_val = decode_upsert_value(row.iter());
256                        let size = upsert_value_byte_len(&new_val);
257                        output_handle
258                            .give_fueled(output_cap, (new_val, ts, Diff::ONE), size)
259                            .await;
260                        output_count += 1;
261                    }
262                    None => {
263                        if let Some(old_val) = old_value {
264                            let size = upsert_value_byte_len(&old_val);
265                            output_handle
266                                .give_fueled(output_cap, (old_val, ts, Diff::MINUS_ONE), size)
267                                .await;
268                            output_count += 1;
269                            deletes += 1;
270                        }
271                    }
272                }
273            }
274            start = end;
275        }
276    }
277
278    tracing::debug!(
279        worker_id = %worker_id,
280        source_id = %source_id,
281        ineligible = ineligible.len(),
282        eligible = eligible_count,
283        "drained stash",
284    );
285
286    DrainStats {
287        eligible: eligible_count,
288        result_count,
289        inserts,
290        updates,
291        deletes,
292        output_count,
293    }
294}