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::{Arrange, Arranged, TraceAgent};
16use differential_dataflow::trace::TraceReader;
17use differential_dataflow::trace::implementations::ord_neu::OrdValBatcher;
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::{ArcOrdValBuilder, 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> =
47    StreamVec<'scope, Timestamp, <SinkTrace as TraceReader>::Batch>;
48
49/// _Renders_ complete _differential_ collections
50/// that represent the sink and its errors as requested
51/// by the original `CREATE SINK` statement.
52pub(crate) fn render_sink<'scope>(
53    scope: Scope<'scope, ()>,
54    storage_state: &mut StorageState,
55    sink_id: GlobalId,
56    sink: &StorageSinkDesc<CollectionMetadata, mz_repr::Timestamp>,
57) -> (
58    StreamVec<'scope, (), HealthStatusMessage>,
59    Vec<PressOnDropButton>,
60) {
61    let snapshot_mode = if sink.with_snapshot {
62        SnapshotMode::Include
63    } else {
64        SnapshotMode::Exclude
65    };
66
67    let error_handler = storage_state.error_handler("storage_sink", sink_id);
68
69    let name = format!("{sink_id}-sinks");
70    let outer_scope = scope.clone();
71
72    scope.scoped(&name, |scope| {
73        let mut tokens = vec![];
74        let sink_render = get_sink_render_for(&sink.connection);
75
76        let (ok_collection, err_collection, persist_tokens) = persist_source::persist_source(
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.arrange_named::<OrdValBatcher<_, _, _, _>, ArcOrdValBuilder<_, _, _, _>, ArcOrdValSpine<_, _, _, _>>("Arrange Sink");
151    stream
152}
153
154/// Rate-limited detector for primary-key uniqueness violations as a sink's
155/// cursor walk observes `(key, timestamp)` groups.
156///
157/// Call [`PkViolationWarner::observe`] once per emitted `DiffPair`. When the
158/// current `(key, timestamp)` group changes — or when input batches finish —
159/// call [`PkViolationWarner::flush`] so the accumulated count is evaluated.
160///
161/// Keys are identified by their `Hashable::hashed()` value rather than held
162/// by value, so the hot observe path does no `Row` clones. A hash collision
163/// can mask a PK violation but this is a purely diagnostic check, so the
164/// trade-off is acceptable.
165pub(crate) struct PkViolationWarner {
166    sink_id: GlobalId,
167    from_id: GlobalId,
168    last_warning: Instant,
169    current: Option<(u64, Timestamp)>,
170    count: usize,
171}
172
173impl PkViolationWarner {
174    pub fn new(sink_id: GlobalId, from_id: GlobalId) -> Self {
175        Self {
176            sink_id,
177            from_id,
178            last_warning: Instant::now(),
179            current: None,
180            count: 0,
181        }
182    }
183
184    /// Record that a `DiffPair` was observed at `(key, time)`. If this starts
185    /// a new group, the previous group's count is flushed (and warned about
186    /// if the count was > 1).
187    pub fn observe(&mut self, key: &Option<Row>, time: Timestamp) {
188        // `None` keys hash to a distinct sentinel from any `Row::hashed()`;
189        // the exact constant doesn't matter for correctness (it just needs
190        // to be stable).
191        let hash = key.as_ref().map(|k| k.hashed()).unwrap_or(u64::MAX);
192        let same = self.current == Some((hash, time));
193        if !same {
194            self.flush();
195            self.current = Some((hash, time));
196        }
197        self.count += 1;
198    }
199
200    /// Flush the pending `(key, timestamp)` group count. Emits a
201    /// rate-limited warning if more than one `DiffPair` was observed.
202    pub fn flush(&mut self) {
203        if self.count > 1 {
204            let now = Instant::now();
205            if now.duration_since(self.last_warning) >= Duration::from_secs(10) {
206                self.last_warning = now;
207                warn!(
208                    sink_id = ?self.sink_id,
209                    from_id = ?self.from_id,
210                    "primary key error: expected at most one update per key and timestamp; \
211                        this can happen when the configured sink key is not a primary key of \
212                        the sinked relation"
213                );
214            }
215        }
216        self.current = None;
217        self.count = 0;
218    }
219}
220
221/// A type that can be rendered as a dataflow sink.
222pub(crate) trait SinkRender<'scope> {
223    /// Gets the indexes of the columns that form the key that the user
224    /// specified when creating the sink, if any.
225    fn get_key_indices(&self) -> Option<&[usize]>;
226
227    /// Gets the indexes of the columns that form a key of the sink's underlying
228    /// relation, if such a key exists.
229    fn get_relation_key_indices(&self) -> Option<&[usize]>;
230
231    /// Renders the sink's dataflow.
232    ///
233    /// The sink receives a stream of arrangement batches keyed on `Option<Row>`.
234    /// The sink is responsible for walking each batch (typically via
235    /// [`mz_interchange::envelopes::for_each_diff_pair`]) and handling any
236    /// envelope-specific diff-pair construction. When `key_is_synthetic` is
237    /// true the arrangement's key is a per-row hash used only for worker
238    /// distribution — the sink should treat the key as absent when producing
239    /// output.
240    fn render_sink(
241        &self,
242        storage_state: &mut StorageState,
243        sink: &StorageSinkDesc<CollectionMetadata, Timestamp>,
244        sink_id: GlobalId,
245        batches: SinkBatchStream<'scope>,
246        key_is_synthetic: bool,
247        err_collection: VecCollection<'scope, Timestamp, DataflowError, Diff>,
248    ) -> (
249        StreamVec<'scope, Timestamp, HealthStatusMessage>,
250        Vec<PressOnDropButton>,
251    );
252}
253
254fn get_sink_render_for<'scope>(connection: &StorageSinkConnection) -> Box<dyn SinkRender<'scope>> {
255    match connection {
256        StorageSinkConnection::Kafka(connection) => Box::new(connection.clone()),
257        StorageSinkConnection::Iceberg(connection) => Box::new(connection.clone()),
258    }
259}