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;
16use differential_dataflow::trace::implementations::ord_neu::{
17    ColValBatcher, ColValBuilder, ColValSpine,
18};
19use differential_dataflow::{AsCollection, Hashable, VecCollection};
20use mz_interchange::avro::DiffPair;
21use mz_interchange::envelopes::combine_at_timestamp;
22use mz_persist_client::operators::shard_source::SnapshotMode;
23use mz_repr::{Datum, Diff, GlobalId, Row, Timestamp};
24use mz_storage_operators::persist_source;
25use mz_storage_types::controller::CollectionMetadata;
26use mz_storage_types::errors::DataflowError;
27use mz_storage_types::sinks::{StorageSinkConnection, StorageSinkDesc};
28use mz_timely_util::builder_async::PressOnDropButton;
29use timely::dataflow::operators::Leave;
30use timely::dataflow::{Scope, Stream};
31use tracing::warn;
32
33use crate::healthcheck::HealthStatusMessage;
34use crate::storage_state::StorageState;
35
36/// _Renders_ complete _differential_ collections
37/// that represent the sink and its errors as requested
38/// by the original `CREATE SINK` statement.
39pub(crate) fn render_sink<G>(
40    scope: &mut G,
41    storage_state: &mut StorageState,
42    sink_id: GlobalId,
43    sink: &StorageSinkDesc<CollectionMetadata, mz_repr::Timestamp>,
44) -> (Stream<G, HealthStatusMessage>, Vec<PressOnDropButton>)
45where
46    G: Scope<Timestamp = ()>,
47{
48    let snapshot_mode = if sink.with_snapshot {
49        SnapshotMode::Include
50    } else {
51        SnapshotMode::Exclude
52    };
53
54    let error_handler = storage_state.error_handler("storage_sink", sink_id);
55
56    let name = format!("{sink_id}-sinks");
57
58    scope.scoped(&name, |scope| {
59        let mut tokens = vec![];
60        let sink_render = get_sink_render_for(&sink.connection);
61
62        let (ok_collection, err_collection, persist_tokens) = persist_source::persist_source(
63            scope,
64            sink.from,
65            Arc::clone(&storage_state.persist_clients),
66            &storage_state.txns_ctx,
67            sink.from_storage_metadata.clone(),
68            None,
69            Some(sink.as_of.clone()),
70            snapshot_mode,
71            timely::progress::Antichain::new(),
72            None,
73            None,
74            async {},
75            error_handler,
76        );
77        tokens.extend(persist_tokens);
78
79        let ok_collection =
80            zip_into_diff_pairs(sink_id, sink, &*sink_render, ok_collection.as_collection());
81
82        let (health, sink_tokens) = sink_render.render_sink(
83            storage_state,
84            sink,
85            sink_id,
86            ok_collection,
87            err_collection.as_collection(),
88        );
89        tokens.extend(sink_tokens);
90        (health.leave(), tokens)
91    })
92}
93
94/// Zip the input to a sink so that updates to the same key appear as
95/// `DiffPair`s.
96fn zip_into_diff_pairs<G>(
97    sink_id: GlobalId,
98    sink: &StorageSinkDesc<CollectionMetadata, mz_repr::Timestamp>,
99    sink_render: &dyn SinkRender<G>,
100    collection: VecCollection<G, Row, Diff>,
101) -> VecCollection<G, (Option<Row>, DiffPair<Row>), Diff>
102where
103    G: Scope<Timestamp = Timestamp>,
104{
105    // We need to consolidate the collection and group records by their key.
106    // We'll first attempt to use the explicitly declared key when the sink was
107    // created. If no such key exists, we'll use a key of the sink's underlying
108    // relation, if one exists.
109    //
110    // If no such key exists, we'll generate a synthetic key based on the hash
111    // of the row, just for purposes of distributing work among workers. In this
112    // case the key offers no uniqueness guarantee.
113
114    let user_key_indices = sink_render.get_key_indices();
115    let relation_key_indices = sink_render.get_relation_key_indices();
116    let key_indices = user_key_indices
117        .or(relation_key_indices)
118        .map(|k| k.to_vec());
119    let key_is_synthetic = key_indices.is_none();
120
121    let collection = match key_indices {
122        None => collection.map(|row| (Some(Row::pack(Some(Datum::UInt64(row.hashed())))), row)),
123        Some(key_indices) => {
124            let mut datum_vec = mz_repr::DatumVec::new();
125            collection.map(move |row| {
126                // TODO[perf] (btv) - is there a way to avoid unpacking and
127                // repacking every row and cloning the datums? Does it matter?
128                let key = {
129                    let datums = datum_vec.borrow_with(&row);
130                    Row::pack(key_indices.iter().map(|&idx| datums[idx].clone()))
131                };
132                (Some(key), row)
133            })
134        }
135    };
136
137    // Group messages by key at each timestamp.
138    //
139    // Allow access to `arrange_named` because we cannot access Mz's wrapper
140    // from here. TODO(database-issues#5046): Revisit with cluster unification.
141    #[allow(clippy::disallowed_methods)]
142    let mut collection =
143        combine_at_timestamp(collection.arrange_named::<ColValBatcher<_,_,_,_>, ColValBuilder<_,_,_,_>, ColValSpine<_, _, _, _>>("Arrange Sink"));
144
145    // If there is no user-specified key, remove the synthetic key.
146    //
147    // We don't want the synthetic key to appear in the sink's actual output; we
148    // just needed a value to use to distribute work.
149    if user_key_indices.is_none() {
150        collection = collection.map(|(_key, value)| (None, value))
151    }
152
153    collection.flat_map({
154        let mut last_warning = Instant::now();
155        let from_id = sink.from;
156        move |(mut k, vs)| {
157            // If the key is not synthetic, emit a warning to internal logs if
158            // we discover a primary key violation.
159            //
160            // TODO: put the sink in a user-visible errored state instead of
161            // only logging internally. See:
162            // https://github.com/MaterializeInc/database-issues/issues/5099.
163            if !key_is_synthetic && vs.len() > 1 {
164                // We rate limit how often we emit this warning to avoid
165                // flooding logs.
166                let now = Instant::now();
167                if now.duration_since(last_warning) >= Duration::from_secs(10) {
168                    last_warning = now;
169                    warn!(
170                        ?sink_id,
171                        ?from_id,
172                        "primary key error: expected at most one update per key and timestamp; \
173                            this can happen when the configured sink key is not a primary key of \
174                            the sinked relation"
175                    )
176                }
177            }
178
179            let max_idx = vs.len() - 1;
180            vs.into_iter().enumerate().map(move |(idx, dp)| {
181                let k = if idx == max_idx { k.take() } else { k.clone() };
182                (k, dp)
183            })
184        }
185    })
186}
187
188/// A type that can be rendered as a dataflow sink.
189pub(crate) trait SinkRender<G>
190where
191    G: Scope<Timestamp = Timestamp>,
192{
193    /// Gets the indexes of the columns that form the key that the user
194    /// specified when creating the sink, if any.
195    fn get_key_indices(&self) -> Option<&[usize]>;
196
197    /// Gets the indexes of the columns that form a key of the sink's underlying
198    /// relation, if such a key exists.
199    fn get_relation_key_indices(&self) -> Option<&[usize]>;
200
201    /// Renders the sink's dataflow.
202    fn render_sink(
203        &self,
204        storage_state: &mut StorageState,
205        sink: &StorageSinkDesc<CollectionMetadata, Timestamp>,
206        sink_id: GlobalId,
207        sinked_collection: VecCollection<G, (Option<Row>, DiffPair<Row>), Diff>,
208        err_collection: VecCollection<G, DataflowError, Diff>,
209    ) -> (Stream<G, HealthStatusMessage>, Vec<PressOnDropButton>);
210}
211
212fn get_sink_render_for<G>(connection: &StorageSinkConnection) -> Box<dyn SinkRender<G>>
213where
214    G: Scope<Timestamp = Timestamp>,
215{
216    match connection {
217        StorageSinkConnection::Kafka(connection) => Box::new(connection.clone()),
218        StorageSinkConnection::Iceberg(_) => unimplemented!("iceberg sinks"),
219    }
220}