: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): v1 publishes through outputs; v1 sink stack deleted (#113850)
Paweł Ledwońc201ce3f0c17
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.mdindex de4dc180e235..7595e205620e 100644--- a/rust/capture/OUTPUTS_REFACTOR_PLAN.md+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md@@ -1,15 +1,15 @@# Capture outputs refactor — implementation plan-Working contract for implementation agents. Steps 1–11 have shipped. Each remaining step is one commit in its own PR.+Working contract for implementation agents. Steps 1–12 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.+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, and unscheduled work becomes issues.## ObjectivesCapture has two produce stacks. The v0 endpoints (`/e`, `/batch`, `/i/v0/*`, replay, OTEL) stay forever. The v1 stack is live beside them: capture-analytics and capture-import serve `/i/v1/analytics/events` through it, and capture-ai serves `/i/v1/ai/events`. Both stacks produce through the outputs layer, and v0's internals move toward v1's shape.1. **Manual fallback for all capture traffic.** If MSK degrades, capture-analytics can produce to another cluster, with its own brokers, TLS, and topic names. One environment variable and a pod roll arm it, for v0 and v1 traffic alike. Boot-time checks prove the configuration is sound before any traffic moves. Steps 9–18.-2. **One set of internals for v0 and v1.** The two stacks share producers and producer tuning, v0 builds prepared events before the outputs layer like v1, and both use one prepared-event builder and one lane-decision model. The v0 endpoints do not change. Steps 19–22.+2. **One set of internals for v0 and v1.** v0 builds prepared events before the outputs layer like v1, and both use one prepared-event builder and one lane-decision model. The two stacks already share one producer and its settings (Step 12). The v0 endpoints do not change. Steps 20–22.3. **Automated fallback, capture side.** A separate circuit-breaker service decides when to switch. Capture sends producer health, receives switch signals, and applies them at runtime without a redeploy. Consumers are out of scope. Steps 23–25.Objective 2 goes before 3 because it deletes v0's event-level route into the outputs layer; the runtime switch is then built once, on the one remaining route. Neither depends on the other otherwise, and objective 3 also waits on the breaker service existing.@@ -24,7 +24,7 @@ All three use one mechanism:A fallback is then a configuration of an output's targets, not a new code path. The policy tree already composes two outputs (Step 7). It needs targets that can be configured independently, a policy that picks the live target at boot (Step 17), and for objective 3, a way to change that pick at runtime.-Today this is not possible. One deployment-wide `KafkaConfig` holds ten topic names, each with a compiled-in default, so a boot check cannot tell a configured topic from a missing one. The existing completeness flag demands all ten on every pod. It fails any deployment that deliberately blanks a topic it never produces to, and where it can be enabled it still misses a missing variable, because the default fills it in. v1 publishes through its own sinks, so nothing in the outputs layer moves its traffic.+Today this is not possible. One deployment-wide `KafkaConfig` holds ten topic names, each with a compiled-in default, so a boot check cannot tell a configured topic from a missing one. The existing completeness flag demands all ten on every pod. It fails any deployment that deliberately blanks a topic it never produces to, and where it can be enabled it still misses a missing variable, because the default fills it in.Every step is a small commit, proven by the Step-1 goldens, and reverted by plain revert. Cluster migration by split or dual-write stays under **Deferred work**.@@ -55,9 +55,9 @@ producers → named connections (brokers, TLS, tuning), instantiated onc### Vocabulary rules- **Address** = a lane of a pipeline, or an admin redirect (`Dlq`, `Custom(topic)`) outside the lane model. v0 builds it through `resolve`, v1 by mapping its `Destination`. Never reintroduce a flat enum that mixes pipeline and lane.-- **Prepared event** = the transport-independent result of processing one event. v1's `PreparedEvent` is the shape; v0's `PreparedPayload` differs only in carrying v0's `Destination` instead of an address.+- **Prepared event** = the transport-independent result of processing one event. The outputs layer's `PreparedEvent` is the shape, and v1 builds it; v0's `PreparedPayload` differs only in carrying v0's `Destination` instead of an address.- **Output** = targets + selection policy. **OutputRegistry** = the address → output map. The Step-3 **TopicTable** became the Step-10 **OutputTable**: one target per `Destination`.-- **Destination** = v0's `sinks::registry::Destination` and v1's `v1::sinks::types::Destination` name the same routed slots. Both map onto `Address`. Never call both a policy tree and a routed topic an `Output`.+- **Destination** = v0's `sinks::registry::Destination` and v1's `v1::types::Destination` name the same routed slots. Both map onto `Address`. Never call both a policy tree and a routed topic an `Output`.- **Sink** = one transport. Anything that picks between sinks is an output policy.- **Producer** config never carries topic names, and output config never carries connection config. An output moves clusters by naming a different producer.@@ -84,21 +84,13 @@ Steps 1–11 shipped the structure:- **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 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.+- **12** — v1 publishes through the outputs layer. `Destination::address` maps each v1 destination to an `Address`, `serialize_batch` builds the outputs layer's `PreparedEvent`s, and `process_batch` calls `state.outputs.publish_prepared` on the registry v0 uses. v0 and v1 are different HTTP endpoints, not different pipelines, so they share the `INGESTION` producer and its settings; per-pipeline tuning stays per deployment. v1's `Router`, `Sink`, `KafkaSink`, producer, per-sink config, `SinkName` and the `topic_ai` injection are deleted, and so is v1's produce timeout, which v0 never had. The capture mode alone decides which v1 endpoints a deployment serves, so `CAPTURE_V1_SINKS` and every `CAPTURE_V1_SINK_*` variable go. Accepted differences: the `capture_v1_kafka_*` metrics give way to the shared Kafka sink's; v1's per-error cause tags collapse into `CaptureError` kinds, so response details read `not_persisted`, `event_too_big` or `rejected`; `InvalidMessage` and `InvalidMessageSize`, which v1 classed as fatal, are now retriable, as in v0; the batch-wide `is_ready` reject and the per-sink lifecycle handles are gone, and producer liveness is the `INGESTION` slot's; v1 traffic takes the deployment's output policy, including S3 failover where it is on. It supersedes Step 19.-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`.+Today the registry holds one deployment-wide `Output`: a Kafka sink, or Kafka→S3 failover. v0 publishes events through it and v1 publishes prepared events through it.## Objective 1 — manual fallback for all capture traffic-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--- **Goal.** v1 maps its `Destination` to `Address` and calls `publish_prepared`. v1's `Router`, `Sink`, `KafkaSink`, and per-sink Kafka config are deleted. Each `CAPTURE_V1_SINK_*` cluster becomes a named producer, and its topics become output rows. The `topic_ai` override in `setup::create_v1_sink_router` goes with it.-- **Produce timeout moves to the shared Kafka sink.** v1 bounds each batch's acks by a produce timeout; acks that miss it return `Outcome::Timeout`, and the events are retried. The shared Kafka sink gains this, configured per target.-- **Kept separate until Step 19.** v1's producer tuning differs from v0's (for example lz4 vs no compression, 4 vs 2 retries, 30 s vs 20 s message timeout), so each stack keeps its own named producer and tuning. capture-analytics keeps its two MSK connections, one per stack.-- **Accepted differences.** The `capture_v1_kafka_*` metrics are replaced by the shared Kafka sink's metrics.-- **Parity proof.** `v1_pipeline`, `v1_sink_integration`, and `overflow_parity.rs` unmodified.-- **Size.** L.+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 13 · Typed per-pipeline lanes@@ -165,10 +157,6 @@ Example of what this catches: until [charts#14941](https://github.com/PostHog/chScheduled when objective 1 closes. The v0 endpoints and their responses do not change.-### Step 19 · One producer per cluster--v0 and v1 producer tuning is reconciled into one set per cluster, and capture-analytics opens one MSK connection instead of two. Each difference (compression, retries, message timeout, metadata refresh, and the rest) is either adopted by both stacks or recorded as a per-producer setting with a reason.-### Step 20 · v0 builds prepared eventsv0 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`.@@ -276,14 +264,14 @@ One step = one commit, subject from the tracker. No `--no-verify`.| 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 | 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` |+| 12 · v1 publishes through the outputs layer | done | `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` || 15 · A reachable output must be configured | pending | `feat(capture): require configuration for every reachable output` || 16 · Verify topics against the producer's broker | pending | `feat(capture): verify each output's topics against its producer's broker at boot` || 17 · capture-analytics emergency fallback | pending | `feat(capture): select policy and emergency fallback for capture-analytics` || 18 · Delete the S3 fallback | pending | `refactor(capture): delete the s3 fallback and the health-gated failover policy` |-| 19 · One producer per cluster | objective 2 | `refactor(capture): v0 and v1 share one producer per cluster` |+| 19 · One producer per cluster | superseded | — (Step 12 put v1 on v0's producer and settings) || 20 · v0 builds prepared events | objective 2 | `refactor(capture): v0 publishes prepared events; PublishEvents retired` || 21 · One prepared-event builder | objective 2 | `refactor(capture): v0 and v1 share one prepared-event builder` || 22 · One lane-decision model | objective 2 | `refactor(capture): v0 lane decision moves to the v1 model` |diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex f4b94d2e4c36..ab193b961bad 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -394,12 +394,6 @@ pub struct Config {#[envconfig(nested = true)]pub continuous_profiling: ContinuousProfilingConfig,- /// Comma-separated list of active v1 sinks (e.g. "msk" or "msk,ws").- /// Parsed by `v1::sinks::load_sinks()` after `Config::init_from_env()`.- /// Empty string means the v1 sink layer is disabled.- #[envconfig(default = "")]- pub capture_v1_sinks: String,-/// Maximum compressed (wire) body size the v1 endpoint will accept (bytes).#[envconfig(default = "10485760")]pub capture_v1_max_compressed_body_bytes: usize,@@ -571,9 +565,9 @@ pub struct OutputsConfig {pub dlq_topic: String,#[envconfig(from = "CAPTURE_OUTPUT_DLQ_PRODUCER", default = "INGESTION")]pub dlq_producer: ProducerName,- /// The v0 (`DataType::AiEvents`) and v1 (`Destination::AiEvents`) pipelines+ /// The v0 (`DataType::AiEvents`) and v1 (`Destination::AiMain`) pipelines/// divert AI events here instead of the main topic on every deployment,- /// capture-ai included. Setup also injects it into every v1 sink config.+ /// capture-ai included.#[envconfig(from = "CAPTURE_OUTPUT_AI_MAIN_TOPIC",default = "events_plugin_ingestion_ai"diff --git a/rust/capture/src/event_restrictions/types.rs b/rust/capture/src/event_restrictions/types.rsindex b954e8247022..0d320f097361 100644--- a/rust/capture/src/event_restrictions/types.rs+++ b/rust/capture/src/event_restrictions/types.rs@@ -18,6 +18,8 @@ pub enum Pipeline {SessionRecordings,Ai,ErrorTracking,+ Heatmaps,+ ClientWarnings,}impl Pipeline {@@ -27,6 +29,8 @@ impl Pipeline {Self::SessionRecordings => "session_recordings",Self::Ai => "ai",Self::ErrorTracking => "errortracking",+ Self::Heatmaps => "heatmaps",+ Self::ClientWarnings => "clientwarnings",}}@@ -36,6 +40,8 @@ impl Pipeline {"session_recordings" => Some(Self::SessionRecordings),"ai" => Some(Self::Ai),"errortracking" => Some(Self::ErrorTracking),+ "heatmaps" => Some(Self::Heatmaps),+ "clientwarnings" => Some(Self::ClientWarnings),_ => None,}}@@ -383,6 +389,11 @@ mod tests {Pipeline::parse("errortracking"),Some(Pipeline::ErrorTracking));+ assert_eq!(Pipeline::parse("heatmaps"), Some(Pipeline::Heatmaps));+ assert_eq!(+ Pipeline::parse("clientwarnings"),+ Some(Pipeline::ClientWarnings)+ );assert_eq!(Pipeline::parse("unknown"), None);}@@ -393,6 +404,8 @@ mod tests {Pipeline::SessionRecordings,Pipeline::Ai,Pipeline::ErrorTracking,+ Pipeline::Heatmaps,+ Pipeline::ClientWarnings,] {assert_eq!(Pipeline::parse(pipeline.as_str()), Some(pipeline));}diff --git a/rust/capture/src/events/ai_byte_limit.rs b/rust/capture/src/events/ai_byte_limit.rsindex 208648a9a645..3c5515765689 100644--- a/rust/capture/src/events/ai_byte_limit.rs+++ b/rust/capture/src/events/ai_byte_limit.rs@@ -1,7 +1,7 @@//! The AI lane's per-project byte budget. The lane is the whole gate: every//! `$ai_` event (`v0_request::is_ai_event`) is bound for the AI Kafka topic on//! every deployment, stamped `DataType::AiEvents` in v0 and-//! `Destination::AiEvents` in v1. Import deployments are exempt — backfills+//! `Destination::AiMain` in v1. Import deployments are exempt — backfills//! are never throttled, matching the other limiters — which setup enforces by//! not building the limiter at all in import mode.//!diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rsindex 1bf591c958ed..8e0d5955a29f 100644--- a/rust/capture/src/events/analytics.rs+++ b/rust/capture/src/events/analytics.rs@@ -433,9 +433,8 @@ async fn process_events_inner(// pipelines its host capture deployment serves; the pipeline argument// selects which slice of restrictions applies to each event. A DropEvent// tagged only for `analytics` will never silently drop an exception event- // on the way to the error tracking topic, and vice versa. Data types- // without a pipeline (heatmaps, ingestion warnings, snapshots) flow- // through unrestricted. `AiEvents` looks up the `ai` pipeline: a diverted+ // on the way to the error tracking topic, and vice versa. Snapshots have+ // no pipeline here and flow through unrestricted. `AiEvents` looks up the `ai` pipeline: a diverted// AI event is governed by ai-scoped restrictions (drop/DLQ/redirect still// win over the lane, redirect_to_topic beats the AI topic in the sink,// force_overflow keeps it on the AI lane) -- mirroring v1.@@ -1972,7 +1971,7 @@ mod tests {/// An ai-scoped RedirectToTopic applies to a diverted AI event: the/// event keeps its AI lane, but the stamped redirect beats the data type/// in the sink so operators can reroute an AI token's traffic ad hoc,- /// matching v1 where the restriction overwrites `Destination::AiEvents`+ /// matching v1 where the restriction overwrites `Destination::AiMain`/// with `Destination::Custom`.#[tokio::test]async fn test_process_events_restriction_redirect_applies_to_ai_events() {diff --git a/rust/capture/src/overflow_parity.rs b/rust/capture/src/overflow_parity.rsindex 15c9ea4cfe56..ac400a6efd70 100644--- a/rust/capture/src/overflow_parity.rs+++ b/rust/capture/src/overflow_parity.rs@@ -2,10 +2,9 @@//!//! The v0 and v1 pipelines stamp their overflow and rate-limit decisions in//! opposite orders (v0 runs the global rate limiter before the burst limiter,-//! v1 after) and reach the broker through separate sinks. Both must still put-//! the same event on the same lane, with the same partition-key presence and-//! the same person-processing header, because those three things are the wire-//! contract downstream ingestion reads.+//! v1 after). Both must still put the same event on the same lane, with the+//! same partition-key presence and the same person-processing header, because+//! those three things are the wire contract downstream ingestion reads.//!//! Each case runs the real pipeline on both paths and asserts both against an//! explicit expectation, not merely against each other, so two paths that drift@@ -173,7 +172,7 @@ async fn run_v0(limits: Limits, batch_size: usize, observe: usize) -> Observed {}}-/// Drive the real v1 pipeline through its sink router and read the record at+/// Drive the real v1 pipeline through its outputs and read the record at/// `observe` off the mock producer.async fn run_v1(limits: Limits, batch_size: usize, observe: usize) -> Observed {let mut builder = TestStateBuilder::new();@@ -198,23 +197,24 @@ async fn run_v1(limits: Limits, batch_size: usize, observe: usize) -> Observed {.await.expect("v1 pipeline must accept the batch");- let cfg = test_utils::test_kafka_config();- ts.mock_producer.with_records(|records| {- assert_eq!(records.len(), batch_size, "v1 must produce every event");- let record = &records[observe];- Observed {- lane: if record.topic == cfg.topic_main {- Lane::Main- } else if record.topic == cfg.topic_overflow {- Lane::Overflow- } else {- Lane::Other(record.topic.clone())- },- has_key: record.key.is_some(),- person_processing_disabled: record.header("force_disable_person_processing")- == Some("true"),- }- })+ let cfg = test_utils::test_outputs_config();+ let records = ts.mock_producer.get_records();+ assert_eq!(records.len(), batch_size, "v1 must produce every event");+ let record = &records[observe];+ Observed {+ lane: if *record.topic == *cfg.analytics_main_topic {+ Lane::Main+ } else if *record.topic == *cfg.analytics_overflow_topic {+ Lane::Overflow+ } else {+ Lane::Other(record.topic.to_string())+ },+ has_key: record.key.is_some(),+ person_processing_disabled: record+ .headers+ .force_disable_person_processing+ .unwrap_or(false),+ }}/// The matrix. Cases with a burst limiter armed send two events and observediff --git a/rust/capture/src/pipeline.rs b/rust/capture/src/pipeline.rsindex 5cb85d26cc33..d0f4bc93f5eb 100644--- a/rust/capture/src/pipeline.rs+++ b/rust/capture/src/pipeline.rs@@ -204,12 +204,9 @@ pub fn resolve(}// Single-lane pipelines: capture has no overflow topic for warnings,// heatmaps, or error tracking, so `Lane::Overflow` is never resolved- // for them. Error tracking is the only one of the three that can- // actually carry overflow intent — an error-tracking-scoped- // ForceOverflow restriction stamps `force_overflow` on an exception- // event — and the stamp is deliberately ignored here; the event- // publishes to main. Warnings and heatmaps flow through event- // restrictions unrestricted (no restriction pipeline covers them).+ // for them. A ForceOverflow restriction scoped to one of these+ // pipelines stamps `force_overflow` on the event, and the stamp is+ // deliberately ignored here; the event publishes to main.DataType::ClientIngestionWarning => AddressDecision::lane(Pipeline::Warnings,Lane::Main,diff --git a/rust/capture/src/prometheus.rs b/rust/capture/src/prometheus.rsindex 1a043c629d10..8297c3639452 100644--- a/rust/capture/src/prometheus.rs+++ b/rust/capture/src/prometheus.rs@@ -264,13 +264,6 @@ pub fn setup_metrics_recorder(role: String, capture_mode: &'static str) -> Prome2500.0, 5000.0, 10000.0, 30000.0, 60000.0, 120000.0, 300000.0,];- // Same shape as KAFKA_PRODUCE_ACK_MS, but in seconds for the v1 sink's- // `capture_v1_kafka_ack_duration_seconds` histogram.- const KAFKA_PRODUCE_ACK_SECONDS: &[f64] = &[- 0.0005, 0.001, 0.002, 0.005, 0.01, 0.015, 0.025, 0.05, 0.075, 0.1, 0.15, 0.25, 0.5, 1.0,- 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0,- ];-PrometheusBuilder::new().add_global_label("role", role).add_global_label("capture_mode", capture_mode)@@ -349,11 +342,6 @@ pub fn setup_metrics_recorder(role: String, capture_mode: &'static str) -> PromeEXPONENTIAL_SECONDS,).unwrap()- .set_buckets_for_metric(- Matcher::Full("capture_v1_kafka_ack_duration_seconds".to_string()),- KAFKA_PRODUCE_ACK_SECONDS,- )- .unwrap()// capture_v1_event_batch_size is covered by the Suffix("_batch_size")// matcher above; only the payload-size and clock-skew histograms need// explicit entries.diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rsindex 31288c8e5ba2..d589eefb4c9a 100644--- a/rust/capture/src/router.rs+++ b/rust/capture/src/router.rs@@ -90,7 +90,7 @@ pub struct State {/// a pure mechanism layer with cheap Arc-based clones.pub overflow_limiter: Option<Arc<OverflowLimiter>>,/// Dedicated overflow limiter for the AI lane (`DataType::AiEvents` /- /// `Destination::AiEvents`). Same knobs as `overflow_limiter` but a+ /// `Destination::AiMain`). Same knobs as `overflow_limiter` but a/// separate governor instance, so per-key budgets are isolated: analytics/// volume never pushes a key's AI events into AI overflow and AI volume/// never burns the analytics budget. Only built when both@@ -108,9 +108,6 @@ pub struct State {/// the kafka sink can route to the replay overflow topic. Same rationale/// as `overflow_limiter` above.pub replay_overflow_limiter: Option<Arc<RedisLimiter>>,- /// V1 sink router for the new capture analytics pipeline.- /// When present, the v1 analytics handler publishes events through this.- pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,/// Whether the AI overflow valve is armed (`CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC` is/// set). Gates overflow stamping for the AI lane in both pipelines: when/// false, AI events never overflow (pre-overflow behavior).@@ -194,7 +191,6 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +ai_events_overflow_limiter: Option<Arc<OverflowLimiter>>,ai_byte_rate_limiter: Option<Arc<GlobalRateLimiter>>,replay_overflow_limiter: Option<Arc<RedisLimiter>>,- v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,capture_v1_scatter_gather_min_batch: usize,ai_gateway_signing_secret: Option<String>,ai_events_overflow_enabled: bool,@@ -225,7 +221,6 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +ai_events_overflow_limiter,ai_byte_rate_limiter,replay_overflow_limiter,- v1_sink_router,capture_v1_scatter_gather_min_batch,ai_gateway_signing_secret,ai_events_overflow_enabled,@@ -461,12 +456,6 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +// scoped to v0/status routes; v1 ships its own policy.router = router.layer(cors);- // The v1 endpoints are only routable when a v1 sink is configured.- // Without a sink the handler can't publish, so we keep the paths- // unregistered (404) rather than advertising endpoints that can only- // ever return 503. This also isolates the routes to deployments that- // opt in via CAPTURE_V1_SINKS.- //// Merged after every legacy layer above: the v1 router owns its full// middleware stack (CORS, limits) and applies the same per-route// concurrency cap to its own routes.@@ -489,7 +478,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +CaptureMode::Ai => true,CaptureMode::Events | CaptureMode::Import | CaptureMode::Recordings => false,};- if (serves_v1_analytics || serves_v1_ai_events) && state.v1_sink_router.is_some() {+ if serves_v1_analytics || serves_v1_ai_events {router = router.merge(crate::v1::router::router(crate::v1::router::RouterConfig {concurrency_limit,max_compressed_body_bytes: state.capture_v1_max_compressed_body_bytes,diff --git a/rust/capture/src/server.rs b/rust/capture/src/server.rsindex 4c6b2cf0188a..bc4c9536fad8 100644--- a/rust/capture/src/server.rs+++ b/rust/capture/src/server.rs@@ -93,7 +93,6 @@ pub async fn serve(listener: TcpListener, components: CaptureComponents) {app,server_handle,producers,- v1_sink_router,event_restriction_service: _,http1_header_read_timeout_ms,} = components;@@ -229,29 +228,17 @@ pub async fn serve(listener: TcpListener, components: CaptureComponents) {graceful.shutdown().await;info!("Hyper accept loop (shutdown): graceful shutdown completed");- // The v0 producers flush is synchronous (rdkafka), so it runs on the- // blocking thread pool. V1 sinks already use spawn_blocking internally- // (see KafkaSink::flush).+ // The producers flush is synchronous (rdkafka), so it runs on the+ // blocking thread pool.info!("Flushing sinks...");- let legacy_flush = async move {- let Some(producers) = producers else {- return;- };+ if let Some(producers) = producers {let result = tokio::task::spawn_blocking(move || producers.flush()).await;match result {Ok(Err(e)) => error!("Producer flush failed: {e:#}"),Err(e) => error!("Producer flush task panicked: {e}"),Ok(Ok(())) => {}}- };- let v1_flush = async {- if let Some(ref v1_router) = v1_sink_router {- if let Err(e) = v1_router.flush().await {- error!("V1 sink router flush failed: {e:#}");- }- }- };- tokio::join!(legacy_flush, v1_flush);+ }info!("Sink flush complete");// _scope drops here -> ProcessScopeGuard signals WorkCompleteddiff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex 504610712df5..36361c112deb 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -41,7 +41,6 @@ pub struct LifecycleHandles {pub advisory: Option<lifecycle::Handle>,pub event_restrictions: Option<lifecycle::Handle>,pub ingestion_warnings: Option<lifecycle::Handle>,- pub v1_sinks: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle>,pub readiness: lifecycle::ReadinessHandler,pub liveness: lifecycle::LivenessHandler,}@@ -90,27 +89,6 @@ pub fn register_components(manager: &mut lifecycle::Manager, config: &Config) ->None};- let v1_sinks: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle> =- if !config.capture_v1_sinks.is_empty() {- crate::v1::sinks::parse_sink_names(&config.capture_v1_sinks)- .unwrap_or_else(|e| {- panic!(- "fatal: failed to parse CAPTURE_V1_SINKS='{}': {e:#}",- config.capture_v1_sinks- )- })- .into_iter()- .map(|name| {- (- name,- manager.register(name.lifecycle_tag(), sink_opts.clone()),- )- })- .collect()- } else {- HashMap::new()- };-let readiness = manager.readiness_handler();let liveness = manager.liveness_handler();@@ -120,7 +98,6 @@ pub fn register_components(manager: &mut lifecycle::Manager, config: &Config) ->advisory,event_restrictions,ingestion_warnings,- v1_sinks,readiness,liveness,}@@ -131,7 +108,6 @@ pub struct CaptureComponents {pub server_handle: lifecycle::Handle,/// `None` with the print or noop sink, which produce to no Kafka.pub producers: Option<Arc<ProducerRegistry>>,- pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,pub event_restriction_service: Option<EventRestrictionService>,pub http1_header_read_timeout_ms: Option<u64>,}@@ -147,7 +123,6 @@ pub async fn build_components(advisory: advisory_handle,event_restrictions: event_restrictions_handle,ingestion_warnings: ingestion_warnings_handle,- v1_sinks: v1_sink_handles,readiness,liveness,} = handles;@@ -369,15 +344,6 @@ pub async fn build_components()});- let v1_sink_router = if !config.capture_v1_sinks.is_empty() {- Some(- create_v1_sink_router(&config, &env, v1_sink_handles)- .unwrap_or_else(|e| panic!("fatal: v1 sink router creation failed: {e:#}")),- )- } else {- None- };-let ingestion_warning_emitter =create_ingestion_warning_emitter(&config, ingestion_warnings_handle).await;@@ -409,7 +375,6 @@ pub async fn build_components(ai_events_overflow_limiter,ai_byte_rate_limiter,replay_overflow_limiter,- v1_sink_router.clone(),config.capture_v1_scatter_gather_min_batch,config.ai_gateway_signing_secret.clone(),ai_events_overflow_enabled,@@ -425,7 +390,6 @@ pub async fn build_components(app,server_handle: server,producers: producers.map(Arc::new),- v1_sink_router,event_restriction_service,http1_header_read_timeout_ms: config.http1_header_read_timeout_ms,}@@ -485,48 +449,6 @@ fn warn_if_ai_ceiling_exceeds_producer_cap(config: &Config, producer_message_max}}-/// Every v1 sink whose `message_max_bytes` sits at or below the AI ceiling,-/// sorted by sink name so the result is stable to assert on.-fn v1_sinks_below_ai_ceiling(- config: &Config,- sinks_cfg: &crate::v1::sinks::Sinks,-) -> Vec<(crate::v1::sinks::SinkName, u32)> {- let ceiling = config.ai_max_event_bytes;- // `0` disables the ceiling, so there is no ordering to be wrong about.- if ceiling == 0 {- return Vec::new();- }- let mut offenders: Vec<(crate::v1::sinks::SinkName, u32)> = sinks_cfg- .configs- .iter()- .filter(|(_, cfg)| ceiling >= cfg.kafka.message_max_bytes as u64)- .map(|(name, cfg)| (*name, cfg.kafka.message_max_bytes))- .collect();- offenders.sort_by_key(|(name, _)| name.as_str());- offenders-}--/// The v1-sink counterpart to [`warn_if_ai_ceiling_exceeds_producer_cap`].-///-/// That check reads `KAFKA_INGESTION_PRODUCER_MESSAGE_MAX_BYTES`, which governs only the-/// v0 producer. Every v1 sink carries its own `message_max_bytes`-/// (`CAPTURE_V1_SINK_<NAME>_KAFKA_MESSAGE_MAX_BYTES`, default 1MB), so a-/// deployment whose AI traffic runs on a v1 sink can pass the v0 check with a-/// correctly-raised cap on a producer it never uses, and still have every event-/// between the sink cap and the ceiling refused by the broker.-fn warn_if_ai_ceiling_exceeds_v1_sink_caps(config: &Config, sinks_cfg: &crate::v1::sinks::Sinks) {- for (name, message_max_bytes) in v1_sinks_below_ai_ceiling(config, sinks_cfg) {- warn!(- sink = name.as_str(),- ai_max_event_bytes = config.ai_max_event_bytes,- message_max_bytes,- "AI_MAX_EVENT_BYTES is at or above this v1 sink's MESSAGE_MAX_BYTES; \- events between the sink cap and the ceiling are built and then \- refused by the producer"- );- }-}-/// Warns when a token sending full-size AI events would be limited on nearly/// every one of them, because the window budget cannot fit even a single event/// at the deployment's ceiling. Both sides come from config, so the check stays@@ -550,64 +472,6 @@ fn warn_if_ai_byte_budget_below_max_event(config: &Config) {}}-/// Builds the v1 sink router. The dedicated AI topics are-/// deployment-level config (`CAPTURE_OUTPUT_AI_MAIN_TOPIC` and `CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC`),-/// so they are injected into every sink config here; the overwrite is-/// unconditional so a stray per-sink `TOPIC_AI`/`TOPIC_AI_OVERFLOW` env var-/// cannot diverge from the shared policy.-fn create_v1_sink_router(- config: &Config,- sink_env: &HashMap<String, String>,- handles: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle>,-) -> anyhow::Result<Arc<crate::v1::sinks::Router>> {- let mut sinks_cfg = crate::v1::sinks::load_sinks_from(&config.capture_v1_sinks, sink_env)- .context("failed to parse CAPTURE_V1_SINKS")?;- sinks_cfg- .validate()- .context("v1 sink config validation failed")?;-- for cfg in sinks_cfg.configs.values_mut() {- cfg.kafka.topic_ai = config.outputs.ai_main_topic.clone();- cfg.kafka.topic_ai_overflow = config.outputs.ai_overflow_topic.clone();- }-- warn_if_ai_ceiling_exceeds_v1_sink_caps(config, &sinks_cfg);-- let mut sink_map: HashMap<crate::v1::sinks::SinkName, Box<dyn crate::v1::sinks::sink::Sink>> =- HashMap::new();-- for (name, cfg) in sinks_cfg.configs {- let handle = handles- .get(&name)- .cloned()- .with_context(|| format!("missing lifecycle handle for v1 sink '{name}'"))?;-- let producer = crate::v1::sinks::kafka::producer::KafkaProducer::new(- name,- &cfg.kafka,- handle.clone(),- config.capture_mode.as_tag(),- )- .with_context(|| format!("failed to create v1 kafka producer for sink '{name}'"))?;-- let kafka_sink = crate::v1::sinks::kafka::sink::KafkaSink::new(- name,- Arc::new(producer),- cfg,- config.capture_mode,- handle,- );- sink_map.insert(name, Box::new(kafka_sink));- }-- let router = crate::v1::sinks::Router::new(sinks_cfg.default, sink_map);- info!(- sinks = config.capture_v1_sinks.as_str(),- "V1 sink router initialized"- );- Ok(Arc::new(router))-}-async fn create_output_registry(config: &Config,producer_configs: &HashMap<ProducerName, ProducerConfig>,@@ -1149,49 +1013,6 @@ mod tests {}));}- #[test]- fn create_v1_sink_router_fails_on_invalid_config() {- let cfg_env: HashMap<String, String> = [- ("REDIS_URL", "redis://localhost:6379/"),- ("CAPTURE_MODE", "events"),- (- "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",- "events_plugin_ingestion",- ),- ("CAPTURE_V1_SINKS", "msk"),- ]- .into_iter()- .map(|(k, v)| (k.to_string(), v.to_string()))- .collect();- let config: Config =- envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");-- let mut manager = lifecycle::Manager::builder("test")- .with_trap_signals(false)- .with_prestop_check(false)- .build();- let handles: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle> =- crate::v1::sinks::parse_sink_names(&config.capture_v1_sinks)- .unwrap()- .into_iter()- .map(|name| {- (- name,- manager.register(name.lifecycle_tag(), lifecycle::ComponentOptions::new()),- )- })- .collect();-- let err = create_v1_sink_router(&config, &HashMap::new(), handles)- .err()- .expect("should fail with invalid config");- let msg = format!("{err:#}");- assert!(- msg.contains("msk"),- "error should name the failing sink: {msg}"- );- }-#[test]fn warnings_kafka_config_is_isolated_from_main_producer_tuning() {let cfg = build_warnings_kafka_config("broker:9092".to_string(), true, 16, 1_048_576);@@ -1390,62 +1211,6 @@ mod tests {);}- /// The v0 check above reads `KAFKA_INGESTION_PRODUCER_MESSAGE_MAX_BYTES`, which a- /// v1-sink-only deployment never produces through. capture-ai is exactly- /// that shape, so without this the AI ceiling is checked against a producer- /// the deployment does not use while the sink that does the producing keeps- /// its 1MB default.- #[rstest::rstest]- #[case::sink_at_default_is_flagged(8_388_608, 1_000_000, true)]- #[case::sink_raised_above_ceiling_is_clear(8_388_608, 10_485_760, false)]- #[case::equal_still_flags(1_000_000, 1_000_000, true)]- #[case::disabled_ceiling_never_flags(0, 1_000_000, false)]- fn ai_ceiling_is_checked_against_each_v1_sink_cap(- #[case] ceiling: u64,- #[case] sink_cap: u32,- #[case] expected_flagged: bool,- ) {- let cfg_env: HashMap<String, String> = [- ("REDIS_URL", "redis://localhost:6379/"),- ("CAPTURE_MODE", "ai"),- (- "CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC",- "events_plugin_ingestion_ai",- ),- ]- .into_iter()- .map(|(k, v)| (k.to_string(), v.to_string()))- .collect();- let mut config: Config =- envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");- config.ai_max_event_bytes = ceiling;- // Raised well above the ceiling, so a v0-only check would say "clear"- // and any flag below must have come from the v1 sink.- let v0_producer_cap = 20_971_520;-- let mut sink_cfg = crate::v1::sinks::Config {- produce_timeout: std::time::Duration::from_secs(30),- kafka: crate::v1::test_utils::test_kafka_config(),- };- sink_cfg.kafka.message_max_bytes = sink_cap;- let sinks_cfg = crate::v1::sinks::Sinks {- default: crate::v1::sinks::SinkName::Ws,- configs: [(crate::v1::sinks::SinkName::Ws, sink_cfg)]- .into_iter()- .collect(),- };-- assert!(- !ai_ceiling_exceeds_producer_cap(&config, v0_producer_cap),- "v0 producer is raised, so only the v1 sink can be the offender"- );- let offenders = v1_sinks_below_ai_ceiling(&config, &sinks_cfg);- assert_eq!(offenders.is_empty(), !expected_flagged);- if expected_flagged {- assert_eq!(offenders[0].1, sink_cap);- }- }-/// Import deployments never build the AI byte limiter, however the knob is/// set — that omission is the entire import exemption, so a rate leaking/// through here would start throttling backfills.diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rsindex 83ed3e8c05b6..a1093ea999a3 100644--- a/rust/capture/src/sinks/kafka.rs+++ b/rust/capture/src/sinks/kafka.rs@@ -2301,7 +2301,7 @@ mod tests {#[tokio::test]async fn ai_events_redirect_to_topic_wins() {// A restriction-driven redirect beats the AI lane, matching v1- // where Destination::Custom overwrites Destination::AiEvents.+ // where Destination::Custom overwrites Destination::AiMain.assert_routing(EventInput {data_type: DataType::AiEvents,diff --git a/rust/capture/src/sinks/producer.rs b/rust/capture/src/sinks/producer.rsindex 46c7bca1f519..dcf259d7530f 100644--- a/rust/capture/src/sinks/producer.rs+++ b/rust/capture/src/sinks/producer.rs@@ -1,4 +1,5 @@use common_types::CapturedEventHeaders;+use futures::channel::oneshot::Canceled;use metrics::{counter, histogram};use rdkafka::error::{KafkaError, RDKafkaErrorCode};use rdkafka::producer::{DeliveryFuture, FutureProducer, FutureRecord, Producer};@@ -60,35 +61,9 @@ impl Future for DeliveryAckFuture {// Mark before recording so a panic inside the match still disables Drop.self.recorded = true;let elapsed_ms = self.started.elapsed().as_secs_f64() * 1000.0;- let (outcome, mapped) = match result {- Err(_) => {- // Cancelled due to timeout while retrying- metrics::counter!("capture_kafka_produce_errors_total").increment(1);- error!("failed to produce to Kafka before write timeout");- ("cancelled", Err(CaptureError::RetryableSinkError))- }- Ok(Err((- KafkaError::MessageProduction(RDKafkaErrorCode::MessageSizeTooLarge),- _,- ))) => {- report_dropped_events("kafka_message_size", 1);- (- "too_large",- Err(CaptureError::EventTooBig(- "Event rejected by kafka broker during ack".to_string(),- )),- )- }- Ok(Err((err, _))) => {- metrics::counter!("capture_kafka_produce_errors_total").increment(1);- error!("failed to produce to Kafka: {err:#}");- ("broker_err", Err(CaptureError::RetryableSinkError))- }- Ok(Ok(_)) => {- metrics::counter!("capture_events_ingested_total").increment(1);- ("ok", Ok(()))- }- };+ let (outcome, mapped) = ack_outcome(+ result.map(|delivery| delivery.map(|_| ()).map_err(|(err, _)| err)),+ );histogram!("capture_kafka_produce_ack_duration_ms","outcome" => outcome,@@ -101,6 +76,53 @@ impl Future for DeliveryAckFuture {}}+fn ack_outcome(+ result: Result<Result<(), KafkaError>, Canceled>,+) -> (&'static str, Result<(), CaptureError>) {+ match result {+ Err(Canceled) => {+ // The producer was dropped before the delivery report arrived, so+ // the record may or may not have been written.+ metrics::counter!("capture_kafka_produce_errors_total").increment(1);+ error!("Kafka producer dropped before the delivery report arrived");+ ("cancelled", Err(CaptureError::RetryableSinkError))+ }+ Ok(Err(KafkaError::MessageProduction(RDKafkaErrorCode::MessageSizeTooLarge))) => {+ report_dropped_events("kafka_message_size", 1);+ (+ "too_large",+ Err(CaptureError::EventTooBig(+ "Event rejected by kafka broker during ack".to_string(),+ )),+ )+ }+ Ok(Err(err)) => {+ metrics::counter!("capture_kafka_produce_errors_total").increment(1);+ error!("failed to produce to Kafka: {err:#}");+ ("broker_err", Err(CaptureError::RetryableSinkError))+ }+ Ok(Ok(())) => {+ metrics::counter!("capture_events_ingested_total").increment(1);+ ("ok", Ok(()))+ }+ }+}++fn send_error(err: &KafkaError) -> CaptureError {+ match err.rdkafka_error_code() {+ Some(RDKafkaErrorCode::MessageSizeTooLarge) => {+ report_dropped_events("kafka_message_size", 1);+ CaptureError::EventTooBig("Event rejected by kafka during send".to_string())+ }+ _ => {+ // Use error counter, not dropped counter - this is retryable+ counter!("capture_kafka_produce_errors_total").increment(1);+ error!("failed to produce event: {err:#}");+ CaptureError::RetryableSinkError+ }+ }+}+impl Drop for DeliveryAckFuture {fn drop(&mut self) {// Only fires when the future is dropped before poll saw Ready@@ -150,20 +172,7 @@ impl<C: rdkafka::ClientContext + Send + Sync + 'static> KafkaProducer for RdKafktopic,recorded: false,}),- Err((e, _)) => match e.rdkafka_error_code() {- Some(RDKafkaErrorCode::MessageSizeTooLarge) => {- report_dropped_events("kafka_message_size", 1);- Err(CaptureError::EventTooBig(- "Event rejected by kafka during send".to_string(),- ))- }- _ => {- // Use error counter, not dropped counter - this is retryable- counter!("capture_kafka_produce_errors_total").increment(1);- error!("failed to produce event: {e:#}");- Err(CaptureError::RetryableSinkError)- }- },+ Err((e, _)) => Err(send_error(&e)),}}@@ -244,3 +253,31 @@ impl KafkaProducer for MockKafkaProducer {Ok(())}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn cancelled_ack_is_retriable() {+ let (outcome, mapped) = ack_outcome(Err(Canceled));++ assert_eq!(outcome, "cancelled");+ assert!(+ matches!(mapped, Err(CaptureError::RetryableSinkError)),+ "{mapped:?}"+ );+ }++ #[test]+ fn queue_full_send_is_retriable() {+ let err = KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull);++ let mapped = send_error(&err);++ assert!(+ matches!(mapped, CaptureError::RetryableSinkError),+ "{mapped:?}"+ );+ }+}diff --git a/rust/capture/src/sinks/registry.rs b/rust/capture/src/sinks/registry.rsindex 3731657a099a..f2fa301757a3 100644--- a/rust/capture/src/sinks/registry.rs+++ b/rust/capture/src/sinks/registry.rs@@ -196,7 +196,7 @@ impl<R> OutputTable<R> {}}- pub(crate) fn map_producers<T>(&self, mut f: impl FnMut(&R) -> T) -> OutputTable<T> {+ pub fn map_producers<T>(&self, mut f: impl FnMut(&R) -> T) -> OutputTable<T> {let custom_producer = f(&self.custom_producer);let mut target = |t: &OutputTarget<R>| OutputTarget {topic: Arc::clone(&t.topic),diff --git a/rust/capture/src/v0_request.rs b/rust/capture/src/v0_request.rsindex c39ea48c5552..2799371a813b 100644--- a/rust/capture/src/v0_request.rs+++ b/rust/capture/src/v0_request.rs@@ -181,7 +181,7 @@ pub enum DataType {HeatmapMain,ExceptionErrorTracking,SnapshotMain,- /// Dedicated AI lane, mirroring v1's `Destination::AiEvents`. The+ /// Dedicated AI lane, mirroring v1's `Destination::AiMain`. The/// kafka sink maps it to `CAPTURE_OUTPUT_AI_MAIN_TOPIC`, so every/// deployment that accepts AI traffic must configure that topic. Like/// heatmaps and exceptions, AI events never reroute historical.@@ -237,10 +237,8 @@ impl DataType {}}- /// Pipeline this event flows to, if any. Heatmaps, ingestion warnings,- /// and snapshots have their own dedicated topics and consumers; they- /// don't share Redis-backed restriction config with any other pipeline,- /// so they're not subject to `EventRestrictionService` lookups.+ /// Restriction pipeline this event is looked up under, if any. Snapshots+ /// have none here: the recordings endpoint looks them up itself.////// `AiEvents` maps to the `ai` restriction pipeline: an event on the AI/// lane is governed by ai-scoped restrictions, the same slice the@@ -251,7 +249,9 @@ impl DataType {Self::AnalyticsMain | Self::AnalyticsHistorical => Some(Pipeline::Analytics),Self::AiEvents => Some(Pipeline::Ai),Self::ExceptionErrorTracking => Some(Pipeline::ErrorTracking),- Self::ClientIngestionWarning | Self::HeatmapMain | Self::SnapshotMain => None,+ Self::HeatmapMain => Some(Pipeline::Heatmaps),+ Self::ClientIngestionWarning => Some(Pipeline::ClientWarnings),+ Self::SnapshotMain => None,}}}diff --git a/rust/capture/src/v1/analytics/constants.rs b/rust/capture/src/v1/analytics/constants.rsindex 7c66f3ee617c..e0523558abdc 100644--- a/rust/capture/src/v1/analytics/constants.rs+++ b/rust/capture/src/v1/analytics/constants.rs@@ -150,6 +150,6 @@ pub(super) const CAPTURE_V1_EVENTS_RESTRICTED: &str = "capture_v1_events_restric/// Counter for per-request batch outcome mix (labels: outcome, path).pub(super) const CAPTURE_V1_BATCH_OUTCOMES: &str = "capture_v1_batch_outcomes";-/// Histogram for end-to-end processing time (parsing through sink publish).+/// Histogram for end-to-end processing time (parsing through publish).pub(super) const CAPTURE_V1_PROCESSING_DURATION_SECONDS: &str ="capture_v1_processing_duration_seconds";diff --git a/rust/capture/src/v1/analytics/context.rs b/rust/capture/src/v1/analytics/context.rsindex 1f0e801cd6f3..2618237f3a71 100644--- a/rust/capture/src/v1/analytics/context.rs+++ b/rust/capture/src/v1/analytics/context.rs@@ -10,7 +10,7 @@ use crate::v1::Error;/// Analytics-mode request context: the shared [`RequestContext`] plus the/// typed analytics [`Query`] refined from `req.raw_query`. Derefs to-/// `RequestContext` so shared contracts (`Event`, `Sink`, logging) consume it+/// `RequestContext` so shared contracts (`Publishable`, logging) consume it/// transparently.pub struct Context {pub req: RequestContext,diff --git a/rust/capture/src/v1/analytics/handler.rs b/rust/capture/src/v1/analytics/handler.rsindex d5a83ccf1b72..194736b89327 100644--- a/rust/capture/src/v1/analytics/handler.rs+++ b/rust/capture/src/v1/analytics/handler.rs@@ -443,21 +443,6 @@ mod tests {assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);}- #[tokio::test]- async fn service_unavailable_no_sink() {- let mut ts = TestStateBuilder::new().build();- ts.state.v1_sink_router = None;- let app = test_app(ts.state);-- let payload = batch_payload(&[valid_event()]);- let resp = app- .oneshot(valid_request().body(Body::from(payload)).unwrap())- .await- .unwrap();-- assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);- }-/// Every registered route must map to its own `&'static` label. The/// fallback is silent apart from a log line, so a route registered without/// being added to `CAPTURE_V1_PATHS` would quietly report AI traffic underdiff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex 1f898bec62cb..4131341a4d1b 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -26,13 +26,14 @@ use limiters::overflow::{OverflowLimiter, OverflowLimiterResult};use tracing::Level;use super::context::Context;+use crate::api::CaptureError;use crate::config::CaptureMode;use crate::ingestion_warnings::{bounded_detail, emit_rate_limit_warning};use crate::router;+use crate::sinks::sink::{Outcome, SinkResult};use crate::v1::context::RequestContext;-use crate::v1::sinks::event::Event as SinkEvent;-use crate::v1::sinks::types::SinkResult;-use crate::v1::sinks::{serialize_batch, Destination};+use crate::v1::prepare::{serialize_batch, SerializationFailure};+use crate::v1::types::{Destination, Publishable};use crate::v1::Error;use common_ingestion_warnings::{emit_request_warning, WarningEmitter, WarningType, CAPTURE_V1_ANALYTICS, CAPTURE_V1_RATE_LIMIT,@@ -46,14 +47,14 @@ use common_ingestion_warnings::{/// (extractHeatmapDataStep) handles extraction when `skip_heatmap_processing` is unset/// in Kafka headers — removing that fallback would break scroll-depth heatmaps for v1.///-/// AI events (per [`is_ai_event`]) are diverted to `Destination::AiEvents` on+/// AI events (per [`is_ai_event`]) are diverted to `Destination::AiMain` on/// every deployment.fn destination_for_event_name(name: &str) -> Destination {match name {- "$exception" => Destination::ExceptionErrorTracking,- "$$heatmap" => Destination::HeatmapMain,- "$$client_ingestion_warning" => Destination::ClientIngestionWarning,- _ if is_ai_event(name) => Destination::AiEvents,+ "$exception" => Destination::ErrorTrackingMain,+ "$$heatmap" => Destination::HeatmapsMain,+ "$$client_ingestion_warning" => Destination::ClientWarningsMain,+ _ if is_ai_event(name) => Destination::AiMain,_ => Destination::AnalyticsMain,}}@@ -105,7 +106,6 @@ async fn run_pipeline(if state.capture_mode.requires_historical_migration() && !context.historical_migration {for ev in events.iter_mut() {ev.result = EventResult::Drop;- ev.destination = Destination::Drop;ev.details = Some(DETAIL_NON_HISTORICAL_DROP);}metrics::counter!(CAPTURE_V1_EVENTS_DROPPED, "reason" => "non_historical_import")@@ -177,7 +177,7 @@ async fn run_pipeline(// 1. Ordering: v1 runs this GRL step AFTER burst overflow stamping (above);// legacy runs its GRL BEFORE overflow stamping. The pass order differs,// but the observable outcome does not: both reroute only- // AnalyticsMain/Destination::Overflow, and both drop the partition key+ // AnalyticsMain/Destination::AnalyticsOverflow, and both drop the partition key// once person processing is off, so a key the GRL wanted spread stays// spread on either path even when the burst limiter preserves locality.// `crate::overflow_parity` pins that across the whole matrix.@@ -206,28 +206,11 @@ async fn run_pipeline().record(processing_start.elapsed().as_secs_f64());- // Serialize (hoisted out of the sink; parallel for large batches), then- // publish and merge results before building the response.- let sink_router = state- .v1_sink_router- .as_ref()- .ok_or_else(|| Error::ServiceUnavailable("v1 sink router not configured".into()))?;-- // serialize_batch consumes the events and hands them back, so we can keep- // correlating results to them and build the response.let (mut events, serialized) =serialize_batch(events, context, state.capture_v1_scatter_gather_min_batch).await;- let sink_results = sink_router- .publish_batch(sink_router.default_sink(), context, &serialized.prepared)- .await- .map_err(|e| Error::InternalError(e.to_string()))?;-- // Serialize-step failures and sink results are both per-event SinkResults;- // merge them together so serialization drops surface in the response.- let mut all_results = serialized.failures;- all_results.extend(sink_results);- merge_sink_results(&mut events, &all_results);+ let publish_results = state.outputs.publish_prepared(serialized.prepared).await;+ merge_publish_results(&mut events, &serialized.failures, &publish_results);Ok(events)}@@ -302,7 +285,6 @@ fn apply_gateway_provenance(state: &router::State, context: &Context, events: &m/// so a forged marker we can't remove would otherwise survive to billing — fail closed.fn drop_unparseable_gateway_props(ev: &mut WrappedEvent) {ev.result = EventResult::Drop;- ev.destination = Destination::Drop;ev.details = Some("gateway_props_unparseable");metrics::counter!(crate::v1::gateway_provenance::PROVENANCE_METRIC,@@ -311,47 +293,47 @@ fn drop_unparseable_gateway_props(ev: &mut WrappedEvent) {.increment(1);}-// ----------------------------------------------------------------------------// SinkResult → WrappedEvent merge-// -----------------------------------------------------------------------------/// Correlate per-event `SinkResult`s back to the batch of `WrappedEvent`s by UUID.-///-/// Events that were not published (`should_publish() == false`) are untouched.-/// Published events receive updated `result` and `details` based on the sink outcome:-/// - `Outcome::Success` → keep existing result (Ok or Warning)-/// - `Outcome::RetriableError` | `Outcome::Timeout` → `EventResult::Retry`-/// - `Outcome::FatalError` → `EventResult::Drop`-pub fn merge_sink_results(events: &mut [WrappedEvent], sink_results: &[Box<dyn SinkResult>]) {- use crate::v1::sinks::types::Outcome;-- let results_by_uuid: HashMap<Uuid, &dyn SinkResult> =- sink_results.iter().map(|r| (r.key(), r.as_ref())).collect();-- for event in events.iter_mut() {- if !event.should_publish() {- continue;+/// Sets `result` and `details` on each published event from its serialize failure or publish result.+pub fn merge_publish_results(+ events: &mut [WrappedEvent],+ failures: &[SerializationFailure],+ publish_results: &[SinkResult],+) {+ // Uuids are unique here: validation rejects a batch with a duplicate.+ let mut published: HashMap<Uuid, &mut WrappedEvent> = events+ .iter_mut()+ .filter(|e| e.should_publish())+ .map(|e| (e.uuid, e))+ .collect();++ for failure in failures {+ if let Some(event) = published.get_mut(&failure.uuid()) {+ event.result = EventResult::Drop;+ event.details = Some(if failure.is_panic() {+ "rejected"+ } else {+ "serialization_failed"+ });}+ }- let Some(result) = results_by_uuid.get(&event.uuid) else {+ for result in publish_results {+ let Some(event) = published.get_mut(&result.uuid) else {continue;};-- match result.outcome() {- Outcome::Success => {- // Leave event.result as-is (Ok or Warning from upstream processing)- }- Outcome::RetriableError | Outcome::Timeout => {+ match &result.outcome {+ Outcome::Published => {}+ Outcome::Failed(CaptureError::RetryableSinkError) => {event.result = EventResult::Retry;event.details = Some("not_persisted");}- Outcome::FatalError => {+ Outcome::Failed(CaptureError::EventTooBig(_)) => {event.result = EventResult::Drop;- let cause = result.cause().unwrap_or("rejected");- event.details = Some(match cause {- "serialization_failed" | "event_too_big" => cause,- _ => "rejected",- });+ event.details = Some("event_too_big");+ }+ Outcome::Failed(_) => {+ event.result = EventResult::Drop;+ event.details = Some("rejected");}}}@@ -807,8 +789,8 @@ fn apply_overflow_stamping(// (CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC) is armed, so limiter// presence encodes the valve here.let (overflow_destination, lane_limiter) = match event.destination {- Destination::AnalyticsMain => (Destination::Overflow, analytics_limiter),- Destination::AiEvents => (Destination::AiEventsOverflow, ai_limiter),+ Destination::AnalyticsMain => (Destination::AnalyticsOverflow, analytics_limiter),+ Destination::AiMain => (Destination::AiOverflow, ai_limiter),_ => continue,};if event.result == EventResult::Drop {@@ -865,9 +847,8 @@ async fn apply_restrictions(// Derive the pipeline from the destination so each event is matched// against the correct restriction slice (Analytics vs ErrorTracking// vs Ai) — an event diverted to the AI lane is governed by ai-scoped- // restrictions, not analytics ones. `pipeline() == None` for heatmaps- // / ingestion warnings → they pass through unrestricted, exactly as- // v0 does (v0 derives the same mapping from `DataType::pipeline`).+ // restrictions, not analytics ones. v0 derives the same mapping from+ // `DataType::pipeline`.let Some(pipeline) = event.destination.pipeline() else {continue;};@@ -885,7 +866,6 @@ async fn apply_restrictions(if applied.should_drop() {event.result = EventResult::Drop;event.details = Some(DETAIL_EVENT_RESTRICTION_DROP);- event.destination = Destination::Drop;metrics::counter!(CAPTURE_V1_EVENTS_DROPPED, "reason" => "event_restriction").increment(1);continue;@@ -893,16 +873,14 @@ async fn apply_restrictions(// Priority: overflow < custom topic < DLQ (DLQ wins, applied last)// Overflow only applies to the overflowing lanes: AnalyticsMain, and- // AiEvents once the AI overflow valve is armed (each rerouting to its+ // AiMain once the AI overflow valve is armed (each rerouting to its// own overflow destination). AnalyticsHistorical must never overflow- // (legacy sink invariant). Today this stage runs before historical+ // (v0's `pipeline::resolve` rule). Today this stage runs before historical// rerouting so an analytics event is always AnalyticsMain here; the// explicit guard makes the invariant ordering-independent.let force_overflow_destination = match event.destination {- Destination::AnalyticsMain => Some(Destination::Overflow),- Destination::AiEvents if ai_events_overflow_enabled => {- Some(Destination::AiEventsOverflow)- }+ Destination::AnalyticsMain => Some(Destination::AnalyticsOverflow),+ Destination::AiMain if ai_events_overflow_enabled => Some(Destination::AiOverflow),_ => None,};if applied.force_overflow() {@@ -959,7 +937,6 @@ fn drop_non_ai_events(state: &router::State, context: &Context, events: &mut [Wrcontinue;}event.result = EventResult::Drop;- event.destination = Destination::Drop;event.details = Some(DETAIL_MISROUTED_EVENT);dropped += 1;single_offender = match dropped {@@ -1007,10 +984,10 @@ fn drop_non_ai_events(state: &router::State, context: &Context, events: &mut [Wr/// Whether this event rides the AI lane, independent of where restrictions/// have since pointed it.///-/// Gating on `destination == AiEvents` would exempt exactly the events an+/// Gating on `destination == AiMain` would exempt exactly the events an/// operator redirected: `force_overflow` retargets an AI event to-/// `AiEventsOverflow`, which is still the AI lane, and a `redirect_to_topic`-/// or DLQ restriction moves it off `AiEvents` without taking it off the wire.+/// `AiOverflow`, which is still the AI lane, and a `redirect_to_topic`+/// or DLQ restriction moves it off `AiMain` without taking it off the wire./// [`is_ai_event`] is the same rule v0 stamps `DataType::AiEvents` from, so both/// pipelines charge and measure the same set.fn on_ai_lane(event: &WrappedEvent) -> bool {@@ -1026,7 +1003,7 @@ fn on_ai_lane(event: &WrappedEvent) -> bool {/// request instead, matching the oversize checks already on it.////// Charged bytes are the event's properties, which dominate an AI event's wire-/// size; the serialized envelope is not built until the sink.+/// size; the serialized envelope is not built until the prepare step.fn apply_ai_event_size_limit(max_event_bytes: u64, events: &mut [WrappedEvent]) {if max_event_bytes == 0 {return;@@ -1041,7 +1018,6 @@ fn apply_ai_event_size_limit(max_event_bytes: u64, events: &mut [WrappedEvent])if exceeds_max_ai_event_bytes(event.event.properties.get().len(), max_event_bytes) {event.result = EventResult::Drop;event.details = Some(DETAIL_AI_EVENT_TOO_BIG);- event.destination = Destination::Drop;dropped += 1;}}@@ -1080,7 +1056,6 @@ async fn apply_ai_byte_limits(if charge_ai_bytes(limiter, token, event.event.properties.get().len()).await {event.result = EventResult::Drop;event.details = Some(DETAIL_AI_BYTE_RATE_LIMITED);- event.destination = Destination::Drop;dropped += 1;}}@@ -1149,10 +1124,10 @@ async fn apply_token_distinct_id_limits(// Reroute to overflow to spread a hot token:distinct_id across// partitions. Gated to AnalyticsMain only: this stage runs after// historical rerouting, and AnalyticsHistorical must never overflow- // (matches the legacy sink invariant). Other lanes (exceptions,+ // (matches v0's `pipeline::resolve`). Other lanes (exceptions,// heatmaps, etc.) keep their own destination.if event.destination == Destination::AnalyticsMain {- event.destination = Destination::Overflow;+ event.destination = Destination::AnalyticsOverflow;}limited_distinct_ids.insert(event.event.distinct_id.as_str());limited_event_count += 1;@@ -1245,11 +1220,12 @@ mod tests {};use crate::v1::analytics::constants::{CAPTURE_V1_PATH, DETAIL_INVALID_OPTIONS};use crate::v1::analytics::types::{Batch, Event};- use crate::v1::sinks::{Destination, DEFAULT_SCATTER_GATHER_MIN_BATCH};+ use crate::v1::prepare::DEFAULT_SCATTER_GATHER_MIN_BATCH;use crate::v1::test_utils::{self, find_by_did, malformed_wrapped_event, raw_obj, valid_event, wrapped_event,wrapped_event_at,};+ use crate::v1::types::Destination;use crate::v1::Error;fn valid_batch(events: Vec<Event>) -> Batch {@@ -1598,7 +1574,6 @@ mod tests {Some(DETAIL_PERSON_PROCESSING_DISABLED),"id={id:?}");- assert_ne!(flagged.destination, Destination::Drop, "id={id:?}");let normal = &events[1];assert_eq!(normal.result, EventResult::Ok, "id={id:?}");@@ -2113,7 +2088,6 @@ mod tests {for ev in &events {assert_eq!(ev.result, EventResult::Drop);- assert_eq!(ev.destination, Destination::Drop);}}@@ -2143,7 +2117,6 @@ mod tests {// valid event gets dropped by restrictionlet valid = find_by_did(&events, "user-valid");assert_eq!(valid.result, EventResult::Drop);- assert_eq!(valid.destination, Destination::Drop);}#[tokio::test]@@ -2165,7 +2138,7 @@ mod tests {let ev = find_by_did(&events, "user-1");assert_eq!(ev.result, EventResult::Ok);- assert_eq!(ev.destination, Destination::Overflow);+ assert_eq!(ev.destination, Destination::AnalyticsOverflow);}/// A diverted AI event consults ai-scoped restrictions: an ai-scoped@@ -2173,9 +2146,9 @@ mod tests {/// valve is armed and leaves it untouched when not, while an/// analytics-scoped ForceOverflow never crosses into the AI lane.#[rstest::rstest]- #[case::armed(Pipeline::Ai, true, Destination::AiEventsOverflow)]- #[case::unarmed(Pipeline::Ai, false, Destination::AiEvents)]- #[case::analytics_scoped_does_not_cross(Pipeline::Analytics, true, Destination::AiEvents)]+ #[case::armed(Pipeline::Ai, true, Destination::AiOverflow)]+ #[case::unarmed(Pipeline::Ai, false, Destination::AiMain)]+ #[case::analytics_scoped_does_not_cross(Pipeline::Analytics, true, Destination::AiMain)]#[tokio::test]async fn restrictions_force_overflow_ai_events_gated_on_valve(#[case] restriction_pipeline: Pipeline,@@ -2194,7 +2167,7 @@ mod tests {.await;let mut events = vec![wrapped_event("$ai_generation", "user-1")];- events[0].destination = Destination::AiEvents;+ events[0].destination = Destination::AiMain;let now_ts = Utc::now().timestamp();apply_restrictions(@@ -2218,12 +2191,12 @@ mod tests {#[tokio::test]async fn oversize_ai_events_drop_individually() {let mut oversized = wrapped_event("$ai_generation", "user-big");- oversized.destination = Destination::AiEvents;+ oversized.destination = Destination::AiMain;oversized.event.properties =test_utils::raw_obj(&format!(r#"{{"$ai_input":"{}"}}"#, "x".repeat(800)));let mut small = wrapped_event("$ai_generation", "user-1");- small.destination = Destination::AiEvents;+ small.destination = Destination::AiMain;let mut events = vec![oversized, small];@@ -2231,7 +2204,6 @@ mod tests {let big = find_by_did(&events, "user-big");assert_eq!(big.result, EventResult::Drop);- assert_eq!(big.destination, Destination::Drop);assert_eq!(big.details, Some(DETAIL_AI_EVENT_TOO_BIG));let kept = find_by_did(&events, "user-1");@@ -2247,7 +2219,7 @@ mod tests {#[tokio::test]async fn a_zero_ai_size_ceiling_disables_the_check() {let mut oversized = wrapped_event("$ai_generation", "user-big");- oversized.destination = Destination::AiEvents;+ oversized.destination = Destination::AiMain;oversized.event.properties =test_utils::raw_obj(&format!(r#"{{"$ai_input":"{}"}}"#, "x".repeat(800)));@@ -2255,7 +2227,7 @@ mod tests {apply_ai_event_size_limit(0, &mut events);assert_eq!(events[0].result, EventResult::Ok);- assert_eq!(events[0].destination, Destination::AiEvents);+ assert_eq!(events[0].destination, Destination::AiMain);}/// The size ceiling follows the same lane rule as the budget: an oversize@@ -2266,23 +2238,22 @@ mod tests {let mut oversized = wrapped_event("$ai_generation", "user-1");oversized.event.properties =test_utils::raw_obj(&format!(r#"{{"$ai_input":"{}"}}"#, "x".repeat(800)));- oversized.destination = Destination::AiEventsOverflow;+ oversized.destination = Destination::AiOverflow;let mut events = vec![oversized];apply_ai_event_size_limit(700, &mut events);assert_eq!(events[0].result, EventResult::Drop);- assert_eq!(events[0].destination, Destination::Drop);}/// Lane membership decides the charge, and a restriction that retargets an/// AI event does not buy the project a free lane. `force_overflow` keeps/// the event on the AI lane outright; a topic or DLQ redirect moves it off- /// `AiEvents` but not off the wire. Gating on the destination instead would+ /// `AiMain` but not off the wire. Gating on the destination instead would/// exempt every one of these, which is the whole point of the case list.#[rstest::rstest]- #[case::ai_lane(Destination::AiEvents)]- #[case::force_overflow_stays_on_the_lane(Destination::AiEventsOverflow)]+ #[case::ai_lane(Destination::AiMain)]+ #[case::force_overflow_stays_on_the_lane(Destination::AiOverflow)]#[case::topic_redirect_still_pays(Destination::Custom("ai_quarantine".to_string()))]#[case::dlq_redirect_still_pays(Destination::Dlq)]#[tokio::test]@@ -2304,7 +2275,6 @@ mod tests {assert_eq!(events[0].result, EventResult::Ok);assert_eq!(events[0].destination, destination);assert_eq!(events[1].result, EventResult::Drop);- assert_eq!(events[1].destination, Destination::Drop);}/// The mirror of the case above: an event that was never on the AI lane is@@ -2335,12 +2305,12 @@ mod tests {let limiter = GlobalRateLimiter::mock_budget(800);let mut already_dropped = wrapped_event("$ai_generation", "user-invalid");- already_dropped.destination = Destination::AiEvents;+ already_dropped.destination = Destination::AiMain;already_dropped.result = EventResult::Drop;already_dropped.details = Some(DETAIL_INVALID_OPTIONS);let mut publishable = wrapped_event("$ai_generation", "user-1");- publishable.destination = Destination::AiEvents;+ publishable.destination = Destination::AiMain;let mut events = vec![already_dropped, publishable];@@ -2352,7 +2322,7 @@ mod tests {EventResult::Ok,"a dropped event's bytes must not shed a publishable one");- assert_eq!(ev.destination, Destination::AiEvents);+ assert_eq!(ev.destination, Destination::AiMain);}#[tokio::test]@@ -2484,20 +2454,20 @@ mod tests {// --- destination_for_event_name ---#[rstest::rstest]- #[case("$exception", Destination::ExceptionErrorTracking)]- #[case("$$heatmap", Destination::HeatmapMain)]- #[case("$$client_ingestion_warning", Destination::ClientIngestionWarning)]+ #[case("$exception", Destination::ErrorTrackingMain)]+ #[case("$$heatmap", Destination::HeatmapsMain)]+ #[case("$$client_ingestion_warning", Destination::ClientWarningsMain)]#[case("$pageview", Destination::AnalyticsMain)]#[case("custom_event", Destination::AnalyticsMain)]#[case("$autocapture", Destination::AnalyticsMain)]// Every `$ai_` name diverts on every deployment.- #[case("$ai_generation", Destination::AiEvents)]- #[case("$ai_span", Destination::AiEvents)]- #[case("$ai_trace", Destination::AiEvents)]- #[case("$ai_generation_summary", Destination::AiEvents)]- #[case("$ai_call", Destination::AiEvents)]- #[case("$ai_generation_enriched", Destination::AiEvents)]- #[case("$ai_model_failover", Destination::AiEvents)]+ #[case("$ai_generation", Destination::AiMain)]+ #[case("$ai_span", Destination::AiMain)]+ #[case("$ai_trace", Destination::AiMain)]+ #[case("$ai_generation_summary", Destination::AiMain)]+ #[case("$ai_call", Destination::AiMain)]+ #[case("$ai_generation_enriched", Destination::AiMain)]+ #[case("$ai_model_failover", Destination::AiMain)]// Prefix means `$ai_`, not `$ai`: a name without the underscore never diverts.#[case("$ai", Destination::AnalyticsMain)]#[case("$aigeneration", Destination::AnalyticsMain)]@@ -2510,16 +2480,11 @@ mod tests {);}- // --- restrictions bypass pipeline-less events ---- // Events whose name maps to DataType::pipeline() == None (heatmaps,- // ingestion warnings) pass through unrestricted regardless of what- // restrictions are configured.-#[rstest::rstest]- #[case("$$heatmap", Destination::HeatmapMain)]- #[case("$$client_ingestion_warning", Destination::ClientIngestionWarning)]+ #[case("$$heatmap", Destination::HeatmapsMain)]+ #[case("$$client_ingestion_warning", Destination::ClientWarningsMain)]#[tokio::test]- async fn restrictions_skip_pipeline_less_events(+ async fn analytics_restrictions_skip_heatmaps_and_warnings(#[case] event_name: &str,#[case] expected_dest: Destination,) {@@ -2562,18 +2527,17 @@ mod tests {wrapped_event("$pageview", "user-1"),wrapped_event("$exception", "user-2"),];- events[1].destination = Destination::ExceptionErrorTracking;+ events[1].destination = Destination::ErrorTrackingMain;let now_ts = Utc::now().timestamp();apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;// Analytics event gets dropped by analytics-pipeline restrictionassert_eq!(events[0].result, EventResult::Drop);- assert_eq!(events[0].destination, Destination::Drop);// Exception event is untouched — it's on the ErrorTracking pipeline,// which has no restrictions configured here.assert_eq!(events[1].result, EventResult::Ok);- assert_eq!(events[1].destination, Destination::ExceptionErrorTracking);+ assert_eq!(events[1].destination, Destination::ErrorTrackingMain);}// --- errortracking pipeline restrictions ---@@ -2597,7 +2561,7 @@ mod tests {wrapped_event("$exception", "user-1"),wrapped_event("$pageview", "user-2"),];- events[0].destination = Destination::ExceptionErrorTracking;+ events[0].destination = Destination::ErrorTrackingMain;let now_ts = Utc::now().timestamp();apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;@@ -2607,7 +2571,6 @@ mod tests {EventResult::Drop,"exception should be dropped");- assert_eq!(events[0].destination, Destination::Drop);assert_eq!(events[1].result, EventResult::Ok, "pageview should be kept");assert_eq!(events[1].destination, Destination::AnalyticsMain);}@@ -2626,7 +2589,7 @@ mod tests {.await;let mut events = vec![wrapped_event("$exception", "user-1")];- events[0].destination = Destination::ExceptionErrorTracking;+ events[0].destination = Destination::ErrorTrackingMain;let now_ts = Utc::now().timestamp();apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;@@ -2634,7 +2597,7 @@ mod tests {assert_eq!(events[0].result, EventResult::Ok);assert_eq!(events[0].destination,- Destination::ExceptionErrorTracking,+ Destination::ErrorTrackingMain,"ForceOverflow is gated to AnalyticsMain; exception stays on its own lane");}@@ -2653,13 +2616,13 @@ mod tests {.await;let mut events = vec![wrapped_event("$exception", "user-1")];- events[0].destination = Destination::ExceptionErrorTracking;+ events[0].destination = Destination::ErrorTrackingMain;let now_ts = Utc::now().timestamp();apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;assert_eq!(events[0].result, EventResult::Ok);- assert_eq!(events[0].destination, Destination::ExceptionErrorTracking);+ assert_eq!(events[0].destination, Destination::ErrorTrackingMain);assert!(events[0].force_disable_person_processing);}@@ -2677,7 +2640,7 @@ mod tests {.await;let mut events = vec![wrapped_event("$exception", "user-1")];- events[0].destination = Destination::ExceptionErrorTracking;+ events[0].destination = Destination::ErrorTrackingMain;let now_ts = Utc::now().timestamp();apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;@@ -2700,7 +2663,7 @@ mod tests {.await;let mut events = vec![wrapped_event("$exception", "user-1")];- events[0].destination = Destination::ExceptionErrorTracking;+ events[0].destination = Destination::ErrorTrackingMain;let now_ts = Utc::now().timestamp();apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;@@ -2733,7 +2696,7 @@ mod tests {.await;let mut events = vec![wrapped_event("$exception", "user-1")];- events[0].destination = Destination::ExceptionErrorTracking;+ events[0].destination = Destination::ErrorTrackingMain;let now_ts = Utc::now().timestamp();apply_restrictions(&service, "phc_token", now_ts, false, &mut events).await;@@ -2862,7 +2825,7 @@ mod tests {let limited_ev = find_by_did(&events, "user-2");assert_eq!(limited_ev.result, EventResult::Warning);// AnalyticsMain event over the limit is rerouted to overflow.- assert_eq!(limited_ev.destination, Destination::Overflow);+ assert_eq!(limited_ev.destination, Destination::AnalyticsOverflow);assert!(limited_ev.force_disable_person_processing);assert_eq!(limited_ev.details, Some(DETAIL_PERSON_PROCESSING_DISABLED));}@@ -2897,7 +2860,7 @@ mod tests {assert_eq!(ev.result, EventResult::Warning, "should be Warning");assert_eq!(ev.destination,- Destination::Overflow,+ Destination::AnalyticsOverflow,"should be rerouted to overflow");assert!(@@ -2922,18 +2885,16 @@ mod tests {// Simulate event already dropped by restrictionslet pd = events.iter_mut().find(|e| e.uuid == pre_drop_uuid).unwrap();pd.result = EventResult::Drop;- pd.destination = Destination::Drop;apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;// Pre-dropped event untouchedlet dropped = find_by_did(&events, "user-1");assert_eq!(dropped.result, EventResult::Drop);- assert_eq!(dropped.destination, Destination::Drop);// Other event rate-limited (person processing disabled, rerouted to overflow)let limited = find_by_did(&events, "user-2");assert_eq!(limited.result, EventResult::Warning);- assert_eq!(limited.destination, Destination::Overflow);+ assert_eq!(limited.destination, Destination::AnalyticsOverflow);assert!(limited.force_disable_person_processing);assert_eq!(limited.details, Some(DETAIL_PERSON_PROCESSING_DISABLED));}@@ -3043,7 +3004,6 @@ mod tests {events[1].force_disable_person_processing = true;// user-3 was dropped by an earlier stage.events[2].result = EventResult::Drop;- events[2].destination = Destination::Drop;let tally = apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;@@ -3163,8 +3123,8 @@ mod tests {async fn td_limits_historical_event_not_rerouted_to_overflow() {// Invariant: AnalyticsHistorical must never be rerouted to Overflow.// A globally rate-limited historical event still gets person processing- // disabled, but stays on the historical lane (matches the legacy sink,- // where the AnalyticsHistorical arm never overflows).+ // disabled, but stays on the historical lane (matches v0's+ // `pipeline::resolve`, where the historical arm never overflows).let limiter = mock_limiter(vec!["phc_tok:user-1"]);let ctx = td_context();let mut events =@@ -3254,7 +3214,7 @@ mod tests {.iter_mut().find(|e| e.uuid == ev_uuid).unwrap()- .destination = Destination::Overflow;+ .destination = Destination::AnalyticsOverflow;apply_historical_rerouting(&cfg, &ctx, &mut events);@@ -3264,7 +3224,7 @@ mod tests {.find(|e| e.uuid == ev_uuid).unwrap().destination,- Destination::Overflow+ Destination::AnalyticsOverflow);}@@ -3278,7 +3238,6 @@ mod tests {let mut events = vec![ev];let e = events.iter_mut().find(|e| e.uuid == ev_uuid).unwrap();e.result = EventResult::Drop;- e.destination = Destination::Drop;apply_historical_rerouting(&cfg, &ctx, &mut events);@@ -3288,7 +3247,7 @@ mod tests {.find(|e| e.uuid == ev_uuid).unwrap().destination,- Destination::Drop+ Destination::AnalyticsMain);}@@ -3441,7 +3400,6 @@ mod tests {);for ev in &events {assert_eq!(ev.result, EventResult::Drop);- assert_eq!(ev.destination, Destination::Drop);}}@@ -3475,13 +3433,13 @@ mod tests {assert_eq!(events[0].destination, Destination::AnalyticsMain);assert!(events[1].force_disable_person_processing);assert_eq!(events[1].result, EventResult::Warning);- assert_eq!(events[1].destination, Destination::Overflow);+ assert_eq!(events[1].destination, Destination::AnalyticsOverflow);assert_eq!(events[1].details, Some(DETAIL_PERSON_PROCESSING_DISABLED));assert!(!events[2].force_disable_person_processing);assert_eq!(events[2].destination, Destination::AnalyticsMain);assert!(events[3].force_disable_person_processing);assert_eq!(events[3].result, EventResult::Warning);- assert_eq!(events[3].destination, Destination::Overflow);+ assert_eq!(events[3].destination, Destination::AnalyticsOverflow);assert_eq!(events[3].details, Some(DETAIL_PERSON_PROCESSING_DISABLED));assert!(!events[4].force_disable_person_processing);assert_eq!(events[4].destination, Destination::AnalyticsMain);@@ -3583,7 +3541,7 @@ mod tests {apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);- assert_eq!(events[0].destination, Destination::Overflow);+ assert_eq!(events[0].destination, Destination::AnalyticsOverflow);assert!(events[0].spread_partitions);assert!(events[0].force_disable_person_processing);}@@ -3597,7 +3555,7 @@ mod tests {apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);- assert_eq!(events[0].destination, Destination::Overflow);+ assert_eq!(events[0].destination, Destination::AnalyticsOverflow);assert!(events[0].spread_partitions);assert!(events[0].force_disable_person_processing);}@@ -3619,7 +3577,7 @@ mod tests {assert!(!events[0].spread_partitions);assert!(!events[0].force_disable_person_processing);- assert_eq!(events[1].destination, Destination::Overflow);+ assert_eq!(events[1].destination, Destination::AnalyticsOverflow);assert!(events[1].spread_partitions,"a bursting key must carry the spread stamp"@@ -3642,7 +3600,7 @@ mod tests {apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);- assert_eq!(events[1].destination, Destination::Overflow);+ assert_eq!(events[1].destination, Destination::AnalyticsOverflow);assert!(!events[1].spread_partitions,"preserve_locality=true keeps the partition key"@@ -3683,8 +3641,8 @@ mod tests {/// (setup builds it exactly when the AI overflow valve is armed); absent/// it is never touched.#[rstest::rstest]- #[case::limiter_present(true, Destination::AiEventsOverflow, true)]- #[case::limiter_absent(false, Destination::AiEvents, false)]+ #[case::limiter_present(true, Destination::AiOverflow, true)]+ #[case::limiter_absent(false, Destination::AiMain, false)]fn overflow_ai_events_gated_on_limiter_presence(#[case] ai_limiter_present: bool,#[case] expected_destination: Destination,@@ -3695,7 +3653,7 @@ mod tests {let limiter = overflow_limiter(100, 100, Some("phc_tok:user-1"));let ai_limiter = ai_limiter_present.then_some(&limiter);let mut events = vec![wrapped_event("$ai_generation", "user-1")];- events[0].destination = Destination::AiEvents;+ events[0].destination = Destination::AiMain;apply_overflow_stamping(None, ai_limiter, &ctx, &mut events);@@ -3715,13 +3673,13 @@ mod tests {wrapped_event("$ai_generation", "user-1"),wrapped_event("$ai_generation", "user-1"),];- events[0].destination = Destination::AiEvents;- events[1].destination = Destination::AiEvents;+ events[0].destination = Destination::AiMain;+ events[1].destination = Destination::AiMain;apply_overflow_stamping(None, Some(&limiter), &ctx, &mut events);- assert_eq!(events[0].destination, Destination::AiEvents);- assert_eq!(events[1].destination, Destination::AiEventsOverflow);+ assert_eq!(events[0].destination, Destination::AiMain);+ assert_eq!(events[1].destination, Destination::AiOverflow);assert!(!events[1].spread_partitions,"preserve_locality=true keeps the partition key"@@ -3740,12 +3698,12 @@ mod tests {wrapped_event("$ai_generation", "user-1"),wrapped_event("$ai_generation", "user-1"),];- events[0].destination = Destination::AiEvents;- events[1].destination = Destination::AiEvents;+ events[0].destination = Destination::AiMain;+ events[1].destination = Destination::AiMain;apply_overflow_stamping(None, Some(&limiter), &ctx, &mut events);- assert_eq!(events[1].destination, Destination::AiEventsOverflow);+ assert_eq!(events[1].destination, Destination::AiOverflow);assert!(events[1].spread_partitions);assert!(!events[1].force_disable_person_processing);}@@ -3757,14 +3715,14 @@ mod tests {#[case::analytics_force_key_leaves_ai_untouched(Some("phc_tok:user-1"),None,- Destination::Overflow,- Destination::AiEvents+ Destination::AnalyticsOverflow,+ Destination::AiMain)]#[case::ai_force_key_leaves_analytics_untouched(None,Some("phc_tok:user-1"),Destination::AnalyticsMain,- Destination::AiEventsOverflow+ Destination::AiOverflow)]fn overflow_lane_budgets_are_isolated_per_key(#[case] analytics_force_keys: Option<&str>,@@ -3780,7 +3738,7 @@ mod tests {wrapped_event("$pageview", "user-1"),wrapped_event("$ai_generation", "user-1"),];- events[1].destination = Destination::AiEvents;+ events[1].destination = Destination::AiMain;apply_overflow_stamping(Some(&analytics_limiter),@@ -4041,13 +3999,13 @@ mod tests {process_batch(&ts.state, &mut ctx, batch).await.unwrap();- ts.mock_producer.with_records(|records| {- assert_eq!(records.len(), 1, "the verified event must be published");- assert!(- records[0].payload.contains("$ai_gateway_verified"),- "verified marker must reach the published payload"- );- });+ let records = ts.mock_producer.get_records();+ assert_eq!(records.len(), 1, "the verified event must be published");+ let payload = std::str::from_utf8(&records[0].payload).unwrap();+ assert!(+ payload.contains("$ai_gateway_verified"),+ "verified marker must reach the published payload"+ );}/// process_batch wiring: a client-set marker with no signature is stripped@@ -4071,18 +4029,18 @@ mod tests {process_batch(&ts.state, &mut ctx, batch).await.unwrap();- ts.mock_producer.with_records(|records| {- assert_eq!(- records.len(),- 1,- "the event is still published, just untrusted"- );- assert!(- !records[0].payload.contains("$ai_gateway"),- "forged marker must be stripped before publish"- );- assert!(records[0].payload.contains("$ai_model"));- });+ let records = ts.mock_producer.get_records();+ assert_eq!(+ records.len(),+ 1,+ "the event is still published, just untrusted"+ );+ let payload = std::str::from_utf8(&records[0].payload).unwrap();+ assert!(+ !payload.contains("$ai_gateway"),+ "forged marker must be stripped before publish"+ );+ assert!(payload.contains("$ai_model"));}/// process_batch wiring: an AI event lands on the AI topic.@@ -4097,10 +4055,9 @@ mod tests {process_batch(&ts.state, &mut ctx, batch).await.unwrap();- ts.mock_producer.with_records(|records| {- assert_eq!(records.len(), 1, "the event must be published");- assert_eq!(records[0].topic, "ai_events");- });+ let records = ts.mock_producer.get_records();+ assert_eq!(records.len(), 1, "the event must be published");+ assert_eq!(&*records[0].topic, "ai_events");}/// process_batch wiring: overflow stamping must run when only the AI-lane@@ -4131,14 +4088,13 @@ mod tests {process_batch(&ts.state, &mut ctx, batch).await.unwrap();- ts.mock_producer.with_records(|records| {- let mut topics: Vec<&str> = records.iter().map(|r| r.topic.as_str()).collect();- topics.sort_unstable();- assert_eq!(- topics,- vec!["ai_events", "ai_events_overflow", "events_main"]- );- });+ let records = ts.mock_producer.get_records();+ let mut topics: Vec<&str> = records.iter().map(|r| &*r.topic).collect();+ topics.sort_unstable();+ assert_eq!(+ topics,+ vec!["ai_events", "ai_events_overflow", "events_main"]+ );}/// process_batch wiring: the AI byte budget runs in the v1 pipeline too, so@@ -4166,66 +4122,80 @@ mod tests {process_batch(&ts.state, &mut ctx, batch).await.unwrap();- ts.mock_producer.with_records(|records| {- let mut topics: Vec<&str> = records.iter().map(|r| r.topic.as_str()).collect();- topics.sort_unstable();- assert_eq!(- topics,- vec!["ai_events", "events_main"],- "the over-budget AI event must not reach the sink, and the analytics event must be untouched"- );- });+ let records = ts.mock_producer.get_records();+ let mut topics: Vec<&str> = records.iter().map(|r| &*r.topic).collect();+ topics.sort_unstable();+ assert_eq!(+ topics,+ vec!["ai_events", "events_main"],+ "the over-budget AI event must not be published, and the analytics event must be untouched"+ );}// =========================================================================- // merge_sink_results tests+ // merge_publish_results tests// =========================================================================- use crate::v1::test_utils::MockSinkResult;+ type Results = (Vec<SerializationFailure>, Vec<SinkResult>);- fn mock_result(uuid: Uuid, outcome: &str, cause: &'static str) -> Box<dyn SinkResult> {- match outcome {- "success" => MockSinkResult::success(uuid),- "retriable" => MockSinkResult::retriable(uuid, cause),- "timeout" => MockSinkResult::timeout(uuid),- "fatal" => MockSinkResult::fatal(uuid, cause),- "fatal_no_cause" => MockSinkResult::fatal_no_cause(uuid),- _ => panic!("unknown outcome: {outcome}"),- }+ fn published(uuid: Uuid) -> Results {+ (vec![], vec![SinkResult::published(uuid)])+ }++ fn retriable(uuid: Uuid) -> Results {+ (+ vec![],+ vec![SinkResult::failed(uuid, CaptureError::RetryableSinkError)],+ )+ }++ fn too_big(uuid: Uuid) -> Results {+ let err = CaptureError::EventTooBig("rejected by the broker".to_string());+ (vec![], vec![SinkResult::failed(uuid, err)])+ }++ fn non_retriable(uuid: Uuid) -> Results {+ (+ vec![],+ vec![SinkResult::failed(+ uuid,+ CaptureError::NonRetryableSinkError,+ )],+ )+ }++ fn serialization_failed(uuid: Uuid) -> Results {+ let failure = SerializationFailure::from_error(uuid, "boom".to_string());+ (vec![failure], vec![])+ }++ fn serialization_panicked(uuid: Uuid) -> Results {+ (vec![SerializationFailure::panicked(uuid)], vec![])}#[rstest::rstest]- #[case::success("success", "", EventResult::Ok, None)]- #[case::retriable("retriable", "queue_full", EventResult::Retry, Some("not_persisted"))]- #[case::timeout("timeout", "", EventResult::Retry, Some("not_persisted"))]- #[case::fatal_serialization(- "fatal",- "serialization_failed",+ #[case::published(published, EventResult::Ok, None)]+ #[case::retriable(retriable, EventResult::Retry, Some("not_persisted"))]+ #[case::too_big(too_big, EventResult::Drop, Some("event_too_big"))]+ #[case::non_retriable(non_retriable, EventResult::Drop, Some("rejected"))]+ #[case::serialization_failed(+ serialization_failed,EventResult::Drop,Some("serialization_failed"))]- #[case::fatal_event_too_big("fatal", "event_too_big", EventResult::Drop, Some("event_too_big"))]- #[case::fatal_generic("fatal", "rdkafka_other", EventResult::Drop, Some("rejected"))]- #[case::fatal_no_cause("fatal_no_cause", "", EventResult::Drop, Some("rejected"))]+ #[case::serialization_panicked(serialization_panicked, EventResult::Drop, Some("rejected"))]fn merge_single_outcome(- #[case] outcome: &str,- #[case] cause: &'static str,+ #[case] results: fn(Uuid) -> Results,#[case] expected_result: EventResult,#[case] expected_details: Option<&'static str>,) {let mut events = vec![wrapped_event("$pageview", "user-1")];- let results: Vec<Box<dyn SinkResult>> = vec![mock_result(events[0].uuid, outcome, cause)];+ let (failures, publish_results) = results(events[0].uuid);- merge_sink_results(&mut events, &results);+ merge_publish_results(&mut events, &failures, &publish_results);- assert_eq!(- events[0].result, expected_result,- "result for {outcome}:{cause}"- );- assert_eq!(- events[0].details, expected_details,- "details for {outcome}:{cause}"- );+ assert_eq!(events[0].result, expected_result);+ assert_eq!(events[0].details, expected_details);}#[test]@@ -4234,8 +4204,8 @@ mod tests {events[0].result = EventResult::Warning;events[0].details = Some("person_processing_disabled");- let results: Vec<Box<dyn SinkResult>> = vec![MockSinkResult::success(events[0].uuid)];- merge_sink_results(&mut events, &results);+ let (failures, publish_results) = published(events[0].uuid);+ merge_publish_results(&mut events, &failures, &publish_results);assert_eq!(events[0].result, EventResult::Warning);assert_eq!(events[0].details, Some("person_processing_disabled"));@@ -4249,12 +4219,10 @@ mod tests {];events[0].result = EventResult::Drop;events[0].details = Some("billing_limit_exceeded");- events[0].destination = Destination::Drop;-- // Only one sink result (for the published event)- let results: Vec<Box<dyn SinkResult>> = vec![MockSinkResult::success(events[1].uuid)];- merge_sink_results(&mut events, &results);+ // Only one publish result (for the published event)+ let (failures, publish_results) = published(events[1].uuid);+ merge_publish_results(&mut events, &failures, &publish_results);// Dropped event unchangedassert_eq!(events[0].result, EventResult::Drop);@@ -4272,57 +4240,24 @@ mod tests {wrapped_event("custom", "user-3"),];- let results: Vec<Box<dyn SinkResult>> = vec![- MockSinkResult::success(events[0].uuid),- MockSinkResult::retriable(events[1].uuid, "queue_full"),- MockSinkResult::fatal(events[2].uuid, "serialization_error"),+ let failures = vec![SerializationFailure::from_error(+ events[2].uuid,+ "boom".to_string(),+ )];+ // Deliberately out of event order: results correlate by uuid.+ let publish_results = vec![+ SinkResult::failed(events[1].uuid, CaptureError::RetryableSinkError),+ SinkResult::published(events[0].uuid),];- merge_sink_results(&mut events, &results);+ merge_publish_results(&mut events, &failures, &publish_results);assert_eq!(events[0].result, EventResult::Ok);assert!(events[0].details.is_none());assert_eq!(events[1].result, EventResult::Retry);assert_eq!(events[1].details, Some("not_persisted"));assert_eq!(events[2].result, EventResult::Drop);- assert_eq!(events[2].details, Some("rejected"));- }-- #[test]- fn merge_uuid_correlation_no_crosstalk() {- let mut events = vec![- wrapped_event("$pageview", "user-1"),- wrapped_event("$pageview", "user-2"),- ];-- // Deliberately swap: result for event[1] is retriable, event[0] is success- let results: Vec<Box<dyn SinkResult>> = vec![- MockSinkResult::retriable(events[1].uuid, "queue_full"),- MockSinkResult::success(events[0].uuid),- ];-- merge_sink_results(&mut events, &results);-- assert_eq!(events[0].result, EventResult::Ok);- assert!(events[0].details.is_none());- assert_eq!(events[1].result, EventResult::Retry);- assert_eq!(events[1].details, Some("not_persisted"));- }-- #[test]- fn merge_empty_sink_results_leaves_all_intact() {- let mut events = vec![- wrapped_event("$pageview", "user-1"),- wrapped_event("$pageview", "user-2"),- ];- // All events published but no sink results (edge case - shouldn't- // happen in practice but should be safe)- let results: Vec<Box<dyn SinkResult>> = vec![];-- merge_sink_results(&mut events, &results);-- assert_eq!(events[0].result, EventResult::Ok);- assert_eq!(events[1].result, EventResult::Ok);+ assert_eq!(events[2].details, Some("serialization_failed"));}#[test]@@ -4332,33 +4267,15 @@ mod tests {events[0].details = Some("missing_event_name");// Should be unreachable in practice (dropped events aren't published- // so they won't have a SinkResult), but even if a result exists for+ // so they won't have a publish result), but even if a result exists for// this UUID, the event shouldn't be touched because should_publish is false- let results: Vec<Box<dyn SinkResult>> =- vec![MockSinkResult::retriable(events[0].uuid, "queue_full")];-- merge_sink_results(&mut events, &results);+ let (failures, publish_results) = retriable(events[0].uuid);+ merge_publish_results(&mut events, &failures, &publish_results);assert_eq!(events[0].result, EventResult::Drop);assert_eq!(events[0].details, Some("missing_event_name"));}- #[tokio::test]- async fn process_batch_returns_service_unavailable_when_no_sink_router() {- let test_state = crate::v1::test_utils::TestStateBuilder::new().build();- let mut state = test_state.state;- state.v1_sink_router = None;-- let mut ctx = test_utils::test_analytics_context();- let batch = valid_batch(vec![valid_event()]);-- let err = process_batch(&state, &mut ctx, batch).await.unwrap_err();- assert!(- matches!(err, Error::ServiceUnavailable(_)),- "expected ServiceUnavailable, got: {err:?}"- );- }-#[tokio::test]async fn process_batch_all_validation_dropped_returns_200_not_402() {let test_state = crate::v1::test_utils::TestStateBuilder::new().build();@@ -4432,8 +4349,10 @@ mod tests {assert_eq!(entry.details, Some(DETAIL_NON_HISTORICAL_DROP));}assert!(!resp.has_retry, "dropped batch must not signal retry");- ts.mock_producer- .with_records(|records| assert!(records.is_empty(), "nothing may be published"));+ assert!(+ ts.mock_producer.get_records().is_empty(),+ "nothing may be published"+ );}fn batch_with_historical_flag(flag: serde_json::Value, events: Vec<Event>) -> Batch {@@ -4456,7 +4375,7 @@ mod tests {#[tokio::test]async fn import_mode_publishes_historical_batch(#[case] flag: serde_json::Value) {// The happy path: a properly flagged historical batch flows through- // Import mode exactly like Events mode and reaches the sink.+ // Import mode exactly like Events mode and is published.let ts = TestStateBuilder::new().with_capture_mode(crate::config::CaptureMode::Import).build();@@ -4469,9 +4388,11 @@ mod tests {for (_, entry) in resp.entries() {assert_eq!(entry.result, EventResult::Ok);}- ts.mock_producer.with_records(|records| {- assert_eq!(records.len(), 2, "both historical events must publish");- });+ assert_eq!(+ ts.mock_producer.get_records().len(),+ 2,+ "both historical events must publish"+ );}#[tokio::test]@@ -4527,20 +4448,20 @@ mod tests {process_batch(&ts.state, &mut ctx, batch).await.unwrap();- ts.mock_producer.with_records(|records| {- assert_eq!(records.len(), 3, "all three historical events must publish");- for r in records {- let expected = if r.payload.contains("$ai_generation") {- "ai_events"- } else {- "events_hist"- };- assert_eq!(- r.topic, expected,- "unexpected lane for a historical import event",- );- }- });+ let records = ts.mock_producer.get_records();+ assert_eq!(records.len(), 3, "all three historical events must publish");+ for r in &records {+ let payload = std::str::from_utf8(&r.payload).unwrap();+ let expected = if payload.contains("$ai_generation") {+ "ai_events"+ } else {+ "events_hist"+ };+ assert_eq!(+ &*r.topic, expected,+ "unexpected lane for a historical import event",+ );+ }}#[tokio::test]@@ -4562,10 +4483,9 @@ mod tests {process_batch(&ts.state, &mut ctx, batch).await.unwrap();- ts.mock_producer.with_records(|records| {- assert_eq!(records.len(), 1);- assert_eq!(records[0].topic, "ai_events");- });+ let records = ts.mock_producer.get_records();+ assert_eq!(records.len(), 1);+ assert_eq!(&*records[0].topic, "ai_events");}#[tokio::test]@@ -4632,10 +4552,9 @@ mod tests {}assert!(!resp.has_retry, "a gated batch must not signal retry");- ts.mock_producer.with_records(|records| {- assert_eq!(records.len(), 1, "only the AI event may publish");- assert_eq!(records[0].topic, "ai_events");- });+ let records = ts.mock_producer.get_records();+ assert_eq!(records.len(), 1, "only the AI event may publish");+ assert_eq!(&*records[0].topic, "ai_events");}/// Any `$ai_*` name is admitted; every other name drops.@@ -4685,8 +4604,7 @@ mod tests {assert_eq!(entry.result, EventResult::Ok);assert_eq!(entry.details, None);}- ts.mock_producer- .with_records(|records| assert_eq!(records.len(), 3));+ assert_eq!(ts.mock_producer.get_records().len(), 3);}/// A batch with nothing but non-AI events leaves no event publishable, so@@ -4715,13 +4633,15 @@ mod tests {assert_eq!(entry.details, Some(DETAIL_MISROUTED_EVENT));}assert!(!resp.has_retry, "a fully gated batch must not signal retry");- ts.mock_producer- .with_records(|records| assert!(records.is_empty(), "nothing may publish"));+ assert!(+ ts.mock_producer.get_records().is_empty(),+ "nothing may publish"+ );}/// The gate keys on the event name, not the destination, so a restriction/// that has already retargeted an AI event cannot smuggle it into the- /// non-AI drop. `force_overflow` sends it to `AiEventsOverflow`,+ /// non-AI drop. `force_overflow` sends it to `AiOverflow`,/// `redirect_to_topic` to `Custom`, a DLQ restriction to `Dlq` -- all three/// are still the AI lane.///@@ -4730,7 +4650,7 @@ mod tests {/// invariant holds on its own terms rather than on stage ordering: if the/// two stages were ever reordered, nothing else in the suite would fail.#[rstest::rstest]- #[case::force_overflow(Destination::AiEventsOverflow)]+ #[case::force_overflow(Destination::AiOverflow)]#[case::redirect_to_topic(Destination::Custom("some_other_topic".to_string()))]#[case::redirect_to_dlq(Destination::Dlq)]#[tokio::test]@@ -4755,7 +4675,7 @@ mod tests {assert_eq!(events[0].details, None);}- /// The other direction: a destination of `AiEvents` does not put a non-AI+ /// The other direction: a destination of `AiMain` does not put a non-AI/// event on the lane. Only the event name decides membership.#[tokio::test]async fn a_non_ai_event_pointed_at_the_ai_destination_is_still_dropped() {@@ -4763,13 +4683,13 @@ mod tests {.with_capture_mode(CaptureMode::Ai).build();let ctx = test_utils::test_analytics_context();- let mut events = vec![test_utils::wrapped_event("$pageview", "user-1")- .with_destination(Destination::AiEvents)];+ let mut events =+ vec![test_utils::wrapped_event("$pageview", "user-1")+ .with_destination(Destination::AiMain)];drop_non_ai_events(&ts.state, &ctx, &mut events);assert_eq!(events[0].result, EventResult::Drop);- assert_eq!(events[0].destination, Destination::Drop);assert_eq!(events[0].details, Some(DETAIL_MISROUTED_EVENT));}@@ -5257,53 +5177,23 @@ mod tests {// Integration-style tests: publish → merge → response flow// =========================================================================// These tests exercise the same code path as the wired process_batch, but- // call the sink router directly rather than constructing a full State.+ // call the outputs directly rather than running the whole pipeline.- use std::collections::HashMap as StdHashMap;+ use crate::outputs::OutputRegistry;use std::sync::Arc;- use crate::config::CaptureMode;- use crate::v1::sinks::kafka::mock::MockProducer;- use crate::v1::sinks::kafka::sink::KafkaSink;- use crate::v1::sinks::router::Router as SinkRouter;- use crate::v1::sinks::sink::Sink;- use crate::v1::sinks::{Config as SinkConfig, SinkName};-use super::BatchResponse;use crate::v1::test_utils::{batch_payload, event_with_all_options, event_with_empty_options, WrappedEventMut,};- fn test_sink_router() -> (SinkRouter, lifecycle::Handle, lifecycle::MonitorGuard) {- let mut manager = lifecycle::Manager::builder("test")- .with_trap_signals(false)- .with_prestop_check(false)- .build();- let handle = manager.register("process_integ", lifecycle::ComponentOptions::new());- handle.report_healthy();- let monitor = manager.monitor_background();-- let producer = Arc::new(MockProducer::new(SinkName::Msk, handle.clone()));- let config = SinkConfig {- produce_timeout: StdDuration::from_secs(30),- kafka: test_utils::test_kafka_config(),- };- let sink: Box<dyn Sink> = Box::new(KafkaSink::new(- SinkName::Msk,- producer,- config,- CaptureMode::Events,- handle.clone(),- ));- let sinks: StdHashMap<SinkName, Box<dyn Sink>> =- [(SinkName::Msk, sink)].into_iter().collect();- let router = SinkRouter::new(SinkName::Msk, sinks);- (router, handle, monitor)+ fn test_outputs() -> Arc<OutputRegistry> {+ test_utils::TestStateBuilder::new().build().state.outputs}#[tokio::test]async fn integration_happy_path_all_ok() {- let (router, _handle, _monitor) = test_sink_router();+ let outputs = test_outputs();let mut ctx = test_utils::test_context();ctx.created_at = None;@@ -5316,14 +5206,8 @@ mod tests {let (mut events, serialized) =serialize_batch(events, &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;- let sink_results = router- .publish_batch(router.default_sink(), &ctx, &serialized.prepared)- .await- .unwrap();-- let mut all_results = serialized.failures;- all_results.extend(sink_results);- merge_sink_results(&mut events, &all_results);+ let publish_results = outputs.publish_prepared(serialized.prepared).await;+ merge_publish_results(&mut events, &serialized.failures, &publish_results);let resp = BatchResponse::build(&ctx, &events);assert!(!resp.has_retry);@@ -5336,7 +5220,7 @@ mod tests {#[tokio::test]async fn integration_mixed_pre_drop_and_publish() {- let (router, _handle, _monitor) = test_sink_router();+ let outputs = test_outputs();let mut ctx = test_utils::test_context();ctx.created_at = None;@@ -5353,14 +5237,8 @@ mod tests {assert_eq!(serialized.prepared.len(), 2); // only Ok + Warning are published- let sink_results = router- .publish_batch(router.default_sink(), &ctx, &serialized.prepared)- .await- .unwrap();-- let mut all_results = serialized.failures;- all_results.extend(sink_results);- merge_sink_results(&mut events, &all_results);+ let publish_results = outputs.publish_prepared(serialized.prepared).await;+ merge_publish_results(&mut events, &serialized.failures, &publish_results);let resp = BatchResponse::build(&ctx, &events);assert!(!resp.has_retry);@@ -5377,7 +5255,7 @@ mod tests {#[tokio::test]async fn integration_all_events_pre_dropped_empty_publish() {- let (router, _handle, _monitor) = test_sink_router();+ let outputs = test_outputs();let mut ctx = test_utils::test_context();ctx.created_at = None;@@ -5393,14 +5271,8 @@ mod tests {assert!(serialized.prepared.is_empty());- let sink_results = router- .publish_batch(router.default_sink(), &ctx, &serialized.prepared)- .await- .unwrap();-- let mut all_results = serialized.failures;- all_results.extend(sink_results);- merge_sink_results(&mut events, &all_results);+ let publish_results = outputs.publish_prepared(serialized.prepared).await;+ merge_publish_results(&mut events, &serialized.failures, &publish_results);let resp = BatchResponse::build(&ctx, &events);assert!(!resp.has_retry);@@ -5411,24 +5283,19 @@ mod tests {#[tokio::test]async fn integration_overflow_destination_published_ok() {- let (router, _handle, _monitor) = test_sink_router();+ let outputs = test_outputs();let mut ctx = test_utils::test_context();ctx.created_at = None;let events =- vec![wrapped_event("$pageview", "user-1").with_destination(Destination::Overflow)];+ vec![wrapped_event("$pageview", "user-1")+ .with_destination(Destination::AnalyticsOverflow)];let (mut events, serialized) =serialize_batch(events, &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;- let sink_results = router- .publish_batch(router.default_sink(), &ctx, &serialized.prepared)- .await- .unwrap();-- let mut all_results = serialized.failures;- all_results.extend(sink_results);- merge_sink_results(&mut events, &all_results);+ let publish_results = outputs.publish_prepared(serialized.prepared).await;+ merge_publish_results(&mut events, &serialized.failures, &publish_results);let resp = BatchResponse::build(&ctx, &events);assert!(!resp.has_retry);diff --git a/rust/capture/src/v1/analytics/response.rs b/rust/capture/src/v1/analytics/response.rsindex 14202d9d628e..a72bfd8a200a 100644--- a/rust/capture/src/v1/analytics/response.rs+++ b/rust/capture/src/v1/analytics/response.rs@@ -47,7 +47,7 @@ pub struct BatchResponse {impl BatchResponse {/// Build the response from a processed batch of WrappedEvents.- /// Call this after sink publishing and result merging are complete.+ /// Call this after publishing and result merging are complete.pub fn build(ctx: &RequestContext, events: &[WrappedEvent]) -> Self {let mut has_retry = false;let entries: Vec<(Uuid, BatchEntryStatus)> = events@@ -161,8 +161,8 @@ mod tests {use super::*;use crate::v1::analytics::types::{Event, EventResult, Options, RawOptions, WrappedEvent};- use crate::v1::sinks::Destination;use crate::v1::test_utils;+ use crate::v1::types::Destination;fn make_wrapped(result: EventResult, details: Option<&'static str>) -> WrappedEvent {let uuid = Uuid::new_v4();diff --git a/rust/capture/src/v1/analytics/router.rs b/rust/capture/src/v1/analytics/router.rsindex 3a892fb69447..257e4c024909 100644--- a/rust/capture/src/v1/analytics/router.rs+++ b/rust/capture/src/v1/analytics/router.rs@@ -27,7 +27,7 @@ pub fn routes() -> Router<State> {/// The handler needs no AI-specific branch: every AI behavior in the v1/// pipeline (gateway provenance, the llm_events quota exemption, `Pipeline::Ai`/// restrictions, the per-event size ceiling, the byte-rate limiter, and the-/// `Destination::AiEvents` lane itself) keys off the event name, not the path.+/// `Destination::AiMain` lane itself) keys off the event name, not the path./// What the path decides is which deployment answers, which `crate::router`/// gates on the capture mode.pub fn ai_routes() -> Router<State> {diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rsindex 9a1c3d536840..8b77b6b2126a 100644--- a/rust/capture/src/v1/analytics/types.rs+++ b/rust/capture/src/v1/analytics/types.rs@@ -26,8 +26,7 @@ impl io::Write for StringWriter<'_> {use super::constants::DETAIL_INVALID_OPTIONS;use crate::ordering::{person_ordering, OrderingGuarantee};use crate::v1::context::RequestContext;-use crate::v1::sinks::event::Event as SinkEvent;-use crate::v1::sinks::Destination;+use crate::v1::types::{Destination, Publishable};fn empty_raw_object() -> Box<RawValue> {RawValue::from_string("{}".to_owned()).unwrap()@@ -362,31 +361,19 @@ impl WrappedEvent {}}-impl SinkEvent for WrappedEvent {- // Pre-parsed UUID for result correlation. By the Sink stage,- // we know ALL well-formed incoming events have a valid UUID.+impl Publishable for WrappedEvent {fn uuid(&self) -> Uuid {self.uuid}- // Publish Ok and Warning events; skip Drop, Retry, and anything routed to Destination::Drop.fn should_publish(&self) -> bool {- (self.result == EventResult::Ok || self.result == EventResult::Warning)- && self.destination != Destination::Drop+ self.result == EventResult::Ok || self.result == EventResult::Warning}- // Resolve the storage-agnostic Destination scope for this event.- // The config for each Sink implementation knows how to resolve- // these to topics (etc.) depending on the sink typefn destination(&self) -> &Destination {&self.destination}- // Returns the full typed header set for this event, combining per-request- // context fields (token, now, historical_migration) with event-owned- // fields. Sinks convert the returned CapturedEventHeaders to their- // backend-specific format (e.g. OwnedHeaders for Kafka) via the From impl- // in common_types — same conversion legacy capture uses.fn headers(&self, ctx: &RequestContext) -> CapturedEventHeaders {// Downstream treats this header as absolute: `decideProcessPerson` in// nodejs/src/common/persons/person-utils.ts skips person processing@@ -527,6 +514,7 @@ impl SinkEvent for WrappedEvent {}impl WrappedEvent {+ /// Server-side `$` properties as comma-separated `"key":value` pairs, without braces.#[allow(unused_assignments)]fn build_property_injections(&self, ctx: &RequestContext) -> anyhow::Result<String> {let mut buf = String::with_capacity(256);@@ -578,8 +566,8 @@ impl WrappedEvent {Ok(buf)}- /// Build spliced properties if injection is needed, or return None- /// to signal the caller should borrow `self.event.properties` directly.+ /// Appends the injected pairs inside the client's raw properties object,+ /// so capture never parses the properties. Returns None when nothing is injected.fn build_spliced_properties(&self,ctx: &RequestContext,@@ -1274,11 +1262,10 @@ mod tests {}}- // --- SinkEvent impl for WrappedEvent ---+ // --- Publishable impl for WrappedEvent ---- use crate::v1::sinks::event::Event as SinkEventTrait;- use crate::v1::sinks::Destination;use crate::v1::test_utils;+ use crate::v1::types::{Destination, Publishable};use common_types::HasEventName;fn ok_wrapped(event_name: &str, distinct_id: &str) -> WrappedEvent {@@ -1323,31 +1310,34 @@ mod tests {Stamps { spread: true, ..Stamps::on(Destination::AnalyticsMain) },OrderingGuarantee::PerDistinctId)]- #[case::overflow_untouched(Stamps::on(Destination::Overflow), OrderingGuarantee::PerDistinctId)]+ #[case::overflow_untouched(+ Stamps::on(Destination::AnalyticsOverflow),+ OrderingGuarantee::PerDistinctId+ )]#[case::overflow_person_off(- Stamps { person_off: true, ..Stamps::on(Destination::Overflow) },+ Stamps { person_off: true, ..Stamps::on(Destination::AnalyticsOverflow) },OrderingGuarantee::None)]#[case::overflow_spread(- Stamps { spread: true, ..Stamps::on(Destination::Overflow) },+ Stamps { spread: true, ..Stamps::on(Destination::AnalyticsOverflow) },OrderingGuarantee::PerDistinctId)]#[case::overflow_spread_person_off(- Stamps { person_off: true, spread: true, ..Stamps::on(Destination::Overflow) },+ Stamps { person_off: true, spread: true, ..Stamps::on(Destination::AnalyticsOverflow) },OrderingGuarantee::None)]#[case::ai_overflow_spread(- Stamps { spread: true, ..Stamps::on(Destination::AiEventsOverflow) },+ Stamps { spread: true, ..Stamps::on(Destination::AiOverflow) },OrderingGuarantee::None)]#[case::ai_overflow_person_off(- Stamps { person_off: true, ..Stamps::on(Destination::AiEventsOverflow) },+ Stamps { person_off: true, ..Stamps::on(Destination::AiOverflow) },OrderingGuarantee::None)]// Lanes whose consumers need the key regardless: person processing being// off must not spread them, matching v0's route().#[case::ai_main_person_off(- Stamps { person_off: true, ..Stamps::on(Destination::AiEvents) },+ Stamps { person_off: true, ..Stamps::on(Destination::AiMain) },OrderingGuarantee::PerDistinctId)]#[case::historical_person_off(@@ -1382,10 +1372,10 @@ mod tests {#[rstest::rstest]#[case::ok_main(EventResult::Ok, Destination::AnalyticsMain)]#[case::ok_historical(EventResult::Ok, Destination::AnalyticsHistorical)]- #[case::ok_overflow(EventResult::Ok, Destination::Overflow)]+ #[case::ok_overflow(EventResult::Ok, Destination::AnalyticsOverflow)]#[case::warning_main(EventResult::Warning, Destination::AnalyticsMain)]#[case::warning_historical(EventResult::Warning, Destination::AnalyticsHistorical)]- #[case::warning_overflow(EventResult::Warning, Destination::Overflow)]+ #[case::warning_overflow(EventResult::Warning, Destination::AnalyticsOverflow)]fn should_publish_true(#[case] result: EventResult, #[case] dest: Destination) {let mut ev = ok_wrapped("$pageview", "user-1");ev.result = result;@@ -1396,10 +1386,6 @@ mod tests {#[rstest::rstest]#[case::drop_main(EventResult::Drop, Destination::AnalyticsMain)]#[case::retry_main(EventResult::Retry, Destination::AnalyticsMain)]- #[case::ok_dest_drop(EventResult::Ok, Destination::Drop)]- #[case::warning_dest_drop(EventResult::Warning, Destination::Drop)]- #[case::drop_dest_drop(EventResult::Drop, Destination::Drop)]- #[case::retry_dest_drop(EventResult::Retry, Destination::Drop)]fn should_publish_false(#[case] result: EventResult, #[case] dest: Destination) {let mut ev = ok_wrapped("$pageview", "user-1");ev.result = result;@@ -1587,8 +1573,8 @@ mod tests {#[test]fn destination_returns_event_destination() {let mut ev = ok_wrapped("$pageview", "user-1");- ev.destination = Destination::Overflow;- assert_eq!(*ev.destination(), Destination::Overflow);+ ev.destination = Destination::AnalyticsOverflow;+ assert_eq!(*ev.destination(), Destination::AnalyticsOverflow);}#[test]diff --git a/rust/capture/src/v1/constants.rs b/rust/capture/src/v1/constants.rsindex adf25d680770..7ff4109cb3a3 100644--- a/rust/capture/src/v1/constants.rs+++ b/rust/capture/src/v1/constants.rs@@ -87,7 +87,7 @@ pub(super) const CAPTURE_V1_PAYLOAD_SIZE: &str = "capture_v1_payload_size_bytes"/// configured in prometheus.rs (CLOCK_SKEW_SECONDS).pub(super) const CAPTURE_V1_CLOCK_SKEW_SECONDS: &str = "capture_v1_clock_skew_seconds";-/// Histogram of batch serialize wall-time (label: batch_size bucket). Sink- and+/// Histogram of batch serialize wall-time (label: batch_size bucket). Output- and/// product-agnostic by design — faceting comes from the per-mode service/// deployment (capture-analytics / capture-replay / capture-ai).pub(super) const CAPTURE_V1_SERIALIZE_DURATION_SECONDS: &str =diff --git a/rust/capture/src/v1/mod.rs b/rust/capture/src/v1/mod.rsindex 5c70253dc070..d7d17c5d838d 100644--- a/rust/capture/src/v1/mod.rs+++ b/rust/capture/src/v1/mod.rs@@ -4,11 +4,12 @@ pub mod context;pub mod error;pub mod gateway_provenance;pub mod middleware;+pub mod prepare;pub mod quota_limiter_shim;pub mod router;-pub mod sinks;#[cfg(any(test, feature = "test-utils"))]pub mod test_utils;+pub mod types;pub mod util;pub use error::Error;diff --git a/rust/capture/src/v1/sinks/prepare.rs b/rust/capture/src/v1/prepare.rssimilarity index 79%rename from rust/capture/src/v1/sinks/prepare.rsrename to rust/capture/src/v1/prepare.rsindex a0127a58d99c..98ed59d731e3 100644--- a/rust/capture/src/v1/sinks/prepare.rs+++ b/rust/capture/src/v1/prepare.rs@@ -1,14 +1,11 @@-//! Hoisted, CaptureMode-agnostic serialize step.+//! The v1 serialize step.//!-//! `serialize_batch` turns a batch of [`Event`]s into [`PreparedEvent`]s-//! (owned, storage-agnostic) before any [`Sink`](super::sink::Sink) sees them.-//! Pulling serialization out of the Sink lets every capture mode (analytics,-//! replay, AI) share one CPU-bound step and enables serialize-once /-//! fan-out-to-many-sinks for dual-write topologies.+//! `serialize_batch` turns [`Publishable`] events into the outputs layer's+//! [`PreparedEvent`]s, which `OutputRegistry::publish_prepared` takes. It runs+//! before any output sees the batch, so CPU-bound encoding stays apart from+//! produce I/O and can run in parallel.//!-//! Small batches serialize sequentially; large batches scatter across tokio-//! tasks and gather back in input order. Per-event panics are isolated so one-//! bad event never fails the whole request.+//! Each event serializes under `catch_unwind`, so a panic fails only that event.use std::panic::{catch_unwind, AssertUnwindSafe};use std::sync::Arc;@@ -19,27 +16,25 @@ use tokio::task::JoinSet;use tracing::Level;use uuid::Uuid;+use crate::outputs::PreparedEvent;use crate::v1::constants::{CAPTURE_V1_SERIALIZE_DURATION_SECONDS, CAPTURE_V1_SERIALIZE_FAILED_TOTAL,CAPTURE_V1_SERIALIZE_PANIC_TOTAL,};use crate::v1::context::RequestContext;-use crate::v1::sinks::event::Event;-use crate::v1::sinks::types::{PreparedEvent, SerializationFailure, SinkResult};+use crate::v1::types::Publishable;-/// Default scatter-gather threshold; overridden by `CAPTURE_V1_SCATTER_GATHER_MIN_BATCH`.+/// Batches smaller than this serialize inline, because spawning a task per+/// event costs more than serializing a handful of events. Overridden by+/// `CAPTURE_V1_SCATTER_GATHER_MIN_BATCH`.pub const DEFAULT_SCATTER_GATHER_MIN_BATCH: usize = 8;-/// Outcome of the serialize step: events ready to publish (input order) plus-/// per-event failures, each already a `SinkResult` so the caller can merge them-/// straight into the batch's result set.pub struct SerializedBatch {+ /// In input order.pub prepared: Vec<PreparedEvent>,- pub failures: Vec<Box<dyn SinkResult>>,+ pub failures: Vec<SerializationFailure>,}-/// Per-event result before aggregation. `Skipped` mirrors the Sink's existing-/// behavior of silently dropping `should_publish() == false` events.// Prepared is the hot, dominant variant and is immediately drained into a// Vec<PreparedEvent>; boxing it just to even out variant sizes would add a// heap allocation per successful event.@@ -50,16 +45,17 @@ enum Slot {Failed(SerializationFailure),}-/// Serialize one event, honoring `should_publish`. Pure and panic-free at this-/// layer — panic isolation is the caller's (`run_one`) job.-fn prepare_one<E: Event>(ev: &E, ctx: &RequestContext) -> anyhow::Result<Option<PreparedEvent>> {+fn prepare_one<E: Publishable>(+ ev: &E,+ ctx: &RequestContext,+) -> anyhow::Result<Option<PreparedEvent>> {if !ev.should_publish() {return Ok(None);}let payload = ev.serialize(ctx)?;Ok(Some(PreparedEvent {uuid: ev.uuid(),- destination: ev.destination().clone(),+ address: ev.destination().address(),payload,headers: ev.headers(ctx),partition_key: ev.partition_key(ctx),@@ -67,10 +63,9 @@ fn prepare_one<E: Event>(ev: &E, ctx: &RequestContext) -> anyhow::Result<Option<}))}-/// Run `prepare_one` with panic isolation so a single misbehaving event (e.g. a-/// `serialize` impl that panics) is recorded as a failure instead of aborting-/// the batch / poisoning the worker.-fn run_one<E: Event>(ev: &E, ctx: &RequestContext) -> Slot {+/// Records a panic in `prepare_one` as this event's failure, so one bad event+/// cannot fail the batch or kill the worker task.+fn run_one<E: Publishable>(ev: &E, ctx: &RequestContext) -> Slot {let uuid = ev.uuid();match catch_unwind(AssertUnwindSafe(|| prepare_one(ev, ctx))) {Ok(Ok(Some(prepared))) => Slot::Prepared(prepared),@@ -80,20 +75,18 @@ fn run_one<E: Event>(ev: &E, ctx: &RequestContext) -> Slot {}}-/// Serialize a whole batch into `PreparedEvent`s, preserving input order for-/// the prepared events so downstream per-partition ordering is unaffected.+/// Prepared events keep input order, so per-partition order downstream+/// matches the request.///-/// Consumes `events` so the parallel path can share them across tokio tasks-/// via `Arc`, then hands ownership back (alongside the results) so the caller-/// can keep correlating results to events and build its response. `ctx` is-/// cloned once and shared across tasks.+/// Takes `events` by value because the parallel path shares them across+/// tasks, and returns them so the caller can build its per-event response.pub async fn serialize_batch<E>(events: Vec<E>,ctx: &RequestContext,scatter_gather_threshold: usize,) -> (Vec<E>, SerializedBatch)where- E: Event + 'static,+ E: Publishable + 'static,{let start = Instant::now();let n = events.len();@@ -112,15 +105,14 @@ wherefor i in 0..n {let events = Arc::clone(&events);let ctx = Arc::clone(&ctx);- // Spawn onto the async runtime workers (not spawn_blocking): the- // per-event work is short CPU, so concurrent execution is naturally- // bounded by worker_threads (~num_cpus) and excess events queue- // cheaply. This mirrors v0's send_batch and avoids saturating the- // shared spawn_blocking pool on huge batches.+ // Spawn onto the async runtime workers, not spawn_blocking: the+ // per-event work is short CPU, so worker_threads bounds the+ // concurrency and excess events queue cheaply. One spawn_blocking+ // task per event would saturate the shared blocking pool on huge+ // batches. The Kafka sink's parallel prep does the same.set.spawn(async move { (i, run_one(&events[i], &ctx)) });}- // Gather out-of-completion-order results back into input order.let mut indexed: Vec<Option<Slot>> = (0..n).map(|_| None).collect();while let Some(joined) = set.join_next().await {// run_one catches panics internally, so a JoinError is unexpected;@@ -142,7 +134,7 @@ where};let mut prepared = Vec::with_capacity(n);- let mut failures: Vec<Box<dyn SinkResult>> = Vec::new();+ let mut failures: Vec<SerializationFailure> = Vec::new();let mut failed_count = 0u64;let mut panic_count = 0u64;for slot in slots {@@ -164,7 +156,7 @@ where);failed_count += 1;}- failures.push(Box::new(f));+ failures.push(f);}}}@@ -192,6 +184,49 @@ fn batch_size_bucket(n: usize) -> &'static str {}}+/// An event that failed to serialize. Always fatal: serializing the same event+/// again fails the same way, so it is dropped, never retried.+#[derive(Debug, Clone)]+pub struct SerializationFailure {+ uuid: Uuid,+ cause: &'static str,+ detail: String,+}++impl SerializationFailure {+ pub fn from_error(uuid: Uuid, detail: String) -> Self {+ Self {+ uuid,+ cause: "serialization_failed",+ detail,+ }+ }++ pub fn panicked(uuid: Uuid) -> Self {+ Self {+ uuid,+ cause: "serialization_panic",+ detail: "serialization task panicked".to_string(),+ }+ }++ pub fn is_panic(&self) -> bool {+ self.cause == "serialization_panic"+ }++ pub fn uuid(&self) -> Uuid {+ self.uuid+ }++ pub fn cause(&self) -> &'static str {+ self.cause+ }++ pub fn detail_str(&self) -> &str {+ &self.detail+ }+}+#[cfg(test)]mod tests {use common_types::CapturedEventHeaders;@@ -199,8 +234,9 @@ mod tests {use super::*;use crate::ordering::OrderingGuarantee;- use crate::v1::sinks::types::{Destination, Outcome};+ use crate::pipeline::{Address, Lane, Pipeline};use crate::v1::test_utils::test_context;+ use crate::v1::types::Destination;fn empty_captured_headers() -> CapturedEventHeaders {CapturedEventHeaders {@@ -257,7 +293,7 @@ mod tests {}}- impl Event for FakeEvent {+ impl Publishable for FakeEvent {fn uuid(&self) -> Uuid {self.uuid}@@ -318,7 +354,13 @@ mod tests {for (i, prepared) in out.prepared.iter().enumerate() {assert_eq!(prepared.payload.as_ref(), format!("payload-{i}").as_bytes());assert_eq!(prepared.partition_key, format!("key-{i}"));- assert_eq!(prepared.destination, Destination::AnalyticsMain);+ assert_eq!(+ prepared.address,+ Address::Lane {+ pipeline: Pipeline::Analytics,+ lane: Lane::Main+ }+ );}}@@ -351,7 +393,7 @@ mod tests {}/// A serialize error is isolated: the good events still come through and the- /// failure surfaces as a fatal, non-retriable `SinkResult`.+ /// failure surfaces as a `serialization_failed` failure.#[rstest]#[case::sequential(3)]#[case::parallel(16)]@@ -369,10 +411,8 @@ mod tests {assert_eq!(out.prepared.len(), n - 1);assert_eq!(out.failures.len(), 1);let failure = &out.failures[0];- assert_eq!(failure.key(), bad_uuid);- assert_eq!(failure.outcome(), Outcome::FatalError);- assert_eq!(failure.cause(), Some("serialization_failed"));- assert!(failure.elapsed().is_none());+ assert_eq!(failure.uuid(), bad_uuid);+ assert_eq!(failure.cause(), "serialization_failed");}/// A panicking `serialize` is caught: the rest of the batch is unaffected@@ -391,8 +431,7 @@ mod tests {assert_eq!(events.len(), n);assert_eq!(out.prepared.len(), n - 1);assert_eq!(out.failures.len(), 1);- assert_eq!(out.failures[0].cause(), Some("serialization_panic"));- assert_eq!(out.failures[0].outcome(), Outcome::FatalError);+ assert_eq!(out.failures[0].cause(), "serialization_panic");}/// Panic failures preserve the correct event UUID (not nil).@@ -410,8 +449,8 @@ mod tests {let (_events, out) = serialize_batch(events, &ctx, DEFAULT_SCATTER_GATHER_MIN_BATCH).await;assert_eq!(out.failures.len(), 1);- assert_eq!(out.failures[0].key(), panic_uuid);- assert_eq!(out.failures[0].cause(), Some("serialization_panic"));+ assert_eq!(out.failures[0].uuid(), panic_uuid);+ assert_eq!(out.failures[0].cause(), "serialization_panic");}#[tokio::test]diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex ae134b08c7f2..731ad14147ca 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -6,7 +6,6 @@ use crate::quota_limiters::CaptureQuotaLimiter;use crate::quota_limiters::{is_exception_event, is_llm_event, is_survey_event, EventInfo};use crate::v1::analytics::constants::CAPTURE_V1_EVENTS_QUOTA_LIMITED;use crate::v1::analytics::types::{EventResult, WrappedEvent};-use crate::v1::sinks::Destination;use crate::v1::Error;type ScopedCheck = (QuotaResource, fn(EventInfo) -> bool);@@ -66,7 +65,6 @@ pub async fn apply_quota_limits(};if predicate(info) {ev.result = EventResult::Drop;- ev.destination = Destination::Drop;ev.details = Some(match resource {QuotaResource::Exceptions => "exceptions_over_quota",QuotaResource::Surveys => "survey_responses_over_quota",@@ -98,6 +96,7 @@ pub async fn apply_quota_limits(#[cfg(test)]mod tests {use super::*;+ use crate::v1::types::Destination;use std::num::NonZeroU32;use std::sync::Arc;use std::time::Duration;@@ -213,7 +212,6 @@ mod tests {body_chunk_read_timeout_ms: None,body_read_chunk_size_kb: 256,continuous_profiling: ContinuousProfilingConfig::default(),- capture_v1_sinks: String::new(),capture_v1_max_compressed_body_bytes: 10 * 1024 * 1024,capture_v1_max_decompressed_body_bytes: 50 * 1024 * 1024,capture_v1_scatter_gather_min_batch: 8,@@ -327,7 +325,7 @@ mod tests {fn quota_dropped_event_names(events: &[WrappedEvent]) -> Vec<&str> {let mut names: Vec<&str> = events.iter()- .filter(|e| e.result == EventResult::Drop && e.destination == Destination::Drop)+ .filter(|e| e.result == EventResult::Drop).map(|e| e.event.event.as_str()).collect();names.sort();@@ -397,7 +395,6 @@ mod tests {// Pre-mark one event as Drop (e.g. from validation)let bad_ev = events.iter_mut().find(|e| e.uuid == bad_uuid).unwrap();bad_ev.result = EventResult::Drop;- bad_ev.destination = Destination::Drop;bad_ev.details = Some("invalid_event_name");let result = apply_quota_limits(&limiter, "tok", &mut events).await;@@ -675,7 +672,6 @@ mod tests {// Pre-mark pageview as Drop from a prior validation steplet pv_ev = events.iter_mut().find(|e| e.uuid == pv_uuid).unwrap();pv_ev.result = EventResult::Drop;- pv_ev.destination = Destination::Drop;let result = apply_quota_limits(&limiter, "tok", &mut events).await;// $exception → Drop (quota), $pageview → already Drop → all non-Ok → errordiff --git a/rust/capture/src/v1/sinks/DESIGN.md b/rust/capture/src/v1/sinks/DESIGN.mddeleted file mode 100644index b69f0ec443b2..000000000000--- a/rust/capture/src/v1/sinks/DESIGN.md+++ /dev/null@@ -1,1368 +0,0 @@-# v1/sinks design--Architecture and design choices in the `v1::sinks` module —-the destination-agnostic event publishing layer for PostHog capture v1.--## Overview--The sinks module decouples capture's request-handling pipeline from the-specifics of _where_ events are published.-Today the only backend is Kafka (via rdkafka); the trait boundaries are-drawn so that future backends (WarpStream, S3, etc.) slot in without-touching request-path code.--### Endpoint paths--v1 capture endpoints follow the naming scheme-`/i/v<version>/<scope>/<payload>/`:--| Endpoint | Path | Status |-|---|---|---|-| Analytics events | `/i/v1/analytics/events/` | First v1 endpoint |--As additional capture domains migrate to v1 (e.g. AI, replay),-they register their own paths under the same scheme.--```text- ┌─────────────┐- │ HTTP layer │- └──────┬───────┘- │ Vec<WrappedEvent>- ▼- ┌──────────────┐- │serialize_batch│─ scatter-gather (prepare.rs)- └──────┬────────┘- │ Vec<PreparedEvent>- ▼- ┌─────────────┐- │ Router │─── resolves SinkName- └──────┬───────┘- ┌──────────┼──────────┐- ▼ ▼ ▼- ┌────────┐ ┌────────┐ ┌────────┐- │KafkaSink│ │KafkaSink│ │ Future │- │ (msk) │ │(msk_alt)│ │ Sink │- └────┬───┘ └────┬───┘ └────────┘- │ │- ▼ ▼- ┌────────┐ ┌────────┐- │Producer│ │Producer│- │ (msk) │ │(msk_alt)- └────────┘ └────────┘-```--Key properties:--- **Storage-agnostic contracts** — `Sink`, `Event`, `SinkResult` know- nothing about Kafka.-- **Multi-sink** — the `Router` maps named sinks to concrete- implementations, supporting concurrent dual-writes (e.g. MSK +- WarpStream during a migration).-- **Per-event results** — `publish_batch` returns one `Box<dyn SinkResult>`- per published event, correlating outcomes back to request events by UUID.-- **Hoisted serialization** — events are serialized into storage-agnostic- `PreparedEvent`s by `serialize_batch` (`prepare.rs`) _before_ any sink is- touched. Sinks consume `&[PreparedEvent]`, never raw `Event` trait objects.- This isolates CPU-bound encoding from sink I/O, lets the same prepared- batch fan out to multiple sinks without re-encoding, and enables the- scatter-gather parallelism described in [section 2a](#2a-serialize_batch-scatter-gather).-- **Owned-payload API** — `Event::serialize()` returns `bytes::Bytes` and- `partition_key()` returns a fresh `String`, keeping the trait simple and- cheap to move into spawned tasks.-------## Module layout--```mermaid-graph TD- mod["sinks/mod.rs<br>SinkName, Config, Sinks,<br>load_sinks, re-exports"]- constants["constants.rs<br>DEFAULT_PRODUCE_TIMEOUT,<br>SINK_LIVENESS_DEADLINE,<br>SINK_STALL_THRESHOLD"]- event["event.rs<br>trait Event"]- sink["sink.rs<br>trait Sink"]- types["types.rs<br>Destination, Outcome,<br>trait SinkResult, BatchSummary,<br>PreparedEvent, SerializationFailure"]- prepare["prepare.rs<br>serialize_batch,<br>SerializedBatch"]- router["router.rs<br>Router,<br>RouterError"]-- kmod["kafka/mod.rs<br>KafkaProducerTrait"]- kconfig["kafka/config.rs<br>Config (Envconfig)"]- kctx["kafka/context.rs<br>KafkaContext<br>(ClientContext)"]- kprod["kafka/producer.rs<br>KafkaProducer,<br>ProduceRecord,<br>ProduceError, SendHandle"]- ktypes["kafka/types.rs<br>KafkaResult,<br>KafkaSinkError,<br>error_code_tag"]- ksink["kafka/sink.rs<br>KafkaSink (Sink impl)"]- kmock["kafka/mock.rs<br>MockProducer"]- ktests["kafka/sink_tests.rs<br>unit tests"]-- mod --> constants- mod --> event- mod --> sink- mod --> types- mod --> prepare- mod --> router- mod --> kmod-- prepare --> event- prepare --> types-- kmod --> kconfig- kmod --> kctx- kmod --> kprod- kmod --> ktypes- kmod --> ksink- kmod --> kmock- kmod --> ktests-- router --> sink- router --> event- router --> types-```--Two layers:--- **Top-level abstractions** (`sink.rs`, `event.rs`, `types.rs`,- `router.rs`) — backend-agnostic traits and routing. Know nothing about- Kafka.-- **`kafka/`** — implements those traits against rdkafka. All- Kafka-specific logic is contained here.--`mod.rs` re-exports the public API:--```rust-pub use event::Event;-pub use kafka::KafkaSink;-pub use prepare::{serialize_batch, SerializedBatch};-pub use router::{Router, RouterError};-pub use sink::Sink;-pub use types::{Destination, Outcome, PreparedEvent, SerializationFailure, SinkResult};-```-------## 1. Sink trait and Router--### Sink--`trait Sink` (`sink.rs`) is the backend-agnostic publishing interface:--```rust-#[async_trait]-pub trait Sink: Send + Sync {- fn name(&self) -> SinkName;-- async fn publish_batch(- &self,- ctx: &RequestContext,- events: &[PreparedEvent],- ) -> Vec<Box<dyn SinkResult>>;-- async fn flush(&self) -> anyhow::Result<()>;-}-```--Each `Sink` owns its identity (`name`), accepts a batch of-already-serialized `PreparedEvent`s, and returns one `Box<dyn SinkResult>`-per event it attempts. Events that never reach the sink — filtered by-`should_publish()` or routed to `Destination::Drop` during-`serialize_batch` — are simply absent from the input slice. A-`Destination` with no configured topic still produces no result entry.--`KafkaSink<P: KafkaProducerTrait>` is currently the only implementation.-It is generic over the producer trait so tests inject `MockProducer`-without touching real Kafka.--### Router--`Router` (`router.rs`) owns the mapping from `SinkName` to concrete-`Box<dyn Sink>` instances and provides the caller-facing publish API:--```rust-pub struct Router {- default: SinkName,- sinks: HashMap<SinkName, Box<dyn Sink>>,-}-```--| Method | Purpose |-|---|---|-| `publish_batch(sink, ctx, events)` | Look up sink by name, delegate to `Sink::publish_batch` |-| `publish(sink, ctx, event)` | Convenience wrapper for single events |-| `default_sink()` | Returns the first sink from the `CAPTURE_V1_SINKS` CSV |-| `available_sinks()` | Lists all configured sink names |-| `flush()` | Flushes all sinks concurrently via `FuturesUnordered` |--The `Sink` trait intentionally takes no `SinkName` parameter — the-Router resolves the target before calling into the sink. This keeps-`Sink` implementations stateless with respect to routing and makes the-single-sink case zero-cost.--`RouterError::SinkNotFound` is returned when a caller requests a sink-name that was not configured. This is a caller bug, not a per-event error.--```text- Caller ──publish_batch(SinkName, ctx, events)──▶ Router- │- lookup by name- │- ▼- HashMap<SinkName, Sink>- │- publish_batch(ctx, events)- │- ▼- KafkaSink- │- Vec<Box<dyn SinkResult>>- │- ▼- Caller ◀───────────Ok(results)─────────────── Router-```-------## 2. Event abstraction--`trait Event` (`event.rs`) decouples the sink from any specific capture-endpoint, `CaptureMode`, or event schema:--```rust-pub trait Event: Send + Sync {- fn uuid(&self) -> Uuid;- fn should_publish(&self) -> bool;- fn destination(&self) -> &Destination;- fn headers(&self, ctx: &RequestContext) -> CapturedEventHeaders;- fn partition_key(&self, ctx: &RequestContext) -> String;- fn serialize(&self, ctx: &RequestContext) -> anyhow::Result<bytes::Bytes>;-}-```--`headers` receives the request `RequestContext` so each `Event` implementation-can combine batch-scoped fields (token, now, historical_migration) with-event-scoped fields into a single `CapturedEventHeaders`-(`common_types`). The sink converts the returned struct to its-transport-specific format via `From<CapturedEventHeaders> for-OwnedHeaders`.--The analytics capture endpoint's `WrappedEvent` implements this trait-(see [section 10](#10-analytics-event-serialization)).-Other capture endpoints (e.g. session replay, exceptions) provide-their own `Event` implementations without changing any sink code.--### Context split--Trait methods take `&RequestContext` — the mode-agnostic request context-(token, IP, timing, raw query string) shared by every future capture mode.-The analytics endpoint wraps it in `analytics::Context { req, query }`,-which `Deref`s to `RequestContext`, so the typed `Query` stays an-analytics-only concern while the sink layer remains capture-mode-agnostic.--### Owned-return serialization--`serialize(ctx)` returns `bytes::Bytes` and `partition_key(ctx)` returns a-fresh owned `String`. `Bytes` is zero-copy to construct from a `Vec<u8>`-and cheap (refcounted) to clone, so a `PreparedEvent` can be moved into a-tokio task and fanned out to multiple sinks without re-encoding.-The owned contract needs no shared mutable buffers, which is what makes-the scatter-gather prep loop safe to parallelize.--`WrappedEvent::serialize` pre-sizes its buffer via-`Vec::with_capacity(data.len() + 512)` to minimize reallocations-for typical payloads, then returns `Bytes::from(buf)`.--### Skip mechanisms--Callers have two orthogonal ways to prevent an event from being produced:--| Mechanism | Where set | Effect |-|---|---|---|-| `should_publish() == false` | Pipeline validation (e.g. `EventResult != Ok`) | Silently skipped, no `SinkResult` returned |-| `Destination::Drop` | Routing logic (e.g. quota limiter) | `topic_for()` returns `None`, event skipped |--### Header construction--Each `Event` implementation builds the full `CapturedEventHeaders`-struct per event, combining batch-scoped context (token, now,-historical_migration) with event-scoped fields (distinct_id, uuid,-timestamp, session_id, etc.):--```text- ┌──────────────────────────────────────────────┐- │ event.headers(ctx: &RequestContext) │- │ │- │ CapturedEventHeaders { │- │ token, ◄─ from ctx │- │ now, ◄─ from ctx │- │ historical_migration, ◄─ from ctx │- │ distinct_id, ◄─ from event │- │ event, ◄─ from event │- │ uuid, ◄─ from event │- │ timestamp, ◄─ from event │- │ session_id?, ◄─ from event │- │ force_disable_*?, ◄─ from event │- │ skip_heatmap_processing?, ◄─ from event │- │ dlq_reason/step/timestamp? ◄─ from event │- │ } │- └──────────────────┬───────────────────────────┘- │- ▼- ┌──────────────────────────────────────────────┐- │ let headers: OwnedHeaders = headers.into(); │- │ (From impl in common_types) │- └──────────────────────────────────────────────┘-```--The sink converts `CapturedEventHeaders` to `OwnedHeaders` via the-`From` impl in `common_types`. There is no separate merge function —-a single structured type flows from event to transport.-------## 2a. serialize_batch (scatter-gather)--`serialize_batch` (`prepare.rs`) is the mode-agnostic step that turns a-`Vec<E: Event>` into a `SerializedBatch` _before_ the router/sink layer.-It is generic over the `Event` impl, so analytics, replay, and AI capture-modes share one implementation.--```rust-pub async fn serialize_batch<E: Event + Send + Sync + 'static>(- events: Vec<E>,- ctx: &RequestContext,- scatter_gather_threshold: usize,-) -> (Vec<E>, SerializedBatch);--pub struct SerializedBatch {- pub prepared: Vec<PreparedEvent>, // publishable, in input order- pub failures: Vec<Box<dyn SinkResult>>, // SerializationFailure per failed event-}-```--The caller gets its `Vec<E>` back so it can still build the per-event HTTP-response after publishing (the prepared events alone don't carry the-original request event). Recovery uses `Arc::try_unwrap` after the spawned-tasks finish — see "Ownership" below.--### PreparedEvent--```rust-pub struct PreparedEvent {- pub uuid: Uuid,- pub destination: Destination,- pub payload: bytes::Bytes,- pub headers: CapturedEventHeaders,- pub partition_key: String, // raw; the sink decides whether to null it-}-```--Storage-agnostic and fully owned. It carries everything a sink needs to-produce a record, so the sink does no serialization and holds no reference-back into the request. `Bytes` makes it cheap to clone across a dual-write.--### Sequential vs parallel--The threshold is configurable via `CAPTURE_V1_SCATTER_GATHER_MIN_BATCH`-(default 8). Set to 0 to force sequential serialization for all batch-sizes (useful for modes like replay where batches are always single large events).--```text- scatter_gather_threshold == 0 OR events.len() < threshold- └── serialize inline on the request task (no spawn overhead)-- events.len() >= threshold (threshold > 0)- └── Arc<Vec<E>> + Arc<RequestContext>- └── JoinSet of tokio tasks (spawn, not spawn_blocking), one per event index- └── each task: catch_unwind(prepare_one(&events[i], &ctx))- └── collect by index → preserves input order-```--Small batches stay inline because a `JoinSet` of tokio tasks costs more-than the serialization itself for a handful of events. Large batches fan-out across the async worker pool to cut tail latency on big payloads. We-use `spawn` (not `spawn_blocking`) to match v0's `send_batch`: per-event-serialize is short CPU work, so concurrent execution is naturally bounded-by `worker_threads` (~num_cpus) and excess events queue cheaply, rather-than spawning one blocking-pool task per event and risking saturation of-the shared `spawn_blocking` pool on very large batches. Both paths produce-identical output (ordering, skips, failures)-— verified by parity tests in `prepare.rs`.--### Panic isolation--Each event is serialized inside `std::panic::catch_unwind`. A panic in one-event's `serialize` becomes a `SerializationFailure { is_panic: true }`-for that event only; the rest of the batch is unaffected. Regular `Err`-returns become `SerializationFailure::from_error`. Both are fatal-(non-retriable) — re-running the same bytes would panic/err again.--### Ownership (Arc::try_unwrap)--`spawn` requires `'static`, so the parallel path wraps the events-in `Arc<Vec<E>>` and tasks borrow by index. After the `JoinSet` drains,-every task has dropped its `Arc` clone, so `Arc::try_unwrap` reclaims the-sole-owner `Vec<E>` and hands it back to the caller. This is why-`serialize_batch` can be parallel yet still return owned events.--### Metrics--| Metric | Type | Labels | When |-|---|---|---|---|-| `capture_v1_serialize_duration_seconds` | histogram | `batch_size` | Per-batch serialize wall-time (sequential or parallel) |-| `capture_v1_serialize_failed_total` | counter | — | Per event that failed to serialize |-| `capture_v1_serialize_panic_total` | counter | — | Per event whose `serialize` panicked |--These are sink- and product-agnostic (serialization happens before any-sink is chosen). Per-mode faceting comes from the Kubernetes deployment-(`capture-analytics` / `-replay` / `-ai`) via the `namespace` label-injected by the metrics pipeline.-------## 3. SinkResult and outcome model--### The SinkResult trait--`trait SinkResult` (`types.rs`) defines a backend-agnostic interface for-inspecting per-event publish outcomes:--```rust-pub trait SinkResult: Send + Sync {- fn key(&self) -> Uuid; // event UUID — correlation key- fn outcome(&self) -> Outcome; // Success | Timeout | RetriableError | FatalError- fn cause(&self) -> Option<&'static str>; // low-cardinality metric tag- fn detail(&self) -> Option<Cow<'_, str>>; // human-readable error detail- fn elapsed(&self) -> Option<Duration>; // enqueue-to-ack latency (std::time::Duration)-}-```--`publish_batch` returns `Vec<Box<dyn SinkResult>>` — one entry per-published event. The trait-object approach keeps the `Sink` trait fully-backend-agnostic: callers never need to know which backend produced a-result. The per-event heap allocation is a deliberate trade-off for-simplicity; at current batch sizes the cost is negligible compared to-Kafka I/O.--Two types implement `SinkResult`: `KafkaResult` (sink-level produce-outcomes) and `SerializationFailure` (pre-sink serialize failures from-`serialize_batch`). `process_batch` concatenates both into one-`Vec<Box<dyn SinkResult>>` before correlating outcomes back to events.--### Outcome--```rust-pub enum Outcome {- Success,- Timeout,- RetriableError,- FatalError,-}-```--### KafkaResult--`KafkaResult` (`kafka/types.rs`) is the Kafka-specific implementation:--```rust-pub struct KafkaResult {- uuid: Uuid,- error: Option<KafkaSinkError>,- enqueued_at: DateTime<Utc>,- completed_at: Option<DateTime<Utc>>,-}-```--Outcome is derived from the error — `None` means `Success`, otherwise-`KafkaSinkError::outcome()` maps to the appropriate `Outcome` variant.--### KafkaSinkError--Captures every failure mode within a single configured sink:--| Variant | Outcome | When |-|---|---|---|-| `SinkUnavailable` | `RetriableError` | Producer health gate failed |-| `Produce(ProduceError)` | Depends on `ProduceError::is_retriable()` | rdkafka send or delivery error |-| `Timeout` | `Timeout` | Ack not received within `produce_timeout` |-| `TaskPanicked` | `RetriableError` | Ack task panicked (should not happen with `FuturesUnordered`) |--Serialization failures are no longer a sink concern — they are produced by-`serialize_batch` as `SerializationFailure` (see-[section 2a](#2a-serialize_batch-scatter-gather)) before any sink runs.--### BatchSummary--`BatchSummary::from_results` aggregates a `&[Box<dyn SinkResult>]` into-counts used for log-level selection, error counters, and health heartbeat-decisions:--```rust-pub struct BatchSummary {- pub total: usize,- pub succeeded: usize,- pub retriable: usize,- pub fatal: usize,- pub timed_out: usize,- pub errors: HashMap<&'static str, usize>, // cause tag → count-}-```--```mermaid-classDiagram- class Outcome {- <<enum>>- Success- Timeout- RetriableError- FatalError- }-- class SinkResult {- <<trait>>- +key() Uuid- +outcome() Outcome- +cause() Option~static str~- +detail() Option~Cow str~- +elapsed() Option~std Duration~- }-- class KafkaResult {- -uuid: Uuid- -error: Option~KafkaSinkError~- -enqueued_at: DateTime- -completed_at: Option~DateTime~- }-- class BatchSummary {- +total: usize- +succeeded: usize- +retriable: usize- +fatal: usize- +timed_out: usize- +errors: HashMap~static str, usize~- +from_results(results) BatchSummary- +all_ok() bool- }-- SinkResult <|.. KafkaResult : implements- SinkResult --> Outcome : returns- BatchSummary ..> SinkResult : aggregates-```-------## 4. Three-phase publish pipeline--`KafkaSink::publish_batch` (`kafka/sink.rs`) processes events in three-phases, returning a `Vec<Box<dyn SinkResult>>` where each entry-corresponds 1:1 to a published event.--```text- ┌──────────────────────────────────────────────────────────────────┐- │ Pre-flight: health gate │- │ │- │ producer.is_ready()? │- │ ├── not ready → reject ALL publishable as SinkUnavailable │- │ └── ready → proceed │- └──────────────────────────┬───────────────────────────────────────┘- │- ┌──────────────────────────▼───────────────────────────────────────┐- │ Phase 1: Enqueue (sequential, per-partition ordering preserved) │- │ │- │ input: &[PreparedEvent] (already serialized by serialize_batch)│- │ for each prepared event: │- │ ├── topic_for(destination)? → skip if Drop/None │- │ ├── payload: prepared.payload (Bytes, no re-encode) │- │ ├── effective_partition_key(prepared.partition_key, dest)? │- │ ├── CapturedEventHeaders → OwnedHeaders (via From) │- │ └── producer.send(ProduceRecord) │- │ ├── Ok(ack_future) → push to FuturesUnordered │- │ ├── Err(QueueFull) + retries left → sleep, retry │- │ └── Err(final) → results.push(KafkaResult err) │- └──────────────────────────┬───────────────────────────────────────┘- │- ┌──────────────────────────▼───────────────────────────────────────┐- │ Phase 2: Drain acks (concurrent, bounded by produce_timeout) │- │ │- │ deadline = now + produce_timeout │- │ │- │ loop: │- │ timeout_at(deadline, pending.next()) │- │ ├── Ok(ack resolved) → results.push(ok or err + completed) │- │ ├── Ok(None) → all drained, break │- │ └── Err(deadline) → break to Phase 3 │- └──────────────────────────┬───────────────────────────────────────┘- │- ┌──────────────────────────▼───────────────────────────────────────┐- │ Phase 3: Sweep timed-out keys │- │ │- │ enqueued_keys ∖ resolved_keys = timed_out │- │ for each: results.push(KafkaResult::Timeout) │- │ │- │ (dropping remaining FuturesUnordered is safe — they are │- │ oneshot::Receivers; the message still completes in │- │ librdkafka via message.timeout.ms) │- └──────────────────────────┬───────────────────────────────────────┘- │- ┌──────────────────────────▼───────────────────────────────────────┐- │ Post-batch: summarize, log, emit metrics, health heartbeat │- │ │- │ BatchSummary::from_results(&results) │- │ log at DEBUG (all ok) / WARN (partial) / ERROR (full failure) │- │ emit capture_v1_kafka_produce_errors_total per error tag │- │ if succeeded > 0 → handle.report_healthy() │- └──────────────────────────┬───────────────────────────────────────┘- │- ▼- Vec<Box<dyn SinkResult>>-```--### Phase 1 — Enqueue--Events arrive already serialized as `PreparedEvent`s, so Phase 1 does no-encoding — it reads `prepared.payload` (`Bytes`) directly. Events are sent-sequentially to preserve per-partition ordering.--If `producer.send()` returns `QueueFull`, the event is failed immediately-as a retriable error. Backpressure is handled by librdkafka's internal-queue and the client-level retry mechanism, not an app-level sleep loop.--Prepared events always carry a key; the sink uses it unless-`PreparedEvent::ordering` is `OrderingGuarantee::None`, in which case-`None` is passed to rdkafka so it round-robins. Passing `Some("")` would-hash to a single deterministic partition via murmur2, creating a hot-partition. See §9 for how the guarantee is decided.--### Phase 2 — Drain--A `FuturesUnordered` stream is drained under a per-sink `produce_timeout`-deadline using `tokio::time::timeout_at`. Each resolved future yields-either a success or an ack-level error, both stamped with `completed_at`-for latency measurement.--`FuturesUnordered` is chosen over `JoinSet` because the ack futures are-`DeliveryFuture` (oneshot receivers) — pure I/O waits with no CPU work.-Polling them inline in a single task is strictly cheaper than spawning-real tokio tasks.--#### Single batch deadline vs per-event deadline (head-of-line coupling)--The deadline is **per batch**, not per event: `deadline = now +-produce_timeout` is computed once, after the whole batch is enqueued, and-every event in the batch shares it. Because enqueue is fast and serial, the-last event's clock starts only marginally after the first's, so per-event-`sent_at` (recorded for the ack-latency histogram) and the shared deadline-stay close in practice.--A per-event deadline (`sent_at + produce_timeout`, now feasible since WS3a-threads `sent_at` through) would decouple a slow head-of-line event from the-rest of the batch. It is **deliberately deferred**: the current model is-simpler, matches v0, and `capture_v1_kafka_ack_duration_seconds` (per-event,-including `outcome="timeout"`) now makes any head-of-line coupling directly-observable. Revisit only if load-test tails (WS7) show the shared deadline-materially penalizing fast events behind a slow one.--### Phase 3 — Sweep--Any keys in `enqueued_keys` not present in `resolved_keys` after the-deadline are recorded as `KafkaSinkError::Timeout`.--Dropping the remaining `FuturesUnordered` items is safe: each is a-`oneshot::Receiver`. Dropping it means rdkafka's delivery callback-`send()` returns `Err` (silently ignored). The message still completes-in librdkafka (or times out via `message.timeout.ms`); we just stop-waiting for the ack.--### HTTP response mapping--The caller correlates results back to original events using-`SinkResult::key()` (the event UUID):--| Method | HTTP response use |-|---|---|-| `key()` | Match result to request event by UUID |-| `outcome()` | Map to HTTP status (Success → 2xx, Retriable → 503, Fatal → 4xx) |-| `cause()` | Optional error code in response body |-| `detail()` | Optional human-readable error message |-| `elapsed()` | Optional latency metadata |-------## 5. Configuration and multi-sink loading--### SinkName--Each sink is identified by a `SinkName` enum variant with a corresponding-env var prefix:--| Variant | `as_str()` | `env_prefix()` | `lifecycle_tag()` |-|---|---|---|---|-| `Msk` | `msk` | `CAPTURE_V1_SINK_MSK_` | `v1-sink-msk` |-| `MskAlt` | `msk_alt` | `CAPTURE_V1_SINK_MSK_ALT_` | `v1-sink-msk_alt` |-| `Ws` | `ws` | `CAPTURE_V1_SINK_WS_` | `v1-sink-ws` |--Active sinks are declared via a CSV env var:--```bash-CAPTURE_V1_SINKS=msk,ws-```--The first entry becomes the default sink for single-write mode.--### Two-pass key split--`load_sink_config` strips the sink prefix from env keys and splits them-into two maps by the `KAFKA_` sub-prefix:--| Sub-prefix | Destination | Example |-|---|---|---|-| `KAFKA_*` | `kafka::config::Config` (Envconfig) | `KAFKA_HOSTS` → field `hosts` |-| everything else | Sink-level config | `PRODUCE_TIMEOUT_MS` → `produce_timeout` |--This makes the transport-specific config composable: a future S3-sink would use an `S3_` sub-prefix alongside `PRODUCE_TIMEOUT_MS`.--```text- Environment variables- ─────────────────────- │- ▼- CAPTURE_V1_SINKS CSV ──▶ load_sinks_from()- │ │- │ per SinkName- ▼ ▼- ["msk", "ws"] load_sink_config(name, env)- │- ┌─────────────┼──────────────┐- │ KAFKA_* keys │ sink-level keys- ▼ ▼- kafka::config::Config produce_timeout, etc.- │ │- └──────────┬─────────────────┘- ▼- Config { produce_timeout, kafka }- │- ▼- Sinks { default, configs: HashMap }-```--### Config structs--```rust-/// Composite per-sink configuration (sinks/mod.rs).-pub struct Config {- pub produce_timeout: Duration,- pub kafka: kafka::config::Config,-}--/// Parsed set of v1 sink configs.-pub struct Sinks {- pub default: SinkName,- pub configs: HashMap<SinkName, Config>,-}-```--### kafka::config::Config fields--The Kafka-specific config is loaded via `Envconfig::init_from_hashmap`.-Sensible prod defaults are set for every field so a minimal deployment-only needs to specify hosts and topics.--| Field | Default | rdkafka property | Notes |-|---|---|---|---|-| `hosts` | _(required)_ | `bootstrap.servers` | Comma-separated broker list |-| `tls` | `false` | `security.protocol` | `ssl` when true |-| `client_id` | `""` | `client.id` | Set only when non-empty |-| `linger_ms` | `20` | `linger.ms` | Batch accumulation window |-| `queue_mib` | `400` | `queue.buffering.max.kbytes` | Converted: MiB × 1024 → KiB |-| `message_timeout_ms` | `30000` | `message.timeout.ms` | ~6 retry cycles at 5s socket timeout |-| `message_max_bytes` | `1000000` | `message.max.bytes` | Per-message size limit |-| `compression_codec` | `lz4` | `compression.codec` | `none\|gzip\|snappy\|lz4\|zstd` |-| `acks` | `all` | `acks` | `0\|1\|-1\|all` |-| `enable_idempotence` | `false` | `enable.idempotence` | |-| `batch_num_messages` | `10000` | `batch.num.messages` | |-| `batch_size` | `1000000` | `batch.size` | Bytes |-| `metadata_refresh_interval_ms` | `5000` | `topic.metadata.refresh.interval.ms` | Fast leader discovery on failover |-| `metadata_max_age_ms` | `15000` | `metadata.max.age.ms` | Must be ≥ 3× refresh interval |-| `socket_timeout_ms` | `5000` | `socket.timeout.ms` | Fast dead-broker detection |-| `statistics_interval_ms` | `10000` | `statistics.interval.ms` | Drives health heartbeat |-| `partitioner` | `murmur2_random` | `partitioner` | v0 parity (python-kafka compat) |-| `max_retries` | `4` | `message.send.max.retries` | Tuned for MSK failover |-| `max_in_flight_requests` | `1000000` | `max.in.flight.requests.per.connection` | |-| `sticky_partitioning_linger_ms` | `10` | `sticky.partitioning.linger.ms` | Keyless message distribution |-| `broker_address_family` | `""` | `broker.address.family` | Empty = librdkafka default; `v4`/`v6`/`any` |-| `log_connection_close` | `true` | `log.connection.close` | Log broker connection close events |-| `queue_buffering_max_messages` | `100000` | `queue.buffering.max.messages` | Max messages buffered in producer queue |-| `retry_backoff_max_ms` | `1000` | `retry.backoff.max.ms` | Upper bound on exponential retry backoff |-| `socket_send_buffer_bytes` | `0` | `socket.send.buffer.bytes` | TCP send buffer size; 0 = OS default |-| `socket_receive_buffer_bytes` | `0` | `socket.receive.buffer.bytes` | TCP receive buffer size; 0 = OS default |-| `topic_main` | _(required)_ | — | Analytics main topic |-| `topic_historical` | _(required)_ | — | Historical migration topic |-| `topic_overflow` | _(required)_ | — | Overflow topic |-| `topic_dlq` | _(required)_ | — | Dead letter queue topic |-| `topic_exception` | _(required)_ | — | Error tracking events topic |-| `topic_heatmap` | _(required)_ | — | Heatmap ingestion topic |-| `topic_client_ingestion_warning` | _(required)_ | — | Client ingestion warning topic |--Topic resolution is handled by `Config::topic_for(&Destination)`:--| Destination | Topic |-|---|---|-| `AnalyticsMain` | `topic_main` |-| `AnalyticsHistorical` | `topic_historical` |-| `Overflow` | `topic_overflow` |-| `Dlq` | `topic_dlq` |-| `ExceptionErrorTracking` | `topic_exception` |-| `HeatmapMain` | `topic_heatmap` |-| `ClientIngestionWarning` | `topic_client_ingestion_warning` |-| `Custom(t)` | `t` (passthrough) |-| `Drop` | `None` (skip) |--### Validation--`Config::validate()` (sink-level) enforces:--- `produce_timeout >= message_timeout_ms` — prevents ghost deliveries- where librdkafka delivers a message after the application has already- timed out and reported failure.-- Delegates to `kafka::Config::validate()`.--`kafka::Config::validate()` enforces:--- Non-empty `hosts`-- `queue_mib > 0`-- `acks` ∈ `{0, 1, -1, all}`-- `compression_codec` ∈ `{none, gzip, snappy, lz4, zstd}`-- `statistics_interval_ms > 0` (0 disables stats, breaking health heartbeat)-- `metadata_max_age_ms >= 3× metadata_refresh_interval_ms`--`Sinks::validate()` ensures at least one sink is configured and-delegates to each `Config::validate()`.--### Multi-producer support--The `SinkName` enum + `HashMap<SinkName, Config>` pattern supports-concurrent dual-writes to multiple Kafka clusters (e.g. MSK + WarpStream-during a migration). Each sink gets its own `KafkaProducer`, independent-config, and independent health tracking. The caller selects which sink(s)-to write to per batch via the `Router`.-------## 6. Kafka producer--### KafkaProducerTrait--```rust-pub trait KafkaProducerTrait: Send + Sync {- type Ack: Future<Output = Result<(), ProduceError>> + Send;-- fn send<'a>(&self, record: ProduceRecord<'a>)- -> Result<Self::Ack, (ProduceError, ProduceRecord<'a>)>;- fn flush(&self, timeout: Duration) -> Result<(), KafkaError>;- fn is_ready(&self) -> bool;- fn sink_name(&self) -> SinkName;-}-```--This trait abstracts the Kafka producer for testability. `KafkaProducer`-is the real implementation wrapping `FutureProducer<KafkaContext>`;-`MockProducer` is the test implementation (see [section 11](#11-testing)).--### KafkaProducer--Constructed by `KafkaProducer::new(sink, &KafkaConfig, handle, capture_mode)`:--1. Builds a `ClientConfig` from `kafka::config::Config` fields,- mapping `queue_mib` to `queue.buffering.max.kbytes` (MiB → KiB).-2. Creates `FutureProducer<KafkaContext>` via `create_with_context`.-3. Performs an initial `fetch_metadata(None, 10s)` probe. On success,- calls `handle.report_healthy()`. On failure, logs an error and- increments `capture_v1_kafka_client_errors_total` with tag- `metadata_fetch_failed` — but still returns the producer (it may- recover via background metadata refresh).--### ProduceRecord and SendHandle--```rust-pub struct ProduceRecord<'a> {- pub topic: &'a str,- pub key: Option<&'a str>,- pub payload: &'a [u8],- pub headers: OwnedHeaders,-}-```--`send()` converts this to a `FutureRecord` and calls `send_result()`.-On success it returns a `SendHandle` wrapping rdkafka's `DeliveryFuture`.-On failure it returns the `ProduceRecord` back to the caller (enabling-the QueueFull retry loop without reallocating the message).--`SendHandle` implements `Future` and maps rdkafka delivery outcomes:--- Channel closed → `ProduceError::DeliveryCancelled` (retriable)-- Kafka error → `ProduceError::Kafka { code }` or- `ProduceError::EventTooBig` for `MessageSizeTooLarge`--### ProduceError--```rust-pub enum ProduceError {- EventTooBig { message: String },- Kafka { code: RDKafkaErrorCode },- DeliveryCancelled,-}-```--Retriability is computed by `ProduceError::is_retriable()` using-`is_fatal_kafka_error(code)`. Fatal (non-retriable) Kafka codes:-`MessageSizeTooLarge`, `InvalidMessageSize`, `InvalidMessage`.-Everything else is retriable.-------## 7. Producer health monitoring--### Health primitive--`lifecycle::Handle` provides a heartbeat-based health model:--- `report_healthy()` — resets the liveness timer-- `is_healthy()` — returns `true` if a heartbeat arrived within the- liveness deadline--There is no explicit `report_unhealthy()`. Unhealthy state is inferred-from **missed heartbeats** — if no source calls `report_healthy()` within-`SINK_LIVENESS_DEADLINE` (30s), the handle is considered stalled.--### Heartbeat sources--Three independent sources feed the same `Handle`:--| Source | When | Location |-|---|---|---|-| `KafkaProducer::new` | Initial metadata fetch succeeds | `producer.rs` |-| `KafkaContext::stats` | Any broker reports state `"UP"` | `context.rs` |-| `KafkaSink::publish_batch` | At least one event in the batch succeeded | `kafka/sink.rs` |--### Timing chain--From `constants.rs`, the worst-case detection sequence:--```text- t=0s t=10s t=20s t=30s t=32s- │ │ │ │ │- │ Last healthy │ stats fires │ stats fires │ │- │ heartbeat │ (brokers down) │ (brokers down) │ │- │ │ │ │ │- ├─────────────────┼─────────────────┼─────────────────┤ │- │ publish_batch running for up to produce_timeout=30s│ │- │ (0 successes → no heartbeat) │ │- │ │ │- │ liveness │ │- │ deadline │ health │- │ expires ────┤ poll │- │ │detects │- │ │ stall │- │ │ │- │ │shutdown│- └─────────────────────────────────────────────────────┴────────┘-```--1. Last successful heartbeat at t=0-2. `publish_batch` runs for up to `produce_timeout` (30s), returns with- 0 successes — no heartbeat-3. Stats callback fires every `statistics_interval_ms` (10s) but all- brokers are down — no heartbeat-4. At t=30s `SINK_LIVENESS_DEADLINE` expires-5. Next health poll (within 2s) detects- `stall_count >= SINK_STALL_THRESHOLD` (1)-6. Global shutdown triggered at ~t=32s--### Health gate--At the top of `publish_batch`, if `!producer.is_ready()` the entire batch-is rejected with `KafkaSinkError::SinkUnavailable` (retriable outcome).-This prevents queueing work against a producer that cannot reach its-brokers.-------## 8. Observability--### Metrics--Metrics are organized into three tiers:--#### Client-level (KafkaContext)--Emitted from the rdkafka stats callback and error callback. These-reflect the health of the underlying Kafka client independent of any-request.--| Metric | Type | Labels | Source |-|---|---|---|---|-| `capture_v1_kafka_client_errors_total` | counter | `cluster`, `mode`, `error` | `error()` callback, all-brokers-down in `stats()`, metadata fetch failure |-| `capture_v1_kafka_producer_queue_depth` | gauge | `cluster`, `mode` | `stats()` |-| `capture_v1_kafka_producer_queue_bytes` | gauge | `cluster`, `mode` | `stats()` |-| `capture_v1_kafka_producer_queue_utilization` | gauge | `cluster`, `mode` | `stats()` (`msg_cnt / msg_max`) |-| `capture_v1_kafka_batch_size_bytes_avg` | gauge | `cluster`, `mode`, `topic` | `stats()` |-| `capture_v1_kafka_broker_connected` | gauge | `cluster`, `mode`, `broker` | `stats()` |-| `capture_v1_kafka_broker_rtt_us` | gauge | `cluster`, `mode`, `quantile`, `broker` | `stats()` (full window: `min`/`avg`/`max`/`stddev`/`p50`/`p90`/`p95`/`p99`) |-| `capture_v1_kafka_broker_int_latency_us` | gauge | `cluster`, `mode`, `quantile`, `broker` | `stats()` — time in producer internal queue (full window) |-| `capture_v1_kafka_broker_outbuf_latency_us` | gauge | `cluster`, `mode`, `quantile`, `broker` | `stats()` — time in broker output buffer (full window) |-| `capture_v1_kafka_broker_tx_errors_total` | counter | `cluster`, `mode`, `broker` | `stats()` via `.absolute()` |-| `capture_v1_kafka_broker_rx_errors_total` | counter | `cluster`, `mode`, `broker` | `stats()` via `.absolute()` |--Note: broker tx/rx error counters use `.absolute()` because librdkafka-reports cumulative values; the metrics library handles delta computation.--#### Request-path (KafkaSink::publish_batch)--Emitted per event or per batch during the publish flow. These carry-request-level context (`path`, `attempt`).--| Metric | Type | Labels | When |-|---|---|---|---|-| `capture_v1_kafka_publish_total` | counter | `mode`, `cluster`, `outcome`, `path`, `attempt` (capped at "6+"), `destination` | Every event outcome (success, error, timeout, reject) |-| `capture_v1_kafka_ack_duration_seconds` | histogram | `mode`, `cluster`, `outcome`, `path`, `attempt` (capped at "6+"), `destination` | Per-event broker-ack latency (successful send → ack resolution), including `outcome="timeout"` for acks that miss `produce_timeout` |-| `capture_v1_kafka_enqueue_duration_seconds` | histogram | `mode`, `cluster`, `path`, `attempt` (capped at "6+") | Per-batch enqueue wall-time (the `enqueue_events` call), isolated from broker-ack latency |--Serialization timing now lives in `capture_v1_serialize_duration_seconds`-(emitted by `serialize_batch`, see-[section 2a](#2a-serialize_batch-scatter-gather)) — it is no longer a-sink-path metric.--Cardinality note: the `destination` label is bounded at 9 values-(`Destination::as_tag()` collapses all `Custom(_)` topics to `custom`)-and the client-controlled `attempt` label is capped at `6+`, so-`capture_v1_kafka_publish_total` stays low-cardinality.--#### Related pipeline metrics (emitted upstream of the sink)--| Metric | Type | Labels | When |-|---|---|---|---|-| `capture_v1_event_adjustments_applied` | counter | `reason` (`future_timestamp_clamp`, `person_processing_disabled`) | An adjustment is applied to an accepted event. Counts adjustments, NOT unique events — one event can emit more than one reason. |-| `capture_v1_events_restricted` | counter | `action` | Non-drop event-restriction action applied |-| `capture_v1_batch_outcomes` | counter | `outcome`, `path` | One increment per request batch. `Warning` results count toward `all_ok` (the event was still accepted). |-| `capture_v1_decompression_errors_total` | counter | `encoding` | Streaming decompression failure |--#### Summary-level (post-batch)--| Metric | Type | Labels | When |-|---|---|---|---|-| `capture_v1_kafka_produce_errors_total` | counter | `cluster`, `mode`, `error` | One increment per distinct error tag in `BatchSummary.errors` |--#### Error tagging--All error-related metrics use stable, low-cardinality tags derived from:--- `error_code_tag()` — maps `RDKafkaErrorCode` variants to snake_case strings- (e.g. `queue_full`, `message_size_too_large`, `all_brokers_down`). Defined in- `common_kafka::error` and re-exported from `kafka/types.rs`, so producers- outside the sink share the same vocabulary-- `KafkaSinkError::as_tag()` — sink-level tags- (e.g. `sink_unavailable`, `timeout`, `task_panicked`)-- `ProduceError::as_tag()` — producer-level tags- (e.g. `event_too_big`, `delivery_cancelled`)--### Structured logging--All sink-level log output uses `ctx_log!` macros which attach-request-scoped context (token, path, attempt) to the log line.--| Level | When | Location |-|---|---|---|-| `DEBUG` (via `ctx_log!`) | All events succeeded | `kafka/sink.rs` |-| `WARN` (via `ctx_log!`) | Partial batch failure | `kafka/sink.rs` |-| `ERROR` (via `ctx_log!`) | Full batch failure | `kafka/sink.rs` |-| `ERROR` (via `ctx_log!`) | Producer not ready | `kafka/sink.rs` |-| `error!` | rdkafka client error callback | `kafka/context.rs` |-| `error!` | All brokers down | `kafka/context.rs` |-| `info!` | Producer connected | `kafka/producer.rs` |-| `error!` | Initial metadata fetch failed | `kafka/producer.rs` |-------## 9. Destination routing and partition key resolution--### Destination--The `Destination` enum (`types.rs`) represents the semantic routing-target for a processed event, _before_ any Kafka-specific topic-resolution:--```rust-pub enum Destination {- AnalyticsMain, // normal analytics events- AnalyticsHistorical, // historical migration imports- Overflow, // overflow-routed events- Dlq, // dead letter queue (event restriction)- ExceptionErrorTracking, // $exception events → error tracking pipeline- HeatmapMain, // $$heatmap events → heatmap ingestion- ClientIngestionWarning, // $$client_ingestion_warning events- Custom(String), // custom topic passthrough- Drop, // do not produce-}-```--`Destination::is_analytics_pipeline()` returns `true` for-`AnalyticsMain` and `AnalyticsHistorical` only. This gate controls-which events are subject to analytics-scoped restrictions, overflow-routing, and related pipeline logic.--Topic resolution happens inside `kafka::config::Config::topic_for()`,-keeping the Sink trait unaware of topic names.--### Partition key resolution--Partition key construction is split between the `Event` implementation-and the sink:--1. **`Event::partition_key(ctx)`** returns an owned key String, captured- into `PreparedEvent.partition_key` by `serialize_batch`.- For analytics events (`WrappedEvent`):--```text- ┌───────────────────────────────────────────────────┐- │ partition_key(ctx) -> String │- │ │- │ cookieless_mode? │- │ ├── yes, capture_internal → "token:127.0.0.1" │- │ ├── yes, normal → "token:client_ip" │- │ └── no → "token:distinct_id" │- └───────────────────────────────────────────────────┘-```--2. **`PreparedEvent::ordering`** decides whether the prepared key is used.- `Event::ordering()` returns an `OrderingGuarantee` (`crate::ordering`,- shared with the v0 sink) and the sink passes `None` to rdkafka for- `OrderingGuarantee::None`, `Some(prepared.partition_key)` otherwise.-- `WrappedEvent::ordering` gives up the guarantee only on the lanes that- exist to absorb hot keys (`AnalyticsMain`, `Overflow`,- `AiEventsOverflow`). On the person-writing lanes (`AnalyticsMain`,- `Overflow`) that takes `force_disable_person_processing`; a- `spread_partitions` stamp alone takes effect only on the read-only- `AiEventsOverflow` lane (`Destination::writes_persons`). It is computed- at prepare time rather than stamped during processing because it- depends on the final destination, which `apply_historical_rerouting`- can still change after `apply_restrictions` has disabled person- processing.--Key design choices:--- **The person-processing header is not a control channel.** Nulling the- key is driven by `ordering`, never by reading- `headers.force_disable_person_processing` back out. That header is an- instruction to downstream to skip identity resolution, so using it to- request partition spreading silently disabled person processing for- every rate-limited overflow event.-- **`spread_partitions` is separate from person processing.** The overflow- limiter sets it alone when a key merely exceeds its burst budget, leaving- person processing on. The sink realizes the spread only where the- consumer does not write persons (the AI overflow lane); on the analytics- lanes the key holds until person processing is off, because spreading one- distinct id across partitions contends the consumer's person updates. A- `ForceLimited` verdict sets both flags, matching v0.-- **`None` = round-robin.** `None` is passed to rdkafka, which- round-robins across partitions. Passing `Some("")` would hash to a- single deterministic partition via murmur2, creating a hot spot.-- **DLQ/Historical/Custom/AI-main retain key** even when- `force_disable_person_processing` is set. Only the analytics main and- overflow lanes and the AI overflow lane drop it, matching v0's- `route()`.-- **Cookieless mode** uses `token:client_ip` as partition key instead- of `token:distinct_id`, with IP redacted to `127.0.0.1` for- `capture_internal` requests.-------## 10. Analytics event serialization--The `v1::analytics::WrappedEvent` is the concrete `Event` implementation-for the analytics capture endpoint (`/i/v1/analytics/events/`). It-bridges the new v1 event schema (`Event`, `Options`, raw `properties`)-to the legacy `IngestionEvent` shape that downstream ingestion workers-expect.--### Data flow--```text- ┌─────────────────────────┐- │ Inbound v1 Request │- │ │- │ Batch { │- │ created_at, │- │ historical_migration,│- │ batch: [Event, ...] │- │ } │- └───────────┬─────────────┘- │ parse + validate- ▼- ┌─────────────────────────┐- │ WrappedEvent │- │ │- │ event: Event { │ ┌────────────────────────────┐- │ event, uuid, │ │ Event::Options │- │ distinct_id, │ │ cookieless_mode │- │ timestamp, │ │ disable_skew_correction │- │ session_id?, │ │ product_tour_id │- │ window_id?, │ │ process_person_profile │- │ options ─────────────┼─────▶└────────────────────────────┘- │ properties (RawValue)│- │ } │- │ uuid: Uuid (pre-parsed)│- │ adjusted_timestamp │- │ result: EventResult │- │ destination: Destination│- │ force_disable_* │- └───────────┬─────────────┘- │ serialize(ctx)- ▼- ┌──────────────────────────────┐- │ IngestionEvent (Kafka msg) │- │ │- │ uuid, distinct_id, ip, │- │ token, event, timestamp, │- │ now, sent_at, │- │ is_cookieless_mode, │- │ historical_migration, │- │ data: IngestionData (JSON) │- │ ├── event │- │ ├── distinct_id │- │ ├── uuid │- │ ├── timestamp (original) │- │ └── properties (merged) │- │ ├── original props │- │ ├── $session_id │- │ ├── $window_id │- │ ├── $cookieless_mode │- │ ├── $ignore_sent_at │- │ ├── $product_tour_id │- │ └── $process_person_* │- └──────────────────────────────┘-```--### Property injection (surgery)--The v1 schema promotes `session_id`, `window_id`, and `Options` fields-to typed, top-level event fields. Legacy ingestion workers expect these-inside `event.properties` under `$`-prefixed keys.--Rather than deserializing the entire properties blob (which is forwarded-as opaque `Box<RawValue>`), `build_property_injections` performs-string-level JSON surgery:--1. Build a comma-separated fragment of `"$key":value` pairs for- non-`None` option fields.-2. If the fragment is non-empty, splice it into the raw JSON object- just before the closing `}`.-3. Validate the result via `RawValue::from_string`.--This avoids a full `serde_json::Value` round-trip and preserves the-original property ordering and formatting.--| v1 field | Injected property key | Notes |-|---|---|---|-| `session_id` | `$session_id` | |-| `window_id` | `$window_id` | |-| `options.cookieless_mode` | `$cookieless_mode` | |-| `options.disable_skew_correction` | `$ignore_sent_at` | Legacy rename. v1 reads only `disable_skew_correction` |-| `options.product_tour_id` | `$product_tour_id` | |-| `options.process_person_profile` | `$process_person_profile` | |--`RawOptions::validate` reads the four expected option keys before injection and ignores every other key:--- Boolean options accept booleans, numbers (zero is off), `true`/`t`/`yes`/`y`/`on`/`1` and `false`/`f`/`no`/`n`/`off`/`0` in any case, and numeric strings. `null` and blank strings mean "not set".-- `product_tour_id` accepts a non-empty string, forwarded unchanged, or an integer, forwarded as its decimal string. `null` and blank strings mean "not set".-- Any other value for an expected key drops the event with `invalid_options`, and emits the `invalid_options` ingestion warning, whose `invalidOptions` detail names the failed keys.-- The batch-level `capture_internal` and `historical_migration` flags use the same boolean reader. An unreadable value means "not set" and never fails the batch.--### IngestionEvent / IngestionData--`IngestionEvent` is the Kafka message payload, field-order-compatible-with `common_types::CapturedEvent` so downstream deserializers work-unchanged.--`IngestionData` is the double-encoded `data` field within-`IngestionEvent`. It carries the event name, distinct_id, uuid,-original (un-adjusted) timestamp, and the merged properties blob.--Fields intentionally omitted vs the legacy `RawEvent`:--| Omitted field | Reason |-|---|---|-| `token` | v1 uses Authorization header; downstream handles absence |-| `offset` | Dead field; Node.js ingestion parses but never reads it |-| `$set`/`$set_once` (top-level) | Legacy Python SDK cruft; v1 schema sends these inside `properties` |--### IP redaction--`capture_internal` requests (events the Django app sends on behalf of a customer team) have their IP-redacted to `127.0.0.1` in both `serialize` (the `ip` field on-`IngestionEvent`) and `partition_key` (cookieless mode).-------## 11. Testing--### KafkaProducerTrait enables mock injection--`KafkaSink<P: KafkaProducerTrait>` is generic over the producer. Tests-instantiate `KafkaSink<MockProducer>` to exercise the full publish-pipeline without real Kafka.--### MockProducer--Builder-style API for configuring failure scenarios:--| Method | Effect |-|---|---|-| `with_send_error(fn)` | Every `send()` returns `Err(fn())` |-| `with_send_error_count(n)` | First `n` sends fail, then succeed |-| `with_ack_error(fn)` | Ack futures resolve to `Err(fn())` |-| `with_ack_delay(duration)` | Ack futures sleep before resolving |-| `with_not_ready()` | `is_ready()` returns `false` |--Sent records are captured as `OwnedProduceRecord` (owned copies of-`ProduceRecord`) and inspectable via:--| Method | Purpose |-|---|---|-| `record_count()` | Number of records sent |-| `with_records(\|recs\| ...)` | Inspect captured records under lock |-| `clear()` | Reset captured records |--### Test infrastructure (sink_tests.rs)--`FakeEvent` implements `Event` with configurable destination, publish-flag, partition key, payload, and headers. Serialize-failure scenarios-(errors, panics) are covered in `prepare.rs` tests, not the sink — the-sink only ever sees already-prepared events.--`TestHarness` / `HarnessBuilder` wrap sink construction with a-`lifecycle::Manager` so tests can verify health heartbeat interactions.-Builder options include:--| Builder method | Controls |-|---|---|-| `produce_timeout(d)` | Per-sink ack deadline |-| `send_error(fn)` | Inject send-path errors |-| `send_error_count(n)` | Limit send errors to first `n` |-| `ack_error(fn)` | Inject ack-path errors |-| `ack_delay(d)` | Simulate slow acks / timeouts |-| `not_ready()` | Producer health gate fails |-| `with_liveness(deadline, poll)` | Custom liveness timing for health tests |--### Analytics event serialization tests--`v1::analytics::types` has a comprehensive test suite validating:--- **Round-trip parity**: `WrappedEvent::serialize` output- deserializes as `common_types::CapturedEvent` + `RawEvent`, verifying- field-by-field compatibility with legacy capture.-- **Property injection**: all option fields are correctly injected into- properties with `$`-prefixed keys.-- **IP redaction**: `capture_internal` → `127.0.0.1`.-- **Partition key × destination × person-processing matrix**: key- presence/absence for all combinations.-- **Header completeness**: distinct_id, event, uuid, timestamp,- session_id, force_disable_*, DLQ headers.diff --git a/rust/capture/src/v1/sinks/constants.rs b/rust/capture/src/v1/sinks/constants.rsdeleted file mode 100644index b751bd43e233..000000000000--- a/rust/capture/src/v1/sinks/constants.rs+++ /dev/null@@ -1,26 +0,0 @@-use std::time::Duration;--pub(crate) const DEFAULT_PRODUCE_TIMEOUT: Duration = Duration::from_secs(30);--// Lifecycle Handle configuration for v1 sinks.-//-// Timing chain (worst-case detection of a fully broken sink):-// 1. Last successful heartbeat at t=0-// 2. publish_batch runs for up to produce_timeout (30s), returns with 0 successes -> no heartbeat-// 3. stats callback fires every statistics_interval_ms (10s) but brokers are down -> no heartbeat-// 4. At t=30s liveness_deadline expires-// 5. Next health_poll (within 2s) detects stall, stall_count=1 >= stall_threshold=1-// 6. Global shutdown triggered at ~t=32s-//-// This matches the existing v0 capture setup (setup.rs + main.rs).--/// The handle must receive a report_healthy() call within this window or-/// the health poll considers it stalled. Set equal to produce_timeout so-/// a single full-timeout batch is the minimum detection unit.-#[allow(dead_code)]-pub(crate) const SINK_LIVENESS_DEADLINE: Duration = Duration::from_secs(30);--/// Consecutive stalled health polls before triggering global shutdown.-/// 1 = immediate (first missed deadline triggers shutdown). Matches v0.-#[allow(dead_code)]-pub(crate) const SINK_STALL_THRESHOLD: u32 = 1;diff --git a/rust/capture/src/v1/sinks/event.rs b/rust/capture/src/v1/sinks/event.rsdeleted file mode 100644index 33436d7f830b..000000000000--- a/rust/capture/src/v1/sinks/event.rs+++ /dev/null@@ -1,46 +0,0 @@-use common_types::CapturedEventHeaders;-use uuid::Uuid;--use crate::ordering::OrderingGuarantee;-use crate::v1::context::RequestContext;-use crate::v1::sinks::Destination;--/// Transport-agnostic trait declaring an event's identity, routing intent,-/// metadata, and serialization. The [`Sink`](super::sink::Sink) implementation-/// resolves `destination()` to a concrete backend target using its own config.-pub trait Event: Send + Sync {- /// Pre-parsed UUID for result correlation.- fn uuid(&self) -> Uuid;-- /// Whether this event should be published. Events returning false are- /// silently skipped by the Sink -- no `SinkResult` is returned for them.- fn should_publish(&self) -> bool;-- /// Semantic routing destination. The Sink resolves this to a concrete- /// backend target (e.g. Kafka topic, S3 bucket) using its own config.- fn destination(&self) -> &Destination;-- /// Resolve the full set of transport headers for this event, using the- /// supplied [`RequestContext`] for batch-scoped fields (token, now,- /// historical_migration) alongside any event-owned fields. Sinks convert- /// the returned [`CapturedEventHeaders`] to their backend-specific format- /// (e.g. `rdkafka::message::OwnedHeaders` via the `From` impl in- /// `common_types`).- fn headers(&self, ctx: &RequestContext) -> CapturedEventHeaders;-- /// Return the partition key for this event. Whether the sink actually uses- /// it is decided by [`Event::ordering`], not by inspecting headers.- fn partition_key(&self, ctx: &RequestContext) -> String;-- /// The ordering guarantee this event's destination must preserve. The sink- /// realizes [`OrderingGuarantee::None`] by publishing without a partition- /// key so the broker round-robins; every other guarantee uses- /// [`Event::partition_key`], which supplies the value that preserves it.- fn ordering(&self) -> OrderingGuarantee;-- /// Serialize the event payload and return the raw bytes. `Bytes` (not- /// `String`) so non-UTF-8 / binary payloads (e.g. replay) share this- /// contract, and so a serialized payload can be cheaply cloned across- /// multiple sinks (dual-write) without re-encoding.- fn serialize(&self, ctx: &RequestContext) -> anyhow::Result<bytes::Bytes>;-}diff --git a/rust/capture/src/v1/sinks/kafka/config.rs b/rust/capture/src/v1/sinks/kafka/config.rsdeleted file mode 100644index 47ee7782fd3f..000000000000--- a/rust/capture/src/v1/sinks/kafka/config.rs+++ /dev/null@@ -1,436 +0,0 @@-use envconfig::Envconfig;--use crate::v1::sinks::types::Destination;--/// Per-sink Kafka producer configuration. Loaded via `Envconfig::init_from_hashmap`-/// from env vars under the `KAFKA_` sub-prefix of a sink's env namespace.-///-/// For example, for sink "msk" the env var `CAPTURE_V1_SINK_MSK_KAFKA_HOSTS`-/// is stripped to key `HOSTS` in the hashmap fed to this struct.-#[derive(Envconfig, Clone, Debug)]-pub struct Config {- // -- Connection --- /// Comma-separated broker list (e.g. "broker1:9092,broker2:9092").- pub hosts: String,- #[envconfig(default = "false")]- pub tls: bool,- #[envconfig(default = "")]- pub client_id: String,-- // -- Producer tuning (maps to librdkafka settings) --- #[envconfig(default = "20")]- pub linger_ms: u32,- /// In-memory producer queue size in MiB (converted to KB for rdkafka).- #[envconfig(default = "400")]- pub queue_mib: u32,- /// Time before we stop retrying producing a message (ms).- /// Allows ~6 retry cycles at 5s socket timeout.- #[envconfig(default = "30000")]- pub message_timeout_ms: u32,- #[envconfig(default = "1000000")]- pub message_max_bytes: u32,- /// none, gzip, snappy, lz4, zstd- #[envconfig(default = "lz4")]- pub compression_codec: String,- #[envconfig(default = "all")]- pub acks: String,- #[envconfig(default = "false")]- pub enable_idempotence: bool,- #[envconfig(default = "10000")]- pub batch_num_messages: u32,- #[envconfig(default = "1000000")]- pub batch_size: u32,- /// How often librdkafka refreshes topic metadata from brokers (ms).- /// Low value ensures fast leader discovery on broker failover.- #[envconfig(default = "5000")]- pub metadata_refresh_interval_ms: u32,- /// Max age of cached metadata before forced refresh (ms). Should be- /// `>= 3x` metadata_refresh_interval_ms. Keeping this low ensures- /// stale broker state is flushed promptly after recovery.- #[envconfig(default = "15000")]- pub metadata_max_age_ms: u32,- /// Timeout for socket operations (ms). Lower = faster dead broker detection.- #[envconfig(default = "5000")]- pub socket_timeout_ms: u32,- /// How often librdkafka fires the stats callback (ms). Controls the- /// refresh cadence for broker health, queue depth, and RTT gauges.- #[envconfig(default = "10000")]- pub statistics_interval_ms: u32,-- // -- v0 parity settings (defaults from production charts/argocd/capture) --- /// Partitioning strategy. Must be murmur2_random for v0 parity- /// (python-kafka compat). librdkafka default varies by version.- #[envconfig(default = "murmur2_random")]- pub partitioner: String,- /// Max retry attempts per message. Production default: 4 (tuned for- /// MSK failover with socket_timeout_ms=5000, message_timeout_ms=30000).- #[envconfig(default = "4")]- pub max_retries: u32,- #[envconfig(default = "1000000")]- pub max_in_flight_requests: u32,- /// How long (ms) the producer sticks to a random partition for keyless- /// messages before switching. Affects distribution of events with- /// force_disable_person_processing (no partition key).- #[envconfig(default = "10")]- pub sticky_partitioning_linger_ms: u32,-- /// IP family for broker connections. Empty = let librdkafka decide (default);- /// "v4" / "v6" / "any" force-select. Matches legacy KAFKA_BROKER_ADDRESS_FAMILY.- #[envconfig(default = "")]- pub broker_address_family: String,- /// Log broker connection close events. librdkafka default = true.- #[envconfig(default = "true")]- pub log_connection_close: bool,- /// Max messages buffered in the producer queue. librdkafka default = 100_000.- #[envconfig(default = "100000")]- pub queue_buffering_max_messages: u32,- /// Upper bound on exponential retry backoff (ms). librdkafka default = 1000.- #[envconfig(default = "1000")]- pub retry_backoff_max_ms: u32,- /// TCP socket send buffer size in bytes. 0 = use OS default. librdkafka default = 0.- #[envconfig(default = "0")]- pub socket_send_buffer_bytes: u32,- /// TCP socket receive buffer size in bytes. 0 = use OS default. librdkafka default = 0.- #[envconfig(default = "0")]- pub socket_receive_buffer_bytes: u32,-- // -- Topics (all required -- envconfig errors if any are missing) --- pub topic_main: String,- pub topic_historical: String,- pub topic_overflow: String,- pub topic_dlq: String,-- // -- Non-analytics topics (also required) --- pub topic_exception: String,- pub topic_heatmap: String,- pub topic_client_ingestion_warning: String,-- /// Dedicated topic for `$ai_*` events. Not meant to be set via per-sink- /// env: setup injects the deployment-level `CAPTURE_OUTPUT_AI_MAIN_TOPIC` into- /// every sink config, overwriting whatever the env parse produced.- #[envconfig(default = "events_plugin_ingestion_ai")]- pub topic_ai: String,-- /// Optional overflow topic for the AI lane. Like `topic_ai`, injected at- /// setup from the deployment-level `CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC`; unset- /// means the pipeline never produces `Destination::AiEventsOverflow`.- pub topic_ai_overflow: Option<String>,-}--const VALID_ACKS: &[&str] = &["0", "1", "-1", "all"];-const VALID_COMPRESSION: &[&str] = &["none", "gzip", "snappy", "lz4", "zstd"];--impl Config {- /// Validate kafka-specific configuration invariants that would otherwise- /// blow up at rdkafka producer creation or silently break runtime health.- pub fn validate(&self) -> anyhow::Result<()> {- anyhow::ensure!(!self.hosts.is_empty(), "empty kafka hosts");-- anyhow::ensure!(- self.queue_mib > 0,- "queue_mib must be > 0 (got 0, which makes the producer queue zero-size)"- );-- anyhow::ensure!(- VALID_ACKS.contains(&self.acks.as_str()),- "acks must be one of {VALID_ACKS:?} (got {:?})",- self.acks- );-- anyhow::ensure!(- VALID_COMPRESSION.contains(&self.compression_codec.as_str()),- "compression_codec must be one of {VALID_COMPRESSION:?} (got {:?})",- self.compression_codec- );-- anyhow::ensure!(- self.statistics_interval_ms > 0,- "statistics_interval_ms must be > 0 (0 disables stats callback, breaking health heartbeat)"- );-- anyhow::ensure!(- self.metadata_max_age_ms >= self.metadata_refresh_interval_ms * 3,- "metadata_max_age_ms ({}) should be >= 3x metadata_refresh_interval_ms ({}) \- for reliable metadata refresh after broker failover",- self.metadata_max_age_ms,- self.metadata_refresh_interval_ms- );-- Ok(())- }-- /// Resolve which topic to use for the given destination on this sink.- pub fn topic_for<'a>(&'a self, dest: &'a Destination) -> Option<&'a str> {- match dest {- Destination::AnalyticsMain => Some(&self.topic_main),- Destination::AnalyticsHistorical => Some(&self.topic_historical),- Destination::Overflow => Some(&self.topic_overflow),- Destination::Dlq => Some(&self.topic_dlq),- Destination::ExceptionErrorTracking => Some(&self.topic_exception),- Destination::HeatmapMain => Some(&self.topic_heatmap),- Destination::ClientIngestionWarning => Some(&self.topic_client_ingestion_warning),- Destination::AiEvents => Some(&self.topic_ai),- Destination::AiEventsOverflow => self.topic_ai_overflow.as_deref(),- Destination::Custom(t) => Some(t.as_str()),- Destination::Drop => None,- }- }-}--#[cfg(test)]-mod tests {- use std::collections::HashMap;-- use envconfig::Envconfig;- use rstest::rstest;-- use super::Config;- use crate::v1::sinks::Destination;-- fn required_kafka_env() -> HashMap<String, String> {- [- ("HOSTS", "localhost:9092"),- ("TOPIC_MAIN", "events_main"),- ("TOPIC_HISTORICAL", "events_hist"),- ("TOPIC_OVERFLOW", "events_overflow"),- ("TOPIC_DLQ", "events_dlq"),- ("TOPIC_EXCEPTION", "error_tracking_events"),- ("TOPIC_HEATMAP", "heatmaps_ingestion"),- ("TOPIC_CLIENT_INGESTION_WARNING", "events_plugin_ingestion"),- ]- .into_iter()- .map(|(k, v)| (k.to_string(), v.to_string()))- .collect()- }-- #[test]- fn all_fields_from_hashmap() {- let mut env = required_kafka_env();- env.insert("TLS".into(), "true".into());- env.insert("CLIENT_ID".into(), "my-client".into());- env.insert("LINGER_MS".into(), "50".into());- env.insert("QUEUE_MIB".into(), "800".into());- env.insert("MESSAGE_TIMEOUT_MS".into(), "30000".into());- env.insert("MESSAGE_MAX_BYTES".into(), "2000000".into());- env.insert("COMPRESSION_CODEC".into(), "lz4".into());- env.insert("ACKS".into(), "1".into());- env.insert("ENABLE_IDEMPOTENCE".into(), "true".into());- env.insert("BATCH_NUM_MESSAGES".into(), "5000".into());- env.insert("BATCH_SIZE".into(), "500000".into());- env.insert("METADATA_REFRESH_INTERVAL_MS".into(), "10000".into());- env.insert("METADATA_MAX_AGE_MS".into(), "30000".into());- env.insert("SOCKET_TIMEOUT_MS".into(), "30000".into());- env.insert("STATISTICS_INTERVAL_MS".into(), "5000".into());- env.insert("PARTITIONER".into(), "consistent_random".into());- env.insert("MAX_RETRIES".into(), "6".into());- env.insert("MAX_IN_FLIGHT_REQUESTS".into(), "500000".into());- env.insert("STICKY_PARTITIONING_LINGER_MS".into(), "20".into());- env.insert("BROKER_ADDRESS_FAMILY".into(), "v4".into());- env.insert("LOG_CONNECTION_CLOSE".into(), "false".into());- env.insert("QUEUE_BUFFERING_MAX_MESSAGES".into(), "250000".into());- env.insert("RETRY_BACKOFF_MAX_MS".into(), "2000".into());- env.insert("SOCKET_SEND_BUFFER_BYTES".into(), "65536".into());- env.insert("SOCKET_RECEIVE_BUFFER_BYTES".into(), "65536".into());-- let cfg = Config::init_from_hashmap(&env).unwrap();- assert_eq!(cfg.hosts, "localhost:9092");- assert!(cfg.tls);- assert_eq!(cfg.client_id, "my-client");- assert_eq!(cfg.linger_ms, 50);- assert_eq!(cfg.queue_mib, 800);- assert_eq!(cfg.message_timeout_ms, 30000);- assert_eq!(cfg.message_max_bytes, 2000000);- assert_eq!(cfg.compression_codec, "lz4");- assert_eq!(cfg.acks, "1");- assert!(cfg.enable_idempotence);- assert_eq!(cfg.batch_num_messages, 5000);- assert_eq!(cfg.batch_size, 500000);- assert_eq!(cfg.metadata_refresh_interval_ms, 10000);- assert_eq!(cfg.metadata_max_age_ms, 30000);- assert_eq!(cfg.socket_timeout_ms, 30000);- assert_eq!(cfg.statistics_interval_ms, 5000);- assert_eq!(cfg.partitioner, "consistent_random");- assert_eq!(cfg.max_retries, 6);- assert_eq!(cfg.max_in_flight_requests, 500000);- assert_eq!(cfg.sticky_partitioning_linger_ms, 20);- assert_eq!(cfg.broker_address_family, "v4");- assert!(!cfg.log_connection_close);- assert_eq!(cfg.queue_buffering_max_messages, 250000);- assert_eq!(cfg.retry_backoff_max_ms, 2000);- assert_eq!(cfg.socket_send_buffer_bytes, 65536);- assert_eq!(cfg.socket_receive_buffer_bytes, 65536);- assert_eq!(cfg.topic_main, "events_main");- }-- #[test]- fn defaults_applied() {- let env = required_kafka_env();- let cfg = Config::init_from_hashmap(&env).unwrap();- assert!(!cfg.tls);- assert_eq!(cfg.client_id, "");- assert_eq!(cfg.linger_ms, 20);- assert_eq!(cfg.queue_mib, 400);- assert_eq!(cfg.message_timeout_ms, 30000);- assert_eq!(cfg.message_max_bytes, 1000000);- assert_eq!(cfg.compression_codec, "lz4");- assert_eq!(cfg.acks, "all");- assert!(!cfg.enable_idempotence);- assert_eq!(cfg.batch_num_messages, 10000);- assert_eq!(cfg.batch_size, 1000000);- assert_eq!(cfg.metadata_refresh_interval_ms, 5000);- assert_eq!(cfg.metadata_max_age_ms, 15000);- assert_eq!(cfg.socket_timeout_ms, 5000);- assert_eq!(cfg.statistics_interval_ms, 10000);- assert_eq!(cfg.partitioner, "murmur2_random");- assert_eq!(cfg.max_retries, 4);- assert_eq!(cfg.max_in_flight_requests, 1000000);- assert_eq!(cfg.sticky_partitioning_linger_ms, 10);- assert_eq!(cfg.broker_address_family, "");- assert!(cfg.log_connection_close);- assert_eq!(cfg.queue_buffering_max_messages, 100000);- assert_eq!(cfg.retry_backoff_max_ms, 1000);- assert_eq!(cfg.socket_send_buffer_bytes, 0);- assert_eq!(cfg.socket_receive_buffer_bytes, 0);- }-- #[rstest]- #[case("HOSTS")]- #[case("TOPIC_MAIN")]- #[case("TOPIC_HISTORICAL")]- #[case("TOPIC_OVERFLOW")]- #[case("TOPIC_DLQ")]- #[case("TOPIC_EXCEPTION")]- #[case("TOPIC_HEATMAP")]- #[case("TOPIC_CLIENT_INGESTION_WARNING")]- fn missing_required_field_errors(#[case] key: &str) {- let mut env = required_kafka_env();- env.remove(key);- assert!(- Config::init_from_hashmap(&env).is_err(),- "{key} should be required"- );- }-- #[test]- fn numeric_field_parsing_error() {- let mut env = required_kafka_env();- env.insert("LINGER_MS".into(), "not_a_number".into());- assert!(Config::init_from_hashmap(&env).is_err());- }-- // -- validate() tests ---- type Mutator = (&'static str, fn(&mut Config));-- fn valid_config() -> Config {- Config::init_from_hashmap(&required_kafka_env()).unwrap()- }-- #[test]- fn validate_accepts_defaults() {- assert!(valid_config().validate().is_ok());- }-- #[test]- fn validate_rejects_bad_configs() {- let cases: &[Mutator] = &[- ("empty_hosts", |c| c.hosts = "".into()),- ("queue_mib_zero", |c| c.queue_mib = 0),- ("acks_garbage", |c| c.acks = "banana".into()),- ("compression_garbage", |c| {- c.compression_codec = "brotli".into()- }),- ("stats_interval_zero", |c| c.statistics_interval_ms = 0),- ("metadata_age_too_low", |c| {- c.metadata_refresh_interval_ms = 5000;- c.metadata_max_age_ms = 10000;- }),- ];-- for (label, mutate) in cases {- let mut cfg = valid_config();- mutate(&mut cfg);- assert!(- cfg.validate().is_err(),- "case '{label}' should fail validation"- );- }- }-- #[test]- fn validate_accepts_valid_acks_values() {- for acks in ["0", "1", "-1", "all"] {- let mut cfg = valid_config();- cfg.acks = acks.to_string();- assert!(cfg.validate().is_ok(), "acks={acks} should be valid");- }- }-- #[test]- fn validate_accepts_all_compression_codecs() {- for codec in ["none", "gzip", "snappy", "lz4", "zstd"] {- let mut cfg = valid_config();- cfg.compression_codec = codec.to_string();- assert!(cfg.validate().is_ok(), "codec={codec} should be valid");- }- }-- #[test]- fn validate_metadata_age_boundary() {- let mut cfg = valid_config();- cfg.metadata_refresh_interval_ms = 5000;-- cfg.metadata_max_age_ms = 14999;- assert!(cfg.validate().is_err(), "just under 3x should fail");-- cfg.metadata_max_age_ms = 15000;- assert!(cfg.validate().is_ok(), "exactly 3x should pass");- }-- #[rstest]- #[case(Destination::AnalyticsMain, Some("events_main"))]- #[case(Destination::AnalyticsHistorical, Some("events_hist"))]- #[case(Destination::Overflow, Some("events_overflow"))]- #[case(Destination::Dlq, Some("events_dlq"))]- #[case(Destination::ExceptionErrorTracking, Some("error_tracking_events"))]- #[case(Destination::HeatmapMain, Some("heatmaps_ingestion"))]- #[case(Destination::ClientIngestionWarning, Some("events_plugin_ingestion"))]- #[case(Destination::Drop, None)]- fn topic_for_resolves_destination(#[case] dest: Destination, #[case] expected: Option<&str>) {- let cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();- assert_eq!(cfg.topic_for(&dest), expected);- }-- #[test]- fn topic_ai_defaults() {- let cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();- assert_eq!(cfg.topic_ai, "events_plugin_ingestion_ai");- assert_eq!(- cfg.topic_for(&Destination::AiEvents),- Some("events_plugin_ingestion_ai")- );- assert_eq!(cfg.topic_ai_overflow, None);- assert_eq!(cfg.topic_for(&Destination::AiEventsOverflow), None);- }-- #[test]- fn topic_ai_overflow_present_resolves_destination() {- // Set the field directly, mirroring how setup injects- // CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC into sink configs after env loading.- let mut cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();- cfg.topic_ai_overflow = Some("ai_events_overflow".to_string());- assert_eq!(- cfg.topic_for(&Destination::AiEventsOverflow),- Some("ai_events_overflow")- );- }-- #[test]- fn topic_ai_present_resolves_destination() {- // Set the field directly, mirroring how setup injects CAPTURE_OUTPUT_AI_MAIN_TOPIC- // into sink configs after env loading.- let mut cfg = Config::init_from_hashmap(&required_kafka_env()).unwrap();- cfg.topic_ai = "ai_events".to_string();- assert_eq!(cfg.topic_for(&Destination::AiEvents), Some("ai_events"));- }-}diff --git a/rust/capture/src/v1/sinks/kafka/constants.rs b/rust/capture/src/v1/sinks/kafka/constants.rsdeleted file mode 100644index 821c792f5ab7..000000000000--- a/rust/capture/src/v1/sinks/kafka/constants.rs+++ /dev/null@@ -1,49 +0,0 @@-// ----------------------------------------------------------------------------// Kafka sink metric keys-// -----------------------------------------------------------------------------/// Per-event outcome counter (success, retriable, fatal, timeout).-pub(super) const KAFKA_PUBLISH_TOTAL: &str = "capture_v1_kafka_publish_total";--/// Per-event broker-ack latency histogram.-pub(super) const KAFKA_ACK_DURATION_SECONDS: &str = "capture_v1_kafka_ack_duration_seconds";--/// Per-batch enqueue wall-time histogram.-pub(super) const KAFKA_ENQUEUE_DURATION_SECONDS: &str = "capture_v1_kafka_enqueue_duration_seconds";--/// Produce-level error counter (distinct from ack errors).-pub(super) const KAFKA_PRODUCE_ERRORS_TOTAL: &str = "capture_v1_kafka_produce_errors_total";--/// Client-level rdkafka error counter.-pub(super) const KAFKA_CLIENT_ERRORS_TOTAL: &str = "capture_v1_kafka_client_errors_total";--/// Producer internal queue depth gauge (messages).-pub(super) const KAFKA_PRODUCER_QUEUE_DEPTH: &str = "capture_v1_kafka_producer_queue_depth";--/// Producer internal queue size gauge (bytes).-pub(super) const KAFKA_PRODUCER_QUEUE_BYTES: &str = "capture_v1_kafka_producer_queue_bytes";--/// Producer queue utilization gauge (0.0–1.0).-pub(super) const KAFKA_PRODUCER_QUEUE_UTILIZATION: &str =- "capture_v1_kafka_producer_queue_utilization";--/// Average batch size (bytes) gauge from rdkafka stats.-pub(super) const KAFKA_BATCH_SIZE_BYTES_AVG: &str = "capture_v1_kafka_batch_size_bytes_avg";--/// Connected brokers gauge.-pub(super) const KAFKA_BROKER_CONNECTED: &str = "capture_v1_kafka_broker_connected";--/// Broker round-trip time (microseconds) histogram.-pub(super) const KAFKA_BROKER_RTT_US: &str = "capture_v1_kafka_broker_rtt_us";--/// Broker internal latency (microseconds) histogram.-pub(super) const KAFKA_BROKER_INT_LATENCY_US: &str = "capture_v1_kafka_broker_int_latency_us";--/// Broker outbound buffer latency (microseconds) histogram.-pub(super) const KAFKA_BROKER_OUTBUF_LATENCY_US: &str = "capture_v1_kafka_broker_outbuf_latency_us";--/// Broker TX error counter.-pub(super) const KAFKA_BROKER_TX_ERRORS_TOTAL: &str = "capture_v1_kafka_broker_tx_errors_total";--/// Broker RX error counter.-pub(super) const KAFKA_BROKER_RX_ERRORS_TOTAL: &str = "capture_v1_kafka_broker_rx_errors_total";diff --git a/rust/capture/src/v1/sinks/kafka/context.rs b/rust/capture/src/v1/sinks/kafka/context.rsdeleted file mode 100644index d9e62ea59ff4..000000000000--- a/rust/capture/src/v1/sinks/kafka/context.rs+++ /dev/null@@ -1,161 +0,0 @@-use std::sync::Arc;--use metrics::{counter, gauge};-use rdkafka::error::KafkaError;-use tracing::error;--use super::constants::*;-use super::types::error_code_tag;-use crate::v1::sinks::SinkName;--const BROKER_STATE_UP: &str = "UP";--/// Emit min/avg/max/stddev + p50/p90/p95/p99 gauges for an rdkafka window-/// stat, tagged by `quantile` and `broker`.-fn emit_window_stats(- metric: &'static str,- w: &rdkafka::statistics::Window,- sink: &'static str,- mode: &'static str,- broker: &Arc<str>,-) {- for (quantile, value) in [- ("min", w.min),- ("avg", w.avg),- ("max", w.max),- ("stddev", w.stddev),- ("p50", w.p50),- ("p90", w.p90),- ("p95", w.p95),- ("p99", w.p99),- ] {- gauge!(- metric,- "cluster" => sink,- "mode" => mode,- "quantile" => quantile,- "broker" => Arc::clone(broker),- )- .set(value as f64);- }-}--// ----------------------------------------------------------------------------// KafkaContext-// -----------------------------------------------------------------------------pub(crate) struct KafkaContext {- handle: lifecycle::Handle,- sink: SinkName,- mode: &'static str,-}--impl KafkaContext {- pub fn new(handle: lifecycle::Handle, sink: SinkName, mode: &'static str) -> Self {- Self { handle, sink, mode }- }-}--impl rdkafka::ClientContext for KafkaContext {- fn error(&self, err: KafkaError, reason: &str) {- let sink = self.sink.as_str();- let mode = self.mode;- let tag = err- .rdkafka_error_code()- .map(error_code_tag)- .unwrap_or("unknown");- error!(- sink = sink,- mode = mode,- error = %err,- error_tag = tag,- reason = reason,- "rdkafka client error"- );- counter!(- KAFKA_CLIENT_ERRORS_TOTAL,- "cluster" => sink,- "mode" => mode,- "error" => tag,- )- .increment(1);- }-- fn stats(&self, stats: rdkafka::Statistics) {- let sink = self.sink.as_str();- let mode = self.mode;-- let brokers_up = stats.brokers.values().any(|b| b.state == BROKER_STATE_UP);- if brokers_up {- self.handle.report_healthy();- } else if !stats.brokers.is_empty() {- error!(- sink = sink,- mode = mode,- broker_count = stats.brokers.len(),- "all brokers DOWN for sink"- );- counter!(- KAFKA_CLIENT_ERRORS_TOTAL,- "cluster" => sink,- "mode" => mode,- "error" => "all_brokers_down",- )- .increment(1);- }-- // metric label key "cluster" kept for dashboard backward compatibility- gauge!(KAFKA_PRODUCER_QUEUE_DEPTH,- "cluster" => sink, "mode" => mode)- .set(stats.msg_cnt as f64);- gauge!(KAFKA_PRODUCER_QUEUE_BYTES,- "cluster" => sink, "mode" => mode)- .set(stats.msg_size as f64);- if stats.msg_max > 0 {- gauge!(KAFKA_PRODUCER_QUEUE_UTILIZATION,- "cluster" => sink, "mode" => mode)- .set(stats.msg_cnt as f64 / stats.msg_max as f64);- }-- for (topic, ts) in stats.topics {- gauge!(KAFKA_BATCH_SIZE_BYTES_AVG,- "cluster" => sink, "mode" => mode, "topic" => topic)- .set(ts.batchsize.avg as f64);- }-- for bs in stats.brokers.values() {- let id: Arc<str> = Arc::from(bs.nodeid.to_string());- gauge!(KAFKA_BROKER_CONNECTED,- "cluster" => sink, "mode" => mode, "broker" => Arc::clone(&id))- .set(if bs.state == BROKER_STATE_UP {- 1.0- } else {- 0.0- });- // Broker round-trip latency.- if let Some(rtt) = &bs.rtt {- emit_window_stats(KAFKA_BROKER_RTT_US, rtt, sink, mode, &id);- }- // Internal queue time (linger + backlog).- if let Some(int_latency) = &bs.int_latency {- emit_window_stats(KAFKA_BROKER_INT_LATENCY_US, int_latency, sink, mode, &id);- }- // Output buffer time before wire send.- if let Some(outbuf_latency) = &bs.outbuf_latency {- emit_window_stats(- KAFKA_BROKER_OUTBUF_LATENCY_US,- outbuf_latency,- sink,- mode,- &id,- );- }- counter!(KAFKA_BROKER_TX_ERRORS_TOTAL,- "cluster" => sink, "mode" => mode, "broker" => Arc::clone(&id))- .absolute(bs.txerrs);- counter!(KAFKA_BROKER_RX_ERRORS_TOTAL,- "cluster" => sink, "mode" => mode, "broker" => id)- .absolute(bs.rxerrs);- }- }-}diff --git a/rust/capture/src/v1/sinks/kafka/mock.rs b/rust/capture/src/v1/sinks/kafka/mock.rsdeleted file mode 100644index ea61b9d812e4..000000000000--- a/rust/capture/src/v1/sinks/kafka/mock.rs+++ /dev/null@@ -1,183 +0,0 @@-use std::future::Future;-use std::pin::Pin;-use std::sync::atomic::{AtomicU32, Ordering};-use std::sync::{Arc, Mutex};-use std::time::Duration;--use rdkafka::error::KafkaError;-use rdkafka::message::{Headers, OwnedHeaders};--use crate::v1::sinks::kafka::producer::{ProduceError, ProduceRecord};-use crate::v1::sinks::SinkName;--// ----------------------------------------------------------------------------// OwnedProduceRecord — owned copy for test assertions-// -----------------------------------------------------------------------------#[derive(Debug)]-pub struct OwnedProduceRecord {- pub topic: String,- pub key: Option<String>,- pub payload: String,- pub headers: Vec<(String, Option<String>)>,-}--impl OwnedProduceRecord {- /// The value of a wire header, or `None` when it was not stamped.- pub fn header(&self, key: &str) -> Option<&str> {- self.headers- .iter()- .find(|(k, _)| k == key)- .and_then(|(_, v)| v.as_deref())- }-}--/// Headers travel to the broker as bytes, so tests read them back the way a-/// consumer would rather than trusting the typed struct they came from.-fn owned_headers(headers: &OwnedHeaders) -> Vec<(String, Option<String>)> {- (0..headers.count())- .map(|i| {- let h = headers.get(i);- (- h.key.to_owned(),- h.value.map(|v| String::from_utf8_lossy(v).into_owned()),- )- })- .collect()-}--impl<'a> From<ProduceRecord<'a>> for OwnedProduceRecord {- fn from(r: ProduceRecord<'a>) -> Self {- Self::from(&r)- }-}--impl<'a> From<&ProduceRecord<'a>> for OwnedProduceRecord {- fn from(r: &ProduceRecord<'a>) -> Self {- Self {- topic: r.topic.to_owned(),- key: r.key.map(str::to_owned),- payload: String::from_utf8_lossy(r.payload).into_owned(),- headers: owned_headers(&r.headers),- }- }-}--// ----------------------------------------------------------------------------// MockProducer-// -----------------------------------------------------------------------------/// Mock Kafka producer for testing. Captures sent records and supports-/// configurable error injection and ack delays.-pub struct MockProducer {- sink: SinkName,- records: Arc<Mutex<Vec<OwnedProduceRecord>>>,- send_error: Option<fn() -> ProduceError>,- send_error_remaining: Arc<AtomicU32>,- ack_error: Option<fn() -> ProduceError>,- ack_delay: Option<Duration>,- ready_override: Option<bool>,- handle: lifecycle::Handle,-}--impl MockProducer {- pub fn new(sink: SinkName, handle: lifecycle::Handle) -> Self {- Self {- sink,- records: Arc::new(Mutex::new(Vec::new())),- send_error: None,- send_error_remaining: Arc::new(AtomicU32::new(u32::MAX)),- ack_error: None,- ack_delay: None,- ready_override: None,- handle,- }- }-- pub fn with_send_error(mut self, f: fn() -> ProduceError) -> Self {- self.send_error = Some(f);- self- }-- /// Limit send errors to the first `n` calls. After `n` errors the- /// send_error function is bypassed and sends succeed normally.- pub fn with_send_error_count(mut self, n: u32) -> Self {- self.send_error_remaining = Arc::new(AtomicU32::new(n));- self- }-- pub fn with_ack_error(mut self, f: fn() -> ProduceError) -> Self {- self.ack_error = Some(f);- self- }-- pub fn with_ack_delay(mut self, d: Duration) -> Self {- self.ack_delay = Some(d);- self- }-- pub fn with_not_ready(mut self) -> Self {- self.ready_override = Some(false);- self- }-- pub fn record_count(&self) -> usize {- self.records.lock().unwrap().len()- }-- pub fn with_records<F, R>(&self, f: F) -> R- where- F: FnOnce(&[OwnedProduceRecord]) -> R,- {- let guard = self.records.lock().unwrap();- f(&guard)- }-- pub fn clear(&self) {- self.records.lock().unwrap().clear();- }-}--impl super::KafkaProducerTrait for MockProducer {- type Ack = Pin<Box<dyn Future<Output = Result<(), ProduceError>> + Send>>;-- fn send<'a>(- &self,- record: ProduceRecord<'a>,- ) -> Result<Self::Ack, (ProduceError, ProduceRecord<'a>)> {- if let Some(err_fn) = &self.send_error {- let remaining = self.send_error_remaining.load(Ordering::Relaxed);- if remaining > 0 {- if remaining != u32::MAX {- self.send_error_remaining.fetch_sub(1, Ordering::Relaxed);- }- return Err((err_fn(), record));- }- }- self.records.lock().unwrap().push((&record).into());- let ack_error = self.ack_error;- let delay = self.ack_delay;- Ok(Box::pin(async move {- if let Some(d) = delay {- tokio::time::sleep(d).await;- }- match ack_error {- Some(err_fn) => Err(err_fn()),- None => Ok(()),- }- }))- }-- fn flush(&self, _: Duration) -> Result<(), KafkaError> {- Ok(())- }-- fn is_ready(&self) -> bool {- self.ready_override- .unwrap_or_else(|| self.handle.is_healthy())- }-- fn sink_name(&self) -> SinkName {- self.sink- }-}diff --git a/rust/capture/src/v1/sinks/kafka/mod.rs b/rust/capture/src/v1/sinks/kafka/mod.rsdeleted file mode 100644index 5be141aa74bd..000000000000--- a/rust/capture/src/v1/sinks/kafka/mod.rs+++ /dev/null@@ -1,34 +0,0 @@-pub mod config;-pub mod constants;-pub mod context;-pub mod mock;-pub mod producer;-pub mod sink;-pub mod types;--#[cfg(test)]-mod sink_tests;--pub use sink::KafkaSink;--use std::future::Future;-use std::time::Duration;--use rdkafka::error::KafkaError;--use crate::v1::sinks::SinkName;-use producer::{ProduceError, ProduceRecord};--/// Trait abstracting a Kafka producer for testability.-/// `KafkaProducer` is the real impl; `MockProducer` is the test impl.-pub trait KafkaProducerTrait: Send + Sync {- type Ack: Future<Output = Result<(), ProduceError>> + Send;-- fn send<'a>(- &self,- record: ProduceRecord<'a>,- ) -> Result<Self::Ack, (ProduceError, ProduceRecord<'a>)>;- fn flush(&self, timeout: Duration) -> Result<(), KafkaError>;- fn is_ready(&self) -> bool;- fn sink_name(&self) -> SinkName;-}diff --git a/rust/capture/src/v1/sinks/kafka/producer.rs b/rust/capture/src/v1/sinks/kafka/producer.rsdeleted file mode 100644index 42c8313df747..000000000000--- a/rust/capture/src/v1/sinks/kafka/producer.rs+++ /dev/null@@ -1,289 +0,0 @@-use std::future::Future;-use std::pin::Pin;-use std::task::{Context, Poll};-use std::time::Duration;--use metrics::counter;-use rdkafka::error::{KafkaError, RDKafkaErrorCode};-use rdkafka::message::OwnedHeaders;-use rdkafka::producer::{DeliveryFuture, FutureProducer, FutureRecord, Producer};-use rdkafka::ClientConfig;-use tracing::{error, info};--use super::constants::KAFKA_CLIENT_ERRORS_TOTAL;-use super::types::error_code_tag;-use crate::v1::sinks::kafka::config::Config as KafkaConfig;-use crate::v1::sinks::kafka::context::KafkaContext;-use crate::v1::sinks::SinkName;--// ----------------------------------------------------------------------------// ProduceError-// -----------------------------------------------------------------------------#[derive(Debug, thiserror::Error)]-pub enum ProduceError {- #[error("event too big: {message}")]- EventTooBig { message: String },-- #[error("kafka error: {code}")]- Kafka { code: RDKafkaErrorCode },-- #[error("delivery cancelled (timeout in librdkafka)")]- DeliveryCancelled,-}--impl ProduceError {- pub fn is_retriable(&self) -> bool {- match self {- Self::EventTooBig { .. } => false,- Self::Kafka { code } => !is_fatal_kafka_error(*code),- Self::DeliveryCancelled => true,- }- }-- pub fn error_code(&self) -> Option<RDKafkaErrorCode> {- match self {- Self::Kafka { code } => Some(*code),- _ => None,- }- }-- pub fn is_queue_full(&self) -> bool {- matches!(- self,- Self::Kafka {- code: RDKafkaErrorCode::QueueFull,- }- )- }-- /// Stable, low-cardinality tag for metrics and log aggregation.- pub fn as_tag(&self) -> &'static str {- match self {- Self::EventTooBig { .. } => "event_too_big",- Self::DeliveryCancelled => "delivery_cancelled",- Self::Kafka { code } => error_code_tag(*code),- }- }-}--// ----------------------------------------------------------------------------// ProduceRecord-// -----------------------------------------------------------------------------#[derive(Debug)]-pub struct ProduceRecord<'a> {- pub topic: &'a str,- pub key: Option<&'a str>,- pub payload: &'a [u8],- pub headers: OwnedHeaders,-}--// ----------------------------------------------------------------------------// SendHandle-// -----------------------------------------------------------------------------pub struct SendHandle {- inner: DeliveryFuture,-}--impl Future for SendHandle {- type Output = Result<(), ProduceError>;-- fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {- match Pin::new(&mut self.inner).poll(cx) {- Poll::Pending => Poll::Pending,- Poll::Ready(Err(_)) => Poll::Ready(Err(ProduceError::DeliveryCancelled)),- Poll::Ready(Ok(Err((e, _)))) => Poll::Ready(Err(produce_error_from_kafka(e))),- Poll::Ready(Ok(Ok(_))) => Poll::Ready(Ok(())),- }- }-}--// ----------------------------------------------------------------------------// KafkaProducer-// -----------------------------------------------------------------------------pub struct KafkaProducer {- inner: FutureProducer<KafkaContext>,- handle: lifecycle::Handle,- sink: SinkName,-}--impl KafkaProducer {- pub fn new(- sink: SinkName,- config: &KafkaConfig,- handle: lifecycle::Handle,- capture_mode: &'static str,- ) -> anyhow::Result<Self> {- let ctx = KafkaContext::new(handle.clone(), sink, capture_mode);-- let mut client_config = ClientConfig::new();- client_config- .set("bootstrap.servers", &config.hosts)- .set(- "statistics.interval.ms",- config.statistics_interval_ms.to_string(),- )- .set("linger.ms", config.linger_ms.to_string())- .set("message.timeout.ms", config.message_timeout_ms.to_string())- .set("message.max.bytes", config.message_max_bytes.to_string())- .set("compression.codec", &config.compression_codec)- .set(- "queue.buffering.max.kbytes",- (config.queue_mib * 1024).to_string(),- )- .set("acks", &config.acks)- .set("batch.num.messages", config.batch_num_messages.to_string())- .set("batch.size", config.batch_size.to_string())- .set("enable.idempotence", config.enable_idempotence.to_string())- .set(- "topic.metadata.refresh.interval.ms",- config.metadata_refresh_interval_ms.to_string(),- )- .set(- "metadata.max.age.ms",- config.metadata_max_age_ms.to_string(),- )- .set("socket.timeout.ms", config.socket_timeout_ms.to_string())- .set("partitioner", &config.partitioner)- .set("message.send.max.retries", config.max_retries.to_string())- .set(- "max.in.flight.requests.per.connection",- config.max_in_flight_requests.to_string(),- )- .set(- "sticky.partitioning.linger.ms",- config.sticky_partitioning_linger_ms.to_string(),- )- .set(- "log.connection.close",- config.log_connection_close.to_string(),- )- .set(- "queue.buffering.max.messages",- config.queue_buffering_max_messages.to_string(),- )- .set(- "retry.backoff.max.ms",- config.retry_backoff_max_ms.to_string(),- )- .set(- "socket.send.buffer.bytes",- config.socket_send_buffer_bytes.to_string(),- )- .set(- "socket.receive.buffer.bytes",- config.socket_receive_buffer_bytes.to_string(),- );-- if !config.broker_address_family.is_empty() {- client_config.set("broker.address.family", &config.broker_address_family);- }- if !config.client_id.is_empty() {- client_config.set("client.id", &config.client_id);- }- if config.tls {- client_config- .set("security.protocol", "ssl")- .set("enable.ssl.certificate.verification", "false");- }-- let producer: FutureProducer<KafkaContext> = client_config.create_with_context(ctx)?;-- match producer- .client()- .fetch_metadata(None, Duration::from_secs(10))- {- Ok(_) => {- handle.report_healthy();- info!("v1 kafka producer [{}] connected", sink.as_str());- }- Err(e) => {- error!(- "v1 kafka producer [{}]: initial metadata fetch failed: {e}",- sink.as_str()- );- counter!(- KAFKA_CLIENT_ERRORS_TOTAL,- "cluster" => sink.as_str(),- "mode" => capture_mode,- "error" => "metadata_fetch_failed",- )- .increment(1);- }- }-- Ok(Self {- inner: producer,- handle,- sink,- })- }-}--impl super::KafkaProducerTrait for KafkaProducer {- type Ack = SendHandle;-- fn send<'a>(- &self,- record: ProduceRecord<'a>,- ) -> Result<SendHandle, (ProduceError, ProduceRecord<'a>)> {- match self.inner.send_result(FutureRecord {- topic: record.topic,- payload: Some(record.payload),- partition: None,- key: record.key,- timestamp: None,- headers: Some(record.headers),- }) {- Ok(future) => Ok(SendHandle { inner: future }),- Err((e, returned)) => {- let returned_record = ProduceRecord {- topic: returned.topic,- key: returned.key,- payload: returned.payload.unwrap_or(&[]),- headers: returned.headers.unwrap_or_else(OwnedHeaders::new),- };- Err((produce_error_from_kafka(e), returned_record))- }- }- }-- fn flush(&self, timeout: Duration) -> Result<(), KafkaError> {- self.inner.flush(rdkafka::util::Timeout::After(timeout))- }-- fn is_ready(&self) -> bool {- self.handle.is_healthy()- }-- fn sink_name(&self) -> SinkName {- self.sink- }-}--// ----------------------------------------------------------------------------// Helpers-// -----------------------------------------------------------------------------fn is_fatal_kafka_error(code: RDKafkaErrorCode) -> bool {- matches!(- code,- RDKafkaErrorCode::MessageSizeTooLarge- | RDKafkaErrorCode::InvalidMessageSize- | RDKafkaErrorCode::InvalidMessage- )-}--pub(crate) fn produce_error_from_kafka(e: KafkaError) -> ProduceError {- let code = e.rdkafka_error_code().unwrap_or(RDKafkaErrorCode::Unknown);- if code == RDKafkaErrorCode::MessageSizeTooLarge {- ProduceError::EventTooBig {- message: e.to_string(),- }- } else {- ProduceError::Kafka { code }- }-}diff --git a/rust/capture/src/v1/sinks/kafka/sink.rs b/rust/capture/src/v1/sinks/kafka/sink.rsdeleted file mode 100644index c183d56de00b..000000000000--- a/rust/capture/src/v1/sinks/kafka/sink.rs+++ /dev/null@@ -1,458 +0,0 @@-use std::collections::HashSet;-use std::future::Future;-use std::pin::Pin;-use std::sync::Arc;-use std::time::{Duration, Instant};--use async_trait::async_trait;-use chrono::{DateTime, Utc};-use futures::stream::FuturesUnordered;-use futures::StreamExt;-use metrics::{counter, histogram};-use tracing::Level;-use uuid::Uuid;--use crate::config::CaptureMode;-use crate::ordering::OrderingGuarantee;-use crate::v1::context::RequestContext;-use crate::v1::sinks::sink::Sink;-use crate::v1::sinks::types::{BatchSummary, Outcome, PreparedEvent, SinkResult};-use crate::v1::sinks::{Config, SinkName};--use super::constants::*;-use super::producer::ProduceRecord;-use super::types::{KafkaResult, KafkaSinkError};-use super::KafkaProducerTrait;--/// Shared label values for metrics emitted within a single `publish_batch` call.-struct MetricLabels {- sink: &'static str,- mode: &'static str,- path: &'static str,- attempt: &'static str,-}--/// Map the client-controlled attempt number to a bounded static label value.-/// Attempts 0-5 map to themselves; 6 or more bucket into "6+" as a-/// cardinality defense (the label reads literally: "6 or more").-fn attempt_tag(attempt: u32) -> &'static str {- match attempt {- 0 => "0",- 1 => "1",- 2 => "2",- 3 => "3",- 4 => "4",- 5 => "5",- _ => "6+",- }-}--pub struct KafkaSink<P: KafkaProducerTrait> {- name: SinkName,- producer: Arc<P>,- config: Config,- capture_mode: CaptureMode,- handle: lifecycle::Handle,-}--impl<P: KafkaProducerTrait> KafkaSink<P> {- pub fn new(- name: SinkName,- producer: Arc<P>,- config: Config,- capture_mode: CaptureMode,- handle: lifecycle::Handle,- ) -> Self {- Self {- name,- producer,- config,- capture_mode,- handle,- }- }-}--/// Reject every event in `events` as `SinkUnavailable`, incrementing a single-/// counter per destination for the batch. Inputs are already serialized and-/// publishable (non-publishable events never reach a sink).-fn reject_all(events: &[PreparedEvent], labels: &MetricLabels) -> Vec<Box<dyn SinkResult>> {- let enqueued_at = Utc::now();- let mut by_dest: std::collections::HashMap<&'static str, u64> =- std::collections::HashMap::new();- for e in events {- *by_dest.entry(e.destination.as_tag()).or_default() += 1;- }- for (dest_tag, count) in &by_dest {- counter!(- KAFKA_PUBLISH_TOTAL,- "mode" => labels.mode,- "cluster" => labels.sink,- "outcome" => Outcome::RetriableError.as_tag(),- "path" => labels.path,- "attempt" => labels.attempt,- "destination" => *dest_tag,- )- .increment(*count);- }- events- .iter()- .map(|e| -> Box<dyn SinkResult> {- Box::new(KafkaResult::err(- e.uuid,- KafkaSinkError::SinkUnavailable,- enqueued_at,- ))- })- .collect()-}--type AckFuture = Pin<- Box<- dyn Future<- Output = (- Uuid,- &'static str,- DateTime<Utc>,- Duration,- Result<(), super::producer::ProduceError>,- ),- > + Send,- >,->;--impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {- /// Phase 1: serialize and enqueue events to the producer sequentially,- /// preserving per-partition ordering. Returns early results for- /// serialization / send failures and collects ack futures for events- /// that were successfully enqueued.- async fn enqueue_events(- &self,- events: &[PreparedEvent],- labels: &MetricLabels,- enqueued_at: DateTime<Utc>,- results: &mut Vec<Box<dyn SinkResult>>,- pending: &mut FuturesUnordered<AckFuture>,- enqueued_keys: &mut Vec<(Uuid, &'static str, Instant)>,- ) {- for event in events {- let uuid = event.uuid;- let dest_tag = event.destination.as_tag();-- let topic = match self.config.kafka.topic_for(&event.destination) {- Some(t) => t,- None => continue,- };-- // `None` is passed to rdkafka so it round-robins. Passing- // `Some("")` would hash to a single deterministic partition via- // murmur2, which is the hot partition this is meant to avoid.- let key = match event.ordering {- OrderingGuarantee::None => None,- _ => Some(event.partition_key.as_str()),- };-- let headers: rdkafka::message::OwnedHeaders = event.headers.clone().into();-- let record = ProduceRecord {- topic,- key,- payload: event.payload.as_ref(),- headers,- };-- match self.producer.send(record) {- Ok(ack_future) => {- let sent_at = Instant::now();- enqueued_keys.push((uuid, dest_tag, sent_at));- pending.push(Box::pin(async move {- let result = ack_future.await;- let ack_latency = sent_at.elapsed();- (uuid, dest_tag, Utc::now(), ack_latency, result)- }));- }- Err((e, _)) => {- let sink_err = KafkaSinkError::Produce(e);- let outcome = sink_err.outcome();- counter!(- KAFKA_PUBLISH_TOTAL,- "mode" => labels.mode,- "cluster" => labels.sink,- "outcome" => outcome.as_tag(),- "path" => labels.path,- "attempt" => labels.attempt,- "destination" => dest_tag,- )- .increment(1);- results.push(Box::new(KafkaResult::err(uuid, sink_err, enqueued_at)));- }- }- }- }-- /// Phase 2: drain ack futures with a per-sink deadline. Dropping remaining- /// futures on timeout is safe — the underlying DeliveryFuture is a- /// oneshot::Receiver; dropping it just means rdkafka's delivery callback- /// send() returns Err (silently ignored). The message still completes in- /// librdkafka (or times out via message.timeout.ms).- async fn drain_acks(- &self,- labels: &MetricLabels,- enqueued_at: DateTime<Utc>,- results: &mut Vec<Box<dyn SinkResult>>,- pending: &mut FuturesUnordered<AckFuture>,- ) -> HashSet<Uuid> {- let deadline = tokio::time::Instant::now() + self.config.produce_timeout;- let mut resolved_keys: HashSet<Uuid> = HashSet::new();-- loop {- match tokio::time::timeout_at(deadline, pending.next()).await {- Ok(Some((uuid, dest_tag, completed_at, ack_latency, ack))) => {- resolved_keys.insert(uuid);-- let outcome_tag = match &ack {- Ok(()) => Outcome::Success.as_tag(),- Err(e) => {- if e.is_retriable() {- Outcome::RetriableError.as_tag()- } else {- Outcome::FatalError.as_tag()- }- }- };-- counter!(- KAFKA_PUBLISH_TOTAL,- "mode" => labels.mode,- "cluster" => labels.sink,- "outcome" => outcome_tag,- "path" => labels.path,- "attempt" => labels.attempt,- "destination" => dest_tag,- )- .increment(1);-- // Per-event broker-ack latency (send → ack), isolated from- // batch enqueue wall-time.- histogram!(- KAFKA_ACK_DURATION_SECONDS,- "mode" => labels.mode,- "cluster" => labels.sink,- "outcome" => outcome_tag,- "path" => labels.path,- "attempt" => labels.attempt,- "destination" => dest_tag,- )- .record(ack_latency.as_secs_f64());-- match ack {- Ok(()) => results.push(Box::new(- KafkaResult::ok(uuid, enqueued_at).with_completed_at(completed_at),- )),- Err(e) => results.push(Box::new(- KafkaResult::err(uuid, KafkaSinkError::Produce(e), enqueued_at)- .with_completed_at(completed_at),- )),- }- }- Ok(None) => break,- Err(_) => break,- }- }- resolved_keys- }-- /// Phase 3: identify enqueued events whose acks were not resolved before- /// the deadline and emit timeout results.- fn collect_timeouts(- labels: &MetricLabels,- enqueued_at: DateTime<Utc>,- enqueued_keys: Vec<(Uuid, &'static str, Instant)>,- resolved_keys: &HashSet<Uuid>,- results: &mut Vec<Box<dyn SinkResult>>,- ) {- let timed_out: Vec<_> = enqueued_keys- .into_iter()- .filter(|(k, _, _)| !resolved_keys.contains(k))- .collect();- if timed_out.is_empty() {- return;- }- let mut by_dest: std::collections::HashMap<&'static str, u64> =- std::collections::HashMap::new();- for (_, dest_tag, _) in &timed_out {- *by_dest.entry(dest_tag).or_default() += 1;- }- for (dest_tag, count) in &by_dest {- counter!(- KAFKA_PUBLISH_TOTAL,- "mode" => labels.mode,- "cluster" => labels.sink,- "outcome" => Outcome::Timeout.as_tag(),- "path" => labels.path,- "attempt" => labels.attempt,- "destination" => *dest_tag,- )- .increment(*count);- }- let gave_up_at = Utc::now();- for (uuid, dest_tag, sent_at) in timed_out {- // Record timed-out acks so the latency tail (>= produce_timeout)- // is visible rather than silently dropped.- histogram!(- KAFKA_ACK_DURATION_SECONDS,- "mode" => labels.mode,- "cluster" => labels.sink,- "outcome" => Outcome::Timeout.as_tag(),- "path" => labels.path,- "attempt" => labels.attempt,- "destination" => dest_tag,- )- .record(sent_at.elapsed().as_secs_f64());- results.push(Box::new(- KafkaResult::err(uuid, KafkaSinkError::Timeout, enqueued_at)- .with_completed_at(gave_up_at),- ));- }- }-}--#[async_trait]-impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {- fn name(&self) -> SinkName {- self.name- }-- async fn publish_batch(- &self,- ctx: &RequestContext,- events: &[PreparedEvent],- ) -> Vec<Box<dyn SinkResult>> {- let labels = MetricLabels {- sink: self.name.as_str(),- mode: self.capture_mode.as_tag(),- path: ctx.path,- attempt: attempt_tag(ctx.attempt),- };-- if !self.producer.is_ready() {- crate::ctx_log!(- Level::ERROR,- ctx,- sink = labels.sink,- mode = labels.mode,- "producer not ready — rejecting batch"- );- return reject_all(events, &labels);- }-- let enqueued_at = Utc::now();- let mut results: Vec<Box<dyn SinkResult>> = Vec::new();- let mut pending: FuturesUnordered<AckFuture> = FuturesUnordered::new();- let mut enqueued_keys: Vec<(Uuid, &'static str, Instant)> = Vec::new();-- // Enqueue wall-time, isolated from per-event broker-ack latency.- let enqueue_start = Instant::now();- self.enqueue_events(- events,- &labels,- enqueued_at,- &mut results,- &mut pending,- &mut enqueued_keys,- )- .await;- histogram!(- KAFKA_ENQUEUE_DURATION_SECONDS,- "mode" => labels.mode,- "cluster" => labels.sink,- "path" => labels.path,- "attempt" => labels.attempt,- )- .record(enqueue_start.elapsed().as_secs_f64());-- let resolved_keys = self- .drain_acks(&labels, enqueued_at, &mut results, &mut pending)- .await;-- Self::collect_timeouts(- &labels,- enqueued_at,- enqueued_keys,- &resolved_keys,- &mut results,- );-- let summary = BatchSummary::from_results(&results);- if summary.all_ok() {- crate::ctx_log!(Level::DEBUG, ctx,- sink = labels.sink,- mode = labels.mode,- %summary,- "batch published");- } else if summary.succeeded == 0 {- crate::ctx_log!(Level::ERROR, ctx,- sink = labels.sink,- mode = labels.mode,- %summary,- errors = ?summary.errors,- "batch fully failed");- } else {- crate::ctx_log!(Level::WARN, ctx,- sink = labels.sink,- mode = labels.mode,- %summary,- errors = ?summary.errors,- "batch partially failed");- }- for (tag, count) in &summary.errors {- counter!(- KAFKA_PRODUCE_ERRORS_TOTAL,- "cluster" => labels.sink,- "mode" => labels.mode,- "error" => *tag- )- .increment(*count as u64);- }-- if summary.succeeded > 0 {- self.handle.report_healthy();- }- results- }-- async fn flush(&self) -> anyhow::Result<()> {- let timeout = self.config.produce_timeout;- let producer = self.producer.clone();- let name_str = self.name.as_str();- tokio::task::spawn_blocking(move || {- producer- .flush(timeout)- .map_err(|e| anyhow::anyhow!("{name_str}: flush error: {e:#}"))- })- .await- .map_err(|e| anyhow::anyhow!("flush task panicked: {e:#}"))?- }-}--#[cfg(test)]-mod attempt_tag_tests {- use super::attempt_tag;-- #[test]- fn maps_in_range_attempts_to_exact_values() {- assert_eq!(attempt_tag(0), "0");- assert_eq!(attempt_tag(1), "1");- assert_eq!(attempt_tag(2), "2");- assert_eq!(attempt_tag(3), "3");- assert_eq!(attempt_tag(4), "4");- assert_eq!(attempt_tag(5), "5");- }-- #[test]- fn caps_out_of_range_attempts() {- assert_eq!(attempt_tag(6), "6+");- assert_eq!(attempt_tag(100), "6+");- assert_eq!(attempt_tag(u32::MAX), "6+");- }-}diff --git a/rust/capture/src/v1/sinks/kafka/sink_tests.rs b/rust/capture/src/v1/sinks/kafka/sink_tests.rsdeleted file mode 100644index b622b4e09142..000000000000--- a/rust/capture/src/v1/sinks/kafka/sink_tests.rs+++ /dev/null@@ -1,1135 +0,0 @@-use std::collections::HashMap;-use std::sync::Arc;-use std::time::Duration;--use common_types::{CapturedEvent, CapturedEventHeaders, RawEvent};-use rdkafka::error::RDKafkaErrorCode;-use rstest::rstest;-use uuid::Uuid;--use crate::config::CaptureMode;-use crate::ordering::OrderingGuarantee;-use crate::v1::context::RequestContext;-use crate::v1::sinks::event::Event;-use crate::v1::sinks::sink::Sink;-use crate::v1::sinks::types::{BatchSummary, Outcome};-use crate::v1::sinks::{Config, Destination, SinkName};-use crate::v1::test_utils::{self, WrappedEventMut};--use super::mock::MockProducer;-use super::producer::ProduceError;-use super::sink::KafkaSink;--/// All-None CapturedEventHeaders for stubbing FakeEvent. `CapturedEventHeaders`-/// does not derive `Default` in common_types; keep the literal here so the-/// stub doesn't leak unrelated fields into sink_tests.-fn empty_captured_headers() -> CapturedEventHeaders {- CapturedEventHeaders {- token: None,- distinct_id: None,- session_id: None,- timestamp: None,- event: None,- uuid: None,- 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,- }-}--// ----------------------------------------------------------------------------// FakeEvent-// -----------------------------------------------------------------------------struct FakeEvent {- parsed_uuid: Uuid,- publish: bool,- destination: Destination,- partition_key: Option<String>,- payload: Result<String, String>,- event_headers: CapturedEventHeaders,- ordering: OrderingGuarantee,-}--impl FakeEvent {- fn ok(uuid: &str) -> Self {- Self {- parsed_uuid: Uuid::new_v4(),- publish: true,- destination: Destination::AnalyticsMain,- partition_key: Some(format!("phc_test:{uuid}")),- payload: Ok(r#"{"event":"test"}"#.to_string()),- event_headers: empty_captured_headers(),- ordering: OrderingGuarantee::PerDistinctId,- }- }-- fn with_ordering(mut self, o: OrderingGuarantee) -> Self {- self.ordering = o;- self- }-- fn with_destination(mut self, d: Destination) -> Self {- self.destination = d;- self- }-- fn with_publish(mut self, p: bool) -> Self {- self.publish = p;- self- }-- fn with_partition_key(mut self, k: Option<&str>) -> Self {- self.partition_key = k.map(String::from);- self- }-- fn with_headers(mut self, h: CapturedEventHeaders) -> Self {- self.event_headers = h;- self- }-}--impl Event for FakeEvent {- fn uuid(&self) -> Uuid {- self.parsed_uuid- }-- fn should_publish(&self) -> bool {- self.publish- }-- fn destination(&self) -> &Destination {- &self.destination- }-- fn headers(&self, _ctx: &RequestContext) -> CapturedEventHeaders {- self.event_headers.clone()- }-- fn partition_key(&self, _ctx: &RequestContext) -> String {- self.partition_key.clone().unwrap_or_default()- }-- fn ordering(&self) -> OrderingGuarantee {- self.ordering- }-- fn serialize(&self, _ctx: &RequestContext) -> anyhow::Result<bytes::Bytes> {- match &self.payload {- Ok(p) => Ok(bytes::Bytes::from(p.clone())),- Err(e) => Err(anyhow::anyhow!(e.clone())),- }- }-}--use crate::v1::test_utils::prepared;--// ----------------------------------------------------------------------------// TestHarness-// -----------------------------------------------------------------------------struct TestHarness {- sink: KafkaSink<MockProducer>,- producer: Arc<MockProducer>,- handle: lifecycle::Handle,- ctx: RequestContext,- _monitor: lifecycle::MonitorGuard,-}--impl TestHarness {- fn new() -> Self {- Self::builder().build()- }-- fn builder() -> HarnessBuilder {- HarnessBuilder {- produce_timeout: Duration::from_secs(30),- send_error: None,- send_error_count: None,- ack_error: None,- ack_delay: None,- not_ready: false,- liveness: None,- }- }-}--struct HarnessBuilder {- produce_timeout: Duration,- send_error: Option<fn() -> ProduceError>,- send_error_count: Option<u32>,- ack_error: Option<fn() -> ProduceError>,- ack_delay: Option<Duration>,- not_ready: bool,- liveness: Option<(Duration, Duration)>,-}--impl HarnessBuilder {- fn produce_timeout(mut self, d: Duration) -> Self {- self.produce_timeout = d;- self- }-- fn send_error(mut self, f: fn() -> ProduceError) -> Self {- self.send_error = Some(f);- self- }-- fn send_error_count(mut self, n: u32) -> Self {- self.send_error_count = Some(n);- self- }-- fn ack_error(mut self, f: fn() -> ProduceError) -> Self {- self.ack_error = Some(f);- self- }-- fn ack_delay(mut self, d: Duration) -> Self {- self.ack_delay = Some(d);- self- }-- fn not_ready(mut self) -> Self {- self.not_ready = true;- self- }-- fn with_liveness(mut self, deadline: Duration, poll_interval: Duration) -> Self {- self.liveness = Some((deadline, poll_interval));- self- }-- fn build(self) -> TestHarness {- let mut builder = lifecycle::Manager::builder("test")- .with_trap_signals(false)- .with_prestop_check(false);-- if let Some((_, poll_interval)) = self.liveness {- builder = builder.with_health_poll_interval(poll_interval);- }-- let mut manager = builder.build();-- let mut opts = lifecycle::ComponentOptions::new();- if let Some((deadline, _)) = self.liveness {- opts = opts.with_liveness_deadline(deadline);- }- let handle = manager.register("kafka_sink_test", opts);- handle.report_healthy();-- let monitor = manager.monitor_background();-- let mut mock = MockProducer::new(SinkName::Msk, handle.clone());- if let Some(f) = self.send_error {- mock = mock.with_send_error(f);- }- if let Some(n) = self.send_error_count {- mock = mock.with_send_error_count(n);- }- if let Some(f) = self.ack_error {- mock = mock.with_ack_error(f);- }- if let Some(d) = self.ack_delay {- mock = mock.with_ack_delay(d);- }- if self.not_ready {- mock = mock.with_not_ready();- }-- let producer = Arc::new(mock);-- let kafka_config = crate::v1::test_utils::test_kafka_config();-- let config = Config {- produce_timeout: self.produce_timeout,- kafka: kafka_config,- };-- let sink = KafkaSink::new(- SinkName::Msk,- Arc::clone(&producer),- config,- CaptureMode::Events,- handle.clone(),- );-- TestHarness {- sink,- producer,- handle,- ctx: {- let mut ctx = crate::v1::test_utils::test_context();- ctx.created_at = None;- ctx- },- _monitor: monitor,- }- }-}--// ----------------------------------------------------------------------------// 1. Happy path (single event)-// -----------------------------------------------------------------------------#[tokio::test]-async fn single_event_success() {- let h = TestHarness::new();- let event = FakeEvent::ok("evt-1");- let events = prepared(&[&event], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].key(), event.parsed_uuid);- assert_eq!(results[0].outcome(), Outcome::Success);- assert!(results[0].cause().is_none());- assert!(results[0].elapsed().is_some());-- assert_eq!(h.producer.record_count(), 1);- h.producer.with_records(|records| {- assert_eq!(records[0].topic, "events_main");- assert_eq!(records[0].payload, r#"{"event":"test"}"#);- assert_eq!(records[0].key.as_deref(), Some("phc_test:evt-1"));- });-}--// ----------------------------------------------------------------------------// 2. Non-publishable events silently skipped-// -----------------------------------------------------------------------------#[tokio::test]-async fn non_publishable_events_skipped() {- let h = TestHarness::new();- let e1 = FakeEvent::ok("evt-1");- let e2 = FakeEvent::ok("evt-2").with_publish(false);- let e3 = FakeEvent::ok("evt-3");- let events = prepared(&[&e1, &e2, &e3], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 2);- assert_eq!(results[0].key(), e1.parsed_uuid);- assert_eq!(results[1].key(), e3.parsed_uuid);- assert_eq!(h.producer.record_count(), 2);-}--// ----------------------------------------------------------------------------// 3. Destination::Drop skips without result-// -----------------------------------------------------------------------------#[tokio::test]-async fn destination_drop_skips_without_result() {- let h = TestHarness::new();- let event = FakeEvent::ok("evt-1").with_destination(Destination::Drop);- let events = prepared(&[&event], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert!(results.is_empty());- assert_eq!(h.producer.record_count(), 0);-}--// ----------------------------------------------------------------------------// 4. Sink unavailable (producer not ready)-// -----------------------------------------------------------------------------#[tokio::test]-async fn sink_unavailable() {- let h = TestHarness::builder().not_ready().build();- let e1 = FakeEvent::ok("evt-1");- let e2 = FakeEvent::ok("evt-2");- let events = prepared(&[&e1, &e2], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 2);- for r in &results {- assert_eq!(r.outcome(), Outcome::RetriableError);- assert_eq!(r.cause(), Some("sink_unavailable"));- }- assert_eq!(h.producer.record_count(), 0);-}--// ----------------------------------------------------------------------------// 5. QueueFull is immediate retriable error (no app-level retry loop;-// backpressure handled by librdkafka queue + client retry).-// -----------------------------------------------------------------------------#[tokio::test]-async fn queue_full_is_immediate_retriable() {- let h = TestHarness::builder()- .send_error(|| ProduceError::Kafka {- code: RDKafkaErrorCode::QueueFull,- })- .build();- let event = FakeEvent::ok("evt-1");- let events = prepared(&[&event], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].key(), event.parsed_uuid);- assert_eq!(results[0].outcome(), Outcome::RetriableError);- assert_eq!(results[0].cause(), Some("queue_full"));- assert_eq!(h.producer.record_count(), 0);-}--// ----------------------------------------------------------------------------// 6. Send-time fatal error (event too big)-// -----------------------------------------------------------------------------#[tokio::test]-async fn send_error_fatal_event_too_big() {- let h = TestHarness::builder()- .send_error(|| ProduceError::EventTooBig {- message: "too big".into(),- })- .build();- let event = FakeEvent::ok("evt-1");- let events = prepared(&[&event], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::FatalError);- assert_eq!(results[0].cause(), Some("event_too_big"));-}--// ----------------------------------------------------------------------------// 7. Ack-time retriable error (delivery cancelled)-// -----------------------------------------------------------------------------#[tokio::test]-async fn ack_error_retriable_delivery_cancelled() {- let h = TestHarness::builder()- .ack_error(|| ProduceError::DeliveryCancelled)- .build();- let event = FakeEvent::ok("evt-1");- let events = prepared(&[&event], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].key(), event.parsed_uuid);- assert_eq!(results[0].outcome(), Outcome::RetriableError);- assert_eq!(results[0].cause(), Some("delivery_cancelled"));- assert!(results[0].elapsed().is_some());- // Enqueue succeeded before ack failed- assert_eq!(h.producer.record_count(), 1);-}--// ----------------------------------------------------------------------------// 8. Ack-time retriable kafka error (topic auth failed — infrastructure-// misconfiguration, may succeed on a different pod)-// -----------------------------------------------------------------------------#[tokio::test]-async fn ack_error_retriable_topic_auth() {- let h = TestHarness::builder()- .ack_error(|| ProduceError::Kafka {- code: RDKafkaErrorCode::TopicAuthorizationFailed,- })- .build();- let event = FakeEvent::ok("evt-1");- let events = prepared(&[&event], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::RetriableError);- assert_eq!(results[0].cause(), Some("topic_authorization_failed"));- assert!(results[0].elapsed().is_some());- assert_eq!(h.producer.record_count(), 1);-}--// ----------------------------------------------------------------------------// 9. Produce timeout-// -----------------------------------------------------------------------------#[tokio::test]-async fn produce_timeout_single() {- let h = TestHarness::builder()- .ack_delay(Duration::from_secs(60))- .produce_timeout(Duration::from_millis(50))- .build();- let event = FakeEvent::ok("evt-1");- let events = prepared(&[&event], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].key(), event.parsed_uuid);- assert_eq!(results[0].outcome(), Outcome::Timeout);- assert_eq!(results[0].cause(), Some("timeout"));-}--#[tokio::test]-async fn produce_timeout_batch_all_pending_get_timeout() {- let h = TestHarness::builder()- .ack_delay(Duration::from_secs(60))- .produce_timeout(Duration::from_millis(50))- .build();- let e1 = FakeEvent::ok("evt-1");- let e2 = FakeEvent::ok("evt-2");- let e3 = FakeEvent::ok("evt-3");- let events = prepared(&[&e1, &e2, &e3], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 3);- for r in &results {- assert_eq!(r.outcome(), Outcome::Timeout);- assert_eq!(r.cause(), Some("timeout"));- }-}--// ----------------------------------------------------------------------------// Flush delegates to producer-// -----------------------------------------------------------------------------#[tokio::test]-async fn flush_ok() {- let h = TestHarness::new();- assert!(h.sink.flush().await.is_ok());-}--// ----------------------------------------------------------------------------// 14. Sink::name() returns configured name-// -----------------------------------------------------------------------------#[test]-fn sink_name_returns_configured_name() {- let h = TestHarness::new();- assert_eq!(h.sink.name(), SinkName::Msk);-}--// ----------------------------------------------------------------------------// Topic routing for non-default destinations-// -----------------------------------------------------------------------------#[rstest]-#[case::historical(Destination::AnalyticsHistorical, "events_hist")]-#[case::overflow(Destination::Overflow, "events_overflow")]-#[case::dlq(Destination::Dlq, "events_dlq")]-#[case::custom(Destination::Custom("my_topic".into()), "my_topic")]-#[case::exception(Destination::ExceptionErrorTracking, "error_tracking_events")]-#[case::heatmap(Destination::HeatmapMain, "heatmaps_ingestion")]-#[case::client_ingestion_warning(Destination::ClientIngestionWarning, "events_plugin_ingestion")]-#[tokio::test]-async fn destination_routes_to_correct_topic(- #[case] destination: Destination,- #[case] expected_topic: &str,-) {- let h = TestHarness::new();- let event = FakeEvent::ok("evt-1").with_destination(destination);- let events = prepared(&[&event], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- h.producer.with_records(|records| {- assert_eq!(records[0].topic, expected_topic);- });-}--// ----------------------------------------------------------------------------// BatchSummary with timeout results-// -----------------------------------------------------------------------------#[tokio::test]-async fn batch_summary_with_timeouts() {- let h = TestHarness::builder()- .ack_delay(Duration::from_secs(60))- .produce_timeout(Duration::from_millis(50))- .build();- let e1 = FakeEvent::ok("evt-1");- let e2 = FakeEvent::ok("evt-2");- let events = prepared(&[&e1, &e2], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;- let summary = BatchSummary::from_results(&results);-- assert_eq!(summary.total, 2);- assert_eq!(summary.succeeded, 0);- assert_eq!(summary.retriable, 0);- assert_eq!(summary.fatal, 0);- assert_eq!(summary.timed_out, 2);- assert!(!summary.all_ok());- assert_eq!(summary.errors.get("timeout").copied(), Some(2));-}--// ----------------------------------------------------------------------------// Slow-ack path: acks resolve within produce_timeout → all events succeed.-// -----------------------------------------------------------------------------#[tokio::test]-async fn slow_ack_within_timeout_batch_all_succeed() {- let h = TestHarness::builder()- .ack_delay(Duration::from_millis(20))- .produce_timeout(Duration::from_secs(30))- .build();- let e1 = FakeEvent::ok("evt-1");- let e2 = FakeEvent::ok("evt-2");- let e3 = FakeEvent::ok("evt-3");- let events = prepared(&[&e1, &e2, &e3], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 3);- for r in &results {- assert_eq!(r.outcome(), Outcome::Success);- assert!(r.cause().is_none());- assert!(r.elapsed().is_some());- }- assert_eq!(h.producer.record_count(), 3);-- let by_key: HashMap<Uuid, _> = results.iter().map(|r| (r.key(), r)).collect();- assert!(by_key.contains_key(&e1.parsed_uuid));- assert!(by_key.contains_key(&e2.parsed_uuid));- assert!(by_key.contains_key(&e3.parsed_uuid));-}--// ===========================================================================-// Health heartbeat tests-//-// Production-proportional timing (100x faster, same ratios):-// production: liveness_deadline=30s, health_poll=2s, produce_timeout=30s-// test: liveness_deadline=300ms, health_poll=20ms, produce_timeout=300ms-// ===========================================================================--const HEALTH_TEST_LIVENESS_DEADLINE: Duration = Duration::from_millis(300);-const HEALTH_TEST_POLL_INTERVAL: Duration = Duration::from_millis(20);-const HEALTH_TEST_PRODUCE_TIMEOUT: Duration = Duration::from_millis(300);-/// Sleep long enough for the liveness deadline to expire + poll to detect it.-const HEALTH_TEST_UNHEALTHY_SLEEP: Duration = Duration::from_millis(500);-/// Sleep just long enough for the poll to run, but well before deadline expiry.-const HEALTH_TEST_HEALTHY_SLEEP: Duration = Duration::from_millis(50);--// ----------------------------------------------------------------------------// Health: no heartbeat when every event fails (parameterized by failure mode)-// -----------------------------------------------------------------------------enum FailureMode {- Timeout,- SendError,- AckError,-}--fn health_harness(mode: &FailureMode) -> TestHarness {- let mut b = TestHarness::builder()- .with_liveness(HEALTH_TEST_LIVENESS_DEADLINE, HEALTH_TEST_POLL_INTERVAL)- .produce_timeout(HEALTH_TEST_PRODUCE_TIMEOUT);- match mode {- FailureMode::Timeout => {- b = b.ack_delay(Duration::from_secs(10));- }- FailureMode::SendError => {- b = b.send_error(|| ProduceError::Kafka {- code: RDKafkaErrorCode::QueueFull,- });- }- FailureMode::AckError => {- b = b.ack_error(|| ProduceError::DeliveryCancelled);- }- }- b.build()-}--fn health_events() -> Vec<FakeEvent> {- vec![- FakeEvent::ok("evt-1"),- FakeEvent::ok("evt-2"),- FakeEvent::ok("evt-3"),- ]-}--fn expected_outcome(mode: &FailureMode) -> Outcome {- match mode {- FailureMode::Timeout => Outcome::Timeout,- FailureMode::SendError => Outcome::RetriableError,- FailureMode::AckError => Outcome::RetriableError,- }-}--#[rstest]-#[case::timeout(FailureMode::Timeout)]-#[case::send_error(FailureMode::SendError)]-#[case::ack_error(FailureMode::AckError)]-#[tokio::test]-async fn health_not_refreshed_on_full_failure(#[case] mode: FailureMode) {- let h = health_harness(&mode);- let owned_events = health_events();- let refs: Vec<&FakeEvent> = owned_events.iter().collect();- let events = prepared(&refs, &h.ctx);- let expected = expected_outcome(&mode);-- let results = h.sink.publish_batch(&h.ctx, &events).await;- for r in &results {- assert_eq!(r.outcome(), expected);- }-- tokio::time::sleep(HEALTH_TEST_UNHEALTHY_SLEEP).await;- assert!(- !h.handle.is_healthy(),- "handle should be unhealthy after full {expected:?} batch"- );-}--// ----------------------------------------------------------------------------// Health: all events succeed -> heartbeat refreshed -> is_healthy stays true-// -----------------------------------------------------------------------------#[tokio::test]-async fn health_refreshed_on_full_success() {- let h = TestHarness::builder()- .with_liveness(HEALTH_TEST_LIVENESS_DEADLINE, HEALTH_TEST_POLL_INTERVAL)- .produce_timeout(HEALTH_TEST_PRODUCE_TIMEOUT)- .build();- let e1 = FakeEvent::ok("evt-1");- let e2 = FakeEvent::ok("evt-2");- let e3 = FakeEvent::ok("evt-3");- let events = prepared(&[&e1, &e2, &e3], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;- for r in &results {- assert_eq!(r.outcome(), Outcome::Success);- }-- tokio::time::sleep(HEALTH_TEST_HEALTHY_SLEEP).await;- assert!(- h.handle.is_healthy(),- "handle should stay healthy after successful batch"- );-}--// ----------------------------------------------------------------------------// Health: partial success (some send errors) -> heartbeat still fires-// -----------------------------------------------------------------------------#[tokio::test]-async fn health_refreshed_on_partial_success() {- let h = TestHarness::builder()- .with_liveness(HEALTH_TEST_LIVENESS_DEADLINE, HEALTH_TEST_POLL_INTERVAL)- .produce_timeout(HEALTH_TEST_PRODUCE_TIMEOUT)- .send_error(|| ProduceError::Kafka {- code: RDKafkaErrorCode::QueueFull,- })- .send_error_count(1)- .build();- let e1 = FakeEvent::ok("evt-1");- let e2 = FakeEvent::ok("evt-2");- let e3 = FakeEvent::ok("evt-3");- let events = prepared(&[&e1, &e2, &e3], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;- let outcomes: Vec<Outcome> = results.iter().map(|r| r.outcome()).collect();- assert!(- outcomes.contains(&Outcome::RetriableError),- "at least one event should fail"- );- assert!(- outcomes.contains(&Outcome::Success),- "at least one event should succeed"- );-- tokio::time::sleep(HEALTH_TEST_HEALTHY_SLEEP).await;- assert!(- h.handle.is_healthy(),- "handle should stay healthy when at least one event succeeds"- );-}--// ----------------------------------------------------------------------------// Partition key: the ordering guarantee decides it-// -----------------------------------------------------------------------------/// The sink realizes the guarantee and nothing else. Which lanes give up-/// ordering is decided upstream (`WrappedEvent::ordering`), and the-/// person-processing header must not influence the key here: reading it back-/// out of the headers is the bug this indirection removes.-#[rstest]-#[case::none_drops_key(OrderingGuarantee::None, true, None)]-#[case::per_distinct_id_keeps_key(OrderingGuarantee::PerDistinctId, false, Some("phc_test:user-1"))]-#[case::per_session_keeps_key(OrderingGuarantee::PerSession, false, Some("phc_test:user-1"))]-#[case::header_alone_does_not_drop_key(- OrderingGuarantee::PerDistinctId,- true,- Some("phc_test:user-1")-)]-#[tokio::test]-async fn ordering_decides_partition_key(- #[case] ordering: OrderingGuarantee,- #[case] force_disable_header: bool,- #[case] expected_key: Option<&str>,-) {- let h = TestHarness::new();- let mut headers = empty_captured_headers();- if force_disable_header {- headers.force_disable_person_processing = Some(true);- }- let event = FakeEvent::ok("evt-1")- .with_partition_key(Some("phc_test:user-1"))- .with_ordering(ordering)- .with_headers(headers);- let events = prepared(&[&event], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- h.producer.with_records(|records| {- assert_eq!(records[0].key.as_deref(), expected_key);- });-}--#[tokio::test]-async fn some_partition_key_propagates_as_some() {- let h = TestHarness::new();- let event = FakeEvent::ok("evt-1").with_partition_key(Some("phc_test:user-1"));- let events = prepared(&[&event], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- h.producer.with_records(|records| {- assert_eq!(records[0].key.as_deref(), Some("phc_test:user-1"));- });-}--// ===========================================================================-// Realistic WrappedEvent round-trip tests-//-// These use production-shaped fixtures from test_utils and verify the-// MockProducer payload deserializes as CapturedEvent + RawEvent.-// ===========================================================================--#[tokio::test]-async fn realistic_single_pageview_round_trip() {- let h = TestHarness::new();- let wrapped = test_utils::realistic_pageview("user-42");- let events = prepared(&[&wrapped], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].key(), wrapped.uuid);- assert_eq!(results[0].outcome(), Outcome::Success);-- h.producer.with_records(|records| {- assert_eq!(records.len(), 1);- assert_eq!(records[0].topic, "events_main");-- let captured: CapturedEvent =- serde_json::from_str(&records[0].payload).expect("must deserialize as CapturedEvent");- assert_eq!(captured.uuid, wrapped.uuid);- assert_eq!(captured.distinct_id, "user-42");- assert_eq!(captured.event, "$pageview");-- let data: RawEvent =- serde_json::from_str(&captured.data).expect("data must deserialize as RawEvent");- assert_eq!(data.event, "$pageview");- assert_eq!(data.properties["$browser"], "Chrome");- assert_eq!(- data.properties["$session_id"],- "01jq9abc-def0-1234-5678-9abcdef01234"- );- assert_eq!(data.properties["$process_person_profile"], true);- });-}--#[tokio::test]-async fn realistic_batch_round_trip() {- let h = TestHarness::new();- let batch = test_utils::realistic_batch();- let events = prepared(&[&batch[0], &batch[1], &batch[2]], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 3);- for r in &results {- assert_eq!(r.outcome(), Outcome::Success);- }-- h.producer.with_records(|records| {- assert_eq!(records.len(), 3);- for record in records {- let captured: CapturedEvent =- serde_json::from_str(&record.payload).expect("must deserialize as CapturedEvent");- let _data: RawEvent =- serde_json::from_str(&captured.data).expect("data must deserialize as RawEvent");- }-- let names: Vec<&str> = records- .iter()- .map(|r| {- let c: CapturedEvent = serde_json::from_str(&r.payload).unwrap();- match c.event.as_str() {- "$pageview" => "$pageview",- "$identify" => "$identify",- _ => "custom",- }- })- .collect();- assert_eq!(names, vec!["$pageview", "$identify", "custom"]);- });-}--#[tokio::test]-async fn realistic_event_with_destination_mutation() {- let h = TestHarness::new();- let wrapped = test_utils::realistic_pageview("user-42")- .with_destination(Destination::AnalyticsHistorical);- let events = prepared(&[&wrapped], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- h.producer.with_records(|records| {- assert_eq!(records[0].topic, "events_hist");- });-}--#[tokio::test]-async fn realistic_dropped_event_not_published() {- use crate::v1::analytics::types::EventResult;-- let h = TestHarness::new();- let wrapped = test_utils::realistic_pageview("user-42")- .with_result(EventResult::Drop, Some("rate_limited"));- let events = prepared(&[&wrapped], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert!(results.is_empty());- assert_eq!(h.producer.record_count(), 0);-}--// ===========================================================================-// Coverage gap fills (C5)-// ===========================================================================--// ----------------------------------------------------------------------------// Mixed send error + ack error in one batch: first event fails at send,-// remaining events fail at ack. Verifies both error types are reported.-// -----------------------------------------------------------------------------#[tokio::test]-async fn mixed_send_error_and_ack_error_in_batch() {- let h = TestHarness::builder()- .send_error(|| ProduceError::Kafka {- code: RDKafkaErrorCode::QueueFull,- })- .send_error_count(1)- .ack_error(|| ProduceError::DeliveryCancelled)- .build();- let e1 = FakeEvent::ok("evt-1");- let e2 = FakeEvent::ok("evt-2");- let e3 = FakeEvent::ok("evt-3");- let events = prepared(&[&e1, &e2, &e3], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 3);- let by_key: HashMap<Uuid, _> = results.iter().map(|r| (r.key(), r)).collect();-- // evt-1: send error (queue_full)- assert_eq!(by_key[&e1.parsed_uuid].outcome(), Outcome::RetriableError);- assert_eq!(by_key[&e1.parsed_uuid].cause(), Some("queue_full"));-- // evt-2 and evt-3: enqueued successfully, but ack error (delivery_cancelled)- assert_eq!(by_key[&e2.parsed_uuid].outcome(), Outcome::RetriableError);- assert_eq!(by_key[&e2.parsed_uuid].cause(), Some("delivery_cancelled"));- assert_eq!(by_key[&e3.parsed_uuid].outcome(), Outcome::RetriableError);- assert_eq!(by_key[&e3.parsed_uuid].cause(), Some("delivery_cancelled"));-- // Only evt-2 and evt-3 were enqueued (evt-1 failed at send)- assert_eq!(h.producer.record_count(), 2);-}--// ----------------------------------------------------------------------------// Partial timeout: first event fails at send (immediate), remaining time out.-// Verifies mixed Outcome::RetriableError and Outcome::Timeout in one batch.-// -----------------------------------------------------------------------------#[tokio::test]-async fn partial_timeout_with_send_error() {- let h = TestHarness::builder()- .send_error(|| ProduceError::Kafka {- code: RDKafkaErrorCode::QueueFull,- })- .send_error_count(1)- .ack_delay(Duration::from_secs(60))- .produce_timeout(Duration::from_millis(50))- .build();- let e1 = FakeEvent::ok("evt-1");- let e2 = FakeEvent::ok("evt-2");- let events = prepared(&[&e1, &e2], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 2);- let by_key: HashMap<Uuid, _> = results.iter().map(|r| (r.key(), r)).collect();-- // evt-1: immediate send error- assert_eq!(by_key[&e1.parsed_uuid].outcome(), Outcome::RetriableError);- assert_eq!(by_key[&e1.parsed_uuid].cause(), Some("queue_full"));-- // evt-2: enqueued successfully, but ack times out- assert_eq!(by_key[&e2.parsed_uuid].outcome(), Outcome::Timeout);- assert_eq!(by_key[&e2.parsed_uuid].cause(), Some("timeout"));-}--// ===========================================================================-// Realistic WrappedEvent — destination routing, property injection, options-// ===========================================================================--#[tokio::test]-async fn realistic_exception_routes_to_exception_topic() {- let h = TestHarness::new();- let wrapped = test_utils::wrapped_event("$exception", "user-1")- .with_destination(Destination::ExceptionErrorTracking);- let events = prepared(&[&wrapped], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- h.producer.with_records(|records| {- assert_eq!(records[0].topic, "error_tracking_events");- });-}--#[tokio::test]-async fn realistic_heatmap_routes_to_heatmap_topic() {- let h = TestHarness::new();- let wrapped =- test_utils::wrapped_event("$$heatmap", "user-1").with_destination(Destination::HeatmapMain);- let events = prepared(&[&wrapped], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- h.producer.with_records(|records| {- assert_eq!(records[0].topic, "heatmaps_ingestion");- });-}--#[tokio::test]-async fn realistic_session_id_injected_into_properties() {- let h = TestHarness::new();- let mut wrapped = test_utils::wrapped_event("$pageview", "user-1");- wrapped.event.session_id = Some("sess-123".to_string());- let events = prepared(&[&wrapped], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- h.producer.with_records(|records| {- let captured: CapturedEvent =- serde_json::from_str(&records[0].payload).expect("must deserialize as CapturedEvent");- let data: RawEvent =- serde_json::from_str(&captured.data).expect("data must deserialize as RawEvent");- assert_eq!(data.properties["$session_id"], "sess-123");- });-}--#[tokio::test]-async fn realistic_window_id_injected_into_properties() {- let h = TestHarness::new();- let mut wrapped = test_utils::wrapped_event("$pageview", "user-1");- wrapped.event.window_id = Some("win-456".to_string());- let events = prepared(&[&wrapped], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- h.producer.with_records(|records| {- let captured: CapturedEvent =- serde_json::from_str(&records[0].payload).expect("must deserialize as CapturedEvent");- let data: RawEvent =- serde_json::from_str(&captured.data).expect("data must deserialize as RawEvent");- assert_eq!(data.properties["$window_id"], "win-456");- });-}--#[tokio::test]-async fn realistic_cookieless_partition_key() {- let h = TestHarness::new();- let mut wrapped = test_utils::wrapped_event("$pageview", "user-1");- wrapped.options.cookieless_mode = Some(true);- let events = prepared(&[&wrapped], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- let expected_key = format!("{}:{}", h.ctx.api_token, h.ctx.client_ip);- h.producer.with_records(|records| {- let key = records[0].key.as_deref().expect("key should be present");- assert_eq!(key, expected_key);- });-}--#[rstest]-#[case::main(0, Some("events_main"))]-#[case::historical(1, Some("events_hist"))]-#[case::overflow(2, Some("events_overflow"))]-#[case::dlq(3, Some("events_dlq"))]-#[case::custom(4, Some("custom_topic"))]-#[case::drop(5, None)]-#[tokio::test]-async fn realistic_spread_destinations_routes_correctly(- #[case] idx: usize,- #[case] expected_topic: Option<&str>,-) {- let h = TestHarness::new();- let all = test_utils::realistic_spread_destinations();- let ev = &all[idx];- let events = prepared(&[ev], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- match expected_topic {- Some(topic) => {- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- h.producer.with_records(|records| {- assert_eq!(records[0].topic, topic);- });- }- None => {- assert!(results.is_empty());- assert_eq!(h.producer.record_count(), 0);- }- }-}--#[tokio::test]-async fn realistic_force_disable_pp_null_partition_key() {- let h = TestHarness::new();- let wrapped = test_utils::wrapped_event("$pageview", "user-1")- .with_force_disable_person_processing(true)- .with_destination(Destination::AnalyticsMain);- let events = prepared(&[&wrapped], &h.ctx);-- let results = h.sink.publish_batch(&h.ctx, &events).await;-- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- h.producer.with_records(|records| {- assert!(records[0].key.is_none());- });-}diff --git a/rust/capture/src/v1/sinks/kafka/types.rs b/rust/capture/src/v1/sinks/kafka/types.rsdeleted file mode 100644index b77a32d8118b..000000000000--- a/rust/capture/src/v1/sinks/kafka/types.rs+++ /dev/null@@ -1,139 +0,0 @@-use std::borrow::Cow;--use chrono::{DateTime, Utc};-use uuid::Uuid;--use super::producer::ProduceError;-use crate::v1::sinks::types::{Outcome, SinkResult};--// ----------------------------------------------------------------------------// error_code_tag-// -----------------------------------------------------------------------------/// Lives in `common_kafka::error` so producers outside capture share one error-/// label vocabulary. Re-exported here because this is the path the sink's-/// callers and DESIGN.md know it by.-pub use common_kafka::error::error_code_tag;--// ----------------------------------------------------------------------------// KafkaSinkError-// -----------------------------------------------------------------------------/// Full-fidelity error enum capturing every failure mode in the Kafka sink.-/// `SinkResult` trait methods derive their output from this.-///-/// Note: "sink not found" is handled at the Router level (`RouterError`),-/// not here. This enum only covers failures within a single configured sink.-#[derive(Debug)]-pub enum KafkaSinkError {- SinkUnavailable,- Produce(ProduceError),- Timeout,- TaskPanicked,-}--impl KafkaSinkError {- pub fn outcome(&self) -> Outcome {- match self {- Self::SinkUnavailable => Outcome::RetriableError,- Self::Produce(e) => {- if e.is_retriable() {- Outcome::RetriableError- } else {- Outcome::FatalError- }- }- Self::Timeout => Outcome::Timeout,- Self::TaskPanicked => Outcome::RetriableError,- }- }-- pub fn as_tag(&self) -> &'static str {- match self {- Self::SinkUnavailable => "sink_unavailable",- Self::Produce(e) => e.as_tag(),- Self::Timeout => "timeout",- Self::TaskPanicked => "task_panicked",- }- }-- pub fn detail(&self) -> Cow<'_, str> {- match self {- Self::SinkUnavailable => Cow::Borrowed("sink unavailable"),- Self::Produce(e) => Cow::Owned(format!("{e}")),- Self::Timeout => Cow::Borrowed("produce timeout"),- Self::TaskPanicked => Cow::Borrowed("task panicked during delivery"),- }- }-}--// ----------------------------------------------------------------------------// KafkaResult-// -----------------------------------------------------------------------------/// Kafka-specific implementation of [`SinkResult`]. Outcome is derived from-/// the error -- no explicit outcome field.-#[derive(Debug)]-pub struct KafkaResult {- uuid: Uuid,- error: Option<KafkaSinkError>,- enqueued_at: DateTime<Utc>,- completed_at: Option<DateTime<Utc>>,-}--impl KafkaResult {- #[allow(dead_code)]- pub(crate) fn ok(uuid: Uuid, enqueued_at: DateTime<Utc>) -> Self {- Self {- uuid,- error: None,- enqueued_at,- completed_at: None,- }- }-- #[allow(dead_code)]- pub(crate) fn err(uuid: Uuid, error: KafkaSinkError, enqueued_at: DateTime<Utc>) -> Self {- Self {- uuid,- error: Some(error),- enqueued_at,- completed_at: None,- }- }-- pub(crate) fn with_completed_at(mut self, t: DateTime<Utc>) -> Self {- self.completed_at = Some(t);- self- }-- pub fn error(&self) -> Option<&KafkaSinkError> {- self.error.as_ref()- }-}--impl SinkResult for KafkaResult {- fn key(&self) -> Uuid {- self.uuid- }-- fn outcome(&self) -> Outcome {- match &self.error {- None => Outcome::Success,- Some(e) => e.outcome(),- }- }-- fn cause(&self) -> Option<&'static str> {- self.error.as_ref().map(|e| e.as_tag())- }-- fn detail(&self) -> Option<Cow<'_, str>> {- self.error.as_ref().map(|e| e.detail())- }-- fn elapsed(&self) -> Option<std::time::Duration> {- self.completed_at- .and_then(|t| t.signed_duration_since(self.enqueued_at).to_std().ok())- }-}diff --git a/rust/capture/src/v1/sinks/mod.rs b/rust/capture/src/v1/sinks/mod.rsdeleted file mode 100644index c8f887192e69..000000000000--- a/rust/capture/src/v1/sinks/mod.rs+++ /dev/null@@ -1,525 +0,0 @@-pub mod constants;-pub mod event;-pub mod kafka;-pub mod prepare;-pub mod router;-pub mod sink;-pub mod types;--use std::collections::HashMap;-use std::str::FromStr;-use std::time::Duration;--use envconfig::Envconfig;--pub use event::Event;-pub use kafka::KafkaSink;-pub use prepare::{serialize_batch, SerializedBatch, DEFAULT_SCATTER_GATHER_MIN_BATCH};-pub use router::{Router, RouterError};-pub use sink::Sink;-pub use types::{Destination, Outcome, PreparedEvent, SerializationFailure, SinkResult};--// ----------------------------------------------------------------------------// SinkName-// -----------------------------------------------------------------------------/// Identity of a v1 sink target. Adding a new sink requires a new variant-/// here plus its `as_str()`, `env_prefix()`, and `FromStr` arms.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]-pub enum SinkName {- /// Primary MSK sink.- Msk,- /// Secondary MSK sink for upgrades, cutovers, or dual-writes.- MskAlt,- /// WarpStream sink for upgrades, cutovers, or dual-writes.- Ws,-}--impl SinkName {- pub fn as_str(&self) -> &'static str {- match self {- Self::Msk => "msk",- Self::MskAlt => "msk_alt",- Self::Ws => "ws",- }- }-- pub fn lifecycle_tag(&self) -> &'static str {- match self {- Self::Msk => "v1-sink-msk",- Self::MskAlt => "v1-sink-msk_alt",- Self::Ws => "v1-sink-ws",- }- }-- pub fn env_prefix(&self) -> &'static str {- match self {- Self::Msk => "CAPTURE_V1_SINK_MSK_",- Self::MskAlt => "CAPTURE_V1_SINK_MSK_ALT_",- Self::Ws => "CAPTURE_V1_SINK_WS_",- }- }-}--impl FromStr for SinkName {- type Err = anyhow::Error;- fn from_str(s: &str) -> Result<Self, Self::Err> {- match s.trim().to_lowercase().as_str() {- "msk" => Ok(Self::Msk),- "msk_alt" => Ok(Self::MskAlt),- "ws" => Ok(Self::Ws),- other => Err(anyhow::anyhow!("unknown sink: {other}")),- }- }-}--impl std::fmt::Display for SinkName {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.write_str(self.as_str())- }-}--// ----------------------------------------------------------------------------// Config (per-sink composite)-// -----------------------------------------------------------------------------/// Composite per-sink configuration. Contains the transport-agnostic-/// produce timeout alongside transport-specific config (Kafka today,-/// S3/etc. in the future).-#[derive(Clone, Debug)]-pub struct Config {- pub produce_timeout: Duration,- pub kafka: kafka::config::Config,-}--impl Config {- pub fn validate(&self) -> anyhow::Result<()> {- let msg_timeout = Duration::from_millis(self.kafka.message_timeout_ms as u64);- anyhow::ensure!(- self.produce_timeout >= msg_timeout,- "produce_timeout ({:?}) must be >= message_timeout_ms ({:?}) \- to avoid ghost deliveries after application-level timeout",- self.produce_timeout,- msg_timeout,- );- self.kafka.validate()?;- Ok(())- }-}--// ----------------------------------------------------------------------------// Sinks (loaded collection)-// -----------------------------------------------------------------------------/// Parsed set of v1 sink configs. The first entry in the CSV is the-/// default sink for single-write mode.-pub struct Sinks {- pub default: SinkName,- pub configs: HashMap<SinkName, Config>,-}--impl Sinks {- pub fn validate(&self) -> anyhow::Result<()> {- anyhow::ensure!(!self.configs.is_empty(), "no v1 sinks configured");- anyhow::ensure!(- self.configs.contains_key(&self.default),- "default sink '{}' is not present in configured sinks",- self.default,- );- for (&name, cfg) in &self.configs {- cfg.validate()- .map_err(|e| anyhow::anyhow!("sink {}: {e}", name))?;- }- Ok(())- }-}--// ----------------------------------------------------------------------------// Loaders-// -----------------------------------------------------------------------------/// Production entry point: reads env vars and loads sink configs.-pub fn load_sinks(sinks_csv: &str) -> anyhow::Result<Sinks> {- let env: HashMap<String, String> = std::env::vars().collect();- load_sinks_from(sinks_csv, &env)-}--/// Parse the comma-separated sink names without loading per-sink configs.-/// Used by `register_components` to register lifecycle handles before the-/// full config is available.-pub fn parse_sink_names(sinks_csv: &str) -> anyhow::Result<Vec<SinkName>> {- let names: Vec<SinkName> = sinks_csv- .split(',')- .filter(|s| !s.trim().is_empty())- .map(|s| s.parse::<SinkName>())- .collect::<Result<_, _>>()- .map_err(|e| anyhow::anyhow!("bad CAPTURE_V1_SINKS: {e}"))?;-- anyhow::ensure!(!names.is_empty(), "CAPTURE_V1_SINKS is empty");- Ok(names)-}--/// Testable core: loads sink configs from a provided env snapshot.-pub fn load_sinks_from(sinks_csv: &str, env: &HashMap<String, String>) -> anyhow::Result<Sinks> {- let names = parse_sink_names(sinks_csv)?;- let default = names[0];-- let mut configs = HashMap::new();- for name in names {- let config = load_sink_config(name, env)- .map_err(|e| anyhow::anyhow!("sink {}: {e}", name.as_str()))?;- configs.insert(name, config);- }- Ok(Sinks { default, configs })-}--/// Load a single sink's config by stripping its env prefix and splitting-/// keys by the `KAFKA_` sub-prefix.-fn load_sink_config(name: SinkName, env: &HashMap<String, String>) -> anyhow::Result<Config> {- let prefix = name.env_prefix();-- // Collect prefixes of other sinks so we can skip keys that belong to a- // longer prefix (e.g. MSK_ALT_ keys when loading MSK_).- let other_prefixes: Vec<&str> = [SinkName::Msk, SinkName::MskAlt, SinkName::Ws]- .iter()- .filter(|n| **n != name)- .map(|n| n.env_prefix())- .collect();-- let mut kafka_map = HashMap::new();- let mut sink_map = HashMap::new();- for (k, v) in env {- if let Some(rest) = k.strip_prefix(prefix) {- if other_prefixes.iter().any(|op| k.starts_with(op)) {- continue;- }- if let Some(kafka_key) = rest.strip_prefix("KAFKA_") {- kafka_map.insert(kafka_key.to_string(), v.clone());- } else {- sink_map.insert(rest.to_string(), v.clone());- }- }- }-- let kafka = kafka::config::Config::init_from_hashmap(&kafka_map)- .map_err(|e| anyhow::anyhow!("kafka config: {e}"))?;-- let produce_timeout_ms: u64 = sink_map- .get("PRODUCE_TIMEOUT_MS")- .map(|v| v.parse::<u64>())- .transpose()- .map_err(|e| anyhow::anyhow!("bad PRODUCE_TIMEOUT_MS: {e}"))?- .unwrap_or(constants::DEFAULT_PRODUCE_TIMEOUT.as_millis() as u64);-- Ok(Config {- produce_timeout: Duration::from_millis(produce_timeout_ms),- kafka,- })-}--// ----------------------------------------------------------------------------// Tests-// -----------------------------------------------------------------------------#[cfg(test)]-mod tests {- use std::collections::HashMap;- use std::time::Duration;-- use super::*;-- /// Build a minimal valid env hashmap for a given SinkName.- fn test_env_for(name: SinkName) -> HashMap<String, String> {- let prefix = name.env_prefix();- [- (- format!("{prefix}PRODUCE_TIMEOUT_MS"),- constants::DEFAULT_PRODUCE_TIMEOUT.as_millis().to_string(),- ),- (format!("{prefix}KAFKA_HOSTS"), "localhost:9092".into()),- (format!("{prefix}KAFKA_TOPIC_MAIN"), "events_main".into()),- (- format!("{prefix}KAFKA_TOPIC_HISTORICAL"),- "events_hist".into(),- ),- (- format!("{prefix}KAFKA_TOPIC_OVERFLOW"),- "events_overflow".into(),- ),- (format!("{prefix}KAFKA_TOPIC_DLQ"), "events_dlq".into()),- (- format!("{prefix}KAFKA_TOPIC_EXCEPTION"),- "error_tracking_events".into(),- ),- (- format!("{prefix}KAFKA_TOPIC_HEATMAP"),- "heatmaps_ingestion".into(),- ),- (- format!("{prefix}KAFKA_TOPIC_CLIENT_INGESTION_WARNING"),- "events_plugin_ingestion".into(),- ),- ]- .into_iter()- .collect()- }-- // -- SinkName tests ---- #[test]- fn parse_valid_names() {- assert_eq!("msk".parse::<SinkName>().unwrap(), SinkName::Msk);- assert_eq!("msk_alt".parse::<SinkName>().unwrap(), SinkName::MskAlt);- assert_eq!("ws".parse::<SinkName>().unwrap(), SinkName::Ws);- }-- #[test]- fn parse_case_insensitive() {- assert_eq!("MSK".parse::<SinkName>().unwrap(), SinkName::Msk);- assert_eq!("Msk_Alt".parse::<SinkName>().unwrap(), SinkName::MskAlt);- assert_eq!("WS".parse::<SinkName>().unwrap(), SinkName::Ws);- }-- #[test]- fn parse_unknown_name() {- assert!("foo".parse::<SinkName>().is_err());- assert!("warpstream".parse::<SinkName>().is_err());- }-- #[test]- fn parse_empty_string() {- assert!("".parse::<SinkName>().is_err());- }-- #[test]- fn env_prefix_correctness() {- assert_eq!(SinkName::Msk.env_prefix(), "CAPTURE_V1_SINK_MSK_");- assert_eq!(SinkName::MskAlt.env_prefix(), "CAPTURE_V1_SINK_MSK_ALT_");- assert_eq!(SinkName::Ws.env_prefix(), "CAPTURE_V1_SINK_WS_");- }-- #[test]- fn as_str_round_trip() {- for name in [SinkName::Msk, SinkName::MskAlt, SinkName::Ws] {- let parsed: SinkName = name.as_str().parse().unwrap();- assert_eq!(parsed, name);- }- }-- // -- load_sink_config tests ---- #[test]- fn two_pass_split_routes_kafka_keys() {- let env = test_env_for(SinkName::Msk);- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- assert_eq!(cfg.kafka.hosts, "localhost:9092");- assert_eq!(cfg.produce_timeout, constants::DEFAULT_PRODUCE_TIMEOUT);- }-- #[test]- fn produce_timeout_default() {- let mut env = test_env_for(SinkName::Msk);- env.remove("CAPTURE_V1_SINK_MSK_PRODUCE_TIMEOUT_MS");- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- assert_eq!(cfg.produce_timeout, constants::DEFAULT_PRODUCE_TIMEOUT);- }-- #[test]- fn produce_timeout_custom() {- let mut env = test_env_for(SinkName::Msk);- env.insert(- "CAPTURE_V1_SINK_MSK_PRODUCE_TIMEOUT_MS".into(),- "45000".into(),- );- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- assert_eq!(cfg.produce_timeout, Duration::from_millis(45000));- }-- #[test]- fn produce_timeout_invalid() {- let mut env = test_env_for(SinkName::Msk);- env.insert(- "CAPTURE_V1_SINK_MSK_PRODUCE_TIMEOUT_MS".into(),- "abc".into(),- );- assert!(load_sink_config(SinkName::Msk, &env).is_err());- }-- #[test]- fn kafka_sub_prefix_stripped() {- let mut env = test_env_for(SinkName::Msk);- env.insert("CAPTURE_V1_SINK_MSK_KAFKA_LINGER_MS".into(), "50".into());- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- assert_eq!(cfg.kafka.linger_ms, 50);- }-- #[test]- fn msk_alt_keys_do_not_leak_into_msk_config() {- let mut env = test_env_for(SinkName::Msk);- env.insert(- "CAPTURE_V1_SINK_MSK_ALT_KAFKA_HOSTS".into(),- "alt-host:9092".into(),- );- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- assert_eq!(- cfg.kafka.hosts, "localhost:9092",- "MSK_ALT host should not leak into MSK config"- );- }-- #[test]- fn non_kafka_keys_ignored_by_kafka_config() {- let mut env = test_env_for(SinkName::Msk);- env.insert(- "CAPTURE_V1_SINK_MSK_SOME_FUTURE_FIELD".into(),- "whatever".into(),- );- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- assert_eq!(cfg.kafka.hosts, "localhost:9092");- }-- #[test]- fn missing_kafka_hosts_errors() {- let mut env = test_env_for(SinkName::Msk);- env.remove("CAPTURE_V1_SINK_MSK_KAFKA_HOSTS");- assert!(load_sink_config(SinkName::Msk, &env).is_err());- }-- // -- load_sinks_from tests ---- #[test]- fn single_sink_csv() {- let env = test_env_for(SinkName::Msk);- let sinks = load_sinks_from("msk", &env).unwrap();- assert_eq!(sinks.default, SinkName::Msk);- assert_eq!(sinks.configs.len(), 1);- assert!(sinks.configs.contains_key(&SinkName::Msk));- }-- #[test]- fn multi_sink_csv() {- let mut env = test_env_for(SinkName::Msk);- env.extend(test_env_for(SinkName::Ws));- let sinks = load_sinks_from("msk,ws", &env).unwrap();- assert_eq!(sinks.default, SinkName::Msk);- assert_eq!(sinks.configs.len(), 2);- }-- #[test]- fn default_is_first_entry() {- let mut env = test_env_for(SinkName::Ws);- env.extend(test_env_for(SinkName::Msk));- let sinks = load_sinks_from("ws,msk", &env).unwrap();- assert_eq!(sinks.default, SinkName::Ws);- }-- #[test]- fn empty_csv_errors() {- let env = HashMap::new();- assert!(load_sinks_from("", &env).is_err());- }-- #[test]- fn unknown_name_in_csv_errors() {- let env = test_env_for(SinkName::Msk);- assert!(load_sinks_from("msk,bogus", &env).is_err());- }-- #[test]- fn missing_env_for_listed_sink_errors() {- let env = HashMap::new();- assert!(load_sinks_from("msk", &env).is_err());- }-- // -- validation tests ---- #[test]- fn config_validate_ok() {- let env = test_env_for(SinkName::Msk);- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- assert!(cfg.validate().is_ok());- }-- #[test]- fn config_validate_timeout_too_short() {- let mut env = test_env_for(SinkName::Msk);- env.insert(- "CAPTURE_V1_SINK_MSK_PRODUCE_TIMEOUT_MS".into(),- "15000".into(),- );- env.insert(- "CAPTURE_V1_SINK_MSK_KAFKA_MESSAGE_TIMEOUT_MS".into(),- "20000".into(),- );- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- let err = cfg.validate().unwrap_err();- assert!(- err.to_string().contains("produce_timeout"),- "expected produce_timeout in error: {err}"- );- }-- #[test]- fn config_validate_empty_hosts() {- let mut env = test_env_for(SinkName::Msk);- env.insert("CAPTURE_V1_SINK_MSK_KAFKA_HOSTS".into(), "".into());- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- let err = cfg.validate().unwrap_err();- assert!(- err.to_string().contains("empty kafka hosts"),- "expected empty hosts in error: {err}"- );- }-- #[test]- fn sinks_validate_empty_map() {- let sinks = Sinks {- default: SinkName::Msk,- configs: HashMap::new(),- };- assert!(sinks.validate().is_err());- }-- #[test]- fn config_validate_propagates_kafka_validation() {- let mut env = test_env_for(SinkName::Msk);- env.insert("CAPTURE_V1_SINK_MSK_KAFKA_QUEUE_MIB".into(), "0".into());- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- let err = cfg.validate().unwrap_err();- assert!(- err.to_string().contains("queue_mib"),- "expected queue_mib in error: {err}"- );- }-- #[test]- fn sinks_validate_default_not_in_configs() {- let env = test_env_for(SinkName::Msk);- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- let sinks = Sinks {- default: SinkName::Ws,- configs: [(SinkName::Msk, cfg)].into_iter().collect(),- };- let err = sinks.validate().unwrap_err();- assert!(- err.to_string().contains("default sink"),- "expected 'default sink' in error: {err}"- );- }-- #[test]- fn sinks_validate_propagates_config_error() {- let mut env = test_env_for(SinkName::Msk);- env.insert("CAPTURE_V1_SINK_MSK_KAFKA_HOSTS".into(), "".into());- let cfg = load_sink_config(SinkName::Msk, &env).unwrap();- let sinks = Sinks {- default: SinkName::Msk,- configs: [(SinkName::Msk, cfg)].into_iter().collect(),- };- let err = sinks.validate().unwrap_err();- assert!(- err.to_string().contains("sink msk"),- "expected sink name in error: {err}"- );- }-}diff --git a/rust/capture/src/v1/sinks/router.rs b/rust/capture/src/v1/sinks/router.rsdeleted file mode 100644index d66c9ed4f438..000000000000--- a/rust/capture/src/v1/sinks/router.rs+++ /dev/null@@ -1,316 +0,0 @@-use std::collections::HashMap;-use std::fmt;--use futures::stream::FuturesUnordered;-use futures::StreamExt;--use crate::v1::context::RequestContext;-use crate::v1::sinks::sink::Sink;-use crate::v1::sinks::types::{PreparedEvent, SinkResult};-use crate::v1::sinks::SinkName;--// ----------------------------------------------------------------------------// RouterError-// -----------------------------------------------------------------------------/// Batch-level routing errors. These are caller bugs (requesting a sink that-/// doesn't exist), not per-event concerns.-#[derive(Debug)]-pub enum RouterError {- SinkNotFound(SinkName),-}--impl fmt::Display for RouterError {- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- match self {- Self::SinkNotFound(name) => write!(f, "sink not found: {name}"),- }- }-}--impl std::error::Error for RouterError {}--// ----------------------------------------------------------------------------// Router-// -----------------------------------------------------------------------------/// Routes publish requests to the appropriate [`Sink`] by [`SinkName`].-///-/// Owns the mapping of configured sink names to concrete sink implementations-/// and the default sink for single-write mode.-pub struct Router {- default: SinkName,- sinks: HashMap<SinkName, Box<dyn Sink>>,-}--impl Router {- pub fn new(default: SinkName, sinks: HashMap<SinkName, Box<dyn Sink>>) -> Self {- Self { default, sinks }- }-- pub fn default_sink(&self) -> SinkName {- self.default- }-- pub fn available_sinks(&self) -> Vec<SinkName> {- self.sinks.keys().copied().collect()- }-- /// Publish a batch of already-serialized events to the named sink.- pub async fn publish_batch(- &self,- sink: SinkName,- ctx: &RequestContext,- events: &[PreparedEvent],- ) -> Result<Vec<Box<dyn SinkResult>>, RouterError> {- let target = self- .sinks- .get(&sink)- .ok_or(RouterError::SinkNotFound(sink))?;- Ok(target.publish_batch(ctx, events).await)- }-- /// Convenience wrapper for single-event publish.- pub async fn publish(- &self,- sink: SinkName,- ctx: &RequestContext,- event: &PreparedEvent,- ) -> Result<Option<Box<dyn SinkResult>>, RouterError> {- let results = self- .publish_batch(sink, ctx, std::slice::from_ref(event))- .await?;- Ok(results.into_iter().next())- }-- /// Flush all sinks concurrently for graceful shutdown.- pub async fn flush(&self) -> anyhow::Result<()> {- let mut futs = FuturesUnordered::new();- for (name, sink) in &self.sinks {- let name = *name;- futs.push(async move { sink.flush().await.map_err(|e| (name, e)) });- }- let mut errors: Vec<String> = Vec::new();- while let Some(result) = futs.next().await {- if let Err((name, e)) = result {- errors.push(format!("sink {name}: {e:#}"));- }- }- if errors.is_empty() {- Ok(())- } else {- Err(anyhow::anyhow!("{}", errors.join("; ")))- }- }-}--// ----------------------------------------------------------------------------// Tests-// -----------------------------------------------------------------------------#[cfg(test)]-mod tests {- use std::collections::HashMap;- use std::sync::Arc;- use std::time::Duration;-- use common_types::CapturedEventHeaders;- use uuid::Uuid;-- use crate::ordering::OrderingGuarantee;-- use crate::config::CaptureMode;- use crate::v1::context::RequestContext;- use crate::v1::sinks::event::Event;- use crate::v1::sinks::kafka::mock::MockProducer;- use crate::v1::sinks::kafka::sink::KafkaSink;- use crate::v1::sinks::sink::Sink;- use crate::v1::sinks::types::Outcome;- use crate::v1::sinks::{Config, Destination, SinkName};-- use super::*;-- // -- Test helpers ---------------------------------------------------------- use crate::v1::test_utils::prepared;-- struct FakeEvent {- parsed_uuid: Uuid,- publish: bool,- destination: Destination,- }-- impl FakeEvent {- fn ok(_uuid: &str) -> Self {- Self {- parsed_uuid: Uuid::new_v4(),- publish: true,- destination: Destination::AnalyticsMain,- }- }- }-- impl Event for FakeEvent {- fn uuid(&self) -> Uuid {- self.parsed_uuid- }-- fn should_publish(&self) -> bool {- self.publish- }- fn destination(&self) -> &Destination {- &self.destination- }- fn headers(&self, _ctx: &RequestContext) -> CapturedEventHeaders {- CapturedEventHeaders {- token: None,- distinct_id: None,- session_id: None,- timestamp: None,- event: None,- uuid: None,- 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 partition_key(&self, _ctx: &RequestContext) -> String {- format!("key:{}", self.uuid())- }- fn ordering(&self) -> OrderingGuarantee {- OrderingGuarantee::PerDistinctId- }- fn serialize(&self, _ctx: &RequestContext) -> anyhow::Result<bytes::Bytes> {- Ok(bytes::Bytes::from(r#"{"event":"test"}"#.to_string()))- }- }-- fn build_sink(name: SinkName, handle: lifecycle::Handle) -> Box<dyn Sink> {- let producer = Arc::new(MockProducer::new(name, handle.clone()));- let config = Config {- produce_timeout: Duration::from_secs(30),- kafka: crate::v1::test_utils::test_kafka_config(),- };- Box::new(KafkaSink::new(- name,- producer,- config,- CaptureMode::Events,- handle,- ))- }-- fn test_router(- default: SinkName,- names: &[SinkName],- ) -> (Router, lifecycle::Handle, lifecycle::MonitorGuard) {- let mut manager = lifecycle::Manager::builder("test")- .with_trap_signals(false)- .with_prestop_check(false)- .build();- let handle = manager.register("router_test", lifecycle::ComponentOptions::new());- handle.report_healthy();- let monitor = manager.monitor_background();-- let sinks: HashMap<SinkName, Box<dyn Sink>> = names- .iter()- .map(|&n| (n, build_sink(n, handle.clone())))- .collect();- let router = Router::new(default, sinks);- (router, handle, monitor)- }-- fn test_ctx() -> RequestContext {- let mut ctx = crate::v1::test_utils::test_context();- ctx.created_at = None;- ctx- }-- // -- Tests ----------------------------------------------------------------- #[test]- fn default_sink_returns_configured_default() {- let (router, _handle, _monitor) = test_router(SinkName::Msk, &[SinkName::Msk]);- assert_eq!(router.default_sink(), SinkName::Msk);- }-- #[test]- fn available_sinks_returns_all_configured() {- let (router, _handle, _monitor) =- test_router(SinkName::Msk, &[SinkName::Msk, SinkName::Ws]);- let mut available = router.available_sinks();- available.sort_by_key(|n| n.as_str());- assert_eq!(available, vec![SinkName::Msk, SinkName::Ws]);- }-- #[tokio::test]- async fn publish_batch_routes_to_correct_sink() {- let (router, _handle, _monitor) =- test_router(SinkName::Msk, &[SinkName::Msk, SinkName::Ws]);- let ctx = test_ctx();- let event = FakeEvent::ok("evt-1");- let events = prepared(&[&event], &ctx);-- let results = router- .publish_batch(SinkName::Msk, &ctx, &events)- .await- .unwrap();- assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);- }-- #[tokio::test]- async fn publish_batch_sink_not_found() {- let (router, _handle, _monitor) = test_router(SinkName::Msk, &[SinkName::Msk]);- let ctx = test_ctx();- let event = FakeEvent::ok("evt-1");- let events = prepared(&[&event], &ctx);-- match router.publish_batch(SinkName::Ws, &ctx, &events).await {- Err(RouterError::SinkNotFound(SinkName::Ws)) => {}- Err(e) => panic!("expected SinkNotFound(Ws), got: {e}"),- Ok(_) => panic!("expected error, got Ok"),- }- }-- #[tokio::test]- async fn publish_single_event_success() {- let (router, _handle, _monitor) = test_router(SinkName::Msk, &[SinkName::Msk]);- let ctx = test_ctx();- let event = FakeEvent::ok("evt-1");- let prepared = prepared(&[&event], &ctx);-- let result = router- .publish(SinkName::Msk, &ctx, &prepared[0])- .await- .unwrap();- assert!(result.is_some());- assert_eq!(result.unwrap().outcome(), Outcome::Success);- }-- #[tokio::test]- async fn publish_sink_not_found() {- let (router, _handle, _monitor) = test_router(SinkName::Msk, &[SinkName::Msk]);- let ctx = test_ctx();- let event = FakeEvent::ok("evt-1");- let prepared = prepared(&[&event], &ctx);-- match router.publish(SinkName::Ws, &ctx, &prepared[0]).await {- Err(RouterError::SinkNotFound(SinkName::Ws)) => {}- Err(e) => panic!("expected SinkNotFound(Ws), got: {e}"),- Ok(_) => panic!("expected error, got Ok"),- }- }-- #[tokio::test]- async fn flush_all_sinks() {- let (router, _handle, _monitor) =- test_router(SinkName::Msk, &[SinkName::Msk, SinkName::Ws]);- assert!(router.flush().await.is_ok());- }-}diff --git a/rust/capture/src/v1/sinks/sink.rs b/rust/capture/src/v1/sinks/sink.rsdeleted file mode 100644index 7ec6dd5c8c2b..000000000000--- a/rust/capture/src/v1/sinks/sink.rs+++ /dev/null@@ -1,24 +0,0 @@-use async_trait::async_trait;--use crate::v1::context::RequestContext;-use crate::v1::sinks::types::{PreparedEvent, SinkResult};-use crate::v1::sinks::SinkName;--/// Backend-agnostic publishing interface for a single sink target.-#[async_trait]-pub trait Sink: Send + Sync {- /// Identity of this sink (used for metrics and logging).- fn name(&self) -> SinkName;-- /// Publish a batch of already-serialized events. Returns one result per- /// event the sink attempted; events the sink itself drops (e.g. a- /// destination with no configured topic) produce no result.- async fn publish_batch(- &self,- ctx: &RequestContext,- events: &[PreparedEvent],- ) -> Vec<Box<dyn SinkResult>>;-- /// Flush the underlying producer for graceful shutdown.- async fn flush(&self) -> anyhow::Result<()>;-}diff --git a/rust/capture/src/v1/sinks/types.rs b/rust/capture/src/v1/sinks/types.rsdeleted file mode 100644index 4920e6e8998c..000000000000--- a/rust/capture/src/v1/sinks/types.rs+++ /dev/null@@ -1,417 +0,0 @@-use std::borrow::Cow;-use std::collections::HashMap;-use std::fmt;--use common_types::CapturedEventHeaders;-use uuid::Uuid;--use crate::event_restrictions::Pipeline;-use crate::ordering::OrderingGuarantee;--/// Kafka topic routing for a processed event.-/// `Drop` means the event should not be produced at all.-#[derive(Debug, Default, Clone, PartialEq, Eq)]-pub enum Destination {- #[default]- AnalyticsMain,- AnalyticsHistorical,- Overflow,- Dlq,- Custom(String),- Drop,- ExceptionErrorTracking,- HeatmapMain,- ClientIngestionWarning,- AiEvents,- /// Overflow lane for `AiEvents`. Only produced when the AI overflow- /// valve (`CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC`) is armed; overflow on the AI lane- /// lands here, never on the analytics `Overflow` destination.- AiEventsOverflow,-}--impl Destination {- /// Returns true for destinations that flow through the analytics ingestion- /// pipeline (and are therefore subject to analytics-scoped restrictions,- /// overflow routing, etc). Mirrors legacy `DataType::is_analytics_pipeline`.- ///- /// `AiEvents` is false: `$ai_*` events are diverted out of the analytics- /// pipeline into a dedicated AI lane, just like heatmaps/exceptions.- pub fn is_analytics_pipeline(&self) -> bool {- matches!(self, Self::AnalyticsMain | Self::AnalyticsHistorical)- }-- /// Restriction pipeline this destination is governed by, if any. Mirrors- /// legacy `DataType::pipeline`: the AI lane (including its overflow arm)- /// consults ai-scoped restrictions, the analytics lanes consult analytics- /// ones. `None` destinations flow through unrestricted — either they have- /// no shared restriction config (heatmaps, ingestion warnings) or they are- /// themselves restriction/terminal outcomes (Dlq, Custom, Drop).- pub fn pipeline(&self) -> Option<Pipeline> {- match self {- Self::AnalyticsMain | Self::AnalyticsHistorical | Self::Overflow => {- Some(Pipeline::Analytics)- }- Self::AiEvents | Self::AiEventsOverflow => Some(Pipeline::Ai),- Self::ExceptionErrorTracking => Some(Pipeline::ErrorTracking),- Self::HeatmapMain | Self::ClientIngestionWarning | Self::Dlq | Self::Custom(_) => None,- Self::Drop => None,- }- }-- /// Whether this lane exists to absorb hot keys, and so may publish without- /// a partition key to spread load across partitions.- ///- /// Everything else keeps its key even when person processing is off,- /// because its consumers rely on per-distinct-id ordering: historical- /// backfills, the dlq, admin custom redirects, and the AI main topic.- /// Matches the lanes legacy `route()` resolves through `person_ordering`.- ///- /// Exhaustive on purpose: a new destination has to state which side it is- /// on rather than silently inheriting "keeps its key".- pub fn absorbs_hot_keys(&self) -> bool {- match self {- Self::AnalyticsMain | Self::Overflow | Self::AiEventsOverflow => true,- Self::AnalyticsHistorical- | Self::Dlq- | Self::Custom(_)- | Self::ExceptionErrorTracking- | Self::HeatmapMain- | Self::ClientIngestionWarning- | Self::AiEvents => false,- // Never published, so it never reaches a partition key.- Self::Drop => false,- }- }-- /// Whether this lane's consumer runs person processing with writes. On- /// such a lane one distinct id must stay on one partition while person- /// processing is on — spreading it turns a hot key into contended- /// person-row updates — so a spread decision only takes effect once the- /// person-processing flag is set. Read-only consumers (the AI lanes,- /// error tracking) and lanes with no person processing at all (heatmaps,- /// client warnings) can take keyless records at any time. The dlq and- /// custom redirects replay into analytics ingestion, so they count as- /// person-writing.- ///- /// Exhaustive for the same reason as [`Self::absorbs_hot_keys`].- pub fn writes_persons(&self) -> bool {- match self {- Self::AnalyticsMain- | Self::AnalyticsHistorical- | Self::Overflow- | Self::Dlq- | Self::Custom(_) => true,- Self::AiEvents- | Self::AiEventsOverflow- | Self::ExceptionErrorTracking- | Self::HeatmapMain- | Self::ClientIngestionWarning => false,- // Never published, so it never reaches a consumer.- Self::Drop => false,- }- }-- /// Stable, low-cardinality metric tag. `Custom(_)` collapses to "custom"- /// so admin-configured topic names never become label values.- pub fn as_tag(&self) -> &'static str {- match self {- Self::AnalyticsMain => "analytics_main",- Self::AnalyticsHistorical => "analytics_historical",- Self::Overflow => "overflow",- Self::Dlq => "dlq",- Self::Custom(_) => "custom",- Self::Drop => "drop",- Self::ExceptionErrorTracking => "exception_error_tracking",- Self::HeatmapMain => "heatmap_main",- Self::ClientIngestionWarning => "client_ingestion_warning",- Self::AiEvents => "ai_events",- Self::AiEventsOverflow => "ai_events_overflow",- }- }-}--#[cfg(test)]-mod destination_tests {- use super::Destination;-- #[test]- fn is_analytics_pipeline_true_for_main_and_historical() {- assert!(Destination::AnalyticsMain.is_analytics_pipeline());- assert!(Destination::AnalyticsHistorical.is_analytics_pipeline());- }-- #[test]- fn is_analytics_pipeline_false_for_non_analytics() {- assert!(!Destination::ExceptionErrorTracking.is_analytics_pipeline());- assert!(!Destination::HeatmapMain.is_analytics_pipeline());- assert!(!Destination::ClientIngestionWarning.is_analytics_pipeline());- assert!(!Destination::AiEvents.is_analytics_pipeline());- assert!(!Destination::AiEventsOverflow.is_analytics_pipeline());- assert!(!Destination::Overflow.is_analytics_pipeline());- assert!(!Destination::Dlq.is_analytics_pipeline());- assert!(!Destination::Drop.is_analytics_pipeline());- assert!(!Destination::Custom("foo".into()).is_analytics_pipeline());- }-- /// Exhaustive: every variant's tag is non-empty, stable, and unique.- /// Custom(_) collapses to "custom" regardless of the topic name, so two- /// different Custom values share the same tag (cardinality defense).- #[test]- fn as_tag_exhaustive_stable_and_unique() {- // One representative per variant. If a new variant is added, the- // as_tag() match becomes non-exhaustive and this file fails to- // compile, forcing an update here too.- let expected: &[(Destination, &str)] = &[- (Destination::AnalyticsMain, "analytics_main"),- (Destination::AnalyticsHistorical, "analytics_historical"),- (Destination::Overflow, "overflow"),- (Destination::Dlq, "dlq"),- (Destination::Custom("topic_a".into()), "custom"),- (Destination::Drop, "drop"),- (- Destination::ExceptionErrorTracking,- "exception_error_tracking",- ),- (Destination::HeatmapMain, "heatmap_main"),- (- Destination::ClientIngestionWarning,- "client_ingestion_warning",- ),- (Destination::AiEvents, "ai_events"),- (Destination::AiEventsOverflow, "ai_events_overflow"),- ];-- let mut seen = std::collections::HashSet::new();- for (dest, tag) in expected {- assert_eq!(dest.as_tag(), *tag, "tag changed for {dest:?}");- assert!(!tag.is_empty(), "tag for {dest:?} must be non-empty");- assert!(seen.insert(*tag), "tag {tag} is not unique across variants");- }-- // Two different Custom values collapse to the same "custom" tag.- assert_eq!(Destination::Custom("topic_b".into()).as_tag(), "custom");- assert_eq!(- Destination::Custom("topic_a".into()).as_tag(),- Destination::Custom("topic_b".into()).as_tag()- );- }-}--// ----------------------------------------------------------------------------// Outcome-// -----------------------------------------------------------------------------/// What happened when a publish attempt resolved.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum Outcome {- Success,- Timeout,- RetriableError,- FatalError,-}--impl Outcome {- pub fn as_tag(&self) -> &'static str {- match self {- Self::Success => "success",- Self::Timeout => "timeout",- Self::RetriableError => "retriable_error",- Self::FatalError => "fatal_error",- }- }-}--// ----------------------------------------------------------------------------// SinkResult-// -----------------------------------------------------------------------------/// Backend-agnostic trait for introspecting per-event publish results.-pub trait SinkResult: Send + Sync {- /// Correlation key -- the originating event's UUID.- fn key(&self) -> Uuid;-- fn outcome(&self) -> Outcome;-- /// Stable, low-cardinality tag for metrics. None on success.- fn cause(&self) -> Option<&'static str>;-- /// Rich human-readable error detail for logging. None on success.- fn detail(&self) -> Option<Cow<'_, str>>;-- /// Time between batch enqueue and this event's ack completion.- /// None if the event never entered the ack path (immediate error).- fn elapsed(&self) -> Option<std::time::Duration>;-}--// ----------------------------------------------------------------------------// PreparedEvent-// -----------------------------------------------------------------------------/// Storage-agnostic, fully-owned output of the serialize step. Produced by-/// [`serialize_batch`](super::prepare::serialize_batch) and consumed by any-/// [`Sink`](super::sink::Sink). Owns its payload (`Bytes`) so it can be cloned-/// across multiple sinks (dual-write) without re-encoding and moved into-/// spawned tasks. The Sink resolves `destination` to a concrete backend target-/// and applies its own routing policy (e.g. nulling `partition_key`).-#[derive(Debug, Clone)]-pub struct PreparedEvent {- pub uuid: Uuid,- pub destination: Destination,- pub payload: bytes::Bytes,- pub headers: CapturedEventHeaders,- /// 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,-}--// ----------------------------------------------------------------------------// SerializationFailure-// -----------------------------------------------------------------------------/// `SinkResult` for an event that failed during the serialize step (before any-/// sink saw it). Always fatal (non-retriable) and has no ack latency.-#[derive(Debug, Clone)]-pub struct SerializationFailure {- uuid: Uuid,- cause: &'static str,- detail: String,-}--impl SerializationFailure {- pub fn from_error(uuid: Uuid, detail: String) -> Self {- Self {- uuid,- cause: "serialization_failed",- detail,- }- }-- pub fn panicked(uuid: Uuid) -> Self {- Self {- uuid,- cause: "serialization_panic",- detail: "serialization task panicked".to_string(),- }- }-- pub fn is_panic(&self) -> bool {- self.cause == "serialization_panic"- }-- pub fn uuid(&self) -> Uuid {- self.uuid- }-- pub fn detail_str(&self) -> &str {- &self.detail- }-}--impl SinkResult for SerializationFailure {- fn key(&self) -> Uuid {- self.uuid- }-- fn outcome(&self) -> Outcome {- Outcome::FatalError- }-- fn cause(&self) -> Option<&'static str> {- Some(self.cause)- }-- fn detail(&self) -> Option<Cow<'_, str>> {- Some(Cow::Borrowed(&self.detail))- }-- fn elapsed(&self) -> Option<std::time::Duration> {- None- }-}--// ----------------------------------------------------------------------------// BatchSummary-// -----------------------------------------------------------------------------/// Aggregated stats for a batch of publish results.-pub struct BatchSummary {- pub total: usize,- pub succeeded: usize,- pub retriable: usize,- pub fatal: usize,- pub timed_out: usize,- /// Counts keyed by cause tag (e.g. "queue_full", "timeout").- pub errors: HashMap<&'static str, usize>,-}--impl BatchSummary {- pub fn from_results(results: &[Box<dyn SinkResult>]) -> Self {- let mut succeeded = 0usize;- let mut retriable = 0usize;- let mut fatal = 0usize;- let mut timed_out = 0usize;- let mut errors: HashMap<&'static str, usize> = HashMap::new();-- for r in results {- match r.outcome() {- Outcome::Success => succeeded += 1,- Outcome::Timeout => {- timed_out += 1;- if let Some(tag) = r.cause() {- *errors.entry(tag).or_default() += 1;- }- }- Outcome::RetriableError => {- retriable += 1;- if let Some(tag) = r.cause() {- *errors.entry(tag).or_default() += 1;- }- }- Outcome::FatalError => {- fatal += 1;- if let Some(tag) = r.cause() {- *errors.entry(tag).or_default() += 1;- }- }- }- }-- Self {- total: results.len(),- succeeded,- retriable,- fatal,- timed_out,- errors,- }- }-- pub fn all_ok(&self) -> bool {- self.retriable == 0 && self.fatal == 0 && self.timed_out == 0- }-}--impl fmt::Display for BatchSummary {- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- write!(- f,- "{} total, {} ok, {} retriable, {} fatal, {} timed_out",- self.total, self.succeeded, self.retriable, self.fatal, self.timed_out- )?;- if !self.errors.is_empty() {- let mut pairs: Vec<_> = self.errors.iter().collect();- pairs.sort_by_key(|(_, count)| std::cmp::Reverse(**count));- write!(f, " (")?;- for (i, (tag, count)) in pairs.iter().enumerate() {- if i > 0 {- write!(f, ", ")?;- }- write!(f, "{}={}", tag, count)?;- }- write!(f, ")")?;- }- Ok(())- }-}diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex 5574a5ed9ccd..d3aa15febbd4 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -7,24 +7,27 @@ use chrono::{DateTime, Utc};use serde_json::value::RawValue;use uuid::Uuid;+use crate::outputs::PreparedEvent;use crate::v1::analytics::constants::CAPTURE_V1_PATH;use crate::v1::analytics::context::Context as AnalyticsContext;use crate::v1::analytics::query::Query;use crate::v1::analytics::types::{Event, EventResult, Options, RawOptions, WrappedEvent};use crate::v1::context::RequestContext;-use crate::v1::sinks::event::Event as SinkEvent;-use crate::v1::sinks::types::PreparedEvent;-use crate::v1::sinks::Destination;+use crate::v1::types::{Destination, Publishable};-/// Serialize publishable events into `PreparedEvent`s for driving sinks in tests.-/// Accepts `&[&dyn Event]` (integration) or `&[&ConcreteType]` (unit) via `?Sized`.-pub fn prepared<E: SinkEvent + ?Sized>(events: &[&E], ctx: &RequestContext) -> Vec<PreparedEvent> {+/// Serialize publishable events into `PreparedEvent`s for driving outputs in+/// tests. Accepts `&[&dyn Publishable]` (integration) or `&[&ConcreteType]` (unit)+/// via `?Sized`.+pub fn prepared<E: Publishable + ?Sized>(+ events: &[&E],+ ctx: &RequestContext,+) -> Vec<PreparedEvent> {events.iter().filter(|e| e.should_publish()).map(|e| PreparedEvent {uuid: e.uuid(),- destination: e.destination().clone(),+ address: e.destination().address(),payload: e.serialize(ctx).expect("test payload must serialize"),headers: e.headers(ctx),partition_key: e.partition_key(ctx),@@ -167,28 +170,29 @@ pub fn find_by_did<'a>(events: &'a [WrappedEvent], distinct_id: &str) -> &'a Wra.unwrap()}-pub fn test_kafka_config() -> crate::v1::sinks::kafka::config::Config {- let env: std::collections::HashMap<String, String> = [- ("HOSTS", "localhost:9092"),- ("TOPIC_MAIN", "events_main"),- ("TOPIC_HISTORICAL", "events_hist"),- ("TOPIC_OVERFLOW", "events_overflow"),- ("TOPIC_DLQ", "events_dlq"),- ("TOPIC_EXCEPTION", "error_tracking_events"),- ("TOPIC_HEATMAP", "heatmaps_ingestion"),- ("TOPIC_CLIENT_INGESTION_WARNING", "events_plugin_ingestion"),+/// The outputs v1 test states publish to, one distinct topic per output.+pub fn test_outputs_config() -> crate::config::OutputsConfig {+ let env: HashMap<String, String> = [+ ("CAPTURE_OUTPUT_ANALYTICS_MAIN_TOPIC", "events_main"),+ ("CAPTURE_OUTPUT_ANALYTICS_HISTORICAL_TOPIC", "events_hist"),+ ("CAPTURE_OUTPUT_ANALYTICS_OVERFLOW_TOPIC", "events_overflow"),+ ("CAPTURE_OUTPUT_DLQ_TOPIC", "events_dlq"),+ (+ "CAPTURE_OUTPUT_ERROR_TRACKING_TOPIC",+ "error_tracking_events",+ ),+ ("CAPTURE_OUTPUT_HEATMAPS_TOPIC", "heatmaps_ingestion"),+ (+ "CAPTURE_OUTPUT_CLIENT_WARNINGS_TOPIC",+ "events_plugin_ingestion",+ ),+ ("CAPTURE_OUTPUT_AI_MAIN_TOPIC", "ai_events"),+ ("CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC", "ai_events_overflow"),].into_iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();- let mut cfg: crate::v1::sinks::kafka::config::Config =- envconfig::Envconfig::init_from_hashmap(&env).unwrap();- // Mirrors production, where setup injects the deployment-level- // CAPTURE_OUTPUT_AI_MAIN_TOPIC and CAPTURE_OUTPUT_AI_OVERFLOW_TOPIC into every sink config- // after env loading.- cfg.topic_ai = "ai_events".to_string();- cfg.topic_ai_overflow = Some("ai_events_overflow".to_string());- cfg+ envconfig::Envconfig::init_from_hashmap(&env).expect("test outputs config")}// ---------------------------------------------------------------------------@@ -338,11 +342,10 @@ pub fn realistic_ordered_mixed_batch() -> Vec<WrappedEvent> {let mut exception_warning = realistic_custom("user-pos-3", "$exception");exception_warning.result = EventResult::Warning;- exception_warning.destination = Destination::Drop;exception_warning.details = Some("exceptions_over_quota");- let click_overflow =- realistic_custom("user-pos-4", "button_clicked").with_destination(Destination::Overflow);+ let click_overflow = realistic_custom("user-pos-4", "button_clicked")+ .with_destination(Destination::AnalyticsOverflow);let pageview_historical =realistic_pageview("user-pos-5").with_destination(Destination::AnalyticsHistorical);@@ -392,13 +395,13 @@ pub fn realistic_spread_destinations() -> Vec<WrappedEvent> {let main = realistic_pageview("user-dest-0").with_destination(Destination::AnalyticsMain);let historical =realistic_pageview("user-dest-1").with_destination(Destination::AnalyticsHistorical);- let overflow = realistic_pageview("user-dest-2").with_destination(Destination::Overflow);+ let overflow =+ realistic_pageview("user-dest-2").with_destination(Destination::AnalyticsOverflow);let dlq = realistic_pageview("user-dest-3").with_destination(Destination::Dlq);let custom = realistic_pageview("user-dest-4").with_destination(Destination::Custom("custom_topic".to_string()));let dropped = realistic_pageview("user-dest-5")- .with_result(EventResult::Drop, Some("missing_event_name"))- .with_destination(Destination::Drop);+ .with_result(EventResult::Drop, Some("missing_event_name"));vec![main, historical, overflow, dlq, custom, dropped]}@@ -439,7 +442,7 @@ pub fn assert_round_trip(wrapped: &WrappedEvent,ctx: &RequestContext,) -> (common_types::CapturedEvent, common_types::RawEvent) {- use crate::v1::sinks::event::Event as SinkEvent;+ use crate::v1::types::Publishable;let buf = wrapped.serialize(ctx).expect("serialize failed");let captured: common_types::CapturedEvent =@@ -567,98 +570,6 @@ pub fn event_with_empty_options() -> Event {}}-// ----------------------------------------------------------------------------// Mock SinkResult for unit testing merge logic-// -----------------------------------------------------------------------------use std::borrow::Cow;-use std::time::Duration;--use crate::v1::sinks::types::{Outcome, SinkResult as SinkResultTrait};--/// Concrete SinkResult for testing — all fields are user-specified.-pub struct MockSinkResult {- pub uuid: Uuid,- pub outcome: Outcome,- pub cause: Option<&'static str>,- pub detail: Option<String>,- pub elapsed: Option<Duration>,-}--impl MockSinkResult {- pub fn success(uuid: Uuid) -> Box<dyn SinkResultTrait> {- Box::new(Self {- uuid,- outcome: Outcome::Success,- cause: None,- detail: None,- elapsed: Some(Duration::from_millis(5)),- })- }-- pub fn retriable(uuid: Uuid, cause: &'static str) -> Box<dyn SinkResultTrait> {- Box::new(Self {- uuid,- outcome: Outcome::RetriableError,- cause: Some(cause),- detail: Some(format!("{cause}: queue full")),- elapsed: Some(Duration::from_millis(100)),- })- }-- pub fn timeout(uuid: Uuid) -> Box<dyn SinkResultTrait> {- Box::new(Self {- uuid,- outcome: Outcome::Timeout,- cause: Some("timeout"),- detail: Some("message delivery timed out".to_string()),- elapsed: Some(Duration::from_secs(30)),- })- }-- pub fn fatal(uuid: Uuid, cause: &'static str) -> Box<dyn SinkResultTrait> {- Box::new(Self {- uuid,- outcome: Outcome::FatalError,- cause: Some(cause),- detail: Some(format!("{cause}: permanent failure")),- elapsed: None,- })- }-- pub fn fatal_no_cause(uuid: Uuid) -> Box<dyn SinkResultTrait> {- Box::new(Self {- uuid,- outcome: Outcome::FatalError,- cause: None,- detail: None,- elapsed: None,- })- }-}--impl SinkResultTrait for MockSinkResult {- fn key(&self) -> Uuid {- self.uuid- }-- fn outcome(&self) -> Outcome {- self.outcome- }-- fn cause(&self) -> Option<&'static str> {- self.cause- }-- fn detail(&self) -> Option<Cow<'_, str>> {- self.detail.as_ref().map(|s| Cow::Borrowed(s.as_str()))- }-- fn elapsed(&self) -> Option<Duration> {- self.elapsed- }-}-// ---------------------------------------------------------------------------// TestStateBuilder — builds a router::State for V1 pipeline integration tests// ---------------------------------------------------------------------------@@ -666,6 +577,7 @@ impl SinkResultTrait for MockSinkResult {use std::collections::HashMap;use std::num::NonZeroU32;use std::sync::Arc;+use std::time::Duration;use common_redis::MockRedisClient;use limiters::overflow::OverflowLimiter;@@ -675,19 +587,20 @@ use limiters::token_dropper::TokenDropper;use crate::config::CaptureMode;use crate::event_restrictions::EventRestrictionService;use crate::global_rate_limiter::GlobalRateLimiter;+use crate::outputs::OutputRegistry;use crate::quota_limiters::CaptureQuotaLimiter;use crate::router::{self, HistoricalConfig};+use crate::sinks::kafka::KafkaSinkBase;+use crate::sinks::producer::MockKafkaProducer;+use crate::sinks::registry::OutputTable;use crate::time::TimeSource;-use crate::v1::sinks::kafka::mock::MockProducer;-use crate::v1::sinks::kafka::sink::KafkaSink;-use crate::v1::sinks::sink::Sink;-use crate::v1::sinks::{self as v1_sinks, SinkName};/// Result of building a test state — gives access to both the `router::State`-/// and the underlying `MockProducer` so tests can inspect sent records.+/// and the `MockKafkaProducer` behind its outputs, so tests can inspect sent+/// records.pub struct TestState {pub state: router::State,- pub mock_producer: Arc<MockProducer>,+ pub mock_producer: MockKafkaProducer,}/// Builder for `router::State` with configurable mock services.@@ -701,7 +614,7 @@ pub struct TestStateBuilder {restriction_service: Option<EventRestrictionService>,global_rate_limiter: Option<Arc<GlobalRateLimiter>>,ai_byte_rate_limiter: Option<Arc<GlobalRateLimiter>>,- mock_producer: Option<Arc<MockProducer>>,+ mock_producer: Option<MockKafkaProducer>,ai_gateway_signing_secret: Option<String>,ingestion_warning_emitter: Option<Arc<dyn common_ingestion_warnings::WarningEmitter>>,capture_mode: CaptureMode,@@ -804,8 +717,8 @@ impl TestStateBuilder {self}- /// Supply a pre-configured MockProducer (e.g. for error injection).- pub fn with_mock_producer(mut self, producer: Arc<MockProducer>) -> Self {+ /// Supply a pre-configured producer (e.g. for error injection).+ pub fn with_mock_producer(mut self, producer: MockKafkaProducer) -> Self {self.mock_producer = Some(producer);self}@@ -832,14 +745,6 @@ impl TestStateBuilder {}pub fn build(self) -> TestState {- let mut manager = lifecycle::Manager::builder("test_state")- .with_trap_signals(false)- .with_prestop_check(false)- .build();- let handle = manager.register("test_state", lifecycle::ComponentOptions::new());- handle.report_healthy();- let _monitor = manager.monitor_background();-let redis: Arc<dyn common_redis::Client + Send + Sync> = if self.quota_limited {let mut mock = MockRedisClient::new();for resource in &[@@ -899,39 +804,16 @@ impl TestStateBuilder {});let ai_events_overflow_enabled = ai_events_overflow_limiter.is_some();- // Build the v1 sink router with a MockProducer-backed KafkaSink- let mock_producer = self- .mock_producer- .unwrap_or_else(|| Arc::new(MockProducer::new(SinkName::Msk, handle.clone())));-- let kafka_config = test_kafka_config();- let sink_config = v1_sinks::Config {- produce_timeout: Duration::from_secs(30),- kafka: kafka_config,- };-- let kafka_sink = KafkaSink::new(- SinkName::Msk,- Arc::clone(&mock_producer),- sink_config,- CaptureMode::Events,- handle.clone(),- );-- let boxed_sink: Box<dyn Sink> = Box::new(kafka_sink);- let sinks_map: HashMap<SinkName, Box<dyn Sink>> =- [(SinkName::Msk, boxed_sink)].into_iter().collect();- let v1_router = v1_sinks::Router::new(SinkName::Msk, sinks_map);-- // Legacy produce surface — no-op since V1 tests go through v1_sink_router- let legacy_outputs = Arc::new(crate::outputs::OutputRegistry::single(- crate::sinks::noop::NoOpSink::new(),- ));+ let mock_producer = self.mock_producer.unwrap_or_default();+ let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(+ mock_producer.clone(),+ OutputTable::from(&test_outputs_config()),+ )));let timesource: Arc<dyn TimeSource + Send + Sync> = Arc::new(crate::time::SystemTime {});let state = router::State {- outputs: legacy_outputs,+ outputs,timesource,redis,global_rate_limiter_token_distinctid: self.global_rate_limiter,@@ -952,7 +834,6 @@ impl TestStateBuilder {ai_events_overflow_limiter,ai_byte_rate_limiter: self.ai_byte_rate_limiter,replay_overflow_limiter: None,- v1_sink_router: Some(Arc::new(v1_router)),capture_v1_scatter_gather_min_batch: 8,ai_gateway_signing_secret: self.ai_gateway_signing_secret,ai_events_overflow_enabled,diff --git a/rust/capture/src/v1/types.rs b/rust/capture/src/v1/types.rsnew file mode 100644index 000000000000..03b23bfefa32--- /dev/null+++ b/rust/capture/src/v1/types.rs@@ -0,0 +1,144 @@+use common_types::CapturedEventHeaders;+use uuid::Uuid;++use crate::event_restrictions::Pipeline;+use crate::ordering::OrderingGuarantee;+use crate::pipeline::{self, Address, Lane};+use crate::v1::context::RequestContext;++#[derive(Debug, Default, Clone, PartialEq, Eq)]+pub enum Destination {+ #[default]+ AnalyticsMain,+ AnalyticsHistorical,+ AnalyticsOverflow,+ Dlq,+ Custom(String),+ ErrorTrackingMain,+ HeatmapsMain,+ ClientWarningsMain,+ AiMain,+ AiOverflow,+}++impl Destination {+ pub fn pipeline(&self) -> Option<Pipeline> {+ match self {+ Self::AnalyticsMain | Self::AnalyticsHistorical | Self::AnalyticsOverflow => {+ Some(Pipeline::Analytics)+ }+ Self::AiMain | Self::AiOverflow => Some(Pipeline::Ai),+ Self::ErrorTrackingMain => Some(Pipeline::ErrorTracking),+ Self::HeatmapsMain => Some(Pipeline::Heatmaps),+ Self::ClientWarningsMain => Some(Pipeline::ClientWarnings),+ Self::Dlq | Self::Custom(_) => None,+ }+ }++ pub fn absorbs_hot_keys(&self) -> bool {+ match self {+ Self::AnalyticsMain | Self::AnalyticsOverflow | Self::AiOverflow => true,+ Self::AnalyticsHistorical+ | Self::Dlq+ | Self::Custom(_)+ | Self::ErrorTrackingMain+ | Self::HeatmapsMain+ | Self::ClientWarningsMain+ | Self::AiMain => false,+ }+ }++ pub fn writes_persons(&self) -> bool {+ match self {+ Self::AnalyticsMain | Self::AnalyticsHistorical | Self::AnalyticsOverflow => true,+ Self::Dlq | Self::Custom(_) => true,+ Self::AiMain+ | Self::AiOverflow+ | Self::ErrorTrackingMain+ | Self::HeatmapsMain+ | Self::ClientWarningsMain => false,+ }+ }++ pub fn address(&self) -> Address {+ let lane = |pipeline, lane| Address::Lane { pipeline, lane };+ match self {+ Self::AnalyticsMain => lane(pipeline::Pipeline::Analytics, Lane::Main),+ Self::AnalyticsHistorical => lane(pipeline::Pipeline::Analytics, Lane::Historical),+ Self::AnalyticsOverflow => lane(pipeline::Pipeline::Analytics, Lane::Overflow),+ Self::AiMain => lane(pipeline::Pipeline::Ai, Lane::Main),+ Self::AiOverflow => lane(pipeline::Pipeline::Ai, Lane::Overflow),+ Self::ErrorTrackingMain => lane(pipeline::Pipeline::ErrorTracking, Lane::Main),+ Self::HeatmapsMain => lane(pipeline::Pipeline::Heatmaps, Lane::Main),+ Self::ClientWarningsMain => lane(pipeline::Pipeline::Warnings, Lane::Main),+ Self::Dlq => Address::Dlq,+ Self::Custom(topic) => Address::Custom(topic.clone()),+ }+ }+}++pub trait Publishable: Send + Sync {+ fn uuid(&self) -> Uuid;++ fn should_publish(&self) -> bool;++ fn destination(&self) -> &Destination;++ fn headers(&self, ctx: &RequestContext) -> CapturedEventHeaders;++ fn partition_key(&self, ctx: &RequestContext) -> String;++ fn ordering(&self) -> OrderingGuarantee;++ fn serialize(&self, ctx: &RequestContext) -> anyhow::Result<bytes::Bytes>;+}++#[cfg(test)]+mod destination_tests {+ use super::Destination;+ use crate::event_restrictions::Pipeline;+ use crate::sinks::registry::Destination as V0Destination;++ #[rstest::rstest]+ #[case(Destination::AnalyticsMain, Some(Pipeline::Analytics))]+ #[case(Destination::AnalyticsHistorical, Some(Pipeline::Analytics))]+ #[case(Destination::AnalyticsOverflow, Some(Pipeline::Analytics))]+ #[case(Destination::AiMain, Some(Pipeline::Ai))]+ #[case(Destination::AiOverflow, Some(Pipeline::Ai))]+ #[case(Destination::ErrorTrackingMain, Some(Pipeline::ErrorTracking))]+ #[case(Destination::HeatmapsMain, Some(Pipeline::Heatmaps))]+ #[case(Destination::ClientWarningsMain, Some(Pipeline::ClientWarnings))]+ #[case(Destination::Dlq, None)]+ #[case(Destination::Custom("admin_topic".into()), None)]+ fn pipeline_classifies_every_destination(+ #[case] destination: Destination,+ #[case] expected: Option<Pipeline>,+ ) {+ assert_eq!(destination.pipeline(), expected);+ }++ #[rstest::rstest]+ #[case(Destination::AnalyticsMain, Some(V0Destination::AnalyticsMain))]+ #[case(+ Destination::AnalyticsHistorical,+ Some(V0Destination::AnalyticsHistorical)+ )]+ #[case(Destination::AnalyticsOverflow, Some(V0Destination::AnalyticsOverflow))]+ #[case(Destination::Dlq, Some(V0Destination::Dlq))]+ #[case(Destination::Custom("admin_topic".into()), Some(V0Destination::Custom("admin_topic".into())))]+ #[case(Destination::ErrorTrackingMain, Some(V0Destination::ErrorTrackingMain))]+ #[case(Destination::HeatmapsMain, Some(V0Destination::HeatmapsMain))]+ #[case(+ Destination::ClientWarningsMain,+ Some(V0Destination::ClientWarningsMain)+ )]+ #[case(Destination::AiMain, Some(V0Destination::AiMain))]+ #[case(Destination::AiOverflow, Some(V0Destination::AiOverflow))]+ fn address_matches_the_v0_destination(+ #[case] destination: Destination,+ #[case] expected: Option<V0Destination>,+ ) {+ let v0 = V0Destination::for_address(destination.address());+ assert_eq!(v0, expected);+ }+}diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rsindex c691eb402cd4..2a4f594e400c 100644--- a/rust/capture/tests/common/integration_utils.rs+++ b/rust/capture/tests/common/integration_utils.rs@@ -14,7 +14,6 @@ use capture::{sinks::sink::SinkResult,time::TimeSource,v0_request::{DataType, ProcessedEvent},- v1::test_utils::TestStateBuilder,};use chrono::{DateTime, Utc};@@ -1042,8 +1041,12 @@ 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")+ /// The v1 route-surface tests publish here and assert only the status.+ async fn publish_prepared(&self, events: Vec<PreparedEvent>) -> Vec<SinkResult> {+ events+ .iter()+ .map(|event| SinkResult::published(event.uuid))+ .collect()}}@@ -1063,32 +1066,16 @@ pub fn test_lifecycle_handlers() -> (}fn setup_capture_router(unit: &TestCase) -> (Router, MemorySink) {- build_router_for_mode_at(unit.mode, unit.fixed_time, None)+ build_router_for_mode_at(unit.mode, unit.fixed_time)}// Builds a capture router for a given mode with test defaults, so route-registration// tests can assert which paths a mode serves without constructing a full TestCase.pub fn build_router_for_mode(mode: CaptureMode) -> Router {- build_router_for_mode_at(mode, DEFAULT_TEST_TIME, None).0+ build_router_for_mode_at(mode, DEFAULT_TEST_TIME).0}-// Same, plus a v1 sink router. The v1 paths stay unregistered without one, so a-// mode-gating assertion needs a sink to tell "this mode does not serve the path"-// apart from "this deployment has no v1 sink".-pub fn build_router_for_mode_with_v1_sink(mode: CaptureMode) -> Router {- let v1_sink_router = TestStateBuilder::new()- .with_capture_mode(mode)- .build()- .state- .v1_sink_router;- build_router_for_mode_at(mode, DEFAULT_TEST_TIME, v1_sink_router).0-}--fn build_router_for_mode_at(- mode: CaptureMode,- fixed_time: &str,- v1_sink_router: Option<Arc<capture::v1::sinks::Router>>,-) -> (Router, MemorySink) {+fn build_router_for_mode_at(mode: CaptureMode, fixed_time: &str) -> (Router, MemorySink) {let (readiness, liveness, _monitor) = test_lifecycle_handlers();let sink = MemorySink::default();let timesource = FixedTime {@@ -1139,11 +1126,10 @@ fn build_router_for_mode_at(None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- v1_sink_router,- 8, // capture_v1_scatter_gather_min_batch- None, // ai_gateway_signing_secret- false, // ai_events_overflow_enabled- None, // ingestion_warning_emitter+ 8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret+ false, // ai_events_overflow_enabled+ None, // ingestion_warning_emitter),sink,)diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex ad404326fb75..47e74431155f 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -146,7 +146,6 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {body_chunk_read_timeout_ms: None, // disabled by default in testsbody_read_chunk_size_kb: 256, // 256KB defaultcontinuous_profiling: ContinuousProfilingConfig::default(),- capture_v1_sinks: String::new(),capture_v1_max_compressed_body_bytes: 10 * 1024 * 1024,capture_v1_max_decompressed_body_bytes: 50 * 1024 * 1024,capture_v1_scatter_gather_min_batch: 8,@@ -163,27 +162,21 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {ai_byte_limit_local_cache_max_entries: 300_000,});-/// Build the per-sink env snapshot the v1 sink loader expects, with every-/// topic pointing at a single (ephemeral) topic. Mirrors the env layout from-/// `v1::sinks::load_sink_config`: keys are `CAPTURE_V1_SINK_<NAME>_KAFKA_*`.-pub fn v1_sink_env_for_topic(sink: &str, topic: &str) -> HashMap<String, String> {- let prefix = format!("CAPTURE_V1_SINK_{}_", sink.to_uppercase());- [- ("KAFKA_HOSTS", TEST_KAFKA_HOSTS),- ("KAFKA_TOPIC_MAIN", topic),- ("KAFKA_TOPIC_HISTORICAL", topic),- ("KAFKA_TOPIC_OVERFLOW", topic),- ("KAFKA_TOPIC_DLQ", topic),- ("KAFKA_TOPIC_EXCEPTION", topic),- ("KAFKA_TOPIC_HEATMAP", topic),- ("KAFKA_TOPIC_CLIENT_INGESTION_WARNING", topic),- ("KAFKA_LINGER_MS", "0"),- ("KAFKA_COMPRESSION_CODEC", "none"),- ("KAFKA_MESSAGE_TIMEOUT_MS", "10000"),- ]- .into_iter()- .map(|(k, v)| (format!("{prefix}{k}"), v.to_string()))- .collect()+/// Points every non-AI output at one (ephemeral) topic, so a consumer of that+/// topic sees whichever lane the v1 pipeline picks.+pub fn point_outputs_at(config: &mut Config, topic: &str) {+ let outputs = &mut config.outputs;+ for field in [+ &mut outputs.analytics_main_topic,+ &mut outputs.analytics_historical_topic,+ &mut outputs.analytics_overflow_topic,+ &mut outputs.dlq_topic,+ &mut outputs.error_tracking_topic,+ &mut outputs.heatmaps_topic,+ &mut outputs.client_warnings_topic,+ ] {+ *field = topic.to_string();+ }}static TRACING_INIT: Once = Once::new();@@ -250,16 +243,12 @@ impl ServerHandle {Self::for_config(config).await}- /// Boots a server with the v1 analytics pipeline enabled: a single `msk`- /// sink whose topics all point at `topic`, injected via a deterministic env- /// snapshot (no global `std::env` mutation, so parallel tests don't race on- /// distinct ephemeral topics). The v1 route is merged because- /// `v1_sink_router` ends up `Some`.+ /// Boots a server with every non-AI output pointed at `topic`. The topics live on the config rather than in+ /// `std::env`, so parallel tests don't race on distinct ephemeral topics.pub async fn for_v1_topic(topic: &EphemeralTopic) -> Self {let mut config = DEFAULT_CONFIG.clone();- config.capture_v1_sinks = "msk".to_string();- let sink_env = v1_sink_env_for_topic("msk", topic.topic_name());- Self::for_config_with_sink_env(config, sink_env).await+ point_outputs_at(&mut config, topic.topic_name());+ Self::for_config(config).await}/// Like `for_v1_topic`, with the synthetic ingestion warnings emitter@@ -271,27 +260,25 @@ impl ServerHandle {warnings_topic: &EphemeralTopic,) -> Self {let mut config = DEFAULT_CONFIG.clone();- config.capture_v1_sinks = "msk".to_string();+ point_outputs_at(&mut config, topic.topic_name());config.capture_ingestion_warnings_enabled = true;// The emitter reads only its own dedicated config now (no v0 KAFKA_*// fallback), so point it at the same ephemeral broker as the main sink.config.capture_ingestion_warnings_kafka_hosts = TEST_KAFKA_HOSTS.to_string();config.capture_ingestion_warnings_kafka_topic = warnings_topic.topic_name().to_string();- let sink_env = v1_sink_env_for_topic("msk", topic.topic_name());- Self::for_config_with_sink_env(config, sink_env).await+ Self::for_config(config).await}/// Like `for_v1_topic`, with the AI-gateway signing secret configured so the/// provenance check runs.pub async fn for_v1_topic_with_signing_secret(topic: &EphemeralTopic, secret: &str) -> Self {let mut config = DEFAULT_CONFIG.clone();- config.capture_v1_sinks = "msk".to_string();+ point_outputs_at(&mut config, topic.topic_name());config.ai_gateway_signing_secret = Some(secret.to_string());// The gateway tests send AI events, which route to the AI topic;// point it at the same ephemeral topic so the consumer sees them.config.outputs.ai_main_topic = topic.topic_name().to_string();- let sink_env = v1_sink_env_for_topic("msk", topic.topic_name());- Self::for_config_with_sink_env(config, sink_env).await+ Self::for_config(config).await}pub async fn for_config(config: Config) -> Self {diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rsindex f6d6cddc96ca..44c07d103f43 100644--- a/rust/capture/tests/integration_ai_endpoint.rs+++ b/rust/capture/tests/integration_ai_endpoint.rs@@ -192,7 +192,6 @@ fn setup_ai_test_router() -> Router {None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -249,7 +248,6 @@ fn setup_ai_router_collecting_warnings() -> (Router, Arc<CollectingEmitter>) {None,None, // ai_byte_rate_limiterNone,- None,8,None,false,@@ -1299,7 +1297,6 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -1969,7 +1966,6 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (RoutNone, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -2036,7 +2032,6 @@ fn setup_ai_test_router_with_byte_limiter() -> (Router, CapturingSink) {None, // ai_events_overflow_limiterSome(byte_limiter),None, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -2299,7 +2294,6 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, CapturinNone, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -2458,7 +2452,6 @@ fn setup_ai_test_router_with_overflow_limiter(Some(ai_events_overflow_limiter),None, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secrettrue, // ai_events_overflow_enabled@@ -2600,7 +2593,6 @@ fn ai_router(None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone,- None,8,Some(GW_SECRET.to_string()),false, // ai_events_overflow_enableddiff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rsindex 83bf415e547f..76abb1340cc9 100644--- a/rust/capture/tests/integration_ai_restrictions.rs+++ b/rust/capture/tests/integration_ai_restrictions.rs@@ -185,7 +185,6 @@ async fn setup_ai_router_with_restriction(None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -507,7 +506,6 @@ async fn setup_ai_router_with_redirect_to_topic(None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -587,7 +585,6 @@ async fn setup_ai_router_with_force_overflow_and_limiter(Some(overflow_limiter), // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretai_events_overflow_enabled,diff --git a/rust/capture/tests/integration_ai_route_surface.rs b/rust/capture/tests/integration_ai_route_surface.rsindex 47a727d0c24f..4320ab9fcd30 100644--- a/rust/capture/tests/integration_ai_route_surface.rs+++ b/rust/capture/tests/integration_ai_route_surface.rs@@ -20,7 +20,7 @@ mod integration_utils;use axum::http::StatusCode;use axum_test_helper::TestClient;use capture::config::CaptureMode;-use integration_utils::{build_router_for_mode, build_router_for_mode_with_v1_sink};+use integration_utils::build_router_for_mode;use rstest::rstest;use serde_json::json;@@ -152,8 +152,8 @@ async fn import_mode_registers_only_the_analytics_paths(// v1 endpoints// ----------------------------------------------------------------------------/// Post a real v1 batch to `path` on a router built for `mode` with a v1 sink-/// wired, and pin what comes back.+/// Post a real v1 batch to `path` on a router built for `mode`, and pin what+/// comes back.////// Unlike the v0 cases above, the payload is one the endpoint fully accepts, so/// [`Answer::Served`] is the 200 a completed publish returns rather than a status@@ -165,7 +165,7 @@ async fn assert_v1_answer(mode: CaptureMode, path: &str, expected: Answer) {event.event = "$ai_generation".to_string();let payload = capture::v1::test_utils::batch_payload(&[event]);- let status = TestClient::new(build_router_for_mode_with_v1_sink(mode))+ let status = TestClient::new(build_router_for_mode(mode)).post(path).body(payload).header("Authorization", "Bearer phc_route_surface_token")@@ -227,17 +227,3 @@ async fn non_ai_modes_never_serve_the_v1_ai_endpoint() {assert_v1_answer(mode, path, expected).await;}--/// Without a v1 sink the paths stay unregistered on every mode, which is what-/// makes the sink-wired assertions above say something about the mode gating-/// rather than about sink presence.-#[rstest]-#[case::ai(CaptureMode::Ai, "/i/v1/ai/events")]-#[case::events(CaptureMode::Events, "/i/v1/analytics/events")]-#[tokio::test]-async fn v1_paths_stay_unregistered_without_a_v1_sink(- #[case] mode: CaptureMode,- #[case] path: &str,-) {- assert_answer(mode, path, Answer::Absent).await;-}diff --git a/rust/capture/tests/integration_analytics_ai_routing.rs b/rust/capture/tests/integration_analytics_ai_routing.rsindex 4b692a265aa9..578ce5321f52 100644--- a/rust/capture/tests/integration_analytics_ai_routing.rs+++ b/rust/capture/tests/integration_analytics_ai_routing.rs@@ -140,7 +140,6 @@ fn setup_router_for_mode(ai_events_overflow_limiter,None, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretai_events_overflow_enabled,diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rsindex d3f755a516a4..9818a6938f8b 100644--- a/rust/capture/tests/integration_analytics_restrictions.rs+++ b/rust/capture/tests/integration_analytics_restrictions.rs@@ -135,7 +135,6 @@ async fn setup_analytics_router_with_restriction(None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretai_events_overflow_enabled,@@ -562,7 +561,6 @@ async fn setup_analytics_router_with_redirect_to_topic(None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enableddiff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rsindex b68a13a55bbf..b87a7ce21af6 100644--- a/rust/capture/tests/integration_otel_endpoint.rs+++ b/rust/capture/tests/integration_otel_endpoint.rs@@ -204,7 +204,6 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOptionoptions.ai_events_overflow_limiter,options.ai_byte_rate_limiter,None, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchoptions.ai_gateway_signing_secret,true, // ai_events_overflow_enableddiff --git a/rust/capture/tests/integration_person_processing_matrix.rs b/rust/capture/tests/integration_person_processing_matrix.rsindex 190dc4c12302..dbfc8ec22446 100644--- a/rust/capture/tests/integration_person_processing_matrix.rs+++ b/rust/capture/tests/integration_person_processing_matrix.rs@@ -263,7 +263,6 @@ async fn run_v0(inputs: Inputs, distinct_ids: &[&str]) -> Batch {None,None, // ai_byte_rate_limiterNone,- None,8,None,false,@@ -316,8 +315,8 @@ async fn run_v0(inputs: Inputs, distinct_ids: &[&str]) -> Batch {}}-/// Drive the v1 endpoint (`/i/v1/analytics/events`) through its own router and-/// sink, reading every record off the v1 mock producer, in request order.+/// Drive the v1 endpoint (`/i/v1/analytics/events`) through its router and the+/// shared outputs, reading every record off the mock producer, in request order.async fn run_v1(inputs: Inputs, distinct_ids: &[&str]) -> Batch {let recorder = DebuggingRecorder::new();let snapshotter = recorder.snapshotter();@@ -383,28 +382,24 @@ async fn run_v1(inputs: Inputs, distinct_ids: &[&str]) -> Batch {let body = response.text().await;assert_eq!(status, StatusCode::OK, "v1 rejected the batch: {body}");- ts.mock_producer.with_records(|produced| {- assert_eq!(- produced.len(),- distinct_ids.len(),- "v1 must produce every event"- );- Batch {- records: produced- .iter()- .map(|r| Record {- lane: v1_lane(&r.topic),- has_key: r.key.is_some(),- // The wire header is bytes, so read it back the way a- // consumer would.- force_disable_person_processing: r- .header("force_disable_person_processing")- .map(|v| v == "true"),- })- .collect(),- limiter_consultations: consultations(&snapshotter),- }- })+ let produced = ts.mock_producer.get_records();+ assert_eq!(+ produced.len(),+ distinct_ids.len(),+ "v1 must produce every event"+ );++ Batch {+ records: produced+ .iter()+ .map(|r| Record {+ lane: v1_lane(&r.topic),+ has_key: r.key.is_some(),+ force_disable_person_processing: r.headers.force_disable_person_processing,+ })+ .collect(),+ limiter_consultations: consultations(&snapshotter),+ }}// Each path names its lanes differently; the matrix compares lanes, not strings.diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rsindex a8e996630235..da810ef15cfb 100644--- a/rust/capture/tests/integration_replay_restrictions.rs+++ b/rust/capture/tests/integration_replay_restrictions.rs@@ -132,7 +132,6 @@ async fn setup_recordings_router_with_restriction(None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -505,7 +504,6 @@ async fn setup_recordings_router_with_redirect_to_topic(None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enableddiff --git a/rust/capture/tests/integration_wire_body_limits.rs b/rust/capture/tests/integration_wire_body_limits.rsindex 25d2d953b68b..a25b996c8c90 100644--- a/rust/capture/tests/integration_wire_body_limits.rs+++ b/rust/capture/tests/integration_wire_body_limits.rs@@ -108,7 +108,6 @@ fn make_test_client(mode: CaptureMode) -> (TestClient, CapturingSink) {None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8,None,false,diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rsindex 969e4bf639b0..a2cb1fb5e36c 100644--- a/rust/capture/tests/quota_limiters.rs+++ b/rust/capture/tests/quota_limiters.rs@@ -154,7 +154,6 @@ async fn setup_router_with_limits(None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -1209,7 +1208,6 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -1302,7 +1300,6 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -1399,7 +1396,6 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enabled@@ -1833,7 +1829,6 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {None, // ai_events_overflow_limiterNone, // ai_byte_rate_limiterNone, // replay_overflow_limiter- None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secretfalse, // ai_events_overflow_enableddiff --git a/rust/capture/tests/v1_http_integration.rs b/rust/capture/tests/v1_http_integration.rsindex 034642572227..47e67864c5e9 100644--- a/rust/capture/tests/v1_http_integration.rs+++ b/rust/capture/tests/v1_http_integration.rs@@ -2,15 +2,13 @@//!//! These tests verify the full server path://! POST /i/v1/analytics/events -> router -> handler -> process_batch-//! -> v1 sink router -> real Kafka -> consumer -> CapturedEvent+//! -> outputs -> real Kafka -> consumer -> CapturedEvent//!//! Requires Docker Kafka (same rig as the other integration tests).//!-//! Scope is deliberately narrow: route gating (404 when no sink is configured)-//! and the HTTP->Kafka round trip for a single event and a small batch. Payload-//! shape, header parity, partition keys, and destination routing are already-//! covered at the sink layer by `v1_sink_integration.rs` — we don't re-test-//! them here.+//! Scope is deliberately narrow: the HTTP->Kafka round trip for a single event+//! and a small batch. `v1_publish.rs` covers payload shape, header parity,+//! partition keys and destination routing at the outputs layer.#[path = "common/utils.rs"]mod utils;@@ -46,27 +44,6 @@ async fn parse_body(res: reqwest::Response) -> serde_json::Value {serde_json::from_slice(&bytes).expect("response body must be JSON")}-// ----------------------------------------------------------------------------// Route gating: the v1 endpoint is unregistered (404) without a v1 sink-// -----------------------------------------------------------------------------#[tokio::test]-async fn v1_route_unregistered_without_sink() {- setup_tracing();- // DEFAULT_CONFIG has capture_v1_sinks empty -> v1_sink_router is None ->- // the route is never merged, so the path 404s rather than 503s.- let server = ServerHandle::for_config(DEFAULT_CONFIG.clone()).await;-- let payload = batch_payload(&[pageview("user-404")]);- let res = server.capture_v1(TOKEN, payload).await;-- assert_eq!(- res.status(),- reqwest::StatusCode::NOT_FOUND,- "v1 route must not be registered when no v1 sink is configured"- );-}-// ---------------------------------------------------------------------------// Single event: HTTP -> real Kafka round trip// ---------------------------------------------------------------------------diff --git a/rust/capture/tests/v1_pipeline.rs b/rust/capture/tests/v1_pipeline.rsindex 2c585dc687c9..6e814e28d1fc 100644--- a/rust/capture/tests/v1_pipeline.rs+++ b/rust/capture/tests/v1_pipeline.rs@@ -1,17 +1,12 @@mod common;-use std::sync::Arc;--use rdkafka::error::RDKafkaErrorCode;use rstest::rstest;use uuid::Uuid;+use capture::sinks::producer::MockKafkaProducer;use capture::v1::analytics::process::process_batch;use capture::v1::analytics::response::BatchResponse;use capture::v1::analytics::types::{Batch, EventResult};-use capture::v1::sinks::kafka::mock::MockProducer;-use capture::v1::sinks::kafka::producer::ProduceError;-use capture::v1::sinks::SinkName;use capture::v1::test_utils::{self, batch_payload, valid_event, TestStateBuilder};use capture::v1::Error;@@ -58,10 +53,9 @@ async fn event_type_routes_to_destination(#[case] event_name: &str, #[case] expeassert_eq!(resp.entries().len(), 1);assert_eq!(resp.entries()[0].1.result, EventResult::Ok);- ts.mock_producer.with_records(|records| {- assert_eq!(records.len(), 1, "expected exactly 1 Kafka record");- assert_eq!(records[0].topic, expected_topic);- });+ let records = ts.mock_producer.get_records();+ assert_eq!(records.len(), 1, "expected exactly 1 Kafka record");+ assert_eq!(&*records[0].topic, expected_topic);}// -------------------------------------------------------------------------@@ -89,21 +83,8 @@ async fn mixed_batch_all_ok() {}#[tokio::test]-async fn sink_ack_error_causes_retry() {- let mut manager = lifecycle::Manager::builder("test_ack_err")- .with_trap_signals(false)- .with_prestop_check(false)- .build();- let handle = manager.register("test_ack_err", lifecycle::ComponentOptions::new());- handle.report_healthy();- let _monitor = manager.monitor_background();-- let producer =- Arc::new(- MockProducer::new(SinkName::Msk, handle).with_ack_error(|| ProduceError::Kafka {- code: RDKafkaErrorCode::BrokerNotAvailable,- }),- );+async fn sink_ack_error_retries_only_that_event() {+ let producer = MockKafkaProducer::new_failing_ack_at(1);let events = vec![event_with_name("$pageview"), event_with_name("$identify")];let payload = batch_payload(&events);@@ -115,11 +96,13 @@ async fn sink_ack_error_causes_retry() {.await.expect("batch should succeed");- assert_eq!(resp.entries().len(), 2);+ let results: Vec<EventResult> = resp+ .entries()+ .iter()+ .map(|(_, status)| status.result)+ .collect();assert!(resp.has_retry);- for (_, status) in resp.entries() {- assert_eq!(status.result, EventResult::Retry);- }+ assert_eq!(results, vec![EventResult::Ok, EventResult::Retry]);}#[tokio::test]@@ -177,13 +160,12 @@ async fn historical_rerouting() {assert_eq!(resp.entries().len(), 1);assert_eq!(resp.entries()[0].1.result, EventResult::Ok);- ts.mock_producer.with_records(|records| {- assert_eq!(records.len(), 1);- assert_eq!(- records[0].topic, "events_hist",- "old event should route to historical topic"- );- });+ let records = ts.mock_producer.get_records();+ assert_eq!(records.len(), 1);+ assert_eq!(+ &*records[0].topic, "events_hist",+ "old event should route to historical topic"+ );}// -------------------------------------------------------------------------diff --git a/rust/capture/tests/v1_sink_integration.rs b/rust/capture/tests/v1_publish.rssimilarity index 68%rename from rust/capture/tests/v1_sink_integration.rsrename to rust/capture/tests/v1_publish.rsindex fbc0b3bec0a6..3cf2ba77ac72 100644--- a/rust/capture/tests/v1_sink_integration.rs+++ b/rust/capture/tests/v1_publish.rs@@ -1,53 +1,31 @@-//! Sink-level integration tests for the v1 analytics pipeline.+//! Outputs-level integration tests for the v1 analytics pipeline.//!//! These tests verify the end-to-end path:-//! WrappedEvent -> KafkaSink.publish_batch() -> real Kafka -> consumer -> CapturedEvent+//! WrappedEvent -> OutputRegistry::publish_prepared() -> real Kafka -> consumer -> CapturedEvent//!//! Requires Docker Kafka (same rig as legacy integration tests).//!//! HTTP-level round trips (POST /i/v1/analytics/events -> Kafka) live in-//! `v1_http_integration.rs`; this file stays focused on the sink layer.+//! `v1_http_integration.rs`; this file stays focused on the outputs layer.#[path = "common/utils.rs"]mod utils;use utils::*;-use std::sync::Arc;-use std::time::Duration;+use std::collections::HashMap;use anyhow::Result;use common_types::{CapturedEvent, RawEvent};-use capture::config::CaptureMode;+use capture::config::EnvelopeCompression;+use capture::outputs::OutputRegistry;+use capture::producers::{self, ProducerRegistry};+use capture::sinks::kafka::KafkaSink;+use capture::sinks::registry::OutputTable;+use capture::sinks::sink::Outcome;use capture::v1::context::RequestContext;-use capture::v1::sinks::event::Event;-use capture::v1::sinks::kafka::producer::KafkaProducer;-use capture::v1::sinks::kafka::KafkaSink;-use capture::v1::sinks::sink::Sink;-use capture::v1::sinks::types::Outcome;-use capture::v1::sinks::{Config, SinkName};use capture::v1::test_utils::{self, prepared, WrappedEventMut};--fn v1_kafka_config(topic: &str) -> capture::v1::sinks::kafka::config::Config {- let env: std::collections::HashMap<String, String> = [- ("HOSTS", "kafka:9092"),- ("TOPIC_MAIN", topic),- ("TOPIC_HISTORICAL", topic),- ("TOPIC_OVERFLOW", topic),- ("TOPIC_DLQ", topic),- ("TOPIC_EXCEPTION", topic),- ("TOPIC_HEATMAP", topic),- ("TOPIC_CLIENT_INGESTION_WARNING", topic),- ("LINGER_MS", "0"),- ("COMPRESSION_CODEC", "none"),- ("MESSAGE_TIMEOUT_MS", "10000"),- ("QUEUE_MIB", "10"),- ]- .into_iter()- .map(|(k, v)| (k.to_string(), v.to_string()))- .collect();- envconfig::Envconfig::init_from_hashmap(&env).unwrap()-}+use capture::v1::types::Publishable;fn v1_test_context() -> RequestContext {let mut ctx = test_utils::test_context();@@ -55,38 +33,17 @@ fn v1_test_context() -> RequestContext {ctx}-async fn build_v1_sink(topic: &str) -> (KafkaSink<KafkaProducer>, lifecycle::MonitorGuard) {- let mut manager = lifecycle::Manager::builder("v1-sink-integration-test")- .with_trap_signals(false)- .with_prestop_check(false)- .build();- let handle = manager.register("v1_kafka", lifecycle::ComponentOptions::new());- handle.report_healthy();- let monitor = manager.monitor_background();-- let kafka_config = v1_kafka_config(topic);- let producer = KafkaProducer::new(- SinkName::Msk,- &kafka_config,- handle.clone(),- CaptureMode::Events.as_tag(),- )- .expect("failed to create v1 KafkaProducer");-- let config = Config {- produce_timeout: Duration::from_secs(10),- kafka: kafka_config,- };+async fn v1_outputs(topic: &str) -> OutputRegistry {+ let producer_configs =+ producers::load_all(&test_producer_env()).expect("failed to load producer config");+ let producers = ProducerRegistry::build(&producer_configs, HashMap::new())+ .expect("failed to create producers");- let sink = KafkaSink::new(- SinkName::Msk,- Arc::new(producer),- config,- CaptureMode::Events,- handle,- );+ let mut config = DEFAULT_CONFIG.clone();+ point_outputs_at(&mut config, topic);+ let table = OutputTable::from(&config.outputs).map_producers(|name| producers.get(*name));- (sink, monitor)+ OutputRegistry::single(KafkaSink::new(table, EnvelopeCompression::None))}// ---------------------------------------------------------------------------@@ -97,17 +54,17 @@ async fn build_v1_sink(topic: &str) -> (KafkaSink<KafkaProducer>, lifecycle::Monasync fn v1_single_pageview_round_trip() -> Result<()> {setup_tracing();let topic = EphemeralTopic::new().await;- let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let outputs = v1_outputs(topic.topic_name()).await;let ctx = v1_test_context();let wrapped = test_utils::realistic_pageview("integ-user-1");- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];+ let events: Vec<&(dyn Publishable + Send + Sync)> = vec![&wrapped];- let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;+ let results = outputs.publish_prepared(prepared(&events, &ctx)).await;assert_eq!(results.len(), 1);- assert_eq!(results[0].key(), wrapped.uuid);- assert_eq!(results[0].outcome(), Outcome::Success);+ assert_eq!(results[0].uuid, wrapped.uuid);+ assert!(matches!(results[0].outcome, Outcome::Published));let event_json = topic.next_event()?;let captured: CapturedEvent = serde_json::from_value(event_json)?;@@ -138,17 +95,17 @@ async fn v1_single_pageview_round_trip() -> Result<()> {async fn v1_batch_round_trip() -> Result<()> {setup_tracing();let topic = EphemeralTopic::new().await;- let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let outputs = v1_outputs(topic.topic_name()).await;let ctx = v1_test_context();let batch = test_utils::realistic_batch();- let events: Vec<&(dyn Event + Send + Sync)> = vec![&batch[0], &batch[1], &batch[2]];+ let events: Vec<&(dyn Publishable + Send + Sync)> = vec![&batch[0], &batch[1], &batch[2]];- let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;+ let results = outputs.publish_prepared(prepared(&events, &ctx)).await;assert_eq!(results.len(), 3);for r in &results {- assert_eq!(r.outcome(), Outcome::Success);+ assert!(matches!(r.outcome, Outcome::Published));}let mut event_names = Vec::new();@@ -179,14 +136,14 @@ async fn v1_batch_round_trip() -> Result<()> {async fn v1_kafka_headers_round_trip() -> Result<()> {setup_tracing();let topic = EphemeralTopic::new().await;- let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let outputs = v1_outputs(topic.topic_name()).await;let ctx = v1_test_context();let wrapped = test_utils::realistic_pageview("integ-user-headers");- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];+ let events: Vec<&(dyn Publishable + Send + Sync)> = vec![&wrapped];- let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;- assert_eq!(results[0].outcome(), Outcome::Success);+ let results = outputs.publish_prepared(prepared(&events, &ctx)).await;+ assert!(matches!(results[0].outcome, Outcome::Published));let (_event_json, headers) = topic.next_message_with_headers()?;@@ -213,14 +170,14 @@ async fn v1_kafka_headers_round_trip() -> Result<()> {async fn v1_partition_key_round_trip() -> Result<()> {setup_tracing();let topic = EphemeralTopic::new().await;- let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let outputs = v1_outputs(topic.topic_name()).await;let ctx = v1_test_context();let wrapped = test_utils::realistic_pageview("integ-user-pkey");- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];+ let events: Vec<&(dyn Publishable + Send + Sync)> = vec![&wrapped];- let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;- assert_eq!(results[0].outcome(), Outcome::Success);+ let results = outputs.publish_prepared(prepared(&events, &ctx)).await;+ assert!(matches!(results[0].outcome, Outcome::Published));let key = topic.next_message_key()?;assert_eq!(@@ -239,16 +196,16 @@ async fn v1_partition_key_round_trip() -> Result<()> {async fn v1_dropped_event_not_published() -> Result<()> {setup_tracing();let topic = EphemeralTopic::new().await;- let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let outputs = v1_outputs(topic.topic_name()).await;let ctx = v1_test_context();let wrapped = test_utils::realistic_pageview("integ-user-dropped").with_result(capture::v1::analytics::types::EventResult::Drop,Some("rate_limited"),);- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];+ let events: Vec<&(dyn Publishable + Send + Sync)> = vec![&wrapped];- let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;+ let results = outputs.publish_prepared(prepared(&events, &ctx)).await;assert!(results.is_empty());topic.assert_empty();@@ -263,7 +220,7 @@ async fn v1_dropped_event_not_published() -> Result<()> {async fn v1_exception_event_round_trip() -> Result<()> {setup_tracing();let topic = EphemeralTopic::new().await;- let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let outputs = v1_outputs(topic.topic_name()).await;let ctx = v1_test_context();let uuid = uuid::Uuid::new_v4();@@ -271,12 +228,12 @@ async fn v1_exception_event_round_trip() -> Result<()> {wrapped.event.event = "$exception".to_string();wrapped.uuid = uuid;wrapped.event.uuid = uuid.to_string();- wrapped.destination = capture::v1::sinks::Destination::ExceptionErrorTracking;+ wrapped.destination = capture::v1::types::Destination::ErrorTrackingMain;- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];- let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;+ let events: Vec<&(dyn Publishable + Send + Sync)> = vec![&wrapped];+ let results = outputs.publish_prepared(prepared(&events, &ctx)).await;assert_eq!(results.len(), 1);- assert_eq!(results[0].outcome(), Outcome::Success);+ assert!(matches!(results[0].outcome, Outcome::Published));let event_json = topic.next_event()?;let captured: CapturedEvent = serde_json::from_value(event_json)?;@@ -296,7 +253,7 @@ async fn v1_exception_event_round_trip() -> Result<()> {async fn v1_cookieless_mode_partition_key() -> Result<()> {setup_tracing();let topic = EphemeralTopic::new().await;- let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let outputs = v1_outputs(topic.topic_name()).await;let mut ctx = v1_test_context();ctx.client_ip = "198.51.100.7".parse().unwrap();@@ -306,9 +263,9 @@ async fn v1_cookieless_mode_partition_key() -> Result<()> {wrapped.event.uuid = uuid.to_string();wrapped.options.cookieless_mode = Some(true);- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];- let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;- assert_eq!(results[0].outcome(), Outcome::Success);+ let events: Vec<&(dyn Publishable + Send + Sync)> = vec![&wrapped];+ let results = outputs.publish_prepared(prepared(&events, &ctx)).await;+ assert!(matches!(results[0].outcome, Outcome::Published));let key = topic.next_message_key()?;assert_eq!(@@ -328,7 +285,7 @@ async fn v1_cookieless_mode_partition_key() -> Result<()> {async fn v1_all_options_property_injection() -> Result<()> {setup_tracing();let topic = EphemeralTopic::new().await;- let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let outputs = v1_outputs(topic.topic_name()).await;let ctx = v1_test_context();let uuid = uuid::Uuid::new_v4();@@ -344,9 +301,9 @@ async fn v1_all_options_property_injection() -> Result<()> {wrapped.event.session_id = Some("sess-opt-test".to_string());wrapped.event.window_id = Some("win-opt-test".to_string());- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];- let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;- assert_eq!(results[0].outcome(), Outcome::Success);+ let events: Vec<&(dyn Publishable + Send + Sync)> = vec![&wrapped];+ let results = outputs.publish_prepared(prepared(&events, &ctx)).await;+ assert!(matches!(results[0].outcome, Outcome::Published));let event_json = topic.next_event()?;let captured: CapturedEvent = serde_json::from_value(event_json)?;@@ -371,7 +328,7 @@ async fn v1_all_options_property_injection() -> Result<()> {async fn v1_empty_options_no_injection() -> Result<()> {setup_tracing();let topic = EphemeralTopic::new().await;- let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let outputs = v1_outputs(topic.topic_name()).await;let ctx = v1_test_context();let uuid = uuid::Uuid::new_v4();@@ -387,9 +344,9 @@ async fn v1_empty_options_no_injection() -> Result<()> {wrapped.event.session_id = None;wrapped.event.window_id = None;- let events: Vec<&(dyn Event + Send + Sync)> = vec![&wrapped];- let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;- assert_eq!(results[0].outcome(), Outcome::Success);+ let events: Vec<&(dyn Publishable + Send + Sync)> = vec![&wrapped];+ let results = outputs.publish_prepared(prepared(&events, &ctx)).await;+ assert!(matches!(results[0].outcome, Outcome::Published));let event_json = topic.next_event()?;let captured: CapturedEvent = serde_json::from_value(event_json)?;@@ -414,20 +371,20 @@ async fn v1_empty_options_no_injection() -> Result<()> {async fn v1_multi_destination_batch() -> Result<()> {setup_tracing();let topic = EphemeralTopic::new().await;- let (sink, _monitor) = build_v1_sink(topic.topic_name()).await;+ let outputs = v1_outputs(topic.topic_name()).await;let ctx = v1_test_context();let main_ev = test_utils::realistic_pageview("integ-dest-main");let hist_ev = test_utils::realistic_pageview("integ-dest-hist")- .with_destination(capture::v1::sinks::Destination::AnalyticsHistorical);+ .with_destination(capture::v1::types::Destination::AnalyticsHistorical);let overflow_ev = test_utils::realistic_pageview("integ-dest-overflow")- .with_destination(capture::v1::sinks::Destination::Overflow);+ .with_destination(capture::v1::types::Destination::AnalyticsOverflow);- let events: Vec<&(dyn Event + Send + Sync)> = vec![&main_ev, &hist_ev, &overflow_ev];- let results = sink.publish_batch(&ctx, &prepared(&events, &ctx)).await;+ let events: Vec<&(dyn Publishable + Send + Sync)> = vec![&main_ev, &hist_ev, &overflow_ev];+ let results = outputs.publish_prepared(prepared(&events, &ctx)).await;assert_eq!(results.len(), 3);for r in &results {- assert_eq!(r.outcome(), Outcome::Success);+ assert!(matches!(r.outcome, Outcome::Published));}let mut distinct_ids = Vec::new();