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): add API for estimating usage cost for replay vision (#59246)

Hayne Ryubfa79f42a338
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index e74b05d895eb..c88b4b21a5f7 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -34,6 +34,7 @@ from products.replay_vision.backend.models.replay_scanner import (
ScannerProvider,
ScannerType,
)
+from products.replay_vision.backend.queries import estimate_scanner_session_volume
from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_WORKFLOW_NAME,
MAX_SESSION_ID_LENGTH,
@@ -263,6 +264,54 @@ class ObserveResponseSerializer(serializers.Serializer):
)
+class EstimateRequestSerializer(serializers.Serializer):
+ """Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config."""
+
+ query = extend_schema_field(RecordingsQuery)( # type: ignore[arg-type, type-var]
+ serializers.JSONField(
+ required=False,
+ help_text=(
+ "Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are "
+ "ignored — the estimate always uses a fixed 30-day lookback. Omit to estimate "
+ "against all recordings."
+ ),
+ )
+ )
+ sampling_rate = serializers.FloatField(
+ required=False,
+ default=1.0,
+ min_value=0.0,
+ max_value=1.0,
+ help_text="0..1 downsample applied to matched sessions. Defaults to 1.0 (no downsampling).",
+ )
+
+ def validate_query(self, value: dict[str, Any]) -> dict[str, Any]:
+ try:
+ RecordingsQuery.model_validate(value)
+ except PydanticValidationError as exc:
+ raise serializers.ValidationError(str(exc))
+ return {k: v for k, v in value.items() if k not in _QUERY_FIELDS_TO_STRIP}
+
+
+class EstimateResponseSerializer(serializers.Serializer):
+ """Forward-looking observation-volume estimate for a proposed scanner. Pricing-agnostic."""
+
+ matched_sessions_in_window = serializers.IntegerField(
+ help_text="Distinct sessions matching the query within the 30-day lookback, before sampling.",
+ )
+ window_days = serializers.IntegerField(
+ help_text=(
+ "Lookback window the estimate is based on. Normally 30; smaller when the team has fewer days of recordings."
+ ),
+ )
+ estimated_observations_per_month = serializers.IntegerField(
+ help_text="Projected monthly observations: matched sessions scaled to 30 days, times sampling_rate.",
+ )
+ sampling_rate = serializers.FloatField(
+ help_text="Sampling rate applied to the projection. Echoed from the request.",
+ )
+
+
@extend_schema(tags=[VISION_TAG])
class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"""CRUD for Replay Vision scanners."""
@@ -338,3 +387,44 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
ObserveResponseSerializer({"workflow_id": workflow_id}).data,
status=status.HTTP_202_ACCEPTED,
)
+
+ @extend_schema(
+ request=EstimateRequestSerializer,
+ responses={200: EstimateResponseSerializer},
+ )
+ @action(
+ detail=False,
+ methods=["post"],
+ url_path="estimate",
+ required_scopes=["replay_scanner:read", "session_recording:read"],
+ )
+ def estimate(self, request: Request, **kwargs: Any) -> Response:
+ """Estimate the observation volume a proposed scanner would generate, for the pre-save cost preview."""
+ # The query runs over recording data, so a probed filter can leak recording metadata
+ # (URLs, events, person properties, console logs); gate on session_recording read.
+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
+ raise PermissionDenied("Estimating scanner volume requires session_recording read access.")
+
+ body = EstimateRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ sampling_rate: float = body.validated_data["sampling_rate"]
+
+ # validate_query already validated this; the empty-dict default needs `kind` to parse.
+ query_dict: dict[str, Any] = dict(body.validated_data.get("query") or {})
+ query_dict.setdefault("kind", "RecordingsQuery")
+ recordings_query = RecordingsQuery.model_validate(query_dict)
+
+ estimate = estimate_scanner_session_volume(team=self.team, query=recordings_query)
+ sessions_per_day = estimate.matched_sessions / estimate.effective_window_days
+ observations_per_month = round(sessions_per_day * 30 * sampling_rate)
+
+ return Response(
+ EstimateResponseSerializer(
+ {
+ "matched_sessions_in_window": estimate.matched_sessions,
+ "window_days": estimate.effective_window_days,
+ "estimated_observations_per_month": observations_per_month,
+ "sampling_rate": sampling_rate,
+ }
+ ).data
+ )
diff --git a/products/replay_vision/backend/queries/__init__.py b/products/replay_vision/backend/queries/__init__.py
new file mode 100644
index 000000000000..5534d114563f
--- /dev/null
+++ b/products/replay_vision/backend/queries/__init__.py
@@ -0,0 +1,6 @@
+from products.replay_vision.backend.queries.scanner_volume_estimate import (
+ ScannerVolumeEstimate,
+ estimate_scanner_session_volume,
+)
+
+__all__ = ["ScannerVolumeEstimate", "estimate_scanner_session_volume"]
diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.py
new file mode 100644
index 000000000000..79429ba122d2
--- /dev/null
+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py
@@ -0,0 +1,95 @@
+import datetime as dt
+from dataclasses import dataclass
+
+from posthog.schema import RecordingsQuery
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.models import Team
+from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
+
+# A pathological filter must not be able to hang the estimate request.
+_ESTIMATE_MAX_EXECUTION_TIME_SECONDS = 30
+
+# The estimate always projects a calendar month from a fixed 30-day lookback.
+ESTIMATE_WINDOW_DAYS = 30
+
+
+@dataclass(frozen=True)
+class ScannerVolumeEstimate:
+ matched_sessions: int
+ # May be smaller than ESTIMATE_WINDOW_DAYS when the team has fewer days of recordings.
+ effective_window_days: int
+
+
+def estimate_scanner_session_volume(*, team: Team, query: RecordingsQuery) -> ScannerVolumeEstimate:
+ """Count sessions matching `query` over the last 30 days, 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
+ earliest recording is fetched in the same round trip via a CROSS JOIN so the cost-preview
+ widget never pays for two sequential HogQL queries.
+ """
+ windowed = query.model_copy(deep=True)
+ windowed.date_from = f"-{ESTIMATE_WINDOW_DAYS}d"
+ windowed.date_to = None
+
+ inner = SessionRecordingListFromQuery(team=team, query=windowed).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
+
+ matched_subquery = ast.SelectQuery(
+ select=[ast.Alias(alias="matched", expr=ast.Call(name="count", args=[]))],
+ select_from=ast.JoinExpr(table=inner, alias="_matched"),
+ )
+ earliest_subquery = ast.SelectQuery(
+ select=[
+ ast.Alias(
+ alias="earliest",
+ expr=ast.Call(name="min", args=[ast.Field(chain=["min_first_timestamp"])]),
+ )
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["raw_session_replay_events"])),
+ )
+ combined_query = ast.SelectQuery(
+ select=[
+ ast.Field(chain=["m", "matched"]),
+ ast.Field(chain=["e", "earliest"]),
+ ],
+ select_from=ast.JoinExpr(
+ table=matched_subquery,
+ alias="m",
+ next_join=ast.JoinExpr(
+ join_type="CROSS JOIN",
+ table=earliest_subquery,
+ alias="e",
+ ),
+ ),
+ )
+
+ response = execute_hogql_query(
+ query=combined_query,
+ team=team,
+ query_type="ReplayVisionScannerEstimateQuery",
+ settings=HogQLGlobalSettings(max_execution_time=_ESTIMATE_MAX_EXECUTION_TIME_SECONDS),
+ )
+ results = response.results or []
+ matched = int(results[0][0]) if results else 0
+ earliest = results[0][1] if results else None
+
+ return ScannerVolumeEstimate(
+ matched_sessions=matched,
+ effective_window_days=_clamp_window_days(earliest),
+ )
+
+
+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
+ 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_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 b29e07efd434..815fcc1b884e 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -1,7 +1,7 @@
from datetime import timedelta
from typing import Any
-from posthog.test.base import APIBaseTest
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
from django.utils import timezone
@@ -10,6 +10,8 @@ from parameterized import parameterized
from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.models import Organization, Team
+from posthog.models.utils import uuid7
+from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
@@ -351,6 +353,11 @@ class TestReplayScannerViewSetFeatureFlag(APIBaseTest):
resp = self.client.post(self.scanners_url, data={"name": "x"}, format="json")
self.assertEqual(resp.status_code, 404)
+ @patch("products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled", return_value=False)
+ def test_flag_off_returns_404_on_estimate(self, _flag_mock) -> None:
+ resp = self.client.post(f"{self.scanners_url}estimate/", data={}, format="json")
+ self.assertEqual(resp.status_code, 404)
+
class TestReplayObservationViewSet(_VisionAPITestCase):
def setUp(self) -> None:
@@ -702,3 +709,58 @@ class TestSessionReplayObservationViewSet(_VisionAPITestCase):
resp = self.client.get(f"{self.session_observations_url}{observation.id}/")
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.json()["id"], str(observation.id))
+
+
+class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):
+ @property
+ def estimate_url(self) -> str:
+ return f"{self.scanners_url}estimate/"
+
+ def _ingest_session(self, *, days_ago: float) -> None:
+ # HogQL skips non-UUIDv7 `$session_id` values, so the estimate query would return 0 for them.
+ first_timestamp = timezone.now() - timedelta(days=days_ago)
+ produce_replay_summary(
+ team_id=self.team.pk,
+ session_id=str(uuid7()),
+ distinct_id="estimate-distinct-id",
+ first_timestamp=first_timestamp,
+ last_timestamp=first_timestamp + timedelta(minutes=5),
+ )
+
+ @parameterized.expand(
+ [
+ ("sampling_rate_above_one", {"sampling_rate": 1.5}),
+ ("sampling_rate_negative", {"sampling_rate": -0.1}),
+ ]
+ )
+ def test_estimate_rejects_invalid_input(self, _name: str, payload: dict[str, Any]) -> None:
+ resp = self.client.post(self.estimate_url, data=payload, format="json")
+ self.assertEqual(resp.status_code, 400)
+
+ 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)
+
+ 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)
+
+ 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)
+
+ 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["sampling_rate"], 0.5)
+ self.assertEqual(body["estimated_observations_per_month"], 2)
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index d8cb4192905b..56d082be5444 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -348,6 +348,34 @@ export interface ObserveResponseApi {
workflow_id: string
}
+/**
+ * Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.
+ */
+export interface EstimateRequestApi {
+ /** Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are ignored — the estimate always uses a fixed 30-day lookback. Omit to estimate against all recordings. */
+ query?: unknown
+ /**
+ * 0..1 downsample applied to matched sessions. Defaults to 1.0 (no downsampling).
+ * @minimum 0
+ * @maximum 1
+ */
+ sampling_rate?: number
+}
+
+/**
+ * Forward-looking observation-volume estimate for a proposed scanner. Pricing-agnostic.
+ */
+export interface EstimateResponseApi {
+ /** Distinct sessions matching the query within the 30-day lookback, before sampling. */
+ matched_sessions_in_window: number
+ /** Lookback window the estimate is based on. Normally 30; smaller when the team has fewer days of recordings. */
+ window_days: number
+ /** Projected monthly observations: matched sessions scaled to 30 days, times sampling_rate. */
+ estimated_observations_per_month: number
+ /** Sampling rate applied to the projection. Echoed from the request. */
+ sampling_rate: number
+}
+
export type VisionObservationsListParams = {
/**
* Number of results to return per page.
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index 6435f9625ab6..a204f0b7b0f0 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -9,6 +9,8 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ EstimateRequestApi,
+ EstimateResponseApi,
ObserveRequestApi,
ObserveResponseApi,
PaginatedReplayObservationListApi,
@@ -266,3 +268,23 @@ export const visionScannersObservationsRetrieve = async (
method: 'GET',
})
}
+
+export const getVisionScannersEstimateCreateUrl = (projectId: string) => {
+ return `/api/environments/${projectId}/vision/scanners/estimate/`
+}
+
+/**
+ * Estimate the observation volume a proposed scanner would generate, for the pre-save cost preview.
+ */
+export const visionScannersEstimateCreate = async (
+ projectId: string,
+ estimateRequestApi?: EstimateRequestApi,
+ options?: RequestInit
+): Promise<EstimateResponseApi> => {
+ return apiMutator<EstimateResponseApi>(getVisionScannersEstimateCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(estimateRequestApi),
+ })
+}
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index 978f39f14d9f..3485eff9a6c5 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -154,3 +154,27 @@ export const VisionScannersObserveCreateBody = /* @__PURE__ */ zod
.describe('ID of the session recording to apply the scanner to.'),
})
.describe('Body of POST \/vision\/scanners\/{id}\/observe\/.')
+
+/**
+ * Estimate the observation volume a proposed scanner would generate, for the pre-save cost preview.
+ */
+export const visionScannersEstimateCreateBodySamplingRateDefault = 1
+export const visionScannersEstimateCreateBodySamplingRateMin = 0
+export const visionScannersEstimateCreateBodySamplingRateMax = 1
+
+export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
+ .object({
+ query: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Proposed `RecordingsQuery` for the candidate filter. `date_from`\/`date_to` are ignored — the estimate always uses a fixed 30-day lookback. Omit to estimate against all recordings.'
+ ),
+ sampling_rate: zod
+ .number()
+ .min(visionScannersEstimateCreateBodySamplingRateMin)
+ .max(visionScannersEstimateCreateBodySamplingRateMax)
+ .default(visionScannersEstimateCreateBodySamplingRateDefault)
+ .describe('0..1 downsample applied to matched sessions. Defaults to 1.0 (no downsampling).'),
+ })
+ .describe('Body of POST \/vision\/scanners\/estimate\/ — a proposed, unsaved scanner config.')
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0d420865e314..da8f6e7c0b56 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -15035,6 +15035,34 @@ export namespace Schemas {
content_hash: string;
}
+ /**
+ * Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.
+ */
+ export interface EstimateRequest {
+ /** Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are ignored — the estimate always uses a fixed 30-day lookback. Omit to estimate against all recordings. */
+ query?: unknown;
+ /**
+ * 0..1 downsample applied to matched sessions. Defaults to 1.0 (no downsampling).
+ * @minimum 0
+ * @maximum 1
+ */
+ sampling_rate?: number;
+ }
+
+ /**
+ * Forward-looking observation-volume estimate for a proposed scanner. Pricing-agnostic.
+ */
+ export interface EstimateResponse {
+ /** Distinct sessions matching the query within the 30-day lookback, before sampling. */
+ matched_sessions_in_window: number;
+ /** Lookback window the estimate is based on. Normally 30; smaller when the team has fewer days of recordings. */
+ window_days: number;
+ /** Projected monthly observations: matched sessions scaled to 30 days, times sampling_rate. */
+ estimated_observations_per_month: number;
+ /** Sampling rate applied to the projection. Echoed from the request. */
+ sampling_rate: number;
+ }
+
/**
* Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}.
*/