Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ingestion): consolidate warning registry into one generated arti… (#72712)

Zach Brown8e50c4db5e87
diff --git a/.agents/skills/adding-ingestion-warnings/SKILL.md b/.agents/skills/adding-ingestion-warnings/SKILL.md
index 7595c1fd7b87..1ce275ed964b 100644
--- a/.agents/skills/adding-ingestion-warnings/SKILL.md
+++ b/.agents/skills/adding-ingestion-warnings/SKILL.md
@@ -59,27 +59,42 @@ Instead they emit a synthetic `$$client_ingestion_warning` `CapturedEvent` onto
### 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:
+There is no hand-maintained Rust copy of the type list. A generator mirrors the **whole registry** — every type with its `category`, `severity`, and `captureProduced` flag — into a committed artifact the Rust build reads:
```text
-INGESTION_WARNING_TYPES (captureProduced: true) # nodejs — source of truth
+INGESTION_WARNING_TYPES (all entries) # 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
+ → rust/common/ingestion_warnings/warning_types.generated.json # committed
+ → build.rs → WarningType enum + ALL + as_str/category/severity/capture_produced
```
-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.
+**Every edit to `INGESTION_WARNING_TYPES` requires regenerating and committing the artifact** — not just capture-produced types. The nodejs no-drift test (`generate-ingestion-warning-types.test.ts`) fails CI whenever the committed artifact and the generator output diverge, including when a type you didn't add lands on master while your branch is in flight: rebase, regenerate, recommit.
+
+The artifact is committed _inside_ the Rust crate so the isolated Rust Docker/CI build context stays self-contained — no cross-workspace file reads. `captureProduced: true` marks the types capture may set via the structured envelope property: it derives the `CAPTURE_PRODUCED_WARNING_TYPES` trust allowlist the consumer enforces, and the Rust `from_tag_domain_equals_the_capture_trust_allowlist` test welds capture's hand-written `from_tag` allowlist to exactly that set — skew in either direction (flag without an arm, arm without the flag) silently drops warnings in production, so the test makes it a red CI run instead.
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.
+2. **Regenerate + commit the artifact** — run `pnpm --filter=@posthog/nodejs gen:ingestion-warning-types` and commit the updated `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 equality-weld test forces you to add the arm.
+
+### Team-aware Rust producers: the direct-row transport
+
+Services that know `team_id` (the personhog services) skip the envelope and produce the terminal v2 row straight to **`clickhouse_ingestion_warnings`** — the topic the v1/v2 ClickHouse tables consume and every nodejs emit path produces to — via the same builder's other terminal. Do not produce rows to the `$$client_ingestion_warning` events topic: its consumer allowlists by event name and silently drops anything that is not an envelope.
+
+```rust
+Warning::new(WarningType::MyNewType)
+ .with_detail("personId", uuid)
+ .with_detail("message", msg)
+ .into_row(team_id, "my-service")
+```
+
+`into_row` injects `teamId` and the registry's `category`/`severity` over the caller's details (they cannot be spoofed or forgotten), and stamps the ClickHouse-format timestamp. A direct-row type needs **no** `captureProduced` flag and no `from_tag` arm — register it, regenerate the artifact, and emit. See the module doc in `rust/common/ingestion_warnings/src/serializer.rs` for the envelope-vs-row correspondence table and the trust rationale (the envelope lane is attacker-writable, so the consumer stamps classification; the row topic is ACL-guarded, so the producer does).
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`.
+- **`source` identifies the producer** (`src/lib.rs`): a `WarningSource { service, path, pipeline_step }`. `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. `pipeline_step` is stamped into the envelope's details as `pipelineStep`. 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.
diff --git a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx
index b83627d319a2..09936c2c620d 100644
--- a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx
+++ b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx
@@ -32,6 +32,7 @@ export const WARNING_TYPE_TO_DESCRIPTION: Record<string, string> = {
event_timestamp_in_future: 'An event was sent more than 23 hours in the future',
ingestion_capacity_overflow: 'Event ingestion has overflowed capacity',
message_size_too_large: 'Discarded event exceeding 1MB limit',
+ person_properties_size_violation: 'Person properties exceeded the size limit and were trimmed or rejected',
replay_timestamp_invalid: 'Replay event timestamp is invalid',
replay_timestamp_too_far: 'Replay event timestamp was too far in the future',
replay_message_too_large: 'Replay data was dropped because it was too large to ingest',
diff --git a/nodejs/src/ingestion/common/ingestion-warning-types.ts b/nodejs/src/ingestion/common/ingestion-warning-types.ts
index 4eacef744e79..22a0f229a486 100644
--- a/nodejs/src/ingestion/common/ingestion-warning-types.ts
+++ b/nodejs/src/ingestion/common/ingestion-warning-types.ts
@@ -1,7 +1,9 @@
/**
* 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).
+ * Rust producers (the whole registry is exported to
+ * `rust/common/ingestion_warnings/warning_types.generated.json`, from which the
+ * Rust `WarningType` enum is generated).
*
* This module is intentionally dependency-free (pure data + types): it can be
* imported by the standalone generator (`bin/generate-ingestion-warning-types.mts`)
@@ -28,6 +30,8 @@ export type IngestionWarningSeverity = 'info' | 'warning' | 'error'
export const INGESTION_WARNING_TYPES = {
// Size limits — payload or property blobs exceeding Kafka/Postgres limits
message_size_too_large: { category: 'size', severity: 'error' },
+ // The personhog leader trimmed or rejected a person property update at
+ // admission to fit the Postgres size constraint.
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' },
@@ -41,10 +45,8 @@ export const INGESTION_WARNING_TYPES = {
// 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.
+ // `captureProduced: true` marks the types capture may set via the structured envelope property —
+ // it derives the CAPTURE_PRODUCED_WARNING_TYPES trust allowlist below.
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 },
@@ -90,7 +92,11 @@ export const INGESTION_WARNING_TYPES = {
message_timestamp_diff_too_large: { category: 'replay', severity: 'warning' },
} as const satisfies Record<
string,
- { category: IngestionWarningCategory; severity: IngestionWarningSeverity; captureProduced?: true }
+ {
+ category: IngestionWarningCategory
+ severity: IngestionWarningSeverity
+ captureProduced?: true
+ }
>
export type IngestionWarningType = keyof typeof INGESTION_WARNING_TYPES
@@ -106,8 +112,10 @@ export type IngestionWarningType = keyof typeof INGESTION_WARNING_TYPES
* 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.
+ * allowlist can never skew from the registry. The flag is also exported in the
+ * generated Rust artifact, where a test welds capture's `from_tag` emit
+ * allowlist to exactly this set — skew in either direction silently drops
+ * warnings (never emitted, or emitted and rejected here at the consumer).
*/
export const CAPTURE_PRODUCED_WARNING_TYPES: ReadonlySet<IngestionWarningType> = new Set(
(Object.entries(INGESTION_WARNING_TYPES) as [IngestionWarningType, { captureProduced?: boolean }][])
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.ts
index f5d26d833f97..221283dd1503 100644
--- a/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.test.ts
+++ b/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.test.ts
@@ -1,22 +1,35 @@
import fs from 'fs'
import { parseJSON } from '~/common/utils/json-parse'
-import { CAPTURE_PRODUCED_WARNING_TYPES } from '~/ingestion/common/ingestion-warning-types'
+import { CAPTURE_PRODUCED_WARNING_TYPES, INGESTION_WARNING_TYPES } from '~/ingestion/common/ingestion-warning-types'
import {
RUST_GENERATED_JSON_PATH,
- buildCaptureWarningTypesJson,
+ buildWarningTypesJson,
} from '~/ingestion/common/scripts/generate-ingestion-warning-types'
-describe('capture warning types codegen', () => {
+describe('warning types codegen', () => {
it('committed Rust artifact matches the generator output', () => {
const committed = fs.readFileSync(RUST_GENERATED_JSON_PATH, 'utf8')
- expect(committed).toEqual(buildCaptureWarningTypesJson())
+ expect(committed).toEqual(buildWarningTypesJson())
// 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())
+ it('artifact lists every registry type with its classification in stable sorted order', () => {
+ const { types } = parseJSON(fs.readFileSync(RUST_GENERATED_JSON_PATH, 'utf8')) as {
+ types: { type: string; category: string; severity: string; captureProduced: boolean }[]
+ }
+ expect(types.map((t) => t.type)).toEqual(Object.keys(INGESTION_WARNING_TYPES).sort())
+ for (const entry of types) {
+ expect(entry.category).toEqual(
+ INGESTION_WARNING_TYPES[entry.type as keyof typeof INGESTION_WARNING_TYPES].category
+ )
+ expect(entry.severity).toEqual(
+ INGESTION_WARNING_TYPES[entry.type as keyof typeof INGESTION_WARNING_TYPES].severity
+ )
+ expect(entry.captureProduced).toEqual(
+ CAPTURE_PRODUCED_WARNING_TYPES.has(entry.type as keyof typeof INGESTION_WARNING_TYPES)
+ )
+ }
})
})
diff --git a/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.ts b/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.ts
index 96415845c78c..989ef2d3764f 100644
--- a/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.ts
+++ b/nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.ts
@@ -1,14 +1,14 @@
import fs from 'fs'
import path from 'path'
-import { CAPTURE_PRODUCED_WARNING_TYPES } from '~/ingestion/common/ingestion-warning-types'
+import { CAPTURE_PRODUCED_WARNING_TYPES, INGESTION_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
+ * source of truth. This script mirrors the whole registry — every type with its category and
+ * severity — 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.
*
@@ -22,19 +22,29 @@ 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'
+ 'rust/common/ingestion_warnings/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.
+ * Canonical artifact contents: every registry type with its classification, in stable sorted order.
+ * Which producer emits which type is not registry data — Rust callers reference the variants they
+ * emit, and the message `source` field records who said it. The one exception is `captureProduced`:
+ * it is the consumer-side trust allowlist for the capture envelope, and it is exported so the Rust
+ * side can assert its `from_tag` emit allowlist stays exactly equal to it — skew in either
+ * direction silently drops warnings (never emitted, or emitted and rejected at the consumer).
*/
-export function buildCaptureWarningTypesJson(): string {
- const types = [...CAPTURE_PRODUCED_WARNING_TYPES].sort()
+export function buildWarningTypesJson(): string {
+ const types = (Object.keys(INGESTION_WARNING_TYPES) as (keyof typeof INGESTION_WARNING_TYPES)[])
+ .sort()
+ .map((type) => ({
+ type,
+ category: INGESTION_WARNING_TYPES[type].category,
+ severity: INGESTION_WARNING_TYPES[type].severity,
+ captureProduced: CAPTURE_PRODUCED_WARNING_TYPES.has(type),
+ }))
const artifact = {
_comment:
- 'GENERATED from INGESTION_WARNING_TYPES (captureProduced) in ' +
+ 'GENERATED from INGESTION_WARNING_TYPES 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.',
@@ -46,11 +56,8 @@ export function buildCaptureWarningTypesJson(): string {
}
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}`
- )
+ fs.writeFileSync(RUST_GENERATED_JSON_PATH, buildWarningTypesJson())
+ console.info(`Wrote ${Object.keys(INGESTION_WARNING_TYPES).length} warning types to ${RUST_GENERATED_JSON_PATH}`)
}
if (require.main === module) {
diff --git a/rust/common/ingestion_warnings/build.rs b/rust/common/ingestion_warnings/build.rs
index ef82818a1015..5d3645d4c983 100644
--- a/rust/common/ingestion_warnings/build.rs
+++ b/rust/common/ingestion_warnings/build.rs
@@ -1,12 +1,12 @@
-//! Codegen for the `WarningType` enum from `capture_warning_types.generated.json`.
+//! Codegen for the `WarningType` enum from `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
+//! That JSON mirrors the whole Node.js registry (the single source of truth,
+//! `nodejs/src/ingestion/common/ingestion-warning-types.ts`) via
//! `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.
+//! committed artifact keeps Rust's warning types — and their category/severity classification —
+//! 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).
use std::env;
use std::fs;
@@ -14,7 +14,7 @@ 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");
+ let json_path = Path::new(&manifest_dir).join("warning_types.generated.json");
// Rerun only when the mirrored artifact changes.
println!("cargo:rerun-if-changed={}", json_path.display());
@@ -23,39 +23,54 @@ fn main() {
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
+ let entries: Vec<(String, String, String, bool)> = 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()
+ let get = |k: &str| {
+ v.get(k)
+ .and_then(|s| s.as_str())
+ .unwrap_or_else(|| panic!("`{k}` missing in {}", json_path.display()))
+ .to_string()
+ };
+ let capture_produced = v
+ .get("captureProduced")
+ .and_then(|b| b.as_bool())
+ .unwrap_or_else(|| panic!("`captureProduced` missing in {}", json_path.display()));
+ (
+ get("type"),
+ get("category"),
+ get("severity"),
+ capture_produced,
+ )
})
.collect();
assert!(
- !tags.is_empty(),
- "capture warning types artifact {} is empty",
+ !entries.is_empty(),
+ "warning types artifact {} is empty",
json_path.display()
);
- let variants: Vec<String> = tags.iter().map(|tag| to_pascal_case(tag)).collect();
+ let variants: Vec<String> = entries
+ .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("// @generated by build.rs from 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, together with each type's declared\n");
code.push_str(
- "/// Generated from the Node.js registry (`captureProduced` types). Every variant's\n",
+ "/// category and severity. Every variant's `as_str()` doubles as the produced\n",
);
code.push_str(
- "/// `as_str()` doubles as the produced message `type` field and the `type` metric\n",
+ "/// message `type` field and the `type` metric label, so the values must stay\n",
);
- code.push_str("/// label, so the values must stay stable.\n");
+ code.push_str("/// stable.\n");
code.push_str("#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n");
code.push_str("pub enum WarningType {\n");
for variant in &variants {
@@ -79,14 +94,46 @@ fn main() {
);
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()) {
+ for (variant, (tag, _, _, _)) in variants.iter().zip(entries.iter()) {
code.push_str(&format!(
" WarningType::{variant} => \"{tag}\",\n"
));
}
- code.push_str(" }\n");
- code.push_str(" }\n");
- code.push_str("}\n");
+ code.push_str(" }\n }\n\n");
+
+ code.push_str(" /// The registry-declared category. Producers that serialize the final\n");
+ code.push_str(" /// warning payload themselves stamp this into `details`.\n");
+ code.push_str(" pub const fn category(self) -> &'static str {\n");
+ code.push_str(" match self {\n");
+ for (variant, (_, category, _, _)) in variants.iter().zip(entries.iter()) {
+ code.push_str(&format!(
+ " WarningType::{variant} => \"{category}\",\n"
+ ));
+ }
+ code.push_str(" }\n }\n\n");
+
+ code.push_str(" /// The registry-declared severity. Producers that serialize the final\n");
+ code.push_str(" /// warning payload themselves stamp this into `details`.\n");
+ code.push_str(" pub const fn severity(self) -> &'static str {\n");
+ code.push_str(" match self {\n");
+ for (variant, (_, _, severity, _)) in variants.iter().zip(entries.iter()) {
+ code.push_str(&format!(
+ " WarningType::{variant} => \"{severity}\",\n"
+ ));
+ }
+ code.push_str(" }\n }\n\n");
+
+ code.push_str(" /// Whether the Node consumer's trust allowlist for the capture envelope\n");
+ code.push_str(" /// (`CAPTURE_PRODUCED_WARNING_TYPES`) contains this type. The registry\n");
+ code.push_str(" /// test welds capture's `from_tag` emit allowlist to exactly this set.\n");
+ code.push_str(" pub const fn capture_produced(self) -> bool {\n");
+ code.push_str(" match self {\n");
+ for (variant, (_, _, _, capture_produced)) in variants.iter().zip(entries.iter()) {
+ code.push_str(&format!(
+ " WarningType::{variant} => {capture_produced},\n"
+ ));
+ }
+ code.push_str(" }\n }\n}\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");
diff --git a/rust/common/ingestion_warnings/capture_warning_types.generated.json b/rust/common/ingestion_warnings/capture_warning_types.generated.json
deleted file mode 100644
index fbcb37ae1534..000000000000
--- a/rust/common/ingestion_warnings/capture_warning_types.generated.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "_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.rs
index 826a8d8434d8..67f14cecfa95 100644
--- a/rust/common/ingestion_warnings/src/lib.rs
+++ b/rust/common/ingestion_warnings/src/lib.rs
@@ -1,13 +1,20 @@
//! 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.
+//! Two transports share the registry ([`WarningType`], generated from the
+//! Node.js source of truth) and one builder ([`serializer::Warning`]):
+//! services that only know API tokens (capture) commit via
+//! [`serializer::Warning::into_event_envelope`], and services that know `team_id`
+//! (personhog leader/writer) commit the terminal row via
+//! [`serializer::Warning::into_row`]. See `serializer.rs` for the
+//! field-by-field correspondence and the trust rationale.
+//!
+//! Envelope producers 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
@@ -32,7 +39,6 @@ pub mod throttle;
use std::time::Duration;
-use chrono::Utc;
use common_kafka::kafka_producer::ThreadedKafkaContext;
use metrics::{counter, gauge};
use rdkafka::error::KafkaError;
@@ -65,17 +71,22 @@ pub const INGESTION_WARNINGS_THROTTLE_KEYS: &str = "ingestion_warnings_throttle_
/// `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.
+/// without inflating the message schema; `pipeline_step` is stamped into the
+/// warning's details as `pipelineStep` — a producer-declared value, since
+/// which stage a warning comes from is a property of the emit site, not of
+/// the warning type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WarningSource {
pub service: &'static str,
pub path: &'static str,
+ pub pipeline_step: &'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",
+ pipeline_step: "capture_validation",
};
/// Sink-agnostic emitter seam. The Kafka implementation is
@@ -177,15 +188,13 @@ impl WarningEmitter for KafkaWarningEmitter {
}
}
- 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 serialized = serializer::Warning::new(warning)
+ .with_details(extra_details)
+ .with_count(count)
+ .into_event_envelope(&token, source)
+ .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)),
diff --git a/rust/common/ingestion_warnings/src/registry.rs b/rust/common/ingestion_warnings/src/registry.rs
index 440a94b601a5..f56f4b643338 100644
--- a/rust/common/ingestion_warnings/src/registry.rs
+++ b/rust/common/ingestion_warnings/src/registry.rs
@@ -1,20 +1,27 @@
//! 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.
+//! The `WarningType` enum — every registered type with its `as_str()` tag and
+//! registry-declared `category()`/`severity()` — is generated at build time (see
+//! `build.rs`) from `warning_types.generated.json`, which mirrors the whole
+//! Node.js registry, the single source of truth for the warning taxonomy
+//! (`nodejs/src/ingestion/common/ingestion-warning-types.ts`). The taxonomy is
+//! producer-agnostic: which service emits which type is not registry data — each
+//! producer references the variants it emits, and the message's `source` field
+//! records who said it.
//!
//! `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.
+//! 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
+//! allowlist's domain is welded by test to the registry's `captureProduced`
+//! flags — the Node consumer's trust allowlist for the capture envelope —
+//! since skew in either direction silently drops warnings: a flagged type
+//! without an arm is never emitted, and an arm without the flag is emitted
+//! but rejected at the consumer. An arm for a type removed from the registry
+//! stops compiling.
-// Brings in `pub enum WarningType`, `WarningType::ALL`, and `WarningType::as_str`.
+// Brings in `pub enum WarningType` with `ALL`, `as_str`, `category`, and
+// `severity`.
include!(concat!(env!("OUT_DIR"), "/warning_types.rs"));
impl WarningType {
@@ -38,12 +45,6 @@ impl WarningType {
_ => 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)]
@@ -52,14 +53,21 @@ mod tests {
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.
+ fn from_tag_domain_equals_the_capture_trust_allowlist() {
+ // Two hand-maintained copies of "the types capture emits" must stay
+ // equal: the `from_tag` arms here (the emit allowlist) and the
+ // registry's `captureProduced` flags (the Node consumer's trust
+ // allowlist, carried through the artifact). Skew fails silently in
+ // production in either direction — a flagged type without an arm is
+ // never emitted; an arm without the flag is emitted and then
+ // rejected at the consumer's trust check. Comparing the variant
+ // itself (not just presence) also pins each arm to the right type,
+ // so a mis-mapped tag can't hide behind an unrelated `Some`.
for warning in WarningType::ALL {
assert_eq!(
WarningType::from_tag(warning.as_str()),
- Some(warning),
- "tag {} must round-trip",
+ warning.capture_produced().then_some(warning),
+ "{}: from_tag arm and captureProduced flag disagree — add the missing side",
warning.as_str()
);
}
diff --git a/rust/common/ingestion_warnings/src/serializer.rs b/rust/common/ingestion_warnings/src/serializer.rs
index 50ca7cc6f7fd..8d6ea9fc50bf 100644
--- a/rust/common/ingestion_warnings/src/serializer.rs
+++ b/rust/common/ingestion_warnings/src/serializer.rs
@@ -1,14 +1,27 @@
-//! Builds the ingestion-warning event envelope shared by every Rust producer.
+//! Serialization of ingestion warnings, for both transports.
//!
-//! 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.
+//! A [`Warning`] is a registered type plus caller details; committing it to a
+//! transport is a terminal call. The two transports produce deliberately
+//! different payloads for different pipeline stages:
+//!
+//! | | [`Warning::into_event_envelope`] (capture) | [`Warning::into_row`] (team-aware services) |
+//! |---|---|---|
+//! | Output | `$$client_ingestion_warning` [`CapturedEvent`] | terminal v2 row JSON |
+//! | Lane | public event stream (attacker-writable namespace) | ACL-guarded warnings topic |
+//! | Addressing | API token (consumer resolves the team) | `team_id` |
+//! | Classification | absent — the Node consumer re-judges the message (trust allowlist, consumer-stamped category/severity) | producer-stamped from the registry |
+//! | Injected details | `count`, the source's `pipelineStep` | `teamId`, `category`, `severity`, the source's `pipelineStep` |
+//! | Timestamp | RFC 3339 envelope fields | ClickHouse-format `timestamp` field |
+//!
+//! The asymmetry is the security design, enforced by the type: classification
+//! exists only inside `into_row`, so an envelope carrying classification or a
+//! row missing it is unrepresentable. Anything arriving on the event lane is
+//! indistinguishable from a client-forged event (the envelope's event name and
+//! properties are writable by any token holder), so the consumer is
+//! authoritative there (see
+//! `nodejs/src/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step.ts`);
+//! rows are trusted by transport. Routing the envelope through that consumer
+//! also means capture never needs database access or token→team resolution.
//!
//! The envelope's top-level `distinct_id` is deliberately the token, never the
//! offending event's distinct_id: the consumer's metadata validation drops
@@ -19,7 +32,7 @@
use std::collections::HashMap;
-use chrono::{DateTime, SecondsFormat, Utc};
+use chrono::{SecondsFormat, Utc};
use common_types::{CapturedEvent, RawEvent};
use serde_json::{json, Map, Value};
use uuid::Uuid;
@@ -40,58 +53,127 @@ 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.
+/// One warning, before it is committed to a transport.
///
-/// `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,
+/// Details carry caller context with camelCase keys (`distinctId`,
+/// `eventUuid`, `personId`, `message`, ...) — identifiers and sizes, never
+/// raw payload content: details are user-visible. Keys a transport injects
+/// are inserted after the caller's, so caller details can never override
+/// them. If direct-row producers multiply, the natural extension is an
+/// additive `details(&impl Serialize)` overload with closed per-warning
+/// structs at the callers; today's caller population doesn't warrant it.
+pub struct Warning {
warning: WarningType,
- mut extra_details: Map<String, Value>,
+ 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,
- })
+}
+
+impl Warning {
+ pub fn new(warning: WarningType) -> Self {
+ Self {
+ warning,
+ details: Map::new(),
+ count: 1,
+ }
+ }
+
+ pub fn with_detail(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
+ self.details.insert(key.into(), value.into());
+ self
+ }
+
+ /// Extend details from a map (colliding keys are overwritten by `details`).
+ pub fn with_details(mut self, details: Map<String, Value>) -> Self {
+ self.details.extend(details);
+ self
+ }
+
+ /// Number of occurrences this warning represents after per-batch dedup.
+ /// Only the envelope transport carries it; defaults to 1.
+ pub fn with_count(mut self, count: u64) -> Self {
+ self.count = count;
+ self
+ }
+
+ /// Commit to the event-envelope transport: a `$$client_ingestion_warning`
+ /// [`CapturedEvent`] for the public event lane, keyed by API token.
+ ///
+ /// Carries no classification: the Node consumer resolves the token to a
+ /// team, applies the capture trust allowlist to the structured type, and
+ /// stamps category/severity from its own registry — nothing arriving on
+ /// this lane is believed about itself. Injects `count` (batch dedup) and
+ /// the source's `pipelineStep` into details.
+ pub fn into_event_envelope(
+ self,
+ token: &str,
+ source: WarningSource,
+ ) -> Result<CapturedEvent, serde_json::Error> {
+ let timestamp = Utc::now();
+ let mut details = self.details;
+ details.insert("count".to_string(), json!(self.count));
+ // The consumer lifts `pipelineStep` out of details into the warning's
+ // top-level pipeline_step column, so it must live inside details here.
+ details.insert("pipelineStep".to_string(), json!(source.pipeline_step));
+
+ let mut properties: HashMap<String, Value> = HashMap::new();
+ properties.insert(PROP_TYPE.to_string(), json!(self.warning.as_str()));
+ properties.insert(PROP_SOURCE.to_string(), json!(source.service));
+ properties.insert(PROP_DETAILS.to_string(), Value::Object(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,
+ })
+ }
+
+ /// Commit to the direct-row transport: the terminal v2 warning row for
+ /// the ACL-guarded warnings topic, addressed by `team_id`.
+ ///
+ /// Classification is producer-stamped here — the registry's
+ /// `category()`/`severity()`, the row's own `teamId`, and the source's
+ /// `pipelineStep` (which the v2 table materializes its `pipeline_step`
+ /// column from) are inserted over the caller's details so a stray key
+ /// can never override them or disagree with the addressing — and the
+ /// `timestamp` uses the ClickHouse format the v2 table materializes
+ /// columns from.
+ pub fn into_row(self, team_id: i64, source: WarningSource) -> Value {
+ let mut details = self.details;
+ details.insert("teamId".to_string(), Value::from(team_id));
+ details.insert("category".to_string(), Value::from(self.warning.category()));
+ details.insert("severity".to_string(), Value::from(self.warning.severity()));
+ details.insert("pipelineStep".to_string(), json!(source.pipeline_step));
+ let details = Value::Object(details);
+ json!({
+ "team_id": team_id,
+ "type": self.warning.as_str(),
+ "source": source.service,
+ "details": details.to_string(),
+ "timestamp": Utc::now().format("%Y-%m-%d %H:%M:%S%.3f").to_string(),
+ })
+ }
}
#[cfg(test)]
@@ -109,15 +191,9 @@ mod tests {
#[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();
+ let event = Warning::new(WarningType::MissingEventName)
+ .into_event_envelope("phc_test_token", CAPTURE_V1_ANALYTICS)
+ .unwrap();
assert_eq!(event.event, "$$client_ingestion_warning");
assert_eq!(event.token, "phc_test_token");
@@ -126,30 +202,27 @@ mod tests {
}
#[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();
+ fn envelope_properties_carry_the_structured_type_source_and_details() {
+ let event = Warning::new(WarningType::MissingEventName)
+ .with_detail("distinctId", "user-1")
+ .with_detail("lib", "posthog-js")
+ .with_count(3)
+ .into_event_envelope("phc_test_token", CAPTURE_V1_ANALYTICS)
+ .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.
+ // Injected by the envelope terminal.
assert_eq!(details["count"], 3);
assert_eq!(details["pipelineStep"], "capture_validation");
- // Caller context passes through untouched.
+ // Caller context passes through untouched — and no classification:
+ // the consumer stamps category/severity itself.
assert_eq!(details["distinctId"], "user-1");
assert_eq!(details["lib"], "posthog-js");
+ assert!(details.get("category").is_none());
+ assert!(details.get("severity").is_none());
}
/// The offending distinct_id lives in `details` only; the envelope's
@@ -158,17 +231,10 @@ mod tests {
#[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();
+ let event = Warning::new(WarningType::DistinctIdTooLarge)
+ .with_detail("distinctId", huge)
+ .into_event_envelope("phc_real", CAPTURE_V1_ANALYTICS)
+ .unwrap();
assert_eq!(event.distinct_id, "phc_real");
let (_, details) = parse_envelope(&event);
@@ -177,23 +243,61 @@ mod tests {
/// 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.
+ /// the envelope for reuse by other Rust services.
#[test]
- fn source_field_reflects_the_caller_supplied_source() {
+ fn envelope_source_field_reflects_the_caller_supplied_source() {
let other = WarningSource {
service: "batch_import",
path: "some_path",
+ pipeline_step: "batch_import_validation",
};
- let event = build_warning_event(
- "phc_test_token",
- other,
- WarningType::EmptyBatch,
- Map::new(),
- 1,
- Utc::now(),
- )
- .unwrap();
- let (raw, _) = parse_envelope(&event);
+ let event = Warning::new(WarningType::EmptyBatch)
+ .into_event_envelope("phc_test_token", other)
+ .unwrap();
+ let (raw, details) = parse_envelope(&event);
assert_eq!(raw["properties"][PROP_SOURCE], "batch_import");
+ assert_eq!(details["pipelineStep"], "batch_import_validation");
+ }
+
+ const TEST_ROW_SOURCE: WarningSource = WarningSource {
+ service: "personhog-test",
+ path: "test_path",
+ pipeline_step: "personhog_test_step",
+ };
+
+ #[test]
+ fn rows_carry_registry_types_and_classifications() {
+ for warning in WarningType::ALL {
+ let payload = Warning::new(warning)
+ .with_detail("personId", "uuid-ish")
+ .into_row(7, TEST_ROW_SOURCE);
+
+ assert_eq!(payload["team_id"], 7);
+ assert_eq!(payload["type"], warning.as_str());
+ assert_eq!(payload["source"], "personhog-test");
+ let details: Value =
+ serde_json::from_str(payload["details"].as_str().unwrap()).unwrap();
+ assert_eq!(details["category"], warning.category());
+ assert_eq!(details["severity"], warning.severity());
+ assert_eq!(details["teamId"], 7, "teamId is injected from addressing");
+ assert_eq!(details["pipelineStep"], "personhog_test_step");
+ assert_eq!(details["personId"], "uuid-ish");
+ let timestamp = payload["timestamp"].as_str().unwrap();
+ assert_eq!(timestamp.len(), 23);
+ assert_eq!(timestamp.as_bytes()[10], b' ');
+ }
+ }
+
+ #[test]
+ fn row_injected_keys_cannot_be_overridden_by_caller_details() {
+ let payload = Warning::new(WarningType::PersonPropertiesSizeViolation)
+ .with_detail("category", "spoofed")
+ .with_detail("teamId", 999)
+ .with_detail("pipelineStep", "spoofed")
+ .into_row(1, TEST_ROW_SOURCE);
+ let details: Value = serde_json::from_str(payload["details"].as_str().unwrap()).unwrap();
+ assert_eq!(details["category"], "size");
+ assert_eq!(details["teamId"], 1);
+ assert_eq!(details["pipelineStep"], "personhog_test_step");
}
}
diff --git a/rust/common/ingestion_warnings/warning_types.generated.json b/rust/common/ingestion_warnings/warning_types.generated.json
new file mode 100644
index 000000000000..0f0837f2cd22
--- /dev/null
+++ b/rust/common/ingestion_warnings/warning_types.generated.json
@@ -0,0 +1,257 @@
+{
+ "_comment": "GENERATED from INGESTION_WARNING_TYPES 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": [
+ {
+ "type": "cannot_merge_already_identified",
+ "category": "merge",
+ "severity": "warning",
+ "captureProduced": false
+ },
+ {
+ "type": "cannot_merge_with_illegal_distinct_id",
+ "category": "merge",
+ "severity": "warning",
+ "captureProduced": false
+ },
+ {
+ "type": "client_ingestion_warning",
+ "category": "event",
+ "severity": "info",
+ "captureProduced": false
+ },
+ {
+ "type": "cookieless_missing_host",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "cookieless_missing_ip",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "cookieless_missing_timestamp",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "cookieless_missing_user_agent",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "cookieless_timestamp_out_of_range",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "distinct_id_too_large",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "duplicate_event_uuid",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "empty_batch",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "error_tracking_exception_processing_errors",
+ "category": "event",
+ "severity": "warning",
+ "captureProduced": false
+ },
+ {
+ "type": "event_dropped_by_transformation",
+ "category": "transformation",
+ "severity": "info",
+ "captureProduced": false
+ },
+ {
+ "type": "event_dropped_too_old",
+ "category": "event",
+ "severity": "info",
+ "captureProduced": false
+ },
+ {
+ "type": "event_name_too_long",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "group_key_too_long",
+ "category": "size",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "group_upsert_message_size_too_large",
+ "category": "size",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "ignored_invalid_timestamp",
+ "category": "event",
+ "severity": "warning",
+ "captureProduced": false
+ },
+ {
+ "type": "invalid_ai_token_property",
+ "category": "event",
+ "severity": "warning",
+ "captureProduced": false
+ },
+ {
+ "type": "invalid_batch",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "invalid_event_timestamp",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "invalid_event_uuid",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "invalid_event_when_process_person_profile_is_false",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "invalid_group_set",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "invalid_heatmap_data",
+ "category": "event",
+ "severity": "warning",
+ "captureProduced": false
+ },
+ {
+ "type": "invalid_options",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "invalid_process_person_profile",
+ "category": "event",
+ "severity": "warning",
+ "captureProduced": false
+ },
+ {
+ "type": "malformed_event_properties",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "merge_race_condition",
+ "category": "merge",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "message_contained_no_valid_rrweb_events",
+ "category": "replay",
+ "severity": "warning",
+ "captureProduced": false
+ },
+ {
+ "type": "message_size_too_large",
+ "category": "size",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "message_timestamp_diff_too_large",
+ "category": "replay",
+ "severity": "warning",
+ "captureProduced": false
+ },
+ {
+ "type": "missing_distinct_id",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "missing_event_name",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "missing_event_uuid",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": true
+ },
+ {
+ "type": "person_properties_size_violation",
+ "category": "size",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "person_upsert_message_size_too_large",
+ "category": "size",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "rejecting_heatmap_data_with_invalid_items",
+ "category": "event",
+ "severity": "warning",
+ "captureProduced": false
+ },
+ {
+ "type": "rejecting_heatmap_data_with_invalid_url",
+ "category": "event",
+ "severity": "warning",
+ "captureProduced": false
+ },
+ {
+ "type": "replay_lib_version_too_old",
+ "category": "replay",
+ "severity": "info",
+ "captureProduced": false
+ },
+ {
+ "type": "schema_validation_failed",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": false
+ },
+ {
+ "type": "skipping_event_invalid_distinct_id",
+ "category": "event",
+ "severity": "error",
+ "captureProduced": false
+ }
+ ]
+}