: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
feat(replay-vision): estimate an experiment scanner's scope before saving (#111459)
Kim Svatos Dugan4c2159b8beb7
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex fa6caa4592b6..61bd06992702 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1415,6 +1415,18 @@ class InlineScanResponseSerializer(BulkObserveResponseSerializer):)+class EstimateExperimentScopeSerializer(serializers.Serializer):+ experiment_id = serializers.IntegerField(min_value=1, help_text="The experiment an experiment scanner watches.")+ variants = serializers.ListField(+ child=serializers.CharField(max_length=400),+ required=False,+ allow_null=True,+ default=None,+ min_length=1,+ help_text="The variant keys it watches. Null or omitted means every variant.",+ )++class EstimateRequestSerializer(serializers.Serializer):"""Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config."""@@ -1468,6 +1480,21 @@ class EstimateRequestSerializer(serializers.Serializer):"way a saved scanner derives it. The estimate then runs as the requesting user."),)+ experiment = EstimateExperimentScopeSerializer(+ required=False,+ allow_null=True,+ default=None,+ help_text=(+ "For an experiment scanner: the `experiment_id` and `variants` it will keep in its config, merged "+ "into the query as its exposure filter so the estimate counts only exposed sessions. Not "+ "combined with `experiment_targeting`."+ ),+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ if attrs.get("experiment") and attrs.get("experiment_targeting"):+ raise serializers.ValidationError({"experiment": "Pass `experiment` or `experiment_targeting`, not both."})+ return attrsdef validate_query(self, value: dict[str, Any]) -> dict[str, Any]:try:@@ -2920,11 +2947,12 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi# A denied experiment must read the same as a nonexistent one, mirroring# validate_experiment_targeting: the query runner's own access check answers with a 403,# which would confirm to a scanner-editor that a hidden experiment id exists.- targeting = body.validated_data.get("experiment_targeting")+ scope_field = "experiment" if body.validated_data.get("experiment") else "experiment_targeting"+ targeting = body.validated_data.get(scope_field)if targeting is not None and not is_experiment_accessible(self.user_access_control, self.team_id, targeting["experiment_id"]):- raise serializers.ValidationError({"experiment_targeting": "Experiment not found in this project."})+ raise serializers.ValidationError({scope_field: "Experiment not found in this project."})# 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 {})diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex a32914e47c0b..03668891a42f 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -58,6 +58,7 @@ from products.replay_vision.backend.models.replay_scanner import (from products.replay_vision.backend.models.replay_scanner_backfill import ReplayScannerBackfillfrom products.replay_vision.backend.queries import ESTIMATE_STALE_AFTER, SAVE_ESTIMATE_BUDGETfrom products.replay_vision.backend.queries.scanner_candidate_query import SETTLE_INTERVAL+from products.replay_vision.backend.queries.scanner_volume_estimate import estimate_scanner_session_volumefrom products.replay_vision.backend.quota import BillingPeriod, _current_period_boundsfrom products.replay_vision.backend.scanner_draft import DraftError, ScannerDraftfrom products.replay_vision.backend.search import ObservationMatch@@ -3910,12 +3911,36 @@ class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):[("sampling_rate_above_one", {"sampling_rate": 1.5}),("sampling_rate_negative", {"sampling_rate": -0.1}),+ (+ "both_scope_shapes",+ {"experiment": {"experiment_id": 1}, "experiment_targeting": {"experiment_id": 1, "variant": None}},+ ),+ ("empty_variant_list", {"experiment": {"experiment_id": 1, "variants": []}}),])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_scopes_to_an_experiment_scanners_experiment(self) -> None:+ # An experiment scanner keeps its experiment in its config, so the estimate has to take that+ # shape, or an agent sizing one counts every session instead of the exposed ones.+ experiment = create_experiment(self.team, "estimate-flag", launched=True, variants=["control", "test"])+ scope = {"experiment_id": experiment.id, "variants": ["test"]}+ with patch(+ "products.replay_vision.backend.api.scanners.estimate_scanner_session_volume",+ wraps=estimate_scanner_session_volume,+ ) as estimate:+ resp = self.client.post(self.estimate_url, data={"experiment": scope}, format="json")+ self.assertEqual(resp.status_code, 200, resp.json())+ exposure = estimate.call_args.kwargs["query"].experiment_exposure+ self.assertEqual((exposure.experiment_id, exposure.variants), (experiment.id, ["test"]))++ # A denied or unknown experiment reads the same, so its existence can't be probed.+ resp = self.client.post(self.estimate_url, data={"experiment": {"experiment_id": 999_999}}, format="json")+ self.assertEqual(resp.status_code, 400)+ self.assertEqual(resp.json()["attr"], "experiment")+def test_estimate_counts_only_in_window_sessions(self) -> None:for index in range(3):self._ingest_session(days_ago=index + 1)diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 2cfad8713b92..4c632b57044a 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -2420,6 +2420,21 @@ export interface DraftScannerResponseApi {estimated_monthly_observations: number | null}+export interface EstimateExperimentScopeApi {+ /**+ * The experiment an experiment scanner watches.+ * @minimum 1+ */+ experiment_id: number+ /**+ * The variant keys it watches. Null or omitted means every variant.+ * @minItems 1+ * @nullable+ * @items.maxLength 400+ */+ variants?: string[] | null+}+/*** Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.*/@@ -2451,6 +2466,8 @@ export interface EstimateRequestApi {model?: ScannerModelEnumApi/** Proposed experiment targeting, merged into the query as its exposure filter the same way a saved scanner derives it. The estimate then runs as the requesting user. */experiment_targeting?: ScannerExperimentTargetingApi | null+ /** For an experiment scanner: the `experiment_id` and `variants` it will keep in its config, merged into the query as its exposure filter so the estimate counts only exposed sessions. Not combined with `experiment_targeting`. */+ experiment?: EstimateExperimentScopeApi | null}/**diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 2506c26dcea2..2ecab96ad64a 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -1192,6 +1192,8 @@ export const visionScannersEstimateCreateBodySamplingModeDefault = `comprehensivexport const visionScannersEstimateCreateBodyModelDefault = `gemini-3-flash-preview`export const visionScannersEstimateCreateBodyExperimentTargetingOneVariantMax = 400+export const visionScannersEstimateCreateBodyExperimentOneVariantsItemMax = 400+export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod.object({query: zod@@ -1251,6 +1253,22 @@ export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod.describe('Proposed experiment targeting, merged into the query as its exposure filter the same way a saved scanner derives it. The estimate then runs as the requesting user.'),+ experiment: zod+ .union([+ zod.object({+ experiment_id: zod.number().min(1).describe('The experiment an experiment scanner watches.'),+ variants: zod+ .array(zod.string().max(visionScannersEstimateCreateBodyExperimentOneVariantsItemMax))+ .min(1)+ .nullish()+ .describe('The variant keys it watches. Null or omitted means every variant.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'For an experiment scanner: the `experiment_id` and `variants` it will keep in its config, merged into the query as its exposure filter so the estimate counts only exposed sessions. Not combined with `experiment_targeting`.'+ ),}).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.tsindex 560cf1c91ce9..532c447ace28 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -40083,6 +40083,21 @@ export namespace Schemas {content_hash: string;}+ export interface EstimateExperimentScope {+ /**+ * The experiment an experiment scanner watches.+ * @minimum 1+ */+ experiment_id: number;+ /**+ * The variant keys it watches. Null or omitted means every variant.+ * @minItems 1+ * @nullable+ * @items.maxLength 400+ */+ variants?: string[] | null;+ }+/*** Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.*/@@ -40114,6 +40129,8 @@ export namespace Schemas {model?: ScannerModelEnum;/** Proposed experiment targeting, merged into the query as its exposure filter the same way a saved scanner derives it. The estimate then runs as the requesting user. */experiment_targeting?: ScannerExperimentTargeting | null;+ /** For an experiment scanner: the `experiment_id` and `variants` it will keep in its config, merged into the query as its exposure filter so the estimate counts only exposed sessions. Not combined with `experiment_targeting`. */+ experiment?: EstimateExperimentScope | null;}/**diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex 67f037be5400..da096e7eb207 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -1936,6 +1936,8 @@ export const visionScannersEstimateCreateBodySamplingModeDefault = `comprehensivexport const visionScannersEstimateCreateBodyModelDefault = `gemini-3-flash-preview`export const visionScannersEstimateCreateBodyExperimentTargetingOneVariantMax = 400+export const visionScannersEstimateCreateBodyExperimentOneVariantsItemMax = 400+export const VisionScannersEstimateCreateBody = () => zod.object({query: zod@@ -1995,6 +1997,22 @@ export const VisionScannersEstimateCreateBody = () => zod.describe('Proposed experiment targeting, merged into the query as its exposure filter the same way a saved scanner derives it. The estimate then runs as the requesting user.'),+ experiment: zod+ .union([+ zod.object({+ experiment_id: zod.number().min(1).describe('The experiment an experiment scanner watches.'),+ variants: zod+ .array(zod.string().max(visionScannersEstimateCreateBodyExperimentOneVariantsItemMax))+ .min(1)+ .nullish()+ .describe('The variant keys it watches. Null or omitted means every variant.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'For an experiment scanner: the `experiment_id` and `variants` it will keep in its config, merged into the query as its exposure filter so the estimate counts only exposed sessions. Not combined with `experiment_targeting`.'+ ),}).describe('Body of POST \/vision\/scanners\/estimate\/ — a proposed, unsaved scanner config.')diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.tsindex 779e0b7453af..ca7a5ccc61b7 100644--- a/services/mcp/src/tools/generated/replay_vision.ts+++ b/services/mcp/src/tools/generated/replay_vision.ts@@ -1078,6 +1078,9 @@ const visionScannersEstimate = (): ToolBase<if (params.experiment_targeting !== undefined) {body['experiment_targeting'] = params.experiment_targeting}+ if (params.experiment !== undefined) {+ body['experiment'] = params.experiment+ }const result = await context.api.request<Schemas.EstimateResponse>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/estimate/`,@@ -1119,6 +1122,9 @@ const visionScannersEstimateCreate = (): ToolBase<if (params.experiment_targeting !== undefined) {body['experiment_targeting'] = params.experiment_targeting}+ if (params.experiment !== undefined) {+ body['experiment'] = params.experiment+ }const result = await context.api.request<Schemas.EstimateResponse>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/estimate/`,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.jsonindex 3fd1da89da5d..ba578daf7927 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.json@@ -2,6 +2,41 @@"$schema": "https://json-schema.org/draft/2020-12/schema","description": "Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.","properties": {+ "experiment": {+ "anyOf": [+ {+ "properties": {+ "experiment_id": {+ "description": "The experiment an experiment scanner watches.",+ "minimum": 1,+ "type": "number"+ },+ "variants": {+ "anyOf": [+ {+ "items": {+ "maxLength": 400,+ "type": "string"+ },+ "minItems": 1,+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "description": "The variant keys it watches. Null or omitted means every variant."+ }+ },+ "required": ["experiment_id"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "For an experiment scanner: the `experiment_id` and `variants` it will keep in its config, merged into the query as its exposure filter so the estimate counts only exposed sessions. Not combined with `experiment_targeting`."+ },"experiment_targeting": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate.jsonindex 3fd1da89da5d..ba578daf7927 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate.json@@ -2,6 +2,41 @@"$schema": "https://json-schema.org/draft/2020-12/schema","description": "Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.","properties": {+ "experiment": {+ "anyOf": [+ {+ "properties": {+ "experiment_id": {+ "description": "The experiment an experiment scanner watches.",+ "minimum": 1,+ "type": "number"+ },+ "variants": {+ "anyOf": [+ {+ "items": {+ "maxLength": 400,+ "type": "string"+ },+ "minItems": 1,+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "description": "The variant keys it watches. Null or omitted means every variant."+ }+ },+ "required": ["experiment_id"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "For an experiment scanner: the `experiment_id` and `variants` it will keep in its config, merged into the query as its exposure filter so the estimate counts only exposed sessions. Not combined with `experiment_targeting`."+ },"experiment_targeting": {"anyOf": [{