: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(capture): make warnings emitter observable and v0-independent (#74287)
Eli Reismanc826bb9f79a9
diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.ymlindex 6d34a1ae01e6..80bb2294eb48 100644--- a/.github/workflows/ci-nodejs.yml+++ b/.github/workflows/ci-nodejs.yml@@ -63,6 +63,11 @@ jobs:- 'rust/replay-anonymizer/**'- 'rust/replay-anonymizer-node/**'- '**/crosslang/**'+ # The clientwarnings consumer e2e replays capture's warning envelope from+ # this shared fixture. Without it the rust filter below decides, and it only+ # admits ingestion-consumer, which does not depend on the fixture's crate, so+ # a capture-side envelope change would skip the test that pins the consumer.+ - 'rust/common/ingestion_warnings/*.json'- 'posthog/clickhouse/**'- 'ee/migrations/**'- 'posthog/management/commands/setup_test_environment.py'diff --git a/nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.test.ts b/nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.test.tsindex 0e0eb81094e4..464b4223cd4c 100644--- a/nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.test.ts+++ b/nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.test.ts@@ -1,5 +1,8 @@import { Message } from 'node-rdkafka'+import { readFileSync } from 'node:fs'+import path from 'node:path'+import { parseJSON } from '~/common/utils/json-parse'import { KafkaProducerRegistryComponent } from '~/ingestion/common/outputs/producer-registry'import {getDefaultKafkaDownstreamProducerEnvConfig,@@ -56,6 +59,17 @@ function constComponent<T extends object>(value: T): Component<T> {return { start: () => Promise.resolve({ value, stop: () => Promise.resolve() }) }}+// Envelope pin shared with rust/capture/tests/ingestion_warnings_integration.rs,+// which asserts real capture output against it. Replaying the same artifact here+// tests the consumer against what capture actually produces, instead of a literal+// on this side that can drift from the producer without either test noticing.+const CAPTURE_ENVELOPE_FIXTURE = parseJSON(+ readFileSync(+ path.resolve(__dirname, '../../../../../rust/common/ingestion_warnings/capture_envelope.fixture.json'),+ 'utf8'+ )+) as { event: string; properties: Record<string, unknown> }+class ClientWarningsTestIngester implements IngesterLike {private stopScope?: () => Promise<void>@@ -143,4 +157,36 @@ describe('ClientWarnings consumer E2E', () => {expect(warnings[0].details.message).toBe('test message')}, 30_000)})++ testWithTeamIngester(+ 'resolves a capture envelope to a structured warning',+ {},+ async ({ ingester, team, token }) => {+ const event = new EventBuilder(team)+ .withEvent(CAPTURE_ENVELOPE_FIXTURE.event)+ .withProperties(CAPTURE_ENVELOPE_FIXTURE.properties)+ .build()++ const { backgroundTask } = await ingester.handleKafkaBatch(createKafkaMessages([event], token))+ await backgroundTask++ await waitForExpect(async () => {+ const warnings = await fetchIngestionWarnings(clickhouse, team.id)+ expect(warnings.length).toBe(1)+ // The structured type survives the trust allowlist rather than+ // being downgraded to `client_ingestion_warning`, and `source`+ // reaches the row so warnings stay attributable to capture.+ expect(warnings[0].type).toBe('missing_event_name')+ expect(warnings[0].source).toBe('capture')+ expect(warnings[0].details).toMatchObject({+ // v2 materializes its pipeline_step column from this key.+ pipelineStep: 'capture_validation',+ count: 2,+ // Stamped from this side's registry, never from the envelope.+ category: 'event',+ severity: 'error',+ })+ }, 30_000)+ }+ )})diff --git a/posthog/api/test/test_ingestion_warnings_v2.py b/posthog/api/test/test_ingestion_warnings_v2.pyindex 8346601a5dfc..aedd0ffcc0ed 100644--- a/posthog/api/test/test_ingestion_warnings_v2.py+++ b/posthog/api/test/test_ingestion_warnings_v2.py@@ -105,6 +105,30 @@ class TestIngestionWarningsV2API(ClickhouseTestMixin, APIBaseTest):assert merge_warnings["category"] == "merge"assert merge_warnings["severity"] == "warning"+ @parameterized.expand(+ [+ ("missing_event_name", {"pipelineStep": "capture_validation"}, "capture_validation"),+ ("empty_batch", {}, "unknown"),+ ]+ )+ def test_samples_report_producer_and_pipeline_step(+ self, warning_type: str, extra_details: dict, expected_step: str+ ):+ create_warning(+ team_id=self.team.id,+ type=warning_type,+ timestamp="2026-07-07 11:30:00",+ details={"category": "event", "severity": "error", **extra_details},+ source="capture",+ )++ status_code, results = self._list(type=warning_type)++ assert status_code == status.HTTP_200_OK+ sample = results[0]["samples"][0]+ assert sample["source"] == "capture"+ assert sample["pipeline_step"] == expected_step+@parameterized.expand([("category", "merge", ["cannot_merge_already_identified"]),diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex aefad9e8a714..bd094a0b1cb8 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -430,9 +430,9 @@ pub struct Config {// --- 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+ // existing `client_ingestion_warning` topic, by default on the main event+ // cluster: absent the warnings-cluster overrides below, 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.@@ -455,6 +455,22 @@ pub struct Config {// the main event producer allows.#[envconfig(default = "1048576")]pub capture_ingestion_warnings_kafka_message_max_bytes: u32,++ // Warnings-cluster overrides, same shape as the traces/metrics overrides in+ // `KafkaConfig` below. When unset, each reuses the corresponding `kafka_*`+ // value: `kafka_client_ingestion_warning_topic`, `kafka_hosts`, `kafka_tls`.+ //+ // The emitter runs in the v1 analytics handler but its destination has+ // always been read from the v0 `KAFKA_*` block. Retiring that block would+ // silently fall these back to their envconfig defaults (an empty topic and+ // TLS off), which is wrong in every environment, so the emitter owns its own+ // names here. Setting them in charts makes the fallback dead config. TLS is+ // separate from `kafka_hosts` because pointing the emitter at a cluster whose+ // TLS requirement differs from the main one otherwise fails the producer's+ // startup metadata fetch, which disables it for the pod's life.+ pub capture_ingestion_warnings_kafka_topic: Option<String>,+ pub capture_ingestion_warnings_kafka_hosts: Option<String>,+ pub capture_ingestion_warnings_kafka_tls: Option<bool>,}#[derive(Envconfig, Clone)]diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex b5b69d197a8f..d267a4515532 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -4,10 +4,13 @@ use std::time::Duration;use anyhow::Context;use axum::Router;-use common_ingestion_warnings::{observe_delivery, KafkaWarningEmitter, WarningEmitter};+use common_ingestion_warnings::{+ observe_delivery, KafkaWarningEmitter, WarningEmitter, INGESTION_WARNINGS_EMITTER_ENABLED,+};use common_kafka::config::KafkaConfig as WarningsKafkaConfig;use common_kafka::kafka_producer::create_threaded_kafka_producer;use common_redis::RedisClient;+use metrics::gauge;use tracing::{info, warn};use crate::ai_s3::AiBlobStorage;@@ -725,11 +728,12 @@ fn build_warnings_kafka_config(/// `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.+/// callback — by default 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. All three are overridable via+/// `CAPTURE_INGESTION_WARNINGS_KAFKA_{HOSTS,TLS,TOPIC}`. 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@@ -743,8 +747,39 @@ async fn create_ingestion_warning_emitter(return None;}- if config.kafka.kafka_hosts.is_empty() {- warn!("ingestion warnings enabled but KAFKA_HOSTS is empty; emitter disabled");+ // Past this point the operator asked for warnings, so every exit reports+ // through the gauge. Leaving it unset above keeps "disabled" distinct from+ // "enabled but broken".+ let report_disabled = || gauge!(INGESTION_WARNINGS_EMITTER_ENABLED).set(0.0);++ let hosts = config+ .capture_ingestion_warnings_kafka_hosts+ .clone()+ .unwrap_or_else(|| config.kafka.kafka_hosts.clone());+ let topic = config+ .capture_ingestion_warnings_kafka_topic+ .clone()+ .unwrap_or_else(|| config.kafka.kafka_client_ingestion_warning_topic.clone());+ let tls = config+ .capture_ingestion_warnings_kafka_tls+ .unwrap_or(config.kafka.kafka_tls);++ if hosts.is_empty() {+ warn!(+ "ingestion warnings enabled but no Kafka hosts \+ (CAPTURE_INGESTION_WARNINGS_KAFKA_HOSTS, KAFKA_HOSTS); emitter disabled"+ );+ report_disabled();+ return None;+ }++ if topic.is_empty() {+ warn!(+ "ingestion warnings enabled but no Kafka topic \+ (CAPTURE_INGESTION_WARNINGS_KAFKA_TOPIC, KAFKA_CLIENT_INGESTION_WARNING_TOPIC); \+ emitter disabled"+ );+ report_disabled();return None;}@@ -752,12 +787,13 @@ async fn create_ingestion_warning_emitter(warn!("ingestion warnings enabled but no lifecycle handle was registered; emitter disabled");+ report_disabled();return None;};let warnings_kafka_config = build_warnings_kafka_config(- config.kafka.kafka_hosts.clone(),- config.kafka.kafka_tls,+ hosts,+ tls,config.capture_ingestion_warnings_kafka_queue_mib,config.capture_ingestion_warnings_kafka_message_max_bytes,);@@ -774,14 +810,12 @@ async fn create_ingestion_warning_emitter(tracing::error!("failed to create ingestion warnings producer, emitter disabled: {e:#}");+ report_disabled();return None;}};- let emitter = Arc::new(KafkaWarningEmitter::new(- producer,- config.kafka.kafka_client_ingestion_warning_topic.clone(),- ));+ let emitter = Arc::new(KafkaWarningEmitter::new(producer, topic.clone()));let emitter_bg = emitter.clone();tokio::spawn(async move {@@ -805,10 +839,8 @@ async fn create_ingestion_warning_emitter(}});- info!(- topic = config.kafka.kafka_client_ingestion_warning_topic.as_str(),- "ingestion warnings emitter enabled"- );+ gauge!(INGESTION_WARNINGS_EMITTER_ENABLED).set(1.0);+ info!(topic = topic.as_str(), "ingestion warnings emitter enabled");Some(emitter)}diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex 13588656cdac..af84c76f4ffb 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -263,6 +263,9 @@ mod tests {capture_ingestion_warnings_enabled: false,capture_ingestion_warnings_kafka_queue_mib: 16,capture_ingestion_warnings_kafka_message_max_bytes: 1048576,+ capture_ingestion_warnings_kafka_topic: None,+ capture_ingestion_warnings_kafka_hosts: None,+ capture_ingestion_warnings_kafka_tls: None,}}diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex d85284f42f6c..bfae78358288 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -179,6 +179,9 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {capture_ingestion_warnings_enabled: false,capture_ingestion_warnings_kafka_queue_mib: 16,capture_ingestion_warnings_kafka_message_max_bytes: 1048576,+ capture_ingestion_warnings_kafka_topic: None,+ capture_ingestion_warnings_kafka_hosts: None,+ capture_ingestion_warnings_kafka_tls: None,});/// Build the per-sink env snapshot the v1 sink loader expects, with every@@ -244,6 +247,23 @@ impl ServerHandle {Self::for_config_with_sink_env(config, sink_env).await}+ /// Like `for_v1_topic`, with the synthetic ingestion warnings emitter+ /// enabled and pointed at its own topic via the emitter's dedicated config,+ /// so warning envelopes are readable independently of the events that+ /// triggered them.+ pub async fn for_v1_topic_with_warnings(+ topic: &EphemeralTopic,+ warnings_topic: &EphemeralTopic,+ ) -> Self {+ let mut config = DEFAULT_CONFIG.clone();+ config.capture_v1_sinks = "msk".to_string();+ config.capture_ingestion_warnings_enabled = true;+ config.capture_ingestion_warnings_kafka_topic =+ Some(warnings_topic.topic_name().to_string());+ let sink_env = v1_sink_env_for_topic("msk", topic.topic_name());+ Self::for_config_with_sink_env(config, sink_env).await+ }+/// Like `for_v1_topic`, with the AI-gateway signing secret configured so the/// provenance check runs.pub async fn for_v1_topic_with_signing_secret(topic: &EphemeralTopic, secret: &str) -> Self {diff --git a/rust/capture/tests/ingestion_warnings_integration.rs b/rust/capture/tests/ingestion_warnings_integration.rsnew file mode 100644index 000000000000..47b132e035c3--- /dev/null+++ b/rust/capture/tests/ingestion_warnings_integration.rs@@ -0,0 +1,83 @@+//! Integration coverage for the synthetic ingestion warnings emitter.+//!+//! Verifies the leg no other test covers: a real capture server booted with+//! `capture_ingestion_warnings_enabled`, a real Kafka producer built at+//! startup, and a `$$client_ingestion_warning` envelope landing on the+//! warnings topic in response to a validation drop. Every other warnings test+//! either hardcodes the flag false or points the producer at an unroutable+//! address, so producer construction, topic resolution, `build_warnings_kafka_config`,+//! and the delivery path are otherwise unexercised.+//!+//! The Kafka -> ClickHouse leg lives in+//! `nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.test.ts`. The+//! two are pinned to each other by `capture_envelope.fixture.json`: this test+//! asserts capture produces it, that one asserts the consumer accepts it.+//!+//! Requires Docker Kafka (same rig as the other integration tests).++#[path = "common/utils.rs"]+mod utils;+use utils::*;++use anyhow::Result;+use common_types::CapturedEvent;+use serde_json::Value;+use uuid::Uuid;++use capture::v1::analytics::types::Event;+use capture::v1::test_utils::{batch_payload, valid_event};++const TOKEN: &str = "phc_warnings_integration_token";++/// The cross-language envelope pin. See the fixture's own `_comment`.+const ENVELOPE_FIXTURE: &str =+ include_str!("../../common/ingestion_warnings/capture_envelope.fixture.json");++/// An event that fails validation with the `missing_event_name` tag.+fn nameless(distinct_id: &str) -> Event {+ let mut e = valid_event();+ e.uuid = Uuid::new_v4().to_string();+ e.distinct_id = distinct_id.to_string();+ e.event = String::new();+ e+}++#[tokio::test]+async fn v1_validation_drop_emits_warning_envelope_to_kafka() -> Result<()> {+ setup_tracing();+ let events_topic = EphemeralTopic::new().await;+ let warnings_topic = EphemeralTopic::new().await;+ let server = ServerHandle::for_v1_topic_with_warnings(&events_topic, &warnings_topic).await;++ // Both events drop under one warning type, which makes+ // `emit_validation_drop_warnings` omit the (then ambiguous) `distinctId`+ // and `eventUuid`, leaving details that are identical on every run and so+ // can be pinned by the fixture.+ let payload = batch_payload(&[nameless("warn-user-0"), nameless("warn-user-1")]);+ let res = server.capture_v1(TOKEN, payload).await;+ assert_eq!(+ res.status(),+ reqwest::StatusCode::OK,+ "an all-dropped batch is still accepted with per-event results"+ );++ let envelope: CapturedEvent = serde_json::from_value(warnings_topic.next_event()?)?;+ assert_eq!(envelope.event, "$$client_ingestion_warning");+ assert_eq!(envelope.token, TOKEN);+ assert_eq!(+ envelope.distinct_id, TOKEN,+ "distinct_id must be the token, never a caller-supplied value"+ );++ let inner: Value = serde_json::from_str(&envelope.data)?;+ let expected: Value = serde_json::from_str(ENVELOPE_FIXTURE)?;+ assert_eq!(inner["event"], expected["event"]);+ assert_eq!(+ inner["properties"], expected["properties"],+ "capture's envelope drifted from the fixture the Node consumer test replays"+ );++ events_topic.assert_empty();+ warnings_topic.assert_empty();+ Ok(())+}diff --git a/rust/common/ingestion_warnings/capture_envelope.fixture.json b/rust/common/ingestion_warnings/capture_envelope.fixture.jsonnew file mode 100644index 000000000000..e6e7eb7c56a9--- /dev/null+++ b/rust/common/ingestion_warnings/capture_envelope.fixture.json@@ -0,0 +1,15 @@+{+ "_comment": "Cross-language pin for the capture-produced ingestion warning envelope. Asserted against real capture output by rust/capture/tests/ingestion_warnings_integration.rs, and replayed as consumer input by nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.test.ts. Editing this by hand without changing both sides is the bug it exists to catch. Only the inner event's stable fields are pinned: uuid, timestamps, and the token vary per run, and distinctId/eventUuid are absent by construction because the fixture's batch drops two events under one type (see emit_validation_drop_warnings).",+ "event": "$$client_ingestion_warning",+ "properties": {+ "$$client_ingestion_warning_type": "missing_event_name",+ "$$client_ingestion_warning_source": "capture",+ "$$client_ingestion_warning_details": {+ "count": 2,+ "lib": "posthog-rs",+ "libVersion": "1.0.0",+ "path": "/i/v1/analytics/events",+ "pipelineStep": "capture_validation"+ }+ }+}diff --git a/rust/common/ingestion_warnings/src/lib.rs b/rust/common/ingestion_warnings/src/lib.rsindex 67f14cecfa95..e2e2038af635 100644--- a/rust/common/ingestion_warnings/src/lib.rs+++ b/rust/common/ingestion_warnings/src/lib.rs@@ -64,6 +64,18 @@ pub const INGESTION_WARNINGS_TOTAL: &str = "ingestion_warnings_total";/// on each sweep. The early-warning signal for the cardinality cap.pub const INGESTION_WARNINGS_THROTTLE_KEYS: &str = "ingestion_warnings_throttle_keys";+/// Gauge reporting whether a process that *wants* an emitter actually built+/// one: `1` healthy, `0` enabled-but-failed. Deliberately unset when warnings+/// are disabled, because otherwise a misconfigured pod reporting `0` would be+/// indistinguishable from an intentionally quiet one. Absence means "off",+/// `0` means "broken".+///+/// Emitter construction is one-shot (`create_threaded_kafka_producer` fetches+/// metadata once, with no retry), so a broker blip at boot mutes that process+/// for its entire life. The only other symptom is lower-than-expected warning+/// volume, which is unobservable without a baseline. Alert on `min() == 0`.+pub const INGESTION_WARNINGS_EMITTER_ENABLED: &str = "ingestion_warnings_emitter_enabled";+/// Identifies which service — and which code path within it — produced a/// warning.///