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): pass capture_internal options through unchanged (#108115)

Eli Reismanab97d00bf129
diff --git a/posthog/api/capture.py b/posthog/api/capture.py
index 450c7672ffba..e0126a9d45d8 100644
--- a/posthog/api/capture.py
+++ b/posthog/api/capture.py
@@ -64,19 +64,16 @@ AI_EVENT_NAME_PREFIX = "$ai_"
SDK_INFO = "posthog-capture-v1-internal/1.0"
-# v1 Options struct fields and their legacy property counterparts.
+# The option keys capture-rs v1 expects, and the legacy property each one replaces.
_OPTIONS_TO_LEGACY_PROPERTY: dict[str, str] = {
"cookieless_mode": "$cookieless_mode",
"disable_skew_correction": "$ignore_sent_at",
"product_tour_id": "$product_tour_id",
"process_person_profile": "$process_person_profile",
}
-_VALID_OPTION_KEYS = frozenset(_OPTIONS_TO_LEGACY_PROPERTY.keys())
-# Extra legacy aliases that must also be stripped from properties.
-_EXTRA_LEGACY_ALIASES: dict[str, str] = {
- "disable_skew_correction": "disable_skew_adjustment",
-}
+# Longest reason from the capture response that `verdict_summary` shows, matching the posthog-rs SDK.
+_MAX_REPORTED_REASON_CHARS = 64
_KNOWN_RESULT_STATUSES = frozenset({"ok", "drop", "warning", "retry"})
@@ -116,7 +113,7 @@ CAPTURE_V1_RESUBMIT = Counter(
)
CAPTURE_V1_OPTION_CONFLICT = Counter(
"capture_v1_internal_option_conflict",
- "Typed option input disagreed with a legacy property; explicit won.",
+ "An explicit option or field disagreed with its legacy property; the explicit value won.",
labelnames=["event_source", "field"],
)
CAPTURE_V1_EVENTS_REROUTED = Counter(
@@ -205,6 +202,33 @@ class CaptureInternalResult:
status_code=0,
)
+ def verdict_summary(self) -> str:
+ """Every ``drop`` and ``retry`` reason with its count on one line, for example
+ ``drop/invalid_options=2, retry/not_persisted=1``.
+
+ ``raise_for_status`` reports only totals; log this line when the reasons matter.
+ Drops come first, then retries, each by count and then by reason. It is empty when
+ nothing was dropped or retried.
+ """
+ parts: list[str] = []
+ for verdict, uids in (("drop", self.dropped), ("retry", self.retried)):
+ tally: dict[str, int] = {}
+ for uid in uids:
+ entry = self.results.get(uid)
+ reason = _reported_reason(entry.get("details") if isinstance(entry, dict) else None)
+ tally[reason] = tally.get(reason, 0) + 1
+ for reason, count in sorted(tally.items(), key=lambda item: (-item[1], item[0])):
+ parts.append(f"{verdict}/{reason}={count}")
+ return ", ".join(parts)
+
+
+def _reported_reason(details: Any) -> str:
+ """Clip a reason from the capture response and drop unprintable characters so it cannot break the summary line."""
+ reason = ""
+ if isinstance(details, str):
+ reason = "".join(ch for ch in details if ch.isprintable())[:_MAX_REPORTED_REASON_CHARS]
+ return reason if reason.strip() else "unspecified"
+
# --------------------------------------------------------------------------- #
# Header builder — single chokepoint for every physical POST
@@ -235,16 +259,12 @@ def _resolve_scalar(
field: str,
event_source: str,
) -> Any:
- """Return *explicit* if set, else *legacy*; log + count when both are set and disagree."""
+ """Return *explicit* if set, else *legacy*; count when both are set and disagree.
+
+ A conflict is only counted, never logged: a busy caller would log it once per event.
+ """
if explicit is not None:
if legacy is not None and legacy != explicit:
- logger.warning(
- "capture_internal option conflict",
- event_source=event_source,
- field=field,
- explicit=explicit,
- legacy=legacy,
- )
CAPTURE_V1_OPTION_CONFLICT.labels(event_source=event_source, field=field).inc()
return explicit
return legacy
@@ -267,46 +287,28 @@ class NormalizedEventParts:
properties: dict[str, Any]
-def _reject_unknown_option_keys(event_dict: dict[str, Any], *, event_source: str) -> None:
- """Refuse option keys the v1 envelope has no field for.
-
- Split out of normalization so the batch path can run it before publishing
- anything. It is a set difference, so running it in both places is cheaper
- than normalizing an event twice.
- """
- unknown = set((event_dict.get("options") or {}).keys()) - _VALID_OPTION_KEYS
- if unknown:
- raise CaptureInternalError(f"capture_internal ({event_source}): unknown option key(s): {sorted(unknown)}")
-
-
def _normalize_options_and_properties(
event_dict: dict[str, Any],
*,
process_person_profile: bool,
event_source: str,
) -> NormalizedEventParts:
- """Separate typed ``options``/fields from free-form ``properties``.
+ """Separate ``options`` and top-level fields from free-form ``properties``.
+
+ Options pass through unchanged, including keys capture-rs does not know yet: capture-rs
+ validates the values and ignores unknown keys, so checking them here would only drift
+ from its rules. Each legacy property is always removed and fills its option only when
+ the option is missing or ``None``, the same as the posthog-rs SDK.
Returns a ``NormalizedEventParts``. The caller's dicts are never mutated.
"""
raw_options: dict[str, Any] = event_dict.get("options") or {}
props: dict[str, Any] = dict(event_dict.get("properties") or {})
- _reject_unknown_option_keys(event_dict, event_source=event_source)
-
- options: dict[str, Any] = {}
-
+ options: dict[str, Any] = dict(raw_options)
for opt_key, legacy_prop in _OPTIONS_TO_LEGACY_PROPERTY.items():
- explicit = raw_options.get(opt_key)
legacy = props.pop(legacy_prop, None)
-
- alias = _EXTRA_LEGACY_ALIASES.get(opt_key)
- if alias:
- alias_val = props.pop(alias, None)
- if legacy is None:
- legacy = alias_val
-
- resolved = _resolve_scalar(explicit, legacy, field=opt_key, event_source=event_source)
+ resolved = _resolve_scalar(raw_options.get(opt_key), legacy, field=opt_key, event_source=event_source)
if resolved is not None:
options[opt_key] = resolved
@@ -324,17 +326,10 @@ def _normalize_options_and_properties(
)
# Function-level override: when the caller says no person processing,
- # force it even if the event-level option disagrees (but log the conflict).
+ # force it even if the event-level option disagrees (and count the conflict).
if not process_person_profile:
existing = options.get("process_person_profile")
if existing not in (None, False):
- logger.warning(
- "capture_internal option conflict",
- event_source=event_source,
- field="process_person_profile",
- explicit=f"function_param={process_person_profile}",
- legacy=existing,
- )
CAPTURE_V1_OPTION_CONFLICT.labels(event_source=event_source, field="process_person_profile").inc()
options["process_person_profile"] = False
@@ -398,8 +393,6 @@ def _validate_event(ev: dict[str, Any], *, event_source: str, ai_lane: bool) ->
if not distinct_id:
raise CaptureInternalError(f"{fn} ({event_source}, {event_name}): distinct_id is required")
- _reject_unknown_option_keys(ev, event_source=event_source)
-
return EventIdentity(event_name=event_name, distinct_id=distinct_id)
@@ -701,6 +694,13 @@ def _merge_results(chunk_results: list[CaptureInternalResult]) -> CaptureInterna
return merged
+def _with_event_uuid(ev: dict[str, Any]) -> dict[str, Any]:
+ """Return ``ev`` with a uuid. It copies ``ev`` when it generates one, so the caller's dict is not changed."""
+ if ev.get("event_uuid") or ev.get("uuid"):
+ return ev
+ return {**ev, "uuid": str(uuid4())}
+
+
def _submit_chunks(
*,
lanes: list[tuple[list[dict[str, Any]], bool]],
@@ -739,6 +739,9 @@ def _submit_chunks(
if len(chunks) == 1:
return _submit_chunk(*chunks[0])
+ # A chunk whose worker raises must still report its events, so fix every uuid before fan-out.
+ chunks = [([_with_event_uuid(ev) for ev in chunk_events], ai_lane) for chunk_events, ai_lane in chunks]
+
logger.info(
"capture_batch_internal_chunked",
event_source=event_source,
@@ -767,10 +770,13 @@ def _submit_chunks(
error=str(exc),
)
error = {"error": "chunk_exception", "error_description": str(exc)}
+ chunk_uuids = [ev.get("event_uuid") or ev["uuid"] for ev in chunks[chunk_idx][0]]
chunk_results.append(
CaptureInternalResult(
status_code=0,
+ results={uid: {"result": "unaccounted"} for uid in chunk_uuids},
error=error,
+ unaccounted=chunk_uuids,
request_failures=[
RequestFailure(
lane=_lane_label(ai_lane),
@@ -887,17 +893,21 @@ def capture_batch_internal(
and counted as rerouted; the rest of the batch goes to the analytics lane as usual.
A uuid that appears twice in one batch is rejected before anything is sent.
- event.options reference (typed options replacing legacy $-prefixed properties):
- ┌─────────────────────────┬────────────────────────────┬──────────────┐
- │ options key │ replaces legacy property │ default │
- ├─────────────────────────┼────────────────────────────┼──────────────┤
- │ cookieless_mode │ $cookieless_mode │ None/omitted │
- │ disable_skew_correction │ $ignore_sent_at │ None/omitted │
- │ │ (alias: disable_skew_ │ │
- │ │ adjustment) │ │
- │ product_tour_id │ $product_tour_id │ None/omitted │
- │ process_person_profile │ $process_person_profile │ see below │
- └─────────────────────────┴────────────────────────────┴──────────────┘
+ event.options reference (the keys capture-rs expects, each replacing a legacy
+ $-prefixed property):
+ ┌─────────────────────────┬────────────────────────────┬────────────────────────┐
+ │ options key │ replaces legacy property │ value │
+ ├─────────────────────────┼────────────────────────────┼────────────────────────┤
+ │ cookieless_mode │ $cookieless_mode │ bool │
+ │ disable_skew_correction │ $ignore_sent_at │ bool │
+ │ product_tour_id │ $product_tour_id │ non-empty str │
+ │ process_person_profile │ $process_person_profile │ bool (see below) │
+ └─────────────────────────┴────────────────────────────┴────────────────────────┘
+
+ Options pass through unchanged, and this module does not check their values.
+ capture-rs validates them: it drops an event whose expected option it cannot read
+ (per-event result ``invalid_options``) and ignores keys it does not know. ``None``
+ counts as not set.
Additional top-level event fields (also extracted from properties):
┌─────────────────────────┬────────────────────────────┬──────────────┐
@@ -907,15 +917,16 @@ def capture_batch_internal(
│ window_id │ $window_id │ None/omitted │
└─────────────────────────┴────────────────────────────┴──────────────┘
- When both a typed key AND its legacy $-property are present, the typed key wins
- (a warning metric ``capture_v1_internal_option_conflict`` is emitted). The legacy
- property is always stripped from ``properties`` regardless.
+ When an option and its legacy $-property are both set, the option wins and
+ ``capture_v1_internal_option_conflict`` counts the conflict; nothing is logged. The
+ legacy property is always removed from ``properties``, and it fills the option only
+ when the option is missing or ``None``.
process_person_profile interaction:
The batch-level ``process_person_profile`` param acts as a SAFETY RAIL. When
False (default), it forces ``options.process_person_profile = False`` for EVERY
- event in the batch — even if the event's own options dict says True (a warning
- is logged on conflict). Only when the batch-level param is True does the
+ event in the batch — even if the event's own options dict says True (the
+ conflict is counted). Only when the batch-level param is True does the
per-event ``options.process_person_profile`` value get respected as-is. This
prevents accidental expensive person profile updates from internal tooling.
@@ -926,9 +937,9 @@ def capture_batch_internal(
- ``properties`` (dict): event properties (required; can be empty)
Optional per-event fields:
- ``timestamp`` (str | datetime): defaults to now UTC if absent
- - ``options`` (dict): typed options per table above
+ - ``options`` (dict): event options per table above, sent unchanged
- ``session_id``, ``window_id`` (str): top-level fields per table above
- - ``event_uuid`` (str): deterministic UUID; defaults to a fresh UUIDv7
+ - ``event_uuid`` (str): deterministic UUID; defaults to a fresh random UUID (v4)
token: API token to submit events on behalf of (required; overrides individual
event tokens)
event_source: observability tag indicating the internal module/codepath submitting
@@ -950,8 +961,8 @@ def capture_batch_internal(
Raises:
CaptureInternalError: on client-side validation failures (missing/empty event_source,
- missing token, empty batch, replay event names, unknown option keys) or
- HTTP/transport errors. The exception carries a ``.status_code`` attribute
+ missing token, empty batch, replay event names, non-dict ``options`` or
+ ``properties``) or HTTP/transport errors. The exception carries a ``.status_code`` attribute
(the HTTP status from capture-rs, or 0 for client-side/transport errors).
"""
# Validate early so we fail fast before chunking/fan-out, not inside a worker thread.
@@ -1079,14 +1090,15 @@ def capture_internal(
timestamp: the timestamp of the event (optional; will be set to now UTC if absent).
Accepts datetime objects or ISO8601 strings.
properties: event properties to submit with the event (optional; can be empty).
- Legacy ``$``-prefixed keys that map to typed options are automatically
+ Legacy ``$``-prefixed keys that map to options are automatically
extracted and stripped — see the options table in capture_batch_internal.
- options: typed event options dict (optional). See the options reference table in
- capture_batch_internal for valid keys, legacy equivalents, and defaults.
+ options: event options dict (optional), sent unchanged. See the options reference
+ table in capture_batch_internal for the keys capture-rs expects and their legacy
+ properties.
session_id: session ID (optional). Preferred over ``$session_id`` in properties.
window_id: window ID (optional). Preferred over ``$window_id`` in properties.
- event_uuid: optional deterministic UUID to assign to the event (default: capture-rs
- assigns a fresh UUIDv7). Use when the caller needs a stable, queryable event
+ event_uuid: optional deterministic UUID to assign to the event (default: a fresh
+ random UUID (v4)). Use when the caller needs a stable, queryable event
UUID — e.g. to link back to the event from an admin UI. Must be a parseable
UUID string.
process_person_profile: batch-level safety rail (default: False). When False,
@@ -1152,13 +1164,15 @@ def capture_ai_internal(
A non-`$ai_` name passed here goes to the analytics lane, and an `$ai_` name
passed to capture_internal goes to the AI lane; each reroute is counted
(``capture_v1_internal_events_rerouted``). Prefer the matching entry point: it
- keeps ``historical_migration`` and ``session_id`` / ``window_id`` off AI events.
+ keeps ``historical_migration`` and the ``session_id`` / ``window_id`` arguments off
+ AI events.
``historical_migration`` is not offered: AI backfills do not run through this path.
Args:
- see capture_internal. ``session_id`` / ``window_id`` are omitted because they are
- replay concepts and carry no meaning on the AI lane.
+ see capture_internal. ``session_id`` / ``window_id`` are not offered as arguments,
+ but a ``$session_id`` or ``$window_id`` property still moves to the top-level
+ field, as on the analytics lane.
Returns:
CaptureInternalResult with per-event outcome, exactly as capture_internal.
diff --git a/posthog/api/csp.py b/posthog/api/csp.py
index 09d6b377195c..0315f5a76679 100644
--- a/posthog/api/csp.py
+++ b/posthog/api/csp.py
@@ -222,10 +222,10 @@ def build_crash_event(
"event": "$browser_crash_report",
"distinct_id": distinct_id,
"timestamp": timestamp.isoformat(),
+ "options": {"process_person_profile": False},
"properties": {
"$session_id": session_id,
"$current_url": props["$browser_crash_document_url"],
- "$process_person_profile": False,
"$raw_user_agent": props.get("$browser_crash_user_agent") or user_agent,
**_ip_property(ip),
**props,
@@ -257,11 +257,11 @@ def build_csp_event(
"event": "$csp_violation",
"distinct_id": distinct_id,
"timestamp": datetime.now(UTC).isoformat(),
+ "options": {"process_person_profile": False},
"properties": {
"$session_id": session_id,
"$csp_version": version,
"$current_url": props["$csp_document_url"],
- "$process_person_profile": False,
"$raw_user_agent": user_agent,
**_ip_property(ip),
**props,
diff --git a/posthog/api/report.py b/posthog/api/report.py
index 242b59f3139f..559f45fe2bc7 100644
--- a/posthog/api/report.py
+++ b/posthog/api/report.py
@@ -77,6 +77,7 @@ def get_csp_event(request):
distinct_id=csp_report.get("distinct_id", ""),
timestamp=csp_report.get("timestamp", None),
properties=csp_report.get("properties", {}),
+ options=csp_report.get("options"),
process_person_profile=False,
)
result.raise_for_status()
diff --git a/posthog/api/test/test_capture_internal.py b/posthog/api/test/test_capture_internal.py
index 5b7a8a7bb1d3..06912a6b9f70 100644
--- a/posthog/api/test/test_capture_internal.py
+++ b/posthog/api/test/test_capture_internal.py
@@ -11,6 +11,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
from requests.adapters import HTTPAdapter
from requests.exceptions import ConnectionError as RequestsConnectionError
+from structlog.testing import capture_logs
from posthog.api.capture import (
CAPTURE_V1_EVENTS_REROUTED,
@@ -167,13 +168,25 @@ class TestNormalizeOptionsAndProperties(SimpleTestCase):
assert "$window_id" not in parts.properties
assert parts.properties["keep_me"] == 42
- def test_legacy_alias_disable_skew_adjustment_stripped(self) -> None:
+ def test_undollared_disable_skew_adjustment_is_an_ordinary_property(self) -> None:
ev: dict[str, Any] = {
"properties": {"disable_skew_adjustment": True, "other": 1},
}
parts = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")
- assert parts.options["disable_skew_correction"] is True
- assert "disable_skew_adjustment" not in parts.properties
+ assert parts.options == {}
+ assert parts.properties == {"disable_skew_adjustment": True, "other": 1}
+
+ @parameterized.expand(
+ [
+ ("missing_option", {}),
+ ("none_option", {"product_tour_id": None}),
+ ]
+ )
+ def test_legacy_property_fills_a_missing_or_none_option(self, _name: str, options: dict[str, Any]) -> None:
+ ev: dict[str, Any] = {"options": options, "properties": {"$product_tour_id": "tour_legacy"}}
+ parts = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")
+ assert parts.options == {"product_tour_id": "tour_legacy"}
+ assert "$product_tour_id" not in parts.properties
def test_explicit_wins_over_legacy_on_conflict(self) -> None:
ev: dict[str, Any] = {
@@ -187,11 +200,19 @@ class TestNormalizeOptionsAndProperties(SimpleTestCase):
assert "$cookieless_mode" not in parts.properties
assert "$session_id" not in parts.properties
- def test_unknown_option_key_raises(self) -> None:
- ev: dict[str, Any] = {"options": {"bogus_key": True}, "properties": {}}
- with self.assertRaises(CaptureInternalError) as ctx:
- _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")
- assert "unknown option key" in str(ctx.exception)
+ @parameterized.expand(
+ [
+ ("unknown_key", {"future_option": {"nested": [1, "two"]}}),
+ ("unconverted_string", {"process_person_profile": "no"}),
+ ("unconverted_number", {"cookieless_mode": 1, "disable_skew_correction": 0}),
+ ("non_string_tour_id", {"product_tour_id": 42}),
+ ("explicit_none", {"cookieless_mode": None}),
+ ]
+ )
+ def test_options_pass_through_unchanged(self, _name: str, options: dict[str, Any]) -> None:
+ ev: dict[str, Any] = {"options": options, "properties": {}}
+ parts = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")
+ assert parts.options == options
def test_process_person_profile_false_forces_option(self) -> None:
ev: dict[str, Any] = {"properties": {}}
@@ -228,11 +249,13 @@ class TestNormalizeOptionsAndProperties(SimpleTestCase):
("window_id_conflict", {"window_id": "a", "properties": {"$window_id": "b"}}, "window_id"),
]
)
- def test_conflict_increments_metric(self, _name: str, ev: dict[str, Any], field: str) -> None:
+ def test_conflict_increments_metric_without_logging(self, _name: str, ev: dict[str, Any], field: str) -> None:
before = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="metric_test", field=field)._value.get()
- _normalize_options_and_properties(ev, process_person_profile=True, event_source="metric_test")
+ with capture_logs() as logs:
+ _normalize_options_and_properties(ev, process_person_profile=True, event_source="metric_test")
after = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="metric_test", field=field)._value.get()
assert after == before + 1
+ assert logs == []
def test_ppp_false_overrides_explicit_true_with_conflict(self) -> None:
ev: dict[str, Any] = {
@@ -240,10 +263,12 @@ class TestNormalizeOptionsAndProperties(SimpleTestCase):
"properties": {},
}
before = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="ppp_test", field="process_person_profile")._value.get()
- parts = _normalize_options_and_properties(ev, process_person_profile=False, event_source="ppp_test")
+ with capture_logs() as logs:
+ parts = _normalize_options_and_properties(ev, process_person_profile=False, event_source="ppp_test")
after = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="ppp_test", field="process_person_profile")._value.get()
assert parts.options["process_person_profile"] is False
assert after == before + 1
+ assert logs == []
class TestResolveScalar(SimpleTestCase):
@@ -466,22 +491,19 @@ class TestCaptureBatchInternal(SimpleTestCase):
@patch("posthog.api.capture.internal_requests_session")
def test_options_propagated_to_wire(self, mock_session_fn: MagicMock) -> None:
uid = str(uuid4())
- events = [
- _make_event(
- event_uuid=uid,
- options={"cookieless_mode": True, "disable_skew_correction": True, "product_tour_id": "t1"},
- session_id="s1",
- window_id="w1",
- )
- ]
+ options = {
+ "cookieless_mode": True,
+ "disable_skew_correction": "yes",
+ "product_tour_id": "t1",
+ "future_option": {"nested": [1, "two"]},
+ }
+ events = [_make_event(event_uuid=uid, options=options, session_id="s1", window_id="w1")]
spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])
capture_batch_internal(events=events, token="tok", event_source="opt")
entry = spy.calls[0]["json"]["batch"][0]
- assert entry["options"]["cookieless_mode"] is True
- assert entry["options"]["disable_skew_correction"] is True
- assert entry["options"]["product_tour_id"] == "t1"
+ assert entry["options"] == {**options, "process_person_profile": False}
assert entry["session_id"] == "s1"
assert entry["window_id"] == "w1"
assert "$cookieless_mode" not in entry["properties"]
@@ -1088,20 +1110,67 @@ class TestCaptureInternalResult(SimpleTestCase):
@parameterized.expand(
[
- ("dropped", {"dropped": ["a"]}),
- ("retried", {"retried": ["a"]}),
- ("unaccounted", {"unaccounted": ["a"]}),
+ (
+ "dropped_reason_left_out",
+ {"dropped": ["a"], "results": {"a": {"result": "drop", "details": "invalid_options"}}},
+ "1 dropped, 0 exhausted retries, 0 unaccounted",
+ ),
+ ("retried", {"retried": ["a"]}, "0 dropped, 1 exhausted retries, 0 unaccounted"),
+ ("unaccounted", {"unaccounted": ["a"]}, "0 dropped, 0 exhausted retries, 1 unaccounted"),
]
)
- def test_raise_for_status_on_partial_failure(self, _name: str, kwargs: dict[str, Any]) -> None:
+ def test_raise_for_status_on_partial_failure(self, _name: str, kwargs: dict[str, Any], totals: str) -> None:
r = CaptureInternalResult(status_code=200, **kwargs)
- with self.assertRaises(CaptureInternalError):
+ with self.assertRaises(CaptureInternalError) as ctx:
r.raise_for_status()
+ assert str(ctx.exception) == f"capture internal partial failure: {totals}"
def test_raise_for_status_noop_on_success(self) -> None:
r = CaptureInternalResult(status_code=200, ok=["a"])
r.raise_for_status()
+ @parameterized.expand(
+ [
+ (
+ "counts_per_reason",
+ [("drop", "invalid_options"), ("drop", "invalid_options"), ("drop", "missing_distinct_id")],
+ [("retry", "not_persisted")],
+ "drop/invalid_options=2, drop/missing_distinct_id=1, retry/not_persisted=1",
+ ),
+ (
+ "lists_every_reason",
+ [("drop", f"r{i}") for i in range(1, 7) for _ in range(7 - i)],
+ [("retry", "not_persisted"), ("retry", "rejected")],
+ "drop/r1=6, drop/r2=5, drop/r3=4, drop/r4=3, drop/r5=2, drop/r6=1, retry/not_persisted=1, retry/rejected=1",
+ ),
+ (
+ "cleans_reasons",
+ [("drop", "x" * 100), ("drop", "bad\nreason"), ("drop", "a\u2028b"), ("drop", None), ("drop", " ")],
+ [],
+ f"drop/unspecified=2, drop/ab=1, drop/badreason=1, drop/{'x' * 64}=1",
+ ),
+ ("nothing_lost", [], [], ""),
+ ]
+ )
+ def test_verdict_summary(
+ self,
+ _name: str,
+ dropped: list[tuple[str, str | None]],
+ retried: list[tuple[str, str | None]],
+ expected: str,
+ ) -> None:
+ results: dict[str, dict[str, Any]] = {}
+ for status, details in [*dropped, *retried]:
+ entry: dict[str, Any] = {"result": status}
+ if details is not None:
+ entry["details"] = details
+ results[str(uuid4())] = entry
+ uids = list(results)
+ r = CaptureInternalResult(
+ status_code=200, results=results, dropped=uids[: len(dropped)], retried=uids[len(dropped) :]
+ )
+ assert r.verdict_summary() == expected
+
# --------------------------------------------------------------------------- #
# Helpers for chunking tests
@@ -1189,22 +1258,30 @@ class TestBatchChunking(SimpleTestCase):
batch_sizes = sorted(len(c["json"]["batch"]) for c in spy.calls)
assert batch_sizes == [50, 200, 200]
+ @parameterized.expand(
+ [
+ ("transport_error_caller_uuids", RequestsConnectionError("connection refused"), True),
+ ("transport_error_generated_uuids", RequestsConnectionError("connection refused"), False),
+ ("worker_exception_caller_uuids", TypeError("Object of type set is not JSON serializable"), True),
+ ("worker_exception_generated_uuids", TypeError("Object of type set is not JSON serializable"), False),
+ ]
+ )
@patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 200)
@patch("posthog.api.capture.CAPTURE_INTERNAL_MAX_WORKERS", 8)
@patch("posthog.api.capture.internal_requests_session")
- def test_partial_chunk_failure_preserves_successful_chunks(self, mock_session_fn: MagicMock) -> None:
+ def test_partial_chunk_failure_preserves_successful_chunks(
+ self, _name: str, failure: Exception, with_uuids: bool, mock_session_fn: MagicMock
+ ) -> None:
events = _make_batch(400)
- chunk1_uuids = [e["event_uuid"] for e in events[:200]]
- lock = threading.Lock()
+ if not with_uuids:
+ for ev in events:
+ del ev["event_uuid"]
def spy_post(url: str, **kwargs: Any) -> MockResponse:
- with lock:
- pass
- batch_uuids = [e["uuid"] for e in kwargs["json"]["batch"]]
- if set(batch_uuids) & set(chunk1_uuids):
- return MockResponse(body=_ok_results(*batch_uuids))
- else:
- raise RequestsConnectionError("connection refused")
+ batch = kwargs["json"]["batch"]
+ if any(e["properties"]["url"].endswith("/page/0") for e in batch):
+ return MockResponse(body=_ok_results(*[e["uuid"] for e in batch]))
+ raise failure
mock_session = MagicMock()
mock_session.post.side_effect = spy_post
@@ -1213,9 +1290,18 @@ class TestBatchChunking(SimpleTestCase):
result = capture_batch_internal(events=events, token="tok", event_source="partial")
- assert not result.succeeded()
- assert len(result.ok) == 200
assert result.error is not None
+ assert result.error["error"] == "partial_request_failure"
+ assert len(result.ok) == 200
+ assert len(result.unaccounted) == 200
+ assert set(result.ok).isdisjoint(result.unaccounted)
+ assert all(result.results[uid] == {"result": "unaccounted"} for uid in result.unaccounted)
+ if with_uuids:
+ assert set(result.unaccounted) == {e["event_uuid"] for e in events[200:]}
+ else:
+ assert all("uuid" not in e for e in events)
+ with self.assertRaisesRegex(CaptureInternalError, "200 events acked, 200 unaccounted"):
+ result.raise_for_status()
@patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 200)
@patch("posthog.api.capture.CAPTURE_INTERNAL_MAX_WORKERS", 8)
@@ -1317,22 +1403,6 @@ class TestBatchChunking(SimpleTestCase):
assert by_url[majority_url] == uuids[:200]
assert by_url[odd_url] == uuids[200:]
- @patch("posthog.api.capture.CAPTURE_INTERNAL_BATCH_CHUNK_SIZE", 200)
- @patch("posthog.api.capture.CAPTURE_INTERNAL_MAX_WORKERS", 8)
- @patch("posthog.api.capture.internal_requests_session")
- def test_bad_option_key_in_a_later_chunk_stops_the_whole_batch(self, mock_session_fn: MagicMock) -> None:
- # The routing checks are not the only client-side rejection: an unknown
- # option key is caught during normalization, which runs per chunk.
- events = _make_batch(201)
- events[200]["options"] = {"bogus_key": True}
- spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results())])
-
- with self.assertRaises(CaptureInternalError) as ctx:
- capture_batch_internal(events=events, token="tok", event_source="bad_option")
-
- assert "unknown option key" in str(ctx.exception)
- assert spy.calls == [], "a batch that fails validation must not publish any chunk"
-
class TestMergeResults(SimpleTestCase):
def test_merge_all_success(self) -> None:
@@ -1679,6 +1749,24 @@ class TestCaptureAiInternal(SimpleTestCase):
assert result.succeeded()
assert [c["url"] for c in spy.calls] == [EXPECTED_URL]
+ @patch("posthog.api.capture.internal_requests_session")
+ def test_session_properties_move_to_top_level_fields_on_the_ai_lane(self, mock_session_fn: MagicMock) -> None:
+ uid = str(uuid4())
+ spy = InstallV1Spy(mock_session_fn, [MockResponse(body=_ok_results(uid))])
+
+ capture_ai_internal(
+ token="tok",
+ event_name="$ai_generation",
+ event_source="ai-src",
+ distinct_id="user-1",
+ event_uuid=uid,
+ properties={"$session_id": "s1", "$window_id": "w1", "$ai_model": "m"},
+ )
+
+ entry = spy.calls[0]["json"]["batch"][0]
+ assert (entry["session_id"], entry["window_id"]) == ("s1", "w1")
+ assert entry["properties"] == {"$ai_model": "m"}
+
@patch("posthog.api.capture.internal_requests_session")
def test_server_side_misrouted_drop_surfaces_per_event(self, mock_session_fn: MagicMock) -> None:
"""Django routes on the prefix; capture applies its own predicate. A prefixed
diff --git a/posthog/api/test/test_csp.py b/posthog/api/test/test_csp.py
index 3b59fc645e9f..3b8f76075dee 100644
--- a/posthog/api/test/test_csp.py
+++ b/posthog/api/test/test_csp.py
@@ -280,6 +280,8 @@ class TestCSPModule(TestCase):
assert event["distinct_id"] == "test-user"
assert event["properties"]["$session_id"] == "test-session"
assert event["properties"]["$csp_version"] == "1"
+ assert event["options"] == {"process_person_profile": False}
+ assert "$process_person_profile" not in event["properties"]
@time_machine.travel("2023-01-01 12:00:00", tick=False)
def test_sample_csp_report(self):
diff --git a/posthog/api/test/test_report.py b/posthog/api/test/test_report.py
index db770049de5e..05bc4111a2c1 100644
--- a/posthog/api/test/test_report.py
+++ b/posthog/api/test/test_report.py
@@ -158,6 +158,8 @@ class TestCspReport(BaseTest):
assert event["properties"]["$browser_crash_reason"] == "oom"
assert event["properties"]["$browser_crash_is_top_level"] is True
assert event["properties"]["$current_url"] == "https://app.example.com/dashboard/1"
+ assert event["options"] == {"process_person_profile": False}
+ assert "$process_person_profile" not in event["properties"]
# the report's `age` (42s here) recovers the crash time; delivery happens on a later visit
assert event["timestamp"] == "2026-08-12T09:59:18+00:00"