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 the experiment scanner type (#108814)

Kim Svatos Dugan81976f684539
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index b893124299c2..dcb616c26960 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -118,7 +118,7 @@ class ScannerSnapshotSerializer(serializers.Serializer):
)
scanner_type = serializers.ChoiceField(
choices=ScannerType.choices,
- help_text="Scanner type (monitor, classifier, scorer, summarizer) at run time.",
+ help_text="Scanner type (monitor, classifier, scorer, summarizer, experiment) at run time.",
)
scanner_version = serializers.IntegerField(
help_text="The `ReplayScanner.scanner_version` value at the moment the workflow ran.",
diff --git a/products/replay_vision/backend/api/prompt_suggestions.py b/products/replay_vision/backend/api/prompt_suggestions.py
index ec7c1e16249c..cd58dd6d76c2 100644
--- a/products/replay_vision/backend/api/prompt_suggestions.py
+++ b/products/replay_vision/backend/api/prompt_suggestions.py
@@ -30,7 +30,7 @@ from posthog.temporal.common.search_attributes import POSTHOG_TEAM_ID_KEY
from products.replay_vision.backend.api.scanners import scanner_lifecycle_properties
from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType, config_experiment_scope
from products.replay_vision.backend.models.replay_scanner_prompt_suggestion import (
PromptSuggestionStatus,
ReplayScannerPromptSuggestion,
@@ -50,6 +50,7 @@ from products.replay_vision.backend.prompt_suggestions import (
labels_fingerprint,
)
from products.replay_vision.backend.quota import compute_scanner_budget, quota_state
+from products.replay_vision.backend.scanner_access import can_read_targeted_experiment
from products.replay_vision.backend.scanner_config import scanner_config_error
from products.replay_vision.backend.scout_writes import refuse_scout_scanner_scan
from products.replay_vision.backend.temporal.constants import (
@@ -278,6 +279,11 @@ class ReplayScannerPromptSuggestionViewSet(
self.check_object_permissions(self.request, scanner)
if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
raise PermissionDenied("Reading prompt suggestions requires session_recording read access.")
+ # Suggestions and their evaluations quote an experiment scanner's observations (session ids,
+ # output text), so reading or acting on them needs experiment access too. Not-found, not 403,
+ # matching the observations endpoint.
+ if not can_read_targeted_experiment(self.user_access_control, self.team_id, scanner):
+ raise NotFound()
self._scanner_for_url_cache = scanner
return scanner
@@ -403,6 +409,13 @@ class ReplayScannerPromptSuggestionViewSet(
config = dict(suggestion.suggested_config)
else:
config = {**(scanner.scanner_config or {}), "prompt": suggestion.suggested_prompt}
+ # The scanner serializer re-checks experiment access whenever the scope changes; this
+ # endpoint writes the config directly, so a scope change here would skip that check.
+ # Recommendations tune prompts, never the watched experiment, so refuse outright.
+ if scanner.scanner_type == ScannerType.EXPERIMENT and config_experiment_scope(config) != (
+ scanner.experiment_scope()
+ ):
+ raise ValidationError("This recommendation can't change the scanner's experiment.")
# Same validation as the scanner edit endpoint: an oversized or malformed LLM rewrite
# must not land in the config that every future observation snapshots.
message = scanner_config_error(ScannerType(scanner.scanner_type), config)
@@ -494,6 +507,11 @@ class ReplayScannerPromptSuggestionViewSet(
# A malformed edited config must be rejected before it charges credits on runs that can't succeed,
# matching the validation apply runs before it writes the config.
if edited_config is not None:
+ # Matching apply's scope rule: a test config must not retarget the watched experiment.
+ if scanner.scanner_type == ScannerType.EXPERIMENT and config_experiment_scope(edited_config) != (
+ scanner.experiment_scope()
+ ):
+ raise ValidationError("A test can't change the scanner's experiment.")
message = scanner_config_error(ScannerType(scanner.scanner_type), edited_config)
if message:
raise ValidationError(f"This config can't be tested: {message}")
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 8f64733f7aa6..d241118e388e 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -117,6 +117,7 @@ from products.replay_vision.backend.models.replay_scanner import (
ScannerProvider,
ScannerType,
apply_experiment_targeting,
+ config_experiment_scope,
)
from products.replay_vision.backend.prompt_questions import (
question_fields_for_save,
@@ -146,6 +147,7 @@ from products.replay_vision.backend.scanner_access import (
accessible_observations,
is_experiment_accessible,
readable_observation_scanner_ids,
+ scanner_experiment_scope_q,
)
from products.replay_vision.backend.scanner_config import (
MAX_PROMPT_LENGTH,
@@ -316,6 +318,7 @@ def scanner_lifecycle_properties(scanner: ReplayScanner) -> dict[str, Any]:
Filter *values* stay out: they can carry customer data (URLs, emails)."""
query = scanner.query if isinstance(scanner.query, dict) else {}
estimate = scanner.estimated_monthly_observations
+ experiment_scope = scanner.experiment_scope()
return {
"scanner_id": str(scanner.id),
"scanner_type": scanner.scanner_type,
@@ -325,10 +328,10 @@ def scanner_lifecycle_properties(scanner: ReplayScanner) -> dict[str, Any]:
"sampling_rate": scanner.sampling_rate,
"sampling_mode": scanner.sampling_mode,
"enabled": scanner.enabled,
- # experiment_targeting narrows the population server-side, so it counts as filtered; the
+ # An experiment scope narrows the population server-side, so it counts as filtered; the
# separate flag keeps experiment-scoped scanners countable apart from hand-filtered ones.
- "has_filters": any(query.get(key) for key in _QUERY_FILTER_KEYS) or bool(scanner.experiment_targeting),
- "has_experiment_targeting": bool(scanner.experiment_targeting),
+ "has_filters": any(query.get(key) for key in _QUERY_FILTER_KEYS) or bool(experiment_scope),
+ "has_experiment_targeting": bool(experiment_scope),
# True when the prompt is a stock template's word for word, so a creation-flow experiment can
# tell a scanner tailored to the team from a template saved with its defaults.
"uses_template_prompt": template_question(scanner.scanner_config) is not None,
@@ -803,7 +806,9 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
if duplicates.exists():
raise serializers.ValidationError({"name": "A scanner with this name already exists in this team."})
self._reject_scanner_type_change(attrs)
+ self._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"))
@@ -832,6 +837,76 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
):
attrs.pop("experiment_targeting")
+ def _restore_redacted_experiment_config(self, attrs: dict[str, Any]) -> None:
+ """Normalize an experiment scanner's config on update, where the experiment itself is fixed.
+
+ The experiment decides the population, the prompt, and the meaning of every observation,
+ so it is as identity-defining as the scanner type: retargeting is a new scanner, not an
+ edit (and per-scanner readouts would otherwise mix two populations). That also makes a
+ written-back config with no experiment_id unambiguous, so the stored id is restored.
+ """
+ if self.instance is None or self.instance.scanner_type != ScannerType.EXPERIMENT:
+ return
+ config = attrs.get("scanner_config")
+ if not isinstance(config, dict):
+ return
+ stored = self.instance.scanner_config if isinstance(self.instance.scanner_config, dict) else {}
+ if stored.get("experiment_id") is None:
+ return
+ if not self._can_view_targeted_experiment({"experiment_id": stored["experiment_id"]}):
+ # A caller denied the experiment can't write this config at all. The scan injects the
+ # experiment's own description into the prompt (see resolve_experiment_variant), so a
+ # prompt they wrote could instruct the model to copy that private text into output that
+ # lands on the team-visible $recording_observed event. One uniform answer for every
+ # write also keeps the hidden id and variants from being enumerated by probing PATCHes.
+ raise serializers.ValidationError({"scanner_config": "Experiment not found in this project."})
+ if config.get("experiment_id") is not None and config["experiment_id"] != stored["experiment_id"]:
+ raise serializers.ValidationError(
+ {
+ "scanner_config": (
+ "The experiment is fixed after creation. Create a new scanner to watch a different experiment."
+ )
+ }
+ )
+ attrs["scanner_config"] = {**config, "experiment_id": stored["experiment_id"]}
+
+ def _validate_experiment_scanner(self, attrs: dict[str, Any]) -> None:
+ """The experiment-type checks that need a viewer or the experiments product, which the
+ pydantic config validation has no access to: experiment access, and a resolvable exposed
+ population (launched, person-aggregated, variants exist)."""
+ scanner_type = attrs.get("scanner_type", getattr(self.instance, "scanner_type", None))
+ if scanner_type != ScannerType.EXPERIMENT:
+ return
+ if attrs.get("experiment_targeting"):
+ raise serializers.ValidationError(
+ {"experiment_targeting": "An experiment scanner keeps its experiment in scanner_config."}
+ )
+ if "scanner_config" not in attrs and "scanner_type" not in attrs:
+ return
+ config = attrs.get("scanner_config", getattr(self.instance, "scanner_config", None)) or {}
+ if self.instance is not None and config_experiment_scope(config) == self.instance.experiment_scope():
+ # Unchanged scope (the restore already required experiment access on updates): the
+ # experiment's launch state was checked when the scope was written.
+ return
+ experiment_id = config.get("experiment_id")
+ if not isinstance(experiment_id, int):
+ # scanner_config_error already rejected this shape; kept as the type narrow.
+ raise serializers.ValidationError({"scanner_config": "Experiment is required."})
+ # Filtered by the caller's experiment access (not just the team), mirroring
+ # validate_experiment_targeting: a denied or cross-team id reads as not-found.
+ if not self._can_view_targeted_experiment({"experiment_id": experiment_id}):
+ raise serializers.ValidationError({"scanner_config": "Experiment not found in this project."})
+ # Deferred: the experiments replay facade pulls in the recordings query modules, which
+ # circle back into this package's importers.
+ from products.experiments.backend.facade.replay import resolve_exposure_linkage # noqa: PLC0415
+
+ try:
+ resolve_exposure_linkage(
+ self.context["get_team"](), experiment_id=experiment_id, variants=config.get("variants")
+ )
+ except serializers.ValidationError as exc:
+ raise serializers.ValidationError({"scanner_config": exc.detail}) from exc
+
def validate_experiment_targeting(self, value: dict[str, Any] | None) -> dict[str, Any] | None:
# The field already validated the blob's shape; this adds the access check, which needs the
# request context the field lacks. Filtered by the caller's experiment access (not just the
@@ -907,6 +982,18 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
# check in validate_experiment_targeting — a caller without experiment access sees null.
if data.get("experiment_targeting") and not self._can_view_targeted_experiment(data["experiment_targeting"]):
data["experiment_targeting"] = None
+ # The experiment type keeps its scope in scanner_config; hide only the experiment keys from
+ # a denied caller, so the rest of the config (prompt, length) stays readable. Writes are a
+ # separate question: `_restore_redacted_experiment_config` refuses every config write from a
+ # denied caller.
+ if instance.scanner_type == ScannerType.EXPERIMENT and isinstance(data.get("scanner_config"), dict):
+ experiment_id = data["scanner_config"].get("experiment_id")
+ if experiment_id is not None and not self._can_view_targeted_experiment({"experiment_id": experiment_id}):
+ data["scanner_config"] = {
+ key: value
+ for key, value in data["scanner_config"].items()
+ if key not in ("experiment_id", "variants")
+ }
return data
def _can_view_targeted_experiment(self, targeting: dict[str, Any]) -> bool:
@@ -1186,7 +1273,7 @@ class ReplayScannerFilter(django_filters.FilterSet):
view = self.request.parser_context.get("view") if self.request else None
if view is None or not is_experiment_accessible(view.user_access_control, view.team_id, experiment_id):
return queryset.none()
- return queryset.filter(experiment_targeting__experiment_id=experiment_id)
+ return queryset.filter(scanner_experiment_scope_q(experiment_ids=[experiment_id]))
@staticmethod
def _filter_search(queryset: QuerySet[ReplayScanner], _name: str, value: str) -> QuerySet[ReplayScanner]:
@@ -1343,6 +1430,13 @@ class InlineScanRequestSerializer(serializers.Serializer):
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
config = attrs["scanner_config"]
+ if attrs["scanner_type"] == ScannerType.EXPERIMENT:
+ # Inline scans skip the saved-scanner path that access-checks the experiment and, for
+ # now, the workflow step that attributes a session's variant. Until those run for
+ # inline scans, the type would scan without its experiment context.
+ raise serializers.ValidationError(
+ {"scanner_type": "Experiment scanners can't run as inline scans. Create the scanner instead."}
+ )
if not isinstance(config, dict):
raise serializers.ValidationError({"scanner_config": "Scanner configuration must be a JSON object."})
if "prompt" in config:
@@ -1446,6 +1540,7 @@ class ScannerStatsByTypeSerializer(serializers.Serializer):
classifier = ScannerTypeStatsSerializer()
scorer = ScannerTypeStatsSerializer()
summarizer = ScannerTypeStatsSerializer()
+ experiment = ScannerTypeStatsSerializer()
class ScannerStatsResponseSerializer(serializers.Serializer):
@@ -1454,7 +1549,7 @@ class ScannerStatsResponseSerializer(serializers.Serializer):
total = serializers.IntegerField(help_text="Total scanners on the team.")
enabled = serializers.IntegerField(help_text="Number of enabled scanners on the team.")
by_type = ScannerStatsByTypeSerializer(
- help_text="Per-scanner-type breakdown (monitor / classifier / scorer / summarizer)."
+ help_text="Per-scanner-type breakdown (monitor / classifier / scorer / summarizer / experiment)."
)
@@ -2192,6 +2287,14 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
self.user_access_control, self.team_id, experiment_id
):
experiment_targeting = None
+ if source.scanner_type == ScannerType.EXPERIMENT:
+ scope_experiment_id = (source.experiment_scope() or {}).get("experiment_id")
+ if scope_experiment_id is None or not is_experiment_accessible(
+ self.user_access_control, self.team_id, scope_experiment_id
+ ):
+ # The experiment type can't exist without its experiment, so there is no
+ # targeting-stripped copy to fall back to the way the legacy types have.
+ raise serializers.ValidationError("Duplicating this scanner requires access to its experiment.")
# One transaction so a failed tag write can't leave an untagged copy behind. Side effects stay outside.
with transaction.atomic():
try:
diff --git a/products/replay_vision/backend/facade/api.py b/products/replay_vision/backend/facade/api.py
index bca7290ef18b..24cc69cd86d2 100644
--- a/products/replay_vision/backend/facade/api.py
+++ b/products/replay_vision/backend/facade/api.py
@@ -64,7 +64,11 @@ def fetch_page_session_observations(
)
if prefer_summarizer:
queryset = queryset.order_by(
- Case(When(scanner__scanner_type=ScannerType.SUMMARIZER, then=0), default=1), "-created_at"
+ Case(
+ When(scanner__scanner_type__in=(ScannerType.SUMMARIZER, ScannerType.EXPERIMENT), then=0),
+ default=1,
+ ),
+ "-created_at",
)
else:
queryset = queryset.order_by("-created_at")
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.py
index 6f0450147e5e..89aa8f014dd8 100644
--- a/products/replay_vision/backend/max_tools.py
+++ b/products/replay_vision/backend/max_tools.py
@@ -302,7 +302,7 @@ class SummarizeReplayVisionSummariesTool(ReplayVisionGatesMixin, MaxTool):
scanner, "viewer"
) or not can_read_targeted_experiment(self.user_access_control, self._team.id, scanner):
return f"Scanner {scanner_id} not found.", {"error": "forbidden"}
- if scanner.scanner_type != ScannerType.SUMMARIZER:
+ if scanner.scanner_type not in (ScannerType.SUMMARIZER, ScannerType.EXPERIMENT):
# Never interpolate the user-editable scanner name into tool output — it's outside the data fence.
return (
f"That scanner is a {scanner.scanner_type} scanner, not a summarizer.",
@@ -310,8 +310,12 @@ class SummarizeReplayVisionSummariesTool(ReplayVisionGatesMixin, MaxTool):
)
observations = (
- ReplayObservation.objects.filter(
- team_id=self._team.id, scanner_id=scanner_id, status=ObservationStatus.SUCCEEDED
+ accessible_observations(
+ self.user_access_control,
+ self._team.id,
+ ReplayObservation.objects.filter(
+ team_id=self._team.id, scanner_id=scanner_id, status=ObservationStatus.SUCCEEDED
+ ),
)
.order_by("-created_at")
.values_list("scanner_result", "created_at")[:MAX_SUMMARIES]
@@ -923,7 +927,7 @@ def _scanner_config_for(
config["tags"] = tags
if scanner_type == ScannerType.SCORER and (scale_min is not None or scale_max is not None):
config["scale"] = {"min": scale_min, "max": scale_max}
- if scanner_type == ScannerType.SUMMARIZER and length is not None:
+ if scanner_type in (ScannerType.SUMMARIZER, ScannerType.EXPERIMENT) and length is not None:
config["length"] = length
return config
@@ -1084,6 +1088,7 @@ class CreateReplayVisionScannerTool(ReplayVisionGatesMixin, MaxTool):
context={
"get_team": lambda: self._team,
"user": self._user,
+ "user_access_control": self.user_access_control,
"event_source": EventSource.POSTHOG_AI,
},
)
@@ -1244,7 +1249,13 @@ class UpdateReplayVisionScannerTool(ReplayVisionGatesMixin, MaxTool):
scanner,
data=data,
partial=True,
- context={"get_team": lambda: self._team, "user": self._user},
+ # No HTTP request here, so the serializer can't derive the access control from one; without
+ # it the experiment-scope write guard would treat the caller as unrestricted.
+ context={
+ "get_team": lambda: self._team,
+ "user": self._user,
+ "user_access_control": self.user_access_control,
+ },
)
if not serializer.is_valid():
return _first_error(serializer.errors), {"error": "invalid_config"}
diff --git a/products/replay_vision/backend/migrations/0104_alter_replayscanner_scanner_type.py b/products/replay_vision/backend/migrations/0104_alter_replayscanner_scanner_type.py
new file mode 100644
index 000000000000..2a3824e095f6
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0104_alter_replayscanner_scanner_type.py
@@ -0,0 +1,26 @@
+# Generated by Django 5.2.17 on 2026-09-29 22:03
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0103_alter_replayobservationmedia_kind"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="replayscanner",
+ name="scanner_type",
+ field=models.CharField(
+ choices=[
+ ("monitor", "Monitor"),
+ ("classifier", "Classifier"),
+ ("scorer", "Scorer"),
+ ("summarizer", "Summarizer"),
+ ("experiment", "Experiment"),
+ ],
+ max_length=32,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 3fb73949e8b6..f076d8108044 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0103_alter_replayobservationmedia_kind
+0104_alter_replayscanner_scanner_type
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index 64aee0d3e359..3da1331060f1 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -41,17 +41,27 @@ def apply_experiment_targeting(query: "RecordingsQuery", targeting: dict | None)
exposure = RecordingsQueryExperimentExposureFilter(
experiment_id=targeting["experiment_id"],
variant=targeting.get("variant") or None,
+ variants=targeting.get("variants") or None,
)
# Shallow copy replacing only the one field: the caller's query is left untouched, and the
# unrelated nested filters are shared by reference rather than deep-copied since nothing mutates them.
return query.model_copy(update={"experiment_exposure": exposure})
+def config_experiment_scope(scanner_config: "dict | None") -> dict | None:
+ """The experiment scope carried inside an experiment scanner's `scanner_config`, or None."""
+ config = scanner_config if isinstance(scanner_config, dict) else {}
+ if config.get("experiment_id") is None:
+ return None
+ return {"experiment_id": config["experiment_id"], "variants": config.get("variants")}
+
+
class ScannerType(models.TextChoices):
MONITOR = "monitor", "Monitor"
CLASSIFIER = "classifier", "Classifier"
SCORER = "scorer", "Scorer"
SUMMARIZER = "summarizer", "Summarizer"
+ EXPERIMENT = "experiment", "Experiment"
class SamplingMode(models.TextChoices):
@@ -239,8 +249,10 @@ class ReplayScanner(Taggable, ModelActivityMixin, UUIDModel):
)
# Shape: ScannerExperimentTargetingSerializer. Stored because the compiled `query` speaks flag
- # keys, so the experiment association isn't recoverable from it. Not version-tracked; scanning
- # never reads it.
+ # keys, so the experiment association isn't recoverable from it. Version-tracked, and every scan
+ # and estimate derives its exposure filter from it through `targeted_recordings_query`. Legacy:
+ # the experiment scanner type keeps its targeting in `scanner_config` instead (see
+ # `experiment_scope`).
experiment_targeting = models.JSONField(
null=True,
blank=True,
@@ -458,7 +470,17 @@ class ReplayScanner(Taggable, ModelActivityMixin, UUIDModel):
if changed:
self.scanner_version = old.scanner_version + 1
extra_fields.append("scanner_version")
- if changed & self._ESTIMATE_FIELDS:
+ estimate_stale = bool(changed & self._ESTIMATE_FIELDS)
+ if (
+ not estimate_stale
+ and "scanner_config" in changed
+ and self.scanner_type == ScannerType.EXPERIMENT
+ ):
+ # The experiment type keeps its targeting in scanner_config, so a scope
+ # change there moves the estimate the way an experiment_targeting change
+ # does; a prompt-only config edit does not.
+ estimate_stale = old.experiment_scope() != self.experiment_scope()
+ if estimate_stale:
# A config edit must not wait out a backoff the old config earned.
self.estimated_at = None
self.estimate_attempted_at = None
@@ -486,15 +508,26 @@ class ReplayScanner(Taggable, ModelActivityMixin, UUIDModel):
return RecordingsQuery.model_validate(self.query or {"kind": "RecordingsQuery"})
+ def experiment_scope(self) -> dict | None:
+ """The experiment this scanner watches, wherever it is stored.
+
+ The experiment scanner type keeps `experiment_id` and `variants` in `scanner_config`; the
+ other types use the legacy `experiment_targeting` column. Both stores are access-checked on
+ write and redacted on read, so this is the one place code may read a scanner's experiment.
+ """
+ if self.scanner_type == ScannerType.EXPERIMENT:
+ return config_experiment_scope(self.scanner_config)
+ return self.experiment_targeting
+
def targeted_recordings_query(self) -> "RecordingsQuery":
"""The query every scan and estimate must run: the persisted filter plus the exposure
- filter derived from `experiment_targeting`.
+ filter derived from `experiment_scope()`.
Derived here rather than persisted into `query` so the experiment can only ever enter
- through `experiment_targeting`, the field the API access-checks on write and redacts on
- read. The serializer rejects `experiment_exposure` inside `query` for the same reason.
+ through the access-checked scope stores (see `experiment_scope`). The serializer rejects
+ `experiment_exposure` inside `query` for the same reason.
"""
- return apply_experiment_targeting(self.recordings_query(), self.experiment_targeting)
+ return apply_experiment_targeting(self.recordings_query(), self.experiment_scope())
def __str__(self) -> str:
return f"{self.name} ({self.scanner_type})"
diff --git a/products/replay_vision/backend/observation_formatting.py b/products/replay_vision/backend/observation_formatting.py
index 878e05309abd..486c234cb20a 100644
--- a/products/replay_vision/backend/observation_formatting.py
+++ b/products/replay_vision/backend/observation_formatting.py
@@ -103,7 +103,7 @@ def describe_output(output: dict[str, Any]) -> str | None:
if scanner_type == ScannerType.CLASSIFIER:
tags = [*_tag_list(output.get("tags")), *_tag_list(output.get("tags_freeform"))]
return f"tags={', '.join(tags)}" if tags else None
- if scanner_type == ScannerType.SUMMARIZER:
+ if scanner_type in (ScannerType.SUMMARIZER, ScannerType.EXPERIMENT):
title = output.get("title")
return str(title) if isinstance(title, str) and title.strip() else None
return None
diff --git a/products/replay_vision/backend/prompt_evaluation.py b/products/replay_vision/backend/prompt_evaluation.py
index 961572b6cd61..bffe23e6d186 100644
--- a/products/replay_vision/backend/prompt_evaluation.py
+++ b/products/replay_vision/backend/prompt_evaluation.py
@@ -32,7 +32,7 @@ def evaluation_usage_id(suggestion_id: uuid.UUID, session_id: str, started_at: s
EVALUATION_SUPPORTED_TYPES = (ScannerType.MONITOR, ScannerType.CLASSIFIER)
-EVALUATION_PREVIEW_TYPES = (ScannerType.SCORER, ScannerType.SUMMARIZER)
+EVALUATION_PREVIEW_TYPES = (ScannerType.SCORER, ScannerType.SUMMARIZER, ScannerType.EXPERIMENT)
EvaluationOutcome = Literal["kept", "regressed", "fixed", "still_wrong", "error", "preview"]
diff --git a/products/replay_vision/backend/proposers/__init__.py b/products/replay_vision/backend/proposers/__init__.py
index de5a26e6c653..8f9270d14a29 100644
--- a/products/replay_vision/backend/proposers/__init__.py
+++ b/products/replay_vision/backend/proposers/__init__.py
@@ -9,6 +9,9 @@ _PROPOSERS: dict[str, ConfigProposer] = {
ClassifierProposer.scanner_type: ClassifierProposer(),
ScorerProposer.scanner_type: ScorerProposer(),
SummarizerProposer.scanner_type: SummarizerProposer(),
+ # The experiment type is a summarizer with experiment context, so "Improve scanner"
+ # tunes its prompt the summarizer way.
+ "experiment": SummarizerProposer(),
}
diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.py
index e47ed403d928..43dd3e90387c 100644
--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py
+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py
@@ -1,5 +1,6 @@
import datetime as dt
from dataclasses import dataclass
+from typing import Any
from django.utils import timezone
@@ -22,7 +23,7 @@ from posthog.models import Team, User
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
from products.replay_vision.backend.billing import ESTIMATE_MONTH_DAYS
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, SamplingMode
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, SamplingMode, ScannerType
from products.replay_vision.backend.queries.scanner_candidate_query import (
eligibility_predicates,
surfacing_score_predicate,
@@ -322,16 +323,21 @@ def refresh_scanner_estimate(
estimated_at = timezone.now()
# Filtered write so a config edit racing the (slow) estimate query can't get stamped fresh with stale numbers.
# JSONField quirk: `field=None` filters for JSON null, not SQL NULL, so the no-targeting case needs isnull.
+ guard_fields: dict[str, Any] = (
+ {"experiment_targeting__isnull": True}
+ if scanner.experiment_targeting is None
+ else {"experiment_targeting": scanner.experiment_targeting}
+ )
+ if scanner.scanner_type == ScannerType.EXPERIMENT:
+ # The experiment type keeps its scope in scanner_config, so a racing config edit must
+ # invalidate the stamp the way an experiment_targeting edit does for the other types.
+ guard_fields["scanner_config"] = scanner.scanner_config
updated = ReplayScanner.objects.filter(
pk=scanner.pk,
query=scanner.query,
sampling_rate=scanner.sampling_rate,
sampling_mode=scanner.sampling_mode,
- **(
- {"experiment_targeting__isnull": True}
- if scanner.experiment_targeting is None
- else {"experiment_targeting": scanner.experiment_targeting}
- ),
+ **guard_fields,
).update(estimated_monthly_observations=projection, estimated_at=estimated_at)
if updated:
scanner.estimated_monthly_observations = projection
@@ -346,8 +352,8 @@ def is_experiment_linkage_unresolved(scanner: ReplayScanner, error: Exception) -
reference; no launch heals that, so callers keep it on their error path. Both groups raise
the same DRF ValidationError type inside the recordings query, so this re-resolves the
linkage to tell them apart. The extra resolution runs on the failure path only."""
- targeting = scanner.experiment_targeting if isinstance(scanner.experiment_targeting, dict) else {}
- experiment_id = targeting.get("experiment_id")
+ scope = scanner.experiment_scope() or {}
+ experiment_id = scope.get("experiment_id")
if experiment_id is None:
return False
if isinstance(error, PermissionDenied):
@@ -358,7 +364,12 @@ def is_experiment_linkage_unresolved(scanner: ReplayScanner, error: Exception) -
from products.experiments.backend.facade.replay import resolve_exposure_linkage # noqa: PLC0415
try:
- resolve_exposure_linkage(scanner.team, experiment_id=experiment_id, variant=targeting.get("variant"))
+ resolve_exposure_linkage(
+ scanner.team,
+ experiment_id=experiment_id,
+ variant=scope.get("variant"),
+ variants=scope.get("variants"),
+ )
except ValidationError:
return True
except Exception:
diff --git a/products/replay_vision/backend/scanner_access.py b/products/replay_vision/backend/scanner_access.py
index b2bbf40dbf39..3c01fb0fef45 100644
--- a/products/replay_vision/backend/scanner_access.py
+++ b/products/replay_vision/backend/scanner_access.py
@@ -6,6 +6,7 @@ Also home to the two queries that read observations back across scanner origins,
appears once instead of at every reading call site."""
import uuid
+from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
from django.db.models import Q
@@ -15,7 +16,6 @@ from rest_framework.exceptions import NotFound, PermissionDenied
from posthog.models.team import Team
from products.access_control.backend.facade.user_access_control import UserAccessControl
-from products.experiments.backend.models.experiment import Experiment
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
if TYPE_CHECKING:
@@ -46,6 +46,17 @@ def scanners_for_reading_observations(team_id: int) -> "QuerySet[ReplayScanner]"
return ReplayScanner.all_origins.filter(team_id=team_id)
+def _accessible_experiment_ids(
+ access: UserAccessControl | None, team_id: int, experiment_ids: set[int] | None
+) -> set[int]:
+ """The experiments the caller may view, through the experiments facade. Empty input, empty result."""
+ # Deferred: the experiments replay facade pulls in the recordings query modules, which circle
+ # back into this package's importers.
+ from products.experiments.backend.facade.replay import accessible_experiment_ids # noqa: PLC0415
+
+ return accessible_experiment_ids(access, team_id, experiment_ids=experiment_ids)
+
+
def is_experiment_accessible(access: UserAccessControl | None, team_id: int, experiment_id: int) -> bool:
"""Whether the caller may view this experiment, filtered by object-level access (not just team).
@@ -54,19 +65,45 @@ def is_experiment_accessible(access: UserAccessControl | None, team_id: int, exp
than disclosing the experiment through a scanner surface. `access` is None only outside request
context (internal serialization), where there is no viewer to gate on, so it passes.
"""
- team_experiments = Experiment.objects.filter(team_id=team_id)
- accessible = access.filter_queryset_by_access_level(team_experiments) if access is not None else team_experiments
- return accessible.filter(id=experiment_id).exists()
+ return experiment_id in _accessible_experiment_ids(access, team_id, {experiment_id})
-def _accessible_experiment_ids(access: UserAccessControl, team_id: int, experiment_ids: set[int]) -> set[int]:
- """The subset of `experiment_ids` the caller may view, in one query. Empty input, empty result."""
- if not experiment_ids:
- return set()
- accessible = access.filter_queryset_by_access_level(
- Experiment.objects.filter(team_id=team_id, id__in=experiment_ids)
- )
- return set(accessible.values_list("id", flat=True))
+def scanner_experiment_scope_q(*, unrestricted: bool = False, experiment_ids: Iterable[int] = ()) -> Q:
+ """Scanner rows whose experiment scope matches: watching no experiment (`unrestricted`) and/or
+ watching one of `experiment_ids`, OR-combined.
+
+ Reads both scope stores: the experiment scanner type's `scanner_config` and the legacy
+ `experiment_targeting` column the other types use (see `ReplayScanner.experiment_scope`).
+ Phrased positively with `isnull` because on a nullable JSON path `.exclude` negates to NULL and
+ wrongly drops unscoped rows. The lookup keys are written as literals (not composed from a
+ variable) so the ORM-field-injection lint sees they're not caller input.
+ """
+ q = Q()
+ if unrestricted:
+ q |= Q(
+ experiment_targeting__experiment_id__isnull=True,
+ scanner_config__experiment_id__isnull=True,
+ )
+ ids = list(experiment_ids)
+ if ids:
+ q |= Q(experiment_targeting__experiment_id__in=ids) | Q(scanner_config__experiment_id__in=ids)
+ return q
+
+
+def snapshot_experiment_scope_q(*, unrestricted: bool = False, experiment_ids: Iterable[int] = ()) -> Q:
+ """`scanner_experiment_scope_q` for observation rows, over the frozen `scanner_snapshot`."""
+ q = Q()
+ if unrestricted:
+ q |= Q(
+ scanner_snapshot__experiment_targeting__experiment_id__isnull=True,
+ scanner_snapshot__scanner_config__experiment_id__isnull=True,
+ )
+ ids = list(experiment_ids)
+ if ids:
+ q |= Q(scanner_snapshot__experiment_targeting__experiment_id__in=ids) | Q(
+ scanner_snapshot__scanner_config__experiment_id__in=ids
+ )
+ return q
def accessible_observations(
@@ -83,18 +120,10 @@ def accessible_observations(
The accessible set comes from the team's experiments, which are few and indexed. The snapshot
path has no index, so reading the ids off the observations instead scans the whole scanner or team.
"""
- accessible = set(
- access.filter_queryset_by_access_level(Experiment.objects.filter(team_id=team_id)).values_list("id", flat=True)
- )
- # Keep rows whose snapshot names no experiment (untargeted, unrestricted) OR an accessible one.
- # Phrased positively rather than `.exclude(path__in=inaccessible)`: on a nullable JSON path, exclude
- # negates to `NOT (path IN (...))`, which is NULL — and therefore false — for untargeted rows, so it
- # would wrongly drop them. `isnull` OR membership is null-safe. The lookup keys are written as
- # literals (not composed from a variable) so the ORM-field-injection lint sees they're not caller input.
- return observations.filter(
- Q(scanner_snapshot__experiment_targeting__experiment_id__isnull=True)
- | Q(scanner_snapshot__experiment_targeting__experiment_id__in=accessible)
- )
+ accessible = _accessible_experiment_ids(access, team_id, None)
+ # Keep rows whose snapshot names no experiment (untargeted, unrestricted) OR an accessible one,
+ # whichever snapshot store names it.
+ return observations.filter(snapshot_experiment_scope_q(unrestricted=True, experiment_ids=accessible))
def readable_observation_scanner_ids(access: UserAccessControl, team_id: int) -> list[uuid.UUID]:
@@ -108,15 +137,15 @@ def readable_observation_scanner_ids(access: UserAccessControl, team_id: int) ->
"""
scanners = list(
access.filter_queryset_by_access_level(scanners_for_reading_observations(team_id)).only(
- "id", "experiment_targeting"
+ "id", "scanner_type", "scanner_config", "experiment_targeting"
)
)
- targeted = {eid for s in scanners if (eid := (s.experiment_targeting or {}).get("experiment_id")) is not None}
+ targeted = {eid for s in scanners if (eid := (s.experiment_scope() or {}).get("experiment_id")) is not None}
accessible = _accessible_experiment_ids(access, team_id, targeted)
return [
s.id
for s in scanners
- if (eid := (s.experiment_targeting or {}).get("experiment_id")) is None or eid in accessible
+ if (eid := (s.experiment_scope() or {}).get("experiment_id")) is None or eid in accessible
]
@@ -127,10 +156,10 @@ def can_read_targeted_experiment(access: UserAccessControl, team_id: int, scanne
reads as not-found. Row-level history within an accessible scanner is gated separately by
`accessible_observations`, which follows each row's snapshot. A scanner with no targeting passes.
"""
- targeting = scanner.experiment_targeting
- if not targeting or targeting.get("experiment_id") is None:
+ scope = scanner.experiment_scope()
+ if not scope or scope.get("experiment_id") is None:
return True
- return is_experiment_accessible(access, team_id, targeting["experiment_id"])
+ return is_experiment_accessible(access, team_id, scope["experiment_id"])
def scanner_for_reading_observations(team_id: int, scanner_id: "str | uuid.UUID") -> ReplayScanner | None:
diff --git a/products/replay_vision/backend/scanner_config.py b/products/replay_vision/backend/scanner_config.py
index 9451f6154e2b..acdd366f0847 100644
--- a/products/replay_vision/backend/scanner_config.py
+++ b/products/replay_vision/backend/scanner_config.py
@@ -45,6 +45,21 @@ def scanner_config_error(scanner_type: ScannerType, scanner_config: Any) -> str
if slug in slugged:
return f"Categories must be unique: '{slugged[slug]}' and '{t}' are the same category."
slugged[slug] = t
+ if scanner_type == ScannerType.EXPERIMENT:
+ experiment_id = scanner_config.get("experiment_id")
+ if isinstance(experiment_id, bool) or not isinstance(experiment_id, int) or experiment_id < 1:
+ return "Experiment is required."
+ variants = scanner_config.get("variants")
+ if variants is not None:
+ if not isinstance(variants, list) or not variants:
+ return "Variants must be a non-empty list, or null to watch every variant."
+ if any(not isinstance(v, str) or not v.strip() for v in variants):
+ return "Variants can't be blank."
+ if len(set(variants)) != len(variants):
+ return "Variants must be unique."
+ balance_variants = scanner_config.get("balance_variants")
+ if balance_variants is not None and not isinstance(balance_variants, bool):
+ return "balance_variants must be true or false."
if scanner_type == ScannerType.SCORER:
scale = scanner_config.get("scale")
if not isinstance(scale, dict):
diff --git a/products/replay_vision/backend/scout_writes.py b/products/replay_vision/backend/scout_writes.py
index f2e7fa5349b3..2bef9e2c1024 100644
--- a/products/replay_vision/backend/scout_writes.py
+++ b/products/replay_vision/backend/scout_writes.py
@@ -14,7 +14,7 @@ from typing import Any
from rest_framework.exceptions import PermissionDenied, ValidationError
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType, config_experiment_scope
DELETE_REFUSED = "Scouts cannot delete scanners. Set `enabled: false` to stop this one."
@@ -96,6 +96,9 @@ def check_scout_scanner_credit_limit(
turning_on = attrs.get("enabled") and not instance.enabled
cost_fields = {"query", "sampling_rate", "sampling_mode", "provider", "model", "experiment_targeting"}
changes_cost = any(field in attrs and attrs[field] != getattr(instance, field) for field in cost_fields)
+ if not changes_cost and instance.scanner_type == ScannerType.EXPERIMENT and "scanner_config" in attrs:
+ # The experiment type keeps its scope (and therefore its volume) in scanner_config.
+ changes_cost = config_experiment_scope(attrs["scanner_config"]) != instance.experiment_scope()
changes_enabled_cost = attrs.get("enabled", instance.enabled) and changes_cost
credit_limit = attrs.get("credit_limit", instance.credit_limit)
if credit_limit is None:
diff --git a/products/replay_vision/backend/search_suggestions.py b/products/replay_vision/backend/search_suggestions.py
index 19022cee3e94..4943da231b4d 100644
--- a/products/replay_vision/backend/search_suggestions.py
+++ b/products/replay_vision/backend/search_suggestions.py
@@ -34,6 +34,7 @@ from products.replay_vision.backend.models.replay_observation import Observation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
from products.replay_vision.backend.models.team_replay_vision_config import TeamReplayVisionConfig
from products.replay_vision.backend.observation_formatting import describe_output, explanation_text, read_output
+from products.replay_vision.backend.scanner_access import scanner_experiment_scope_q, snapshot_experiment_scope_q
from ee.hogai.utils.untrusted import neutralize_markup
@@ -204,17 +205,15 @@ def stale_suggestion_candidates(limit: int) -> QuerySet[ReplayScanner]:
def _team_rows() -> QuerySet[ReplayObservation]:
"""Observations that may feed a team's phrases. A row captured while its scanner targeted an experiment stays
readable only to that experiment's viewers, even after the targeting is removed, so it never feeds them."""
- return ReplayObservation.objects.filter(
- status=ObservationStatus.SUCCEEDED, scanner_snapshot__experiment_targeting__experiment_id__isnull=True
+ return ReplayObservation.objects.filter(status=ObservationStatus.SUCCEEDED).filter(
+ snapshot_experiment_scope_q(unrestricted=True)
)
def _team_sources() -> QuerySet[ReplayScanner]:
"""Enabled scanners that may feed a team's cross-scanner phrases. An experiment-targeted scanner's
observations are readable per experiment, so they never feed phrases every viewer of the team sees."""
- return ReplayScanner.objects.filter(enabled=True).filter(
- Q(experiment_targeting__isnull=True) | Q(experiment_targeting={})
- )
+ return ReplayScanner.objects.filter(enabled=True).filter(scanner_experiment_scope_q(unrestricted=True))
def stale_team_candidates(limit: int) -> list[int]:
@@ -344,10 +343,12 @@ def _recent_observation_samples(scanner: ReplayScanner) -> tuple[list[str], dt.d
Rows are gated like `scanner_access.accessible_observations`: a viewer of this scanner can read its
current experiment, so only observations whose snapshot names no experiment or that same one may feed
phrases everyone who opens the scanner sees."""
- current_experiment = (scanner.experiment_targeting or {}).get("experiment_id")
+ current_experiment = (scanner.experiment_scope() or {}).get("experiment_id")
rows = ReplayObservation.objects.filter(scanner_id=scanner.id, status=ObservationStatus.SUCCEEDED).filter(
- Q(scanner_snapshot__experiment_targeting__experiment_id__isnull=True)
- | Q(scanner_snapshot__experiment_targeting__experiment_id=current_experiment)
+ snapshot_experiment_scope_q(
+ unrestricted=True,
+ experiment_ids=[current_experiment] if current_experiment is not None else (),
+ )
)
if scanner.search_suggestions_watermark is not None:
rows = rows.filter(completed_at__gt=scanner.search_suggestions_watermark)
diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.py
index 305b89abfcaf..6b785eada348 100644
--- a/products/replay_vision/backend/temporal/activities/backfill.py
+++ b/products/replay_vision/backend/temporal/activities/backfill.py
@@ -166,7 +166,7 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> F
raise ApplicationError(
f"ReplayScannerBackfill {inputs.backfill_id} has malformed frozen query: {exc}", non_retryable=True
) from exc
- query = apply_experiment_targeting(query, snapshot.experiment_targeting)
+ query = apply_experiment_targeting(query, snapshot.experiment_scope())
candidate_query = WindowedCandidateQuery(
team=backfill.team,
diff --git a/products/replay_vision/backend/temporal/scanners/__init__.py b/products/replay_vision/backend/temporal/scanners/__init__.py
index bb844d27b579..3ed4aac20a70 100644
--- a/products/replay_vision/backend/temporal/scanners/__init__.py
+++ b/products/replay_vision/backend/temporal/scanners/__init__.py
@@ -8,6 +8,7 @@ from temporalio.exceptions import ApplicationError
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
from products.replay_vision.backend.temporal.scanners.base import BaseScanner, BaseScannerOutput
from products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutput, ClassifierScanner
+from products.replay_vision.backend.temporal.scanners.experiment import ExperimentOutput, ExperimentScanner
from products.replay_vision.backend.temporal.scanners.monitor import MonitorLlmResponse, MonitorOutput, MonitorScanner
from products.replay_vision.backend.temporal.scanners.scorer import ScorerOutput, ScorerScanner, ScoreScale
from products.replay_vision.backend.temporal.scanners.summarizer import (
@@ -18,7 +19,7 @@ from products.replay_vision.backend.temporal.scanners.summarizer import (
from products.replay_vision.backend.temporal.types import AnyScannerOutput, ScannerSnapshot
AnyScanner = Annotated[
- ClassifierScanner | MonitorScanner | ScorerScanner | SummarizerScanner,
+ ClassifierScanner | ExperimentScanner | MonitorScanner | ScorerScanner | SummarizerScanner,
Field(discriminator="scanner_type"),
]
_SCANNER_ADAPTER: TypeAdapter[AnyScanner] = TypeAdapter(AnyScanner)
@@ -72,6 +73,8 @@ __all__ = [
"BaseScannerOutput",
"ClassifierScanner",
"ClassifierOutput",
+ "ExperimentScanner",
+ "ExperimentOutput",
"MonitorScanner",
"MonitorLlmResponse",
"MonitorOutput",
diff --git a/products/replay_vision/backend/temporal/scanners/experiment.py b/products/replay_vision/backend/temporal/scanners/experiment.py
new file mode 100644
index 000000000000..30b861050527
--- /dev/null
+++ b/products/replay_vision/backend/temporal/scanners/experiment.py
@@ -0,0 +1,55 @@
+"""Experiment scanner: a summarizer that watches one experiment's exposed sessions.
+
+The type is the summarizer with experiment context: the prompt names the experiment, the change
+under test, and the session's variant, so the summary can speak to the change rather than guess
+at it. Which sessions it watches comes from `experiment_id`/`variants` in the scanner config,
+never from the persisted recordings query (see `ReplayScanner.experiment_scope`).
+"""
+
+from typing import Any, ClassVar, Literal
+
+from pydantic import Field
+
+from products.replay_vision.backend.models.replay_scanner import ScannerType
+from products.replay_vision.backend.temporal.scanners.base import BaseScannerOutput
+from products.replay_vision.backend.temporal.scanners.summarizer import SummarizerOutput, SummarizerScanner
+
+
+class ExperimentOutput(SummarizerOutput, frozen=True):
+ """Persisted output: the summarizer's shape under its own discriminator, so search and the
+ summary readers work unchanged. The session's variant is not model output; the workflow
+ stores it beside `model_output` in `scanner_result`."""
+
+ scanner_type: Literal[ScannerType.EXPERIMENT] = ScannerType.EXPERIMENT # type: ignore[assignment]
+
+
+class ExperimentScanner(SummarizerScanner, frozen=True):
+ scanner_type: Literal[ScannerType.EXPERIMENT] = ScannerType.EXPERIMENT # type: ignore[assignment]
+ core_step_template: ClassVar[str] = "experiment_step.jinja"
+ output_cls: ClassVar[type[BaseScannerOutput]] = ExperimentOutput
+ experiment_id: int = Field(ge=1, description="The experiment this scanner watches.")
+ variants: list[str] | None = Field(
+ default=None,
+ min_length=1,
+ description="Variant keys to watch; null means every variant.",
+ )
+ balance_variants: bool = Field(
+ default=True,
+ description="Sample each watched variant about evenly instead of proportionally to rollout.",
+ )
+ # Scan-time context rather than persisted config, injected per scan by the apply workflow
+ # (like the classifier's `known_freeform_tags`). `exclude=True` keeps both out of dumps, so
+ # they can never leak into a stored scanner_config or snapshot.
+ experiment_context: dict[str, Any] | None = Field(default=None, exclude=True)
+ session_variant: str | None = Field(default=None, exclude=True)
+ session_fields: ClassVar[frozenset[str]] = SummarizerScanner.session_fields | {
+ "experiment_context",
+ "session_variant",
+ }
+
+ def prompt_context(self) -> dict[str, Any]:
+ return {
+ **super().prompt_context(),
+ "experiment": self.experiment_context,
+ "session_variant": self.session_variant,
+ }
diff --git a/products/replay_vision/backend/temporal/scanners/prompts/experiment_step.jinja b/products/replay_vision/backend/temporal/scanners/prompts/experiment_step.jinja
new file mode 100644
index 000000000000..8fc89eebf74c
--- /dev/null
+++ b/products/replay_vision/backend/temporal/scanners/prompts/experiment_step.jinja
@@ -0,0 +1,22 @@
+{% from "_macros.jinja" import cite_in, pick_media, rate_notability %}Summarize this session as one exposed session of an A/B experiment.{% if experiment %}
+
+The experiment under test:
+- Name: {{ experiment.name }}{% if experiment.description %}
+- Hypothesis: {{ experiment.description }}{% endif %}
+- Feature flag: {{ experiment.feature_flag_key }}
+- Variants:{% for variant in experiment.variants %}
+ - `{{ variant.key }}` ({{ variant.rollout_percentage }}% rollout){% if variant.description %}: {{ variant.description }}{% endif %}{% endfor %}{% if experiment.primary_metric_names %}
+- Primary metrics: {{ experiment.primary_metric_names | join(', ') }}{% endif %}{% endif %}{% if session_variant %}
+
+This session's user was exposed to the `{{ session_variant }}` variant. Judge the session with that variant's experience in mind: describe how the user moves through the surface the experiment changes, and whether the variant's change helps, hinders, or goes unnoticed. Never guess at what another variant would have shown.{% endif %}{% if user_prompt %}
+
+Additional context from the team operating the product being recorded:
+{{ user_prompt }}{% endif %}
+
+`title` is a short, plain-text headline, up to 120 characters (citations go in `summary`, not the title).{% if user_prompt %} If the context above specifies a naming convention or format for observations, `title` must follow it exactly (an observation's name is its title).{% endif %} `summary` should be {{ length_guidance }}. Lead the summary with what happened around the experiment's surface; general session context comes after.
+
+{{ cite_in('summary') }}
+
+{{ rate_notability() }}
+
+{{ pick_media() }}
diff --git a/products/replay_vision/backend/temporal/snapshots.py b/products/replay_vision/backend/temporal/snapshots.py
index 8828a9a3ca7f..0e2b846535d8 100644
--- a/products/replay_vision/backend/temporal/snapshots.py
+++ b/products/replay_vision/backend/temporal/snapshots.py
@@ -11,7 +11,7 @@ from uuid import UUID
from pydantic import BaseModel, Field, ValidationError
from temporalio.exceptions import ApplicationError
-from products.replay_vision.backend.models.replay_scanner import ScannerType
+from products.replay_vision.backend.models.replay_scanner import ScannerType, config_experiment_scope
if TYPE_CHECKING:
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
@@ -40,6 +40,13 @@ class ScannerSnapshot(BaseModel, frozen=True):
# so a retired mode never breaks old-row loads.
verify_positives: str = "off"
+ def experiment_scope(self) -> dict[str, Any] | None:
+ """The experiment this scan watched, wherever the snapshot stores it; mirrors
+ `ReplayScanner.experiment_scope`."""
+ if self.scanner_type == ScannerType.EXPERIMENT:
+ return config_experiment_scope(self.scanner_config)
+ return self.experiment_targeting
+
@classmethod
def from_scanner(cls, scanner: "ReplayScanner") -> "ScannerSnapshot":
"""The single scanner→snapshot field mapping; every snapshot producer must build through here."""
diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.py
index 4da5693ab950..af812bf4aa71 100644
--- a/products/replay_vision/backend/temporal/types.py
+++ b/products/replay_vision/backend/temporal/types.py
@@ -9,6 +9,7 @@ from products.replay_vision.backend.models.replay_scanner import ScannerType
from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTH
from products.replay_vision.backend.temporal.scanners.base import SignalFinding
from products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutput
+from products.replay_vision.backend.temporal.scanners.experiment import ExperimentOutput
from products.replay_vision.backend.temporal.scanners.monitor import MonitorOutput, MonitorVerdict
from products.replay_vision.backend.temporal.scanners.scorer import ScorerOutput
from products.replay_vision.backend.temporal.scanners.summarizer import SummarizerOutput
@@ -18,7 +19,7 @@ from products.replay_vision.backend.temporal.snapshots import (
)
AnyScannerOutput = Annotated[
- ClassifierOutput | MonitorOutput | ScorerOutput | SummarizerOutput,
+ ClassifierOutput | ExperimentOutput | MonitorOutput | ScorerOutput | SummarizerOutput,
Field(discriminator="scanner_type"),
]
diff --git a/products/replay_vision/backend/tests/helpers.py b/products/replay_vision/backend/tests/helpers.py
index 75b8c1b49fba..41aed8f00a80 100644
--- a/products/replay_vision/backend/tests/helpers.py
+++ b/products/replay_vision/backend/tests/helpers.py
@@ -54,11 +54,27 @@ def seed_scanner_spend(scanner: ReplayScanner, credits: int, *, observations: in
)
-def create_experiment(team: Team, flag_key: str, created_by: User | None = None) -> Experiment:
- """A launched-enough experiment with a multivariate flag, for targeting tests."""
- flag = FeatureFlag.objects.create(
+def create_experiment(
+ team: Team,
+ flag_key: str,
+ created_by: User | None = None,
+ *,
+ launched: bool = False,
+ variants: list[str] | None = None,
+) -> Experiment:
+ """An experiment for targeting tests. `launched` plus `variants` makes it resolvable by
+ `resolve_exposure_linkage`, which the experiment scanner type's write path requires."""
+ filters: dict[str, Any] = {"groups": [{"properties": [], "rollout_percentage": 100}]}
+ if variants:
+ filters["multivariate"] = {
+ "variants": [{"key": key, "rollout_percentage": 100 // len(variants)} for key in variants]
+ }
+ flag = FeatureFlag.objects.create(team=team, key=flag_key, filters=filters)
+ return Experiment.objects.create(
team=team,
- key=flag_key,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ name=f"exp-{flag_key}",
+ feature_flag=flag,
+ created_by=created_by,
+ start_date=timezone.now() if launched else None,
+ exposure_criteria={},
)
- return Experiment.objects.create(team=team, name=f"exp-{flag_key}", feature_flag=flag, created_by=created_by)
diff --git a/products/replay_vision/backend/tests/test_access_control.py b/products/replay_vision/backend/tests/test_access_control.py
index e5a95c7014b7..a3cd999d7fb3 100644
--- a/products/replay_vision/backend/tests/test_access_control.py
+++ b/products/replay_vision/backend/tests/test_access_control.py
@@ -4,6 +4,8 @@ from django.db import connection
from django.test.utils import CaptureQueriesContext
from django.utils import timezone
+from parameterized import parameterized
+
from posthog.constants import AvailableFeature
from posthog.models import OrganizationMembership, PersonalAPIKey, User
from posthog.models.utils import generate_random_token_personal, hash_key_value
@@ -13,6 +15,7 @@ from products.access_control.backend.models.access_control import AccessControl
from products.exports.backend.models.exported_asset import ExportedAsset
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMedia
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
from products.replay_vision.backend.tests.helpers import create_experiment, snapshot_for
from products.replay_vision.backend.tests.test_api import _VisionAPITestCase
@@ -199,6 +202,17 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
self.assertEqual(self.client.post(f"{url}estimate/", window, format="json").status_code, 403)
self.assertEqual(self.client.post(url, window, format="json").status_code, 403)
+ def _create_experiment_scoped_scanner(self, name: str, experiment_id: int, location: str) -> ReplayScanner:
+ # The two places a scanner's experiment scope can live: the legacy column on the four
+ # original types, and scanner_config on the experiment type.
+ if location == "column":
+ return self._create_scanner(name=name, experiment_targeting={"experiment_id": experiment_id})
+ return self._create_scanner(
+ name=name,
+ scanner_type=ScannerType.EXPERIMENT,
+ scanner_config={"prompt": "p", "experiment_id": experiment_id},
+ )
+
def test_experiment_targeting_rejects_an_experiment_the_caller_cannot_view(self) -> None:
# A scanner-editor without experiment access must not be able to confirm an experiment's
# existence via the targeting validation response; a denied experiment reads as not-found.
@@ -273,6 +287,109 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
scanner.refresh_from_db()
self.assertIsNone(scanner.experiment_targeting)
+ def test_experiment_scanner_create_rejects_a_denied_experiment(self) -> None:
+ # The experiment type keeps its scope in scanner_config, a write path the
+ # experiment_targeting field's access check never sees; the config path must gate the same way.
+ experiment = create_experiment(self.team, "denied-flag", launched=True, variants=["control", "test"])
+ self._set_resource_default("experiment", "none")
+ self._grant_object_access(self.other_user, "experiment", str(experiment.id), "none")
+
+ self.client.force_login(self.other_user)
+ resp = self.client.post(
+ self.scanners_url,
+ data={
+ "name": "config-denied",
+ "scanner_type": "experiment",
+ "scanner_config": {"prompt": "p", "experiment_id": experiment.id},
+ "model": "gemini-3.8-flash",
+ },
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 400, resp.json())
+ self.assertEqual(resp.json()["attr"], "scanner_config")
+
+ def test_experiment_scanner_config_is_partially_hidden_from_a_denied_viewer(self) -> None:
+ # Only the experiment keys are hidden, so the rest of the config (prompt, length) stays
+ # readable; hiding the whole config would break the editor for a scanner-level viewer.
+ experiment = create_experiment(self.team, "hidden-flag", created_by=self.user)
+ config = {"prompt": "p", "experiment_id": experiment.id, "variants": ["test"]}
+ scanner = self._create_scanner(name="config-scoped", scanner_type=ScannerType.EXPERIMENT, scanner_config=config)
+ self._set_resource_default("replay_scanner", "viewer")
+ self._set_resource_default("experiment", "none")
+ self._grant_object_access(self.other_user, "experiment", str(experiment.id), "none")
+
+ self.client.force_login(self.other_user)
+ resp = self.client.get(f"{self.scanners_url}{scanner.id}/")
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertEqual(resp.json()["scanner_config"], {"prompt": "p"})
+
+ # The creator, who can view the experiment, still sees the whole config.
+ self.client.force_login(self.user)
+ self.assertEqual(self.client.get(f"{self.scanners_url}{scanner.id}/").json()["scanner_config"], config)
+
+ def test_config_writes_by_an_editor_denied_the_experiment_read_as_not_found(self) -> None:
+ # The scan injects the experiment's own description into the prompt, so a prompt written by
+ # a caller who can't view the experiment could instruct the model to copy that private text
+ # into output on the team-visible $recording_observed event. A viewing editor stays the
+ # control: the redacted round-trip (scope keys omitted) still restores the stored scope.
+ experiment = create_experiment(self.team, "hidden-flag", created_by=self.user)
+ config = {"prompt": "p", "experiment_id": experiment.id, "variants": ["test"]}
+ scanner = self._create_scanner(name="config-scoped", scanner_type=ScannerType.EXPERIMENT, scanner_config=config)
+ self._set_resource_default("replay_scanner", "editor")
+ self._set_resource_default("experiment", "none")
+ self._grant_object_access(self.other_user, "experiment", str(experiment.id), "none")
+
+ self.client.force_login(self.other_user)
+ resp = self.client.patch(
+ f"{self.scanners_url}{scanner.id}/",
+ data={"scanner_config": {"prompt": "sharper prompt"}},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 400, resp.json())
+ self.assertIn("Experiment not found", str(resp.json()))
+ scanner.refresh_from_db()
+ self.assertEqual(scanner.scanner_config, config)
+
+ # The creator can view the experiment, so their redacted-shape save restores the scope.
+ self.client.force_login(self.user)
+ resp = self.client.patch(
+ f"{self.scanners_url}{scanner.id}/",
+ data={"scanner_config": {"prompt": "sharper prompt", "variants": ["test"]}},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 200, resp.json())
+ scanner.refresh_from_db()
+ self.assertEqual(
+ scanner.scanner_config,
+ {"prompt": "sharper prompt", "experiment_id": experiment.id, "variants": ["test"]},
+ )
+
+ def test_explicit_scope_from_a_denied_editor_never_confirms_the_hidden_values(self) -> None:
+ # The mismatch error ("fixed after creation") differing from the match path would let a
+ # denied editor enumerate the redacted experiment id (or variants) by probing PATCHes, so
+ # every explicit scope key must get the identical not-found answer.
+ experiment = create_experiment(self.team, "hidden-flag", created_by=self.user)
+ config = {"prompt": "p", "experiment_id": experiment.id, "variants": ["test"]}
+ scanner = self._create_scanner(name="probe-target", scanner_type=ScannerType.EXPERIMENT, scanner_config=config)
+ self._set_resource_default("replay_scanner", "editor")
+ self._set_resource_default("experiment", "none")
+ self._grant_object_access(self.other_user, "experiment", str(experiment.id), "none")
+
+ self.client.force_login(self.other_user)
+ probes = [
+ {"prompt": "p", "experiment_id": experiment.id},
+ {"prompt": "p", "experiment_id": experiment.id + 1},
+ {"prompt": "p", "variants": ["test"]},
+ ]
+ bodies = []
+ for probe in probes:
+ resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data={"scanner_config": probe}, format="json")
+ self.assertEqual(resp.status_code, 400, resp.json())
+ bodies.append(resp.json())
+ self.assertEqual(len({str(b) for b in bodies}), 1)
+ scanner.refresh_from_db()
+ self.assertEqual(scanner.scanner_config, config)
+
def test_estimate_treats_a_denied_experiment_targeting_as_not_found(self) -> None:
# The query runner's own access check answers a denied experiment with a 403, which would
# confirm the hidden id exists; the endpoint must answer 400 not-found, like the scanner
@@ -290,13 +407,13 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
self.assertEqual(resp.status_code, 400, resp.json())
self.assertEqual(resp.json()["attr"], "experiment_targeting")
- def test_experiment_id_filter_returns_no_matches_for_an_inaccessible_experiment(self) -> None:
+ @parameterized.expand([("column",), ("config",)])
+ def test_experiment_id_filter_returns_no_matches_for_an_inaccessible_experiment(self, location: str) -> None:
# Guards the ?experiment_id= disclosure: a scanner-viewer who can't access the experiment must
# not confirm a scanner targets it via the filter's match count. Distinct code path from the
# serializer redaction above — the scanner is hidden from the list entirely, not just nulled.
experiment = create_experiment(self.team, "hidden-flag", created_by=self.user)
- targeting = {"experiment_id": experiment.id, "variant": "test"}
- self._create_scanner(name="targeted", experiment_targeting=targeting)
+ self._create_experiment_scoped_scanner("targeted", experiment.id, location)
self._set_resource_default("replay_scanner", "viewer")
self._set_resource_default("experiment", "none")
self._grant_object_access(self.other_user, "experiment", str(experiment.id), "none")
@@ -322,7 +439,8 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
self.assertEqual(resp.status_code, 200, resp.json())
self.assertEqual([s["name"] for s in resp.json()["results"]], ["targeted"])
- def test_observations_of_a_denied_experiment_scanner_read_as_not_found(self) -> None:
+ @parameterized.expand([("column",), ("config",)])
+ def test_observations_of_a_denied_experiment_scanner_read_as_not_found(self, location: str) -> None:
# An experiment scanner's observations are the experiment's exposed sessions, so scanner +
# session_recording access is not enough to read them: a caller denied the experiment must
# not learn which sessions and people were exposed. Reads as not-found, not 403, matching
@@ -332,7 +450,7 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
self._set_resource_default("session_recording", "editor")
self._set_resource_default("experiment", "none")
self._grant_object_access(self.other_user, "experiment", str(experiment.id), "none")
- targeted = self._create_scanner(name="targeted", experiment_targeting={"experiment_id": experiment.id})
+ targeted = self._create_experiment_scoped_scanner("targeted", experiment.id, location)
plain = self._create_scanner(name="plain")
# Observations carry the scanner's snapshot, so their experiment targeting is recorded on the row.
ReplayObservation.objects.create(
@@ -356,6 +474,27 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
self.assertEqual(dock_resp.status_code, 200, dock_resp.json())
self.assertEqual(dock_resp.json()["results"], [])
+ def test_prompt_suggestions_of_a_denied_experiment_scanner_read_as_not_found(self) -> None:
+ # Suggestions and their evaluations quote the scanner's observations (session ids, output
+ # text), so without this gate a caller denied the experiment could read that content — and
+ # act on suggestions — through the suggestions endpoints alone.
+ experiment = create_experiment(self.team, "hidden-flag")
+ self._set_resource_default("replay_scanner", "editor")
+ self._set_resource_default("session_recording", "editor")
+ self._set_resource_default("experiment", "none")
+ self._grant_object_access(self.other_user, "experiment", str(experiment.id), "none")
+ targeted = self._create_experiment_scoped_scanner("targeted", experiment.id, "config")
+ plain = self._create_scanner(name="plain")
+
+ self.client.force_login(self.other_user)
+ targeted_url = f"{self.scanners_url}{targeted.id}/prompt_suggestions/"
+ self.assertEqual(self.client.get(f"{targeted_url}current/").status_code, 404)
+ self.assertEqual(self.client.post(f"{targeted_url}generate/").status_code, 404)
+
+ # Same access, non-targeted scanner: the experiment gate must not have widened to a blanket block.
+ plain_resp = self.client.get(f"{self.scanners_url}{plain.id}/prompt_suggestions/current/")
+ self.assertEqual(plain_resp.status_code, 200, plain_resp.json())
+
def test_retargeting_a_scanner_does_not_expose_historical_observations(self) -> None:
# An observation's population is fixed at creation, so the read gate follows the experiment in
# each row's snapshot, not the scanner's current targeting. Removing or changing targeting must
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 87e8bc092ba0..12afd7df6bc7 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -338,6 +338,85 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
)
self.assertEqual(resp.status_code, 201, resp.json())
+ def test_experiment_scanner_create_validates_the_experiment(self) -> None:
+ # The type is unusable without a resolvable exposed population, so the write path must
+ # refuse a draft experiment and an unknown variant with the linkage's own message, and
+ # must keep the experiment out of the legacy targeting column.
+ launched = create_experiment(self.team, "launched-flag", launched=True, variants=["control", "test"])
+ draft = create_experiment(self.team, "draft-flag", variants=["control", "test"])
+
+ def post(name: str, experiment_id: int, **config_overrides: Any) -> Any:
+ return self.client.post(
+ self.scanners_url,
+ data={
+ "name": name,
+ "scanner_type": ScannerType.EXPERIMENT,
+ "scanner_config": {"prompt": "p", "experiment_id": experiment_id, **config_overrides},
+ "model": ScannerModel.GEMINI_3_8_FLASH,
+ },
+ format="json",
+ )
+
+ draft_resp = post("draft-scanner", draft.id)
+ self.assertEqual(draft_resp.status_code, 400, draft_resp.json())
+ self.assertIn("hasn't launched", draft_resp.json()["detail"])
+
+ unknown_variant = post("unknown-variant", launched.id, variants=["control", "nope"])
+ self.assertEqual(unknown_variant.status_code, 400, unknown_variant.json())
+ self.assertIn("not a variant", unknown_variant.json()["detail"])
+
+ valid = post("experiment-scanner", launched.id, variants=["test"])
+ self.assertEqual(valid.status_code, 201, valid.json())
+ scanner = ReplayScanner.objects.get(id=valid.json()["id"])
+ self.assertEqual(scanner.experiment_scope(), {"experiment_id": launched.id, "variants": ["test"]})
+ exposure = scanner.targeted_recordings_query().experiment_exposure
+ assert exposure is not None
+ self.assertEqual(exposure.variants, ["test"])
+
+ with_column = self.client.post(
+ self.scanners_url,
+ data={
+ "name": "column-on-experiment-type",
+ "scanner_type": ScannerType.EXPERIMENT,
+ "scanner_config": {"prompt": "p", "experiment_id": launched.id},
+ "model": ScannerModel.GEMINI_3_8_FLASH,
+ "experiment_targeting": {"experiment_id": launched.id},
+ },
+ format="json",
+ )
+ self.assertEqual(with_column.status_code, 400, with_column.json())
+ self.assertEqual(with_column.json()["attr"], "experiment_targeting")
+
+ def test_experiment_scanner_experiment_is_fixed_after_creation(self) -> None:
+ # Retargeting would mix two experiments' populations under one scanner's history and
+ # readouts, so it is a new scanner, not an edit; `variants` stays editable.
+ watched = create_experiment(self.team, "watched-flag", launched=True, variants=["control", "test"])
+ other = create_experiment(self.team, "other-flag", launched=True, variants=["control", "test"])
+ scanner = self._create_scanner(
+ name="fixed-experiment",
+ scanner_type=ScannerType.EXPERIMENT,
+ scanner_config={"prompt": "p", "experiment_id": watched.id},
+ )
+
+ retarget = self.client.patch(
+ f"{self.scanners_url}{scanner.id}/",
+ data={"scanner_config": {"prompt": "p", "experiment_id": other.id}},
+ format="json",
+ )
+ self.assertEqual(retarget.status_code, 400, retarget.json())
+ self.assertIn("fixed after creation", retarget.json()["detail"])
+
+ narrowed = self.client.patch(
+ f"{self.scanners_url}{scanner.id}/",
+ data={"scanner_config": {"prompt": "sharper", "variants": ["test"]}},
+ format="json",
+ )
+ self.assertEqual(narrowed.status_code, 200, narrowed.json())
+ scanner.refresh_from_db()
+ self.assertEqual(
+ scanner.scanner_config, {"prompt": "sharper", "variants": ["test"], "experiment_id": watched.id}
+ )
+
@parameterized.expand(
[
("classifier_without_tags", ScannerType.CLASSIFIER, {"prompt": "p"}),
@@ -425,6 +504,24 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
{"prompt": "p"},
"Scale is required.",
),
+ (
+ "experiment_missing_experiment",
+ ScannerType.EXPERIMENT,
+ {"prompt": "p"},
+ "Experiment is required.",
+ ),
+ (
+ "experiment_empty_variants",
+ ScannerType.EXPERIMENT,
+ {"prompt": "p", "experiment_id": 1, "variants": []},
+ "Variants must be a non-empty list, or null to watch every variant.",
+ ),
+ (
+ "experiment_duplicate_variants",
+ ScannerType.EXPERIMENT,
+ {"prompt": "p", "experiment_id": 1, "variants": ["test", "test"]},
+ "Variants must be unique.",
+ ),
(
"not_a_dict",
ScannerType.MONITOR,
@@ -461,6 +558,13 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
{"prompt": "p", "chapter_target": 50},
"Unknown scanner configuration keys: chapter_target.",
),
+ # A saved value would fake the variant or hypothesis in every scan's prompt.
+ (
+ "experiment_scan_time_keys",
+ ScannerType.EXPERIMENT,
+ {"prompt": "p", "experiment_id": 1, "session_variant": "test", "experiment_context": {}},
+ "Unknown scanner configuration keys: experiment_context, session_variant.",
+ ),
]
)
def test_validation_returns_specific_message_per_invalid_config(
@@ -4167,6 +4271,16 @@ class TestInlineScanAction(_VisionAPITestCase):
completed_at=timezone.now(),
)
+ def test_experiment_type_is_refused(self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock) -> None:
+ # Inline scans skip the saved-scanner access check and the variant attribution, so an
+ # experiment-type inline scan would read an experiment's population with neither.
+ resp = self._scan(
+ scanner_type="experiment",
+ scanner_config={"experiment_id": 1},
+ )
+ self.assertEqual(resp.status_code, 400, resp.json())
+ self.assertEqual(resp.json()["attr"], "scanner_type")
+
def test_a_fully_refused_scan_still_reports_the_request(
self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
) -> None:
diff --git a/products/replay_vision/backend/tests/test_max_tools.py b/products/replay_vision/backend/tests/test_max_tools.py
index 48cb837c4906..b110fd86b50e 100644
--- a/products/replay_vision/backend/tests/test_max_tools.py
+++ b/products/replay_vision/backend/tests/test_max_tools.py
@@ -898,6 +898,35 @@ class TestUpdateReplayVisionScannerTool(BaseTest):
scanner = await sync_to_async(ReplayScanner.objects.get)(id=created["scanner_id"])
assert scanner.enabled is True
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_a_denied_experiment_refuses_config_edits_through_max(self):
+ # Without an access control in the serializer context the experiment-scope write guard
+ # treats the caller as unrestricted, so Max would bypass the refusal the API enforces.
+ from products.experiments.backend.models.experiment import Experiment
+ from products.replay_vision.backend.tests.helpers import create_experiment
+
+ experiment = await sync_to_async(create_experiment)(self.team, "restricted-flag")
+ scanner = await sync_to_async(self._scanner)(
+ scanner_type=ScannerType.EXPERIMENT,
+ scanner_config={"prompt": "p", "experiment_id": experiment.id},
+ )
+
+ with patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.filter_queryset_by_access_level",
+ side_effect=lambda qs, **_: qs.exclude(pk=experiment.pk) if qs.model is Experiment else qs,
+ ):
+ _, result = await self._tool()._arun_impl(scanner_id=str(scanner.id), prompt="rewritten")
+
+ assert result == {"error": "invalid_config"}
+ await sync_to_async(scanner.refresh_from_db)()
+ assert scanner.scanner_config["prompt"] == "p"
+
+ # The same edit from a caller the experiment allows still lands.
+ with patch(_REFRESH_ESTIMATE_PATH):
+ _, allowed = await self._tool()._arun_impl(scanner_id=str(scanner.id), prompt="rewritten")
+ assert "error" not in allowed, allowed
+
@parameterized.expand(
[
# Only starting a schedule or widening a running one commits the project to spend.
diff --git a/products/replay_vision/backend/tests/test_models.py b/products/replay_vision/backend/tests/test_models.py
index 03fcf32d251a..edd310d3ada5 100644
--- a/products/replay_vision/backend/tests/test_models.py
+++ b/products/replay_vision/backend/tests/test_models.py
@@ -96,6 +96,32 @@ class TestReplayScanner(BaseTest):
scanner.save()
self.assertEqual(scanner.scanner_version, 2)
+ @parameterized.expand(
+ [
+ ("scope_change_stales", {"prompt": "p", "experiment_id": 42, "variants": ["test"]}, True),
+ ("prompt_only_change_keeps", {"prompt": "sharper", "experiment_id": 42}, False),
+ ]
+ )
+ def test_experiment_config_edits_stale_the_estimate_only_on_scope_change(
+ self, _label: str, new_config: dict, expect_stale: bool
+ ) -> None:
+ # The experiment type's volume is set by experiment_id/variants inside scanner_config, so
+ # only a scope change may reset the estimate; a prompt edit must not discard it.
+ scanner = self._create_scanner(
+ scanner_type=ScannerType.EXPERIMENT,
+ scanner_config={"prompt": "p", "experiment_id": 42},
+ )
+ stamped = timezone.now()
+ ReplayScanner.objects.filter(pk=scanner.pk).update(estimated_monthly_observations=100, estimated_at=stamped)
+ scanner.refresh_from_db()
+
+ scanner.scanner_config = new_config
+ scanner.save()
+ scanner.refresh_from_db()
+
+ self.assertEqual(scanner.scanner_version, 2)
+ self.assertEqual(scanner.estimated_at is None, expect_stale)
+
def test_scanner_version_does_not_bump_on_metadata_change(self) -> None:
scanner = self._create_scanner(name="original")
scanner.name = "renamed"
@@ -406,3 +432,17 @@ class TestTargetedRecordingsQuery(BaseTest):
assert exposure is not None
assert exposure.experiment_id == 42
assert exposure.variant == "test"
+
+ def test_the_experiment_type_reads_its_scope_from_scanner_config(self) -> None:
+ # The experiment type carries no experiment_targeting column value; a sweep that kept
+ # reading only the column would scan the team's whole replay population.
+ scanner = _make_scanner(
+ self.team,
+ scanner_type=ScannerType.EXPERIMENT,
+ scanner_config={"prompt": "p", "experiment_id": 42, "variants": ["control", "test"]},
+ query={"kind": "RecordingsQuery"},
+ )
+ exposure = scanner.targeted_recordings_query().experiment_exposure
+ assert exposure is not None
+ assert exposure.experiment_id == 42
+ assert exposure.variants == ["control", "test"]
diff --git a/products/replay_vision/backend/tests/test_prompt_suggestions_api.py b/products/replay_vision/backend/tests/test_prompt_suggestions_api.py
index 9a7838e76139..c410096e3878 100644
--- a/products/replay_vision/backend/tests/test_prompt_suggestions_api.py
+++ b/products/replay_vision/backend/tests/test_prompt_suggestions_api.py
@@ -22,6 +22,7 @@ from products.replay_vision.backend.prompt_suggestions import (
generate_prompt_suggestion,
refresh_prompt_suggestion_if_stale,
)
+from products.replay_vision.backend.tests.helpers import create_experiment
from products.replay_vision.backend.tests.test_api import _VisionAPITestCase
@@ -348,6 +349,35 @@ class TestPromptSuggestions(_VisionAPITestCase):
scanner.refresh_from_db()
self.assertEqual(scanner.scanner_config["prompt"], "keep me")
+ def test_apply_rejects_a_config_that_changes_the_experiment(self) -> None:
+ # Apply writes the config directly, so without this guard an edited config could retarget
+ # the scanner's watched experiment — skipping the serializer's experiment access re-check.
+ experiment = create_experiment(self.team, "apply-scope-flag")
+ current = {"prompt": "p", "experiment_id": experiment.id}
+ scanner = self._create_scanner(name="exp-apply", scanner_type="experiment", scanner_config=dict(current))
+ suggestion = ReplayScannerPromptSuggestion.objects.create(
+ scanner=scanner,
+ team=self.team,
+ suggested_prompt="new",
+ base_prompt="p",
+ base_config=dict(current),
+ suggested_config={"prompt": "new", "experiment_id": experiment.id},
+ changes=[{"field": "prompt", "kind": "prompt", "op": "set", "before": "p", "after": "new"}],
+ status=PromptSuggestionStatus.PENDING,
+ scanner_version=scanner.scanner_version,
+ )
+
+ url = f"{self.scanners_url}{scanner.id}/prompt_suggestions/{suggestion.id}/apply/"
+ resp = self.client.post(
+ url, {"config": {"prompt": "edited", "experiment_id": experiment.id + 1}}, format="json"
+ )
+
+ self.assertEqual(resp.status_code, 400)
+ scanner.refresh_from_db()
+ self.assertEqual(scanner.scanner_config, current)
+ suggestion.refresh_from_db()
+ self.assertEqual(suggestion.status, PromptSuggestionStatus.PENDING)
+
def test_apply_old_prompt_only_row_still_works(self) -> None:
# Rows generated before config-generic suggestions existed have suggested_config=None.
scanner = self._create_scanner(name="legacy-apply", scanner_type="monitor", scanner_config={"prompt": "old"})
diff --git a/products/replay_vision/backend/tests/test_scanners.py b/products/replay_vision/backend/tests/test_scanners.py
index e7443d36a075..b2562e6bd082 100644
--- a/products/replay_vision/backend/tests/test_scanners.py
+++ b/products/replay_vision/backend/tests/test_scanners.py
@@ -10,6 +10,8 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner,
from products.replay_vision.backend.temporal.scanners import (
ClassifierOutput,
ClassifierScanner,
+ ExperimentOutput,
+ ExperimentScanner,
MonitorLlmResponse,
MonitorOutput,
MonitorScanner,
@@ -1040,3 +1042,56 @@ class TestSignalSideMission:
long = SignalFinding.model_validate({**self._VALID_SIGNAL, "headline": "word " * 40})
assert len(long.headline) <= SIGNAL_HEADLINE_MAX_LENGTH
assert not long.headline.endswith(" ")
+
+
+class TestExperimentScanner:
+ def _scanner(self, **config_overrides):
+ config = {"prompt": "watch the checkout change", "experiment_id": 42, **config_overrides}
+ return scanner_from_db(_build_replay_scanner(scanner_type=ScannerType.EXPERIMENT, scanner_config=config))
+
+ def test_scanner_from_db_picks_experiment_subclass_with_summarizer_defaults(self) -> None:
+ scanner = self._scanner()
+ assert isinstance(scanner, ExperimentScanner)
+ assert isinstance(scanner, SummarizerScanner)
+ assert (scanner.length, scanner.balance_variants, scanner.variants) == ("medium", True, None)
+
+ def test_scanner_from_db_requires_experiment_id(self) -> None:
+ with pytest.raises(ApplicationError, match="experiment_id"):
+ scanner_from_db(_build_replay_scanner(scanner_type=ScannerType.EXPERIMENT, scanner_config={"prompt": "p"}))
+
+ def test_core_step_renders_without_scan_time_context(self) -> None:
+ # The prompt env uses StrictUndefined, and the workflow that injects the experiment context
+ # ships separately, so the template must render from the persisted config alone.
+ instruction = self._scanner().core_steps()[0].instruction
+ assert "A/B experiment" in instruction
+ assert "watch the checkout change" in instruction
+ assert "(t " in instruction
+
+ def test_core_step_carries_injected_experiment_context_and_variant(self) -> None:
+ scanner = self._scanner().model_copy(
+ update={
+ "experiment_context": {
+ "name": "Checkout CTA copy",
+ "description": "One-click checkout raises conversion.",
+ "feature_flag_key": "checkout-cta",
+ "variants": [
+ {"key": "control", "description": "", "rollout_percentage": 50.0},
+ {"key": "test", "description": "One-click", "rollout_percentage": 50.0},
+ ],
+ "primary_metric_names": ["Purchases"],
+ },
+ "session_variant": "test",
+ }
+ )
+ instruction = scanner.core_steps()[0].instruction
+ assert "Checkout CTA copy" in instruction
+ assert "checkout-cta" in instruction
+ assert "Purchases" in instruction
+ assert "`test` variant" in instruction
+
+ def test_output_round_trip_keeps_the_summarizer_shape(self) -> None:
+ out = ExperimentOutput(title="Faster checkout", summary="They breezed through.", confidence=0.9)
+ round_tripped = ExperimentOutput.model_validate_json(out.model_dump_json())
+ assert round_tripped == out
+ assert round_tripped.scanner_type == ScannerType.EXPERIMENT
+ assert summary_embedding_text(round_tripped) == "Faster checkout\n\nThey breezed through."
diff --git a/products/replay_vision/backend/watch_feed.py b/products/replay_vision/backend/watch_feed.py
index ed3015c98baa..4b5614574c78 100644
--- a/products/replay_vision/backend/watch_feed.py
+++ b/products/replay_vision/backend/watch_feed.py
@@ -270,7 +270,7 @@ def _type_hit(
return reason, 1.0 - share
elif candidate.verdict == "yes":
return {"kind": "verdict_yes"}, VERDICT_YES_STRENGTH
- if candidate.scanner_type == "summarizer":
+ if candidate.scanner_type in ("summarizer", "experiment"):
similarity = _max_summary_similarity(candidate, siblings)
if similarity is not None and similarity <= NOVEL_SUMMARY_MAX_SIMILARITY:
return {"kind": "novel_summary"}, 1.0 - similarity
diff --git a/products/replay_vision/frontend/components/ScannerTypeBadge.tsx b/products/replay_vision/frontend/components/ScannerTypeBadge.tsx
index a4a20f24e785..39d43b6a6084 100644
--- a/products/replay_vision/frontend/components/ScannerTypeBadge.tsx
+++ b/products/replay_vision/frontend/components/ScannerTypeBadge.tsx
@@ -1,4 +1,4 @@
-import { IconEye, IconNotebook, IconPulse, IconTarget } from '@posthog/icons'
+import { IconEye, IconFlask, IconNotebook, IconPulse, IconTarget } from '@posthog/icons'
import { LemonTag } from '@posthog/lemon-ui'
import { SCANNER_TYPE_TAG_TYPE, ScannerType, scannerTypeLabel } from '../replay_scanners/types'
@@ -13,6 +13,8 @@ export function scannerTypeIcon(scannerType: ScannerType): JSX.Element {
return <IconPulse />
case 'summarizer':
return <IconNotebook />
+ case 'experiment':
+ return <IconFlask />
}
}
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 1bbd2612d13e..29d87832f397 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -616,6 +616,7 @@ export const ObservationStatusEnumApi = {
* * `classifier` - Classifier
* * `scorer` - Scorer
* * `summarizer` - Summarizer
+ * * `experiment` - Experiment
*/
export type ScannerTypeEnumApi = (typeof ScannerTypeEnumApi)[keyof typeof ScannerTypeEnumApi]
@@ -624,6 +625,7 @@ export const ScannerTypeEnumApi = {
Classifier: 'classifier',
Scorer: 'scorer',
Summarizer: 'summarizer',
+ Experiment: 'experiment',
} as const
/**
@@ -632,12 +634,13 @@ export const ScannerTypeEnumApi = {
export interface ScannerSnapshotApi {
/** Scanner name at run time. */
name: string
- /** Scanner type (monitor, classifier, scorer, summarizer) at run time.
+ /** Scanner type (monitor, classifier, scorer, summarizer, experiment) at run time.
*
* * `monitor` - Monitor
* * `classifier` - Classifier
* * `scorer` - Scorer
- * * `summarizer` - Summarizer */
+ * * `summarizer` - Summarizer
+ * * `experiment` - Experiment */
scanner_type: ScannerTypeEnumApi
/** The `ReplayScanner.scanner_version` value at the moment the workflow ran. */
scanner_version: number
@@ -1088,7 +1091,8 @@ export interface ReplayScannerApi {
* * `monitor` - Monitor
* * `classifier` - Classifier
* * `scorer` - Scorer
- * * `summarizer` - Summarizer */
+ * * `summarizer` - Summarizer
+ * * `experiment` - Experiment */
scanner_type: ScannerTypeEnumApi
/**
* The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update.
@@ -1222,7 +1226,8 @@ export interface PatchedReplayScannerApi {
* * `monitor` - Monitor
* * `classifier` - Classifier
* * `scorer` - Scorer
- * * `summarizer` - Summarizer */
+ * * `summarizer` - Summarizer
+ * * `experiment` - Experiment */
scanner_type?: ScannerTypeEnumApi
/**
* The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update.
@@ -2421,7 +2426,8 @@ export interface DraftScannerResponseApi {
* * `monitor` - Monitor
* * `classifier` - Classifier
* * `scorer` - Scorer
- * * `summarizer` - Summarizer */
+ * * `summarizer` - Summarizer
+ * * `experiment` - Experiment */
scanner_type: ScannerTypeEnumApi
/** Type-specific config for the drafted `scanner_type`; always includes `prompt`. */
scanner_config: unknown
@@ -2535,7 +2541,8 @@ export interface InlineScanRequestApi {
* * `monitor` - Monitor
* * `classifier` - Classifier
* * `scorer` - Scorer
- * * `summarizer` - Summarizer */
+ * * `summarizer` - Summarizer
+ * * `experiment` - Experiment */
scanner_type?: ScannerTypeEnumApi
/** Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here. */
scanner_config?: unknown
@@ -2580,6 +2587,7 @@ export interface ScannerStatsByTypeApi {
classifier: ScannerTypeStatsApi
scorer: ScannerTypeStatsApi
summarizer: ScannerTypeStatsApi
+ experiment: ScannerTypeStatsApi
}
/**
@@ -2590,7 +2598,7 @@ export interface ScannerStatsResponseApi {
total: number
/** Number of enabled scanners on the team. */
enabled: number
- /** Per-scanner-type breakdown (monitor / classifier / scorer / summarizer). */
+ /** Per-scanner-type breakdown (monitor / classifier / scorer / summarizer / experiment). */
by_type: ScannerStatsByTypeApi
}
@@ -3340,6 +3348,7 @@ export type VisionScannersWatchFeedRetrieveParams = {
* * `classifier` - Classifier
* * `scorer` - Scorer
* * `summarizer` - Summarizer
+ * * `experiment` - Experiment
* @minLength 1
*/
scanner_type?: VisionScannersWatchFeedRetrieveScannerType
@@ -3363,4 +3372,5 @@ export const VisionScannersWatchFeedRetrieveScannerType = {
Classifier: 'classifier',
Scorer: 'scorer',
Summarizer: 'summarizer',
+ Experiment: 'experiment',
} as const
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index a28064cf00c5..64293b232391 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -514,12 +514,12 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod
"Organizational tags for this scanner. Distinct from a classifier's categories in scanner_config. Tags cannot contain commas."
),
scanner_type: zod
- .enum(['monitor', 'classifier', 'scorer', 'summarizer'])
+ .enum(['monitor', 'classifier', 'scorer', 'summarizer', 'experiment'])
.describe(
- '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'
)
.describe(
- 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'
),
goal: zod
.string()
@@ -664,13 +664,13 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod
"Organizational tags for this scanner. Distinct from a classifier's categories in scanner_config. Tags cannot contain commas."
),
scanner_type: zod
- .enum(['monitor', 'classifier', 'scorer', 'summarizer'])
+ .enum(['monitor', 'classifier', 'scorer', 'summarizer', 'experiment'])
.describe(
- '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'
)
.optional()
.describe(
- 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'
),
goal: zod
.string()
@@ -1311,13 +1311,13 @@ export const VisionScannersInlineScanCreateBody = /* @__PURE__ */ zod
'What to look for in these sessions, in plain language. The same instruction a saved scanner carries.'
),
scanner_type: zod
- .enum(['monitor', 'classifier', 'scorer', 'summarizer'])
+ .enum(['monitor', 'classifier', 'scorer', 'summarizer', 'experiment'])
.describe(
- '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'
)
.default(visionScannersInlineScanCreateBodyScannerTypeDefault)
.describe(
- "What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer"
+ "What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment"
),
scanner_config: zod
.unknown()
diff --git a/products/replay_vision/frontend/observations/ObservationHeadline.tsx b/products/replay_vision/frontend/observations/ObservationHeadline.tsx
index 3f12827cdd0a..1bb122011b51 100644
--- a/products/replay_vision/frontend/observations/ObservationHeadline.tsx
+++ b/products/replay_vision/frontend/observations/ObservationHeadline.tsx
@@ -27,6 +27,7 @@ const HEADLINE_LABEL: Record<ScannerTypeEnumApi, string> = {
scorer: 'Score',
classifier: 'Assigned categories',
summarizer: 'Summary',
+ experiment: 'Summary',
}
// The `--success`/`--danger` family LemonTag uses. The `text-success` utility maps to a different, brighter green.
diff --git a/products/replay_vision/frontend/replayVisionSetupLogic.test.ts b/products/replay_vision/frontend/replayVisionSetupLogic.test.ts
index e55e4b0bb72c..94d02bfd9c22 100644
--- a/products/replay_vision/frontend/replayVisionSetupLogic.test.ts
+++ b/products/replay_vision/frontend/replayVisionSetupLogic.test.ts
@@ -21,6 +21,7 @@ function statsWithTotal(total: number): Awaited<ReturnType<typeof visionScanners
classifier: { enabled: 0, total: 0 },
scorer: { enabled: 0, total: 0 },
summarizer: { enabled: total, total },
+ experiment: { enabled: 0, total: 0 },
},
}
}
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index 67ce48e6f3f6..7be8da443ca9 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -151,6 +151,7 @@ const scannerStats: ScannerStatsResponseApi = {
classifier: { enabled: 0, total: 1 },
scorer: { enabled: 1, total: 1 },
summarizer: { enabled: 1, total: 1 },
+ experiment: { enabled: 0, total: 0 },
},
}
@@ -964,6 +965,7 @@ const emptyProjectDecorators = [
classifier: { enabled: 0, total: 0 },
scorer: { enabled: 0, total: 0 },
summarizer: { enabled: 0, total: 0 },
+ experiment: { enabled: 0, total: 0 },
},
} satisfies ScannerStatsResponseApi,
'/api/projects/:team_id/vision/scanners/creators/': { creators: [] },
diff --git a/products/replay_vision/frontend/replay_scanners/scannerScout.ts b/products/replay_vision/frontend/replay_scanners/scannerScout.ts
index 889cac61e783..d07d2a8cdd62 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerScout.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerScout.ts
@@ -245,6 +245,15 @@ const TREND_LENSES: Record<ScannerTypeEnumApi, TrendLens> = {
'The same complaint, flow, or failure described again and again across many distinct sessions, especially one that did not recur in prior weeks. Summaries are freeform, so never group on the raw text: read the recent summaries and name the theme yourself, then count the distinct sessions that show it.',
skip: '- A theme resting on a handful of sessions, or one you can only see by reading the text loosely — say so rather than inflating it.\n- Themes that recur every week at the same rate; those are the baseline, not a shift.',
},
+ // The experiment type is a summarizer over one experiment's exposed sessions, so it trends the same way.
+ experiment: {
+ description: "Watches for themes recurring across this scanner's summaries.",
+ metric: 'recurring themes across summaries',
+ seriesSelect: 'uniq(properties.session_id) AS sessions',
+ notable:
+ 'The same complaint, flow, or failure described again and again across many distinct sessions, especially one that did not recur in prior weeks. Summaries are freeform, so never group on the raw text: read the recent summaries and name the theme yourself, then count the distinct sessions that show it.',
+ skip: '- A theme resting on a handful of sessions, or one you can only see by reading the text loosely — say so rather than inflating it.\n- Themes that recur every week at the same rate; those are the baseline, not a shift.',
+ },
}
/** The name the create form starts with. It leads with the scanner because the scout also lands in
diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.ts
index d5771d818015..8f944be576b9 100644
--- a/products/replay_vision/frontend/replay_scanners/types.ts
+++ b/products/replay_vision/frontend/replay_scanners/types.ts
@@ -21,6 +21,7 @@ export const SCANNER_TYPE_TAG_TYPE: Record<ScannerType, LemonTagType> = {
classifier: 'completion',
scorer: 'warning',
summarizer: 'success',
+ experiment: 'highlight',
}
export const OBSERVATION_TRIGGER_TAG: Record<
@@ -387,6 +388,7 @@ const SCANNER_TYPE_OUTPUT_HINT: Record<ScannerType, string> = {
classifier: 'a category from a set you define',
scorer: 'a number score',
summarizer: 'a text summary',
+ experiment: 'a text summary per exposed session',
}
export function scannerTypeOutputHint(scannerType: ScannerType): string {
@@ -399,6 +401,7 @@ export const SUCCEEDED_OUTPUT_LABEL: Record<ScannerType, string> = {
summarizer: 'Summary',
monitor: 'Verdict',
scorer: 'Score',
+ experiment: 'Summary',
}
export function createdByLabel(user: ScannerCreatedBy | null): string {
@@ -454,11 +457,21 @@ export interface ScorerScannerConfig {
scale: { min: number; max: number; label?: string }
}
+export interface ExperimentScannerConfig {
+ prompt: string
+ length?: 'short' | 'medium' | 'long'
+ experiment_id: number
+ /** Variant keys to watch; null or absent means every variant. */
+ variants?: string[] | null
+ balance_variants?: boolean
+}
+
export type ScannerConfig =
| MonitorScannerConfig
| SummarizerScannerConfig
| ClassifierScannerConfig
| ScorerScannerConfig
+ | ExperimentScannerConfig
export type SamplingMode = 'focused' | 'balanced' | 'comprehensive'
@@ -518,7 +531,12 @@ export interface ScorerScanner extends BaseReplayScanner {
scanner_config: ScorerScannerConfig
}
-export type ReplayScanner = MonitorScanner | SummarizerScanner | ClassifierScanner | ScorerScanner
+export interface ExperimentScanner extends BaseReplayScanner {
+ scanner_type: 'experiment'
+ scanner_config: ExperimentScannerConfig
+}
+
+export type ReplayScanner = MonitorScanner | SummarizerScanner | ClassifierScanner | ScorerScanner | ExperimentScanner
// The editor form's values: the API scanner plus UI-only state that is stripped before every API write.
// `credit_limit_enabled` keeps "limit toggle on, amount still empty" representable so it can block the save.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c72e7b9b0123..3a7cdd1cb068 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -36140,6 +36140,7 @@ export namespace Schemas {
* * `classifier` - Classifier
* * `scorer` - Scorer
* * `summarizer` - Summarizer
+ * * `experiment` - Experiment
*/
export type ScannerTypeEnum = typeof ScannerTypeEnum[keyof typeof ScannerTypeEnum];
@@ -36149,6 +36150,7 @@ export namespace Schemas {
Classifier: 'classifier',
Scorer: 'scorer',
Summarizer: 'summarizer',
+ Experiment: 'experiment',
} as const;
/**
@@ -36211,7 +36213,8 @@ export namespace Schemas {
* * `monitor` - Monitor
* * `classifier` - Classifier
* * `scorer` - Scorer
- * * `summarizer` - Summarizer */
+ * * `summarizer` - Summarizer
+ * * `experiment` - Experiment */
scanner_type: ScannerTypeEnum;
/** Type-specific config for the drafted `scanner_type`; always includes `prompt`. */
scanner_config: unknown;
@@ -56311,7 +56314,8 @@ export namespace Schemas {
* * `monitor` - Monitor
* * `classifier` - Classifier
* * `scorer` - Scorer
- * * `summarizer` - Summarizer */
+ * * `summarizer` - Summarizer
+ * * `experiment` - Experiment */
scanner_type?: ScannerTypeEnum;
/** Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here. */
scanner_config?: unknown;
@@ -64158,12 +64162,13 @@ export namespace Schemas {
export interface ScannerSnapshot {
/** Scanner name at run time. */
name: string;
- /** Scanner type (monitor, classifier, scorer, summarizer) at run time.
+ /** Scanner type (monitor, classifier, scorer, summarizer, experiment) at run time.
*
* * `monitor` - Monitor
* * `classifier` - Classifier
* * `scorer` - Scorer
- * * `summarizer` - Summarizer */
+ * * `summarizer` - Summarizer
+ * * `experiment` - Experiment */
scanner_type: ScannerTypeEnum;
/** The `ReplayScanner.scanner_version` value at the moment the workflow ran. */
scanner_version: number;
@@ -68325,7 +68330,8 @@ export namespace Schemas {
* * `monitor` - Monitor
* * `classifier` - Classifier
* * `scorer` - Scorer
- * * `summarizer` - Summarizer */
+ * * `summarizer` - Summarizer
+ * * `experiment` - Experiment */
scanner_type: ScannerTypeEnum;
/**
* The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update.
@@ -79824,7 +79830,8 @@ export namespace Schemas {
* * `monitor` - Monitor
* * `classifier` - Classifier
* * `scorer` - Scorer
- * * `summarizer` - Summarizer */
+ * * `summarizer` - Summarizer
+ * * `experiment` - Experiment */
scanner_type?: ScannerTypeEnum;
/**
* The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update.
@@ -92634,6 +92641,7 @@ export namespace Schemas {
classifier: ScannerTypeStats;
scorer: ScannerTypeStats;
summarizer: ScannerTypeStats;
+ experiment: ScannerTypeStats;
}
/**
@@ -92644,7 +92652,7 @@ export namespace Schemas {
total: number;
/** Number of enabled scanners on the team. */
enabled: number;
- /** Per-scanner-type breakdown (monitor / classifier / scorer / summarizer). */
+ /** Per-scanner-type breakdown (monitor / classifier / scorer / summarizer / experiment). */
by_type: ScannerStatsByType;
}
@@ -123002,6 +123010,7 @@ export namespace Schemas {
* * `classifier` - Classifier
* * `scorer` - Scorer
* * `summarizer` - Summarizer
+ * * `experiment` - Experiment
* @minLength 1
*/
scanner_type?: VisionScannersWatchFeedRetrieveScannerType;
@@ -123025,6 +123034,7 @@ export namespace Schemas {
Classifier: 'classifier',
Scorer: 'scorer',
Summarizer: 'summarizer',
+ Experiment: 'experiment',
} as const;
export type VisualReviewReposListParams = {
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 654f63f305c4..18b0111330b4 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -754,12 +754,12 @@ export const VisionScannersCreateBody = () => zod
"Organizational tags for this scanner. Distinct from a classifier's categories in scanner_config. Tags cannot contain commas."
),
scanner_type: zod
- .enum(['monitor', 'classifier', 'scorer', 'summarizer'])
+ .enum(['monitor', 'classifier', 'scorer', 'summarizer', 'experiment'])
.describe(
- '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'
)
.describe(
- 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'
),
goal: zod
.string()
@@ -925,13 +925,13 @@ export const VisionScannersPartialUpdateBody = () => zod
"Organizational tags for this scanner. Distinct from a classifier's categories in scanner_config. Tags cannot contain commas."
),
scanner_type: zod
- .enum(['monitor', 'classifier', 'scorer', 'summarizer'])
+ .enum(['monitor', 'classifier', 'scorer', 'summarizer', 'experiment'])
.describe(
- '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'
)
.optional()
.describe(
- 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ 'What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'
),
goal: zod
.string()
@@ -2051,13 +2051,13 @@ export const VisionScannersInlineScanCreateBody = () => zod
'What to look for in these sessions, in plain language. The same instruction a saved scanner carries.'
),
scanner_type: zod
- .enum(['monitor', 'classifier', 'scorer', 'summarizer'])
+ .enum(['monitor', 'classifier', 'scorer', 'summarizer', 'experiment'])
.describe(
- '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'
)
.default(visionScannersInlineScanCreateBodyScannerTypeDefault)
.describe(
- "What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer"
+ "What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment"
),
scanner_config: zod
.unknown()
@@ -2181,10 +2181,10 @@ export const VisionScannersWatchFeedRetrieveQueryParams = () => zod.object({
.optional()
.describe('Comma-separated scanner UUIDs to restrict the feed to. Defaults to every scanner you can read.'),
scanner_type: zod
- .enum(['monitor', 'classifier', 'scorer', 'summarizer'])
+ .enum(['monitor', 'classifier', 'scorer', 'summarizer', 'experiment'])
.optional()
.describe(
- 'Restrict the feed to observations from scanners of this type.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ 'Restrict the feed to observations from scanners of this type.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer\n\* `experiment` - Experiment'
),
search: zod
.string()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
index 4f45b38a5216..b8841820c157 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
@@ -121,8 +121,8 @@
"description": "Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`."
},
"scanner_type": {
- "description": "What the scanner does: monitor, classifier, scorer, or summarizer.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer",
- "enum": ["monitor", "classifier", "scorer", "summarizer"],
+ "description": "What the scanner does: monitor, classifier, scorer, or summarizer.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer\n* `experiment` - Experiment",
+ "enum": ["monitor", "classifier", "scorer", "summarizer", "experiment"],
"type": "string"
},
"tags": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan-create.json
index eee0c4996fc4..13888cfb8fc8 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan-create.json
@@ -18,8 +18,8 @@
},
"scanner_type": {
"default": "monitor",
- "description": "What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer",
- "enum": ["monitor", "classifier", "scorer", "summarizer"],
+ "description": "What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer\n* `experiment` - Experiment",
+ "enum": ["monitor", "classifier", "scorer", "summarizer", "experiment"],
"type": "string"
},
"session_ids": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan.json
index eee0c4996fc4..13888cfb8fc8 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-inline-scan.json
@@ -18,8 +18,8 @@
},
"scanner_type": {
"default": "monitor",
- "description": "What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer",
- "enum": ["monitor", "classifier", "scorer", "summarizer"],
+ "description": "What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` to get PostHog's own AI summary of a recording. An inline scan is keyed by its whole config, so the Summarize button in the replay player shares this scan only when the prompt and `scanner_config` match the ones it sends.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer\n* `experiment` - Experiment",
+ "enum": ["monitor", "classifier", "scorer", "summarizer", "experiment"],
"type": "string"
},
"session_ids": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
index 3ef8373b129d..2668a6ac0a9e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
@@ -124,8 +124,8 @@
"description": "Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`."
},
"scanner_type": {
- "description": "What the scanner does: monitor, classifier, scorer, or summarizer.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer",
- "enum": ["monitor", "classifier", "scorer", "summarizer"],
+ "description": "What the scanner does: monitor, classifier, scorer, or summarizer.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer\n* `experiment` - Experiment",
+ "enum": ["monitor", "classifier", "scorer", "summarizer", "experiment"],
"type": "string"
},
"tags": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-watch-feed.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-watch-feed.json
index 4c1e53827dcd..79723e215f7c 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-watch-feed.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-watch-feed.json
@@ -25,8 +25,8 @@
"type": "string"
},
"scanner_type": {
- "description": "Restrict the feed to observations from scanners of this type.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer",
- "enum": ["monitor", "classifier", "scorer", "summarizer"],
+ "description": "Restrict the feed to observations from scanners of this type.\n\n* `monitor` - Monitor\n* `classifier` - Classifier\n* `scorer` - Scorer\n* `summarizer` - Summarizer\n* `experiment` - Experiment",
+ "enum": ["monitor", "classifier", "scorer", "summarizer", "experiment"],
"type": "string"
},
"search": {