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(capture): parse v1 event options leniently (#108097)

Eli Reisman5fdc200fcef3
diff --git a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md
index ae31451d6a48..9de962a5e2a8 100644
--- a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md
+++ b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md
@@ -58,21 +58,22 @@ Those decisions come only from this skill's guidance and your own reasoning.
### Event validation (`event`)
-| Type | What happened | Fix |
-| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `client_ingestion_warning` | The SDK itself reported a problem | Read `details.message` — the SDK wrote the diagnosis at the moment it caught the misuse (e.g. an invalid group key). Never debounced (like `merge_race_condition`), so counts are true counts; group by message and map each back to the misused SDK call |
-| `ignored_invalid_timestamp` | `timestamp` didn't parse; the event was kept with the server time | Read [references/fixing-ignored-invalid-timestamp.md](references/fixing-ignored-invalid-timestamp.md) — send ISO 8601; the event was kept at server time |
-| `schema_validation_failed` | Event dropped: it violates a schema the team enforces for that event | Compare `details.errors` against the payload; align the code or update the schema |
-| `skipping_event_invalid_distinct_id` | Event dropped: distinct ID over 400 chars | Read [references/fixing-invalid-distinct-ids.md](references/fixing-invalid-distinct-ids.md) — a token/payload was passed as the distinct ID |
-| `distinct_id_truncated` | Event ingested after its distinct ID was shortened to the 200-char cap (legacy capture endpoints) | Read [references/fixing-invalid-distinct-ids.md](references/fixing-invalid-distinct-ids.md) — a token/payload was passed as the distinct ID; `details.distinctIdLength` is the original length, and events land under the shortened ID until the sender is fixed |
-| `invalid_ai_token_property` | An `$ai_*` token property wasn't numeric; it was nulled | Read [references/fixing-invalid-ai-token-property.md](references/fixing-invalid-ai-token-property.md) — token counts must be plain numbers |
-| `invalid_group_set` | `$groupidentify` dropped: `$group_set` wasn't a plain object (a string, number, boolean, or array was sent) | `details.receivedType` names what was sent — `string` usually means the caller JSON-stringified the group properties before passing them; pass a plain object to the SDK's `groupIdentify` call. Omitting `$group_set` is fine (group upserts with no property changes) |
-| `invalid_process_person_profile` | `$process_person_profile` wasn't boolean; the default (true) was used | Read [references/fixing-process-person-profile-warnings.md](references/fixing-process-person-profile-warnings.md) — a stringified boolean silently opts back into person processing |
-| `invalid_event_when_process_person_profile_is_false` | `$identify`/`$create_alias`/`$merge_dangerously`/`$groupidentify` dropped because the event disabled person processing | Read [references/fixing-process-person-profile-warnings.md](references/fixing-process-person-profile-warnings.md) — identity events require person processing |
-| `event_dropped_person_processing_disabled` | Intentional: person processing is off for the project, so `$identify`/`$create_alias`/`$merge_dangerously`/`$groupidentify` are dropped | Read [references/fixing-process-person-profile-warnings.md](references/fixing-process-person-profile-warnings.md) — no payload fix exists; drop the identity calls or ask staff to re-enable person processing |
-| `event_dropped_too_old` | Intentional: the event is older than the team's configured drop threshold | Read [references/fixing-event-dropped-too-old.md](references/fixing-event-dropped-too-old.md) — mind mobile SDKs: offline queues legitimately deliver days-old events; threshold changes are the user's call |
-| `cookieless_missing_timestamp` / `cookieless_timestamp_out_of_range` / `cookieless_missing_user_agent` / `cookieless_missing_ip` / `cookieless_missing_host` | Cookieless-mode event dropped: a field required to compute the cookieless ID was missing or invalid | Read [references/fixing-cookieless-warnings.md](references/fixing-cookieless-warnings.md) — the missing field identifies the broken layer; beware the silent variant where a server relay omits $ip and users collapse onto the server's IP |
-| `cookieless_team_disabled` | Cookieless-mode event dropped: the SDK sent it in cookieless mode but cookieless tracking is off in the project settings | Read [references/fixing-cookieless-warnings.md](references/fixing-cookieless-warnings.md) — enable Settings → Web analytics → Cookieless tracking, or remove `cookieless_mode` from the SDK config; no code fix needed |
+| Type | What happened | Fix |
+| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `client_ingestion_warning` | The SDK itself reported a problem | Read `details.message` — the SDK wrote the diagnosis at the moment it caught the misuse (e.g. an invalid group key). Never debounced (like `merge_race_condition`), so counts are true counts; group by message and map each back to the misused SDK call |
+| `ignored_invalid_timestamp` | `timestamp` didn't parse; the event was kept with the server time | Read [references/fixing-ignored-invalid-timestamp.md](references/fixing-ignored-invalid-timestamp.md) — send ISO 8601; the event was kept at server time |
+| `schema_validation_failed` | Event dropped: it violates a schema the team enforces for that event | Compare `details.errors` against the payload; align the code or update the schema |
+| `skipping_event_invalid_distinct_id` | Event dropped: distinct ID over 400 chars | Read [references/fixing-invalid-distinct-ids.md](references/fixing-invalid-distinct-ids.md) — a token/payload was passed as the distinct ID |
+| `distinct_id_truncated` | Event ingested after its distinct ID was shortened to the 200-char cap (legacy capture endpoints) | Read [references/fixing-invalid-distinct-ids.md](references/fixing-invalid-distinct-ids.md) — a token/payload was passed as the distinct ID; `details.distinctIdLength` is the original length, and events land under the shortened ID until the sender is fixed |
+| `invalid_ai_token_property` | An `$ai_*` token property wasn't numeric; it was nulled | Read [references/fixing-invalid-ai-token-property.md](references/fixing-invalid-ai-token-property.md) — token counts must be plain numbers |
+| `invalid_group_set` | `$groupidentify` dropped: `$group_set` wasn't a plain object (a string, number, boolean, or array was sent) | `details.receivedType` names what was sent — `string` usually means the caller JSON-stringified the group properties before passing them; pass a plain object to the SDK's `groupIdentify` call. Omitting `$group_set` is fine (group upserts with no property changes) |
+| `invalid_process_person_profile` | `$process_person_profile` wasn't boolean; the default (true) was used | Read [references/fixing-process-person-profile-warnings.md](references/fixing-process-person-profile-warnings.md) — a stringified boolean silently opts back into person processing |
+| `invalid_event_when_process_person_profile_is_false` | `$identify`/`$create_alias`/`$merge_dangerously`/`$groupidentify` dropped because the event disabled person processing | Read [references/fixing-process-person-profile-warnings.md](references/fixing-process-person-profile-warnings.md) — identity events require person processing |
+| `event_dropped_person_processing_disabled` | Intentional: person processing is off for the project, so `$identify`/`$create_alias`/`$merge_dangerously`/`$groupidentify` are dropped | Read [references/fixing-process-person-profile-warnings.md](references/fixing-process-person-profile-warnings.md) — no payload fix exists; drop the identity calls or ask staff to re-enable person processing |
+| `event_dropped_too_old` | Intentional: the event is older than the team's configured drop threshold | Read [references/fixing-event-dropped-too-old.md](references/fixing-event-dropped-too-old.md) — mind mobile SDKs: offline queues legitimately deliver days-old events; threshold changes are the user's call |
+| `cookieless_missing_timestamp` / `cookieless_timestamp_out_of_range` / `cookieless_missing_user_agent` / `cookieless_missing_ip` / `cookieless_missing_host` | Cookieless-mode event dropped: a field required to compute the cookieless ID was missing or invalid | Read [references/fixing-cookieless-warnings.md](references/fixing-cookieless-warnings.md) — the missing field identifies the broken layer; beware the silent variant where a server relay omits $ip and users collapse onto the server's IP |
+| `cookieless_team_disabled` | Cookieless-mode event dropped: the SDK sent it in cookieless mode but cookieless tracking is off in the project settings | Read [references/fixing-cookieless-warnings.md](references/fixing-cookieless-warnings.md) — enable Settings → Web analytics → Cookieless tracking, or remove `cookieless_mode` from the SDK config; no code fix needed |
+| `invalid_options` | Event dropped by a capture v1 endpoint (`/i/v1/analytics/events`, `/i/v1/ai/events`): an event option had a value PostHog couldn't read | `details.invalidOptions` (when present) names the failed options. Send `process_person_profile`, `cookieless_mode` and `disable_skew_correction` as booleans (common forms such as `"false"`, `"no"`, `"off"` or `0` also work) and `product_tour_id` as a non-empty string (an integer also works) |
### LLM analytics endpoints (`event`)
diff --git a/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-process-person-profile-warnings.md b/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-process-person-profile-warnings.md
index c5916b1485bc..c04975cf68d4 100644
--- a/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-process-person-profile-warnings.md
+++ b/products/ingestion/skills/resolving-ingestion-warnings/references/fixing-process-person-profile-warnings.md
@@ -12,6 +12,10 @@ All three are silent from the SDK's side. The first quietly opts you back **into
Check the third before diagnosing a payload: if `event_dropped_person_processing_disabled` is the type, no SDK change will bring the events back, because the drop is the configured outcome of the project's person processing opt-out.
+On the capture v1 endpoints (`/i/v1/analytics/events`, `/i/v1/ai/events`), the flag is the `process_person_profile` event option, and SDKs move the legacy property into it.
+PostHog converts common forms of the option (`"false"`, `"no"`, `0`), so `invalid_process_person_profile` does not fire for it. A value PostHog can't read drops the event with `invalid_options` instead.
+Some SDKs convert the property themselves before sending and silently drop forms they don't recognize, such as `"no"`, which leaves person processing on. Send a real boolean.
+
## Diagnose
1. Query the warnings with `posthog:execute-sql`: `SELECT timestamp, details FROM system.ingestion_warnings WHERE type IN ('invalid_process_person_profile', 'invalid_event_when_process_person_profile_is_false', 'event_dropped_person_processing_disabled') AND timestamp > now() - INTERVAL 7 DAY ORDER BY timestamp DESC LIMIT 20` (narrow to a single `type` to isolate one variant). For the non-boolean variant, the `details` JSON shows the exact value received — its type names the bug (`"false"` = stringified config/env value, `0` = numeric flag). For the dropped variant, the `details` show which identity event was dropped and for which distinct IDs.
diff --git a/rust/capture/src/v1/analytics/constants.rs b/rust/capture/src/v1/analytics/constants.rs
index fc39b3768712..d68c546d3864 100644
--- a/rust/capture/src/v1/analytics/constants.rs
+++ b/rust/capture/src/v1/analytics/constants.rs
@@ -74,7 +74,7 @@ pub(super) const DETAIL_NON_HISTORICAL_DROP: &str = "non_historical_import_drop"
/// on the AI lane. Same tag as the `misrouted_event` ingestion warning it emits.
pub(super) const DETAIL_MISROUTED_EVENT: &str = "misrouted_event";
-/// Detail tag for events dropped due to uncoercible options fields.
+/// Detail tag for events dropped because an expected option's value is unreadable.
pub(super) const DETAIL_INVALID_OPTIONS: &str = "invalid_options";
/// Detail tag for AI-lane events dropped because the project is over its
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rs
index 6ff1c34708f1..7fb74c6e58a2 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -1,5 +1,6 @@
use std::collections::{HashMap, HashSet};
-use std::sync::Arc;
+use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
+use std::sync::{Arc, LazyLock};
use std::time::Instant;
use chrono::{DateTime, Utc};
@@ -12,12 +13,11 @@ use super::constants::{
CAPTURE_V1_EVENT_ADJUSTMENTS_APPLIED, CAPTURE_V1_MAX_EVENT_NAME_LENGTH,
CAPTURE_V1_OVERFLOW_ROUTED, CAPTURE_V1_PARSED_EVENTS, CAPTURE_V1_PROCESSING_DURATION_SECONDS,
CAPTURE_V1_RATE_LIMITER, DETAIL_AI_BYTE_RATE_LIMITED, DETAIL_AI_EVENT_TOO_BIG,
- DETAIL_EVENT_RESTRICTION_DROP, DETAIL_INVALID_OPTIONS, DETAIL_MISROUTED_EVENT,
- DETAIL_NON_HISTORICAL_DROP, DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS,
- ILLEGAL_DISTINCT_IDS,
+ DETAIL_EVENT_RESTRICTION_DROP, DETAIL_MISROUTED_EVENT, DETAIL_NON_HISTORICAL_DROP,
+ DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS, ILLEGAL_DISTINCT_IDS,
};
use super::response::BatchResponse;
-use super::types::{Batch, Event, EventResult, Options, WrappedEvent};
+use super::types::{Batch, Event, EventResult, OptionKeys, Options, WrappedEvent};
use crate::event_restrictions::{EventContext, EventRestrictionService};
use crate::events::ai_byte_limit::charge_ai_bytes;
use crate::global_rate_limiter::{GlobalRateLimitKey, GlobalRateLimiter};
@@ -410,8 +410,16 @@ fn emit_drop_warnings(state: &router::State, context: &Context, events: &[Wrappe
return;
}
- // (count, identifiers-of-the-single-event-if-unique) per warning type.
- type DropGroup<'a> = (u64, Option<(&'a str, Uuid)>);
+ struct DroppedEvent<'a> {
+ distinct_id: &'a str,
+ uuid: Uuid,
+ }
+ struct DropGroup<'a> {
+ count: u64,
+ /// The dropped event, kept only while the group has one event.
+ single_event: Option<DroppedEvent<'a>>,
+ failed_options: OptionKeys,
+ }
let mut grouped: HashMap<WarningType, DropGroup> = HashMap::new();
for ev in events {
if ev.result != EventResult::Drop {
@@ -420,19 +428,39 @@ fn emit_drop_warnings(state: &router::State, context: &Context, events: &[Wrappe
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;
+ let group = grouped.entry(warning).or_insert(DropGroup {
+ count: 0,
+ single_event: Some(DroppedEvent {
+ distinct_id: ev.event.distinct_id.as_str(),
+ uuid: ev.uuid,
+ }),
+ failed_options: OptionKeys::default(),
+ });
+ group.count += 1;
+ if group.count > 1 {
+ group.single_event = None;
}
+ group.failed_options = group.failed_options.union(ev.failed_option_keys());
}
let request = context.warning_context();
- for (warning, (count, single_event)) in grouped {
+ for (
+ warning,
+ DropGroup {
+ count,
+ single_event,
+ failed_options,
+ },
+ ) in grouped
+ {
let mut details = serde_json::Map::new();
- if let Some((distinct_id, uuid)) = single_event {
+ if !failed_options.is_empty() {
+ details.insert(
+ "invalidOptions".to_string(),
+ serde_json::json!(failed_options.names().collect::<Vec<_>>()),
+ );
+ }
+ if let Some(DroppedEvent { 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
@@ -525,21 +553,17 @@ fn validate_events(
match validate_event(&event) {
Ok(raw_ts) => {
- // Options validation: coerce known fields or drop the event.
- // The malformed-event metric (CAPTURE_V1_PARSED_EVENTS{malformed})
- // is emitted uniformly by observe_malformed_events, matching the
- // other validate-stage drops. Per-field detail is deferred to the
- // sampled verbose-logging mode rather than logged per-event here.
+ // `observe_malformed_events` counts and logs this drop.
let options = match event.options.validate() {
Ok(opts) => opts,
- Err(_) => {
+ Err(err) => {
events.push(WrappedEvent {
event,
uuid,
options: Options::default(),
adjusted_timestamp: None,
result: EventResult::Drop,
- details: Some(DETAIL_INVALID_OPTIONS),
+ details: Some(err.detail()),
destination,
force_disable_person_processing: false,
spread_partitions: false,
@@ -627,13 +651,72 @@ fn observe_malformed_events(context: &RequestContext, events: &[WrappedEvent]) {
.increment(*count);
}
+ if !MALFORMED_EVENTS_LOG_GATE.try_pass(process_uptime_ms()) {
+ return;
+ }
+
let summary: String = malformed
.iter()
.map(|(tag, count)| format!("{tag}={count}"))
.collect::<Vec<_>>()
.join(", ");
+ let failed_options = events
+ .iter()
+ .fold(OptionKeys::default(), |keys, event| {
+ keys.union(event.failed_option_keys())
+ })
+ .names()
+ .collect::<Vec<_>>()
+ .join(",");
- crate::ctx_log!(Level::WARN, context, "malformed events: {summary}");
+ crate::ctx_log!(
+ Level::WARN,
+ context,
+ batch_size = events.len(),
+ capture_internal = context.capture_internal,
+ historical_migration = context.historical_migration,
+ failed_options = %failed_options,
+ "malformed events: {summary}"
+ );
+}
+
+/// Admits at most one caller per interval, process-wide.
+struct LogGate {
+ interval_ms: u64,
+ next_allowed_ms: AtomicU64,
+}
+
+impl LogGate {
+ const fn new(interval_ms: u64) -> Self {
+ Self {
+ interval_ms,
+ next_allowed_ms: AtomicU64::new(0),
+ }
+ }
+
+ fn try_pass(&self, now_ms: u64) -> bool {
+ let next_allowed = self.next_allowed_ms.load(AtomicOrdering::Relaxed);
+ now_ms >= next_allowed
+ && self
+ .next_allowed_ms
+ .compare_exchange(
+ next_allowed,
+ now_ms + self.interval_ms,
+ AtomicOrdering::Relaxed,
+ AtomicOrdering::Relaxed,
+ )
+ .is_ok()
+ }
+}
+
+/// Caps the malformed-events WARN at one line per second per pod to stop log floods.
+/// The metric still counts every drop.
+static MALFORMED_EVENTS_LOG_GATE: LogGate = LogGate::new(1_000);
+
+static PROCESS_START: LazyLock<Instant> = LazyLock::new(Instant::now);
+
+fn process_uptime_ms() -> u64 {
+ PROCESS_START.elapsed().as_millis() as u64
}
/// Expects a pre-trimmed distinct_id (`Event.distinct_id` is trimmed at
@@ -1179,7 +1262,7 @@ mod tests {
use crate::event_restrictions::{
Pipeline, Restriction, RestrictionManager, RestrictionScope, RestrictionType,
};
- use crate::v1::analytics::constants::CAPTURE_V1_PATH;
+ use crate::v1::analytics::constants::{CAPTURE_V1_PATH, DETAIL_INVALID_OPTIONS};
use crate::v1::analytics::types::{Batch, Event};
use crate::v1::sinks::{Destination, DEFAULT_SCATTER_GATHER_MIN_BATCH};
use crate::v1::test_utils::{
@@ -1209,10 +1292,8 @@ mod tests {
serde_json::from_str(&json.to_string()).unwrap()
}
- /// Runs `f` under a local metrics recorder and returns the recorded
- /// `capture_v1_events_dropped` counter for the given `reason`+`stage` labels,
- /// so whole-batch-abort tests can assert the exact per-event drop count.
- fn dropped_count(reason: &str, stage: &str, f: impl FnOnce()) -> Option<u64> {
+ /// Runs `f` and returns counter `name` whose labels include all of `labels`.
+ fn counter_value(name: &str, labels: &[(&str, &str)], f: impl FnOnce()) -> Option<u64> {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
let recorder = DebuggingRecorder::new();
@@ -1225,12 +1306,15 @@ mod tests {
.into_vec()
.into_iter()
.find_map(|(key, _, _, value)| {
- if key.key().name() != CAPTURE_V1_EVENTS_DROPPED {
+ if key.key().name() != name {
return None;
}
- let labels: std::collections::HashMap<&str, &str> =
+ let recorded: std::collections::HashMap<&str, &str> =
key.key().labels().map(|l| (l.key(), l.value())).collect();
- if labels.get("reason") != Some(&reason) || labels.get("stage") != Some(&stage) {
+ if labels
+ .iter()
+ .any(|(label, value)| recorded.get(label) != Some(value))
+ {
return None;
}
match value {
@@ -1240,6 +1324,15 @@ mod tests {
})
}
+ /// The `capture_v1_events_dropped` count for `reason` and `stage` while `f` runs.
+ fn dropped_count(reason: &str, stage: &str, f: impl FnOnce()) -> Option<u64> {
+ counter_value(
+ CAPTURE_V1_EVENTS_DROPPED,
+ &[("reason", reason), ("stage", stage)],
+ f,
+ )
+ }
+
// --- validate_batch ---
#[test]
@@ -1759,32 +1852,62 @@ mod tests {
assert_eq!(event.details, Some("malformed_event_properties"));
}
- #[test]
- fn validate_events_invalid_options_drops_single_event() {
- use crate::v1::analytics::types::RawOptions;
+ /// Build an Event through serde, so distinct_id trimming applies.
+ fn event_with_options(uuid: &str, distinct_id: &str, options: serde_json::Value) -> Event {
+ serde_json::from_value(serde_json::json!({
+ "event": "$pageview",
+ "uuid": uuid,
+ "distinct_id": distinct_id,
+ "timestamp": "2026-03-19T14:29:58.123Z",
+ "options": options,
+ }))
+ .unwrap()
+ }
+ #[rstest::rstest]
+ #[case::bad_value("user-1", serde_json::json!({"cookieless_mode": [1, 2, 3]}), Some("invalid_options"))]
+ #[case::placeholder_without_option("$posthog_cookieless", serde_json::json!(null), None)]
+ #[case::placeholder_null_option("$posthog_cookieless", serde_json::json!({"cookieless_mode": null}), None)]
+ #[case::placeholder_false("$posthog_cookieless", serde_json::json!({"cookieless_mode": false}), None)]
+ #[case::placeholder_with_option("$posthog_cookieless", serde_json::json!({"cookieless_mode": true}), None)]
+ fn validate_events_option_rules_drop_only_the_offending_event(
+ #[case] distinct_id: &str,
+ #[case] options: serde_json::Value,
+ #[case] expected_drop: Option<&'static str>,
+ ) {
let ctx = test_utils::test_context();
- let mut good = valid_event();
- good.uuid = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d".to_string();
-
- let mut bad = valid_event();
- bad.uuid = "b1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5e".to_string();
- bad.options = RawOptions(serde_json::json!({"cookieless_mode": [1, 2, 3]}));
+ let batch = valid_batch(vec![
+ event_with_options(
+ "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
+ "user-ok",
+ serde_json::json!(null),
+ ),
+ event_with_options("b1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5e", distinct_id, options),
+ ]);
- let batch = Batch {
- created_at: "2026-03-19T14:30:00.000Z".to_string(),
- historical_migration: false,
- capture_internal: None,
- batch: vec![good, bad],
- };
- let events = validate_events(&ctx, AiLanePredicate::Allowlist, batch).unwrap();
- assert_eq!(events.len(), 2);
+ let mut events = Vec::new();
+ let malformed = counter_value(
+ CAPTURE_V1_PARSED_EVENTS,
+ &[
+ ("result", "malformed"),
+ ("error", expected_drop.unwrap_or("none")),
+ ],
+ || events = validate_events(&ctx, AiLanePredicate::Allowlist, batch).unwrap(),
+ );
assert_eq!(events[0].result, EventResult::Ok);
- assert_eq!(events[0].details, None);
-
- assert_eq!(events[1].result, EventResult::Drop);
- assert_eq!(events[1].details, Some("invalid_options"));
+ match expected_drop {
+ Some(tag) => {
+ assert_eq!(events[1].result, EventResult::Drop);
+ assert_eq!(events[1].details, Some(tag));
+ assert_eq!(malformed, Some(1));
+ }
+ None => {
+ assert_eq!(events[1].result, EventResult::Ok);
+ assert_eq!(events[1].details, None);
+ assert_eq!(malformed, None);
+ }
+ }
}
#[test]
@@ -4356,8 +4479,15 @@ mod tests {
}
}
+ #[rstest::rstest]
+ #[case::null_flag(serde_json::json!(null))]
+ #[case::real_false(serde_json::json!(false))]
+ #[case::lenient_no(serde_json::json!("no"))]
+ #[case::unreadable(serde_json::json!("maybe"))]
#[tokio::test]
- async fn import_mode_drops_non_historical_batch_and_publishes_nothing() {
+ async fn import_mode_drops_non_historical_batch_and_publishes_nothing(
+ #[case] flag: serde_json::Value,
+ ) {
// Import mode exists to ingest backfills only: a batch without
// historical_migration must be fully dropped (200, per-event Drop) and
// never published — otherwise live traffic could sneak in via the
@@ -4366,7 +4496,7 @@ mod tests {
.with_capture_mode(crate::config::CaptureMode::Import)
.build();
let mut ctx = test_utils::test_analytics_context();
- let batch = valid_batch(vec![valid_event(), valid_event()]);
+ let batch = batch_with_historical_flag(flag, vec![valid_event(), valid_event()]);
let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();
@@ -4380,15 +4510,32 @@ mod tests {
.with_records(|records| assert!(records.is_empty(), "nothing may be published"));
}
+ fn batch_with_historical_flag(flag: serde_json::Value, events: Vec<Event>) -> Batch {
+ let parsed: Batch = serde_json::from_value(serde_json::json!({
+ "created_at": "2026-03-19T14:30:00.000Z",
+ "historical_migration": flag,
+ "batch": [],
+ }))
+ .unwrap();
+ Batch {
+ batch: events,
+ ..parsed
+ }
+ }
+
+ #[rstest::rstest]
+ #[case::real_bool(serde_json::json!(true))]
+ #[case::lenient_word(serde_json::json!("yes"))]
+ #[case::lenient_number(serde_json::json!(1))]
#[tokio::test]
- async fn import_mode_publishes_historical_batch() {
+ async fn import_mode_publishes_historical_batch(#[case] flag: serde_json::Value) {
// The happy path: a properly flagged historical batch flows through
// Import mode exactly like Events mode and reaches the sink.
let ts = TestStateBuilder::new()
.with_capture_mode(crate::config::CaptureMode::Import)
.build();
let mut ctx = test_utils::test_analytics_context();
- let batch = historical_batch(vec![valid_event(), valid_event()]);
+ let batch = batch_with_historical_flag(flag, vec![valid_event(), valid_event()]);
let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();
@@ -4783,6 +4930,123 @@ mod tests {
);
}
+ /// Option drops are per event, share one `invalid_options` warning, and lenient forms pass.
+ #[rstest::rstest]
+ #[case::analytics_deployment(CaptureMode::Events, "$pageview")]
+ #[case::ai_deployment(CaptureMode::Ai, "$ai_generation")]
+ #[tokio::test]
+ async fn option_drops_report_their_reason_and_share_one_warning(
+ #[case] capture_mode: CaptureMode,
+ #[case] event_name: &str,
+ ) {
+ use crate::v1::analytics::types::RawOptions;
+
+ let collector = Arc::new(CollectingEmitter::new());
+ let ts = TestStateBuilder::new()
+ .with_capture_mode(capture_mode)
+ .with_ingestion_warning_emitter(collector.clone())
+ .build();
+ let mut ctx = test_utils::test_analytics_context();
+ let event = |distinct_id: &str, options: serde_json::Value| Event {
+ distinct_id: distinct_id.to_string(),
+ options: RawOptions(options),
+ ..named_event(event_name)
+ };
+ let bad_cookieless = event("user-3", serde_json::json!({"cookieless_mode": "maybe"}));
+ let bad_cookieless_again = event("user-4", serde_json::json!({"cookieless_mode": [1]}));
+ let bad_tour = event("user-1", serde_json::json!({"product_tour_id": true}));
+ let cookieless_ok = event(
+ "$posthog_cookieless",
+ serde_json::json!({"cookieless_mode": true}),
+ );
+ let lenient_ok = event(
+ "user-2",
+ serde_json::json!({
+ "cookieless_mode": "YES",
+ "disable_skew_correction": "off",
+ "process_person_profile": 0.0,
+ "product_tour_id": 5
+ }),
+ );
+ let lenient_placeholder_ok = event(
+ "$posthog_cookieless",
+ serde_json::json!({
+ "cookieless_mode": " t ",
+ "disable_skew_correction": 1,
+ "process_person_profile": "n"
+ }),
+ );
+ let expected: HashMap<Uuid, (EventResult, Option<&str>)> = HashMap::from([
+ (
+ bad_cookieless.uuid.parse().unwrap(),
+ (EventResult::Drop, Some("invalid_options")),
+ ),
+ (
+ bad_cookieless_again.uuid.parse().unwrap(),
+ (EventResult::Drop, Some("invalid_options")),
+ ),
+ (
+ bad_tour.uuid.parse().unwrap(),
+ (EventResult::Drop, Some("invalid_options")),
+ ),
+ (cookieless_ok.uuid.parse().unwrap(), (EventResult::Ok, None)),
+ (lenient_ok.uuid.parse().unwrap(), (EventResult::Ok, None)),
+ (
+ lenient_placeholder_ok.uuid.parse().unwrap(),
+ (EventResult::Ok, None),
+ ),
+ ]);
+ let batch = valid_batch(vec![
+ bad_cookieless,
+ bad_cookieless_again,
+ bad_tour,
+ cookieless_ok,
+ lenient_ok,
+ lenient_placeholder_ok,
+ ]);
+
+ let resp = process_batch(&ts.state, &mut ctx, batch).await.unwrap();
+
+ let results: HashMap<Uuid, (EventResult, Option<&str>)> = resp
+ .entries()
+ .iter()
+ .map(|(uuid, entry)| (*uuid, (entry.result, entry.details)))
+ .collect();
+ assert_eq!(results, expected);
+
+ let emitted = collector.emitted();
+ assert_eq!(emitted.len(), 1, "every option drop shares one warning");
+ assert_eq!(emitted[0].warning, WarningType::InvalidOptions);
+ assert_eq!(emitted[0].count, 3);
+ assert_eq!(
+ emitted[0].extra_details.get("invalidOptions"),
+ Some(&serde_json::json!(["cookieless_mode", "product_tour_id"]))
+ );
+ }
+
+ #[test]
+ fn failed_option_keys_ignore_drops_for_other_reasons() {
+ let mut dropped = malformed_wrapped_event();
+ dropped.event.options = crate::v1::analytics::types::RawOptions(serde_json::json!({
+ "cookieless_mode": "maybe"
+ }));
+ assert!(dropped.failed_option_keys().is_empty());
+ }
+
+ #[rstest::rstest]
+ #[case::first_call_passes(&[0], &[true])]
+ #[case::second_call_in_the_interval_is_blocked(&[0, 999], &[true, false])]
+ #[case::call_after_the_interval_passes(&[0, 999, 1_000], &[true, false, true])]
+ #[case::interval_restarts_from_the_last_pass(&[5_000, 5_500, 6_000, 6_999], &[true, false, true, false])]
+ fn log_gate_lets_one_call_through_per_interval(
+ #[case] times_ms: &[u64],
+ #[case] expected: &[bool],
+ ) {
+ let gate = LogGate::new(1_000);
+ let passed: Vec<bool> = times_ms.iter().map(|now| gate.try_pass(*now)).collect();
+ assert_eq!(passed, expected);
+ }
+
/// Drops from different stages of one batch each surface once. Validation
/// and the AI size ceiling both drop an event here; the single end-of-batch
/// sweep reports both without repeating either.
diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rs
index ed45565cd510..9a1c3d536840 100644
--- a/rust/capture/src/v1/analytics/types.rs
+++ b/rust/capture/src/v1/analytics/types.rs
@@ -23,6 +23,7 @@ impl io::Write for StringWriter<'_> {
}
}
+use super::constants::DETAIL_INVALID_OPTIONS;
use crate::ordering::{person_ordering, OrderingGuarantee};
use crate::v1::context::RequestContext;
use crate::v1::sinks::event::Event as SinkEvent;
@@ -63,13 +64,36 @@ pub enum EventResult {
#[derive(Debug, Deserialize)]
pub struct Batch {
pub created_at: String,
- #[serde(default)]
+ /// An unreadable value means false instead of failing the batch.
+ #[serde(default, deserialize_with = "deserialize_lenient_flag_or_false")]
pub historical_migration: bool,
- #[serde(default)]
+ /// An unreadable value means unset instead of failing the batch.
+ #[serde(default, deserialize_with = "deserialize_lenient_flag")]
pub capture_internal: Option<bool>,
pub batch: Vec<Event>,
}
+fn lenient_flag(value: &Value) -> Option<bool> {
+ match coerce_bool(value) {
+ Parsed::Set(flag) => Some(flag),
+ Parsed::Unset | Parsed::Invalid => None,
+ }
+}
+
+fn deserialize_lenient_flag<'de, D>(deserializer: D) -> Result<Option<bool>, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ Ok(lenient_flag(&Value::deserialize(deserializer)?))
+}
+
+fn deserialize_lenient_flag_or_false<'de, D>(deserializer: D) -> Result<bool, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ Ok(lenient_flag(&Value::deserialize(deserializer)?).unwrap_or(false))
+}
+
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
pub struct Options {
#[serde(skip_serializing_if = "Option::is_none")]
@@ -88,101 +112,192 @@ pub struct Options {
#[serde(transparent)]
pub struct RawOptions(pub Value);
-/// Error produced when `RawOptions::validate` cannot coerce one or more fields.
-/// Carries the offending field names for logging; the wire/metric tag is the
-/// static `DETAIL_INVALID_OPTIONS` constant applied at the drop site.
-#[derive(Debug)]
-pub struct OptionsError {
- pub invalid_fields: Vec<&'static str>,
+/// An option key capture validates and forwards; it ignores all other keys.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ExpectedOption {
+ CookielessMode,
+ DisableSkewCorrection,
+ ProcessPersonProfile,
+ ProductTourId,
+}
+
+impl ExpectedOption {
+ /// Check and report order.
+ const ALL: [Self; 4] = [
+ Self::CookielessMode,
+ Self::DisableSkewCorrection,
+ Self::ProcessPersonProfile,
+ Self::ProductTourId,
+ ];
+
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::CookielessMode => "cookieless_mode",
+ Self::DisableSkewCorrection => "disable_skew_correction",
+ Self::ProcessPersonProfile => "process_person_profile",
+ Self::ProductTourId => "product_tour_id",
+ }
+ }
+
+ fn bit(self) -> u8 {
+ 1 << self as u8
+ }
+}
+
+/// Expected option keys, each at most once, in `ExpectedOption::ALL` order.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+pub struct OptionKeys(u8);
+
+impl OptionKeys {
+ pub fn of(key: ExpectedOption) -> Self {
+ Self(key.bit())
+ }
+
+ fn insert(&mut self, key: ExpectedOption) {
+ self.0 |= key.bit();
+ }
+
+ pub fn union(self, other: Self) -> Self {
+ Self(self.0 | other.0)
+ }
+
+ pub fn is_empty(self) -> bool {
+ self.0 == 0
+ }
+
+ pub fn names(self) -> impl Iterator<Item = &'static str> {
+ ExpectedOption::ALL
+ .into_iter()
+ .filter(move |key| self.0 & key.bit() != 0)
+ .map(ExpectedOption::as_str)
+ }
+}
+
+/// Expected keys with unreadable values; empty when `options` is not an object.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct OptionsError(pub OptionKeys);
+
+impl OptionsError {
+ /// The per-event `details` tag and malformed-metric label.
+ pub fn detail(self) -> &'static str {
+ DETAIL_INVALID_OPTIONS
+ }
+
+ /// Keys to name in logs and the ingestion warning.
+ pub fn failed_keys(self) -> OptionKeys {
+ self.0
+ }
}
impl RawOptions {
- /// Validate and coerce raw JSON into typed Options.
- ///
- /// - Null/absent -> Ok(default)
- /// - Object -> coerce each known key, ignore unknown, collect invalid fields
- /// - Non-object -> Err with no field names
+ /// Read the expected keys leniently and ignore the rest.
pub fn validate(&self) -> Result<Options, OptionsError> {
- match &self.0 {
- Value::Null => Ok(Options::default()),
- Value::Object(map) => {
- let mut opts = Options::default();
- let mut invalid_fields: Vec<&'static str> = Vec::new();
-
- if let Some(v) = map.get("cookieless_mode") {
- if !v.is_null() {
- match coerce_bool(v) {
- Some(b) => opts.cookieless_mode = Some(b),
- None => invalid_fields.push("cookieless_mode"),
- }
- }
- }
- if let Some(v) = map.get("disable_skew_correction") {
- if !v.is_null() {
- match coerce_bool(v) {
- Some(b) => opts.disable_skew_correction = Some(b),
- None => invalid_fields.push("disable_skew_correction"),
- }
- }
- }
- if let Some(v) = map.get("process_person_profile") {
- if !v.is_null() {
- match coerce_bool(v) {
- Some(b) => opts.process_person_profile = Some(b),
- None => invalid_fields.push("process_person_profile"),
- }
- }
- }
- if let Some(v) = map.get("product_tour_id") {
- if !v.is_null() {
- match coerce_string(v) {
- Some(s) => opts.product_tour_id = Some(s),
- None => invalid_fields.push("product_tour_id"),
- }
- }
- }
+ let map = match &self.0 {
+ Value::Null => return Ok(Options::default()),
+ Value::Object(map) => map,
+ _ => return Err(OptionsError(OptionKeys::default())),
+ };
- if invalid_fields.is_empty() {
- Ok(opts)
- } else {
- Err(OptionsError { invalid_fields })
- }
- }
- _ => Err(OptionsError {
- invalid_fields: Vec::new(),
- }),
+ let mut invalid = OptionKeys::default();
+ let options = Options {
+ cookieless_mode: read_option(
+ map,
+ ExpectedOption::CookielessMode,
+ coerce_bool,
+ &mut invalid,
+ ),
+ disable_skew_correction: read_option(
+ map,
+ ExpectedOption::DisableSkewCorrection,
+ coerce_bool,
+ &mut invalid,
+ ),
+ process_person_profile: read_option(
+ map,
+ ExpectedOption::ProcessPersonProfile,
+ coerce_bool,
+ &mut invalid,
+ ),
+ product_tour_id: read_option(
+ map,
+ ExpectedOption::ProductTourId,
+ coerce_product_tour_id,
+ &mut invalid,
+ ),
+ };
+
+ if invalid.is_empty() {
+ Ok(options)
+ } else {
+ Err(OptionsError(invalid))
+ }
+ }
+}
+
+/// The result of reading one expected option value.
+enum Parsed<T> {
+ Set(T),
+ Unset,
+ Invalid,
+}
+
+fn read_option<T>(
+ map: &serde_json::Map<String, Value>,
+ key: ExpectedOption,
+ parse: fn(&Value) -> Parsed<T>,
+ invalid: &mut OptionKeys,
+) -> Option<T> {
+ match map.get(key.as_str()).map_or(Parsed::Unset, parse) {
+ Parsed::Set(value) => Some(value),
+ Parsed::Unset => None,
+ Parsed::Invalid => {
+ invalid.insert(key);
+ None
}
}
}
-/// Coerce a JSON value to bool with conservative rules:
-/// - native bool passes through
-/// - strings "true"/"false"/"1"/"0" (trimmed, case-insensitive)
-/// - any nonzero number -> true, 0 -> false
-fn coerce_bool(v: &Value) -> Option<bool> {
+/// Booleans, numbers (zero is off), on/off words or numeric strings; `null` or blank is unset.
+fn coerce_bool(v: &Value) -> Parsed<bool> {
match v {
- Value::Bool(b) => Some(*b),
- Value::String(s) => match s.trim().to_ascii_lowercase().as_str() {
- "true" | "1" => Some(true),
- "false" | "0" => Some(false),
- _ => None,
+ Value::Null => Parsed::Unset,
+ Value::Bool(b) => Parsed::Set(*b),
+ Value::Number(n) => n
+ .as_f64()
+ .map_or(Parsed::Invalid, |f| Parsed::Set(f != 0.0)),
+ Value::String(s) => parse_bool_str(s),
+ Value::Array(_) | Value::Object(_) => Parsed::Invalid,
+ }
+}
+
+fn parse_bool_str(raw: &str) -> Parsed<bool> {
+ let trimmed = raw.trim();
+ if trimmed.is_empty() {
+ return Parsed::Unset;
+ }
+ match trimmed.to_ascii_lowercase().as_str() {
+ "true" | "t" | "yes" | "y" | "on" => Parsed::Set(true),
+ "false" | "f" | "no" | "n" | "off" => Parsed::Set(false),
+ // `f64` parsing accepts "inf" and "nan", which are not flags.
+ other => match other.parse::<f64>() {
+ Ok(f) if f.is_finite() => Parsed::Set(f != 0.0),
+ _ => Parsed::Invalid,
},
- Value::Number(n) => n.as_f64().map(|f| f != 0.0),
- _ => None,
}
}
-/// Coerce a JSON value to string:
-/// - native string passes through
-/// - integer number -> its decimal string representation
-fn coerce_string(v: &Value) -> Option<String> {
+/// A string as-is, or an integer as its decimal string; blank is unset.
+fn coerce_product_tour_id(v: &Value) -> Parsed<String> {
match v {
- Value::String(s) => Some(s.clone()),
+ Value::Null => Parsed::Unset,
+ Value::String(s) if s.trim().is_empty() => Parsed::Unset,
+ Value::String(s) => Parsed::Set(s.clone()),
Value::Number(n) => n
.as_i64()
.map(|i| i.to_string())
- .or_else(|| n.as_u64().map(|u| u.to_string())),
- _ => None,
+ .or_else(|| n.as_u64().map(|u| u.to_string()))
+ .map_or(Parsed::Invalid, Parsed::Set),
+ Value::Bool(_) | Value::Array(_) | Value::Object(_) => Parsed::Invalid,
}
}
@@ -232,6 +347,21 @@ pub struct WrappedEvent {
pub is_gateway_verified: bool,
}
+impl WrappedEvent {
+ /// Option keys that dropped this event; recomputed since only drops need it.
+ pub fn failed_option_keys(&self) -> OptionKeys {
+ match self.details {
+ Some(DETAIL_INVALID_OPTIONS) => self
+ .event
+ .options
+ .validate()
+ .err()
+ .map_or_else(OptionKeys::default, OptionsError::failed_keys),
+ _ => OptionKeys::default(),
+ }
+ }
+}
+
impl SinkEvent for WrappedEvent {
// Pre-parsed UUID for result correlation. By the Sink stage,
// we know ALL well-formed incoming events have a valid UUID.
@@ -894,6 +1024,27 @@ mod tests {
// --- RawOptions::validate coercion matrix ---
+ fn invalid(keys: &[ExpectedOption]) -> OptionsError {
+ OptionsError(keys.iter().fold(OptionKeys::default(), |acc, key| {
+ acc.union(OptionKeys::of(*key))
+ }))
+ }
+
+ fn options_with(key: ExpectedOption, value: serde_json::Value) -> RawOptions {
+ let mut map = serde_json::Map::new();
+ map.insert(key.as_str().to_string(), value);
+ RawOptions(serde_json::Value::Object(map))
+ }
+
+ fn bool_option(options: &Options, key: ExpectedOption) -> Option<bool> {
+ match key {
+ ExpectedOption::CookielessMode => options.cookieless_mode,
+ ExpectedOption::DisableSkewCorrection => options.disable_skew_correction,
+ ExpectedOption::ProcessPersonProfile => options.process_person_profile,
+ ExpectedOption::ProductTourId => unreachable!("product_tour_id is not a boolean"),
+ }
+ }
+
#[test]
fn raw_options_null_validates_to_defaults() {
let raw = RawOptions::default();
@@ -912,56 +1063,101 @@ mod tests {
assert_eq!(opts.disable_skew_correction, None);
}
+ const READABLE_BOOLS: &[(&str, Option<bool>)] = &[
+ ("true", Some(true)),
+ ("false", Some(false)),
+ (r#""true""#, Some(true)),
+ (r#""false""#, Some(false)),
+ (r#""t""#, Some(true)),
+ (r#""f""#, Some(false)),
+ (r#""yes""#, Some(true)),
+ (r#""no""#, Some(false)),
+ (r#""y""#, Some(true)),
+ (r#""n""#, Some(false)),
+ (r#""on""#, Some(true)),
+ (r#""off""#, Some(false)),
+ (r#""1""#, Some(true)),
+ (r#""0""#, Some(false)),
+ (r#""FALSE""#, Some(false)),
+ (r#""Yes""#, Some(true)),
+ (r#"" true ""#, Some(true)),
+ (r#""1.0""#, Some(true)),
+ (r#""0.0""#, Some(false)),
+ (r#""-0""#, Some(false)),
+ (r#""-1""#, Some(true)),
+ ("1", Some(true)),
+ ("0", Some(false)),
+ ("0.0", Some(false)),
+ ("-0.0", Some(false)),
+ ("1.5", Some(true)),
+ ("42", Some(true)),
+ ("-1", Some(true)),
+ ("null", None),
+ (r#""""#, None),
+ (r#"" ""#, None),
+ ];
+
+ const UNREADABLE_BOOLS: &[&str] = &[
+ "[1, 2, 3]",
+ r#"{"nested": true}"#,
+ r#""maybe""#,
+ r#""[Filtered]""#,
+ r#""nan""#,
+ r#""inf""#,
+ ];
+
+ fn json(source: &str) -> serde_json::Value {
+ serde_json::from_str(source).expect("test table holds valid JSON")
+ }
+
#[rstest::rstest]
- #[case::native_true(serde_json::json!(true), Some(true))]
- #[case::native_false(serde_json::json!(false), Some(false))]
- #[case::str_true(serde_json::json!("true"), Some(true))]
- #[case::str_false(serde_json::json!("false"), Some(false))]
- #[case::str_one(serde_json::json!("1"), Some(true))]
- #[case::str_zero(serde_json::json!("0"), Some(false))]
- #[case::str_uppercase(serde_json::json!("FALSE"), Some(false))]
- #[case::str_padded(serde_json::json!(" true "), Some(true))]
- #[case::num_one(serde_json::json!(1), Some(true))]
- #[case::num_zero(serde_json::json!(0), Some(false))]
- #[case::num_large(serde_json::json!(42), Some(true))]
- #[case::num_negative(serde_json::json!(-1), Some(true))]
fn raw_options_bool_coercion_valid(
- #[case] input: serde_json::Value,
- #[case] expected: Option<bool>,
+ #[values(
+ ExpectedOption::CookielessMode,
+ ExpectedOption::DisableSkewCorrection,
+ ExpectedOption::ProcessPersonProfile
+ )]
+ key: ExpectedOption,
) {
- let raw = RawOptions(serde_json::json!({ "cookieless_mode": input }));
- assert_eq!(raw.validate().unwrap().cookieless_mode, expected);
+ for (source, expected) in READABLE_BOOLS {
+ let options = options_with(key, json(source)).validate().unwrap();
+ assert_eq!(
+ bool_option(&options, key),
+ *expected,
+ "{} = {source}",
+ key.as_str()
+ );
+ }
}
#[rstest::rstest]
- #[case::array(serde_json::json!([1, 2, 3]))]
- #[case::object(serde_json::json!({"nested": true}))]
- #[case::yes(serde_json::json!("yes"))]
- #[case::off(serde_json::json!("off"))]
- #[case::empty_string(serde_json::json!(""))]
- fn raw_options_bool_uncoercible(#[case] input: serde_json::Value) {
- let raw = RawOptions(serde_json::json!({ "cookieless_mode": input }));
- let err = raw.validate().unwrap_err();
- assert_eq!(err.invalid_fields, vec!["cookieless_mode"]);
- }
-
- #[test]
- fn raw_options_all_bool_fields_routed_to_correct_slot() {
- let raw = RawOptions(serde_json::json!({
- "cookieless_mode": "true",
- "disable_skew_correction": 0,
- "process_person_profile": false
- }));
- let opts = raw.validate().unwrap();
- assert_eq!(opts.cookieless_mode, Some(true));
- assert_eq!(opts.disable_skew_correction, Some(false));
- assert_eq!(opts.process_person_profile, Some(false));
+ fn raw_options_bool_uncoercible(
+ #[values(
+ ExpectedOption::CookielessMode,
+ ExpectedOption::DisableSkewCorrection,
+ ExpectedOption::ProcessPersonProfile
+ )]
+ key: ExpectedOption,
+ ) {
+ for source in UNREADABLE_BOOLS {
+ assert_eq!(
+ options_with(key, json(source)).validate().unwrap_err(),
+ invalid(&[key]),
+ "{} = {source}",
+ key.as_str()
+ );
+ }
}
#[rstest::rstest]
#[case::string(serde_json::json!("tour-123"), Some("tour-123"))]
+ #[case::padded_kept_unchanged(serde_json::json!(" tour-123 "), Some(" tour-123 "))]
#[case::integer(serde_json::json!(999), Some("999"))]
#[case::negative_integer(serde_json::json!(-5), Some("-5"))]
+ #[case::integer_above_i64(serde_json::json!(u64::MAX), Some("18446744073709551615"))]
+ #[case::null_is_unset(serde_json::json!(null), None)]
+ #[case::empty_is_unset(serde_json::json!(""), None)]
+ #[case::blank_is_unset(serde_json::json!(" "), None)]
fn raw_options_product_tour_id_coercion_valid(
#[case] input: serde_json::Value,
#[case] expected: Option<&str>,
@@ -971,35 +1167,63 @@ mod tests {
}
#[rstest::rstest]
- #[case::object(serde_json::json!({"nested": true}))]
- #[case::array(serde_json::json!(["a"]))]
- #[case::bool(serde_json::json!(true))]
#[case::float(serde_json::json!(1.5))]
+ #[case::integral_float(serde_json::json!(42.0))]
+ #[case::bool(serde_json::json!(true))]
+ #[case::array(serde_json::json!(["a"]))]
+ #[case::object(serde_json::json!({"nested": true}))]
fn raw_options_product_tour_id_uncoercible(#[case] input: serde_json::Value) {
let raw = RawOptions(serde_json::json!({ "product_tour_id": input }));
- let err = raw.validate().unwrap_err();
- assert_eq!(err.invalid_fields, vec!["product_tour_id"]);
+ assert_eq!(
+ raw.validate().unwrap_err(),
+ invalid(&[ExpectedOption::ProductTourId])
+ );
}
#[test]
- fn raw_options_multiple_invalid_fields_collected() {
+ fn raw_options_invalid_keys_reported_once_in_check_order() {
let raw = RawOptions(serde_json::json!({
- "cookieless_mode": {"bad": true},
+ "product_tour_id": 7.5,
"disable_skew_correction": [false],
- "product_tour_id": "valid-string",
+ "cookieless_mode": {"bad": true},
"process_person_profile": null
}));
let err = raw.validate().unwrap_err();
- assert!(err.invalid_fields.contains(&"cookieless_mode"));
- assert!(err.invalid_fields.contains(&"disable_skew_correction"));
- assert!(!err.invalid_fields.contains(&"product_tour_id"));
+ assert_eq!(err.detail(), "invalid_options");
+ assert_eq!(
+ err.failed_keys().names().collect::<Vec<_>>(),
+ vec![
+ "cookieless_mode",
+ "disable_skew_correction",
+ "product_tour_id"
+ ]
+ );
+ }
+
+ #[test]
+ fn option_keys_union_is_deduplicated_and_ordered() {
+ let first = OptionKeys::of(ExpectedOption::ProductTourId)
+ .union(OptionKeys::of(ExpectedOption::CookielessMode));
+ let second = OptionKeys::of(ExpectedOption::CookielessMode)
+ .union(OptionKeys::of(ExpectedOption::ProcessPersonProfile))
+ .union(OptionKeys::of(ExpectedOption::DisableSkewCorrection));
+ assert_eq!(
+ first.union(second).names().collect::<Vec<_>>(),
+ vec![
+ "cookieless_mode",
+ "disable_skew_correction",
+ "process_person_profile",
+ "product_tour_id"
+ ]
+ );
}
#[test]
fn raw_options_non_object_value_returns_error() {
let raw = RawOptions(serde_json::json!("just a string"));
let err = raw.validate().unwrap_err();
- assert!(err.invalid_fields.is_empty());
+ assert_eq!(err.detail(), "invalid_options");
+ assert!(err.failed_keys().is_empty());
}
#[test]
@@ -1012,17 +1236,6 @@ mod tests {
assert_eq!(opts.cookieless_mode, Some(true));
}
- #[test]
- fn raw_options_null_field_treated_as_absent() {
- let raw = RawOptions(serde_json::json!({
- "cookieless_mode": null,
- "disable_skew_correction": true
- }));
- let opts = raw.validate().unwrap();
- assert_eq!(opts.cookieless_mode, None);
- assert_eq!(opts.disable_skew_correction, Some(true));
- }
-
#[test]
fn batch_deserialization_survives_mistyped_options() {
let json = r#"{
@@ -1037,10 +1250,28 @@ mod tests {
}"#;
let batch: Batch = serde_json::from_str(json).unwrap();
assert_eq!(batch.batch.len(), 1);
- // 999 coerces to true (nonzero), "banana" does not coerce
let err = batch.batch[0].options.validate().unwrap_err();
- assert!(err.invalid_fields.contains(&"cookieless_mode"));
- assert!(!err.invalid_fields.contains(&"disable_skew_correction"));
+ assert_eq!(err, invalid(&[ExpectedOption::CookielessMode]));
+ }
+
+ #[test]
+ fn parse_batch_flags_are_lenient() {
+ let unreadable = UNREADABLE_BOOLS.iter().map(|source| (*source, None));
+ for (source, expected) in READABLE_BOOLS.iter().copied().chain(unreadable) {
+ let body = format!(
+ r#"{{"created_at": "2026-03-19T14:30:00.000Z", "capture_internal": {source}, "historical_migration": {source}, "batch": []}}"#
+ );
+ let batch: Batch = serde_json::from_str(&body).unwrap();
+ assert_eq!(
+ batch.capture_internal, expected,
+ "capture_internal = {source}"
+ );
+ assert_eq!(
+ batch.historical_migration,
+ expected.unwrap_or(false),
+ "historical_migration = {source}"
+ );
+ }
}
// --- SinkEvent impl for WrappedEvent ---
@@ -1896,6 +2127,25 @@ mod tests {
assert_eq!(data.properties["$process_person_profile"], false);
}
+ // Ingestion honors only a JSON `false`, so capture must inject the parsed boolean.
+ #[rstest::rstest]
+ #[case::cookieless_yes(ExpectedOption::CookielessMode, serde_json::json!("YES"), "$cookieless_mode", true)]
+ #[case::skew_off(ExpectedOption::DisableSkewCorrection, serde_json::json!("off"), "$ignore_sent_at", false)]
+ #[case::skew_t(ExpectedOption::DisableSkewCorrection, serde_json::json!("t"), "$ignore_sent_at", true)]
+ #[case::person_profile_float_zero(ExpectedOption::ProcessPersonProfile, serde_json::json!(0.0), "$process_person_profile", false)]
+ #[case::person_profile_no(ExpectedOption::ProcessPersonProfile, serde_json::json!(" no "), "$process_person_profile", false)]
+ fn serialize_injects_lenient_options_as_booleans(
+ #[case] key: ExpectedOption,
+ #[case] raw: serde_json::Value,
+ #[case] property: &str,
+ #[case] expected: bool,
+ ) {
+ let mut wrapped = pageview_event();
+ wrapped.options = options_with(key, raw).validate().unwrap();
+ let (_, data) = serialize_and_parse(&wrapped, &serialize_ctx());
+ assert_eq!(data.properties[property], serde_json::Value::Bool(expected));
+ }
+
#[test]
fn serialize_force_disable_does_not_affect_data() {
let uuid = Uuid::new_v4();
diff --git a/rust/capture/src/v1/sinks/DESIGN.md b/rust/capture/src/v1/sinks/DESIGN.md
index e5afb7e73dd9..b69f0ec443b2 100644
--- a/rust/capture/src/v1/sinks/DESIGN.md
+++ b/rust/capture/src/v1/sinks/DESIGN.md
@@ -1200,13 +1200,13 @@ expect.
┌─────────────────────────┐
│ WrappedEvent │
│ │
- │ event: Event { │ ┌───────────────────────┐
- │ event, uuid, │ │ Event::Options │
- │ distinct_id, │ │ cookieless_mode │
- │ timestamp, │ │ disable_skew_adjust │
- │ session_id?, │ │ product_tour_id │
- │ window_id?, │ │ process_person_prof │
- │ options ─────────────┼─────▶└───────────────────────┘
+ │ event: Event { │ ┌────────────────────────────┐
+ │ event, uuid, │ │ Event::Options │
+ │ distinct_id, │ │ cookieless_mode │
+ │ timestamp, │ │ disable_skew_correction │
+ │ session_id?, │ │ product_tour_id │
+ │ window_id?, │ │ process_person_profile │
+ │ options ─────────────┼─────▶└────────────────────────────┘
│ properties (RawValue)│
│ } │
│ uuid: Uuid (pre-parsed)│
@@ -1265,10 +1265,17 @@ original property ordering and formatting.
| `session_id` | `$session_id` | |
| `window_id` | `$window_id` | |
| `options.cookieless_mode` | `$cookieless_mode` | |
-| `options.disable_skew_correction` | `$ignore_sent_at` | Legacy rename (alias: `disable_skew_adjustment`) |
+| `options.disable_skew_correction` | `$ignore_sent_at` | Legacy rename. v1 reads only `disable_skew_correction` |
| `options.product_tour_id` | `$product_tour_id` | |
| `options.process_person_profile` | `$process_person_profile` | |
+`RawOptions::validate` reads the four expected option keys before injection and ignores every other key:
+
+- Boolean options accept booleans, numbers (zero is off), `true`/`t`/`yes`/`y`/`on`/`1` and `false`/`f`/`no`/`n`/`off`/`0` in any case, and numeric strings. `null` and blank strings mean "not set".
+- `product_tour_id` accepts a non-empty string, forwarded unchanged, or an integer, forwarded as its decimal string. `null` and blank strings mean "not set".
+- Any other value for an expected key drops the event with `invalid_options`, and emits the `invalid_options` ingestion warning, whose `invalidOptions` detail names the failed keys.
+- The batch-level `capture_internal` and `historical_migration` flags use the same boolean reader. An unreadable value means "not set" and never fails the batch.
+
### IngestionEvent / IngestionData
`IngestionEvent` is the Kafka message payload, field-order-compatible
@@ -1289,7 +1296,7 @@ Fields intentionally omitted vs the legacy `RawEvent`:
### IP redaction
-`capture_internal` requests (PostHog's own telemetry) have their IP
+`capture_internal` requests (events the Django app sends on behalf of a customer team) have their IP
redacted to `127.0.0.1` in both `serialize` (the `ip` field on
`IngestionEvent`) and `partition_key` (cookieless mode).