: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): let a goal target a named survey or action (#92070)
Kim Svatos Dugance22d6f40bc8
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 262ed3256666..0c49987c2043 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -2211,9 +2211,11 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi"goal_flow": goal_flow,"monthly_credit_budget": monthly_credit_budget,}- # Core memory's own API is INTERNAL (session-only), so scoped tokens must not- # receive its content through the draft either.- include_business_context = get_authenticator_scopes(request.successful_authenticator) is None+ # Scoped tokens must not receive data their scopes exclude. Core memory is INTERNAL+ # (session-only), so any scoped token loses it; the goal-based entity grounding (surveys,+ # actions) is gated per resource against these scopes inside the drafter.+ allowed_scopes = get_authenticator_scopes(request.successful_authenticator)+ include_business_context = allowed_scopes is Nonetry:if goal_flow:@@ -2224,6 +2226,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vimonthly_credit_budget=cast(int, monthly_credit_budget),user_access_control=self.user_access_control,include_business_context=include_business_context,+ allowed_scopes=allowed_scopes,)else:drafted = draft_scanner_from_goal(diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.pyindex 03c289cf595b..9fa64c594639 100644--- a/products/replay_vision/backend/scanner_draft.py+++ b/products/replay_vision/backend/scanner_draft.py@@ -26,10 +26,15 @@ from pydantic import BaseModel, Fieldfrom posthog.schema import RecordingsQuery+from posthog.api.search import (+ ENTITY_MAP as _SEARCH_ENTITY_MAP,+ search_entities,+)from posthog.llm.semantic_enrichment import get_team_business_contextfrom posthog.models import EventDefinitionfrom posthog.models.team import Teamfrom posthog.models.user import User+from posthog.scopes import APIScopeObjectfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.replay_vision.backend.billing import observation_credits_for_model@@ -97,6 +102,19 @@ _MAX_GOAL_MATCHED_EVENTS = 30_MIN_GOAL_TERM_CHARS = 4# Only the first terms are looked up, so a long goal stays one bounded query._MAX_GOAL_TERMS = 8+# Surveys whose names match the goal, shown with their IDs so a filter can name one exactly.+_MAX_MATCHED_SURVEYS = 10+# The events that carry a survey's identity, and the property holding it. A filter on one survey is+# an event filter plus this property, which is why the draft needs property filters at all.+_SURVEY_EVENTS = ("survey sent", "survey shown", "survey dismissed")+_SURVEY_ID_PROPERTY = "$survey_id"+# Actions whose names match the goal, shown so the draft can filter on a curated behavior.+_MAX_MATCHED_ACTIONS = 10+# Actions AND with the other filters like events do, so the same small ceiling applies.+_MAX_FILTER_ACTIONS = 2+# Property filters the model may attach to its chosen events. Two is enough to name a thing and+# qualify it; more usually means the filter is describing several flows at once.+_MAX_FILTER_EVENT_PROPERTIES = 2# Words common to almost any goal. Matching them returns arbitrary events rather than the ones the# user means, and crowds out the terms that carry the intent._GOAL_STOPWORDS = frozenset(@@ -241,6 +259,30 @@ class ScannerDraft:credit_limit: int | None = None+@dataclass(frozen=True, kw_only=True)+class _MatchedSurvey:+ """One of the team's surveys whose name matches the goal, with the ID a filter needs."""++ name: str+ survey_id: str+++@dataclass(frozen=True, kw_only=True)+class _MatchedAction:+ """One of the team's actions whose name matches the goal, with the ID a filter needs."""++ name: str+ action_id: int+++class _SearchView:+ """The duck type `search_entities` reads from its `view` argument. The real callers are+ viewsets; here only the access-control handle is needed."""++ def __init__(self, user_access_control: UserAccessControl) -> None:+ self.user_access_control = user_access_control++@dataclass(frozen=True, kw_only=True)class _ExistingScanner:"""One existing scanner, condensed for the drafting prompt."""@@ -618,6 +660,14 @@ def _finalize(# ---------------------------------------------------------------------------+class _LlmEventPropertyFilter(BaseModel):+ """One property condition narrowing an event the draft already filters on."""++ event: str = Field(description="The event to narrow, copied from this draft's `filter_events`.")+ property: str = Field(description="The property name, copied verbatim from the briefing (e.g. '$survey_id').")+ value: str = Field(description="The value to match, copied verbatim from the briefing (e.g. a survey's id).")++class _LlmDraftV2(BaseModel):"""The model's structured output for the goal-based flow: one drafted scanner plus targeting."""@@ -663,6 +713,18 @@ class _LlmDraftV2(BaseModel):"fired when a flow starts). Each event ANDs, with the other events and with the pages, so a session must ""have all of them; keep to the one or two that define the flow, and leave empty when pages already capture it.",)+ filter_actions: list[str] = Field(+ default_factory=list,+ description="Actions a session must contain to be worth scanning, each copied verbatim from the "+ "briefing's matching-actions list. An action is the team's own saved definition of a behavior, so "+ "prefer one over hand-picking events when it covers the goal. Each ANDs with the other filters.",+ )+ filter_event_properties: list[_LlmEventPropertyFilter] = Field(+ default_factory=list,+ description="Narrows an event in `filter_events` to one thing, for goals that name a specific survey "+ "rather than surveys in general. Only use a property and value the briefing showed; anything else is "+ "dropped. Leave empty when the event alone is what the goal means.",+ )sampling_mode: Literal["comprehensive", "balanced", "focused"] = Field(default="comprehensive",description="Which sessions deserve the budget when it cannot cover everything; see the drafting rules.",@@ -727,6 +789,16 @@ Pick the single type that best fits the goal, then draft the scanner:nothing. Anything not copied from the briefing's lists is discarded.- Leave both empty ONLY when the goal genuinely spans the whole product ("summarize what users dohere").+- filter_event_properties: use ONLY when the goal names one specific thing its event cannot identify+ on its own. The case this exists for is surveys: every survey fires the same "survey sent" event,+ so a goal about ONE survey needs that event AND the property filter the briefing lists beside the+ matching survey. Copy the event, property, and value exactly as shown. An invented value matches+ nothing and the scanner never runs, so anything not from the briefing is discarded. When the goal+ is about surveys in general, filter on the event alone and leave this empty.+- filter_actions: the briefing may list the team's saved actions matching the goal. An action is the+ team's own curated definition of a behavior, so when one covers the goal, prefer it over hand-picking+ events or pages. Copy the name exactly; anything not in the list is discarded. Actions AND with every+ other filter, so the one strongest action usually stands alone.- sampling_mode: who deserves the budget when it cannot cover every matching session. Each sessioncarries a score of how eventful it looks; the mode drops the lowest-scoring sessions before randomsampling. Choose by what the goal hunts:@@ -770,6 +842,8 @@ def _build_user_content_v2(pages: Sequence[VisitedPath],*,scanners: list[_ExistingScanner] | None = None,+ surveys: Sequence[_MatchedSurvey] = (),+ actions: Sequence[_MatchedAction] = (),business_context: str = "",company: str = "",) -> str:@@ -810,6 +884,34 @@ def _build_user_content_v2(source="the scanners the team already has (the goal may reference these by name)",))+ if surveys:+ lines.append(+ "\n"+ + as_untrusted_data(+ "matching-surveys",+ [+ f'"{s.name}" -> filter_event_properties {{"event": "survey sent", '+ f'"property": "{_SURVEY_ID_PROPERTY}", "value": "{s.survey_id}"}}'+ for s in surveys+ ],+ source=(+ "the team's surveys whose names match the goal. Every survey shares the same "+ "'survey sent' event, so targeting one needs the property filter shown beside it"+ ),+ )+ )+ if actions:+ lines.append(+ "\n"+ + as_untrusted_data(+ "matching-actions",+ [f'"{a.name}"' for a in actions],+ source=(+ "the team's saved actions whose names match the goal. Each is a curated definition "+ "of a behavior; copy a name into filter_actions to scan only sessions containing it"+ ),+ )+ )return "\n".join(lines)@@ -865,6 +967,86 @@ def _events_for_goal(team: Team, goal: str) -> list[str]:return list(dict.fromkeys([*matched, *baseline]))+def _scopes_allow_read(allowed_scopes: list[str] | None, resource: APIScopeObject) -> bool:+ """Whether a credential's API scopes permit reading `resource`.++ `None` means session or other non-token auth, which is not scope-gated (RBAC applies instead).+ Mirrors APIScopePermission's matching: `*` grants everything, and a `:write` scope implies+ `:read`. Without this, a scoped token carrying only `replay_scanner:write` and+ `session_recording:read` could name a team's surveys and receive their IDs through the draft,+ despite lacking `survey:read`.+ """+ if allowed_scopes is None:+ return True+ return "*" in allowed_scopes or f"{resource}:read" in allowed_scopes or f"{resource}:write" in allowed_scopes+++def _goal_entity_matches(+ team: Team,+ goal: str,+ user_access_control: UserAccessControl,+ allowed_scopes: list[str] | None = None,+) -> tuple[list[_MatchedSurvey], list[_MatchedAction]]:+ """Surveys and actions the caller can read whose names match the goal's words.++ A goal that names a survey ("people who answered the pricing survey") cannot be filtered from+ events alone: every survey shares the same `survey sent` event, and the one the user means is+ identified by `$survey_id`. Reading the survey by name gives that ID exactly, where sampling the+ property's values would return a list of UUIDs with nothing to choose between them. Actions are+ the team's own curated definitions of a behavior, so a goal naming one is the sharpest filter+ available.++ Matching goes through `search_entities`, the ranked full-text search behind the app's search bar,+ one bounded call per goal term because its query grammar ANDs every word of its input.++ Both kinds are gated two ways. RBAC: `search_entities` applies the queryset filter, but that+ filter passes everything through when the caller has neither resource access nor object grants,+ and this helper has no viewset permission check behind it, so each kind needs the resource-level+ gate here. Scope: a scoped token must not receive a resource its scopes exclude, since this path+ has no viewset to enforce `required_scopes`. A kind must clear both.+ """+ terms = _goal_terms(goal)+ if not terms:+ return [], []++ def _readable(resource: APIScopeObject) -> bool:+ return user_access_control.check_access_level_for_resource(+ resource, required_level="viewer"+ ) or user_access_control.has_any_specific_access_for_resource(resource, required_level="viewer")++ searchable: tuple[APIScopeObject, ...] = ("survey", "action")+ kinds: set[str] = {kind for kind in searchable if _readable(kind) and _scopes_allow_read(allowed_scopes, kind)}+ if not kinds:+ return [], []++ surveys: dict[str, _MatchedSurvey] = {}+ actions: dict[str, _MatchedAction] = {}+ view = _SearchView(user_access_control)+ try:+ for term in terms:+ results, _, _ = search_entities(+ entities=kinds,+ query=term,+ project_id=team.project_id,+ view=view, # type: ignore[arg-type]+ entity_map=_SEARCH_ENTITY_MAP,+ include_counts=False,+ )+ for result in results:+ extra = result.get("extra_fields") or {}+ name, result_id = str(extra.get("name") or ""), str(result.get("result_id") or "")+ if not name or not result_id:+ continue+ if result.get("type") == "survey" and len(surveys) < _MAX_MATCHED_SURVEYS:+ surveys.setdefault(result_id, _MatchedSurvey(name=name, survey_id=result_id))+ elif result.get("type") == "action" and len(actions) < _MAX_MATCHED_ACTIONS:+ actions.setdefault(result_id, _MatchedAction(name=name, action_id=int(result_id)))+ except Exception:+ # Losing the entity matches costs the precise filters, not the draft.+ logger.warning("replay_vision.scanner_draft.goal_entities_failed", team_id=team.id, exc_info=True)+ return list(surveys.values()), list(actions.values())++def _page_filter_regex(pathname: str) -> str | None:"""A ClickHouse regex matching real URLs for a collapsed grounding path, or None when the pathcannot narrow.@@ -892,23 +1074,48 @@ def _strip_page_count(page: str) -> str:return re.sub(r"\s*\(\d+\)\s*$", "", page).strip()-def _v2_query(pathnames: Sequence[str], events: Sequence[str]) -> dict[str, Any] | None:- """The scanner's recording filter from the grounded pages and events.+def _v2_query(+ pathnames: Sequence[str],+ events: Sequence[str],+ event_properties: Sequence[_LlmEventPropertyFilter] = (),+ actions: Sequence[_MatchedAction] = (),+) -> dict[str, Any] | None:+ """The scanner's recording filter from the grounded pages, events, and event properties.Pages become ONE multi-value `visited_page` property (its values OR). Each value is a regex thatmatches the collapsed page against real URLs, with ":id" runs wildcarded. Events go in the- `events` list, where each event ANDs, with the other events and with the page property. The- estimate the caller runs, and the review page's Save-at-zero gate, catch an over-constrained AND- before it ever becomes a scanner.+ `events` list, where each event ANDs, with the other events and with the page property. A+ property filter rides on its event's entry, so "survey sent where $survey_id is X" stays one+ condition rather than matching every survey. The estimate the caller runs, and the review page's+ Save-at-zero gate, catch an over-constrained AND before it ever becomes a scanner."""query: dict[str, Any] = {"kind": "RecordingsQuery"}values = list(dict.fromkeys(v for p in pathnames if (v := _page_filter_regex(p)) is not None))if values:query["properties"] = [{"type": "recording", "key": "visited_page", "value": values, "operator": "regex"}]if events:+ by_event: dict[str, list[dict[str, Any]]] = {}+ for prop in event_properties:+ by_event.setdefault(prop.event, []).append(+ {"key": prop.property, "value": [prop.value], "operator": "exact", "type": "event"}+ )# The shape the replay filter UI produces for an event condition.- query["events"] = [{"id": event, "name": event, "type": "events", "order": 0} for event in events]- if "properties" not in query and "events" not in query:+ query["events"] = [+ {+ "id": event,+ "name": event,+ "type": "events",+ "order": 0,+ **({"properties": p} if (p := by_event.get(event)) else {}),+ }+ for event in events+ ]+ if actions:+ # The shape the replay filter UI produces for an action condition.+ query["actions"] = [+ {"id": action.action_id, "name": action.name, "type": "actions", "order": 0} for action in actions+ ]+ if not any(key in query for key in ("properties", "events", "actions")):return Nonereturn query@@ -984,8 +1191,39 @@ def _solve_budget()+def _grounded_event_properties(+ proposed: Sequence[_LlmEventPropertyFilter],+ *,+ kept_events: Sequence[str],+ allowed_surveys: Sequence[_MatchedSurvey],+) -> list[_LlmEventPropertyFilter]:+ """Property filters whose event survived grounding and whose value the briefing actually showed.++ A property filter narrows a scan, so an invented value is worse than a dropped one: it would+ match nothing and the scanner would never run. Only values read back from the team's own data+ are allowed through.+ """+ allowed_values = {s.survey_id for s in allowed_surveys}+ kept = set(kept_events)+ out: list[_LlmEventPropertyFilter] = []+ for prop in proposed:+ event, name, value = prop.event.strip(), prop.property.strip(), prop.value.strip()+ if event not in kept or name != _SURVEY_ID_PROPERTY or value not in allowed_values:+ continue+ out.append(_LlmEventPropertyFilter(event=event, property=name, value=value))+ if len(out) >= _MAX_FILTER_EVENT_PROPERTIES:+ break+ return out++def _finalize_v2(- parsed: _LlmDraftV2, *, allowed_pages: Sequence[str], allowed_events: Sequence[str], team_id: int+ parsed: _LlmDraftV2,+ *,+ allowed_pages: Sequence[str],+ allowed_events: Sequence[str],+ team_id: int,+ allowed_surveys: Sequence[_MatchedSurvey] = (),+ allowed_actions: Sequence[_MatchedAction] = (),) -> ScannerDraft:"""Normalize the v2 model output; costing is applied by the caller."""name = parsed.name.strip()[:_MAX_NAME_LENGTH]@@ -1006,7 +1244,18 @@ def _finalize_v2(# creator says otherwise (the recordings step can toggle it back on). No-op for a team that has# not configured internal-user filters. The narrowing query is None when no page or event# survives, so the base still carries this default.- narrowing = _v2_query(pages, events)+ event_properties = _grounded_event_properties(+ parsed.filter_event_properties, kept_events=events, allowed_surveys=allowed_surveys+ )+ # Grounding by construction: a name maps back to the matched action's own id, so an invented+ # name has no id to resolve to and drops out.+ actions_by_name = {a.name: a for a in allowed_actions}+ kept_actions = [+ actions_by_name[name]+ for name in dict.fromkeys(n.strip() for n in parsed.filter_actions)+ if name in actions_by_name+ ][:_MAX_FILTER_ACTIONS]+ narrowing = _v2_query(pages, events, event_properties, kept_actions)query: dict[str, Any] = narrowing if narrowing is not None else {"kind": "RecordingsQuery"}query["filter_test_accounts"] = True@@ -1015,7 +1264,7 @@ def _finalize_v2(# A page can ground yet drop to None in `_page_filter_value` (a too-short prefix) with nothing# formally dropped, so the query still widens to everything. Fire the warning whenever the model# wanted a filter but none survived, not only when a value was dropped.- widened_unexpectedly = narrowing is None and bool(proposed_pages or parsed.filter_events)+ widened_unexpectedly = narrowing is None and bool(proposed_pages or parsed.filter_events or parsed.filter_actions)if dropped_pages or dropped_events or widened_unexpectedly:# Every dropped value silently broadens the scan (worst case to every non-internal session,# the most expensive outcome) while the rationale may still describe a narrow one.@@ -1052,6 +1301,7 @@ def draft_scanner_from_goal_v2(monthly_credit_budget: int,user_access_control: UserAccessControl,include_business_context: bool = True,+ allowed_scopes: list[str] | None = None,) -> ScannerDraft:"""The goal-based flow: ground the goal in the team's real pages, draft the whole scanner in onemodel call, then solve the sampling dials from the stated monthly credit budget.@@ -1071,11 +1321,19 @@ def draft_scanner_from_goal_v2(if include_business_contextelse "")+ surveys, matched_actions = _goal_entity_matches(team, goal, user_access_control, allowed_scopes)+ if surveys:+ # A goal can name a survey without using the word "survey" ("who answered XYZ Feedback"), so+ # the survey events may not have matched on their own. A property filter is useless without+ # the event it rides on, so offer those events whenever a survey matched.+ events = list(dict.fromkeys([*_SURVEY_EVENTS, *events]))user_content = _build_user_content_v2(goal,events,pages,scanners=_existing_scanners(team, user_access_control),+ surveys=surveys,+ actions=matched_actions,business_context=_business_context(team, user) if include_business_context else "",company=company,)@@ -1092,6 +1350,8 @@ def draft_scanner_from_goal_v2(allowed_pages=[p.pathname for p in pages],allowed_events=events,team_id=team.id,+ allowed_surveys=surveys,+ allowed_actions=matched_actions,)# The cap is the stated budget, so a mis-estimate stops the scanner at the credits the user# agreed to rather than overspending. Kept even when costing fails, so the guardrail survives.diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.pyindex cb4cf85a4d02..8775b991f865 100644--- a/products/replay_vision/backend/tests/test_scanner_draft.py+++ b/products/replay_vision/backend/tests/test_scanner_draft.py@@ -11,6 +11,7 @@ from posthog.models import EventDefinition, PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.rate_limit import AIBurstRateThrottle+from products.actions.backend.models.action import Actionfrom products.posthog_ai.backend.models.assistant import CoreMemoryfrom products.replay_vision.backend.models.replay_scanner import ScannerTypefrom products.replay_vision.backend.queries.scanner_candidate_query import MIN_SAMPLING_RATE@@ -28,15 +29,20 @@ from products.replay_vision.backend.scanner_draft import (_finalize,_finalize_v2,_generate,+ _goal_entity_matches,_goal_terms,_LlmDraft,_LlmDraftV2,+ _LlmEventPropertyFilter,+ _MatchedAction,+ _MatchedSurvey,_solve_budget,_v2_query,draft_scanner_from_goal_v2,)from products.replay_vision.backend.tag_suggestions import _ProductTaxonomyfrom products.replay_vision.backend.tests.test_api import _VisionAPITestCase+from products.surveys.backend.models import Survey_GENERATE_PATH = "products.replay_vision.backend.scanner_draft._generate"_MODULE = "products.replay_vision.backend.scanner_draft"@@ -46,7 +52,12 @@ _CORE_MEMORY_FLAG_PATH = "products.replay_vision.backend.scanner_draft.is_core_mdef _access_control(*, allow: bool) -> MagicMock:ac = MagicMock()- ac.filter_queryset_by_access_level.side_effect = (lambda qs: qs) if allow else (lambda qs: qs.none())+ # Callers pass `resource=` for resources that have their own access controls, so accept kwargs.+ ac.filter_queryset_by_access_level.side_effect = (+ (lambda qs, **kwargs: qs) if allow else (lambda qs, **kwargs: qs.none())+ )+ # The resource-level checks default to a truthy MagicMock, which is the "has access" path; a+ # test that needs the denial sets them False explicitly.return ac@@ -647,6 +658,82 @@ class TestEventsForGoal(_VisionAPITestCase):assert events == ["checkout_started"]+class TestGoalEntityMatches(_VisionAPITestCase):+ def _survey(self, name: str):+ return Survey.objects.create(team=self.team, name=name, created_by=self.user)++ def test_a_survey_named_in_the_goal_comes_back_with_its_id(self):+ # The filter needs the id: every survey fires the same "survey sent" event, so a name alone+ # cannot target one.+ survey = self._survey("Pricing feedback")+ self._survey("Onboarding NPS")++ surveys, _ = _goal_entity_matches(+ self.team, "watch people who answered the pricing feedback survey", _access_control(allow=True)+ )++ assert [(m.name, m.survey_id) for m in surveys] == [("Pricing feedback", str(survey.id))]++ def test_an_action_named_in_the_goal_comes_back_with_its_id(self):+ # An action is the team's own curated definition of a behavior, so a goal naming one is the+ # sharpest filter available and must come back with the id the query needs.+ action = Action.objects.create(team=self.team, name="Completed checkout")++ _, actions = _goal_entity_matches(+ self.team, "sessions where someone completed checkout", _access_control(allow=True)+ )++ assert [(a.name, a.action_id) for a in actions] == [("Completed checkout", action.id)]++ def test_an_entity_the_caller_cannot_read_is_never_named_back(self):+ # Surveys and actions are access-controlled, so naming one back would leak its existence.+ self._survey("Pricing feedback")+ Action.objects.create(team=self.team, name="Pricing feedback click")++ assert _goal_entity_matches(self.team, "the pricing feedback survey", _access_control(allow=False)) == ([], [])++ def test_no_resource_access_returns_nothing_even_though_the_queryset_filter_would_pass_it(self):+ # `filter_queryset_by_access_level` returns the queryset untouched when the caller has+ # neither resource access nor object grants, and this helper has no viewset permission check+ # behind it, so the resource check is what stops the leak.+ self._survey("Pricing feedback")+ denied = _access_control(allow=True)+ denied.check_access_level_for_resource.return_value = False+ denied.has_any_specific_access_for_resource.return_value = False++ assert _goal_entity_matches(self.team, "the pricing feedback survey", denied) == ([], [])++ def test_a_scoped_token_lacking_survey_read_gets_no_surveys(self):+ # A token with scanner and recording scopes but not survey:read must not learn a survey's+ # name or id through the draft. RBAC alone would allow it; the scope gate is what stops it.+ self._survey("Pricing feedback")+ Action.objects.create(team=self.team, name="Pricing feedback click")++ surveys, actions = _goal_entity_matches(+ self.team,+ "the pricing feedback survey",+ _access_control(allow=True),+ allowed_scopes=["replay_scanner:write", "session_recording:read"],+ )++ assert surveys == []+ # The action is also gated: no action:read scope either.+ assert actions == []++ def test_a_write_scope_implies_read_and_a_star_scope_grants_all(self):+ survey = self._survey("Pricing feedback")++ by_write, _ = _goal_entity_matches(+ self.team, "the pricing feedback survey", _access_control(allow=True), allowed_scopes=["survey:write"]+ )+ by_star, _ = _goal_entity_matches(+ self.team, "the pricing feedback survey", _access_control(allow=True), allowed_scopes=["*"]+ )++ assert [s.survey_id for s in by_write] == [str(survey.id)]+ assert [s.survey_id for s in by_star] == [str(survey.id)]++class TestV2Query:def test_pages_become_one_multi_value_property(self):# Separate properties would AND and match almost nothing: measured 68 sessions where the@@ -681,6 +768,22 @@ class TestV2Query:assert query["properties"][0]["value"] == ["/billing"]assert query["events"][0]["id"] == "checkout_started"+ def test_a_property_filter_rides_on_its_own_event_entry(self):+ # Every survey fires the same event, so the property has to sit on that event's entry. A+ # sibling event must not inherit it, or the filter would demand the wrong condition.+ query = _v2_query(+ [],+ ["survey sent", "checkout_started"],+ [_LlmEventPropertyFilter(event="survey sent", property="$survey_id", value="abc-123")],+ )++ assert query is not None+ by_id = {e["id"]: e for e in query["events"]}+ assert by_id["survey sent"]["properties"] == [+ {"key": "$survey_id", "value": ["abc-123"], "operator": "exact", "type": "event"}+ ]+ assert "properties" not in by_id["checkout_started"]+def test_no_pages_and_no_events_is_no_query(self):assert _v2_query([], []) is None@@ -732,6 +835,71 @@ class TestV2Query:assert query["properties"][0]["value"] == ["/invoice/[^/]+", "/invoice/[^/]+/edit"]+class TestFinalizeV2PropertyFilters:+ _SURVEY = _MatchedSurvey(name="Pricing feedback", survey_id="abc-123")++ def _finalize(self, **overrides):+ return _finalize_v2(+ _draft_v2(filter_events=["survey sent"], **overrides),+ allowed_pages=[],+ allowed_events=["survey sent"],+ team_id=1,+ allowed_surveys=[self._SURVEY],+ )++ def test_a_grounded_survey_filter_reaches_the_query(self):+ draft = self._finalize(+ filter_event_properties=[+ _LlmEventPropertyFilter(event="survey sent", property="$survey_id", value="abc-123")+ ]+ )++ assert draft.query is not None+ assert draft.query["events"][0]["properties"] == [+ {"key": "$survey_id", "value": ["abc-123"], "operator": "exact", "type": "event"}+ ]++ @pytest.mark.parametrize(+ "bad",+ [+ # An id the briefing never showed: it would match no session, so the scanner never runs.+ _LlmEventPropertyFilter(event="survey sent", property="$survey_id", value="not-a-real-id"),+ # A property the briefing never showed.+ _LlmEventPropertyFilter(event="survey sent", property="$made_up", value="abc-123"),+ # An event that did not survive grounding, so there is no entry to attach to.+ _LlmEventPropertyFilter(event="never_seen_event", property="$survey_id", value="abc-123"),+ ],+ )+ def test_an_ungrounded_property_filter_is_dropped(self, bad):+ draft = self._finalize(filter_event_properties=[bad])++ assert draft.query is not None+ assert "properties" not in draft.query["events"][0]+++class TestFinalizeV2Actions:+ _ACTION = _MatchedAction(name="Completed checkout", action_id=42)++ def _finalize(self, **overrides):+ return _finalize_v2(+ _draft_v2(**overrides), allowed_pages=[], allowed_events=[], team_id=1, allowed_actions=[self._ACTION]+ )++ def test_a_grounded_action_name_becomes_an_action_filter_with_its_id(self):+ draft = self._finalize(filter_actions=["Completed checkout"])++ assert draft.query is not None+ assert draft.query["actions"] == [{"id": 42, "name": "Completed checkout", "type": "actions", "order": 0}]++ def test_an_invented_action_name_is_dropped(self):+ # A name has no id to resolve to unless it came from the matched list, so it cannot invent+ # a filter that silently matches nothing.+ draft = self._finalize(filter_actions=["Made-up behavior"])++ assert draft.query is not None+ assert "actions" not in draft.query++class TestFinalizeV2:def test_hallucinated_pages_are_dropped(self):draft = _finalize_v2(