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): fall back to the pages when a drafted filter is dead (#94422)

Kim Svatos Dugan63269ce08979
diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.py
index e22adab6568c..e5d62f6ee100 100644
--- a/products/replay_vision/backend/scanner_draft.py
+++ b/products/replay_vision/backend/scanner_draft.py
@@ -1499,9 +1499,107 @@ def draft_scanner_from_goal_v2(
# A slow count must not throw away a good draft; the wizard falls back to its defaults.
logger.warning("replay_vision.scanner_draft.budget_solve_failed", team_id=team.id, exc_info=True)
return replace(draft, sampling_mode=None, sampling_rate=None, estimated_monthly_observations=None)
+ if solution.estimated_monthly_observations == 0:
+ draft, solution = _fall_back_to_pages(
+ team=team,
+ user=user,
+ draft=draft,
+ solution=solution,
+ monthly_credit_budget=monthly_credit_budget,
+ )
return replace(
draft,
sampling_mode=solution.sampling_mode,
sampling_rate=solution.sampling_rate,
estimated_monthly_observations=solution.estimated_monthly_observations,
)
+
+
+def _pages_only(query: dict[str, Any] | None) -> dict[str, Any] | None:
+ """The draft's page and cohort filters, without its events and actions. None when the draft has
+ no page filter to fall back to.
+
+ Cohorts stay because a cohort says who the goal is about, not what the product still emits.
+ Dropping one would scan those pages for everybody, spending credits on sessions the goal never
+ asked about. When the cohort is itself what matched nothing, the caller's re-estimate comes back
+ zero again and the original draft is kept.
+
+ Keeps `filter_test_accounts`, because dropping it would widen the scan to internal traffic while
+ trying to make the filter match.
+ """
+ if not query:
+ return None
+ properties = query.get("properties") or []
+ pages = [p for p in properties if p.get("key") == "visited_page"]
+ if not pages:
+ return None
+ cohorts = [p for p in properties if p.get("type") == "cohort"]
+ return {
+ "kind": "RecordingsQuery",
+ "properties": [*pages, *cohorts],
+ "filter_test_accounts": query.get("filter_test_accounts", True),
+ }
+
+
+def _fall_back_to_pages(
+ *,
+ team: Team,
+ user: User,
+ draft: ScannerDraft,
+ solution: _BudgetSolution,
+ monthly_credit_budget: int,
+) -> tuple[ScannerDraft, _BudgetSolution]:
+ """Replace a filter that matches no sessions with the draft's page filter.
+
+ Events and actions AND with everything else, so one that the product stopped emitting takes the
+ whole filter to zero and the scanner never runs. The pages come from measured traffic, which
+ makes them the one part of the filter that cannot be dead.
+
+ Returns the draft and solution unchanged when the draft has no page filter, when the estimate
+ fails, or when the pages match nothing either, because widening to every session would scan a
+ product the goal never asked about.
+ """
+ fallback = _pages_only(draft.query)
+ if fallback is None:
+ return draft, solution
+ try:
+ relaxed = _solve_budget(
+ team=team,
+ user=user,
+ query=fallback,
+ monthly_credit_budget=monthly_credit_budget,
+ credits_per_observation=observation_credits_for_model(draft.model or ScannerModel.GEMINI_3_FLASH_PREVIEW),
+ model_mode=draft.sampling_mode or SamplingMode.COMPREHENSIVE,
+ )
+ except Exception:
+ logger.warning("replay_vision.scanner_draft.fallback_solve_failed", team_id=team.id, exc_info=True)
+ return draft, solution
+ if relaxed.estimated_monthly_observations == 0:
+ return draft, solution
+
+ dropped_events = len(draft.query.get("events") or []) if draft.query else 0
+ dropped_actions = len(draft.query.get("actions") or []) if draft.query else 0
+ logger.warning(
+ "replay_vision.scanner_draft.filters_matched_nothing",
+ team_id=team.id,
+ dropped_events=dropped_events,
+ dropped_actions=dropped_actions,
+ )
+ rationale = _fallback_rationale(draft.rationale, dropped_events=dropped_events, dropped_actions=dropped_actions)
+ return replace(draft, query=fallback, rationale=rationale), relaxed
+
+
+def _fallback_rationale(rationale: str, *, dropped_events: int, dropped_actions: int) -> str:
+ """The draft's rationale plus a note that the filter it describes was replaced.
+
+ The rationale still describes the filter the model picked, so leaving it alone would tell the
+ user this scanner watches something it no longer watches.
+
+ Trims the model's own text rather than the note, so the note cannot be cut in half by the cap.
+ """
+ if dropped_events and dropped_actions:
+ filters = "event and action filters"
+ else:
+ filters = "event filter" if dropped_events else "action filter"
+ note = f"The {filters} matched no recent recordings, so this scans the pages instead."
+ return f"{rationale[: _MAX_RATIONALE_LENGTH - len(note) - 1].strip()} {note}".strip()
diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.py
index f345694f4e5a..c0556c998492 100644
--- a/products/replay_vision/backend/tests/test_scanner_draft.py
+++ b/products/replay_vision/backend/tests/test_scanner_draft.py
@@ -1188,6 +1188,79 @@ class TestDraftV2(_VisionAPITestCase):
# survives — but the scanner still defaults to excluding internal users.
assert draft.query == {"kind": "RecordingsQuery", "filter_test_accounts": True}
+ def _estimate_by_query(self, dead_when):
+ def estimate(*, team, query, user, sampling_mode, budget):
+ matched = 0 if dead_when(query) else 300
+ return ScannerVolumeEstimate(matched_sessions=matched, effective_window_days=30)
+
+ return estimate
+
+ def _drafted_with(self, generate, estimate):
+ with (
+ patch(f"{_MODULE}.fetch_visited_paths", return_value=(VisitedPath(pathname="/billing", sessions=10),)),
+ patch(_GENERATE_PATH, return_value=generate),
+ patch(f"{_MODULE}.estimate_scanner_session_volume", side_effect=estimate),
+ ):
+ return draft_scanner_from_goal_v2(
+ team=self.team,
+ user=self.user,
+ goal="find out where people give up in billing",
+ monthly_credit_budget=10_000,
+ user_access_control=_access_control(allow=True),
+ )
+
+ def test_an_event_filter_that_matches_nothing_falls_back_to_the_pages(self):
+ # An event the product stopped emitting ANDs the whole filter to zero, so the scanner would
+ # never run. The pages come from measured traffic, so they cannot be dead the same way.
+ EventDefinition.objects.create(team=self.team, name="billing_limit_set", last_seen_at=timezone.now())
+
+ draft = self._drafted_with(
+ _draft_v2(filter_pages=["/billing"], filter_events=["billing_limit_set"]),
+ self._estimate_by_query(lambda query: bool(query.events)),
+ )
+
+ assert draft.query is not None
+ assert "events" not in draft.query
+ assert draft.query["properties"][0]["key"] == "visited_page"
+ assert draft.estimated_monthly_observations == 300
+ # The rationale describes the filter the model picked, so it has to say the filter changed.
+ assert "scans the pages instead" in draft.rationale
+
+ def test_the_fallback_keeps_the_audience_the_goal_named(self):
+ # A cohort says who the goal is about, so it does not go stale the way an event does.
+ # Dropping it alongside the dead event would scan the pages for everybody, spending credits
+ # on sessions the goal never asked about.
+ EventDefinition.objects.create(team=self.team, name="billing_limit_set", last_seen_at=timezone.now())
+ cohort = Cohort.objects.create(team=self.team, name="Billing power users")
+
+ draft = self._drafted_with(
+ _draft_v2(
+ filter_pages=["/billing"],
+ filter_events=["billing_limit_set"],
+ filter_cohorts=["Billing power users"],
+ ),
+ self._estimate_by_query(lambda query: bool(query.events)),
+ )
+
+ assert draft.query is not None
+ assert "events" not in draft.query
+ assert {"type": "cohort", "key": "id", "value": cohort.id, "operator": "in"} in draft.query["properties"]
+ assert any(p.get("key") == "visited_page" for p in draft.query["properties"])
+
+ def test_a_draft_with_no_pages_to_fall_back_to_is_left_alone(self):
+ # Widening to every session would scan a product the goal never asked about, which is worse
+ # than a filter the review page already refuses to save.
+ EventDefinition.objects.create(team=self.team, name="billing_limit_set", last_seen_at=timezone.now())
+
+ draft = self._drafted_with(
+ _draft_v2(filter_events=["billing_limit_set"]),
+ self._estimate_by_query(lambda query: True),
+ )
+
+ assert draft.query is not None
+ assert [e["id"] for e in draft.query["events"]] == ["billing_limit_set"]
+ assert draft.estimated_monthly_observations == 0
+
def test_solved_dials_reach_the_draft(self):
draft = self._run(pages=("/billing",), generate=_draft_v2(filter_pages=["/billing"]))