:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ingestion): preserve structured warning type/source from backend producers (#70557)
Eli Reisman66250b0e9cb9
diff --git a/.agents/skills/adding-ingestion-warnings/SKILL.md b/.agents/skills/adding-ingestion-warnings/SKILL.mdindex cf02ce723296..e4df16ef72ae 100644--- a/.agents/skills/adding-ingestion-warnings/SKILL.md+++ b/.agents/skills/adding-ingestion-warnings/SKILL.md@@ -14,7 +14,8 @@ They are produced to the `clickhouse_ingestion_warnings` Kafka topic and land in## The registry is the source of truthEvery warning type must be registered in `INGESTION_WARNING_TYPES` in-[nodejs/src/ingestion/common/ingestion-warnings.ts](../../../nodejs/src/ingestion/common/ingestion-warnings.ts).+[nodejs/src/ingestion/common/ingestion-warning-types.ts](../../../nodejs/src/ingestion/common/ingestion-warning-types.ts)+(a dependency-free leaf, re-exported from `ingestion-warnings.ts`, so codegen and its test can import it cheaply).The registry fixes the type's `category` and `severity`; they are resolved at serialization time, so callsites cannot drift or forget them.An unregistered type is a compile error (`IngestionWarningType` is the registry's key union).@@ -52,8 +53,44 @@ Warnings are rate-limited per `team:type:key`. Set `key` to the entity you want## Rust-No Rust service emits ingestion warnings today — the Rust capture service only routes `$$client_ingestion_warning` events to Kafka; the nodejs pipeline turns them into warnings.-If a Rust service ever needs to produce to `clickhouse_ingestion_warnings` directly, mirror the nodejs registry in a Rust module (type enum with `category()` / `severity()`), keep the JSON shape identical to `serializeIngestionWarning`, and update this skill to point at it.+Rust services emit warnings through the `common-ingestion-warnings` crate ([rust/common/ingestion_warnings](../../../rust/common/ingestion_warnings)).+Unlike nodejs (which has database access and writes the v2 row directly), Rust producers have no token→team resolution, so they don't write the row themselves.+Instead they emit a synthetic `$$client_ingestion_warning` `CapturedEvent` onto the existing `client_ingestion_warning` topic; the nodejs `clientwarnings` consumer resolves the token to a `team_id`, reads the structured type/details/source, and writes the v2 row (see [handle-client-ingestion-warning-step.ts](../../../nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.ts)).++### The Rust `WarningType` is generated — nodejs is the single source of truth++There is no hand-maintained Rust copy of the type list. Entries in `INGESTION_WARNING_TYPES` flagged `captureProduced: true` are exactly the types Rust may emit, and a generator mirrors that set into a committed artifact the Rust build reads:++```text+INGESTION_WARNING_TYPES (captureProduced: true) # nodejs — source of truth+ → pnpm --filter=@posthog/nodejs gen:ingestion-warning-types+ → rust/common/ingestion_warnings/capture_warning_types.generated.json # committed+ → build.rs → WarningType enum + ALL + as_str() # generated at build time+```++The artifact is committed _inside_ the Rust crate so the isolated Rust Docker/CI build context stays self-contained — no cross-workspace file reads. The same `captureProduced` flag also derives the `CAPTURE_PRODUCED_WARNING_TYPES` allowlist the consumer enforces, so a single edit wires a type on both sides. Two tests guard the chain: the nodejs no-drift test (`generate-ingestion-warning-types.test.ts`) fails if the committed artifact and the generator output diverge, and the Rust `from_tag_round_trips_every_registered_type` test fails if a generated variant has no `from_tag` arm.++To add a **capture-produced** type:++1. **Register it in nodejs** — add the type to `INGESTION_WARNING_TYPES` with `captureProduced: true` (see the nodejs steps above for `category`/`severity`, which the consumer owns). This also puts it on the `CAPTURE_PRODUCED_WARNING_TYPES` allowlist automatically.+2. **Regenerate + commit the artifact** — run `pnpm --filter=@posthog/nodejs gen:ingestion-warning-types` and commit the updated `capture_warning_types.generated.json`.+3. **Add the Rust `from_tag` arm** — in `src/registry.rs`, map the capture error tag (`v1::Error::tag()` / per-event drop detail) to the newly generated `WarningType` variant. The variant, `as_str`, and `ALL` are generated — never hand-write them. `from_tag` stays hand-written because it maps capture's error taxonomy onto the registry and is the allowlist that makes unregistered tags emit nothing; the round-trip test forces you to add the arm.++Emitting from Rust:++- **Emit it** via `WarningEmitter::emit(token, source, warning, details, count)` — the builder injects `count` and `pipelineStep` into details and stamps `type`/`source`/`details` into the event properties the consumer reads. Use the same camelCase details keys as nodejs (`distinctId`, `eventUuid`, ...). The envelope's top-level `distinct_id` is always the token (never the offending id), so an oversized offending distinct_id can't make the consumer drop the warning.+- **`source` identifies the producer** (`src/lib.rs`): a `WarningSource { service, path }`. `service` is the stable message `source` field and metric label (e.g. `"capture"`) — pick one per service, don't invent a new value per call site. `path` is metric-only, for splitting volume within one service's emit sites (e.g. `"v1_analytics"`); it never reaches the message. Capture's only source today is `CAPTURE_V1_ANALYTICS`.+- **Best-effort, fire-and-forget**: throttled per `(token, type)` per pod, never awaited, never fails the caller. Capture gates it behind `CAPTURE_INGESTION_WARNINGS_ENABLED` (default off; see `rust/capture/src/config.rs`). The producer is a `common-kafka` `ThreadedProducer` (built via `create_threaded_kafka_producer` with `observe_delivery` as its delivery callback, so delivered/failed outcomes are counted on the producer's own poll thread — no per-message task). It reuses the main event cluster's hosts/TLS and the `client_ingestion_warning` topic but runs on its own dedicated `KafkaConfig`: the fire-and-forget policy (`client.id=capture-ingestion-warnings`, `acks=1`, `retries=0`, `linger.ms=100`, a bounded 10k-message queue, a 5s message timeout) is fixed in code as the `WARNINGS_KAFKA_*` constants in `rust/capture/src/setup.rs` — not env-configurable — while only the two capacity/safety limits stay tunable via env (`CAPTURE_INGESTION_WARNINGS_KAFKA_QUEUE_MIB` and `..._MESSAGE_MAX_BYTES`). So a slow or saturated warnings topic can never contend with the main event producer.+- **Crate deps**: `common-ingestion-warnings` depends on `common-types` (for `CapturedEvent`) and `common-kafka` (the producer) — not on `capture` or any service crate. `WarningEmitter` is a plain trait object (`Arc<dyn WarningEmitter>`), so any Rust service can depend on the crate and wire it the way capture does in `router::State` / `setup.rs`; a team-aware service just supplies its own token.++## Rolling out a new capture-produced type++Adding a `captureProduced` type is an additive schema change, but nodejs and Rust capture deploy independently, so order matters:++- **Deploy the consumer (nodejs) before the producer (Rust capture).** The `clientwarnings` consumer must recognize the new type before capture emits it. If capture ships first, the consumer falls back to the generic `client_ingestion_warning` type for the unknown value (no crash — but the structured type/details are lost until nodejs catches up).+- Because the Rust enum is generated from the committed artifact, both changes normally land in the **same PR/commit** — but they still roll out as two separate deploys, so merging together doesn't guarantee simultaneous rollout. Treat nodejs-before-capture as the safe order.+- Capture is gated behind `CAPTURE_INGESTION_WARNINGS_ENABLED` (default off). On a brand-new producer path, keep it disabled until the consumer deploy carrying the new type is live, then enable.+- Removing a type is the reverse: stop emitting from capture first, then drop it from the nodejs registry (and regenerate) once no in-flight messages reference it.## Downstream checklistdiff --git a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsxindex 5254276ffe7d..e39a8ee010cf 100644--- a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx+++ b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx@@ -38,6 +38,19 @@ export const WARNING_TYPE_TO_DESCRIPTION: Record<string, string> = {set_on_exception: '$set or $set_once is ignored on exception events and should not be sent',schema_validation_failed: 'Event rejected due to schema validation failure',invalid_heatmap_data: 'Invalid heatmap data',+ // Emitted by the capture service when it drops events at validation time+ missing_event_name: 'Discarded event with no event name',+ event_name_too_long: 'Discarded event whose name exceeds the length limit',+ missing_distinct_id: 'Discarded event with no distinct ID',+ distinct_id_too_large: 'Discarded event whose distinct ID exceeds the size limit',+ invalid_event_timestamp: 'Discarded event with an invalid timestamp',+ malformed_event_properties: 'Discarded event with malformed properties',+ invalid_options: 'Discarded event with invalid capture options',+ empty_batch: 'Rejected a request containing no events',+ invalid_batch: 'Rejected a batch with invalid metadata',+ missing_event_uuid: 'Rejected a batch containing an event with no UUID',+ invalid_event_uuid: 'Rejected a batch containing an event with an invalid UUID',+ duplicate_event_uuid: 'Rejected a batch containing duplicate event UUIDs',}// Explicit anchor on https://posthog.com/docs/data/ingestion-warnings for each warning type.@@ -289,7 +302,7 @@ export const WARNING_TYPE_RENDERER = {distinct_id <Link to={urls.personByDistinctId(details.distinctId)}>{details.distinctId}</Link> (eventuuid: <code>{details.eventUuid}</code>):<ul>- {details.errors.map((error, index) => (+ {(details.errors ?? []).map((error, index) => (<li key={index}>{error.reason === 'missing_required' ? (<>diff --git a/nodejs/package.json b/nodejs/package.jsonindex b5b9d19df6d9..8ca91410b388 100644--- a/nodejs/package.json+++ b/nodejs/package.json@@ -52,6 +52,7 @@"build:replay-anonymizer:dev": "pnpm --filter=@posthog/replay-anonymizer run build:dev","generate:personhog-proto": "cd ../proto && buf generate --template ../nodejs/buf.gen.yaml --path personhog/service --path personhog/types .","update-ai-costs": "ts-node src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts",+ "gen:ingestion-warning-types": "ts-node src/ingestion/common/scripts/generate-ingestion-warning-types.ts","sync-segment-icons": "DATABASE_URL=something ts-node src/cdp/segment/sync-segment-icons.ts","start:recording-rasterizer": "node dist/session-replay/recording-rasterizer/index.js"},diff --git a/nodejs/src/ingestion/common/ingestion-warning-types.ts b/nodejs/src/ingestion/common/ingestion-warning-types.tsnew file mode 100644index 000000000000..1827652d7281--- /dev/null+++ b/nodejs/src/ingestion/common/ingestion-warning-types.ts@@ -0,0 +1,115 @@+/**+ * Ingestion warning registry — the single source of truth for every warning type+ * this platform emits, shared across the Node.js pipeline and, via codegen, the+ * Rust producers (see the `captureProduced` note on the registry below).+ *+ * This module is intentionally dependency-free (pure data + types): it can be+ * imported by the standalone generator (`bin/generate-ingestion-warning-types.mts`)+ * and the no-drift test without loading the ingestion runtime. The runtime helpers+ * (serialize/emit, Kafka producer wiring) live in `./ingestion-warnings.ts`, which+ * re-exports everything here so existing `~/ingestion/common/ingestion-warnings`+ * importers are unaffected.+ */++export type IngestionWarningCategory = 'size' | 'merge' | 'event' | 'transformation' | 'replay'+export type IngestionWarningSeverity = 'info' | 'warning' | 'error'++/**+ * Central registry of every ingestion warning type this service can emit.+ * Category and severity are fixed attributes of the type, resolved at+ * serialization time so callsites cannot drift or forget them. Adding a new+ * warning requires registering it here, which keeps the ClickHouse v2+ * structured columns, the API filters, and agent-facing docs in sync.+ *+ * Severity convention: 'error' = the event (or message) was dropped,+ * 'warning' = ingested but modified or partially rejected,+ * 'info' = informational or an intentional, team-configured drop.+ */+export const INGESTION_WARNING_TYPES = {+ // Size limits — payload or property blobs exceeding Kafka/Postgres limits+ message_size_too_large: { category: 'size', severity: 'error' },+ person_properties_size_violation: { category: 'size', severity: 'error' },+ person_upsert_message_size_too_large: { category: 'size', severity: 'error' },+ group_upsert_message_size_too_large: { category: 'size', severity: 'error' },+ group_key_too_long: { category: 'size', severity: 'error' },++ // Person merges — rejected $identify / $create_alias / $merge_dangerously operations+ cannot_merge_already_identified: { category: 'merge', severity: 'warning' },+ cannot_merge_with_illegal_distinct_id: { category: 'merge', severity: 'warning' },+ merge_race_condition: { category: 'merge', severity: 'error' },++ // Event validation — malformed or rejected event data+ client_ingestion_warning: { category: 'event', severity: 'info' },+ // Capture-side validation drops (Rust capture; see rust/common/ingestion_warnings/src/registry.rs).+ // `captureProduced: true` is the source of truth for the cross-language contract: it derives+ // CAPTURE_PRODUCED_WARNING_TYPES (below) and is exported to+ // rust/common/ingestion_warnings/capture_warning_types.generated.json (`pnpm gen:ingestion-warning-types`),+ // from which the Rust WarningType enum is generated. Adding/removing a capture type is one edit here.+ missing_event_name: { category: 'event', severity: 'error', captureProduced: true },+ event_name_too_long: { category: 'event', severity: 'error', captureProduced: true },+ missing_distinct_id: { category: 'event', severity: 'error', captureProduced: true },+ distinct_id_too_large: { category: 'event', severity: 'error', captureProduced: true },+ invalid_event_timestamp: { category: 'event', severity: 'error', captureProduced: true },+ malformed_event_properties: { category: 'event', severity: 'error', captureProduced: true },+ invalid_options: { category: 'event', severity: 'error', captureProduced: true },+ empty_batch: { category: 'event', severity: 'error', captureProduced: true },+ invalid_batch: { category: 'event', severity: 'error', captureProduced: true },+ missing_event_uuid: { category: 'event', severity: 'error', captureProduced: true },+ invalid_event_uuid: { category: 'event', severity: 'error', captureProduced: true },+ duplicate_event_uuid: { category: 'event', severity: 'error', captureProduced: true },+ ignored_invalid_timestamp: { category: 'event', severity: 'warning' },+ schema_validation_failed: { category: 'event', severity: 'error' },+ skipping_event_invalid_distinct_id: { category: 'event', severity: 'error' },+ invalid_ai_token_property: { category: 'event', severity: 'warning' },+ invalid_process_person_profile: { category: 'event', severity: 'warning' },+ invalid_event_when_process_person_profile_is_false: { category: 'event', severity: 'error' },+ event_dropped_too_old: { category: 'event', severity: 'info' },++ // Cookieless mode — events missing the data required to compute a cookieless distinct id+ cookieless_missing_timestamp: { category: 'event', severity: 'error' },+ cookieless_timestamp_out_of_range: { category: 'event', severity: 'error' },+ cookieless_missing_user_agent: { category: 'event', severity: 'error' },+ cookieless_missing_ip: { category: 'event', severity: 'error' },+ cookieless_missing_host: { category: 'event', severity: 'error' },++ // Heatmaps — rejected $heatmap_data payloads+ invalid_heatmap_data: { category: 'event', severity: 'warning' },+ rejecting_heatmap_data_with_invalid_url: { category: 'event', severity: 'warning' },+ rejecting_heatmap_data_with_invalid_items: { category: 'event', severity: 'warning' },++ // Error tracking — exception event processing+ error_tracking_exception_processing_errors: { category: 'event', severity: 'warning' },++ // Transformations — user-configured hog transformations+ event_dropped_by_transformation: { category: 'transformation', severity: 'info' },++ // Session replay — rejected or suspicious replay messages+ replay_lib_version_too_old: { category: 'replay', severity: 'info' },+ message_contained_no_valid_rrweb_events: { category: 'replay', severity: 'warning' },+ message_timestamp_diff_too_large: { category: 'replay', severity: 'warning' },+} as const satisfies Record<+ string,+ { category: IngestionWarningCategory; severity: IngestionWarningSeverity; captureProduced?: true }+>++export type IngestionWarningType = keyof typeof INGESTION_WARNING_TYPES++/**+ * The subset of `INGESTION_WARNING_TYPES` that trusted Rust backend producers+ * (capture; see `rust/common/ingestion_warnings/src/registry.rs`) are allowed to+ * set via the structured `$$client_ingestion_warning_type` property.+ * `$$client_ingestion_warning` events arrive over the public capture path, so+ * that property is attacker-controlled — promoting it to an arbitrary registered+ * type would let a client impersonate any producer and forge details for+ * renderer-only types (e.g. `schema_validation_failed`, whose UI assumes a+ * validated `errors` array shape).+ *+ * Derived from the `captureProduced` flag above rather than hand-listed, so this+ * allowlist can never skew from the registry, and the same flag drives the Rust+ * codegen — a new capture type is wired on both sides from a single edit.+ */+export const CAPTURE_PRODUCED_WARNING_TYPES: ReadonlySet<IngestionWarningType> = new Set(+ (Object.entries(INGESTION_WARNING_TYPES) as [IngestionWarningType, { captureProduced?: boolean }][])+ .filter(([, meta]) => meta.captureProduced === true)+ .map(([type]) => type)+)diff --git a/nodejs/src/ingestion/common/ingestion-warnings.ts b/nodejs/src/ingestion/common/ingestion-warnings.tsindex 8ed9e98bcb96..6b84180feac4 100644--- a/nodejs/src/ingestion/common/ingestion-warnings.ts+++ b/nodejs/src/ingestion/common/ingestion-warnings.ts@@ -7,77 +7,32 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { logger } from '~/common/utils/logger'import { IngestionWarningLimiter } from '~/common/utils/token-bucket'import { castTimestampOrNow } from '~/common/utils/utils'+import {+ CAPTURE_PRODUCED_WARNING_TYPES,+ INGESTION_WARNING_TYPES,+ type IngestionWarningCategory,+ type IngestionWarningSeverity,+ type IngestionWarningType,+} from '~/ingestion/common/ingestion-warning-types'import { TeamId, TimestampFormat } from '~/types'+// The warning registry lives in the dependency-free `./ingestion-warning-types` leaf so the+// codegen generator and its no-drift test can import it without loading the ingestion runtime.+// Re-exported here so existing `~/ingestion/common/ingestion-warnings` importers are unaffected.+export {+ CAPTURE_PRODUCED_WARNING_TYPES,+ INGESTION_WARNING_TYPES,+ type IngestionWarningCategory,+ type IngestionWarningSeverity,+ type IngestionWarningType,+}+export const ingestionWarningCounter = new Counter({name: 'ingestion_warnings_total',help: 'Total number of ingestion warnings by type and emission status',labelNames: ['type', 'emitted'],})-export type IngestionWarningCategory = 'size' | 'merge' | 'event' | 'transformation' | 'replay'-export type IngestionWarningSeverity = 'info' | 'warning' | 'error'--/**- * Central registry of every ingestion warning type this service can emit.- * Category and severity are fixed attributes of the type, resolved here at- * serialization time so callsites cannot drift or forget them. Adding a new- * warning requires registering it here, which keeps the ClickHouse v2- * structured columns, the API filters, and agent-facing docs in sync.- *- * Severity convention: 'error' = the event (or message) was dropped,- * 'warning' = ingested but modified or partially rejected,- * 'info' = informational or an intentional, team-configured drop.- */-export const INGESTION_WARNING_TYPES = {- // Size limits — payload or property blobs exceeding Kafka/Postgres limits- message_size_too_large: { category: 'size', severity: 'error' },- person_properties_size_violation: { category: 'size', severity: 'error' },- person_upsert_message_size_too_large: { category: 'size', severity: 'error' },- group_upsert_message_size_too_large: { category: 'size', severity: 'error' },- group_key_too_long: { category: 'size', severity: 'error' },-- // Person merges — rejected $identify / $create_alias / $merge_dangerously operations- cannot_merge_already_identified: { category: 'merge', severity: 'warning' },- cannot_merge_with_illegal_distinct_id: { category: 'merge', severity: 'warning' },- merge_race_condition: { category: 'merge', severity: 'error' },-- // Event validation — malformed or rejected event data- client_ingestion_warning: { category: 'event', severity: 'info' },- ignored_invalid_timestamp: { category: 'event', severity: 'warning' },- schema_validation_failed: { category: 'event', severity: 'error' },- skipping_event_invalid_distinct_id: { category: 'event', severity: 'error' },- invalid_ai_token_property: { category: 'event', severity: 'warning' },- invalid_process_person_profile: { category: 'event', severity: 'warning' },- invalid_event_when_process_person_profile_is_false: { category: 'event', severity: 'error' },- event_dropped_too_old: { category: 'event', severity: 'info' },-- // Cookieless mode — events missing the data required to compute a cookieless distinct id- cookieless_missing_timestamp: { category: 'event', severity: 'error' },- cookieless_timestamp_out_of_range: { category: 'event', severity: 'error' },- cookieless_missing_user_agent: { category: 'event', severity: 'error' },- cookieless_missing_ip: { category: 'event', severity: 'error' },- cookieless_missing_host: { category: 'event', severity: 'error' },-- // Heatmaps — rejected $heatmap_data payloads- invalid_heatmap_data: { category: 'event', severity: 'warning' },- rejecting_heatmap_data_with_invalid_url: { category: 'event', severity: 'warning' },- rejecting_heatmap_data_with_invalid_items: { category: 'event', severity: 'warning' },-- // Error tracking — exception event processing- error_tracking_exception_processing_errors: { category: 'event', severity: 'warning' },-- // Transformations — user-configured hog transformations- event_dropped_by_transformation: { category: 'transformation', severity: 'info' },-- // Session replay — rejected or suspicious replay messages- replay_lib_version_too_old: { category: 'replay', severity: 'info' },- message_contained_no_valid_rrweb_events: { category: 'replay', severity: 'warning' },- message_timestamp_diff_too_large: { category: 'replay', severity: 'warning' },-} as const satisfies Record<string, { category: IngestionWarningCategory; severity: IngestionWarningSeverity }>--export type IngestionWarningType = keyof typeof INGESTION_WARNING_TYPES-/*** Unified ingestion warning structure used across pipeline warnings and direct producer calls.* Category and severity come from INGESTION_WARNING_TYPES; only the per-occurrence@@ -89,6 +44,9 @@ export interface IngestionWarning {pipelineStep?: stringkey?: stringalwaysSend?: boolean+ // Producing service, stamped into the v2 message `source` column. Defaults+ // to 'plugin-server'; other producers (e.g. 'capture') set it explicitly.+ source?: string}function serializeIngestionWarning(teamId: TeamId, warning: IngestionWarning): string {@@ -104,7 +62,7 @@ function serializeIngestionWarning(teamId: TeamId, warning: IngestionWarning): sreturn JSON.stringify({team_id: teamId,type: warning.type,- source: 'plugin-server',+ source: warning.source ?? 'plugin-server',details: JSON.stringify(fullDetails),timestamp: castTimestampOrNow(null, TimestampFormat.ClickHouse),})diff --git a/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.test.ts b/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.test.tsnew file mode 100644index 000000000000..f5d26d833f97--- /dev/null+++ b/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.test.ts@@ -0,0 +1,22 @@+import fs from 'fs'++import { parseJSON } from '~/common/utils/json-parse'+import { CAPTURE_PRODUCED_WARNING_TYPES } from '~/ingestion/common/ingestion-warning-types'+import {+ RUST_GENERATED_JSON_PATH,+ buildCaptureWarningTypesJson,+} from '~/ingestion/common/scripts/generate-ingestion-warning-types'++describe('capture warning types codegen', () => {+ it('committed Rust artifact matches the generator output', () => {+ const committed = fs.readFileSync(RUST_GENERATED_JSON_PATH, 'utf8')+ expect(committed).toEqual(buildCaptureWarningTypesJson())+ // If this fails, INGESTION_WARNING_TYPES changed without regenerating the artifact the+ // Rust build reads. Run `pnpm --filter=@posthog/nodejs gen:ingestion-warning-types`.+ })++ it('artifact lists exactly the capture-produced types in stable sorted order', () => {+ const { types } = parseJSON(fs.readFileSync(RUST_GENERATED_JSON_PATH, 'utf8')) as { types: string[] }+ expect(types).toEqual([...CAPTURE_PRODUCED_WARNING_TYPES].sort())+ })+})diff --git a/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.ts b/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.tsnew file mode 100644index 000000000000..96415845c78c--- /dev/null+++ b/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.ts@@ -0,0 +1,58 @@+import fs from 'fs'+import path from 'path'++import { CAPTURE_PRODUCED_WARNING_TYPES } from '~/ingestion/common/ingestion-warning-types'++/**+ * Codegen for the cross-language ingestion-warning contract.+ *+ * `INGESTION_WARNING_TYPES` (nodejs/src/ingestion/common/ingestion-warning-types.ts) is the single+ * source of truth. Entries flagged `captureProduced: true` are the types Rust capture may emit; this+ * script mirrors that set into a JSON artifact committed inside the Rust crate, from which+ * `rust/common/ingestion_warnings/build.rs` generates the `WarningType` enum. Committing the artifact+ * (rather than reading the .ts from Rust) keeps the isolated Rust Docker/CI build context self-contained.+ *+ * Run: `pnpm --filter=@posthog/nodejs gen:ingestion-warning-types`+ * The no-drift Jest test (`generate-ingestion-warning-types.test.ts`) fails CI if the committed+ * artifact and this output diverge.+ */++const REPO_ROOT = path.resolve(__dirname, '../../../../..')++/** Absolute path of the committed artifact consumed by the Rust build. */+export const RUST_GENERATED_JSON_PATH = path.join(+ REPO_ROOT,+ 'rust/common/ingestion_warnings/capture_warning_types.generated.json'+)++/**+ * Canonical artifact contents: a stable, sorted set of the capture-produced warning type strings.+ * Only the type strings cross the boundary — category/severity are resolved Node-side at+ * serialization time, and the Rust pipeline step is a constant, so neither belongs here.+ */+export function buildCaptureWarningTypesJson(): string {+ const types = [...CAPTURE_PRODUCED_WARNING_TYPES].sort()+ const artifact = {+ _comment:+ 'GENERATED from INGESTION_WARNING_TYPES (captureProduced) in ' ++ 'nodejs/src/ingestion/common/ingestion-warning-types.ts via ' ++ '`pnpm --filter=@posthog/nodejs gen:ingestion-warning-types`. Do not edit by hand; ' ++ 'rust/common/ingestion_warnings/build.rs codegens the WarningType enum from this file.',+ types,+ }+ // 2-space indent + trailing newline matches Prettier's JSON default, so the artifact stays+ // byte-stable across formatters and the no-drift test can compare exact contents.+ return JSON.stringify(artifact, null, 2) + '\n'+}++function main(): void {+ const contents = buildCaptureWarningTypesJson()+ fs.writeFileSync(RUST_GENERATED_JSON_PATH, contents)+ console.log(+ `Wrote ${[...CAPTURE_PRODUCED_WARNING_TYPES].length} capture warning types to ${RUST_GENERATED_JSON_PATH}`+ )+}++if (require.main === module) {+ main()+}diff --git a/nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.test.tsindex 9502f0277f17..4e1bafc89dc6 100644--- a/nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.test.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.test.ts@@ -127,6 +127,137 @@ describe('handleClientIngestionWarningStep', () => {})})+ describe('structured backend warnings', () => {+ it('preserves the structured type, source, and details from the envelope', async () => {+ const step = createHandleClientIngestionWarningStep(mockOutputs)+ const input: HandleClientIngestionWarningStepInput = {+ ...baseInput,+ event: {+ ...baseEvent,+ event: '$$client_ingestion_warning',+ properties: {+ $$client_ingestion_warning_type: 'missing_event_name',+ $$client_ingestion_warning_source: 'capture',+ $$client_ingestion_warning_details: {+ distinctId: 'offending-id',+ eventUuid: 'offending-uuid',+ count: 3,+ pipelineStep: 'capture_validation',+ },+ },+ },+ }++ const result = await step(input)++ expect(result.type).toBe(PipelineResultType.OK)+ const warning = producedWarning()+ expect(warning.type).toBe('missing_event_name')+ expect((warning as any).source).toBe('capture')+ // The producer's own ids win over the synthetic warning event's ids.+ expect(warning.details).toMatchObject({+ distinctId: 'offending-id',+ eventUuid: 'offending-uuid',+ count: 3,+ pipelineStep: 'capture_validation',+ // Category/severity come from the registry, not the envelope.+ category: 'event',+ severity: 'error',+ })+ })++ it('falls back to the client warning shape for an unrecognized structured type', async () => {+ const step = createHandleClientIngestionWarningStep(mockOutputs)+ const input: HandleClientIngestionWarningStepInput = {+ ...baseInput,+ event: {+ ...baseEvent,+ event: '$$client_ingestion_warning',+ properties: {+ $$client_ingestion_warning_type: 'not_a_real_type',+ $$client_ingestion_warning_message: 'legacy',+ },+ },+ }++ const result = await step(input)++ expect(result.type).toBe(PipelineResultType.OK)+ const warning = producedWarning()+ expect(warning.type).toBe('client_ingestion_warning')+ expect((warning as any).source).toBe('plugin-server')+ expect(warning.details.message).toBe('legacy')+ })++ it('falls back to the client warning shape for a registered but non-capture type, even with forged details', async () => {+ // $$client_ingestion_warning arrives over the public capture path, so a+ // client could try to impersonate a plugin-server-only type (registered,+ // but never emitted by capture) to reach a renderer that assumes a+ // validated shape (e.g. schema_validation_failed's `details.errors`).+ // The allowlist must reject this even though the type itself is+ // registered in INGESTION_WARNING_TYPES.+ const step = createHandleClientIngestionWarningStep(mockOutputs)+ const input: HandleClientIngestionWarningStepInput = {+ ...baseInput,+ event: {+ ...baseEvent,+ event: '$$client_ingestion_warning',+ properties: {+ $$client_ingestion_warning_type: 'schema_validation_failed',+ $$client_ingestion_warning_source: 'capture',+ $$client_ingestion_warning_details: {},+ },+ },+ }++ const result = await step(input)++ expect(result.type).toBe(PipelineResultType.OK)+ const warning = producedWarning()+ expect(warning.type).toBe('client_ingestion_warning')+ expect((warning as any).source).toBe('plugin-server')+ })++ // Unique team ids so each row hits a fresh per-(team,type) limiter bucket+ // rather than the one the 'preserves' test above already consumed.+ it.each([+ ['a string', 'x'.repeat(10), 90001],+ ['an array', ['a', 'b', 'c'], 90002],+ ])(+ 'drops non-object details (%s) instead of exploding it into indexed keys',+ async (_label, badDetails, teamId) => {+ // A client can set details to a large string/array; object-rest would+ // otherwise expand it into one key per character/element in the hot+ // consumer path, before the per-(team,type) limiter can throttle it.+ const step = createHandleClientIngestionWarningStep(mockOutputs)+ const input: HandleClientIngestionWarningStepInput = {+ ...baseInput,+ team: { id: teamId },+ event: {+ ...baseEvent,+ event: '$$client_ingestion_warning',+ properties: {+ $$client_ingestion_warning_type: 'missing_event_name',+ $$client_ingestion_warning_source: 'capture',+ $$client_ingestion_warning_details: badDetails,+ },+ },+ }++ const result = await step(input)++ expect(result.type).toBe(PipelineResultType.OK)+ const warning = producedWarning()+ // Still promoted (type is allowlisted), but details carry only the+ // envelope defaults — no indexed keys leaked from the bad shape.+ expect(warning.type).toBe('missing_event_name')+ const indexedKeys = Object.keys(warning.details).filter((k) => /^\d+$/.test(k))+ expect(indexedKeys).toEqual([])+ expect(warning.details).toMatchObject({ eventUuid, distinctId: 'my_id' })+ }+ )+ })+describe('non-client ingestion warning events', () => {it.each([['$pageview'], ['$identify'], ['custom_event']])('DLQs %s events', async (eventName) => {const step = createHandleClientIngestionWarningStep(mockOutputs)diff --git a/nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.ts b/nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.tsindex b36daae0ad4d..6496bfa53577 100644--- a/nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.ts@@ -2,7 +2,12 @@ import { Message } from 'node-rdkafka'import { IngestionWarningsOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'-import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'+import {+ CAPTURE_PRODUCED_WARNING_TYPES,+ IngestionWarning,+ IngestionWarningType,+ emitIngestionWarning,+} from '~/ingestion/common/ingestion-warnings'import { PipelineResult, dlq, ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'import { PluginEvent } from '~/plugin-scaffold'@@ -41,18 +46,67 @@ export function createHandleClientIngestionWarningStep<TInput extends HandleCliepartition: message.partition,}- const ingested = emitIngestionWarning(outputs, team.id, {- type: 'client_ingestion_warning',- details: {- eventUuid: event.uuid,- event: event.event,- distinctId: event.distinct_id,- message: event.properties?.$$client_ingestion_warning_message,- },- pipelineStep: 'client-emit',- alwaysSend: true,- }).then((emitted) => (emitted ? ingestedInfo : null))+ const ingested = emitIngestionWarning(outputs, team.id, buildWarning(event)).then((emitted) =>+ emitted ? ingestedInfo : null+ )return Promise.resolve(ok({ ingested: [ingested] }, [ingested]))}}++/**+ * Build the ingestion warning for a `$$client_ingestion_warning` event.+ *+ * Backend producers that can't resolve token->team (capture) emit a synthetic+ * `$$client_ingestion_warning` event carrying a structured warning type,+ * details, and source in its properties. When present and one of the types a+ * trusted backend producer actually emits (`CAPTURE_PRODUCED_WARNING_TYPES`)+ * we preserve them and let the per-(team,type) limiter throttle the warning.+ * Otherwise we fall back to the original client-emitted warning shape.+ *+ * These properties ride on a publicly-ingestible event, so they are+ * attacker-controlled — the allowlist (rather than the full ingestion-warning+ * registry) stops a client from impersonating another producer or forging+ * details for a renderer-only type it was never meant to set.+ */+function buildWarning(event: PluginEvent): IngestionWarning {+ const props = event.properties ?? {}+ const structuredType = props.$$client_ingestion_warning_type++ if (+ typeof structuredType === 'string' &&+ CAPTURE_PRODUCED_WARNING_TYPES.has(structuredType as IngestionWarningType)+ ) {+ // Details ride on a publicly-ingestible event, so this is attacker-controlled.+ // Object-rest over a string or array explodes it into one property per+ // character/element (before the limiter runs), so only accept a plain object+ // and drop any other shape (note: typeof null === 'object').+ const rawDetails = props.$$client_ingestion_warning_details+ const detailsIn: Record<string, any> =+ rawDetails !== null && typeof rawDetails === 'object' && !Array.isArray(rawDetails) ? rawDetails : {}+ const { pipelineStep, ...restDetails } = detailsIn+ const source = props.$$client_ingestion_warning_source+ return {+ type: structuredType as IngestionWarningType,+ // Envelope ids are defaults; the producer's own ids (the offending+ // event, not the synthetic warning event) win when supplied.+ details: { eventUuid: event.uuid, distinctId: event.distinct_id, ...restDetails },+ pipelineStep: typeof pipelineStep === 'string' ? pipelineStep : undefined,+ source: typeof source === 'string' ? source : undefined,+ // Deliberately no alwaysSend: the per-(team,type) limiter is the+ // gatekeeper for backend-produced volume.+ }+ }++ return {+ type: 'client_ingestion_warning',+ details: {+ eventUuid: event.uuid,+ event: event.event,+ distinctId: event.distinct_id,+ message: props.$$client_ingestion_warning_message,+ },+ pipelineStep: 'client-emit',+ alwaysSend: true,+ }+}diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 681341a9a9a6..5fae8e973834 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -1801,6 +1801,8 @@ dependencies = ["common-alloc","common-compression","common-continuous-profiling",+ "common-ingestion-warnings",+ "common-kafka","common-redis","common-types","envconfig",@@ -2453,6 +2455,23 @@ dependencies = ["tracing",]+[[package]]+name = "common-ingestion-warnings"+version = "0.1.0"+dependencies = [+ "chrono",+ "common-kafka",+ "common-liveness",+ "common-types",+ "governor",+ "metrics",+ "rdkafka",+ "rstest",+ "serde_json",+ "tracing",+ "uuid",+]+[[package]]name = "common-kafka"version = "0.1.0"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 8815f3da81a1..c4915e422a04 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -46,6 +46,7 @@ members = ["embedding-worker","common/geoip","common/hogvm",+ "common/ingestion_warnings","hogql/parser","kafka-assigner","kafka-assigner-proto",diff --git a/rust/capture/Cargo.toml b/rust/capture/Cargo.tomlindex 38cd846a38db..c52f5a12f291 100644--- a/rust/capture/Cargo.toml+++ b/rust/capture/Cargo.toml@@ -28,6 +28,8 @@ hyper-util = { workspace = true }common-alloc = { path = "../common/alloc" }common-compression = { path = "../common/compression" }common-continuous-profiling = { path = "../common/continuous_profiling" }+common-ingestion-warnings = { path = "../common/ingestion_warnings" }+common-kafka = { path = "../common/kafka" }common-redis = { path = "../common/redis" }common-types = { path = "../common/types" }limiters = { path = "../common/limiters" }diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex 3456cbabea68..a69b76274759 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -342,6 +342,34 @@ pub struct Config {/// Batch size threshold for parallel scatter-gather serialization; 0 disables fanout.#[envconfig(default = "8")]pub capture_v1_scatter_gather_min_batch: usize,++ // --- Ingestion warnings emitter (fire-and-forget, best-effort) ---+ // Warnings are emitted as `$$client_ingestion_warning` events onto the+ // existing `client_ingestion_warning` topic on the main event cluster+ // (see `KAFKA_CLIENT_INGESTION_WARNING_TOPIC`), so the producer reuses the+ // main cluster's hosts/TLS — but it gets its OWN dedicated+ // `common_kafka::config::KafkaConfig` (below) with fire-and-forget+ // acks/retries and a small queue, so a saturated or slow warnings topic+ // can never behave like — or contend with — the main event producer.+ // Defaults off (fail open).+ #[envconfig(default = "false")]+ pub capture_ingestion_warnings_enabled: bool,++ // The producer's fire-and-forget policy (acks, retries, linger, queue+ // depth in messages, message timeout) is fixed in code — see the+ // `WARNINGS_KAFKA_*` constants in `setup.rs` — not env-configurable, since+ // those define the "a warning is worth less than the cost of retrying it"+ // contract rather than operator knobs. Only the two capacity/safety limits+ // below stay tunable.+ #[envconfig(default = "16")]+ pub capture_ingestion_warnings_kafka_queue_mib: u32,++ // rdkafka "message.max.bytes": a hard per-message ceiling, independent of+ // the main producer's, so an oversized warning envelope (e.g. built from+ // attacker-controlled input) cannot inflate past this regardless of what+ // the main event producer allows.+ #[envconfig(default = "1048576")]+ pub capture_ingestion_warnings_kafka_message_max_bytes: u32,}#[derive(Envconfig, Clone)]diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rsindex cbe6acd0908e..dc6d81f93ed1 100644--- a/rust/capture/src/router.rs+++ b/rust/capture/src/router.rs@@ -21,6 +21,7 @@ use crate::otel;use crate::test_endpoint;use crate::v0_request::DataType;use crate::{ai_endpoint, sinks, time::TimeSource, v0_endpoint};+use common_ingestion_warnings::WarningEmitter;use common_redis::Client;use limiters::overflow::OverflowLimiter;use limiters::redis::RedisLimiter;@@ -84,6 +85,12 @@ pub struct State {pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,pub capture_v1_scatter_gather_min_batch: usize,pub ai_gateway_signing_secret: Option<String>,+ /// Best-effort v2 ingestion warnings emitter (fire-and-forget Kafka+ /// producer behind a per-(token, type) throttle). `None` when disabled —+ /// emit points skip on `is_none()`, same optionality pattern as+ /// `overflow_limiter` / `event_restriction_service`. Never awaited and+ /// never allowed to fail a request.+ pub ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,}#[derive(Clone, Copy)]@@ -153,6 +160,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,capture_v1_scatter_gather_min_batch: usize,ai_gateway_signing_secret: Option<String>,+ ingestion_warning_emitter: Option<Arc<dyn WarningEmitter>>,) -> Router {let state = State {sink,@@ -180,6 +188,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +v1_sink_router,capture_v1_scatter_gather_min_batch,ai_gateway_signing_secret,+ ingestion_warning_emitter,};// Very permissive CORS policy, as old SDK versionsdiff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex ca839dc2f55e..14370be54ff5 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -4,6 +4,9 @@ use std::time::Duration;use anyhow::Context;use axum::Router;+use common_ingestion_warnings::{observe_delivery, KafkaWarningEmitter, WarningEmitter};+use common_kafka::config::KafkaConfig as WarningsKafkaConfig;+use common_kafka::kafka_producer::create_threaded_kafka_producer;use common_redis::RedisClient;use tracing::{info, warn};@@ -33,6 +36,7 @@ pub struct LifecycleHandles {pub sink: Option<lifecycle::Handle>,pub advisory: Option<lifecycle::Handle>,pub event_restrictions: Option<lifecycle::Handle>,+ pub ingestion_warnings: Option<lifecycle::Handle>,pub v1_sinks: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle>,pub readiness: lifecycle::ReadinessHandler,pub liveness: lifecycle::LivenessHandler,@@ -79,6 +83,21 @@ pub fn register_components(manager: &mut lifecycle::Manager, config: &Config) ->None};+ // Advisory: the warnings producer is best-effort, so a stalled or dead+ // producer must never gate pod liveness/readiness or trigger shutdown.+ let ingestion_warnings = if config.capture_ingestion_warnings_enabled {+ Some(+ manager.register(+ "ingestion-warnings",+ lifecycle::ComponentOptions::new()+ .with_liveness_deadline(Duration::from_secs(30))+ .is_advisory(true),+ ),+ )+ } else {+ None+ };+let v1_sinks: HashMap<crate::v1::sinks::SinkName, lifecycle::Handle> =if !config.capture_v1_sinks.is_empty() {crate::v1::sinks::parse_sink_names(&config.capture_v1_sinks)@@ -108,6 +127,7 @@ pub fn register_components(manager: &mut lifecycle::Manager, config: &Config) ->sink,advisory,event_restrictions,+ ingestion_warnings,v1_sinks,readiness,liveness,@@ -132,6 +152,7 @@ pub async fn build_components(sink: sink_handle,advisory: advisory_handle,event_restrictions: event_restrictions_handle,+ ingestion_warnings: ingestion_warnings_handle,v1_sinks: v1_sink_handles,readiness,liveness,@@ -357,6 +378,9 @@ pub async fn build_components(None};+ let ingestion_warning_emitter =+ create_ingestion_warning_emitter(&config, ingestion_warnings_handle).await;+let app = router::router(crate::time::SystemTime {},readiness,@@ -387,6 +411,7 @@ pub async fn build_components(v1_sink_router.clone(),config.capture_v1_scatter_gather_min_batch,config.ai_gateway_signing_secret.clone(),+ ingestion_warning_emitter,);info!(@@ -529,6 +554,146 @@ async fn create_sink(}}+// Fixed fire-and-forget tuning for the warnings producer. These are+// deliberately not env-configurable: they define the "a warning is worth less+// than the cost of retrying it" contract, not knobs an operator should turn.+// (Queue size in MiB and the per-message byte ceiling stay env-configurable in+// `Config` because they're capacity/safety limits, not the delivery policy.)+const WARNINGS_KAFKA_CLIENT_ID: &str = "capture-ingestion-warnings";+// rdkafka "acks": leader ack only, trading durability for latency.+const WARNINGS_KAFKA_ACKS: &str = "1";+// rdkafka "retries": never retry a dropped warning.+const WARNINGS_KAFKA_RETRIES: u32 = 0;+// Small batching window, in ms.+const WARNINGS_KAFKA_LINGER_MS: u32 = 100;+// Bound the in-flight local backlog by message count.+const WARNINGS_KAFKA_QUEUE_MESSAGES: u32 = 10_000;+// Drop a message not delivered within this many ms.+const WARNINGS_KAFKA_MESSAGE_TIMEOUT_MS: u32 = 5_000;++/// Build the dedicated, warnings-only Kafka config. Reuses only the+/// destination cluster (`hosts`/`tls`) from capture's main Kafka config;+/// everything else is the fixed fire-and-forget policy (client id, acks,+/// retries, linger, queue depth, message timeout) plus the two tunable limits+/// (`queue_mib`, `message_max_bytes`). `..Default::default()` supplies the+/// shared-crate defaults (compression codec, empty client rack) and — critically+/// — leaves every opt-in producer tuning knob at `None`, so warnings never+/// inherit the main event producer's batching/idempotence tuning.+fn build_warnings_kafka_config(+ kafka_hosts: String,+ kafka_tls: bool,+ queue_mib: u32,+ message_max_bytes: u32,+) -> WarningsKafkaConfig {+ WarningsKafkaConfig {+ kafka_hosts,+ kafka_tls,+ kafka_client_id: WARNINGS_KAFKA_CLIENT_ID.to_string(),+ kafka_producer_acks: Some(WARNINGS_KAFKA_ACKS.to_string()),+ kafka_producer_retries: Some(WARNINGS_KAFKA_RETRIES),+ kafka_producer_linger_ms: WARNINGS_KAFKA_LINGER_MS,+ kafka_producer_queue_messages: WARNINGS_KAFKA_QUEUE_MESSAGES,+ kafka_message_timeout_ms: WARNINGS_KAFKA_MESSAGE_TIMEOUT_MS,+ kafka_producer_queue_mib: queue_mib,+ kafka_producer_message_max_bytes: Some(message_max_bytes),+ ..Default::default()+ }+}++/// Build the optional v2 ingestion warnings emitter. Best-effort by contract:+/// any misconfiguration or producer-creation failure logs and returns `None`+/// (capture runs without warnings) instead of failing startup. The producer+/// is a `common_kafka` `ThreadedProducer`, built via+/// `common_kafka::kafka_producer::create_threaded_kafka_producer` from a+/// dedicated, warnings-only `common_kafka::config::KafkaConfig` (fire-and-forget+/// acks/retries, a small queue) with `observe_delivery` as its delivery+/// callback — it shares only the destination cluster (hosts/TLS) and the+/// `client_ingestion_warning` topic with capture's main event producer, never+/// its tuning or connection. When built, a background task heartbeats the+/// advisory lifecycle handle, sweeps the throttle's per-key state, and flushes+/// the producer once at shutdown.+///+/// Fail-open note: unlike the previous bespoke producer (which never pinged+/// brokers at startup), `create_threaded_kafka_producer` does a one-time+/// metadata fetch. If brokers are unreachable at boot, the emitter stays+/// disabled for the pod's life rather than retrying.+async fn create_ingestion_warning_emitter(+ config: &Config,+ handle: Option<lifecycle::Handle>,+) -> Option<Arc<dyn WarningEmitter>> {+ if !config.capture_ingestion_warnings_enabled {+ return None;+ }++ if config.kafka.kafka_hosts.is_empty() {+ warn!("ingestion warnings enabled but KAFKA_HOSTS is empty; emitter disabled");+ return None;+ }++ let Some(handle) = handle else {+ warn!(+ "ingestion warnings enabled but no lifecycle handle was registered; emitter disabled"+ );+ return None;+ };++ let warnings_kafka_config = build_warnings_kafka_config(+ config.kafka.kafka_hosts.clone(),+ config.kafka.kafka_tls,+ config.capture_ingestion_warnings_kafka_queue_mib,+ config.capture_ingestion_warnings_kafka_message_max_bytes,+ );++ let producer = match create_threaded_kafka_producer(+ &warnings_kafka_config,+ handle.clone(),+ observe_delivery,+ )+ .await+ {+ Ok(producer) => producer,+ Err(e) => {+ tracing::error!(+ "failed to create ingestion warnings producer, emitter disabled: {e:#}"+ );+ return None;+ }+ };++ let emitter = Arc::new(KafkaWarningEmitter::new(+ producer,+ config.kafka.kafka_client_ingestion_warning_topic.clone(),+ ));++ let emitter_bg = emitter.clone();+ tokio::spawn(async move {+ let mut heartbeat = tokio::time::interval(Duration::from_secs(10));+ let mut sweep = tokio::time::interval(Duration::from_secs(60));+ loop {+ tokio::select! {+ _ = heartbeat.tick() => handle.report_healthy(),+ _ = sweep.tick() => emitter_bg.sweep_throttle(),+ _ = handle.shutdown_recv() => break,+ }+ }+ // Advisory flush: rdkafka flush blocks, so keep it off the async+ // workers. Dropping the handle after shutdown signals completion.+ let flush_result = tokio::task::spawn_blocking(move || {+ emitter_bg.flush(Duration::from_secs(2));+ })+ .await;+ if let Err(e) = flush_result {+ warn!("ingestion warnings flush task panicked: {e}");+ }+ });++ info!(+ topic = config.kafka.kafka_client_ingestion_warning_topic.as_str(),+ "ingestion warnings emitter enabled"+ );+ Some(emitter)+}+fn create_event_restriction_service(config: &Config,handle: lifecycle::Handle,@@ -644,6 +809,49 @@ mod tests {);}+ #[test]+ fn warnings_kafka_config_is_isolated_from_main_producer_tuning() {+ let cfg = build_warnings_kafka_config("broker:9092".to_string(), true, 16, 1_048_576);++ // Reuses only the destination cluster from the main config.+ assert_eq!(cfg.kafka_hosts, "broker:9092");+ assert!(cfg.kafka_tls);++ // Fixed fire-and-forget policy (not env-configurable).+ assert_eq!(cfg.kafka_client_id, WARNINGS_KAFKA_CLIENT_ID);+ assert_eq!(+ cfg.kafka_producer_acks.as_deref(),+ Some(WARNINGS_KAFKA_ACKS)+ );+ assert_eq!(cfg.kafka_producer_retries, Some(WARNINGS_KAFKA_RETRIES));+ assert_eq!(cfg.kafka_producer_linger_ms, WARNINGS_KAFKA_LINGER_MS);+ assert_eq!(+ cfg.kafka_producer_queue_messages,+ WARNINGS_KAFKA_QUEUE_MESSAGES+ );+ assert_eq!(+ cfg.kafka_message_timeout_ms,+ WARNINGS_KAFKA_MESSAGE_TIMEOUT_MS+ );++ // The two tunable capacity/safety limits pass through unchanged.+ assert_eq!(cfg.kafka_producer_queue_mib, 16);+ assert_eq!(cfg.kafka_producer_message_max_bytes, Some(1_048_576));++ // Critically: none of the main event producer's opt-in tuning leaks in+ // — `..Default::default()` must leave every WarpStream knob at `None`.+ assert_eq!(cfg.kafka_producer_batch_size, None);+ assert_eq!(cfg.kafka_producer_batch_num_messages, None);+ assert_eq!(cfg.kafka_producer_enable_idempotence, None);+ assert_eq!(+ cfg.kafka_producer_max_in_flight_requests_per_connection,+ None+ );+ assert_eq!(cfg.kafka_producer_topic_metadata_refresh_interval_ms, None);+ assert_eq!(cfg.kafka_producer_sticky_partitioning_linger_ms, None);+ assert_eq!(cfg.kafka_producer_partitioner, None);+ }+#[test]#[should_panic(expected = "S3_FALLBACK_ENABLED cannot be combined with AI secondary routing")]fn register_components_rejects_s3_fallback_with_ai_secondary() {diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex ff7d45d63e0c..f5224ffbc494 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -28,6 +28,7 @@ use crate::v1::sinks::event::Event as SinkEvent;use crate::v1::sinks::types::SinkResult;use crate::v1::sinks::{serialize_batch, Destination};use crate::v1::Error;+use common_ingestion_warnings::{WarningType, CAPTURE_V1_ANALYTICS};/// Maps event name to its Kafka destination, mirroring legacy DataType assignment.///@@ -53,10 +54,24 @@ pub async fn process_batch(let processing_start = Instant::now();crate::ctx_log!(Level::INFO, context, "process_batch called");- validate_batch(&batch)?;+ let batch_len = batch.batch.len();+ if let Err(err) = validate_batch(&batch) {+ emit_batch_abort_warning(state, context, &err, batch_len);+ return Err(err);+ }context.set_batch_metadata(&batch);- let mut events = validate_events(context, batch)?;+ let mut events = match validate_events(context, batch) {+ Ok(events) => events,+ Err(err) => {+ emit_batch_abort_warning(state, context, &err, batch_len);+ return Err(err);+ }+ };++ // Best-effort v2 ingestion warnings for validation drops, emitted before+ // the all-dropped early return so those batches are covered too.+ emit_validation_drop_warnings(state, context, &events);// Nothing left to process — return 200 with per-event drops.if events.iter().all(|ev| ev.result != EventResult::Ok) {@@ -253,6 +268,111 @@ pub fn merge_sink_results(events: &mut [WrappedEvent], sink_results: &[Box<dyn S}}+/// Stamps request-level context (sdk lib/version, request path) into a+/// warning's details map. Keys are camelCase to match the v2 `DEFAULT`+/// extractors' expectations for entity keys.+fn warning_context_details(context: &Context) -> serde_json::Map<String, serde_json::Value> {+ let mut details = serde_json::Map::new();+ if let Some((lib, version)) = context.sdk_lib_and_version() {+ details.insert("lib".to_string(), serde_json::json!(lib));+ details.insert("libVersion".to_string(), serde_json::json!(version));+ }+ details.insert("path".to_string(), serde_json::json!(context.path));+ details+}++/// Best-effort v2 ingestion warning for a whole-batch validation abort (4xx).+/// The batch is rejected as a unit, so `count` charges the full batch length;+/// no per-event identifiers exist at this point. Unregistered tags emit+/// nothing (allowlist in `WarningType::from_tag`). Never fails the request.+fn emit_batch_abort_warning(+ state: &router::State,+ context: &Context,+ err: &Error,+ batch_len: usize,+) {+ let Some(ref emitter) = state.ingestion_warning_emitter else {+ return;+ };+ let Some(warning) = WarningType::from_tag(err.tag()) else {+ return;+ };+ // `empty_batch` aborts have batch_len == 0; the rejected request is still+ // one occurrence, so never charge a count of zero.+ emitter.emit(+ context.api_token.clone(),+ CAPTURE_V1_ANALYTICS,+ warning,+ warning_context_details(context),+ batch_len.max(1) as u64,+ );+}++/// Best-effort v2 ingestion warnings for per-event validation drops: one+/// message per registered drop tag with the deduped occurrence count.+/// `distinctId`/`eventUuid` are included only when a tag matched exactly one+/// event — with multiple events they would be ambiguous, so they are omitted.+/// Skips entirely when the emitter is off or the batch had no drops.+fn emit_validation_drop_warnings(+ state: &router::State,+ context: &Context,+ events: &[WrappedEvent],+) {+ let Some(ref emitter) = state.ingestion_warning_emitter else {+ return;+ };++ // (count, identifiers-of-the-single-event-if-unique) per warning type.+ type DropGroup<'a> = (u64, Option<(&'a str, Uuid)>);+ let mut grouped: HashMap<WarningType, DropGroup> = HashMap::new();+ for ev in events {+ if ev.result != EventResult::Drop {+ continue;+ }+ let Some(warning) = ev.details.and_then(WarningType::from_tag) else {+ continue;+ };+ let entry = grouped+ .entry(warning)+ .or_insert((0, Some((ev.event.distinct_id.as_str(), ev.uuid))));+ entry.0 += 1;+ if entry.0 > 1 {+ entry.1 = None;+ }+ }++ for (warning, (count, single_event)) in grouped {+ let mut details = warning_context_details(context);+ if let Some((distinct_id, uuid)) = single_event {+ // A public request can submit a `distinct_id` far larger than+ // CAPTURE_V1_DISTINCT_ID_MAX_SIZE (that oversized value is exactly+ // what triggers `distinct_id_too_large`), so bound what enters the+ // warning: a fixed-size prefix keeps it useful for debugging while+ // the length preserves how large the real value was.+ let char_count = distinct_id.chars().count();+ let prefix: String = distinct_id+ .chars()+ .take(CAPTURE_V1_DISTINCT_ID_MAX_SIZE)+ .collect();+ details.insert("distinctId".to_string(), serde_json::json!(prefix));+ if char_count > CAPTURE_V1_DISTINCT_ID_MAX_SIZE {+ details.insert(+ "distinctIdLength".to_string(),+ serde_json::json!(char_count),+ );+ }+ details.insert("eventUuid".to_string(), serde_json::json!(uuid.to_string()));+ }+ emitter.emit(+ context.api_token.clone(),+ CAPTURE_V1_ANALYTICS,+ warning,+ details,+ count,+ );+ }+}+/// Records a whole-batch validation abort. These errors reject the batch as a/// unit, so every event in it is dropped — but the request only ever ticks one/// `capture_v1_analytics_error`, leaving the event count invisible. Charge the@@ -3159,6 +3279,234 @@ mod tests {}}+ // =========================================================================+ // Ingestion warning emission — process_batch with a CollectingEmitter+ // =========================================================================++ use common_ingestion_warnings::test_support::CollectingEmitter;+ use common_ingestion_warnings::WarningType;++ /// State wired to a `CollectingEmitter` so tests can assert exactly what+ /// `process_batch` emitted (type, count, details) without any Kafka.+ fn state_with_warning_collector() -> (router::State, Arc<CollectingEmitter>) {+ let collector = Arc::new(CollectingEmitter::new());+ let state = TestStateBuilder::new()+ .with_ingestion_warning_emitter(collector.clone())+ .build()+ .state;+ (state, collector)+ }++ #[tokio::test]+ async fn warnings_same_tag_drops_dedupe_to_one_emit_without_identifiers() {+ let (state, collector) = state_with_warning_collector();+ let mut ctx = test_utils::test_analytics_context();+ let bad = || Event {+ event: String::new(),+ ..valid_event()+ };+ let batch = valid_batch(vec![bad(), bad(), bad(), valid_event()]);++ process_batch(&state, &mut ctx, batch).await.unwrap();++ let emitted = collector.emitted();+ assert_eq!(emitted.len(), 1, "same-tag drops must dedupe to one emit");+ assert_eq!(emitted[0].warning, WarningType::MissingEventName);+ assert_eq!(emitted[0].count, 3);+ assert_eq!(emitted[0].token, "phc_test_token");+ // With multiple affected events, per-event identifiers are ambiguous+ // and must be omitted; request-level context is always present.+ assert!(!emitted[0].extra_details.contains_key("distinctId"));+ assert!(!emitted[0].extra_details.contains_key("eventUuid"));+ assert_eq!(+ emitted[0].extra_details.get("path"),+ Some(&serde_json::json!(CAPTURE_V1_PATH))+ );+ }++ #[tokio::test]+ async fn warnings_single_drop_includes_event_identifiers_and_sdk_info() {+ let (state, collector) = state_with_warning_collector();+ let mut ctx = test_utils::test_analytics_context();+ let bad = Event {+ event: String::new(),+ distinct_id: "user-warned".to_string(),+ ..valid_event()+ };+ let bad_uuid = bad.uuid.clone();+ let batch = valid_batch(vec![bad, valid_event()]);++ process_batch(&state, &mut ctx, batch).await.unwrap();++ let emitted = collector.emitted();+ assert_eq!(emitted.len(), 1);+ assert_eq!(emitted[0].count, 1);+ assert_eq!(+ emitted[0].extra_details.get("distinctId"),+ Some(&serde_json::json!("user-warned"))+ );+ assert_eq!(+ emitted[0].extra_details.get("eventUuid"),+ Some(&serde_json::json!(bad_uuid))+ );+ // sdk_info "posthog-rs/1.0.0" from test_context splits into lib fields.+ assert_eq!(+ emitted[0].extra_details.get("lib"),+ Some(&serde_json::json!("posthog-rs"))+ );+ assert_eq!(+ emitted[0].extra_details.get("libVersion"),+ Some(&serde_json::json!("1.0.0"))+ );+ }++ /// A public request can submit a `distinct_id` far larger than+ /// CAPTURE_V1_DISTINCT_ID_MAX_SIZE — that's exactly what makes it+ /// `distinct_id_too_large`. The warning must never copy the raw oversized+ /// value into `details`: it stores a bounded prefix plus the true length+ /// instead, so a flood of such requests can't inflate warning payload+ /// size proportional to attacker-controlled input.+ #[tokio::test]+ async fn warnings_oversized_distinct_id_is_truncated_in_details() {+ let (state, collector) = state_with_warning_collector();+ let mut ctx = test_utils::test_analytics_context();+ let huge_id = "d".repeat(CAPTURE_V1_DISTINCT_ID_MAX_SIZE * 100);+ let bad = Event {+ distinct_id: huge_id.clone(),+ ..valid_event()+ };+ let batch = valid_batch(vec![bad]);++ process_batch(&state, &mut ctx, batch).await.unwrap();++ let emitted = collector.emitted();+ assert_eq!(emitted.len(), 1);+ assert_eq!(emitted[0].warning, WarningType::DistinctIdTooLarge);+ let stored = emitted[0]+ .extra_details+ .get("distinctId")+ .and_then(|v| v.as_str())+ .expect("distinctId must be present");+ assert_eq!(+ stored.len(),+ CAPTURE_V1_DISTINCT_ID_MAX_SIZE,+ "stored distinctId must be bounded regardless of the offending value's size"+ );+ assert_eq!(+ emitted[0].extra_details.get("distinctIdLength"),+ Some(&serde_json::json!(huge_id.chars().count())),+ "the true length must still be observable for debugging"+ );+ }++ #[tokio::test]+ async fn warnings_mixed_tags_emit_one_message_per_tag() {+ let (state, collector) = state_with_warning_collector();+ let mut ctx = test_utils::test_analytics_context();+ let missing_name = || Event {+ event: String::new(),+ ..valid_event()+ };+ let oversized_id = Event {+ distinct_id: "d".repeat(CAPTURE_V1_DISTINCT_ID_MAX_SIZE + 1),+ ..valid_event()+ };+ let batch = valid_batch(vec![missing_name(), missing_name(), oversized_id]);++ process_batch(&state, &mut ctx, batch).await.unwrap();++ let counts: HashMap<WarningType, u64> = collector+ .emitted()+ .into_iter()+ .map(|w| (w.warning, w.count))+ .collect();+ assert_eq!(+ counts,+ HashMap::from([+ (WarningType::MissingEventName, 2),+ (WarningType::DistinctIdTooLarge, 1),+ ])+ );+ }++ /// `dropped_performance_event` is legacy cruft deliberately absent from the+ /// `WarningType::from_tag` allowlist — this locks in that it never emits.+ #[tokio::test]+ async fn warnings_excluded_tag_dropped_performance_event_emits_nothing() {+ let (state, collector) = state_with_warning_collector();+ let mut ctx = test_utils::test_analytics_context();+ let perf = Event {+ event: "$performance_event".to_string(),+ ..valid_event()+ };+ let batch = valid_batch(vec![perf, valid_event()]);++ process_batch(&state, &mut ctx, batch).await.unwrap();++ assert!(collector.emitted().is_empty());+ }++ #[tokio::test]+ async fn warnings_fully_valid_batch_emits_nothing() {+ let (state, collector) = state_with_warning_collector();+ let mut ctx = test_utils::test_analytics_context();+ let batch = valid_batch(vec![valid_event(), valid_event()]);++ process_batch(&state, &mut ctx, batch).await.unwrap();++ assert!(collector.emitted().is_empty());+ }++ #[tokio::test]+ async fn warnings_batch_abort_emits_once_with_full_batch_count() {+ let (state, collector) = state_with_warning_collector();+ let mut ctx = test_utils::test_analytics_context();+ let shared_uuid = Uuid::new_v4().to_string();+ let dup_a = Event {+ uuid: shared_uuid.clone(),+ ..valid_event()+ };+ let dup_b = Event {+ uuid: shared_uuid,+ distinct_id: "someone-else".to_string(),+ ..valid_event()+ };+ let batch = valid_batch(vec![dup_a, dup_b, valid_event()]);++ let err = process_batch(&state, &mut ctx, batch).await.unwrap_err();+ assert!(matches!(err, Error::DuplicateEventUuid(_)));++ let emitted = collector.emitted();+ assert_eq!(emitted.len(), 1);+ assert_eq!(emitted[0].warning, WarningType::DuplicateEventUuid);+ assert_eq!(+ emitted[0].count, 3,+ "a batch abort charges the whole batch length"+ );+ assert!(+ !emitted[0].extra_details.contains_key("distinctId"),+ "no per-event identifiers exist for a whole-batch abort"+ );+ }++ #[tokio::test]+ async fn warnings_empty_batch_abort_charges_count_one_not_zero() {+ let (state, collector) = state_with_warning_collector();+ let mut ctx = test_utils::test_analytics_context();+ let batch = valid_batch(vec![]);++ let err = process_batch(&state, &mut ctx, batch).await.unwrap_err();+ assert!(matches!(err, Error::EmptyBatch));++ let emitted = collector.emitted();+ assert_eq!(emitted.len(), 1);+ assert_eq!(emitted[0].warning, WarningType::EmptyBatch);+ assert_eq!(+ emitted[0].count, 1,+ "an empty-batch abort is one occurrence, never zero"+ );+ }+// =========================================================================// Integration-style tests: publish → merge → response flow// =========================================================================diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex bbb11ae400d3..21a11feb969c 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -253,6 +253,9 @@ mod tests {capture_v1_max_compressed_body_bytes: 10 * 1024 * 1024,capture_v1_max_decompressed_body_bytes: 50 * 1024 * 1024,capture_v1_scatter_gather_min_batch: 8,+ capture_ingestion_warnings_enabled: false,+ capture_ingestion_warnings_kafka_queue_mib: 16,+ capture_ingestion_warnings_kafka_message_max_bytes: 1048576,}}diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex c2e2e5e92466..8274fa4f1266 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -676,6 +676,7 @@ pub struct TestStateBuilder {global_rate_limiter: Option<Arc<GlobalRateLimiter>>,mock_producer: Option<Arc<MockProducer>>,ai_gateway_signing_secret: Option<String>,+ ingestion_warning_emitter: Option<Arc<dyn common_ingestion_warnings::WarningEmitter>>,}impl Default for TestStateBuilder {@@ -694,6 +695,7 @@ impl TestStateBuilder {global_rate_limiter: None,mock_producer: None,ai_gateway_signing_secret: None,+ ingestion_warning_emitter: None,}}@@ -742,6 +744,15 @@ impl TestStateBuilder {self}+ /// Supply an ingestion warnings emitter (e.g. a `CollectingEmitter`).+ pub fn with_ingestion_warning_emitter(+ mut self,+ emitter: Arc<dyn common_ingestion_warnings::WarningEmitter>,+ ) -> Self {+ self.ingestion_warning_emitter = Some(emitter);+ self+ }+pub fn build(self) -> TestState {let mut manager = lifecycle::Manager::builder("test_state").with_trap_signals(false)@@ -846,6 +857,7 @@ impl TestStateBuilder {v1_sink_router: Some(Arc::new(v1_router)),capture_v1_scatter_gather_min_batch: 8,ai_gateway_signing_secret: self.ai_gateway_signing_secret,+ ingestion_warning_emitter: self.ingestion_warning_emitter,};TestState {diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rsindex 49b0966f1952..0a08aa035ccc 100644--- a/rust/capture/tests/common/integration_utils.rs+++ b/rust/capture/tests/common/integration_utils.rs@@ -1111,6 +1111,7 @@ fn setup_capture_router(unit: &TestCase) -> (Router, MemorySink) {None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter),sink,)diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 272a3b91b8c5..1affadc7e618 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -169,6 +169,9 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {capture_v1_max_compressed_body_bytes: 10 * 1024 * 1024,capture_v1_max_decompressed_body_bytes: 50 * 1024 * 1024,capture_v1_scatter_gather_min_batch: 8,+ capture_ingestion_warnings_enabled: false,+ capture_ingestion_warnings_kafka_queue_mib: 16,+ capture_ingestion_warnings_kafka_message_max_bytes: 1048576,});/// Build the per-sink env snapshot the v1 sink loader expects, with everydiff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rsindex 69631e65d1ad..009088880fd7 100644--- a/rust/capture/tests/integration_ai_endpoint.rs+++ b/rust/capture/tests/integration_ai_endpoint.rs@@ -197,6 +197,7 @@ fn setup_ai_test_router() -> Router {None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter)}@@ -1660,6 +1661,7 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -2575,6 +2577,7 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (RoutNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -2785,6 +2788,7 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, CapturinNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -2940,6 +2944,7 @@ fn setup_ai_test_router_with_overflow_limiter(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -3079,6 +3084,7 @@ fn ai_router(None,8,Some(GW_SECRET.to_string()),+ None,);(router, sink_clone)}diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rsindex 80c7d16a1258..99bcad77a093 100644--- a/rust/capture/tests/integration_ai_restrictions.rs+++ b/rust/capture/tests/integration_ai_restrictions.rs@@ -195,6 +195,7 @@ async fn setup_ai_router_with_restriction(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -514,6 +515,7 @@ async fn setup_ai_router_with_redirect_to_topic(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -590,6 +592,7 @@ async fn setup_ai_router_with_force_overflow_and_limiter(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(router, sink_clone)diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rsindex f113ccd10ad4..3b453a5d338a 100644--- a/rust/capture/tests/integration_analytics_restrictions.rs+++ b/rust/capture/tests/integration_analytics_restrictions.rs@@ -129,6 +129,7 @@ async fn setup_analytics_router_with_restriction(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -473,6 +474,7 @@ async fn setup_analytics_router_with_redirect_to_topic(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(router, sink_clone)diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rsindex 6d581e2150c5..fa75fa33f56b 100644--- a/rust/capture/tests/integration_otel_endpoint.rs+++ b/rust/capture/tests/integration_otel_endpoint.rs@@ -187,6 +187,7 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOptionNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);TestClient::new(app)diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rsindex 4d3be7b2026b..ad6c56cbc56b 100644--- a/rust/capture/tests/integration_replay_restrictions.rs+++ b/rust/capture/tests/integration_replay_restrictions.rs@@ -131,6 +131,7 @@ async fn setup_recordings_router_with_restriction(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(router, sink_clone)@@ -501,6 +502,7 @@ async fn setup_recordings_router_with_redirect_to_topic(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(router, sink_clone)diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rsindex 4a044c2223e6..2cae179075a7 100644--- a/rust/capture/tests/quota_limiters.rs+++ b/rust/capture/tests/quota_limiters.rs@@ -153,6 +153,7 @@ async fn setup_router_with_limits(None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);(app, sink)@@ -1205,6 +1206,7 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);let client = TestClient::new(app);@@ -1295,6 +1297,7 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);let client = TestClient::new(app);@@ -1389,6 +1392,7 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);let client = TestClient::new(app);@@ -1820,6 +1824,7 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {None, // v1_sink_router8, // capture_v1_scatter_gather_min_batchNone, // ai_gateway_signing_secret+ None, // ingestion_warning_emitter);let client = TestClient::new(app);diff --git a/rust/cohort-event-shuffler/src/config.rs b/rust/cohort-event-shuffler/src/config.rsindex 74f256e3f993..c73d7ecc9dfc 100644--- a/rust/cohort-event-shuffler/src/config.rs+++ b/rust/cohort-event-shuffler/src/config.rs@@ -176,6 +176,8 @@ impl Config {kafka_producer_topic_metadata_refresh_interval_ms: None,kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,}}diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rsindex 64c86a2ccd23..996ac8efe5de 100644--- a/rust/cohort-stream-processor/src/config.rs+++ b/rust/cohort-stream-processor/src/config.rs@@ -804,6 +804,8 @@ impl Config {kafka_producer_topic_metadata_refresh_interval_ms: None,kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,}}diff --git a/rust/cohort-stream-processor/tests/cascade_consumer.rs b/rust/cohort-stream-processor/tests/cascade_consumer.rsindex b1ba0122abf4..de11facbf117 100644--- a/rust/cohort-stream-processor/tests/cascade_consumer.rs+++ b/rust/cohort-stream-processor/tests/cascade_consumer.rs@@ -185,6 +185,8 @@ fn producer_kafka_config() -> KafkaConfig {kafka_producer_topic_metadata_refresh_interval_ms: None,kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,}}diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rsindex 8c9b90ab7de8..747fa9355712 100644--- a/rust/cohort-stream-processor/tests/events_consumer.rs+++ b/rust/cohort-stream-processor/tests/events_consumer.rs@@ -315,6 +315,8 @@ fn shadow_kafka_config() -> KafkaConfig {kafka_producer_topic_metadata_refresh_interval_ms: None,kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,}}diff --git a/rust/cohort-stream-processor/tests/merge_consumer.rs b/rust/cohort-stream-processor/tests/merge_consumer.rsindex 512786350ca4..9848a990690d 100644--- a/rust/cohort-stream-processor/tests/merge_consumer.rs+++ b/rust/cohort-stream-processor/tests/merge_consumer.rs@@ -223,6 +223,8 @@ fn producer_kafka_config() -> KafkaConfig {kafka_producer_topic_metadata_refresh_interval_ms: None,kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,}}diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rsindex 4ea627c1a0c9..66f9aa004a7c 100644--- a/rust/cohort-stream-processor/tests/merge_durability.rs+++ b/rust/cohort-stream-processor/tests/merge_durability.rs@@ -236,6 +236,8 @@ fn producer_kafka_config() -> KafkaConfig {kafka_producer_topic_metadata_refresh_interval_ms: None,kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,}}diff --git a/rust/common/ingestion_warnings/Cargo.toml b/rust/common/ingestion_warnings/Cargo.tomlnew file mode 100644index 000000000000..e0d338f07b54--- /dev/null+++ b/rust/common/ingestion_warnings/Cargo.toml@@ -0,0 +1,27 @@+[package]+name = "common-ingestion-warnings"+version = "0.1.0"+edition = "2021"++[lints]+workspace = true++[build-dependencies]+# Parses capture_warning_types.generated.json (mirrored from the Node.js registry)+# to codegen the WarningType enum. See build.rs.+serde_json = { workspace = true }++[dependencies]+chrono = { workspace = true }+common-kafka = { path = "../kafka" }+common-types = { path = "../types" }+governor = { workspace = true }+metrics = { workspace = true }+rdkafka = { workspace = true }+serde_json = { workspace = true }+tracing = { workspace = true }+uuid = { workspace = true }++[dev-dependencies]+common-liveness = { path = "../liveness" }+rstest = "0.26"diff --git a/rust/common/ingestion_warnings/build.rs b/rust/common/ingestion_warnings/build.rsnew file mode 100644index 000000000000..ef82818a1015--- /dev/null+++ b/rust/common/ingestion_warnings/build.rs@@ -0,0 +1,109 @@+//! Codegen for the `WarningType` enum from `capture_warning_types.generated.json`.+//!+//! That JSON is mirrored from the Node.js registry (the single source of truth,+//! `nodejs/src/ingestion/common/ingestion-warning-types.ts`) by+//! `pnpm --filter=@posthog/nodejs gen:ingestion-warning-types`. Generating the enum from the+//! committed artifact keeps Rust's warning types from drifting out of the Node.js registry while+//! respecting the isolated Rust build context (the artifact lives inside this crate, so no+//! cross-workspace file access is needed at build time). The hand-written `from_tag` mapping and+//! the round-trip test in `registry.rs` force a human to wire any newly generated variant.++use std::env;+use std::fs;+use std::path::Path;++fn main() {+ let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo");+ let json_path = Path::new(&manifest_dir).join("capture_warning_types.generated.json");+ // Rerun only when the mirrored artifact changes.+ println!("cargo:rerun-if-changed={}", json_path.display());++ let raw = fs::read_to_string(&json_path)+ .unwrap_or_else(|e| panic!("read {}: {e}", json_path.display()));+ let parsed: serde_json::Value =+ serde_json::from_str(&raw).unwrap_or_else(|e| panic!("parse {}: {e}", json_path.display()));++ let tags: Vec<String> = parsed+ .get("types")+ .and_then(|t| t.as_array())+ .unwrap_or_else(|| panic!("`types` array missing in {}", json_path.display()))+ .iter()+ .map(|v| {+ v.as_str()+ .unwrap_or_else(|| panic!("non-string entry in `types` in {}", json_path.display()))+ .to_string()+ })+ .collect();++ assert!(+ !tags.is_empty(),+ "capture warning types artifact {} is empty",+ json_path.display()+ );++ let variants: Vec<String> = tags.iter().map(|tag| to_pascal_case(tag)).collect();++ let mut code = String::new();+ code.push_str(+ "// @generated by build.rs from capture_warning_types.generated.json — do not edit.\n",+ );+ code.push_str("/// A warning type known to the v2 ingestion warnings pipeline.\n");+ code.push_str("///\n");+ code.push_str(+ "/// Generated from the Node.js registry (`captureProduced` types). Every variant's\n",+ );+ code.push_str(+ "/// `as_str()` doubles as the produced message `type` field and the `type` metric\n",+ );+ code.push_str("/// label, so the values must stay stable.\n");+ code.push_str("#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n");+ code.push_str("pub enum WarningType {\n");+ for variant in &variants {+ code.push_str(&format!(" {variant},\n"));+ }+ code.push_str("}\n\n");++ code.push_str("impl WarningType {\n");+ code.push_str(" /// All registered warning types, for exhaustive tests.\n");+ code.push_str(&format!(+ " pub const ALL: [WarningType; {}] = [\n",+ variants.len()+ ));+ for variant in &variants {+ code.push_str(&format!(" WarningType::{variant},\n"));+ }+ code.push_str(" ];\n\n");++ code.push_str(+ " /// The message/metric `type` string. Matches the originating error tag 1:1.\n",+ );+ code.push_str(" pub const fn as_str(self) -> &'static str {\n");+ code.push_str(" match self {\n");+ for (variant, tag) in variants.iter().zip(tags.iter()) {+ code.push_str(&format!(+ " WarningType::{variant} => \"{tag}\",\n"+ ));+ }+ code.push_str(" }\n");+ code.push_str(" }\n");+ code.push_str("}\n");++ let out_dir = env::var("OUT_DIR").expect("OUT_DIR is set by cargo");+ let dest = Path::new(&out_dir).join("warning_types.rs");+ fs::write(&dest, code).unwrap_or_else(|e| panic!("write {}: {e}", dest.display()));+}++/// `missing_event_name` -> `MissingEventName`.+fn to_pascal_case(snake: &str) -> String {+ snake+ .split('_')+ .filter(|part| !part.is_empty())+ .map(|part| {+ let mut chars = part.chars();+ match chars.next() {+ Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),+ None => String::new(),+ }+ })+ .collect()+}diff --git a/rust/common/ingestion_warnings/capture_warning_types.generated.json b/rust/common/ingestion_warnings/capture_warning_types.generated.jsonnew file mode 100644index 000000000000..fbcb37ae1534--- /dev/null+++ b/rust/common/ingestion_warnings/capture_warning_types.generated.json@@ -0,0 +1,17 @@+{+ "_comment": "GENERATED from INGESTION_WARNING_TYPES (captureProduced) in nodejs/src/ingestion/common/ingestion-warning-types.ts via `pnpm --filter=@posthog/nodejs gen:ingestion-warning-types`. Do not edit by hand; rust/common/ingestion_warnings/build.rs codegens the WarningType enum from this file.",+ "types": [+ "distinct_id_too_large",+ "duplicate_event_uuid",+ "empty_batch",+ "event_name_too_long",+ "invalid_batch",+ "invalid_event_timestamp",+ "invalid_event_uuid",+ "invalid_options",+ "malformed_event_properties",+ "missing_distinct_id",+ "missing_event_name",+ "missing_event_uuid"+ ]+}diff --git a/rust/common/ingestion_warnings/src/lib.rs b/rust/common/ingestion_warnings/src/lib.rsnew file mode 100644index 000000000000..826a8d8434d8--- /dev/null+++ b/rust/common/ingestion_warnings/src/lib.rs@@ -0,0 +1,364 @@+//! Best-effort, fire-and-forget emission of ingestion warnings to Kafka.+//!+//! Producers (capture today; other Rust services later, see [`WarningSource`])+//! call [`WarningEmitter::emit`] with the offending event's API token, a+//! source, a registered [`WarningType`], and caller context; the emitter+//! throttles per `(token, type)`, builds a `$$client_ingestion_warning`+//! [`common_types::CapturedEvent`] envelope, and enqueues it to a producer+//! without ever awaiting delivery. Everything fails open: a throttled,+//! unserializable, or unenqueueable warning is counted and dropped — the+//! caller's hot path is never blocked or failed.+//!+//! The producer is a `common_kafka` `ThreadedProducer` (built by+//! [`common_kafka::kafka_producer::create_threaded_kafka_producer`]) rather+//! than a bespoke client: callers supply their own dedicated, warnings-tuned+//! [`common_kafka::config::KafkaConfig`] (fire-and-forget acks/retries, a+//! small queue) so warnings never share tuning or a connection with a+//! caller's main event producer. Delivery reports are observed on the+//! producer's own poll thread via [`observe_delivery`] (no per-message task);+//! `emit` attaches the warning type/source as the delivery opaque so the+//! async `delivered`/`delivery_failed` metric is attributed correctly.+//!+//! The envelope lands on the `client_ingestion_warning` topic, where the+//! Node.js `clientwarnings` consumer resolves the token to a `team_id` and+//! writes the v2 row. That keeps every Rust producer database-free and+//! identical; see [`serializer`] and+//! `nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.ts`.++pub mod registry;+pub mod serializer;+pub mod test_support;+pub mod throttle;++use std::time::Duration;++use chrono::Utc;+use common_kafka::kafka_producer::ThreadedKafkaContext;+use metrics::{counter, gauge};+use rdkafka::error::KafkaError;+use rdkafka::message::OwnedHeaders;+use rdkafka::producer::{BaseRecord, DeliveryResult, Producer, ThreadedProducer};+use rdkafka::types::RDKafkaErrorCode;+use serde_json::{Map, Value};+use tracing::warn;++pub use registry::WarningType;+pub use throttle::{ThrottleDecision, WarningThrottle};++/// Counter of emission attempts: labels `type` (warning type), `source`+/// (producing service, matches the message's `source` field), `path`+/// (metric-only, finer-grained attribution within one service), and+/// `outcome`. Enqueue-time outcomes: `emitted | throttled |+/// cardinality_capped | queue_full | serialize_error | enqueue_error`.+/// Delivery-time outcomes (reported asynchronously for each `emitted`+/// message): `delivered | delivery_failed`.+pub const INGESTION_WARNINGS_TOTAL: &str = "ingestion_warnings_total";++/// Gauge of `(token, type)` keys currently tracked by the throttle, updated+/// on each sweep. The early-warning signal for the cardinality cap.+pub const INGESTION_WARNINGS_THROTTLE_KEYS: &str = "ingestion_warnings_throttle_keys";++/// Identifies which service — and which code path within it — produced a+/// warning.+///+/// `service` is the stable v2 message `source` field (also used as the+/// `source` metric label) and must be a value a reader of the ClickHouse+/// table can rely on; `path` is metric-only, for attributing volume to a+/// specific emit site within one service (e.g. `v1_analytics` vs `legacy`)+/// without inflating the message schema.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct WarningSource {+ pub service: &'static str,+ pub path: &'static str,+}++/// Capture's v1 analytics validation pipeline (`rust/capture/src/v1/analytics`).+pub const CAPTURE_V1_ANALYTICS: WarningSource = WarningSource {+ service: serializer::SOURCE_CAPTURE,+ path: "v1_analytics",+};++/// Sink-agnostic emitter seam. The Kafka implementation is+/// [`KafkaWarningEmitter`]; tests use+/// [`test_support::CollectingEmitter`].+pub trait WarningEmitter: Send + Sync {+ /// Emit one (possibly batch-deduped) warning. Synchronous and non-blocking;+ /// implementations must swallow all failures.+ ///+ /// `token` is the offending event's API token; the consumer resolves it to+ /// a team and it also scopes the throttle, so one token's warnings never+ /// starve another's budget. `source` identifies the producing service and+ /// code path (see [`WarningSource`]). `extra_details` carries caller+ /// context with camelCase keys (`distinctId`, `eventUuid`, `lib`, `path`,+ /// ...); `count` is the number of occurrences this message represents+ /// after per-batch dedup.+ fn emit(+ &self,+ token: String,+ source: WarningSource,+ warning: WarningType,+ extra_details: Map<String, Value>,+ count: u64,+ );++ /// Advisory drain of any buffered messages, e.g. at graceful shutdown.+ fn flush(&self, timeout: Duration);+}++/// Production emitter: per-(token, type) throttle in front of a+/// `common_kafka` `ThreadedProducer`. Callers build the producer themselves+/// (via `common_kafka::kafka_producer::create_threaded_kafka_producer` with a+/// dedicated, fire-and-forget-tuned `KafkaConfig` and [`observe_delivery`] as+/// the delivery callback) and hand it in — this type never constructs its own+/// client. The producer's opaque is [`WarningDelivery`], so each message's+/// delivery report carries the type/source needed to label the async outcome+/// metric.+pub struct KafkaWarningEmitter {+ producer: ThreadedProducer<ThreadedKafkaContext<WarningDelivery>>,+ topic: String,+ throttle: WarningThrottle,+}++impl KafkaWarningEmitter {+ pub fn new(+ producer: ThreadedProducer<ThreadedKafkaContext<WarningDelivery>>,+ topic: impl Into<String>,+ ) -> Self {+ Self {+ producer,+ topic: topic.into(),+ throttle: WarningThrottle::default(),+ }+ }++ /// Evict fully-refilled throttle keys to bound memory and publish the+ /// tracked-key gauge. Call periodically from a maintenance task.+ pub fn sweep_throttle(&self) {+ self.throttle.sweep();+ gauge!(INGESTION_WARNINGS_THROTTLE_KEYS).set(self.throttle.tracked_keys() as f64);+ }+}++impl WarningEmitter for KafkaWarningEmitter {+ fn emit(+ &self,+ token: String,+ source: WarningSource,+ warning: WarningType,+ extra_details: Map<String, Value>,+ count: u64,+ ) {+ // Key by token so one team's warnings stay partition-local and+ // throttle-independent from every other team's, matching the Node.js+ // consumer's per-team keying downstream.+ match self.throttle.check(&token, warning) {+ ThrottleDecision::Emit => {}+ ThrottleDecision::Throttled => {+ counter!(+ INGESTION_WARNINGS_TOTAL,+ "type" => warning.as_str(),+ "source" => source.service,+ "path" => source.path,+ "outcome" => "throttled",+ )+ .increment(1);+ return;+ }+ ThrottleDecision::CardinalityCapped => {+ counter!(+ INGESTION_WARNINGS_TOTAL,+ "type" => warning.as_str(),+ "source" => source.service,+ "path" => source.path,+ "outcome" => "cardinality_capped",+ )+ .increment(1);+ return;+ }+ }++ let serialized = serializer::build_warning_event(+ &token,+ source,+ warning,+ extra_details,+ count,+ Utc::now(),+ )+ .and_then(|event| serde_json::to_vec(&event).map(|payload| (payload, event.to_headers())));++ let (payload, headers) = match serialized {+ Ok((payload, headers)) => (payload, OwnedHeaders::from(headers)),+ Err(err) => {+ counter!(+ INGESTION_WARNINGS_TOTAL,+ "type" => warning.as_str(),+ "source" => source.service,+ "path" => source.path,+ "outcome" => "serialize_error",+ )+ .increment(1);+ warn!(warning_type = warning.as_str(), source = source.service, error = %err,+ "failed to serialize ingestion warning");+ return;+ }+ };++ let record =+ BaseRecord::with_opaque_to(&self.topic, Box::new(WarningDelivery { warning, source }))+ .key(&token)+ .headers(headers)+ .payload(&payload);++ // `send` enqueues and returns immediately; the delivery report is+ // handled off the hot path by the producer's poll thread, which calls+ // [`observe_delivery`] via the threaded context. This is the+ // fire-and-forget shape, not `common_kafka::send_*`, which awaits+ // delivery inline.+ match self.producer.send(record) {+ Ok(()) => {+ counter!(+ INGESTION_WARNINGS_TOTAL,+ "type" => warning.as_str(),+ "source" => source.service,+ "path" => source.path,+ "outcome" => "emitted",+ )+ .increment(1);+ }+ Err((KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull), _record)) => {+ counter!(+ INGESTION_WARNINGS_TOTAL,+ "type" => warning.as_str(),+ "source" => source.service,+ "path" => source.path,+ "outcome" => "queue_full",+ )+ .increment(1);+ }+ Err((err, _record)) => {+ counter!(+ INGESTION_WARNINGS_TOTAL,+ "type" => warning.as_str(),+ "source" => source.service,+ "path" => source.path,+ "outcome" => "enqueue_error",+ )+ .increment(1);+ warn!(warning_type = warning.as_str(), source = source.service, error = %err,+ "failed to enqueue ingestion warning");+ }+ }+ }++ fn flush(&self, timeout: Duration) {+ // Advisory only (shutdown path); errors are not actionable here.+ drop(self.producer.flush(timeout));+ }+}++/// Per-message opaque carried through the threaded producer to its delivery+/// callback, so each report can be attributed to the warning type and source+/// that produced it. Passed via `BaseRecord::delivery_opaque` at `emit` and+/// handed back to [`observe_delivery`] on the producer's poll thread.+#[derive(Debug, Clone, Copy)]+pub struct WarningDelivery {+ pub warning: WarningType,+ pub source: WarningSource,+}++/// Delivery-report callback for the warnings `ThreadedProducer`. Runs on+/// rdkafka's poll thread for every produced message and ticks the+/// `delivered`/`delivery_failed` outcome — the async half of the `emitted`+/// counter, which alone only proves the message entered the local queue.+/// Without this, a broken topic or broker at rollout looks healthy while+/// nothing lands. Metric-only (no per-message log) since a broken topic at+/// rollout would otherwise flood logs at post-throttle volume.+pub fn observe_delivery(result: &DeliveryResult, delivery: WarningDelivery) {+ let outcome = match result {+ Ok(_) => "delivered",+ Err(_) => "delivery_failed",+ };+ counter!(+ INGESTION_WARNINGS_TOTAL,+ "type" => delivery.warning.as_str(),+ "source" => delivery.source.service,+ "path" => delivery.source.path,+ "outcome" => outcome,+ )+ .increment(1);+}++#[cfg(test)]+mod tests {+ use common_liveness::SyncLivenessReporter;+ use rdkafka::ClientConfig;++ use super::*;++ /// No-op liveness sink: these tests build a producer directly (not via+ /// `create_kafka_producer`) specifically to skip its 15s broker-metadata+ /// ping, so there is no real health signal to report.+ #[derive(Clone, Copy)]+ struct AlwaysHealthy;++ impl SyncLivenessReporter for AlwaysHealthy {+ fn report_healthy(&self) {}+ fn report_unhealthy(&self) {}+ }++ /// Build a threaded producer against an unreachable broker (TEST-NET-1)+ /// without `create_threaded_kafka_producer`'s startup metadata fetch, so+ /// tests stay fast and offline while still exercising the exact+ /// `ThreadedProducer<ThreadedKafkaContext<WarningDelivery>>` type+ /// `KafkaWarningEmitter` holds in production. `observe_delivery` is wired+ /// as the callback, matching the production path.+ fn unreachable_producer(+ message_timeout_ms: u32,+ linger_ms: u32,+ ) -> ThreadedProducer<ThreadedKafkaContext<WarningDelivery>> {+ ClientConfig::new()+ .set("bootstrap.servers", "192.0.2.1:9092")+ .set("message.timeout.ms", message_timeout_ms.to_string())+ .set("linger.ms", linger_ms.to_string())+ .set("queue.buffering.max.messages", "10")+ .set("retries", "0")+ .create_with_context(ThreadedKafkaContext::new(AlwaysHealthy, observe_delivery))+ .expect("client config is valid, so creation cannot fail without a broker round-trip")+ }++ #[test]+ fn kafka_emitter_throttles_repeats_and_never_blocks() {+ // Unreachable broker (TEST-NET-1): emit must return instantly whether+ // the message is enqueued or throttled.+ let emitter =+ KafkaWarningEmitter::new(unreachable_producer(500, 5), "client_ingestion_warning");++ let start = std::time::Instant::now();+ emitter.emit(+ "tok".to_string(),+ CAPTURE_V1_ANALYTICS,+ WarningType::MissingEventName,+ Map::new(),+ 2,+ );+ emitter.emit(+ "tok".to_string(),+ CAPTURE_V1_ANALYTICS,+ WarningType::MissingEventName,+ Map::new(),+ 1,+ );+ emitter.emit(+ "tok".to_string(),+ CAPTURE_V1_ANALYTICS,+ WarningType::EmptyBatch,+ Map::new(),+ 5,+ );+ assert!(+ start.elapsed() < std::time::Duration::from_millis(500),+ "emit must be fire-and-forget"+ );+ }+}diff --git a/rust/common/ingestion_warnings/src/registry.rs b/rust/common/ingestion_warnings/src/registry.rsnew file mode 100644index 000000000000..440a94b601a5--- /dev/null+++ b/rust/common/ingestion_warnings/src/registry.rs@@ -0,0 +1,93 @@+//! Registry of ingestion warning types emitted by Rust services.+//!+//! The `WarningType` enum, its `ALL` list, and `as_str()` are generated at build+//! time (see `build.rs`) from `capture_warning_types.generated.json`, which is+//! mirrored from the Node.js registry — the single source of truth for the warning+//! taxonomy (`nodejs/src/ingestion/common/ingestion-warning-types.ts`). Category and+//! severity are resolved Node-side at serialization time and are not represented here.+//!+//! `from_tag` is a hand-written allowlist mapping capture error tags to warning+//! types: only tags registered here ever produce a warning. Unknown or deliberately+//! excluded tags (auth/transport/server errors, intentional drops like+//! `dropped_performance_event`) map to `None` and emit nothing. The+//! `from_tag_round_trips_every_registered_type` test guarantees every generated+//! variant has a `from_tag` arm, so adding a capture type in Node.js forces the+//! matching Rust mapping here.++// Brings in `pub enum WarningType`, `WarningType::ALL`, and `WarningType::as_str`.+include!(concat!(env!("OUT_DIR"), "/warning_types.rs"));++impl WarningType {+ /// Map a capture error tag (`v1::Error::tag()` / per-event drop detail) to a+ /// registered warning type. Returns `None` for anything not on the allowlist —+ /// callers emit nothing in that case.+ pub fn from_tag(tag: &str) -> Option<Self> {+ match tag {+ "missing_event_name" => Some(Self::MissingEventName),+ "event_name_too_long" => Some(Self::EventNameTooLong),+ "missing_distinct_id" => Some(Self::MissingDistinctId),+ "distinct_id_too_large" => Some(Self::DistinctIdTooLarge),+ "invalid_event_timestamp" => Some(Self::InvalidEventTimestamp),+ "malformed_event_properties" => Some(Self::MalformedEventProperties),+ "invalid_options" => Some(Self::InvalidOptions),+ "empty_batch" => Some(Self::EmptyBatch),+ "invalid_batch" => Some(Self::InvalidBatch),+ "missing_event_uuid" => Some(Self::MissingEventUuid),+ "invalid_event_uuid" => Some(Self::InvalidEventUuid),+ "duplicate_event_uuid" => Some(Self::DuplicateEventUuid),+ _ => None,+ }+ }++ /// Pipeline step recorded in the details JSON (`pipelineStep`). Every registered+ /// capture type is a validation-stage drop, so they share this step.+ pub const fn pipeline_step(self) -> &'static str {+ "capture_validation"+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use rstest::rstest;++ #[test]+ fn from_tag_round_trips_every_registered_type() {+ // Guards the hand-written `from_tag` against the generated enum: a new+ // variant mirrored from Node.js without a matching `from_tag` arm fails here.+ for warning in WarningType::ALL {+ assert_eq!(+ WarningType::from_tag(warning.as_str()),+ Some(warning),+ "tag {} must round-trip",+ warning.as_str()+ );+ }+ }++ // Excluded on purpose: intentional drops, auth/transport/server errors, and+ // post-validation drops are not data-quality signals for the v2 surface.+ #[rstest]+ #[case::intentional_drop("dropped_performance_event")]+ #[case::auth("invalid_api_token")]+ #[case::auth_missing("missing_authorization")]+ #[case::transport("payload_too_large")]+ #[case::transport_decoding("request_decoding_error")]+ #[case::transport_parsing("request_parsing_error")]+ #[case::transport_encoding("unsupported_content_encoding")]+ #[case::timeout("request_timeout")]+ #[case::server("internal_error")]+ #[case::server_unavailable("service_unavailable")]+ #[case::billing("billing_limit_exceeded")]+ #[case::post_validation("event_restriction")]+ #[case::sink("rejected")]+ #[case::unknown("some_future_tag")]+ #[case::empty("")]+ fn from_tag_rejects_unregistered_tags(#[case] tag: &str) {+ assert_eq!(+ WarningType::from_tag(tag),+ None,+ "tag {tag:?} must not emit"+ );+ }+}diff --git a/rust/common/ingestion_warnings/src/serializer.rs b/rust/common/ingestion_warnings/src/serializer.rsnew file mode 100644index 000000000000..50ca7cc6f7fd--- /dev/null+++ b/rust/common/ingestion_warnings/src/serializer.rs@@ -0,0 +1,199 @@+//! Builds the ingestion-warning event envelope shared by every Rust producer.+//!+//! A warning is emitted as a synthetic `$$client_ingestion_warning`+//! [`CapturedEvent`] on the `client_ingestion_warning` topic — the same lane+//! the JS SDK's client warnings already use. The Node.js `clientwarnings`+//! consumer resolves the token to a `team_id`, reads the structured+//! type/details/source we stamp into the event properties, and writes the v2+//! ingestion-warning row (see+//! `nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.ts`).+//! Routing through that consumer means capture never needs database access or+//! token→team resolution, and every Rust service emits warnings identically.+//!+//! The envelope's top-level `distinct_id` is deliberately the token, never the+//! offending event's distinct_id: the consumer's metadata validation drops+//! events whose distinct_id exceeds the length limit, and `distinct_id_too_large`+//! is itself a warning type — reusing the offending id would silently discard+//! exactly those warnings. The real offending identifiers ride in `details`,+//! which the consumer does not length-validate.++use std::collections::HashMap;++use chrono::{DateTime, SecondsFormat, Utc};+use common_types::{CapturedEvent, RawEvent};+use serde_json::{json, Map, Value};+use uuid::Uuid;++use crate::registry::WarningType;+use crate::WarningSource;++/// `source` field value for warnings emitted by capture. Also used as+/// [`crate::CAPTURE_V1_ANALYTICS`]'s `service`.+pub const SOURCE_CAPTURE: &str = "capture";++/// Synthetic event name the Node.js `clientwarnings` consumer routes on.+pub const CLIENT_INGESTION_WARNING_EVENT: &str = "$$client_ingestion_warning";++/// Event-property keys the consumer reads to reconstruct the structured+/// warning (see `handle-client-ingestion-warning-step.ts`).+const PROP_TYPE: &str = "$$client_ingestion_warning_type";+const PROP_SOURCE: &str = "$$client_ingestion_warning_source";+const PROP_DETAILS: &str = "$$client_ingestion_warning_details";++/// Build the `$$client_ingestion_warning` envelope for one (batch-deduped)+/// warning.+///+/// `extra_details` carries caller context (camelCase keys such as `distinctId`,+/// `eventUuid`, `lib`, `path`). The builder injects `count` and `pipelineStep`;+/// `team_id`, `category`, and `severity` are the consumer's responsibility (it+/// owns the authoritative registry), so we never stamp them here.+pub fn build_warning_event(+ token: &str,+ source: WarningSource,+ warning: WarningType,+ mut extra_details: Map<String, Value>,+ count: u64,+ timestamp: DateTime<Utc>,+) -> Result<CapturedEvent, serde_json::Error> {+ extra_details.insert("count".to_string(), json!(count));+ // The consumer lifts `pipelineStep` out of details into the warning's+ // top-level pipeline_step column, so it must live inside details here.+ extra_details.insert("pipelineStep".to_string(), json!(warning.pipeline_step()));++ let mut properties: HashMap<String, Value> = HashMap::new();+ properties.insert(PROP_TYPE.to_string(), json!(warning.as_str()));+ properties.insert(PROP_SOURCE.to_string(), json!(source.service));+ properties.insert(PROP_DETAILS.to_string(), Value::Object(extra_details));++ let uuid = Uuid::now_v7();+ let raw_event = RawEvent {+ token: Some(token.to_string()),+ distinct_id: Some(json!(token)),+ uuid: Some(uuid),+ event: CLIENT_INGESTION_WARNING_EVENT.to_string(),+ properties,+ ..Default::default()+ };+ // Capture serialises the inner event to a string, then the whole+ // `CapturedEvent` again on send — matching the normal sink wire format.+ let data = serde_json::to_string(&raw_event)?;++ Ok(CapturedEvent {+ uuid,+ distinct_id: token.to_string(),+ session_id: None,+ ip: String::new(),+ data,+ now: timestamp.to_rfc3339_opts(SecondsFormat::Millis, true),+ sent_at: None,+ token: token.to_string(),+ event: CLIENT_INGESTION_WARNING_EVENT.to_string(),+ timestamp,+ is_cookieless_mode: false,+ historical_migration: false,+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::CAPTURE_V1_ANALYTICS;++ /// Parse the inner `RawEvent` and its `$$client_ingestion_warning_details`+ /// object back out of a built envelope.+ fn parse_envelope(event: &CapturedEvent) -> (Value, Value) {+ let raw: Value = serde_json::from_str(&event.data).unwrap();+ let details = raw["properties"][PROP_DETAILS].clone();+ (raw, details)+ }++ #[test]+ fn envelope_is_a_client_ingestion_warning_event_keyed_by_token() {+ let event = build_warning_event(+ "phc_test_token",+ CAPTURE_V1_ANALYTICS,+ WarningType::MissingEventName,+ Map::new(),+ 3,+ Utc::now(),+ )+ .unwrap();++ assert_eq!(event.event, "$$client_ingestion_warning");+ assert_eq!(event.token, "phc_test_token");+ // distinct_id must be the (safe, bounded) token, never a caller value.+ assert_eq!(event.distinct_id, "phc_test_token");+ }++ #[test]+ fn properties_carry_the_structured_type_source_and_details() {+ let mut extra = Map::new();+ extra.insert("distinctId".to_string(), json!("user-1"));+ extra.insert("lib".to_string(), json!("posthog-js"));+ let event = build_warning_event(+ "phc_test_token",+ CAPTURE_V1_ANALYTICS,+ WarningType::MissingEventName,+ extra,+ 3,+ Utc::now(),+ )+ .unwrap();++ let (raw, details) = parse_envelope(&event);+ assert_eq!(raw["properties"][PROP_TYPE], "missing_event_name");+ assert_eq!(raw["properties"][PROP_SOURCE], "capture");++ // Injected by the builder.+ assert_eq!(details["count"], 3);+ assert_eq!(details["pipelineStep"], "capture_validation");+ // Caller context passes through untouched.+ assert_eq!(details["distinctId"], "user-1");+ assert_eq!(details["lib"], "posthog-js");+ }++ /// The offending distinct_id lives in `details` only; the envelope's+ /// top-level distinct_id stays the token so an oversized id can never make+ /// the consumer drop a `distinct_id_too_large` warning.+ #[test]+ fn oversized_offender_distinct_id_never_reaches_the_envelope_field() {+ let huge = "x".repeat(10_000);+ let mut extra = Map::new();+ extra.insert("distinctId".to_string(), json!(huge));+ let event = build_warning_event(+ "phc_real",+ CAPTURE_V1_ANALYTICS,+ WarningType::DistinctIdTooLarge,+ extra,+ 1,+ Utc::now(),+ )+ .unwrap();++ assert_eq!(event.distinct_id, "phc_real");+ let (_, details) = parse_envelope(&event);+ assert_eq!(details["distinctId"].as_str().unwrap().len(), 10_000);+ }++ /// The message `source` reflects the caller's [`crate::WarningSource`]+ /// rather than a hardcoded capture literal — the point of parameterizing+ /// the builder for reuse by other Rust services.+ #[test]+ fn source_field_reflects_the_caller_supplied_source() {+ let other = WarningSource {+ service: "batch_import",+ path: "some_path",+ };+ let event = build_warning_event(+ "phc_test_token",+ other,+ WarningType::EmptyBatch,+ Map::new(),+ 1,+ Utc::now(),+ )+ .unwrap();+ let (raw, _) = parse_envelope(&event);+ assert_eq!(raw["properties"][PROP_SOURCE], "batch_import");+ }+}diff --git a/rust/common/ingestion_warnings/src/test_support.rs b/rust/common/ingestion_warnings/src/test_support.rsnew file mode 100644index 000000000000..dceeceed03f3--- /dev/null+++ b/rust/common/ingestion_warnings/src/test_support.rs@@ -0,0 +1,60 @@+//! Test double for [`crate::WarningEmitter`], available to downstream crates'+//! dev-tests (which is why this module is not `#[cfg(test)]`-gated).++use std::sync::Mutex;+use std::time::Duration;++use serde_json::{Map, Value};++use crate::registry::WarningType;+use crate::{WarningEmitter, WarningSource};++/// One captured [`WarningEmitter::emit`] call.+#[derive(Debug, Clone, PartialEq)]+pub struct EmittedWarning {+ pub token: String,+ pub source: WarningSource,+ pub warning: WarningType,+ pub extra_details: Map<String, Value>,+ pub count: u64,+}++/// Emitter that records every call for assertions. No throttling, no I/O.+#[derive(Default)]+pub struct CollectingEmitter {+ emitted: Mutex<Vec<EmittedWarning>>,+}++impl CollectingEmitter {+ pub fn new() -> Self {+ Self::default()+ }++ pub fn emitted(&self) -> Vec<EmittedWarning> {+ self.emitted.lock().expect("emitter mutex poisoned").clone()+ }+}++impl WarningEmitter for CollectingEmitter {+ fn emit(+ &self,+ token: String,+ source: WarningSource,+ warning: WarningType,+ extra_details: Map<String, Value>,+ count: u64,+ ) {+ self.emitted+ .lock()+ .expect("emitter mutex poisoned")+ .push(EmittedWarning {+ token,+ source,+ warning,+ extra_details,+ count,+ });+ }++ fn flush(&self, _timeout: Duration) {}+}diff --git a/rust/common/ingestion_warnings/src/throttle.rs b/rust/common/ingestion_warnings/src/throttle.rsnew file mode 100644index 000000000000..0b2141a555bc--- /dev/null+++ b/rust/common/ingestion_warnings/src/throttle.rs@@ -0,0 +1,197 @@+//! Cross-request throttle for warning emission — the outage guard.+//!+//! Mirrors the Node.js `IngestionWarningLimiter` semantics: by default at most+//! one warning per `(token, type)` key per hour (burst 1), enforced per pod.+//! Combined with per-batch dedup at the emit site, steady-state volume is+//! bounded at roughly `affected tokens × warning types` messages per hour per+//! pod regardless of traffic.++use std::num::NonZeroU32;+use std::time::Duration;++use governor::{clock, state::keyed::DefaultKeyedStateStore, Quota, RateLimiter};++/// Default refill period: one permit per (token, type) per hour.+pub const DEFAULT_THROTTLE_PERIOD: Duration = Duration::from_secs(3600);++/// Default bound on tracked `(token, type)` keys. Capture cannot verify+/// tokens, so a flood of spoofed tokens would otherwise grow the key map+/// without limit until the hourly sweep; legit steady-state cardinality+/// (tokens with drops in the last hour × types) sits orders of magnitude+/// below this, so hitting the cap means abuse, and the cheap fail-open+/// response is to stop emitting until the sweep evicts refilled keys.+pub const DEFAULT_MAX_TRACKED_KEYS: usize = 100_000;++type Key = (String, crate::registry::WarningType);++/// Outcome of a throttle check; names align with the emission metric's+/// `outcome` label values.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ThrottleDecision {+ /// Budget available — emit the warning.+ Emit,+ /// This `(token, type)` already emitted within the period — drop.+ Throttled,+ /// The key map is at capacity (token-flood guard) — drop without+ /// consulting or growing the limiter.+ CardinalityCapped,+}++/// Keyed governor rate limiter over `(token, WarningType)`.+pub struct WarningThrottle {+ limiter: RateLimiter<Key, DefaultKeyedStateStore<Key>, clock::DefaultClock>,+ max_tracked_keys: usize,+}++impl WarningThrottle {+ /// `period` is the refill interval per permit; `burst` is the bucket size.+ /// Production callers use [`WarningThrottle::default`]; the parameters+ /// exist so tests can exercise refill without waiting an hour.+ pub fn new(period: Duration, burst: NonZeroU32) -> Self {+ let quota = Quota::with_period(period)+ .expect("throttle period must be non-zero")+ .allow_burst(burst);+ Self {+ limiter: RateLimiter::dashmap(quota),+ max_tracked_keys: DEFAULT_MAX_TRACKED_KEYS,+ }+ }++ /// Override the tracked-key cap (tests use small values).+ pub fn with_max_tracked_keys(mut self, max_tracked_keys: usize) -> Self {+ self.max_tracked_keys = max_tracked_keys;+ self+ }++ /// Consume a permit for this `(token, type)` if the key map has room and+ /// the key has budget. Anything but [`ThrottleDecision::Emit`] means the+ /// caller should drop the warning.+ pub fn check(&self, token: &str, warning: crate::registry::WarningType) -> ThrottleDecision {+ // Governor's keyed limiter inserts on lookup, so the cap must gate+ // every check — including keys already tracked — to stay O(1).+ if self.limiter.len() >= self.max_tracked_keys {+ return ThrottleDecision::CardinalityCapped;+ }+ match self.limiter.check_key(&(token.to_string(), warning)) {+ Ok(()) => ThrottleDecision::Emit,+ Err(_) => ThrottleDecision::Throttled,+ }+ }++ /// Drop per-key state that has fully refilled, bounding memory. Call+ /// periodically from a maintenance task (see `OverflowLimiter::clean_state`+ /// for the established capture pattern).+ pub fn sweep(&self) {+ self.limiter.retain_recent();+ self.limiter.shrink_to_fit();+ }++ /// Number of currently tracked keys (for metrics/tests).+ pub fn tracked_keys(&self) -> usize {+ self.limiter.len()+ }+}++impl Default for WarningThrottle {+ fn default() -> Self {+ Self::new(DEFAULT_THROTTLE_PERIOD, NonZeroU32::MIN)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::registry::WarningType;++ #[test]+ fn burst_one_allows_first_and_blocks_repeat_per_key() {+ let throttle = WarningThrottle::default();++ assert_eq!(+ throttle.check("tok_a", WarningType::MissingEventName),+ ThrottleDecision::Emit+ );+ assert_eq!(+ throttle.check("tok_a", WarningType::MissingEventName),+ ThrottleDecision::Throttled,+ "same (token, type) within the period must be throttled"+ );++ // Different type and different token are independent buckets.+ assert_eq!(+ throttle.check("tok_a", WarningType::EmptyBatch),+ ThrottleDecision::Emit+ );+ assert_eq!(+ throttle.check("tok_b", WarningType::MissingEventName),+ ThrottleDecision::Emit+ );+ }++ #[test]+ fn permits_refill_after_the_period() {+ let throttle = WarningThrottle::new(Duration::from_millis(50), NonZeroU32::MIN);+ assert_eq!(+ throttle.check("tok", WarningType::InvalidBatch),+ ThrottleDecision::Emit+ );+ assert_eq!(+ throttle.check("tok", WarningType::InvalidBatch),+ ThrottleDecision::Throttled+ );+ std::thread::sleep(Duration::from_millis(80));+ assert_eq!(+ throttle.check("tok", WarningType::InvalidBatch),+ ThrottleDecision::Emit,+ "permit must refill after the period elapses"+ );+ }++ #[test]+ fn sweep_evicts_refilled_keys() {+ let throttle = WarningThrottle::new(Duration::from_millis(10), NonZeroU32::MIN);+ assert_eq!(+ throttle.check("tok", WarningType::MissingDistinctId),+ ThrottleDecision::Emit+ );+ assert_eq!(throttle.tracked_keys(), 1);+ std::thread::sleep(Duration::from_millis(30));+ throttle.sweep();+ assert_eq!(+ throttle.tracked_keys(),+ 0,+ "fully refilled keys are evicted"+ );+ }++ #[test]+ fn cardinality_cap_stops_emission_until_sweep_frees_keys() {+ let throttle = WarningThrottle::new(Duration::from_millis(10), NonZeroU32::MIN)+ .with_max_tracked_keys(2);+ assert_eq!(+ throttle.check("tok_a", WarningType::MissingEventName),+ ThrottleDecision::Emit+ );+ assert_eq!(+ throttle.check("tok_b", WarningType::MissingEventName),+ ThrottleDecision::Emit+ );+ // Map is at capacity: new AND existing keys are capped (fail open).+ assert_eq!(+ throttle.check("tok_c", WarningType::MissingEventName),+ ThrottleDecision::CardinalityCapped+ );+ assert_eq!(+ throttle.check("tok_a", WarningType::EmptyBatch),+ ThrottleDecision::CardinalityCapped+ );++ std::thread::sleep(Duration::from_millis(30));+ throttle.sweep();+ assert_eq!(+ throttle.check("tok_c", WarningType::MissingEventName),+ ThrottleDecision::Emit,+ "sweep must free capacity for new keys"+ );+ }+}diff --git a/rust/common/kafka/src/config.rs b/rust/common/kafka/src/config.rsindex fa475f5c9888..34375a82400f 100644--- a/rust/common/kafka/src/config.rs+++ b/rust/common/kafka/src/config.rs@@ -48,6 +48,44 @@ pub struct KafkaConfig {// Set to "murmur2_random" to co-partition a keyed topic with Kafka-Java/python-kafka/Node// producers; `None` uses librdkafka's CRC32-based default, which routes keys differently.pub kafka_producer_partitioner: Option<String>,++ // `None` means "let librdkafka pick its default" (acks=all, effectively unbounded retries+ // within message.timeout.ms) — existing callers are unaffected. Fire-and-forget producers+ // (e.g. best-effort warning emitters) set these explicitly to acks="1"/retries=0 so a slow+ // broker times out and drops instead of retrying.+ pub kafka_producer_acks: Option<String>,++ pub kafka_producer_retries: Option<u32>,+}++// Keep these values in sync with the `#[envconfig(default = ...)]` attributes+// above: `KafkaConfig::default()` must match `init_from_env()` with no env set,+// so callers that build a config with `..Default::default()` get the same base+// as env-driven callers.+impl Default for KafkaConfig {+ fn default() -> Self {+ Self {+ kafka_producer_linger_ms: 20,+ kafka_producer_queue_mib: 400,+ kafka_producer_queue_messages: 10_000_000,+ kafka_message_timeout_ms: 20_000,+ kafka_compression_codec: "none".to_string(),+ kafka_tls: false,+ kafka_hosts: "localhost:9092".to_string(),+ kafka_client_rack: String::new(),+ kafka_client_id: String::new(),+ kafka_producer_batch_size: None,+ kafka_producer_batch_num_messages: None,+ kafka_producer_enable_idempotence: None,+ kafka_producer_max_in_flight_requests_per_connection: None,+ kafka_producer_topic_metadata_refresh_interval_ms: None,+ kafka_producer_message_max_bytes: None,+ kafka_producer_sticky_partitioning_linger_ms: None,+ kafka_producer_partitioner: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,+ }+ }}#[derive(Envconfig, Clone)]@@ -114,3 +152,64 @@ impl ConsumerConfig {}}}++#[cfg(test)]+mod tests {+ use std::collections::HashMap;++ use envconfig::Envconfig;++ use super::KafkaConfig;++ // Guards the two-spot-defaults hazard: `Default` must stay byte-identical to+ // the `#[envconfig(default = ...)]` values, so `..Default::default()`+ // callers get the same base as env-driven ones. Uses an empty hashmap+ // (not process env) to stay deterministic under any CI environment.+ #[test]+ fn default_matches_envconfig_defaults() {+ let d = KafkaConfig::default();+ let e = KafkaConfig::init_from_hashmap(&HashMap::new())+ .expect("envconfig must initialize from its declared defaults");++ assert_eq!(d.kafka_producer_linger_ms, e.kafka_producer_linger_ms);+ assert_eq!(d.kafka_producer_queue_mib, e.kafka_producer_queue_mib);+ assert_eq!(+ d.kafka_producer_queue_messages,+ e.kafka_producer_queue_messages+ );+ assert_eq!(d.kafka_message_timeout_ms, e.kafka_message_timeout_ms);+ assert_eq!(d.kafka_compression_codec, e.kafka_compression_codec);+ assert_eq!(d.kafka_tls, e.kafka_tls);+ assert_eq!(d.kafka_hosts, e.kafka_hosts);+ assert_eq!(d.kafka_client_rack, e.kafka_client_rack);+ assert_eq!(d.kafka_client_id, e.kafka_client_id);+ assert_eq!(d.kafka_producer_batch_size, e.kafka_producer_batch_size);+ assert_eq!(+ d.kafka_producer_batch_num_messages,+ e.kafka_producer_batch_num_messages+ );+ assert_eq!(+ d.kafka_producer_enable_idempotence,+ e.kafka_producer_enable_idempotence+ );+ assert_eq!(+ d.kafka_producer_max_in_flight_requests_per_connection,+ e.kafka_producer_max_in_flight_requests_per_connection+ );+ assert_eq!(+ d.kafka_producer_topic_metadata_refresh_interval_ms,+ e.kafka_producer_topic_metadata_refresh_interval_ms+ );+ assert_eq!(+ d.kafka_producer_message_max_bytes,+ e.kafka_producer_message_max_bytes+ );+ assert_eq!(+ d.kafka_producer_sticky_partitioning_linger_ms,+ e.kafka_producer_sticky_partitioning_linger_ms+ );+ assert_eq!(d.kafka_producer_partitioner, e.kafka_producer_partitioner);+ assert_eq!(d.kafka_producer_acks, e.kafka_producer_acks);+ assert_eq!(d.kafka_producer_retries, e.kafka_producer_retries);+ }+}diff --git a/rust/common/kafka/src/kafka_producer.rs b/rust/common/kafka/src/kafka_producer.rsindex 263b954b85dd..9a96a8e836b5 100644--- a/rust/common/kafka/src/kafka_producer.rs+++ b/rust/common/kafka/src/kafka_producer.rs@@ -5,7 +5,9 @@ use crate::config::KafkaConfig;use common_liveness::SyncLivenessReporter;use lz4::EncoderBuilder;use rdkafka::error::KafkaError;-use rdkafka::producer::{FutureProducer, FutureRecord, Producer};+use rdkafka::producer::{+ DeliveryResult, FutureProducer, FutureRecord, Producer, ProducerContext, ThreadedProducer,+};use rdkafka::{ClientConfig, ClientContext};use serde::Serialize;use serde_json::error::Error as SerdeError;@@ -69,13 +71,10 @@ impl rdkafka::ClientContext for KafkaContext {}}-pub async fn create_kafka_producer<L>(- config: &KafkaConfig,- liveness: L,-) -> Result<FutureProducer<KafkaContext>, KafkaError>-where- L: SyncLivenessReporter + Clone + 'static,-{+/// Build the shared rdkafka `ClientConfig` from our `KafkaConfig`. Both the+/// `FutureProducer` and `ThreadedProducer` builders go through this, so the two+/// producer styles always apply identical connection and tuning settings.+fn build_client_config(config: &KafkaConfig) -> ClientConfig {let mut client_config = ClientConfig::new();client_config.set("bootstrap.servers", &config.kafka_hosts)@@ -98,6 +97,13 @@ whereconfig.kafka_producer_queue_messages.to_string(),);+ // `client.id` identifies this producer to the broker (shows up in broker+ // metrics/logs). Only set when non-empty so existing callers keep+ // librdkafka's default identity.+ if !config.kafka_client_id.is_empty() {+ client_config.set("client.id", &config.kafka_client_id);+ }+// WarpStream producer tuning — only set when explicitly configured, so existing services// that don't opt in keep their previous librdkafka defaults.if let Some(v) = config.kafka_producer_batch_size {@@ -124,6 +130,12 @@ whereif let Some(ref v) = config.kafka_producer_partitioner {client_config.set("partitioner", v);}+ if let Some(ref v) = config.kafka_producer_acks {+ client_config.set("acks", v);+ }+ if let Some(v) = config.kafka_producer_retries {+ client_config.set("retries", v.to_string());+ }if config.kafka_tls {client_config@@ -131,12 +143,17 @@ where.set("enable.ssl.certificate.verification", "false");};- debug!("rdkafka configuration: {:?}", client_config);- let api: FutureProducer<KafkaContext> =- client_config.create_with_context(KafkaContext::new(liveness))?;+ client_config+}- // "Ping" the Kafka brokers by requesting metadata- match api+/// Ping the Kafka brokers by fetching metadata, so a broker that's unreachable+/// at startup surfaces as an error here rather than silently later.+fn ping_brokers<C, P>(producer: &P) -> Result<(), KafkaError>+where+ C: ProducerContext,+ P: Producer<C>,+{+ match producer.client().fetch_metadata(None, std::time::Duration::from_secs(15)){@@ -145,16 +162,103 @@ where"Successfully connected to Kafka brokers. Found {} topics.",metadata.topics().len());+ Ok(())}Err(error) => {error!("Failed to fetch metadata from Kafka brokers: {:?}", error);- return Err(error);+ Err(error)}}+}++pub async fn create_kafka_producer<L>(+ config: &KafkaConfig,+ liveness: L,+) -> Result<FutureProducer<KafkaContext>, KafkaError>+where+ L: SyncLivenessReporter + Clone + 'static,+{+ let client_config = build_client_config(config);+ debug!("rdkafka configuration: {:?}", client_config);+ let api: FutureProducer<KafkaContext> =+ client_config.create_with_context(KafkaContext::new(liveness))?;++ ping_brokers(&api)?;Ok(api)}+/// A producer context that reports liveness (like [`KafkaContext`]) and, for+/// each produced message, invokes a caller-supplied closure with the delivery+/// report. This lets a caller observe delivery outcomes — e.g. emit+/// metrics — from rdkafka's own poll thread, with no per-message task and+/// without baking caller-specific logic into the shared context.+///+/// `K` is the per-message opaque payload the caller attaches via+/// [`rdkafka::producer::BaseRecord::delivery_opaque`]; it is handed back to the+/// closure on delivery so labels/context travel with the message.+/// Shared delivery-report callback for [`ThreadedKafkaContext`]: invoked once+/// per message with the delivery result and the per-message opaque `K`.+type DeliveryCallback<K> = Arc<dyn Fn(&DeliveryResult, K) + Send + Sync>;++pub struct ThreadedKafkaContext<K: Send + Sync + 'static> {+ liveness: Arc<dyn SyncLivenessReporter>,+ on_delivery: DeliveryCallback<K>,+}++impl<K: Send + Sync + 'static> ThreadedKafkaContext<K> {+ pub fn new(+ liveness: impl SyncLivenessReporter + Clone + 'static,+ on_delivery: impl Fn(&DeliveryResult, K) + Send + Sync + 'static,+ ) -> Self {+ Self {+ liveness: Arc::new(liveness),+ on_delivery: Arc::new(on_delivery),+ }+ }+}++impl<K: Send + Sync + 'static> ClientContext for ThreadedKafkaContext<K> {+ fn stats(&self, _: rdkafka::Statistics) {+ // Signal liveness, as the rdkafka poll thread is running and calling us.+ self.liveness.report_healthy();+ }+}++impl<K: Send + Sync + 'static> ProducerContext for ThreadedKafkaContext<K> {+ type DeliveryOpaque = Box<K>;++ fn delivery(&self, delivery_result: &DeliveryResult, delivery_opaque: Self::DeliveryOpaque) {+ (self.on_delivery)(delivery_result, *delivery_opaque);+ }+}++/// Create a [`ThreadedProducer`] that reports liveness and calls `on_delivery`+/// with each message's delivery report (see [`ThreadedKafkaContext`]). The+/// producer runs its own poll thread, so no manual polling is needed. This is+/// the opt-in path for fire-and-forget producers that want delivery+/// observability without a per-message task; existing `FutureProducer` callers+/// are unaffected.+pub async fn create_threaded_kafka_producer<K, L, F>(+ config: &KafkaConfig,+ liveness: L,+ on_delivery: F,+) -> Result<ThreadedProducer<ThreadedKafkaContext<K>>, KafkaError>+where+ K: Send + Sync + 'static,+ L: SyncLivenessReporter + Clone + 'static,+ F: Fn(&DeliveryResult, K) + Send + Sync + 'static,+{+ let client_config = build_client_config(config);+ debug!("rdkafka configuration (threaded): {:?}", client_config);+ let producer: ThreadedProducer<ThreadedKafkaContext<K>> =+ client_config.create_with_context(ThreadedKafkaContext::new(liveness, on_delivery))?;++ ping_brokers(&producer)?;++ Ok(producer)+}+#[derive(Error, Debug)]pub enum KafkaProduceError {#[error("failed to serialize: {error}")]@@ -389,9 +493,33 @@ mod tests {use lz4::Decoder;- use super::{compress_lz4_frame, maybe_compress_lz4_frame, EnvelopeEncoding};+ use super::{+ build_client_config, compress_lz4_frame, maybe_compress_lz4_frame, EnvelopeEncoding,+ };+ use crate::config::KafkaConfig;use crate::kafka_consumer::LZ4_FRAME_MAGIC;+ #[test]+ fn client_id_is_set_only_when_non_empty() {+ // Empty client_id (every existing caller today) must leave the key+ // unset so librdkafka keeps its default identity — the behavior-neutral+ // guarantee the shared helper makes.+ let config = KafkaConfig {+ kafka_client_id: String::new(),+ ..Default::default()+ };+ assert_eq!(build_client_config(&config).get("client.id"), None);++ let config = KafkaConfig {+ kafka_client_id: "capture-ingestion-warnings".to_string(),+ ..Default::default()+ };+ assert_eq!(+ build_client_config(&config).get("client.id"),+ Some("capture-ingestion-warnings")+ );+ }+#[test]fn lz4_frame_starts_with_magic_and_round_trips() {let original = br#"{"team_id":1,"property_key":"$browser","property_value":"Chrome"}"#;diff --git a/rust/common/kafka/src/test.rs b/rust/common/kafka/src/test.rsindex dd227dff7bfa..cadf62273561 100644--- a/rust/common/kafka/src/test.rs+++ b/rust/common/kafka/src/test.rs@@ -33,6 +33,8 @@ pub async fn create_mock_kafka() -> (kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,kafka_producer_partitioner: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,};(diff --git a/rust/flags-consumer/src/config.rs b/rust/flags-consumer/src/config.rsindex 82e4bbd52ab7..6e902434e646 100644--- a/rust/flags-consumer/src/config.rs+++ b/rust/flags-consumer/src/config.rs@@ -146,6 +146,8 @@ impl Config {kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,kafka_producer_partitioner: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,}}diff --git a/rust/kafka-deduplicator/src/service.rs b/rust/kafka-deduplicator/src/service.rsindex 555ba3aa0802..08ca40bade13 100644--- a/rust/kafka-deduplicator/src/service.rs+++ b/rust/kafka-deduplicator/src/service.rs@@ -442,6 +442,8 @@ impl KafkaDeduplicatorService {kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,kafka_producer_partitioner: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,};// Normalize empty strings to None for optional topic configsdiff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rsindex 3083d1b9b849..5704448a9fbf 100644--- a/rust/personhog-leader/src/coordination/mod.rs+++ b/rust/personhog-leader/src/coordination/mod.rs@@ -140,6 +140,8 @@ mod tests {kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,kafka_producer_partitioner: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,},topic: "personhog_updates".to_string(),pod_name: "test".to_string(),diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rsindex 1e7b4cd96b00..7737ef4c39ab 100644--- a/rust/personhog-leader/tests/common/mod.rs+++ b/rust/personhog-leader/tests/common/mod.rs@@ -196,6 +196,8 @@ pub fn test_kafka_config() -> KafkaConfig {kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,kafka_producer_partitioner: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,}}@@ -251,6 +253,8 @@ pub async fn create_local_kafka_producer() -> FutureProducer<KafkaContext> {kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,kafka_producer_partitioner: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,};create_kafka_producer(&config, handle).awaitdiff --git a/rust/personhog-writer/tests/common/mod.rs b/rust/personhog-writer/tests/common/mod.rsindex 5819d73a5b8b..469fa65b2975 100644--- a/rust/personhog-writer/tests/common/mod.rs+++ b/rust/personhog-writer/tests/common/mod.rs@@ -61,6 +61,8 @@ pub async fn create_local_kafka_producer() -> FutureProducer<KafkaContext> {kafka_producer_message_max_bytes: None,kafka_producer_sticky_partitioning_linger_ms: None,kafka_producer_partitioner: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,};common_kafka::kafka_producer::create_kafka_producer(&config, handle).await