:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(capture-v1): remove queue-full retry loop (#64094)
Eli Reisman9a66658f2ad3
diff --git a/rust/capture/src/v1/analytics/constants.rs b/rust/capture/src/v1/analytics/constants.rsindex 03088df5cc11..6bfe74910e5c 100644--- a/rust/capture/src/v1/analytics/constants.rs+++ b/rust/capture/src/v1/analytics/constants.rs@@ -119,3 +119,7 @@ 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).+pub(super) const CAPTURE_V1_PROCESSING_DURATION_SECONDS: &str =+ "capture_v1_processing_duration_seconds";diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex 1b4040146237..4e74251963ee 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -1,15 +1,17 @@use std::collections::{HashMap, HashSet};+use std::time::Instant;use chrono::{DateTime, Utc};+use metrics::histogram;use uuid::Uuid;use super::constants::{CAPTURE_V1_DISTINCT_ID_MAX_SIZE, CAPTURE_V1_EVENTS_DROPPED,CAPTURE_V1_EVENTS_REROUTED_HISTORICAL, CAPTURE_V1_EVENTS_RESTRICTED,CAPTURE_V1_EVENT_ADJUSTMENTS_APPLIED, CAPTURE_V1_MAX_EVENT_NAME_LENGTH,- CAPTURE_V1_OVERFLOW_ROUTED, CAPTURE_V1_PARSED_EVENTS, CAPTURE_V1_RATE_LIMITER,- DETAIL_EVENT_RESTRICTION_DROP, DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS,- ILLEGAL_DISTINCT_IDS,+ CAPTURE_V1_OVERFLOW_ROUTED, CAPTURE_V1_PARSED_EVENTS, CAPTURE_V1_PROCESSING_DURATION_SECONDS,+ CAPTURE_V1_RATE_LIMITER, DETAIL_EVENT_RESTRICTION_DROP, DETAIL_PERSON_PROCESSING_DISABLED,+ FUTURE_EVENT_HOURS_CUTOFF_MS, ILLEGAL_DISTINCT_IDS,};use super::response::BatchResponse;use super::types::{Batch, Event, EventResult, WrappedEvent};@@ -47,6 +49,7 @@ pub async fn process_batch(context: &mut Context,batch: Batch,) -> Result<BatchResponse, Error> {+ let processing_start = Instant::now();crate::ctx_log!(Level::INFO, context, "process_batch called");validate_batch(&batch)?;@@ -88,6 +91,12 @@ pub async fn process_batch(apply_token_distinct_id_limits(limiter, context, &mut events).await;}+ histogram!(+ CAPTURE_V1_PROCESSING_DURATION_SECONDS,+ "path" => context.path,+ )+ .record(processing_start.elapsed().as_secs_f64());+// Publish to v1 sink, merge results, build responselet sink_router = state.v1_sink_router@@ -358,8 +367,6 @@ fn apply_historical_rerouting(}fn apply_overflow_stamping(limiter: &OverflowLimiter, ctx: &Context, events: &mut [WrappedEvent]) {- let mut buf = String::with_capacity(128);-for event in events.iter_mut() {if event.destination != Destination::AnalyticsMain {continue;@@ -368,10 +375,9 @@ fn apply_overflow_stamping(limiter: &OverflowLimiter, ctx: &Context, events: &mucontinue;}- buf.clear();- event.partition_key(ctx, &mut buf);+ let key = event.partition_key(ctx);- match limiter.is_limited(&buf) {+ match limiter.is_limited(&key) {OverflowLimiterResult::ForceLimited => {event.destination = Destination::Overflow;// Disables person processing AND nulls partition key at sink.diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rsindex 2685f19e3180..23a5eb60c763 100644--- a/rust/capture/src/v1/analytics/types.rs+++ b/rust/capture/src/v1/analytics/types.rs@@ -189,8 +189,9 @@ impl SinkEvent for WrappedEvent {}}- fn partition_key(&self, ctx: &Context, buf: &mut String) {+ fn partition_key(&self, ctx: &Context) -> String {use std::fmt::Write;+ let mut buf = String::with_capacity(128);match (self.event.options.cookieless_mode == Some(true),ctx.capture_internal,@@ -205,9 +206,10 @@ impl SinkEvent for WrappedEvent {let _ = write!(buf, "{}:{}", ctx.api_token, self.event.distinct_id);}}+ buf}- fn serialize_into(&self, ctx: &Context, buf: &mut String) -> anyhow::Result<()> {+ fn serialize(&self, ctx: &Context) -> anyhow::Result<String> {let spliced = self.build_spliced_properties(ctx)?;let properties: &RawValue = spliced.as_deref().unwrap_or(&self.event.properties);let ingestion_data = IngestionData {@@ -228,7 +230,7 @@ impl SinkEvent for WrappedEvent {&ip};let timestamp = self.adjusted_timestamp.ok_or_else(|| {- anyhow::anyhow!("serialize_into called on event without adjusted_timestamp")+ anyhow::anyhow!("serialize called on event without adjusted_timestamp")})?;let now = ctx.server_received_at@@ -247,9 +249,10 @@ impl SinkEvent for WrappedEvent {historical_migration: ctx.historical_migration,};- serde_json::to_string(&ie)- .map(|s| buf.push_str(&s))- .map_err(|e| anyhow::anyhow!("serializing IngestionEvent: {e:#}"))+ let mut buf = String::with_capacity(data.len() + 512);+ serde_json::to_writer(StringWriter(&mut buf), &ie)+ .map_err(|e| anyhow::anyhow!("serializing IngestionEvent: {e:#}"))?;+ Ok(buf)}}@@ -362,7 +365,7 @@ impl HasEventName for WrappedEvent {}}-/// The Kafka payload produced by `WrappedEvent::serialize_into`.+/// The Kafka payload produced by `WrappedEvent::serialize`.////// Field order matches `CapturedEvent` from `common_types` so that serde's/// derived `Serialize` emits JSON keys in the same order as v0. Serde@@ -370,7 +373,7 @@ impl HasEventName for WrappedEvent {////// Borrows from `WrappedEvent` and `Context` to avoid per-event heap/// allocations -- the struct is created, serialized, and dropped within-/// a single `serialize_into` call.+/// a single `serialize` call.#[derive(Debug, Serialize)]pub struct IngestionEvent<'a> {pub uuid: Uuid,@@ -929,20 +932,11 @@ mod tests {assert!(h.historical_migration.is_none());}- fn partition_key_str(ev: &WrappedEvent, ctx: &Context) -> String {- let mut buf = String::new();- ev.partition_key(ctx, &mut buf);- buf- }-#[test]fn partition_key_normal_mode() {let ctx = test_utils::test_context();let ev = ok_wrapped("$pageview", "user-42");- assert_eq!(- partition_key_str(&ev, &ctx),- format!("{}:user-42", ctx.api_token)- );+ assert_eq!(ev.partition_key(&ctx), format!("{}:user-42", ctx.api_token));}#[test]@@ -951,7 +945,7 @@ mod tests {let mut ev = ok_wrapped("$pageview", "user-42");ev.event.options.cookieless_mode = Some(true);assert_eq!(- partition_key_str(&ev, &ctx),+ ev.partition_key(&ctx),format!("{}:{}", ctx.api_token, ctx.client_ip));}@@ -963,7 +957,7 @@ mod tests {let mut ev = ok_wrapped("$pageview", "user-42");ev.event.options.cookieless_mode = Some(true);assert_eq!(- partition_key_str(&ev, &ctx),+ ev.partition_key(&ctx),format!("{}:127.0.0.1", ctx.api_token));}@@ -982,7 +976,7 @@ mod tests {ev.force_disable_person_processing = true;ev.destination = Destination::AnalyticsMain;assert_eq!(- partition_key_str(&ev, &ctx),+ ev.partition_key(&ctx),format!("{}:user-42", ctx.api_token),"partition_key() is unconditional; sink applies null-key policy");@@ -1015,7 +1009,7 @@ mod tests {assert!(!ev.has_property("unknown_key"));}- // --- serialize_into ---+ // --- serialize ---use std::net::{IpAddr, Ipv4Addr};@@ -1074,10 +1068,7 @@ mod tests {wrapped: &WrappedEvent,ctx: &crate::v1::context::Context,) -> (CapturedEvent, RawEvent) {- let mut buf = String::new();- wrapped- .serialize_into(ctx, &mut buf)- .expect("serialize_into failed");+ let buf = wrapped.serialize(ctx).expect("serialize failed");let captured: CapturedEvent =serde_json::from_str(&buf).expect("v1 output must deserialize as CapturedEvent");let data: RawEvent =@@ -1086,12 +1077,11 @@ mod tests {}#[test]- fn serialize_into_fails_without_adjusted_timestamp() {+ fn serialize_fails_without_adjusted_timestamp() {let mut ev = pageview_event();ev.adjusted_timestamp = None;let ctx = serialize_ctx();- let mut buf = String::new();- let err = ev.serialize_into(&ctx, &mut buf).unwrap_err();+ let err = ev.serialize(&ctx).unwrap_err();assert!(err.to_string().contains("adjusted_timestamp"),"error should mention adjusted_timestamp: {err}"@@ -1205,8 +1195,7 @@ mod tests {let headers = wrapped.headers(&ctx);assert_eq!(headers.distinct_id.as_deref(), Some("user-42"));- let mut key = String::new();- wrapped.partition_key(&ctx, &mut key);+ let key = wrapped.partition_key(&ctx);assert_eq!(key, format!("{}:user-42", ctx.api_token));}@@ -1434,8 +1423,7 @@ mod tests {let wrapped = pageview_event();assert_eq!(wrapped.event.options.cookieless_mode, Some(false));let ctx = serialize_ctx();- let mut buf = String::new();- wrapped.serialize_into(&ctx, &mut buf).unwrap();+ let buf = wrapped.serialize(&ctx).unwrap();let val: Value = serde_json::from_str(&buf).unwrap();assert!(val.get("is_cookieless_mode").is_none(),@@ -1456,8 +1444,7 @@ mod tests {fn serialize_historical_migration_false_skipped() {let wrapped = pageview_event();let ctx = serialize_ctx();- let mut buf = String::new();- wrapped.serialize_into(&ctx, &mut buf).unwrap();+ let buf = wrapped.serialize(&ctx).unwrap();let val: Value = serde_json::from_str(&buf).unwrap();assert!(val.get("historical_migration").is_none(),@@ -1608,8 +1595,7 @@ mod tests {};let ctx = serialize_ctx();- let mut buf = String::new();- let err = wrapped.serialize_into(&ctx, &mut buf).unwrap_err();+ let err = wrapped.serialize(&ctx).unwrap_err();assert!(err.to_string().contains("must be a JSON object"),"expected object guard, got: {err}"@@ -1775,9 +1761,8 @@ mod tests {fn partition_key_parity_normal() {let ctx = serialize_ctx();let ev = realistic_pageview("user-42");- let mut buf = String::new();- ev.partition_key(&ctx, &mut buf);- assert_eq!(buf, format!("{}:user-42", ctx.api_token));+ let key = ev.partition_key(&ctx);+ assert_eq!(key, format!("{}:user-42", ctx.api_token));}#[test]@@ -1785,9 +1770,8 @@ mod tests {let ctx = serialize_ctx();let mut ev = realistic_pageview("user-42");ev.event.options.cookieless_mode = Some(true);- let mut buf = String::new();- ev.partition_key(&ctx, &mut buf);- assert_eq!(buf, format!("{}:{}", ctx.api_token, ctx.client_ip));+ let key = ev.partition_key(&ctx);+ assert_eq!(key, format!("{}:{}", ctx.api_token, ctx.client_ip));}#[test]@@ -1796,10 +1780,9 @@ mod tests {let ev = realistic_pageview("user-42").with_force_disable_person_processing(true).with_destination(Destination::AnalyticsMain);- let mut buf = String::new();- ev.partition_key(&ctx, &mut buf);+ let key = ev.partition_key(&ctx);assert_eq!(- buf,+ key,format!("{}:user-42", ctx.api_token),"partition_key() is unconditional; sink applies null-key policy");diff --git a/rust/capture/src/v1/sinks/DESIGN.md b/rust/capture/src/v1/sinks/DESIGN.mdindex 221d598b1ab2..fd0c7e71f70d 100644--- a/rust/capture/src/v1/sinks/DESIGN.md+++ b/rust/capture/src/v1/sinks/DESIGN.md@@ -55,8 +55,8 @@ Key properties: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.-- **Buffer-reuse** — serialization and partition-key methods write into- caller-owned `String` buffers, eliminating per-event allocations.+- **Owned-return API** — `serialize()` and `partition_key()` each return+ a fresh `String`, keeping the trait simple and parallelism-ready.---@@ -210,8 +210,8 @@ pub trait Event: Send + Sync {fn should_publish(&self) -> bool;fn destination(&self) -> &Destination;fn headers(&self, ctx: &Context) -> CapturedEventHeaders;- fn partition_key(&self, ctx: &Context, buf: &mut String);- fn serialize_into(&self, ctx: &Context, buf: &mut String) -> anyhow::Result<()>;+ fn partition_key(&self, ctx: &Context) -> String;+ fn serialize(&self, ctx: &Context) -> anyhow::Result<String>;}```@@ -227,28 +227,16 @@ The analytics capture endpoint's `WrappedEvent` implements this traitOther capture endpoints (e.g. session replay, exceptions) providetheir own `Event` implementations without changing any sink code.-### Buffer-reuse pattern+### Owned-return serialization-`partition_key` and `serialize_into` write into caller-owned-`String` buffers that are cleared between events. This eliminates-per-event allocations after the first iteration — the buffers grow to-high-water mark and stay there for the entire batch.+`partition_key(ctx)` and `serialize(ctx)` each return a fresh owned+`String`. This trades a small per-event allocation for a simpler trait+contract that needs no shared mutable buffers — making the prep loop+trivially parallelizable if needed in the future.-```text- ┌──────────────────────────────────────────────┐- │ publish_batch │- │ │- │ payload_buf = String::with_capacity(4096) │- │ key_buf = String::with_capacity(128) │- │ │- │ for event in events: │- │ payload_buf.clear() ◄─ no alloc │- │ key_buf.clear() ◄─ no alloc │- │ event.serialize_into(ctx, &payload_buf) │- │ event.partition_key(ctx, &key_buf) │- │ producer.send(...) │- └──────────────────────────────────────────────┘-```+`WrappedEvent::serialize` pre-sizes its buffer via+`String::with_capacity(data.len() + 512)` to minimize reallocations+for typical payloads.### Skip mechanisms@@ -356,7 +344,7 @@ Captures every failure mode within a single configured sink:| Variant | Outcome | When ||---|---|---|| `SinkUnavailable` | `RetriableError` | Producer health gate failed |-| `SerializationFailed(String)` | `FatalError` | `serialize_into` returned `Err` |+| `SerializationFailed(String)` | `FatalError` | `serialize` returned `Err` || `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`) |@@ -443,10 +431,10 @@ corresponds 1:1 to a published event.│ for each event: ││ ├── should_publish()? → skip if false ││ ├── topic_for(destination)? → skip if Drop/None │- │ ├── serialize_into(ctx, payload_buf) │+ │ ├── event.serialize(ctx) → payload String ││ ├── event.headers(ctx) → CapturedEventHeaders │- │ ├── event.partition_key(ctx, key_buf) │- │ ├── effective_partition_key(key, headers, dest) → key/None │+ │ ├── should_null_partition_key(headers, dest)? │+ │ │ └── false → event.partition_key(ctx) → Some(key) ││ ├── CapturedEventHeaders → OwnedHeaders (via From) ││ └── producer.send(ProduceRecord) ││ ├── Ok(ack_future) → push to FuturesUnordered │@@ -497,10 +485,9 @@ reusable `String` buffers (`payload_buf`, `key_buf`) are cleared andrewritten each iteration, amortizing allocations to zero after the firstevent.-If `producer.send()` returns `QueueFull`, the sink retries up to-`enqueue_retry_max` times with `enqueue_poll_ms` pauses. This gives-rdkafka's background thread time to drain in-flight deliveries. Metrics-track recovery vs exhaustion via `capture_v1_kafka_queue_full_retries_total`.+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.After serialization and header construction, `effective_partition_key()`(`kafka/sink.rs`) decides whether the partition key should be nulled.@@ -673,8 +660,6 @@ only needs to specify hosts and topics.| `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 |-| `enqueue_retry_max` | `3` | _(application-level)_ | QueueFull backpressure retries |-| `enqueue_poll_ms` | `33` | _(application-level)_ | Pause between QueueFull retries || `topic_main` | _(required)_ | — | Analytics main topic || `topic_historical` | _(required)_ | — | Historical migration topic || `topic_overflow` | _(required)_ | — | Overflow topic |@@ -906,7 +891,7 @@ request-level context (`path`, `attempt`).| `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 |-| `capture_v1_kafka_queue_full_retries_total` | counter | `mode`, `cluster`, `result` | QueueFull retry (`result` = `recovered` or `exhausted`) |+| `capture_v1_kafka_serialize_duration_seconds` | histogram | `mode`, `cluster`, `path`, `attempt` (capped at "6+"), `batch_size` | Per-batch serialization time (serialize + partition-key + enqueue loop), bucketed by batch size for latency/size correlation |Cardinality note: the `destination` label is bounded at 9 values(`Destination::as_tag()` collapses all `Custom(_)` topics to `custom`)@@ -993,12 +978,12 @@ keeping the Sink trait unaware of topic names.Partition key construction is split between the `Event` implementationand the sink:-1. **`Event::partition_key(ctx, buf)`** always writes a key into the- buffer. For analytics events (`WrappedEvent`):+1. **`Event::partition_key(ctx)`** returns an owned key String.+ For analytics events (`WrappedEvent`):```text┌───────────────────────────────────────────────────┐- │ partition_key(ctx, buf) │+ │ partition_key(ctx) -> String ││ ││ cookieless_mode? ││ ├── yes, capture_internal → "token:127.0.0.1" │@@ -1007,7 +992,7 @@ and the sink:└───────────────────────────────────────────────────┘```-2. **`effective_partition_key()`** (`kafka/sink.rs`) decides whether+2. **`should_null_partition_key()`** (`kafka/sink.rs`) decides whetherthe key should be nulled before sending to the producer:```rust@@ -1076,7 +1061,7 @@ expect.│ destination: Destination││ force_disable_* │└───────────┬─────────────┘- │ serialize_into(ctx, buf)+ │ serialize(ctx)▼┌──────────────────────────────┐│ IngestionEvent (Kafka msg) │@@ -1151,7 +1136,7 @@ Fields intentionally omitted vs the legacy `RawEvent`:### IP redaction`capture_internal` requests (PostHog's own telemetry) have their IP-redacted to `127.0.0.1` in both `serialize_into` (the `ip` field on+redacted to `127.0.0.1` in both `serialize` (the `ip` field on`IngestionEvent`) and `partition_key` (cookieless mode).---@@ -1204,14 +1189,12 @@ Builder options include:| `ack_delay(d)` | Simulate slow acks / timeouts || `not_ready()` | Producer health gate fails || `with_liveness(deadline, poll)` | Custom liveness timing for health tests |-| `enqueue_retry_max(n)` | QueueFull retry budget |-| `enqueue_poll_ms(ms)` | QueueFull retry pause |### Analytics event serialization tests`v1::analytics::types` has a comprehensive test suite validating:-- **Round-trip parity**: `WrappedEvent::serialize_into` output+- **Round-trip parity**: `WrappedEvent::serialize` outputdeserializes as `common_types::CapturedEvent` + `RawEvent`, verifyingfield-by-field compatibility with legacy capture.- **Property injection**: all option fields are correctly injected intodiff --git a/rust/capture/src/v1/sinks/event.rs b/rust/capture/src/v1/sinks/event.rsindex 2fba52ed82cc..f8c3022bddd7 100644--- a/rust/capture/src/v1/sinks/event.rs+++ b/rust/capture/src/v1/sinks/event.rs@@ -27,11 +27,11 @@ pub trait Event: Send + Sync {/// `common_types`).fn headers(&self, ctx: &Context) -> CapturedEventHeaders;- /// Write the partition key for this event into `buf`.- /// Always writes unconditionally -- the sink decides whether to use it- /// or null it based on routing policy (e.g. force_disable_person_processing).- fn partition_key(&self, ctx: &Context, buf: &mut String);+ /// Return the partition key for this event.+ /// The sink decides whether to use it or null it based on routing policy+ /// (e.g. force_disable_person_processing).+ fn partition_key(&self, ctx: &Context) -> String;- /// Serialize the event payload into a caller-provided buffer.- fn serialize_into(&self, ctx: &Context, buf: &mut String) -> anyhow::Result<()>;+ /// Serialize the event payload and return the JSON string.+ fn serialize(&self, ctx: &Context) -> anyhow::Result<String>;}diff --git a/rust/capture/src/v1/sinks/kafka/config.rs b/rust/capture/src/v1/sinks/kafka/config.rsindex 853bdc9f36cd..4b1ed71d3597 100644--- a/rust/capture/src/v1/sinks/kafka/config.rs+++ b/rust/capture/src/v1/sinks/kafka/config.rs@@ -94,16 +94,6 @@ pub struct Config {#[envconfig(default = "0")]pub socket_receive_buffer_bytes: u32,- // -- QueueFull backpressure --- /// Max enqueue retry attempts when rdkafka returns QueueFull.- /// 0 = no retries (immediate failure, pre-backpressure behavior).- #[envconfig(default = "3")]- pub enqueue_retry_max: u32,- /// Pause between QueueFull retry attempts (ms). Gives rdkafka's- /// background poller time to drain in-flight deliveries.- #[envconfig(default = "33")]- pub enqueue_poll_ms: u32,-// -- Topics (all required -- envconfig errors if any are missing) --pub topic_main: String,pub topic_historical: String,@@ -218,8 +208,6 @@ mod tests {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("ENQUEUE_RETRY_MAX".into(), "5".into());- env.insert("ENQUEUE_POLL_MS".into(), "50".into());env.insert("PARTITIONER".into(), "consistent_random".into());env.insert("MAX_RETRIES".into(), "6".into());env.insert("MAX_IN_FLIGHT_REQUESTS".into(), "500000".into());@@ -248,8 +236,6 @@ mod tests {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.enqueue_retry_max, 5);- assert_eq!(cfg.enqueue_poll_ms, 50);assert_eq!(cfg.partitioner, "consistent_random");assert_eq!(cfg.max_retries, 6);assert_eq!(cfg.max_in_flight_requests, 500000);@@ -282,8 +268,6 @@ mod tests {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.enqueue_retry_max, 3);- assert_eq!(cfg.enqueue_poll_ms, 33);assert_eq!(cfg.partitioner, "murmur2_random");assert_eq!(cfg.max_retries, 4);assert_eq!(cfg.max_in_flight_requests, 1000000);diff --git a/rust/capture/src/v1/sinks/kafka/constants.rs b/rust/capture/src/v1/sinks/kafka/constants.rsnew file mode 100644index 000000000000..e996a818b805--- /dev/null+++ b/rust/capture/src/v1/sinks/kafka/constants.rs@@ -0,0 +1,53 @@+// ---------------------------------------------------------------------------+// 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";++/// Per-batch serialization time histogram (labeled by batch_size bucket).+pub(super) const KAFKA_SERIALIZE_DURATION_SECONDS: &str =+ "capture_v1_kafka_serialize_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.rsindex c579b8f5bd79..d9e62ea59ff4 100644--- a/rust/capture/src/v1/sinks/kafka/context.rs+++ b/rust/capture/src/v1/sinks/kafka/context.rs@@ -4,6 +4,7 @@ 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;@@ -72,7 +73,7 @@ impl rdkafka::ClientContext for KafkaContext {"rdkafka client error");counter!(- "capture_v1_kafka_client_errors_total",+ KAFKA_CLIENT_ERRORS_TOTAL,"cluster" => sink,"mode" => mode,"error" => tag,@@ -95,7 +96,7 @@ impl rdkafka::ClientContext for KafkaContext {"all brokers DOWN for sink");counter!(- "capture_v1_kafka_client_errors_total",+ KAFKA_CLIENT_ERRORS_TOTAL,"cluster" => sink,"mode" => mode,"error" => "all_brokers_down",@@ -104,27 +105,27 @@ impl rdkafka::ClientContext for KafkaContext {}// metric label key "cluster" kept for dashboard backward compatibility- gauge!("capture_v1_kafka_producer_queue_depth",+ gauge!(KAFKA_PRODUCER_QUEUE_DEPTH,"cluster" => sink, "mode" => mode).set(stats.msg_cnt as f64);- gauge!("capture_v1_kafka_producer_queue_bytes",+ gauge!(KAFKA_PRODUCER_QUEUE_BYTES,"cluster" => sink, "mode" => mode).set(stats.msg_size as f64);if stats.msg_max > 0 {- gauge!("capture_v1_kafka_producer_queue_utilization",+ 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!("capture_v1_kafka_batch_size_bytes_avg",+ 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!("capture_v1_kafka_broker_connected",+ gauge!(KAFKA_BROKER_CONNECTED,"cluster" => sink, "mode" => mode, "broker" => Arc::clone(&id)).set(if bs.state == BROKER_STATE_UP {1.0@@ -133,32 +134,26 @@ impl rdkafka::ClientContext for KafkaContext {});// Broker round-trip latency.if let Some(rtt) = &bs.rtt {- emit_window_stats("capture_v1_kafka_broker_rtt_us", rtt, sink, mode, &id);+ 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(- "capture_v1_kafka_broker_int_latency_us",- int_latency,- sink,- mode,- &id,- );+ 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(- "capture_v1_kafka_broker_outbuf_latency_us",+ KAFKA_BROKER_OUTBUF_LATENCY_US,outbuf_latency,sink,mode,&id,);}- counter!("capture_v1_kafka_broker_tx_errors_total",+ counter!(KAFKA_BROKER_TX_ERRORS_TOTAL,"cluster" => sink, "mode" => mode, "broker" => Arc::clone(&id)).absolute(bs.txerrs);- counter!("capture_v1_kafka_broker_rx_errors_total",+ counter!(KAFKA_BROKER_RX_ERRORS_TOTAL,"cluster" => sink, "mode" => mode, "broker" => id).absolute(bs.rxerrs);}diff --git a/rust/capture/src/v1/sinks/kafka/mod.rs b/rust/capture/src/v1/sinks/kafka/mod.rsindex aa02447860b7..5be141aa74bd 100644--- a/rust/capture/src/v1/sinks/kafka/mod.rs+++ b/rust/capture/src/v1/sinks/kafka/mod.rs@@ -1,4 +1,5 @@pub mod config;+pub mod constants;pub mod context;pub mod mock;pub mod producer;diff --git a/rust/capture/src/v1/sinks/kafka/producer.rs b/rust/capture/src/v1/sinks/kafka/producer.rsindex f2a76dc74330..784a1d4d1271 100644--- a/rust/capture/src/v1/sinks/kafka/producer.rs+++ b/rust/capture/src/v1/sinks/kafka/producer.rs@@ -10,6 +10,7 @@ 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;@@ -205,7 +206,7 @@ impl KafkaProducer {sink.as_str());counter!(- "capture_v1_kafka_client_errors_total",+ KAFKA_CLIENT_ERRORS_TOTAL,"cluster" => sink.as_str(),"mode" => capture_mode,"error" => "metadata_fetch_failed",diff --git a/rust/capture/src/v1/sinks/kafka/sink.rs b/rust/capture/src/v1/sinks/kafka/sink.rsindex ed3c59d03cf2..f191c58b83a9 100644--- a/rust/capture/src/v1/sinks/kafka/sink.rs+++ b/rust/capture/src/v1/sinks/kafka/sink.rs@@ -19,28 +19,36 @@ use crate::v1::sinks::sink::Sink;use crate::v1::sinks::types::{BatchSummary, Destination, Outcome, SinkResult};use crate::v1::sinks::{Config, SinkName};+use super::constants::*;use super::producer::ProduceRecord;use super::types::{KafkaResult, KafkaSinkError};use super::KafkaProducerTrait;-/// Null the partition key when person processing is force-disabled for-/// Main/Overflow destinations — spreads load across partitions instead of-/// hotspotting on a single token:distinct_id pair.-fn effective_partition_key<'a>(- key_buf: &'a str,+/// Bounded batch-size bucket for the serialize_duration histogram label.+/// 5 values keeps cardinality manageable while giving visibility into+/// the batch-size / latency relationship.+fn batch_size_bucket(n: usize) -> &'static str {+ match n {+ 0..=1 => "1",+ 2..=8 => "2-8",+ 9..=32 => "9-32",+ 33..=128 => "33-128",+ _ => "129+",+ }+}++/// Returns true when the partition key should be nulled — i.e. when person+/// processing is force-disabled for Main/Overflow destinations, spreading+/// load across partitions instead of hotspotting on a single key.+fn should_null_partition_key(force_disable_person_processing: bool,destination: &Destination,-) -> Option<&'a str> {- if force_disable_person_processing+) -> bool {+ force_disable_person_processing&& matches!(destination,Destination::AnalyticsMain | Destination::Overflow)- {- None- } else {- Some(key_buf)- }}/// Shared label values for metrics emitted within a single `publish_batch` call.@@ -107,7 +115,7 @@ fn reject_publishable(}for (dest_tag, count) in &by_dest {counter!(- "capture_v1_kafka_publish_total",+ KAFKA_PUBLISH_TOTAL,"mode" => labels.mode,"cluster" => labels.sink,"outcome" => Outcome::RetriableError.as_tag(),@@ -159,8 +167,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {pending: &mut FuturesUnordered<AckFuture>,enqueued_keys: &mut Vec<(Uuid, &'static str, Instant)>,) {- let mut payload_buf = String::with_capacity(4096);- let mut key_buf = String::with_capacity(128);+ let serialize_start = Instant::now();for event in events {if !event.should_publish() {@@ -175,119 +182,95 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {None => continue,};- payload_buf.clear();- if let Err(e) = event.serialize_into(ctx, &mut payload_buf) {- crate::ctx_log!(- Level::ERROR,- ctx,- sink = labels.sink,- event_uuid = %uuid,- error = %e,- "event serialization failed, dropping event"- );- counter!(- "capture_v1_kafka_publish_total",- "mode" => labels.mode,- "cluster" => labels.sink,- "outcome" => Outcome::FatalError.as_tag(),- "path" => labels.path,- "attempt" => labels.attempt,- "destination" => dest_tag,- )- .increment(1);- results.push(Box::new(KafkaResult::err(- uuid,- KafkaSinkError::SerializationFailed(format!("{e:#}")),- enqueued_at,- )));- continue;- }+ let payload = match event.serialize(ctx) {+ Ok(p) => p,+ Err(e) => {+ crate::ctx_log!(+ Level::ERROR,+ ctx,+ sink = labels.sink,+ event_uuid = %uuid,+ error = %e,+ "event serialization failed, dropping event"+ );+ counter!(+ KAFKA_PUBLISH_TOTAL,+ "mode" => labels.mode,+ "cluster" => labels.sink,+ "outcome" => Outcome::FatalError.as_tag(),+ "path" => labels.path,+ "attempt" => labels.attempt,+ "destination" => dest_tag,+ )+ .increment(1);+ results.push(Box::new(KafkaResult::err(+ uuid,+ KafkaSinkError::SerializationFailed(format!("{e:#}")),+ enqueued_at,+ )));+ continue;+ }+ };let captured_headers = event.headers(ctx);- key_buf.clear();- event.partition_key(ctx, &mut key_buf);- let key = effective_partition_key(- &key_buf,+ let key = if should_null_partition_key(captured_headers.force_disable_person_processing.unwrap_or(false),event.destination(),- );+ ) {+ None+ } else {+ Some(event.partition_key(ctx))+ };let headers: rdkafka::message::OwnedHeaders = captured_headers.into();- let mut record = ProduceRecord {+ let record = ProduceRecord {topic,- key,- payload: &payload_buf,+ key: key.as_deref(),+ payload: &payload,headers,};- let enqueue_retry_max = self.config.kafka.enqueue_retry_max;- let enqueue_poll = Duration::from_millis(self.config.kafka.enqueue_poll_ms as u64);- let mut hit_queue_full = false;-- for enqueue_attempt in 0..=enqueue_retry_max {- if enqueue_attempt > 0 {- tokio::time::sleep(enqueue_poll).await;+ 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)+ }));}-- match self.producer.send(record) {- Ok(ack_future) => {- if hit_queue_full {- counter!(- "capture_v1_kafka_queue_full_retries_total",- "mode" => labels.mode,- "cluster" => labels.sink,- "result" => "recovered",- )- .increment(1);- }- 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)- }));- break;- }- Err((e, returned_record))- if e.is_queue_full() && enqueue_attempt < enqueue_retry_max =>- {- hit_queue_full = true;- record = returned_record;- continue;- }- Err((e, _)) => {- if hit_queue_full || e.is_queue_full() {- counter!(- "capture_v1_kafka_queue_full_retries_total",- "mode" => labels.mode,- "cluster" => labels.sink,- "result" => "exhausted",- )- .increment(1);- }- let sink_err = KafkaSinkError::Produce(e);- let outcome = sink_err.outcome();- counter!(- "capture_v1_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)));- break;- }+ 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)));}}}++ histogram!(+ KAFKA_SERIALIZE_DURATION_SECONDS,+ "mode" => labels.mode,+ "cluster" => labels.sink,+ "path" => labels.path,+ "attempt" => labels.attempt,+ "batch_size" => batch_size_bucket(events.len()),+ )+ .record(serialize_start.elapsed().as_secs_f64());}/// Phase 2: drain ack futures with a per-sink deadline. Dropping remaining@@ -322,7 +305,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {};counter!(- "capture_v1_kafka_publish_total",+ KAFKA_PUBLISH_TOTAL,"mode" => labels.mode,"cluster" => labels.sink,"outcome" => outcome_tag,@@ -335,7 +318,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {// Per-event broker-ack latency (send → ack), isolated from// batch enqueue wall-time.histogram!(- "capture_v1_kafka_ack_duration_seconds",+ KAFKA_ACK_DURATION_SECONDS,"mode" => labels.mode,"cluster" => labels.sink,"outcome" => outcome_tag,@@ -385,7 +368,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {}for (dest_tag, count) in &by_dest {counter!(- "capture_v1_kafka_publish_total",+ KAFKA_PUBLISH_TOTAL,"mode" => labels.mode,"cluster" => labels.sink,"outcome" => Outcome::Timeout.as_tag(),@@ -400,7 +383,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {// Record timed-out acks so the latency tail (>= produce_timeout)// is visible rather than silently dropped.histogram!(- "capture_v1_kafka_ack_duration_seconds",+ KAFKA_ACK_DURATION_SECONDS,"mode" => labels.mode,"cluster" => labels.sink,"outcome" => Outcome::Timeout.as_tag(),@@ -464,7 +447,7 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {).await;histogram!(- "capture_v1_kafka_enqueue_duration_seconds",+ KAFKA_ENQUEUE_DURATION_SECONDS,"mode" => labels.mode,"cluster" => labels.sink,"path" => labels.path,@@ -508,7 +491,7 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {}for (tag, count) in &summary.errors {counter!(- "capture_v1_kafka_produce_errors_total",+ KAFKA_PRODUCE_ERRORS_TOTAL,"cluster" => labels.sink,"mode" => labels.mode,"error" => *tag@@ -537,23 +520,19 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {}#[cfg(test)]-mod effective_partition_key_tests {+mod should_null_partition_key_tests {use super::*;use rstest::rstest;#[rstest]- #[case::main_disabled(true, Destination::AnalyticsMain, None)]- #[case::overflow_disabled(true, Destination::Overflow, None)]- #[case::dlq_disabled(true, Destination::Dlq, Some("k"))]- #[case::historical_disabled(true, Destination::AnalyticsHistorical, Some("k"))]- #[case::custom_disabled(true, Destination::Custom("t".into()), Some("k"))]- #[case::main_not_disabled(false, Destination::AnalyticsMain, Some("k"))]- fn policy(- #[case] force_disable: bool,- #[case] dest: Destination,- #[case] expected: Option<&str>,- ) {- assert_eq!(effective_partition_key("k", force_disable, &dest), expected);+ #[case::main_disabled(true, Destination::AnalyticsMain, true)]+ #[case::overflow_disabled(true, Destination::Overflow, true)]+ #[case::dlq_disabled(true, Destination::Dlq, false)]+ #[case::historical_disabled(true, Destination::AnalyticsHistorical, false)]+ #[case::custom_disabled(true, Destination::Custom("t".into()), false)]+ #[case::main_not_disabled(false, Destination::AnalyticsMain, false)]+ fn policy(#[case] force_disable: bool, #[case] dest: Destination, #[case] expected: bool) {+ assert_eq!(should_null_partition_key(force_disable, &dest), expected);}}diff --git a/rust/capture/src/v1/sinks/kafka/sink_tests.rs b/rust/capture/src/v1/sinks/kafka/sink_tests.rsindex 3d8653d82f88..b911f1e13901 100644--- a/rust/capture/src/v1/sinks/kafka/sink_tests.rs+++ b/rust/capture/src/v1/sinks/kafka/sink_tests.rs@@ -109,18 +109,13 @@ impl Event for FakeEvent {self.event_headers.clone()}- fn partition_key(&self, _ctx: &Context, buf: &mut String) {- if let Some(k) = &self.partition_key {- buf.push_str(k);- }+ fn partition_key(&self, _ctx: &Context) -> String {+ self.partition_key.clone().unwrap_or_default()}- fn serialize_into(&self, _ctx: &Context, buf: &mut String) -> anyhow::Result<()> {+ fn serialize(&self, _ctx: &Context) -> anyhow::Result<String> {match &self.payload {- Ok(p) => {- buf.push_str(p);- Ok(())- }+ Ok(p) => Ok(p.clone()),Err(e) => Err(anyhow::anyhow!(e.clone())),}}@@ -152,8 +147,6 @@ impl TestHarness {ack_delay: None,not_ready: false,liveness: None,- enqueue_retry_max: None,- enqueue_poll_ms: None,}}}@@ -166,8 +159,6 @@ struct HarnessBuilder {ack_delay: Option<Duration>,not_ready: bool,liveness: Option<(Duration, Duration)>,- enqueue_retry_max: Option<u32>,- enqueue_poll_ms: Option<u32>,}impl HarnessBuilder {@@ -206,16 +197,6 @@ impl HarnessBuilder {self}- fn enqueue_retry_max(mut self, n: u32) -> Self {- self.enqueue_retry_max = Some(n);- self- }-- fn enqueue_poll_ms(mut self, ms: u32) -> Self {- self.enqueue_poll_ms = Some(ms);- self- }-fn build(self) -> TestHarness {let mut builder = lifecycle::Manager::builder("test").with_trap_signals(false)@@ -255,13 +236,7 @@ impl HarnessBuilder {let producer = Arc::new(mock);- let mut kafka_config = crate::v1::test_utils::test_kafka_config();- if let Some(n) = self.enqueue_retry_max {- kafka_config.enqueue_retry_max = n;- }- if let Some(ms) = self.enqueue_poll_ms {- kafka_config.enqueue_poll_ms = ms;- }+ let kafka_config = crate::v1::test_utils::test_kafka_config();let config = Config {produce_timeout: self.produce_timeout,@@ -374,66 +349,16 @@ async fn sink_unavailable() {}// ----------------------------------------------------------------------------// 5. Send-time retriable error (queue full)-// -----------------------------------------------------------------------------#[tokio::test]-async fn send_error_retriable_queue_full() {- let h = TestHarness::builder()- .send_error(|| ProduceError::Kafka {- code: RDKafkaErrorCode::QueueFull,- })- .enqueue_retry_max(0)- .build();- let event = FakeEvent::ok("evt-1");- let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];-- 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);-}--// ----------------------------------------------------------------------------// 5b. QueueFull retry succeeds after drain-// -----------------------------------------------------------------------------#[tokio::test]-async fn queue_full_retry_succeeds_after_drain() {- let h = TestHarness::builder()- .send_error(|| ProduceError::Kafka {- code: RDKafkaErrorCode::QueueFull,- })- .send_error_count(2)- .enqueue_retry_max(3)- .enqueue_poll_ms(1)- .build();- let event = FakeEvent::ok("evt-1");- let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];-- 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_eq!(h.producer.record_count(), 1);-}--// ----------------------------------------------------------------------------// 5c. QueueFull retry exhausted+// 5. QueueFull is immediate retriable error (no app-level retry loop;+// backpressure handled by librdkafka queue + client retry).// ---------------------------------------------------------------------------#[tokio::test]-async fn queue_full_retry_exhausted() {+async fn queue_full_is_immediate_retriable() {let h = TestHarness::builder().send_error(|| ProduceError::Kafka {code: RDKafkaErrorCode::QueueFull,})- .enqueue_retry_max(2)- .enqueue_poll_ms(1).build();let event = FakeEvent::ok("evt-1");let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];@@ -447,31 +372,6 @@ async fn queue_full_retry_exhausted() {assert_eq!(h.producer.record_count(), 0);}-// ----------------------------------------------------------------------------// 5d. QueueFull retry disabled (enqueue_retry_max = 0)-// -----------------------------------------------------------------------------#[tokio::test]-async fn queue_full_retry_zero_max_disables_retry() {- let h = TestHarness::builder()- .send_error(|| ProduceError::Kafka {- code: RDKafkaErrorCode::QueueFull,- })- .send_error_count(1)- .enqueue_retry_max(0)- .enqueue_poll_ms(1)- .build();- let event = FakeEvent::ok("evt-1");- let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];-- 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("queue_full"));- assert_eq!(h.producer.record_count(), 0);-}-// ---------------------------------------------------------------------------// 6. Send-time fatal error (event too big)// ---------------------------------------------------------------------------@@ -806,11 +706,9 @@ fn health_harness(mode: &FailureMode) -> TestHarness {b = b.ack_delay(Duration::from_secs(10));}FailureMode::SendError => {- b = b- .send_error(|| ProduceError::Kafka {- code: RDKafkaErrorCode::QueueFull,- })- .enqueue_retry_max(0);+ b = b.send_error(|| ProduceError::Kafka {+ code: RDKafkaErrorCode::QueueFull,+ });}FailureMode::AckError => {b = b.ack_error(|| ProduceError::DeliveryCancelled);@@ -1093,7 +991,6 @@ async fn mixed_send_error_and_ack_error_in_batch() {code: RDKafkaErrorCode::QueueFull,}).send_error_count(1)- .enqueue_retry_max(0).ack_error(|| ProduceError::DeliveryCancelled).build();let e1 = FakeEvent::ok("evt-1");@@ -1132,7 +1029,6 @@ async fn partial_timeout_with_send_error() {code: RDKafkaErrorCode::QueueFull,}).send_error_count(1)- .enqueue_retry_max(0).ack_delay(Duration::from_secs(60)).produce_timeout(Duration::from_millis(50)).build();diff --git a/rust/capture/src/v1/sinks/router.rs b/rust/capture/src/v1/sinks/router.rsindex b76f09ef5b3e..c7cf606d7de4 100644--- a/rust/capture/src/v1/sinks/router.rs+++ b/rust/capture/src/v1/sinks/router.rs@@ -179,13 +179,11 @@ mod tests {content_encoding: None,}}- fn partition_key(&self, _ctx: &Context, buf: &mut String) {- use std::fmt::Write;- let _ = write!(buf, "key:{}", self.uuid());+ fn partition_key(&self, _ctx: &Context) -> String {+ format!("key:{}", self.uuid())}- fn serialize_into(&self, _ctx: &Context, buf: &mut String) -> anyhow::Result<()> {- buf.push_str(r#"{"event":"test"}"#);- Ok(())+ fn serialize(&self, _ctx: &Context) -> anyhow::Result<String> {+ Ok(r#"{"event":"test"}"#.to_string())}}diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex d62d811c8ae6..59a88f85b7b0 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -390,10 +390,7 @@ pub fn assert_round_trip() -> (common_types::CapturedEvent, common_types::RawEvent) {use crate::v1::sinks::event::Event as SinkEvent;- let mut buf = String::new();- wrapped- .serialize_into(ctx, &mut buf)- .expect("serialize_into failed");+ let buf = wrapped.serialize(ctx).expect("serialize failed");let captured: common_types::CapturedEvent =serde_json::from_str(&buf).expect("v1 output must deserialize as CapturedEvent");let data: common_types::RawEvent =