: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 scope to a named cohort (#92094)
Kim Svatos Dugan68519be319ea
diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.pyindex e3080bca939e..6cf7e8967553 100644--- a/products/replay_vision/backend/scanner_draft.py+++ b/products/replay_vision/backend/scanner_draft.py@@ -28,6 +28,7 @@ from posthog.schema import RecordingsQueryfrom posthog.api.search import (ENTITY_MAP as _SEARCH_ENTITY_MAP,+ EntityConfig,search_entities,)from posthog.llm.semantic_enrichment import get_team_business_context@@ -111,9 +112,24 @@ _SURVEY_ID_PROPERTY = "$survey_id"_MAX_MATCHED_ACTIONS = 10# Actions AND with the other filters like events do, so the same small ceiling applies._MAX_FILTER_ACTIONS = 2+# Cohorts whose names match the goal, shown so the draft can scope to a curated audience.+_MAX_MATCHED_COHORTS = 10+# A cohort filter is a person-level property, and separate properties AND, so one is usually the point.+_MAX_FILTER_COHORTS = 1# 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+# The shared search does not exclude soft-deleted rows, and a deleted entity is worse than no+# filter. A deleted cohort's filter is dropped when the recordings query resolves it+# (`CohortPropertyGroupsSubQuery` skips a cohort it cannot load), so the scan silently widens to+# every session while the rationale still describes an audience. Surveys are excluded from this on+# purpose: an archived survey keeps its id and its past `survey sent` events, so scanning the people+# who answered it is a real goal.+_LIVE_SEARCH_ENTITY_MAP: dict[str, EntityConfig] = {+ **_SEARCH_ENTITY_MAP,+ "action": {**_SEARCH_ENTITY_MAP["action"], "filters": {"deleted": False}},+ "cohort": {**_SEARCH_ENTITY_MAP["cohort"], "filters": {"deleted": False}},+}# 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(@@ -274,6 +290,24 @@ class _MatchedAction:action_id: int+@dataclass(frozen=True, kw_only=True)+class _MatchedCohort:+ """One of the team's cohorts whose name matches the goal, with the ID a filter needs."""++ name: str+ cohort_id: int+++@dataclass(frozen=True, kw_only=True)+class _GoalEntityMatches:+ """The named objects a goal can target, each resolved to the ID a filter needs. Empty lists+ where the goal named nothing of that kind, or the caller's scopes exclude reading it."""++ surveys: list[_MatchedSurvey]+ actions: list[_MatchedAction]+ cohorts: list[_MatchedCohort]++class _SearchView:"""The duck type `search_entities` reads from its `view` argument. The real callers areviewsets; here only the access-control handle is needed."""@@ -718,6 +752,12 @@ class _LlmDraftV2(BaseModel):"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_cohorts: list[str] = Field(+ default_factory=list,+ description="Cohorts whose members the scan is limited to, each copied verbatim from the briefing's "+ "matching-cohorts list. Use when the goal is about a specific audience ('what do power users do'); a "+ "cohort scopes to those people. Usually just one; leave empty when the goal is not about who the user is.",+ )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 "@@ -798,6 +838,10 @@ Pick the single type that best fits the goal, then draft the scanner:team's own curated definition of a behavior, so when one covers the goal, prefer it over hand-pickingevents or pages. Copy the name exactly; anything not in the list is discarded. Actions AND with everyother filter, so the one strongest action usually stands alone.+- filter_cohorts: the briefing may list the team's cohorts matching the goal. A cohort is a saved+ audience, so use one when the goal is about WHO the user is ('what do power users struggle with')+ rather than what they did. Copy the name exactly; anything not in the list is discarded. Usually+ one cohort; it ANDs with every other filter.- 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:@@ -843,6 +887,7 @@ def _build_user_content_v2(scanners: list[_ExistingScanner] | None = None,surveys: Sequence[_MatchedSurvey] = (),actions: Sequence[_MatchedAction] = (),+ cohorts: Sequence[_MatchedCohort] = (),business_context: str = "",company: str = "",) -> str:@@ -911,6 +956,18 @@ def _build_user_content_v2(),))+ if cohorts:+ lines.append(+ "\n"+ + as_untrusted_data(+ "matching-cohorts",+ [f'"{c.name}"' for c in cohorts],+ source=(+ "the team's cohorts whose names match the goal. Each is a saved audience; copy a name "+ "into filter_cohorts to scan only sessions from people in it"+ ),+ )+ )return "\n".join(lines)@@ -985,41 +1042,51 @@ def _goal_entity_matches(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.+) -> _GoalEntityMatches:+ """Surveys, actions, and cohorts 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 fromevents alone: every survey shares the same `survey sent` event, and the one the user means isidentified 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.+ property's values would return a list of UUIDs with nothing to choose between them. Actions and+ cohorts are the team's own curated definitions of a behavior and an audience, 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.+ Access control has two gates, and RBAC differs by kind. 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+ resource in `ACCESS_CONTROL_RESOURCES` (`survey`, `action`) needs the resource-level gate here.+ `cohort` is not an access-controlled resource, so it has no resource gate to apply (gating it+ would always deny). Scope: a scoped token must not receive any resource its scopes exclude, since+ this path has no viewset to enforce `required_scopes`, so every kind is also scope-gated."""terms = _goal_terms(goal)if not terms:- return [], []+ return _GoalEntityMatches(surveys=[], actions=[], cohorts=[])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)}+ acl_kinds: tuple[APIScopeObject, ...] = ("survey", "action")+ kinds: set[str] = {kind for kind in acl_kinds if _readable(kind) and _scopes_allow_read(allowed_scopes, kind)}+ # Cohorts are team-scoped only, not in ACCESS_CONTROL_RESOURCES, so they get no resource gate,+ # but a scoped token still must hold cohort:read to receive them.+ if _scopes_allow_read(allowed_scopes, "cohort"):+ kinds.add("cohort")+ # `search_entities` builds its result by unioning one queryset per kind, then orders by the rank+ # those querysets annotate. With no kind it orders an empty base queryset by a column that was+ # never added, which raises.if not kinds:- return [], []+ return _GoalEntityMatches(surveys=[], actions=[], cohorts=[])surveys: dict[str, _MatchedSurvey] = {}actions: dict[str, _MatchedAction] = {}+ cohorts: dict[str, _MatchedCohort] = {}view = _SearchView(user_access_control)try:for term in terms:@@ -1028,7 +1095,7 @@ def _goal_entity_matches(query=term,project_id=team.project_id,view=view, # type: ignore[arg-type]- entity_map=_SEARCH_ENTITY_MAP,+ entity_map=_LIVE_SEARCH_ENTITY_MAP,include_counts=False,)for result in results:@@ -1036,14 +1103,19 @@ def _goal_entity_matches(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:+ kind = result.get("type")+ if kind == "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:+ elif kind == "action" and len(actions) < _MAX_MATCHED_ACTIONS:actions.setdefault(result_id, _MatchedAction(name=name, action_id=int(result_id)))+ elif kind == "cohort" and len(cohorts) < _MAX_MATCHED_COHORTS:+ cohorts.setdefault(result_id, _MatchedCohort(name=name, cohort_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())+ return _GoalEntityMatches(+ surveys=list(surveys.values()), actions=list(actions.values()), cohorts=list(cohorts.values())+ )def _page_filter_regex(pathname: str) -> str | None:@@ -1078,6 +1150,7 @@ def _v2_query(events: Sequence[str],event_properties: Sequence[_LlmEventPropertyFilter] = (),actions: Sequence[_MatchedAction] = (),+ cohorts: Sequence[_MatchedCohort] = (),) -> dict[str, Any] | None:"""The scanner's recording filter from the grounded pages, events, and event properties.@@ -1089,9 +1162,17 @@ def _v2_query(Save-at-zero gate, catch an over-constrained AND before it ever becomes a scanner."""query: dict[str, Any] = {"kind": "RecordingsQuery"}+ properties: list[dict[str, Any]] = []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"}]+ properties.append({"type": "recording", "key": "visited_page", "value": values, "operator": "regex"})+ # A cohort is a person-level property; separate properties AND, so this narrows to sessions from+ # people in the cohort on top of any page filter.+ properties.extend(+ {"type": "cohort", "key": "id", "value": cohort.cohort_id, "operator": "in"} for cohort in cohorts+ )+ if properties:+ query["properties"] = propertiesif events:by_event: dict[str, list[dict[str, Any]]] = {}for prop in event_properties:@@ -1223,6 +1304,7 @@ def _finalize_v2(team_id: int,allowed_surveys: Sequence[_MatchedSurvey] = (),allowed_actions: Sequence[_MatchedAction] = (),+ allowed_cohorts: Sequence[_MatchedCohort] = (),) -> ScannerDraft:"""Normalize the v2 model output; costing is applied by the caller."""name = parsed.name.strip()[:_MAX_NAME_LENGTH]@@ -1254,7 +1336,13 @@ def _finalize_v2(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)+ cohorts_by_name = {c.name: c for c in allowed_cohorts}+ kept_cohorts = [+ cohorts_by_name[name]+ for name in dict.fromkeys(n.strip() for n in parsed.filter_cohorts)+ if name in cohorts_by_name+ ][:_MAX_FILTER_COHORTS]+ narrowing = _v2_query(pages, events, event_properties, kept_actions, kept_cohorts)query: dict[str, Any] = narrowing if narrowing is not None else {"kind": "RecordingsQuery"}query["filter_test_accounts"] = True@@ -1263,7 +1351,9 @@ 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 or parsed.filter_actions)+ widened_unexpectedly = narrowing is None and bool(+ proposed_pages or parsed.filter_events or parsed.filter_actions or parsed.filter_cohorts+ )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.@@ -1320,8 +1410,8 @@ 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:+ matches = _goal_entity_matches(team, goal, user_access_control, allowed_scopes)+ if matches.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.@@ -1331,8 +1421,9 @@ def draft_scanner_from_goal_v2(events,pages,scanners=_existing_scanners(team, user_access_control),- surveys=surveys,- actions=matched_actions,+ surveys=matches.surveys,+ actions=matches.actions,+ cohorts=matches.cohorts,business_context=_business_context(team, user) if include_business_context else "",company=company,)@@ -1349,8 +1440,9 @@ 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,+ allowed_surveys=matches.surveys,+ allowed_actions=matches.actions,+ allowed_cohorts=matches.cohorts,)# 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 f597f45a80d5..ffd3862c2209 100644--- a/products/replay_vision/backend/tests/test_scanner_draft.py+++ b/products/replay_vision/backend/tests/test_scanner_draft.py@@ -12,6 +12,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.rate_limit import AIBurstRateThrottlefrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom 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@@ -35,6 +36,7 @@ from products.replay_vision.backend.scanner_draft import (_LlmDraftV2,_LlmEventPropertyFilter,_MatchedAction,+ _MatchedCohort,_MatchedSurvey,_solve_budget,_v2_query,@@ -668,29 +670,30 @@ class TestGoalEntityMatches(_VisionAPITestCase):survey = self._survey("Pricing feedback")self._survey("Onboarding NPS")- surveys, _ = _goal_entity_matches(+ matches = _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))]+ assert [(m.name, m.survey_id) for m in matches.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(+ matches = _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)]+ assert [(a.name, a.action_id) for a in matches.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)) == ([], [])+ matches = _goal_entity_matches(self.team, "the pricing feedback survey", _access_control(allow=False))+ assert (matches.surveys, matches.actions, matches.cohorts) == ([], [], [])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@@ -701,37 +704,71 @@ class TestGoalEntityMatches(_VisionAPITestCase):denied.check_access_level_for_resource.return_value = Falsedenied.has_any_specific_access_for_resource.return_value = False- assert _goal_entity_matches(self.team, "the pricing feedback survey", denied) == ([], [])+ # Cohorts have no resource gate, so denial affects only surveys and actions; a cohort by the+ # same name still comes back, which is correct: cohorts are not resource-access-controlled.+ matches = _goal_entity_matches(self.team, "the pricing feedback survey", denied)+ assert matches.surveys == [] and matches.actions == []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")+ Cohort.objects.create(team=self.team, name="Pricing feedback cohort")- surveys, actions = _goal_entity_matches(+ matches = _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 == []+ # Every kind is scope-gated: the token holds none of survey:read, action:read, cohort:read.+ assert matches.surveys == []+ assert matches.actions == []+ assert matches.cohorts == []++ def test_no_readable_kind_searches_nothing(self):+ # `search_entities` orders by a rank its per-kind querysets annotate, so calling it with no+ # kind raises on a column that was never added. The broad except would hide that as an empty+ # result, with a traceback logged on every draft.+ self._survey("Pricing feedback")++ with patch(f"{_MODULE}.search_entities") as search:+ matches = _goal_entity_matches(+ self.team,+ "the pricing feedback survey",+ _access_control(allow=True),+ allowed_scopes=["replay_scanner:write", "session_recording:read"],+ )++ assert not search.called+ assert (matches.surveys, matches.actions, matches.cohorts) == ([], [], [])++ def test_a_soft_deleted_entity_is_never_matched(self):+ # The shared search does not exclude deleted rows. A deleted cohort is the expensive case:+ # the recordings query drops a cohort filter it cannot resolve, so the scan widens to every+ # session while the rationale still describes an audience.+ Cohort.objects.create(team=self.team, name="Power users", deleted=True)+ Action.objects.create(team=self.team, name="Power users click", deleted=True)++ matches = _goal_entity_matches(self.team, "what do power users struggle with", _access_control(allow=True))++ assert matches.cohorts == []+ assert matches.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(+ by_write = _goal_entity_matches(self.team, "the pricing feedback survey", _access_control(allow=True), allowed_scopes=["survey:write"])- by_star, _ = _goal_entity_matches(+ 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)]+ assert [s.survey_id for s in by_write.surveys] == [str(survey.id)]+ assert [s.survey_id for s in by_star.surveys] == [str(survey.id)]class TestV2Query:@@ -784,6 +821,14 @@ class TestV2Query:]assert "properties" not in by_id["checkout_started"]+ def test_a_cohort_becomes_a_top_level_person_property(self):+ # A cohort scopes to people; it rides the top-level properties array, ANDing with a page+ # filter rather than a per-event one.+ query = _v2_query(["/billing"], [], cohorts=[_MatchedCohort(name="Power users", cohort_id=7)])++ assert query is not None+ assert {"type": "cohort", "key": "id", "value": 7, "operator": "in"} in query["properties"]+def test_no_pages_and_no_events_is_no_query(self):assert _v2_query([], []) is None@@ -877,6 +922,27 @@ class TestFinalizeV2PropertyFilters:assert "properties" not in draft.query["events"][0]+class TestFinalizeV2Cohorts:+ _COHORT = _MatchedCohort(name="Power users", cohort_id=7)++ def _finalize(self, **overrides):+ return _finalize_v2(+ _draft_v2(**overrides), allowed_pages=[], allowed_events=[], team_id=1, allowed_cohorts=[self._COHORT]+ )++ def test_a_grounded_cohort_name_becomes_a_person_property_with_its_id(self):+ draft = self._finalize(filter_cohorts=["Power users"])++ assert draft.query is not None+ assert {"type": "cohort", "key": "id", "value": 7, "operator": "in"} in draft.query["properties"]++ def test_an_invented_cohort_name_is_dropped(self):+ draft = self._finalize(filter_cohorts=["Made-up audience"])++ assert draft.query is not None+ assert "properties" not in draft.query++class TestFinalizeV2Actions:_ACTION = _MatchedAction(name="Completed checkout", action_id=42)