: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
feat(replay-vision): summarize any scanner type via reasoning fallback (#67513)
Kim Svatos Dugan6790440c5443
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.pyindex 43c24c38916d..7357c88ae557 100644--- a/products/replay_vision/backend/max_tools.py+++ b/products/replay_vision/backend/max_tools.py@@ -64,6 +64,28 @@ def _as_untrusted_data(label: str, lines: list[str]) -> str:)+def describe_scanner_outcome(output: dict[str, Any]) -> str | None:+ """Short type-specific descriptor (verdict / score / tags / title) for a persisted model_output.++ This is the observation's *outcome* — what the scanner concluded — as distinct from the `reasoning`+ prose. Each call site leads its formatted line with this (Max brackets it, the group summary prefixes+ it) so a reader sees the result directly instead of inferring it from the reasoning text.+ """+ scanner_type = output.get("scanner_type")+ if scanner_type == ScannerType.MONITOR and output.get("verdict") is not None:+ return f"verdict={output['verdict']}"+ if scanner_type == ScannerType.SCORER and output.get("score") is not None:+ label = output.get("label")+ return f"score={output['score']}{f' ({label})' if label else ''}"+ if scanner_type == ScannerType.CLASSIFIER:+ tags = [*(output.get("tags") or []), *(output.get("tags_freeform") or [])]+ return f"tags={', '.join(str(t) for t in tags)}" if tags else None+ if scanner_type == ScannerType.SUMMARIZER:+ title = output.get("title")+ return str(title) if isinstance(title, str) and title.strip() else None+ return None++DRAFT_PROMPT_TOOL_DESCRIPTION = dedent("""Use this tool to write or improve the instruction prompt for the Replay Vision scanner the user iscurrently configuring, then fill it into their configuration form.@@ -610,14 +632,15 @@ class SearchReplayVisionObservationsTool(MaxTool):return output if isinstance(output, dict) else Nonedef _format_line(self, obs: ReplayObservation, output: dict[str, Any], *, show_scanner: bool) -> str:- descriptor = self._describe_output(output)+ descriptor = describe_scanner_outcome(output)explanation = output.get("reasoning") or output.get("summary")if not isinstance(explanation, str) or not explanation.strip():# Summarizer rows have no `reasoning`; fall back to the facets we did embed.explanation = output.get("intent") or output.get("outcome") or ""# All of reasoning, descriptor (freeform tags), session_id (client-settable) and scanner name are- # untrusted, but they don't need per-field defanging here — `_as_untrusted_data` defangs the whole block.- clean = _EVENT_ID_CITATION_RE.sub("", explanation).strip()[:_SEARCH_SNIPPET_LIMIT]+ # untrusted, but they don't need per-field defanging here — `_as_untrusted_data` defangs the whole+ # block. Collapse whitespace so a match stays one line and can't forge extra result lines.+ clean = re.sub(r"\s+", " ", _EVENT_ID_CITATION_RE.sub("", explanation)).strip()[:_SEARCH_SNIPPET_LIMIT]prefix = f"{obs.created_at:%Y-%m-%d}"session = str(obs.session_id)@@ -625,19 +648,3 @@ class SearchReplayVisionObservationsTool(MaxTool):scanner_part = f" {obs.scanner.name}" if show_scanner and obs.scanner else ""descriptor_part = f" [{descriptor}]" if descriptor else ""return f"- (session {session}, {prefix}){scanner_part}{descriptor_part} {clean}".rstrip()-- def _describe_output(self, output: dict[str, Any]) -> str | None:- """Short type-specific descriptor (verdict / score / tags / title) prepended to each result line."""- scanner_type = output.get("scanner_type")- if scanner_type == ScannerType.MONITOR and output.get("verdict") is not None:- return f"verdict={output['verdict']}"- if scanner_type == ScannerType.SCORER and output.get("score") is not None:- label = output.get("label")- return f"score={output['score']}{f' ({label})' if label else ''}"- if scanner_type == ScannerType.CLASSIFIER:- tags = [*(output.get("tags") or []), *(output.get("tags_freeform") or [])]- return f"tags={', '.join(str(t) for t in tags)}" if tags else None- if scanner_type == ScannerType.SUMMARIZER:- title = output.get("title")- return str(title) if isinstance(title, str) and title.strip() else None- return Nonediff --git a/products/replay_vision/backend/temporal/vision_actions/synthesis.py b/products/replay_vision/backend/temporal/vision_actions/synthesis.pyindex fd50be7ba4c7..ed352e574871 100644--- a/products/replay_vision/backend/temporal/vision_actions/synthesis.py+++ b/products/replay_vision/backend/temporal/vision_actions/synthesis.py@@ -6,8 +6,9 @@ is written onto `VisionActionRun` inside the activity — it never crosses the T"""import re+import uuidfrom datetime import UTC, datetime, timedelta, tzinfo-from typing import Any, NamedTuple+from typing import TYPE_CHECKING, Any, NamedTuplefrom zoneinfo import ZoneInfoimport structlog@@ -17,11 +18,12 @@ from temporalio import activityfrom posthog.helpers.markdown_safety import strip_external_links_markdownfrom posthog.models.team import Team+from posthog.rbac.user_access_control import UserAccessControlfrom posthog.sync import database_sync_to_async-from products.replay_vision.backend.max_tools import _EVENT_ID_CITATION_RE, _as_untrusted_data+from products.replay_vision.backend.max_tools import _EVENT_ID_CITATION_RE, _as_untrusted_data, describe_scanner_outcomefrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation-from products.replay_vision.backend.models.replay_scanner import ScannerModel+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModelfrom products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun, VisionActionRunStatusfrom products.replay_vision.backend.temporal.constants import replay_vision_distinct_idfrom products.replay_vision.backend.temporal.decorators import track_activity@@ -34,6 +36,9 @@ from products.replay_vision.backend.temporal.vision_actions.types import (from ee.billing.quota_limiting import is_team_over_ai_credit_budget+if TYPE_CHECKING:+ from posthog.models.user import User+logger = structlog.get_logger(__name__)# Track the scanners' default Gemini model so synthesis and scanning move together. Runs through the@@ -112,7 +117,9 @@ def _synthesize(inputs: SynthesizeGroupSummaryInputs) -> SynthesizeGroupSummaryR# spans — so the reader has that context in-app and in Slack. Defang links across the whole report# AFTER prepending: the header carries the free-text scanner name, so a name with link/image# markdown must be neutralized too, not just the LLM body.- markdown = strip_external_links_markdown(_summary_header(action, batch.window_start, len(batch.lines)) + markdown)+ markdown = strip_external_links_markdown(+ _summary_header(action, batch.window_start, len(batch.lines), batch.window_total) + markdown+ )slack_text = _markdown_to_slack(markdown)run.synthesized_markdown = markdown@@ -163,6 +170,39 @@ class _ObservationBatch(NamedTuple):lines: list[str]observation_ids: list[str]window_start: datetime | None+ # Total SUCCEEDED observations in the window before the cap. When it exceeds the number summarized,+ # the report only covers a sample — surfaced in the header so the reader knows it isn't exhaustive.+ window_total: int+++def _is_uuid(value: str) -> bool:+ try:+ uuid.UUID(str(value))+ except (ValueError, TypeError):+ return False+ return True+++def _readable_scanner_ids(user: "User", team: Team, scanner_ids: list[str]) -> list[str]:+ """Restrict an action's bound scanner ids to the ones its creator may actually read.++ A vision action's scanner binding is user-supplied, so without this a creator could point an action+ at a same-team scanner they lack `replay_scanner` viewer access to and receive its recording-derived+ reasoning and outcome in the synthesized summary. Filtering through the creator's RBAC keeps synthesis+ from surfacing a scanner the creator can't see, mirroring the scanner-access gate `max_tools` applies+ on interactive reads (object-level access control; note the underlying queryset filter is a no-op for+ orgs without the access-control feature, where no per-scanner restriction exists anyway).+ """+ # Drop non-UUID ids before querying: `selection.scanner_ids` is a user-supplied CharField list, and a+ # malformed value would raise ValidationError inside the Temporal activity on every run (a permanent+ # retry loop). Mirrors the UUID pre-validation in `max_tools._resolve_scanner_scope`.+ valid_ids = [scanner_id for scanner_id in scanner_ids if _is_uuid(scanner_id)]+ if not valid_ids:+ return []+ readable = UserAccessControl(user=user, team=team).filter_queryset_by_access_level(+ ReplayScanner.objects.filter(team_id=team.id, id__in=valid_ids)+ )+ return [str(scanner_id) for scanner_id in readable.values_list("id", flat=True)]def _fetch_observations(team: Team, action: VisionAction, run: VisionActionRun) -> _ObservationBatch:@@ -171,9 +211,24 @@ def _fetch_observations(team: Team, action: VisionAction, run: VisionActionRun)Models the summarizer fetch in `max_tools._fetch_and_format`."""selection: dict[str, Any] = action.selection or {}- scanner_ids = selection.get("scanner_ids") or ([str(action.scanner_id)] if action.scanner_id else [])+ requested_scanner_ids = selection.get("scanner_ids") or ([str(action.scanner_id)] if action.scanner_id else [])+ # The bound scanner ids (`scanner`/`selection.scanner_ids`) are user-supplied, so filter them through+ # the action creator's RBAC before reading any observations — otherwise an action could surface a+ # same-team scanner's recording-derived reasoning/outcome that its creator can't access. Mirrors the+ # scanner-access gate `max_tools` applies when reading observations. Upstream guarantees a creator.+ creator = action.created_by+ scanner_ids = _readable_scanner_ids(creator, team, requested_scanner_ids) if creator is not None else []+ if len(scanner_ids) < len(requested_scanner_ids):+ # RBAC (or a malformed id) dropped some bound scanners. Log it so a silently shrinking summary is+ # diagnosable rather than reading like "no observations this period".+ logger.info(+ "vision_action.synthesis.scanners_filtered",+ vision_action_id=str(action.id),+ requested=len(requested_scanner_ids),+ readable=len(scanner_ids),+ )if not scanner_ids:- return _ObservationBatch(lines=[], observation_ids=[], window_start=None)+ return _ObservationBatch(lines=[], observation_ids=[], window_start=None, window_total=0)window_start = _window_start(team, action, run)observations_qs = ReplayObservation.objects.filter(@@ -184,6 +239,9 @@ def _fetch_observations(team: Team, action: VisionAction, run: VisionActionRun)created_at__lt=_window_end(run),)+ # Count the whole window so the header can say when the summary is only a sample of it (see cap below).+ window_total = observations_qs.count()+# Cap how many observations feed the summary (bounds context size + LLM cost). Per-action, tunable# via Django admin; falls back to the module default. Fast path: one query fetches the newest `cap`# rows. If it returns exactly `cap`, the window may hold more — only then scan ids and sample evenly@@ -213,26 +271,39 @@ def _fetch_observations(team: Team, action: VisionAction, run: VisionActionRun)output = scanner_result.get("model_output") if isinstance(scanner_result, dict) else Noneif not isinstance(output, dict):continue- summary = output.get("summary")- if not isinstance(summary, str) or not summary.strip():+ # Summarizers emit `summary`; monitor/classifier/scorer emit only `reasoning`. Fall back to+ # reasoning (an empty summary counts as absent) so a group summary works on any scanner type —+ # otherwise a non-summarizer action skips as empty. Each line then leads with the scanner's+ # outcome (verdict / score / tags, or the summarizer's title) so the model reads what the+ # observation concluded rather than inferring it from the prose.+ text = output.get("summary") or output.get("reasoning")+ if not isinstance(text, str) or not text.strip():continue- title = output.get("title") if isinstance(output.get("title"), str) else None- clean = _EVENT_ID_CITATION_RE.sub("", summary).strip()- lines.append(f"- ({created_at:%Y-%m-%d}) {f'{title}: ' if title else ''}{clean}")+ # Collapse to a single line: keeps the feed one-observation-per-line and stops recording-derived+ # text from forging extra descriptor-bearing lines inside the untrusted fence.+ clean = re.sub(r"\s+", " ", _EVENT_ID_CITATION_RE.sub("", text)).strip()+ descriptor = describe_scanner_outcome(output)+ lines.append(f"- ({created_at:%Y-%m-%d}) {f'{descriptor}: ' if descriptor else ''}{clean}")# Recorded in lockstep with `lines`: only observations whose summary was actually included.observation_ids.append(str(observation_id))- return _ObservationBatch(lines=lines, observation_ids=observation_ids, window_start=window_start)+ return _ObservationBatch(+ lines=lines, observation_ids=observation_ids, window_start=window_start, window_total=window_total+ )-def _summary_header(action: VisionAction, window_start: datetime | None, count: int) -> str:+def _summary_header(action: VisionAction, window_start: datetime | None, count: int, window_total: int = 0) -> str:"""A trusted one-line preface stating which scanner this summary is for, how many recordings it- covers, and the window's start — the "summary for scans since <prev run>" context the reader needs."""+ covers, and the window's start — the "summary for scans since <prev run>" context the reader needs.+ When the window held more observations than the cap, it says so ("sampled N of M") so the reader+ knows the report covers only a sample of the period, not every observation."""# Scanner name is free-text; strip markdown/mrkdwn control chars so it can't garble the bold header# (in-app Markdown or the Slack `**`→`*` pass) and collapse any newlines that would break the line.raw_name = action.scanner.name if action.scanner_id else ""scanner_name = re.sub(r"\s+", " ", re.sub(r"[*_`#]", "", raw_name)).strip() or "your scanner"noun = "recording" if count == 1 else "recordings"+ # When the period held more observations than the cap, only `count` were summarized — say so.+ coverage = f"sampled {count} of {window_total:,} {noun}" if window_total > count else f"{count} {noun}"since = ""if window_start is not None:tz: tzinfo = UTC@@ -248,7 +319,7 @@ def _summary_header(action: VisionAction, window_start: datetime | None, count:since = (f" since {local.strftime('%b')} {local.day}, {local.year} at {local.strftime('%I:%M %p %Z').lstrip('0')}")- return f"**Summary for {scanner_name}** — {count} {noun}{since}\n\n"+ return f"**Summary for {scanner_name}** — {coverage}{since}\n\n"def _run_synthesis(team: Team, action: VisionAction, lines: list[str]) -> str:diff --git a/products/replay_vision/backend/tests/test_vision_action_synthesis.py b/products/replay_vision/backend/tests/test_vision_action_synthesis.pyindex d2fbb1eee591..ee00db1dce85 100644--- a/products/replay_vision/backend/tests/test_vision_action_synthesis.py+++ b/products/replay_vision/backend/tests/test_vision_action_synthesis.py@@ -19,9 +19,14 @@ from products.replay_vision.backend.tests.helpers import snapshot_for_SYNTH_PATH = "products.replay_vision.backend.temporal.vision_actions.synthesis"-def _mock_genai(content: str):+def _mock_genai(content: str, captured: list[str] | None = None):# genai.Client(...).models.generate_content(...) → object with .text- client = SimpleNamespace(models=SimpleNamespace(generate_content=lambda **_kwargs: SimpleNamespace(text=content)))+ def _generate(**kwargs) -> SimpleNamespace:+ if captured is not None:+ captured.append(kwargs.get("contents", ""))+ return SimpleNamespace(text=content)++ client = SimpleNamespace(models=SimpleNamespace(generate_content=_generate))return SimpleNamespace(Client=lambda **_kwargs: client)@@ -51,7 +56,13 @@ class TestVisionActionSynthesis(BaseTest):triggered_by=ObservationTrigger.SCHEDULE,status=ObservationStatus.SUCCEEDED,completed_at=timezone.now(),- scanner_result={"model_output": {"summary": summary, **({"title": title} if title else {})}},+ scanner_result={+ "model_output": {+ "scanner_type": ScannerType.SUMMARIZER,+ "summary": summary,+ **({"title": title} if title else {}),+ }+ },)def _action(self, **overrides) -> VisionAction:@@ -72,10 +83,16 @@ class TestVisionActionSynthesis(BaseTest):run.save()return run- def _synthesize(self, action: VisionAction, run: VisionActionRun, llm_content: str = "# Themes\nAll good."):+ def _synthesize(+ self,+ action: VisionAction,+ run: VisionActionRun,+ llm_content: str = "# Themes\nAll good.",+ captured_prompts: list[str] | None = None,+ ):with (patch(f"{_SYNTH_PATH}.is_team_over_ai_credit_budget", return_value=False),- patch(f"{_SYNTH_PATH}.genai", _mock_genai(llm_content)),+ patch(f"{_SYNTH_PATH}.genai", _mock_genai(llm_content, captured_prompts)),):return _synthesize(SynthesizeGroupSummaryInputs(run_id=run.id, team_id=self.team.id))@@ -114,6 +131,19 @@ class TestVisionActionSynthesis(BaseTest):# The header rides into the Slack payload too (bold header → *bold*).self.assertIn("*Summary for summarizer*", run.output["slack"])+ def test_header_flags_sampling_when_window_exceeds_cap(self) -> None:+ # When the period holds more observations than the cap, the header must say the summary covers+ # only a sample — otherwise a capped summary reads as if it saw everything.+ for i in range(3):+ self._observation(f"obs {i}", session_id=f"s{i}")+ action = self._action(max_observations=2)+ run = self._run_for(action)++ self._synthesize(action, run)++ run.refresh_from_db()+ self.assertIn("sampled 2 of 3 recordings", run.synthesized_markdown)+def test_summary_header_sanitizes_scanner_name(self) -> None:# A scanner name is free text; markdown/mrkdwn control chars must be stripped so they can't# garble the bold header (the "**" bold regex breaks on an interior "*").@@ -282,6 +312,72 @@ class TestVisionActionSynthesis(BaseTest):result = self._synthesize(action, run)self.assertEqual(result.observation_count, 1)+ def test_summarizes_reasoning_and_outcome_when_no_summary(self) -> None:+ # Non-summarizer scanners (monitor/classifier/scorer) emit `reasoning`, not `summary`. The group+ # summary must fall back to reasoning so those actions don't skip as empty — and must feed the model+ # the actual outcome (verdict/score/tags) too, not just reasoning it would otherwise have to infer.+ ReplayObservation.objects.create(+ scanner=self.scanner,+ session_id="classified",+ scanner_snapshot=snapshot_for(self.scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ scanner_result={+ "model_output": {+ "scanner_type": ScannerType.CLASSIFIER,+ "reasoning": "user abandoned at the payment step",+ "tags": ["abandoned"],+ }+ },+ )+ action = self._action()+ run = self._run_for(action)++ prompts: list[str] = []+ result = self._synthesize(action, run, captured_prompts=prompts)++ self.assertEqual(result.status, SynthesisStatus.SYNTHESIZED)+ self.assertEqual(result.observation_count, 1)+ # The observation's outcome (tags) and its reasoning both reach the model.+ self.assertIn("tags=abandoned", prompts[0])+ self.assertIn("user abandoned at the payment step", prompts[0])++ def test_excludes_scanners_the_creator_cannot_read(self) -> None:+ # The action's bound scanner_ids are user-supplied, so synthesis must filter them through the+ # creator's RBAC. Without that a creator could bind a same-team scanner they can't read and pull+ # its recording-derived reasoning/outcome into the summary.+ hidden = ReplayScanner.objects.create(+ team=self.team,+ name="hidden",+ scanner_type=ScannerType.CLASSIFIER,+ scanner_config={"prompt": "classify"},+ model=ScannerModel.GEMINI_3_FLASH,+ )+ self._observation("visible scanner output", session_id="visible")+ ReplayObservation.objects.create(+ scanner=hidden,+ session_id="hidden",+ scanner_snapshot=snapshot_for(hidden),+ triggered_by=ObservationTrigger.SCHEDULE,+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ scanner_result={"model_output": {"scanner_type": ScannerType.CLASSIFIER, "reasoning": "leaked reasoning"}},+ )+ action = self._action(selection={"scanner_ids": [str(self.scanner.id), str(hidden.id)]})+ run = self._run_for(action)++ prompts: list[str] = []+ with patch(+ "posthog.rbac.user_access_control.UserAccessControl.filter_queryset_by_access_level",+ side_effect=lambda qs, **_: qs.exclude(pk=hidden.pk),+ ):+ result = self._synthesize(action, run, captured_prompts=prompts)++ self.assertEqual(result.observation_count, 1)+ self.assertIn("visible scanner output", prompts[0])+ self.assertNotIn("leaked reasoning", prompts[0])+def test_external_links_are_stripped(self) -> None:self._observation("something")action = self._action()diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionActionForm.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionActionForm.tsxindex e3293a04ce8d..09b256723fe6 100644--- a/products/replay_vision/frontend/replay_scanners/components/VisionActionForm.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/VisionActionForm.tsx@@ -122,6 +122,10 @@ function ScheduleSection(): JSX.Element {</div><span className="text-xs text-muted">{humanizeCadence(cadence)}</span>+ <span className="text-xs text-muted">+ Each run summarizes up to 100 observations from the period. Busier periods are sampled down to that+ limit.+ </span></div>)}