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): draft session filters and allow_inconclusive from the scanner goal (#83417)

Arno Hillen5e8bf0a60b2d
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 19580a68c715..f0eb792458b6 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -1257,10 +1257,13 @@ class DraftScannerResponseSerializer(serializers.Serializer):
allow_blank=True,
help_text="Why the draft picked this scanner type and configuration, addressed to the user.",
)
- query = serializers.JSONField(
- allow_null=True,
- help_text="Drafted `RecordingsQuery` narrowing which sessions get scanned, holding one event filter "
- "picked from the team's real events; null when no event clearly matched the goal.",
+ query = extend_schema_field(RecordingsQuery)( # type: ignore[arg-type, type-var]
+ serializers.JSONField(
+ allow_null=True,
+ help_text=(
+ "`RecordingsQuery` narrowing which sessions get scanned; null when the draft targets every session."
+ ),
+ )
)
diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.py
index b004471cc789..ba4a3a2d1c48 100644
--- a/products/replay_vision/backend/scanner_draft.py
+++ b/products/replay_vision/backend/scanner_draft.py
@@ -10,6 +10,7 @@ re-validates everything on save.
"""
import uuid
+from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, Literal
@@ -57,6 +58,14 @@ _MAX_OUTPUT_TOKENS = 4096
# Bounds on assembled context so a scanner-heavy team can't blow up the prompt.
_MAX_EXISTING_SCANNERS = 15
_SCANNER_GIST_CHARS = 200
+# Filters combine with AND on the recordings query, so a couple of well-chosen ones is the ceiling;
+# more just zeroes out the match set.
+_MAX_FILTER_SCREENS = 1
+_MAX_FILTER_EVENTS = 2
+# Screens match via icontains, so a short pathname like "/" or "/en" matches nearly every URL:
+# it renders as a narrowing filter while narrowing nothing. Require this many non-slash
+# characters before a screen can ground a filter.
+_MIN_SCREEN_FILTER_CHARS = 3
class DraftError(Exception):
@@ -90,10 +99,20 @@ class _LlmDraft(BaseModel):
length: Literal["short", "medium", "long"] = Field(
default="medium", description="Summarizer only: how long each summary should be."
)
- filter_event: str | None = Field(
- default=None,
- description="The one event name, copied EXACTLY from the briefing's most-active-events list, that a "
- "session must contain to be relevant to the goal; null when no listed event clearly maps to it.",
+ allow_inconclusive: bool = Field(
+ default=False,
+ description="Monitor only: let the scanner answer inconclusive when a recording doesn't contain "
+ "enough evidence to decide. Turn on when many sessions won't reach the flow the question is about.",
+ )
+ filter_screens: list[str] = Field(
+ default_factory=list,
+ description="Screens/paths a session must have visited to be worth scanning, copied verbatim from "
+ "the briefing's screens list; empty when the goal concerns all sessions.",
+ )
+ filter_events: list[str] = Field(
+ default_factory=list,
+ description="Events a session must contain to be worth scanning, copied verbatim from the "
+ "briefing's custom events list; empty when the goal concerns all sessions.",
)
@@ -194,15 +213,19 @@ Pick the single type that best fits the goal, then draft the scanner:
separately via `scale_min`/`scale_max`.
- summarizer prompts say what the summary should focus on.
- Fill only the fields relevant to the chosen type; leave the rest at their defaults.
+- For monitors: set allow_inconclusive to true when many sessions won't even reach the flow the question
+ is about (e.g. a checkout question when most sessions never open checkout), so those sessions aren't
+ forced into a no.
- For classifiers: 4-8 lowercase snake_case tags that are distinct, non-overlapping categories along the
dimension. No vague catch-alls ("other", "misc").
+- filter_screens / filter_events: when the goal targets one specific flow, screen, or feature, narrow which
+ sessions get scanned: up to 1 screen and up to 2 events a session must include, each copied EXACTLY from
+ the briefing's screens and custom events lists (anything not in those lists is discarded). The filters
+ AND together, so only combine a screen and an event when sessions genuinely have both. Leave both empty
+ when the goal spans all sessions or no listed entry clearly matches the flow.
- rationale: one or two sentences, addressed to the user, explaining why the chosen type and settings fit
their goal (e.g. why a classifier rather than a scorer, or what the scale's endpoints capture). It is
shown next to the draft in the creation wizard; plain language, and don't restate the config itself.
-- filter_event: when the goal targets a specific flow AND one event in the briefing's "most active custom
- events" list clearly marks that flow (e.g. a checkout goal and a checkout_started event), set it to that
- event name copied EXACTLY as listed, so only sessions containing it get scanned. When the goal is broad,
- or no listed event clearly maps to it, leave it null. Never invent or reword an event name.
The briefing may include the company's name, its business context, and the team's existing scanners:
- Use the business context to make the name, description, and prompt specific to THIS company's product,
@@ -298,7 +321,7 @@ def draft_scanner_from_goal(
company=company,
)
parsed = _generate(user_content=user_content, team_id=team.id, distinct_id=str(user.uuid))
- return _finalize(parsed, offered_events=taxonomy.events)
+ return _finalize(parsed, allowed_screens=taxonomy.screens, allowed_events=taxonomy.events, team_id=team.id)
def _generate(*, user_content: str, team_id: int, distinct_id: str) -> _LlmDraft:
@@ -352,7 +375,40 @@ def _generate(*, user_content: str, team_id: int, distinct_id: str) -> _LlmDraft
raise DraftError("invalid response") from e
-def _finalize(parsed: _LlmDraft, offered_events: list[str] | None = None) -> ScannerDraft:
+def _grounded(proposed: list[str], allowed: Sequence[str], cap: int) -> list[str]:
+ """Keep only filter values that exist verbatim in the taxonomy the model was shown: a filter the
+ product never emits would silently match zero sessions, so a hallucinated one must not survive."""
+ allowed_set = set(allowed)
+ return list(dict.fromkeys(v for raw in proposed if (v := raw.strip()) in allowed_set))[:cap]
+
+
+def _screen_can_ground(screen: str) -> bool:
+ return len(screen.strip().replace("/", "")) >= _MIN_SCREEN_FILTER_CHARS
+
+
+def _filters_query(screens: list[str], events: list[str]) -> dict[str, Any] | None:
+ if not screens and not events:
+ return None
+ query: dict[str, Any] = {"kind": "RecordingsQuery"}
+ if screens:
+ # The shape the replay filter UI produces: visited_page matches the recording's all_urls,
+ # so it catches the screen even when no event fired there.
+ query["properties"] = [
+ {"type": "recording", "key": "visited_page", "value": [screen], "operator": "icontains"}
+ for screen in screens
+ ]
+ if events:
+ query["events"] = [{"id": event, "name": event, "type": "events", "order": 0} for event in events]
+ return query
+
+
+def _finalize(
+ parsed: _LlmDraft,
+ *,
+ allowed_screens: Sequence[str] = (),
+ allowed_events: Sequence[str] = (),
+ team_id: int | None = None,
+) -> ScannerDraft:
"""Normalize the model output into a draft the wizard form (and later the create endpoint) will accept."""
name = parsed.name.strip()[:_MAX_NAME_LENGTH]
prompt = parsed.prompt.strip()[:_MAX_PROMPT_LENGTH]
@@ -360,7 +416,11 @@ def _finalize(parsed: _LlmDraft, offered_events: list[str] | None = None) -> Sca
raise DraftError("draft missing name or prompt")
scanner_config: dict[str, Any] = {"prompt": prompt}
- if parsed.scanner_type == "classifier":
+ if parsed.scanner_type == "monitor":
+ # Only carried when on, mirroring the wizard toggle's off-by-default.
+ if parsed.allow_inconclusive:
+ scanner_config["allow_inconclusive"] = True
+ elif parsed.scanner_type == "classifier":
# Order-preserving dedup of slugified tags, dropping anything that slugs to empty.
tags = list(dict.fromkeys(s for t in parsed.tags if (s := slugify_tag(t))))[:_MAX_DRAFT_TAGS]
scanner_config["tags"] = tags
@@ -388,14 +448,26 @@ def _finalize(parsed: _LlmDraft, offered_events: list[str] | None = None) -> Sca
if error:
raise DraftError(f"draft config invalid: {error}")
- # Only an event that exists in the offered taxonomy may become a filter: anything else is a
- # hallucinated name that would silently match no recordings.
- query: dict[str, Any] | None = None
- if parsed.filter_event and parsed.filter_event in (offered_events or []):
- query = {
- "kind": "RecordingsQuery",
- "events": [{"type": "events", "id": parsed.filter_event, "name": parsed.filter_event, "order": 0}],
- }
+ screens = _grounded(
+ [s for s in parsed.filter_screens if _screen_can_ground(s)], allowed_screens, _MAX_FILTER_SCREENS
+ )
+ events = _grounded(parsed.filter_events, allowed_events, _MAX_FILTER_EVENTS)
+ dropped_screens = {s for s in (v.strip() for v in parsed.filter_screens) if s} - set(screens)
+ dropped_events = {e for e in (v.strip() for v in parsed.filter_events) if e} - set(events)
+ if dropped_screens or dropped_events:
+ # Every dropped value silently broadens the scan (worst case to every session, the most
+ # expensive outcome) while the rationale may still describe a narrow one, so the drop
+ # rate has to be observable.
+ logger.warning(
+ "replay_vision.scanner_draft.filter_values_dropped",
+ team_id=team_id,
+ scanner_type=parsed.scanner_type,
+ dropped_screens=len(dropped_screens),
+ dropped_events=len(dropped_events),
+ kept_screens=len(screens),
+ kept_events=len(events),
+ scans_every_session=not screens and not events,
+ )
return ScannerDraft(
name=name,
@@ -403,5 +475,5 @@ def _finalize(parsed: _LlmDraft, offered_events: list[str] | None = None) -> Sca
scanner_type=parsed.scanner_type,
scanner_config=scanner_config,
rationale=parsed.rationale.strip()[:_MAX_RATIONALE_LENGTH],
- query=query,
+ query=_filters_query(screens, events),
)
diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.py
index db1d281a5732..206cd3398ed0 100644
--- a/products/replay_vision/backend/tests/test_scanner_draft.py
+++ b/products/replay_vision/backend/tests/test_scanner_draft.py
@@ -3,6 +3,8 @@ from unittest.mock import MagicMock, patch
from rest_framework import status
+from posthog.schema import RecordingsQuery
+
from posthog.models import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.rate_limit import AIBurstRateThrottle
@@ -19,6 +21,7 @@ from products.replay_vision.backend.scanner_draft import (
_generate,
_LlmDraft,
)
+from products.replay_vision.backend.tag_suggestions import _ProductTaxonomy
from products.replay_vision.backend.tests.test_api import _VisionAPITestCase
_GENERATE_PATH = "products.replay_vision.backend.scanner_draft._generate"
@@ -143,42 +146,130 @@ class TestFinalize:
assert result.scanner_config == {"prompt": _draft().prompt, "length": "short"}
- def test_offered_filter_event_becomes_a_recordings_query(self):
- result = _finalize(_draft(filter_event="checkout_started"), offered_events=["checkout_started", "signup"])
+ def test_rationale_is_trimmed_and_capped(self):
+ result = _finalize(_draft(rationale=" why " + "x" * 600))
+
+ assert result.rationale.startswith("why x")
+ assert len(result.rationale) == 500
+
+ def test_blank_prompt_is_an_error(self):
+ with pytest.raises(DraftError):
+ _finalize(_draft(prompt=" "))
+
+ def test_classifier_whose_tags_all_slugify_away_is_an_error(self):
+ # `tags: []` would 200 into a configure form the create endpoint then rejects.
+ with pytest.raises(DraftError):
+ _finalize(_draft(scanner_type="classifier", tags=["!!!", "***"]))
+
+ def test_monitor_carries_allow_inconclusive_only_when_on(self):
+ # Off stays absent, mirroring the wizard toggle's default; on any other type it's not a valid key.
+ assert "allow_inconclusive" not in _finalize(_draft()).scanner_config
+ assert _finalize(_draft(allow_inconclusive=True)).scanner_config["allow_inconclusive"] is True
+ assert (
+ "allow_inconclusive"
+ not in _finalize(_draft(scanner_type="summarizer", allow_inconclusive=True)).scanner_config
+ )
+
+ def test_filters_build_a_recordings_query_grounded_in_the_taxonomy(self):
+ result = _finalize(
+ _draft(filter_screens=["/checkout"], filter_events=["checkout_started"]),
+ allowed_screens=["/checkout", "/cart"],
+ allowed_events=["checkout_started", "payment_failed"],
+ )
assert result.query == {
"kind": "RecordingsQuery",
- "events": [{"type": "events", "id": "checkout_started", "name": "checkout_started", "order": 0}],
+ "properties": [
+ {"type": "recording", "key": "visited_page", "value": ["/checkout"], "operator": "icontains"}
+ ],
+ "events": [{"id": "checkout_started", "name": "checkout_started", "type": "events", "order": 0}],
}
+ # The wizard and the scan pipeline both parse this as a RecordingsQuery; shape drift must fail here.
+ RecordingsQuery.model_validate(result.query)
@pytest.mark.parametrize(
- "filter_event,offered_events",
+ "screens,events,expected_keys",
[
- ("checkout started", ["checkout_started"]), # reworded, would match nothing
- ("made_up_event", ["checkout_started"]), # hallucinated
- ("checkout_started", []), # nothing offered to ground it
- (None, ["checkout_started"]), # model declined
+ (["/checkout"], ["checkout_started"], {"kind", "properties", "events"}),
+ (["/checkout"], [], {"kind", "properties"}),
+ ([], ["checkout_started"], {"kind", "events"}),
+ ([], [], None),
],
)
- def test_ungrounded_filter_event_yields_no_query(self, filter_event, offered_events):
- result = _finalize(_draft(filter_event=filter_event), offered_events=offered_events)
+ def test_query_carries_only_the_keys_with_surviving_filters(self, screens, events, expected_keys):
+ result = _finalize(
+ _draft(filter_screens=screens, filter_events=events),
+ allowed_screens=["/checkout"],
+ allowed_events=["checkout_started"],
+ )
+
+ if expected_keys is None:
+ assert result.query is None
+ else:
+ assert result.query is not None
+ # A key must be absent, not an empty list, when its filter kind didn't survive.
+ assert set(result.query) == expected_keys
+ RecordingsQuery.model_validate(result.query)
+
+ def test_hallucinated_filters_are_dropped(self):
+ # A filter value the product never emits would silently make the scanner match zero sessions.
+ result = _finalize(
+ _draft(filter_screens=["/imaginary"], filter_events=["made_up_event"]),
+ allowed_screens=["/checkout"],
+ allowed_events=["checkout_started"],
+ )
assert result.query is None
- def test_rationale_is_trimmed_and_capped(self):
- result = _finalize(_draft(rationale=" why " + "x" * 600))
+ @pytest.mark.parametrize("screen", ["/", "/en", "/a/b"])
+ def test_short_screens_cannot_ground_a_filter(self, screen):
+ # An icontains match on "/" or "/en" catches nearly every URL: the draft would render
+ # as narrowing while narrowing nothing.
+ result = _finalize(_draft(filter_screens=[screen]), allowed_screens=[screen, "/checkout"])
- assert result.rationale.startswith("why x")
- assert len(result.rationale) == 500
+ assert result.query is None
- def test_blank_prompt_is_an_error(self):
- with pytest.raises(DraftError):
- _finalize(_draft(prompt=" "))
+ def test_short_screen_does_not_consume_the_screen_cap(self):
+ result = _finalize(_draft(filter_screens=["/en", "/checkout"]), allowed_screens=["/en", "/checkout"])
- def test_classifier_whose_tags_all_slugify_away_is_an_error(self):
- # `tags: []` would 200 into a configure form the create endpoint then rejects.
- with pytest.raises(DraftError):
- _finalize(_draft(scanner_type="classifier", tags=["!!!", "***"]))
+ assert result.query is not None
+ assert [p["value"] for p in result.query["properties"]] == [["/checkout"]]
+
+ def test_dropping_proposed_filter_values_emits_a_structured_warning(self):
+ with patch("products.replay_vision.backend.scanner_draft.logger.warning") as warn:
+ grounded = _finalize(
+ _draft(filter_screens=["/checkout"], filter_events=["checkout_started"]),
+ allowed_screens=["/checkout"],
+ allowed_events=["checkout_started"],
+ team_id=42,
+ )
+ assert grounded.query is not None
+ warn.assert_not_called()
+
+ _finalize(
+ _draft(filter_screens=["/imaginary"], filter_events=["made_up_event"]),
+ allowed_screens=["/checkout"],
+ allowed_events=["checkout_started"],
+ team_id=42,
+ )
+
+ warn.assert_called_once()
+ kwargs = warn.call_args.kwargs
+ assert kwargs["team_id"] == 42
+ assert kwargs["dropped_screens"] == 1
+ assert kwargs["dropped_events"] == 1
+ assert kwargs["scans_every_session"] is True
+
+ def test_filters_are_stripped_capped_and_deduped(self):
+ result = _finalize(
+ _draft(filter_screens=["/alpha", "/beta"], filter_events=[" e1", "e1", "e2", "e3"]),
+ allowed_screens=["/alpha", "/beta"],
+ allowed_events=["e1", "e2", "e3"],
+ )
+
+ assert result.query is not None
+ assert [p["value"] for p in result.query["properties"]] == [["/alpha"]]
+ assert [e["id"] for e in result.query["events"]] == ["e1", "e2"]
class TestDraftGrounding(_VisionAPITestCase):
@@ -334,6 +425,25 @@ class TestDraftScannerEndpoint(_VisionAPITestCase):
"query": None,
}
+ @patch(_GENERATE_PATH)
+ @patch("products.replay_vision.backend.scanner_draft._product_taxonomy")
+ def test_returns_drafted_session_filters_grounded_in_taxonomy(self, mock_taxonomy, mock_generate):
+ mock_taxonomy.return_value = _ProductTaxonomy(events=["checkout_started"], screens=["/checkout"])
+ mock_generate.return_value = _draft(
+ filter_screens=["/checkout"], filter_events=["checkout_started", "made_up_event"]
+ )
+
+ resp = self.client.post(self.draft_url, data={"goal": "watch sessions that reach checkout"}, format="json")
+
+ assert resp.status_code == status.HTTP_200_OK, resp.json()
+ assert resp.json()["query"] == {
+ "kind": "RecordingsQuery",
+ "properties": [
+ {"type": "recording", "key": "visited_page", "value": ["/checkout"], "operator": "icontains"}
+ ],
+ "events": [{"id": "checkout_started", "name": "checkout_started", "type": "events", "order": 0}],
+ }
+
@patch(_CORE_MEMORY_FLAG_PATH, return_value=False)
@patch(_GENERATE_PATH)
def test_grounds_the_model_call_in_scanners_and_business_context(self, mock_generate, _flag):
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 9e5f756c3237..8eeea57cc8d5 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -1643,7 +1643,7 @@ export interface DraftScannerResponseApi {
scanner_config: unknown
/** Why the draft picked this scanner type and configuration, addressed to the user. */
rationale: string
- /** Drafted `RecordingsQuery` narrowing which sessions get scanned, holding one event filter picked from the team's real events; null when no event clearly matched the goal. */
+ /** `RecordingsQuery` narrowing which sessions get scanned; null when the draft targets every session. */
query: unknown
}
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
index 2e0a4c85720c..e92e94c3e5d3 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
@@ -119,7 +119,7 @@ describe('replayScannerLogic', () => {
rationale: 'A classifier fits because you want the mix of visit intents.',
query: {
kind: 'RecordingsQuery',
- events: [{ type: 'events', id: 'signed_up', name: 'signed_up', order: 0 }],
+ events: [{ id: 'signed_up', name: 'signed_up', type: 'events', order: 0 }],
},
}
draftSpy.mockReturnValue([200, draft])
@@ -148,6 +148,27 @@ describe('replayScannerLogic', () => {
expect(logic.values.goalDraft).toBeNull()
})
+ it('keeps the default query (every session) when the draft has no session filter', async () => {
+ draftSpy.mockReturnValue([
+ 200,
+ {
+ name: 'Overview',
+ description: 'Summarizes sessions.',
+ scanner_type: 'summarizer',
+ scanner_config: { prompt: 'Summarize the session.' },
+ rationale: '',
+ query: null,
+ },
+ ])
+ router.actions.push(urls.replayVisionScannerTemplate('new'))
+
+ await expectLogic(logic, () =>
+ logic.actions.draftScannerFromGoal('what are users doing?')
+ ).toFinishAllListeners()
+
+ expect(logic.values.scanner?.query).toEqual({ kind: 'RecordingsQuery' })
+ })
+
it('drops a stale draft when the user has left the template step mid-request', async () => {
draftSpy.mockReturnValue([
200,
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index 51577635bebe..84e05ea52b82 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -1671,8 +1671,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
description: goalDraft.description,
scanner_type: goalDraft.scanner_type as ScannerType,
scanner_config: goalDraft.scanner_config as ScannerConfig,
- // The drafted event filter (when the goal mapped to a real event); the triggers step
- // shows it for review like any hand-picked filter.
+ // The drafted session filter (when the goal mapped to real screens or events); the
+ // triggers step shows it for review like any hand-picked filter.
...(goalDraft.query ? { query: goalDraft.query as RecordingsQuery } : {}),
})
router.actions.push(urls.replayVisionScannerDetails('new'))
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7f7cd0140ce9..2c8ad0d2db72 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27329,7 +27329,7 @@ export namespace Schemas {
scanner_config: unknown;
/** Why the draft picked this scanner type and configuration, addressed to the user. */
rationale: string;
- /** Drafted `RecordingsQuery` narrowing which sessions get scanned, holding one event filter picked from the team's real events; null when no event clearly matched the goal. */
+ /** `RecordingsQuery` narrowing which sessions get scanned; null when the draft targets every session. */
query: unknown;
}