: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
docs(capture): replan capture outputs around a kafka fallback for v0 and v1 (#91761)
Paweł Ledwońd7a7b52cecdc
diff --git a/rust/capture/OUTPUTS_REFACTOR_PLAN.md b/rust/capture/OUTPUTS_REFACTOR_PLAN.mdindex b67aef5a64f1..92972ba0e082 100644--- a/rust/capture/OUTPUTS_REFACTOR_PLAN.md+++ b/rust/capture/OUTPUTS_REFACTOR_PLAN.md@@ -1,264 +1,283 @@# 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.+Working contract for implementation agents. Steps 1–8 have shipped. Each remaining step is one commit in its own PR.-## Motivation+This doc is deleted when it schedules nothing. Step 18 closes objective 1; objectives 2 and 3 are then scheduled in order. Before deletion, the parts still needed — the vocabulary rules, the ordering-vs-person-processing contract, the repartitioning note — move into module docs or `v1/sinks/DESIGN.md`, and unscheduled work becomes issues.-Three drivers, in order:+## Objectives-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.+Capture has two produce stacks. The v0 endpoints (`/e`, `/batch`, `/i/v0/*`, replay, OTEL) stay forever. The v1 stack is live beside them: capture-analytics and capture-import serve `/i/v1/analytics/events` through it, and capture-ai serves `/i/v1/ai/events`. Both stacks produce through the outputs layer, and v0's internals move toward v1's shape.-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.+1. **Manual fallback for all capture traffic.** If MSK degrades, capture-analytics can produce to another cluster, with its own brokers, TLS, and topic names. One environment variable and a pod roll arm it, for v0 and v1 traffic alike. Boot-time checks prove the configuration is sound before any traffic moves. Steps 9–18.+2. **One set of internals for v0 and v1.** The two stacks share producers and producer tuning, v0 builds prepared events before the outputs layer like v1, and both use one prepared-event builder and one lane-decision model. The v0 endpoints do not change. Steps 19–22.+3. **Automated fallback, capture side.** A separate circuit-breaker service decides when to switch. Capture sends producer health, receives switch signals, and applies them at runtime without a redeploy. Consumers are out of scope. Steps 23–25.-## Target architecture+Objective 2 goes before 3 because it deletes v0's event-level route into the outputs layer; the runtime switch is then built once, on the one remaining route. Neither depends on the other otherwise, and objective 3 also waits on the breaker service existing.++All three use one mechanism:++- A **producer** is named, holds only connection config, and is instantiated once.+- An **output** holds its own topic names and the name of the producer it publishes through.+- Outputs take **prepared events**; each sink does its transport's encoding.+- Every output a deployment can reach must be fully configured.+- Each output's topics are checked against its producer's broker at boot.++A fallback is then a configuration of an output's targets, not a new code path. The policy tree already composes two outputs (Step 7). It needs targets that can be configured independently, a policy that picks the live target at boot (Step 17), and for objective 3, a way to change that pick at runtime.-Layer `rust/capture`'s produce path into five strata with one-way dependencies:+Today this is not possible. One deployment-wide `KafkaConfig` holds ten topic names, each with a compiled-in default, so a boot check cannot tell a configured topic from a missing one. The existing completeness flag demands all ten on every pod. It fails any deployment that deliberately blanks a topic it never produces to, and where it can be enabled it still misses a missing variable, because the default fills it in. v1 publishes through its own sinks, so nothing in the outputs layer moves its traffic.++Every step is a small commit, proven by the Step-1 goldens, and reverted by plain revert. Cluster migration by split or dual-write stays under **Deferred work**.++## Target architecture```text-edge → Pipeline {Analytics, Heatmaps, Warnings, ErrorTracking, Replay}+request handler → Pipeline {Analytics, Ai, 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.+lane decision → Address {(Pipeline, Lane {Main, Overflow, Historical}) | Dlq | Custom(topic)}+ + ordering guarantee+prepared event → address, ordering + key, header values, JSON body; built once per event+outputs → Address → output = 1..n targets + selection policy+ (single | select | split | dual-write);+ target = own topics + a named producer+sinks → transport encoding (Kafka: topic, key, headers, optional lz4 envelope;+ S3 until Step 18: JSON lines), enqueue, ack+producers → named connections (brokers, TLS, tuning), instantiated once,+ shared by every output that names them```-- **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 `TopicTable` 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.+- **Pipeline** is decided by the HTTP handler that receives the request, from the endpoint and the event name, and stamped on the event as its `DataType`.+- **Lane** is decided once per event, by `pipeline::resolve` in v0 and by assign-then-reroute in v1. Precedence: dlq > custom > historical > overflow > main.+- **Prepared event** is everything a destination's consumers see, independent of transport: the address, the ordering guarantee and its key, the header values, and the event body as JSON. It is built once, and every target of an output receives the same bytes.+- **Output** is the destination for an address. It owns 1..n targets and the policy that picks between them per batch. A target maps the address to its own topic and publishes through its named producer. All multi-target behavior lives here.+- **Sink** is one transport. It turns a prepared event into its wire record and acks it. The lz4 envelope and its `content-encoding` header are Kafka encoding, set per target. The sink makes no routing decision.+- **Producer** is a named connection, configured under its own namespace, like Node.js ingestion's `KafkaProducerRegistry`. Outputs share producers by name and never open their own connection. The ingestion-warnings producer (fire-and-forget, its own hosts) stays outside this model.### 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. **OutputRegistry** = the `(Pipeline, Lane)` → output mapping with the per-mode completeness check. The Step-3 **TopicTable** (destination → topic) is absorbed into the registry's targets.-- **Destination** = a routed topic slot (`AnalyticsMain`, `Dlq`, `AiEvents`, `Custom`). One word across both stacks: v0's `sinks::registry::Destination` and v1's `v1::sinks::types::Destination` are the same concept and converge at Step 20. Never name a backend policy tree an `Output` *and* a routed topic an `Output`.-- **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.+- **Address** = a lane of a pipeline, or an admin redirect (`Dlq`, `Custom(topic)`) outside the lane model. v0 builds it through `resolve`, v1 by mapping its `Destination`. Never reintroduce a flat enum that mixes pipeline and lane.+- **Prepared event** = the transport-independent result of processing one event. v1's `PreparedEvent` is the shape; v0's `PreparedPayload` differs only in carrying a topic instead of an address.+- **Output** = targets + selection policy. **OutputRegistry** = the address → output map. The Step-3 **TopicTable** is absorbed into the targets.+- **Destination** = v0's `sinks::registry::Destination` and v1's `v1::sinks::types::Destination` name the same routed slots. Both map onto `Address`. Never call both a policy tree and a routed topic an `Output`.+- **Sink** = one transport. Anything that picks between sinks is an output policy.+- **Producer** config never carries topic names, and output config never carries connection config. An output moves clusters by naming a different producer.### Invariants-- Metric names and labels stay stable: `capture_events_rerouted_*`, `capture_primary_sink_health`, `capture_fallback_sink_failovers_total`, `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.+- Metric names and labels stay stable: `capture_events_rerouted_*`, `capture_event_batch_size`, and until Step 18, `capture_primary_sink_health` and `capture_fallback_sink_failovers_total`. Steps that retire a metric list it as an accepted difference.+- Wire parity: the Step-1 goldens and existing endpoint and integration tests pass **unmodified**, unless a step 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.+- Every step ships green (`cargo test -p capture`, clippy `-D warnings`, fmt).+- v0 call sites keep the whole-request `CaptureError`. v1 keeps its per-event response.+- No new sink code reads `ProcessedEventMetadata`. The Kafka sink's v0 prep path is the one remaining reader; Step 20 removes it.-## The stages and steps+## Starting point++Steps 1–8 shipped the structure:-### Stage A — oracle and groundwork+- **1** — `assert_routing` goldens pin topic, partition key, headers, and reroute counters for every pipeline and lane.+- **2, 5** — routing is the pure `pipeline::resolve(&metadata, ai_events_overflow_armed) -> AddressDecision { address, ordering }`. The Kafka sink still calls it during prep.+- **3** — `TopicTable` maps each `Destination` to a topic. `check_complete` refuses to boot on an empty topic, behind `CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED` (default off).+- **4** — `serialization`: `Format` (JSON only) × `Envelope` (none or lz4) → `Serializer`, used in Kafka prep.+- **6** — the `Sink` trait takes `PreparedPayload`s and returns per-event `SinkResult`s. Kafka's `prepare_batch` is an inherent method.+- **7** — `outputs.rs`: `Output` is a leaf or a `failover` over two outputs. `FallbackSink` is deleted. Accepted metric change: `capture_event_batch_size` now records on the S3 fallback path and on print/noop single sends.+- **8** — every v0 call site publishes through `OutputRegistry::publish`. `State.outputs` is a concrete `Arc<OutputRegistry>`. The v0 `Event` trait is deleted. `kafka_send` stays on the one-event path: removing it adds a task spawn per event and drops the `ack_wait_one` span, so Step 20 takes it.-#### Step 1 · Consolidate the routing golden oracle+Today the registry holds one deployment-wide `Output`: a Kafka leaf, or Kafka→S3 failover. v1 (`CAPTURE_V1_SINKS`) serializes its own `PreparedEvent`s and publishes them through its own `Router` to one default sink, the first name in `CAPTURE_V1_SINKS`.-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.+## Objective 1 — manual fallback for all capture traffic-#### Step 2 · Extract routing into a pure `route()`+Steps 9–10 move configuration onto named producers and outputs. Steps 11–12 bring v1 onto the outputs layer. Steps 13–14 make the set of reachable outputs a type. Steps 15–16 are the checks that type allows. Step 17 is the fallback. Step 18 deletes the S3 fallback it replaces.-`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 9 · Named producers, instantiated once-#### Step 3 · `TopicTable` + startup completeness check+- **Goal.** Producer slots are declared in code, and each holds only connection config (brokers, TLS, client tuning) and is instantiated once at startup. The v0 Kafka output publishes through the `INGESTION` slot, which replaces the connection half of `KafkaConfig`. Behavior is byte-identical.+- **Why.** Two outputs on one cluster must share one connection, and moving one output to another cluster must not move the others. Sharing by name makes both structural.+- **Same model as Node.js ingestion.** A slot is a role, not a cluster; charts wire it to a cluster per deployment. Its settings are `KAFKA_<SLOT>_PRODUCER_<RDKAFKA_KEY>`, for example `KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST`. Slot names are single words, so no slot's prefix is a prefix of another's.+- **Migration.** Explicit: capture stops reading `KAFKA_HOSTS`, `KAFKA_TLS`, and the `KAFKA_PRODUCER_*` tuning; charts set the new variables first. The broker list defaults to `kafka:9092`, the local dev and hobby broker, so those setups need no change. capture-logs keeps its own `KafkaConfig`.+- **Parity proof.** Goldens and integration suites unmodified. A test pins the rdkafka settings of the default slot config to capture's current ones.+- **Size.** M.-One destination→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 `OutputRegistry`; the mode-scoped demand is folded in at Step 9, where `(Pipeline, Lane)` makes the per-mode reachable set explicit.+### Step 10 · An output owns its topics and names its producer-### Stage B — the two new seams (no caller-visible change)+- **Goal.** Each leaf output is built from its own config block: its topic names and a producer name. It no longer reads `KafkaConfig`. Two outputs can name different producers (different clusters) or the same one (one connection).+- **Why.** The policy tree composes any two outputs; the only pair today is Kafka→S3 because `setup` builds it that way. After this step, a second cluster is one more producer and one more output block: a `setup` change and a values file.+- **Topic defaults stay** until Step 15.+- **Size.** M.-#### Step 4 · Serialization layer: format × envelope+### Step 11 · Outputs accept prepared events-- **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.+- **Goal.** A second route into the outputs layer: `publish_prepared(Vec<PreparedEvent>) -> Vec<SinkResult>`, one result per event. Each target maps the event's address to its own topic, and its sink does the transport encoding: the Kafka sink builds the record, and the S3 sink writes the JSON body as a line. Every policy works on this route. v0's event route is unchanged.+- **Why.** v1 already produces prepared events with per-event results. Joining at this level leaves v1's lane decision, JSON body, and response model untouched, so there is no second pass through `resolve` and no parity mapping of v1 decisions onto v0 metadata.+- **Parity proof.** New tests drive prepared events through each leaf and each policy. Goldens unmodified.- **Size.** M.-#### Step 5 · `Pipeline` + `Lane`; the lane decision becomes pipeline-layer code+### Step 12 · v1 publishes through the outputs layer-- **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.+- **Goal.** v1 maps its `Destination` to `Address` and calls `publish_prepared`. v1's `Router`, `Sink`, `KafkaSink`, and per-sink Kafka config are deleted. Each `CAPTURE_V1_SINK_*` cluster becomes a named producer, and its topics become output rows. The `topic_ai` override in `setup::create_v1_sink_router` goes with it.+- **Produce timeout moves to the shared Kafka sink.** v1 bounds each batch's acks by a produce timeout; acks that miss it return `Outcome::Timeout`, and the events are retried. The shared Kafka sink gains this, configured per target.+- **Kept separate until Step 19.** v1's producer tuning differs from v0's (for example lz4 vs no compression, 4 vs 2 retries, 30 s vs 20 s message timeout), so each stack keeps its own named producer and tuning. capture-analytics keeps its two MSK connections, one per stack.+- **Accepted differences.** The `capture_v1_kafka_*` metrics are replaced by the shared Kafka sink's metrics.+- **Parity proof.** `v1_pipeline`, `v1_sink_integration`, and `overflow_parity.rs` unmodified.+- **Size.** L.-### Stage C — sinks become mechanism, outputs become the API+### Step 13 · Typed per-pipeline lanes-#### Step 6 · Narrow the Kafka sink to backend mechanism+- **Goal.** Replace the flat `Lane` with `AnalyticsLane`, `AiLane`, `SessionReplayLane`, `BasicLane`, so invalid `(pipeline, lane)` pairs cannot be built. There is no `AiLane::Historical`: the AI divert wins over historical, as in v1. Both stacks hand this address type to the outputs layer.+- **Why.** Step 14's registry rows need one field per lane that exists. With a flat `Lane`, the registry needs a runtime error for pairs routing never produces.+- **Parity proof.** Goldens unmodified; `resolve` precedence tests retyped with the same assertions.+- **Size.** M/L.-- **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` is never ported onto the mechanism trait: the outputs layer owns multi-target policies (single | failover) from its first commit, built from the same config, and the Event-era composite is deleted when its last caller migrates. `SplitKafkaSink` is already gone — deleted with the retired AI secondary-cluster routing — so split survives only as a policy shape the outputs layer grows back when a cluster migration needs it.-- **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 14 · Per-mode output registries-#### 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* — today `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). Targets are outputs themselves, so a future policy (a split for the next cluster migration) composes over pairs the way the old composites did. 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)` `PublishEvents` trait (prep → publish → fold); no caller ever sees a two-phase protocol.- - `OutputRegistry`: the `(pipeline, lane)` → output handle the state holds; degenerate today (one deployment-wide output; per-lane topics resolve in prep via the `TopicTable`).- - `setup::create_output` builds the policy tree from the same config; **`FallbackSink` is deleted**, its 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.- - The facade is the only `dyn Event` the production call sites see, so the per-sink `Event` impls on s3, print, and noop are deleted here rather than rewired onto `PublishEvents`. `Event` survives only where callers still need it: the Kafka bridge and `MockSink`, both consumed by tests that Step 8 retypes.-- **Files.** `rust/capture/src/outputs.rs` (new); `rust/capture/src/setup.rs`; `rust/capture/src/sinks/{mod,s3,print,noop,test_sink}.rs` (mechanism + `PublishEvents` impls); `fallback.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.+- **Goal.** One registry type per capture mode, with required fields: `AnalyticsFamilyOutputs` (analytics, ai, heatmaps, warnings, error tracking) for Events and Import pods, `AiOutputs` for Ai pods, and `SessionReplayOutputs` for Recordings pods. Rows naming the same producer share its one instance.+- **Each type holds exactly what its mode can reach.** The set comes from the routes the mode mounts: Ai pods serve only the AI batch, AI, OTEL, and v1 AI routes (`router.rs`), so `AiOutputs` does not demand heatmaps, warnings, or error-tracking topics. The exact rows for each mode, Import included, are derived from its routes when this step is scheduled.+- **Why.** Step 15 demands configuration per mode. Without these types, that demand is a hand-written mode → outputs map. With them, the type is the list.+- **Out of scope.** Binding handlers to capability traits over a generic `State<T>` (Step 29).+- **Parity proof.** Goldens and integration suites unmodified; per-mode construction tests.- **Size.** L.-#### Step 8 · Call sites migrate to the table; `Event` retired+### Step 15 · A reachable output must be configured-- **Goal.** All four call sites (`events/analytics.rs`, `ai_endpoint.rs`, `otel/mod.rs`, `events/recordings.rs`) publish via `OutputRegistry::publish`, recording `capture_event_batch_size` at the call site; `State` and test mocks retype; then delete the v0 `Event` trait, its `Box<T>` blanket, the outputs facade, and the `Event` impls on Kafka, S3, print, noop, and the test mock.-- **`State` drops its trait object.** `State.sink: Arc<dyn Event>` becomes `State.outputs: Arc<OutputRegistry>` — a concrete type, since `Output::single` already accepts any leaf. The substitution seam moves down to the leaf: `PublishEvents` and `Output::single` become `pub` so the `tests/` suites can stand their own capturing sinks in (`test_sink` is `cfg(test)`-gated and unreachable from there), and pipeline tests drive the real table and policy path instead of bypassing the outputs layer.-- **`kafka_send` survives this step.** It is not reachable only from `Event::send`: `PublishEvents::publish_events` calls it on its one-event branch, and that is the production single-event path (recordings publishes one event per call). Deleting it means re-expressing that branch over `prepare_batch` + `Sink::publish` + `fold_results`, which adds a task spawn per single event and drops the `ack_wait_one` span — a behavior change, and this step is a mechanical move. Step 12 retires it with the prep hoist.-- **Parity proof.** All endpoint/integration suites green; grep proves `Event` call-site-free before the deletion half.-- **Size.** M/L. May split into per-call-site commits if the diff grows.+- **Goal.** An output the deployment's mode can reach must have its topics and a defined producer name, or capture refuses to boot. An unreachable output is never asked for: a Recordings pod has no error-tracking row.+- **Defaults go.** Delete `#[envconfig(default = ...)]` from reachable outputs' topic fields. Today a missing or misspelled variable silently resolves to a compiled-in name.+- **Replaces** `CAPTURE_OUTPUTS_COMPLETENESS_CHECK_ENABLED`.+- **Parity proof.** Per-mode refusal tests, and tests proving no mode is asked for an output it cannot reach.+- **Size.** M.-### Stage D — completeness, dark failover, convergence+Example of what this catches: until [charts#14941](https://github.com/PostHog/charts/pull/14941) (2026-09-01), capture-replay set its overflow topic under `KAFKA_OVERFLOW_TOPIC`, which replay does not read. Replay overflow went to the default `session_recording_snapshot_item_overflow`, and nothing failed. Step 15 refuses that at boot.-#### Step 9 · Mode-scoped registry completeness+### Step 16 · Check each output's topics against its producer's broker-- **Goal.** `TopicTable::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.+- **Goal.** At boot, read cluster metadata for every topic each reachable output can produce to, once per distinct producer, and refuse to start on a missing topic.+- **Why separate from Step 15.** Step 15 checks config and never connects. Step 16 checks that the topics exist on the cluster, which matters most for a cluster this deployment has never written to.+- **The check never creates a topic.** A producer's metadata request can make a broker with topic auto-creation create the topic, with broker defaults, and then the check passes. The check uses an admin metadata request with auto-creation disabled, so a missing topic stays missing until someone provisions it.+- **Enabled per deployment.**- **Size.** M.-#### Step 10 · Breaker failover mode (dark)+### Step 17 · capture-analytics emergency fallback++- **Shape.** The capture-analytics output tree holds two Kafka outputs, primary and fallback. Each names its own producer (own brokers, own TLS) and its own topic names. The fallback cluster does not have to copy the primary's topic names. v0 and v1 traffic both publish through this tree.+- **Arming.** One environment variable, matched exactly against a sentinel value. `"1"`, `"true"`, or `"yes"` does not arm it; any value other than the sentinel refuses to boot. Unset is normal operation.+- **Static at boot.** A new `select` policy holds both targets and publishes to one, picked by the arming variable. It does not react to health: switching means setting the variable and rolling the pods, because a person decides to move off a degraded MSK. Automatic switching is objective 3. The health-gated `failover` policy is not used here; it serves only S3.+- **A retryable error stays on the live target.** It returns to the caller like any other publish error and never sends the batch to the other target.+- **The idle fallback is checked on every boot.** capture-analytics enables Step 16, and the tree always holds the fallback, so a broken fallback config shows up on an ordinary deploy, not in the emergency.+- **What an idle-fallback failure does is configuration.** It covers a failed Step-16 check on the fallback cluster and a fallback producer that cannot connect. Producer creation returns the result of its broker probe instead of only logging it, so the configured mode can act on it:+ - `warn` (default): capture keeps serving on the primary. The fallback producer is advisory, a per-producer health gauge reports it as down, and capture logs an error. The gauge needs an alert, since nothing else fails.+ - `strict`: capture refuses to boot, and a dead fallback producer fails pod liveness.+- **Armed, the checks follow the live target.** The fallback is live, so a failed Step-16 check or a fallback producer that cannot connect refuses boot, whatever the mode. In a rolling update the new pods fail and the old pods keep serving on the primary, so traffic never moves to a dead cluster. The primary is idle and always gets `warn` handling: arming means MSK is degraded, so its checks are expected to fail, and they must not block the switch.+- **Gauge** for the live target, emitted in both states, so a dashboard can tell "on primary" from "not reporting".+- **Scope.** capture-analytics only. Other modes have no fallback output and are not asked to configure one.+- **Not in this plan: the consumer switch.** Arming moves where capture writes. It does not move the consumers, which keep reading the primary cluster until they are repointed. This plan does not implement that switch; the runbook repoints consumers in the same operation. Until then, events wait in the fallback topics.+- **Known gaps, for the runbook.** capture-import writes the same topics and must be stopped before any drain-to-zero check. The AI lane's bridges read MSK topic names.+- **Size.** M/L.-- **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.+### Step 18 · Delete the S3 fallback++- **Goal.** Delete `S3Sink`, the `s3_fallback_*` config, the Kafka→S3 wiring in `setup`, and the health-gated `failover` policy, which serves only S3.+- **Why it is safe.** No production deployment enables it. The charts set `S3_FALLBACK_ENABLED: "false"` in six values files and `"true"` only in `apps/capture-analytics/values.dev.yaml`.+- **Why Step 17 replaces it.** A second Kafka cluster keeps events flowing to consumers. S3 needs a replay path that has never run in production.+- **Accepted differences.** `capture_primary_sink_health` and `capture_fallback_sink_failovers_total` go with the policy that emits them.+- **What is lost.** S3 failover is automatic; Step 17 is manual. No deployment uses the automatic path today, but the capability goes. Objective 3 brings it back through Step 23.+- **Cross-repo.** The seven charts values entries, the `CaptureAnalyticsV0S3FallbackActive` alert spec and runbook, and the IAM role in cloud-infra.- **Size.** M.-#### Step 11 · v1 converges on the shared strata+## Objective 2 — one set of internals for v0 and v1 (unscheduled)-- **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.+Scheduled when objective 1 closes. The v0 endpoints and their responses do not change.-### Stage E — prep hoists up; sinks become pure transport+### Step 19 · One producer per cluster-#### Step 12 · Prep hoists into the outputs layer; `PublishEvents` retired+v0 and v1 producer tuning is reconciled into one set per cluster, and capture-analytics opens one MSK connection instead of two. Each difference (compression, retries, message timeout, metadata refresh, and the rest) is either adopted by both stacks or recorded as a per-producer setting with a reason.-- **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 `TopicTable` move with it (`outputs::topics`). The `PublishEvents` 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.+### Step 20 · v0 builds prepared events-### Per-mode output registries (Step 15)+v0 resolves the lane, builds the JSON body and header values, and hands prepared events to `publish_prepared`, as v1 does. The lz4 envelope moves into the Kafka sink as target config. `PublishEvents`, `kafka_send`, and v0's event route into the outputs layer are deleted. v0 call sites fold per-event results into the whole-request `CaptureError`.-The deployment's output registry is a concrete type — `AnalyticsFamilyOutputs` (analytics, ai, heatmaps, warnings, error tracking rows) for Events/Ai pods, `SessionReplayOutputs` for Recordings pods — with required fields, so the narrow list of what a deployment must wire is the type itself. Handlers bound on sealed capability traits (`PublishesAnalyticsFamily`, `PublishesSessionReplay`); `State<T>` is generic over the registry and `setup` instantiates the monomorphized router per `CaptureMode` (`router` for the analytics family, `session_replay_router` for recordings) — mounting an ingress on a table that cannot publish its family is a compile error. Rows share backends (one Kafka connection, one S3 client, one breaker controller), so per-row policy trees behave as the single pre-table output did. The runtime backstop for a pipeline without a row is an explicit fatal error, structurally dead while ingress mounting and registry type derive from the same mode.+- **Tests.** Capturing mocks see prepared events, not `ProcessedEvent`s, so about 60 metadata assertions become wire-level (topic, key, headers, payload). The `ExpectedEvent` checkers rebuild the expected record, so test bodies stay the same. This also pins that replay events redirected to dlq/custom partition on the event key, not the session id.+- **Accepted differences.** print/noop run the real prep path, so they can now fail prep (e.g. `MissingSessionId`). Prep histograms keep their `capture_kafka_*` names.-### Per-pipeline output overrides and boot verification (Step 18)+### Step 21 · One prepared-event builder-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.+v0 and v1 build the JSON body and header values with the same code. Known differences are settled here: `sent_at` fractional-second formatting (parses equal; v1 adopts v0's), and the header differences pinned by `overflow_parity.rs`.-`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).+### Step 22 · One lane-decision model-### Outputs as an open trait (Step 19)+v0's lane decision moves to v1's model.-`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.+**Hazard: overflow carries two separate decisions.** Whether person processing is disabled (the `force_disable_person_processing` header, which customers see) and whether the partition key is dropped (`OrderingGuarantee`, a load decision). Both stacks follow one rule today, and the merged model must keep it:-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.+- The header follows the person-processing flag. A `ForceLimited` reason implies the flag (`person_processing_disabled`). v1 has no reason on the event; its one stamping site sets the flag.+- The key is dropped on the analytics main and overflow lanes when the flag is set, and on the AI overflow lane when the flag or a spread decision is set. Nowhere else. Analytics consumers update persons by distinct id, so a person-on burst keeps its key; the AI overflow consumer only reads persons. Historical, dlq, custom, and AI main always keep the key.-### v1 convergence on the outputs machinery (Step 20)+`overflow_parity.rs` pins lane, key presence, and header for both stacks over the overflow and rate-limit matrix. It stays green through the merge.-Goal: v1 endpoints publish through `dyn Outputs` like every other ingress, so fallback/split/dynamic policies apply uniformly. Plan:+## Objective 3 — automated fallback (unscheduled)-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.+A separate circuit-breaker service decides; how it decides is out of scope. Capture sends producer health and receives switch signals. These steps are scheduled with parity proofs once objectives 1 and 2 close.-**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:+### Step 23 · Target selection at runtime-- 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.+The `select` policy's live target becomes swappable state with no lock on the request path. Each batch reads the live target once, and its acks and retries stay on that target, so a switch never splits a batch or sends it twice. Step 17's arming sets its boot value. A signal switches the target. No signal, or an unreachable control plane, keeps the current target: missing information must never move traffic. The Step-17 gauge reports the live target. With no service configured, behavior matches Step 17 exactly. As in Step 17, a switch moves only where capture writes. Repointing consumers happens outside capture and outside this plan, and must be coordinated with the switch before it is automated.-`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.+### Step 24 · Producer health out-**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.+Each named producer reports delivery latency, error rate, and queue depth under its name, including the idle fallback producer. Transport and cadence are decided when scheduled. Reporting must never slow the produce path.-### AI pipeline and Import mode+### Step 25 · Switch signals in-- **AI pipeline membership is one predicate, resolved once into a stamp.** `AiLanePredicate` (`CAPTURE_AI_LANE_PREDICATE`: `allowlist` = exact membership in `AI_EVENT_NAMES`, `prefix` = any `$ai_*` name) decides which names are on the lane; `DataType::from_event_name` resolves a name against it and stamps `DataType::AiEvents`, on every capture mode, mirroring v1's `Destination::AiEvents`. Everything downstream reads the stamp — `Pipeline::from_metadata` maps it, and the multipart and OTEL AI ingress stamp the same lane at the handler. A deployment may only run `prefix` once its AI ingestion pipeline admits by prefix too, otherwise a prefixed-but-unlisted name like `$ai_call` is diverted and then DLQed. (The quota predicate `is_llm_event` is separate and always prefix-based.) There is no per-batch routing config and no per-deployment divert switch — the rollout-era `AiRouting` mode/allowlist/percentage machinery is retired, and so is the capture-mode predicate that replaced it. A deployment that wants AI traffic on a given topic points `CAPTURE_ANALYTICS_AI_EVENTS_TOPIC` at it.-- **The AI lanes own dedicated topics.** `TopicTable` grows an `ai_events` row (`CAPTURE_ANALYTICS_AI_EVENTS_TOPIC`, required with default `events_plugin_ingestion_ai`) and an optional `ai_events_overflow` row (`..._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.+Capture applies the service's switch signals through Step 23 and acknowledges them. The Step-17 variable stays the manual override and outranks the service; exact precedence is decided when scheduled. The breaker logic that an earlier plan put inside capture (`FailoverMode::Breaker`) belongs to the service.-## Repartitioning coordinator (design note)+## Deferred work-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.+Unscheduled. To revive a step, move it under an objective with its parity proof.-**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.+### Step 29 · Handlers bound by publish capabilities-**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 the old `Split` composite, no serialization changes (both clusters share the prep/serialization contract, as the retired AI-secondary split proved).+Handlers bind on sealed traits (`PublishesAnalyticsFamily`, `PublishesSessionReplay`). `State<T>` is generic over the Step-14 registry, and `setup` builds the router per mode. Mounting an ingress on a registry that cannot publish its pipeline becomes a compile error.-**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.+### Steps 34–35 · Outputs as an open trait-**Per-partition fence (drain-and-switch).** Moving shard `s` from Old to New, without reordering a key's events across clusters:+`Outputs` becomes an open trait replacing the closed policy enum: `KafkaOutputs`, `PrintOutputs`/`NoopOutputs`, and `SelectOutputs`/`SplitOutputs` over `Arc<dyn Outputs>`. A test-only prototype (`outputs::dynamic`, Step 35) has `DynamicKafkaOutputs` take config pushes from an in-process `KafkaManagerService` and switch topics and brokers partition by partition.-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).+Split and dual-write policies are also unscheduled. Before either is scheduled, it must define how per-target results become one result per event, which failures it retries, and how it handles an event delivered to both targets.-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.+Steps 30 and 33 are listed in the tracker only. Steps 26, 28, 31, and 32 are superseded; the tracker says by what.-**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.+## Repartitioning coordinator (design note)-**Seam inventory:**+Unscheduled. This records where a coordinator plugs in, so nothing already landed has to move. The goal: move a deployment between clusters one partition at a time, with a short hold per partition.-- `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.+- **Shards decided above the sinks.** The coordinator owns `shard = hash(key) % N`, over the same key the sink hashes, with its own `N`. The prepared event gets `shard: Option<u32>`, so both targets of a pair see the same shard.+- **A `ShardRouted` output policy** holds two child outputs (old, new) and a swappable `shard → Old | New` table (`ArcSwap`, updated like Step 23). A batch splits by assignment.+- **Partition pass-through.** `ProduceRecord` gets `partition: Option<i32>`; the Kafka sink maps shard to a partition of its topic. `None` keeps key hashing.+- **Fence per shard `s`, Old → New:**+ 1. Swap the entry for `s`; new `s` events are held.+ 2. Wait for in-flight `s` publishes to Old to resolve (a count of `SinkResult`s).+ 3. Flush Old's producer.+ 4. Record Old's end offset as the consumer-side watermark: consumers read Old to it, then start on New. Release the held events to New.+ 5. Rollback runs the same steps in reverse. A failure before step 4 releases to the still-assigned side.+- The hold lasts at most one producer flush per shard.+- **Keyless events** (`OrderingGuarantee::None`) switch with a bare swap. Replay follows the fence (keyed by session). dlq/custom follow it too (keyed by `token:distinct_id`).## End state-When all steps land, the five strata hold:+When the three objectives close:-- **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 `OutputRegistry`; the `Output` policy tree (single | failover) owns all multi-target behavior, composing the way the old sink composites did. The v0 `Event` trait and `FallbackSink` are gone; `SplitKafkaSink` already is, deleted with the retired AI secondary-cluster routing.-- **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 `TopicTable`** via `Destination::as_output`. The v1 `Sink`/`Router` trait convergence stays gated on the per-event response model.+- v0 and v1 share producers, one prepared-event builder, and one lane-decision model; the v0 endpoints are unchanged.+- Every prepared event publishes through the `OutputRegistry`. The `Output` policy tree owns all multi-target behavior. The v1 sink stack is gone.+- Connection config lives with named producers, one per cluster. Pointing an output at another cluster means naming another producer.+- Sinks do transport encoding only and make no routing decisions.+- The `select` policy's live target can be switched at runtime by the breaker service, and a silent control plane keeps the current target.## Agent conventions-**Build / test.** All cargo commands run via `flox activate -- cargo <cmd>` from `rust/`.--**Acceptance per step:**+Run cargo as `flox activate -d <worktree root> -- cargo <cmd>` from `rust/`. Each step must pass:-- `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`+- `cargo test -p capture`. Scope to the named suites if the full run is slow; the Step-1 goldens always run.+- `cargo clippy -p capture --all-targets -- -D warnings`+- `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.+One step = one commit, subject from the tracker. No `--no-verify`.## Progress tracker@@ -274,20 +293,30 @@ When all steps land, the five strata hold:| 7 · Outputs layer with policies; composites retired | done | `feat(capture): outputs layer owns the failover policy` || 8a · Call sites on the table | done | `refactor(capture): call sites publish through outputs` || 8b · `Event` retired | done | `refactor(capture): retire v0 Event trait` |-| 9 · Mode-scoped completeness | pending | `refactor(capture): mode-scoped output registry completeness` |-| 10 · Breaker mode (dark) | pending | `feat(capture): breaker-driven failover mode (dark)` |-| 11 · v1 convergence | pending | `refactor(capture): v1 resolves through shared pipeline/lane strata` |-| 12 · Prep hoist; `PublishEvents` retired | pending | `refactor(capture): hoist prep into outputs; sinks take prepared payloads only` |-| 13 · Typed addresses; AI pipeline | pending | `refactor(capture): typed per-pipeline lanes; custom redirects and the ai stream become addresses` |-| 14 · Sinks realize namespaces | pending | `refactor(capture): payloads carry addresses; sinks realize them in their own namespace` |-| 15 · Per-mode output registries | pending | `feat(capture): per-mode output registries; handlers bound by publish capabilities` |-| 16 · AI ingress family | pending | `feat(capture): ai ingress is its own router family with its own capability` |-| 17 · Topic tables injected into sinks | pending | `refactor(capture): topic tables are sink-side data, injected at construction` |-| 18 · Per-pipeline output overrides; boot topic verification | pending | `feat(capture): per-pipeline output overrides and boot topic verification` |-| 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` |+| 9 · Named producers, instantiated once | pending | `refactor(capture): named producers own their connection config` |+| 10 · An output owns its topics and names its producer | pending | `refactor(capture): outputs carry their own topics and name their producer` |+| 11 · Outputs accept prepared events | pending | `feat(capture): outputs publish prepared events with per-event results` |+| 12 · v1 publishes through the outputs layer | pending | `refactor(capture): v1 publishes through outputs; v1 sink stack deleted` |+| 13 · Typed per-pipeline lanes | pending | `refactor(capture): typed per-pipeline lanes` |+| 14 · Per-mode output registries | pending | `feat(capture): per-mode output registries with required rows` |+| 15 · A reachable output must be configured | pending | `feat(capture): require configuration for every reachable output` |+| 16 · Verify topics against the producer's broker | pending | `feat(capture): verify each output's topics against its producer's broker at boot` |+| 17 · capture-analytics emergency fallback | pending | `feat(capture): select policy and emergency fallback for capture-analytics` |+| 18 · Delete the S3 fallback | pending | `refactor(capture): delete the s3 fallback and the health-gated failover policy` |+| 19 · One producer per cluster | objective 2 | `refactor(capture): v0 and v1 share one producer per cluster` |+| 20 · v0 builds prepared events | objective 2 | `refactor(capture): v0 publishes prepared events; PublishEvents retired` |+| 21 · One prepared-event builder | objective 2 | `refactor(capture): v0 and v1 share one prepared-event builder` |+| 22 · One lane-decision model | objective 2 | `refactor(capture): v0 lane decision moves to the v1 model` |+| 23 · Target selection at runtime | objective 3 | `feat(capture): select policy target switchable at runtime` |+| 24 · Producer health metrics out | objective 3 | `feat(capture): producers report health for the breaker service` |+| 25 · Switch signals in | objective 3 | `feat(capture): apply breaker switch signals to the select policy` |+| 26 · Prep hoist; `PublishEvents` retired | superseded | — (became Step 20) |+| 27 · AI membership stamp; `AiRouting` retired | done | — (landed with the AI lane rollout, outside this plan's sequence) |+| 28 · Sinks realize namespaces | superseded | — (targets map addresses to topics from Step 11) |+| 29 · Handlers bound by publish capabilities | deferred | `feat(capture): handlers bound by publish capabilities over per-mode state` |+| 30 · AI ingress family | deferred | `feat(capture): ai ingress is its own router family with its own capability` |+| 31 · Topic tables injected into sinks | superseded | — (each target owns its topics from Step 10) |+| 32 · Per-pipeline output overrides; boot topic verification | superseded | — (boot verification became Step 16; retargeting is configuration after Steps 10 and 14) |+| 33 · Naming and import hygiene | deferred | `refactor(capture): replace remaining nested paths with imports` + `refactor(capture): name the session replay pipeline consistently` |+| 34 · Outputs as an open trait | deferred | `refactor(capture): Outputs becomes an open trait` |+| 35 · Dynamic outputs prototype | deferred | `feat(capture): prototype dynamic outputs with incremental switchover (test-only)` |