:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ingestion): return frozen dataclasses instead of tuples (#76127)
Arno Hillen882a613d8d5c
diff --git a/posthog/api/capture.py b/posthog/api/capture.pyindex 78e172885f67..f02c61628012 100644--- a/posthog/api/capture.py+++ b/posthog/api/capture.py@@ -218,16 +218,23 @@ def _resolve_scalar(return legacy+@dataclass(frozen=True, kw_only=True, slots=True)+class NormalizedEventParts:+ options: dict[str, Any]+ session_id: Optional[str]+ window_id: Optional[str]+ properties: dict[str, Any]++def _normalize_options_and_properties(event_dict: dict[str, Any],*,process_person_profile: bool,event_source: str,-) -> tuple[dict[str, Any], Optional[str], Optional[str], dict[str, Any]]:+) -> NormalizedEventParts:"""Separate typed ``options``/fields from free-form ``properties``.- Returns ``(options_dict, session_id, window_id, cleaned_properties)``.- The caller's dicts are never mutated.+ 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 {})@@ -280,7 +287,7 @@ def _normalize_options_and_properties(CAPTURE_V1_OPTION_CONFLICT.labels(event_source=event_source, field="process_person_profile").inc()options["process_person_profile"] = False- return options, session_id, window_id, props+ return NormalizedEventParts(options=options, session_id=session_id, window_id=window_id, properties=props)# --------------------------------------------------------------------------- #@@ -346,7 +353,7 @@ def prepare_capture_internal_batch(else:timestamp_str = str(raw_ts)- options, session_id, window_id, cleaned_props = _normalize_options_and_properties(+ parts = _normalize_options_and_properties(ev, process_person_profile=process_person_profile, event_source=event_source)@@ -355,14 +362,14 @@ def prepare_capture_internal_batch("uuid": event_uuid,"distinct_id": distinct_id,"timestamp": timestamp_str,- "properties": cleaned_props,+ "properties": parts.properties,}- if session_id is not None:- entry["session_id"] = session_id- if window_id is not None:- entry["window_id"] = window_id- if options:- entry["options"] = options+ if parts.session_id is not None:+ entry["session_id"] = parts.session_id+ if parts.window_id is not None:+ entry["window_id"] = parts.window_id+ if parts.options:+ entry["options"] = parts.optionsbatch.append(entry)diff --git a/posthog/api/test/test_capture_internal.py b/posthog/api/test/test_capture_internal.pyindex 2b2b1c96bcff..c3f45aee7418 100644--- a/posthog/api/test/test_capture_internal.py+++ b/posthog/api/test/test_capture_internal.py@@ -120,16 +120,14 @@ class TestNormalizeOptionsAndProperties(SimpleTestCase):"options": {"cookieless_mode": True, "disable_skew_correction": True, "product_tour_id": "tour-1"},"properties": {"some_prop": "val"},}- options, sid, wid, props = _normalize_options_and_properties(- ev, process_person_profile=True, event_source="test"- )- assert options["cookieless_mode"] is True- assert options["disable_skew_correction"] is True- assert options["product_tour_id"] == "tour-1"- assert "process_person_profile" not in options- assert sid is None- assert wid is None- assert props == {"some_prop": "val"}+ parts = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")+ assert parts.options["cookieless_mode"] is True+ assert parts.options["disable_skew_correction"] is True+ assert parts.options["product_tour_id"] == "tour-1"+ assert "process_person_profile" not in parts.options+ assert parts.session_id is None+ assert parts.window_id is None+ assert parts.properties == {"some_prop": "val"}def test_legacy_properties_lifted_and_stripped(self) -> None:ev: dict[str, Any] = {@@ -143,29 +141,27 @@ class TestNormalizeOptionsAndProperties(SimpleTestCase):"keep_me": 42,},}- options, sid, wid, props = _normalize_options_and_properties(- ev, process_person_profile=True, event_source="test"- )- assert options["cookieless_mode"] is True- assert options["disable_skew_correction"] is True- assert options["product_tour_id"] == "tour-2"- assert sid == "sess-1"- assert wid == "win-1"- assert "$cookieless_mode" not in props- assert "$ignore_sent_at" not in props- assert "$product_tour_id" not in props- assert "$process_person_profile" not in props- assert "$session_id" not in props- assert "$window_id" not in props- assert props["keep_me"] == 42+ parts = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")+ assert parts.options["cookieless_mode"] is True+ assert parts.options["disable_skew_correction"] is True+ assert parts.options["product_tour_id"] == "tour-2"+ assert parts.session_id == "sess-1"+ assert parts.window_id == "win-1"+ assert "$cookieless_mode" not in parts.properties+ assert "$ignore_sent_at" not in parts.properties+ assert "$product_tour_id" not in parts.properties+ assert "$process_person_profile" not in parts.properties+ assert "$session_id" not in parts.properties+ assert "$window_id" not in parts.properties+ assert parts.properties["keep_me"] == 42def test_legacy_alias_disable_skew_adjustment_stripped(self) -> None:ev: dict[str, Any] = {"properties": {"disable_skew_adjustment": True, "other": 1},}- options, _, _, props = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")- assert options["disable_skew_correction"] is True- assert "disable_skew_adjustment" not in props+ 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.propertiesdef test_explicit_wins_over_legacy_on_conflict(self) -> None:ev: dict[str, Any] = {@@ -173,11 +169,11 @@ class TestNormalizeOptionsAndProperties(SimpleTestCase):"session_id": "explicit-sess","properties": {"$cookieless_mode": True, "$session_id": "legacy-sess"},}- options, sid, _, props = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")- assert options["cookieless_mode"] is False- assert sid == "explicit-sess"- assert "$cookieless_mode" not in props- assert "$session_id" not in props+ parts = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")+ assert parts.options["cookieless_mode"] is False+ assert parts.session_id == "explicit-sess"+ assert "$cookieless_mode" not in parts.properties+ assert "$session_id" not in parts.propertiesdef test_unknown_option_key_raises(self) -> None:ev: dict[str, Any] = {"options": {"bogus_key": True}, "properties": {}}@@ -187,23 +183,21 @@ class TestNormalizeOptionsAndProperties(SimpleTestCase):def test_process_person_profile_false_forces_option(self) -> None:ev: dict[str, Any] = {"properties": {}}- options, _, _, _ = _normalize_options_and_properties(ev, process_person_profile=False, event_source="test")- assert options["process_person_profile"] is False+ parts = _normalize_options_and_properties(ev, process_person_profile=False, event_source="test")+ assert parts.options["process_person_profile"] is Falsedef test_process_person_profile_true_leaves_unset(self) -> None:ev: dict[str, Any] = {"properties": {}}- options, _, _, _ = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")- assert "process_person_profile" not in options+ parts = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")+ assert "process_person_profile" not in parts.optionsdef test_no_options_when_all_empty_and_ppp_true(self) -> None:ev: dict[str, Any] = {"properties": {"keep": 1}}- options, sid, wid, props = _normalize_options_and_properties(- ev, process_person_profile=True, event_source="test"- )- assert options == {}- assert sid is None- assert wid is None- assert props == {"keep": 1}+ parts = _normalize_options_and_properties(ev, process_person_profile=True, event_source="test")+ assert parts.options == {}+ assert parts.session_id is None+ assert parts.window_id is None+ assert parts.properties == {"keep": 1}def test_caller_input_not_mutated(self) -> None:original_props = {"$session_id": "s1", "keep": 1}@@ -234,9 +228,9 @@ class TestNormalizeOptionsAndProperties(SimpleTestCase):"properties": {},}before = CAPTURE_V1_OPTION_CONFLICT.labels(event_source="ppp_test", field="process_person_profile")._value.get()- options, _, _, _ = _normalize_options_and_properties(ev, process_person_profile=False, event_source="ppp_test")+ 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 options["process_person_profile"] is False+ assert parts.options["process_person_profile"] is Falseassert after == before + 1diff --git a/posthog/dags/person_property_reconciliation.py b/posthog/dags/person_property_reconciliation.pyindex e4bfd46c65b2..2ce7377a14e9 100644--- a/posthog/dags/person_property_reconciliation.py+++ b/posthog/dags/person_property_reconciliation.py@@ -1494,6 +1494,14 @@ def backup_person_with_computed_state(return cursor.rowcount > 0+@dataclass(frozen=True, kw_only=True, slots=True)+class PersonUpdateResult:+ success: bool+ updated_person_data: dict | None+ backup_created: bool+ skip_reason: str++def update_person_with_version_check(cursor,job_id: str,@@ -1503,7 +1511,7 @@ def update_person_with_version_check(dry_run: bool = False,backup_enabled: bool = True,max_retries: int = 3,-) -> tuple[bool, dict | None, bool, str]:+) -> PersonUpdateResult:"""Update a person's properties with optimistic locking and conflict resolution.@@ -1524,10 +1532,10 @@ def update_person_with_version_check(max_retries: Maximum retry attempts on version mismatchReturns:- Tuple of (success: bool, updated_person_data: dict | None, backup_created: bool, skip_reason: str)- updated_person_data contains the final state for Kafka publishing- backup_created indicates if a backup row was inserted- skip_reason indicates why the person was skipped (see SkipReason class)+ PersonUpdateResult where:+ - updated_person_data contains the final state for Kafka publishing+ - backup_created indicates if a backup row was inserted+ - skip_reason indicates why the person was skipped (see SkipReason class)"""ch_version = person_property_diffs.person_version@@ -1535,7 +1543,9 @@ def update_person_with_version_check(# Fetch current person state from Postgresperson = fetch_person_from_postgres(cursor, team_id, person_uuid)if not person:- return False, None, False, SkipReason.NOT_FOUND+ return PersonUpdateResult(+ success=False, updated_person_data=None, backup_created=False, skip_reason=SkipReason.NOT_FOUND+ )postgres_version = person.get("version") or 0@@ -1550,7 +1560,9 @@ def update_person_with_version_check(ch_properties = fetch_person_properties_from_clickhouse(team_id, person_uuid, ch_version)if ch_properties is None:# Person version doesn't exist in CH anymore, skip- return False, None, False, SkipReason.NOT_FOUND+ return PersonUpdateResult(+ success=False, updated_person_data=None, backup_created=False, skip_reason=SkipReason.NOT_FOUND+ )# 3-way merge: apply our changes while respecting concurrent Postgres changesupdate = reconcile_with_concurrent_changes(ch_properties, person, person_property_diffs)@@ -1558,7 +1570,9 @@ def update_person_with_version_check(if not update:# No changes needed (either no diffs or all conflicts resolved to Postgres values)- return True, None, False, SkipReason.NO_CHANGES+ return PersonUpdateResult(+ success=True, updated_person_data=None, backup_created=False, skip_reason=SkipReason.NO_CHANGES+ )# Backup before and after state for audit/rollbackbackup_created = False@@ -1568,7 +1582,9 @@ def update_person_with_version_check()if dry_run:- return True, None, backup_created, SkipReason.SUCCESS+ return PersonUpdateResult(+ success=True, updated_person_data=None, backup_created=backup_created, skip_reason=SkipReason.SUCCESS+ )# Write with version checkcursor.execute(@@ -1594,9 +1610,9 @@ def update_person_with_version_check(if cursor.rowcount > 0:# Success - return data for Kafka publishing- return (- True,- {+ return PersonUpdateResult(+ success=True,+ updated_person_data={"id": person_uuid,"team_id": team_id,"properties": update["properties"],@@ -1605,15 +1621,17 @@ def update_person_with_version_check("created_at": person.get("created_at"),"version": target_version + 1,},- backup_created,- SkipReason.SUCCESS,+ backup_created=backup_created,+ skip_reason=SkipReason.SUCCESS,)# Version mismatch during UPDATE - retry with fresh data# (loop will re-fetch person)# Exhausted retries- return False, None, False, SkipReason.VERSION_CONFLICT+ return PersonUpdateResult(+ success=False, updated_person_data=None, backup_created=False, skip_reason=SkipReason.VERSION_CONFLICT+ )@dataclass@@ -1702,7 +1720,7 @@ def process_persons_in_batches(batch_num += 1for i, person_diffs in enumerate(person_property_diffs):- success, person_data, backup_created, skip_reason = update_person_with_version_check(+ update_result = update_person_with_version_check(cursor=cursor,job_id=job_id,team_id=team_id,@@ -1712,20 +1730,22 @@ def process_persons_in_batches(backup_enabled=backup_enabled,)- if backup_created:+ if update_result.backup_created:batch_has_backups = True- if not success:+ if not update_result.success:total_skipped += 1if logger:- logger.warning(f"Skipped person uuid={person_diffs.person_id} team_id={team_id} reason={skip_reason}")- elif person_data:- batch_persons_to_publish.append(person_data)+ logger.warning(+ f"Skipped person uuid={person_diffs.person_id} team_id={team_id} reason={update_result.skip_reason}"+ )+ elif update_result.updated_person_data:+ batch_persons_to_publish.append(update_result.updated_person_data)total_updated += 1if on_person_updated:- on_person_updated(person_data)+ on_person_updated(update_result.updated_person_data)else:- # No changes needed (success=True but person_data=None)+ # No changes needed (success=True but updated_person_data=None)total_skipped += 1total_processed += 1diff --git a/posthog/dags/tests/test_person_property_reconciliation.py b/posthog/dags/tests/test_person_property_reconciliation.pyindex 28a2df263901..66a2ab49999b 100644--- a/posthog/dags/tests/test_person_property_reconciliation.py+++ b/posthog/dags/tests/test_person_property_reconciliation.py@@ -692,7 +692,7 @@ class TestUpdatePersonWithVersionCheck:unset_updates={},)- success, result_data, _backup_created, _skip_reason = update_person_with_version_check(+ result = update_person_with_version_check(cursor=cursor,job_id="test-job-id",team_id=1,@@ -701,11 +701,11 @@ class TestUpdatePersonWithVersionCheck:dry_run=False,)- assert success is True- assert result_data is not None- assert result_data["version"] == 6 # version incremented- assert result_data["properties"]["email"] == "[email protected]"- assert result_data["properties"]["existing"] == "value"+ assert result.success is True+ assert result.updated_person_data is not None+ assert result.updated_person_data["version"] == 6 # version incremented+ assert result.updated_person_data["properties"]["email"] == "[email protected]"+ assert result.updated_person_data["properties"]["existing"] == "value"# Verify UPDATE was executedupdate_calls = [call for call in cursor.execute.call_args_list if "UPDATE posthog_person" in str(call)]@@ -755,7 +755,7 @@ class TestUpdatePersonWithVersionCheck:unset_updates={},)- success, result_data, _backup_created, _skip_reason = update_person_with_version_check(+ result = update_person_with_version_check(cursor=cursor,job_id="test-job-id",team_id=1,@@ -764,8 +764,8 @@ class TestUpdatePersonWithVersionCheck:dry_run=True,)- assert success is True- assert result_data is None # No data returned for Kafka in dry run+ assert result.success is True+ assert result.updated_person_data is None # No data returned for Kafka in dry run# Verify UPDATE was NOT executedupdate_calls = [call for call in cursor.execute.call_args_list if "UPDATE posthog_person" in str(call)]@@ -791,7 +791,7 @@ class TestUpdatePersonWithVersionCheck:unset_updates={},)- success, result_data, _backup_created, skip_reason = update_person_with_version_check(+ result = update_person_with_version_check(cursor=cursor,job_id="test-job-id",team_id=1,@@ -799,9 +799,9 @@ class TestUpdatePersonWithVersionCheck:person_property_diffs=person_diffs,)- assert success is False- assert result_data is None- assert skip_reason == SkipReason.NOT_FOUND+ assert result.success is False+ assert result.updated_person_data is None+ assert result.skip_reason == SkipReason.NOT_FOUND@patch("posthog.dags.person_property_reconciliation.fetch_person_properties_from_clickhouse")def test_version_mismatch_retry(self, mock_fetch_ch_properties):@@ -860,7 +860,7 @@ class TestUpdatePersonWithVersionCheck:unset_updates={},)- success, result_data, _backup_created, _skip_reason = update_person_with_version_check(+ result = update_person_with_version_check(cursor=cursor,job_id="test-job-id",team_id=1,@@ -869,12 +869,12 @@ class TestUpdatePersonWithVersionCheck:max_retries=3,)- assert success is True- assert result_data is not None- assert result_data["version"] == 3 # v2 + 1+ assert result.success is True+ assert result.updated_person_data is not None+ assert result.updated_person_data["version"] == 3 # v2 + 1# Concurrent change should be preserved, our change should be applied- assert result_data["properties"]["other"] == "concurrent_change"- assert result_data["properties"]["email"] == "[email protected]"+ assert result.updated_person_data["properties"]["other"] == "concurrent_change"+ assert result.updated_person_data["properties"]["email"] == "[email protected]"def test_exhausted_retries(self):"""Test failure after exhausting all retries."""@@ -901,7 +901,7 @@ class TestUpdatePersonWithVersionCheck:unset_updates={},)- success, result_data, _backup_created, skip_reason = update_person_with_version_check(+ result = update_person_with_version_check(cursor=cursor,job_id="test-job-id",team_id=1,@@ -910,9 +910,9 @@ class TestUpdatePersonWithVersionCheck:max_retries=3,)- assert success is False- assert result_data is None- assert skip_reason == SkipReason.VERSION_CONFLICT+ assert result.success is False+ assert result.updated_person_data is None+ assert result.skip_reason == SkipReason.VERSION_CONFLICTclass TestBatchCommits:@@ -1308,7 +1308,7 @@ class TestBackupFunctionality:unset_updates={},)- success, result_data, backup_created, _skip_reason = update_person_with_version_check(+ result = update_person_with_version_check(cursor=cursor,job_id="test-job-id",team_id=1,@@ -1318,9 +1318,9 @@ class TestBackupFunctionality:backup_enabled=False,)- assert success is True- assert result_data is not None- assert backup_created is False+ assert result.success is True+ assert result.updated_person_data is not None+ assert result.backup_created is False# Verify backup INSERT was NOT executedbackup_calls = [@@ -1359,7 +1359,7 @@ class TestBackupFunctionality:unset_updates={},)- success, _result_data, backup_created, _skip_reason = update_person_with_version_check(+ result = update_person_with_version_check(cursor=cursor,job_id="test-job-id",team_id=1,@@ -1369,8 +1369,8 @@ class TestBackupFunctionality:backup_enabled=True,)- assert success is True- assert backup_created is True+ assert result.success is True+ assert result.backup_created is Truedef test_backup_created_false_when_conflict(self):"""@@ -1416,7 +1416,7 @@ class TestBackupFunctionality:unset_updates={},)- success, _result_data, backup_created, _skip_reason = update_person_with_version_check(+ result = update_person_with_version_check(cursor=cursor,job_id="test-job-id",team_id=1,@@ -1426,9 +1426,9 @@ class TestBackupFunctionality:backup_enabled=True,)- assert success is True+ assert result.success is True# Key assertion: backup_created should be False because rowcount was 0- assert backup_created is False+ assert result.backup_created is Falseclass TestFilterEventPersonProperties: