: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
fix(replay-vision): stamp the recorded session's location on recording (#111843)
Hayne Ryu348cdc19a29e
diff --git a/.github/new-events-schema-targets.txt b/.github/new-events-schema-targets.txtindex 267875b43662..04fe5a11e700 100644--- a/.github/new-events-schema-targets.txt+++ b/.github/new-events-schema-targets.txt@@ -39,6 +39,7 @@ products/mcp_analytics/backend/tests/test_protocol_version_breakdown.pyproducts/mcp_analytics/backend/tests/test_tool_quality_tables.pyproducts/mcp_analytics/backend/tests/test_tool_tables.pyproducts/product_analytics/backend/hogql_queries+products/replay_vision/backend/tests/test_session_identity.pyproducts/web_analytics/backend/hogql_queries# Code outside HogQL that builds events SQL itself and branches on the schemadiff --git a/products/replay_vision/backend/migrations/0111_replayobservation_session_geoip.py b/products/replay_vision/backend/migrations/0111_replayobservation_session_geoip.pynew file mode 100644index 000000000000..05bed54647bf--- /dev/null+++ b/products/replay_vision/backend/migrations/0111_replayobservation_session_geoip.py@@ -0,0 +1,19 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0110_replayscanner_prompt_valence"),+ ]++ operations = [+ migrations.AddField(+ model_name="replayobservation",+ name="session_geoip",+ field=models.JSONField(+ blank=True,+ null=True,+ help_text="`$geoip_*` properties the recorded session's events carry (country, region, city, time zone). Resolved at scan time and stamped on the emitted event, which is otherwise geolocated to the worker.",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex f8f31b70b9ba..faea1b5800d3 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0110_replayscanner_prompt_valence+0111_replayobservation_session_geoipdiff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.pyindex 2d09138db866..ee66a413b9af 100644--- a/products/replay_vision/backend/models/replay_observation.py+++ b/products/replay_vision/backend/models/replay_observation.py@@ -72,6 +72,14 @@ class ReplayObservation(UUIDModel):"Resolved at scan time so the emitted event can be attributed to the group without re-querying."),)+ session_geoip = models.JSONField(+ null=True,+ blank=True,+ help_text=(+ "`$geoip_*` properties the recorded session's events carry (country, region, city, time zone). "+ "Resolved at scan time and stamped on the emitted event, which is otherwise geolocated to the worker."+ ),+ )status = models.CharField(max_length=16, choices=ObservationStatus.choices, default=ObservationStatus.PENDING)error_reason = models.TextField(blank=True, default="", help_text=ERROR_REASON_HELP_TEXT)diff --git a/products/replay_vision/backend/queries/session_identity.py b/products/replay_vision/backend/queries/session_identity.pyindex 246986c2b992..e233e2c018cc 100644--- a/products/replay_vision/backend/queries/session_identity.py+++ b/products/replay_vision/backend/queries/session_identity.py@@ -28,9 +28,21 @@ PERSON_ORGANIZATION_KEYS = ("org__name", "organization_name", "organization", "cPERSON_NAME_KEYS = ("name", "full_name")PERSON_NAME_PART_KEYS = ("first_name", "last_name")-# Every property the identity query reads, in the column order it returns them.+# Every person property the identity query reads, in the column order it returns them.PERSON_IDENTITY_KEYS = ("email", *PERSON_NAME_KEYS, *PERSON_NAME_PART_KEYS, *PERSON_ORGANIZATION_KEYS)+# Location of the recorded session, read off the subject's own events.+SESSION_GEOIP_KEYS = (+ "$geoip_country_code",+ "$geoip_country_name",+ "$geoip_subdivision_1_code",+ "$geoip_subdivision_1_name",+ "$geoip_city_name",+ "$geoip_time_zone",+)+# The location fields travel as one tuple column so they all come from the same event.+_GEOIP_COLUMN = "geoip"+# Person and group properties are customer-controlled free text of unbounded length, and they render into a prompt# that is cached and re-sent on every turn. No real name, email, or company needs more than this.MAX_IDENTITY_VALUE_LEN = 200@@ -41,9 +53,9 @@ IDENTITY_TIMESTAMP_SLACK = dt.timedelta(hours=1)def _person_identity_query() -> str:- """`SELECT` over the subject's events in the session, one aggregate per identity property.+ """`SELECT` over the subject's events in the session, one aggregate per identity and location property.- Built from `PERSON_IDENTITY_KEYS` so the columns and the readers below cannot drift apart.+ Built from `PERSON_IDENTITY_KEYS` and `SESSION_GEOIP_KEYS` so the columns and the readers below cannot drift apart.The `distinct_id` clause is load-bearing, not an optimization. A project's write token is public by design,so anyone who knows a session id can post an event carrying it under a `distinct_id` of their choosing.@@ -51,8 +63,13 @@ def _person_identity_query() -> str:be persisted as the subject and shown as authoritative. Bind to the distinct id the replay metadata names."""selects = ", ".join(- f"any(person.properties.{escape_hogql_identifier(key)}) AS {escape_hogql_identifier(key)}"- for key in PERSON_IDENTITY_KEYS+ [+ *(+ f"any(person.properties.{escape_hogql_identifier(key)}) AS {escape_hogql_identifier(key)}"+ for key in PERSON_IDENTITY_KEYS+ ),+ _geoip_select(),+ ])return (f"SELECT {selects} FROM events WHERE `$session_id` = {{session_id}} "@@ -60,6 +77,14 @@ def _person_identity_query() -> str:)+def _geoip_select() -> str:+ fields = [f"properties.{escape_hogql_identifier(key)}" for key in SESSION_GEOIP_KEYS]+ located = " OR ".join(f"notEmpty(coalesce({field}, ''))" for field in fields)+ # Earliest event with a country wins; one without a country only when no event has one.+ order = f"tuple(empty(coalesce({fields[0]}, '')), timestamp)"+ return f"argMinIf(tuple({', '.join(fields)}), {order}, {located}) AS {_GEOIP_COLUMN}"++# Module-level so the eval collector can run the identical query through the query API.SESSION_PERSON_IDENTITY_QUERY = _person_identity_query()@@ -67,7 +92,7 @@ SESSION_PERSON_IDENTITY_QUERY = _person_identity_query()def fetch_session_person_properties(*, team: Team, session_id: str, distinct_id: str | None, start: dt.datetime, end: dt.datetime) -> dict[str, Any]:- """Identity properties of the person the recording is of, keyed by property name.+ """Identity properties of the person the recording is of, plus the session's location, keyed by property name.`distinct_id` is the subject named by the replay metadata; without one there is no subject to attribute to,so the caller gets nothing rather than whatever else shares the session id.@@ -96,7 +121,16 @@ def person_properties_from_row(row: Sequence[Any]) -> dict[str, Any]:Unset properties are dropped: the query aggregates, so a session with no matching person still returns onerow of nulls rather than no rows, and a dict of nulls would read as a person who carries every property blank."""- return {key: value for key, value in zip(PERSON_IDENTITY_KEYS, row) if value is not None}+ properties = {key: value for key, value in zip(PERSON_IDENTITY_KEYS, row) if value is not None}+ geoip = row[len(PERSON_IDENTITY_KEYS)] if len(row) > len(PERSON_IDENTITY_KEYS) else None+ if isinstance(geoip, Sequence) and not isinstance(geoip, str):+ properties.update({key: value for key, value in zip(SESSION_GEOIP_KEYS, geoip) if value is not None})+ return properties+++def session_geoip(properties: Mapping[str, Any]) -> dict[str, str]:+ """The session's location keys the subject's events carried, ready to stamp on the emitted event."""+ return {key: value for key in SESSION_GEOIP_KEYS if (value := clean_identity_value(properties.get(key)))}def clean_identity_value(value: Any) -> str | None:diff --git a/products/replay_vision/backend/temporal/activities/emit_observation_event.py b/products/replay_vision/backend/temporal/activities/emit_observation_event.pyindex 026a169fe6cf..0c0c2bbbaaf2 100644--- a/products/replay_vision/backend/temporal/activities/emit_observation_event.py+++ b/products/replay_vision/backend/temporal/activities/emit_observation_event.py@@ -61,6 +61,9 @@ def _emit_event(inputs: EmitObservationEventInputs) -> None:"session_id": observation.session_id,"recording_distinct_id": recording_distinct_id,"recording_subject_email": recording_subject_email,+ # Internal captures resolve to the worker's address, so carry the recorded session's location instead.+ "$geoip_disable": True,+ **(observation.session_geoip or {}),"triggered_by": str(observation.triggered_by),"triggered_by_user_id": observation.triggered_by_user_id,"model_used": snapshot.model,diff --git a/products/replay_vision/backend/temporal/activities/fetch_session_events.py b/products/replay_vision/backend/temporal/activities/fetch_session_events.pyindex 8c3ddad09e3d..54fd34e657df 100644--- a/products/replay_vision/backend/temporal/activities/fetch_session_events.py+++ b/products/replay_vision/backend/temporal/activities/fetch_session_events.py@@ -24,6 +24,7 @@ from products.replay_vision.backend.queries.session_identity import (person_display_name,person_email,person_organization,+ session_geoip,)from products.replay_vision.backend.session_limits import (MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,@@ -118,6 +119,7 @@ def _persist_session_identity(observation_id: Any, payload: ScannerLlmInputs) ->recording_subject_email=payload.identity.person_email,session_started_at=payload.metadata.start_time,session_group_keys=payload.group_keys or None,+ session_geoip=payload.session_geoip or None,)@@ -138,15 +140,12 @@ def _resolve_group_keys(team: Team, session_id: str, metadata: RecordingMetadatareturn {}-def _resolve_identity(- team: Team, session_id: str, metadata: RecordingMetadata, group_keys: dict[int, str]-) -> SessionIdentity:+def _resolve_identity(team: Team, properties: dict[str, Any], group_keys: dict[int, str]) -> SessionIdentity:"""The recorded person and the groups their session belongs to, as far as each can be read.Every lookup is independent and best-effort: a scanner that only needs the video must not fail becausethe person query returned nothing or the groups query errored."""- properties = _resolve_person_properties(team, session_id, metadata)return SessionIdentity(person_email=person_email(properties),person_name=person_display_name(properties),@@ -278,6 +277,7 @@ def fetch_session_payload(team_id: int, session_id: str) -> ScannerLlmInputs | Ngroup_keys = _resolve_group_keys(team, session_id, metadata)distinct_id = metadata.get("distinct_id")+ subject_properties = _resolve_person_properties(team, session_id, metadata)return ScannerLlmInputs(session_id=session_id,@@ -292,8 +292,9 @@ def fetch_session_payload(team_id: int, session_id: str) -> ScannerLlmInputs | Nnavigation_dropped=processed.navigation_dropped,events_truncated=events_truncated,distinct_id=distinct_id,- identity=_resolve_identity(team, session_id, metadata, group_keys),+ identity=_resolve_identity(team, subject_properties, group_keys),group_keys=group_keys,+ session_geoip=session_geoip(subject_properties),metadata=SessionMetadata(start_time=metadata["start_time"],end_time=metadata["end_time"],diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.pyindex 000aef43c79d..565f383288ed 100644--- a/products/replay_vision/backend/temporal/types.py+++ b/products/replay_vision/backend/temporal/types.py@@ -249,6 +249,8 @@ class ScannerLlmInputs(BaseModel, frozen=True):identity: SessionIdentity = Field(default_factory=SessionIdentity)# Group keys by group type index, for the observation row's group attribution.group_keys: dict[int, str] = Field(default_factory=dict)+ # `$geoip_*` of the recorded session, for the emitted event. Kept off `SessionIdentity` so it never reaches the LLM.+ session_geoip: dict[str, str] = Field(default_factory=dict)class EnsureSessionAssetInputs(BaseModel, frozen=True):diff --git a/products/replay_vision/backend/tests/test_session_identity.py b/products/replay_vision/backend/tests/test_session_identity.pyindex b4fe0cef15c2..c15709ff73f0 100644--- a/products/replay_vision/backend/tests/test_session_identity.py+++ b/products/replay_vision/backend/tests/test_session_identity.py@@ -10,6 +10,7 @@ from products.replay_vision.backend.queries.session_identity import (fetch_session_person_properties,person_display_name,person_organization,+ session_geoip,)_START = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)@@ -30,7 +31,7 @@ class TestFetchSessionPersonProperties(ClickhouseTestMixin):event="$pageview",distinct_id="user-1",timestamp=_START,- properties={"$session_id": session_id},+ properties={"$session_id": session_id, "$geoip_country_code": "US", "$geoip_subdivision_1_code": "CA"},)flush_persons_and_events()@@ -41,6 +42,44 @@ class TestFetchSessionPersonProperties(ClickhouseTestMixin):assert properties["email"] == "[email protected]"assert properties["name"] == "Rene Diaz"assert properties["org__name"] == "Customer Co"+ assert properties["$geoip_country_code"] == "US"+ assert properties["$geoip_subdivision_1_code"] == "CA"+ assert "$geoip_city_name" not in properties++ @pytest.mark.django_db+ @pytest.mark.parametrize(+ "events,expected",+ [+ (+ [{}, {"$geoip_city_name": "Oakland"}, {"$geoip_country_code": "US", "$geoip_city_name": "Reno"}],+ {"$geoip_country_code": "US", "$geoip_city_name": "Reno"},+ ),+ (+ [{"$geoip_country_code": ""}, {"$geoip_country_code": "US", "$geoip_city_name": "Oakland"}],+ {"$geoip_country_code": "US", "$geoip_city_name": "Oakland"},+ ),+ ([{}, {"$geoip_city_name": "Oakland"}, {"$geoip_city_name": "Reno"}], {"$geoip_city_name": "Oakland"}),+ ],+ )+ def test_takes_every_location_field_from_one_event_preferring_a_country(self, team, events, expected) -> None:+ # Per-field aggregates could mix events into a location no event carried.+ session_id = str(uuid7())+ _create_person(team_id=team.pk, distinct_ids=["user-1"], properties={})+ for minutes, geoip in enumerate(events):+ _create_event(+ team=team,+ event="$pageview",+ distinct_id="user-1",+ timestamp=_START + dt.timedelta(minutes=minutes),+ properties={"$session_id": session_id, **geoip},+ )+ flush_persons_and_events()++ properties = fetch_session_person_properties(+ team=team, session_id=session_id, distinct_id="user-1", start=_START, end=_END+ )++ assert {key: value for key, value in properties.items() if key.startswith("$geoip_")} == expected@pytest.mark.django_dbdef test_ignores_events_another_person_posted_under_the_same_session_id(self, team) -> None:@@ -127,3 +166,19 @@ class TestPersonDisplayName:# Each part is capped, so the join has to be capped too or it lands at twice the limit.joined = person_display_name({"first_name": "x" * 5000, "last_name": "y" * 5000})assert joined is not None and len(joined) == MAX_IDENTITY_VALUE_LEN+++class TestSessionGeoip:+ @pytest.mark.parametrize(+ "properties,expected",+ [+ (+ {"email": "[email protected]", "$geoip_country_code": "US", "$geoip_subdivision_1_code": "CA"},+ {"$geoip_country_code": "US", "$geoip_subdivision_1_code": "CA"},+ ),+ ({"$geoip_country_code": " ", "$geoip_city_name": None, "$geoip_time_zone": 42}, {}),+ ({}, {}),+ ],+ )+ def test_keeps_only_the_location_keys_with_a_usable_value(self, properties, expected) -> None:+ assert session_geoip(properties) == expecteddiff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex 4e70e91e6bcf..d10a63221417 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -1538,6 +1538,31 @@ class TestEmitObservationEventActivity:assert properties["$group_2"] == "proj-9"assert properties["$groups"] == {"organization": "acme-inc", "project": "proj-9"}+ @pytest.mark.parametrize(+ "session_geoip",+ [{"$geoip_country_code": "US", "$geoip_subdivision_1_code": "CA"}, None],+ )+ def test_event_carries_the_session_location_with_geoip_disabled(self, session_geoip) -> None:+ # Without `$geoip_disable` the GeoIP transformation geolocates the worker, not the recorded user.+ scanner = _make_scanner()+ observation = _make_observation(scanner, session_geoip=session_geoip)+ inputs = EmitObservationEventInputs(+ observation_id=observation.id,+ model_output=MonitorOutput(verdict="yes", reasoning="ok", confidence=0.9),+ )++ with patch(+ "products.replay_vision.backend.temporal.activities.emit_observation_event.capture_internal"+ ) as capture:+ _emit_event(inputs)++ properties = capture.call_args.kwargs["properties"]+ assert properties["$geoip_disable"] is True+ for key, value in (session_geoip or {}).items():+ assert properties[key] == value+ if not session_geoip:+ assert not any(key.startswith("$geoip_") for key in properties if key != "$geoip_disable")+def test_event_omits_group_properties_when_the_session_carried_none(self) -> None:# Observations scanned before group keys were resolved leave the column null; they must still emit.scanner = _make_scanner()@@ -1886,7 +1911,13 @@ class TestFetchSessionEventsActivity:),patch("products.replay_vision.backend.temporal.activities.fetch_session_events.fetch_session_person_properties",- return_value={"email": "[email protected]", "name": "Rene Diaz", "org__name": "Customer Co"},+ return_value={+ "email": "[email protected]",+ "name": "Rene Diaz",+ "org__name": "Customer Co",+ "$geoip_country_code": "US",+ "$geoip_subdivision_1_code": "CA",+ },),):await fetch_session_events_activity(@@ -1900,9 +1931,11 @@ class TestFetchSessionEventsActivity:assert stored.identity.person_email == "[email protected]"assert stored.identity.person_name == "Rene Diaz"assert stored.identity.person_organization == "Customer Co"+ assert stored.session_geoip == {"$geoip_country_code": "US", "$geoip_subdivision_1_code": "CA"}await sync_to_async(observation.refresh_from_db)()assert observation.recording_subject_email == "[email protected]"+ assert observation.session_geoip == {"$geoip_country_code": "US", "$geoip_subdivision_1_code": "CA"}@pytest.mark.asyncioasync def test_fetches_a_single_page_with_the_configured_limit(self) -> None: