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(replay-vision): attribute observations to the recorded session's groups (#74779)

Arno Hillend727e91b8cd1
diff --git a/products/replay_vision/backend/migrations/0074_observation_session_group_keys.py b/products/replay_vision/backend/migrations/0074_observation_session_group_keys.py
new file mode 100644
index 000000000000..2060fff5a395
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0074_observation_session_group_keys.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.14 on 2026-07-29 14:22
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0073_rebackfill_usage_scanner_id"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="replayobservation",
+ name="session_group_keys",
+ field=models.JSONField(
+ blank=True,
+ help_text="Group keys the recorded session's events carry, keyed by group type index (e.g. {'0': 'acme-inc'}). Resolved at scan time so the emitted event can be attributed to the group without re-querying.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index ea53eb4abd31..e80166d12b45 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0073_rebackfill_usage_scanner_id
+0074_observation_session_group_keys
diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.py
index 7bcd8dd6d150..a9f6b39abf53 100644
--- a/products/replay_vision/backend/models/replay_observation.py
+++ b/products/replay_vision/backend/models/replay_observation.py
@@ -56,6 +56,14 @@ class ReplayObservation(UUIDModel):
blank=True,
help_text="Start time of the recorded session; copied from session metadata so downstream steps don't re-query.",
)
+ session_group_keys = models.JSONField(
+ null=True,
+ blank=True,
+ help_text=(
+ "Group keys the recorded session's events carry, keyed by group type index (e.g. {'0': 'acme-inc'}). "
+ "Resolved at scan time so the emitted event can be attributed to the group without re-querying."
+ ),
+ )
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_group_keys.py b/products/replay_vision/backend/queries/session_group_keys.py
new file mode 100644
index 000000000000..49285baeeb98
--- /dev/null
+++ b/products/replay_vision/backend/queries/session_group_keys.py
@@ -0,0 +1,47 @@
+import datetime as dt
+
+import structlog
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.models import Team
+
+logger = structlog.get_logger(__name__)
+
+# The five `$group_N` columns every event carries; the team's own group types occupy a prefix of these.
+GROUP_TYPE_INDEXES = range(5)
+
+# Widens the timestamp window around the session so an event stamped slightly outside the recording's
+# bounds (client clock skew) still contributes its group keys.
+_TIMESTAMP_SLACK = dt.timedelta(hours=1)
+
+
+def fetch_session_group_keys(*, team: Team, session_id: str, start: dt.datetime, end: dt.datetime) -> dict[int, str]:
+ """Group keys the session's events carry, keyed by group type index.
+
+ Takes each key off the latest event that carried it. A session normally holds one key per group type,
+ but when it holds two (a user switching org mid-session) the most recent one is the group the observed
+ activity belongs to, where a lexicographic pick would attribute the observation to whichever key
+ happened to sort highest.
+ """
+ tag_queries(team_id=team.id, product=Product.REPLAY_VISION, feature=Feature.QUERY)
+ selects = ", ".join(
+ f"argMaxIf(`$group_{i}`, timestamp, `$group_{i}` != '') AS group_{i}" for i in GROUP_TYPE_INDEXES
+ )
+ query = parse_select(
+ f"SELECT {selects} FROM events WHERE `$session_id` = {{session_id}} "
+ "AND timestamp >= {start} AND timestamp <= {end}",
+ placeholders={
+ "session_id": ast.Constant(value=session_id),
+ "start": ast.Constant(value=start - _TIMESTAMP_SLACK),
+ "end": ast.Constant(value=end + _TIMESTAMP_SLACK),
+ },
+ )
+ response = execute_hogql_query(query=query, team=team)
+ if not response.results:
+ return {}
+ row = response.results[0]
+ return {index: key for index, key in zip(GROUP_TYPE_INDEXES, row) if key}
diff --git a/products/replay_vision/backend/temporal/activities/emit_observation_event.py b/products/replay_vision/backend/temporal/activities/emit_observation_event.py
index b89e69247225..e4aa0082180d 100644
--- a/products/replay_vision/backend/temporal/activities/emit_observation_event.py
+++ b/products/replay_vision/backend/temporal/activities/emit_observation_event.py
@@ -6,6 +6,7 @@ import structlog
from temporalio import activity
from posthog.api.capture import capture_internal
+from posthog.models.group_type_mapping import get_group_types_for_project
from posthog.models.team import Team
from posthog.sync import database_sync_to_async
@@ -69,6 +70,7 @@ def _emit_event(inputs: EmitObservationEventInputs) -> None:
"emits_signals": snapshot.emits_signals,
# Flatten scanner output so HogQL can query individual fields without a JSON extract.
**inputs.model_output.to_event_properties(),
+ **_group_properties(team, observation),
}
distinct_id = (
str(observation.triggered_by_user_id)
@@ -89,3 +91,30 @@ def _emit_event(inputs: EmitObservationEventInputs) -> None:
event_uuid=str(observation.id),
)
result.raise_for_status()
+
+
+def _group_properties(team: Team, observation: ReplayObservation) -> dict:
+ """Group attribution for the recorded session: `$group_N` for group analytics, `$groups` for readers.
+
+ Ingestion only derives `$group_N` from `$groups` when it processes a person profile, which this event
+ deliberately doesn't, so the indexed keys are written here directly (the same rewrite ingestion would do).
+ """
+ group_keys = observation.session_group_keys or {}
+ if not group_keys:
+ return {}
+ properties: dict = {f"$group_{index}": key for index, key in group_keys.items()}
+ try:
+ index_to_type = {
+ mapping["group_type_index"]: mapping["group_type"]
+ for mapping in get_group_types_for_project(team.project_id, caller_tag="replay_vision/emit_observation")
+ }
+ except Exception:
+ # Named groups are a nicety for webhook and alert consumers; the indexed keys above already carry
+ # everything group analytics needs, so a group-type lookup failure must not lose them.
+ logger.warning("replay_vision.emit.group_types_lookup_failed", observation_id=str(observation.id))
+ return properties
+ # `int(index)` because the stored map round-tripped through JSON, where object keys are always strings.
+ named = {group_type: key for index, key in group_keys.items() if (group_type := index_to_type.get(int(index)))}
+ if named:
+ properties["$groups"] = named
+ return properties
diff --git a/products/replay_vision/backend/temporal/activities/fetch_session_events.py b/products/replay_vision/backend/temporal/activities/fetch_session_events.py
index a64cc6052a72..393781097e3b 100644
--- a/products/replay_vision/backend/temporal/activities/fetch_session_events.py
+++ b/products/replay_vision/backend/temporal/activities/fetch_session_events.py
@@ -14,6 +14,7 @@ from posthog.models.person.util import get_person_by_distinct_id
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
from products.replay_vision.backend.models.replay_observation import ReplayObservation
+from products.replay_vision.backend.queries.session_group_keys import fetch_session_group_keys
from products.replay_vision.backend.session_limits import (
MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,
MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,
@@ -108,9 +109,30 @@ def _persist_session_identity(observation_id: Any, payload: ScannerLlmInputs) ->
distinct_id=payload.distinct_id,
recording_subject_email=email,
session_started_at=payload.metadata.start_time,
+ session_group_keys=_resolve_group_keys(observation_id, payload),
)
+def _resolve_group_keys(observation_id: Any, payload: ScannerLlmInputs) -> dict[int, str] | None:
+ """Group keys for the recorded session, or None when they can't be read.
+
+ Best-effort: a scan that produced a real observation must not fail over missing group attribution.
+ """
+ try:
+ team = Team.objects.get(pk=payload.team_id)
+ return fetch_session_group_keys(
+ team=team,
+ session_id=payload.session_id,
+ start=payload.metadata.start_time,
+ end=payload.metadata.end_time,
+ )
+ except Exception:
+ logger.warning(
+ "replay_vision.fetch.group_keys_lookup_failed", observation_id=str(observation_id), exc_info=True
+ )
+ return None
+
+
def _fetch_payload(team_id: int, session_id: str) -> ScannerLlmInputs | None:
# select_related saves the extra round trip when fetch_product_context reads team.project.
team = Team.objects.select_related("project").get(pk=team_id)
diff --git a/products/replay_vision/backend/tests/test_session_group_keys.py b/products/replay_vision/backend/tests/test_session_group_keys.py
new file mode 100644
index 000000000000..bfa638a02b95
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_session_group_keys.py
@@ -0,0 +1,73 @@
+import datetime as dt
+
+import pytest
+from posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_and_events
+
+from posthog.uuidt import uuid7
+
+from products.replay_vision.backend.queries.session_group_keys import fetch_session_group_keys
+
+_START = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)
+_END = _START + dt.timedelta(minutes=5)
+
+
+def _event(team, session_id: str, *, at: dt.datetime, **properties) -> None:
+ _create_event(
+ team=team,
+ event="$pageview",
+ distinct_id="user-1",
+ timestamp=at,
+ properties={"$session_id": session_id, **properties},
+ )
+
+
+class TestFetchSessionGroupKeys(ClickhouseTestMixin):
+ @pytest.mark.django_db
+ def test_returns_only_the_indexes_the_session_carries(self, team) -> None:
+ session_id = str(uuid7())
+ _event(team, session_id, at=_START, **{"$group_0": "acme-inc", "$group_2": "proj-9"})
+ flush_persons_and_events()
+
+ assert fetch_session_group_keys(team=team, session_id=session_id, start=_START, end=_END) == {
+ 0: "acme-inc",
+ 2: "proj-9",
+ }
+
+ @pytest.mark.django_db
+ def test_ignores_events_from_other_sessions(self, team) -> None:
+ # The scanner watches one recording; picking up a neighbouring session's org would misattribute the spend.
+ session_id = str(uuid7())
+ _event(team, session_id, at=_START, **{"$group_0": "acme-inc"})
+ _event(team, str(uuid7()), at=_START, **{"$group_0": "other-co"})
+ flush_persons_and_events()
+
+ assert fetch_session_group_keys(team=team, session_id=session_id, start=_START, end=_END) == {0: "acme-inc"}
+
+ @pytest.mark.django_db
+ def test_finds_keys_on_a_later_event_when_the_first_carries_none(self, team) -> None:
+ # Group keys ride on the events that have them, not necessarily the one that opened the session.
+ session_id = str(uuid7())
+ _event(team, session_id, at=_START)
+ _event(team, session_id, at=_START + dt.timedelta(minutes=1), **{"$group_0": "acme-inc"})
+ flush_persons_and_events()
+
+ assert fetch_session_group_keys(team=team, session_id=session_id, start=_START, end=_END) == {0: "acme-inc"}
+
+ @pytest.mark.django_db
+ def test_takes_the_latest_key_when_one_group_type_carries_two(self, team) -> None:
+ # A user switching org mid-session leaves two keys on the same index. The later one is the group the
+ # observed activity belongs to; the keys here are ordered so a lexicographic pick would return the earlier.
+ session_id = str(uuid7())
+ _event(team, session_id, at=_START, **{"$group_0": "zeta-co"})
+ _event(team, session_id, at=_START + dt.timedelta(minutes=2), **{"$group_0": "alpha-co"})
+ flush_persons_and_events()
+
+ assert fetch_session_group_keys(team=team, session_id=session_id, start=_START, end=_END) == {0: "alpha-co"}
+
+ @pytest.mark.django_db
+ def test_returns_empty_for_a_session_with_no_groups(self, team) -> None:
+ session_id = str(uuid7())
+ _event(team, session_id, at=_START)
+ flush_persons_and_events()
+
+ assert fetch_session_group_keys(team=team, session_id=session_id, start=_START, end=_END) == {}
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 07a43d6514d5..e7058014df9b 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -1083,6 +1083,78 @@ class TestEmitObservationEventActivity:
properties = capture.call_args.kwargs["properties"]
assert properties["credits"] == observation_credits_for_model(observation.scanner_snapshot["model"])
+ def test_event_carries_indexed_and_named_group_keys(self) -> None:
+ # `$group_N` is what group analytics filters and breaks down on; `$groups` is what a webhook or alert
+ # consumer reads. Ingestion derives one from the other only when it processes a person profile, which
+ # this event doesn't, so both have to be written here.
+ scanner = _make_scanner()
+ observation = _make_observation(scanner, session_group_keys={"0": "acme-inc", "2": "proj-9"})
+ 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,
+ patch(
+ "products.replay_vision.backend.temporal.activities.emit_observation_event.get_group_types_for_project",
+ return_value=[
+ {"group_type_index": 0, "group_type": "organization"},
+ {"group_type_index": 2, "group_type": "project"},
+ ],
+ ),
+ ):
+ _emit_event(inputs)
+
+ properties = capture.call_args.kwargs["properties"]
+ assert properties["$group_0"] == "acme-inc"
+ assert properties["$group_2"] == "proj-9"
+ assert properties["$groups"] == {"organization": "acme-inc", "project": "proj-9"}
+
+ 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()
+ observation = _make_observation(scanner, session_group_keys=None)
+ 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 "$groups" not in properties
+ assert not [key for key in properties if key.startswith("$group_")]
+
+ def test_event_keeps_indexed_group_keys_when_group_types_are_unavailable(self) -> None:
+ # Losing the names costs a nicety; losing `$group_N` would cost the group attribution entirely.
+ scanner = _make_scanner()
+ observation = _make_observation(scanner, session_group_keys={"0": "acme-inc"})
+ 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,
+ patch(
+ "products.replay_vision.backend.temporal.activities.emit_observation_event.get_group_types_for_project",
+ side_effect=RuntimeError("personhog down"),
+ ),
+ ):
+ _emit_event(inputs)
+
+ properties = capture.call_args.kwargs["properties"]
+ assert properties["$group_0"] == "acme-inc"
+ assert "$groups" not in properties
+
def _counter_value(metric_name: str, **labels: str) -> float:
return REGISTRY.get_sample_value(metric_name, labels) or 0.0