Skip to main content

mz_storage/sink/
kafka.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//! Code to render the sink dataflow of a [`KafkaSinkConnection`]. The dataflow consists
11//! of two operators in order to take advantage of all the available workers.
12//!
13//! ```text
14//!        ┏━━━━━━━━━━━━━━┓
15//!        ┃   persist    ┃
16//!        ┃    source    ┃
17//!        ┗━━━━━━┯━━━━━━━┛
18//!               │ stream of arrangement batches (trace reader dropped)
19//!               │
20//!        ┏━━━━━━v━━━━━━┓
21//!        ┃    row      ┃ walks each batch's cursor and emits one
22//!        ┃   encoder   ┃ encoded `KafkaMessage` per DiffPair
23//!        ┗━━━━━━┯━━━━━━┛
24//!               │ encoded data
25//!               │
26//!        ┏━━━━━━v━━━━━━┓
27//!        ┃    kafka    ┃ (single worker)
28//!        ┃    sink     ┃
29//!        ┗━━┯━━━━━━━━┯━┛
30//!   records │        │ uppers
31//!      ╭────v──╮ ╭───v──────╮
32//!      │ data  │ │ progress │  <- records and uppers are produced
33//!      │ topic │ │  topic   │     transactionally to both topics
34//!      ╰───────╯ ╰──────────╯
35//! ```
36//!
37//! # Encoding
38//!
39//! One part of the dataflow deals with encoding the rows that we read from persist. The encoder
40//! walks the input arrangement's batches via
41//! [`mz_interchange::envelopes::for_each_diff_pair`], producing one encoded `KafkaMessage` per
42//! `DiffPair` observed at each `(key, timestamp)`. An initialization step first ensures that the
43//! schemas are published to the Schema Registry.
44//!
45//! # Sinking
46//!
47//! The other part of the dataflow, and what this module mostly deals with, is interacting with the
48//! Kafka cluster in order to transactionally commit batches (sets of records associated with a
49//! frontier). All the processing happens in a single worker and so all previously encoded records
50//! go through an exchange in order to arrive at the chosen worker. We may be able to improve this
51//! in the future by committing disjoint partitions of the key space for independent workers but
52//! for now we do the simple thing.
53//!
54//! ## Retries
55//!
56//! All of the retry logic heavy lifting is offloaded to `librdkafka` since it already implements
57//! the required behavior[1]. In particular we only ever enqueue records to its send queue and
58//! eventually call `commit_transaction` which will ensure that all queued messages are
59//! successfully delivered before the transaction is reported as committed.
60//!
61//! The only error that is possible during sending is that the queue is full. We are purposefully
62//! NOT handling this error and simply configure `librdkafka` with a very large queue. The reason
63//! for this choice is that the only choice for hanlding such an error ourselves would be to queue
64//! it, and there isn't a good argument about two small queues being better than one big one. If we
65//! reach the queue limit we simply error out the entire sink dataflow and start over.
66//!
67//! # Error handling
68//!
69//! Both the encoding operator and the sinking operator can produce a transient error that is wired
70//! up with our health monitoring and will trigger a restart of the sink dataflow.
71//!
72//! [1]: https://github.com/confluentinc/librdkafka/blob/master/INTRODUCTION.md#message-reliability
73
74use std::cell::RefCell;
75use std::cmp::Ordering;
76use std::collections::BTreeMap;
77use std::future::Future;
78use std::rc::Rc;
79use std::sync::atomic::AtomicU64;
80use std::sync::{Arc, Weak};
81use std::time::Duration;
82
83use anyhow::{Context, anyhow, bail};
84use differential_dataflow::{AsCollection, Hashable, VecCollection};
85use futures::StreamExt;
86use maplit::btreemap;
87use mz_ccsr::PublishError;
88use mz_expr::{Eval, MirScalarExpr};
89use mz_interchange::avro::{AvroEncoder, AvroSchemaId};
90use mz_interchange::encode::Encode;
91use mz_interchange::envelopes::{dbz_format, for_each_diff_pair};
92use mz_interchange::json::JsonEncoder;
93use mz_interchange::text_binary::{BinaryEncoder, TextEncoder};
94use mz_kafka_util::admin::EnsureTopicConfig;
95use mz_kafka_util::client::{
96    DEFAULT_FETCH_METADATA_TIMEOUT, GetPartitionsError, MzClientContext, TimeoutConfig,
97    TunnelingClientContext,
98};
99use mz_ore::cast::CastFrom;
100use mz_ore::collections::CollectionExt;
101use mz_ore::error::ErrorExt;
102use mz_ore::future::InTask;
103use mz_ore::soft_assert_or_log;
104use mz_ore::task::{self, AbortOnDropHandle};
105use mz_persist_client::Diagnostics;
106use mz_persist_client::write::WriteHandle;
107use mz_persist_types::codec_impls::UnitSchema;
108use mz_repr::{Datum, DatumVec, Diff, GlobalId, RelationDesc, Row, RowArena, Timestamp};
109use mz_storage_client::sink::GlueSchemaIncompatibleError;
110use mz_storage_client::sink::progress_key::ProgressKey;
111use mz_storage_types::StorageDiff;
112use mz_storage_types::configuration::StorageConfiguration;
113use mz_storage_types::controller::CollectionMetadata;
114use mz_storage_types::dyncfgs::{
115    KAFKA_BUFFERED_EVENT_RESIZE_THRESHOLD_ELEMENTS, KAFKA_SINK_BATCH_NUM_MESSAGES,
116    KAFKA_SINK_BATCH_SIZE, KAFKA_SINK_EMIT_SINK_ID_HEADER, KAFKA_SINK_MESSAGE_MAX_BYTES,
117    SINK_ENSURE_TOPIC_CONFIG, SINK_PROGRESS_SEARCH,
118};
119use mz_storage_types::errors::{ContextCreationError, ContextCreationErrorExt, DataflowError};
120use mz_storage_types::sinks::{
121    KafkaSinkConnection, KafkaSinkFormatType, SinkEnvelope, StorageSinkDesc,
122};
123use mz_storage_types::sources::SourceData;
124use mz_storage_types::wire_format::WireFormat;
125use mz_timely_util::antichain::AntichainExt;
126use mz_timely_util::builder_async::{
127    Event, OperatorBuilder as AsyncOperatorBuilder, PressOnDropButton,
128};
129use rdkafka::consumer::{BaseConsumer, Consumer, ConsumerContext};
130use rdkafka::error::KafkaError;
131use rdkafka::message::{Header, OwnedHeaders, ToBytes};
132use rdkafka::producer::{BaseRecord, Producer, ThreadedProducer};
133use rdkafka::types::RDKafkaErrorCode;
134use rdkafka::{Message, Offset, Statistics, TopicPartitionList};
135use serde::{Deserialize, Deserializer, Serialize, Serializer};
136use timely::PartialOrder;
137use timely::container::CapacityContainerBuilder;
138use timely::dataflow::StreamVec;
139use timely::dataflow::channels::pact::{Exchange, Pipeline};
140use timely::dataflow::operators::vec::{Map, ToStream};
141use timely::dataflow::operators::{CapabilitySet, Concatenate};
142use timely::progress::{Antichain, Timestamp as _};
143use tokio::sync::watch;
144use tokio::time::{self, MissedTickBehavior};
145use tracing::{debug, error, info, warn};
146
147use crate::healthcheck::{HealthStatusMessage, HealthStatusUpdate, StatusNamespace};
148use crate::metrics::sink::kafka::KafkaSinkMetrics;
149use crate::render::sinks::{PkViolationWarner, SinkBatchStream, SinkRender};
150use crate::statistics::SinkStatistics;
151use crate::storage_state::StorageState;
152
153impl<'scope> SinkRender<'scope> for KafkaSinkConnection {
154    fn get_key_indices(&self) -> Option<&[usize]> {
155        self.key_desc_and_indices
156            .as_ref()
157            .map(|(_desc, indices)| indices.as_slice())
158    }
159
160    fn get_relation_key_indices(&self) -> Option<&[usize]> {
161        self.relation_key_indices.as_deref()
162    }
163
164    fn render_sink(
165        &self,
166        storage_state: &mut StorageState,
167        sink: &StorageSinkDesc<CollectionMetadata, Timestamp>,
168        sink_id: GlobalId,
169        batches: SinkBatchStream<'scope>,
170        key_is_synthetic: bool,
171        // TODO(benesch): errors should stream out through the sink,
172        // if we figure out a protocol for that.
173        _err_collection: VecCollection<'scope, Timestamp, DataflowError, Diff>,
174    ) -> (
175        StreamVec<'scope, Timestamp, HealthStatusMessage>,
176        Vec<PressOnDropButton>,
177    ) {
178        let scope = batches.scope();
179
180        let write_handle = {
181            let persist = Arc::clone(&storage_state.persist_clients);
182            let shard_meta = sink.to_storage_metadata.clone();
183            async move {
184                let client = persist.open(shard_meta.persist_location).await?;
185                let handle = client
186                    .open_writer(
187                        shard_meta.data_shard,
188                        Arc::new(shard_meta.relation_desc),
189                        Arc::new(UnitSchema),
190                        Diagnostics::from_purpose("sink handle"),
191                    )
192                    .await?;
193                Ok(handle)
194            }
195        };
196
197        let write_frontier = Rc::new(RefCell::new(Antichain::from_elem(Timestamp::minimum())));
198        storage_state
199            .sink_write_frontiers
200            .insert(sink_id, Rc::clone(&write_frontier));
201
202        let (encoded, encode_status, encode_token) = encode_collection(
203            format!("kafka-{sink_id}-{}-encode", self.format.get_format_name()),
204            batches,
205            sink.envelope,
206            self.clone(),
207            storage_state.storage_configuration.clone(),
208            sink_id,
209            sink.from,
210            key_is_synthetic,
211        );
212
213        let metrics = storage_state.metrics.get_kafka_sink_metrics(sink_id);
214        let statistics = storage_state
215            .aggregated_statistics
216            .get_sink(&sink_id)
217            .expect("statistics initialized")
218            .clone();
219
220        let (sink_status, sink_token) = sink_collection(
221            format!("kafka-{sink_id}-sink"),
222            encoded,
223            sink_id,
224            self.clone(),
225            storage_state.storage_configuration.clone(),
226            sink,
227            metrics,
228            statistics,
229            write_handle,
230            write_frontier,
231        );
232
233        let running_status = Some(HealthStatusMessage {
234            id: None,
235            update: HealthStatusUpdate::Running,
236            namespace: StatusNamespace::Kafka,
237        })
238        .to_stream(scope);
239
240        let status = scope.concatenate([running_status, encode_status, sink_status]);
241
242        (status, vec![encode_token, sink_token])
243    }
244}
245
246struct TransactionalProducer {
247    /// The task name used for any blocking calls spawned onto the tokio threadpool.
248    task_name: String,
249    /// The topic where all the updates go.
250    data_topic: String,
251    /// The topic where all the upper frontiers go.
252    progress_topic: String,
253    /// The key each progress record is associated with.
254    progress_key: ProgressKey,
255    /// The version of this sink, used to fence out previous versions from writing.
256    sink_version: u64,
257    /// The `materialize-sink-id` header value, when the header is enabled.
258    sink_id_header: Option<String>,
259    /// The number of partitions in the target topic.
260    partition_count: Arc<AtomicU64>,
261    /// A task to periodically refresh the partition count.
262    _partition_count_task: AbortOnDropHandle<()>,
263    /// The underlying Kafka producer.
264    producer: ThreadedProducer<TunnelingClientContext<MzClientContext>>,
265    /// A handle to the metrics associated with this sink.
266    statistics: SinkStatistics,
267    /// The number of messages staged for the currently open transactions. It is reset to zero
268    /// every time a transaction commits.
269    staged_messages: u64,
270    /// The total number bytes staged for the currently open transactions. It is reset to zero
271    /// every time a transaction commits.
272    staged_bytes: u64,
273    /// The timeout to use for network operations.
274    socket_timeout: Duration,
275    /// The timeout to use for committing transactions.
276    transaction_timeout: Duration,
277}
278
279impl TransactionalProducer {
280    /// Initializes a transcational producer for the sink identified by `sink_id`. After this call
281    /// returns it is guranteed that all previous `TransactionalProducer` instances for the same
282    /// sink have been fenced out (i.e `init_transations()` has been called successfully).
283    async fn new(
284        sink_id: GlobalId,
285        connection: &KafkaSinkConnection,
286        storage_configuration: &StorageConfiguration,
287        metrics: Arc<KafkaSinkMetrics>,
288        statistics: SinkStatistics,
289        sink_version: u64,
290    ) -> Result<(Self, Antichain<mz_repr::Timestamp>), ContextCreationError> {
291        let client_id = connection.client_id(
292            storage_configuration.config_set(),
293            &storage_configuration.connection_context,
294            sink_id,
295        );
296        let transactional_id =
297            connection.transactional_id(&storage_configuration.connection_context, sink_id);
298
299        let timeout_config = &storage_configuration.parameters.kafka_timeout_config;
300        let mut options = BTreeMap::new();
301        // Ensure that messages are sinked in order and without duplicates. Note that this only
302        // applies to a single instance of a producer - in the case of restarts, all bets are off
303        // and full exactly once support is required.
304        options.insert("enable.idempotence", "true".into());
305        // Use the compression type requested by the user.
306        options.insert(
307            "compression.type",
308            connection.compression_type.to_librdkafka_option().into(),
309        );
310        // Set the maximum buffer size limit. We don't want to impose anything lower than the max
311        // here as the operator has nothing better to do with the data than to buffer them.
312        options.insert("queue.buffering.max.kbytes", "2147483647".into());
313        // Disable the default buffer limit of 100k messages. We don't want to impose any limit
314        // here as the operator has nothing better to do with the data than to buffer them.
315        options.insert("queue.buffering.max.messages", "0".into());
316        // Make the Kafka producer wait at least 10 ms before sending out MessageSets
317        options.insert("queue.buffering.max.ms", format!("{}", 10));
318        // Time out transactions after `transaction_timeout`.
319        options.insert(
320            "transaction.timeout.ms",
321            format!("{}", timeout_config.transaction_timeout.as_millis()),
322        );
323        // Use the transactional ID requested by the user.
324        options.insert("transactional.id", transactional_id);
325        // Allow Kafka monitoring tools to identify this producer.
326        options.insert("client.id", client_id);
327        // We want to be notified regularly with statistics
328        options.insert("statistics.interval.ms", "1000".into());
329        // Maximum size of a single produced message, controlled by dyncfg so
330        // operators can raise the limit when messages exceed librdkafka's 1MB
331        // default.
332        options.insert(
333            "message.max.bytes",
334            format!(
335                "{}",
336                KAFKA_SINK_MESSAGE_MAX_BYTES.get(storage_configuration.config_set())
337            ),
338        );
339        // Maximum size (bytes) of a produced MessageSet.
340        options.insert(
341            "batch.size",
342            format!(
343                "{}",
344                KAFKA_SINK_BATCH_SIZE.get(storage_configuration.config_set())
345            ),
346        );
347        // Maximum number of messages batched in one MessageSet.
348        options.insert(
349            "batch.num.messages",
350            format!(
351                "{}",
352                KAFKA_SINK_BATCH_NUM_MESSAGES.get(storage_configuration.config_set())
353            ),
354        );
355
356        let ctx = MzClientContext::default();
357
358        let stats_receiver = ctx.subscribe_statistics();
359        let task_name = format!("kafka_sink_metrics_collector:{sink_id}");
360        task::spawn(
361            || &task_name,
362            collect_statistics(stats_receiver, Arc::clone(&metrics)),
363        );
364
365        let producer: ThreadedProducer<_> = connection
366            .connection
367            .create_with_context(storage_configuration, ctx, &options, InTask::Yes)
368            .await?;
369
370        // The partition count is fixed up after we ensure the topic exists.
371        let partition_count = Arc::new(AtomicU64::new(0));
372        let update_partition_count = {
373            let partition_count = Arc::clone(&partition_count);
374            let metrics = Arc::clone(&metrics);
375            Arc::new(move |pc| {
376                partition_count.store(pc, std::sync::atomic::Ordering::SeqCst);
377                metrics.partition_count.set(pc);
378            })
379        };
380
381        // Start a task that will keep the partition count up to date in the
382        // background.
383        let partition_count_task = task::spawn(
384            || format!("kafka_sink_producer_fetch_metadata_loop:{sink_id}"),
385            fetch_partition_count_loop(
386                producer.clone(),
387                sink_id,
388                connection.topic.clone(),
389                connection.topic_metadata_refresh_interval,
390                Arc::clone(&update_partition_count),
391            ),
392        );
393
394        let task_name = format!("kafka_sink_producer:{sink_id}");
395        let progress_key = ProgressKey::new(sink_id);
396
397        let producer = Self {
398            task_name,
399            data_topic: connection.topic.clone(),
400            partition_count,
401            _partition_count_task: partition_count_task.abort_on_drop(),
402            progress_topic: connection
403                .progress_topic(&storage_configuration.connection_context)
404                .into_owned(),
405            progress_key,
406            sink_version,
407            sink_id_header: KAFKA_SINK_EMIT_SINK_ID_HEADER
408                .get(storage_configuration.config_set())
409                .then(|| sink_id.to_string()),
410            producer,
411            statistics,
412            staged_messages: 0,
413            staged_bytes: 0,
414            socket_timeout: timeout_config.socket_timeout,
415            transaction_timeout: timeout_config.transaction_timeout,
416        };
417
418        let timeout = timeout_config.socket_timeout;
419        producer
420            .spawn_blocking(move |p| p.init_transactions(timeout))
421            .await?;
422
423        // We have just called init_transactions, which means that we have fenced out all previous
424        // transactional producers, making it safe to determine the resume upper.
425        let progress = determine_sink_progress(
426            sink_id,
427            connection,
428            storage_configuration,
429            Arc::clone(&metrics),
430        )
431        .await?;
432
433        let resume_upper = match progress {
434            Some(progress) => {
435                if sink_version < progress.version {
436                    return Err(ContextCreationError::Other(anyhow!(
437                        "Fenced off by newer version of the sink. ours={} theirs={}",
438                        sink_version,
439                        progress.version
440                    )));
441                }
442                progress.frontier
443            }
444            None => {
445                mz_storage_client::sink::ensure_kafka_topic(
446                    connection,
447                    storage_configuration,
448                    &connection.topic,
449                    &connection.topic_options,
450                    EnsureTopicConfig::Skip,
451                )
452                .await?;
453                Antichain::from_elem(Timestamp::minimum())
454            }
455        };
456
457        // At this point the topic must exist and so we can query for its
458        // partition count. Even though we have a background task to fetch the
459        // partition count, we do this synchronously to ensure we don't attempt
460        // to produce any messages with our initial partition count of 0.
461        let partition_count =
462            fetch_partition_count(&producer.producer, sink_id, &connection.topic).await?;
463        update_partition_count(partition_count);
464
465        Ok((producer, resume_upper))
466    }
467
468    /// Runs the blocking operation `f` on the producer in the tokio threadpool and checks for SSH
469    /// status in case of failure.
470    async fn spawn_blocking<F, R>(&self, f: F) -> Result<R, ContextCreationError>
471    where
472        F: FnOnce(
473                ThreadedProducer<TunnelingClientContext<MzClientContext>>,
474            ) -> Result<R, KafkaError>
475            + Send
476            + 'static,
477        R: Send + 'static,
478    {
479        let producer = self.producer.clone();
480        task::spawn_blocking(|| &self.task_name, move || f(producer))
481            .await
482            .check_ssh_status(self.producer.context())
483    }
484
485    async fn begin_transaction(&self) -> Result<(), ContextCreationError> {
486        self.spawn_blocking(|p| p.begin_transaction()).await
487    }
488
489    /// Synchronously puts the provided message to librdkafka's send queue. This method only
490    /// returns an error if the queue is full. Handling this error by buffering the message and
491    /// retrying is equivalent to adjusting the maximum number of queued items in rdkafka so it is
492    /// adviced that callers only handle this error in order to apply backpressure to the rest of
493    /// the system.
494    fn send(
495        &mut self,
496        message: &KafkaMessage,
497        time: Timestamp,
498        diff: Diff,
499    ) -> Result<(), KafkaError> {
500        assert_eq!(diff, Diff::ONE, "invalid sink update");
501
502        let mut headers = OwnedHeaders::new().insert(Header {
503            key: "materialize-timestamp",
504            value: Some(time.to_string().as_bytes()),
505        });
506        if let Some(sink_id) = &self.sink_id_header {
507            headers = headers.insert(Header {
508                key: "materialize-sink-id",
509                value: Some(sink_id.as_bytes()),
510            });
511        }
512        for header in &message.headers {
513            // Headers that start with `materialize-` are reserved for our
514            // internal use, so we silently drop any such user-specified
515            // headers. While this behavior is documented, it'd be a nicer UX to
516            // send a warning or error somewhere. Unfortunately sinks don't have
517            // anywhere user-visible to send errors. See database-issues#5148.
518            if header.key.starts_with("materialize-") {
519                continue;
520            }
521
522            headers = headers.insert(Header {
523                key: header.key.as_str(),
524                value: header.value.as_ref(),
525            });
526        }
527
528        let pc = self
529            .partition_count
530            .load(std::sync::atomic::Ordering::SeqCst);
531        let partition = Some(i32::try_from(message.hash % pc).unwrap());
532
533        let record = BaseRecord {
534            topic: &self.data_topic,
535            key: message.key.as_ref(),
536            payload: message.value.as_ref(),
537            headers: Some(headers),
538            partition,
539            timestamp: None,
540            delivery_opaque: (),
541        };
542        let key_size = message.key.as_ref().map(|k| k.len()).unwrap_or(0);
543        let value_size = message.value.as_ref().map(|k| k.len()).unwrap_or(0);
544        let headers_size = message
545            .headers
546            .iter()
547            .map(|h| h.key.len() + h.value.as_ref().map(|v| v.len()).unwrap_or(0))
548            .sum::<usize>();
549        let record_size = u64::cast_from(key_size + value_size + headers_size);
550        self.statistics.inc_messages_staged_by(1);
551        self.staged_messages += 1;
552        self.statistics.inc_bytes_staged_by(record_size);
553        self.staged_bytes += record_size;
554        self.producer.send(record).map_err(|(e, _)| e)
555    }
556
557    /// Commits all the staged updates of the currently open transaction plus a progress record
558    /// describing `upper` to the progress topic.
559    async fn commit_transaction(
560        &mut self,
561        upper: Antichain<Timestamp>,
562    ) -> Result<(), ContextCreationError> {
563        let progress = ProgressRecord {
564            frontier: upper,
565            version: self.sink_version,
566        };
567        let payload = serde_json::to_vec(&progress).expect("infallible");
568        let record = BaseRecord::to(&self.progress_topic)
569            .payload(&payload)
570            .key(&self.progress_key);
571        self.producer.send(record).map_err(|(e, _)| e)?;
572
573        fail::fail_point!("kafka_sink_commit_transaction");
574
575        let timeout = self.transaction_timeout;
576        match self
577            .spawn_blocking(move |p| p.commit_transaction(timeout))
578            .await
579        {
580            Ok(()) => {
581                self.statistics
582                    .inc_messages_committed_by(self.staged_messages);
583                self.statistics.inc_bytes_committed_by(self.staged_bytes);
584                self.staged_messages = 0;
585                self.staged_bytes = 0;
586                Ok(())
587            }
588            Err(ContextCreationError::KafkaError(KafkaError::Transaction(err))) => {
589                // Make one attempt at aborting the transaction before letting the error percolate
590                // up and the process exit. Aborting allows the consumers of the topic to skip over
591                // any messages we've written in the transaction, so it's polite to do... but if it
592                // fails, the transaction will be aborted either when fenced out by a future
593                // version of this producer or by the broker-side timeout.
594                if err.txn_requires_abort() {
595                    let timeout = self.socket_timeout;
596                    self.spawn_blocking(move |p| p.abort_transaction(timeout))
597                        .await?;
598                }
599                Err(ContextCreationError::KafkaError(KafkaError::Transaction(
600                    err,
601                )))
602            }
603            Err(err) => Err(err),
604        }
605    }
606}
607
608/// Listens for statistics updates from librdkafka and updates our Prometheus metrics.
609async fn collect_statistics(
610    mut receiver: watch::Receiver<Statistics>,
611    metrics: Arc<KafkaSinkMetrics>,
612) {
613    while receiver.changed().await.is_ok() {
614        // The librdkafka per-broker statistics are either running totals (counters)
615        // or point-in-time values (gauges). In both cases we aggregate across brokers
616        // by re-summing from scratch each interval, so these accumulators are reset
617        // every time statistics are fetched.
618        //
619        // see <https://docs.confluent.io/platform/current/clients/librdkafka/html/md_STATISTICS.html#autotoc_md121>
620        let mut outbuf_cnt: i64 = 0;
621        let mut outbuf_msg_cnt: i64 = 0;
622        let mut waitresp_cnt: i64 = 0;
623        let mut waitresp_msg_cnt: i64 = 0;
624        let mut txerrs: u64 = 0;
625        let mut txretries: u64 = 0;
626        let mut req_timeouts: u64 = 0;
627        let mut connects: i64 = 0;
628        let mut disconnects: i64 = 0;
629
630        let stats = receiver.borrow();
631        for broker in stats.brokers.values() {
632            outbuf_cnt += broker.outbuf_cnt;
633            outbuf_msg_cnt += broker.outbuf_msg_cnt;
634            waitresp_cnt += broker.waitresp_cnt;
635            waitresp_msg_cnt += broker.waitresp_msg_cnt;
636            txerrs += broker.txerrs;
637            txretries += broker.txretries;
638            req_timeouts += broker.req_timeouts;
639            connects += broker.connects.unwrap_or(0);
640            disconnects += broker.disconnects.unwrap_or(0);
641        }
642        metrics.rdkafka_msg_cnt.set(stats.msg_cnt);
643        metrics.rdkafka_msg_size.set(stats.msg_size);
644        metrics.rdkafka_txmsgs.set(stats.txmsgs);
645        metrics.rdkafka_txmsg_bytes.set(stats.txmsg_bytes);
646        metrics.rdkafka_tx.set(stats.tx);
647        metrics.rdkafka_tx_bytes.set(stats.tx_bytes);
648        metrics.rdkafka_outbuf_cnt.set(outbuf_cnt);
649        metrics.rdkafka_outbuf_msg_cnt.set(outbuf_msg_cnt);
650        metrics.rdkafka_waitresp_cnt.set(waitresp_cnt);
651        metrics.rdkafka_waitresp_msg_cnt.set(waitresp_msg_cnt);
652        metrics.rdkafka_txerrs.set(txerrs);
653        metrics.rdkafka_txretries.set(txretries);
654        metrics.rdkafka_req_timeouts.set(req_timeouts);
655        metrics.rdkafka_connects.set(connects);
656        metrics.rdkafka_disconnects.set(disconnects);
657    }
658}
659
660/// A message to produce to Kafka.
661#[derive(Debug, Clone, Serialize, Deserialize)]
662struct KafkaMessage {
663    /// A hash of the key that can be used for partitioning.
664    hash: u64,
665    /// The message key.
666    key: Option<Vec<u8>>,
667    /// The message value.
668    value: Option<Vec<u8>>,
669    /// Message headers.
670    headers: Vec<KafkaHeader>,
671}
672
673/// A header to attach to a Kafka message.
674#[derive(Debug, Clone, Serialize, Deserialize)]
675struct KafkaHeader {
676    /// The header key.
677    key: String,
678    /// The header value.
679    value: Option<Vec<u8>>,
680}
681
682/// Sinks a collection of encoded rows to Kafka.
683///
684/// This operator exchanges all updates to a single worker by hashing on the given sink `id`.
685///
686/// Updates are sent in ascending timestamp order.
687fn sink_collection<'scope>(
688    name: String,
689    input: VecCollection<'scope, Timestamp, KafkaMessage, Diff>,
690    sink_id: GlobalId,
691    connection: KafkaSinkConnection,
692    storage_configuration: StorageConfiguration,
693    sink: &StorageSinkDesc<CollectionMetadata, Timestamp>,
694    metrics: KafkaSinkMetrics,
695    statistics: SinkStatistics,
696    write_handle: impl Future<
697        Output = anyhow::Result<WriteHandle<SourceData, (), Timestamp, StorageDiff>>,
698    > + 'static,
699    write_frontier: Rc<RefCell<Antichain<Timestamp>>>,
700) -> (
701    StreamVec<'scope, Timestamp, HealthStatusMessage>,
702    PressOnDropButton,
703) {
704    let scope = input.scope();
705    let mut builder = AsyncOperatorBuilder::new(name.clone(), input.inner.scope());
706
707    // We want exactly one worker to send all the data to the sink topic.
708    let hashed_id = sink_id.hashed();
709    let is_active_worker = usize::cast_from(hashed_id) % scope.peers() == scope.index();
710    let buffer_min_capacity =
711        KAFKA_BUFFERED_EVENT_RESIZE_THRESHOLD_ELEMENTS.handle(storage_configuration.config_set());
712
713    let mut input = builder.new_disconnected_input(input.inner, Exchange::new(move |_| hashed_id));
714
715    let as_of = sink.as_of.clone();
716    let sink_version = sink.version;
717    let (button, errors) = builder.build_fallible(move |_caps| {
718        Box::pin(async move {
719            if !is_active_worker {
720                write_frontier.borrow_mut().clear();
721                return Ok(());
722            }
723
724            fail::fail_point!("kafka_sink_creation_error", |_| Err(
725                ContextCreationError::Other(anyhow::anyhow!("synthetic error"))
726            ));
727
728            let mut write_handle = write_handle.await?;
729
730            let metrics = Arc::new(metrics);
731
732            let (mut producer, resume_upper) = TransactionalProducer::new(
733                sink_id,
734                &connection,
735                &storage_configuration,
736                Arc::clone(&metrics),
737                statistics,
738                sink_version,
739            )
740            .await?;
741
742            // The input has overcompacted if
743            let overcompacted =
744                // ..we have made some progress in the past
745                *resume_upper != [Timestamp::minimum()] &&
746                // ..but the since frontier is now beyond that
747                !PartialOrder::less_equal(&as_of, &resume_upper);
748            if overcompacted {
749                let err =
750                    super::overcompacted_error(&name, &as_of, &resume_upper, "recreate the sink");
751                // This would normally be an assertion but because it can happen after a
752                // Materialize backup/restore we log an error so that it appears on Sentry but
753                // leaves the rest of the objects in the cluster unaffected.
754                error!("{err}");
755                return Err(anyhow!("{err}").into());
756            }
757
758            info!(
759                "{name}: as_of: {}, resume upper: {}",
760                as_of.pretty(),
761                resume_upper.pretty()
762            );
763
764            // The section below relies on TotalOrder for correctness so we'll work with timestamps
765            // directly to make sure this doesn't compile if someone attempts to make this operator
766            // generic over partial orders in the future.
767            let Some(mut upper) = resume_upper.clone().into_option() else {
768                write_frontier.borrow_mut().clear();
769                return Ok(());
770            };
771
772            let mut deferred_updates = vec![];
773            let mut extra_updates = vec![];
774            // We must wait until we have data to commit before starting a transaction because
775            // Kafka doesn't have a heartbeating mechanism to keep a transaction open indefinitely.
776            // This flag tracks whether we have started the transaction.
777            let mut transaction_begun = false;
778            while let Some(event) = input.next().await {
779                match event {
780                    Event::Data(_cap, batch) => {
781                        for (message, time, diff) in batch {
782                            // We want to publish updates in time order and we know that we have
783                            // already committed all times not beyond `upper`. Therefore, if this
784                            // update happens *exactly* at upper then it is the minimum pending
785                            // time and so emitting it now will not violate the timestamp publish
786                            // order. This optimization is load bearing because it is the mechanism
787                            // by which we incrementally stream the initial snapshot out to Kafka
788                            // instead of buffering it all in memory first. This argument doesn't
789                            // hold for partially ordered time because many different timestamps
790                            // can be *exactly* at upper but we can't know ahead of time which one
791                            // will be advanced in the next progress message.
792                            match upper.cmp(&time) {
793                                Ordering::Less => deferred_updates.push((message, time, diff)),
794                                Ordering::Equal => {
795                                    if !transaction_begun {
796                                        producer.begin_transaction().await?;
797                                        transaction_begun = true;
798                                    }
799                                    producer.send(&message, time, diff)?;
800                                }
801                                Ordering::Greater => continue,
802                            }
803                        }
804                    }
805                    Event::Progress(progress) => {
806                        // Ignore progress updates before our resumption frontier
807                        if !PartialOrder::less_equal(&resume_upper, &progress) {
808                            continue;
809                        }
810                        // Also ignore progress updates until we are past the as_of frontier. This
811                        // is to avoid the following pathological scenario:
812                        // 1. Sink gets instantiated with an as_of = {10}, resume_upper = {0}.
813                        //    `progress` initially jumps at {10}, then the snapshot appears at time
814                        //    10.
815                        // 2. `progress` would normally advance to say {11} and we would commit the
816                        //    snapshot but clusterd crashes instead.
817                        // 3. A new cluster restarts the sink with an earlier as_of, say {5}. This
818                        //    is valid, the earlier as_of has strictly more information. The
819                        //    snapshot now appears at time 5.
820                        //
821                        // If we were to commit an empty transaction in step 1 and advanced the
822                        // resume_upper to {10} then in step 3 we would ignore the snapshot that
823                        // now appears at 5 completely. So it is important to only start committing
824                        // transactions after we're strictly beyond the as_of.
825                        // TODO(petrosagg): is this logic an indication of us holding something
826                        // wrong elsewhere? Investigate.
827                        // Note: !PartialOrder::less_than(as_of, progress) would not be equivalent
828                        // nor correct for partially ordered times.
829                        if !as_of.iter().all(|t| !progress.less_equal(t)) {
830                            continue;
831                        }
832                        if !transaction_begun {
833                            producer.begin_transaction().await?;
834                        }
835
836                        extra_updates.extend(
837                            deferred_updates
838                                .extract_if(.., |(_, time, _)| !progress.less_equal(time)),
839                        );
840                        // Shrink after draining items out, so the call actually
841                        // reduces capacity in the oversized-buffer scenario
842                        // (e.g. progress topic was deleted and resume upper is 0).
843                        deferred_updates.shrink_to(buffer_min_capacity.get());
844                        extra_updates.sort_unstable_by(|a, b| a.1.cmp(&b.1));
845
846                        for (message, time, diff) in extra_updates.drain(..) {
847                            producer.send(&message, time, diff)?;
848                        }
849                        extra_updates.shrink_to(buffer_min_capacity.get());
850
851                        debug!("{name}: committing transaction for {}", progress.pretty());
852                        producer.commit_transaction(progress.clone()).await?;
853                        transaction_begun = false;
854                        let mut expect_upper = write_handle.shared_upper();
855                        loop {
856                            if PartialOrder::less_equal(&progress, &expect_upper) {
857                                // The frontier has already been advanced as far as necessary.
858                                break;
859                            }
860                            // TODO(sinks): include the high water mark in the output topic for
861                            // the messages we've published, if and when we allow reads to the sink
862                            // directly, to allow monitoring the progress of the sink in terms of
863                            // the output system.
864                            const EMPTY: &[((SourceData, ()), Timestamp, StorageDiff)] = &[];
865                            match write_handle
866                                .compare_and_append(EMPTY, expect_upper, progress.clone())
867                                .await
868                                .expect("valid usage")
869                            {
870                                Ok(()) => break,
871                                Err(mismatch) => {
872                                    expect_upper = mismatch.current;
873                                }
874                            }
875                        }
876                        write_frontier.borrow_mut().clone_from(&progress);
877                        match progress.into_option() {
878                            Some(new_upper) => upper = new_upper,
879                            None => break,
880                        }
881                    }
882                }
883            }
884            Ok(())
885        })
886    });
887
888    let statuses = errors.map(|error: Rc<ContextCreationError>| {
889        let hint = match *error {
890            ContextCreationError::KafkaError(KafkaError::Transaction(ref e)) => {
891                if e.is_retriable() && e.code() == RDKafkaErrorCode::OperationTimedOut {
892                    let hint = "If you're running a single Kafka broker, ensure that the configs \
893                        transaction.state.log.replication.factor, transaction.state.log.min.isr, \
894                        and offsets.topic.replication.factor are set to 1 on the broker";
895                    Some(hint.to_owned())
896                } else {
897                    None
898                }
899            }
900            _ => None,
901        };
902
903        HealthStatusMessage {
904            id: None,
905            update: HealthStatusUpdate::halting(format!("{}", error.display_with_causes()), hint),
906            namespace: if matches!(*error, ContextCreationError::Ssh(_)) {
907                StatusNamespace::Ssh
908            } else {
909                StatusNamespace::Kafka
910            },
911        }
912    });
913
914    (statuses, button.press_on_drop())
915}
916
917/// Determines the latest progress record from the specified topic for the given
918/// progress key.
919///
920/// IMPORTANT: to achieve exactly once guarantees, the producer that will resume
921/// production at the returned timestamp *must* have called `init_transactions`
922/// prior to calling this method.
923async fn determine_sink_progress(
924    sink_id: GlobalId,
925    connection: &KafkaSinkConnection,
926    storage_configuration: &StorageConfiguration,
927    metrics: Arc<KafkaSinkMetrics>,
928) -> Result<Option<ProgressRecord>, ContextCreationError> {
929    // ****************************** WARNING ******************************
930    // Be VERY careful when editing the code in this function. It is very easy
931    // to accidentally introduce a correctness or liveness bug when refactoring
932    // this code.
933    // ****************************** WARNING ******************************
934
935    let TimeoutConfig {
936        fetch_metadata_timeout,
937        progress_record_fetch_timeout,
938        ..
939    } = storage_configuration.parameters.kafka_timeout_config;
940
941    let client_id = connection.client_id(
942        storage_configuration.config_set(),
943        &storage_configuration.connection_context,
944        sink_id,
945    );
946    let group_id = connection.progress_group_id(&storage_configuration.connection_context, sink_id);
947    let progress_topic = connection
948        .progress_topic(&storage_configuration.connection_context)
949        .into_owned();
950    let progress_topic_options = &connection.connection.progress_topic_options;
951    let progress_key = ProgressKey::new(sink_id);
952
953    let common_options = btreemap! {
954        // Consumer group ID, which may have been overridden by the user. librdkafka requires this,
955        // even though we'd prefer to disable the consumer group protocol entirely.
956        "group.id" => group_id,
957        // Allow Kafka monitoring tools to identify this consumer.
958        "client.id" => client_id,
959        "enable.auto.commit" => "false".into(),
960        "auto.offset.reset" => "earliest".into(),
961        // The fetch loop below needs EOF notifications to reliably detect that we have reached the
962        // high watermark.
963        "enable.partition.eof" => "true".into(),
964    };
965
966    // Construct two cliens in read committed and read uncommitted isolations respectively. See
967    // comment below for an explanation on why we need it.
968    let progress_client_read_committed: BaseConsumer<_> = {
969        let mut opts = common_options.clone();
970        opts.insert("isolation.level", "read_committed".into());
971        let ctx = MzClientContext::default();
972        connection
973            .connection
974            .create_with_context(storage_configuration, ctx, &opts, InTask::Yes)
975            .await?
976    };
977
978    let progress_client_read_uncommitted: BaseConsumer<_> = {
979        let mut opts = common_options;
980        opts.insert("isolation.level", "read_uncommitted".into());
981        let ctx = MzClientContext::default();
982        connection
983            .connection
984            .create_with_context(storage_configuration, ctx, &opts, InTask::Yes)
985            .await?
986    };
987
988    let ctx = Arc::clone(progress_client_read_committed.client().context());
989
990    // Ensure the progress topic exists.
991    let ensure_topic_config =
992        match &*SINK_ENSURE_TOPIC_CONFIG.get(storage_configuration.config_set()) {
993            "skip" => EnsureTopicConfig::Skip,
994            "check" => EnsureTopicConfig::Check,
995            "alter" => EnsureTopicConfig::Alter,
996            _ => {
997                tracing::warn!(
998                    topic = progress_topic,
999                    "unexpected value for ensure-topic-config; skipping checks"
1000                );
1001                EnsureTopicConfig::Skip
1002            }
1003        };
1004    mz_storage_client::sink::ensure_kafka_topic(
1005        connection,
1006        storage_configuration,
1007        &progress_topic,
1008        progress_topic_options,
1009        ensure_topic_config,
1010    )
1011    .await
1012    .add_context("error registering kafka progress topic for sink")?;
1013
1014    // We are about to spawn a blocking task that cannot be aborted by simply calling .abort() on
1015    // its handle but we must be able to cancel it prompty so as to not leave long running
1016    // operations around when interest to this task is lost. To accomplish this we create a shared
1017    // token of which a weak reference is given to the task and a strong reference is held by the
1018    // parent task. The task periodically checks if its weak reference is still valid before
1019    // continuing its work.
1020    let parent_token = Arc::new(());
1021    let child_token = Arc::downgrade(&parent_token);
1022    let task_name = format!("get_latest_ts:{sink_id}");
1023    let sink_progress_search = SINK_PROGRESS_SEARCH.get(storage_configuration.config_set());
1024    let result = task::spawn_blocking(|| task_name, move || {
1025        let progress_topic = progress_topic.as_ref();
1026        // Ensure the progress topic has exactly one partition. Kafka only
1027        // guarantees ordering within a single partition, and we need a strict
1028        // order on the progress messages we read and write.
1029        let partitions = match mz_kafka_util::client::get_partitions(
1030            progress_client_read_committed.client(),
1031            progress_topic,
1032            fetch_metadata_timeout,
1033        ) {
1034            Ok(partitions) => partitions,
1035            Err(GetPartitionsError::TopicDoesNotExist) => {
1036                // The progress topic doesn't exist, which indicates there is
1037                // no committed timestamp.
1038                return Ok(None);
1039            }
1040            e => e.with_context(|| {
1041                format!(
1042                    "Unable to fetch metadata about progress topic {}",
1043                    progress_topic
1044                )
1045            })?,
1046        };
1047        if partitions.len() != 1 {
1048            bail!(
1049                    "Progress topic {} should contain a single partition, but instead contains {} partitions",
1050                    progress_topic, partitions.len(),
1051                );
1052        }
1053        let partition = partitions.into_element();
1054
1055        // We scan from the beginning and see if we can find a progress record. We have
1056        // to do it like this because Kafka Control Batches mess with offsets. We
1057        // therefore cannot simply take the last offset from the back and expect a
1058        // progress message there. With a transactional producer, the OffsetTail(1) will
1059        // not point to an progress message but a control message. With aborted
1060        // transactions, there might even be a lot of garbage at the end of the
1061        // topic or in between.
1062
1063        metrics.consumed_progress_records.set(0);
1064
1065        // First, determine the current high water mark for the progress topic.
1066        // This is the position our `progress_client` consumer *must* reach
1067        // before we can conclude that we've seen the latest progress record for
1068        // the specified `progress_key`. A safety argument:
1069        //
1070        //   * Our caller has initialized transactions before calling this
1071        //     method, which prevents the prior incarnation of this sink from
1072        //     committing any further progress records.
1073        //
1074        //   * We use `read_uncommitted` isolation to ensure that we fetch the
1075        //     true high water mark for the topic, even if there are pending
1076        //     transactions in the topic. If we used the `read_committed`
1077        //     isolation level, we'd instead get the "last stable offset" (LSO),
1078        //     which is the offset of the first message in an open transaction,
1079        //     which might not include the last progress message committed for
1080        //     this sink! (While the caller of this function has fenced out
1081        //     older producers for this sink, *other* sinks writing using the
1082        //     same progress topic might have long-running transactions that
1083        //     hold back the LSO.)
1084        //
1085        //   * If another sink spins up and fences out the producer for this
1086        //     incarnation of the sink, we may not see the latest progress
1087        //     record... but since the producer has been fenced out, it will be
1088        //     unable to act on our stale information.
1089        //
1090        let (lo, hi) = progress_client_read_uncommitted
1091            .fetch_watermarks(progress_topic, partition, fetch_metadata_timeout)
1092            .map_err(|e| {
1093                anyhow!(
1094                    "Failed to fetch metadata while reading from progress topic: {}",
1095                    e
1096                )
1097            })?;
1098
1099        // This topic might be long, but the desired offset will usually be right near the end.
1100        // Instead of always scanning through the entire topic, we scan through exponentially-growing
1101        // suffixes of it. (Because writes are ordered, the largest progress record in any suffix,
1102        // if present, is the global max.) If we find it in one of our suffixes, we've saved at least
1103        // an order of magnitude of work; if we don't, we've added at most a constant factor.
1104        let mut start_indices = vec![lo];
1105        if sink_progress_search {
1106            let mut lookback = hi.saturating_sub(lo) / 10;
1107            while lookback >= 20_000 {
1108                start_indices.push(hi - lookback);
1109                lookback /= 10;
1110            }
1111        }
1112        for lo in start_indices.into_iter().rev() {
1113            if let Some(found) = progress_search(
1114                &progress_client_read_committed,
1115                progress_record_fetch_timeout,
1116                progress_topic,
1117                partition,
1118                lo,
1119                hi,
1120                progress_key.clone(),
1121                Weak::clone(&child_token),
1122                Arc::clone(&metrics)
1123            )? {
1124                return Ok(Some(found));
1125            }
1126        }
1127        Ok(None)
1128    }).await.check_ssh_status(&ctx);
1129    // Express interest to the computation until after we've received its result
1130    drop(parent_token);
1131    result
1132}
1133
1134fn progress_search<C: ConsumerContext + 'static>(
1135    progress_client_read_committed: &BaseConsumer<C>,
1136    progress_record_fetch_timeout: Duration,
1137    progress_topic: &str,
1138    partition: i32,
1139    lo: i64,
1140    hi: i64,
1141    progress_key: ProgressKey,
1142    child_token: Weak<()>,
1143    metrics: Arc<KafkaSinkMetrics>,
1144) -> anyhow::Result<Option<ProgressRecord>> {
1145    // Seek to the beginning of the given range in the progress topic.
1146    let mut tps = TopicPartitionList::new();
1147    tps.add_partition(progress_topic, partition);
1148    tps.set_partition_offset(progress_topic, partition, Offset::Offset(lo))?;
1149    progress_client_read_committed
1150        .assign(&tps)
1151        .with_context(|| {
1152            format!(
1153                "Error seeking in progress topic {}:{}",
1154                progress_topic, partition
1155            )
1156        })?;
1157
1158    // Helper to get the progress consumer's current position.
1159    let get_position = || {
1160        if child_token.strong_count() == 0 {
1161            bail!("operation cancelled");
1162        }
1163        let position = progress_client_read_committed
1164            .position()?
1165            .find_partition(progress_topic, partition)
1166            .ok_or_else(|| {
1167                anyhow!(
1168                    "No position info found for progress topic {}",
1169                    progress_topic
1170                )
1171            })?
1172            .offset();
1173        let position = match position {
1174            Offset::Offset(position) => position,
1175            // An invalid offset indicates the consumer has not yet read a
1176            // message. Since we assigned the consumer to the beginning of
1177            // the topic, it's safe to return the low water mark here, which
1178            // indicates the position before the first possible message.
1179            //
1180            // Note that it's important to return the low water mark and not
1181            // the minimum possible offset (i.e., zero) in order to break
1182            // out of the loop if the topic is empty but the low water mark
1183            // is greater than zero.
1184            Offset::Invalid => lo,
1185            _ => bail!(
1186                "Consumer::position returned offset of wrong type: {:?}",
1187                position
1188            ),
1189        };
1190        // Record the outstanding number of progress records that remain to be processed
1191        let outstanding = u64::try_from(std::cmp::max(0, hi - position)).unwrap();
1192        metrics.outstanding_progress_records.set(outstanding);
1193        Ok(position)
1194    };
1195
1196    info!("fetching latest progress record for {progress_key}, lo/hi: {lo}/{hi}");
1197
1198    // Read messages until the consumer is positioned at or beyond the high
1199    // water mark.
1200    //
1201    // We use `read_committed` isolation to ensure we don't see progress
1202    // records for transactions that did not commit. This means we have to
1203    // wait for the LSO to progress to the high water mark `hi`, which means
1204    // waiting for any open transactions for other sinks using the same
1205    // progress topic to complete. We set a short transaction timeout (10s)
1206    // to ensure we never need to wait more than 10s.
1207    //
1208    // Note that the stall time on the progress topic is not a function of
1209    // transaction size. We've designed our transactions so that the
1210    // progress record is always written last, after all the data has been
1211    // written, and so the window of time in which the progress topic has an
1212    // open transaction is quite small. The only vulnerability is if another
1213    // sink using the same progress topic crashes in that small window
1214    // between writing the progress record and committing the transaction,
1215    // in which case we have to wait out the transaction timeout.
1216    //
1217    // Important invariant: we only exit this loop successfully (i.e., not
1218    // returning an error) if we have positive proof of a position at or
1219    // beyond the high water mark. To make this invariant easy to check, do
1220    // not use `break` in the body of the loop.
1221    let mut last_progress: Option<ProgressRecord> = None;
1222    loop {
1223        let current_position = get_position()?;
1224
1225        if current_position >= hi {
1226            // consumer is at or beyond the high water mark and has read enough messages
1227            break;
1228        }
1229
1230        let message = match progress_client_read_committed.poll(progress_record_fetch_timeout) {
1231            Some(Ok(message)) => message,
1232            Some(Err(KafkaError::PartitionEOF(_))) => {
1233                // No message, but the consumer's position may have advanced
1234                // past a transaction control message that positions us at
1235                // or beyond the high water mark. Go around the loop again
1236                // to check.
1237                continue;
1238            }
1239            Some(Err(e)) => bail!("failed to fetch progress message {e}"),
1240            None => {
1241                bail!(
1242                    "timed out while waiting to reach high water mark of non-empty \
1243                        topic {progress_topic}:{partition}, lo/hi: {lo}/{hi}, current position: {current_position}"
1244                );
1245            }
1246        };
1247
1248        if message.key() != Some(progress_key.to_bytes()) {
1249            // This is a progress message for a different sink.
1250            continue;
1251        }
1252
1253        metrics.consumed_progress_records.inc();
1254
1255        let Some(payload) = message.payload() else {
1256            continue;
1257        };
1258        let progress = parse_progress_record(payload)?;
1259
1260        match last_progress {
1261            Some(last_progress)
1262                if !PartialOrder::less_equal(&last_progress.frontier, &progress.frontier) =>
1263            {
1264                bail!(
1265                    "upper regressed in topic {progress_topic}:{partition} from {:?} to {:?}",
1266                    last_progress.frontier,
1267                    progress.frontier,
1268                );
1269            }
1270            _ => last_progress = Some(progress),
1271        }
1272    }
1273
1274    // If we get here, we are assured that we've read all messages up to
1275    // the high water mark, and therefore `last_timestamp` contains the
1276    // most recent timestamp for the sink under consideration.
1277    Ok(last_progress)
1278}
1279
1280/// This is the legacy struct that used to be emitted as part of a transactional produce and
1281/// contains the largest timestamp within the batch committed. Since it is just a timestamp it
1282/// cannot encode the fact that a sink has finished and deviates from upper frontier semantics.
1283/// Materialize no longer produces this record but it's possible that we encounter this in topics
1284/// written by older versions. In those cases we convert it into upper semantics by stepping the
1285/// timestamp forward.
1286#[derive(Debug, PartialEq, Serialize, Deserialize)]
1287pub struct LegacyProgressRecord {
1288    // Double Option to tell apart an omitted field from one set to null explicitly
1289    // https://github.com/serde-rs/serde/issues/984
1290    #[serde(default, deserialize_with = "deserialize_some")]
1291    pub timestamp: Option<Option<Timestamp>>,
1292}
1293
1294// Any value that is present is considered Some value, including null.
1295fn deserialize_some<'de, T, D>(deserializer: D) -> Result<Option<T>, D::Error>
1296where
1297    T: Deserialize<'de>,
1298    D: Deserializer<'de>,
1299{
1300    Deserialize::deserialize(deserializer).map(Some)
1301}
1302
1303/// This struct is emitted as part of a transactional produce, and contains the upper frontier of
1304/// the batch committed. It is used to recover the frontier a sink needs to resume at.
1305#[derive(Debug, PartialEq, Serialize, Deserialize)]
1306pub struct ProgressRecord {
1307    #[serde(
1308        deserialize_with = "deserialize_frontier",
1309        serialize_with = "serialize_frontier"
1310    )]
1311    pub frontier: Antichain<Timestamp>,
1312    #[serde(default)]
1313    pub version: u64,
1314}
1315fn serialize_frontier<S>(frontier: &Antichain<Timestamp>, serializer: S) -> Result<S::Ok, S::Error>
1316where
1317    S: Serializer,
1318{
1319    Serialize::serialize(frontier.elements(), serializer)
1320}
1321
1322fn deserialize_frontier<'de, D>(deserializer: D) -> Result<Antichain<Timestamp>, D::Error>
1323where
1324    D: Deserializer<'de>,
1325{
1326    let times: Vec<Timestamp> = Deserialize::deserialize(deserializer)?;
1327    Ok(Antichain::from(times))
1328}
1329
1330fn parse_progress_record(payload: &[u8]) -> Result<ProgressRecord, anyhow::Error> {
1331    Ok(match serde_json::from_slice::<ProgressRecord>(payload) {
1332        Ok(progress) => progress,
1333        // If we fail to deserialize we might be reading a legacy progress record
1334        Err(_) => match serde_json::from_slice::<LegacyProgressRecord>(payload) {
1335            Ok(LegacyProgressRecord {
1336                timestamp: Some(Some(time)),
1337            }) => ProgressRecord {
1338                frontier: Antichain::from_elem(time.step_forward()),
1339                version: 0,
1340            },
1341            Ok(LegacyProgressRecord {
1342                timestamp: Some(None),
1343            }) => ProgressRecord {
1344                frontier: Antichain::new(),
1345                version: 0,
1346            },
1347            _ => match std::str::from_utf8(payload) {
1348                Ok(payload) => bail!("invalid progress record: {payload}"),
1349                Err(_) => bail!("invalid progress record bytes: {payload:?}"),
1350            },
1351        },
1352    })
1353}
1354
1355/// Fetches the partition count for the identified topic.
1356async fn fetch_partition_count(
1357    producer: &ThreadedProducer<TunnelingClientContext<MzClientContext>>,
1358    sink_id: GlobalId,
1359    topic_name: &str,
1360) -> Result<u64, anyhow::Error> {
1361    let meta = task::spawn_blocking(|| format!("kafka_sink_fetch_partition_count:{sink_id}"), {
1362        let producer = producer.clone();
1363        move || {
1364            producer
1365                .client()
1366                .fetch_metadata(None, DEFAULT_FETCH_METADATA_TIMEOUT)
1367        }
1368    })
1369    .await
1370    .check_ssh_status(producer.context())?;
1371
1372    match meta.topics().iter().find(|t| t.name() == topic_name) {
1373        Some(topic) => {
1374            let partition_count = u64::cast_from(topic.partitions().len());
1375            if partition_count == 0 {
1376                bail!("topic {topic_name} has an impossible partition count of zero");
1377            }
1378            Ok(partition_count)
1379        }
1380        None => bail!("topic {topic_name} does not exist"),
1381    }
1382}
1383
1384/// Fetches the partition count for the identified topic at the specified
1385/// interval.
1386///
1387/// When an updated partition count is discovered, invokes
1388/// `update_partition_count` with the new partition count.
1389async fn fetch_partition_count_loop<F>(
1390    producer: ThreadedProducer<TunnelingClientContext<MzClientContext>>,
1391    sink_id: GlobalId,
1392    topic_name: String,
1393    interval: Duration,
1394    update_partition_count: Arc<F>,
1395) where
1396    F: Fn(u64),
1397{
1398    let mut interval = time::interval(interval);
1399    interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
1400    loop {
1401        interval.tick().await;
1402        match fetch_partition_count(&producer, sink_id, &topic_name).await {
1403            Ok(pc) => update_partition_count(pc),
1404            Err(e) => {
1405                warn!(%sink_id, "failed updating partition count: {e}");
1406                continue;
1407            }
1408        };
1409    }
1410}
1411
1412/// Register an Avro `schema` with the sink's schema registry and build an
1413/// [`AvroEncoder`] framing records for that registry.
1414///
1415/// `subject` is the registry name for the schema, either `{topic}-key` or
1416/// `{topic}-value`. It is the Confluent subject or, for Glue, the schema name.
1417/// Registration happens here in the render cycle, so schemas are re-published
1418/// each time the sink is rendered. The `WireFormat` must carry a registry:
1419/// sinks are never built without one (see the sink planner), so a missing
1420/// registry is unreachable.
1421async fn build_avro_encoder(
1422    desc: RelationDesc,
1423    debezium: bool,
1424    schema: String,
1425    compatibility_level: Option<mz_ccsr::CompatibilityLevel>,
1426    wire_format: WireFormat,
1427    subject: String,
1428    storage_configuration: &StorageConfiguration,
1429) -> Result<AvroEncoder, anyhow::Error> {
1430    let schema_id = match wire_format {
1431        WireFormat::Confluent {
1432            registry: Some(csr),
1433        } => {
1434            let ccsr = csr.connect(storage_configuration, InTask::Yes).await?;
1435            let schema_id = mz_storage_client::sink::publish_kafka_schema(
1436                ccsr,
1437                subject,
1438                schema.clone(),
1439                mz_ccsr::SchemaType::Avro,
1440                compatibility_level,
1441            )
1442            .await
1443            .context("error publishing kafka schemas for sink")?;
1444            AvroSchemaId::Confluent(schema_id)
1445        }
1446        WireFormat::Glue {
1447            registry: Some(glue),
1448        } => {
1449            let enforce_external_addresses = mz_storage_types::dyncfgs::ENFORCE_EXTERNAL_ADDRESSES
1450                .get(storage_configuration.config_set());
1451            let sdk_config = glue
1452                .aws_connection
1453                .connection
1454                .load_sdk_config(
1455                    &storage_configuration.connection_context,
1456                    glue.aws_connection.connection_id,
1457                    InTask::Yes,
1458                    enforce_external_addresses,
1459                )
1460                .await?;
1461            let client = mz_aws_glue_schema_registry::ClientConfig::new(sdk_config).build();
1462            let compatibility =
1463                compatibility_level.map(mz_storage_client::sink::glue_compatibility_from_csr);
1464            // `subject` is used verbatim as the Glue schema name. When it is
1465            // topic-derived (`{topic}-key` or `{topic}-value`) no mangling is
1466            // needed: Kafka topic chars `[a-zA-Z0-9._-]` are a subset of Glue's
1467            // `[a-zA-Z0-9-_$#.]`, and the longest suffix `-value` (6 chars) plus
1468            // the max Kafka topic length (249) lands exactly on Glue's max
1469            // schema name length (255).
1470            //
1471            // A user-supplied schema name carries no such guarantee. As with
1472            // CSR subjects, it is not validated at plan time, so an out-of-range
1473            // or ill-formed name is rejected by Glue here at registration.
1474            //
1475            // Kafka topic name rules:
1476            // https://github.com/a0x8o/kafka/blob/master/core/src/main/scala/kafka/common/Topic.scala
1477            // Glue schema name rules:
1478            // https://docs.aws.amazon.com/glue/latest/webapi/API_CreateSchema.html
1479            let schema_version_id = mz_storage_client::sink::publish_glue_schema(
1480                client,
1481                glue.registry_name,
1482                subject,
1483                schema.clone(),
1484                compatibility,
1485            )
1486            .await
1487            .context("error publishing glue schemas for sink")?;
1488            AvroSchemaId::Glue(schema_version_id)
1489        }
1490        other => unreachable!(
1491            "sink Avro wire_format must carry a registry, got {:?}",
1492            other
1493        ),
1494    };
1495    Ok(AvroEncoder::new(desc, debezium, &schema, schema_id))
1496}
1497
1498/// Walks each arrangement batch and emits encoded Kafka messages, one per
1499/// `DiffPair` observed at each `(key, timestamp)`.
1500///
1501/// When `key_is_synthetic`, the batch keys are per-row hashes used only for
1502/// worker distribution; the emitted `KafkaMessage` uses no key in that case.
1503fn encode_collection<'scope>(
1504    name: String,
1505    batches: SinkBatchStream<'scope>,
1506    envelope: SinkEnvelope,
1507    connection: KafkaSinkConnection,
1508    storage_configuration: StorageConfiguration,
1509    sink_id: GlobalId,
1510    from_id: GlobalId,
1511    key_is_synthetic: bool,
1512) -> (
1513    VecCollection<'scope, Timestamp, KafkaMessage, Diff>,
1514    StreamVec<'scope, Timestamp, HealthStatusMessage>,
1515    PressOnDropButton,
1516) {
1517    let mut builder = AsyncOperatorBuilder::new(name, batches.scope());
1518
1519    let (output, stream) = builder.new_output::<CapacityContainerBuilder<Vec<_>>>();
1520    let mut input = builder.new_input_for(batches, Pipeline, &output);
1521
1522    let (button, errors) = builder.build_fallible(move |caps| {
1523        Box::pin(async move {
1524            let [capset]: &mut [_; 1] = caps.try_into().unwrap();
1525            let key_desc = connection
1526                .key_desc_and_indices
1527                .as_ref()
1528                .map(|(desc, _indices)| desc.clone());
1529            let value_desc = connection.value_desc;
1530
1531            let key_encoder: Option<Box<dyn Encode>> =
1532                match (key_desc, connection.format.key_format) {
1533                    (Some(desc), Some(KafkaSinkFormatType::Bytes)) => {
1534                        Some(Box::new(BinaryEncoder::new(desc, false)))
1535                    }
1536                    (Some(desc), Some(KafkaSinkFormatType::Text)) => {
1537                        Some(Box::new(TextEncoder::new(desc, false)))
1538                    }
1539                    (Some(desc), Some(KafkaSinkFormatType::Json)) => {
1540                        Some(Box::new(JsonEncoder::new(desc, false)))
1541                    }
1542                    (Some(desc), Some(KafkaSinkFormatType::Avro {
1543                        schema,
1544                        compatibility_level,
1545                        schema_name,
1546                        wire_format,
1547                    })) => {
1548                        let subject = schema_name
1549                            .unwrap_or_else(|| format!("{}-key", connection.topic));
1550                        let encoder = build_avro_encoder(
1551                            desc,
1552                            false,
1553                            schema,
1554                            compatibility_level,
1555                            wire_format,
1556                            subject,
1557                            &storage_configuration,
1558                        )
1559                        .await?;
1560                        Some(Box::new(encoder))
1561                    }
1562                    (None, None) => None,
1563                    (desc, format) => {
1564                        return Err(anyhow!(
1565                            "key_desc and key_format must be both set or both unset, but key_desc: {:?}, key_format: {:?}",
1566                            desc,
1567                            format
1568                        ))
1569                    }
1570                };
1571
1572            // whether to apply the debezium envelope to the value encoding
1573            let debezium = matches!(envelope, SinkEnvelope::Debezium);
1574
1575            let value_encoder: Box<dyn Encode> = match connection.format.value_format {
1576                KafkaSinkFormatType::Bytes => Box::new(BinaryEncoder::new(value_desc, debezium)),
1577                KafkaSinkFormatType::Text => Box::new(TextEncoder::new(value_desc, debezium)),
1578                KafkaSinkFormatType::Json => Box::new(JsonEncoder::new(value_desc, debezium)),
1579                KafkaSinkFormatType::Avro {
1580                    schema,
1581                    compatibility_level,
1582                    schema_name,
1583                    wire_format,
1584                } => {
1585                    let subject = schema_name
1586                        .unwrap_or_else(|| format!("{}-value", connection.topic));
1587                    let encoder = build_avro_encoder(
1588                        value_desc,
1589                        debezium,
1590                        schema,
1591                        compatibility_level,
1592                        wire_format,
1593                        subject,
1594                        &storage_configuration,
1595                    )
1596                    .await?;
1597                    Box::new(encoder)
1598                }
1599            };
1600
1601            // !IMPORTANT!
1602            // Correctness of this operator relies on no fallible operations happening after this
1603            // point. This is a temporary workaround of build_fallible's bad interaction of owned
1604            // capabilities and errors.
1605            // TODO(petrosagg): Make the fallible async operator safe
1606            *capset = CapabilitySet::new();
1607
1608            let mut row_buf = Row::default();
1609            let mut datums = DatumVec::new();
1610            let mut pk_warner =
1611                (!key_is_synthetic).then(|| PkViolationWarner::new(sink_id, from_id));
1612
1613            while let Some(event) = input.next().await {
1614                if let Event::Data(cap, mut batches) = event {
1615                    for span in batches.drain(..) {
1616                        // A span with no updates carries no batch to encode.
1617                        let Some(batch) = &span.inner else {
1618                            continue;
1619                        };
1620                        for_each_diff_pair(batch, |key, time, value| {
1621                            if let Some(warner) = pk_warner.as_mut() {
1622                                warner.observe(key, time);
1623                            }
1624                            // Only emit the arrangement key when the user configured one; relation-key
1625                            // and synthetic-hash arrangements exist purely for grouping / worker
1626                            // distribution and have no corresponding key encoder.
1627                            let key_for_message = if key_encoder.is_some() { key } else { &None };
1628
1629                            let mut hash = None;
1630                            let mut headers = vec![];
1631                            if connection.headers_index.is_some()
1632                                || connection.partition_by.is_some()
1633                            {
1634                                // Header values and partition by values are derived from the row
1635                                // that produces an event. But it is ambiguous whether to use the
1636                                // `before` or `after` from the event. The rule applied here is
1637                                // simple: use `after` if it exists (insertions and updates),
1638                                // otherwise fall back to `before` (deletions).
1639                                //
1640                                // It is up to the SQL planner to ensure this produces sensible
1641                                // results. (When using the upsert envelope and both `before` and
1642                                // `after` are present, it's always unambiguous to use `after`
1643                                // because that's all that will be present in the Kafka message;
1644                                // when using the Debezium envelope, it's okay to refer to columns
1645                                // in the key because those are guaranteed to be the same in both
1646                                // `before` and `after`.)
1647                                let row = value
1648                                    .after
1649                                    .as_ref()
1650                                    .or(value.before.as_ref())
1651                                    .expect("one of before or after must be set");
1652                                let row = datums.borrow_with(row);
1653
1654                                if let Some(i) = connection.headers_index {
1655                                    headers = encode_headers(row[i]);
1656                                }
1657
1658                                if let Some(partition_by) = &connection.partition_by {
1659                                    hash = Some(evaluate_partition_by(partition_by, &row));
1660                                }
1661                            }
1662                            let (encoded_key, hash) = match key_for_message {
1663                                Some(key) => {
1664                                    let key_encoder =
1665                                        key_encoder.as_ref().expect("key present");
1666                                    let encoded = key_encoder.encode_unchecked(key.clone());
1667                                    let hash =
1668                                        hash.unwrap_or_else(|| key_encoder.hash(&encoded));
1669                                    (Some(encoded), hash)
1670                                }
1671                                None => (None, hash.unwrap_or(0)),
1672                            };
1673                            let value = match envelope {
1674                                SinkEnvelope::Upsert => value.after,
1675                                SinkEnvelope::Debezium => {
1676                                    dbz_format(&mut row_buf.packer(), value);
1677                                    Some(row_buf.clone())
1678                                }
1679                                SinkEnvelope::Append => {
1680                                    unreachable!("Append envelope is not valid for Kafka sinks")
1681                                }
1682                            };
1683                            let value = value.map(|value| value_encoder.encode_unchecked(value));
1684                            let message = KafkaMessage {
1685                                hash,
1686                                key: encoded_key,
1687                                value,
1688                                headers,
1689                            };
1690                            output.give(&cap, (message, time, Diff::ONE));
1691                        });
1692                        // Flush after each batch so the final `(key, time)` group of the walk is
1693                        // resolved immediately — a PK violation in the last group is otherwise
1694                        // held until more data arrives or the operator shuts down.
1695                        if let Some(warner) = pk_warner.as_mut() {
1696                            warner.flush();
1697                        }
1698                    }
1699                }
1700            }
1701
1702            Ok::<(), anyhow::Error>(())
1703        })
1704    });
1705
1706    let statuses = errors.map(|error| encode_error_status(&error));
1707
1708    (stream.as_collection(), statuses, button.press_on_drop())
1709}
1710
1711/// The status the encode operator reports for `error`.
1712fn encode_error_status(error: &anyhow::Error) -> HealthStatusMessage {
1713    let message = format!("{}", error.display_with_causes());
1714    // A restart publishes the same schema. NOTE: a fix made in the registry needs a sink restart.
1715    let incompatible = error.is::<GlueSchemaIncompatibleError>()
1716        || matches!(
1717            error.downcast_ref::<PublishError>(),
1718            Some(PublishError::IncompatibleSchema)
1719        );
1720    let update = if incompatible {
1721        HealthStatusUpdate::suspending(message, None)
1722    } else {
1723        HealthStatusUpdate::halting(message, None)
1724    };
1725    HealthStatusMessage {
1726        id: None,
1727        update,
1728        namespace: StatusNamespace::Kafka,
1729    }
1730}
1731
1732fn encode_headers(datum: Datum) -> Vec<KafkaHeader> {
1733    let mut out = vec![];
1734    if datum.is_null() {
1735        return out;
1736    }
1737    for (key, value) in datum.unwrap_map().iter() {
1738        out.push(KafkaHeader {
1739            key: key.into(),
1740            value: match value {
1741                Datum::Null => None,
1742                Datum::String(s) => Some(s.as_bytes().to_vec()),
1743                Datum::Bytes(b) => Some(b.to_vec()),
1744                _ => panic!("encode_headers called with unexpected header value {value:?}"),
1745            },
1746        })
1747    }
1748    out
1749}
1750
1751/// Evaluates a partition by expression on the given row, returning the hash
1752/// value to use for partition assignment.
1753///
1754/// The provided expression must have type `Int32`, `Int64`, `UInt32`, or
1755/// `UInt64`. If the expression produces an error when evaluated, or if the
1756/// expression is of a signed integer type and produces a negative value, this
1757/// function returns 0.
1758fn evaluate_partition_by(partition_by: &MirScalarExpr, row: &[Datum]) -> u64 {
1759    // NOTE(benesch): The way this function converts errors and invalid values
1760    // to 0 is somewhat surpising. Ideally, we would put the sink in a
1761    // permanently errored state if the partition by expression produces an
1762    // error or invalid value. But we don't presently have a way for sinks to
1763    // report errors (see materialize#17688), so the current behavior was determined to be
1764    // the best available option. The behavior is clearly documented in the
1765    // user-facing `CREATE SINK` docs.
1766    let temp_storage = RowArena::new();
1767    match partition_by.eval(row, &temp_storage) {
1768        Ok(Datum::UInt64(u)) => u,
1769        Ok(datum) => {
1770            // If we are here the only valid type that we should be seeing is
1771            // null. Anything else is a bug in the planner.
1772            soft_assert_or_log!(datum.is_null(), "unexpected partition_by result: {datum:?}");
1773            // We treat nulls the same as we treat errors: map them to partition 0.
1774            0
1775        }
1776        Err(_) => 0,
1777    }
1778}
1779
1780#[cfg(test)]
1781mod test {
1782    use mz_ore::assert_err;
1783
1784    use super::*;
1785
1786    #[mz_ore::test]
1787    fn encode_error_status_suspends_only_schema_incompatibility() {
1788        use crate::healthcheck::StallAction;
1789
1790        let action = |error: anyhow::Error| {
1791            let error = error.context("error publishing schemas for sink");
1792            encode_error_status(&error).update.stall_action()
1793        };
1794
1795        let glue = GlueSchemaIncompatibleError {
1796            version_id: uuid::Uuid::nil(),
1797        };
1798        assert_eq!(action(glue.into()), StallAction::Suspend);
1799        assert_eq!(
1800            action(PublishError::IncompatibleSchema.into()),
1801            StallAction::Suspend
1802        );
1803
1804        let server = PublishError::Server {
1805            code: 500,
1806            message: "unavailable".into(),
1807        };
1808        assert_eq!(action(server.into()), StallAction::Restart);
1809        assert_eq!(
1810            action(anyhow!("registry unreachable")),
1811            StallAction::Restart
1812        );
1813    }
1814
1815    #[mz_ore::test]
1816    fn progress_record_migration() {
1817        assert_err!(parse_progress_record(b"{}"));
1818
1819        assert_eq!(
1820            parse_progress_record(b"{\"timestamp\":1}").unwrap(),
1821            ProgressRecord {
1822                frontier: Antichain::from_elem(2.into()),
1823                version: 0,
1824            }
1825        );
1826
1827        assert_eq!(
1828            parse_progress_record(b"{\"timestamp\":null}").unwrap(),
1829            ProgressRecord {
1830                frontier: Antichain::new(),
1831                version: 0,
1832            }
1833        );
1834
1835        assert_eq!(
1836            parse_progress_record(b"{\"frontier\":[1]}").unwrap(),
1837            ProgressRecord {
1838                frontier: Antichain::from_elem(1.into()),
1839                version: 0,
1840            }
1841        );
1842
1843        assert_eq!(
1844            parse_progress_record(b"{\"frontier\":[]}").unwrap(),
1845            ProgressRecord {
1846                frontier: Antichain::new(),
1847                version: 0,
1848            }
1849        );
1850
1851        assert_eq!(
1852            parse_progress_record(b"{\"frontier\":[], \"version\": 42}").unwrap(),
1853            ProgressRecord {
1854                frontier: Antichain::new(),
1855                version: 42,
1856            }
1857        );
1858
1859        assert_err!(parse_progress_record(b"{\"frontier\":null}"));
1860    }
1861}