:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(capture): narrow the kafka sink to backend mechanism over prepared payloads (#79461)
Paweł Ledwońefb3546cd8c7
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.mdindex 108d1a6a500e..b0bfb3d75fe9 100644--- a/rust/capture/OUTPUTS_REFACTOR_PLAN.md+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md@@ -266,7 +266,7 @@ When all steps land, the five strata hold:| 3 · `OutputRegistry` + completeness | done | `refactor(capture): output registry with startup completeness check` || 4 · Serialization layer | done | `refactor(capture): serialization layer behind one seam` || 5 · `Pipeline` + `Lane`; lane resolution | done | `refactor(capture): lane decision moves to the pipeline layer` |-| 6 · Kafka sink → backend mechanism | pending | `refactor(capture): narrow the kafka sink to backend mechanism over prepared payloads` |+| 6 · Kafka sink → backend mechanism | done | `refactor(capture): narrow the kafka sink to backend mechanism over prepared payloads` || 7 · Outputs layer with policies; composites retired | pending | `feat(capture): outputs layer owns the failover policy` || 8a · Call sites on the table | pending | `refactor(capture): call sites publish through outputs` || 8b · `Event` retired | pending | `refactor(capture): retire v0 Event trait` |diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rsindex 9a9f8ae890f0..4f0ff9c15f26 100644--- a/rust/capture/src/sinks/kafka.rs+++ b/rust/capture/src/sinks/kafka.rs@@ -24,6 +24,7 @@ use crate::pipeline::{self, Address, Lane, Pipeline};use crate::serialization::Serializer;use crate::sinks::producer::{KafkaProducer, ProduceRecord};use crate::sinks::registry::{Output, OutputRegistry};+use crate::sinks::sink::{fold_results, Outcome, PreparedPayload, Sink, SinkResult};use crate::sinks::Event;use crate::v0_request::{DataType, ProcessedEvent};use async_trait::async_trait;@@ -410,20 +411,29 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {/// CPU-bound prep work: serialize payload + build headers + pick topic/key./// Safe to run concurrently across events in a batch because it does not- /// touch the librdkafka producer queue — phase 2 of `send_batch` is what- /// enforces per-partition ordering by calling `enqueue_record` serially- /// in the original event order.+ /// touch the librdkafka producer queue — `Sink::publish` is what enforces+ /// per-partition ordering by calling `enqueue_record` serially in the+ /// original event order.////// Routing policy is read from `ProcessedEventMetadata` (stamped upstream/// by the pipeline). This function does not consult any limiter — it is/// pure mechanism. DLQ and custom-topic redirects take priority over/// overflow routing.///+ /// Prep lives in this file rather than the outputs layer because it+ /// reads state the sink still owns (the topic registry, the replay+ /// envelope setting). Keeping it off the `Sink` trait is what matters+ /// for the layering: callers above can prep and publish as separate+ /// phases. The prep hoist (step 12 of+ /// `rust/capture/OUTPUTS_REFACTOR_PLAN.md`) moves the assembly and that+ /// state up; drop this note when it lands.+ ////// Not `async`: there are no await points, and keeping it- /// synchronous lets `send_batch`'s serial fast path call it inline without- /// any runtime indirection.- fn prepare_record(&self, event: ProcessedEvent) -> Result<ProduceRecord, CaptureError> {+ /// synchronous lets `prepare_batch`'s serial fast path call it inline+ /// without any runtime indirection.+ fn prepare_record(&self, event: ProcessedEvent) -> Result<PreparedPayload, CaptureError> {let (event, metadata) = (event.event, event.metadata);+ let uuid = event.uuid;// Encoding is resolved by data_type, not by the routed destination:// session replay gets the lz4 envelope when configured, everything@@ -496,90 +506,98 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {},};- let topic: &str = self.topics.topic_for(&target);+ let destination = self.topics.topic_for(&target).to_string();- let partition_key: Option<&str> = match decision.ordering {- OrderingGuarantee::PerDistinctId => Some(event_key.as_str()),- OrderingGuarantee::None => None,+ let partition_key = match decision.ordering {// resolve() rejects replay events without a session id, so the id// is present whenever PerSession is decided.- OrderingGuarantee::PerSession => Some(- metadata- .session_id- .as_deref()- .ok_or(CaptureError::MissingSessionId)?,- ),+ OrderingGuarantee::PerSession => {+ metadata.session_id.ok_or(CaptureError::MissingSessionId)?+ }+ OrderingGuarantee::PerDistinctId | OrderingGuarantee::None => event_key,};if let Some(encoding) = serializer.content_encoding() {headers.set_content_encoding(encoding.to_string());}- Ok(ProduceRecord {- topic: topic.to_string(),- key: partition_key.map(|s| s.to_string()),+ Ok(PreparedPayload {+ uuid,+ destination,+ partition_key,+ ordering: decision.ordering,payload,headers,})}- /// Serial, ordering-preserving enqueue into librdkafka. Emits the per-topic- /// bytes counter and returns the ack future for the caller to await.- /// librdkafka preserves on-wire partition order by `send_result` call order,- /// so this MUST be called in the original event order within a batch.- fn enqueue_record(&self, record: ProduceRecord) -> Result<P::AckFuture, CaptureError> {- let payload_bytes = record.payload.len() as u64;- counter!("capture_kafka_produce_bytes_total", "topic" => record.topic.clone())- .increment(payload_bytes);- self.producer.send(record)+ /// Serial, ordering-preserving enqueue into librdkafka. The one place the+ /// backend-agnostic payload becomes Kafka-shaped: `destination` is the+ /// topic, and `ordering` decides whether the record is keyed. Emits the+ /// per-topic bytes counter and returns the ack future for the caller to+ /// await. librdkafka preserves on-wire partition order by `send_result`+ /// call order, so this MUST be called in the original event order within+ /// a batch.+ fn enqueue_record(&self, payload: PreparedPayload) -> Result<P::AckFuture, CaptureError> {+ counter!("capture_kafka_produce_bytes_total", "topic" => payload.destination.clone())+ .increment(payload.payload.len() as u64);++ // No key reaches rdkafka as round-robin; `Some("")` would murmur2-hash+ // every record onto one deterministic hot partition.+ let key = match payload.ordering {+ OrderingGuarantee::None => None,+ _ => Some(payload.partition_key),+ };++ self.producer.send(ProduceRecord {+ topic: payload.destination,+ key,+ payload: payload.payload,+ headers: payload.headers,+ })}/// Prep + enqueue for the single-event path. Retained as a thin wrapper so- /// the `Event::send` impl stays unchanged; `send_batch` uses prepare_record- /// and enqueue_record directly to parallelize the prep phase.+ /// the `Event::send` impl stays unchanged; the batch path runs the same+ /// pieces through `prepare_batch` and `Sink::publish`.fn kafka_send(&self, event: ProcessedEvent) -> Result<P::AckFuture, CaptureError> {- let record = self.prepare_record(event)?;- self.enqueue_record(record)+ let payload = self.prepare_record(event)?;+ self.enqueue_record(payload)}}-/// Batches below this size take the serial fast path in `send_batch`: spawning-/// N `JoinSet` tasks to run `prepare_record` in parallel is net-negative when-/// each task does only a `serde_json::to_string` and a header build — the-/// scheduler overhead dominates the CPU savings. Scatter-gather kicks in at-/// or above this threshold where parallel prep wins back its spawn cost.+/// Batches below this size take the serial fast path in `prepare_batch`:+/// spawning N `JoinSet` tasks to run `prepare_record` in parallel is+/// net-negative when each task does only a `serde_json::to_string` and a+/// header build — the scheduler overhead dominates the CPU savings.+/// Scatter-gather kicks in at or above this threshold where parallel prep+/// wins back its spawn cost.pub(crate) const SCATTER_GATHER_MIN_BATCH: usize = 8;-#[async_trait]-impl<P: KafkaProducer + 'static> Event for KafkaSinkBase<P> {- #[instrument(skip_all)]- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- let ack_future = self.kafka_send(event)?;- histogram!("capture_event_batch_size").record(1.0);- ack_future.instrument(info_span!("ack_wait_one")).await- }-- #[instrument(skip_all)]- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl<P: KafkaProducer + 'static> KafkaSinkBase<P> {+ /// CPU-bound batch prep: run `prepare_record` over the batch and return+ /// the payloads in the original event order, fail-fast on the first prep+ /// error so no partially-prepped batch reaches the producer. Inherent+ /// rather than on the `Sink` trait: payload assembly is not backend+ /// mechanism, and the outputs layer becomes its caller.+ pub(crate) async fn prepare_batch(+ &self,+ events: Vec<ProcessedEvent>,+ ) -> Result<Vec<PreparedPayload>, CaptureError> {let batch_size = events.len();- // Record the batch-size histogram up front so the distribution is a- // faithful view of batches submitted, not only those that succeeded.- // Matches the single-event `send` path which records before any await.- histogram!("capture_event_batch_size").record(batch_size as f64);// Small-batch fast path. For batches under `SCATTER_GATHER_MIN_BATCH`// the JoinSet spawn overhead dominates any parallel-prep win, so we- // stay single-threaded. We keep the scatter-gather path's semantic- // "prep error -> no records produced" by prepping all events first- // into a Vec, then doing the serial enqueue phase only if all prep- // succeeded. Both duration histograms are recorded so dashboards+ // stay single-threaded. Both paths share the semantic "prep error ->+ // no records produced": all events prep before anything is enqueued.+ // The duration histogram is recorded on every exit so dashboards// keep a faithful view of the fast path.if batch_size < SCATTER_GATHER_MIN_BATCH {let prep_start = Instant::now();- let mut prepared: Vec<ProduceRecord> = Vec::with_capacity(batch_size);+ let mut prepared: Vec<PreparedPayload> = Vec::with_capacity(batch_size);for event in events {match self.prepare_record(event) {- Ok(record) => prepared.push(record),+ Ok(payload) => prepared.push(payload),Err(err) => {histogram!("capture_kafka_batch_prep_duration_seconds").record(prep_start.elapsed().as_secs_f64());@@ -589,38 +607,16 @@ impl<P: KafkaProducer + 'static> Event for KafkaSinkBase<P> {}histogram!("capture_kafka_batch_prep_duration_seconds").record(prep_start.elapsed().as_secs_f64());-- let enqueue_start = Instant::now();- let mut ack_set = JoinSet::new();- for record in prepared {- match self.enqueue_record(record) {- Ok(ack_future) => {- ack_set.spawn(ack_future);- }- Err(err) => {- // Dropping ack_set aborts any in-flight spawned ack- // futures; DeliveryAckFuture::drop records the- // "dropped" outcome on capture_kafka_produce_ack_duration_ms.- // Mirror of phase-2 behavior in the scatter-gather path.- histogram!("capture_kafka_batch_enqueue_duration_seconds")- .record(enqueue_start.elapsed().as_secs_f64());- return Err(err);- }- }- }- histogram!("capture_kafka_batch_enqueue_duration_seconds")- .record(enqueue_start.elapsed().as_secs_f64());-- return drain_acks(ack_set).await;+ return Ok(prepared);}- // Phase 1: parallel prep across tokio workers. Each task returns its- // input index so we can reassemble results in the original event order+ // Parallel prep across tokio workers. Each task returns its input+ // index so we can reassemble results in the original event order// before the serial enqueue phase. This is where the CPU win lives:// serde_json::to_string + header build run concurrently on up to N// worker threads, rather than sequentially on a single task.let prep_start = Instant::now();- let mut prep_set: JoinSet<(usize, Result<ProduceRecord, CaptureError>)> = JoinSet::new();+ let mut prep_set: JoinSet<(usize, Result<PreparedPayload, CaptureError>)> = JoinSet::new();for (idx, event) in events.into_iter().enumerate() {let this = self.clone();prep_set.spawn(@@ -629,14 +625,14 @@ impl<P: KafkaProducer + 'static> Event for KafkaSinkBase<P> {);}- // Collect into a (idx, record) Vec and sort rather than indexing into- // a `Vec<Option<ProduceRecord>>`. Encodes the "every slot filled"+ // Collect into a (idx, payload) Vec and sort rather than indexing into+ // a `Vec<Option<PreparedPayload>>`. Encodes the "every slot filled"// invariant in the type: no `Option`, no unreachable `expect`, no// N-element `None` preallocation. Our only cancellation source is// `prep_set.abort_all()` below, invoked only from an already-errored// branch, so any `JoinError` observed during normal drain implies a// panic inside `prepare_record` — counted separately so it's alertable.- let mut prepared: Vec<(usize, ProduceRecord)> = Vec::with_capacity(batch_size);+ let mut prepared: Vec<(usize, PreparedPayload)> = Vec::with_capacity(batch_size);while let Some(join_result) = prep_set.join_next().await {let (idx, result) = match join_result {Err(err) => {@@ -654,7 +650,7 @@ impl<P: KafkaProducer + 'static> Event for KafkaSinkBase<P> {Ok(inner) => inner,};match result {- Ok(record) => prepared.push((idx, record)),+ Ok(payload) => prepared.push((idx, payload)),Err(err) => {prep_set.abort_all();histogram!("capture_kafka_batch_prep_duration_seconds")@@ -668,36 +664,67 @@ impl<P: KafkaProducer + 'static> Event for KafkaSinkBase<P> {histogram!("capture_kafka_batch_prep_duration_seconds").record(prep_start.elapsed().as_secs_f64());- // Phase 2: serial enqueue in original event order. This is the ordering- // bottleneck we deliberately keep: librdkafka preserves per-partition- // on-wire order by send_result() call order, and same-distinct_id events- // hash to the same partition via murmur2. Within-batch same-key ordering- // must survive so e.g. $identify lands before subsequent events.+ Ok(prepared.into_iter().map(|(_, payload)| payload).collect())+ }+}++#[async_trait]+impl<P: KafkaProducer + 'static> Sink for KafkaSinkBase<P> {+ /// Serial enqueue in payload order + fail-fast ack drain. The serial+ /// enqueue is the ordering bottleneck we deliberately keep: librdkafka+ /// preserves per-partition on-wire order by send_result() call order, and+ /// same-distinct_id events hash to the same partition via murmur2.+ /// Within-batch same-key ordering must survive so e.g. $identify lands+ /// before subsequent events.+ ///+ /// Results are batch-uniform: the whole batch reports the first failure,+ /// acked-before-failure events included. The per-event surface refines+ /// only with the per-event response model.+ async fn publish(&self, payloads: Vec<PreparedPayload>) -> Vec<SinkResult> {+ // Results are built in payload order as the loop enqueues, so the one+ // Vec the return type requires is the only allocation on the happy+ // path. Failure paths rewrite it in place to the batch-uniform error.+ let mut results: Vec<SinkResult> = Vec::with_capacity(payloads.len());+let enqueue_start = Instant::now();let mut ack_set = JoinSet::new();- for (_, record) in prepared {- match self.enqueue_record(record) {+ let mut payloads = payloads.into_iter();+ for payload in payloads.by_ref() {+ let uuid = payload.uuid;+ match self.enqueue_record(payload) {Ok(ack_future) => {ack_set.spawn(ack_future);+ results.push(SinkResult::published(uuid));}Err(err) => {// Record enqueue duration on the error path too so slow-fail// cases (e.g. QueueFull after a long stall) stay observable.- // Dropping `ack_set` when we return Err aborts any already- // spawned ack futures for this batch; DeliveryAckFuture::drop- // then records the "dropped" outcome on- // capture_kafka_produce_ack_duration_ms. This is the phase-2- // mirror of phase-1's explicit `prep_set.abort_all()`.+ // Dropping `ack_set` aborts any already spawned ack futures+ // for this batch; DeliveryAckFuture::drop then records the+ // "dropped" outcome on capture_kafka_produce_ack_duration_ms.histogram!("capture_kafka_batch_enqueue_duration_seconds").record(enqueue_start.elapsed().as_secs_f64());- return Err(err);+ for result in &mut results {+ result.outcome = Outcome::Failed(err.clone());+ }+ results.push(SinkResult::failed(uuid, err.clone()));+ results.extend(payloads.map(|p| SinkResult::failed(p.uuid, err.clone())));+ return results;}}}histogram!("capture_kafka_batch_enqueue_duration_seconds").record(enqueue_start.elapsed().as_secs_f64());- drain_acks(ack_set).await+ match drain_acks(ack_set).await {+ Ok(()) => results,+ Err(err) => {+ for result in &mut results {+ result.outcome = Outcome::Failed(err.clone());+ }+ results+ }+ }}fn flush(&self) -> Result<(), anyhow::Error> {@@ -705,11 +732,38 @@ impl<P: KafkaProducer + 'static> Event for KafkaSinkBase<P> {}}-/// Phase 3 of `send_batch`: concurrent ack drain, fail-fast on first ack error.-/// Shared between the scatter-gather path and the small-batch serial fast path-/// so both converge on the same fail-fast + abort-siblings semantics. Dropping-/// the JoinSet on error aborts remaining spawned ack futures; DeliveryAckFuture-/// Drop then records the "dropped" outcome on capture_kafka_produce_ack_duration_ms.+#[async_trait]+impl<P: KafkaProducer + 'static> Event for KafkaSinkBase<P> {+ #[instrument(skip_all)]+ async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {+ let ack_future = self.kafka_send(event)?;+ histogram!("capture_event_batch_size").record(1.0);+ ack_future.instrument(info_span!("ack_wait_one")).await+ }++ /// The v0 bridge onto the mechanism seam: prep, publish, fold. The+ /// per-event results collapse to the whole-request `CaptureError` the+ /// `Event` callers expect.+ #[instrument(skip_all)]+ async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ // Record the batch-size histogram up front so the distribution is a+ // faithful view of batches submitted, not only those that succeeded.+ // Matches the single-event `send` path which records before any await.+ histogram!("capture_event_batch_size").record(events.len() as f64);++ let payloads = self.prepare_batch(events).await?;+ fold_results(self.publish(payloads).await)+ }++ fn flush(&self) -> Result<(), anyhow::Error> {+ Sink::flush(self)+ }+}++/// Concurrent ack drain for `Sink::publish`, fail-fast on first ack error.+/// Dropping the JoinSet on error aborts remaining spawned ack futures;+/// DeliveryAckFuture Drop then records the "dropped" outcome on+/// capture_kafka_produce_ack_duration_ms.async fn drain_acks(mut ack_set: JoinSet<Result<(), CaptureError>>) -> Result<(), CaptureError> {async move {while let Some(res) = ack_set.join_next().await {@@ -1131,6 +1185,7 @@ mod tests {use super::*;use crate::sinks::kafka::{test_topics, KafkaSinkBase, SCATTER_GATHER_MIN_BATCH};use crate::sinks::producer::MockKafkaProducer;+ use crate::sinks::sink::{Outcome, Sink};use rstest::rstest;const MAIN_TOPIC: &str = "events_plugin_ingestion";@@ -3052,6 +3107,88 @@ mod tests {);}+ // ==================== Sink mechanism seam ====================+ // The per-event result surface `Sink::publish` reports: uuid-aligned+ // with the input payloads, batch-uniform on failure. `fold_results`+ // discards this shape, so the send_batch tests above cannot see it —+ // and the outputs layer builds on it.++ #[tokio::test]+ async fn publish_reports_uuid_aligned_results() {+ let producer = MockKafkaProducer::new();+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());++ let payloads = sink+ .prepare_batch(build_batch(3))+ .await+ .expect("prepare_batch failed");+ let input_uuids: Vec<_> = payloads.iter().map(|p| p.uuid).collect();++ let results = sink.publish(payloads).await;++ assert_eq!(results.len(), 3);+ for (result, uuid) in results.iter().zip(&input_uuids) {+ assert_eq!(result.uuid, *uuid, "results must align with input order");+ assert!(matches!(result.outcome, Outcome::Published));+ }+ }++ #[tokio::test]+ async fn publish_enqueue_failure_is_batch_uniform() {+ const FAIL_IDX: usize = 1;+ let producer = MockKafkaProducer::new_failing_at(FAIL_IDX);+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());++ let payloads = sink+ .prepare_batch(build_batch(3))+ .await+ .expect("prepare_batch failed");+ let input_uuids: Vec<_> = payloads.iter().map(|p| p.uuid).collect();++ let results = sink.publish(payloads).await;++ // Every event reports the failure, the one enqueued before it+ // included; only the records before the failing index reached+ // the producer.+ assert_eq!(results.len(), 3);+ for (result, uuid) in results.iter().zip(&input_uuids) {+ assert_eq!(result.uuid, *uuid, "results must align with input order");+ assert!(matches!(+ result.outcome,+ Outcome::Failed(CaptureError::RetryableSinkError)+ ));+ }+ assert_eq!(producer.get_records().len(), FAIL_IDX);+ }++ #[tokio::test]+ async fn publish_ack_failure_is_batch_uniform() {+ const FAIL_IDX: usize = 1;+ let producer = MockKafkaProducer::new_failing_ack_at(FAIL_IDX);+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());++ let payloads = sink+ .prepare_batch(build_batch(3))+ .await+ .expect("prepare_batch failed");+ let input_uuids: Vec<_> = payloads.iter().map(|p| p.uuid).collect();++ let results = sink.publish(payloads).await;++ // The producer accepted every record — all three were enqueued —+ // but one delivery report failed, so the whole batch reports the+ // failure, acked-before-failure events included.+ assert_eq!(results.len(), 3);+ for (result, uuid) in results.iter().zip(&input_uuids) {+ assert_eq!(result.uuid, *uuid, "results must align with input order");+ assert!(matches!(+ result.outcome,+ Outcome::Failed(CaptureError::RetryableSinkError)+ ));+ }+ assert_eq!(producer.get_records().len(), 3);+ }+/// Per-event-type topic routing is covered by `assert_routing` for/// the single-event path. This test verifies routing survives the/// batch path for a mixed batch of data types plus one force_overflowdiff --git a/rust/capture/src/sinks/mod.rs b/rust/capture/src/sinks/mod.rsindex f6f78dd9ee72..1b6e44ee96a6 100644--- a/rust/capture/src/sinks/mod.rs+++ b/rust/capture/src/sinks/mod.rs@@ -9,6 +9,7 @@ pub mod print;pub mod producer;pub mod registry;pub mod s3;+pub mod sink;#[cfg(test)]pub(crate) mod test_sink;#[async_trait]diff --git a/rust/capture/src/sinks/producer.rs b/rust/capture/src/sinks/producer.rsindex 228fcefae7e1..eb2d7c9df73f 100644--- a/rust/capture/src/sinks/producer.rs+++ b/rust/capture/src/sinks/producer.rs@@ -173,14 +173,18 @@ impl<C: rdkafka::ClientContext + Send + Sync + 'static> KafkaProducer for RdKafk/// Mock Kafka producer for testing - captures all sent records.///-/// Optionally fails on a specific send index (0-based) by returning-/// `CaptureError::RetryableSinkError`. Records before the failing index are-/// still captured; the failing record is not. Used by send-batch tests that-/// need to simulate a mid-batch enqueue failure.+/// Two failure modes, both keyed on the 0-based send index:+/// - `new_failing_at`: the `idx`-th `send()` itself returns+/// `CaptureError::RetryableSinkError` (an enqueue failure). Records before+/// the failing index are still captured; the failing record is not.+/// - `new_failing_ack_at`: every `send()` succeeds and captures its record,+/// but the `idx`-th ack future resolves to `RetryableSinkError` — the+/// producer accepted the record and its delivery report failed.#[derive(Clone, Default)]pub struct MockKafkaProducer {records: std::sync::Arc<std::sync::Mutex<Vec<ProduceRecord>>>,fail_at_index: Option<usize>,+ fail_ack_at_index: Option<usize>,call_count: std::sync::Arc<std::sync::atomic::AtomicUsize>,}@@ -198,6 +202,15 @@ impl MockKafkaProducer {}}+ /// Build a producer whose `idx`-th (0-based) ack future resolves to+ /// `RetryableSinkError` after the send itself succeeded.+ pub fn new_failing_ack_at(idx: usize) -> Self {+ Self {+ fail_ack_at_index: Some(idx),+ ..Self::default()+ }+ }+/// Get all records that were sentpub fn get_records(&self) -> Vec<ProduceRecord> {self.records.lock().unwrap().clone()@@ -220,6 +233,9 @@ impl KafkaProducer for MockKafkaProducer {return Err(CaptureError::RetryableSinkError);}self.records.lock().unwrap().push(record);+ if self.fail_ack_at_index == Some(idx) {+ return Ok(std::future::ready(Err(CaptureError::RetryableSinkError)));+ }Ok(std::future::ready(Ok(())))}diff --git a/rust/capture/src/sinks/sink.rs b/rust/capture/src/sinks/sink.rsnew file mode 100644index 000000000000..3beb4dc42dbc--- /dev/null+++ b/rust/capture/src/sinks/sink.rs@@ -0,0 +1,141 @@+//! The sink mechanism contract: publish already-prepared payloads, report+//! per-event results.+//!+//! A sink is a single backend (Kafka today; S3, print, noop join with the+//! outputs layer). It receives [`PreparedPayload`]s — serialized, addressed,+//! headers stamped — and turns them into wire records. It reads no event+//! metadata and makes no routing decision; anything that picks between+//! backends is an output policy, not a sink.+//!+//! [`Sink::publish`] is infallible at the call level: every input payload gets+//! a [`SinkResult`], and failures travel inside them. Callers that need the+//! v0 whole-request response collapse the results with [`fold_results`].++use async_trait::async_trait;+use common_types::CapturedEventHeaders;+use uuid::Uuid;++use crate::api::CaptureError;+use crate::ordering::OrderingGuarantee;++/// A serialized, addressed record ready for a backend: the sink input.+/// The uuid identifies the source event so per-event results can be+/// reported without the sink ever seeing event metadata.+///+/// The fields are backend-agnostic: each sink interprets them in its own+/// terms, and nothing here names a Kafka concept. Kept field-for-field in+/// sync with `v1::sinks::types::PreparedEvent`, the shape the two stacks+/// converge on.+#[derive(Debug, Clone)]+pub(crate) struct PreparedPayload {+ pub uuid: Uuid,+ /// Realized namespace within the backend: a Kafka topic, an S3 prefix.+ /// Namespace realization happens above the sink.+ pub destination: String,+ /// Raw key; whether the sink uses it is decided by `ordering`.+ pub partition_key: String,+ /// The guarantee `partition_key` exists to preserve.+ /// [`OrderingGuarantee::None`] means publish without a key.+ pub ordering: OrderingGuarantee,+ pub payload: Vec<u8>,+ pub headers: CapturedEventHeaders,+}++/// What happened to one published payload.+#[derive(Debug)]+pub(crate) enum Outcome {+ Published,+ Failed(CaptureError),+}++/// Per-event publish result, correlated to the input by uuid.+///+/// The sink treats the uuid as pass-through: results align with the input+/// payloads by position, and nothing in the sink assumes uuids are unique+/// within a batch (v0 accepts client-supplied uuids unchecked). It is+/// carried anyway so a result is attributable to its event without the+/// caller holding the input list, which makes the per-event response model+/// (steps 19d and 20 of `rust/capture/OUTPUTS_REFACTOR_PLAN.md`) a+/// caller-side change instead of a trait change. Until that model lands,+/// `fold_results` is the only consumer and ignores it; drop this note when+/// the uuid gains its consumer.+#[derive(Debug)]+pub(crate) struct SinkResult {+ // Unread outside tests until the per-event response model consumes it;+ // see the doc comment above.+ #[allow(dead_code)]+ pub uuid: Uuid,+ pub outcome: Outcome,+}++impl SinkResult {+ pub(crate) fn published(uuid: Uuid) -> Self {+ Self {+ uuid,+ outcome: Outcome::Published,+ }+ }++ pub(crate) fn failed(uuid: Uuid, err: CaptureError) -> Self {+ Self {+ uuid,+ outcome: Outcome::Failed(err),+ }+ }+}++/// Backend mechanism: enqueue prepared payloads, ack them, report results.+/// No prepare on the trait — payload assembly belongs to the layers above.+#[async_trait]+pub(crate) trait Sink {+ async fn publish(&self, payloads: Vec<PreparedPayload>) -> Vec<SinkResult>;++ /// Flush any buffered/pending data before shutdown.+ fn flush(&self) -> Result<(), anyhow::Error>;+}++/// Collapse per-event results into the v0 whole-request response:+/// the first failure in publish order wins.+pub(crate) fn fold_results(results: Vec<SinkResult>) -> Result<(), CaptureError> {+ for result in results {+ if let Outcome::Failed(err) = result.outcome {+ return Err(err);+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn fold_results_empty_is_ok() {+ assert!(fold_results(vec![]).is_ok());+ }++ #[test]+ fn fold_results_all_published_is_ok() {+ let results = vec![+ SinkResult::published(Uuid::now_v7()),+ SinkResult::published(Uuid::now_v7()),+ ];+ assert!(fold_results(results).is_ok());+ }++ #[test]+ fn fold_results_first_failure_wins() {+ let results = vec![+ SinkResult::published(Uuid::now_v7()),+ SinkResult::failed(+ Uuid::now_v7(),+ CaptureError::EventTooBig("first".to_string()),+ ),+ SinkResult::failed(Uuid::now_v7(), CaptureError::RetryableSinkError),+ ];+ match fold_results(results) {+ Err(CaptureError::EventTooBig(msg)) => assert_eq!(msg, "first"),+ other => panic!("expected the first failure, got {other:?}"),+ }+ }+}