: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): call sites publish through outputs; Event retired (#89039)
Paweł Ledwońb8a80d12e370
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.mdindex 5529c43111c8..3d0df100350e 100644--- a/rust/capture/OUTPUTS_REFACTOR_PLAN.md+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md@@ -124,7 +124,9 @@ Step 7 absorbs it into the `OutputRegistry`; the mode-scoped demand is folded in#### Step 8 · Call sites migrate to the table; `Event` retired-- **Goal.** All four call sites (`events/analytics.rs`, `ai_endpoint.rs`, `otel/mod.rs`, `events/recordings.rs`) publish via `OutputRegistry::publish`, recording `capture_event_batch_size` at the call site; `State` and test mocks retype; then delete the v0 `Event` trait, the outputs facade, the Kafka `Event` bridge, and the single-event `kafka_send` path.+- **Goal.** All four call sites (`events/analytics.rs`, `ai_endpoint.rs`, `otel/mod.rs`, `events/recordings.rs`) publish via `OutputRegistry::publish`, recording `capture_event_batch_size` at the call site; `State` and test mocks retype; then delete the v0 `Event` trait, its `Box<T>` blanket, the outputs facade, and the `Event` impls on Kafka, S3, print, noop, and the test mock.+- **`State` drops its trait object.** `State.sink: Arc<dyn Event>` becomes `State.outputs: Arc<OutputRegistry>` — a concrete type, since `Output::single` already accepts any leaf. The substitution seam moves down to the leaf: `PublishEvents` and `Output::single` become `pub` so the `tests/` suites can stand their own capturing sinks in (`test_sink` is `cfg(test)`-gated and unreachable from there), and pipeline tests drive the real table and policy path instead of bypassing the outputs layer.+- **`kafka_send` survives this step.** It is not reachable only from `Event::send`: `PublishEvents::publish_events` calls it on its one-event branch, and that is the production single-event path (recordings publishes one event per call). Deleting it means re-expressing that branch over `prepare_batch` + `Sink::publish` + `fold_results`, which adds a task spawn per single event and drops the `ack_wait_one` span — a behavior change, and this step is a mechanical move. Step 12 retires it with the prep hoist.- **Parity proof.** All endpoint/integration suites green; grep proves `Event` call-site-free before the deletion half.- **Size.** M/L. May split into per-call-site commits if the diff grows.@@ -160,9 +162,9 @@ Step 7 absorbs it into the `OutputRegistry`; the mode-scoped demand is folded in- **Files.** `outputs/mod.rs`, `outputs/registry.rs` (moved), `sinks/*`, `setup.rs`, all capturing test mocks.- **Size.** L.-### Per-mode output tables (Step 15)+### Per-mode output registries (Step 15)-The deployment's output table is a concrete type — `AnalyticsFamilyOutputs` (analytics, ai, heatmaps, warnings, error tracking rows) for Events/Ai pods, `SessionReplayOutputs` for Recordings pods — with required fields, so the narrow list of what a deployment must wire is the type itself. Handlers bound on sealed capability traits (`PublishesAnalyticsFamily`, `PublishesSessionReplay`); `State<T>` is generic over the table and `setup` instantiates the monomorphized router per `CaptureMode` (`router` for the analytics family, `session_replay_router` for recordings) — mounting an ingress on a table that cannot publish its family is a compile error. Rows share backends (one Kafka connection, one S3 client, one breaker controller), so per-row policy trees behave as the single pre-table output did. The runtime backstop for a pipeline without a row is an explicit fatal error, structurally dead while ingress mounting and table type derive from the same mode.+The deployment's output registry is a concrete type — `AnalyticsFamilyOutputs` (analytics, ai, heatmaps, warnings, error tracking rows) for Events/Ai pods, `SessionReplayOutputs` for Recordings pods — with required fields, so the narrow list of what a deployment must wire is the type itself. Handlers bound on sealed capability traits (`PublishesAnalyticsFamily`, `PublishesSessionReplay`); `State<T>` is generic over the registry and `setup` instantiates the monomorphized router per `CaptureMode` (`router` for the analytics family, `session_replay_router` for recordings) — mounting an ingress on a table that cannot publish its family is a compile error. Rows share backends (one Kafka connection, one S3 client, one breaker controller), so per-row policy trees behave as the single pre-table output did. The runtime backstop for a pipeline without a row is an explicit fatal error, structurally dead while ingress mounting and registry type derive from the same mode.### Per-pipeline output overrides and boot verification (Step 18)@@ -270,15 +272,15 @@ When all steps land, the five strata hold:| 5 · `Pipeline` + `Lane`; lane resolution | done | `refactor(capture): lane decision moves to the pipeline layer` || 6 · Kafka sink → backend mechanism | done | `refactor(capture): narrow the kafka sink to backend mechanism over prepared payloads` || 7 · Outputs layer with policies; composites retired | done | `feat(capture): outputs layer owns the failover policy` |-| 8a · Call sites on the table | pending | `refactor(capture): call sites publish through outputs` |-| 8b · `Event` retired | pending | `refactor(capture): retire v0 Event trait` |+| 8a · Call sites on the table | done | `refactor(capture): call sites publish through outputs` |+| 8b · `Event` retired | done | `refactor(capture): retire v0 Event trait` || 9 · Mode-scoped completeness | pending | `refactor(capture): mode-scoped output registry completeness` || 10 · Breaker mode (dark) | pending | `feat(capture): breaker-driven failover mode (dark)` || 11 · v1 convergence | pending | `refactor(capture): v1 resolves through shared pipeline/lane strata` || 12 · Prep hoist; `PublishEvents` retired | pending | `refactor(capture): hoist prep into outputs; sinks take prepared payloads only` || 13 · Typed addresses; AI pipeline | pending | `refactor(capture): typed per-pipeline lanes; custom redirects and the ai stream become addresses` || 14 · Sinks realize namespaces | pending | `refactor(capture): payloads carry addresses; sinks realize them in their own namespace` |-| 15 · Per-mode output tables | pending | `feat(capture): per-mode output tables; handlers bound by publish capabilities` |+| 15 · Per-mode output registries | pending | `feat(capture): per-mode output registries; handlers bound by publish capabilities` || 16 · AI ingress family | pending | `feat(capture): ai ingress is its own router family with its own capability` || 17 · Topic tables injected into sinks | pending | `refactor(capture): topic tables are sink-side data, injected at construction` || 18 · Per-pipeline output overrides; boot topic verification | pending | `feat(capture): per-pipeline output overrides and boot topic verification` |diff --git a/rust/capture/src/ai_endpoint.rs b/rust/capture/src/ai_endpoint.rsindex 6c0f08e6b517..dd897232453e 100644--- a/rust/capture/src/ai_endpoint.rs+++ b/rust/capture/src/ai_endpoint.rs@@ -7,7 +7,7 @@ use bytes::Bytes;use common_types::{CapturedEvent, HasEventName};use futures::stream;use limiters::redis::QuotaResource;-use metrics::counter;+use metrics::{counter, histogram};use multer::{parse_boundary, Multipart};use serde::{Deserialize, Serialize};use serde_json::Value;@@ -396,11 +396,16 @@ async fn ai_handler_inner(state.ai_events_overflow_limiter.as_ref(),);- // Step 9: Send event to Kafka- state.sink.send(processed_event).await.map_err(|e| {- warn!("Failed to send AI event to Kafka: {:?}", e);- e- })?;+ // Step 9: Publish the event. One event per request on this endpoint.+ histogram!("capture_event_batch_size").record(1.0);+ state+ .outputs+ .publish(vec![processed_event])+ .await+ .map_err(|e| {+ warn!("Failed to send AI event to Kafka: {:?}", e);+ e+ })?;// Log request details for debuggingdebug!("AI endpoint request validated and sent to Kafka successfully");diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rsindex 3375c2150e8e..2fb44596c8a1 100644--- a/rust/capture/src/events/analytics.rs+++ b/rust/capture/src/events/analytics.rs@@ -12,7 +12,7 @@ use common_ingestion_warnings::{};use common_types::{CapturedEvent, RawEvent};use limiters::token_dropper::TokenDropper;-use metrics::counter;+use metrics::{counter, histogram};use serde_json;use tracing::{error, instrument, warn, Span};use uuid::Uuid;@@ -29,8 +29,9 @@ use crate::{emit_distinct_id_truncated_warning, emit_rate_limit_warning,legacy::{emit_processing_abort_warning, request_context},},+ outputs::OutputRegistry,prometheus::{report_clock_skew, report_dropped_events},- router, sinks,+ router,utils::uuid_v7_from_datetime,v0_request::{exceeds_max_ai_event_bytes, DataType, OverflowReason, ProcessedEvent,@@ -236,7 +237,7 @@ pub fn process_single_event(#[instrument(skip_all, fields(events = events.len(), request_id))]#[allow(clippy::too_many_arguments)]pub async fn process_events(- sink: Arc<dyn sinks::Event + Send + Sync>,+ outputs: Arc<OutputRegistry>,dropper: Arc<TokenDropper>,restriction_service: Option<EventRestrictionService>,historical_cfg: router::HistoricalConfig,@@ -257,7 +258,7 @@ pub async fn process_events(let event_count = events.len() as u64;let emitter = ingestion_warning_emitter.clone();let result = process_events_inner(- sink,+ outputs,dropper,restriction_service,historical_cfg,@@ -279,7 +280,7 @@ pub async fn process_events(#[allow(clippy::too_many_arguments)]async fn process_events_inner(- sink: Arc<dyn sinks::Event + Send + Sync>,+ outputs: Arc<OutputRegistry>,dropper: Arc<TokenDropper>,restriction_service: Option<EventRestrictionService>,historical_cfg: router::HistoricalConfig,@@ -612,11 +613,8 @@ async fn process_events_inner(return Ok(());}- if events.len() == 1 {- sink.send(events[0].clone()).await?;- } else {- sink.send_batch(events).await?;- }+ histogram!("capture_event_batch_size").record(events.len() as f64);+ outputs.publish(events).await?;debug_or_info!(chatty_debug_enabled, context=?context, "sent analytics events");@@ -733,13 +731,13 @@ mod tests {}async fn run_pipeline(- sink: Arc<dyn sinks::Event + Send + Sync>,+ outputs: Arc<OutputRegistry>,events: Vec<RawEvent>,context: &ProcessingContext,options: PipelineOptions,) -> Result<(), CaptureError> {process_events(- sink,+ outputs,options.dropper,options.restriction_service,options.historical_cfg,@@ -962,7 +960,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// Create restriction service with DropEventlet service =@@ -980,7 +978,7 @@ mod tests {service.update(manager).await;let result = run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -1007,7 +1005,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// Create restriction service with ForceOverflowlet service =@@ -1025,7 +1023,7 @@ mod tests {service.update(manager).await;let result = run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -1053,7 +1051,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// Create restriction service with SkipPersonProcessinglet service =@@ -1071,7 +1069,7 @@ mod tests {service.update(manager).await;let result = run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -1099,7 +1097,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// Create restriction service with RedirectToDlqlet service =@@ -1117,7 +1115,7 @@ mod tests {service.update(manager).await;let result = run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -1145,7 +1143,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// Create restriction service with multiple restrictionslet service =@@ -1170,7 +1168,7 @@ mod tests {service.update(manager).await;let result = run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -1199,10 +1197,16 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// No restriction service- let result = run_pipeline(sink.clone(), events, &context, PipelineOptions::default()).await;+ let result = run_pipeline(+ Arc::new(OutputRegistry::single(sink.clone())),+ events,+ &context,+ PipelineOptions::default(),+ )+ .await;assert!(result.is_ok());let captured = sink.get_events();@@ -1225,7 +1229,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// Create restriction that only applies to different event namelet service =@@ -1245,7 +1249,7 @@ mod tests {service.update(manager).await;let result = run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -1273,7 +1277,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let service =EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));@@ -1290,7 +1294,7 @@ mod tests {service.update(manager).await;let result = run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -1374,11 +1378,16 @@ mod tests {),];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();- run_pipeline(sink.clone(), events, &context, PipelineOptions::default())- .await- .unwrap();+ run_pipeline(+ Arc::new(OutputRegistry::single(sink.clone())),+ events,+ &context,+ PipelineOptions::default(),+ )+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(captured.len(), 2);@@ -1409,10 +1418,10 @@ mod tests {let limiter = Some(Arc::new(GlobalRateLimiter::mock_budget(800)));let producer = MockKafkaProducer::new();- let sink = Arc::new(KafkaSinkBase::with_producer(+ let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(producer.clone(),test_topics(),- ));+ )));let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z").unwrap()@@ -1436,7 +1445,7 @@ mod tests {.insert("$ai_input".to_string(), json!("x".repeat(500)));process_events(- sink,+ outputs,Arc::new(TokenDropper::default()),None,router::HistoricalConfig::new(false, 1),@@ -1477,7 +1486,7 @@ mod tests {let mut context = create_test_context(now, None);context.ai_max_event_bytes = 700;- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let mut oversized = create_test_event_with_name("$ai_generation",Some("2023-01-01T11:00:00Z".to_string()),@@ -1493,7 +1502,7 @@ mod tests {oversized.uuid = Some(offender_uuid);let err = run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),vec![create_test_event_with_name("$ai_generation",@@ -1533,7 +1542,7 @@ mod tests {let mut context = create_test_context(now, None);context.ai_max_event_bytes = 700;- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let mut oversized = create_test_event_with_name("$pageview",Some("2023-01-01T11:00:00Z".to_string()),@@ -1545,7 +1554,7 @@ mod tests {.insert("big".to_string(), json!("x".repeat(800)));run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),vec![oversized],&context,PipelineOptions::default(),@@ -1589,7 +1598,7 @@ mod tests {);service.update(manager).await;- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let events = vec![create_test_event_with_name("$ai_generation",@@ -1606,7 +1615,7 @@ mod tests {];run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -1670,10 +1679,10 @@ mod tests {create_test_event_with_name(case.second_event, None, None, None),];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let collector = Arc::new(CollectingEmitter::new());let result = run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -1719,10 +1728,15 @@ mod tests {create_test_event_with_name("$pageview", None, None, None),];- let sink = Arc::new(MockSink::new());- run_pipeline(sink.clone(), events, &context, PipelineOptions::default())- .await- .expect("capture-analytics must accept a mixed batch");+ let sink = MockSink::new();+ run_pipeline(+ Arc::new(OutputRegistry::single(sink.clone())),+ events,+ &context,+ PipelineOptions::default(),+ )+ .await+ .expect("capture-analytics must accept a mixed batch");let captured = sink.get_events();assert_eq!(captured.len(), 2);@@ -1747,10 +1761,10 @@ mod tests {let limiter = Some(Arc::new(GlobalRateLimiter::mock_budget(800)));let producer = MockKafkaProducer::new();- let sink = Arc::new(KafkaSinkBase::with_producer(+ let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(producer.clone(),test_topics(),- ));+ )));let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z").unwrap()@@ -1775,7 +1789,7 @@ mod tests {.insert("$ai_input".to_string(), json!("x".repeat(500)));process_events(- sink,+ outputs,Arc::new(TokenDropper::default()),None,router::HistoricalConfig::new(false, 1),@@ -1811,7 +1825,7 @@ mod tests {async fn events_mode_leaves_analytics_main_untouched_end_to_end() {let limiter = Some(Arc::new(GlobalRateLimiter::mock_budget(300)));- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z").unwrap()@@ -1841,7 +1855,7 @@ mod tests {.insert("$current_url".to_string(), json!("x".repeat(500)));process_events(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),Arc::new(TokenDropper::default()),None,router::HistoricalConfig::new(false, 1),@@ -1898,7 +1912,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let service = EventRestrictionService::new(vec![Pipeline::Analytics, Pipeline::Ai],@@ -1917,7 +1931,7 @@ mod tests {service.update(manager).await;run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -1955,7 +1969,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let service = EventRestrictionService::new(vec![Pipeline::Analytics, Pipeline::Ai],@@ -1974,7 +1988,7 @@ mod tests {service.update(manager).await;run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2013,7 +2027,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let service =EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));@@ -2030,7 +2044,7 @@ mod tests {service.update(manager).await;run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2071,7 +2085,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let service =EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));@@ -2100,7 +2114,7 @@ mod tests {service.update(manager).await;run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2148,7 +2162,7 @@ mod tests {),];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// Single service serving both pipelines, with a DropEvent restriction// attached only to the errortracking pipeline.@@ -2169,7 +2183,7 @@ mod tests {service.update(manager).await;run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2214,7 +2228,7 @@ mod tests {),];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let service = EventRestrictionService::new(vec![Pipeline::Analytics, Pipeline::ErrorTracking],@@ -2233,7 +2247,7 @@ mod tests {service.update(manager).await;run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2272,7 +2286,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let service =EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));@@ -2289,7 +2303,7 @@ mod tests {service.update(manager).await;run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2336,11 +2350,16 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();- run_pipeline(sink.clone(), events, &context, PipelineOptions::default())- .await- .unwrap();+ run_pipeline(+ Arc::new(OutputRegistry::single(sink.clone())),+ events,+ &context,+ PipelineOptions::default(),+ )+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(captured.len(), 1);@@ -2359,12 +2378,12 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// test_token is in the reroute list -> ForceLimitedlet limiter = build_limiter(10, 10, Some("test_token".to_string()), false);run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2414,13 +2433,13 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let ai_limiter = case.ai_limiter_present.then(|| build_limiter(10, 10, Some("test_token".to_string()), false));run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2448,12 +2467,12 @@ mod tests {create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None),];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// burst of 1 -> first event passes, second event rate-limitedlet limiter = build_limiter(1, 1, None, true);run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2486,11 +2505,11 @@ mod tests {create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None),];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let limiter = build_limiter(1, 1, None, false);run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2525,7 +2544,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// Even with a limiter that would flag this token, force_overflow wins.let limiter = build_limiter(10, 10, Some("test_token".to_string()), false);@@ -2544,7 +2563,7 @@ mod tests {service.update(manager).await;run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2577,11 +2596,11 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let limiter = build_limiter(10, 10, Some("test_token".to_string()), false);run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2619,7 +2638,7 @@ mod tests {create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None),];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();// Global RL: limits (test_token, test_user) -> key `test_token:test_user`.let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));@@ -2629,7 +2648,7 @@ mod tests {let overflow_limiter = build_limiter(1, 1, None, true);run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2686,11 +2705,11 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2750,12 +2769,12 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));let collector = Arc::new(CollectingEmitter::new());run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2800,11 +2819,11 @@ mod tests {create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None),];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let collector = Arc::new(CollectingEmitter::new());let result = run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2835,11 +2854,11 @@ mod tests {// fix, so the customer-facing warning must stay silent.struct RejectingSink;#[async_trait::async_trait]- impl sinks::Event for RejectingSink {- async fn send(&self, _event: ProcessedEvent) -> Result<(), CaptureError> {- Err(CaptureError::RetryableSinkError)- }- async fn send_batch(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ impl crate::outputs::PublishEvents for RejectingSink {+ async fn publish_events(+ &self,+ _events: Vec<ProcessedEvent>,+ ) -> Result<(), CaptureError> {Err(CaptureError::RetryableSinkError)}}@@ -2857,7 +2876,7 @@ mod tests {let collector = Arc::new(CollectingEmitter::new());let result = run_pipeline(- Arc::new(RejectingSink),+ Arc::new(OutputRegistry::single(RejectingSink)),events,&context,PipelineOptions {@@ -2888,7 +2907,7 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));let collector = Arc::new(CollectingEmitter::new());@@ -2907,7 +2926,7 @@ mod tests {service.update(manager).await;run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2945,11 +2964,11 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -2990,11 +3009,16 @@ mod tests {create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None),];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();- run_pipeline(sink.clone(), events, &context, PipelineOptions::default())- .await- .unwrap();+ run_pipeline(+ Arc::new(OutputRegistry::single(sink.clone())),+ events,+ &context,+ PipelineOptions::default(),+ )+ .await+ .unwrap();assert_eq!(sink.get_events().len(),@@ -3018,11 +3042,16 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();- run_pipeline(sink.clone(), events, &context, PipelineOptions::default())- .await- .unwrap();+ run_pipeline(+ Arc::new(OutputRegistry::single(sink.clone())),+ events,+ &context,+ PipelineOptions::default(),+ )+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(captured.len(), 1);@@ -3050,11 +3079,11 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));run_pipeline(- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),events,&context,PipelineOptions {@@ -3095,15 +3124,15 @@ mod tests {)];let producer = MockKafkaProducer::new();- let sink = Arc::new(KafkaSinkBase::with_producer(+ let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(producer.clone(),test_topics(),- ));+ )));// test_token in reroute list -> ForceLimited stamped in pipeline.let limiter = build_limiter(10, 10, Some("test_token".to_string()), false);run_pipeline(- sink,+ outputs,events,&context,PipelineOptions {@@ -3151,15 +3180,15 @@ mod tests {];let producer = MockKafkaProducer::new();- let sink = Arc::new(KafkaSinkBase::with_producer(+ let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(producer.clone(),test_topics(),- ));+ )));// burst=1 => event[1] stamped RateLimited { preserve_locality }.let limiter = build_limiter(1, 1, None, preserve_locality);run_pipeline(- sink,+ outputs,events,&context,PipelineOptions {@@ -3430,11 +3459,16 @@ mod tests {let context = create_test_context(now, None);let events = vec![build_heatmap_carrier_event(shape)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();- run_pipeline(sink.clone(), events, &context, PipelineOptions::default())- .await- .unwrap();+ run_pipeline(+ Arc::new(OutputRegistry::single(sink.clone())),+ events,+ &context,+ PipelineOptions::default(),+ )+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(captured.len(), 2, "should produce original + redirect");@@ -3467,11 +3501,16 @@ mod tests {event.event = "$$heatmap".to_string();let events = vec![event];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();- run_pipeline(sink.clone(), events, &context, PipelineOptions::default())- .await- .unwrap();+ run_pipeline(+ Arc::new(OutputRegistry::single(sink.clone())),+ events,+ &context,+ PipelineOptions::default(),+ )+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(@@ -3493,11 +3532,16 @@ mod tests {None,)];- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();- run_pipeline(sink.clone(), events, &context, PipelineOptions::default())- .await- .unwrap();+ run_pipeline(+ Arc::new(OutputRegistry::single(sink.clone())),+ events,+ &context,+ PipelineOptions::default(),+ )+ .await+ .unwrap();let captured = sink.get_events();assert_eq!(captured.len(), 1);@@ -3524,12 +3568,12 @@ mod tests {let events = vec![event];let producer = MockKafkaProducer::new();- let sink = Arc::new(KafkaSinkBase::with_producer(+ let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(producer.clone(),test_topics(),- ));+ )));- run_pipeline(sink, events, &context, PipelineOptions::default())+ run_pipeline(outputs, events, &context, PipelineOptions::default()).await.unwrap();@@ -3710,14 +3754,14 @@ mod tests {async fn run_batch_collecting_warnings(events: Vec<RawEvent>,- sink: Arc<dyn sinks::Event + Send + Sync>,+ outputs: Arc<OutputRegistry>,) -> (Result<(), CaptureError>,Vec<common_ingestion_warnings::test_support::EmittedWarning>,) {run_batch_collecting_warnings_with_dropper(events,- sink,+ outputs,Arc::new(limiters::token_dropper::TokenDropper::default()),).await@@ -3725,7 +3769,7 @@ mod tests {async fn run_batch_collecting_warnings_with_dropper(events: Vec<RawEvent>,- sink: Arc<dyn sinks::Event + Send + Sync>,+ outputs: Arc<OutputRegistry>,dropper: Arc<limiters::token_dropper::TokenDropper>,) -> (Result<(), CaptureError>,@@ -3738,7 +3782,7 @@ mod tests {let collector = Arc::new(CollectingEmitter::new());let result = run_pipeline(- sink,+ outputs,events,&context,PipelineOptions {@@ -3760,8 +3804,10 @@ mod tests {event_with_distinct_id("normal_user"),];- let sink = Arc::new(MockSink::new());- let (result, emitted) = run_batch_collecting_warnings(events, sink.clone()).await;+ let sink = MockSink::new();+ let (result, emitted) =+ run_batch_collecting_warnings(events, Arc::new(OutputRegistry::single(sink.clone())))+ .await;result.unwrap();let sent = sink.get_events();@@ -3793,8 +3839,11 @@ mod tests {event_with_distinct_id(&"y".repeat(300)),];- let (result, emitted) =- run_batch_collecting_warnings(events, Arc::new(MockSink::new())).await;+ let (result, emitted) = run_batch_collecting_warnings(+ events,+ Arc::new(OutputRegistry::single(MockSink::new())),+ )+ .await;result.unwrap();assert_eq!(emitted.len(), 1);@@ -3812,8 +3861,11 @@ mod tests {async fn no_truncation_warning_for_ids_within_the_cap() {let events = vec![event_with_distinct_id(&"z".repeat(200))];- let (result, emitted) =- run_batch_collecting_warnings(events, Arc::new(MockSink::new())).await;+ let (result, emitted) = run_batch_collecting_warnings(+ events,+ Arc::new(OutputRegistry::single(MockSink::new())),+ )+ .await;result.unwrap();assert!(emitted.is_empty());@@ -3835,13 +3887,13 @@ mod tests {// Only truncated event is dropped: nothing was ingested-but-modified,// so no warning at all.- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let (result, emitted) = run_batch_collecting_warnings_with_dropper(vec![event_with_distinct_id(&dropped_id),event_with_distinct_id("normal_user"),],- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),dropper.clone(),).await;@@ -3851,13 +3903,13 @@ mod tests {// One truncated event dropped, another survives: count and sample// must reflect only the survivor.- let sink = Arc::new(MockSink::new());+ let sink = MockSink::new();let (result, emitted) = run_batch_collecting_warnings_with_dropper(vec![event_with_distinct_id(&dropped_id),event_with_distinct_id(&surviving_id),],- sink.clone(),+ Arc::new(OutputRegistry::single(sink.clone())),dropper,).await;@@ -3879,11 +3931,11 @@ mod tests {// the sink refused was not ingested, so emitting would misreport.struct RejectingSink;#[async_trait::async_trait]- impl sinks::Event for RejectingSink {- async fn send(&self, _event: ProcessedEvent) -> Result<(), CaptureError> {- Err(CaptureError::RetryableSinkError)- }- async fn send_batch(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ impl crate::outputs::PublishEvents for RejectingSink {+ async fn publish_events(+ &self,+ _events: Vec<ProcessedEvent>,+ ) -> Result<(), CaptureError> {Err(CaptureError::RetryableSinkError)}}@@ -3891,7 +3943,8 @@ mod tests {let events = vec![event_with_distinct_id(&"x".repeat(250))];let (result, emitted) =- run_batch_collecting_warnings(events, Arc::new(RejectingSink)).await;+ run_batch_collecting_warnings(events, Arc::new(OutputRegistry::single(RejectingSink)))+ .await;assert!(matches!(result, Err(CaptureError::RetryableSinkError)));assert!(emitted.is_empty());diff --git a/rust/capture/src/events/recordings.rs b/rust/capture/src/events/recordings.rsindex 9f57970a775c..2cb566938616 100644--- a/rust/capture/src/events/recordings.rs+++ b/rust/capture/src/events/recordings.rs@@ -38,8 +38,8 @@ use crate::{SnapshotDataRejection,},},+ outputs::OutputRegistry,prometheus::report_dropped_events,- sinks,utils::uuid_v7_from_datetime,v0_request::{DataType, OverflowReason, ProcessedEvent, ProcessedEventMetadata, ProcessingContext,@@ -254,7 +254,7 @@ impl HasEventName for RawRecording {///#[instrument(skip_all, fields(events = events.len(), session_id, request_id))]pub async fn process_replay_events(- sink: Arc<dyn sinks::Event + Send + Sync>,+ outputs: Arc<OutputRegistry>,restriction_service: Option<EventRestrictionService>,replay_overflow_limiter: Option<Arc<RedisLimiter>>,ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,@@ -264,7 +264,7 @@ pub async fn process_replay_events(let event_count = events.len() as u64;let abort = match process_replay_events_inner(- sink,+ outputs,restriction_service,replay_overflow_limiter,events,@@ -349,7 +349,7 @@ impl ReplayAbort {/// modified, including when the request was dropped by an event restriction and/// so ingested nothing to warn about.async fn process_replay_events_inner(- sink: Arc<dyn sinks::Event + Send + Sync>,+ outputs: Arc<OutputRegistry>,restriction_service: Option<EventRestrictionService>,replay_overflow_limiter: Option<Arc<RedisLimiter>>,events: Vec<RawRecording>,@@ -600,7 +600,11 @@ async fn process_replay_events_inner(historical_migration: context.historical_migration,};- sink.send(ProcessedEvent { metadata, event }).await?;+ // One `$snapshot_items` event per call.+ histogram!("capture_event_batch_size").record(1.0);+ outputs+ .publish(vec![ProcessedEvent { metadata, event }])+ .await?;debug_or_info!(chatty_debug_enabled, context=?context, "sent recordings CapturedEvent");@@ -826,8 +830,8 @@ mod tests {use crate::event_restrictions::{EventRestrictionService, Restriction, RestrictionManager, RestrictionScope,};+ use crate::outputs::OutputRegistry;use crate::sinks::test_sink::MockSink;- use crate::sinks::Event;use common_redis::MockRedisClient;use limiters::redis::{QuotaResource, ServiceName, OVERFLOW_LIMITER_CACHE_KEY};use std::sync::{Arc, Mutex};@@ -868,9 +872,9 @@ mod tests {#[tokio::test]async fn test_process_replay_events_drop_event_restriction() {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let service = EventRestrictionService::new(vec![Pipeline::SessionRecordings],@@ -892,8 +896,15 @@ mod tests {let recording = create_test_recording();let context = create_test_context();- let result =- process_replay_events(sink, Some(service), None, None, vec![recording], &context).await;+ let result = process_replay_events(+ outputs,+ Some(service),+ None,+ None,+ vec![recording],+ &context,+ )+ .await;assert!(result.is_ok());assert!(events_captured.lock().unwrap().is_empty());@@ -902,9 +913,9 @@ mod tests {#[tokio::test]async fn test_process_replay_events_redirect_to_dlq_restriction() {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let service = EventRestrictionService::new(vec![Pipeline::SessionRecordings],@@ -926,8 +937,15 @@ mod tests {let recording = create_test_recording();let context = create_test_context();- let result =- process_replay_events(sink, Some(service), None, None, vec![recording], &context).await;+ let result = process_replay_events(+ outputs,+ Some(service),+ None,+ None,+ vec![recording],+ &context,+ )+ .await;assert!(result.is_ok());let captured = events_captured.lock().unwrap();@@ -938,9 +956,9 @@ mod tests {#[tokio::test]async fn test_process_replay_events_force_overflow_restriction() {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let service = EventRestrictionService::new(vec![Pipeline::SessionRecordings],@@ -962,8 +980,15 @@ mod tests {let recording = create_test_recording();let context = create_test_context();- let result =- process_replay_events(sink, Some(service), None, None, vec![recording], &context).await;+ let result = process_replay_events(+ outputs,+ Some(service),+ None,+ None,+ vec![recording],+ &context,+ )+ .await;assert!(result.is_ok());let captured = events_captured.lock().unwrap();@@ -974,9 +999,9 @@ mod tests {#[tokio::test]async fn test_process_replay_events_skip_person_processing_restriction() {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let service = EventRestrictionService::new(vec![Pipeline::SessionRecordings],@@ -998,8 +1023,15 @@ mod tests {let recording = create_test_recording();let context = create_test_context();- let result =- process_replay_events(sink, Some(service), None, None, vec![recording], &context).await;+ let result = process_replay_events(+ outputs,+ Some(service),+ None,+ None,+ vec![recording],+ &context,+ )+ .await;assert!(result.is_ok());let captured = events_captured.lock().unwrap();@@ -1010,14 +1042,15 @@ mod tests {#[tokio::test]async fn test_process_replay_events_no_restriction_service() {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let recording = create_test_recording();let context = create_test_context();- let result = process_replay_events(sink, None, None, None, vec![recording], &context).await;+ let result =+ process_replay_events(outputs, None, None, None, vec![recording], &context).await;assert!(result.is_ok());let captured = events_captured.lock().unwrap();@@ -1039,14 +1072,14 @@ mod tests {];for (stamp, expected) in cases {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let mut recording = create_test_recording();recording.properties.snapshot_host = stamp.clone();let context = create_test_context();- process_replay_events(sink, None, None, None, vec![recording], &context)+ process_replay_events(outputs, None, None, None, vec![recording], &context).await.unwrap();@@ -1063,9 +1096,9 @@ mod tests {#[tokio::test]async fn test_process_replay_events_filtered_restriction() {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let service = EventRestrictionService::new(vec![Pipeline::SessionRecordings],@@ -1090,8 +1123,15 @@ mod tests {let recording = create_test_recording(); // has session_id "test-session-123"let context = create_test_context();- let result =- process_replay_events(sink, Some(service), None, None, vec![recording], &context).await;+ let result = process_replay_events(+ outputs,+ Some(service),+ None,+ None,+ vec![recording],+ &context,+ )+ .await;// Should NOT be dropped because session_id doesn't match filterassert!(result.is_ok());@@ -1128,14 +1168,15 @@ mod tests {#[tokio::test]async fn test_replay_overflow_stamp_none_when_limiter_absent() {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let recording = create_test_recording();let context = create_test_context();- let result = process_replay_events(sink, None, None, None, vec![recording], &context).await;+ let result =+ process_replay_events(outputs, None, None, None, vec![recording], &context).await;assert!(result.is_ok());let captured = events_captured.lock().unwrap();@@ -1146,16 +1187,23 @@ mod tests {#[tokio::test]async fn test_replay_overflow_stamp_replay_limited_for_matching_session() {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let limiter = build_replay_limiter(vec!["test-session-123".to_string()]).await;let recording = create_test_recording(); // session_id = "test-session-123"let context = create_test_context();- let result =- process_replay_events(sink, None, Some(limiter), None, vec![recording], &context).await;+ let result = process_replay_events(+ outputs,+ None,+ Some(limiter),+ None,+ vec![recording],+ &context,+ )+ .await;assert!(result.is_ok());let captured = events_captured.lock().unwrap();@@ -1169,16 +1217,23 @@ mod tests {#[tokio::test]async fn test_replay_overflow_stamp_none_for_unlimited_session() {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let limiter = build_replay_limiter(vec!["some-other-session".to_string()]).await;let recording = create_test_recording();let context = create_test_context();- let result =- process_replay_events(sink, None, Some(limiter), None, vec![recording], &context).await;+ let result = process_replay_events(+ outputs,+ None,+ Some(limiter),+ None,+ vec![recording],+ &context,+ )+ .await;assert!(result.is_ok());let captured = events_captured.lock().unwrap();@@ -1192,9 +1247,9 @@ mod tests {// must leave overflow_reason = None so the sink routes on force_overflow// directly (matching the old sink precedence).let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let service = EventRestrictionService::new(vec![Pipeline::SessionRecordings],@@ -1218,7 +1273,7 @@ mod tests {let context = create_test_context();let result = process_replay_events(- sink,+ outputs,Some(service),Some(limiter),None,@@ -1241,16 +1296,16 @@ mod tests {// uniformly to the batch. This guards against a regression where a// per-item check might diverge from batch-level routing.let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured.clone(),- });+ }));let limiter = build_replay_limiter(vec!["test-session-123".to_string()]).await;let recordings = vec![create_test_recording(), create_test_recording()];let context = create_test_context();let result =- process_replay_events(sink, None, Some(limiter), None, recordings, &context).await;+ process_replay_events(outputs, None, Some(limiter), None, recordings, &context).await;assert!(result.is_ok());let captured = events_captured.lock().unwrap();@@ -1307,15 +1362,22 @@ mod tests {async fn test_replay_overflow_histogram_recorded_when_limited() {let (histograms, _) = run_with_metric_capture(|| async {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured,- });+ }));let limiter = build_replay_limiter(vec!["test-session-123".to_string()]).await;let recording = create_test_recording();let context = create_test_context();- process_replay_events(sink, None, Some(limiter), None, vec![recording], &context)- .await- .unwrap();+ process_replay_events(+ outputs,+ None,+ Some(limiter),+ None,+ vec![recording],+ &context,+ )+ .await+ .unwrap();}).await;@@ -1331,17 +1393,24 @@ mod tests {async fn test_replay_overflow_histogram_recorded_when_not_limited() {let (histograms, _) = run_with_metric_capture(|| async {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured,- });+ }));// Session NOT in the limited set -> limiter returns false, but// the histogram must still record the call duration.let limiter = build_replay_limiter(vec!["some-other-session".to_string()]).await;let recording = create_test_recording();let context = create_test_context();- process_replay_events(sink, None, Some(limiter), None, vec![recording], &context)- .await- .unwrap();+ process_replay_events(+ outputs,+ None,+ Some(limiter),+ None,+ vec![recording],+ &context,+ )+ .await+ .unwrap();}).await;@@ -1357,9 +1426,9 @@ mod tests {async fn test_replay_overflow_histogram_not_recorded_on_force_overflow() {let (histograms, _) = run_with_metric_capture(|| async {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured,- });+ }));// force_overflow short-circuits the limiter branch; the pipeline// must skip the redis call AND the histogram record.@@ -1383,7 +1452,7 @@ mod tests {let recording = create_test_recording();let context = create_test_context();process_replay_events(- sink,+ outputs,Some(service),Some(limiter),None,@@ -1407,12 +1476,12 @@ mod tests {async fn test_replay_overflow_histogram_not_recorded_when_limiter_absent() {let (histograms, _) = run_with_metric_capture(|| async {let events_captured = Arc::new(Mutex::new(Vec::new()));- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: events_captured,- });+ }));let recording = create_test_recording();let context = create_test_context();- process_replay_events(sink, None, None, None, vec![recording], &context)+ process_replay_events(outputs, None, None, None, vec![recording], &context).await.unwrap();})@@ -1438,18 +1507,25 @@ mod tests {#[tokio::test]async fn e2e_replay_limited_pipeline_to_sink_routes_to_replay_overflow_with_session_key() {let producer = MockKafkaProducer::new();- let sink: Arc<dyn Event + Send + Sync> = Arc::new(KafkaSinkBase::with_producer(+ let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(producer.clone(),test_topics(),- ));+ )));let limiter = build_replay_limiter(vec!["test-session-123".to_string()]).await;let recording = create_test_recording(); // session_id = "test-session-123"let context = create_test_context();- process_replay_events(sink, None, Some(limiter), None, vec![recording], &context)- .await- .unwrap();+ process_replay_events(+ outputs,+ None,+ Some(limiter),+ None,+ vec![recording],+ &context,+ )+ .await+ .unwrap();let records = producer.get_records();assert_eq!(records.len(), 1);@@ -1476,16 +1552,16 @@ mod tests {async fn warnings_from_replay(events: Vec<RawRecording>,) -> Vec<common_ingestion_warnings::test_support::EmittedWarning> {- let sink: Arc<dyn Event + Send + Sync> = Arc::new(MockSink {+ let outputs = Arc::new(OutputRegistry::single(MockSink {events: Arc::new(Mutex::new(Vec::new())),- });+ }));let emitter = Arc::new(CollectingEmitter::default());// The outcome is asserted by each caller through the warnings; a failing// result is the point in most of these cases.drop(process_replay_events(- sink,+ outputs,None,None,Some(emitter.clone()),diff --git a/rust/capture/src/otel/mod.rs b/rust/capture/src/otel/mod.rsindex d27bb358edc4..a27e3d5c0d16 100644--- a/rust/capture/src/otel/mod.rs+++ b/rust/capture/src/otel/mod.rs@@ -343,7 +343,8 @@ pub async fn otel_handler(// the size ceiling and the byte budget, either of which may have shed spans.let ingested = processed_events.len() as u64;- state.sink.send_batch(processed_events).await.map_err(|e| {+ histogram!("capture_event_batch_size").record(processed_events.len() as f64);+ state.outputs.publish(processed_events).await.map_err(|e| {report_internal_error_metrics(e.to_metric_tag(), "otel_sink");warn!("Failed to send OTel events to Kafka: {:?}", e);e.into_response()diff --git a/rust/capture/src/outputs.rs b/rust/capture/src/outputs.rsindex 02dbdbead4eb..f77d9b7e96ef 100644--- a/rust/capture/src/outputs.rs+++ b/rust/capture/src/outputs.rs@@ -7,22 +7,25 @@//! topics and serializes for itself.use async_trait::async_trait;-use metrics::{counter, gauge, histogram};+use metrics::{counter, gauge};use tracing::instrument;use tracing::log::error;use crate::api::CaptureError;-use crate::sinks::Event;use crate::v0_request::ProcessedEvent;/// The leaf produce contract: run prep, publish, and fold internally and/// report the v0 whole-request result, so no caller sees a two-phase/// protocol.+///+/// `pub` rather than `pub(crate)` because the integration suites in+/// `tests/` stand their own capturing sinks in as output leaves; there is+/// no other reason to implement it outside this crate.#[async_trait]-pub(crate) trait PublishEvents: Send + Sync {- async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError>;-- async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError>;+pub trait PublishEvents: Send + Sync {+ /// One method for any batch size: a backend that serves a one-event+ /// batch more cheaply specializes inside its own impl.+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError>;fn flush(&self) -> Result<(), anyhow::Error> {Ok(())@@ -39,7 +42,7 @@ enum Inner {}impl Output {- pub(crate) fn single<L: PublishEvents + 'static>(leaf: L) -> Self {+ pub fn single<L: PublishEvents + 'static>(leaf: L) -> Self {Self {inner: Inner::Single(Box::new(leaf)),}@@ -74,17 +77,10 @@ impl Output {// future type.#[async_trait]impl PublishEvents for Output {- async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- match &self.inner {- Inner::Single(leaf) => leaf.publish_one(event).await,- Inner::Failover(failover) => failover.publish_one(event).await,- }- }-- async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {match &self.inner {- Inner::Single(leaf) => leaf.publish_batch(events).await,- Inner::Failover(failover) => failover.publish_batch(events).await,+ Inner::Single(leaf) => leaf.publish_events(events).await,+ Inner::Failover(failover) => failover.publish_events(events).await,}}@@ -111,44 +107,23 @@ impl Failover {}#[instrument(skip_all)]- async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {let healthy = self.primary_is_healthy();gauge!("capture_primary_sink_health").set(if healthy { 1.0 } else { 0.0 });if healthy {- match self.primary.publish_one(event.clone()).await {+ match self.primary.publish_events(events.clone()).await {Ok(()) => Ok(()),Err(CaptureError::RetryableSinkError) => {error!("Primary output failed, falling back");counter!("capture_fallback_sink_failovers_total").increment(1);- self.fallback.publish_one(event).await+ self.fallback.publish_events(events).await}Err(e) => Err(e),}} else {counter!("capture_fallback_sink_failovers_total").increment(1);- self.fallback.publish_one(event).await- }- }-- #[instrument(skip_all)]- async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {- let healthy = self.primary_is_healthy();- gauge!("capture_primary_sink_health").set(if healthy { 1.0 } else { 0.0 });-- if healthy {- match self.primary.publish_batch(events.clone()).await {- Ok(()) => Ok(()),- Err(CaptureError::RetryableSinkError) => {- error!("Primary output failed, falling back");- counter!("capture_fallback_sink_failovers_total").increment(1);- self.fallback.publish_batch(events).await- }- Err(e) => Err(e),- }- } else {- counter!("capture_fallback_sink_failovers_total").increment(1);- self.fallback.publish_batch(events).await+ self.fallback.publish_events(events).await}}@@ -170,22 +145,20 @@ impl OutputRegistry {pub fn new(output: Output) -> Self {Self { output }}-}-/// Transitional facade serving the `Event` call sites from the registry.-#[async_trait]-impl Event for OutputRegistry {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- histogram!("capture_event_batch_size").record(1.0);- self.output.publish_one(event).await+ pub fn single<L: PublishEvents + 'static>(leaf: L) -> Self {+ Self::new(Output::single(leaf))}- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {- histogram!("capture_event_batch_size").record(events.len() as f64);- self.output.publish_batch(events).await+ /// Per-event failures collapse to a whole-request `CaptureError`.+ ///+ /// Callers record `capture_event_batch_size` themselves: batch size is a+ /// property of the request, not of the output it lands on.+ pub async fn publish(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ self.output.publish_events(events).await}- fn flush(&self) -> Result<(), anyhow::Error> {+ pub fn flush(&self) -> Result<(), anyhow::Error> {self.output.flush()}}@@ -203,11 +176,7 @@ mod tests {#[async_trait]impl PublishEvents for FailLeaf {- async fn publish_one(&self, _event: ProcessedEvent) -> Result<(), CaptureError> {- Err(self.0.clone())- }-- async fn publish_batch(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ async fn publish_events(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {Err(self.0.clone())}}@@ -257,17 +226,11 @@ mod tests {);output- .publish_one(test_event())+ .publish_events(vec![test_event(), test_event()]).await- .expect("Failed to send event");+ .expect("Failed to publish batch");- let batch = vec![test_event(), test_event()];- output- .publish_batch(batch)- .await- .expect("Failed to send batch");-- assert_eq!(fallback.get_events().len(), 3);+ assert_eq!(fallback.get_events().len(), 2);}#[tokio::test]@@ -279,13 +242,9 @@ mod tests {);assert!(matches!(- output.publish_one(test_event()).await,- Err(CaptureError::RetryableSinkError)- ));-- let batch = vec![test_event(), test_event()];- assert!(matches!(- output.publish_batch(batch).await,+ output+ .publish_events(vec![test_event(), test_event()])+ .await,Err(CaptureError::RetryableSinkError)));}@@ -300,11 +259,7 @@ mod tests {);assert!(matches!(- output.publish_one(test_event()).await,- Err(CaptureError::NonRetryableSinkError)- ));- assert!(matches!(- output.publish_batch(vec![test_event()]).await,+ output.publish_events(vec![test_event()]).await,Err(CaptureError::NonRetryableSinkError)));@@ -345,7 +300,7 @@ mod tests {kafka_handle.report_healthy();tokio::time::sleep(Duration::from_millis(100)).await;- output.publish_one(test_event()).await.unwrap();+ output.publish_events(vec![test_event()]).await.unwrap();assert_eq!((primary.get_events().len(), fallback.get_events().len()),(1, 0),@@ -354,7 +309,7 @@ mod tests {// Let the advisory handle's deadline expire without calling report_healthytokio::time::sleep(Duration::from_millis(400)).await;- output.publish_one(test_event()).await.unwrap();+ output.publish_events(vec![test_event()]).await.unwrap();assert_eq!((primary.get_events().len(), fallback.get_events().len()),(1, 1),@@ -363,7 +318,7 @@ mod tests {kafka_handle.report_healthy();tokio::time::sleep(Duration::from_millis(100)).await;- output.publish_one(test_event()).await.unwrap();+ output.publish_events(vec![test_event()]).await.unwrap();assert_eq!((primary.get_events().len(), fallback.get_events().len()),(2, 1),@@ -372,13 +327,13 @@ mod tests {}#[tokio::test]- async fn registry_facade_serves_event_call_sites() {+ async fn registry_publishes_to_its_output() {let leaf = MockSink::new();- let registry = OutputRegistry::new(Output::single(leaf.clone()));+ let registry = OutputRegistry::single(leaf.clone());- registry.send(test_event()).await.unwrap();+ registry.publish(vec![test_event()]).await.unwrap();registry- .send_batch(vec![test_event(), test_event()])+ .publish(vec![test_event(), test_event()]).await.unwrap();diff --git a/rust/capture/src/overflow_parity.rs b/rust/capture/src/overflow_parity.rsindex 331d8fdeef32..675c0f64e3f0 100644--- a/rust/capture/src/overflow_parity.rs+++ b/rust/capture/src/overflow_parity.rs@@ -20,6 +20,7 @@ use rstest::rstest;use std::num::NonZeroU32;use crate::global_rate_limiter::GlobalRateLimiter;+use crate::outputs::OutputRegistry;use crate::router::HistoricalConfig;use crate::sinks::kafka::{test_topics, KafkaSinkBase};use crate::sinks::producer::MockKafkaProducer;@@ -122,10 +123,10 @@ fn v0_context(now: DateTime<Utc>) -> ProcessingContext {/// at `observe` off the mock producer.async fn run_v0(limits: Limits, batch_size: usize, observe: usize) -> Observed {let producer = MockKafkaProducer::new();- let sink = Arc::new(KafkaSinkBase::with_producer(+ let outputs = Arc::new(OutputRegistry::single(KafkaSinkBase::with_producer(producer.clone(),test_topics(),- ));+ )));let global = limits.globally_limited.then(|| {Arc::new(GlobalRateLimiter::mock_limiting(&[&format!("{V0_TOKEN}:{V0_DISTINCT_ID}"@@ -137,7 +138,7 @@ async fn run_v0(limits: Limits, batch_size: usize, observe: usize) -> Observed {.with_timezone(&Utc);crate::events::analytics::process_events(- sink,+ outputs,Arc::new(TokenDropper::default()),None,HistoricalConfig::new(false, 1),diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rsindex ca836ff92632..efe7f29e55b9 100644--- a/rust/capture/src/router.rs+++ b/rust/capture/src/router.rs@@ -18,9 +18,10 @@ use tower_http::trace::TraceLayer;use crate::event_restrictions::EventRestrictionService;use crate::global_rate_limiter::GlobalRateLimiter;use crate::otel;+use crate::outputs::OutputRegistry;use crate::test_endpoint;use crate::v0_request::DataType;-use crate::{ai_endpoint, sinks, time::TimeSource, v0_endpoint};+use crate::{ai_endpoint, time::TimeSource, v0_endpoint};use common_ingestion_warnings::WarningEmitter;use common_redis::Client;use limiters::overflow::OverflowLimiter;@@ -50,7 +51,7 @@ pub struct WireBodyLimit(pub usize);#[derive(Clone)]pub struct State {- pub sink: Arc<dyn sinks::Event + Send + Sync>,+ pub outputs: Arc<OutputRegistry>,pub timesource: Arc<dyn TimeSource + Send + Sync>,pub redis: Arc<dyn Client + Send + Sync>,pub global_rate_limiter_token_distinctid: Option<Arc<GlobalRateLimiter>>,@@ -169,7 +170,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +timesource: TZ,readiness: ReadinessHandler,liveness: LivenessHandler,- sink: Arc<dyn sinks::Event + Send + Sync>,+ outputs: Arc<OutputRegistry>,redis: Arc<R>,global_rate_limiter_token_distinctid: Option<Arc<GlobalRateLimiter>>,quota_limiter: CaptureQuotaLimiter,@@ -200,7 +201,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,) -> Router {let state = State {- sink,+ outputs,timesource: Arc::new(timesource),redis,global_rate_limiter_token_distinctid,diff --git a/rust/capture/src/server.rs b/rust/capture/src/server.rsindex 99b3367433f9..cf02150a08ec 100644--- a/rust/capture/src/server.rs+++ b/rust/capture/src/server.rs@@ -93,7 +93,7 @@ pub async fn serve(listener: TcpListener, components: CaptureComponents) {let CaptureComponents {app,server_handle,- sink,+ outputs,v1_sink_router,event_restriction_service: _,http1_header_read_timeout_ms,@@ -230,17 +230,17 @@ pub async fn serve(listener: TcpListener, components: CaptureComponents) {graceful.shutdown().await;info!("Hyper accept loop (shutdown): graceful shutdown completed");- // Flush both sink layers concurrently. Legacy flush is synchronous- // (rdkafka), so it runs on the blocking thread pool. V1 sinks already- // use spawn_blocking internally (see KafkaSink::flush).+ // Flush both produce layers concurrently. The v0 outputs flush is+ // synchronous (rdkafka), so it runs on the blocking thread pool. V1+ // sinks already use spawn_blocking internally (see KafkaSink::flush).info!("Flushing sinks...");let legacy_flush = {- let sink = Arc::clone(&sink);+ let outputs = Arc::clone(&outputs);async move {- let result = tokio::task::spawn_blocking(move || sink.flush()).await;+ let result = tokio::task::spawn_blocking(move || outputs.flush()).await;match result {- Ok(Err(e)) => error!("Sink flush failed: {e:#}"),- Err(e) => error!("Sink flush task panicked: {e}"),+ Ok(Err(e)) => error!("Output flush failed: {e:#}"),+ Err(e) => error!("Output flush task panicked: {e}"),Ok(Ok(())) => {}}}diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex 24bd247ed569..0c961976616a 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -27,7 +27,6 @@ use crate::sinks::kafka::KafkaSink;use crate::sinks::noop::NoOpSink;use crate::sinks::print::PrintSink;use crate::sinks::s3::S3Sink;-use crate::sinks::Event;use limiters::overflow::OverflowLimiter;use limiters::redis::{QuotaResource, RedisLimiter, ServiceName, OVERFLOW_LIMITER_CACHE_KEY};use limiters::token_dropper::TokenDropper;@@ -126,7 +125,7 @@ pub fn register_components(manager: &mut lifecycle::Manager, config: &Config) ->pub struct CaptureComponents {pub app: Router,pub server_handle: lifecycle::Handle,- pub sink: Arc<dyn Event + Send + Sync>,+ pub outputs: Arc<OutputRegistry>,pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,pub event_restriction_service: Option<EventRestrictionService>,pub http1_header_read_timeout_ms: Option<u64>,@@ -291,12 +290,12 @@ pub async fn build_components(_ => None,};- let sink: Arc<dyn Event + Send + Sync> = Arc::from(- create_sink(&config, sink_handle, advisory_handle)+ let outputs = Arc::new(+ create_output_registry(&config, sink_handle, advisory_handle).await- .expect("failed to create sink"),+ .expect("failed to create the output registry"),);- let sink_for_flush = sink.clone();+ let outputs_for_flush = outputs.clone();let event_restriction_service = if let Some(handle) = event_restrictions_handle {create_event_restriction_service(@@ -384,7 +383,7 @@ pub async fn build_components(crate::time::SystemTime {},readiness,liveness,- sink,+ outputs,redis_client,global_rate_limiter_token_distinctid,quota_limiter,@@ -423,7 +422,7 @@ pub async fn build_components(CaptureComponents {app,server_handle: server,- sink: sink_for_flush,+ outputs: outputs_for_flush,v1_sink_router,event_restriction_service,http1_header_read_timeout_ms: config.http1_header_read_timeout_ms,@@ -566,13 +565,13 @@ fn create_v1_sink_router(Ok(Arc::new(router))}-async fn create_sink(+async fn create_output_registry(config: &Config,sink_handle: Option<lifecycle::Handle>,advisory_handle: Option<lifecycle::Handle>,-) -> anyhow::Result<Box<dyn Event + Send + Sync>> {+) -> anyhow::Result<OutputRegistry> {let output = create_output(config, sink_handle, advisory_handle).await?;- Ok(Box::new(OutputRegistry::new(output)))+ Ok(OutputRegistry::new(output))}async fn create_output(@@ -1249,7 +1248,7 @@ mod tests {config.kafka.outputs_completeness_check_enabled = true;config.kafka.kafka_dlq_topic = String::new();- let err = create_sink(&config, None, None)+ let err = create_output_registry(&config, None, None).await.err().expect("boot must be refused when an output topic is empty");@@ -1262,7 +1261,7 @@ mod tests {// The default: with the check off, the same blank topic boots (and// would fail at first produce instead).config.kafka.outputs_completeness_check_enabled = false;- create_sink(&config, None, None)+ create_output_registry(&config, None, None).await.expect("boot must proceed when the completeness check is disabled");}diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rsindex 3fa38d829709..1205e620a28c 100644--- a/rust/capture/src/sinks/kafka.rs+++ b/rust/capture/src/sinks/kafka.rs@@ -26,7 +26,6 @@ use crate::serialization::Serializer;use crate::sinks::producer::{KafkaProducer, ProduceRecord};use crate::sinks::registry::{Destination, TopicTable};use crate::sinks::sink::{fold_results, Outcome, PreparedPayload, Sink, SinkResult};-use crate::sinks::Event;use crate::v0_request::{DataType, ProcessedEvent};use async_trait::async_trait;use metrics::{counter, gauge, histogram};@@ -199,14 +198,11 @@ impl<P: KafkaProducer> Clone for KafkaSinkBase<P> {}}-/// Map a lane address to the sink's configured [`Destination`]. The sink owns-/// this mapping only until the outputs layer exists to own the address →-/// output table. Every `(pipeline, lane)` pair is spelled out so that a new-/// lane, or a change making an unbacked pair reachable, has to visit this-/// match instead of being absorbed by a wildcard. `None` marks a pair-/// [`pipeline::resolve`] never produces — no output backs it, and the caller-/// dlqs the event (the typed-per-pipeline-lanes step makes these pairs-/// unrepresentable).+/// Map a lane address to the sink's configured [`Destination`]. Every+/// `(pipeline, lane)` pair is spelled out so that a new lane, or a change+/// making an unbacked pair reachable, has to visit this match instead of+/// being absorbed by a wildcard. `None` marks a pair [`pipeline::resolve`]+/// never produces — no output backs it, and the caller dlqs the event.fn lane_output(pipeline: Pipeline, lane: Lane) -> Option<Destination> {match (pipeline, lane) {(Pipeline::Analytics, Lane::Main) => Some(Destination::AnalyticsMain),@@ -550,12 +546,25 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {})}- /// Prep + enqueue for the single-event path. Retained as a thin wrapper so- /// the `Event::send` impl stays unchanged; the batch path runs the same- /// pieces through `prepare_batch` and `Sink::publish`.+ /// Prep + enqueue for the one-event fast path, returning the raw ack+ /// future so a single send can await it inline.+ ///+ /// Records the same two phase histograms as the batch path, on the error+ /// exits as well, so a publish of one event stays in the same population+ /// as a publish of many. Without this, the cheapest publishes leave the+ /// distribution and the in-process quantiles step up on their own.fn kafka_send(&self, event: ProcessedEvent) -> Result<P::AckFuture, CaptureError> {- let payload = self.prepare_record(event)?;- self.enqueue_record(payload)+ let prep_start = Instant::now();+ let payload = self.prepare_record(event);+ histogram!("capture_kafka_batch_prep_duration_seconds")+ .record(prep_start.elapsed().as_secs_f64());++ let enqueue_start = Instant::now();+ let ack_future = self.enqueue_record(payload?);+ histogram!("capture_kafka_batch_enqueue_duration_seconds")+ .record(enqueue_start.elapsed().as_secs_f64());++ ack_future}}@@ -728,41 +737,19 @@ impl<P: KafkaProducer + 'static> Sink for KafkaSinkBase<P> {#[async_trait]impl<P: KafkaProducer + 'static> PublishEvents for KafkaSinkBase<P> {#[instrument(skip_all)]- async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.kafka_send(event)?- .instrument(info_span!("ack_wait_one"))- .await- }+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ // Skip `prepare_batch`, a `JoinSet` of one, and a fold over one+ // result on the endpoints that publish a single event per request.+ if events.len() == 1 {+ let event = events.into_iter().next().expect("length checked above");+ return self+ .kafka_send(event)?+ .instrument(info_span!("ack_wait_one"))+ .await;+ }- #[instrument(skip_all)]- async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {let payloads = self.prepare_batch(events).await?;- fold_results(self.publish(payloads).await)- }-- fn flush(&self) -> Result<(), anyhow::Error> {- Sink::flush(self)- }-}--#[async_trait]-impl<P: KafkaProducer + 'static> Event for KafkaSinkBase<P> {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- let ack_future = self.kafka_send(event)?;- histogram!("capture_event_batch_size").record(1.0);- ack_future.instrument(info_span!("ack_wait_one")).await- }-- /// The v0 bridge onto the mechanism seam: prep, publish, fold. The- /// per-event results collapse to the whole-request `CaptureError` the- /// `Event` callers expect.- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {- // Record the batch-size histogram up front so the distribution is a- // faithful view of batches submitted, not only those that succeeded.- // Matches the single-event `send` path which records before any await.- histogram!("capture_event_batch_size").record(events.len() as f64);-- PublishEvents::publish_batch(self, events).await+ fold_results(Sink::publish(self, payloads).await)}fn flush(&self) -> Result<(), anyhow::Error> {@@ -803,8 +790,8 @@ pub(crate) use crate::sinks::registry::test_topics;mod tests {use crate::api::CaptureError;use crate::config::{self, EnvelopeCompression};+ use crate::outputs::PublishEvents;use crate::sinks::kafka::KafkaSink;- use crate::sinks::Event;use crate::utils::uuid_v7_from_datetime;use crate::v0_request::{DataType, OverflowReason, ProcessedEvent, ProcessedEventMetadata};use common_types::CapturedEvent;@@ -946,16 +933,16 @@ mod tests {// Wait for producer to be healthy, to keep kafka_message_timeout_ms short and tests fasterfor _ in 0..20 {- if sink.send(event.clone()).await.is_ok() {+ if sink.publish_events(vec![event.clone()]).await.is_ok() {break;}}// Send events to confirm happy path- sink.send(event.clone())+ sink.publish_events(vec![event.clone()]).await.expect("failed to send one initial event");- sink.send_batch(vec![event.clone(), event.clone()])+ sink.publish_events(vec![event.clone(), event.clone()]).await.expect("failed to send initial event batch");@@ -986,7 +973,7 @@ mod tests {metadata: metadata.clone(),};- sink.send(big_event)+ sink.publish_events(vec![big_event]).await.expect("failed to send event larger than default max size");@@ -1016,7 +1003,7 @@ mod tests {metadata: metadata.clone(),};- match sink.send(big_event).await {+ match sink.publish_events(vec![big_event]).await {Err(CaptureError::EventTooBig(_)) => {} // ExpectedErr(err) => panic!("wrong error code {err}"),Ok(()) => panic!("should have errored"),@@ -1026,7 +1013,7 @@ mod tests {cluster.clear_request_errors(RDKafkaApiKey::Produce);let err = [RDKafkaRespErr::RD_KAFKA_RESP_ERR_MSG_SIZE_TOO_LARGE; 1];cluster.request_errors(RDKafkaApiKey::Produce, &err);- match sink.send(event.clone()).await {+ match sink.publish_events(vec![event.clone()]).await {Err(CaptureError::EventTooBig(_)) => {} // ExpectedErr(err) => panic!("wrong error code {err}"),Ok(()) => panic!("should have errored"),@@ -1034,7 +1021,10 @@ mod tests {cluster.clear_request_errors(RDKafkaApiKey::Produce);let err = [RDKafkaRespErr::RD_KAFKA_RESP_ERR_INVALID_PARTITIONS; 1];cluster.request_errors(RDKafkaApiKey::Produce, &err);- match sink.send_batch(vec![event.clone(), event.clone()]).await {+ match sink+ .publish_events(vec![event.clone(), event.clone()])+ .await+ {Err(CaptureError::RetryableSinkError) => {} // ExpectedErr(err) => panic!("wrong error code {err}"),Ok(()) => panic!("should have errored"),@@ -1044,13 +1034,13 @@ mod tests {cluster.clear_request_errors(RDKafkaApiKey::Produce);let err = [RDKafkaRespErr::RD_KAFKA_RESP_ERR_BROKER_NOT_AVAILABLE; 2];cluster.request_errors(RDKafkaApiKey::Produce, &err);- sink.send(event.clone())+ sink.publish_events(vec![event.clone()]).await.expect("failed to send one event after recovery");cluster.clear_request_errors(RDKafkaApiKey::Produce);let err = [RDKafkaRespErr::RD_KAFKA_RESP_ERR_BROKER_NOT_AVAILABLE; 2];cluster.request_errors(RDKafkaApiKey::Produce, &err);- sink.send_batch(vec![event.clone(), event.clone()])+ sink.publish_events(vec![event.clone(), event.clone()]).await.expect("failed to send event batch after recovery");@@ -1058,12 +1048,15 @@ mod tests {cluster.clear_request_errors(RDKafkaApiKey::Produce);let err = [RDKafkaRespErr::RD_KAFKA_RESP_ERR_BROKER_NOT_AVAILABLE; 50];cluster.request_errors(RDKafkaApiKey::Produce, &err);- match sink.send(event.clone()).await {+ match sink.publish_events(vec![event.clone()]).await {Err(CaptureError::RetryableSinkError) => {} // ExpectedErr(err) => panic!("wrong error code {err}"),Ok(()) => panic!("should have errored"),};- match sink.send_batch(vec![event.clone(), event.clone()]).await {+ match sink+ .publish_events(vec![event.clone(), event.clone()])+ .await+ {Err(CaptureError::RetryableSinkError) => {} // ExpectedErr(err) => panic!("wrong error code {err}"),Ok(()) => panic!("should have errored"),@@ -1326,7 +1319,7 @@ mod tests {);let event = create_test_event(&input);- sink.send(event).await.unwrap();+ sink.publish_events(vec![event]).await.unwrap();let records = producer.get_records();assert_eq!(records.len(), 1, "Expected exactly one record");@@ -2413,7 +2406,7 @@ mod tests {..Default::default()});event.metadata.overflow_reason = Some(OverflowReason::ForceLimited);- sink.send(event).await.unwrap();+ sink.publish_events(vec![event]).await.unwrap();let records = producer.get_records();assert_eq!(records.len(), 1);@@ -2508,8 +2501,8 @@ mod tests {let mut exception_event = base;exception_event.metadata.data_type = DataType::ExceptionErrorTracking;- sink.send(ai_event).await.unwrap();- sink.send(exception_event).await.unwrap();+ sink.publish_events(vec![ai_event]).await.unwrap();+ sink.publish_events(vec![exception_event]).await.unwrap();let records = producer.get_records();assert_eq!(records.len(), 2);@@ -2854,14 +2847,14 @@ mod tests {.await;}- // ==================== send_batch ordering + error tests ====================- // These exercise the B2 three-phase send_batch: parallel prepare_record,+ // ==================== publish_events ordering + error tests ====================+ // These exercise the three-phase batch path: parallel prepare_record,// serial enqueue_record, concurrent ack drain. The ordering test runs on// a multi-thread runtime so phase 1 actually parallelizes across workers// and we can detect if phase 2 is accidentally reordering records.#[tokio::test(flavor = "multi_thread", worker_threads = 4)]- async fn send_batch_preserves_order_same_key() {+ async fn publish_events_preserves_order_same_key() {let producer = MockKafkaProducer::new();let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());@@ -2885,7 +2878,9 @@ mod tests {let input_uuids: Vec<String> =events.iter().map(|e| e.event.uuid.to_string()).collect();- sink.send_batch(events).await.expect("send_batch failed");+ sink.publish_events(events)+ .await+ .expect("publish_events failed");let records = producer.get_records();assert_eq!(records.len(), 20, "expected 20 records");@@ -2908,7 +2903,7 @@ mod tests {assert_eq!(output_uuids, input_uuids,- "send_batch must preserve input order for same-key events"+ "publish_events must preserve input order for same-key events");// Sanity: all records share the same partition key.@@ -2923,7 +2918,7 @@ mod tests {}#[tokio::test(flavor = "multi_thread", worker_threads = 4)]- async fn send_batch_prep_error_aborts_batch() {+ async fn publish_events_prep_error_aborts_batch() {let producer = MockKafkaProducer::new();let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());@@ -2961,11 +2956,11 @@ mod tests {bad.metadata.session_id = None;events[2] = bad;- let res = sink.send_batch(events).await;+ let res = sink.publish_events(events).await;match res {Err(CaptureError::MissingSessionId) => {}Err(other) => panic!("expected MissingSessionId, got {other:?}"),- Ok(()) => panic!("expected send_batch to fail on prep error"),+ Ok(()) => panic!("expected publish_events to fail on prep error"),}let records = producer.get_records();@@ -2976,7 +2971,7 @@ mod tests {);}- // ==================== send_batch fast-path + mid-batch failure tests ====================+ // ==================== publish_events fast-path + mid-batch failure tests ====================/// Builds N AnalyticsMain events with sequential distinct_ids so each/// record is individually identifiable in the mock producer's output.@@ -2991,9 +2986,9 @@ mod tests {}#[tokio::test(flavor = "multi_thread", worker_threads = 4)]- async fn send_batch_mid_enqueue_failure_preserves_earlier_records() {+ async fn publish_events_mid_enqueue_failure_preserves_earlier_records() {// Fail at phase-2 send #3 (0-indexed): events [0, 1, 2] should land- // in the mock, send_batch must return Err, and no event at index+ // in the mock, publish_events must return Err, and no event at index// >= 3 should ever hit the producer. Batch size is well above the// scatter-gather threshold so phase 2 runs post-parallel-prep.const BATCH: usize = 10;@@ -3005,11 +3000,11 @@ mod tests {let input_distinct_ids: Vec<String> =events.iter().map(|e| e.event.distinct_id.clone()).collect();- let res = sink.send_batch(events).await;+ let res = sink.publish_events(events).await;match res {Err(CaptureError::RetryableSinkError) => {}Err(other) => panic!("expected RetryableSinkError, got {other:?}"),- Ok(()) => panic!("expected send_batch to fail on enqueue #{FAIL_IDX}"),+ Ok(()) => panic!("expected publish_events to fail on enqueue #{FAIL_IDX}"),}let records = producer.get_records();@@ -3041,22 +3036,90 @@ mod tests {}#[tokio::test]- async fn send_batch_single_event_via_batch_path() {- // batch_size=1 exercises the serial fast path (1 < SCATTER_GATHER_MIN_BATCH)- // and verifies the loop handles a single-element batch correctly.+ async fn publish_events_single_event_skips_the_batch_path() {+ // One event short-circuits to kafka_send: no prepare_batch, no+ // JoinSet. This is the live path for the single-event endpoints.let producer = MockKafkaProducer::new();let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());let events = build_batch(1);- sink.send_batch(events).await.expect("send_batch failed");+ sink.publish_events(events)+ .await+ .expect("publish_events failed");let records = producer.get_records();assert_eq!(records.len(), 1, "expected exactly one record");assert_eq!(records[0].topic, MAIN_TOPIC);}+ #[tokio::test]+ async fn publish_events_two_events_take_the_batch_path() {+ // Two events is the smallest batch that still reaches+ // prepare_batch. A one-event guard that grew an off-by-one would+ // swallow the second event here and nowhere else.+ let producer = MockKafkaProducer::new();+ let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());++ sink.publish_events(build_batch(2))+ .await+ .expect("publish_events failed");++ let records = producer.get_records();+ assert_eq!(records.len(), 2, "both events must reach the producer");+ }++ /// Runs `f` under a local metrics recorder and counts the samples that+ /// landed on `name`. The recorder is thread-scoped, so `f` has to drive+ /// its own futures on this thread.+ fn histogram_sample_count(name: &str, f: impl FnOnce()) -> usize {+ use metrics_util::debugging::{DebugValue, DebuggingRecorder};++ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let _guard = metrics::set_default_local_recorder(&recorder);+ f();++ snapshotter+ .snapshot()+ .into_vec()+ .into_iter()+ .filter_map(|(key, _, _, value)| match value {+ DebugValue::Histogram(samples) if key.key().name() == name => {+ Some(samples.len())+ }+ _ => None,+ })+ .sum()+ }++ #[test]+ fn publish_events_one_event_feeds_the_phase_histograms() {+ // The one-event path skips prepare_batch and Sink::publish, which+ // own these two histograms, so it has to record them itself.+ // Otherwise every single-event endpoint drops out of the+ // distribution and the in-process quantiles step up unprompted.+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .expect("runtime");++ for name in [+ "capture_kafka_batch_prep_duration_seconds",+ "capture_kafka_batch_enqueue_duration_seconds",+ ] {+ let samples = histogram_sample_count(name, || {+ let producer = MockKafkaProducer::new();+ let sink = KafkaSinkBase::with_producer(producer, test_topics());+ runtime+ .block_on(sink.publish_events(build_batch(1)))+ .expect("publish_events failed");+ });+ assert_eq!(samples, 1, "{name} must see the one-event publish");+ }+ }+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]- async fn send_batch_just_below_threshold_uses_serial_path() {+ async fn publish_events_just_below_threshold_uses_serial_path() {// batch_size = SCATTER_GATHER_MIN_BATCH - 1 takes the serial fast// path. We can't observe "which path ran" directly, so we assert// behavioral equivalence: N records, correct topic, input order.@@ -3068,7 +3131,9 @@ mod tests {let input_distinct_ids: Vec<String> =events.iter().map(|e| e.event.distinct_id.clone()).collect();- sink.send_batch(events).await.expect("send_batch failed");+ sink.publish_events(events)+ .await+ .expect("publish_events failed");let records = producer.get_records();assert_eq!(records.len(), size);@@ -3087,7 +3152,7 @@ mod tests {}#[tokio::test(flavor = "multi_thread", worker_threads = 4)]- async fn send_batch_at_threshold_uses_scatter_gather_path() {+ async fn publish_events_at_threshold_uses_scatter_gather_path() {// batch_size = SCATTER_GATHER_MIN_BATCH takes the scatter-gather// path. Behavioral equivalence with the serial path must hold:// same N records, same order, same topics.@@ -3099,7 +3164,9 @@ mod tests {let input_distinct_ids: Vec<String> =events.iter().map(|e| e.event.distinct_id.clone()).collect();- sink.send_batch(events).await.expect("send_batch failed");+ sink.publish_events(events)+ .await+ .expect("publish_events failed");let records = producer.get_records();assert_eq!(records.len(), size);@@ -3120,7 +3187,7 @@ mod tests {// ==================== Sink mechanism seam ====================// The per-event result surface `Sink::publish` reports: uuid-aligned// with the input payloads, batch-uniform on failure. `fold_results`- // discards this shape, so the send_batch tests above cannot see it —+ // discards this shape, so the publish_events tests above cannot see it —// and the outputs layer builds on it.#[tokio::test]@@ -3240,7 +3307,9 @@ mod tests {events.push(create_test_event(&EventInput::default()));}- sink.send_batch(events).await.expect("send_batch failed");+ sink.publish_events(events)+ .await+ .expect("publish_events failed");let records = producer.get_records();assert_eq!(records.len(), pad_to.max(5));@@ -3264,13 +3333,13 @@ mod tests {}#[tokio::test]- async fn send_batch_mixed_datatypes_serial_path() {+ async fn publish_events_mixed_datatypes_serial_path() {// 5 events < SCATTER_GATHER_MIN_BATCH => serial fast path.mixed_datatypes_routing_for_batch(5).await;}#[tokio::test(flavor = "multi_thread", worker_threads = 4)]- async fn send_batch_mixed_datatypes_scatter_gather_path() {+ async fn publish_events_mixed_datatypes_scatter_gather_path() {// 10 events >= SCATTER_GATHER_MIN_BATCH => scatter-gather path.mixed_datatypes_routing_for_batch(10).await;}diff --git a/rust/capture/src/sinks/mod.rs b/rust/capture/src/sinks/mod.rsindex d39284d78e48..d41b3c9b7569 100644--- a/rust/capture/src/sinks/mod.rs+++ b/rust/capture/src/sinks/mod.rs@@ -1,7 +1,3 @@-use async_trait::async_trait;--use crate::{api::CaptureError, v0_request::ProcessedEvent};-pub mod kafka;pub mod noop;pub mod print;@@ -11,28 +7,3 @@ pub mod s3;pub mod sink;#[cfg(test)]pub(crate) mod test_sink;-#[async_trait]-pub trait Event {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError>;- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError>;-- /// Flush any buffered/pending data before shutdown. Default is no-op.- fn flush(&self) -> Result<(), anyhow::Error> {- Ok(())- }-}--#[async_trait]-impl<T: Event + ?Sized + Send + Sync> Event for Box<T> {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- (**self).send(event).await- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {- (**self).send_batch(events).await- }-- fn flush(&self) -> Result<(), anyhow::Error> {- (**self).flush()- }-}diff --git a/rust/capture/src/sinks/noop.rs b/rust/capture/src/sinks/noop.rsindex 085021d91566..cdb94aa45272 100644--- a/rust/capture/src/sinks/noop.rs+++ b/rust/capture/src/sinks/noop.rs@@ -16,12 +16,7 @@ impl NoOpSink {#[async_trait]impl PublishEvents for NoOpSink {- async fn publish_one(&self, _event: ProcessedEvent) -> Result<(), CaptureError> {- counter!("capture_events_ingested_total").increment(1);- Ok(())- }-- async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {counter!("capture_events_ingested_total").increment(events.len() as u64);Ok(())}diff --git a/rust/capture/src/sinks/print.rs b/rust/capture/src/sinks/print.rsindex c11925c349eb..f7ea8a9001c4 100644--- a/rust/capture/src/sinks/print.rs+++ b/rust/capture/src/sinks/print.rs@@ -11,14 +11,7 @@ pub struct PrintSink {}#[async_trait]impl PublishEvents for PrintSink {- async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- info!("single event: {:?}", event);- counter!("capture_events_ingested_total").increment(1);-- Ok(())- }-- async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {let span = tracing::span!(tracing::Level::INFO, "batch of events");let _enter = span.enter();diff --git a/rust/capture/src/sinks/s3.rs b/rust/capture/src/sinks/s3.rsindex 955a31d34d64..005225a2b889 100644--- a/rust/capture/src/sinks/s3.rs+++ b/rust/capture/src/sinks/s3.rs@@ -276,18 +276,7 @@ impl Inner {#[async_trait]impl PublishEvents for S3Sink {#[instrument(skip_all)]- async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- let mut buffer = self.inner.buffer.lock().await;- buffer.add_event(event)?;- let mut rx = buffer.tx.subscribe();- drop(buffer);- rx.recv()- .await- .map_err(|_| CaptureError::NonRetryableSinkError)?- }-- #[instrument(skip_all)]- async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {let mut buffer = self.inner.buffer.lock().await;for event in events {buffer.add_event(event)?;@@ -376,13 +365,13 @@ mod tests {// Test single eventlet event = create_test_event();- sink.publish_one(event.clone())+ sink.publish_events(vec![event.clone()]).await.expect("Failed to publish event");// Test batchlet batch = vec![event.clone(), event.clone()];- sink.publish_batch(batch)+ sink.publish_events(batch).await.expect("Failed to publish batch");}@@ -401,7 +390,7 @@ mod tests {metadata: create_test_event().metadata,};- sink.publish_one(event)+ sink.publish_events(vec![event]).await.expect("Failed to publish large event");}diff --git a/rust/capture/src/sinks/test_sink.rs b/rust/capture/src/sinks/test_sink.rsindex 2c2c2e860c90..f1c764c392d3 100644--- a/rust/capture/src/sinks/test_sink.rs+++ b/rust/capture/src/sinks/test_sink.rs@@ -1,17 +1,8 @@//! Shared `MockSink` test helper for pipeline-level tests across the capture-//! crate. Captures every `ProcessedEvent` sent through `send` / `send_batch`-//! in an `Arc<Mutex<Vec<_>>>` so tests can assert on the exact stamped-//! metadata the pipeline produced.-//!-//! Supports both construction patterns used across existing tests:-//! - `Arc::new(MockSink::new())` + `sink.get_events()` (analytics tests)-//! - `Arc::new(MockSink { events: events_captured.clone() })` + manual-//! `events_captured.lock()` (recordings tests that share the handle with-//! the sink before wrapping in `Arc<dyn Event>`)+//! crate.use crate::api::CaptureError;use crate::outputs::PublishEvents;-use crate::sinks::Event;use crate::v0_request::ProcessedEvent;use async_trait::async_trait;use std::sync::{Arc, Mutex};@@ -31,27 +22,9 @@ impl MockSink {}}-#[async_trait]-impl Event for MockSink {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.events.lock().unwrap().push(event);- Ok(())- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {- self.events.lock().unwrap().extend(events);- Ok(())- }-}-#[async_trait]impl PublishEvents for MockSink {- async fn publish_one(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.events.lock().unwrap().push(event);- Ok(())- }-- async fn publish_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {self.events.lock().unwrap().extend(events);Ok(())}diff --git a/rust/capture/src/v0_endpoint.rs b/rust/capture/src/v0_endpoint.rsindex d01ab903f1a0..e8f3014454ba 100644--- a/rust/capture/src/v0_endpoint.rs+++ b/rust/capture/src/v0_endpoint.rs@@ -74,7 +74,7 @@ pub async fn event(Ok((context, events)) => {let event_count = events.len() as u64;if let Err(err) = process_events(- state.sink.clone(),+ state.outputs.clone(),state.token_dropper.clone(),state.event_restriction_service.clone(),state.historical_cfg,@@ -156,7 +156,7 @@ pub async fn recording(Ok((context, events)) => {let count = events.len() as u64;if let Err(err) = process_replay_events(- state.sink.clone(),+ state.outputs.clone(),state.event_restriction_service.clone(),state.replay_overflow_limiter.clone(),state.ingestion_warning_emitter.clone(),diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex 05e43d89e592..4b1f98f73649 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -675,10 +675,8 @@ use limiters::token_dropper::TokenDropper;use crate::config::CaptureMode;use crate::event_restrictions::EventRestrictionService;use crate::global_rate_limiter::GlobalRateLimiter;-use crate::outputs::{Output, OutputRegistry};use crate::quota_limiters::CaptureQuotaLimiter;use crate::router::{self, HistoricalConfig};-use crate::sinks;use crate::time::TimeSource;use crate::v1::sinks::kafka::mock::MockProducer;use crate::v1::sinks::kafka::sink::KafkaSink;@@ -915,15 +913,15 @@ impl TestStateBuilder {[(SinkName::Msk, boxed_sink)].into_iter().collect();let v1_router = v1_sinks::Router::new(SinkName::Msk, sinks_map);- // Legacy sink — no-op since V1 tests go through v1_sink_router- let legacy_sink: Arc<dyn sinks::Event + Send + Sync> = Arc::new(OutputRegistry::new(- Output::single(crate::sinks::noop::NoOpSink::new()),+ // 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 timesource: Arc<dyn TimeSource + Send + Sync> = Arc::new(crate::time::SystemTime {});let state = router::State {- sink: legacy_sink,+ outputs: legacy_outputs,timesource,redis,global_rate_limiter_token_distinctid: self.global_rate_limiter,diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rsindex 8f29b604d8e5..6a7a90d3c3af 100644--- a/rust/capture/tests/common/integration_utils.rs+++ b/rust/capture/tests/common/integration_utils.rs@@ -8,9 +8,9 @@ use std::time::Duration;use capture::{api::{CaptureError, CaptureResponse, CaptureResponseCode},config::CaptureMode,+ outputs::{OutputRegistry, PublishEvents},quota_limiters::CaptureQuotaLimiter,router::router,- sinks::Event,time::TimeSource,v0_request::{DataType, ProcessedEvent},};@@ -1031,13 +1031,8 @@ impl MemorySink {}#[async_trait]-impl Event for MemorySink {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.events.lock().unwrap().push(event);- Ok(())- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl PublishEvents for MemorySink {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {self.events.lock().unwrap().extend_from_slice(&events);Ok(())}@@ -1095,7 +1090,7 @@ fn build_router_for_mode_at(mode: CaptureMode, fixed_time: &str) -> (Router, Memtimesource,readiness,liveness,- Arc::new(sink.clone()),+ Arc::new(OutputRegistry::single(sink.clone())),redis,None, // global_rate_limiter_token_distinctidquota_limiter,diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rsindex a4ec1438792f..6a5727d9f08c 100644--- a/rust/capture/tests/integration_ai_endpoint.rs+++ b/rust/capture/tests/integration_ai_endpoint.rs@@ -8,9 +8,9 @@ use axum_test_helper::TestClient;use capture::api::CaptureError;use capture::config::CaptureMode;use capture::global_rate_limiter::GlobalRateLimiter;+use capture::outputs::{OutputRegistry, PublishEvents};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;-use capture::sinks::Event;use capture::time::TimeSource;use capture::v0_request::{OverflowReason, ProcessedEvent};use chrono::{DateTime, TimeZone, Utc};@@ -44,12 +44,8 @@ impl TimeSource for FixedTime {struct TestSink;#[async_trait]-impl Event for TestSink {- async fn send(&self, _event: ProcessedEvent) -> Result<(), CaptureError> {- Ok(())- }-- async fn send_batch(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl PublishEvents for TestSink {+ async fn publish_events(&self, _events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {Ok(())}}@@ -73,13 +69,8 @@ impl CapturingSink {}#[async_trait]-impl Event for CapturingSink {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.events.lock().await.push(event);- Ok(())- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl PublishEvents for CapturingSink {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {self.events.lock().await.extend(events);Ok(())}@@ -162,7 +153,7 @@ fn setup_ai_test_router() -> Router {timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None,quota_limiter,@@ -219,7 +210,7 @@ fn setup_ai_router_collecting_warnings() -> (Router, Arc<CollectingEmitter>) {timesource,readiness,liveness,- Arc::new(TestSink),+ Arc::new(OutputRegistry::single(TestSink)),redis,None,quota_limiter,@@ -1289,7 +1280,7 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None,quota_limiter,@@ -1959,7 +1950,7 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (Routtimesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None,quota_limiter,@@ -2026,7 +2017,7 @@ fn setup_ai_test_router_with_byte_limiter() -> (Router, CapturingSink) {timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None,quota_limiter,@@ -2289,7 +2280,7 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, Capturintimesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None,quota_limiter,@@ -2448,7 +2439,7 @@ fn setup_ai_test_router_with_overflow_limiter(timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None,quota_limiter,@@ -2590,7 +2581,7 @@ fn ai_router(timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None,quota_limiter,diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rsindex d6b8c3a047b0..30f7b8e4a8bb 100644--- a/rust/capture/tests/integration_ai_restrictions.rs+++ b/rust/capture/tests/integration_ai_restrictions.rs@@ -11,9 +11,9 @@ use capture::event_restrictions::{EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,RestrictionType,};+use capture::outputs::{OutputRegistry, PublishEvents};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;-use capture::sinks::Event;use capture::time::TimeSource;use capture::v0_request::{DataType, OverflowReason, ProcessedEvent};use chrono::{DateTime, Utc};@@ -56,13 +56,8 @@ impl CapturingSink {}#[async_trait]-impl Event for CapturingSink {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.events.lock().await.push(event);- Ok(())- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl PublishEvents for CapturingSink {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {self.events.lock().await.extend(events);Ok(())}@@ -158,7 +153,7 @@ async fn setup_ai_router_with_restriction(timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None, // global_rate_limiter_token_distinctidquota_limiter,@@ -480,7 +475,7 @@ async fn setup_ai_router_with_redirect_to_topic(timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None, // global_rate_limiter_token_distinctidquota_limiter,@@ -560,7 +555,7 @@ async fn setup_ai_router_with_force_overflow_and_limiter(timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None,quota_limiter,diff --git a/rust/capture/tests/integration_analytics_ai_routing.rs b/rust/capture/tests/integration_analytics_ai_routing.rsindex e00d3646b302..7edc844a0244 100644--- a/rust/capture/tests/integration_analytics_ai_routing.rs+++ b/rust/capture/tests/integration_analytics_ai_routing.rs@@ -14,9 +14,9 @@ use axum::Router;use axum_test_helper::TestClient;use capture::api::CaptureError;use capture::config::CaptureMode;+use capture::outputs::{OutputRegistry, PublishEvents};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;-use capture::sinks::Event;use capture::time::TimeSource;use capture::v0_request::{DataType, OverflowReason, ProcessedEvent};use chrono::{DateTime, Utc};@@ -61,13 +61,8 @@ impl CapturingSink {}#[async_trait]-impl Event for CapturingSink {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.events.lock().await.push(event);- Ok(())- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl PublishEvents for CapturingSink {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {self.events.lock().await.extend(events);Ok(())}@@ -113,7 +108,7 @@ fn setup_router_for_mode(timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None, // global_rate_limiter_token_distinctidquota_limiter,diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rsindex 722930ce849f..9d4f881e267e 100644--- a/rust/capture/tests/integration_analytics_restrictions.rs+++ b/rust/capture/tests/integration_analytics_restrictions.rs@@ -11,9 +11,9 @@ use capture::event_restrictions::{EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,RestrictionType,};+use capture::outputs::{OutputRegistry, PublishEvents};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;-use capture::sinks::Event;use capture::time::TimeSource;use capture::v0_request::{DataType, ProcessedEvent};use chrono::{DateTime, Utc};@@ -52,13 +52,8 @@ impl CapturingSink {}#[async_trait]-impl Event for CapturingSink {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.events.lock().await.push(event);- Ok(())- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl PublishEvents for CapturingSink {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {self.events.lock().await.extend(events);Ok(())}@@ -108,7 +103,7 @@ async fn setup_analytics_router_with_restriction(timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None, // global_rate_limiter_token_distinctidquota_limiter,@@ -535,7 +530,7 @@ async fn setup_analytics_router_with_redirect_to_topic(timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None, // global_rate_limiter_token_distinctidquota_limiter,diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rsindex 83be090fc346..d221647cc673 100644--- a/rust/capture/tests/integration_otel_endpoint.rs+++ b/rust/capture/tests/integration_otel_endpoint.rs@@ -10,9 +10,9 @@ use capture::event_restrictions::{RestrictionScope, RestrictionType,};use capture::global_rate_limiter::GlobalRateLimiter;+use capture::outputs::{OutputRegistry, PublishEvents};use capture::quota_limiters::{is_llm_event, CaptureQuotaLimiter, EventInfo};use capture::router::router;-use capture::sinks::Event;use capture::time::TimeSource;use capture::v0_request::{DataType, OverflowReason, ProcessedEvent};use chrono::{DateTime, Utc};@@ -69,13 +69,8 @@ impl CapturingSink {}#[async_trait]-impl Event for CapturingSink {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.events.lock().await.push(event);- Ok(())- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl PublishEvents for CapturingSink {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {self.events.lock().await.extend(events);Ok(())}@@ -177,7 +172,7 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOptiontimesource,readiness,liveness,- Arc::new(sink.clone()),+ Arc::new(OutputRegistry::single(sink.clone())),redis,None, // global_rate_limiter_token_distinctidquota_limiter,diff --git a/rust/capture/tests/integration_person_processing_matrix.rs b/rust/capture/tests/integration_person_processing_matrix.rsindex 837e69cbd4ed..0dade80b71c1 100644--- a/rust/capture/tests/integration_person_processing_matrix.rs+++ b/rust/capture/tests/integration_person_processing_matrix.rs@@ -41,6 +41,7 @@ use capture::event_restrictions::{RestrictionScope, RestrictionType,};use capture::global_rate_limiter::GlobalRateLimiter;+use capture::outputs::OutputRegistry;use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;use capture::sinks::kafka::KafkaSinkBase;@@ -238,7 +239,7 @@ async fn run_v0(inputs: Inputs, distinct_ids: &[&str]) -> Batch {},readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,Some(Arc::new(limiter)),quota_limiter,diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rsindex e013fdf73b4e..1d4963416fe7 100644--- a/rust/capture/tests/integration_replay_restrictions.rs+++ b/rust/capture/tests/integration_replay_restrictions.rs@@ -11,9 +11,9 @@ use capture::event_restrictions::{EventRestrictionService, Pipeline, Restriction, RestrictionManager, RestrictionScope,RestrictionType,};+use capture::outputs::{OutputRegistry, PublishEvents};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::router;-use capture::sinks::Event;use capture::time::TimeSource;use capture::v0_request::{DataType, ProcessedEvent};use chrono::{DateTime, Utc};@@ -53,13 +53,8 @@ impl CapturingSink {}#[async_trait]-impl Event for CapturingSink {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.events.lock().await.push(event);- Ok(())- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl PublishEvents for CapturingSink {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {self.events.lock().await.extend(events);Ok(())}@@ -105,7 +100,7 @@ async fn setup_recordings_router_with_restriction(timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None, // global_rate_limiter_token_distinctidquota_limiter,@@ -478,7 +473,7 @@ async fn setup_recordings_router_with_redirect_to_topic(timesource,readiness,liveness,- Arc::new(sink),+ Arc::new(OutputRegistry::single(sink)),redis,None, // global_rate_limiter_token_distinctidquota_limiter,diff --git a/rust/capture/tests/integration_wire_body_limits.rs b/rust/capture/tests/integration_wire_body_limits.rsindex 234b2771dd34..7f934a76eec8 100644--- a/rust/capture/tests/integration_wire_body_limits.rs+++ b/rust/capture/tests/integration_wire_body_limits.rs@@ -6,9 +6,9 @@ use axum::http::StatusCode;use axum_test_helper::TestClient;use capture::api::CaptureError;use capture::config::CaptureMode;+use capture::outputs::{OutputRegistry, PublishEvents};use capture::quota_limiters::CaptureQuotaLimiter;use capture::router::{router, BATCH_BODY_SIZE};-use capture::sinks::Event;use capture::time::TimeSource;use capture::v0_request::ProcessedEvent;use chrono::{DateTime, Utc};@@ -48,13 +48,8 @@ impl CapturingSink {}#[async_trait]-impl Event for CapturingSink {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.events.lock().await.push(event);- Ok(())- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl PublishEvents for CapturingSink {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {self.events.lock().await.extend(events);Ok(())}@@ -79,7 +74,7 @@ fn make_test_client(mode: CaptureMode) -> (TestClient, CapturingSink) {timesource,readiness,liveness,- Arc::new(sink.clone()),+ Arc::new(OutputRegistry::single(sink.clone())),redis.clone(),None,CaptureQuotaLimiter::new(&cfg, redis, Duration::from_secs(60)),diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rsindex 2a823ceec06d..01e3dfd45936 100644--- a/rust/capture/tests/quota_limiters.rs+++ b/rust/capture/tests/quota_limiters.rs@@ -16,11 +16,11 @@ use serde_json::Value;use capture::api::CaptureError;use capture::config::CaptureMode;+use capture::outputs::{OutputRegistry, PublishEvents};use capture::quota_limiters::{is_exception_event, is_llm_event, is_survey_event, CaptureQuotaLimiter, EventInfo,};use capture::router::router;-use capture::sinks::Event;use capture::time::TimeSource;use capture::v0_request::ProcessedEvent;use chrono::{DateTime, Utc};@@ -31,13 +31,8 @@ struct MemorySink {}#[async_trait]-impl Event for MemorySink {- async fn send(&self, event: ProcessedEvent) -> Result<(), CaptureError> {- self.events.lock().unwrap().push(event);- Ok(())- }-- async fn send_batch(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {+impl PublishEvents for MemorySink {+ async fn publish_events(&self, events: Vec<ProcessedEvent>) -> Result<(), CaptureError> {self.events.lock().unwrap().extend(events);Ok(())}@@ -127,7 +122,7 @@ async fn setup_router_with_limits(timesource,readiness,liveness,- Arc::new(sink.clone()),+ Arc::new(OutputRegistry::single(sink.clone())),redis,None,quota_limiter,@@ -1182,7 +1177,7 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {timesource,readiness,liveness,- Arc::new(sink.clone()),+ Arc::new(OutputRegistry::single(sink.clone())),redis,None,quota_limiter,@@ -1275,7 +1270,7 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {timesource,readiness,liveness,- Arc::new(sink.clone()),+ Arc::new(OutputRegistry::single(sink.clone())),redis,None,quota_limiter,@@ -1372,7 +1367,7 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {timesource,readiness,liveness,- Arc::new(sink.clone()),+ Arc::new(OutputRegistry::single(sink.clone())),redis,None,quota_limiter,@@ -1806,7 +1801,7 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {timesource,readiness,liveness,- Arc::new(sink.clone()),+ Arc::new(OutputRegistry::single(sink.clone())),redis,None,quota_limiter,