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): incorrect projection in estimates (#81735)

Hayne Ryu55c8307a2592
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 9cb87a7ad0b1..fa43e4216d1c 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -613,6 +613,18 @@ class SessionEventDeltasSustainedRateThrottle(_TeamBucketRateThrottle):
rate = "100/hour"
+# The scanner volume estimate can run two ClickHouse queries per call, and its primary caller is
+# the session-authenticated editor, which the ClickHouse*RateThrottle pair does not cover.
+class ReplayVisionEstimateBurstRateThrottle(_TeamBucketRateThrottle):
+ scope = "replay_vision_estimate_burst"
+ rate = "20/minute"
+
+
+class ReplayVisionEstimateSustainedRateThrottle(_TeamBucketRateThrottle):
+ scope = "replay_vision_estimate_sustained"
+ rate = "200/hour"
+
+
class _AIThrottleBase(UserRateThrottle):
action_name: str
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 13a95c3eba59..6251cc795a15 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -30,6 +30,7 @@ from posthog.api.shared import UserBasicSerializer
from posthog.event_usage import report_user_action
from posthog.exceptions import QuotaLimitExceeded
from posthog.models.user import User
+from posthog.rate_limit import ReplayVisionEstimateBurstRateThrottle, ReplayVisionEstimateSustainedRateThrottle
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
@@ -1641,6 +1642,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
methods=["post"],
url_path="estimate",
required_scopes=["replay_scanner:read", "session_recording:read"],
+ throttle_classes=[ReplayVisionEstimateBurstRateThrottle, ReplayVisionEstimateSustainedRateThrottle],
)
def estimate(self, request: Request, **kwargs: Any) -> Response:
"""Estimate the observation volume a proposed scanner would generate, for the pre-save cost preview."""
diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.py
index 90a83f157bff..1ccefa32e81d 100644
--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py
+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py
@@ -11,6 +11,11 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.exceptions import (
+ ClickHouseEstimatedQueryExecutionTimeTooLong,
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseQueryTimeOut,
+)
from posthog.models import Team
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
@@ -22,8 +27,9 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
# The estimate always projects to a calendar month.
ESTIMATE_WINDOW_DAYS = 30
-# Events subqueries additionally SAMPLE users at 10%; matched counts are corrected back up.
+# Fallback sample rate for events subqueries; matched counts are corrected back up.
_ESTIMATE_EVENTS_SAMPLE_FACTOR = 0.1
+_EXACT_ATTEMPT_BUDGET_FRACTION = 0.5
@dataclass(frozen=True, kw_only=True)
@@ -67,6 +73,13 @@ class ScannerVolumeEstimate:
matched_sessions: int
# May be smaller than the scan window when the team has fewer days of recordings.
effective_window_days: int
+ sampled: bool = False
+
+
+@dataclass(frozen=True)
+class _EstimateQueryPlan:
+ combined_query: ast.SelectQuery
+ sampled: bool
def estimate_scanner_session_volume(
@@ -79,11 +92,10 @@ def estimate_scanner_session_volume(
) -> ScannerVolumeEstimate:
"""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
- list agree on what "matches"; `project_monthly_observations` extrapolates to 30 days. The team's
- 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.
+ Reuses `SessionRecordingListFromQuery`'s filter compilation so the estimate and the real
+ recordings list agree on what "matches". The exact count runs first; when it times out, is
+ rejected as too slow, or hits a memory limit, it retries with sampled events subqueries and
+ corrects the count back up (`sampled=True` on the result).
"""
# 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
@@ -99,13 +111,77 @@ def estimate_scanner_session_volume(
windowed.date_from = window_start.isoformat()
windowed.date_to = None
+ sampled_plan = _plan_estimate_query(
+ team=team,
+ query=windowed,
+ sampling_mode=sampling_mode,
+ sample_factor=sample_factor,
+ scan_window_days=scan_window_days,
+ now=now,
+ )
+
+ tag_queries(team_id=team.id, product=Product.REPLAY_VISION, feature=Feature.QUERY)
+ if not sampled_plan.sampled:
+ # Nothing was sampled, so a fallback would rerun the identical query.
+ return _execute_estimate_query(
+ sampled_plan,
+ team=team,
+ query_type="ReplayVisionScannerEstimateQuery",
+ max_execution_seconds=budget.max_execution_seconds,
+ scan_window_days=scan_window_days,
+ ch_user=ch_user,
+ )
+
+ exact_plan = _plan_estimate_query(
+ team=team,
+ query=windowed,
+ sampling_mode=sampling_mode,
+ sample_factor=None,
+ scan_window_days=scan_window_days,
+ now=now,
+ )
+ exact_budget = max(1, round(budget.max_execution_seconds * _EXACT_ATTEMPT_BUDGET_FRACTION))
+ try:
+ return _execute_estimate_query(
+ exact_plan,
+ team=team,
+ query_type="ReplayVisionScannerEstimateExactQuery",
+ max_execution_seconds=exact_budget,
+ scan_window_days=scan_window_days,
+ ch_user=ch_user,
+ )
+ except (
+ ClickHouseQueryTimeOut,
+ ClickHouseEstimatedQueryExecutionTimeTooLong,
+ ClickHouseQueryMemoryLimitExceeded,
+ ):
+ # Full budget: halving it fails teams whose sampled count needs more than half.
+ return _execute_estimate_query(
+ sampled_plan,
+ team=team,
+ query_type="ReplayVisionScannerEstimateSampledQuery",
+ max_execution_seconds=budget.max_execution_seconds,
+ scan_window_days=scan_window_days,
+ ch_user=ch_user,
+ )
+
+
+def _plan_estimate_query(
+ *,
+ team: Team,
+ query: RecordingsQuery,
+ sampling_mode: SamplingMode | str,
+ sample_factor: float | None,
+ scan_window_days: int,
+ now: dt.datetime,
+) -> _EstimateQueryPlan:
# Count only sessions the sweep would actually observe, so the forecast matches the eligible set the candidate query selects.
extra_having = eligibility_predicates()
if (surfacing := surfacing_score_predicate(sampling_mode)) is not None:
extra_having.append(surfacing)
list_query = SessionRecordingListFromQuery(
team=team,
- query=windowed,
+ query=query,
extra_having_predicates=extra_having,
events_sample_factor=sample_factor,
)
@@ -147,24 +223,36 @@ def estimate_scanner_session_volume(
),
),
)
+ return _EstimateQueryPlan(combined_query=combined_query, sampled=list_query.events_subqueries_sampled)
- tag_queries(team_id=team.id, product=Product.REPLAY_VISION, feature=Feature.QUERY)
+
+def _execute_estimate_query(
+ plan: _EstimateQueryPlan,
+ *,
+ team: Team,
+ query_type: str,
+ max_execution_seconds: int,
+ scan_window_days: int,
+ ch_user: ClickHouseUser,
+) -> ScannerVolumeEstimate:
response = execute_hogql_query(
- query=combined_query,
+ query=plan.combined_query,
team=team,
- query_type="ReplayVisionScannerEstimateQuery",
- settings=HogQLGlobalSettings(max_execution_time=budget.max_execution_seconds),
+ query_type=query_type,
+ # "throw" so a timeout raises instead of returning a partial count as exact.
+ settings=HogQLGlobalSettings(max_execution_time=max_execution_seconds, timeout_overflow_mode="throw"),
ch_user=ch_user,
)
results = response.results or []
matched = int(results[0][0]) if results else 0
- if list_query.events_subqueries_sampled:
+ if plan.sampled:
matched = round(matched / _ESTIMATE_EVENTS_SAMPLE_FACTOR)
earliest = results[0][1] if results else None
return ScannerVolumeEstimate(
matched_sessions=matched,
effective_window_days=_clamp_window_days(earliest, scan_window_days),
+ sampled=plan.sampled,
)
diff --git a/products/replay_vision/backend/tests/test_estimate_refresh.py b/products/replay_vision/backend/tests/test_estimate_refresh.py
index c746cc5f6907..baa7b151a88b 100644
--- a/products/replay_vision/backend/tests/test_estimate_refresh.py
+++ b/products/replay_vision/backend/tests/test_estimate_refresh.py
@@ -15,6 +15,7 @@ from posthog.schema import FilterLogicalOperator, RecordingsQuery
from posthog.hogql.context import HogQLContext
from posthog.hogql.printer import prepare_and_print_ast
+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
from posthog.models import Organization, Team
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
@@ -103,29 +104,70 @@ def test_estimate_samples_only_positive_events_subqueries(
assert (sql.count(f"SAMPLE {_ESTIMATE_EVENTS_SAMPLE_FACTOR}") > 0) == expect_sampled
+_EVENT_FILTERED_AND_QUERY = RecordingsQuery(
+ events=[{"id": "$pageview", "type": "events", "name": "$pageview"}],
+ properties=[{"type": "person", "key": "email", "operator": "icontains", "value": "@"}],
+ operand=FilterLogicalOperator.AND_,
+)
+
+
@pytest.mark.django_db
@pytest.mark.parametrize(
- "operand, expected_matched",
+ "execute_outcomes, expected_matched, expected_sampled, expected_budgets",
[
- (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
+ ([MagicMock(results=[[5, None]])], 5, False, [15]),
+ ([ClickHouseQueryTimeOut(), MagicMock(results=[[5, None]])], 50, True, [15, 30]),
+ ([ClickHouseQueryMemoryLimitExceeded(), MagicMock(results=[[5, None]])], 50, True, [15, 30]),
],
)
-def test_estimate_corrects_count_only_when_sampling_is_sound(
- operand: FilterLogicalOperator, expected_matched: int
+def test_estimate_falls_back_to_sampling_only_when_the_exact_count_times_out(
+ execute_outcomes: list[Any], expected_matched: int, expected_sampled: bool, expected_budgets: list[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)
+ side_effect=execute_outcomes,
+ ) as mock_execute:
+ estimate = estimate_scanner_session_volume(team=scanner.team, query=_EVENT_FILTERED_AND_QUERY)
assert estimate.matched_sessions == expected_matched
+ assert estimate.sampled == expected_sampled
+ settings = [call.kwargs["settings"] for call in mock_execute.call_args_list]
+ assert [s.max_execution_time for s in settings] == expected_budgets
+ assert all(s.timeout_overflow_mode == "throw" for s in settings)
+ query_types = [call.kwargs["query_type"] for call in mock_execute.call_args_list]
+ assert query_types == (
+ ["ReplayVisionScannerEstimateExactQuery", "ReplayVisionScannerEstimateSampledQuery"]
+ if expected_sampled
+ else ["ReplayVisionScannerEstimateExactQuery"]
+ )
+
+
+ "recordings_query, error",
+ [
+ (
+ RecordingsQuery(
+ events=[{"id": "$pageview", "type": "events", "name": "$pageview"}],
+ properties=[{"type": "person", "key": "email", "operator": "icontains", "value": "@"}],
+ operand=FilterLogicalOperator.OR_,
+ ),
+ ClickHouseQueryTimeOut(),
+ ),
+ (RecordingsQuery(), ClickHouseQueryTimeOut()),
+ ],
+)
+def test_estimate_propagates_errors_when_a_retry_would_not_help(
+ recordings_query: RecordingsQuery, error: Exception
+) -> None:
+ scanner = _make_scanner()
+ with patch(
+ "products.replay_vision.backend.queries.scanner_volume_estimate.execute_hogql_query",
+ side_effect=error,
+ ) as mock_execute:
+ with pytest.raises(type(error)):
+ estimate_scanner_session_volume(team=scanner.team, query=recordings_query)
+ assert mock_execute.call_count == 1
@pytest.mark.parametrize(