Skip to main content

mz_storage/render/
sinks.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//! Logic related to the creation of dataflow sinks.
11
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use differential_dataflow::operators::arrange::{Arranged, TraceAgent};
16use differential_dataflow::trace::SpanOf;
17use differential_dataflow::trace::implementations::merge_batcher::MergeBatcher;
18use differential_dataflow::{AsCollection, Hashable, VecCollection};
19use mz_persist_client::operators::shard_source::SnapshotMode;
20use mz_repr::{Datum, Diff, GlobalId, Row, Timestamp};
21use mz_row_spine::{ArcOrdValBatcher, ArcOrdValSpine};
22use mz_storage_operators::persist_source;
23use mz_storage_types::controller::CollectionMetadata;
24use mz_storage_types::errors::DataflowError;
25use mz_storage_types::sinks::{StorageSinkConnection, StorageSinkDesc};
26use mz_timely_util::builder_async::PressOnDropButton;
27use timely::dataflow::operators::Leave;
28use timely::dataflow::{Scope, StreamVec};
29use tracing::warn;
30
31use crate::healthcheck::HealthStatusMessage;
32use crate::storage_state::StorageState;
33
34/// The concrete trace type produced internally when arranging a sink's input.
35/// The sink never sees this directly — only the batches flowing through it —
36/// but it's the anchor for the batch type in [`SinkBatchStream`].
37pub(crate) type SinkTrace = TraceAgent<ArcOrdValSpine<Option<Row>, Row, Timestamp, Diff>>;
38
39/// Stream of arrangement batches handed to [`SinkRender::render_sink`].
40///
41/// This is `Arranged::stream` with the trace reader dropped: sinks only need
42/// batch-level access (no random-access reads via a cursor), so we don't keep
43/// a `TraceAgent` alive. Dropping the reader lets the spine's compaction
44/// frontiers advance to the empty antichain, so the arrange operator can
45/// aggressively compact / release batch state as updates flow through.
46pub(crate) type SinkBatchStream<'scope> = StreamVec<'scope, Timestamp, SpanOf<SinkTrace>>;
47
48/// _Renders_ complete _differential_ collections
49/// that represent the sink and its errors as requested
50/// by the original `CREATE SINK` statement.
51pub(crate) fn render_sink<'scope>(
52    scope: Scope<'scope, ()>,
53    storage_state: &mut StorageState,
54    sink_id: GlobalId,
55    sink: &StorageSinkDesc<CollectionMetadata, mz_repr::Timestamp>,
56) -> (
57    StreamVec<'scope, (), HealthStatusMessage>,
58    Vec<PressOnDropButton>,
59) {
60    let snapshot_mode = if sink.with_snapshot {
61        SnapshotMode::Include
62    } else {
63        SnapshotMode::Exclude
64    };
65
66    let error_handler = storage_state.error_handler("storage_sink", sink_id);
67
68    let name = format!("{sink_id}-sinks");
69    let outer_scope = scope.clone();
70
71    scope.scoped(&name, |scope| {
72        let mut tokens = vec![];
73        let sink_render = get_sink_render_for(&sink.connection);
74
75        let (ok_collection, err_collection, persist_tokens) =
76            persist_source::persist_source::<_, persist_source::RowVecBuilder<Timestamp>>(
77                scope,
78                sink.from,
79                Arc::clone(&storage_state.persist_clients),
80                &storage_state.txns_ctx,
81                sink.from_storage_metadata.clone(),
82                None,
83                Some(sink.as_of.clone()),
84                snapshot_mode,
85                timely::progress::Antichain::new(),
86                None,
87                None,
88                async {},
89                error_handler,
90            );
91        tokens.extend(persist_tokens);
92
93        let batches = arrange_sink_input(&*sink_render, ok_collection.as_collection());
94        let key_is_synthetic = sink_render.get_key_indices().is_none()
95            && sink_render.get_relation_key_indices().is_none();
96
97        let (health, sink_tokens) = sink_render.render_sink(
98            storage_state,
99            sink,
100            sink_id,
101            batches,
102            key_is_synthetic,
103            err_collection.as_collection(),
104        );
105        tokens.extend(sink_tokens);
106        (health.leave(outer_scope), tokens)
107    })
108}
109
110/// Extract the sink's key column(s) from each row, arrange the resulting
111/// `(Option<Row>, Row)` collection by key, and return just the stream of
112/// batches — dropping the trace reader.
113///
114/// Prefers the user-specified sink key, falling back to any natural key of the
115/// underlying relation. When neither exists, a synthetic per-row hash is used
116/// purely to distribute work across workers — in that case the sink should
117/// treat the key as absent (`key_is_synthetic`).
118///
119/// Partial-moving `arranged.stream` lets the surrounding `Arranged` (and the
120/// `TraceAgent` it holds) drop, releasing the spine's compaction holds so the
121/// arrange operator can compact batch state as it's emitted.
122fn arrange_sink_input<'scope>(
123    sink_render: &dyn SinkRender<'scope>,
124    collection: VecCollection<'scope, Timestamp, Row, Diff>,
125) -> SinkBatchStream<'scope> {
126    let key_indices = sink_render
127        .get_key_indices()
128        .or_else(|| sink_render.get_relation_key_indices())
129        .map(|k| k.to_vec());
130
131    let keyed = match key_indices {
132        None => collection.map(|row| (Some(Row::pack(Some(Datum::UInt64(row.hashed())))), row)),
133        Some(key_indices) => {
134            let mut datum_vec = mz_repr::DatumVec::new();
135            collection.map(move |row| {
136                // TODO[perf] (btv) - is there a way to avoid unpacking and
137                // repacking every row and cloning the datums? Does it matter?
138                let key = {
139                    let datums = datum_vec.borrow_with(&row);
140                    Row::pack(key_indices.iter().map(|&idx| datums[idx].clone()))
141                };
142                (Some(key), row)
143            })
144        }
145    };
146
147    // Allow access to `arrange_named` because we cannot access Mz's wrapper
148    // from here. TODO(database-issues#5046): Revisit with cluster unification.
149    #[allow(clippy::disallowed_methods)]
150    let Arranged { stream, trace: _ } = keyed
151        .arrange_named::<ArcOrdValBatcher<_, _, _, _>, ArcOrdValSpine<_, _, _, _>>(
152            "Arrange Sink",
153            MergeBatcher::new,
154        );
155    stream
156}
157
158/// Rate-limited detector for primary-key uniqueness violations as a sink's
159/// cursor walk observes `(key, timestamp)` groups.
160///
161/// Call [`PkViolationWarner::observe`] once per emitted `DiffPair`. When the
162/// current `(key, timestamp)` group changes — or when input batches finish —
163/// call [`PkViolationWarner::flush`] so the accumulated count is evaluated.
164///
165/// Keys are identified by their `Hashable::hashed()` value rather than held
166/// by value, so the hot observe path does no `Row` clones. A hash collision
167/// can mask a PK violation but this is a purely diagnostic check, so the
168/// trade-off is acceptable.
169pub(crate) struct PkViolationWarner {
170    sink_id: GlobalId,
171    from_id: GlobalId,
172    last_warning: Instant,
173    current: Option<(u64, Timestamp)>,
174    count: usize,
175}
176
177impl PkViolationWarner {
178    pub fn new(sink_id: GlobalId, from_id: GlobalId) -> Self {
179        Self {
180            sink_id,
181            from_id,
182            last_warning: Instant::now(),
183            current: None,
184            count: 0,
185        }
186    }
187
188    /// Record that a `DiffPair` was observed at `(key, time)`. If this starts
189    /// a new group, the previous group's count is flushed (and warned about
190    /// if the count was > 1).
191    pub fn observe(&mut self, key: &Option<Row>, time: Timestamp) {
192        // `None` keys hash to a distinct sentinel from any `Row::hashed()`;
193        // the exact constant doesn't matter for correctness (it just needs
194        // to be stable).
195        let hash = key.as_ref().map(|k| k.hashed()).unwrap_or(u64::MAX);
196        let same = self.current == Some((hash, time));
197        if !same {
198            self.flush();
199            self.current = Some((hash, time));
200        }
201        self.count += 1;
202    }
203
204    /// Flush the pending `(key, timestamp)` group count. Emits a
205    /// rate-limited warning if more than one `DiffPair` was observed.
206    pub fn flush(&mut self) {
207        if self.count > 1 {
208            let now = Instant::now();
209            if now.duration_since(self.last_warning) >= Duration::from_secs(10) {
210                self.last_warning = now;
211                warn!(
212                    sink_id = ?self.sink_id,
213                    from_id = ?self.from_id,
214                    "primary key error: expected at most one update per key and timestamp; \
215                        this can happen when the configured sink key is not a primary key of \
216                        the sinked relation"
217                );
218            }
219        }
220        self.current = None;
221        self.count = 0;
222    }
223}
224
225/// A type that can be rendered as a dataflow sink.
226pub(crate) trait SinkRender<'scope> {
227    /// Gets the indexes of the columns that form the key that the user
228    /// specified when creating the sink, if any.
229    fn get_key_indices(&self) -> Option<&[usize]>;
230
231    /// Gets the indexes of the columns that form a key of the sink's underlying
232    /// relation, if such a key exists.
233    fn get_relation_key_indices(&self) -> Option<&[usize]>;
234
235    /// Renders the sink's dataflow.
236    ///
237    /// The sink receives a stream of arrangement batches keyed on `Option<Row>`.
238    /// The sink is responsible for walking each batch (typically via
239    /// [`mz_interchange::envelopes::for_each_diff_pair`]) and handling any
240    /// envelope-specific diff-pair construction. When `key_is_synthetic` is
241    /// true the arrangement's key is a per-row hash used only for worker
242    /// distribution — the sink should treat the key as absent when producing
243    /// output.
244    fn render_sink(
245        &self,
246        storage_state: &mut StorageState,
247        sink: &StorageSinkDesc<CollectionMetadata, Timestamp>,
248        sink_id: GlobalId,
249        batches: SinkBatchStream<'scope>,
250        key_is_synthetic: bool,
251        err_collection: VecCollection<'scope, Timestamp, DataflowError, Diff>,
252    ) -> (
253        StreamVec<'scope, Timestamp, HealthStatusMessage>,
254        Vec<PressOnDropButton>,
255    );
256}
257
258fn get_sink_render_for<'scope>(connection: &StorageSinkConnection) -> Box<dyn SinkRender<'scope>> {
259    match connection {
260        StorageSinkConnection::Kafka(connection) => Box::new(connection.clone()),
261        StorageSinkConnection::Iceberg(connection) => Box::new(connection.clone()),
262    }
263}