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.

fix(replay-vision): cheaper unsampled estimate previews (#81726)

Tue Haulundd11ad40a036a
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 382311667f6e..8d6907badf85 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -68,9 +68,10 @@ from products.replay_vision.backend.models.replay_scanner import (
ScannerType,
)
from products.replay_vision.backend.queries import (
- ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS,
ESTIMATE_STALE_AFTER,
MIN_SAMPLING_RATE,
+ PREVIEW_ESTIMATE_BUDGET,
+ SAVE_ESTIMATE_BUDGET,
estimate_scanner_session_volume,
project_monthly_observations,
refresh_scanner_estimate,
@@ -140,7 +141,7 @@ def _scanner_lifecycle_properties(scanner: ReplayScanner) -> dict[str, Any]:
def _refresh_estimate_fail_soft(scanner: ReplayScanner) -> None:
# The estimate is advisory — never fail a scanner save over it, and keep the save's latency tail short.
try:
- refresh_scanner_estimate(scanner, max_execution_seconds=ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS)
+ refresh_scanner_estimate(scanner, budget=SAVE_ESTIMATE_BUDGET)
except Exception:
logger.exception("replay_vision.estimate_refresh_failed", scanner_id=str(scanner.id))
@@ -1628,7 +1629,10 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
recordings_query = RecordingsQuery.model_validate(query_dict)
estimate = estimate_scanner_session_volume(
- team=self.team, query=recordings_query, sampling_mode=body.validated_data["sampling_mode"]
+ team=self.team,
+ query=recordings_query,
+ sampling_mode=body.validated_data["sampling_mode"],
+ budget=PREVIEW_ESTIMATE_BUDGET,
)
observations_per_month = project_monthly_observations(estimate, sampling_rate)
credits_per_observation = observation_credits_for_model(body.validated_data["model"])
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.py
index 9779f409844c..5d336e18f7b0 100644
--- a/products/replay_vision/backend/max_tools.py
+++ b/products/replay_vision/backend/max_tools.py
@@ -43,6 +43,7 @@ from products.replay_vision.backend.models.vision_action import ActionMode, Visi
from products.replay_vision.backend.observation_formatting import EVENT_ID_CITATION_RE, format_line, read_output
from products.replay_vision.backend.queries.scanner_volume_estimate import (
ESTIMATE_STALE_AFTER,
+ PREVIEW_ESTIMATE_BUDGET,
estimate_scanner_session_volume,
project_monthly_observations,
)
@@ -1701,6 +1702,7 @@ class EstimateReplayVisionScannerTool(ReplayVisionGatesMixin, MaxTool):
query=scanner.recordings_query(),
sampling_mode=scanner.sampling_mode,
ch_user=ClickHouseUser.REPLAY_VISION,
+ budget=PREVIEW_ESTIMATE_BUDGET,
)
except Exception:
logger.exception("replay_vision.max_tools.estimate_failed", scanner_id=scanner_id)
diff --git a/products/replay_vision/backend/queries/__init__.py b/products/replay_vision/backend/queries/__init__.py
index ff787bc329b6..89c1d0fa4c07 100644
--- a/products/replay_vision/backend/queries/__init__.py
+++ b/products/replay_vision/backend/queries/__init__.py
@@ -8,8 +8,9 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
ScannerCandidateQuery,
)
from products.replay_vision.backend.queries.scanner_volume_estimate import (
- ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS,
ESTIMATE_STALE_AFTER,
+ PREVIEW_ESTIMATE_BUDGET,
+ SAVE_ESTIMATE_BUDGET,
ScannerVolumeEstimate,
estimate_scanner_session_volume,
project_monthly_observations,
@@ -19,7 +20,8 @@ from products.replay_vision.backend.queries.scanner_volume_estimate import (
__all__ = [
"DEFAULT_CANDIDATE_LIMIT",
"DEFAULT_MAX_EXECUTION_SECONDS",
- "ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS",
+ "PREVIEW_ESTIMATE_BUDGET",
+ "SAVE_ESTIMATE_BUDGET",
"ESTIMATE_STALE_AFTER",
"MIN_SAMPLING_RATE",
"SAMPLE_RATE_PRECISION",
diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.py
index 3d39e81fa102..90a83f157bff 100644
--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py
+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py
@@ -20,21 +20,43 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
surfacing_score_predicate,
)
-# A pathological filter must not be able to hang the estimate request.
-_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 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 only needs to see past the scan window; anything older clamps identically.
-_EARLIEST_PROBE_LOOKBACK_DAYS = _ESTIMATE_SCAN_WINDOW_DAYS + 1
+
+@dataclass(frozen=True, kw_only=True)
+class EstimateBudget:
+ """What a single estimate may spend. Keyword-only because the fields are plain counts, so
+ positional arguments would let a call site swap them without any type error.
+
+ Only windows that are whole weeks are safe to persist. A shorter one inherits whichever weekdays
+ it happened to land on, which biases the monthly projection instead of merely adding noise.
+ """
+
+ # A pathological filter must not be able to hang the caller.
+ max_execution_seconds: int
+ # Scanning a slice and extrapolating: a 30-day scan of event-filtered queries reads billions of rows.
+ scan_window_days: int
+ # Used when the operand rules out sampling, which makes the scan full price. None keeps one window
+ # for both cases, which is what any estimate that gets persisted needs.
+ unsampled_scan_window_days: int | None = None
+
+ def window_days(self, *, unsampled: bool) -> int:
+ if unsampled and self.unsampled_scan_window_days is not None:
+ return self.unsampled_scan_window_days
+ return self.scan_window_days
+
+
+# The refresher recomputes at most daily per scanner, so it can afford the full window.
+BATCH_ESTIMATE_BUDGET = EstimateBudget(max_execution_seconds=30, scan_window_days=7)
+# A save blocks the request, so it gets a tighter clock and fails soft. It still writes the persisted
+# number, so the window stays a whole week.
+SAVE_ESTIMATE_BUDGET = EstimateBudget(max_execution_seconds=10, scan_window_days=7)
+# The editor's cost preview and Max both re-estimate freely and neither result is persisted, so where
+# sampling is unavailable they take an order-of-magnitude answer from a shorter window.
+PREVIEW_ESTIMATE_BUDGET = EstimateBudget(max_execution_seconds=10, scan_window_days=7, unsampled_scan_window_days=2)
# Persisted per-scanner estimates older than this are recomputed by the sweep.
ESTIMATE_STALE_AFTER = dt.timedelta(hours=24)
@@ -52,10 +74,10 @@ def estimate_scanner_session_volume(
team: Team,
query: RecordingsQuery,
sampling_mode: SamplingMode | str = SamplingMode.COMPREHENSIVE,
- max_execution_seconds: int = _ESTIMATE_MAX_EXECUTION_TIME_SECONDS,
ch_user: ClickHouseUser = ClickHouseUser.APP,
+ budget: EstimateBudget = BATCH_ESTIMATE_BUDGET,
) -> ScannerVolumeEstimate:
- """Count sessions matching `query` over the last week, for the scanner cost preview.
+ """Count sessions matching `query` over a recent window, for the scanner cost preview.
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
@@ -63,8 +85,15 @@ def estimate_scanner_session_volume(
earliest recent recording is fetched in the same round trip via a CROSS JOIN so the
cost-preview widget never pays for two sequential HogQL queries.
"""
+ # 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. Without sampling the scan is full price, so bound its window instead.
+ unsampled = query.operand == FilterLogicalOperator.OR_
+ sample_factor = None if unsampled else _ESTIMATE_EVENTS_SAMPLE_FACTOR
+ scan_window_days = budget.window_days(unsampled=unsampled)
+
now = dt.datetime.now(dt.UTC)
- window_start = now - dt.timedelta(days=_ESTIMATE_SCAN_WINDOW_DAYS)
+ window_start = now - dt.timedelta(days=scan_window_days)
windowed = query.model_copy(deep=True)
# Exact timestamp — the relative date form truncates to start-of-day, over-counting a day against the divisor.
windowed.date_from = window_start.isoformat()
@@ -74,9 +103,6 @@ def estimate_scanner_session_volume(
extra_having = eligibility_predicates()
if (surfacing := surfacing_score_predicate(sampling_mode)) is not None:
extra_having.append(surfacing)
- # 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,
@@ -103,7 +129,7 @@ def estimate_scanner_session_volume(
where=ast.CompareOperation(
op=ast.CompareOperationOp.GtEq,
left=ast.Field(chain=["min_first_timestamp"]),
- right=ast.Constant(value=now - dt.timedelta(days=_EARLIEST_PROBE_LOOKBACK_DAYS)),
+ right=ast.Constant(value=now - dt.timedelta(days=scan_window_days + 1)),
),
)
combined_query = ast.SelectQuery(
@@ -127,7 +153,7 @@ def estimate_scanner_session_volume(
query=combined_query,
team=team,
query_type="ReplayVisionScannerEstimateQuery",
- settings=HogQLGlobalSettings(max_execution_time=max_execution_seconds),
+ settings=HogQLGlobalSettings(max_execution_time=budget.max_execution_seconds),
ch_user=ch_user,
)
results = response.results or []
@@ -138,7 +164,7 @@ def estimate_scanner_session_volume(
return ScannerVolumeEstimate(
matched_sessions=matched,
- effective_window_days=_clamp_window_days(earliest),
+ effective_window_days=_clamp_window_days(earliest, scan_window_days),
)
@@ -150,7 +176,7 @@ def project_monthly_observations(estimate: ScannerVolumeEstimate, sampling_rate:
def refresh_scanner_estimate(
scanner: ReplayScanner,
*,
- max_execution_seconds: int = _ESTIMATE_MAX_EXECUTION_TIME_SECONDS,
+ budget: EstimateBudget = BATCH_ESTIMATE_BUDGET,
ch_user: ClickHouseUser = ClickHouseUser.APP,
) -> None:
"""Recompute and persist the scanner's projected monthly volume. Raises on failure; callers decide severity."""
@@ -158,7 +184,7 @@ def refresh_scanner_estimate(
team=scanner.team,
query=scanner.recordings_query(),
sampling_mode=scanner.sampling_mode,
- max_execution_seconds=max_execution_seconds,
+ budget=budget,
ch_user=ch_user,
)
projection = project_monthly_observations(estimate, scanner.sampling_rate)
@@ -172,12 +198,12 @@ def refresh_scanner_estimate(
scanner.estimated_at = estimated_at
-def _clamp_window_days(earliest: object) -> int:
+def _clamp_window_days(earliest: object, scan_window_days: int) -> 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):
# The probe covers the whole scan window, so no-earliest implies matched == 0 and any divisor projects 0.
- return _ESTIMATE_SCAN_WINDOW_DAYS
+ return scan_window_days
if 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_SCAN_WINDOW_DAYS, days_of_data))
+ return max(1, min(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.py
index 605333d98aba..3054ae67173a 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -34,6 +34,7 @@ from products.replay_vision.backend.models.replay_scanner import (
)
from products.replay_vision.backend.models.replay_scanner_backfill import ReplayScannerBackfill
from products.replay_vision.backend.models.vision_action import VisionAction
+from products.replay_vision.backend.queries import SAVE_ESTIMATE_BUDGET
from products.replay_vision.backend.queries.scanner_candidate_query import SETTLE_INTERVAL
from products.replay_vision.backend.quota import BillingPeriod, _current_period_bounds
from products.replay_vision.backend.temporal.constants import (
@@ -904,6 +905,9 @@ class TestScannerEstimatePersistence(_VisionAPITestCase):
self.assertEqual(resp.status_code, 201, resp.json())
self.mock_refresh_estimate.assert_called_once()
self.assertEqual(str(self.mock_refresh_estimate.call_args.args[0].id), resp.json()["id"])
+ # A save blocks the request, so it takes the tighter clock, and it persists the number, so it
+ # keeps the full week.
+ self.assertEqual(self.mock_refresh_estimate.call_args.kwargs["budget"], SAVE_ESTIMATE_BUDGET)
def test_create_succeeds_when_estimate_refresh_fails(self) -> None:
self.mock_refresh_estimate.side_effect = RuntimeError("clickhouse down")
diff --git a/products/replay_vision/backend/tests/test_scanner_candidate_query.py b/products/replay_vision/backend/tests/test_scanner_candidate_query.py
index 3131f9283f21..960cea9b0cdb 100644
--- a/products/replay_vision/backend/tests/test_scanner_candidate_query.py
+++ b/products/replay_vision/backend/tests/test_scanner_candidate_query.py
@@ -4,7 +4,13 @@ import pytest
from freezegun import freeze_time
from posthog.test.base import ClickhouseTestMixin, _create_event
-from posthog.schema import EventPropertyFilter, PropertyOperator, RecordingPropertyFilter, RecordingsQuery
+from posthog.schema import (
+ EventPropertyFilter,
+ FilterLogicalOperator,
+ PropertyOperator,
+ RecordingPropertyFilter,
+ RecordingsQuery,
+)
from posthog.hogql import ast
@@ -24,7 +30,8 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
surfacing_score_predicate,
)
from products.replay_vision.backend.queries.scanner_volume_estimate import (
- _ESTIMATE_SCAN_WINDOW_DAYS,
+ BATCH_ESTIMATE_BUDGET,
+ PREVIEW_ESTIMATE_BUDGET,
estimate_scanner_session_volume,
project_monthly_observations,
)
@@ -435,7 +442,7 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
@pytest.mark.django_db
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)
+ bound = _NOW - dt.timedelta(days=BATCH_ESTIMATE_BUDGET.scan_window_days)
self._produce(
team.id,
"same-day-but-outside",
@@ -455,6 +462,31 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
assert estimate.matched_sessions == 1
+ @pytest.mark.django_db
+ def test_unsampled_estimate_window_narrows_only_for_previews(self, team) -> None:
+ # An OR operand rules out the events SAMPLE, so a preview scans a shorter window instead of
+ # paying full price. A persisted estimate keeps the whole week, because a partial week
+ # inherits whichever weekdays it covered and biases the monthly projection.
+ first = _NOW - dt.timedelta(days=3)
+ self._produce(team.id, "older-match", first, first + dt.timedelta(minutes=10))
+ _create_event(
+ team=team,
+ event="$pageview",
+ distinct_id="d1",
+ timestamp=first,
+ properties={"$session_id": "older-match"},
+ )
+ query = RecordingsQuery(
+ operand=FilterLogicalOperator.OR_,
+ events=[{"id": "$pageview", "type": "events", "order": 0, "name": "$pageview"}],
+ )
+
+ preview = estimate_scanner_session_volume(team=team, query=query, budget=PREVIEW_ESTIMATE_BUDGET)
+ batch = estimate_scanner_session_volume(team=team, query=query, budget=BATCH_ESTIMATE_BUDGET)
+
+ assert preview.matched_sessions == 0
+ assert batch.matched_sessions == 1
+
@pytest.mark.django_db
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.
@@ -464,7 +496,7 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
estimate = estimate_scanner_session_volume(team=team, query=RecordingsQuery())
assert estimate.matched_sessions == 0
- assert estimate.effective_window_days == _ESTIMATE_SCAN_WINDOW_DAYS
+ assert estimate.effective_window_days == BATCH_ESTIMATE_BUDGET.scan_window_days
assert project_monthly_observations(estimate, 1.0) == 0
@pytest.mark.django_db