: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
refactor(replay-vision): define a scanner's recording filter rules once (#125758)
Kim Svatos Dugand96ca82c89ee
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 7d8ca166df33..a0d0ffb9c318 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -165,6 +165,7 @@ from products.replay_vision.backend.scanner_draft import (draft_scanner_from_goal,scopes_allow_read,)+from products.replay_vision.backend.scanner_query import ScannerQueryError, clean_scanner_queryfrom products.replay_vision.backend.scanning import (MAX_SESSIONS_PER_SCAN,run_inline_scan,@@ -189,9 +190,6 @@ from products.replay_vision.backend.watch_rank import ()from products.signals.backend.facade.api import get_outcomes_for_signal_source_slice-# Date is set by the schedule at trigger time, not by the user — strip on save.-_QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")-class ScannerCreationMethod(models.TextChoices):"""How a person built a scanner in the UI. Reported once at creation, never stored.@@ -232,19 +230,8 @@ def _reported_creation_method(context: dict[str, Any], claimed: str | None) -> sreturn claimed if source == EventSource.WEB else source.value-def _reject_direct_experiment_exposure(query: dict[str, Any]) -> None:- # Exposure is derived from experiment_targeting at scan time, never persisted in the query blob:- # writable exposure there would bypass experiment_targeting's access check and let an editor run- # the exposure filter under the creator's access.- if query.get("experiment_exposure") is not None:- raise serializers.ValidationError(- "Recording filter can't set experiment exposure directly. Set experiment_targeting instead."- )--# Size caps enforced at the write boundary; scanner_config and query are copied into every observation's snapshot._MAX_DESCRIPTION_LENGTH = 1_000-_MAX_QUERY_BYTES = 50_000# Each tag costs get_or_create round trips in set_tags_on_object, so cap the list._MAX_TAGS = 32@@ -252,6 +239,24 @@ _MAX_TAGS = 32logger = structlog.get_logger(__name__)+class RecordingsQueryField(serializers.JSONField):+ """A scanner's recording filter, a `RecordingsQuery`. The rules in `scanner_query` decide what a+ scanner may keep, so this only refuses a value that is not an object, before any of them reads it."""++ def to_internal_value(self, data: Any) -> Any:+ value = super().to_internal_value(data)+ if not isinstance(value, dict):+ raise serializers.ValidationError("Recording filter must be a JSON object.")+ return value+++def _clean_query(value: dict[str, Any]) -> dict[str, Any]:+ try:+ return clean_scanner_query(value)+ except ScannerQueryError as error:+ raise serializers.ValidationError(str(error))++# Query keys that narrow which sessions a scanner matches. Date keys are schedule-controlled# and stripped on save, so they never count as user-chosen filters.SCANNER_QUERY_FILTER_KEYS = (@@ -472,14 +477,12 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial"Falls back to the prompt's first line when no question matches the current prompt."),)- query = extend_schema_field(RecordingsQuery)( # type: ignore[arg-type, type-var]- serializers.JSONField(- required=False,- help_text=(- "Persisted `RecordingsQuery` shape used to pick candidate sessions. "- "`date_from`/`date_to` are stripped on save — the schedule controls time, not the user."- ),- )+ query = RecordingsQueryField(+ required=False,+ help_text=(+ "Persisted `RecordingsQuery` shape used to pick candidate sessions. "+ "`date_from`/`date_to` are stripped on save — the schedule controls time, not the user."+ ),)sampling_rate = serializers.FloatField(required=False,@@ -799,7 +802,6 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerialself._restore_redacted_experiment_config(attrs)self._validate_scanner_config(attrs)self._validate_experiment_scanner(attrs)- self._validate_and_strip_query(attrs)self._drop_redacted_targeting_clear(attrs)scout_caller = bool(self.context.get("scout_sandbox_caller"))check_scout_scanner_credit_limit(@@ -971,20 +973,9 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerialif message is not None:raise serializers.ValidationError({"scanner_config": message})- def _validate_and_strip_query(self, attrs: dict[str, Any]) -> None:- if "query" not in attrs:- return- try:- RecordingsQuery.model_validate(attrs["query"])- except PydanticValidationError:- raise serializers.ValidationError({"query": "Recording filter is invalid."})- _reject_direct_experiment_exposure(attrs["query"])+ def validate_query(self, value: dict[str, Any]) -> dict[str, Any]:# Persist exactly what the user sent (validated), minus the date keys the schedule controls.- attrs["query"] = {k: v for k, v in attrs["query"].items() if k not in _QUERY_FIELDS_TO_STRIP}- if len(json.dumps(attrs["query"], separators=(",", ":")).encode()) > _MAX_QUERY_BYTES:- raise serializers.ValidationError(- {"query": f"Recording filter is too large. Keep it under {_MAX_QUERY_BYTES // 1000} KB."}- )+ return _clean_query(value)def to_representation(self, instance: ReplayScanner) -> dict[str, Any]:data = super().to_representation(instance)@@ -1546,15 +1537,13 @@ class EstimateExperimentScopeSerializer(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 scans a recent window (`window_days` in the response) and "- "scales it to 30 days. Omit to estimate against all recordings."- ),- )+ query = RecordingsQueryField(+ required=False,+ help_text=(+ "Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are "+ "ignored — the estimate scans a recent window (`window_days` in the response) and "+ "scales it to 30 days. Omit to estimate against all recordings."+ ),)sampling_rate = serializers.FloatField(required=False,@@ -1613,12 +1602,7 @@ class EstimateRequestSerializer(serializers.Serializer):return attrsdef validate_query(self, value: dict[str, Any]) -> dict[str, Any]:- try:- RecordingsQuery.model_validate(value)- except PydanticValidationError:- raise serializers.ValidationError("Recording filter is invalid.")- _reject_direct_experiment_exposure(value)- return {k: v for k, v in value.items() if k not in _QUERY_FIELDS_TO_STRIP}+ return _clean_query(value)class ScannerTypeStatsSerializer(serializers.Serializer):diff --git a/products/replay_vision/backend/scanner_query.py b/products/replay_vision/backend/scanner_query.pynew file mode 100644index 000000000000..b6845e033b56--- /dev/null+++ b/products/replay_vision/backend/scanner_query.py@@ -0,0 +1,56 @@+"""What a scanner's recording filter may hold, defined once for every path that accepts one.++A scanner keeps less of a recording filter than the replay list does, and each difference fails+silently: a dropped condition saves a scanner that watches more than the person chose, and a broken+one saves a scanner whose runs keep failing. Create, update and the estimate all accept a filter, so+they share these rules rather than each keeping a copy that can drift.+"""++import json+from typing import Any++from pydantic import ValidationError as PydanticValidationError++from posthog.schema import RecordingsQuery++# A scanner's schedule owns time, so a saved filter never carries a date range.+DATE_FIELDS = ("date_from", "date_to")+# Copied into every observation's snapshot, so the write boundary caps it.+MAX_QUERY_BYTES = 50_000+++class ScannerQueryError(ValueError):+ """A recording filter a scanner cannot keep. The message is safe to show to the caller."""+++def _as_object(value: object) -> dict[str, Any]:+ if not isinstance(value, dict):+ raise ScannerQueryError("Recording filter must be a JSON object.")+ return value+++def _parsed(value: dict[str, Any]) -> RecordingsQuery:+ try:+ return RecordingsQuery.model_validate(value)+ except PydanticValidationError:+ raise ScannerQueryError("Recording filter is invalid.")+++def clean_scanner_query(value: object) -> dict[str, Any]:+ """The filter as a scanner stores it: a valid `RecordingsQuery` without the date range.++ Raises `ScannerQueryError` for anything a saved scanner must not hold.+ """+ value = _as_object(value)+ _parsed(value)+ # Exposure is derived from experiment_targeting at scan time, never persisted in the query blob:+ # writable exposure there would bypass experiment_targeting's access check and let an editor run+ # the exposure filter under the creator's access.+ if value.get("experiment_exposure") is not None:+ raise ScannerQueryError(+ "Recording filter can't set experiment exposure directly. Set experiment_targeting instead."+ )+ cleaned = {key: item for key, item in value.items() if key not in DATE_FIELDS}+ if len(json.dumps(cleaned, separators=(",", ":")).encode()) > MAX_QUERY_BYTES:+ raise ScannerQueryError(f"Recording filter is too large. Keep it under {MAX_QUERY_BYTES // 1000} KB.")+ return cleaneddiff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 80c301b40f7d..457a4fb0a016 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -777,12 +777,24 @@ class TestReplayScannerViewSet(_VisionAPITestCase):@parameterized.expand([- ("unknown_field", {"this_field_does_not_exist": True}),+ ("unknown_field", {"this_field_does_not_exist": True}, "Recording filter is invalid."),# An oversized query is copied into every observation's snapshot, so it is capped on save.- ("oversized", {"distinct_ids": ["x" * 1_000 for _ in range(100)]}),+ (+ "oversized",+ {"distinct_ids": ["x" * 1_000 for _ in range(100)]},+ "Recording filter is too large. Keep it under 50 KB.",+ ),+ # Every rule reads fields off the query, so any other shape must be refused before they run.+ ("not_an_object", ["kind", "RecordingsQuery"], "Recording filter must be a JSON object."),+ # Exposure in the query would skip experiment_targeting's access check.+ (+ "experiment_exposure",+ {"experiment_exposure": {"experiment_id": 1}},+ "Recording filter can't set experiment exposure directly. Set experiment_targeting instead.",+ ),])- def test_create_rejects_invalid_query(self, _name: str, query: dict) -> None:+ def test_create_rejects_invalid_query(self, _name: str, query: object, detail: str) -> None:resp = self.client.post(self.scanners_url,data={@@ -795,7 +807,7 @@ class TestReplayScannerViewSet(_VisionAPITestCase):format="json",)self.assertEqual(resp.status_code, 400, resp.json())- self.assertEqual(resp.json()["attr"], "query")+ self.assertEqual((resp.json()["attr"], resp.json()["detail"]), ("query", detail))def test_delete(self) -> None:scanner = self._create_scanner()@@ -4200,6 +4212,10 @@ class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):{"experiment": {"experiment_id": 1}, "experiment_targeting": {"experiment_id": 1, "variant": None}},),("empty_variant_list", {"experiment": {"experiment_id": 1, "variants": []}}),+ # The estimate takes the same filter a saved scanner keeps, so it applies the same rules.+ ("query_oversized", {"query": {"distinct_ids": ["x" * 1_000 for _ in range(100)]}}),+ ("query_experiment_exposure", {"query": {"experiment_exposure": {"experiment_id": 1}}}),+ ("query_not_an_object", {"query": ["kind", "RecordingsQuery"]}),])def test_estimate_rejects_invalid_input(self, _name: str, payload: dict[str, Any]) -> None: