: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
fix(replay-vision): estimate from a sampled week instead of a full 30-day scan (#78108)
Tue Haulund075ad3c5003b
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.pyindex 18609307bf4f..51822b33b7ea 100644--- a/posthog/session_recordings/queries/session_recording_list_from_query.py+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py@@ -134,9 +134,13 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):session_ids_to_exclude: list[str] | None = None,bypass_date_window_for_session_ids: bool = False,user: User | None = None,+ events_sample_factor: float | None = None,**_,):self._user = user+ # Storage-level SAMPLE on any events subqueries; opt-in for estimates.+ self._events_sample_factor = events_sample_factor+ self.events_subqueries_sampled = Falseself._bypass_date_window_for_session_ids = bypass_date_window_for_session_ids# TRICKY: we need to make sure we init test account filters only once,# otherwise we'll end up with a lot of duplicated test account filters in the query@@ -372,7 +376,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):# if in PoE mode then we should be pushing person property queries into hereevents_sub_query_builder = ReplayFiltersEventsSubQuery(- self._team, self._query, self._allow_event_property_expansion+ self._team, self._query, self._allow_event_property_expansion, sample_factor=self._events_sample_factor)events_sub_queries = events_sub_query_builder.get_queries_for_session_id_matching()for events_sub_query in events_sub_queries:@@ -391,6 +395,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):# find the small set of sessions that MATCH the positive form, then exclude them.# This avoids scanning all event-sessions which can exceed the LIMIT on high-traffic teams.negative_blocklist = events_sub_query_builder.get_negative_blocklist_query()+ self.events_subqueries_sampled |= events_sub_query_builder.emitted_sampled_subqueryif negative_blocklist:exprs.append(ast.CompareOperation(@@ -469,7 +474,10 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):test_account_query.console_log_filters = Nonetest_account_events_builder = ReplayFiltersEventsSubQuery(- self._team, test_account_query, self._allow_event_property_expansion+ self._team,+ test_account_query,+ self._allow_event_property_expansion,+ sample_factor=self._events_sample_factor,)for sub_q in test_account_events_builder.get_queries_for_session_id_matching():exprs.append(@@ -478,6 +486,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):))test_account_negative_blocklist = test_account_events_builder.get_negative_blocklist_query()+ self.events_subqueries_sampled |= test_account_events_builder.emitted_sampled_subqueryif test_account_negative_blocklist:exprs.append(ast.CompareOperation(diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.pyindex 49888d456ff4..feeaf567529f 100644--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py@@ -84,10 +84,21 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):query: RecordingsQuery,allow_event_property_expansion: bool = False,hogql_query_modifiers: Optional[HogQLQueryModifiers] = None,+ sample_factor: Optional[float] = None,):super().__init__(team, query)self._hogql_query_modifiers = hogql_query_modifiersself._allow_event_property_expansion = allow_event_property_expansion+ self._sample_factor = sample_factor+ self.emitted_sampled_subquery = False++ def _events_join(self, sample: bool = True) -> ast.JoinExpr:+ join = ast.JoinExpr(table=ast.Field(chain=["events"]))+ # Only positive session-selectors sample; a sampled exclusion blocklist would under-exclude.+ if sample and self._sample_factor is not None:+ join.sample = ast.SampleExpr(sample_value=ast.RatioExpr(left=ast.Constant(value=self._sample_factor)))+ self.emitted_sampled_subquery = True+ return join@staticmethoddef _event_predicates(@@ -134,9 +145,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):return ast.SelectQuery(select=select_expr if isinstance(select_expr, list) else [select_expr],- select_from=ast.JoinExpr(- table=ast.Field(chain=["events"]),- ),+ select_from=self._events_join(),where=self._where_predicates(where_expr),having=self._having_predicates(),group_by=group_by,@@ -270,7 +279,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):return ast.SelectQuery(select=[ast.Alias(alias="session_id", expr=_event_session_id_field())],- select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ select_from=self._events_join(),where=ast.And(exprs=[ast.CompareOperation(@@ -730,7 +739,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):return ast.SelectQuery(select=[ast.Alias(alias="session_id", expr=_event_session_id_field())],- select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ select_from=self._events_join(sample=False),where=self._where_predicates(where_expr),group_by=[_event_session_id_field()],limit=ast.Constant(value=1000000),diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.pyindex d9d0c46c29b5..6f745c400db1 100644--- a/products/replay_vision/backend/max_tools.py+++ b/products/replay_vision/backend/max_tools.py@@ -10,6 +10,7 @@ from posthog.hogql import astfrom posthog.hogql.query import execute_hogql_queryfrom posthog.api.embedding_worker import async_generate_embedding+from posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.rbac.user_access_control import AccessControlLevelfrom posthog.scopes import APIScopeObject@@ -569,5 +570,11 @@ class SearchReplayVisionObservationsTool(MaxTool):LIMIT {{limit}}"""tag_queries(product=Product.REPLAY_VISION, feature=Feature.SEMANTIC_SEARCH)- result = execute_hogql_query(query=hogql_query, team=self._team, user=self._user, placeholders=placeholders)+ result = execute_hogql_query(+ query=hogql_query,+ team=self._team,+ user=self._user,+ placeholders=placeholders,+ ch_user=ClickHouseUser.REPLAY_VISION,+ )return [row[0] for row in (result.results or [])]diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.pyindex 096ea23e4137..3d39e81fa102 100644--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py@@ -3,7 +3,7 @@ from dataclasses import dataclassfrom django.utils import timezone-from posthog.schema import RecordingsQuery+from posthog.schema import FilterLogicalOperator, RecordingsQueryfrom posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings@@ -26,11 +26,15 @@ _ESTIMATE_MAX_EXECUTION_TIME_SECONDS = 30# Interactive saves get a tighter budget and fail soft; the batch refresher can afford the full cap.ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS = 10-# The estimate always projects a calendar month from a fixed 30-day lookback.+# The estimate always projects to a calendar month.ESTIMATE_WINDOW_DAYS = 30+# Scan a week and extrapolate: a 30-day scan of event-filtered queries reads billions of rows and blows the budget.+_ESTIMATE_SCAN_WINDOW_DAYS = 7+# Events subqueries additionally SAMPLE users at 10%; matched counts are corrected back up.+_ESTIMATE_EVENTS_SAMPLE_FACTOR = 0.1-# The earliest-recording probe scans at most this far back; anything older clamps the divisor to the full window.-_EARLIEST_PROBE_LOOKBACK_DAYS = 3 * ESTIMATE_WINDOW_DAYS+# The earliest-recording probe only needs to see past the scan window; anything older clamps identically.+_EARLIEST_PROBE_LOOKBACK_DAYS = _ESTIMATE_SCAN_WINDOW_DAYS + 1# Persisted per-scanner estimates older than this are recomputed by the sweep.ESTIMATE_STALE_AFTER = dt.timedelta(hours=24)@@ -39,7 +43,7 @@ ESTIMATE_STALE_AFTER = dt.timedelta(hours=24)@dataclass(frozen=True)class ScannerVolumeEstimate:matched_sessions: int- # May be smaller than ESTIMATE_WINDOW_DAYS when the team has fewer days of recordings.+ # May be smaller than the scan window when the team has fewer days of recordings.effective_window_days: int@@ -51,17 +55,18 @@ def estimate_scanner_session_volume(max_execution_seconds: int = _ESTIMATE_MAX_EXECUTION_TIME_SECONDS,ch_user: ClickHouseUser = ClickHouseUser.APP,) -> ScannerVolumeEstimate:- """Count sessions matching `query` over the last 30 days, for the scanner cost preview.+ """Count sessions matching `query` over the last week, for the scanner cost preview.- Reuses `SessionRecordingListFromQuery`'s filter compilation verbatim and wraps it in a- COUNT, so the estimate and the real recordings list agree on what "matches". The team's+ Reuses `SessionRecordingListFromQuery`'s filter compilation (with events subqueries sampled+ at 10% and corrected back up) wrapped in a COUNT, so the estimate and the real recordings+ list agree on what "matches"; `project_monthly_observations` extrapolates to 30 days. The team'searliest recent recording is fetched in the same round trip via a CROSS JOIN so thecost-preview widget never pays for two sequential HogQL queries."""now = dt.datetime.now(dt.UTC)- window_start = now - dt.timedelta(days=ESTIMATE_WINDOW_DAYS)+ window_start = now - dt.timedelta(days=_ESTIMATE_SCAN_WINDOW_DAYS)windowed = query.model_copy(deep=True)- # Exact timestamp — the relative "-30d" form truncates to start-of-day, counting up to 31 days against a /30 divisor.+ # Exact timestamp — the relative date form truncates to start-of-day, over-counting a day against the divisor.windowed.date_from = window_start.isoformat()windowed.date_to = None@@ -69,7 +74,16 @@ def estimate_scanner_session_volume(extra_having = eligibility_predicates()if (surfacing := surfacing_score_predicate(sampling_mode)) is not None:extra_having.append(surfacing)- inner = SessionRecordingListFromQuery(team=team, query=windowed, extra_having_predicates=extra_having).get_query()+ # Sampling is only sound when every match must pass the sampled events leg; under OR, sessions+ # matched via unsampled branches (persons, cohorts, console logs) would be multiplied by the correction.+ sample_factor = None if windowed.operand == FilterLogicalOperator.OR_ else _ESTIMATE_EVENTS_SAMPLE_FACTOR+ list_query = SessionRecordingListFromQuery(+ team=team,+ query=windowed,+ extra_having_predicates=extra_having,+ events_sample_factor=sample_factor,+ )+ inner = list_query.get_query()# The inner query groups by session_id, so one row is one session; order is irrelevant to a count.inner.order_by = None@@ -85,7 +99,7 @@ def estimate_scanner_session_volume()],select_from=ast.JoinExpr(table=ast.Field(chain=["raw_session_replay_events"])),- # Bounded so the probe partition-prunes; older data would clamp the divisor to the full window anyway.+ # Bounded so the probe partition-prunes; older data clamps the divisor to the scan window anyway.where=ast.CompareOperation(op=ast.CompareOperationOp.GtEq,left=ast.Field(chain=["min_first_timestamp"]),@@ -118,6 +132,8 @@ def estimate_scanner_session_volume()results = response.results or []matched = int(results[0][0]) if results else 0+ if list_query.events_subqueries_sampled:+ matched = round(matched / _ESTIMATE_EVENTS_SAMPLE_FACTOR)earliest = results[0][1] if results else Nonereturn ScannerVolumeEstimate(@@ -159,8 +175,9 @@ def refresh_scanner_estimate(def _clamp_window_days(earliest: object) -> int:"""Clamp the divisor to the team's actual data span so a new team isn't under-estimated."""if not isinstance(earliest, dt.datetime):- return ESTIMATE_WINDOW_DAYS+ # The probe covers the whole scan window, so no-earliest implies matched == 0 and any divisor projects 0.+ return _ESTIMATE_SCAN_WINDOW_DAYSif earliest.tzinfo is None:earliest = earliest.replace(tzinfo=dt.UTC)days_of_data = (dt.datetime.now(dt.UTC) - earliest).days + 1- return max(1, min(ESTIMATE_WINDOW_DAYS, days_of_data))+ return max(1, min(_ESTIMATE_SCAN_WINDOW_DAYS, days_of_data))diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 95ac451a897a..4537792d8259 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -2478,18 +2478,19 @@ class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):def test_estimate_counts_only_in_window_sessions(self) -> None:for index in range(3):self._ingest_session(days_ago=index + 1)- self._ingest_session(days_ago=40)+ # Inside the earliest probe but outside the 7-day scan window, clamping window_days to a deterministic 7.+ self._ingest_session(days_ago=7)resp = self.client.post(self.estimate_url, data={}, format="json")self.assertEqual(resp.status_code, 200)body = resp.json()self.assertEqual(body["matched_sessions_in_window"], 3)- self.assertEqual(body["window_days"], 30)- self.assertEqual(body["estimated_observations_per_month"], 3)+ self.assertEqual(body["window_days"], 7)+ self.assertEqual(body["estimated_observations_per_month"], round(3 / 7 * 30))# Defaults to gemini-3-flash-preview (5 credits) when the request names no model.self.assertEqual(body["credits_per_observation"], 5)- self.assertEqual(body["estimated_credits_per_month"], 15)+ self.assertEqual(body["estimated_credits_per_month"], round(3 / 7 * 30) * 5)def test_estimate_prices_credits_at_proposed_model(self) -> None:for index in range(3):@@ -2506,17 +2507,17 @@ class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):def test_estimate_applies_sampling(self) -> None:for index in range(4):self._ingest_session(days_ago=index + 1)- # Anchor 40 days back so `window_days` clamps to a deterministic 30, not the recent data span.- self._ingest_session(days_ago=40)+ # Inside the earliest probe but outside the 7-day scan window, clamping window_days to a deterministic 7.+ self._ingest_session(days_ago=7)resp = self.client.post(self.estimate_url, data={"sampling_rate": 0.5}, format="json")self.assertEqual(resp.status_code, 200)body = resp.json()self.assertEqual(body["matched_sessions_in_window"], 4)- self.assertEqual(body["window_days"], 30)+ self.assertEqual(body["window_days"], 7)self.assertEqual(body["sampling_rate"], 0.5)- self.assertEqual(body["estimated_observations_per_month"], 2)+ self.assertEqual(body["estimated_observations_per_month"], round(4 / 7 * 30 * 0.5))def test_estimate_others_sum_is_enabled_only_and_excludes_the_edited_scanner(self) -> None:self._ingest_session(days_ago=1)diff --git a/products/replay_vision/backend/tests/test_estimate_refresh.py b/products/replay_vision/backend/tests/test_estimate_refresh.pyindex 9a2242c3f610..c746cc5f6907 100644--- a/products/replay_vision/backend/tests/test_estimate_refresh.py+++ b/products/replay_vision/backend/tests/test_estimate_refresh.py@@ -10,7 +10,13 @@ from django.utils import timezonefrom parameterized import parameterizedfrom temporalio.exceptions import ApplicationError+from posthog.schema import FilterLogicalOperator, RecordingsQuery++from posthog.hogql.context import HogQLContext+from posthog.hogql.printer import prepare_and_print_ast+from posthog.models import Organization, Team+from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQueryfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerTypefrom products.replay_vision.backend.queries import (@@ -18,6 +24,10 @@ from products.replay_vision.backend.queries import (project_monthly_observations,refresh_scanner_estimate,)+from products.replay_vision.backend.queries.scanner_volume_estimate import (+ _ESTIMATE_EVENTS_SAMPLE_FACTOR,+ estimate_scanner_session_volume,+)from products.replay_vision.backend.temporal.activities.list_stale_scanner_estimates import (list_stale_scanner_estimates_activity,)@@ -62,10 +72,67 @@ def _set_estimate(scanner: ReplayScanner, value: int, hours_ago: float) -> None:)+ "recordings_query, expect_sampled",+ [+ (RecordingsQuery(events=[{"id": "$pageview", "type": "events", "name": "$pageview"}]), True),+ (RecordingsQuery(), False),+ # Negative filters build only the exclusion blocklist, which must never sample: it would under-exclude.+ (+ RecordingsQuery(+ properties=[{"type": "event", "key": "$host", "operator": "not_icontains", "value": "localhost"}]+ ),+ False,+ ),+ ],+)+def test_estimate_samples_only_positive_events_subqueries(+ recordings_query: RecordingsQuery, expect_sampled: bool+) -> None:+ scanner = _make_scanner()+ list_query = SessionRecordingListFromQuery(+ team=scanner.team, query=recordings_query, events_sample_factor=_ESTIMATE_EVENTS_SAMPLE_FACTOR+ )+ built = list_query.get_query()++ assert list_query.events_subqueries_sampled == expect_sampled+ sql = prepare_and_print_ast(built, HogQLContext(team_id=scanner.team.pk, enable_select_queries=True), "clickhouse")[+ 0+ ]+ assert (sql.count(f"SAMPLE {_ESTIMATE_EVENTS_SAMPLE_FACTOR}") > 0) == expect_sampled+++ "operand, expected_matched",+ [+ (FilterLogicalOperator.AND_, 50), # sampled leg gates every match, so the count is corrected up+ (FilterLogicalOperator.OR_, 5), # unsampled branches could match alone, so no sampling and no correction+ ],+)+def test_estimate_corrects_count_only_when_sampling_is_sound(+ operand: FilterLogicalOperator, expected_matched: int+) -> None:+ scanner = _make_scanner()+ query = RecordingsQuery(+ events=[{"id": "$pageview", "type": "events", "name": "$pageview"}],+ properties=[{"type": "person", "key": "email", "operator": "icontains", "value": "@"}],+ operand=operand,+ )+ with patch(+ "products.replay_vision.backend.queries.scanner_volume_estimate.execute_hogql_query",+ return_value=MagicMock(results=[[5, None]]),+ ):+ estimate = estimate_scanner_session_volume(team=scanner.team, query=query)+ assert estimate.matched_sessions == expected_matched++@pytest.mark.parametrize("matched, window_days, sampling_rate, expected",[(60, 30, 1.0, 60),+ (14, 7, 1.0, 60),(60, 30, 0.5, 30),(0, 30, 1.0, 0),(10, 1, 0.5, 150),diff --git a/products/replay_vision/backend/tests/test_scanner_candidate_query.py b/products/replay_vision/backend/tests/test_scanner_candidate_query.pyindex c7482b89cb36..b467994ec937 100644--- a/products/replay_vision/backend/tests/test_scanner_candidate_query.py+++ b/products/replay_vision/backend/tests/test_scanner_candidate_query.py@@ -22,8 +22,9 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (surfacing_score_predicate,)from products.replay_vision.backend.queries.scanner_volume_estimate import (- ESTIMATE_WINDOW_DAYS,+ _ESTIMATE_SCAN_WINDOW_DAYS,estimate_scanner_session_volume,+ project_monthly_observations,)_NOW = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)@@ -430,9 +431,9 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):assert estimate.matched_sessions == 1@pytest.mark.django_db- def test_volume_estimate_window_is_exactly_30_days(self, team) -> None:- # A relative "-30d" date_from truncates to start-of-day, counting up to 31 days against the /30 divisor.- bound = _NOW - dt.timedelta(days=ESTIMATE_WINDOW_DAYS)+ def test_volume_estimate_window_is_exactly_the_scan_window(self, team) -> None:+ # An exact-timestamp date_from keeps the boundary sharp: a relative form would truncate to start-of-day.+ bound = _NOW - dt.timedelta(days=_ESTIMATE_SCAN_WINDOW_DAYS)self._produce(team.id,"same-day-but-outside",@@ -453,15 +454,16 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):assert estimate.matched_sessions == 1@pytest.mark.django_db- def test_volume_estimate_divisor_stays_full_for_old_but_quiet_teams(self, team) -> None:- # The bounded earliest-recording probe must not shrink the divisor for teams older than the window.+ def test_volume_estimate_projects_zero_for_old_but_quiet_teams(self, team) -> None:+ # Recordings older than the probe fall back to the full scan-window divisor, which is inert: matched is 0.old = _NOW - dt.timedelta(days=40)self._produce(team.id, "old-session", old, old + dt.timedelta(seconds=60), active_milliseconds=30_000)estimate = estimate_scanner_session_volume(team=team, query=RecordingsQuery())assert estimate.matched_sessions == 0- assert estimate.effective_window_days == ESTIMATE_WINDOW_DAYS+ assert estimate.effective_window_days == _ESTIMATE_SCAN_WINDOW_DAYS+ assert project_monthly_observations(estimate, 1.0) == 0@pytest.mark.django_dbdef test_filter_test_accounts_excludes_internal_users(self, team) -> None: