: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): keep dead actions out of a goal's briefing (#94421)
Kim Svatos Dugance64bbeb70a3
diff --git a/products/actions/backend/facade/__init__.py b/products/actions/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/actions/backend/facade/api.py b/products/actions/backend/facade/api.pynew file mode 100644index 000000000000..0b0ab8cc4758--- /dev/null+++ b/products/actions/backend/facade/api.py@@ -0,0 +1,50 @@+"""+Facade API for actions.++This is the module that other apps / the presentation layer should+import from. It accepts plain inputs and returns HogQL conditions or+contract DTOs, never ORM instances or QuerySets.++Do NOT:+- Import DRF / serializers / HTTP concerns here+- Return ORM instances or QuerySets+"""++from __future__ import annotations++from collections.abc import Sequence++from posthog.hogql import ast+from posthog.hogql.property import action_to_expr++from posthog.models import Team++from products.actions.backend.models.action import Action+++def action_filter_conditions(*, team: Team, action_ids: Sequence[int]) -> dict[int, ast.Expr]:+ """The HogQL condition matching each action's events, keyed by action id.++ Lets another product filter events by action without holding the Action model, which stays in+ this product. A caller that puts a condition in two places in one query must clone it with+ `clone_expr`, because the HogQL resolver annotates the nodes it walks.++ Scoped to the team's project, the same way actions are read everywhere else.++ An action is absent from the result when it belongs to another project, when it is deleted, or+ when it has no steps. A stepless action compiles to a condition that matches every event, which+ reads as a filter but is not one.+ """+ if not action_ids:+ return {}++ conditions: dict[int, ast.Expr] = {}+ for action in Action.objects.filter(team__project_id=team.project_id, id__in=action_ids, deleted=False):+ if not action.steps:+ continue+ try:+ conditions[action.id] = action_to_expr(action)+ except Exception:+ # One action with an uncompilable step must not cost the caller the rest of them.+ continue+ return conditionsdiff --git a/products/actions/backend/tests/test_facade.py b/products/actions/backend/tests/test_facade.pynew file mode 100644index 000000000000..f434d1af04a5--- /dev/null+++ b/products/actions/backend/tests/test_facade.py@@ -0,0 +1,33 @@+from posthog.test.base import APIBaseTest++from posthog.models import Team++from products.actions.backend.facade.api import action_filter_conditions+from products.actions.backend.models.action import Action+++class TestActionFilterConditions(APIBaseTest):+ def _action(self, name: str, **kwargs) -> Action:+ kwargs.setdefault("steps_json", [{"event": "checkout completed"}])+ kwargs.setdefault("team", self.team)+ return Action.objects.create(name=name, **kwargs)++ def test_only_actions_that_can_filter_come_back(self):+ # A caller uses the returned keys to decide which actions are usable, so an action that+ # cannot narrow anything must be absent rather than present with a condition that matches+ # everything. A stepless action is the trap: `steps_to_expr` compiles it to a constant true.+ live = self._action("Completed checkout")+ stepless = self._action("Never finished", steps_json=[])+ deleted = self._action("Removed", deleted=True)++ conditions = action_filter_conditions(team=self.team, action_ids=[live.id, stepless.id, deleted.id])++ assert list(conditions) == [live.id]++ def test_an_action_outside_the_project_is_never_returned(self):+ # The ids reach this function from a search, so trusting them would let a caller compile a+ # filter against another project's action.+ other_team = Team.objects.create(organization=self.organization, name="other")+ theirs = Action.objects.create(team=other_team, name="Theirs", steps_json=[{"event": "checkout completed"}])++ assert action_filter_conditions(team=self.team, action_ids=[theirs.id]) == {}diff --git a/products/replay_vision/backend/queries/action_volume.py b/products/replay_vision/backend/queries/action_volume.pynew file mode 100644index 000000000000..3ff364aac5e7--- /dev/null+++ b/products/replay_vision/backend/queries/action_volume.py@@ -0,0 +1,92 @@+import datetime as dt+from collections.abc import Sequence++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.query import execute_hogql_query+from posthog.hogql.visitor import clone_expr++from posthog.clickhouse.client.connection import ClickHouseUser+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.models import Team++from products.actions.backend.facade.api import action_filter_conditions++# The same window the visited pages list uses, so a briefing can compare an action against a page.+_ACTION_WINDOW_DAYS = 7+# Actions are counted in one query, so the whole measurement shares this budget.+_ACTION_QUERY_MAX_EXECUTION_SECONDS = 5+++def _any_of(conditions: list[ast.Expr]) -> ast.Expr:+ """One condition unchanged, or several ORed. `ast.Or` needs at least two operands."""+ return conditions[0] if len(conditions) == 1 else ast.Or(exprs=conditions)+++def recent_action_sessions(+ *,+ team: Team,+ action_ids: Sequence[int],+ window_days: int = _ACTION_WINDOW_DAYS,+ ch_user: ClickHouseUser = ClickHouseUser.APP,+) -> dict[int, int]:+ """How many sessions each action fired in over a recent window, keyed by action id.++ An action is a saved definition, not collected data, so it outlives the thing it describes. An+ autocapture action keyed to a button's text stops matching when the copy changes, and nothing on+ the action records that it went quiet. Measuring is the only way to tell a live action from one+ that has matched nothing for years.++ A count of 0 means the action fired in no session in the window. An action absent from the result+ could not be read, or does not compile to a filter.++ Raises on query failure, so the caller decides whether a missing measurement is fatal.+ """+ conditions = action_filter_conditions(team=team, action_ids=action_ids)+ if not conditions:+ return {}++ measured = list(conditions)+ columns: list[ast.Expr] = [+ ast.Alias(+ alias=f"action_{action_id}",+ expr=ast.Call(name="uniqIf", args=[ast.Field(chain=["$session_id"]), condition]),+ )+ for action_id, condition in conditions.items()+ ]++ window_start = dt.datetime.now(dt.UTC) - dt.timedelta(days=window_days)+ query = ast.SelectQuery(+ select=columns,+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ where=ast.And(+ exprs=[+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=window_start),+ ),+ # Narrows the scan to events at least one action can match, so the cost tracks the+ # actions asked about and not the team's whole event volume. Cloned because the+ # resolver annotates the nodes it walks, and these also sit in the SELECT.+ _any_of([clone_expr(condition) for condition in conditions.values()]),+ ]+ ),+ )++ tag_queries(team_id=team.id, product=Product.REPLAY_VISION, feature=Feature.QUERY)+ response = execute_hogql_query(+ query=query,+ team=team,+ query_type="ReplayVisionActionVolumeQuery",+ # "throw", not "break": a partial aggregate reads as a live action that went quiet, which is+ # the exact distinction this query exists to make.+ settings=HogQLGlobalSettings(+ max_execution_time=_ACTION_QUERY_MAX_EXECUTION_SECONDS, timeout_overflow_mode="throw"+ ),+ ch_user=ch_user,+ )+ rows = response.results or []+ if not rows:+ return dict.fromkeys(measured, 0)+ return {action_id: int(count) for action_id, count in zip(measured, rows[0])}diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.pyindex 6cf7e8967553..e22adab6568c 100644--- a/products/replay_vision/backend/scanner_draft.py+++ b/products/replay_vision/backend/scanner_draft.py@@ -40,6 +40,7 @@ from posthog.scopes import APIScopeObjectfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, SamplingMode, ScannerModel, ScannerType+from products.replay_vision.backend.queries.action_volume import recent_action_sessionsfrom products.replay_vision.backend.queries.scanner_candidate_query import MIN_SAMPLING_RATE, SAMPLE_RATE_PRECISIONfrom products.replay_vision.backend.queries.scanner_volume_estimate import (PREVIEW_ESTIMATE_BUDGET,@@ -288,6 +289,9 @@ class _MatchedAction:name: straction_id: int+ # Sessions the action fired in over the volume query's window. Shown in the briefing so the model+ # can prefer a busy action when several match the goal.+ recent_sessions: int = 0@dataclass(frozen=True, kw_only=True)@@ -837,7 +841,9 @@ Pick the single type that best fits the goal, then draft the scanner:- filter_actions: the briefing may list the team's saved actions matching the goal. An action is theteam'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 every- other filter, so the one strongest action usually stands alone.+ other filter, so the one strongest action usually stands alone. Each action shows the sessions it+ fired in recently: when several fit the goal, pick the busier one, and prefer an event or a page over+ an action that barely fires.- filter_cohorts: the briefing may list the team's cohorts matching the goal. A cohort is a savedaudience, 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@@ -949,10 +955,11 @@ def _build_user_content_v2("\n"+ as_untrusted_data("matching-actions",- [f'"{a.name}"' for a in actions],+ [f'"{a.name}" ({a.recent_sessions} sessions last 7 days)' 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"+ "the team's saved actions whose names match the goal, each with the sessions it "+ "fired in recently. Each is a curated definition of a behavior; copy a name into "+ "filter_actions to scan only sessions containing it"),))@@ -1118,6 +1125,34 @@ def _goal_entity_matches()+def _live_actions(team: Team, actions: list[_MatchedAction]) -> list[_MatchedAction]:+ """The matched actions that still fire, each carrying its recent session count.++ A name match cannot tell a current action from one whose definition stopped matching years ago.+ An autocapture action keyed to a button's text dies when the copy changes, while its name keeps+ matching a goal about that feature. Offering a dead action costs the whole scanner, because an+ action ANDs with every other filter and takes the session count to zero.++ Fails open, because name matches without their counts still beat no matches at all.+ """+ if not actions:+ return []+ try:+ sessions = recent_action_sessions(team=team, action_ids=[action.action_id for action in actions])+ except Exception:+ logger.warning("replay_vision.scanner_draft.action_volume_failed", team_id=team.id, exc_info=True)+ return actions+ live = [replace(a, recent_sessions=count) for a in actions if (count := sessions.get(a.action_id, 0)) > 0]+ if len(live) < len(actions):+ logger.info(+ "replay_vision.scanner_draft.dead_actions_dropped",+ team_id=team.id,+ matched=len(actions),+ dropped=len(actions) - len(live),+ )+ return live++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.@@ -1411,6 +1446,9 @@ def draft_scanner_from_goal_v2(else "")matches = _goal_entity_matches(team, goal, user_access_control, allowed_scopes)+ # Measured here rather than inside the match, so the access-control helper stays free of a+ # ClickHouse query its other callers do not need.+ matches = replace(matches, actions=_live_actions(team, matches.actions))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 withoutdiff --git a/products/replay_vision/backend/tests/test_action_volume.py b/products/replay_vision/backend/tests/test_action_volume.pynew file mode 100644index 000000000000..30a2ce6e4e20--- /dev/null+++ b/products/replay_vision/backend/tests/test_action_volume.py@@ -0,0 +1,73 @@+import datetime as dt++import pytest+from freezegun import freeze_time+from posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_and_events++from posthog.models import Team++from products.actions.backend.models.action import Action+from products.replay_vision.backend.queries.action_volume import recent_action_sessions++_NOW = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)+_FROZEN_TIME = _NOW.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _event(team, event: str, session_id: str, at: dt.datetime) -> None:+ _create_event(+ team=team,+ event=event,+ distinct_id="d1",+ timestamp=at,+ properties={"$session_id": session_id},+ )+++def _action(team, name: str, event: str) -> Action:+ return Action.objects.create(team=team, name=name, steps_json=[{"event": event}])+++@freeze_time(_FROZEN_TIME)+class TestRecentActionSessions(ClickhouseTestMixin):+ @pytest.mark.django_db+ def test_a_dead_action_separates_from_a_live_one_by_its_session_count(self, team) -> None:+ live = _action(team, "Completed checkout", "checkout completed")+ dead = _action(team, "Clicked the old button", "button clicked v1")+ _event(team, "checkout completed", "s1", _NOW - dt.timedelta(hours=2))+ # Same session twice: the count is sessions, not events, so this must not read as two.+ _event(team, "checkout completed", "s1", _NOW - dt.timedelta(hours=1))+ _event(team, "checkout completed", "s2", _NOW - dt.timedelta(days=3))++ counts = recent_action_sessions(team=team, action_ids=[live.id, dead.id])++ assert counts == {live.id: 2, dead.id: 0}++ @pytest.mark.django_db+ def test_an_action_that_only_fired_before_the_window_reads_as_dead(self, team) -> None:+ # The whole point of the measurement is recency: an action that fired years ago and stopped+ # is the case that produces a scanner with nothing to scan.+ stale = _action(team, "Clicked the old button", "button clicked v1")+ _event(team, "button clicked v1", "s1", _NOW - dt.timedelta(days=30))++ assert recent_action_sessions(team=team, action_ids=[stale.id]) == {stale.id: 0}++ @pytest.mark.django_db+ def test_an_action_with_no_steps_is_never_measured(self, team) -> None:+ # A stepless action compiles to a condition that matches every event, so measuring it would+ # report the team's whole session count and read as the liveliest action in the briefing.+ stepless = Action.objects.create(team=team, name="Never finished", steps_json=[])+ _event(team, "checkout completed", "s1", _NOW - dt.timedelta(hours=2))+ # This path returns before it queries, and `_create_event` only writes its batch when a+ # query runs. Without the flush the event stays pending and fails the next test's teardown.+ flush_persons_and_events()++ assert recent_action_sessions(team=team, action_ids=[stepless.id]) == {}++ @pytest.mark.django_db+ def test_an_action_from_another_project_is_never_measured(self, team) -> None:+ # The ids come from a search, so a measurement that trusted them would read another+ # project's action and report its volume back into this team's briefing.+ other_team = Team.objects.create(organization=team.organization, name="other")+ theirs = _action(other_team, "Completed checkout", "checkout completed")++ assert recent_action_sessions(team=team, action_ids=[theirs.id]) == {}diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.pyindex ffd3862c2209..f345694f4e5a 100644--- a/products/replay_vision/backend/tests/test_scanner_draft.py+++ b/products/replay_vision/backend/tests/test_scanner_draft.py@@ -32,6 +32,7 @@ from products.replay_vision.backend.scanner_draft import (_generate,_goal_entity_matches,_goal_terms,+ _live_actions,_LlmDraft,_LlmDraftV2,_LlmEventPropertyFilter,@@ -771,6 +772,27 @@ class TestGoalEntityMatches(_VisionAPITestCase):assert [s.survey_id for s in by_star.surveys] == [str(survey.id)]+class TestLiveActions(_VisionAPITestCase):+ def test_an_action_that_fires_in_no_session_never_reaches_the_briefing(self):+ # A name match cannot tell a live action from one whose definition stopped matching years+ # ago. An action ANDs with every other filter, so offering a dead one drafts a scanner that+ # matches nothing.+ live = _MatchedAction(name="Completed checkout", action_id=1)+ dead = _MatchedAction(name="Clicked the old button", action_id=2)++ with patch(f"{_MODULE}.recent_action_sessions", return_value={1: 42, 2: 0}):+ kept = _live_actions(self.team, [live, dead])++ assert [(a.name, a.recent_sessions) for a in kept] == [("Completed checkout", 42)]++ def test_a_failed_measurement_keeps_every_match(self):+ # Losing the counts must cost the ranking hint, not the actions themselves.+ actions = [_MatchedAction(name="Completed checkout", action_id=1)]++ with patch(f"{_MODULE}.recent_action_sessions", side_effect=Exception("clickhouse down")):+ assert _live_actions(self.team, actions) == actions++class TestV2Query:def test_pages_become_one_multi_value_property(self):# Separate properties would AND and match almost nothing: measured 68 sessions where thediff --git a/tach.toml b/tach.tomlindex 7f247697b680..1d316b37ea6d 100644--- a/tach.toml+++ b/tach.toml@@ -725,6 +725,7 @@ path = "products.replay_vision"depends_on = ["ee","posthog",+ "products.actions","products.alerts","products.cdp","products.cohorts",