Skip to content

: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.

refactor(capture): typed per-pipeline lanes (#113851)

Paweł Ledwoń923a3cd50c15
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.md
index 7595e205620e..36fb64d2788e 100644
--- a/rust/capture/OUTPUTS_REFACTOR_PLAN.md
+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md
@@ -1,6 +1,6 @@
# Capture outputs refactor — implementation plan
-Working contract for implementation agents. Steps 1–12 have shipped. Each remaining step is one commit in its own PR.
+Working contract for implementation agents. Steps 1–13 have shipped. Each remaining step is one commit in its own PR.
This doc is deleted when it schedules nothing. Step 18 closes objective 1; objectives 2 and 3 are then scheduled in order. Before deletion, the parts still needed — the vocabulary rules, the ordering-vs-person-processing contract, the repartitioning note — move into module docs, and unscheduled work becomes issues.
@@ -33,7 +33,8 @@ Every step is a small commit, proven by the Step-1 goldens, and reverted by plai
```text
request handler → Pipeline {Analytics, Ai, Heatmaps, Warnings, ErrorTracking, Replay}
pipeline steps → stamp intent (restrictions, overflow, historical)
-lane decision → Address {(Pipeline, Lane {Main, Overflow, Historical}) | Dlq | Custom(topic)}
+lane decision → Address {Lane(PipelineLane) | Dlq | Custom(topic)}, each pipeline
+ typed with only its own lanes
+ ordering guarantee
prepared event → address, ordering + key, header values, JSON body; built once per event
outputs → Address → output = 1..n targets + selection policy
@@ -85,19 +86,13 @@ Steps 1–11 shipped the structure:
- **10** — each v0 `Destination` is an output with a topic and a producer, read from `CAPTURE_OUTPUT_<OUTPUT>_TOPIC` and `CAPTURE_OUTPUT_<OUTPUT>_PRODUCER` as in Node.js ingestion. `OutputTable` replaces `TopicTable`. `PreparedPayload` carries the `Destination`. Setup maps each target's producer name to its handle once and hands the Kafka sink the resolved table; at enqueue the sink publishes through the target's own producer. Custom redirects publish through `CAPTURE_OUTPUT_CUSTOM_PRODUCER`. The resolved table is the Kafka sink's address-to-target lookup for both routes until Step 14's registries replace it.
- **11** — outputs take prepared events: `OutputRegistry::publish_prepared(Vec<PreparedEvent>) -> Vec<SinkResult>`, one result per event, in input order. `PreparedEvent` carries an `Address` and a `Bytes` payload. Every sink implements `PublishPrepared` beside `PublishEvents`; the `Sink` bound makes both required. The Kafka sink maps the address to its `Destination` and publishes through that target's topic and producer, enqueueing serially in input order; an enqueue or ack failure fails only its event. The S3 sink writes each payload as one line. Failover moves only the events with a retriable primary failure to the fallback. Test sinks that serve only v0 endpoints mark the prepared route `unreachable!`. Deviation from the original step text: the address-to-topic lookup is the Step-10 resolved `OutputTable` held by the Kafka sink, not a separate per-producer sink type; Step 14's registries replace the lookup.
- **12** — v1 publishes through the outputs layer. `Destination::address` maps each v1 destination to an `Address`, `serialize_batch` builds the outputs layer's `PreparedEvent`s, and `process_batch` calls `state.outputs.publish_prepared` on the registry v0 uses. v0 and v1 are different HTTP endpoints, not different pipelines, so they share the `INGESTION` producer and its settings; per-pipeline tuning stays per deployment. v1's `Router`, `Sink`, `KafkaSink`, producer, per-sink config, `SinkName` and the `topic_ai` injection are deleted, and so is v1's produce timeout, which v0 never had. The capture mode alone decides which v1 endpoints a deployment serves, so `CAPTURE_V1_SINKS` and every `CAPTURE_V1_SINK_*` variable go. Accepted differences: the `capture_v1_kafka_*` metrics give way to the shared Kafka sink's; v1's per-error cause tags collapse into `CaptureError` kinds, so response details read `not_persisted`, `event_too_big` or `rejected`; `InvalidMessage` and `InvalidMessageSize`, which v1 classed as fatal, are now retriable, as in v0; the batch-wide `is_ready` reject and the per-sink lifecycle handles are gone, and producer liveness is the `INGESTION` slot's; v1 traffic takes the deployment's output policy, including S3 failover where it is on. It supersedes Step 19.
+- **13** — lanes are typed per pipeline: `Address::Lane(PipelineLane)`, where `PipelineLane` is `Analytics(AnalyticsLane)`, `Ai(AiLane)`, `Heatmaps`/`Warnings`/`ErrorTracking(BasicLane)` or `Replay(SessionReplayLane)`, and the standalone `Pipeline` enum folds into it. There is no `AiLane::Historical`. The lane → output map is total, so v0 prep loses its dlq fallback for an unbacked pair and the prepared route loses its `NonRetryableSinkError` for one. Goldens unmodified; `resolve` tests retyped with the same assertions.
Today the registry holds one deployment-wide `Output`: a Kafka sink, or Kafka→S3 failover. v0 publishes events through it and v1 publishes prepared events through it.
## Objective 1 — manual fallback for all capture traffic
-Steps 13–14 make the set of reachable outputs a type. Steps 15–16 are the checks that type allows. Step 17 is the fallback. Step 18 deletes the S3 fallback it replaces.
-
-### Step 13 · Typed per-pipeline lanes
-
-- **Goal.** Replace the flat `Lane` with `AnalyticsLane`, `AiLane`, `SessionReplayLane`, `BasicLane`, so invalid `(pipeline, lane)` pairs cannot be built. There is no `AiLane::Historical`: the AI divert wins over historical, as in v1. Both stacks hand this address type to the outputs layer.
-- **Why.** Step 14's registry rows need one field per lane that exists. With a flat `Lane`, the registry needs a runtime error for pairs routing never produces.
-- **Parity proof.** Goldens unmodified; `resolve` precedence tests retyped with the same assertions.
-- **Size.** M/L.
+Step 14 makes the set of reachable outputs a type. Steps 15–16 are the checks that type allows. Step 17 is the fallback. Step 18 deletes the S3 fallback it replaces.
### Step 14 · Per-mode output registries
@@ -265,7 +260,7 @@ One step = one commit, subject from the tracker. No `--no-verify`.
| 10 · An output owns its topics and names its producer | done | `feat(capture): each output reads its own topic and producer` |
| 11 · Outputs accept prepared events | done | `feat(capture): outputs publish prepared events with per-event results` |
| 12 · v1 publishes through the outputs layer | done | `refactor(capture): v1 publishes through outputs; v1 sink stack deleted` |
-| 13 · Typed per-pipeline lanes | pending | `refactor(capture): typed per-pipeline lanes` |
+| 13 · Typed per-pipeline lanes | done | `refactor(capture): typed per-pipeline lanes` |
| 14 · Per-mode output registries | pending | `feat(capture): per-mode output registries with required rows` |
| 15 · A reachable output must be configured | pending | `feat(capture): require configuration for every reachable output` |
| 16 · Verify topics against the producer's broker | pending | `feat(capture): verify each output's topics against its producer's broker at boot` |
diff --git a/rust/capture/src/outputs.rs b/rust/capture/src/outputs.rs
index 5b337ec18f68..f6c8a99ce6fd 100644
--- a/rust/capture/src/outputs.rs
+++ b/rust/capture/src/outputs.rs
@@ -1,7 +1,7 @@
//! The outputs layer: the produce surface above the sinks.
//!
//! An [`Output`] is a published-to destination: either a single backend
-//! sink, or a policy composing two child outputs. Today the one policy is
+//! sink, or a policy composing two child outputs. The one policy is
//! failover (health-gated Kafka primary with an S3 secondary).
//!
//! Outputs take two routes. The v0 event route ([`PublishEvents`]) hands over
@@ -198,9 +198,8 @@ impl Failover {
}
}
-/// The (pipeline, lane) → output map the deployment state holds. One
-/// deployment-wide output serves every address; the Kafka sink resolves
-/// per-lane topics through its [`OutputTable`] at enqueue.
+/// The deployment's output. One output serves every address; the Kafka sink
+/// resolves per-lane topics through its [`OutputTable`] at enqueue.
///
/// [`OutputTable`]: crate::sinks::registry::OutputTable
pub struct OutputRegistry {
@@ -232,7 +231,7 @@ impl OutputRegistry {
#[cfg(test)]
mod tests {
use super::*;
- use crate::pipeline::{Lane, Pipeline};
+ use crate::pipeline::{AnalyticsLane, PipelineLane};
use crate::sinks::test_sink::MockSink;
use crate::utils::uuid_v7_from_datetime;
use crate::v0_request::{DataType, ProcessedEventMetadata};
@@ -307,10 +306,7 @@ mod tests {
let event = test_event().event;
PreparedEvent {
uuid: Uuid::now_v7(),
- address: Address::Lane {
- pipeline: Pipeline::Analytics,
- lane: Lane::Main,
- },
+ address: Address::Lane(PipelineLane::Analytics(AnalyticsLane::Main)),
partition_key: event.key(),
ordering: OrderingGuarantee::PerDistinctId,
payload: bytes::Bytes::from_static(b"{}"),
diff --git a/rust/capture/src/pipeline.rs b/rust/capture/src/pipeline.rs
index d0f4bc93f5eb..8dd7989eab92 100644
--- a/rust/capture/src/pipeline.rs
+++ b/rust/capture/src/pipeline.rs
@@ -7,47 +7,54 @@
//! the customer-facing [`OrderingGuarantee`] the sink realizes as a partition
//! key. The decision is pure — no counters, no headers, no I/O; side effects
//! are implied by the address and applied by the layer that realizes it.
-//!
-//! The sink still invokes `resolve` from its prep path and bridges the
-//! decision to its configured topics; the invocation site moves up when the
-//! outputs layer exists to own it (see the plan doc).
use crate::api::CaptureError;
use crate::ordering::{person_ordering, OrderingGuarantee};
use crate::v0_request::{DataType, OverflowReason, ProcessedEventMetadata};
-/// The high-level "which product stream is this" classification, decided at
-/// the edge (endpoint + event name) and stamped as the pipeline half of
-/// [`DataType`]. AI membership is stamp-based, not name-based: an undiverted
-/// `$ai_*` event is a plain analytics event.
+/// Pipeline from [`DataType`], lane from [`resolve`]. Each pipeline names only
+/// the lanes it has, so an address no output backs cannot be built.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
-pub enum Pipeline {
- Analytics,
- Ai,
- Heatmaps,
- Warnings,
- ErrorTracking,
- Replay,
+pub enum PipelineLane {
+ Analytics(AnalyticsLane),
+ Ai(AiLane),
+ Heatmaps(BasicLane),
+ Warnings(BasicLane),
+ ErrorTracking(BasicLane),
+ Replay(SessionReplayLane),
}
-/// A lane of a pipeline. Flat for now — every pipeline shares this shape, and
-/// `resolve` only ever pairs a pipeline with the lanes it actually has (the
-/// typed-per-pipeline lanes step makes invalid pairs unrepresentable).
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
-pub enum Lane {
+pub enum AnalyticsLane {
Main,
Overflow,
Historical,
}
+/// No historical lane: the AI divert wins over historical rerouting.
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub enum AiLane {
+ Main,
+ Overflow,
+}
+
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub enum SessionReplayLane {
+ Main,
+ Overflow,
+}
+
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub enum BasicLane {
+ Main,
+}
+
/// Where an event publishes: a lane of its pipeline, or an admin redirect
-/// that sits outside the pipeline-lane model. The redirects carry no
-/// pipeline because nothing consumes one — every pipeline shares a single
-/// dlq output today (per-pipeline dlq rows arrive with typed addresses), and
-/// a custom redirect carries its own topic.
+/// outside the pipeline-lane model. A redirect carries no pipeline: every
+/// pipeline shares one dlq output, and a custom redirect names its own topic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Address {
- Lane { pipeline: Pipeline, lane: Lane },
+ Lane(PipelineLane),
Dlq,
Custom(String),
}
@@ -68,9 +75,9 @@ pub struct AddressDecision {
}
impl AddressDecision {
- fn lane(pipeline: Pipeline, lane: Lane, ordering: OrderingGuarantee) -> Self {
+ fn lane(lane: PipelineLane, ordering: OrderingGuarantee) -> Self {
Self {
- address: Address::Lane { pipeline, lane },
+ address: Address::Lane(lane),
ordering,
}
}
@@ -85,7 +92,9 @@ impl AddressDecision {
}
/// Decide an event's address from its metadata. DLQ and custom-topic
-/// redirects take priority over per-datatype and overflow routing. Consulted
+/// redirects take priority over per-datatype and overflow routing, and a
+/// restriction's `force_overflow` takes priority over a stamped
+/// `overflow_reason`. Consulted
/// by the sink, which resolves the address to a topic string and the ordering
/// guarantee to a partition key, and applies the address-implied side
/// effects. A replay event with no session id is rejected here, so every
@@ -94,7 +103,6 @@ pub fn resolve(
metadata: &ProcessedEventMetadata,
ai_events_overflow_armed: bool,
) -> Result<AddressDecision, CaptureError> {
- // redirect_to_dlq takes priority over all other routing.
if metadata.redirect_to_dlq {
return Ok(AddressDecision::redirect(Address::Dlq));
}
@@ -105,26 +113,21 @@ pub fn resolve(
Ok(match metadata.data_type {
DataType::AnalyticsHistorical => AddressDecision::lane(
- Pipeline::Analytics,
// Historical events never overflow — force_overflow and
// overflow_reason are deliberately ignored here.
- Lane::Historical,
+ PipelineLane::Analytics(AnalyticsLane::Historical),
OrderingGuarantee::PerDistinctId,
),
DataType::AnalyticsMain => {
- // Precedence: force_overflow (restrictions) -> overflow_reason
- // (pipeline-stamped) -> default main-lane routing.
if metadata.force_overflow {
AddressDecision::lane(
- Pipeline::Analytics,
- Lane::Overflow,
+ PipelineLane::Analytics(AnalyticsLane::Overflow),
person_ordering(metadata.person_processing_disabled()),
)
} else {
match &metadata.overflow_reason {
Some(OverflowReason::ForceLimited) => AddressDecision::lane(
- Pipeline::Analytics,
- Lane::Overflow,
+ PipelineLane::Analytics(AnalyticsLane::Overflow),
OrderingGuarantee::None,
),
// The person flag alone decides the key here, in both
@@ -138,8 +141,7 @@ pub fn resolve(
// before the overflow limiter overwrites the reason) must
// not get its partition back.
Some(OverflowReason::RateLimited { .. }) => AddressDecision::lane(
- Pipeline::Analytics,
- Lane::Overflow,
+ PipelineLane::Analytics(AnalyticsLane::Overflow),
person_ordering(metadata.person_processing_disabled()),
),
// ReplayLimited is stamped only by the recordings pipeline,
@@ -147,8 +149,7 @@ pub fn resolve(
// OverflowReason enum forces the arm, which treats the
// impossible stamp as unstamped.
Some(OverflowReason::ReplayLimited) | None => AddressDecision::lane(
- Pipeline::Analytics,
- Lane::Main,
+ PipelineLane::Analytics(AnalyticsLane::Main),
person_ordering(metadata.person_processing_disabled()),
),
}
@@ -163,68 +164,61 @@ pub fn resolve(
// force_overflow and stamped reasons are deliberately ignored
// (the pipeline never stamps a reason on this lane anyway). The
// default route keeps the event key regardless of
- // skip_person_processing (v1 only nulls keys for
- // Main/Overflow-shaped destinations). AI events never reroute
- // historical.
+ // skip_person_processing.
if ai_events_overflow_armed && metadata.force_overflow {
AddressDecision::lane(
- Pipeline::Ai,
- Lane::Overflow,
+ PipelineLane::Ai(AiLane::Overflow),
person_ordering(metadata.person_processing_disabled()),
)
} else if ai_events_overflow_armed {
match &metadata.overflow_reason {
- Some(OverflowReason::ForceLimited) => {
- AddressDecision::lane(Pipeline::Ai, Lane::Overflow, OrderingGuarantee::None)
- }
+ Some(OverflowReason::ForceLimited) => AddressDecision::lane(
+ PipelineLane::Ai(AiLane::Overflow),
+ OrderingGuarantee::None,
+ ),
Some(OverflowReason::RateLimited {
preserve_locality: true,
}) => AddressDecision::lane(
- Pipeline::Ai,
- Lane::Overflow,
+ PipelineLane::Ai(AiLane::Overflow),
// Same precedence as the analytics overflow lane above.
person_ordering(metadata.person_processing_disabled()),
),
Some(OverflowReason::RateLimited {
preserve_locality: false,
- }) => {
- AddressDecision::lane(Pipeline::Ai, Lane::Overflow, OrderingGuarantee::None)
- }
+ }) => AddressDecision::lane(
+ PipelineLane::Ai(AiLane::Overflow),
+ OrderingGuarantee::None,
+ ),
// ReplayLimited cannot be stamped on the AI lane either;
// treated as unstamped, as above.
Some(OverflowReason::ReplayLimited) | None => AddressDecision::lane(
- Pipeline::Ai,
- Lane::Main,
+ PipelineLane::Ai(AiLane::Main),
OrderingGuarantee::PerDistinctId,
),
}
} else {
- AddressDecision::lane(Pipeline::Ai, Lane::Main, OrderingGuarantee::PerDistinctId)
+ AddressDecision::lane(
+ PipelineLane::Ai(AiLane::Main),
+ OrderingGuarantee::PerDistinctId,
+ )
}
}
- // Single-lane pipelines: capture has no overflow topic for warnings,
- // heatmaps, or error tracking, so `Lane::Overflow` is never resolved
- // for them. A ForceOverflow restriction scoped to one of these
- // pipelines stamps `force_overflow` on the event, and the stamp is
- // deliberately ignored here; the event publishes to main.
+ // A ForceOverflow restriction can stamp `force_overflow` on these
+ // events. Their lane type has no overflow, so the stamp is ignored and
+ // the event publishes to main.
DataType::ClientIngestionWarning => AddressDecision::lane(
- Pipeline::Warnings,
- Lane::Main,
+ PipelineLane::Warnings(BasicLane::Main),
OrderingGuarantee::PerDistinctId,
),
DataType::HeatmapMain => AddressDecision::lane(
- Pipeline::Heatmaps,
- Lane::Main,
+ PipelineLane::Heatmaps(BasicLane::Main),
OrderingGuarantee::PerDistinctId,
),
DataType::ExceptionErrorTracking => AddressDecision::lane(
- Pipeline::ErrorTracking,
- Lane::Main,
+ PipelineLane::ErrorTracking(BasicLane::Main),
OrderingGuarantee::PerDistinctId,
),
DataType::SnapshotMain => {
- // Precedence: force_overflow (restrictions) -> overflow_reason
- // (pipeline-stamped ReplayLimited) -> default main-lane routing.
// Partition key is always session_id for replay to keep per-session
// ordering on the overflow lane; a missing id makes the decision
// unrealizable, so it is rejected as part of the decision.
@@ -236,11 +230,11 @@ pub fn resolve(
metadata.overflow_reason,
Some(OverflowReason::ReplayLimited)
) {
- Lane::Overflow
+ SessionReplayLane::Overflow
} else {
- Lane::Main
+ SessionReplayLane::Main
};
- AddressDecision::lane(Pipeline::Replay, lane, OrderingGuarantee::PerSession)
+ AddressDecision::lane(PipelineLane::Replay(lane), OrderingGuarantee::PerSession)
}
})
}
@@ -266,8 +260,8 @@ mod tests {
}
}
- fn lane(pipeline: Pipeline, lane: Lane) -> Address {
- Address::Lane { pipeline, lane }
+ fn lane(lane: PipelineLane) -> Address {
+ Address::Lane(lane)
}
#[test]
@@ -303,45 +297,52 @@ mod tests {
}
#[rstest]
- #[case(DataType::AnalyticsMain, Pipeline::Analytics, Lane::Main)]
- #[case(DataType::AnalyticsHistorical, Pipeline::Analytics, Lane::Historical)]
- #[case(DataType::ClientIngestionWarning, Pipeline::Warnings, Lane::Main)]
- #[case(DataType::HeatmapMain, Pipeline::Heatmaps, Lane::Main)]
- #[case(DataType::ExceptionErrorTracking, Pipeline::ErrorTracking, Lane::Main)]
- #[case(DataType::AiEvents, Pipeline::Ai, Lane::Main)]
- #[case(DataType::SnapshotMain, Pipeline::Replay, Lane::Main)]
- fn per_datatype_addresses(
- #[case] data_type: DataType,
- #[case] pipeline: Pipeline,
- #[case] expected_lane: Lane,
- ) {
+ #[case(DataType::AnalyticsMain, PipelineLane::Analytics(AnalyticsLane::Main))]
+ #[case(
+ DataType::AnalyticsHistorical,
+ PipelineLane::Analytics(AnalyticsLane::Historical)
+ )]
+ #[case(
+ DataType::ClientIngestionWarning,
+ PipelineLane::Warnings(BasicLane::Main)
+ )]
+ #[case(DataType::HeatmapMain, PipelineLane::Heatmaps(BasicLane::Main))]
+ #[case(
+ DataType::ExceptionErrorTracking,
+ PipelineLane::ErrorTracking(BasicLane::Main)
+ )]
+ #[case(DataType::AiEvents, PipelineLane::Ai(AiLane::Main))]
+ #[case(DataType::SnapshotMain, PipelineLane::Replay(SessionReplayLane::Main))]
+ fn per_datatype_addresses(#[case] data_type: DataType, #[case] expected_lane: PipelineLane) {
let m = meta(data_type);
let d = resolve(&m, false).unwrap();
assert_eq!(
d.address,
- lane(pipeline, expected_lane),
+ lane(expected_lane),
"wrong address for {data_type:?}"
);
}
- /// The single-lane pipelines have no overflow lane to give: stamped
- /// overflow intent (an error-tracking-scoped ForceOverflow restriction is
- /// the reachable case) must resolve to main, not to an overflow address
- /// no output backs.
#[rstest]
- #[case(DataType::ClientIngestionWarning, Pipeline::Warnings)]
- #[case(DataType::HeatmapMain, Pipeline::Heatmaps)]
- #[case(DataType::ExceptionErrorTracking, Pipeline::ErrorTracking)]
+ #[case(
+ DataType::ClientIngestionWarning,
+ PipelineLane::Warnings(BasicLane::Main)
+ )]
+ #[case(DataType::HeatmapMain, PipelineLane::Heatmaps(BasicLane::Main))]
+ #[case(
+ DataType::ExceptionErrorTracking,
+ PipelineLane::ErrorTracking(BasicLane::Main)
+ )]
fn single_lane_pipelines_ignore_overflow_intent(
#[case] data_type: DataType,
- #[case] pipeline: Pipeline,
+ #[case] main: PipelineLane,
) {
let mut m = meta(data_type);
m.force_overflow = true;
m.overflow_reason = Some(OverflowReason::ForceLimited);
assert_eq!(
resolve(&m, true).unwrap().address,
- lane(pipeline, Lane::Main),
+ lane(main),
"overflow intent must not move {data_type:?} off its main lane"
);
}
@@ -362,7 +363,7 @@ mod tests {
);
assert_eq!(
resolve(&m, false).unwrap().address,
- lane(Pipeline::Analytics, Lane::Overflow)
+ lane(PipelineLane::Analytics(AnalyticsLane::Overflow))
);
}
@@ -375,7 +376,7 @@ mod tests {
assert_eq!(
resolve(&force_limited, false).unwrap(),
AddressDecision {
- address: lane(Pipeline::Analytics, Lane::Overflow),
+ address: lane(PipelineLane::Analytics(AnalyticsLane::Overflow)),
ordering: OrderingGuarantee::None,
}
);
@@ -390,7 +391,7 @@ mod tests {
);
assert_eq!(
resolve(&preserve, false).unwrap().address,
- lane(Pipeline::Analytics, Lane::Overflow)
+ lane(PipelineLane::Analytics(AnalyticsLane::Overflow))
);
// The locality preference is irrelevant on the analytics lane: a
@@ -406,7 +407,7 @@ mod tests {
);
assert_eq!(
resolve(&no_preserve, false).unwrap().address,
- lane(Pipeline::Analytics, Lane::Overflow)
+ lane(PipelineLane::Analytics(AnalyticsLane::Overflow))
);
no_preserve.skip_person_processing = true;
assert_eq!(
@@ -421,7 +422,7 @@ mod tests {
replay.overflow_reason = Some(OverflowReason::ReplayLimited);
assert_eq!(
resolve(&replay, false).unwrap().address,
- lane(Pipeline::Analytics, Lane::Main)
+ lane(PipelineLane::Analytics(AnalyticsLane::Main))
);
}
@@ -429,13 +430,16 @@ mod tests {
/// overflow limiter runs, and the overflow limiter overwrites the reason it
/// stamped. Without this precedence a key the rate limiter declared too hot
/// would go back to hashing onto a single overflow partition whenever the
- /// limiter preserves locality, which is how prod-US is configured.
+ /// limiter preserves locality.
#[rstest]
- #[case::analytics(DataType::AnalyticsMain, Pipeline::Analytics)]
- #[case::ai(DataType::AiEvents, Pipeline::Ai)]
+ #[case::analytics(
+ DataType::AnalyticsMain,
+ PipelineLane::Analytics(AnalyticsLane::Overflow)
+ )]
+ #[case::ai(DataType::AiEvents, PipelineLane::Ai(AiLane::Overflow))]
fn person_processing_off_outranks_preserve_locality(
#[case] data_type: DataType,
- #[case] expected_pipeline: Pipeline,
+ #[case] overflow: PipelineLane,
) {
let armed = data_type == DataType::AiEvents;
let mut m = meta(data_type);
@@ -453,7 +457,7 @@ mod tests {
assert_eq!(
resolve(&m, armed).unwrap(),
AddressDecision {
- address: lane(expected_pipeline, Lane::Overflow),
+ address: lane(overflow),
ordering: OrderingGuarantee::None,
}
);
@@ -468,7 +472,7 @@ mod tests {
assert_eq!(
resolve(&m, false).unwrap(),
AddressDecision {
- address: lane(Pipeline::Ai, Lane::Main),
+ address: lane(PipelineLane::Ai(AiLane::Main)),
ordering: OrderingGuarantee::PerDistinctId,
}
);
@@ -476,7 +480,7 @@ mod tests {
// Valve armed: mirrors the analytics main lane's overflow handling.
assert_eq!(
resolve(&m, true).unwrap().address,
- lane(Pipeline::Ai, Lane::Overflow)
+ lane(PipelineLane::Ai(AiLane::Overflow))
);
assert_eq!(
resolve(&m, true).unwrap().ordering,
@@ -490,13 +494,13 @@ mod tests {
assert_eq!(
resolve(&force_limited, true).unwrap(),
AddressDecision {
- address: lane(Pipeline::Ai, Lane::Overflow),
+ address: lane(PipelineLane::Ai(AiLane::Overflow)),
ordering: OrderingGuarantee::None,
}
);
assert_eq!(
resolve(&force_limited, false).unwrap().address,
- lane(Pipeline::Ai, Lane::Main)
+ lane(PipelineLane::Ai(AiLane::Main))
);
}
@@ -510,7 +514,7 @@ mod tests {
assert_eq!(
resolve(&m, armed).unwrap(),
AddressDecision {
- address: lane(Pipeline::Ai, Lane::Main),
+ address: lane(PipelineLane::Ai(AiLane::Main)),
ordering: OrderingGuarantee::PerDistinctId,
},
"armed={armed}"
@@ -524,7 +528,7 @@ mod tests {
assert_eq!(
resolve(&m, false).unwrap(),
AddressDecision {
- address: lane(Pipeline::Replay, Lane::Main),
+ address: lane(PipelineLane::Replay(SessionReplayLane::Main)),
ordering: OrderingGuarantee::PerSession,
}
);
@@ -532,7 +536,7 @@ mod tests {
m.force_overflow = true;
assert_eq!(
resolve(&m, false).unwrap().address,
- lane(Pipeline::Replay, Lane::Overflow)
+ lane(PipelineLane::Replay(SessionReplayLane::Overflow))
);
assert_eq!(
resolve(&m, false).unwrap().ordering,
@@ -543,7 +547,7 @@ mod tests {
m.overflow_reason = Some(OverflowReason::ReplayLimited);
assert_eq!(
resolve(&m, false).unwrap().address,
- lane(Pipeline::Replay, Lane::Overflow)
+ lane(PipelineLane::Replay(SessionReplayLane::Overflow))
);
}
diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rs
index a1093ea999a3..496ab0ff01f6 100644
--- a/rust/capture/src/sinks/kafka.rs
+++ b/rust/capture/src/sinks/kafka.rs
@@ -1,19 +1,12 @@
//! Kafka sink (mechanism layer).
//!
-//! This sink is pure mechanism: it serializes `ProcessedEvent`s and produces them
-//! to Kafka using `rdkafka`. All routing *policy* (overflow rerouting, DLQ
-//! redirects, custom-topic redirects, force-disable-person-processing headers) is
-//! decided *upstream* in the pipeline and stamped onto
-//! `ProcessedEventMetadata`. `KafkaSinkBase::prepare_record` reads that metadata
-//! and maps it to a [`Destination`] and partition key; enqueue resolves the
-//! destination to a topic and producer.
-//!
-//! The `overflow_reason` stamping specifically runs at four call sites, all via
-//! the shared `events::overflow_stamping::stamp_overflow_reason` helper:
-//! * `events::analytics::process_events` (analytics batch path: `/e/`, `/batch/`, `/capture`, etc.)
-//! * `events::recordings::process_replay_events` (replay-specific `RedisLimiter`, stamps `OverflowReason::ReplayLimited`)
-//! * `ai_endpoint::ai_handler` (`/i/v0/ai`, single-event)
-//! * `otel::otel_handler` (`/i/v0/ai/otel`, multi-span batch)
+//! This sink is pure mechanism: it produces to Kafka with `rdkafka`.
+//! `KafkaSinkBase::prepare_record` serializes a `ProcessedEvent` and maps the
+//! metadata the pipeline stamped to a [`Destination`] and partition key; v1's
+//! prepared events arrive serialized and carry their own address. All routing
+//! *policy* (overflow, DLQ and custom-topic redirects, person-processing
+//! headers) is decided *upstream*. Enqueue resolves the destination to a topic
+//! and producer.
//!
//! Keeping routing policy out of the sink keeps the clone-per-spawned-task
//! cost in the scatter-gather batch path at one `Arc::clone` call (the output
@@ -34,6 +27,7 @@ use bytes::Bytes;
use common_types::CapturedEventHeaders;
use futures::future::join_all;
use metrics::{counter, gauge, histogram};
+use std::future::Future;
use std::sync::Arc;
use std::time::Instant;
use tokio::task::JoinSet;
@@ -85,7 +79,6 @@ fn emit_window_stats(
impl rdkafka::ClientContext for KafkaContext {
fn stats(&self, stats: rdkafka::Statistics) {
- // Signal liveness when brokers are up
let brokers_up = stats.brokers.values().any(|broker| broker.state == "UP");
if brokers_up {
if let Some(liveness) = &self.liveness {
@@ -102,7 +95,6 @@ impl rdkafka::ClientContext for KafkaContext {
let down_brokers = total_brokers.saturating_sub(up_brokers);
gauge!("capture_kafka_any_brokers_down").set(if down_brokers > 0 { 1.0 } else { 0.0 });
- // Update exported metrics
gauge!("capture_kafka_callback_queue_depth",).set(stats.replyq as f64);
gauge!("capture_kafka_producer_queue_depth",).set(stats.msg_cnt as f64);
gauge!("capture_kafka_producer_queue_depth_limit",).set(stats.msg_max as f64);
@@ -223,9 +215,7 @@ impl KafkaSink {
}
impl<P: KafkaProducer> KafkaSinkBase<P> {
- /// Create a new KafkaSinkBase with a custom producer (useful for testing).
- /// No limiters — the sink is a mechanism layer; overflow stamping happens
- /// upstream in the pipeline. See the module header for details.
+ /// Create a KafkaSinkBase over a custom producer, for tests.
pub fn with_producer(producer: P, outputs: OutputTable) -> Self {
Self::with_producer_and_compression(producer, outputs, EnvelopeCompression::None)
}
@@ -281,7 +271,6 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
let event_key = event.key();
- // Use the event's to_headers() method for consistent header serialization
let mut headers = event.to_headers();
drop(event); // Events can be EXTREMELY memory hungry
@@ -314,20 +303,7 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {
.increment(1);
Destination::Custom(topic)
}
- Address::Lane { pipeline, lane } => match Destination::for_lane(pipeline, lane) {
- Some(output) => output,
- // A pair `resolve` never produces: no output backs it, so
- // the event goes to the dlq — preserved and replayable —
- // instead of being processed through a lane with the wrong
- // semantics. Loud, because reaching this arm means a change
- // made the pair producible without giving it an output.
- None => {
- debug_assert!(false, "no output backs ({pipeline:?}, {lane:?})");
- error!("no output backs ({pipeline:?}, {lane:?}), publishing to the dlq");
- dlq_reroute_effects(&mut headers, "unbacked_lane");
- Destination::Dlq
- }
- },
+ Address::Lane(lane) => Destination::for_lane(lane),
};
let partition_key = match decision.ordering {
@@ -428,8 +404,8 @@ impl<P: KafkaProducer + 'static> KafkaSinkBase<P> {
/// CPU-bound batch prep: run `prepare_record` over the batch and return
/// the payloads in the original event order, fail-fast on the first prep
/// error so no partially-prepped batch reaches the producer. Inherent
- /// rather than on the `PublishPayloads` trait: payload assembly is not backend
- /// mechanism, and the outputs layer becomes its caller.
+ /// rather than on the `PublishPayloads` trait: payload assembly is not
+ /// backend mechanism.
pub(crate) async fn prepare_batch(
&self,
events: Vec<ProcessedEvent>,
@@ -528,8 +504,7 @@ impl<P: KafkaProducer + 'static> PublishPayloads for KafkaSinkBase<P> {
/// before subsequent events.
///
/// Results are batch-uniform: the whole batch reports the first failure,
- /// acked-before-failure events included. The per-event surface refines
- /// only with the per-event response model.
+ /// acked-before-failure events included. `publish_prepared` reports per event.
async fn publish(&self, payloads: Vec<PreparedPayload>) -> Vec<SinkResult> {
// Results are built in payload order as the loop enqueues, so the one
// Vec the return type requires is the only allocation on the happy
@@ -537,7 +512,7 @@ impl<P: KafkaProducer + 'static> PublishPayloads for KafkaSinkBase<P> {
let mut results: Vec<SinkResult> = Vec::with_capacity(payloads.len());
let enqueue_start = Instant::now();
- let mut ack_set = JoinSet::new();
+ let mut ack_set = AckSet::new();
let mut payloads = payloads.into_iter();
for payload in payloads.by_ref() {
let uuid = payload.uuid;
@@ -547,11 +522,9 @@ impl<P: KafkaProducer + 'static> PublishPayloads for KafkaSinkBase<P> {
results.push(SinkResult::published(uuid));
}
Err(err) => {
+ ack_set.cancel();
// Record enqueue duration on the error path too so slow-fail
// cases (e.g. QueueFull after a long stall) stay observable.
- // Dropping `ack_set` aborts any already spawned ack futures
- // for this batch; DeliveryAckFuture::drop then records the
- // "dropped" outcome on capture_kafka_produce_ack_duration_ms.
histogram!("capture_kafka_batch_enqueue_duration_seconds")
.record(enqueue_start.elapsed().as_secs_f64());
for result in &mut results {
@@ -566,7 +539,7 @@ impl<P: KafkaProducer + 'static> PublishPayloads for KafkaSinkBase<P> {
histogram!("capture_kafka_batch_enqueue_duration_seconds")
.record(enqueue_start.elapsed().as_secs_f64());
- match drain_acks(ack_set).await {
+ match ack_set.wait().await {
Ok(()) => results,
Err(err) => {
for result in &mut results {
@@ -606,19 +579,13 @@ impl<P: KafkaProducer + 'static> PublishPrepared for KafkaSinkBase<P> {
.into_iter()
.map(|event| {
let uuid = event.uuid;
- let ack = match Destination::for_address(event.address) {
- Some(destination) => self.send(
- &destination,
- event.partition_key,
- event.ordering,
- event.payload,
- event.headers,
- ),
- None => {
- error!("no output backs the event's address, dropping it");
- Err(CaptureError::NonRetryableSinkError)
- }
- };
+ let ack = self.send(
+ &Destination::for_address(event.address),
+ event.partition_key,
+ event.ordering,
+ event.payload,
+ event.headers,
+ );
(uuid, ack)
})
.collect();
@@ -639,30 +606,49 @@ impl<P: KafkaProducer + 'static> PublishPrepared for KafkaSinkBase<P> {
}
}
-/// Concurrent ack drain for `PublishPayloads::publish`, fail-fast on first ack error.
-/// Dropping the JoinSet on error aborts remaining spawned ack futures;
-/// DeliveryAckFuture Drop then records the "dropped" outcome on
-/// capture_kafka_produce_ack_duration_ms.
-async fn drain_acks(mut ack_set: JoinSet<Result<(), CaptureError>>) -> Result<(), CaptureError> {
- async move {
- while let Some(res) = ack_set.join_next().await {
- match res {
- Ok(Ok(_)) => {}
- Ok(Err(err)) => {
- ack_set.abort_all();
- return Err(err);
- }
- Err(err) => {
- ack_set.abort_all();
- error!("join error while waiting on Kafka ACK: {err:#}");
- return Err(CaptureError::RetryableSinkError);
+/// The ack futures of one `PublishPayloads::publish` batch, awaited concurrently.
+struct AckSet(JoinSet<Result<(), CaptureError>>);
+
+impl AckSet {
+ fn new() -> Self {
+ Self(JoinSet::new())
+ }
+
+ fn spawn<F>(&mut self, ack: F)
+ where
+ F: Future<Output = Result<(), CaptureError>> + Send + 'static,
+ {
+ self.0.spawn(ack);
+ }
+
+ /// Waits for every ack. The first failure cancels the rest.
+ async fn wait(mut self) -> Result<(), CaptureError> {
+ async move {
+ while let Some(res) = self.0.join_next().await {
+ match res {
+ Ok(Ok(_)) => {}
+ Ok(Err(err)) => {
+ self.cancel();
+ return Err(err);
+ }
+ Err(err) => {
+ self.cancel();
+ error!("join error while waiting on Kafka ACK: {err:#}");
+ return Err(CaptureError::RetryableSinkError);
+ }
}
}
+ Ok(())
}
- Ok(())
+ .instrument(info_span!("ack_wait_many"))
+ .await
+ }
+
+ /// Cancels every unfinished ack. A cancelled `DeliveryAckFuture` records
+ /// its wait as outcome `dropped`.
+ fn cancel(mut self) {
+ self.0.abort_all();
}
- .instrument(info_span!("ack_wait_many"))
- .await
}
#[cfg(test)]
@@ -774,7 +760,6 @@ mod tests {
}
}
- // Send events to confirm happy path
sink.publish_events(vec![event.clone()])
.await
.expect("failed to send one initial event");
@@ -955,7 +940,6 @@ mod tests {
use common_types::CapturedEventHeaders;
use rdkafka::message::OwnedHeaders;
- // Test that the 'now' header is correctly set and parsed
let test_now = "2024-01-15T10:30:45Z".to_string();
let headers = CapturedEventHeaders {
token: Some("test_token".to_string()),
@@ -974,11 +958,9 @@ mod tests {
content_encoding: None,
};
- // Convert to owned headers and back
let owned_headers: OwnedHeaders = headers.into();
let parsed_headers = CapturedEventHeaders::from(owned_headers);
- // Verify the 'now' field is preserved
assert_eq!(parsed_headers.now, Some(test_now));
assert_eq!(parsed_headers.token, Some("test_token".to_string()));
assert_eq!(parsed_headers.distinct_id, Some("test_id".to_string()));
@@ -989,7 +971,6 @@ mod tests {
use common_types::CapturedEventHeaders;
use rdkafka::message::OwnedHeaders;
- // Test that the 'now' header is correctly set and parsed
let test_now = "2024-01-15T10:30:45Z".to_string();
let dlq_timestamp = "2025-01-15T10:30:45Z".to_string();
let headers = CapturedEventHeaders {
@@ -1009,11 +990,9 @@ mod tests {
content_encoding: None,
};
- // Convert to owned headers and back
let owned_headers: OwnedHeaders = headers.into();
let parsed_headers = CapturedEventHeaders::from(owned_headers);
- // Verify the 'now' field is preserved
assert_eq!(parsed_headers.dlq_reason, Some("test reason".to_string()));
assert_eq!(parsed_headers.dlq_step, Some("test step".to_string()));
assert_eq!(parsed_headers.dlq_timestamp, Some(dlq_timestamp));
@@ -1140,7 +1119,7 @@ mod tests {
async fn assert_routing(input: EventInput, expected: ExpectedRouting<'_>) {
// Capture reroute counters on a thread-local recorder. `assert_routing`
- // runs on the default current-thread test runtime and `send` prepares
+ // runs on the current-thread test runtime and `kafka_send` prepares
// the record inline before the first await, so the guard stays visible
// when `prepare_record` increments the counter.
let recorder = metrics_util::debugging::DebuggingRecorder::new();
@@ -2253,7 +2232,7 @@ mod tests {
#[tokio::test]
async fn ai_events_skip_person_keeps_key() {
// skip_person_processing sets the header but must not null the
- // key: v1's sink only nulls keys for Main/Overflow destinations.
+ // key: the AI main lane keeps per-distinct-id ordering.
assert_routing(
EventInput {
data_type: DataType::AiEvents,
@@ -2609,10 +2588,8 @@ mod tests {
#[tokio::test]
async fn overflow_reason_force_overflow_short_circuits_overflow_reason() {
- // Precedence check: force_overflow set by event restrictions wins
- // over any overflow_reason stamped by the governor. This ensures
- // the event_restriction counter label stays distinct from
- // force_limited / rate_limited labels.
+ // force_overflow from an event restriction wins over a stamped
+ // overflow_reason.
assert_routing(
EventInput {
data_type: DataType::AnalyticsMain,
@@ -2931,9 +2908,8 @@ mod tests {
#[test]
fn publish_events_one_event_feeds_the_phase_histograms() {
// The one-event path skips prepare_batch and PublishPayloads::publish, which
- // own these two histograms, so it has to record them itself.
- // Otherwise every single-event endpoint drops out of the
- // distribution and the in-process quantiles step up unprompted.
+ // own these two histograms, so it records them itself. Otherwise single-event
+ // endpoints drop out of the distribution and the quantiles shift.
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
@@ -3023,8 +2999,7 @@ mod tests {
// ==================== Sink mechanism seam ====================
// The per-event result surface `PublishPayloads::publish` reports: uuid-aligned
// with the input payloads, batch-uniform on failure. `fold_results`
- // discards this shape, so the publish_events tests above cannot see it —
- // and the outputs layer builds on it.
+ // discards this shape, so the publish_events tests above cannot see it.
#[tokio::test]
async fn publish_reports_uuid_aligned_results() {
@@ -3262,7 +3237,9 @@ mod tests {
use super::*;
use crate::ordering::OrderingGuarantee;
use crate::outputs::{PreparedEvent, PublishPrepared};
- use crate::pipeline::{Address, Lane, Pipeline};
+ use crate::pipeline::{
+ Address, AiLane, AnalyticsLane, BasicLane, PipelineLane, SessionReplayLane,
+ };
use crate::sinks::kafka::KafkaSinkBase;
use crate::sinks::producer::MockKafkaProducer;
use crate::sinks::sink::{Outcome, SinkResult};
@@ -3300,10 +3277,7 @@ mod tests {
fn analytics_main() -> PreparedEvent {
prepared(
- Address::Lane {
- pipeline: Pipeline::Analytics,
- lane: Lane::Main,
- },
+ Address::Lane(PipelineLane::Analytics(AnalyticsLane::Main)),
OrderingGuarantee::PerDistinctId,
)
}
@@ -3330,39 +3304,39 @@ mod tests {
#[rstest]
#[case::analytics_main(
- EventInput { address: Address::Lane { pipeline: Pipeline::Analytics, lane: Lane::Main }, ordering: OrderingGuarantee::PerDistinctId },
+ EventInput { address: Address::Lane(PipelineLane::Analytics(AnalyticsLane::Main)), ordering: OrderingGuarantee::PerDistinctId },
ExpectedRecord { topic: "events_plugin_ingestion", keyed: true },
)]
#[case::analytics_overflow_spread(
- EventInput { address: Address::Lane { pipeline: Pipeline::Analytics, lane: Lane::Overflow }, ordering: OrderingGuarantee::None },
+ EventInput { address: Address::Lane(PipelineLane::Analytics(AnalyticsLane::Overflow)), ordering: OrderingGuarantee::None },
ExpectedRecord { topic: "events_plugin_ingestion_overflow", keyed: false },
)]
#[case::analytics_historical(
- EventInput { address: Address::Lane { pipeline: Pipeline::Analytics, lane: Lane::Historical }, ordering: OrderingGuarantee::PerDistinctId },
+ EventInput { address: Address::Lane(PipelineLane::Analytics(AnalyticsLane::Historical)), ordering: OrderingGuarantee::PerDistinctId },
ExpectedRecord { topic: "events_plugin_ingestion_historical", keyed: true },
)]
#[case::ai_main(
- EventInput { address: Address::Lane { pipeline: Pipeline::Ai, lane: Lane::Main }, ordering: OrderingGuarantee::PerDistinctId },
+ EventInput { address: Address::Lane(PipelineLane::Ai(AiLane::Main)), ordering: OrderingGuarantee::PerDistinctId },
ExpectedRecord { topic: "ai_events", keyed: true },
)]
#[case::ai_overflow(
- EventInput { address: Address::Lane { pipeline: Pipeline::Ai, lane: Lane::Overflow }, ordering: OrderingGuarantee::None },
+ EventInput { address: Address::Lane(PipelineLane::Ai(AiLane::Overflow)), ordering: OrderingGuarantee::None },
ExpectedRecord { topic: "ai_events_overflow", keyed: false },
)]
#[case::heatmaps(
- EventInput { address: Address::Lane { pipeline: Pipeline::Heatmaps, lane: Lane::Main }, ordering: OrderingGuarantee::PerDistinctId },
+ EventInput { address: Address::Lane(PipelineLane::Heatmaps(BasicLane::Main)), ordering: OrderingGuarantee::PerDistinctId },
ExpectedRecord { topic: "heatmaps", keyed: true },
)]
#[case::warnings(
- EventInput { address: Address::Lane { pipeline: Pipeline::Warnings, lane: Lane::Main }, ordering: OrderingGuarantee::PerDistinctId },
+ EventInput { address: Address::Lane(PipelineLane::Warnings(BasicLane::Main)), ordering: OrderingGuarantee::PerDistinctId },
ExpectedRecord { topic: "client_ingestion_warning", keyed: true },
)]
#[case::error_tracking(
- EventInput { address: Address::Lane { pipeline: Pipeline::ErrorTracking, lane: Lane::Main }, ordering: OrderingGuarantee::PerDistinctId },
+ EventInput { address: Address::Lane(PipelineLane::ErrorTracking(BasicLane::Main)), ordering: OrderingGuarantee::PerDistinctId },
ExpectedRecord { topic: "error_tracking_events", keyed: true },
)]
#[case::replay_overflow(
- EventInput { address: Address::Lane { pipeline: Pipeline::Replay, lane: Lane::Overflow }, ordering: OrderingGuarantee::PerSession },
+ EventInput { address: Address::Lane(PipelineLane::Replay(SessionReplayLane::Overflow)), ordering: OrderingGuarantee::PerSession },
ExpectedRecord { topic: "replay_overflow", keyed: true },
)]
#[case::dlq(
@@ -3456,29 +3430,6 @@ mod tests {
assert_eq!(producer.get_records().len(), 3);
}
- #[tokio::test]
- async fn prepared_event_on_an_unbacked_lane_fails_without_producing() {
- let producer = MockKafkaProducer::new();
- let sink = KafkaSinkBase::with_producer(producer.clone(), test_outputs());
- let unbacked = prepared(
- Address::Lane {
- pipeline: Pipeline::Heatmaps,
- lane: Lane::Overflow,
- },
- OrderingGuarantee::PerDistinctId,
- );
-
- let results = sink
- .publish_prepared(vec![unbacked, analytics_main()])
- .await;
-
- assert_eq!(
- outcomes(&results),
- vec![Some("NonRetryableSinkError".to_string()), None]
- );
- assert_eq!(producer.get_records().len(), 1);
- }
-
#[tokio::test]
async fn prepared_event_publishes_through_its_targets_producer() {
let ingestion = Arc::new(MockKafkaProducer::new());
@@ -3490,10 +3441,7 @@ mod tests {
replay_envelope_compression: EnvelopeCompression::None,
};
let ai_event = prepared(
- Address::Lane {
- pipeline: Pipeline::Ai,
- lane: Lane::Main,
- },
+ Address::Lane(PipelineLane::Ai(AiLane::Main)),
OrderingGuarantee::PerDistinctId,
);
diff --git a/rust/capture/src/sinks/registry.rs b/rust/capture/src/sinks/registry.rs
index f2fa301757a3..42f27c66d6e1 100644
--- a/rust/capture/src/sinks/registry.rs
+++ b/rust/capture/src/sinks/registry.rs
@@ -1,14 +1,10 @@
//! Binds every fixed routing [`Destination`] to its output: a Kafka topic and
-//! the named producer that carries it. Adding an output is a one-place change:
-//! the `target_for` and `is_required` matches are compiler-forced exhaustive,
-//! a test pins `REGISTERED` to the required set, and
-//! [`OutputTable::check_complete`] catches an unwired output at boot instead
-//! of at first produce.
+//! the named producer that carries it.
use std::sync::Arc;
use crate::config::OutputsConfig;
-use crate::pipeline::{Address, Lane, Pipeline};
+use crate::pipeline::{Address, AiLane, AnalyticsLane, BasicLane, PipelineLane, SessionReplayLane};
use crate::producers::ProducerName;
/// Which configured output a routing decision selects, named by pipeline and
@@ -48,40 +44,26 @@ impl Destination {
Destination::AiMain,
];
- /// `None` marks a pair [`pipeline::resolve`] never produces: no output
- /// backs it.
- ///
- /// [`pipeline::resolve`]: crate::pipeline::resolve
- pub(crate) fn for_lane(pipeline: Pipeline, lane: Lane) -> Option<Destination> {
- // Every pair is spelled out so that a new lane, or a change making an
- // unbacked pair reachable, has to visit this match instead of being
- // absorbed by a wildcard. Step 13 of OUTPUTS_REFACTOR_PLAN.md types
- // lanes per pipeline so such pairs cannot be built; drop the `None`
- // arms and this note then.
- match (pipeline, lane) {
- (Pipeline::Analytics, Lane::Main) => Some(Destination::AnalyticsMain),
- (Pipeline::Analytics, Lane::Overflow) => Some(Destination::AnalyticsOverflow),
- (Pipeline::Analytics, Lane::Historical) => Some(Destination::AnalyticsHistorical),
- (Pipeline::Ai, Lane::Main) => Some(Destination::AiMain),
- (Pipeline::Ai, Lane::Overflow) => Some(Destination::AiOverflow),
- (Pipeline::Ai, Lane::Historical) => None,
- (Pipeline::Warnings, Lane::Main) => Some(Destination::ClientWarningsMain),
- (Pipeline::Warnings, Lane::Overflow | Lane::Historical) => None,
- (Pipeline::Heatmaps, Lane::Main) => Some(Destination::HeatmapsMain),
- (Pipeline::Heatmaps, Lane::Overflow | Lane::Historical) => None,
- (Pipeline::ErrorTracking, Lane::Main) => Some(Destination::ErrorTrackingMain),
- (Pipeline::ErrorTracking, Lane::Overflow | Lane::Historical) => None,
- (Pipeline::Replay, Lane::Main) => Some(Destination::SessionReplayMain),
- (Pipeline::Replay, Lane::Overflow) => Some(Destination::SessionReplayOverflow),
- (Pipeline::Replay, Lane::Historical) => None,
+ pub(crate) fn for_lane(lane: PipelineLane) -> Destination {
+ match lane {
+ PipelineLane::Analytics(AnalyticsLane::Main) => Destination::AnalyticsMain,
+ PipelineLane::Analytics(AnalyticsLane::Overflow) => Destination::AnalyticsOverflow,
+ PipelineLane::Analytics(AnalyticsLane::Historical) => Destination::AnalyticsHistorical,
+ PipelineLane::Ai(AiLane::Main) => Destination::AiMain,
+ PipelineLane::Ai(AiLane::Overflow) => Destination::AiOverflow,
+ PipelineLane::Warnings(BasicLane::Main) => Destination::ClientWarningsMain,
+ PipelineLane::Heatmaps(BasicLane::Main) => Destination::HeatmapsMain,
+ PipelineLane::ErrorTracking(BasicLane::Main) => Destination::ErrorTrackingMain,
+ PipelineLane::Replay(SessionReplayLane::Main) => Destination::SessionReplayMain,
+ PipelineLane::Replay(SessionReplayLane::Overflow) => Destination::SessionReplayOverflow,
}
}
- pub(crate) fn for_address(address: Address) -> Option<Destination> {
+ pub(crate) fn for_address(address: Address) -> Destination {
match address {
- Address::Lane { pipeline, lane } => Self::for_lane(pipeline, lane),
- Address::Dlq => Some(Destination::Dlq),
- Address::Custom(topic) => Some(Destination::Custom(topic)),
+ Address::Lane(lane) => Self::for_lane(lane),
+ Address::Dlq => Destination::Dlq,
+ Address::Custom(topic) => Destination::Custom(topic),
}
}
@@ -382,11 +364,7 @@ mod tests {
assert!(test_outputs().check_complete().is_ok());
}
- /// `REGISTERED` is a hand-maintained array while `is_required` is
- /// compiler-exhaustive; this pins them together. A new variant cannot
- /// compile without an `is_required` arm, and putting it on the wrong
- /// side of `REGISTERED` fails here. The all-variants list below is the
- /// one hand-maintained enumeration left — grow it with the enum.
+ /// The all-variants list below is hand-maintained: grow it with the enum.
#[test]
fn registered_is_exactly_the_required_outputs() {
let all = [
diff --git a/rust/capture/src/v1/prepare.rs b/rust/capture/src/v1/prepare.rs
index 98ed59d731e3..4df903e46737 100644
--- a/rust/capture/src/v1/prepare.rs
+++ b/rust/capture/src/v1/prepare.rs
@@ -91,7 +91,6 @@ where
let start = Instant::now();
let n = events.len();
- // 0 disables fanout entirely (e.g. replay's single large consolidated event).
let (events, slots): (Vec<E>, Vec<Slot>) = if scatter_gather_threshold == 0
|| n < scatter_gather_threshold
{
@@ -234,7 +233,7 @@ mod tests {
use super::*;
use crate::ordering::OrderingGuarantee;
- use crate::pipeline::{Address, Lane, Pipeline};
+ use crate::pipeline::{Address, AnalyticsLane, PipelineLane};
use crate::v1::test_utils::test_context;
use crate::v1::types::Destination;
@@ -356,10 +355,7 @@ mod tests {
assert_eq!(prepared.partition_key, format!("key-{i}"));
assert_eq!(
prepared.address,
- Address::Lane {
- pipeline: Pipeline::Analytics,
- lane: Lane::Main
- }
+ Address::Lane(PipelineLane::Analytics(AnalyticsLane::Main))
);
}
}
diff --git a/rust/capture/src/v1/types.rs b/rust/capture/src/v1/types.rs
index 03b23bfefa32..8c5774a84c50 100644
--- a/rust/capture/src/v1/types.rs
+++ b/rust/capture/src/v1/types.rs
@@ -3,7 +3,7 @@ use uuid::Uuid;
use crate::event_restrictions::Pipeline;
use crate::ordering::OrderingGuarantee;
-use crate::pipeline::{self, Address, Lane};
+use crate::pipeline::{Address, AiLane, AnalyticsLane, BasicLane, PipelineLane};
use crate::v1::context::RequestContext;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
@@ -61,16 +61,19 @@ impl Destination {
}
pub fn address(&self) -> Address {
- let lane = |pipeline, lane| Address::Lane { pipeline, lane };
match self {
- Self::AnalyticsMain => lane(pipeline::Pipeline::Analytics, Lane::Main),
- Self::AnalyticsHistorical => lane(pipeline::Pipeline::Analytics, Lane::Historical),
- Self::AnalyticsOverflow => lane(pipeline::Pipeline::Analytics, Lane::Overflow),
- Self::AiMain => lane(pipeline::Pipeline::Ai, Lane::Main),
- Self::AiOverflow => lane(pipeline::Pipeline::Ai, Lane::Overflow),
- Self::ErrorTrackingMain => lane(pipeline::Pipeline::ErrorTracking, Lane::Main),
- Self::HeatmapsMain => lane(pipeline::Pipeline::Heatmaps, Lane::Main),
- Self::ClientWarningsMain => lane(pipeline::Pipeline::Warnings, Lane::Main),
+ Self::AnalyticsMain => Address::Lane(PipelineLane::Analytics(AnalyticsLane::Main)),
+ Self::AnalyticsHistorical => {
+ Address::Lane(PipelineLane::Analytics(AnalyticsLane::Historical))
+ }
+ Self::AnalyticsOverflow => {
+ Address::Lane(PipelineLane::Analytics(AnalyticsLane::Overflow))
+ }
+ Self::AiMain => Address::Lane(PipelineLane::Ai(AiLane::Main)),
+ Self::AiOverflow => Address::Lane(PipelineLane::Ai(AiLane::Overflow)),
+ Self::ErrorTrackingMain => Address::Lane(PipelineLane::ErrorTracking(BasicLane::Main)),
+ Self::HeatmapsMain => Address::Lane(PipelineLane::Heatmaps(BasicLane::Main)),
+ Self::ClientWarningsMain => Address::Lane(PipelineLane::Warnings(BasicLane::Main)),
Self::Dlq => Address::Dlq,
Self::Custom(topic) => Address::Custom(topic.clone()),
}
@@ -118,25 +121,19 @@ mod destination_tests {
}
#[rstest::rstest]
- #[case(Destination::AnalyticsMain, Some(V0Destination::AnalyticsMain))]
- #[case(
- Destination::AnalyticsHistorical,
- Some(V0Destination::AnalyticsHistorical)
- )]
- #[case(Destination::AnalyticsOverflow, Some(V0Destination::AnalyticsOverflow))]
- #[case(Destination::Dlq, Some(V0Destination::Dlq))]
- #[case(Destination::Custom("admin_topic".into()), Some(V0Destination::Custom("admin_topic".into())))]
- #[case(Destination::ErrorTrackingMain, Some(V0Destination::ErrorTrackingMain))]
- #[case(Destination::HeatmapsMain, Some(V0Destination::HeatmapsMain))]
- #[case(
- Destination::ClientWarningsMain,
- Some(V0Destination::ClientWarningsMain)
- )]
- #[case(Destination::AiMain, Some(V0Destination::AiMain))]
- #[case(Destination::AiOverflow, Some(V0Destination::AiOverflow))]
+ #[case(Destination::AnalyticsMain, V0Destination::AnalyticsMain)]
+ #[case(Destination::AnalyticsHistorical, V0Destination::AnalyticsHistorical)]
+ #[case(Destination::AnalyticsOverflow, V0Destination::AnalyticsOverflow)]
+ #[case(Destination::Dlq, V0Destination::Dlq)]
+ #[case(Destination::Custom("admin_topic".into()), V0Destination::Custom("admin_topic".into()))]
+ #[case(Destination::ErrorTrackingMain, V0Destination::ErrorTrackingMain)]
+ #[case(Destination::HeatmapsMain, V0Destination::HeatmapsMain)]
+ #[case(Destination::ClientWarningsMain, V0Destination::ClientWarningsMain)]
+ #[case(Destination::AiMain, V0Destination::AiMain)]
+ #[case(Destination::AiOverflow, V0Destination::AiOverflow)]
fn address_matches_the_v0_destination(
#[case] destination: Destination,
- #[case] expected: Option<V0Destination>,
+ #[case] expected: V0Destination,
) {
let v0 = V0Destination::for_address(destination.address());
assert_eq!(v0, expected);