Skip to main content

mz_storage/upsert_continual_feedback_v2/
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//! The persist-feedback side of the upsert-v2 operator: the feedback
11//! arrangement's types, and the `UpsertValue` to `Row` encoding it stores.
12
13use differential_dataflow::hashable::Hashable;
14use differential_dataflow::trace::chunk::ChunkBatch;
15use differential_dataflow::{AsCollection, VecCollection};
16use mz_repr::{Datum, Diff, Row};
17// Only the fuzzing-gated `datum_seq_to_upsert_value` takes a `DatumSeq`.
18#[cfg(feature = "fuzzing")]
19use mz_row_spine::DatumSeq;
20use mz_storage_types::errors::{DataflowError, UpsertError};
21use mz_timely_util::builder_async::ButtonHandle;
22use mz_timely_util::columnar::Column;
23use mz_timely_util::columnar::builder::ColumnBuilder;
24use mz_timely_util::columnar::chunk::{ColumnChunk, StorageSpill};
25use timely::dataflow::Stream;
26use timely::dataflow::channels::pact::Pipeline;
27use timely::dataflow::operators::Exchange as _;
28use timely::dataflow::operators::generic::Operator;
29use timely::order::TotalOrder;
30use timely::progress::Timestamp;
31use timely::progress::timestamp::Refines;
32
33use crate::statistics::SourceStatistics;
34use crate::upsert::{UpsertKey, UpsertValue};
35
36/// One persist-feedback update: a key, its current value row, the time, and
37/// an additive count.
38pub(super) type FeedbackUpdate<T> = ((UpsertKey, Row), T, Diff);
39
40/// One feedback-arrangement chunk: a sorted, consolidated run of updates,
41/// resident or spilled to the buffer pool. Both batcher chains and sealed
42/// spine batches are sequences of these, so the arrangement's state pages out
43/// of RSS under the pool's budget, and the drain reads it back through the
44/// bulk [`UnloadChunk`](mz_timely_util::columnar::unload::UnloadChunk)
45/// surface: copy-out probes, no cursor borrows.
46pub(super) type FeedbackChunk<T> = ColumnChunk<(UpsertKey, Row), T, Diff, StorageSpill>;
47
48/// The feedback arrangement's trace: a funded spine of `Rc`-shared chunk
49/// batches. See [`mz_timely_util::funded_spine`].
50pub(super) type FeedbackSpine<T> =
51    mz_timely_util::funded_spine::Spine<std::rc::Rc<ChunkBatch<FeedbackChunk<T>>>>;
52
53// The persist-feedback arrangement stores `(UpsertKey, Row)` pairs in columnar
54// chunk batches ([`FeedbackSpine`]). `UpsertValue` is
55// `Result<Row, Box<UpsertError>>`, so we fold both arms into a single `Row`
56// with a leading tag column so they share the value column.
57
58/// Encode an [`UpsertValue`] as a `Row` with a leading tag column so both `Ok`
59/// and `Err` payloads round-trip through `Row` byte storage.
60///
61/// Used on the render path. `pub` only so [`crate::fuzz_exports`] can re-export
62/// it under the `fuzzing` feature for the storage fuzz crate. The enclosing
63/// module is crate-private, so it is not otherwise reachable. Not a stable
64/// public API.
65#[doc(hidden)]
66pub fn upsert_value_to_row(value: &UpsertValue) -> Row {
67    let mut row = Row::default();
68    let mut packer = row.packer();
69    match value {
70        Ok(ok) => {
71            packer.push(Datum::UInt8(0));
72            packer.extend(ok.iter());
73        }
74        Err(err) => {
75            packer.push(Datum::UInt8(1));
76            let bytes =
77                bincode::serialize(err.as_ref()).expect("UpsertError is serializable via bincode");
78            packer.push(Datum::Bytes(&bytes));
79        }
80    }
81    row
82}
83
84/// Heap-size estimate for an emitted [`UpsertValue`], used to drive
85/// `give_fueled` yielding on the output edge.
86pub(super) fn upsert_value_byte_len(value: &UpsertValue) -> usize {
87    match value {
88        Ok(row) => row.byte_len(),
89        Err(err) => std::mem::size_of_val(err.as_ref()),
90    }
91}
92
93/// Decode an [`UpsertValue`] produced by [`upsert_value_to_row`] back from the
94/// `DatumSeq` view of a stored value.
95///
96/// Exists only for the storage fuzz crate, so it is gated behind the `fuzzing`
97/// feature. Not a stable public API.
98#[cfg(feature = "fuzzing")]
99#[doc(hidden)]
100pub fn datum_seq_to_upsert_value(seq: DatumSeq<'_>) -> UpsertValue {
101    decode_upsert_value(seq)
102}
103
104/// Decode an [`UpsertValue`] produced by [`upsert_value_to_row`] from any
105/// datum iterator, whether over a columnar `Row` reference or an owned `Row`.
106pub(super) fn decode_upsert_value<'a>(mut iter: impl Iterator<Item = Datum<'a>>) -> UpsertValue {
107    let tag = match iter.next() {
108        Some(Datum::UInt8(tag)) => tag,
109        other => panic!("upsert value missing UInt8 tag, got {:?}", other),
110    };
111    match tag {
112        0 => {
113            let mut row = Row::default();
114            row.packer().extend(iter);
115            Ok(row)
116        }
117        1 => {
118            let bytes = match iter.next() {
119                Some(Datum::Bytes(b)) => b,
120                other => panic!("upsert error tag missing Bytes payload, got {:?}", other),
121            };
122            let err: UpsertError =
123                bincode::deserialize(bytes).expect("UpsertError bincode round-trip");
124            Err(Box::new(err))
125        }
126        tag => panic!("unknown upsert value tag {tag}"),
127    }
128}
129
130/// Key the persist feedback by [`UpsertKey`], record source statistics, and
131/// encode `(UpsertKey, UpsertValue)` as `(UpsertKey, Row)` `Column` chunks,
132/// the input the feedback arrangement consumes. Built with
133/// `Pipeline` downstream of an `UpsertKey::hashed` exchange, so the
134/// arrangement keeps that locality.
135pub(super) fn encode_feedback<'scope, T>(
136    persist_ok: VecCollection<'scope, T, Row, Diff>,
137    persist_err: VecCollection<'scope, T, DataflowError, Diff>,
138    key_indices: Vec<usize>,
139    source_statistics: SourceStatistics,
140    stats_shutdown: ButtonHandle,
141) -> Stream<'scope, T, Column<((UpsertKey, Row), T, Diff)>>
142where
143    T: Timestamp + TotalOrder + Sync,
144    T: Refines<mz_repr::Timestamp> + differential_dataflow::lattice::Lattice,
145    T: columnation::Columnation,
146    T: columnar::Columnar + Default,
147    for<'a> columnar::Ref<'a, T>: Copy + Ord,
148{
149    let persist_keyed = crate::upsert::key_persist_feedback(persist_ok, persist_err, key_indices);
150    let persist_keyed = persist_keyed
151        .inner
152        // The arrangement already implicitly exchanges by key, so this is redundant, but we want to
153        // do it earlier so that we can inspect the stream properly for source statistics.
154        .exchange(move |((key, _), _, _)| UpsertKey::hashed(key))
155        .as_collection()
156        .inspect(move |((_, row), _, diff)| {
157            // A restarting ingestion presses the button and resets the
158            // `source_statistics` it shares with its next incarnation in the
159            // same worker step, while this incarnation's feedback is still in
160            // flight to here. Counting that feedback adds it on top of the
161            // next incarnation's rehydration, overstating `records_indexed`.
162            if stats_shutdown.local_pressed() {
163                return;
164            }
165            source_statistics.update_records_indexed_by(diff.into_inner());
166            source_statistics.update_bytes_indexed_by(
167                row.as_ref().map_or(0, |r| r.byte_len().try_into().unwrap()) * diff.into_inner(),
168            );
169        });
170    persist_keyed
171        .inner
172        .unary::<ColumnBuilder<((UpsertKey, Row), T, Diff)>, _, _, _>(
173            Pipeline,
174            "Persist feedback encode",
175            |_, _| {
176                move |input, output| {
177                    input.for_each(|time, data| {
178                        let mut session = output.session_with_builder(&time);
179                        for ((key, value), ts, diff) in data.drain(..) {
180                            let row = upsert_value_to_row(&value);
181                            session.give(((&key, &row), &ts, &diff));
182                        }
183                    });
184                }
185            },
186        )
187}