: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): outputs plan, routing goldens, pure route(), output registry (#74228)
Paweł Ledwoń2ad50086453a
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.mdnew file mode 100644index 000000000000..38197e43f697--- /dev/null+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md@@ -0,0 +1,289 @@+# Capture outputs refactor — implementation plan++Working contract for implementation agents. This doc is the first commit of the draft PR; each `Step N` below becomes one commit in this combined PR and later graduates to its own standalone PR.++## Motivation++Three drivers, in order:++1. **Safe automatic failover**: Kafka-primary / S3-secondary failover as an output policy over any two targets, driven by a health breaker.+2. **Cluster migrations without code changes**: split (AI → WarpStream) and dual-write become configuration of an output's targets, as in the Node.js `IngestionOutputs` module — capture and Node converge on the same model.+3. **Payload format evolution**: a protobuf cutover becomes an output-level config change behind the serialization seam, rolled out with content-header coexistence like the replay lz4 envelope.++None of these fit the current shape: routing policy, serialization choice, and multi-target behavior are all tangled into the sink layer, so every one of them requires new sink composites with information smuggled through serialized records.++## Target architecture++Layer `rust/capture`'s produce path into five strata with one-way dependencies:++```text+edge → Pipeline {Analytics, Heatmaps, Warnings, ErrorTracking, Replay}+pipeline steps → stamp intent (restrictions, overflow, historical)+lane resolution → Lane {Main, Overflow, Historical, Dlq, Custom} + key policy + headers+outputs → (Pipeline, Lane) → output = 1..n targets + selection policy+ (single | failover(health) | split(token) | dual-write(pct))+serialization → per-output: format (json | protobuf…) × envelope (none | lz4);+ stamps content-type/encoding headers; produces sink-agnostic payload+sinks → single backend: wrap payload into wire record (topic/key vs object key),+ enqueue, ack. Kafka, S3, print, noop.+```++- **Pipeline** is decided at the edge (endpoint + event name) — the high-level "which product stream is this" classification.+- **Lane** is decided once, at the end of a pipeline, by folding the intent stamped during processing (restrictions, overflow reasons, historical flag) through one precedence chain. Today that chain is `route()` inside the Kafka sink; it moves up and runs before anything is serialized.+- **Output** is the named destination an event is published to, addressed by `(Pipeline, Lane)`. An output owns 1..n targets and the policy that picks between them per batch. All multi-target behavior lives here and only here.+- **Serialization** is a contract with the *consumers of a destination*, not a property of a transport. Each output names its format and envelope; the produced payload is sink-agnostic bytes plus the content headers that let old and new encodings coexist on a topic during migration (the existing replay lz4 `content-encoding` design, generalized).+- **Sink** is a single backend. It turns an addressed, serialized payload into its wire shape and acks it. It reads no event metadata and makes no decision.++## Starting point++Steps 1–3 land together with this doc: the routing golden oracle, the pure `route()`, and the `OutputRegistry` with its startup completeness check. Production call sites still publish through the v0 `Event` trait (`send` / `send_batch`); the v1 stack (`CAPTURE_V1_SINKS`, opt-in) still runs its own serialize-then-publish pipeline with a per-event response model. The v1 `PreparedEvent { uuid, destination, payload: Bytes, headers, partition_key }` is the shape our output→sink handoff adopts.++### Vocabulary rules++- An event's **Address** is a lane of its pipeline (lanes typed per pipeline — `AnalyticsLane`, `AiLane`, `SessionReplayLane`, `BasicLane` — so invalid pairs are unrepresentable), or an admin **custom redirect** that carries its own topic outside the lane model. Pipeline and lane kind are projections; construction goes through `resolve`. Never reintroduce a flat destination enum that conflates pipeline and lane.+- **Output** = the addressed destination: targets + selection policy + serializer. **OutputTable** = the `(Pipeline, Lane)` → output mapping with the per-mode completeness check. The Step-3 `OutputRegistry` (output → topic) is absorbed into the table's targets.+- **Sink** = backend mechanism. Kafka, S3, print, noop. Nothing else is a sink; a thing that picks between sinks is an output policy.+- **Serializer** = format × envelope. Formats and envelopes compose; neither knows about sinks or outputs.++### Invariants++- Metric names and labels stay stable: `capture_events_rerouted_*`, `capture_primary_sink_health`, `capture_fallback_sink_failovers_total`, `capture_split_sink_selected`, `capture_failover_breaker_*`, `capture_event_batch_size`. Renames are out of scope for every step.+- Wire parity is proven by the Step-1 goldens and existing endpoint/integration tests passing **unmodified**, except where a step explicitly says otherwise.+- Never mix a mechanical move with a behavior change in one commit.+- Every step ships green (`cargo test -p capture`, clippy `-D warnings`, fmt) and rolls back by plain revert.+- The per-event response model (v1 `BatchResponse`) stays out of scope; call sites keep folding per-event results into today's whole-request `CaptureError`.+- Sinks read no `ProcessedEventMetadata`. After Step 6 the only consumer of routing metadata is lane resolution.++## The stages and steps++### Stage A — oracle and groundwork++#### Step 1 · Consolidate the routing golden oracle++The `assert_routing` suite pins topic + partition key + every stamped header + the rerouted counters for all pipelines and lanes. It is the parity instrument for every later step.++#### Step 2 · Extract routing into a pure `route()`++`route(&ProcessedEventMetadata, ai_events_overflow_armed) -> Result<Route { target, ordering }, CaptureError>`, consulted by the sink.+The decision is the target `Output` plus the customer-facing `OrderingGuarantee` the sink realizes as a partition key; side effects are implied by the target rather than carried as decision data, the AI overflow valve rides in as an explicit argument to keep the function pure, and a replay decision with no session id is rejected rather than returned unrealizable.+This is the function Step 5 hoists out of the sink into lane resolution.++#### Step 3 · `OutputRegistry` + startup completeness check++One output→topic wiring point plus refuse-to-boot on a blank topic, gated behind `CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED` (default off; see Step 9's arming precondition).+Step 7 absorbs it into the `OutputTable`; the mode-scoped demand is folded in at Step 9, where `(Pipeline, Lane)` makes the per-mode reachable set explicit.++### Stage B — the two new seams (no caller-visible change)++#### Step 4 · Serialization layer: format × envelope++- **Goal.** New `serialization` module: `Format` (event → payload bytes + `content-type`) with `Json` as the only impl, `Envelope` (bytes → bytes + `content-encoding`) with `None` and `Lz4` (the replay 4-byte LE size-prefix block format, moved verbatim), and a `Serializer` composing one of each. `prepare_record` calls the serializer instead of inlining `serde_json::to_string` + the lz4 branch. Replay's serializer is `Json × Lz4` when `kafka_replay_envelope_compression` says so; everything else `Json × None`.+- **Explicitly not in the serializer:** partition keys, routing headers, topics. Bytes and content headers only.+- **Files.** `rust/capture/src/serialization/` (new); `rust/capture/src/sinks/kafka.rs` (`prepare_record` consumes it).+- **Parity proof.** Step-1 goldens unmodified — including the lz4 goldens and `content-encoding` assertions. New unit tests on format/envelope composition.+- **Risk / rollback.** Low — mechanical hoist. Revert.+- **Size.** M.++#### Step 5 · `Pipeline` + `Lane`; the lane decision becomes pipeline-layer code++- **Goal.** Introduce the address pair and relocate the decision logic:+ - `Pipeline { Analytics, Heatmaps, Warnings, ErrorTracking, Replay }` (`Pipeline::from_data_type` extracts the pipeline half of `DataType`).+ - `Lane { Main, Overflow, Historical, Dlq, Custom(&str) }`.+ - `pipeline::resolve(&ProcessedEventMetadata) -> Result<LaneDecision { pipeline, lane, ordering }, CaptureError>` — Step-2's `route()` moved out of the sink module wholesale, precedence unchanged (dlq > custom > historical > overflow > main), pure (no counters, no headers, no I/O). `OrderingGuarantee` moves with it as decision *data*.+ - The sink keeps a private `output_for((pipeline, lane)) -> Output` bridge and still *invokes* `resolve` from its prep path — the invocation site moves up in Step 7 when the outputs layer exists to own it. This keeps the commit a pure relocation: no metadata changes, no call-site changes, goldens byte-identical.+- **Files.** `rust/capture/src/pipeline.rs` (new); `rust/capture/src/sinks/kafka.rs` (drops `route()`/`Route`/`OrderingGuarantee`, gains the `output_for` bridge); `rust/capture/src/lib.rs`.+- **Parity proof.** Step-1 goldens unmodified. `route()`'s precedence tests move to `pipeline::tests` with assertions preserved, plus a pipeline classification test.+- **Risk / rollback.** Low-medium — mechanical relocation. Revert.+- **Size.** M/L.++### Stage C — sinks become mechanism, outputs become the API++#### Step 6 · Narrow the Kafka sink to backend mechanism++- **Goal.** New `sinks/sink.rs`: `PreparedPayload { uuid, record: ProduceRecord }` (serialized, addressed) is the sink input; `trait Sink { publish(Vec<PreparedPayload>) -> Vec<SinkResult>; flush() }` — no prepare on the trait, no metadata access — plus `Outcome` and `fold_results` (first failure wins). Kafka: `prepare_batch` (serial <8 / scatter-gather ≥8, fail-fast) extracted from `send_batch` as an inherent method the outputs layer will call; `impl Sink` = serial enqueue + fail-fast ack drain, reporting batch-uniform per-event results (the per-event surface refines only with the response model). `Event::send_batch` becomes the bridge: prep → publish → fold. Kafka only — s3/print/noop gain mechanism impls with the outputs layer, which is what needs them.+- **Sequencing decision.** `FallbackSink` and `SplitKafkaSink` are never ported onto the mechanism trait: the outputs layer owns multi-target policies (single | failover | split) from its first commit, built from the same config, and the Event-era composites are deleted when their last caller migrates.+- **Files.** `rust/capture/src/sinks/sink.rs` (new), `rust/capture/src/sinks/kafka.rs`, `rust/capture/src/sinks/mod.rs`.+- **Parity proof.** Step-1 goldens + `send_batch` three-phase suite unmodified (they now drive prep → publish → fold — the exact production path).+- **Risk / rollback.** Medium-high — core mechanism. Revert.+- **Size.** L.++#### Step 7 · Outputs layer with policies; composites retired++- **Goal.** New `outputs` module — the produce surface, with multi-target policy ownership from day one:+ - `Output`: a single backend, or a policy composing two *outputs* — `failover` (health-gated Kafka→S3: skip primary while the advisory handle is unhealthy, re-publish the batch on a retriable failure, fatal never fails over) and `split` (token-routed AI secondary). Targets are outputs themselves, so policies compose the way the old composites did (split over a failover pair). Policies operate on *events*, before prep — each target resolves topics and serializes for itself, exactly like the old per-sink `send_batch` paths, so parity is structural.+ - Leaves run the dance internally via the `pub(crate)` `Prepare` trait (prep → publish → fold); no caller ever sees a two-phase protocol.+ - `OutputTable`: the `(pipeline, lane)` → output handle the state holds; degenerate today (one deployment-wide output; per-lane topics resolve in prep via the `OutputRegistry`).+ - `setup::create_output` builds the policy tree from the same config; **`FallbackSink` and `SplitKafkaSink` are deleted**, their tests re-expressed on `Output` with assertions preserved (+ a new fatal-no-failover case).+ - Call sites are untouched: the table serves them through a transitional `Event` facade (which records `capture_event_batch_size`, where the old sink impls recorded it). Migration is Step 8.+- **Files.** `rust/capture/src/outputs.rs` (new); `rust/capture/src/setup.rs`; `rust/capture/src/sinks/{mod,s3,print,noop,test_sink}.rs` (mechanism + `Prepare` impls); `fallback.rs`/`split.rs` deleted.+- **Parity proof.** Goldens + all integration suites unmodified. Known metrics-only deltas, accepted: the batch-size histogram now records on the fallback-to-S3 path (it silently didn't before), and print/noop single sends record it (they didn't).+- **Risk / rollback.** Medium. Revert.+- **Size.** L.++#### 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 `OutputTable::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.+- **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.++### Stage D — completeness, dark failover, convergence++#### Step 9 · Mode-scoped registry completeness++- **Goal.** `OutputRegistry::check_complete` scopes its demand per `CaptureMode`: an Events/Ai pod demands the analytics family, a Recordings pod main/replay-overflow/dlq only.+- **Arming precondition.** `CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED` stays off in every deployment until this step lands and the chart env is audited for explicitly-blank topic values.+ The mode-blind check demands every registered topic on every pod, so a recordings or import deployment that sets an analytics topic to `""` would crashloop the fleet at boot, not degrade.+- **Parity proof.** Per-mode refusal + anti-over-demand tests.+- **Size.** M.++#### Step 10 · Breaker failover mode (dark)++- **Goal.** `FailoverMode::Breaker` — a pure clock-injected `Breaker` state machine, half-open single-probe permit, and a `StaticControlPlane` seam, as the second failover mode, dark behind `failover_enabled` (default off; off ⇒ Advisory mode byte-identical).+- **Parity proof.** 13+ deterministic breaker unit tests; four output-level behavior tests (healthy-primary, open→fallback→recover cycle, control-plane-down, fatal-no-failover). The effective-route gauge harness and a Notify-gated probe-concurrency harness graduate with the feature when it leaves dark mode.+- **Size.** M.++#### Step 11 · v1 converges on the shared strata++- **Goal.** v1's `Destination` bridges to `(Pipeline, Lane)`; v1 topic resolution goes through the shared table; v1's `serialize_batch` uses the Step-4 serializer. The v1 `Sink`/`Router` trait convergence stays gated on the per-event response model, as before.+- **Parity proof.** v1_pipeline (17) + v1_sink_integration (10) unmodified, plus `overflow_parity.rs` unmodified. That suite drives both pipelines end to end over the overflow and rate-limit matrix and is the oracle for the ordering-vs-person-processing contract this step has to carry across (see the Hazard note under "v1 convergence on the outputs machinery"). Both paths already share `OrderingGuarantee` from `crate::ordering`.+- **Size.** M/L.++### Stage E — prep hoists up; sinks become pure transport++#### Step 12 · Prep hoists into the outputs layer; `Prepare` retired++- **Goal.** Sinks take prepared payloads as input, full stop. `PrepSpec` (registry + per-destination serializers) moves payload assembly — lane resolution, serialization, header stamps, topic and partition key, and the scatter-gather batch prep — into the outputs layer; the `(pipeline, lane)` → output bridge and the `OutputRegistry` move with it (`outputs::registry`). The `Prepare` trait is deleted; every backend (Kafka, S3, print, noop) preps identically via its output's spec, and the Kafka sink is reduced to producer + enqueue + ack drain. The boot completeness check moves to `setup::create_output`.+- **Test posture change (deliberate).** Capturing mocks intercept *published payloads*, not `ProcessedEvent`s, so ~60 assertions that read metadata stamps migrate to wire-level outcomes: topic, partition key, headers, and payload bytes (deserialized for content checks). The declarative `ExpectedEvent` checkers recompute the expected record from the same expectations, so test bodies stay put. Wire-level assertions also pin a semantic the metadata-level ones couldn't see: replay events redirected to dlq/custom topics partition on the event key, not the session id.+- **Known deltas, accepted:** print/noop deployments run the real prep path (lane effects and their counters included), and prep can fail there (e.g. `MissingSessionId`) where the old passthrough couldn't. The prep histograms keep their `capture_kafka_*` names for dashboard continuity.+- **Files.** `outputs/mod.rs`, `outputs/registry.rs` (moved), `sinks/*`, `setup.rs`, all capturing test mocks.+- **Size.** L.++### Per-mode output tables (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.++### Per-pipeline output overrides and boot verification (Step 18)++Each row of a deployment's table can be retargeted independently: `CAPTURE_OUTPUT_<PIPELINE>_BROKERS` points a pipeline's row at another cluster, `CAPTURE_OUTPUT_<PIPELINE>_TOPIC_<LANE>` renames a lane's topic in that row's namespace (existing `KAFKA_*` keys stay the defaults). The row factory builds one sink per pipeline, each with its own `TopicTable` (base config overlaid with that pipeline's overrides via `TopicTable::with_overrides`); producers are shared per distinct broker set, so the no-override configuration still opens exactly one connection. The gating liveness handle lands on the cluster carrying the deployment's ingress pipeline; other clusters' producers are non-gating. Overrides compose only with the plain per-row Kafka path — combining them with S3 fallback or AI secondary routing is refused at boot, since those policy trees assume every row shares one primary cluster.++`CAPTURE_VERIFY_TOPICS_ON_BOOT` (default off) probes cluster metadata for every topic a row can produce to — pipeline-scoped (`TopicTable::topics_for_pipeline`), so an overridden row probes only its own cluster's namespace — and refuses to start on a missing topic. Off by default because brokers with topic auto-creation make the check misleading (the metadata probe itself can create the topic).++### Outputs as an open trait (Step 19)++`Outputs` is an open trait — a produce surface handling every destination its configuration maps — replacing the closed policy enum. Implementations own payload assembly, namespace realization, backend composition, and policy: `KafkaOutputs` (one cluster: prep + address→topic table + transport sink), `S3Outputs`, `PrintOutputs`/`NoopOutputs`, `FailoverOutputs` and `SplitOutputs` (policies over `Arc<dyn Outputs>`), and the per-mode tables themselves (dispatch-by-pipeline is just another surface; capability traits are markers over `Outputs`). Sinks are pure transport and never see an `Address`: the Kafka sink publishes realized records (concrete topic, key, payload, headers); namespace realization lives in the outputs layer. `publish` reports per-event `SinkResult`s (a provided `publish_folded` collapses to the v0 whole-request response) — the granularity v1's `BatchResponse` requires.++A test-only prototype (`outputs::dynamic`) demonstrates the coordinator-managed surface: `DynamicKafkaOutputs` subscribes to an in-process `KafkaManagerService` (RPC-shaped, acked config pushes) and applies broker add/remove and mapping changes with an enabled-partition set per address — the incremental, key-deterministic drain-and-switch — with tests simulating a topic switchover and a broker switchover end to end.++### v1 convergence on the outputs machinery (Step 20)++Goal: v1 endpoints publish through `dyn Outputs` like every other ingress, so fallback/split/dynamic policies apply uniformly. Plan:++1. **Boundary mapping.** After v1 processing (destination decided, result stamped), map each publishable `WrappedEvent` into `ProcessedEvent`: the existing v1 serialize path already produces CapturedEvent-compatible payloads, so the mapping builds the `CapturedEvent` plus a `ProcessedEventMetadata` that makes `pipeline::resolve` reproduce the decided destination (AnalyticsMain → main; Overflow → force_overflow; Historical → historical data type; Dlq → redirect_to_dlq; Custom → redirect_to_topic). `Destination::Drop` events never reach the outputs layer — dropping is a processing decision, recorded in the response.+2. **Named surfaces.** `CAPTURE_V1_SINKS` names become named `Arc<dyn Outputs>` rows (each a `KafkaOutputs` built from that sink's config); the v1 `Router`/`Sink`/`Event` traits and `serialize_batch` dissolve.+3. **Response granularity.** `Outputs::publish` already returns per-event `SinkResult`s; `merge_sink_results` consumes them unchanged.+4. **Parity oracle.** The v1 pipeline tests and the real-Kafka `v1_sink_integration` suite must pass against the converged path — payload bytes, headers, topics, keys. Documented v1-vs-v0 header deltas (overflow/person-processing decoupling) must be preserved in the mapping, not silently erased. The legacy serializer/header builder survive only as a frozen `cfg(test)` oracle (`legacy_serialize`/`legacy_headers`) the parity suite compares against.+5. **Plan retirement.** The 20c commit deletes this document — the plan must not outlive its last step.+ Anything still load-bearing then (the repartitioning design note, the ordering-vs-person-processing contract) graduates into module docs or `v1/sinks/DESIGN.md` first.++**Hazard.** The `Destination::Overflow` → metadata mapping must preserve the split between the two intents that ride together on this lane: whether person processing is disabled (a customer-visible instruction, the `force_disable_person_processing` header) and whether the partition key is dropped (a load decision, `OrderingGuarantee`). Both paths now state the same rule, so the mapping has one contract to satisfy rather than two dialects to reconcile:++- The header follows the stamped person-processing intent: the flag, which a `ForceLimited` reason implies on its own (`person_processing_disabled`), so a v0 stamping site cannot keep person processing on for a force-limited key by forgetting the flag.+ v1 carries no reason on the event — its one stamping site sets the flag directly.+- The key is dropped on the analytics main/overflow lanes when the person-processing flag is set, and on the AI overflow lane when either the flag or a spread decision is set — nowhere else.+ The analytics consumers update persons keyed on distinct id, so a person-on burst keeps its key there (spreading one distinct id across partitions contends those updates); the read-only AI overflow consumer takes keyless person-on records safely.+ Historical, dlq, custom redirects and the AI main topic keep the key regardless.++`overflow_parity.rs` is the oracle: it drives both pipelines over the overflow and rate-limit matrix and pins lane, key presence, and header. Extend it with the mapped v1 destinations rather than reasoning about the two paths separately.++**Accepted deltas:** `sent_at` fractional-second formatting (parse-equal; v1 adopts v0's serializer) and the v1 sink-stage metrics (`capture_v1_serialize_*`, per-sink publish metrics), superseded by the outputs-layer metrics.++### AI pipeline and Import mode++- **AI pipeline membership is stamp-based, not name-based.** The per-batch-token `AiRouting` divert decision (`CAPTURE_ANALYTICS_AI_EVENTS_MODE` + allowlist/percentage) stamps `DataType::AiEvents` during processing, mirroring v1's `Destination::AiEvents`; `Pipeline::from_metadata` maps the stamp. An undiverted `$ai_*` event is a plain analytics event on the analytics lanes — the multipart/OTEL AI ingress stamps `AnalyticsMain` and publishes to the analytics rows. `AI_EVENT_PREFIX` remains only for the quota predicate and the stamping decision.+- **The AI lanes own dedicated topics.** `TopicTable` grows optional `ai_events` / `ai_events_overflow` rows (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` / `..._OVERFLOW_TOPIC`); there is no `AiLane::Historical` — the divert decision wins over historical, matching v1. The AI overflow valve (overflow topic set) rides `PrepSpec` into `resolve`, so an unarmed deployment never routes the AI lane to overflow, force_overflow included.+- **Import mode** is an analytics-family deployment on `router::router`; it mounts `/i/v0/ai/batch` (gated batch handler) but not the ai/otel handlers, and shares the Events topic requirements.++## Repartitioning coordinator (design note)++Not built in this PR; this note records where it plugs in so nothing landed here has to move. The goal: switch a deployment between clusters partition by partition — drain-and-switch with minimal delay — driven by a coordinator, with sinks staying pure mechanism.++**Logical shards, decided before the sinks.** The coordinator owns a stable shard function: `shard = hash(key) % N` over the same partition key the sink would hash, with coordinator-owned `N` (not either cluster's partition count). The shard is stamped at prep time — `AddressedPayload` grows `shard: Option<u32>`, `None` meaning "let the producer partition as today". Stamping at prep keeps the decision above the sinks: both clusters of a failover pair see the same shard on the same payload, so a switchover decision is consistent across targets by construction.++**A `ShardRouted` output policy.** Routing lives in the outputs layer as a policy node holding two child outputs (old cluster, new cluster) and a swappable assignment table `shard → Old | New` (an `ArcSwap`, updated by the coordinator's control plane the same way the failover breaker's control plane seam works). Batch publish splits by assignment and forwards — scatter-gather like `Split`, no serialization changes (both clusters share the prep/serialization contract, as the AI-secondary split already proves).++**Explicit partition pass-through in the sink.** `ProduceRecord` grows `partition: Option<i32>`; the Kafka sink maps `shard` to a concrete partition of its own topic (its table realizes the namespace; a shard→ partition map is the same kind of sink-side data as topic names) and sets it on the record. `None` keeps today's key hashing. The sink still makes no routing decisions — it realizes an address (topic) and a shard (partition) in its own namespace.++**Per-partition fence (drain-and-switch).** Moving shard `s` from Old to New, without reordering a key's events across clusters:++1. **Swap** the assignment entry for `s` — new publishes head to New but are *held* (the policy parks `s`-payloads in a short buffer).+2. **Quiesce**: wait for in-flight `s`-publishes accepted before the swap to resolve (the outputs layer already tracks per-payload acks — `SinkResult` — so this is a count, not a scan).+3. **Flush** Old's producer for the affected partition (producer-level `flush`, already a `Sink` trait method).+4. **Watermark**: record Old's end offset for the partition; the consumer side treats it as the fence — consume Old to the watermark, then start New. Only then release the held `s`-payloads to New.+5. **Handoff complete**; rollback is the same protocol with Old/New reversed. Failure inside the fence window falls back to releasing to the still-assigned side (the swap is not observable until step 4 completes).++The hold window is per-shard and bounded by one producer flush — that is the "minimal delay" drain. Shards move independently, so the deployment migrates partition by partition.++**Keyless traffic needs no fence.** `OrderingGuarantee::None` payloads (anonymous analytics without ordering constraints) have no per-key ordering contract — they switch clusters with a bare assignment swap, no hold/flush/watermark. Replay is keyed by session and follows the fenced path; dlq/custom redirects partition on the event key (`token:distinct_id`), same as main.++**Seam inventory:**++- `AddressedPayload` — carries key + address; grows `shard`.+- Outputs policy tree — `ShardRouted` slots in beside single/failover/split.+- Breaker control-plane seam — the pattern for the coordinator's assignment updates (swappable state, no request-path locks).+- `ProduceRecord` — grows `partition`; sinks realize shard → partition.+- Per-pipeline rows + topic tables (Step 18) — a coordinator can retarget one pipeline's row without touching the rest of the deployment.++## End state++When all steps land, the five strata hold:++- **Pipelines and lanes.** `pipeline::resolve` is the one lane decision (dlq > custom > historical > overflow > main), pure over `ProcessedEventMetadata`; `Pipeline`/`Lane` are the event's address.+- **Outputs are the produce surface.** Every pipeline publishes through the `OutputTable`; the `Output` policy tree (single | failover | split) owns all multi-target behavior, composing the way the old sink composites did. The v0 `Event` trait, `FallbackSink`, and `SplitKafkaSink` are gone.+- **Serialization is a seam.** Format × envelope per destination, with content headers carrying encoding coexistence (the lz4 replay design, generalized); a protobuf cutover is an output-level config change.+- **Sinks are mechanism, and own their namespace.** Payloads carry the abstract `Address`; each sink realizes it in its own namespace at publish time (Kafka: its per-cluster topic table — the swappable seam a repartitioning coordinator plugs into; S3: the buffer path; print/noop: trivially). Sinks make no routing decisions; a failover pair can share one prepared batch because payloads are target-agnostic. Serialization stays output-level (a consumer contract, shared across targets).+- **Breaker failover is dark-launched** behind `CAPTURE_FAILOVER_ENABLED` as the failover output's autonomous mode.+- **v1 resolves topics through the shared `OutputRegistry`** via `Destination::as_output`. The v1 `Sink`/`Router` trait convergence stays gated on the per-event response model.++## Agent conventions++**Build / test.** All cargo commands run via `flox activate -- cargo <cmd>` from `rust/`.++**Acceptance per step:**++- `flox activate -- cargo test -p capture` — scope to the named suites where the full run is slow; the Step-1 goldens always run.+- `flox activate -- cargo clippy -p capture --all-targets -- -D warnings`+- `flox activate -- cargo fmt`++**Git.** The orchestrator commits each step; one step = one commit, subject from the tracker below. No `--no-verify` — pre-commit hooks must pass.++## Progress tracker++| Step | Status | Commit subject |+| --- | --- | --- |+| 0 · This plan doc | done | `docs(capture): outputs refactor plan and progress tracker` |+| 1 · Routing golden oracle | done | `test(capture): consolidate routing golden oracle with headers and counters` |+| 2 · Pure `route()` | done | `refactor(capture): extract pure route() from prepare_record` |+| 3 · `OutputRegistry` + completeness | done | `refactor(capture): output registry with startup completeness check` |+| 4 · Serialization layer | pending | `refactor(capture): serialization layer — format and envelope behind one seam` |+| 5 · `Pipeline` + `Lane`; lane resolution | pending | `refactor(capture): pipeline and lane address; lane decision moves to the pipeline layer` |+| 6 · Kafka sink → backend mechanism | pending | `refactor(capture): narrow the kafka sink to backend mechanism over prepared payloads` |+| 7 · Outputs layer with policies; composites retired | pending | `feat(capture): outputs layer owns failover and split policies` |+| 8a · Call sites on the table | pending | `refactor(capture): call sites publish through outputs` |+| 8b · `Event` retired | pending | `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; `Prepare` 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` |+| 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` |+| 19a · Naming and import hygiene | pending | `refactor(capture): replace remaining nested paths with imports` + `refactor(capture): name the session replay pipeline consistently` |+| 19b · Outputs as an open trait; sinks pure transport | pending | `refactor(capture): outputs own namespace realization; Outputs becomes an open trait` |+| 19c · Dynamic outputs prototype | pending | `feat(capture): prototype dynamic outputs with incremental switchover (test-only)` |+| 19d · Per-event publish results | pending | `refactor(capture): Outputs::publish reports per-event results` |+| 20a · v1 boundary mapping + parity oracle | pending | `feat(capture): v1 boundary mapping onto the shared produce interchange` |+| 20b · v1 publishes through shared outputs | pending | `feat(capture): v1 endpoints publish through the shared outputs machinery` |+| 20c · Legacy v1 sink stack deleted; this plan retired | pending | `refactor(capture): delete the legacy v1 sink stack` |diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex 62ceff25cbe6..3edb28def8aa 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -494,6 +494,14 @@ pub struct KafkaConfig {/// Set to "lz4" to enable. Default "none" for safe rollout and rollback.#[envconfig(default = "none")]pub kafka_replay_envelope_compression: EnvelopeCompression,+ /// Refuse to boot when a registered output resolves to an empty topic+ /// name (see `OutputRegistry::check_complete`). Config-only — the broker+ /// is never probed, so topic autocreation on first publish is unaffected.+ /// Opt-in (default off) so deployments that deliberately blank a topic+ /// they never produce to keep booting; arm it per deployment once its+ /// topic wiring is known-complete.+ #[envconfig(from = "CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED", default = "false")]+ pub outputs_completeness_check_enabled: bool,pub kafka_hosts: String,#[envconfig(default = "events_plugin_ingestion")]pub kafka_topic: String,diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rsindex 39e5972fd002..9ad2a5045905 100644--- a/rust/capture/src/events/analytics.rs+++ b/rust/capture/src/events/analytics.rs@@ -2768,8 +2768,16 @@ mod tests {);}+ /// A person-on burst keeps its key on either locality setting: the+ /// overflow consumer updates persons keyed on distinct id, so spreading+ /// one distinct id across partitions would contend those updates.+ #[rstest]+ #[case::preserving_locality(true)]+ #[case::spreading(false)]#[tokio::test]- async fn e2e_rate_limited_preserve_locality_pipeline_to_sink_keeps_key() {+ async fn e2e_rate_limited_pipeline_to_sink_keeps_key_while_person_on(+ #[case] preserve_locality: bool,+ ) {let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z").unwrap().with_timezone(&Utc);@@ -2786,8 +2794,8 @@ mod tests {));let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());let historical_cfg = router::HistoricalConfig::new(false, 1);- // burst=1, preserve_locality=true => event[1] stamped RateLimited{preserve_locality: true}.- let limiter = build_limiter(1, 1, None, true);+ // burst=1 => event[1] stamped RateLimited { preserve_locality }.+ let limiter = build_limiter(1, 1, None, preserve_locality);process_events(sink,@@ -2817,7 +2825,7 @@ mod tests {);assert!(records[1].key.is_some(),- "RateLimited{{preserve_locality:true}} must preserve partition key"+ "a person-on burst must keep its partition key");assert!(records[1].headers.force_disable_person_processing.is_none(),@@ -2825,52 +2833,6 @@ mod tests {);}- #[tokio::test]- async fn e2e_rate_limited_no_preserve_locality_pipeline_to_sink_drops_key() {- let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")- .unwrap()- .with_timezone(&Utc);- let context = create_test_context(now, None);- let events = vec![- create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None),- create_test_event(Some("2023-01-01T11:00:00Z".to_string()), None, None),- ];-- let producer = MockKafkaProducer::new();- let sink = Arc::new(KafkaSinkBase::with_producer(- producer.clone(),- test_topics(),- ));- let dropper = Arc::new(limiters::token_dropper::TokenDropper::default());- let historical_cfg = router::HistoricalConfig::new(false, 1);- // burst=1, preserve_locality=false => event[1] stamped RateLimited{preserve_locality: false}.- let limiter = build_limiter(1, 1, None, false);-- process_events(- sink,- dropper,- None,- historical_cfg,- None,- Some(limiter),- None,- None,- &AiRouting::Primary,- events,- &context,- )- .await- .unwrap();-- let records = producer.get_records();- assert_eq!(records.len(), 2);- assert_eq!(records[1].topic, "events_plugin_ingestion_overflow");- assert_eq!(- records[1].key, None,- "RateLimited{{preserve_locality:false}} must drop partition key"- );- }-// ============ heatmap redirect tests ============/// Two shapes of input event qualify for a heatmap redirect: an eventdiff --git a/rust/capture/src/events/overflow_stamping.rs b/rust/capture/src/events/overflow_stamping.rsindex 28fd74dc4c01..bd12f7f457f9 100644--- a/rust/capture/src/events/overflow_stamping.rs+++ b/rust/capture/src/events/overflow_stamping.rs@@ -61,8 +61,9 @@ use crate::v0_request::{DataType, OverflowReason, ProcessedEvent};/// * If the lane's limiter is `Some`, `is_limited(event.key())` is consulted/// and the resulting [`OverflowReason`] is stamped, plus the matching/// counter. `ForceLimited` additionally sets `skip_person_processing =-/// true` so the sink's generic skip-person branch picks up the-/// `force_disable_person_processing` header without a separate code path.+/// true` for pipeline-level readers of the flag; the sink derives the+/// `force_disable_person_processing` header from the reason itself, so+/// the header does not depend on this stamp.////// Counter labels are intentionally identical to the pre-refactor sink so/// existing dashboards (filtering on `capture_events_rerouted_overflow`'s@@ -101,13 +102,11 @@ pub fn stamp_overflow_reason().increment(1);event.metadata.overflow_reason = Some(OverflowReason::ForceLimited);- // Self-describing metadata: ForceLimited implies person- // processing is skipped. Pre-refactor the sink inferred this- // from the limiter result; now we stamp it alongside the- // reason so the sink's generic skip-person path handles it- // uniformly. Kafka output is byte-identical — the sink's- // ForceLimited arm still sets the header redundantly as- // defense against a future caller stamping reason-only.+ // ForceLimited implies person processing is skipped; the sink+ // derives that from the reason itself+ // (`person_processing_disabled`). The flag is stamped+ // alongside so pipeline-level readers of the flag see the+ // same truth.event.metadata.skip_person_processing = true;}OverflowLimiterResult::Limited => {diff --git a/rust/capture/src/lib.rs b/rust/capture/src/lib.rsindex 53102fd2deff..069db9750980 100644--- a/rust/capture/src/lib.rs+++ b/rust/capture/src/lib.rs@@ -10,7 +10,11 @@ pub mod global_rate_limiter;pub mod ingestion_warnings;pub mod log_util;pub mod metrics_middleware;+pub mod ordering;pub mod otel;+/// Cross-path parity suite for the v0 and v1 overflow / rate-limit matrix.+#[cfg(test)]+mod overflow_parity;pub mod payload;pub mod prometheus;pub mod quota_limiters;diff --git a/rust/capture/src/ordering.rs b/rust/capture/src/ordering.rsnew file mode 100644index 000000000000..d4f5d616a48f--- /dev/null+++ b/rust/capture/src/ordering.rs@@ -0,0 +1,43 @@+//! The ordering guarantee a produced record preserves.+//!+//! Shared by both produce paths so they name one concept: the v0 sink's+//! `route()` and the v1 `Event::ordering` impls each decide a guarantee, and+//! each sink realizes it as a Kafka partition key. Keeping the vocabulary in+//! one place is what lets the two paths be compared case for case by the+//! cross-path overflow parity suite.++/// The ordering guarantee a route preserves, which is what the customer can+/// rely on. A sink realizes it as a Kafka partition key; the deciding layer+/// only chooses the guarantee.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OrderingGuarantee {+ /// Ordering preserved per distinct id — the guarantee for every+ /// non-replay lane. Partitions on the event's canonical key+ /// ([`common_types::CapturedEvent::key`]): `token:distinct_id`, or+ /// `token:ip` in cookieless mode, where the ip stands in for the distinct+ /// id derived later in the pipeline.+ PerDistinctId,+ /// Ordering preserved per replay session: partitions on the raw+ /// `session_id`, no token prefix (a missing id is rejected by the deciding layer).+ PerSession,+ /// No guarantee — no partition key, round-robin; ordering is+ /// intentionally dropped to spread load.+ None,+}++/// Drop the guarantee when person processing is skipped, otherwise keep+/// per-distinct-id ordering.+///+/// This is the shared half of the ordering rule both paths implement: on the+/// analytics and AI main/overflow lanes, taking person processing away also+/// takes the ordering guarantee away, because the stage that disabled person+/// processing did so to spread a hot key. Lanes whose consumers need the key+/// regardless (historical, dlq, custom redirects, the AI main topic) never+/// consult this.+pub fn person_ordering(skip_person_processing: bool) -> OrderingGuarantee {+ if skip_person_processing {+ OrderingGuarantee::None+ } else {+ OrderingGuarantee::PerDistinctId+ }+}diff --git a/rust/capture/src/overflow_parity.rs b/rust/capture/src/overflow_parity.rsnew file mode 100644index 000000000000..781b315db25c--- /dev/null+++ b/rust/capture/src/overflow_parity.rs@@ -0,0 +1,268 @@+//! Cross-path parity for overflow and global-rate-limit interaction.+//!+//! The v0 and v1 pipelines stamp their overflow and rate-limit decisions in+//! opposite orders (v0 runs the global rate limiter before the burst limiter,+//! v1 after) and reach the broker through separate sinks. Both must still put+//! the same event on the same lane, with the same partition-key presence and+//! the same person-processing header, because those three things are the wire+//! contract downstream ingestion reads.+//!+//! Each case runs the real pipeline on both paths and asserts both against an+//! explicit expectation, not merely against each other, so two paths that drift+//! together still fail.++use std::sync::Arc;++use chrono::{DateTime, Utc};+use limiters::overflow::OverflowLimiter;+use limiters::token_dropper::TokenDropper;+use rstest::rstest;+use std::num::NonZeroU32;++use crate::config::AiRouting;+use crate::global_rate_limiter::GlobalRateLimiter;+use crate::router::HistoricalConfig;+use crate::sinks::kafka::{test_topics, KafkaSinkBase};+use crate::sinks::producer::MockKafkaProducer;+use crate::v0_request::ProcessingContext;+use crate::v1::analytics::process::process_batch;+use crate::v1::test_utils::{self, TestStateBuilder};+use common_types::RawEvent;++/// v0's canonical key is `token:distinct_id`; the two paths use different test+/// tokens and distinct ids, so each side gets a limiter keyed for its own.+const V0_TOKEN: &str = "test_token";+const V0_DISTINCT_ID: &str = "test_user";+const V1_HOT_KEY: &str = "phc_test_token:user-42";++/// The lane an event landed on, independent of each path's test topic names.+#[derive(Debug, PartialEq, Eq)]+enum Lane {+ Main,+ Overflow,+ Other(String),+}++/// The three wire facts downstream ingestion actually reads.+#[derive(Debug, PartialEq, Eq)]+struct Observed {+ lane: Lane,+ has_key: bool,+ person_processing_disabled: bool,+}++#[derive(Clone, Copy)]+struct Limits {+ /// The token:distinct_id is over the global rate limit window.+ globally_limited: bool,+ /// A burst limiter is armed. `burst` of 1 limits every event after the first.+ burst_limiter: bool,+ /// The burst limiter keeps partition keys, as prod-US is configured.+ preserve_locality: bool,+ /// The burst limiter force-routes the key outright.+ force_limited: bool,+}++impl Limits {+ const NONE: Self = Self {+ globally_limited: false,+ burst_limiter: false,+ preserve_locality: false,+ force_limited: false,+ };+}++fn v0_overflow_limiter(limits: Limits) -> Option<Arc<OverflowLimiter>> {+ if !limits.burst_limiter && !limits.force_limited {+ return None;+ }+ let forced = limits.force_limited.then(|| V0_TOKEN.to_string());+ Some(Arc::new(OverflowLimiter::new(+ NonZeroU32::new(1).unwrap(),+ NonZeroU32::new(1).unwrap(),+ forced,+ limits.preserve_locality,+ )))+}++fn v0_raw_event() -> RawEvent {+ let mut properties = std::collections::HashMap::new();+ properties.insert("distinct_id".to_string(), serde_json::json!(V0_DISTINCT_ID));+ RawEvent {+ uuid: None,+ distinct_id: None,+ event: "test_event".to_string(),+ properties,+ timestamp: Some("2026-03-19T14:29:58.123Z".to_string()),+ offset: None,+ set: Some(std::collections::HashMap::new()),+ set_once: Some(std::collections::HashMap::new()),+ token: Some(V0_TOKEN.to_string()),+ }+}++fn v0_context(now: DateTime<Utc>) -> ProcessingContext {+ ProcessingContext {+ user_agent: None,+ sent_at: None,+ token: V0_TOKEN.to_string(),+ now,+ client_ip: "127.0.0.1".to_string(),+ request_id: "parity".to_string(),+ path: "/e/".to_string(),+ is_mirror_deploy: false,+ historical_migration: false,+ chatty_debug_enabled: false,+ capture_mode: crate::config::CaptureMode::Events,+ sdk_attribution: crate::ingestion_warnings::SdkAttribution::default(),+ }+}++/// Drive the real v0 pipeline into a real `KafkaSinkBase` and read the record+/// 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(+ producer.clone(),+ test_topics(),+ ));+ let global = limits.globally_limited.then(|| {+ Arc::new(GlobalRateLimiter::mock_limiting(&[&format!(+ "{V0_TOKEN}:{V0_DISTINCT_ID}"+ )]))+ });++ let now = DateTime::parse_from_rfc3339("2026-03-19T14:30:00Z")+ .unwrap()+ .with_timezone(&Utc);++ crate::events::analytics::process_events(+ sink,+ Arc::new(TokenDropper::default()),+ None,+ HistoricalConfig::new(false, 1),+ global,+ v0_overflow_limiter(limits),+ None,+ None,+ &AiRouting::Primary,+ (0..batch_size).map(|_| v0_raw_event()).collect(),+ &v0_context(now),+ )+ .await+ .expect("v0 pipeline must accept the batch");++ let records = producer.get_records();+ assert_eq!(records.len(), batch_size, "v0 must produce every event");+ let record = &records[observe];+ let topics = test_topics();+ Observed {+ lane: if record.topic == topics.main {+ Lane::Main+ } else if record.topic == topics.overflow {+ Lane::Overflow+ } else {+ Lane::Other(record.topic.clone())+ },+ has_key: record.key.is_some(),+ person_processing_disabled: record+ .headers+ .force_disable_person_processing+ .unwrap_or(false),+ }+}++/// Drive the real v1 pipeline through its sink router and read the record at+/// `observe` off the mock producer.+async fn run_v1(limits: Limits, batch_size: usize, observe: usize) -> Observed {+ let mut builder = TestStateBuilder::new();+ if limits.burst_limiter || limits.force_limited {+ builder = builder.with_overflow_limiter(1, 1);+ }+ if limits.preserve_locality {+ builder = builder.with_overflow_preserve_locality();+ }+ if limits.force_limited {+ builder = builder.with_overflow_forced_key("phc_test_token");+ }+ if limits.globally_limited {+ builder = builder+ .with_global_rate_limiter(Arc::new(GlobalRateLimiter::mock_limiting(&[V1_HOT_KEY])));+ }+ let ts = builder.build();++ let mut ctx = test_utils::test_analytics_context();+ let events: Vec<_> = (0..batch_size).map(|_| test_utils::valid_event()).collect();+ process_batch(&ts.state, &mut ctx, test_utils::valid_batch(events))+ .await+ .expect("v1 pipeline must accept the batch");++ let cfg = test_utils::test_kafka_config();+ ts.mock_producer.with_records(|records| {+ assert_eq!(records.len(), batch_size, "v1 must produce every event");+ let record = &records[observe];+ Observed {+ lane: if record.topic == cfg.topic_main {+ Lane::Main+ } else if record.topic == cfg.topic_overflow {+ Lane::Overflow+ } else {+ Lane::Other(record.topic.clone())+ },+ has_key: record.key.is_some(),+ person_processing_disabled: record.header("force_disable_person_processing")+ == Some("true"),+ }+ })+}++/// The matrix. Cases with a burst limiter armed send two events and observe+/// the second (`burst` of 1 admits the first event and limits the rest);+/// every other case observes its only event.+#[rstest]+#[case::no_limits(+ Limits::NONE,+ Observed { lane: Lane::Main, has_key: true, person_processing_disabled: false }+)]+// A person-on burst keeps its key on either locality setting: the analytics+// overflow consumer updates persons keyed on distinct id, so spreading one+// distinct id across partitions would contend those updates. Person+// processing stays on — a burst says nothing about identity resolution.+#[case::burst_rate_limited(+ Limits { burst_limiter: true, ..Limits::NONE },+ Observed { lane: Lane::Overflow, has_key: true, person_processing_disabled: false }+)]+#[case::burst_rate_limited_preserving_locality(+ Limits { burst_limiter: true, preserve_locality: true, ..Limits::NONE },+ Observed { lane: Lane::Overflow, has_key: true, person_processing_disabled: false }+)]+#[case::force_limited(+ Limits { force_limited: true, ..Limits::NONE },+ Observed { lane: Lane::Overflow, has_key: false, person_processing_disabled: true }+)]+#[case::globally_limited(+ Limits { globally_limited: true, ..Limits::NONE },+ Observed { lane: Lane::Overflow, has_key: false, person_processing_disabled: true }+)]+#[case::globally_limited_and_burst_rate_limited(+ Limits { globally_limited: true, burst_limiter: true, ..Limits::NONE },+ Observed { lane: Lane::Overflow, has_key: false, person_processing_disabled: true }+)]+// The cell the two paths used to disagree on: the global rate limiter has taken+// person processing away, so the burst limiter's locality preference must not+// hand the hot key its partition back.+#[case::globally_limited_and_burst_preserving_locality(+ Limits { globally_limited: true, burst_limiter: true, preserve_locality: true, ..Limits::NONE },+ Observed { lane: Lane::Overflow, has_key: false, person_processing_disabled: true }+)]+#[tokio::test]+async fn v0_and_v1_agree(#[case] limits: Limits, #[case] expected: Observed) {+ let batch_size = if limits.burst_limiter { 2 } else { 1 };+ let observe = batch_size - 1;++ let v0 = run_v0(limits, batch_size, observe).await;+ let v1 = run_v1(limits, batch_size, observe).await;++ assert_eq!(v0, expected, "v0 diverged from the contract");+ assert_eq!(v1, expected, "v1 diverged from the contract");+}diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex e5ccefeadbed..8c3460a61dc4 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -654,7 +654,7 @@ async fn create_sink(let kafka_sink = KafkaSink::new(config.kafka.clone(), Some(kafka_handle.clone())).await- .expect("failed to start Kafka sink");+ .context("failed to start Kafka sink")?;let s3_sink = S3Sink::new(config@@ -678,7 +678,7 @@ async fn create_sink(// full `Secondary` cutover hands the gating handle to the secondary).let kafka_sink = KafkaSink::new(config.kafka.clone(), sink_handle).await- .expect("failed to start Kafka sink");+ .context("failed to start Kafka sink")?;Ok(Box::new(kafka_sink))}@@ -1182,6 +1182,47 @@ mod tests {assert!(super::parse_token_allowlist(" , , ").is_empty());}+ /// A blank output topic makes `create_sink` refuse to boot in every capture+ /// mode — the misconfig fails fast at startup (via the `OutputRegistry`+ /// completeness check inside `KafkaSink::new`) rather than at first produce.+ #[rstest::rstest]+ #[case(CaptureMode::Events)]+ #[case(CaptureMode::Recordings)]+ #[case(CaptureMode::Ai)]+ #[case(CaptureMode::Import)]+ #[tokio::test]+ async fn create_sink_refuses_boot_on_missing_output_topic(#[case] mode: CaptureMode) {+ let cfg_env: HashMap<String, String> = [+ ("REDIS_URL", "redis://localhost:6379/"),+ ("CAPTURE_MODE", mode.as_tag()),+ ("KAFKA_HOSTS", "localhost:9092"),+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ let mut config: Config =+ envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");+ config.kafka.outputs_completeness_check_enabled = true;+ config.kafka.kafka_dlq_topic = String::new();++ let err = create_sink(&config, None, None)+ .await+ .err()+ .expect("boot must be refused when an output topic is empty");+ let msg = format!("{err:#}");+ assert!(+ msg.contains("dlq"),+ "error should name the missing output: {msg}"+ );++ // 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)+ .await+ .expect("boot must proceed when the completeness check is disabled");+ }+/// Absent gauge means warnings are off on purpose; `0` means an operator/// asked for them and we could not build them. `reason` says which.#[rstest]diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rsindex 5dfafe26dcaf..091ef2d25a00 100644--- a/rust/capture/src/sinks/kafka.rs+++ b/rust/capture/src/sinks/kafka.rs@@ -19,11 +19,12 @@//! + topics) rather than deep copies of limiter state.use crate::api::CaptureError;use crate::config::{EnvelopeCompression, KafkaConfig};+use crate::ordering::{person_ordering, OrderingGuarantee};use crate::sinks::producer::{KafkaProducer, ProduceRecord};+use crate::sinks::registry::{Output, OutputRegistry};use crate::sinks::Event;-use crate::v0_request::{DataType, OverflowReason, ProcessedEvent};+use crate::v0_request::{DataType, OverflowReason, ProcessedEvent, ProcessedEventMetadata};use async_trait::async_trait;-use common_types::CapturedEventHeaders;use metrics::{counter, gauge, histogram};use rdkafka::producer::{FutureProducer, Producer};use rdkafka::util::Timeout;@@ -31,7 +32,7 @@ use rdkafka::ClientConfig;use std::sync::Arc;use std::time::{Duration, Instant};use tokio::task::JoinSet;-use tracing::log::{debug, error, info, warn};+use tracing::log::{debug, error, info};use tracing::{info_span, instrument, Instrument};use super::producer::RdKafkaProducer;@@ -170,47 +171,6 @@ impl rdkafka::ClientContext for KafkaContext {}}-/// Topic configuration for the Kafka sink-#[derive(Clone)]-pub struct KafkaTopicConfig {- pub main_topic: String,- pub overflow_topic: String,- pub historical_topic: String,- pub client_ingestion_warning_topic: String,- pub heatmaps_topic: String,- pub replay_overflow_topic: String,- pub dlq_topic: String,- pub error_tracking_topic: String,- pub traces_topic: String,- /// Dedicated topic for `DataType::AiEvents` (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`). Optional- /// because the AI lane is opt-in: startup validation guarantees it is set- /// whenever the routing policy can produce `AiEvents` records.- pub ai_events_topic: Option<String>,- /// Overflow topic for the AI lane (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`). Unset- /// means AI events never overflow; when set, stamped/forced overflow on- /// `AiEvents` records reroutes here with the same key semantics as the- /// analytics overflow topic.- pub ai_events_overflow_topic: Option<String>,-}--impl From<&KafkaConfig> for KafkaTopicConfig {- fn from(config: &KafkaConfig) -> Self {- Self {- main_topic: config.kafka_topic.clone(),- overflow_topic: config.kafka_overflow_topic.clone(),- historical_topic: config.kafka_historical_topic.clone(),- client_ingestion_warning_topic: config.kafka_client_ingestion_warning_topic.clone(),- heatmaps_topic: config.kafka_heatmaps_topic.clone(),- replay_overflow_topic: config.kafka_replay_overflow_topic.clone(),- dlq_topic: config.kafka_dlq_topic.clone(),- error_tracking_topic: config.kafka_error_tracking_topic.clone(),- traces_topic: config.kafka_traces_topic.clone(),- ai_events_topic: config.capture_analytics_ai_events_topic.clone(),- ai_events_overflow_topic: config.capture_analytics_ai_events_overflow_topic.clone(),- }- }-}-/// Generic Kafka sink that can use any producer implementation.////// Holds only the producer handle, the topic config, and the replay envelope@@ -222,7 +182,7 @@ impl From<&KafkaConfig> for KafkaTopicConfig {/// is cloned once per spawned prep task.pub struct KafkaSinkBase<P: KafkaProducer> {producer: Arc<P>,- topics: Arc<KafkaTopicConfig>,+ topics: Arc<OutputRegistry>,replay_envelope_compression: EnvelopeCompression,}@@ -236,50 +196,452 @@ impl<P: KafkaProducer> Clone for KafkaSinkBase<P> {}}-/// Overflow routing shared by the lanes that own a dedicated overflow topic:-/// the analytics main lane always, and the AI lane once-/// `CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC` is set. Keeping both lanes on one function-/// guarantees identical semantics, including the partition-key handling-/// driven by `overflow_preserve_partition_locality`.-///-/// Precedence (matches the pre-refactor sink ordering): force_overflow-/// (restrictions) -> overflow_reason (pipeline-stamped) -> the lane's-/// `default_route`. `ReplayLimited` never applies to these lanes and falls-/// through to the default.-fn route_with_overflow<'a>(- overflow_topic: &'a str,- default_route: (&'a str, Option<&'a str>),- event_key: &'a str,- force_overflow: bool,- skip_person_processing: bool,- overflow_reason: Option<&OverflowReason>,- headers: &mut CapturedEventHeaders,-) -> (&'a str, Option<&'a str>) {- if force_overflow {- // Drop partition key if skip_person_processing is set- let key = if skip_person_processing {- None- } else {- Some(event_key)- };- return (overflow_topic, key);+/// The pure routing decision for a single event: which output, and which+/// ordering guarantee. Depends only on [`ProcessedEventMetadata`] (stamped+/// upstream by the pipeline) and the AI overflow valve — the one piece of+/// sink config that changes a routing decision rather than a topic name.+/// Side effects are not part of the decision: the dlq header set and the+/// reroute counters follow from the target, and the person-processing header+/// follows from [`ProcessedEventMetadata::person_processing_disabled`] —+/// the stamped flag, or a `ForceLimited` reason, which implies the skip on+/// its own.+#[derive(Debug, Clone, PartialEq, Eq)]+struct Route {+ target: Output,+ ordering: OrderingGuarantee,+}++/// Decide an event's route from its metadata. DLQ and custom-topic redirects+/// take priority over per-datatype and overflow routing. Consulted by the+/// sink, which resolves the target to a topic string and the ordering+/// guarantee to a partition key, and applies the target-implied side effects.+/// A replay event with no session id is rejected here, so every returned+/// `Route` is realizable by the sink.+fn route(+ metadata: &ProcessedEventMetadata,+ ai_events_overflow_armed: bool,+) -> Result<Route, CaptureError> {+ // redirect_to_dlq takes priority over all other routing.+ if metadata.redirect_to_dlq {+ return Ok(Route {+ target: Output::Dlq,+ ordering: OrderingGuarantee::PerDistinctId,+ });}- match overflow_reason {- Some(OverflowReason::ForceLimited) => {- // Redundant with the generic skip-person path (the pipeline- // stamps `metadata.skip_person_processing = true` alongside- // `OverflowReason::ForceLimited`), but kept as defense against a- // future caller that stamps the reason without the side-effect.- headers.set_force_disable_person_processing(true);- (overflow_topic, None)++ if let Some(ref topic) = metadata.redirect_to_topic {+ return Ok(Route {+ target: Output::Custom(topic.clone()),+ ordering: OrderingGuarantee::PerDistinctId,+ });+ }++ Ok(match metadata.data_type {+ DataType::AnalyticsHistorical => Route {+ // Historical events never overflow — force_overflow and+ // overflow_reason are deliberately ignored here.+ target: Output::AnalyticsHistorical,+ ordering: OrderingGuarantee::PerDistinctId,+ },+ DataType::AnalyticsMain => {+ // Precedence: force_overflow (restrictions) -> overflow_reason+ // (pipeline-stamped) -> default main-topic routing.+ if metadata.force_overflow {+ Route {+ target: Output::AnalyticsOverflow,+ ordering: person_ordering(metadata.person_processing_disabled()),+ }+ } else {+ match &metadata.overflow_reason {+ Some(OverflowReason::ForceLimited) => Route {+ target: Output::AnalyticsOverflow,+ ordering: OrderingGuarantee::None,+ },+ // The person flag alone decides the key here, in both+ // directions. A burst keeps its key while person processing+ // is on — the overflow consumer updates persons keyed on+ // distinct id, so spreading one distinct id across+ // partitions turns a hot key into contended person-row+ // updates — which makes the locality preference irrelevant+ // on this lane. And a key whose person processing is+ // already off (the global rate limiter stamps its verdict+ // before the overflow limiter overwrites the reason) must+ // not get its partition back.+ Some(OverflowReason::RateLimited { .. }) => Route {+ target: Output::AnalyticsOverflow,+ ordering: person_ordering(metadata.person_processing_disabled()),+ },+ // ReplayLimited is stamped only by the recordings pipeline,+ // so an analytics event cannot carry it — the shared+ // OverflowReason enum forces the arm, which treats the+ // impossible stamp as unstamped.+ Some(OverflowReason::ReplayLimited) | None => Route {+ target: Output::AnalyticsMain,+ ordering: person_ordering(metadata.person_processing_disabled()),+ },+ }+ }+ }+ DataType::AiEvents => {+ // Valve armed: the AI lanes route overflow like analytics, except+ // that a burst may spread while person processing is on — the AI+ // consumer reads persons without writing them, so keyless+ // person-on records cause no person-update contention there.+ // Valve unarmed: AI events never overflow —+ // 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.+ if ai_events_overflow_armed && metadata.force_overflow {+ Route {+ target: Output::AiOverflow,+ ordering: person_ordering(metadata.person_processing_disabled()),+ }+ } else if ai_events_overflow_armed {+ match &metadata.overflow_reason {+ Some(OverflowReason::ForceLimited) => Route {+ target: Output::AiOverflow,+ ordering: OrderingGuarantee::None,+ },+ Some(OverflowReason::RateLimited {+ preserve_locality: true,+ }) => Route {+ target: Output::AiOverflow,+ // Same precedence as the analytics overflow lane above.+ ordering: person_ordering(metadata.person_processing_disabled()),+ },+ Some(OverflowReason::RateLimited {+ preserve_locality: false,+ }) => Route {+ target: Output::AiOverflow,+ ordering: OrderingGuarantee::None,+ },+ // ReplayLimited cannot be stamped on the AI lane either;+ // treated as unstamped, as above.+ Some(OverflowReason::ReplayLimited) | None => Route {+ target: Output::AiMain,+ ordering: OrderingGuarantee::PerDistinctId,+ },+ }+ } else {+ Route {+ target: Output::AiMain,+ ordering: OrderingGuarantee::PerDistinctId,+ }+ }+ }+ DataType::ClientIngestionWarning => Route {+ target: Output::ClientWarningsMain,+ ordering: OrderingGuarantee::PerDistinctId,+ },+ DataType::HeatmapMain => Route {+ target: Output::HeatmapsMain,+ ordering: OrderingGuarantee::PerDistinctId,+ },+ DataType::ExceptionErrorTracking => Route {+ target: Output::ErrorTrackingMain,+ ordering: OrderingGuarantee::PerDistinctId,+ },+ DataType::SnapshotMain => {+ // Precedence: force_overflow (restrictions) -> overflow_reason+ // (pipeline-stamped ReplayLimited) -> default main-topic routing.+ // Partition key is always session_id for replay to keep per-session+ // ordering on the overflow topic; a missing id makes the decision+ // unrealizable, so it is rejected as part of the decision.+ if metadata.session_id.is_none() {+ return Err(CaptureError::MissingSessionId);+ }+ let target = if metadata.force_overflow+ || matches!(+ metadata.overflow_reason,+ Some(OverflowReason::ReplayLimited)+ ) {+ Output::SessionReplayOverflow+ } else {+ Output::SessionReplayMain+ };+ Route {+ target,+ ordering: OrderingGuarantee::PerSession,+ }+ }+ })+}++#[cfg(test)]+mod route_tests {+ use super::*;+ use rstest::rstest;++ fn meta(data_type: DataType) -> ProcessedEventMetadata {+ ProcessedEventMetadata {+ data_type,+ session_id: Some("session123".to_string()),+ computed_timestamp: None,+ event_name: "test_event".to_string(),+ force_overflow: false,+ skip_person_processing: false,+ redirect_to_dlq: false,+ redirect_to_topic: None,+ skip_heatmap_processing: false,+ overflow_reason: None,+ distinct_id_truncated_from: None,+ }+ }++ #[test]+ fn dlq_wins_over_custom_topic_and_datatype() {+ // redirect_to_dlq set alongside redirect_to_topic and an overflow+ // reason: DLQ still wins, keyed on the event key, with the DLQ effect.+ let mut m = meta(DataType::AnalyticsMain);+ m.redirect_to_dlq = true;+ m.redirect_to_topic = Some("custom".to_string());+ m.force_overflow = true;+ assert_eq!(+ route(&m, false).unwrap(),+ Route {+ target: Output::Dlq,+ ordering: OrderingGuarantee::PerDistinctId,+ }+ );+ }++ #[test]+ fn custom_topic_wins_over_datatype() {+ // Custom-topic redirect beats per-datatype/overflow routing (but not DLQ).+ let mut m = meta(DataType::AnalyticsMain);+ m.redirect_to_topic = Some("my_topic".to_string());+ m.force_overflow = true;+ assert_eq!(+ route(&m, false).unwrap(),+ Route {+ target: Output::Custom("my_topic".to_string()),+ ordering: OrderingGuarantee::PerDistinctId,+ }+ );+ }++ #[test]+ fn per_datatype_targets() {+ for (dt, target) in [+ (DataType::AnalyticsMain, Output::AnalyticsMain),+ (DataType::AnalyticsHistorical, Output::AnalyticsHistorical),+ (DataType::ClientIngestionWarning, Output::ClientWarningsMain),+ (DataType::HeatmapMain, Output::HeatmapsMain),+ (DataType::ExceptionErrorTracking, Output::ErrorTrackingMain),+ (DataType::AiEvents, Output::AiMain),+ (DataType::SnapshotMain, Output::SessionReplayMain),+ ] {+ let m = meta(dt);+ let r = route(&m, false).unwrap();+ assert_eq!(r.target, target, "wrong target for {dt:?}");}- Some(OverflowReason::RateLimited {+ }++ #[test]+ fn analytics_main_overflow_ordering() {+ // force_overflow -> overflow topic; key policy follows skip_person.+ let mut m = meta(DataType::AnalyticsMain);+ m.force_overflow = true;+ assert_eq!(+ route(&m, false).unwrap().ordering,+ OrderingGuarantee::PerDistinctId+ );+ m.skip_person_processing = true;+ assert_eq!(route(&m, false).unwrap().ordering, OrderingGuarantee::None);+ assert_eq!(route(&m, false).unwrap().target, Output::AnalyticsOverflow);+ }++ #[test]+ fn analytics_main_overflow_reason_precedence() {+ let base = meta(DataType::AnalyticsMain);++ let mut force_limited = base.clone();+ force_limited.overflow_reason = Some(OverflowReason::ForceLimited);+ assert_eq!(+ route(&force_limited, false).unwrap(),+ Route {+ target: Output::AnalyticsOverflow,+ ordering: OrderingGuarantee::None,+ }+ );++ let mut preserve = base.clone();+ preserve.overflow_reason = Some(OverflowReason::RateLimited {preserve_locality: true,- }) => (overflow_topic, Some(event_key)),- Some(OverflowReason::RateLimited {+ });+ assert_eq!(+ route(&preserve, false).unwrap().ordering,+ OrderingGuarantee::PerDistinctId+ );+ assert_eq!(+ route(&preserve, false).unwrap().target,+ Output::AnalyticsOverflow+ );++ // The locality preference is irrelevant on the analytics lane: a+ // person-on burst keeps its key either way, because the overflow+ // consumer writes persons keyed on distinct id.+ let mut no_preserve = base.clone();+ no_preserve.overflow_reason = Some(OverflowReason::RateLimited {preserve_locality: false,- }) => (overflow_topic, None),- Some(OverflowReason::ReplayLimited) | None => default_route,+ });+ assert_eq!(+ route(&no_preserve, false).unwrap().ordering,+ OrderingGuarantee::PerDistinctId+ );+ assert_eq!(+ route(&no_preserve, false).unwrap().target,+ Output::AnalyticsOverflow+ );+ no_preserve.skip_person_processing = true;+ assert_eq!(+ route(&no_preserve, false).unwrap().ordering,+ OrderingGuarantee::None+ );++ // ReplayLimited cannot be stamped on analytics events (only the+ // recordings pipeline produces it); the impossible combination is+ // treated as unstamped.+ let mut replay = base;+ replay.overflow_reason = Some(OverflowReason::ReplayLimited);+ assert_eq!(route(&replay, false).unwrap().target, Output::AnalyticsMain);+ }++ /// The global rate limiter stamps `skip_person_processing` before the+ /// 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.+ #[rstest]+ #[case::analytics(DataType::AnalyticsMain, Output::AnalyticsOverflow)]+ #[case::ai(DataType::AiEvents, Output::AiOverflow)]+ fn person_processing_off_outranks_preserve_locality(+ #[case] data_type: DataType,+ #[case] expected_target: Output,+ ) {+ let armed = data_type == DataType::AiEvents;+ let mut m = meta(data_type);+ m.overflow_reason = Some(OverflowReason::RateLimited {+ preserve_locality: true,+ });++ assert_eq!(+ route(&m, armed).unwrap().ordering,+ OrderingGuarantee::PerDistinctId,+ "locality is preserved while person processing is on"+ );++ m.skip_person_processing = true;+ assert_eq!(+ route(&m, armed).unwrap(),+ Route {+ target: expected_target,+ ordering: OrderingGuarantee::None,+ }+ );+ }++ #[test]+ fn ai_events_overflow_gated_on_valve() {+ // Valve unarmed: force_overflow and stamped reasons are ignored — the+ // AI lane never overflows and keeps its event key.+ let mut m = meta(DataType::AiEvents);+ m.force_overflow = true;+ assert_eq!(+ route(&m, false).unwrap(),+ Route {+ target: Output::AiMain,+ ordering: OrderingGuarantee::PerDistinctId,+ }+ );++ // Valve armed: mirrors the analytics main lane's overflow handling.+ assert_eq!(route(&m, true).unwrap().target, Output::AiOverflow);+ assert_eq!(+ route(&m, true).unwrap().ordering,+ OrderingGuarantee::PerDistinctId+ );+ m.skip_person_processing = true;+ assert_eq!(route(&m, true).unwrap().ordering, OrderingGuarantee::None);++ let mut force_limited = meta(DataType::AiEvents);+ force_limited.overflow_reason = Some(OverflowReason::ForceLimited);+ assert_eq!(+ route(&force_limited, true).unwrap(),+ Route {+ target: Output::AiOverflow,+ ordering: OrderingGuarantee::None,+ }+ );+ assert_eq!(route(&force_limited, false).unwrap().target, Output::AiMain);+ }++ #[test]+ fn ai_events_default_route_keeps_event_key() {+ // skip_person_processing must not null the key on the AI default+ // route: v1 only nulls keys for Main/Overflow-shaped destinations.+ let mut m = meta(DataType::AiEvents);+ m.skip_person_processing = true;+ for armed in [false, true] {+ assert_eq!(+ route(&m, armed).unwrap(),+ Route {+ target: Output::AiMain,+ ordering: OrderingGuarantee::PerDistinctId,+ },+ "armed={armed}"+ );+ }+ }++ #[test]+ fn snapshot_routing_uses_session_id_key() {+ let mut m = meta(DataType::SnapshotMain);+ assert_eq!(+ route(&m, false).unwrap(),+ Route {+ target: Output::SessionReplayMain,+ ordering: OrderingGuarantee::PerSession,+ }+ );++ m.force_overflow = true;+ assert_eq!(+ route(&m, false).unwrap().target,+ Output::SessionReplayOverflow+ );+ assert_eq!(+ route(&m, false).unwrap().ordering,+ OrderingGuarantee::PerSession+ );++ m.force_overflow = false;+ m.overflow_reason = Some(OverflowReason::ReplayLimited);+ assert_eq!(+ route(&m, false).unwrap().target,+ Output::SessionReplayOverflow+ );+ }++ /// A replay event with no session id has no realizable route — the+ /// decision itself rejects, rather than handing the sink a `PerSession`+ /// guarantee it cannot key.+ #[test]+ fn snapshot_without_session_id_is_rejected() {+ let mut m = meta(DataType::SnapshotMain);+ m.session_id = None;+ assert!(matches!(+ route(&m, false),+ Err(CaptureError::MissingSessionId)+ ));++ // A dlq redirect keys on the event key, so it stays realizable+ // without a session id.+ m.redirect_to_dlq = true;+ assert_eq!(route(&m, false).unwrap().target, Output::Dlq);}}@@ -291,6 +653,17 @@ impl KafkaSink {config: KafkaConfig,liveness: Option<lifecycle::Handle>,) -> anyhow::Result<KafkaSink> {+ // Refuse to boot on incomplete output wiring: a blank topic fails+ // here, at startup, instead of at first produce. Config-only, so it+ // runs before the producer is built and the broker is pinged — the+ // refusal is instant, not one connect attempt later.+ let registry = OutputRegistry::from(&config);+ if config.outputs_completeness_check_enabled {+ registry.check_complete()?;+ } else {+ info!("outputs completeness check disabled; a blank output topic will fail at first produce instead of at boot");+ }+info!("connecting to Kafka brokers at {}...", config.kafka_hosts);let mut client_config = ClientConfig::new();@@ -408,7 +781,7 @@ impl KafkaSink {info!("connected to Kafka brokers");};- let topics = Arc::new(KafkaTopicConfig::from(&config));+ let topics = Arc::new(registry);let rd_producer = RdKafkaProducer::new(producer);Ok(KafkaSinkBase {@@ -423,7 +796,7 @@ 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.- pub fn with_producer(producer: P, topics: KafkaTopicConfig) -> Self {+ pub fn with_producer(producer: P, topics: OutputRegistry) -> Self {Self {producer: Arc::new(producer),topics: Arc::new(topics),@@ -434,7 +807,7 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {/// Same as `with_producer` but with envelope compression enabled. Used in tests.pub fn with_producer_and_compression(producer: P,- topics: KafkaTopicConfig,+ topics: OutputRegistry,replay_envelope_compression: EnvelopeCompression,) -> Self {Self {@@ -453,9 +826,9 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {/// Routing policy is read from `ProcessedEventMetadata` (stamped upstream/// by the pipeline). This function does not consult any limiter — it is/// pure mechanism. DLQ and custom-topic redirects take priority over- /// overflow routing, matching the pre-refactor ordering.+ /// overflow routing.///- /// Not `async`: post-refactor there are no await points, and keeping it+ /// Not `async`: there are no await points, and keeping it/// synchronous lets `send_batch`'s serial fast path call it inline without/// any runtime indirection.fn prepare_record(&self, event: ProcessedEvent) -> Result<ProduceRecord, CaptureError> {@@ -488,148 +861,73 @@ impl<P: KafkaProducer> KafkaSinkBase<P> {_ => json.into_bytes(),};- let data_type = metadata.data_type;let event_key = event.key();- let session_id = metadata.session_id.clone();- let force_overflow = metadata.force_overflow;- let skip_person_processing = metadata.skip_person_processing;- let redirect_to_dlq = metadata.redirect_to_dlq;- let redirect_to_topic = metadata.redirect_to_topic;- let skip_heatmap_processing = metadata.skip_heatmap_processing;- let overflow_reason = metadata.overflow_reason;// Use the event's to_headers() method for consistent header serializationlet mut headers = event.to_headers();drop(event); // Events can be EXTREMELY memory hungry- // Apply skip_person_processing from event restrictions / upstream decisions- if skip_person_processing {+ // The stamped flag (event restrictions / upstream decisions) or a+ // ForceLimited reason, which implies the skip on its own.+ if metadata.person_processing_disabled() {headers.set_force_disable_person_processing(true);}- if skip_heatmap_processing {+ if metadata.skip_heatmap_processing {headers.set_skip_heatmap_processing(true);}- // Check for redirect_to_dlq first - takes priority over all other routing- let (topic, partition_key): (&str, Option<&str>) = if redirect_to_dlq {- counter!(- "capture_events_rerouted_dlq",- &[("reason", "event_restriction")]- )- .increment(1);-- // Set DLQ specific headers- // DLQ reason cannot be known beyond being triggered by an event restriction.- headers.set_dlq_reason("event_restriction".to_string());- // Unlike with our node code, DLQ step will always be static.- headers.set_dlq_step("capture".to_string());- headers.set_dlq_timestamp(- chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),- );+ // The routing decision is pure metadata policy; the sink resolves the+ // target against its topic config, the key policy against the values+ // it owns, and applies the target-implied side effects.+ let decision = route(&metadata, self.topics.ai_events_overflow_armed())?;++ let topic: &str = self.topics.topic_for(&decision.target);++ let partition_key: Option<&str> = match decision.ordering {+ OrderingGuarantee::PerDistinctId => Some(event_key.as_str()),+ OrderingGuarantee::None => None,+ // route() rejects replay events without a session id, so the id+ // is present whenever PerSession is decided.+ OrderingGuarantee::PerSession => Some(+ metadata+ .session_id+ .as_deref()+ .ok_or(CaptureError::MissingSessionId)?,+ ),+ };- (&self.topics.dlq_topic, Some(event_key.as_str()))- } else if let Some(ref topic) = redirect_to_topic {- counter!(- "capture_events_rerouted_custom_topic",- &[("reason", "event_restriction")]- )- .increment(1);- (topic.as_str(), Some(event_key.as_str()))- } else {- match data_type {- DataType::AnalyticsHistorical => {- // Historical events never overflow — force_overflow and- // overflow_reason are deliberately ignored here.- (&self.topics.historical_topic, Some(event_key.as_str()))- }- DataType::AnalyticsMain => {- // Drop the partition key on the default main-topic route- // if skip_person_processing is set.- let default_key = if skip_person_processing {- None- } else {- Some(event_key.as_str())- };- route_with_overflow(- &self.topics.overflow_topic,- (&self.topics.main_topic, default_key),- &event_key,- force_overflow,- skip_person_processing,- overflow_reason.as_ref(),- &mut headers,- )- }- DataType::ClientIngestionWarning => (- &self.topics.client_ingestion_warning_topic,- Some(event_key.as_str()),- ),- DataType::HeatmapMain => (&self.topics.heatmaps_topic, Some(event_key.as_str())),- DataType::ExceptionErrorTracking => {- (&self.topics.error_tracking_topic, Some(event_key.as_str()))- }- DataType::AiEvents => {- // AI events never reroute historical; like the- // exception/heatmap lanes the record keeps its event key- // on the default route (v1 only nulls keys for- // Main/Overflow-shaped destinations). An unset topic- // should be impossible here (startup validation requires- // CAPTURE_ANALYTICS_AI_EVENTS_TOPIC whenever the routing policy can produce- // AiEvents), so fall back to the main topic rather than- // failing the batch.- let default_topic: &str = match self.topics.ai_events_topic.as_deref() {- Some(topic) if !topic.is_empty() => topic,- _ => {- warn!(- "CAPTURE_ANALYTICS_AI_EVENTS_TOPIC not configured for an AiEvents record; falling back to main topic"- );- &self.topics.main_topic- }- };- match self.topics.ai_events_overflow_topic.as_deref() {- // The AI overflow valve is armed: mirror the- // analytics main lane's overflow handling onto the- // AI topics.- Some(overflow_topic) if !overflow_topic.is_empty() => route_with_overflow(- overflow_topic,- (default_topic, Some(event_key.as_str())),- &event_key,- force_overflow,- skip_person_processing,- overflow_reason.as_ref(),- &mut headers,- ),- // Valve unarmed: AI events never overflow;- // force_overflow and overflow_reason are- // deliberately ignored, and the pipeline never- // stamps a reason on this lane anyway.- _ => (default_topic, Some(event_key.as_str())),- }- }- DataType::SnapshotMain => {- let session_id = session_id- .as_deref()- .ok_or(CaptureError::MissingSessionId)?;-- // Precedence: force_overflow (restrictions) -> overflow_reason- // (pipeline-stamped ReplayLimited) -> default main-topic- // routing. Partition key is always session_id for replay- // to keep per-session ordering on the overflow topic.- if force_overflow- || matches!(overflow_reason, Some(OverflowReason::ReplayLimited))- {- (&self.topics.replay_overflow_topic, Some(session_id))- } else {- (&self.topics.main_topic, Some(session_id))- }- }+ // Output-implied side effects: the dlq output's contract includes the+ // dlq header set, and both redirect outputs count their reroutes.+ match decision.target {+ Output::Dlq => {+ counter!(+ "capture_events_rerouted_dlq",+ &[("reason", "event_restriction")]+ )+ .increment(1);++ // DLQ reason cannot be known beyond being triggered by an event restriction.+ headers.set_dlq_reason("event_restriction".to_string());+ // Unlike with our node code, DLQ step will always be static.+ headers.set_dlq_step("capture".to_string());+ headers.set_dlq_timestamp(+ chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),+ );}- };+ Output::Custom(_) => {+ counter!(+ "capture_events_rerouted_custom_topic",+ &[("reason", "event_restriction")]+ )+ .increment(1);+ }+ _ => {}+ }if matches!(self.replay_envelope_compression, EnvelopeCompression::Lz4)- && matches!(data_type, DataType::SnapshotMain)+ && matches!(metadata.data_type, DataType::SnapshotMain){headers.set_content_encoding("lz4".to_string());}@@ -851,25 +1149,8 @@ async fn drain_acks(mut ack_set: JoinSet<Result<(), CaptureError>>) -> Result<().await}-/// Shared `KafkaTopicConfig` fixture for tests across the capture crate. Used-/// by sink-side routing tests and pipeline-to-sink E2E tests to ensure every-/// test site asserts against the same canonical topic names.#[cfg(test)]-pub(crate) fn test_topics() -> KafkaTopicConfig {- KafkaTopicConfig {- main_topic: "events_plugin_ingestion".to_string(),- overflow_topic: "events_plugin_ingestion_overflow".to_string(),- historical_topic: "events_plugin_ingestion_historical".to_string(),- client_ingestion_warning_topic: "client_ingestion_warning".to_string(),- heatmaps_topic: "heatmaps".to_string(),- replay_overflow_topic: "replay_overflow".to_string(),- dlq_topic: "events_plugin_ingestion_dlq".to_string(),- error_tracking_topic: "error_tracking_events".to_string(),- traces_topic: "tracing_ingestion".to_string(),- ai_events_topic: Some("ai_events".to_string()),- ai_events_overflow_topic: Some("ai_events_overflow".to_string()),- }-}+pub(crate) use crate::sinks::registry::test_topics;#[cfg(test)]mod tests {@@ -919,6 +1200,7 @@ mod tests {kafka_heatmaps_topic: "events_plugin_ingestion".to_string(),kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),+ outputs_completeness_check_enabled: true,capture_analytics_ai_events_topic: None,capture_analytics_ai_events_overflow_topic: None,kafka_traces_topic: "traces_ingestion".to_string(),@@ -1279,13 +1561,25 @@ mod tests {const AI_EVENTS_TOPIC: &str = "ai_events";const AI_EVENTS_OVERFLOW_TOPIC: &str = "ai_events_overflow";+ /// Which reroute counter (if any) an event must increment. DLQ and+ /// custom-topic redirects are mutually exclusive at the sink because DLQ+ /// takes strict priority, so a single event fires at most one counter.+ #[derive(Clone, Copy, PartialEq, Debug)]+ enum Rerouted {+ None,+ Dlq,+ CustomTopic,+ }+struct EventInput {data_type: DataType,force_overflow: bool,skip_person_processing: bool,+ skip_heatmap_processing: bool,redirect_to_dlq: bool,redirect_to_topic: Option<String>,overflow_reason: Option<OverflowReason>,+ compression: EnvelopeCompression,}impl Default for EventInput {@@ -1294,9 +1588,11 @@ mod tests {data_type: DataType::AnalyticsMain,force_overflow: false,skip_person_processing: false,+ skip_heatmap_processing: false,redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ compression: EnvelopeCompression::None,}}}@@ -1327,7 +1623,7 @@ mod tests {skip_person_processing: input.skip_person_processing,redirect_to_dlq: input.redirect_to_dlq,redirect_to_topic: input.redirect_to_topic.clone(),- skip_heatmap_processing: false,+ skip_heatmap_processing: input.skip_heatmap_processing,overflow_reason: input.overflow_reason.clone(),distinct_id_truncated_from: None,};@@ -1335,48 +1631,187 @@ mod tests {ProcessedEvent { event, metadata }}+ /// The full routing fingerprint of one event: topic + partition key ++ /// every header the sink can stamp + which reroute counter (if any)+ /// fires. This is the golden oracle produce-path refactors prove wire+ /// parity against, so each field is stated explicitly rather than+ /// re-derived from the input. Fields default to the "normal main-topic" outcome so+ /// each case only spells out what makes it different.struct ExpectedRouting<'a> {topic: &'a str,has_key: bool,force_disable_person_processing: Option<bool>,+ skip_heatmap_processing: Option<bool>,+ content_encoding: Option<&'a str>,+ dlq_headers: bool,+ rerouted: Rerouted,+ }++ impl Default for ExpectedRouting<'_> {+ fn default() -> Self {+ Self {+ topic: "",+ has_key: true,+ force_disable_person_processing: None,+ skip_heatmap_processing: None,+ content_encoding: None,+ dlq_headers: false,+ rerouted: Rerouted::None,+ }+ }}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+ // 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();+ let snapshotter = recorder.snapshotter();+ let _guard = metrics::set_default_local_recorder(&recorder);+let producer = MockKafkaProducer::new();- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());+ let sink = KafkaSinkBase::with_producer_and_compression(+ producer.clone(),+ test_topics(),+ input.compression,+ );let event = create_test_event(&input);sink.send(event).await.unwrap();let records = producer.get_records();assert_eq!(records.len(), 1, "Expected exactly one record");- assert_eq!(- records[0].topic,- expected.topic,- "Wrong topic for {:?} (overflow={}, skip_person={}, dlq={})",+ let record = &records[0];+ let headers = &record.headers;++ let ctx = format!(+ "{:?} (force_overflow={}, skip_person={}, skip_heatmap={}, dlq={}, redirect_to_topic={:?}, overflow_reason={:?})",input.data_type,input.force_overflow,input.skip_person_processing,- input.redirect_to_dlq+ input.skip_heatmap_processing,+ input.redirect_to_dlq,+ input.redirect_to_topic,+ input.overflow_reason,);++ assert_eq!(record.topic, expected.topic, "wrong topic for {ctx}");assert_eq!(- records[0].key.is_some(),+ record.key.is_some(),expected.has_key,- "Wrong key presence for {:?} (overflow={}, skip_person={}, dlq={})",- input.data_type,- input.force_overflow,- input.skip_person_processing,- input.redirect_to_dlq+ "wrong key presence for {ctx}");assert_eq!(- records[0].headers.force_disable_person_processing,- expected.force_disable_person_processing,- "Wrong header for {:?} (overflow={}, skip_person={}, dlq={})",- input.data_type,- input.force_overflow,- input.skip_person_processing,- input.redirect_to_dlq+ headers.force_disable_person_processing, expected.force_disable_person_processing,+ "wrong force_disable_person_processing header for {ctx}"+ );+ assert_eq!(+ headers.skip_heatmap_processing, expected.skip_heatmap_processing,+ "wrong skip_heatmap_processing header for {ctx}"+ );+ assert_eq!(+ headers.content_encoding.as_deref(),+ expected.content_encoding,+ "wrong content_encoding header for {ctx}");++ // DLQ headers travel as a set: a reason, a step, and a valid RFC-3339+ // timestamp when the event is routed to the DLQ; all three absent on+ // every other route.+ if expected.dlq_headers {+ assert_eq!(+ headers.dlq_reason.as_deref(),+ Some("event_restriction"),+ "wrong dlq_reason for {ctx}"+ );+ assert_eq!(+ headers.dlq_step.as_deref(),+ Some("capture"),+ "wrong dlq_step for {ctx}"+ );+ let ts = headers+ .dlq_timestamp+ .as_deref()+ .unwrap_or_else(|| panic!("dlq_timestamp missing for {ctx}"));+ chrono::DateTime::parse_from_rfc3339(ts).unwrap_or_else(|e| {+ panic!("dlq_timestamp '{ts}' is not valid RFC 3339 for {ctx}: {e}")+ });+ } else {+ assert_eq!(+ headers.dlq_reason, None,+ "dlq_reason must be absent for {ctx}"+ );+ assert_eq!(headers.dlq_step, None, "dlq_step must be absent for {ctx}");+ assert_eq!(+ headers.dlq_timestamp, None,+ "dlq_timestamp must be absent for {ctx}"+ );+ }++ // Exactly one reroute counter fires per redirected event; neither+ // fires on the normal per-datatype or overflow paths.+ let snapshot = snapshotter.snapshot().into_vec();+ let count = |name: &str| -> Option<u64> {+ snapshot.iter().find_map(|(key, _, _, value)| {+ if key.key().name() != name {+ return None;+ }+ match value {+ metrics_util::debugging::DebugValue::Counter(v) => Some(*v),+ _ => None,+ }+ })+ };+ // Recorder liveness: enqueue emits the bytes counter for every+ // record, on the same inline pre-await path as the reroute+ // counters. If it is absent, the thread-local recorder is no+ // longer observing prep (e.g. prep moved to a spawned thread)+ // and every absence assertion below would pass vacuously — so+ // fail here first, in every case.+ assert_eq!(+ count("capture_kafka_produce_bytes_total"),+ Some(record.payload.len() as u64),+ "recorder did not observe the produce path for {ctx}; \+ the counter assertions below cannot be trusted"+ );++ let dlq_count = count("capture_events_rerouted_dlq");+ let custom_count = count("capture_events_rerouted_custom_topic");+ match expected.rerouted {+ Rerouted::None => {+ assert_eq!(+ dlq_count, None,+ "capture_events_rerouted_dlq must not fire for {ctx}"+ );+ assert_eq!(+ custom_count, None,+ "capture_events_rerouted_custom_topic must not fire for {ctx}"+ );+ }+ Rerouted::Dlq => {+ assert_eq!(+ dlq_count,+ Some(1),+ "capture_events_rerouted_dlq must fire once for {ctx}"+ );+ assert_eq!(+ custom_count, None,+ "capture_events_rerouted_custom_topic must not fire for {ctx}"+ );+ }+ Rerouted::CustomTopic => {+ assert_eq!(+ custom_count,+ Some(1),+ "capture_events_rerouted_custom_topic must fire once for {ctx}"+ );+ assert_eq!(+ dlq_count, None,+ "capture_events_rerouted_dlq must not fire for {ctx}"+ );+ }+ }}// ==================== AnalyticsMain ====================@@ -1391,11 +1826,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: MAIN_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1411,11 +1848,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: OVERFLOW_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1432,11 +1871,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: OVERFLOW_TOPIC,has_key: false,force_disable_person_processing: Some(true),+ ..Default::default()},).await;@@ -1453,11 +1894,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: MAIN_TOPIC,has_key: false,force_disable_person_processing: Some(true),+ ..Default::default()},).await;@@ -1473,11 +1916,15 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: None,+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -1494,11 +1941,15 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: None,+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -1514,11 +1965,15 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: Some(true),+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -1535,11 +1990,15 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: Some(true),+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -1558,11 +2017,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: HISTORICAL_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1579,11 +2040,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: HISTORICAL_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1599,11 +2062,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: HISTORICAL_TOPIC,has_key: true,force_disable_person_processing: Some(true),+ ..Default::default()},).await;@@ -1619,11 +2084,15 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: None,+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -1640,11 +2109,15 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: Some(true),+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -1662,11 +2135,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: MAIN_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1682,11 +2157,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: REPLAY_OVERFLOW_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1703,11 +2180,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: REPLAY_OVERFLOW_TOPIC,has_key: true,force_disable_person_processing: Some(true),+ ..Default::default()},).await;@@ -1723,11 +2202,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: MAIN_TOPIC,has_key: true,force_disable_person_processing: Some(true),+ ..Default::default()},).await;@@ -1743,11 +2224,15 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: None,+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -1763,11 +2248,54 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: None,+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()+ },+ )+ .await;+ }++ #[tokio::test]+ async fn snapshot_lz4_sets_content_encoding_header() {+ // With envelope compression on, a snapshot event carries the+ // `content-encoding: lz4` header alongside its normal main-topic+ // routing. The compressed-payload bytes are covered by the lz4+ // payload goldens below; here the oracle pins just the header.+ assert_routing(+ EventInput {+ data_type: DataType::SnapshotMain,+ compression: EnvelopeCompression::Lz4,+ ..Default::default()+ },+ ExpectedRouting {+ topic: MAIN_TOPIC,+ content_encoding: Some("lz4"),+ ..Default::default()+ },+ )+ .await;+ }++ #[tokio::test]+ async fn analytics_main_lz4_leaves_content_encoding_unset() {+ // Envelope compression only applies to snapshots: a non-snapshot+ // event under the same sink config carries no content-encoding.+ assert_routing(+ EventInput {+ data_type: DataType::AnalyticsMain,+ compression: EnvelopeCompression::Lz4,+ ..Default::default()+ },+ ExpectedRouting {+ topic: MAIN_TOPIC,+ ..Default::default()},).await;@@ -1786,11 +2314,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: HEATMAPS_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1806,11 +2336,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: HEATMAPS_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1826,11 +2358,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: HEATMAPS_TOPIC,has_key: true,force_disable_person_processing: Some(true),+ ..Default::default()},).await;@@ -1846,11 +2380,56 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: None,+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()+ },+ )+ .await;+ }++ #[tokio::test]+ async fn heatmap_skip_heatmap_processing_sets_header() {+ // The skip_heatmap_processing metadata flag stamps its own header,+ // independent of the routing topic and the person-processing flag.+ assert_routing(+ EventInput {+ data_type: DataType::HeatmapMain,+ skip_heatmap_processing: true,+ ..Default::default()+ },+ ExpectedRouting {+ topic: HEATMAPS_TOPIC,+ skip_heatmap_processing: Some(true),+ ..Default::default()+ },+ )+ .await;+ }++ #[tokio::test]+ async fn analytics_main_skip_heatmap_processing_sets_header() {+ // skip_heatmap_processing is not gated on data type: it rides through+ // for AnalyticsMain too, orthogonally to skip_person_processing.+ assert_routing(+ EventInput {+ data_type: DataType::AnalyticsMain,+ skip_heatmap_processing: true,+ skip_person_processing: true,+ ..Default::default()+ },+ ExpectedRouting {+ topic: MAIN_TOPIC,+ has_key: false,+ force_disable_person_processing: Some(true),+ skip_heatmap_processing: Some(true),+ ..Default::default()},).await;@@ -1869,11 +2448,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: ERROR_TRACKING_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1889,11 +2470,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: ERROR_TRACKING_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1909,11 +2492,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: ERROR_TRACKING_TOPIC,has_key: true,force_disable_person_processing: Some(true),+ ..Default::default()},).await;@@ -1929,11 +2514,15 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: None,+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -1952,11 +2541,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: CLIENT_INGESTION_WARNING_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1972,11 +2563,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: CLIENT_INGESTION_WARNING_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -1992,11 +2585,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: CLIENT_INGESTION_WARNING_TOPIC,has_key: true,force_disable_person_processing: Some(true),+ ..Default::default()},).await;@@ -2012,11 +2607,15 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: None,+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -2039,11 +2638,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: AI_EVENTS_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -2061,11 +2662,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: AI_EVENTS_OVERFLOW_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -2082,19 +2685,24 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: AI_EVENTS_OVERFLOW_TOPIC,has_key: false,force_disable_person_processing: Some(true),+ ..Default::default()},).await;}- /// Stamped overflow reasons on the AI lane route exactly like the- /// analytics main lane, including the preserve-partition-locality- /// key handling mirrored from the limiter config.+ /// Stamped overflow reasons on the AI lane, where — unlike the+ /// analytics lane — a burst without locality preservation spreads+ /// while person processing is on: the AI consumer reads persons+ /// without writing them, so keyless person-on records contend+ /// nothing downstream. `ForceLimited` implies the person-processing+ /// header on its own, flag or no flag.#[rstest]#[case::force_limited(OverflowReason::ForceLimited, false, Some(true))]#[case::rate_limited_preserving(@@ -2112,7 +2720,7 @@ mod tests {None)]#[tokio::test]- async fn ai_events_stamped_overflow_mirrors_analytics(+ async fn ai_events_stamped_overflow_routing(#[case] reason: OverflowReason,#[case] has_key: bool,#[case] force_disable_person_processing: Option<bool>,@@ -2125,11 +2733,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: Some(reason),+ ..Default::default()},ExpectedRouting {topic: AI_EVENTS_OVERFLOW_TOPIC,has_key,force_disable_person_processing,+ ..Default::default()},).await;@@ -2142,7 +2752,7 @@ mod tests {// gated pipeline would not produce anyway) are ignored.let producer = MockKafkaProducer::new();let mut topics = test_topics();- topics.ai_events_overflow_topic = None;+ topics.ai_events_overflow = None;let sink = KafkaSinkBase::with_producer(producer.clone(), topics);let mut event = create_test_event(&EventInput {@@ -2152,6 +2762,7 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()});event.metadata.overflow_reason = Some(OverflowReason::ForceLimited);sink.send(event).await.unwrap();@@ -2174,11 +2785,13 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: AI_EVENTS_TOPIC,has_key: true,force_disable_person_processing: Some(true),+ ..Default::default()},).await;@@ -2194,11 +2807,15 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: None,+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -2216,11 +2833,14 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: Some("custom_topic".to_string()),overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: "custom_topic",has_key: true,force_disable_person_processing: None,+ rerouted: Rerouted::CustomTopic,+ ..Default::default()},).await;@@ -2262,7 +2882,7 @@ mod tests {// misconfigured sink must degrade to the main topic, not error.let producer = MockKafkaProducer::new();let mut topics = test_topics();- topics.ai_events_topic = None;+ topics.ai_events = None;let sink = KafkaSinkBase::with_producer(producer.clone(), topics);let input = EventInput {@@ -2281,7 +2901,7 @@ mod tests {async fn ai_events_empty_topic_falls_back_to_main() {let producer = MockKafkaProducer::new();let mut topics = test_topics();- topics.ai_events_topic = Some(String::new());+ topics.ai_events = Some(String::new());let sink = KafkaSinkBase::with_producer(producer.clone(), topics);let input = EventInput {@@ -2308,11 +2928,14 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: Some("custom_topic".to_string()),overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: "custom_topic",has_key: true,force_disable_person_processing: None,+ rerouted: Rerouted::CustomTopic,+ ..Default::default()},).await;@@ -2328,11 +2951,15 @@ mod tests {redirect_to_dlq: true,redirect_to_topic: Some("custom_topic".to_string()),overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: DLQ_TOPIC,has_key: true,force_disable_person_processing: None,+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -2348,11 +2975,14 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: Some("custom_topic".to_string()),overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: "custom_topic",has_key: true,force_disable_person_processing: None,+ rerouted: Rerouted::CustomTopic,+ ..Default::default()},).await;@@ -2368,11 +2998,14 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: Some("custom_topic".to_string()),overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: "custom_topic",has_key: true,force_disable_person_processing: Some(true),+ rerouted: Rerouted::CustomTopic,+ ..Default::default()},).await;@@ -2388,74 +3021,19 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: Some("custom_topic".to_string()),overflow_reason: None,+ ..Default::default()},ExpectedRouting {topic: "custom_topic",has_key: true,force_disable_person_processing: None,+ rerouted: Rerouted::CustomTopic,+ ..Default::default()},).await;}- // ==================== DLQ Header Tests ====================- // Verify that DLQ-specific headers (reason, step, timestamp) are set- // when routing to DLQ, and absent for all other routes.-- #[tokio::test]- async fn dlq_headers_set_when_redirect_to_dlq() {- let producer = MockKafkaProducer::new();- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());-- let event = create_test_event(&EventInput {- data_type: DataType::AnalyticsMain,- force_overflow: false,- skip_person_processing: false,- redirect_to_dlq: true,- redirect_to_topic: None,- overflow_reason: None,- });- sink.send(event).await.unwrap();-- let records = producer.get_records();- assert_eq!(records.len(), 1);- let headers = &records[0].headers;-- assert_eq!(headers.dlq_reason.as_deref(), Some("event_restriction"));- assert_eq!(headers.dlq_step.as_deref(), Some("capture"));- assert!(- headers.dlq_timestamp.is_some(),- "dlq_timestamp should be set"- );-- // Verify the timestamp is a valid RFC 3339 string- let ts = headers.dlq_timestamp.as_deref().unwrap();- chrono::DateTime::parse_from_rfc3339(ts)- .unwrap_or_else(|e| panic!("dlq_timestamp '{ts}' is not valid RFC 3339: {e}"));- }-- #[tokio::test]- async fn dlq_headers_absent_for_normal_analytics() {- let producer = MockKafkaProducer::new();- let sink = KafkaSinkBase::with_producer(producer.clone(), test_topics());-- let event = create_test_event(&EventInput {- data_type: DataType::AnalyticsMain,- force_overflow: false,- skip_person_processing: false,- redirect_to_dlq: false,- redirect_to_topic: None,- overflow_reason: None,- });- sink.send(event).await.unwrap();-- let records = producer.get_records();- let headers = &records[0].headers;- assert_eq!(headers.dlq_reason, None);- assert_eq!(headers.dlq_step, None);- assert_eq!(headers.dlq_timestamp, None);- }-// ==================== overflow_reason routing tests ====================// The pipeline stamps ProcessedEventMetadata::overflow_reason upstream;// the sink is a pure mechanism layer that switches on it. These cover@@ -2464,11 +3042,21 @@ mod tests {// analytics_main_force_overflow / snapshot_main_force_overflow cases// above (force_overflow short-circuits the overflow_reason branch).+ /// `ForceLimited` implies person processing is off on its own: the+ /// header is set whether or not the stamping site also set the flag,+ /// so a keyless force-limited record can never reach person+ /// processing with identity resolution still on.+ #[rstest]+ #[case::stamped_with_flag(true)]+ #[case::reason_only(false)]#[tokio::test]- async fn overflow_reason_force_limited_routes_to_overflow_with_null_key_and_flag() {+ async fn overflow_reason_force_limited_routes_to_overflow_with_null_key(+ #[case] skip_person_processing: bool,+ ) {assert_routing(EventInput {data_type: DataType::AnalyticsMain,+ skip_person_processing,overflow_reason: Some(OverflowReason::ForceLimited),..Default::default()},@@ -2476,44 +3064,66 @@ mod tests {topic: OVERFLOW_TOPIC,has_key: false,force_disable_person_processing: Some(true),+ ..Default::default()},).await;}+ /// A person-on burst keeps its key on the analytics lane regardless of+ /// the locality preference: the overflow consumer updates persons+ /// keyed on distinct id, and spreading one distinct id across+ /// partitions contends those updates.+ #[rstest]+ #[case::preserving_locality(true)]+ #[case::spreading(false)]#[tokio::test]- async fn overflow_reason_rate_limited_preserves_key_when_preserve_locality() {+ async fn overflow_reason_rate_limited_keeps_key_while_person_processing_on(+ #[case] preserve_locality: bool,+ ) {assert_routing(EventInput {data_type: DataType::AnalyticsMain,- overflow_reason: Some(OverflowReason::RateLimited {- preserve_locality: true,- }),+ overflow_reason: Some(OverflowReason::RateLimited { preserve_locality }),..Default::default()},ExpectedRouting {topic: OVERFLOW_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;}+ /// The wire outcome for the combination the global rate limiter and the+ /// overflow limiter produce together (the GRL stamps the person flag,+ /// the burst limiter overwrites the reason): the record keeps the+ /// person-processing header and loses the partition key, on either+ /// locality setting.+ #[rstest]+ #[case::analytics_preserving(DataType::AnalyticsMain, true, OVERFLOW_TOPIC)]+ #[case::analytics_spreading(DataType::AnalyticsMain, false, OVERFLOW_TOPIC)]+ #[case::ai_preserving(DataType::AiEvents, true, AI_EVENTS_OVERFLOW_TOPIC)]#[tokio::test]- async fn overflow_reason_rate_limited_drops_key_when_not_preserve_locality() {+ async fn overflow_reason_rate_limited_drops_key_when_person_off(+ #[case] data_type: DataType,+ #[case] preserve_locality: bool,+ #[case] expected_topic: &str,+ ) {assert_routing(EventInput {- data_type: DataType::AnalyticsMain,- overflow_reason: Some(OverflowReason::RateLimited {- preserve_locality: false,- }),+ data_type,+ skip_person_processing: true,+ overflow_reason: Some(OverflowReason::RateLimited { preserve_locality }),..Default::default()},ExpectedRouting {- topic: OVERFLOW_TOPIC,+ topic: expected_topic,has_key: false,- force_disable_person_processing: None,+ force_disable_person_processing: Some(true),+ ..Default::default()},).await;@@ -2535,6 +3145,7 @@ mod tests {topic: HISTORICAL_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -2552,6 +3163,7 @@ mod tests {topic: REPLAY_OVERFLOW_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -2576,6 +3188,7 @@ mod tests {topic: OVERFLOW_TOPIC,has_key: true,force_disable_person_processing: None,+ ..Default::default()},).await;@@ -2584,7 +3197,10 @@ mod tests {#[tokio::test]async fn overflow_reason_redirect_to_dlq_wins_over_overflow_reason() {// DLQ routing is the highest-priority routing decision: it wins- // over both force_overflow and overflow_reason.+ // over both force_overflow and overflow_reason. The+ // person-processing header still travels with the ForceLimited+ // reason — routing precedence changes the topic, not the skip+ // (production stamps the flag alongside the reason anyway).assert_routing(EventInput {data_type: DataType::AnalyticsMain,@@ -2595,7 +3211,10 @@ mod tests {ExpectedRouting {topic: DLQ_TOPIC,has_key: true,- force_disable_person_processing: None,+ force_disable_person_processing: Some(true),+ dlq_headers: true,+ rerouted: Rerouted::Dlq,+ ..Default::default()},).await;@@ -2616,7 +3235,11 @@ mod tests {ExpectedRouting {topic: "custom_topic",has_key: true,- force_disable_person_processing: None,+ // The header travels with the reason regardless of the+ // routing precedence, as in the dlq case above.+ force_disable_person_processing: Some(true),+ rerouted: Rerouted::CustomTopic,+ ..Default::default()},).await;@@ -2645,6 +3268,7 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()})}).collect();@@ -2708,6 +3332,7 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()})}).collect();@@ -2722,6 +3347,7 @@ mod tests {redirect_to_dlq: false,redirect_to_topic: None,overflow_reason: None,+ ..Default::default()});bad.metadata.session_id = None;events[2] = bad;diff --git a/rust/capture/src/sinks/mod.rs b/rust/capture/src/sinks/mod.rsindex ef3d86e115bb..c5f4af0dd623 100644--- a/rust/capture/src/sinks/mod.rs+++ b/rust/capture/src/sinks/mod.rs@@ -7,6 +7,7 @@ pub mod kafka;pub mod noop;pub mod print;pub mod producer;+pub mod registry;pub mod s3;pub mod split;#[cfg(test)]diff --git a/rust/capture/src/sinks/registry.rs b/rust/capture/src/sinks/registry.rsnew file mode 100644index 000000000000..dbedfbc74573--- /dev/null+++ b/rust/capture/src/sinks/registry.rs@@ -0,0 +1,349 @@+//! Output registry — the topic-completeness surface.+//!+//! Binds every fixed routing [`Output`] variant to its configured Kafka topic+//! and provides a startup completeness check ([`OutputRegistry::check_complete`])+//! that refuses to boot when any fixed output resolves to an empty topic. This+//! is the single place the output→topic wiring lives, so adding an output is a+//! one-place change: the `topic_for` and `is_required` matches are+//! compiler-forced exhaustive, a test pins `REGISTERED` to the required set,+//! and `check_complete` catches an unwired output at boot rather than at+//! first produce.+//!+//! Two outputs sit outside the completeness check: `Custom` topics are+//! admin-supplied inline on the event's metadata (they carry their own topic),+//! and the AI outputs are opt-in — setup separately requires+//! `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` whenever the routing policy can produce+//! `AiEvents` records.++use tracing::log::warn;++use crate::config::KafkaConfig;++/// Which configured output a routing decision selects, named **pipeline ++/// lane** — the vocabulary the refactor converges on (typed per-pipeline+/// lanes; see the plan doc). The sink resolves each output to a concrete+/// topic string against the [`OutputRegistry`]; distinct outputs may share a+/// topic (analytics main and session-replay main both resolve the+/// deployment's main topic today). Mirrors v1's `Destination` split — the+/// convergence target when the v1 stack folds onto this registry (see the+/// plan doc).+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Output {+ AnalyticsMain,+ AnalyticsOverflow,+ AnalyticsHistorical,+ ClientWarningsMain,+ HeatmapsMain,+ SessionReplayMain,+ SessionReplayOverflow,+ /// Every pipeline's dlq lane; one shared output until the typed-address+ /// step gives each pipeline its own dlq row.+ Dlq,+ ErrorTrackingMain,+ /// The AI pipeline's main lane — the dedicated `$ai_*` topic+ /// (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`). Opt-in, so not part of the+ /// completeness check — setup validates it whenever the routing policy+ /// can produce `AiEvents` records.+ AiMain,+ /// The AI pipeline's overflow lane; only routed to when the AI overflow+ /// valve (`CAPTURE_ANALYTICS_AI_EVENTS_OVERFLOW_TOPIC`) is armed.+ AiOverflow,+ /// Admin-configured custom topic copied from `redirect_to_topic`. Resolved+ /// inline by the sink; never registered (it carries its own topic).+ Custom(String),+}++impl Output {+ /// Every registered always-required output. `check_complete` walks this so+ /// a newly added output is caught at boot rather than at first produce.+ const REGISTERED: [Output; 9] = [+ Output::AnalyticsMain,+ Output::AnalyticsOverflow,+ Output::AnalyticsHistorical,+ Output::ClientWarningsMain,+ Output::HeatmapsMain,+ Output::SessionReplayMain,+ Output::SessionReplayOverflow,+ Output::Dlq,+ Output::ErrorTrackingMain,+ ];++ /// Whether this output participates in the boot completeness check.+ /// Deliberately exhaustive: a new variant cannot compile without+ /// declaring which side it is on, and+ /// `registered_is_exactly_the_required_outputs` pins [`Self::REGISTERED`]+ /// to the `true` arms so declaring `true` without joining the array+ /// fails a test instead of silently skipping the check.+ #[cfg(test)]+ fn is_required(&self) -> bool {+ match self {+ Output::AnalyticsMain+ | Output::AnalyticsOverflow+ | Output::AnalyticsHistorical+ | Output::ClientWarningsMain+ | Output::HeatmapsMain+ | Output::SessionReplayMain+ | Output::SessionReplayOverflow+ | Output::Dlq+ | Output::ErrorTrackingMain => true,+ // Opt-in AI lanes (setup validates them against the routing+ // mode) and per-event custom topics sit outside the check.+ Output::AiMain | Output::AiOverflow | Output::Custom(_) => false,+ }+ }++ /// Stable, low-cardinality label for diagnostics. `Custom` collapses to+ /// "custom" so admin topic names never leak into error messages.+ fn name(&self) -> &'static str {+ match self {+ Output::AnalyticsMain => "analytics-main",+ Output::AnalyticsOverflow => "analytics-overflow",+ Output::AnalyticsHistorical => "analytics-historical",+ Output::ClientWarningsMain => "clientwarnings-main",+ Output::HeatmapsMain => "heatmaps-main",+ Output::SessionReplayMain => "sessionreplay-main",+ Output::SessionReplayOverflow => "sessionreplay-overflow",+ Output::Dlq => "dlq",+ Output::ErrorTrackingMain => "errortracking-main",+ Output::AiMain => "ai-main",+ Output::AiOverflow => "ai-overflow",+ Output::Custom(_) => "custom",+ }+ }+}++/// The one place output→topic wiring lives. Holds the configured topic for every+/// fixed [`Output`] variant. Cheap to clone; the sink holds it behind an `Arc`.+#[derive(Clone, Debug)]+pub struct OutputRegistry {+ pub(crate) main: String,+ pub(crate) overflow: String,+ pub(crate) historical: String,+ pub(crate) client_ingestion_warning: String,+ pub(crate) heatmaps: String,+ pub(crate) replay_overflow: String,+ pub(crate) dlq: String,+ pub(crate) error_tracking: String,+ /// Dedicated topic for `Output::AiMain`. Optional because the AI lane+ /// is opt-in: startup validation guarantees it is set whenever the routing+ /// policy can produce `AiEvents` records.+ pub(crate) ai_events: Option<String>,+ /// Overflow topic for the AI lane. Unset means the AI overflow valve is+ /// unarmed and routing never selects `Output::AiOverflow`.+ pub(crate) ai_events_overflow: Option<String>,+}++impl OutputRegistry {+ /// Resolve an output to its topic. Fixed outputs read the registered topic;+ /// `Custom` returns its inline, admin-supplied topic.+ ///+ /// An unset AI topic should be impossible for a reachable AI output+ /// (startup validation requires `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`+ /// whenever the routing policy can produce `AiEvents`), so it falls back+ /// to the main topic rather than failing the batch.+ pub fn topic_for<'a>(&'a self, output: &'a Output) -> &'a str {+ match output {+ Output::AnalyticsMain | Output::SessionReplayMain => &self.main,+ Output::AnalyticsOverflow => &self.overflow,+ Output::AnalyticsHistorical => &self.historical,+ Output::ClientWarningsMain => &self.client_ingestion_warning,+ Output::HeatmapsMain => &self.heatmaps,+ Output::SessionReplayOverflow => &self.replay_overflow,+ Output::Dlq => &self.dlq,+ Output::ErrorTrackingMain => &self.error_tracking,+ Output::AiMain => self.ai_events_topic_or_fallback(),+ Output::AiOverflow => match self.ai_events_overflow.as_deref() {+ Some(topic) if !topic.is_empty() => topic,+ // Unreachable: routing only selects this output when the+ // valve is armed, i.e. exactly when the topic is set.+ _ => self.ai_events_topic_or_fallback(),+ },+ Output::Custom(topic) => topic,+ }+ }++ /// Whether the AI overflow valve is armed: the AI overflow topic is wired,+ /// so routing may select `Output::AiOverflow`.+ pub fn ai_events_overflow_armed(&self) -> bool {+ self.ai_events_overflow+ .as_deref()+ .is_some_and(|t| !t.is_empty())+ }++ fn ai_events_topic_or_fallback(&self) -> &str {+ match self.ai_events.as_deref() {+ Some(topic) if !topic.is_empty() => topic,+ _ => {+ warn!(+ "CAPTURE_ANALYTICS_AI_EVENTS_TOPIC not configured for an AiEvents record; falling back to main topic"+ );+ &self.main+ }+ }+ }++ /// Startup completeness check: every registered output must resolve to a+ /// non-empty topic, so a misconfigured or newly-added-but-unwired output+ /// fails fast at boot instead of at first produce. `Custom` is excluded (it carries its own topic per event), as+ /// are the opt-in AI outputs (validated by setup against the routing mode).+ pub fn check_complete(&self) -> anyhow::Result<()> {+ for output in &Output::REGISTERED {+ anyhow::ensure!(+ !self.topic_for(output).is_empty(),+ "output '{}' resolves to an empty Kafka topic; every non-custom \+ output must be bound to a configured, non-empty topic",+ output.name(),+ );+ }+ Ok(())+ }+}++impl From<&KafkaConfig> for OutputRegistry {+ fn from(config: &KafkaConfig) -> Self {+ Self {+ main: config.kafka_topic.clone(),+ overflow: config.kafka_overflow_topic.clone(),+ historical: config.kafka_historical_topic.clone(),+ client_ingestion_warning: config.kafka_client_ingestion_warning_topic.clone(),+ heatmaps: config.kafka_heatmaps_topic.clone(),+ replay_overflow: config.kafka_replay_overflow_topic.clone(),+ dlq: config.kafka_dlq_topic.clone(),+ error_tracking: config.kafka_error_tracking_topic.clone(),+ ai_events: config.capture_analytics_ai_events_topic.clone(),+ ai_events_overflow: config.capture_analytics_ai_events_overflow_topic.clone(),+ }+ }+}++/// Shared `OutputRegistry` fixture for tests across the capture crate. Used by+/// sink-side routing tests and pipeline-to-sink E2E tests so every test site+/// asserts against the same canonical topic names.+#[cfg(test)]+pub(crate) fn test_topics() -> OutputRegistry {+ OutputRegistry {+ main: "events_plugin_ingestion".to_string(),+ overflow: "events_plugin_ingestion_overflow".to_string(),+ historical: "events_plugin_ingestion_historical".to_string(),+ client_ingestion_warning: "client_ingestion_warning".to_string(),+ heatmaps: "heatmaps".to_string(),+ replay_overflow: "replay_overflow".to_string(),+ dlq: "events_plugin_ingestion_dlq".to_string(),+ error_tracking: "error_tracking_events".to_string(),+ ai_events: Some("ai_events".to_string()),+ ai_events_overflow: Some("ai_events_overflow".to_string()),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use rstest::rstest;++ #[rstest]+ #[case(Output::AnalyticsMain, "events_plugin_ingestion")]+ #[case(Output::SessionReplayMain, "events_plugin_ingestion")]+ #[case(Output::AnalyticsOverflow, "events_plugin_ingestion_overflow")]+ #[case(Output::AnalyticsHistorical, "events_plugin_ingestion_historical")]+ #[case(Output::ClientWarningsMain, "client_ingestion_warning")]+ #[case(Output::HeatmapsMain, "heatmaps")]+ #[case(Output::SessionReplayOverflow, "replay_overflow")]+ #[case(Output::Dlq, "events_plugin_ingestion_dlq")]+ #[case(Output::ErrorTrackingMain, "error_tracking_events")]+ #[case(Output::AiMain, "ai_events")]+ #[case(Output::AiOverflow, "ai_events_overflow")]+ fn topic_for_resolves_registered_outputs(#[case] output: Output, #[case] expected: &str) {+ assert_eq!(test_topics().topic_for(&output), expected);+ }++ #[test]+ fn topic_for_custom_returns_inline_topic() {+ let registry = test_topics();+ assert_eq!(+ registry.topic_for(&Output::Custom("admin_topic".to_string())),+ "admin_topic"+ );+ }++ /// Unset AI topics carry no completeness requirement (they are opt-in) and+ /// degrade to the main topic instead of failing the batch.+ #[test]+ fn unset_ai_outputs_fall_back_to_main() {+ let mut registry = test_topics();+ registry.ai_events = None;+ registry.ai_events_overflow = None;+ assert!(registry.check_complete().is_ok());+ assert!(!registry.ai_events_overflow_armed());+ assert_eq!(+ registry.topic_for(&Output::AiMain),+ "events_plugin_ingestion"+ );+ assert_eq!(+ registry.topic_for(&Output::AiOverflow),+ "events_plugin_ingestion"+ );+ }++ #[test]+ fn check_complete_accepts_full_registry() {+ assert!(test_topics().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.+ #[test]+ fn registered_is_exactly_the_required_outputs() {+ let all = [+ Output::AnalyticsMain,+ Output::AnalyticsOverflow,+ Output::AnalyticsHistorical,+ Output::ClientWarningsMain,+ Output::HeatmapsMain,+ Output::SessionReplayMain,+ Output::SessionReplayOverflow,+ Output::Dlq,+ Output::ErrorTrackingMain,+ Output::AiMain,+ Output::AiOverflow,+ Output::Custom("t".to_string()),+ ];+ for output in &all {+ assert_eq!(+ Output::REGISTERED.contains(output),+ output.is_required(),+ "'{}' must be in REGISTERED exactly when it is required",+ output.name()+ );+ }+ }++ /// Every registered output, blanked one at a time, must fail the check and+ /// the error must name the offending output.+ #[rstest]+ #[case("analytics-main", |r: &mut OutputRegistry| r.main.clear())]+ #[case("analytics-overflow", |r: &mut OutputRegistry| r.overflow.clear())]+ #[case("analytics-historical", |r: &mut OutputRegistry| r.historical.clear())]+ #[case("clientwarnings-main", |r: &mut OutputRegistry| r.client_ingestion_warning.clear())]+ #[case("heatmaps-main", |r: &mut OutputRegistry| r.heatmaps.clear())]+ #[case("sessionreplay-overflow", |r: &mut OutputRegistry| r.replay_overflow.clear())]+ #[case("dlq", |r: &mut OutputRegistry| r.dlq.clear())]+ #[case("errortracking-main", |r: &mut OutputRegistry| r.error_tracking.clear())]+ fn check_complete_rejects_empty_topic(+ #[case] output_name: &str,+ #[case] blank: fn(&mut OutputRegistry),+ ) {+ let mut registry = test_topics();+ blank(&mut registry);+ let err = registry+ .check_complete()+ .expect_err("blank topic must fail the completeness check");+ let msg = format!("{err:#}");+ assert!(+ msg.contains(output_name),+ "error should name the missing output '{output_name}': {msg}"+ );+ }+}diff --git a/rust/capture/src/v0_request.rs b/rust/capture/src/v0_request.rsindex 4ecb06a5e96b..77f3f8b5e4c5 100644--- a/rust/capture/src/v0_request.rs+++ b/rust/capture/src/v0_request.rs@@ -284,9 +284,14 @@ pub struct ProcessedEvent {/// for overflow beyond this mapping.#[derive(Debug, Clone, PartialEq, Eq)]pub enum OverflowReason {- /// Governor matched a configured `keys_to_reroute` entry for this event's- /// key. Events in this state always have `skip_person_processing = true`- /// and are routed to the overflow topic with a null partition key.+ /// The overflow governor matched a configured `keys_to_reroute` entry+ /// for this event's key, or the global rate limiter put the key over its+ /// window. Routed to the overflow topic with a null partition key, with+ /// person processing off: the reason itself implies the skip+ /// ([`ProcessedEventMetadata::person_processing_disabled`]), so a+ /// stamping site cannot keep person processing on for a force-limited+ /// key by forgetting the flag. Stamping sites still set+ /// `skip_person_processing = true` alongside for pipeline-level readers.ForceLimited,/// Per-key rate exceeded the configured governor quota. Routed to the/// overflow topic. `preserve_locality` mirrors the@@ -327,6 +332,17 @@ pub struct ProcessedEventMetadata {pub distinct_id_truncated_from: Option<usize>,}+impl ProcessedEventMetadata {+ /// Whether person processing is off for this event: the stamped flag, or+ /// a `ForceLimited` reason — force-limiting implies the skip, so the+ /// sink's header and ordering cannot silently keep person processing on+ /// for a force-limited key whose stamping site forgot the flag.+ pub fn person_processing_disabled(&self) -> bool {+ self.skip_person_processing+ || matches!(self.overflow_reason, Some(OverflowReason::ForceLimited))+ }+}+#[cfg(test)]mod tests {use crate::token::InvalidTokenReason;diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex e76da6fd16c6..3cc954f59f01 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -153,9 +153,12 @@ pub async fn process_batch(// DIVERGENCE from legacy (`events::analytics`), intentional and out of scope// to reconcile here — a future routing refactor must not assume parity:// 1. Ordering: v1 runs this GRL step AFTER burst overflow stamping (above);- // legacy runs its GRL BEFORE overflow stamping. Both set overflow on- // AnalyticsMain/Destination::Overflow only, so the end state matches,- // but the pass order differs.+ // legacy runs its GRL BEFORE overflow stamping. The pass order differs,+ // but the observable outcome does not: both reroute only+ // AnalyticsMain/Destination::Overflow, and both drop the partition key+ // once person processing is off, so a key the GRL wanted spread stays+ // spread on either path even when the burst limiter preserves locality.+ // `crate::overflow_parity` pins that across the whole matrix.// 2. Lane assignment is assign-then-reroute in v1 versus a single// `DataType::from_event_name` match in legacy.// Both paths consult the same shared limiter for every non-dropped event, so@@ -505,6 +508,7 @@ fn validate_events(details: Some(DETAIL_INVALID_OPTIONS),destination,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,});continue;@@ -534,6 +538,7 @@ fn validate_events(},destination,force_disable_person_processing: illegal,+ spread_partitions: false,is_gateway_verified: false,});}@@ -547,6 +552,7 @@ fn validate_events(details: Some(err.tag()),destination,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,});}@@ -714,16 +720,24 @@ fn apply_overflow_stamping(match limiter.is_limited(&key) {OverflowLimiterResult::ForceLimited => {event.destination = overflow_destination;- // Disables person processing AND nulls partition key at sink.+ // A force-limited key is hot enough that we both spread it and+ // stop paying for identity resolution on it, matching v0's+ // ForceLimited arm.event.force_disable_person_processing = true;+ event.spread_partitions = true;metrics::counter!(CAPTURE_V1_OVERFLOW_ROUTED, "reason" => "force_limited").increment(1);}OverflowLimiterResult::Limited => {event.destination = overflow_destination;if !limiter.should_preserve_locality() {- // Nulls partition key at sink -- spreads across partitions.- event.force_disable_person_processing = true;+ // Spread only. Person processing stays on, because a burst+ // over the per-second budget says nothing about whether the+ // customer wants identity resolution for this event. On the+ // person-writing analytics lane the sink holds the key+ // until person processing is off (`WrappedEvent::ordering`);+ // the read-only AI overflow lane spreads immediately.+ event.spread_partitions = true;}metrics::counter!(CAPTURE_V1_OVERFLOW_ROUTED, "reason" => "rate_limited").increment(1);@@ -847,11 +861,15 @@ async fn apply_token_distinct_id_limits(let limited = limiter.is_limited(&cache_key, 1).await.is_some();// Person processing is already off for this event (illegal distinct_id,- // an ops restriction, or burst overflow stamping upstream). Its volume+ // an ops restriction, or a force-limited key upstream). Its volume// still counts toward the shared window above -- v0 and v1 feed one// limiter instance, so both must consult it for every non-dropped event// to keep the per-key counts identical. The stamps below would be// redundant here, so skip them.+ //+ // A merely rate-limited burst does NOT land here: it sets+ // `spread_partitions` without touching person processing, so such an+ // event still gets its warning stamped below, as it does on the v0 path.if event.force_disable_person_processing {already_disabled_count += 1;continue;@@ -859,7 +877,8 @@ async fn apply_token_distinct_id_limits(if limited {event.result = EventResult::Warning;- // Disables person processing -- sink will null partition key for Main/Overflow.+ // Disabling person processing also drops the ordering guarantee on+ // the main/overflow lanes, via `WrappedEvent::ordering`.event.force_disable_person_processing = true;event.details = Some(DETAIL_PERSON_PROCESSING_DISABLED);// Reroute to overflow to spread a hot token:distinct_id across@@ -2471,6 +2490,45 @@ mod tests {assert_eq!(limited.details, Some(DETAIL_PERSON_PROCESSING_DISABLED));}+ /// The two stages run in v1's production order: the burst limiter first,+ /// then the global rate limiter. A key that trips both must still get its+ /// warning, because the global limiter skips events whose person processing+ /// is already off, and a burst used to leave that flag set on its way past.+ /// The legacy path always warns here (its global limiter runs first), so+ /// swallowing it would drop a customer-visible warning on v1 only.+ ///+ /// The spread stamp itself is covered by+ /// `overflow_rate_limited_stamps_spread_without_disabling_person_processing`;+ /// this case exists for the warning and the tally.+ #[tokio::test]+ async fn burst_overflow_then_global_limit_still_warns() {+ let mut ctx = test_utils::test_context();+ ctx.api_token = "phc_tok".to_string();+ let burst = overflow_limiter(1, 1, None);+ let global = mock_limiter(vec!["phc_tok:user-1"]);+ let mut events = vec![+ wrapped_event("$pageview", "user-1"),+ wrapped_event("$pageview", "user-1"),+ ];++ apply_overflow_stamping(Some(&burst), None, &ctx, &mut events);+ let tally = apply_token_distinct_id_limits(&global, &ctx, None, &mut events).await;++ // events[1] is the one the burst limiter sent to overflow.+ let spread = &events[1];+ assert_eq!(+ spread.result,+ EventResult::Warning,+ "a spread key must still be warned about when the global limiter hits it"+ );+ assert_eq!(spread.details, Some(DETAIL_PERSON_PROCESSING_DISABLED));+ assert_eq!(+ tally.already_disabled, 0,+ "spreading must not look like person processing was already off"+ );+ assert_eq!(tally.limited, 2);+ }+#[tokio::test]async fn td_limits_evaluates_but_does_not_restamp_force_disable_pp() {// An event that already has person processing disabled (illegal@@ -3064,6 +3122,7 @@ mod tests {apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);assert_eq!(events[0].destination, Destination::Overflow);+ assert!(events[0].spread_partitions);assert!(events[0].force_disable_person_processing);}@@ -3077,11 +3136,12 @@ mod tests {apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);assert_eq!(events[0].destination, Destination::Overflow);+ assert!(events[0].spread_partitions);assert!(events[0].force_disable_person_processing);}#[test]- fn overflow_rate_limited_disables_person_processing() {+ fn overflow_rate_limited_stamps_spread_without_disabling_person_processing() {let mut ctx = test_utils::test_context();ctx.api_token = "phc_tok".to_string();// burst=1 means only 1 event allowed, the second will be limited@@ -3094,9 +3154,18 @@ mod tests {apply_overflow_stamping(Some(&limiter), None, &ctx, &mut events);assert_eq!(events[0].destination, Destination::AnalyticsMain);+ assert!(!events[0].spread_partitions);assert!(!events[0].force_disable_person_processing);+assert_eq!(events[1].destination, Destination::Overflow);- assert!(events[1].force_disable_person_processing);+ assert!(+ events[1].spread_partitions,+ "a bursting key must carry the spread stamp"+ );+ assert!(+ !events[1].force_disable_person_processing,+ "exceeding the burst budget must not skip identity resolution"+ );}#[test]@@ -3113,9 +3182,10 @@ mod tests {assert_eq!(events[1].destination, Destination::Overflow);assert!(- !events[1].force_disable_person_processing,- "preserve_locality=true means person processing stays enabled"+ !events[1].spread_partitions,+ "preserve_locality=true keeps the partition key");+ assert!(!events[1].force_disable_person_processing);}#[test]@@ -3191,9 +3261,31 @@ mod tests {assert_eq!(events[0].destination, Destination::AiEvents);assert_eq!(events[1].destination, Destination::AiEventsOverflow);assert!(- !events[1].force_disable_person_processing,- "preserve_locality=true means person processing stays enabled"+ !events[1].spread_partitions,+ "preserve_locality=true keeps the partition key");+ assert!(!events[1].force_disable_person_processing);+ }++ /// The AI lane gets the same decoupling as the analytics lane: a burst over+ /// the budget spreads the key without disabling person processing.+ #[test]+ fn overflow_ai_events_rate_limited_spreads_without_disabling_person_processing() {+ let mut ctx = test_utils::test_context();+ ctx.api_token = "phc_tok".to_string();+ let limiter = overflow_limiter(1, 1, None);+ let mut events = vec![+ wrapped_event("$ai_generation", "user-1"),+ wrapped_event("$ai_generation", "user-1"),+ ];+ events[0].destination = Destination::AiEvents;+ events[1].destination = Destination::AiEvents;++ apply_overflow_stamping(None, Some(&limiter), &ctx, &mut events);++ assert_eq!(events[1].destination, Destination::AiEventsOverflow);+ assert!(events[1].spread_partitions);+ assert!(!events[1].force_disable_person_processing);}/// The two lanes consult separate limiter instances: a key the analyticsdiff --git a/rust/capture/src/v1/analytics/response.rs b/rust/capture/src/v1/analytics/response.rsindex 407ecce7a3c4..14202d9d628e 100644--- a/rust/capture/src/v1/analytics/response.rs+++ b/rust/capture/src/v1/analytics/response.rs@@ -184,6 +184,7 @@ mod tests {details,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,}}diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rsindex f3a9308f79c2..ed45565cd510 100644--- a/rust/capture/src/v1/analytics/types.rs+++ b/rust/capture/src/v1/analytics/types.rs@@ -23,6 +23,7 @@ impl io::Write for StringWriter<'_> {}}+use crate::ordering::{person_ordering, OrderingGuarantee};use crate::v1::context::RequestContext;use crate::v1::sinks::event::Event as SinkEvent;use crate::v1::sinks::Destination;@@ -217,6 +218,15 @@ pub struct WrappedEvent {pub details: Option<&'static str>,pub destination: Destination,pub force_disable_person_processing: bool,+ /// Set when the overflow limiter decided this key is bursting and should+ /// be spread across the overflow topic's partitions. Deliberately separate+ /// from `force_disable_person_processing`: spreading a hot key is a+ /// partitioning decision, while disabling person processing is a+ /// customer-visible instruction to skip identity resolution, and the+ /// overflow limiter only means the former. Consumed by `ordering()`,+ /// which realizes it only on lanes whose consumers do not write persons —+ /// elsewhere the key holds until person processing is off.+ pub spread_partitions: bool,/// Set by the gateway-provenance step when a valid signature was verified;/// read by the quota shim to exempt the event from the llm_events limiter.pub is_gateway_verified: bool,@@ -248,10 +258,10 @@ impl SinkEvent for WrappedEvent {// backend-specific format (e.g. OwnedHeaders for Kafka) via the From impl// in common_types — same conversion legacy capture uses.fn headers(&self, ctx: &RequestContext) -> CapturedEventHeaders {- // v0 compat: downstream consumers key on "force_disable_person_processing".- // v1 decouples overflow routing from person-processing (unlike v0 where- // overflow ForceLimited unconditionally sets this); operators configure- // this flag alongside ForceOverflow when needed.+ // Downstream treats this header as absolute: `decideProcessPerson` in+ // nodejs/src/common/persons/person-utils.ts skips person processing+ // outright when it is set. So it carries only the person-processing+ // decision, never the partitioning one, which travels as `ordering()`.let force_disable_person_processing = if self.force_disable_person_processing {Some(true)} else {@@ -319,6 +329,26 @@ impl SinkEvent for WrappedEvent {buf}+ /// Computed here rather than stamped during processing because it depends+ /// on the final destination: `apply_restrictions` can disable person+ /// processing while an event is still `AnalyticsMain`, and+ /// `apply_historical_rerouting` may afterwards move it to+ /// `AnalyticsHistorical`, whose consumers need the key. Deciding late+ /// keeps the rule correct no matter how the stages are ordered.+ fn ordering(&self) -> OrderingGuarantee {+ if !self.destination.absorbs_hot_keys() {+ return OrderingGuarantee::PerDistinctId;+ }+ // A spread decision takes effect on its own only where the consumer+ // does not write persons; on person-writing lanes the key holds until+ // person processing is off, so the person flag alone decides there+ // (see `Destination::writes_persons`).+ if self.spread_partitions && !self.destination.writes_persons() {+ return OrderingGuarantee::None;+ }+ person_ordering(self.force_disable_person_processing)+ }+fn serialize(&self, ctx: &RequestContext) -> anyhow::Result<bytes::Bytes> {let spliced = self.build_spliced_properties(ctx)?;let properties: &RawValue = spliced.as_deref().unwrap_or(&self.event.properties);@@ -1024,6 +1054,100 @@ mod tests {test_utils::wrapped_event(event_name, distinct_id)}+ /// One row of the ordering matrix: the lane, plus the two event stamps+ /// `ordering()` consults — `person_off` mirrors+ /// `force_disable_person_processing`, `spread` mirrors `spread_partitions`.+ struct Stamps {+ destination: Destination,+ person_off: bool,+ spread: bool,+ }++ impl Stamps {+ fn on(destination: Destination) -> Self {+ Self {+ destination,+ person_off: false,+ spread: false,+ }+ }+ }++ /// The ordering rule, per lane and per reason for giving ordering up. The+ /// `spread`-without-`person_off` rows are the ones that matter most:+ /// on the person-writing analytics lanes a bursting key must keep its+ /// partition key while person processing is on (spreading one distinct id+ /// across partitions contends the consumer's person updates), while the+ /// read-only AI overflow lane spreads it immediately.+ #[rstest::rstest]+ #[case::main_untouched(+ Stamps::on(Destination::AnalyticsMain),+ OrderingGuarantee::PerDistinctId+ )]+ #[case::main_person_off(+ Stamps { person_off: true, ..Stamps::on(Destination::AnalyticsMain) },+ OrderingGuarantee::None+ )]+ #[case::main_spread(+ Stamps { spread: true, ..Stamps::on(Destination::AnalyticsMain) },+ OrderingGuarantee::PerDistinctId+ )]+ #[case::overflow_untouched(Stamps::on(Destination::Overflow), OrderingGuarantee::PerDistinctId)]+ #[case::overflow_person_off(+ Stamps { person_off: true, ..Stamps::on(Destination::Overflow) },+ OrderingGuarantee::None+ )]+ #[case::overflow_spread(+ Stamps { spread: true, ..Stamps::on(Destination::Overflow) },+ OrderingGuarantee::PerDistinctId+ )]+ #[case::overflow_spread_person_off(+ Stamps { person_off: true, spread: true, ..Stamps::on(Destination::Overflow) },+ OrderingGuarantee::None+ )]+ #[case::ai_overflow_spread(+ Stamps { spread: true, ..Stamps::on(Destination::AiEventsOverflow) },+ OrderingGuarantee::None+ )]+ #[case::ai_overflow_person_off(+ Stamps { person_off: true, ..Stamps::on(Destination::AiEventsOverflow) },+ OrderingGuarantee::None+ )]+ // Lanes whose consumers need the key regardless: person processing being+ // off must not spread them, matching v0's route().+ #[case::ai_main_person_off(+ Stamps { person_off: true, ..Stamps::on(Destination::AiEvents) },+ OrderingGuarantee::PerDistinctId+ )]+ #[case::historical_person_off(+ Stamps { person_off: true, ..Stamps::on(Destination::AnalyticsHistorical) },+ OrderingGuarantee::PerDistinctId+ )]+ #[case::dlq_person_off(+ Stamps { person_off: true, ..Stamps::on(Destination::Dlq) },+ OrderingGuarantee::PerDistinctId+ )]+ #[case::custom_person_off(+ Stamps { person_off: true, ..Stamps::on(Destination::Custom("t".into())) },+ OrderingGuarantee::PerDistinctId+ )]+ fn ordering_per_lane(#[case] stamps: Stamps, #[case] expected: OrderingGuarantee) {+ let ctx = test_utils::test_context();+ let mut ev = ok_wrapped("$pageview", "user-1");+ ev.destination = stamps.destination;+ ev.force_disable_person_processing = stamps.person_off;+ ev.spread_partitions = stamps.spread;++ assert_eq!(ev.ordering(), expected);+ // The header tracks the person-processing flag and nothing else, so+ // spreading a key never asks downstream to skip identity resolution.+ assert_eq!(+ ev.headers(&ctx).force_disable_person_processing,+ stamps.person_off.then_some(true),+ "the header must follow the person flag alone"+ );+ }+#[rstest::rstest]#[case::ok_main(EventResult::Ok, Destination::AnalyticsMain)]#[case::ok_historical(EventResult::Ok, Destination::AnalyticsHistorical)]@@ -1329,6 +1453,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,}}@@ -1511,6 +1636,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,};@@ -1553,6 +1679,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,};@@ -1594,6 +1721,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,};@@ -1632,6 +1760,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,};@@ -1673,6 +1802,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,};@@ -1792,6 +1922,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: true,+ spread_partitions: false,is_gateway_verified: false,};@@ -1835,6 +1966,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,};@@ -1876,6 +2008,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,};@@ -1913,6 +2046,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,};diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex d4278d1b6334..082f1bd8e624 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -171,6 +171,7 @@ mod tests {kafka_heatmaps_topic: "events_plugin_ingestion".to_string(),kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),+ outputs_completeness_check_enabled: true,capture_analytics_ai_events_topic: None,capture_analytics_ai_events_overflow_topic: None,kafka_traces_topic: "ingestion_traces".to_string(),@@ -341,6 +342,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,}}diff --git a/rust/capture/src/v1/sinks/DESIGN.md b/rust/capture/src/v1/sinks/DESIGN.mdindex 01debb91a451..e5afb7e73dd9 100644--- a/rust/capture/src/v1/sinks/DESIGN.md+++ b/rust/capture/src/v1/sinks/DESIGN.md@@ -624,13 +624,11 @@ If `producer.send()` returns `QueueFull`, the event is failed immediatelyas a retriable error. Backpressure is handled by librdkafka's internalqueue and the client-level retry mechanism, not an app-level sleep loop.-`effective_partition_key()` (`kafka/sink.rs`) decides whether the-prepared key should be nulled. Prepared events always carry a key;-the sink nulls it when-`force_disable_person_processing` is set and the destination is-`AnalyticsMain` or `Overflow`. In that case `None` is passed to rdkafka-so it round-robins; passing `Some("")` would hash to a single-deterministic partition via murmur2, creating a hot partition.+Prepared events always carry a key; the sink uses it unless+`PreparedEvent::ordering` is `OrderingGuarantee::None`, in which case+`None` is passed to rdkafka so it round-robins. Passing `Some("")` would+hash to a single deterministic partition via murmur2, creating a hot+partition. See §9 for how the guarantee is decided.### Phase 2 — Drain@@ -1133,29 +1131,44 @@ and the sink:└───────────────────────────────────────────────────┘```-2. **`should_null_partition_key()`** (`kafka/sink.rs`) decides whether- the prepared key should be nulled before sending to the producer:--```rust-fn should_null_partition_key(- force_disable_person_processing: bool,- destination: &Destination,-) -> bool-```-- If `force_disable_person_processing` is set and the destination is- `AnalyticsMain` or `Overflow`, it returns `true` and the sink passes- `None` to rdkafka. Otherwise the sink passes- `Some(prepared.partition_key)`.+2. **`PreparedEvent::ordering`** decides whether the prepared key is used.+ `Event::ordering()` returns an `OrderingGuarantee` (`crate::ordering`,+ shared with the v0 sink) and the sink passes `None` to rdkafka for+ `OrderingGuarantee::None`, `Some(prepared.partition_key)` otherwise.++ `WrappedEvent::ordering` gives up the guarantee only on the lanes that+ exist to absorb hot keys (`AnalyticsMain`, `Overflow`,+ `AiEventsOverflow`). On the person-writing lanes (`AnalyticsMain`,+ `Overflow`) that takes `force_disable_person_processing`; a+ `spread_partitions` stamp alone takes effect only on the read-only+ `AiEventsOverflow` lane (`Destination::writes_persons`). It is computed+ at prepare time rather than stamped during processing because it+ depends on the final destination, which `apply_historical_rerouting`+ can still change after `apply_restrictions` has disabled person+ processing.Key design choices:+- **The person-processing header is not a control channel.** Nulling the+ key is driven by `ordering`, never by reading+ `headers.force_disable_person_processing` back out. That header is an+ instruction to downstream to skip identity resolution, so using it to+ request partition spreading silently disabled person processing for+ every rate-limited overflow event.+- **`spread_partitions` is separate from person processing.** The overflow+ limiter sets it alone when a key merely exceeds its burst budget, leaving+ person processing on. The sink realizes the spread only where the+ consumer does not write persons (the AI overflow lane); on the analytics+ lanes the key holds until person processing is off, because spreading one+ distinct id across partitions contends the consumer's person updates. A+ `ForceLimited` verdict sets both flags, matching v0.- **`None` = round-robin.** `None` is passed to rdkafka, whichround-robins across partitions. Passing `Some("")` would hash to asingle deterministic partition via murmur2, creating a hot spot.-- **DLQ/Historical/Custom retain key** even when- `force_disable_person_processing` is set — only Main and Overflow- drop the key, matching v0 behavior.+- **DLQ/Historical/Custom/AI-main retain key** even when+ `force_disable_person_processing` is set. Only the analytics main and+ overflow lanes and the AI overflow lane drop it, matching v0's+ `route()`.- **Cookieless mode** uses `token:client_ip` as partition key insteadof `token:distinct_id`, with IP redacted to `127.0.0.1` for`capture_internal` requests.diff --git a/rust/capture/src/v1/sinks/event.rs b/rust/capture/src/v1/sinks/event.rsindex 29ba3b72cb39..33436d7f830b 100644--- a/rust/capture/src/v1/sinks/event.rs+++ b/rust/capture/src/v1/sinks/event.rs@@ -1,6 +1,7 @@use common_types::CapturedEventHeaders;use uuid::Uuid;+use crate::ordering::OrderingGuarantee;use crate::v1::context::RequestContext;use crate::v1::sinks::Destination;@@ -27,11 +28,16 @@ pub trait Event: Send + Sync {/// `common_types`).fn headers(&self, ctx: &RequestContext) -> CapturedEventHeaders;- /// Return the partition key for this event.- /// The sink decides whether to use it or null it based on routing policy- /// (e.g. force_disable_person_processing).+ /// Return the partition key for this event. Whether the sink actually uses+ /// it is decided by [`Event::ordering`], not by inspecting headers.fn partition_key(&self, ctx: &RequestContext) -> String;+ /// The ordering guarantee this event's destination must preserve. The sink+ /// realizes [`OrderingGuarantee::None`] by publishing without a partition+ /// key so the broker round-robins; every other guarantee uses+ /// [`Event::partition_key`], which supplies the value that preserves it.+ fn ordering(&self) -> OrderingGuarantee;+/// Serialize the event payload and return the raw bytes. `Bytes` (not/// `String`) so non-UTF-8 / binary payloads (e.g. replay) share this/// contract, and so a serialized payload can be cheaply cloned acrossdiff --git a/rust/capture/src/v1/sinks/kafka/mock.rs b/rust/capture/src/v1/sinks/kafka/mock.rsindex 1be572771ce8..ea61b9d812e4 100644--- a/rust/capture/src/v1/sinks/kafka/mock.rs+++ b/rust/capture/src/v1/sinks/kafka/mock.rs@@ -5,6 +5,7 @@ use std::sync::{Arc, Mutex};use std::time::Duration;use rdkafka::error::KafkaError;+use rdkafka::message::{Headers, OwnedHeaders};use crate::v1::sinks::kafka::producer::{ProduceError, ProduceRecord};use crate::v1::sinks::SinkName;@@ -18,15 +19,36 @@ pub struct OwnedProduceRecord {pub topic: String,pub key: Option<String>,pub payload: String,+ pub headers: Vec<(String, Option<String>)>,+}++impl OwnedProduceRecord {+ /// The value of a wire header, or `None` when it was not stamped.+ pub fn header(&self, key: &str) -> Option<&str> {+ self.headers+ .iter()+ .find(|(k, _)| k == key)+ .and_then(|(_, v)| v.as_deref())+ }+}++/// Headers travel to the broker as bytes, so tests read them back the way a+/// consumer would rather than trusting the typed struct they came from.+fn owned_headers(headers: &OwnedHeaders) -> Vec<(String, Option<String>)> {+ (0..headers.count())+ .map(|i| {+ let h = headers.get(i);+ (+ h.key.to_owned(),+ h.value.map(|v| String::from_utf8_lossy(v).into_owned()),+ )+ })+ .collect()}impl<'a> From<ProduceRecord<'a>> for OwnedProduceRecord {fn from(r: ProduceRecord<'a>) -> Self {- Self {- topic: r.topic.to_owned(),- key: r.key.map(str::to_owned),- payload: String::from_utf8_lossy(r.payload).into_owned(),- }+ Self::from(&r)}}@@ -36,6 +58,7 @@ impl<'a> From<&ProduceRecord<'a>> for OwnedProduceRecord {topic: r.topic.to_owned(),key: r.key.map(str::to_owned),payload: String::from_utf8_lossy(r.payload).into_owned(),+ headers: owned_headers(&r.headers),}}}diff --git a/rust/capture/src/v1/sinks/kafka/sink.rs b/rust/capture/src/v1/sinks/kafka/sink.rsindex 20c6bba9bd58..c183d56de00b 100644--- a/rust/capture/src/v1/sinks/kafka/sink.rs+++ b/rust/capture/src/v1/sinks/kafka/sink.rs@@ -13,9 +13,10 @@ use tracing::Level;use uuid::Uuid;use crate::config::CaptureMode;+use crate::ordering::OrderingGuarantee;use crate::v1::context::RequestContext;use crate::v1::sinks::sink::Sink;-use crate::v1::sinks::types::{BatchSummary, Destination, Outcome, PreparedEvent, SinkResult};+use crate::v1::sinks::types::{BatchSummary, Outcome, PreparedEvent, SinkResult};use crate::v1::sinks::{Config, SinkName};use super::constants::*;@@ -23,21 +24,6 @@ use super::producer::ProduceRecord;use super::types::{KafkaResult, KafkaSinkError};use super::KafkaProducerTrait;-/// Returns true when the partition key should be nulled — i.e. when person-/// processing is force-disabled for Main/Overflow-shaped destinations-/// (including the AI lane's own overflow), spreading load across partitions-/// instead of hotspotting on a single key.-fn should_null_partition_key(- force_disable_person_processing: bool,- destination: &Destination,-) -> bool {- force_disable_person_processing- && matches!(- destination,- Destination::AnalyticsMain | Destination::Overflow | Destination::AiEventsOverflow- )-}-/// Shared label values for metrics emitted within a single `publish_batch` call.struct MetricLabels {sink: &'static str,@@ -158,16 +144,12 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {None => continue,};- let key = if should_null_partition_key(- event- .headers- .force_disable_person_processing- .unwrap_or(false),- &event.destination,- ) {- None- } else {- Some(event.partition_key.as_str())+ // `None` is passed to rdkafka so it round-robins. Passing+ // `Some("")` would hash to a single deterministic partition via+ // murmur2, which is the hot partition this is meant to avoid.+ let key = match event.ordering {+ OrderingGuarantee::None => None,+ _ => Some(event.partition_key.as_str()),};let headers: rdkafka::message::OwnedHeaders = event.headers.clone().into();@@ -453,26 +435,6 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {}}-#[cfg(test)]-mod should_null_partition_key_tests {- use super::*;- use rstest::rstest;-- #[rstest]- #[case::main_disabled(true, Destination::AnalyticsMain, true)]- #[case::overflow_disabled(true, Destination::Overflow, true)]- #[case::ai_overflow_disabled(true, Destination::AiEventsOverflow, true)]- #[case::ai_disabled(true, Destination::AiEvents, false)]- #[case::dlq_disabled(true, Destination::Dlq, false)]- #[case::historical_disabled(true, Destination::AnalyticsHistorical, false)]- #[case::custom_disabled(true, Destination::Custom("t".into()), false)]- #[case::main_not_disabled(false, Destination::AnalyticsMain, false)]- #[case::ai_overflow_not_disabled(false, Destination::AiEventsOverflow, false)]- fn policy(#[case] force_disable: bool, #[case] dest: Destination, #[case] expected: bool) {- assert_eq!(should_null_partition_key(force_disable, &dest), expected);- }-}-#[cfg(test)]mod attempt_tag_tests {use super::attempt_tag;diff --git a/rust/capture/src/v1/sinks/kafka/sink_tests.rs b/rust/capture/src/v1/sinks/kafka/sink_tests.rsindex 0060f87f83bc..b622b4e09142 100644--- a/rust/capture/src/v1/sinks/kafka/sink_tests.rs+++ b/rust/capture/src/v1/sinks/kafka/sink_tests.rs@@ -8,6 +8,7 @@ use rstest::rstest;use uuid::Uuid;use crate::config::CaptureMode;+use crate::ordering::OrderingGuarantee;use crate::v1::context::RequestContext;use crate::v1::sinks::event::Event;use crate::v1::sinks::sink::Sink;@@ -52,6 +53,7 @@ struct FakeEvent {partition_key: Option<String>,payload: Result<String, String>,event_headers: CapturedEventHeaders,+ ordering: OrderingGuarantee,}impl FakeEvent {@@ -63,9 +65,15 @@ impl FakeEvent {partition_key: Some(format!("phc_test:{uuid}")),payload: Ok(r#"{"event":"test"}"#.to_string()),event_headers: empty_captured_headers(),+ ordering: OrderingGuarantee::PerDistinctId,}}+ fn with_ordering(mut self, o: OrderingGuarantee) -> Self {+ self.ordering = o;+ self+ }+fn with_destination(mut self, d: Destination) -> Self {self.destination = d;self@@ -108,6 +116,10 @@ impl Event for FakeEvent {self.partition_key.clone().unwrap_or_default()}+ fn ordering(&self) -> OrderingGuarantee {+ self.ordering+ }+fn serialize(&self, _ctx: &RequestContext) -> anyhow::Result<bytes::Bytes> {match &self.payload {Ok(p) => Ok(bytes::Bytes::from(p.clone())),@@ -736,30 +748,36 @@ async fn health_refreshed_on_partial_success() {}// ----------------------------------------------------------------------------// Partition key: null-key policy × destination+// Partition key: the ordering guarantee decides it// ---------------------------------------------------------------------------+/// The sink realizes the guarantee and nothing else. Which lanes give up+/// ordering is decided upstream (`WrappedEvent::ordering`), and the+/// person-processing header must not influence the key here: reading it back+/// out of the headers is the bug this indirection removes.#[rstest]-#[case::analytics_main(Destination::AnalyticsMain, true, None)]-#[case::overflow(Destination::Overflow, true, None)]-#[case::dlq(Destination::Dlq, true, Some("phc_test:user-1"))]-#[case::historical(Destination::AnalyticsHistorical, true, Some("phc_test:user-1"))]-#[case::custom(Destination::Custom("my_topic".into()), true, Some("phc_test:user-1"))]-#[case::analytics_main_no_disable(Destination::AnalyticsMain, false, Some("phc_test:user-1"))]+#[case::none_drops_key(OrderingGuarantee::None, true, None)]+#[case::per_distinct_id_keeps_key(OrderingGuarantee::PerDistinctId, false, Some("phc_test:user-1"))]+#[case::per_session_keeps_key(OrderingGuarantee::PerSession, false, Some("phc_test:user-1"))]+#[case::header_alone_does_not_drop_key(+ OrderingGuarantee::PerDistinctId,+ true,+ Some("phc_test:user-1")+)]#[tokio::test]-async fn force_disable_null_key_policy(- #[case] destination: Destination,- #[case] force_disable: bool,+async fn ordering_decides_partition_key(+ #[case] ordering: OrderingGuarantee,+ #[case] force_disable_header: bool,#[case] expected_key: Option<&str>,) {let h = TestHarness::new();let mut headers = empty_captured_headers();- if force_disable {+ if force_disable_header {headers.force_disable_person_processing = Some(true);}let event = FakeEvent::ok("evt-1").with_partition_key(Some("phc_test:user-1"))- .with_destination(destination)+ .with_ordering(ordering).with_headers(headers);let events = prepared(&[&event], &h.ctx);diff --git a/rust/capture/src/v1/sinks/prepare.rs b/rust/capture/src/v1/sinks/prepare.rsindex 6f377e5401bc..a0127a58d99c 100644--- a/rust/capture/src/v1/sinks/prepare.rs+++ b/rust/capture/src/v1/sinks/prepare.rs@@ -63,6 +63,7 @@ fn prepare_one<E: Event>(ev: &E, ctx: &RequestContext) -> anyhow::Result<Option<payload,headers: ev.headers(ctx),partition_key: ev.partition_key(ctx),+ ordering: ev.ordering(),}))}@@ -197,6 +198,7 @@ mod tests {use rstest::rstest;use super::*;+ use crate::ordering::OrderingGuarantee;use crate::v1::sinks::types::{Destination, Outcome};use crate::v1::test_utils::test_context;@@ -276,6 +278,10 @@ mod tests {self.partition_key.clone()}+ fn ordering(&self) -> OrderingGuarantee {+ OrderingGuarantee::PerDistinctId+ }+fn serialize(&self, _ctx: &RequestContext) -> anyhow::Result<bytes::Bytes> {match &self.behavior {Behavior::Ok(bytes) => Ok(bytes::Bytes::from(bytes.clone())),diff --git a/rust/capture/src/v1/sinks/router.rs b/rust/capture/src/v1/sinks/router.rsindex 386d403582ce..d66c9ed4f438 100644--- a/rust/capture/src/v1/sinks/router.rs+++ b/rust/capture/src/v1/sinks/router.rs@@ -117,6 +117,8 @@ mod tests {use common_types::CapturedEventHeaders;use uuid::Uuid;+ use crate::ordering::OrderingGuarantee;+use crate::config::CaptureMode;use crate::v1::context::RequestContext;use crate::v1::sinks::event::Event;@@ -180,6 +182,9 @@ mod tests {fn partition_key(&self, _ctx: &RequestContext) -> String {format!("key:{}", self.uuid())}+ fn ordering(&self) -> OrderingGuarantee {+ OrderingGuarantee::PerDistinctId+ }fn serialize(&self, _ctx: &RequestContext) -> anyhow::Result<bytes::Bytes> {Ok(bytes::Bytes::from(r#"{"event":"test"}"#.to_string()))}diff --git a/rust/capture/src/v1/sinks/types.rs b/rust/capture/src/v1/sinks/types.rsindex 36581674364f..34776a053090 100644--- a/rust/capture/src/v1/sinks/types.rs+++ b/rust/capture/src/v1/sinks/types.rs@@ -6,6 +6,7 @@ use common_types::CapturedEventHeaders;use uuid::Uuid;use crate::event_restrictions::Pipeline;+use crate::ordering::OrderingGuarantee;/// Kafka topic routing for a processed event./// `Drop` means the event should not be produced at all.@@ -57,6 +58,59 @@ impl Destination {}}+ /// Whether this lane exists to absorb hot keys, and so may publish without+ /// a partition key to spread load across partitions.+ ///+ /// Everything else keeps its key even when person processing is off,+ /// because its consumers rely on per-distinct-id ordering: historical+ /// backfills, the dlq, admin custom redirects, and the AI main topic.+ /// Matches the lanes legacy `route()` resolves through `person_ordering`.+ ///+ /// Exhaustive on purpose: a new destination has to state which side it is+ /// on rather than silently inheriting "keeps its key".+ pub fn absorbs_hot_keys(&self) -> bool {+ match self {+ Self::AnalyticsMain | Self::Overflow | Self::AiEventsOverflow => true,+ Self::AnalyticsHistorical+ | Self::Dlq+ | Self::Custom(_)+ | Self::ExceptionErrorTracking+ | Self::HeatmapMain+ | Self::ClientIngestionWarning+ | Self::AiEvents => false,+ // Never published, so it never reaches a partition key.+ Self::Drop => false,+ }+ }++ /// Whether this lane's consumer runs person processing with writes. On+ /// such a lane one distinct id must stay on one partition while person+ /// processing is on — spreading it turns a hot key into contended+ /// person-row updates — so a spread decision only takes effect once the+ /// person-processing flag is set. Read-only consumers (the AI lanes,+ /// error tracking) and lanes with no person processing at all (heatmaps,+ /// client warnings) can take keyless records at any time. The dlq and+ /// custom redirects replay into analytics ingestion, so they count as+ /// person-writing.+ ///+ /// Exhaustive for the same reason as [`Self::absorbs_hot_keys`].+ pub fn writes_persons(&self) -> bool {+ match self {+ Self::AnalyticsMain+ | Self::AnalyticsHistorical+ | Self::Overflow+ | Self::Dlq+ | Self::Custom(_) => true,+ Self::AiEvents+ | Self::AiEventsOverflow+ | Self::ExceptionErrorTracking+ | Self::HeatmapMain+ | Self::ClientIngestionWarning => false,+ // Never published, so it never reaches a consumer.+ Self::Drop => false,+ }+ }+/// Stable, low-cardinality metric tag. `Custom(_)` collapses to "custom"/// so admin-configured topic names never become label values.pub fn as_tag(&self) -> &'static str {@@ -205,8 +259,11 @@ pub struct PreparedEvent {pub destination: Destination,pub payload: bytes::Bytes,pub headers: CapturedEventHeaders,- /// Raw key; the Sink decides whether to use or null it per routing policy.+ /// Raw key; whether the Sink uses it is decided by `ordering`.pub partition_key: String,+ /// The guarantee `partition_key` exists to preserve.+ /// [`OrderingGuarantee::None`] means publish without a key.+ pub ordering: OrderingGuarantee,}// ---------------------------------------------------------------------------diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex 218366c8b538..c6c83feaab3b 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -28,6 +28,7 @@ pub fn prepared<E: SinkEvent + ?Sized>(events: &[&E], ctx: &RequestContext) -> Vpayload: e.serialize(ctx).expect("test payload must serialize"),headers: e.headers(ctx),partition_key: e.partition_key(ctx),+ ordering: e.ordering(),}).collect()}@@ -104,6 +105,7 @@ pub fn wrapped_event(event_name: &str, distinct_id: &str) -> WrappedEvent {details: None,destination: Destination::default(),force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,}}@@ -128,6 +130,7 @@ pub fn wrapped_event_at(timestamp: DateTime<Utc>) -> WrappedEvent {details: None,destination: Destination::default(),force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,}}@@ -152,6 +155,7 @@ pub fn malformed_wrapped_event() -> WrappedEvent {details: Some("missing_event_name"),destination: Destination::default(),force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,}}@@ -226,6 +230,7 @@ pub fn realistic_pageview(distinct_id: &str) -> WrappedEvent {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,}}@@ -264,6 +269,7 @@ pub fn realistic_identify(distinct_id: &str) -> WrappedEvent {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,}}@@ -302,6 +308,7 @@ pub fn realistic_custom(distinct_id: &str, event_name: &str) -> WrappedEvent {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ spread_partitions: false,is_gateway_verified: false,}}@@ -452,6 +459,16 @@ pub fn assert_round_trip(// ---------------------------------------------------------------------------/// Serialize a list of Events into a valid V1 batch JSON payload.+/// A non-historical batch wrapping `events`, the shape `process_batch` takes.+pub fn valid_batch(events: Vec<Event>) -> crate::v1::analytics::types::Batch {+ crate::v1::analytics::types::Batch {+ created_at: "2026-03-19T14:30:00.000Z".to_string(),+ historical_migration: false,+ capture_internal: None,+ batch: events,+ }+}+pub fn batch_payload(events: &[Event]) -> Vec<u8> {let batch_json = serde_json::json!({"created_at": "2026-03-19T14:30:00.000Z",@@ -678,6 +695,8 @@ pub struct TestState {pub struct TestStateBuilder {quota_limited: bool,overflow_limiter: Option<(NonZeroU32, NonZeroU32)>,+ overflow_preserve_locality: bool,+ overflow_forced_key: Option<String>,ai_events_overflow_limiter: Option<(NonZeroU32, NonZeroU32)>,historical_threshold_days: Option<i64>,restriction_service: Option<EventRestrictionService>,@@ -700,6 +719,8 @@ impl TestStateBuilder {Self {quota_limited: false,overflow_limiter: None,+ overflow_preserve_locality: false,+ overflow_forced_key: None,ai_events_overflow_limiter: None,historical_threshold_days: None,restriction_service: None,@@ -739,6 +760,20 @@ impl TestStateBuilder {self}+ /// Keep partition keys when rerouting to overflow, as prod-US does via+ /// `OVERFLOW_PRESERVE_PARTITION_LOCALITY`. Applies to both lanes' limiters+ /// because production derives both from that one setting.+ pub fn with_overflow_preserve_locality(mut self) -> Self {+ self.overflow_preserve_locality = true;+ self+ }++ /// Force-route this key outright, as an ops-configured hot key does.+ pub fn with_overflow_forced_key(mut self, key: impl Into<String>) -> Self {+ self.overflow_forced_key = Some(key.into());+ self+ }+/// Arm the AI overflow valve: a dedicated AI-lane limiter with the given/// rate and burst. Also sets `ai_events_overflow_enabled`, mirroring/// production where both derive from the same overflow-topic config.@@ -836,13 +871,23 @@ impl TestStateBuilder {None => HistoricalConfig::new(false, 1),};- let overflow_limiter = self- .overflow_limiter- .map(|(per_sec, burst)| Arc::new(OverflowLimiter::new(per_sec, burst, None, false)));-- let ai_events_overflow_limiter = self- .ai_events_overflow_limiter- .map(|(per_sec, burst)| Arc::new(OverflowLimiter::new(per_sec, burst, None, false)));+ let overflow_limiter = self.overflow_limiter.map(|(per_sec, burst)| {+ Arc::new(OverflowLimiter::new(+ per_sec,+ burst,+ self.overflow_forced_key.clone(),+ self.overflow_preserve_locality,+ ))+ });++ let ai_events_overflow_limiter = self.ai_events_overflow_limiter.map(|(per_sec, burst)| {+ Arc::new(OverflowLimiter::new(+ per_sec,+ burst,+ self.overflow_forced_key.clone(),+ self.overflow_preserve_locality,+ ))+ });let ai_events_overflow_enabled = ai_events_overflow_limiter.is_some();// Build the v1 sink router with a MockProducer-backed KafkaSinkdiff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 0e1000be618d..2a7cfcaea8c0 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -87,6 +87,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {kafka_heatmaps_topic: "events_plugin_ingestion".to_string(),kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),+ outputs_completeness_check_enabled: true,capture_analytics_ai_events_topic: None,capture_analytics_ai_events_overflow_topic: None,kafka_traces_topic: "ingestion_traces".to_string(),diff --git a/rust/capture/tests/events.rs b/rust/capture/tests/events.rsindex b23990c217ec..66132e19f68e 100644--- a/rust/capture/tests/events.rs+++ b/rust/capture/tests/events.rs@@ -901,14 +901,13 @@ async fn it_overflows_events_on_burst() -> Result<()> {topic.assert_empty();- // Third event should be in overflow topic, but has no- // message key as overflow locality is off for this test- assert_json_include!(- actual: overflow_topic.next_event()?,- expected: json!({- "token": token,- "distinct_id": distinct_id,- })+ // Third event should be in overflow topic. Locality is off for this+ // test, but a person-on burst keeps its key anyway: the overflow+ // consumer updates persons keyed on distinct id, so the key only drops+ // once person processing is off.+ assert_eq!(+ overflow_topic.next_message_key()?.unwrap(),+ format!("{token}:{distinct_id}"));overflow_topic.assert_empty();