: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
feat(capture): outputs publish prepared events with per-event results (#110892)
Paweł Ledwoń14a43b7a00ca
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.mdindex 2ccda094c5bf..de4dc180e235 100644--- a/rust/capture/OUTPUTS_REFACTOR_PLAN.md+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md@@ -1,6 +1,6 @@# Capture outputs refactor — implementation plan-Working contract for implementation agents. Steps 1–10 have shipped. Each remaining step is one commit in its own PR.+Working contract for implementation agents. Steps 1–11 have shipped. Each remaining step is one commit in its own PR.This doc is deleted when it schedules nothing. Step 18 closes objective 1; objectives 2 and 3 are then scheduled in order. Before deletion, the parts still needed — the vocabulary rules, the ordering-vs-person-processing contract, the repartitioning note — move into module docs or `v1/sinks/DESIGN.md`, and unscheduled work becomes issues.@@ -72,31 +72,24 @@ producers → named connections (brokers, TLS, tuning), instantiated onc## Starting point-Steps 1–10 shipped the structure:+Steps 1–11 shipped the structure:- **1** — `assert_routing` goldens pin topic, partition key, headers, and reroute counters for every pipeline and lane.- **2, 5** — routing is the pure `pipeline::resolve(&metadata, ai_events_overflow_armed) -> AddressDecision { address, ordering }`. The Kafka sink still calls it during prep.- **3** — `TopicTable` maps each `Destination` to a topic. `check_complete` refuses to boot on an empty topic, behind `CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED` (default off).- **4** — `serialization`: `Format` (JSON only) × `Envelope` (none or lz4) → `Serializer`, used in Kafka prep.-- **6** — the `Sink` trait takes `PreparedPayload`s and returns per-event `SinkResult`s. Kafka's `prepare_batch` is an inherent method.-- **7** — `outputs.rs`: `Output` is a leaf or a `failover` over two outputs. `FallbackSink` is deleted. Accepted metric change: `capture_event_batch_size` now records on the S3 fallback path and on print/noop single sends.+- **6** — the `PublishPayloads` trait takes `PreparedPayload`s and returns per-event `SinkResult`s. Kafka's `prepare_batch` is an inherent method.+- **7** — `outputs.rs`: `Output` is a sink or a `failover` over two outputs. `FallbackSink` is deleted. Accepted metric change: `capture_event_batch_size` now records on the S3 fallback path and on print/noop single sends.- **8** — every v0 call site publishes through `OutputRegistry::publish`. `State.outputs` is a concrete `Arc<OutputRegistry>`. The v0 `Event` trait is deleted. `kafka_send` stays on the one-event path: removing it adds a task spawn per event and drops the `ack_wait_one` span, so Step 20 takes it.- **9** — named producers (`producers.rs`): each slot reads `KAFKA_<SLOT>_PRODUCER_<RDKAFKA_KEY>` and is instantiated once. `INGESTION` is the one slot. ([#105335](https://github.com/PostHog/posthog/pull/105335))-- **10** — each v0 `Destination` is an output with a topic and a producer, read from `CAPTURE_OUTPUT_<OUTPUT>_TOPIC` and `CAPTURE_OUTPUT_<OUTPUT>_PRODUCER` as in Node.js ingestion. `OutputTable` replaces `TopicTable`. `PreparedPayload` carries the `Destination`. Setup maps each target's producer name to its handle once and hands the Kafka sink the resolved table; at enqueue the sink publishes through the target's own producer. Custom redirects publish through `CAPTURE_OUTPUT_CUSTOM_PRODUCER`. The table sits inside the sink only because v0 resolves the lane during Kafka prep; it serves the v0 event route and is deleted in Step 20.+- **10** — each v0 `Destination` is an output with a topic and a producer, read from `CAPTURE_OUTPUT_<OUTPUT>_TOPIC` and `CAPTURE_OUTPUT_<OUTPUT>_PRODUCER` as in Node.js ingestion. `OutputTable` replaces `TopicTable`. `PreparedPayload` carries the `Destination`. Setup maps each target's producer name to its handle once and hands the Kafka sink the resolved table; at enqueue the sink publishes through the target's own producer. Custom redirects publish through `CAPTURE_OUTPUT_CUSTOM_PRODUCER`. The resolved table is the Kafka sink's address-to-target lookup for both routes until Step 14's registries replace it.+- **11** — outputs take prepared events: `OutputRegistry::publish_prepared(Vec<PreparedEvent>) -> Vec<SinkResult>`, one result per event, in input order. `PreparedEvent` carries an `Address` and a `Bytes` payload. Every sink implements `PublishPrepared` beside `PublishEvents`; the `Sink` bound makes both required. The Kafka sink maps the address to its `Destination` and publishes through that target's topic and producer, enqueueing serially in input order; an enqueue or ack failure fails only its event. The S3 sink writes each payload as one line. Failover moves only the events with a retriable primary failure to the fallback. Test sinks that serve only v0 endpoints mark the prepared route `unreachable!`. Deviation from the original step text: the address-to-topic lookup is the Step-10 resolved `OutputTable` held by the Kafka sink, not a separate per-producer sink type; Step 14's registries replace the lookup.-Today the registry holds one deployment-wide `Output`: a Kafka leaf, or Kafka→S3 failover. v1 (`CAPTURE_V1_SINKS`) serializes its own `PreparedEvent`s and publishes them through its own `Router` to one default sink, the first name in `CAPTURE_V1_SINKS`.+Today the registry holds one deployment-wide `Output`: a Kafka sink, or Kafka→S3 failover. v1 (`CAPTURE_V1_SINKS`) serializes its own `PreparedEvent`s and publishes them through its own `Router` to one default sink, the first name in `CAPTURE_V1_SINKS`.## Objective 1 — manual fallback for all capture traffic-Steps 11–12 bring v1 onto the outputs layer. Steps 13–14 make the set of reachable outputs a type. Steps 15–16 are the checks that type allows. Step 17 is the fallback. Step 18 deletes the S3 fallback it replaces.--### Step 11 · Outputs accept prepared events--- **Goal.** A second route into the outputs layer: `publish_prepared(Vec<PreparedEvent>) -> Vec<SinkResult>`, one result per event. Each target maps the event's address to its own topic, and its sink does the transport encoding: the Kafka sink builds the record, and the S3 sink writes the JSON body as a line. Every policy works on this route. v0's event route is unchanged.-- **Targets live in the outputs layer.** A target is a topic plus a sink. There is one Kafka sink per named producer, built once in setup; it takes a topic and a prepared event and makes no routing decision. This route never reads the Step-10 in-sink `OutputTable`.-- **Why.** v1 already produces prepared events with per-event results. Joining at this level leaves v1's lane decision, JSON body, and response model untouched, so there is no second pass through `resolve` and no parity mapping of v1 decisions onto v0 metadata.-- **Parity proof.** New tests drive prepared events through each leaf and each policy. Goldens unmodified.-- **Size.** M.+Step 12 brings v1 onto the outputs layer. Steps 13–14 make the set of reachable outputs a type. Steps 15–16 are the checks that type allows. Step 17 is the fallback. Step 18 deletes the S3 fallback it replaces.### Step 12 · v1 publishes through the outputs layer@@ -178,7 +171,7 @@ v0 and v1 producer tuning is reconciled into one set per cluster, and capture-an### Step 20 · v0 builds prepared events-v0 resolves the lane, builds the JSON body and header values, and hands prepared events to `publish_prepared`, as v1 does. The lz4 envelope moves into the Kafka sink as target config. `PublishEvents`, `kafka_send`, and v0's event route into the outputs layer are deleted, and with them the in-sink `OutputTable`, its `resolve`, and `map_producers`. v0 call sites fold per-event results into the whole-request `CaptureError`.+v0 resolves the lane, builds the JSON body and header values, and hands prepared events to `publish_prepared`, as v1 does. The lz4 envelope moves into the Kafka sink as target config. `PublishEvents`, `kafka_send`, and v0's event route into the outputs layer are deleted, and with them v0's Kafka prep and the test sinks' `unreachable!` prepared impls. v0 call sites fold per-event results into the whole-request `CaptureError`.- **Tests.** Capturing mocks see prepared events, not `ProcessedEvent`s, so about 60 metadata assertions become wire-level (topic, key, headers, payload). The `ExpectedEvent` checkers rebuild the expected record, so test bodies stay the same. This also pins that replay events redirected to dlq/custom partition on the event key, not the session id.- **Accepted differences.** print/noop run the real prep path, so they can now fail prep (e.g. `MissingSessionId`). Prep histograms keep their `capture_kafka_*` names.@@ -282,7 +275,7 @@ One step = one commit, subject from the tracker. No `--no-verify`.| 8b · `Event` retired | done | `refactor(capture): retire v0 Event trait` || 9 · Named producers, instantiated once | done | `refactor(capture): named producers own their connection config` || 10 · An output owns its topics and names its producer | done | `feat(capture): each output reads its own topic and producer` |-| 11 · Outputs accept prepared events | pending | `feat(capture): outputs publish prepared events with per-event results` |+| 11 · Outputs accept prepared events | done | `feat(capture): outputs publish prepared events with per-event results` || 12 · v1 publishes through the outputs layer | pending | `refactor(capture): v1 publishes through outputs; v1 sink stack deleted` || 13 · Typed per-pipeline lanes | pending | `refactor(capture): typed per-pipeline lanes` || 14 · Per-mode output registries | pending | `feat(capture): per-mode output registries with required rows` |@@ -302,7 +295,7 @@ One step = one commit, subject from the tracker. No `--no-verify`.| 28 · Sinks realize namespaces | superseded | — (targets map addresses to topics from Step 11) || 29 · Handlers bound by publish capabilities | deferred | `feat(capture): handlers bound by publish capabilities over per-mode state` || 30 · AI ingress family | deferred | `feat(capture): ai ingress is its own router family with its own capability` |-| 31 · Topic tables injected into sinks | superseded | — (targets move to the outputs layer in Step 11; the in-sink table goes in Step 20) |+| 31 · Topic tables injected into sinks | superseded | — (the Kafka sink resolves addresses through its table from Step 11; Step 14's registries replace it) || 32 · Per-pipeline output overrides; boot topic verification | superseded | — (boot verification became Step 16; retargeting is configuration after Steps 10 and 14) || 33 · Naming and import hygiene | deferred | `refactor(capture): replace remaining nested paths with imports` + `refactor(capture): name the session replay pipeline consistently` || 34 · Outputs as an open trait | deferred | `refactor(capture): Outputs becomes an open trait` |diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rsindex e95cd73ad509..5206d865a60b 100644--- a/rust/capture/src/events/analytics.rs+++ b/rust/capture/src/events/analytics.rs@@ -2881,6 +2881,16 @@ mod tests {}}+ #[async_trait::async_trait]+ impl crate::outputs::PublishPrepared for RejectingSink {+ async fn publish_prepared(+ &self,+ _events: Vec<crate::outputs::PreparedEvent>,+ ) -> Vec<crate::sinks::sink::SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+ }+let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z").unwrap().with_timezone(&Utc);@@ -4050,6 +4060,16 @@ mod tests {}}+ #[async_trait::async_trait]+ impl crate::outputs::PublishPrepared for RejectingSink {+ async fn publish_prepared(+ &self,+ _events: Vec<crate::outputs::PreparedEvent>,+ ) -> Vec<crate::sinks::sink::SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+ }+let events = vec![event_with_distinct_id(&"x".repeat(250))];let (result, emitted) =diff --git a/rust/capture/src/outputs.rs b/rust/capture/src/outputs.rsindex 3e0c6297f05c..5b337ec18f68 100644--- a/rust/capture/src/outputs.rs+++ b/rust/capture/src/outputs.rs@@ -1,25 +1,34 @@//! The outputs layer: the produce surface above the sinks.//!//! An [`Output`] is a published-to destination: either a single backend-//! leaf, or a policy composing two child outputs. Today the one policy is-//! failover (health-gated Kafka primary with an S3 secondary). Policies-//! operate on *events*, before any payload prep, so each target resolves-//! topics and serializes for itself.+//! sink, or a policy composing two child outputs. Today the one policy is+//! failover (health-gated Kafka primary with an S3 secondary).+//!+//! Outputs take two routes. The v0 event route ([`PublishEvents`]) hands over+//! events before any payload prep, so each target resolves topics and+//! serializes for itself. The prepared route ([`PublishPrepared`]) hands over+//! [`PreparedEvent`]s, already serialized and addressed, and reports one+//! result per event. Every sink and every policy serves both.use async_trait::async_trait;+use common_types::CapturedEventHeaders;use metrics::{counter, gauge};use tracing::instrument;use tracing::log::error;+use uuid::Uuid;use crate::api::CaptureError;+use crate::ordering::OrderingGuarantee;+use crate::pipeline::Address;+use crate::sinks::sink::{Outcome, SinkResult};use crate::v0_request::ProcessedEvent;-/// The leaf produce contract: run prep, publish, and fold internally and+/// The sink produce contract: run prep, publish, and fold internally and/// report the v0 whole-request result, so no caller sees a two-phase/// protocol.////// `pub` rather than `pub(crate)` because the integration suites in-/// `tests/` stand their own capturing sinks in as output leaves; there is+/// `tests/` stand their own capturing sinks in as outputs; there is/// no other reason to implement it outside this crate.#[async_trait]pub trait PublishEvents: Send + Sync {@@ -28,26 +37,48 @@ pub trait PublishEvents: Send + Sync {async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError>;}+#[derive(Debug, Clone)]+pub struct PreparedEvent {+ pub uuid: Uuid,+ pub address: Address,+ pub partition_key: String,+ pub ordering: OrderingGuarantee,+ pub payload: bytes::Bytes,+ pub headers: CapturedEventHeaders,+}++/// Returns one [`SinkResult`] per input event, in input order. A failure is+/// reported in that event's result and does not affect the other events.+#[async_trait]+pub trait PublishPrepared: Send + Sync {+ async fn publish_prepared(&self, events: Vec<PreparedEvent>) -> Vec<SinkResult>;+}++pub trait Sink: PublishEvents + PublishPrepared {}++impl<T: PublishEvents + PublishPrepared> Sink for T {}+pub struct Output {inner: Inner,}enum Inner {- Single(Box<dyn PublishEvents>),+ Single(Box<dyn Sink>),Failover(Failover),}impl Output {- pub fn single<L: PublishEvents + 'static>(leaf: L) -> Self {+ pub fn single<S: Sink + 'static>(sink: S) -> Self {Self {- inner: Inner::Single(Box::new(leaf)),+ inner: Inner::Single(Box::new(sink)),}}/// Health-gated failover over two outputs. While the advisory handle/// reports unhealthy the primary is skipped entirely; without a handle/// the primary is always tried first. A retriable primary failure- /// re-publishes the batch on the fallback. Any other error is final:+ /// re-publishes the batch on the fallback, or on the prepared route only+ /// the events that failed. Any other error is final:/// a non-retryable error is a property of the event, not the backend,/// so the fallback would reject it too.pub(crate) fn failover(@@ -75,12 +106,22 @@ impl Output {impl PublishEvents for Output {async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {match &self.inner {- Inner::Single(leaf) => leaf.publish_events(events).await,+ Inner::Single(sink) => sink.publish_events(events).await,Inner::Failover(failover) => failover.publish_events(events).await,}}}+#[async_trait]+impl PublishPrepared for Output {+ async fn publish_prepared(&self, events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ match &self.inner {+ Inner::Single(sink) => sink.publish_prepared(events).await,+ Inner::Failover(failover) => failover.publish_prepared(events).await,+ }+ }+}+struct Failover {primary: Box<Output>,fallback: Box<Output>,@@ -115,6 +156,46 @@ impl Failover {self.fallback.publish_events(events).await}}++ #[instrument(skip_all)]+ async fn publish_prepared(&self, events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ let healthy = self.primary_is_healthy();+ gauge!("capture_primary_sink_health").set(if healthy { 1.0 } else { 0.0 });++ if !healthy {+ counter!("capture_fallback_sink_failovers_total").increment(1);+ return self.fallback.publish_prepared(events).await;+ }++ let mut results = self.primary.publish_prepared(events.clone()).await;+ debug_assert_eq!(results.len(), events.len());+ // Retry by position, not uuid: v0 accepts client-supplied uuids+ // unchecked, so a batch can repeat one.+ let retry: Vec<usize> = results+ .iter()+ .enumerate()+ .filter(|(_, result)| {+ matches!(+ result.outcome,+ Outcome::Failed(CaptureError::RetryableSinkError)+ )+ })+ .map(|(idx, _)| idx)+ .collect();+ if retry.is_empty() {+ return results;+ }++ error!("Primary output failed, falling back");+ counter!("capture_fallback_sink_failovers_total").increment(1);+ let mut events: Vec<Option<PreparedEvent>> = events.into_iter().map(Some).collect();+ let retry_events = retry.iter().filter_map(|&idx| events[idx].take()).collect();+ let fallback_results = self.fallback.publish_prepared(retry_events).await;+ for (idx, result) in retry.into_iter().zip(fallback_results) {+ results[idx] = result;+ }+ results+ }}/// The (pipeline, lane) → output map the deployment state holds. One@@ -131,8 +212,8 @@ impl OutputRegistry {Self { output }}- pub fn single<L: PublishEvents + 'static>(leaf: L) -> Self {- Self::new(Output::single(leaf))+ pub fn single<S: Sink + 'static>(sink: S) -> Self {+ Self::new(Output::single(sink))}/// Per-event failures collapse to a whole-request `CaptureError`.@@ -142,26 +223,115 @@ impl OutputRegistry {pub async fn publish(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {self.output.publish_events(events).await}++ pub async fn publish_prepared(&self, events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ self.output.publish_prepared(events).await+ }}#[cfg(test)]mod tests {use super::*;+ use crate::pipeline::{Lane, Pipeline};use crate::sinks::test_sink::MockSink;use crate::utils::uuid_v7_from_datetime;use crate::v0_request::{DataType, ProcessedEventMetadata};use common_types::CapturedEvent;+ use std::collections::HashMap;+ use std::sync::{Arc, Mutex};use std::time::Duration;- struct FailLeaf(CaptureError);+ struct FailSink(CaptureError);#[async_trait]- impl PublishEvents for FailLeaf {+ impl PublishEvents for FailSink {async fn publish_events(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {Err(self.0.clone())}}+ #[async_trait]+ impl PublishPrepared for FailSink {+ async fn publish_prepared(&self, events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ events+ .iter()+ .map(|event| SinkResult::failed(event.uuid, self.0.clone()))+ .collect()+ }+ }++ #[derive(Clone, Default)]+ struct PreparedSink {+ failures: Arc<HashMap<Uuid, CaptureError>>,+ seen: Arc<Mutex<Vec<Uuid>>>,+ }++ impl PreparedSink {+ fn failing(failures: impl IntoIterator<Item = (Uuid, CaptureError)>) -> Self {+ Self {+ failures: Arc::new(failures.into_iter().collect()),+ ..Self::default()+ }+ }++ fn seen(&self) -> Vec<Uuid> {+ self.seen.lock().unwrap().clone()+ }+ }++ #[async_trait]+ impl PublishEvents for PreparedSink {+ async fn publish_events(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ unreachable!("prepared-route tests publish prepared events")+ }+ }++ #[async_trait]+ impl PublishPrepared for PreparedSink {+ async fn publish_prepared(&self, events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ self.seen+ .lock()+ .unwrap()+ .extend(events.iter().map(|event| event.uuid));+ events+ .iter()+ .map(|event| match self.failures.get(&event.uuid) {+ Some(err) => SinkResult::failed(event.uuid, err.clone()),+ None => SinkResult::published(event.uuid),+ })+ .collect()+ }+ }++ fn prepared_event() -> PreparedEvent {+ let event = test_event().event;+ PreparedEvent {+ uuid: Uuid::now_v7(),+ address: Address::Lane {+ pipeline: Pipeline::Analytics,+ lane: Lane::Main,+ },+ partition_key: event.key(),+ ordering: OrderingGuarantee::PerDistinctId,+ payload: bytes::Bytes::from_static(b"{}"),+ headers: event.to_headers(),+ }+ }++ fn outcomes(results: Vec<SinkResult>) -> Vec<(Uuid, Option<String>)> {+ results+ .into_iter()+ .map(|result| match result.outcome {+ Outcome::Published => (result.uuid, None),+ Outcome::Failed(err) => (result.uuid, Some(format!("{err:?}"))),+ })+ .collect()+ }++ fn failed(err: CaptureError) -> Option<String> {+ Some(format!("{err:?}"))+ }+fn test_event() -> ProcessedEvent {let timestamp = chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z").unwrap()@@ -201,7 +371,7 @@ mod tests {async fn failover_republishes_on_retriable_primary_failure() {let fallback = MockSink::new();let output = Output::failover(- Output::single(FailLeaf(CaptureError::RetryableSinkError)),+ Output::single(FailSink(CaptureError::RetryableSinkError)),Output::single(fallback.clone()),None,);@@ -217,8 +387,8 @@ mod tests {#[tokio::test]async fn failover_reports_the_error_when_both_targets_fail() {let output = Output::failover(- Output::single(FailLeaf(CaptureError::RetryableSinkError)),- Output::single(FailLeaf(CaptureError::RetryableSinkError)),+ Output::single(FailSink(CaptureError::RetryableSinkError)),+ Output::single(FailSink(CaptureError::RetryableSinkError)),None,);@@ -234,7 +404,7 @@ mod tests {async fn fatal_primary_error_does_not_fail_over() {let fallback = MockSink::new();let output = Output::failover(- Output::single(FailLeaf(CaptureError::NonRetryableSinkError)),+ Output::single(FailSink(CaptureError::NonRetryableSinkError)),Output::single(fallback.clone()),None,);@@ -309,8 +479,8 @@ mod tests {#[tokio::test]async fn registry_publishes_to_its_output() {- let leaf = MockSink::new();- let registry = OutputRegistry::single(leaf.clone());+ let sink = MockSink::new();+ let registry = OutputRegistry::single(sink.clone());registry.publish(vec![test_event()]).await.unwrap();registry@@ -318,6 +488,121 @@ mod tests {.await.unwrap();- assert_eq!(leaf.get_events().len(), 3);+ assert_eq!(sink.get_events().len(), 3);+ }++ #[tokio::test]+ async fn prepared_route_reports_one_result_per_event_in_order() {+ let events = vec![prepared_event(), prepared_event(), prepared_event()];+ let uuids: Vec<Uuid> = events.iter().map(|event| event.uuid).collect();+ let sink = PreparedSink::failing([(uuids[1], CaptureError::NonRetryableSinkError)]);+ let registry = OutputRegistry::single(sink.clone());++ let results = outcomes(registry.publish_prepared(events).await);++ assert_eq!(+ results,+ vec![+ (uuids[0], None),+ (uuids[1], failed(CaptureError::NonRetryableSinkError)),+ (uuids[2], None),+ ]+ );+ assert_eq!(sink.seen(), uuids);+ }++ #[tokio::test]+ async fn prepared_failover_republishes_only_retriable_events() {+ let events = vec![prepared_event(), prepared_event(), prepared_event()];+ let uuids: Vec<Uuid> = events.iter().map(|event| event.uuid).collect();+ let primary = PreparedSink::failing([+ (uuids[1], CaptureError::RetryableSinkError),+ (uuids[2], CaptureError::NonRetryableSinkError),+ ]);+ let fallback = PreparedSink::default();+ let output = Output::failover(+ Output::single(primary.clone()),+ Output::single(fallback.clone()),+ None,+ );++ let results = outcomes(output.publish_prepared(events).await);++ assert_eq!(+ results,+ vec![+ (uuids[0], None),+ (uuids[1], None),+ (uuids[2], failed(CaptureError::NonRetryableSinkError)),+ ],+ "a fatal primary failure is final; a retriable one takes the fallback's result"+ );+ assert_eq!(primary.seen(), uuids);+ assert_eq!(fallback.seen(), vec![uuids[1]]);+ }++ #[tokio::test]+ async fn prepared_failover_leaves_the_fallback_idle_when_the_primary_succeeds() {+ let fallback = PreparedSink::default();+ let output = Output::failover(+ Output::single(PreparedSink::default()),+ Output::single(fallback.clone()),+ None,+ );++ let results = outcomes(+ output+ .publish_prepared(vec![prepared_event(), prepared_event()])+ .await,+ );++ assert!(results.iter().all(|(_, err)| err.is_none()));+ assert!(fallback.seen().is_empty());+ }++ #[tokio::test]+ async fn prepared_failover_reports_the_fallback_failure() {+ let output = Output::failover(+ Output::single(FailSink(CaptureError::RetryableSinkError)),+ Output::single(FailSink(CaptureError::RetryableSinkError)),+ None,+ );++ let results = outcomes(output.publish_prepared(vec![prepared_event()]).await);++ assert_eq!(results[0].1, failed(CaptureError::RetryableSinkError));+ }++ #[tokio::test]+ async fn prepared_failover_skips_an_unhealthy_primary() {+ let mut manager = lifecycle::Manager::builder("test")+ .with_trap_signals(false)+ .with_prestop_check(false)+ .with_health_poll_interval(Duration::from_millis(50))+ .build();+ let kafka_handle = manager.register(+ "kafka-advisory",+ lifecycle::ComponentOptions::new()+ .with_liveness_deadline(Duration::from_millis(200))+ .is_advisory(true),+ );+ let _monitor = manager.monitor_background();++ let primary = PreparedSink::default();+ let fallback = PreparedSink::default();+ let output = Output::failover(+ Output::single(primary.clone()),+ Output::single(fallback.clone()),+ Some(kafka_handle.clone()),+ );++ kafka_handle.report_healthy();+ tokio::time::sleep(Duration::from_millis(400)).await;+ let event = prepared_event();+ let uuid = event.uuid;+ output.publish_prepared(vec![event]).await;++ assert!(primary.seen().is_empty());+ assert_eq!(fallback.seen(), vec![uuid]);}}diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rsindex 8226166552a9..83ed3e8c05b6 100644--- a/rust/capture/src/sinks/kafka.rs+++ b/rust/capture/src/sinks/kafka.rs@@ -21,15 +21,18 @@use crate::api::CaptureError;use crate::config::EnvelopeCompression;use crate::ordering::OrderingGuarantee;-use crate::outputs::PublishEvents;-use crate::pipeline::{self, Address, Lane, Pipeline};+use crate::outputs::{PreparedEvent, PublishEvents, PublishPrepared};+use crate::pipeline::{self, Address};use crate::producers::ProducerHandle;use crate::serialization::Serializer;use crate::sinks::producer::{KafkaProducer, ProduceRecord};use crate::sinks::registry::{Destination, OutputTable};-use crate::sinks::sink::{fold_results, Outcome, PreparedPayload, Sink, SinkResult};+use crate::sinks::sink::{fold_results, Outcome, PreparedPayload, PublishPayloads, SinkResult};use crate::v0_request::{DataType, ProcessedEvent};use async_trait::async_trait;+use bytes::Bytes;+use common_types::CapturedEventHeaders;+use futures::future::join_all;use metrics::{counter, gauge, histogram};use std::sync::Arc;use std::time::Instant;@@ -193,31 +196,6 @@ impl<P: KafkaProducer> Clone for KafkaSinkBase<P> {}}-/// Map a lane address to the sink's configured [`Destination`]. Every-/// `(pipeline, lane)` pair is spelled out so that a new lane, or a change-/// making an unbacked pair reachable, has to visit this match instead of-/// being absorbed by a wildcard. `None` marks a pair [`pipeline::resolve`]-/// never produces — no output backs it, and the caller dlqs the event.-fn lane_output(pipeline: Pipeline, lane: Lane) -> Option<Destination> {- match (pipeline, lane) {- (Pipeline::Analytics, Lane::Main) => Some(Destination::AnalyticsMain),- (Pipeline::Analytics, Lane::Overflow) => Some(Destination::AnalyticsOverflow),- (Pipeline::Analytics, Lane::Historical) => Some(Destination::AnalyticsHistorical),- (Pipeline::Ai, Lane::Main) => Some(Destination::AiMain),- (Pipeline::Ai, Lane::Overflow) => Some(Destination::AiOverflow),- (Pipeline::Ai, Lane::Historical) => None,- (Pipeline::Warnings, Lane::Main) => Some(Destination::ClientWarningsMain),- (Pipeline::Warnings, Lane::Overflow | Lane::Historical) => None,- (Pipeline::Heatmaps, Lane::Main) => Some(Destination::HeatmapsMain),- (Pipeline::Heatmaps, Lane::Overflow | Lane::Historical) => None,- (Pipeline::ErrorTracking, Lane::Main) => Some(Destination::ErrorTrackingMain),- (Pipeline::ErrorTracking, Lane::Overflow | Lane::Historical) => None,- (Pipeline::Replay, Lane::Main) => Some(Destination::SessionReplayMain),- (Pipeline::Replay, Lane::Overflow) => Some(Destination::SessionReplayOverflow),- (Pipeline::Replay, Lane::Historical) => None,- }-}-/// The dlq output's contract: count the reroute and stamp the dlq header set.fn dlq_reroute_effects(headers: &mut common_types::CapturedEventHeaders, reason: &'static str) {counter!("capture_events_rerouted_dlq", &[("reason", reason)]).increment(1);@@ -267,7 +245,7 @@ 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 — `Sink::publish` is what enforces+ /// touch the librdkafka producer queue — `PublishPayloads::publish` is what enforces/// per-partition ordering by calling `enqueue_record` serially in the/// original event order.///@@ -336,7 +314,7 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {.increment(1);Destination::Custom(topic)}- Address::Lane { pipeline, lane } => match lane_output(pipeline, lane) {+ Address::Lane { pipeline, lane } => match Destination::for_lane(pipeline, lane) {Some(output) => output,// A pair `resolve` never produces: no output backs it, so// the event goes to the dlq — preserved and replayable —@@ -379,23 +357,40 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {/// order, so this MUST be called in the original event order within a/// batch.fn enqueue_record(&self, payload: PreparedPayload) -> Result<P::AckFuture, CaptureError> {- let (topic, producer) = self.outputs.resolve(&payload.destination);+ self.send(+ &payload.destination,+ payload.partition_key,+ payload.ordering,+ payload.payload.into(),+ payload.headers,+ )+ }++ fn send(+ &self,+ destination: &Destination,+ partition_key: String,+ ordering: OrderingGuarantee,+ payload: Bytes,+ headers: CapturedEventHeaders,+ ) -> Result<P::AckFuture, CaptureError> {+ let (topic, producer) = self.outputs.resolve(destination);counter!("capture_kafka_produce_bytes_total", "topic" => Arc::clone(&topic))- .increment(payload.payload.len() as u64);+ .increment(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 {+ let key = match ordering {OrderingGuarantee::None => None,- _ => Some(payload.partition_key),+ _ => Some(partition_key),};producer.send(ProduceRecord {topic,key,- payload: payload.payload,- headers: payload.headers,+ payload,+ headers,})}@@ -433,7 +428,7 @@ 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+ /// rather than on the `PublishPayloads` trait: payload assembly is not backend/// mechanism, and the outputs layer becomes its caller.pub(crate) async fn prepare_batch(&self,@@ -524,7 +519,7 @@ impl<P: KafkaProducer + 'static> KafkaSinkBase<P> {}#[async_trait]-impl<P: KafkaProducer + 'static> Sink for KafkaSinkBase<P> {+impl<P: KafkaProducer + 'static> PublishPayloads 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@@ -598,11 +593,53 @@ impl<P: KafkaProducer + 'static> PublishEvents for KafkaSinkBase<P> {}let payloads = self.prepare_batch(events).await?;- fold_results(Sink::publish(self, payloads).await)+ fold_results(PublishPayloads::publish(self, payloads).await)+ }+}++#[async_trait]+impl<P: KafkaProducer + 'static> PublishPrepared for KafkaSinkBase<P> {+ #[instrument(skip_all)]+ async fn publish_prepared(&self, events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ let enqueue_start = Instant::now();+ let enqueued: Vec<_> = events+ .into_iter()+ .map(|event| {+ let uuid = event.uuid;+ let ack = match Destination::for_address(event.address) {+ Some(destination) => self.send(+ &destination,+ event.partition_key,+ event.ordering,+ event.payload,+ event.headers,+ ),+ None => {+ error!("no output backs the event's address, dropping it");+ Err(CaptureError::NonRetryableSinkError)+ }+ };+ (uuid, ack)+ })+ .collect();+ histogram!("capture_kafka_batch_enqueue_duration_seconds")+ .record(enqueue_start.elapsed().as_secs_f64());++ join_all(enqueued.into_iter().map(|(uuid, ack)| async move {+ match ack {+ Ok(ack) => match ack.await {+ Ok(()) => SinkResult::published(uuid),+ Err(err) => SinkResult::failed(uuid, err),+ },+ Err(err) => SinkResult::failed(uuid, err),+ }+ }))+ .instrument(info_span!("ack_wait_many"))+ .await}}-/// Concurrent ack drain for `Sink::publish`, fail-fast on first ack error.+/// Concurrent ack drain for `PublishPayloads::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.@@ -987,7 +1024,7 @@ mod tests {use super::*;use crate::sinks::kafka::{test_outputs, KafkaSinkBase, SCATTER_GATHER_MIN_BATCH};use crate::sinks::producer::MockKafkaProducer;- use crate::sinks::sink::{Outcome, Sink};+ use crate::sinks::sink::{Outcome, PublishPayloads};use rstest::rstest;const MAIN_TOPIC: &str = "events_plugin_ingestion";@@ -2893,7 +2930,7 @@ mod tests {#[test]fn publish_events_one_event_feeds_the_phase_histograms() {- // The one-event path skips prepare_batch and Sink::publish, which+ // The one-event path skips prepare_batch and PublishPayloads::publish, which// own these two histograms, so it has to record them itself.// Otherwise every single-event endpoint drops out of the// distribution and the in-process quantiles step up unprompted.@@ -2984,7 +3021,7 @@ mod tests {}// ==================== Sink mechanism seam ====================- // The per-event result surface `Sink::publish` reports: uuid-aligned+ // The per-event result surface `PublishPayloads::publish` reports: uuid-aligned// with the input payloads, batch-uniform on failure. `fold_results`// discards this shape, so the publish_events tests above cannot see it —// and the outputs layer builds on it.@@ -3220,4 +3257,258 @@ mod tests {assert!(v.get("distinct_id").is_some());}}++ mod prepared_route {+ use super::*;+ use crate::ordering::OrderingGuarantee;+ use crate::outputs::{PreparedEvent, PublishPrepared};+ use crate::pipeline::{Address, Lane, Pipeline};+ use crate::sinks::kafka::KafkaSinkBase;+ use crate::sinks::producer::MockKafkaProducer;+ use crate::sinks::sink::{Outcome, SinkResult};+ use common_types::CapturedEventHeaders;+ use rstest::rstest;+ use std::sync::Arc;+ use uuid::Uuid;++ fn prepared(address: Address, ordering: OrderingGuarantee) -> PreparedEvent {+ let uuid = Uuid::now_v7();+ PreparedEvent {+ uuid,+ address,+ partition_key: "token:distinct_id".to_string(),+ ordering,+ payload: bytes::Bytes::from(format!(r#"{{"uuid":"{uuid}"}}"#)),+ headers: CapturedEventHeaders {+ token: Some("token".to_string()),+ distinct_id: Some("distinct_id".to_string()),+ session_id: None,+ timestamp: None,+ event: Some("event".to_string()),+ uuid: Some(uuid.to_string()),+ now: None,+ force_disable_person_processing: None,+ historical_migration: None,+ skip_heatmap_processing: None,+ dlq_reason: None,+ dlq_step: None,+ dlq_timestamp: None,+ content_encoding: None,+ },+ }+ }++ fn analytics_main() -> PreparedEvent {+ prepared(+ Address::Lane {+ pipeline: Pipeline::Analytics,+ lane: Lane::Main,+ },+ OrderingGuarantee::PerDistinctId,+ )+ }++ fn outcomes(results: &[SinkResult]) -> Vec<Option<String>> {+ results+ .iter()+ .map(|result| match &result.outcome {+ Outcome::Published => None,+ Outcome::Failed(err) => Some(format!("{err:?}")),+ })+ .collect()+ }++ struct EventInput {+ address: Address,+ ordering: OrderingGuarantee,+ }++ struct ExpectedRecord<'a> {+ topic: &'a str,+ keyed: bool,+ }++ #[rstest]+ #[case::analytics_main(+ EventInput { address: Address::Lane { pipeline: Pipeline::Analytics, lane: Lane::Main }, ordering: OrderingGuarantee::PerDistinctId },+ ExpectedRecord { topic: "events_plugin_ingestion", keyed: true },+ )]+ #[case::analytics_overflow_spread(+ EventInput { address: Address::Lane { pipeline: Pipeline::Analytics, lane: Lane::Overflow }, ordering: OrderingGuarantee::None },+ ExpectedRecord { topic: "events_plugin_ingestion_overflow", keyed: false },+ )]+ #[case::analytics_historical(+ EventInput { address: Address::Lane { pipeline: Pipeline::Analytics, lane: Lane::Historical }, ordering: OrderingGuarantee::PerDistinctId },+ ExpectedRecord { topic: "events_plugin_ingestion_historical", keyed: true },+ )]+ #[case::ai_main(+ EventInput { address: Address::Lane { pipeline: Pipeline::Ai, lane: Lane::Main }, ordering: OrderingGuarantee::PerDistinctId },+ ExpectedRecord { topic: "ai_events", keyed: true },+ )]+ #[case::ai_overflow(+ EventInput { address: Address::Lane { pipeline: Pipeline::Ai, lane: Lane::Overflow }, ordering: OrderingGuarantee::None },+ ExpectedRecord { topic: "ai_events_overflow", keyed: false },+ )]+ #[case::heatmaps(+ EventInput { address: Address::Lane { pipeline: Pipeline::Heatmaps, lane: Lane::Main }, ordering: OrderingGuarantee::PerDistinctId },+ ExpectedRecord { topic: "heatmaps", keyed: true },+ )]+ #[case::warnings(+ EventInput { address: Address::Lane { pipeline: Pipeline::Warnings, lane: Lane::Main }, ordering: OrderingGuarantee::PerDistinctId },+ ExpectedRecord { topic: "client_ingestion_warning", keyed: true },+ )]+ #[case::error_tracking(+ EventInput { address: Address::Lane { pipeline: Pipeline::ErrorTracking, lane: Lane::Main }, ordering: OrderingGuarantee::PerDistinctId },+ ExpectedRecord { topic: "error_tracking_events", keyed: true },+ )]+ #[case::replay_overflow(+ EventInput { address: Address::Lane { pipeline: Pipeline::Replay, lane: Lane::Overflow }, ordering: OrderingGuarantee::PerSession },+ ExpectedRecord { topic: "replay_overflow", keyed: true },+ )]+ #[case::dlq(+ EventInput { address: Address::Dlq, ordering: OrderingGuarantee::PerDistinctId },+ ExpectedRecord { topic: "events_plugin_ingestion_dlq", keyed: true },+ )]+ #[case::custom(+ EventInput { address: Address::Custom("admin_topic".to_string()), ordering: OrderingGuarantee::PerDistinctId },+ ExpectedRecord { topic: "admin_topic", keyed: true },+ )]+ #[tokio::test]+ async fn prepared_event_lands_on_its_address_topic(+ #[case] input: EventInput,+ #[case] expected: ExpectedRecord<'_>,+ ) {+ let producer = MockKafkaProducer::new();+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());+ let event = prepared(input.address, input.ordering);+ let (payload, headers) = (event.payload.clone(), event.headers.clone());++ let results = sink.publish_prepared(vec![event]).await;++ assert_eq!(outcomes(&results), vec![None]);+ let records = producer.get_records();+ assert_eq!(records.len(), 1);+ assert_eq!(&*records[0].topic, expected.topic);+ assert_eq!(+ records[0].key.as_deref(),+ expected.keyed.then_some("token:distinct_id")+ );+ assert_eq!(+ records[0].payload, payload,+ "the payload passes through unchanged"+ );+ assert_eq!(+ format!("{:?}", records[0].headers),+ format!("{headers:?}"),+ "the headers pass through unchanged"+ );+ }++ #[tokio::test]+ async fn prepared_events_keep_input_order() {+ let producer = MockKafkaProducer::new();+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());+ let events: Vec<PreparedEvent> = (0..10).map(|_| analytics_main()).collect();+ let payloads: Vec<_> = events.iter().map(|event| event.payload.clone()).collect();+ let uuids: Vec<_> = events.iter().map(|event| event.uuid).collect();++ let results = sink.publish_prepared(events).await;++ let result_uuids: Vec<_> = results.iter().map(|result| result.uuid).collect();+ assert_eq!(result_uuids, uuids);+ let record_payloads: Vec<_> = producer+ .get_records()+ .into_iter()+ .map(|record| record.payload)+ .collect();+ assert_eq!(record_payloads, payloads);+ }++ #[tokio::test]+ async fn prepared_enqueue_failure_fails_only_that_event() {+ let producer = MockKafkaProducer::new_failing_at(1);+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());++ let results = sink+ .publish_prepared(vec![analytics_main(), analytics_main(), analytics_main()])+ .await;++ assert_eq!(+ outcomes(&results),+ vec![None, Some("RetryableSinkError".to_string()), None]+ );+ assert_eq!(producer.get_records().len(), 2);+ }++ #[tokio::test]+ async fn prepared_ack_failure_fails_only_that_event() {+ let producer = MockKafkaProducer::new_failing_ack_at(1);+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());++ let results = sink+ .publish_prepared(vec![analytics_main(), analytics_main(), analytics_main()])+ .await;++ assert_eq!(+ outcomes(&results),+ vec![None, Some("RetryableSinkError".to_string()), None]+ );+ assert_eq!(producer.get_records().len(), 3);+ }++ #[tokio::test]+ async fn prepared_event_on_an_unbacked_lane_fails_without_producing() {+ let producer = MockKafkaProducer::new();+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());+ let unbacked = prepared(+ Address::Lane {+ pipeline: Pipeline::Heatmaps,+ lane: Lane::Overflow,+ },+ OrderingGuarantee::PerDistinctId,+ );++ let results = sink+ .publish_prepared(vec![unbacked, analytics_main()])+ .await;++ assert_eq!(+ outcomes(&results),+ vec![Some("NonRetryableSinkError".to_string()), None]+ );+ assert_eq!(producer.get_records().len(), 1);+ }++ #[tokio::test]+ async fn prepared_event_publishes_through_its_targets_producer() {+ let ingestion = Arc::new(MockKafkaProducer::new());+ let ai = Arc::new(MockKafkaProducer::new());+ let mut outputs = test_outputs().map_producers(|_| Arc::clone(&ingestion));+ outputs.ai_main.producer = Arc::clone(&ai);+ let sink = KafkaSinkBase {+ outputs: Arc::new(outputs),+ replay_envelope_compression: EnvelopeCompression::None,+ };+ let ai_event = prepared(+ Address::Lane {+ pipeline: Pipeline::Ai,+ lane: Lane::Main,+ },+ OrderingGuarantee::PerDistinctId,+ );++ sink.publish_prepared(vec![analytics_main(), ai_event])+ .await;++ let topics = |producer: &MockKafkaProducer| -> Vec<String> {+ producer+ .get_records()+ .iter()+ .map(|record| record.topic.to_string())+ .collect()+ };+ assert_eq!(topics(&ingestion), vec!["events_plugin_ingestion"]);+ assert_eq!(topics(&ai), vec!["ai_events"]);+ }+ }}diff --git a/rust/capture/src/sinks/noop.rs b/rust/capture/src/sinks/noop.rsindex cdb94aa45272..00b32025b78b 100644--- a/rust/capture/src/sinks/noop.rs+++ b/rust/capture/src/sinks/noop.rs@@ -2,7 +2,8 @@ use async_trait::async_trait;use metrics::counter;use crate::api::CaptureError;-use crate::outputs::PublishEvents;+use crate::outputs::{PreparedEvent, PublishEvents, PublishPrepared};+use crate::sinks::sink::SinkResult;use crate::v0_request::ProcessedEvent;#[derive(Default)]@@ -21,3 +22,14 @@ impl PublishEvents for NoOpSink {Ok(())}}++#[async_trait]+impl PublishPrepared for NoOpSink {+ async fn publish_prepared(&self, events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ counter!("capture_events_ingested_total").increment(events.len() as u64);+ events+ .into_iter()+ .map(|event| SinkResult::published(event.uuid))+ .collect()+ }+}diff --git a/rust/capture/src/sinks/print.rs b/rust/capture/src/sinks/print.rsindex f7ea8a9001c4..6459641cff76 100644--- a/rust/capture/src/sinks/print.rs+++ b/rust/capture/src/sinks/print.rs@@ -4,7 +4,8 @@ use metrics::counter;use tracing::log::info;use crate::api::CaptureError;-use crate::outputs::PublishEvents;+use crate::outputs::{PreparedEvent, PublishEvents, PublishPrepared};+use crate::sinks::sink::SinkResult;use crate::v0_request::ProcessedEvent;pub struct PrintSink {}@@ -23,3 +24,20 @@ impl PublishEvents for PrintSink {Ok(())}}++#[async_trait]+impl PublishPrepared for PrintSink {+ async fn publish_prepared(&self, events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ let span = tracing::span!(tracing::Level::INFO, "batch of prepared events");+ let _enter = span.enter();++ counter!("capture_events_ingested_total").increment(events.len() as u64);+ events+ .into_iter()+ .map(|event| {+ info!("prepared event: {event:?}");+ SinkResult::published(event.uuid)+ })+ .collect()+ }+}diff --git a/rust/capture/src/sinks/producer.rs b/rust/capture/src/sinks/producer.rsindex 15102a642ff2..46c7bca1f519 100644--- a/rust/capture/src/sinks/producer.rs+++ b/rust/capture/src/sinks/producer.rs@@ -17,7 +17,7 @@ use crate::prometheus::report_dropped_events;pub struct ProduceRecord {pub topic: Arc<str>,pub key: Option<String>,- pub payload: Vec<u8>,+ pub payload: bytes::Bytes,pub headers: CapturedEventHeaders,}@@ -138,7 +138,7 @@ impl<C: rdkafka::ClientContext + Send + Sync + 'static> KafkaProducer for RdKafkmatch self.producer.send_result(FutureRecord {topic: &record.topic,- payload: Some(record.payload.as_slice()),+ payload: Some(record.payload.as_ref()),partition: None,key: record.key.as_deref(),timestamp: None,diff --git a/rust/capture/src/sinks/registry.rs b/rust/capture/src/sinks/registry.rsindex b291482ee38d..3731657a099a 100644--- a/rust/capture/src/sinks/registry.rs+++ b/rust/capture/src/sinks/registry.rs@@ -8,6 +8,7 @@use std::sync::Arc;use crate::config::OutputsConfig;+use crate::pipeline::{Address, Lane, Pipeline};use crate::producers::ProducerName;/// Which configured output a routing decision selects, named by pipeline and@@ -47,6 +48,43 @@ impl Destination {Destination::AiMain,];+ /// `None` marks a pair [`pipeline::resolve`] never produces: no output+ /// backs it.+ ///+ /// [`pipeline::resolve`]: crate::pipeline::resolve+ pub(crate) fn for_lane(pipeline: Pipeline, lane: Lane) -> Option<Destination> {+ // Every pair is spelled out so that a new lane, or a change making an+ // unbacked pair reachable, has to visit this match instead of being+ // absorbed by a wildcard. Step 13 of OUTPUTS_REFACTOR_PLAN.md types+ // lanes per pipeline so such pairs cannot be built; drop the `None`+ // arms and this note then.+ match (pipeline, lane) {+ (Pipeline::Analytics, Lane::Main) => Some(Destination::AnalyticsMain),+ (Pipeline::Analytics, Lane::Overflow) => Some(Destination::AnalyticsOverflow),+ (Pipeline::Analytics, Lane::Historical) => Some(Destination::AnalyticsHistorical),+ (Pipeline::Ai, Lane::Main) => Some(Destination::AiMain),+ (Pipeline::Ai, Lane::Overflow) => Some(Destination::AiOverflow),+ (Pipeline::Ai, Lane::Historical) => None,+ (Pipeline::Warnings, Lane::Main) => Some(Destination::ClientWarningsMain),+ (Pipeline::Warnings, Lane::Overflow | Lane::Historical) => None,+ (Pipeline::Heatmaps, Lane::Main) => Some(Destination::HeatmapsMain),+ (Pipeline::Heatmaps, Lane::Overflow | Lane::Historical) => None,+ (Pipeline::ErrorTracking, Lane::Main) => Some(Destination::ErrorTrackingMain),+ (Pipeline::ErrorTracking, Lane::Overflow | Lane::Historical) => None,+ (Pipeline::Replay, Lane::Main) => Some(Destination::SessionReplayMain),+ (Pipeline::Replay, Lane::Overflow) => Some(Destination::SessionReplayOverflow),+ (Pipeline::Replay, Lane::Historical) => None,+ }+ }++ pub(crate) fn for_address(address: Address) -> Option<Destination> {+ match address {+ Address::Lane { pipeline, lane } => Self::for_lane(pipeline, lane),+ Address::Dlq => Some(Destination::Dlq),+ Address::Custom(topic) => Some(Destination::Custom(topic)),+ }+ }+/// Whether this output participates in the boot completeness check./// Deliberately exhaustive: a new variant cannot compile without/// declaring which side it is on, and@@ -132,8 +170,8 @@ impl<R> OutputTable<R> {Destination::AiMain => Some(&self.ai_main),Destination::AiOverflow => match &self.ai_overflow {Some(target) if !target.topic.is_empty() => Some(target),- // Unreachable: routing only selects this output when the- // valve is armed, i.e. exactly when the topic is set.+ // Callers select this output only when the valve is armed,+ // i.e. exactly when the topic is set._ => Some(&self.ai_main),},Destination::Custom(_) => None,diff --git a/rust/capture/src/sinks/s3.rs b/rust/capture/src/sinks/s3.rsindex 005225a2b889..da060065ad53 100644--- a/rust/capture/src/sinks/s3.rs+++ b/rust/capture/src/sinks/s3.rs@@ -17,7 +17,8 @@ use tracing::instrument;use tracing::log::{debug, error, info};use crate::api::CaptureError;-use crate::outputs::PublishEvents;+use crate::outputs::{PreparedEvent, PublishEvents, PublishPrepared};+use crate::sinks::sink::SinkResult;const FLUSH_INTERVAL: Duration = Duration::from_secs(1);const HEALTH_INTERVAL: Duration = Duration::from_secs(10);@@ -54,12 +55,10 @@ impl EventBuffer {}}- fn add_event(&mut self, event: ProcessedEvent) -> Result<(), CaptureError> {- let json = serde_json::to_string(&event.event)?;- self.event_bytes.extend_from_slice(json.as_bytes());+ fn add_line(&mut self, body: &[u8]) {+ self.event_bytes.extend_from_slice(body);self.event_bytes.push(b'\n');self.event_count += 1;- Ok(())}fn should_flush(&self) -> bool {@@ -273,19 +272,53 @@ impl Inner {}}-#[async_trait]-impl PublishEvents for S3Sink {- #[instrument(skip_all)]- async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl S3Sink {+ async fn write_lines<B: AsRef<[u8]>>(+ &self,+ bodies: impl ExactSizeIterator<Item = B> + Send,+ ) -> Result<(), CaptureError> {+ // An idle buffer never flushes, so waiting on it would never return.+ if bodies.len() == 0 {+ return Ok(());+ }let mut buffer = self.inner.buffer.lock().await;- for event in events {- buffer.add_event(event)?;+ for body in bodies {+ buffer.add_line(body.as_ref());}let mut rx = buffer.tx.subscribe();drop(buffer);rx.recv().await- .map_err(|_| CaptureError::NonRetryableSinkError)?+ .unwrap_or(Err(CaptureError::NonRetryableSinkError))+ }+}++#[async_trait]+impl PublishEvents for S3Sink {+ #[instrument(skip_all)]+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ let bodies = events+ .iter()+ .map(|event| serde_json::to_vec(&event.event))+ .collect::<Result<Vec<_>, _>>()?;+ self.write_lines(bodies.iter()).await+ }+}++#[async_trait]+impl PublishPrepared for S3Sink {+ #[instrument(skip_all)]+ async fn publish_prepared(&self, events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ let flushed = self+ .write_lines(events.iter().map(|event| &event.payload))+ .await;+ events+ .iter()+ .map(|event| match &flushed {+ Ok(()) => SinkResult::published(event.uuid),+ Err(err) => SinkResult::failed(event.uuid, err.clone()),+ })+ .collect()}}@@ -359,6 +392,17 @@ mod tests {}}+ #[tokio::test]+ async fn empty_prepared_batch_returns_without_waiting_for_a_flush() {+ let sink = setup_test_sink().await;++ let results = tokio::time::timeout(Duration::from_secs(5), sink.publish_prepared(vec![]))+ .await+ .expect("an empty batch must not wait on the idle buffer");++ assert!(results.is_empty());+ }+#[tokio::test]async fn test_basic_functionality() {let sink = setup_test_sink().await;diff --git a/rust/capture/src/sinks/sink.rs b/rust/capture/src/sinks/sink.rsindex 1eac0304175e..0f3e74fa77ed 100644--- a/rust/capture/src/sinks/sink.rs+++ b/rust/capture/src/sinks/sink.rs@@ -7,9 +7,10 @@//! 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`].+//! [`PublishPayloads::publish`] does not return an error: every input payload gets a+//! [`SinkResult`], and a failure is reported in that payload's result. Callers+//! that need the v0 whole-request response collapse the results with+//! [`fold_results`].use async_trait::async_trait;use common_types::CapturedEventHeaders;@@ -24,19 +25,14 @@ use crate::sinks::registry::Destination;/// 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.+/// terms, and nothing here names a Kafka concept.#[derive(Debug, Clone)]pub(crate) struct PreparedPayload {pub uuid: Uuid,/// The output this record is addressed to. Each sink resolves it to its/// own target, as v1's sinks resolve their `Destination`.pub destination: Destination,- /// 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,@@ -44,40 +40,26 @@ pub(crate) struct PreparedPayload {/// What happened to one published payload.#[derive(Debug)]-pub(crate) enum Outcome {+pub 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 struct SinkResult {pub uuid: Uuid,pub outcome: Outcome,}impl SinkResult {- pub(crate) fn published(uuid: Uuid) -> Self {+ pub fn published(uuid: Uuid) -> Self {Self {uuid,outcome: Outcome::Published,}}- pub(crate) fn failed(uuid: Uuid, err: CaptureError) -> Self {+ pub fn failed(uuid: Uuid, err: CaptureError) -> Self {Self {uuid,outcome: Outcome::Failed(err),@@ -88,7 +70,7 @@ impl SinkResult {/// 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 {+pub(crate) trait PublishPayloads {async fn publish(&self, payloads: Vec<PreparedPayload>) -> Vec<SinkResult>;}diff --git a/rust/capture/src/sinks/test_sink.rs b/rust/capture/src/sinks/test_sink.rsindex f1c764c392d3..e713629c7c09 100644--- a/rust/capture/src/sinks/test_sink.rs+++ b/rust/capture/src/sinks/test_sink.rs@@ -2,7 +2,8 @@//! crate.use crate::api::CaptureError;-use crate::outputs::PublishEvents;+use crate::outputs::{PreparedEvent, PublishEvents, PublishPrepared};+use crate::sinks::sink::SinkResult;use crate::v0_request::ProcessedEvent;use async_trait::async_trait;use std::sync::{Arc, Mutex};@@ -29,3 +30,10 @@ impl PublishEvents for MockSink {Ok(())}}++#[async_trait]+impl PublishPrepared for MockSink {+ async fn publish_prepared(&self, _events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+}diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rsindex 229aff1e1712..c691eb402cd4 100644--- a/rust/capture/tests/common/integration_utils.rs+++ b/rust/capture/tests/common/integration_utils.rs@@ -8,9 +8,10 @@ use std::time::Duration;use capture::{api::{CaptureError, CaptureResponse, CaptureResponseCode},config::CaptureMode,- outputs::{OutputRegistry, PublishEvents},+ outputs::{OutputRegistry, PreparedEvent, PublishEvents, PublishPrepared},quota_limiters::CaptureQuotaLimiter,router::router,+ sinks::sink::SinkResult,time::TimeSource,v0_request::{DataType, ProcessedEvent},v1::test_utils::TestStateBuilder,@@ -1039,6 +1040,13 @@ impl PublishEvents for MemorySink {}}+#[async_trait]+impl PublishPrepared for MemorySink {+ async fn publish_prepared(&self, _events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+}+pub fn test_lifecycle_handlers() -> (lifecycle::ReadinessHandler,lifecycle::LivenessHandler,diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rsindex 4e845775844c..f6d6cddc96ca 100644--- a/rust/capture/tests/integration_ai_endpoint.rs+++ b/rust/capture/tests/integration_ai_endpoint.rs@@ -8,9 +8,10 @@ use axum_test_helper::TestClient;use capture::api::CaptureError;use capture::config::CaptureMode;use capture::global_rate_limiter::GlobalRateLimiter;-use capture::outputs::{OutputRegistry, PublishEvents};+use capture::outputs::{OutputRegistry, PreparedEvent, PublishEvents, PublishPrepared};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;+use capture::sinks::sink::SinkResult;use capture::time::TimeSource;use capture::v0_request::{OverflowReason, ProcessedEvent};use chrono::{DateTime, TimeZone, Utc};@@ -50,6 +51,13 @@ impl PublishEvents for TestSink {}}+#[async_trait]+impl PublishPrepared for TestSink {+ async fn publish_prepared(&self, _events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+}+// Capturing sink for Kafka tests - stores events in memory#[derive(Clone)]struct CapturingSink {@@ -76,6 +84,13 @@ impl PublishEvents for CapturingSink {}}+#[async_trait]+impl PublishPrepared for CapturingSink {+ async fn publish_prepared(&self, _events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+}+// Helper to build multipart form and send requestasync fn send_multipart_request(client: &TestClient,diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rsindex 30f7b8e4a8bb..83bf415e547f 100644--- a/rust/capture/tests/integration_ai_restrictions.rs+++ b/rust/capture/tests/integration_ai_restrictions.rs@@ -11,9 +11,10 @@ use capture::event_restrictions::{EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,RestrictionType,};-use capture::outputs::{OutputRegistry, PublishEvents};+use capture::outputs::{OutputRegistry, PreparedEvent, PublishEvents, PublishPrepared};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;+use capture::sinks::sink::SinkResult;use capture::time::TimeSource;use capture::v0_request::{DataType, OverflowReason, ProcessedEvent};use chrono::{DateTime, Utc};@@ -63,6 +64,13 @@ impl PublishEvents for CapturingSink {}}+#[async_trait]+impl PublishPrepared for CapturingSink {+ async fn publish_prepared(&self, _events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+}+async fn send_multipart_request(client: &TestClient,form: Form,diff --git a/rust/capture/tests/integration_analytics_ai_routing.rs b/rust/capture/tests/integration_analytics_ai_routing.rsindex 55328e837714..4b692a265aa9 100644--- a/rust/capture/tests/integration_analytics_ai_routing.rs+++ b/rust/capture/tests/integration_analytics_ai_routing.rs@@ -14,9 +14,10 @@ use axum::Router;use axum_test_helper::TestClient;use capture::api::CaptureError;use capture::config::CaptureMode;-use capture::outputs::{OutputRegistry, PublishEvents};+use capture::outputs::{OutputRegistry, PreparedEvent, PublishEvents, PublishPrepared};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;+use capture::sinks::sink::SinkResult;use capture::time::TimeSource;use capture::v0_request::{DataType, OverflowReason, ProcessedEvent};use chrono::{DateTime, Utc};@@ -68,6 +69,13 @@ impl PublishEvents for CapturingSink {}}+#[async_trait]+impl PublishPrepared for CapturingSink {+ async fn publish_prepared(&self, _events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+}+fn setup_analytics_router(ai_events_overflow_enabled: bool,overflow_limiter: Option<Arc<OverflowLimiter>>,diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rsindex 9d4f881e267e..d3f755a516a4 100644--- a/rust/capture/tests/integration_analytics_restrictions.rs+++ b/rust/capture/tests/integration_analytics_restrictions.rs@@ -11,9 +11,10 @@ use capture::event_restrictions::{EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,RestrictionType,};-use capture::outputs::{OutputRegistry, PublishEvents};+use capture::outputs::{OutputRegistry, PreparedEvent, PublishEvents, PublishPrepared};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;+use capture::sinks::sink::SinkResult;use capture::time::TimeSource;use capture::v0_request::{DataType, ProcessedEvent};use chrono::{DateTime, Utc};@@ -59,6 +60,13 @@ impl PublishEvents for CapturingSink {}}+#[async_trait]+impl PublishPrepared for CapturingSink {+ async fn publish_prepared(&self, _events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+}+async fn setup_analytics_router_with_restriction(restriction_type: RestrictionType,restriction_pipeline: Pipeline,diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rsindex d221647cc673..b68a13a55bbf 100644--- a/rust/capture/tests/integration_otel_endpoint.rs+++ b/rust/capture/tests/integration_otel_endpoint.rs@@ -10,9 +10,10 @@ use capture::event_restrictions::{RestrictionScope, RestrictionType,};use capture::global_rate_limiter::GlobalRateLimiter;-use capture::outputs::{OutputRegistry, PublishEvents};+use capture::outputs::{OutputRegistry, PreparedEvent, PublishEvents, PublishPrepared};use capture::quota_limiters::{is_llm_event, CaptureQuotaLimiter, EventInfo};use capture::router::router;+use capture::sinks::sink::SinkResult;use capture::time::TimeSource;use capture::v0_request::{DataType, OverflowReason, ProcessedEvent};use chrono::{DateTime, Utc};@@ -76,6 +77,13 @@ impl PublishEvents for CapturingSink {}}+#[async_trait]+impl PublishPrepared for CapturingSink {+ async fn publish_prepared(&self, _events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+}+const TOKEN: &str = "phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3";fn make_kv(key: &str, value: any_value::Value) -> KeyValue {diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rsindex 1d4963416fe7..a8e996630235 100644--- a/rust/capture/tests/integration_replay_restrictions.rs+++ b/rust/capture/tests/integration_replay_restrictions.rs@@ -11,9 +11,10 @@ use capture::event_restrictions::{EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,RestrictionType,};-use capture::outputs::{OutputRegistry, PublishEvents};+use capture::outputs::{OutputRegistry, PreparedEvent, PublishEvents, PublishPrepared};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;+use capture::sinks::sink::SinkResult;use capture::time::TimeSource;use capture::v0_request::{DataType, ProcessedEvent};use chrono::{DateTime, Utc};@@ -60,6 +61,13 @@ impl PublishEvents for CapturingSink {}}+#[async_trait]+impl PublishPrepared for CapturingSink {+ async fn publish_prepared(&self, _events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+}+async fn setup_recordings_router_with_restriction(restriction_type: RestrictionType,token: &str,diff --git a/rust/capture/tests/integration_wire_body_limits.rs b/rust/capture/tests/integration_wire_body_limits.rsindex 4f7da52735ee..25d2d953b68b 100644--- a/rust/capture/tests/integration_wire_body_limits.rs+++ b/rust/capture/tests/integration_wire_body_limits.rs@@ -6,9 +6,10 @@ use axum::http::StatusCode;use axum_test_helper::TestClient;use capture::api::CaptureError;use capture::config::CaptureMode;-use capture::outputs::{OutputRegistry, PublishEvents};+use capture::outputs::{OutputRegistry, PreparedEvent, PublishEvents, PublishPrepared};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::{router, BATCH_BODY_SIZE};+use capture::sinks::sink::SinkResult;use capture::time::TimeSource;use capture::v0_request::ProcessedEvent;use chrono::{DateTime, Utc};@@ -55,6 +56,13 @@ impl PublishEvents for CapturingSink {}}+#[async_trait]+impl PublishPrepared for CapturingSink {+ async fn publish_prepared(&self, _events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+}+/// A client whose decompressed budget is far above the wire cap, so only the/// wire cap can produce a 413. This mirrors production, where the decompressed/// budget is five times the wire cap.diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rsindex 01e3dfd45936..969e4bf639b0 100644--- a/rust/capture/tests/quota_limiters.rs+++ b/rust/capture/tests/quota_limiters.rs@@ -16,11 +16,12 @@ use serde_json::Value;use capture::api::CaptureError;use capture::config::CaptureMode;-use capture::outputs::{OutputRegistry, PublishEvents};+use capture::outputs::{OutputRegistry, PreparedEvent, PublishEvents, PublishPrepared};use capture::quota_limiters::{is_exception_event, is_llm_event, is_survey_event, CaptureQuotaLimiter, EventInfo,};use capture::router::router;+use capture::sinks::sink::SinkResult;use capture::time::TimeSource;use capture::v0_request::ProcessedEvent;use chrono::{DateTime, Utc};@@ -38,6 +39,13 @@ impl PublishEvents for MemorySink {}}+#[async_trait]+impl PublishPrepared for MemorySink {+ async fn publish_prepared(&self, _events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ unreachable!("v0 endpoints publish events")+ }+}+impl MemorySink {fn events(&self) -> Vec<ProcessedEvent> {self.events.lock().unwrap().clone()