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): start an experiment scanner when its experiment launches (#112018)

Kim Svatos Dugandf9b91b93967
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 1959fde767a7..ad1c1356e38b 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -49,6 +49,7 @@ from posthog.utils import str_to_bool
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models import EventDefinition, effective_project_id_expr
+from products.experiments.backend.facade.launch_signals import experiment_launched
from products.experiments.backend.flag_cleanup import build_cleanup_prompt, cleanup_plan
from products.experiments.backend.hogql_queries import CONTROL_VARIANT_KEY, get_baseline_variant_key
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
@@ -1378,6 +1379,20 @@ class ExperimentService:
except Exception:
logger.exception("experiment_launched_analytics_failed", experiment_id=experiment.id)
+ @staticmethod
+ def _notify_experiment_launched(experiment: Experiment) -> None:
+ responses = experiment_launched.send_robust(
+ sender=Experiment, team_id=experiment.team_id, experiment_id=experiment.id
+ )
+ for receiver, response in responses:
+ if isinstance(response, Exception):
+ logger.error(
+ "experiment_launched_receiver_failed",
+ receiver=getattr(receiver, "__qualname__", repr(receiver)),
+ experiment_id=experiment.id,
+ exc_info=response,
+ )
+
def _ensure_feature_flag(
self,
feature_flag_key: str,
@@ -1789,6 +1804,7 @@ class ExperimentService:
)
self._report_experiment_launched(experiment, launch_path="launch_endpoint", request=request)
+ self._notify_experiment_launched(experiment)
return experiment
@@ -3679,6 +3695,7 @@ class ExperimentService:
request=report_request,
event_source=event_source,
)
+ self._notify_experiment_launched(experiment)
return experiment
diff --git a/products/experiments/backend/facade/__init__.py b/products/experiments/backend/facade/__init__.py
index 0c06d59cadd1..546e4137de7e 100644
--- a/products/experiments/backend/facade/__init__.py
+++ b/products/experiments/backend/facade/__init__.py
@@ -4,9 +4,28 @@ Facade for experiments product.
This module provides the public interface for other products to interact with experiments.
"""
-from .api import count_running_experiments_on_feature_flag_called, create_experiment
+import importlib
+from typing import TYPE_CHECKING, Any
+
from .contracts import CreateExperimentInput, Experiment, FeatureFlag
+if TYPE_CHECKING:
+ from .api import count_running_experiments_on_feature_flag_called, create_experiment
+
+# Loaded on first use (PEP 562): light submodules such as `launch_signals` load in every process at
+# startup, and importing one runs this file first, so an eager `api` import would drag the whole
+# experiments service onto the startup path.
+_LAZY_API_NAMES = frozenset({"count_running_experiments_on_feature_flag_called", "create_experiment"})
+
+
+def __getattr__(name: str) -> Any:
+ if name not in _LAZY_API_NAMES:
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+ value = getattr(importlib.import_module(".api", __name__), name)
+ globals()[name] = value
+ return value
+
+
__all__ = [
"count_running_experiments_on_feature_flag_called",
"create_experiment",
diff --git a/products/experiments/backend/facade/launch_signals.py b/products/experiments/backend/facade/launch_signals.py
new file mode 100644
index 000000000000..7d9ad81a7c67
--- /dev/null
+++ b/products/experiments/backend/facade/launch_signals.py
@@ -0,0 +1,13 @@
+from collections.abc import Callable
+
+from django.dispatch import Signal
+
+# Sent with `team_id=` and `experiment_id=` after a launch saves, so other products react to it
+# without the experiments product importing them.
+experiment_launched = Signal()
+
+
+def connect_experiment_launched(receiver: Callable[..., object], *, dispatch_uid: str) -> None:
+ """``receiver`` gets ``team_id=`` and ``experiment_id=`` once a launch saves. A receiver that
+ raises is logged and never fails the launch."""
+ experiment_launched.connect(receiver, dispatch_uid=dispatch_uid)
diff --git a/products/experiments/backend/facade/replay.py b/products/experiments/backend/facade/replay.py
index 2be9a7f33416..78500cc396dc 100644
--- a/products/experiments/backend/facade/replay.py
+++ b/products/experiments/backend/facade/replay.py
@@ -4,6 +4,7 @@ from products.experiments.backend.replay_context import (
accessible_experiment_ids,
experiment_prompt_context,
experiment_status,
+ launched_experiment_ids,
session_attribution,
session_variant,
variant_rollout_shares,
@@ -21,6 +22,7 @@ from products.experiments.backend.replay_linkage import (
resolve_exposure_linkage,
resolve_in_session_exposure_semantics,
targetable_experiments,
+ validate_draft_experiment_scope,
validate_experiment_exposure_access,
)
@@ -34,6 +36,7 @@ __all__ = [
"accessible_experiment_ids",
"experiment_prompt_context",
"experiment_status",
+ "launched_experiment_ids",
"exposed_distinct_ids_select",
"exposed_persons_select",
"exposed_session_ids_select",
@@ -42,6 +45,7 @@ __all__ = [
"session_attribution",
"session_variant",
"targetable_experiments",
+ "validate_draft_experiment_scope",
"validate_experiment_exposure_access",
"variant_rollout_shares",
]
diff --git a/products/experiments/backend/replay_context.py b/products/experiments/backend/replay_context.py
index 0a4b8ef36572..f469e2f5a7fe 100644
--- a/products/experiments/backend/replay_context.py
+++ b/products/experiments/backend/replay_context.py
@@ -56,6 +56,15 @@ def accessible_experiment_ids(
return set(queryset.values_list("id", flat=True))
+def launched_experiment_ids(team_id: int, experiment_ids: Collection[int]) -> set[int]:
+ """The ids in ``experiment_ids`` of live experiments in the team that have launched."""
+ return set(
+ Experiment.objects.filter(
+ team_id=team_id, id__in=experiment_ids, deleted=False, start_date__isnull=False
+ ).values_list("id", flat=True)
+ )
+
+
def _live_experiment(team: Team, experiment_id: int) -> Experiment | None:
return Experiment.objects.filter(id=experiment_id, team=team, deleted=False).select_related("feature_flag").first()
diff --git a/products/experiments/backend/replay_linkage.py b/products/experiments/backend/replay_linkage.py
index e434a86a29e2..2f3b0673a898 100644
--- a/products/experiments/backend/replay_linkage.py
+++ b/products/experiments/backend/replay_linkage.py
@@ -86,6 +86,7 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import get_
from products.experiments.backend.models.experiment import Experiment
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.session_exposure import SessionExposure, resolve_session_exposure
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
logger = structlog.get_logger(__name__)
@@ -317,28 +318,24 @@ def targetable_experiments(team: Team, *, experiment_ids: Sequence[int]) -> list
return targetable
-def resolve_exposure_linkage(
+@dataclass(frozen=True, kw_only=True)
+class _ValidatedScope:
+ experiment: Experiment
+ flag: FeatureFlag
+ # Every requestable variant of the experiment.
+ variant_keys: list[str]
+ # The caller's narrowing of `variant_keys`, or all of them when it asked for none.
+ requested_variants: list[str]
+
+
+def _validated_scope(
team: Team,
*,
experiment_id: int,
- variant: str | None = None,
- variants: list[str] | None = None,
- in_session: bool = False,
-) -> ExperimentExposureLinkage:
- """Validate the experiment and resolve how its exposed population will be read.
-
- ``variants`` narrows the population to any subset of the experiment's variants; ``variant``
- is the single-variant form that predates it, kept for existing callers. Pass at most one of
- the two. With neither, the population covers every requestable variant.
-
- Raises ValidationError for experiments the linkage can't answer for: unknown or draft
- experiments, group-aggregated ones (whose exposed entities are groups rather than
- persons and so never match a recording's distinct id), unknown variants, and
- experiments whose exposures can be resolved neither from the preaggregated table nor
- with a live scan the team can afford. An `in_session` request is refused when the
- exposure event was never captured with a session id and nothing stands in for it
- (custom criteria get no stand-in), because every session would then read as unexposed.
- """
+ variant: str | None,
+ variants: list[str] | None,
+ require_launched: bool,
+) -> _ValidatedScope:
try:
experiment = Experiment.objects.get(id=experiment_id, team=team, deleted=False)
except Experiment.DoesNotExist:
@@ -347,7 +344,7 @@ def resolve_exposure_linkage(
flag = getattr(experiment, "feature_flag", None)
if flag is None:
raise ValidationError(EXPERIMENT_HAS_NO_FLAG_MESSAGE)
- if experiment.start_date is None:
+ if require_launched and experiment.start_date is None:
raise ValidationError("This experiment hasn't launched, so it has no exposed sessions yet.")
if (flag.filters or {}).get("aggregation_group_type_index") is not None:
raise ValidationError(
@@ -370,6 +367,46 @@ def resolve_exposure_linkage(
raise ValidationError(f"'{requested_key}' is not a variant of this experiment.")
# Keep the caller's order, drop duplicates, so the query's IN list stays minimal.
requested_variants = list(dict.fromkeys(requested))
+ return _ValidatedScope(
+ experiment=experiment, flag=flag, variant_keys=variant_keys, requested_variants=requested_variants
+ )
+
+
+def validate_draft_experiment_scope(team: Team, *, experiment_id: int, variants: list[str] | None = None) -> None:
+ """Apply every `resolve_exposure_linkage` refusal that a draft experiment can already answer.
+
+ A draft has no exposures to read, so this skips the launch check and the exposure read. A
+ surface that waits for launch uses it to refuse a scope that would still fail after launch.
+ """
+ _validated_scope(team, experiment_id=experiment_id, variant=None, variants=variants, require_launched=False)
+
+
+def resolve_exposure_linkage(
+ team: Team,
+ *,
+ experiment_id: int,
+ variant: str | None = None,
+ variants: list[str] | None = None,
+ in_session: bool = False,
+) -> ExperimentExposureLinkage:
+ """Validate the experiment and resolve how its exposed population will be read.
+
+ ``variants`` narrows the population to any subset of the experiment's variants; ``variant``
+ is the single-variant form that predates it, kept for existing callers. Pass at most one of
+ the two. With neither, the population covers every requestable variant.
+
+ Raises ValidationError for experiments the linkage can't answer for: unknown or draft
+ experiments, group-aggregated ones (whose exposed entities are groups rather than
+ persons and so never match a recording's distinct id), unknown variants, and
+ experiments whose exposures can be resolved neither from the preaggregated table nor
+ with a live scan the team can afford. An `in_session` request is refused when the
+ exposure event was never captured with a session id and nothing stands in for it
+ (custom criteria get no stand-in), because every session would then read as unexposed.
+ """
+ scope = _validated_scope(
+ team, experiment_id=experiment_id, variant=variant, variants=variants, require_launched=True
+ )
+ experiment = scope.experiment
session_exposure: SessionExposure | None = None
if in_session:
@@ -387,14 +424,14 @@ def resolve_exposure_linkage(
)
context = ExperimentQueryContext(
team=team,
- feature_flag_key=flag.key_without_tombstone(),
+ feature_flag_key=scope.flag.key_without_tombstone(),
exposure_config=exposure_params.exposure_config,
filter_test_accounts=exposure_params.filter_test_accounts,
multiple_variant_handling=exposure_params.multiple_variant_handling,
# The full variant list, not the requested one: variant attribution and multiple-variant
# detection must see every variant, or a person exposed to two variants would pass as
# cleanly exposed to the requested one. Narrowing happens in the WHERE below instead.
- variants=tuple(variant_keys),
+ variants=tuple(scope.variant_keys),
date_range_query=date_range_query,
entity_key=get_entity_key(None),
breakdowns=(),
@@ -405,7 +442,7 @@ def resolve_exposure_linkage(
read = _resolve_exposure_read(team, experiment, context)
return ExperimentExposureLinkage(
context=context,
- requested_variants=requested_variants,
+ requested_variants=scope.requested_variants,
preaggregation_job_ids=read.preaggregation_job_ids,
# The evidence scan always runs live whatever path the population resolves through, so a
# narrowed listing carries the ceiling even where the population read needs none. Activation
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 61bd06992702..cb6f1fc03eaf 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -825,7 +825,8 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
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)."""
+ population (launched, person-aggregated, variants exist). A draft experiment passes only
+ for a scanner saved off with `start_on_launch`, which `experiment_launch` turns on."""
scanner_type = attrs.get("scanner_type", getattr(self.instance, "scanner_type", None))
if scanner_type != ScannerType.EXPERIMENT:
return
@@ -833,12 +834,34 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
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
+ # 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 ( # noqa: PLC0415
+ experiment_status,
+ resolve_exposure_linkage,
+ validate_draft_experiment_scope,
+ )
+
+ team = self.context["get_team"]()
config = attrs.get("scanner_config", getattr(self.instance, "scanner_config", None)) or {}
+ enabled = attrs.get("enabled", self.instance.enabled if self.instance is not None else True)
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.
+ # linkage was checked when the scope was written. Only the launch can have moved since.
+ experiment_id = config.get("experiment_id")
+ turning_on = enabled and not self.instance.enabled
+ writes_marker = "start_on_launch" in config and "scanner_config" in attrs
+ if isinstance(experiment_id, int) and (turning_on or writes_marker):
+ status = experiment_status(team, experiment_id=experiment_id)
+ if turning_on and status is not None and status.start_date is None:
+ raise serializers.ValidationError(
+ {"enabled": "This experiment hasn't launched. Turn the scanner on after launch."}
+ )
+ launched = status is not None and status.start_date is not None
+ if "start_on_launch" in config and (turning_on or (writes_marker and launched)):
+ # A stale form can send the marker back after the launch consumed it, and the
+ # reconciler's launch catch-up would then turn the scanner on.
+ attrs["scanner_config"] = {k: v for k, v in config.items() if k != "start_on_launch"}
return
experiment_id = config.get("experiment_id")
if not isinstance(experiment_id, int):
@@ -848,16 +871,21 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
# 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
-
+ status = experiment_status(team, experiment_id=experiment_id)
+ waits_for_launch = (
+ status is not None and status.start_date is None and not enabled and config.get("start_on_launch") is True
+ )
try:
- resolve_exposure_linkage(
- self.context["get_team"](), experiment_id=experiment_id, variants=config.get("variants")
- )
+ if waits_for_launch:
+ validate_draft_experiment_scope(team, experiment_id=experiment_id, variants=config.get("variants"))
+ else:
+ resolve_exposure_linkage(team, experiment_id=experiment_id, variants=config.get("variants"))
except serializers.ValidationError as exc:
raise serializers.ValidationError({"scanner_config": exc.detail}) from exc
+ if not waits_for_launch and "start_on_launch" in config and "scanner_config" in attrs:
+ # Only a draft has a launch to wait for. A stale key would turn the scanner on at a
+ # later relaunch.
+ attrs["scanner_config"] = {k: v for k, v in config.items() if k != "start_on_launch"}
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
diff --git a/products/replay_vision/backend/apps.py b/products/replay_vision/backend/apps.py
index 85ffb574ed1b..16d918458cb7 100644
--- a/products/replay_vision/backend/apps.py
+++ b/products/replay_vision/backend/apps.py
@@ -11,6 +11,7 @@ class ReplayVisionConfig(AppConfig):
# Temporal workers and commands write scanners too, so the receivers connect in every process.
from products.replay_vision.backend import ( # noqa: F401, PLC0415
activity_logging,
+ experiment_launch,
media_expiry,
search_suggestion_cleanup,
)
diff --git a/products/replay_vision/backend/experiment_launch.py b/products/replay_vision/backend/experiment_launch.py
new file mode 100644
index 000000000000..91e8647faa61
--- /dev/null
+++ b/products/replay_vision/backend/experiment_launch.py
@@ -0,0 +1,92 @@
+from collections import defaultdict
+from typing import Any
+
+from django.db import transaction
+
+from products.experiments.backend.facade.launch_signals import connect_experiment_launched
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
+
+START_ON_LAUNCH_KEY = "start_on_launch"
+
+
+def start_scanners_waiting_for_launch(
+ *, team_id: int, experiment_id: int, enabled_by: str = "experiment_launch", **kwargs: Any
+) -> int:
+ """Turn on the experiment's scanners saved off with `start_on_launch`, and return how many.
+
+ Runs as the launch signal's receiver, and again from the reconciler for a launch whose receiver
+ failed, so it is safe to run more than once.
+ """
+ started: list[ReplayScanner] = []
+ with transaction.atomic():
+ waiting = (
+ ReplayScanner.objects.select_related("created_by", "team")
+ .select_for_update(of=("self",))
+ .filter(
+ team_id=team_id,
+ scanner_type=ScannerType.EXPERIMENT,
+ enabled=False,
+ scanner_config__experiment_id=experiment_id,
+ scanner_config__start_on_launch=True,
+ )
+ )
+ for scanner in waiting:
+ # Cleared with the enable, so a reset and relaunch never turns on a scanner its owner
+ # turned off after the first launch.
+ scanner.scanner_config = {k: v for k, v in scanner.scanner_config.items() if k != START_ON_LAUNCH_KEY}
+ # nosemgrep: semgrep.rules.security.replay-vision-alert-state-direct-mutation — enables a ReplayScanner, not an alert; scanners have no state machine.
+ scanner.enabled = True
+ scanner.save(update_fields=["scanner_config", "enabled"])
+ started.append(scanner)
+ if not started:
+ return 0
+ # Deferred: both are heavy, and this module loads in every process at startup.
+ from posthog.event_usage import report_user_action # noqa: PLC0415
+
+ from products.replay_vision.backend.api.scanners import scanner_lifecycle_properties # noqa: PLC0415
+
+ for scanner in started:
+ if scanner.created_by is None:
+ continue
+ report_user_action(
+ scanner.created_by,
+ "replay_vision_scanner_enabled",
+ {**scanner_lifecycle_properties(scanner), "enabled_by": enabled_by},
+ team=scanner.team,
+ )
+ return len(started)
+
+
+def start_scanners_of_launched_experiments() -> int:
+ """Start the waiting scanners of every experiment that has launched, and return how many.
+
+ The launch signal starts them, but its receiver is best-effort so it can never fail a launch.
+ The launch has committed by then, so nothing else would retry a failed start.
+ """
+ # 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 launched_experiment_ids # noqa: PLC0415
+
+ waiting = (
+ ReplayScanner.objects.filter(
+ scanner_type=ScannerType.EXPERIMENT, enabled=False, scanner_config__start_on_launch=True
+ )
+ .values_list("team_id", "scanner_config__experiment_id")
+ .distinct()
+ )
+ experiment_ids_by_team: dict[int, set[int]] = defaultdict(set)
+ for team_id, experiment_id in waiting:
+ if isinstance(experiment_id, int):
+ experiment_ids_by_team[team_id].add(experiment_id)
+ started = 0
+ for team_id, experiment_ids in experiment_ids_by_team.items():
+ for experiment_id in launched_experiment_ids(team_id, experiment_ids):
+ started += start_scanners_waiting_for_launch(
+ team_id=team_id, experiment_id=experiment_id, enabled_by="experiment_launch_retry"
+ )
+ return started
+
+
+connect_experiment_launched(
+ start_scanners_waiting_for_launch, dispatch_uid="replay_vision.start_scanners_waiting_for_launch"
+)
diff --git a/products/replay_vision/backend/scanner_config.py b/products/replay_vision/backend/scanner_config.py
index 3bb3e226615c..175a582f539d 100644
--- a/products/replay_vision/backend/scanner_config.py
+++ b/products/replay_vision/backend/scanner_config.py
@@ -61,6 +61,9 @@ def scanner_config_error(scanner_type: ScannerType, scanner_config: Any) -> str
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."
+ start_on_launch = scanner_config.get("start_on_launch")
+ if start_on_launch is not None and not isinstance(start_on_launch, bool):
+ return "start_on_launch 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 2bef9e2c1024..2dcbbcdff0ac 100644
--- a/products/replay_vision/backend/scout_writes.py
+++ b/products/replay_vision/backend/scout_writes.py
@@ -93,7 +93,14 @@ def check_scout_scanner_credit_limit(
return
if "credit_limit" in attrs and attrs["credit_limit"] is None:
raise ValidationError({"credit_limit": CREDIT_LIMIT_NOT_CLEARABLE})
- turning_on = attrs.get("enabled") and not instance.enabled
+ # Arming a disabled experiment scanner to start on launch is a deferred enable.
+ arms_start_on_launch = (
+ instance.scanner_type == ScannerType.EXPERIMENT
+ and isinstance(attrs.get("scanner_config"), dict)
+ and attrs["scanner_config"].get("start_on_launch") is True
+ and (instance.scanner_config or {}).get("start_on_launch") is not True
+ )
+ turning_on = (attrs.get("enabled") and not instance.enabled) or arms_start_on_launch
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:
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index 94c808db199f..b60abf6bee05 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -42,6 +42,7 @@ from products.replay_vision.backend.temporal.activities import (
reap_orphaned_observations_activity,
refresh_scanner_estimate_activity,
resolve_experiment_variant_activity,
+ start_launched_scanners_activity,
upload_video_to_gemini_activity,
upsert_scanner_schedule_activity,
)
@@ -148,6 +149,7 @@ ACTIVITIES: list[Callable[..., Any]] = [
meter_scanner_read_bytes_activity,
reap_childless_inline_scanners_activity,
reap_orphaned_observations_activity,
+ start_launched_scanners_activity,
sweep_gemini_files_activity,
judge_watch_ranks_activity,
list_stale_search_suggestions_activity,
@@ -203,6 +205,7 @@ __all__ = [
"reap_childless_inline_scanners_activity",
"reap_orphaned_observations_activity",
"refresh_scanner_estimate_activity",
+ "start_launched_scanners_activity",
"sweep_gemini_files_activity",
"upload_video_to_gemini_activity",
"upsert_scanner_schedule_activity",
diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.py
index 86fee420ac0c..0145e42e3196 100644
--- a/products/replay_vision/backend/temporal/activities/__init__.py
+++ b/products/replay_vision/backend/temporal/activities/__init__.py
@@ -63,6 +63,7 @@ from products.replay_vision.backend.temporal.activities.refresh_scanner_estimate
from products.replay_vision.backend.temporal.activities.resolve_experiment_variant import (
resolve_experiment_variant_activity,
)
+from products.replay_vision.backend.temporal.activities.start_launched_scanners import start_launched_scanners_activity
from products.replay_vision.backend.temporal.activities.upload_video_to_gemini import upload_video_to_gemini_activity
__all__ = [
@@ -105,6 +106,7 @@ __all__ = [
"reap_childless_inline_scanners_activity",
"reap_orphaned_observations_activity",
"resolve_experiment_variant_activity",
+ "start_launched_scanners_activity",
"refresh_scanner_estimate_activity",
"upload_video_to_gemini_activity",
"upsert_scanner_schedule_activity",
diff --git a/products/replay_vision/backend/temporal/activities/start_launched_scanners.py b/products/replay_vision/backend/temporal/activities/start_launched_scanners.py
new file mode 100644
index 000000000000..bfb5e2f96b2c
--- /dev/null
+++ b/products/replay_vision/backend/temporal/activities/start_launched_scanners.py
@@ -0,0 +1,30 @@
+"""Starts experiment scanners that are still waiting for an experiment that has already launched.
+
+The launch signal starts them, but its receiver must never fail a launch, so a failure there is only
+logged. The launch has committed by then, and a relaunch does not send the signal again, so without
+this the scanner stays off for good.
+"""
+
+from temporalio import activity
+
+from posthog.sync import database_sync_to_async
+
+from products.replay_vision.backend.experiment_launch import start_scanners_of_launched_experiments
+from products.replay_vision.backend.temporal.constants import REAPER_OP_TIMEOUT
+from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
+
+
+@database_sync_to_async
+def _start_launched_scanners() -> int:
+ with bounded_queries(REAPER_OP_TIMEOUT):
+ return start_scanners_of_launched_experiments()
+
+
+@track_activity()
+async def start_launched_scanners_activity() -> int:
+ started = await _start_launched_scanners()
+ if started:
+ activity.logger.info("Started scanners whose experiment launched", extra={"started": started})
+ return started
diff --git a/products/replay_vision/backend/temporal/reconciler.py b/products/replay_vision/backend/temporal/reconciler.py
index c8daba8c5cf9..142ad25f5d37 100644
--- a/products/replay_vision/backend/temporal/reconciler.py
+++ b/products/replay_vision/backend/temporal/reconciler.py
@@ -50,6 +50,7 @@ with workflow.unsafe.imports_passed_through():
reap_backfill_schedules_activity,
reap_childless_inline_scanners_activity,
reap_orphaned_observations_activity,
+ start_launched_scanners_activity,
upsert_scanner_schedule_activity,
)
@@ -110,6 +111,12 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):
except Exception:
workflow.logger.exception("replay_vision.reap_backfill_schedules_failed")
+ if workflow.patched("start-launched-scanners-2026-10"):
+ try:
+ await self._run_reaper(start_launched_scanners_activity)
+ except Exception:
+ workflow.logger.exception("replay_vision.start_launched_scanners_failed")
+
async def _sync_schedules(self) -> tuple[ReconcileScannerSchedulesResult, ApplicationError | None]:
"""Converge per-scanner schedules with the table. Returns the result plus a systemic failure to
raise once the rest of the tick is done."""
diff --git a/products/replay_vision/backend/temporal/scanners/experiment.py b/products/replay_vision/backend/temporal/scanners/experiment.py
index 30b861050527..23a21b481810 100644
--- a/products/replay_vision/backend/temporal/scanners/experiment.py
+++ b/products/replay_vision/backend/temporal/scanners/experiment.py
@@ -37,6 +37,13 @@ class ExperimentScanner(SummarizerScanner, frozen=True):
default=True,
description="Sample each watched variant about evenly instead of proportionally to rollout.",
)
+ # Lifecycle intent, not scan config, so model dumps leave it out. The launch receiver clears
+ # it from the stored config before the first scan.
+ start_on_launch: bool = Field(
+ default=False,
+ exclude=True,
+ description="Saved disabled on a draft experiment; turned on when the experiment launches.",
+ )
# 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.
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 03668891a42f..dbf0b6f6bf5d 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -40,6 +40,7 @@ from products.replay_vision.backend.api.scanners import (
from products.replay_vision.backend.api.trigger import WorkflowStartOutcome, start_apply_scanner_workflow
from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.enqueue_claims import _scanner_key, _team_key, pending_enqueue_claims_for_team
+from products.replay_vision.backend.experiment_launch import start_scanners_of_launched_experiments
from products.replay_vision.backend.jev_watch_feed import store_watch_ranks
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
@@ -388,6 +389,93 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
self.assertEqual(with_column.status_code, 400, with_column.json())
self.assertEqual(with_column.json()["attr"], "experiment_targeting")
+ def test_experiment_scanner_saved_off_on_a_draft_turns_on_at_launch(self) -> None:
+ draft = create_experiment(self.team, "waiting-flag", variants=["control", "test"])
+ other_draft = create_experiment(self.team, "other-draft-flag", variants=["control", "test"])
+
+ def post(name: str, experiment_id: int, *, enabled: bool, **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,
+ "start_on_launch": True,
+ **config_overrides,
+ },
+ "model": ScannerModel.GEMINI_3_8_FLASH,
+ "enabled": enabled,
+ },
+ format="json",
+ )
+
+ enabled_on_draft = post("enabled-on-draft", draft.id, enabled=True)
+ self.assertEqual(enabled_on_draft.status_code, 400, enabled_on_draft.json())
+ self.assertIn("hasn't launched", enabled_on_draft.json()["detail"])
+
+ unknown_variant = post("unknown-variant-on-draft", draft.id, enabled=False, variants=["nope"])
+ self.assertEqual(unknown_variant.status_code, 400, unknown_variant.json())
+ self.assertIn("not a variant", unknown_variant.json()["detail"])
+
+ waiting = post("waiting", draft.id, enabled=False)
+ self.assertEqual(waiting.status_code, 201, waiting.json())
+ other = post("waiting-on-other-draft", other_draft.id, enabled=False)
+ self.assertEqual(other.status_code, 201, other.json())
+
+ early_enable = self.client.patch(
+ f"{self.scanners_url}{waiting.json()['id']}/", data={"enabled": True}, format="json"
+ )
+ self.assertEqual(early_enable.status_code, 400, early_enable.json())
+ self.assertEqual(early_enable.json()["attr"], "enabled")
+
+ launch = self.client.post(f"/api/projects/{self.team.id}/experiments/{draft.id}/launch/")
+ self.assertEqual(launch.status_code, 200, launch.json())
+
+ started = ReplayScanner.objects.get(id=waiting.json()["id"])
+ self.assertTrue(started.enabled)
+ self.assertNotIn("start_on_launch", started.scanner_config)
+ self.assertFalse(ReplayScanner.objects.get(id=other.json()["id"]).enabled)
+
+ # Setting a start date on a draft also launches it, through the experiment update path.
+ patch_launch = self.client.patch(
+ f"/api/projects/{self.team.id}/experiments/{other_draft.id}/",
+ data={"start_date": "2026-09-01T00:00:00Z"},
+ format="json",
+ )
+ self.assertEqual(patch_launch.status_code, 200, patch_launch.json())
+ self.assertTrue(ReplayScanner.objects.get(id=other.json()["id"]).enabled)
+
+ def test_stale_save_after_launch_drops_the_start_on_launch_marker(self) -> None:
+ draft = create_experiment(self.team, "stale-form-flag", variants=["control", "test"])
+ config = {"prompt": "p", "experiment_id": draft.id, "start_on_launch": True}
+ created = self.client.post(
+ self.scanners_url,
+ data={
+ "name": "stale-form",
+ "scanner_type": ScannerType.EXPERIMENT,
+ "scanner_config": config,
+ "model": ScannerModel.GEMINI_3_8_FLASH,
+ "enabled": False,
+ },
+ format="json",
+ )
+ self.assertEqual(created.status_code, 201, created.json())
+ scanner_url = f"{self.scanners_url}{created.json()['id']}/"
+ launch = self.client.post(f"/api/projects/{self.team.id}/experiments/{draft.id}/launch/")
+ self.assertEqual(launch.status_code, 200, launch.json())
+ self.client.patch(scanner_url, data={"enabled": False}, format="json")
+
+ stale = self.client.patch(scanner_url, data={"enabled": False, "scanner_config": config}, format="json")
+ self.assertEqual(stale.status_code, 200, stale.json())
+
+ scanner = ReplayScanner.objects.get(id=created.json()["id"])
+ self.assertNotIn("start_on_launch", scanner.scanner_config)
+ start_scanners_of_launched_experiments()
+ scanner.refresh_from_db()
+ self.assertFalse(scanner.enabled)
+
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.
diff --git a/products/replay_vision/backend/tests/test_reconciler.py b/products/replay_vision/backend/tests/test_reconciler.py
index 2376b9e1ba3b..a351ad9072f2 100644
--- a/products/replay_vision/backend/tests/test_reconciler.py
+++ b/products/replay_vision/backend/tests/test_reconciler.py
@@ -35,6 +35,7 @@ from products.replay_vision.backend.temporal.activities import (
reap_backfill_schedules_activity,
reap_childless_inline_scanners_activity,
reap_orphaned_observations_activity,
+ start_launched_scanners_activity,
upsert_scanner_schedule_activity,
)
from products.replay_vision.backend.temporal.constants import (
@@ -61,6 +62,7 @@ from products.replay_vision.backend.temporal.schedule import (
compute_schedule_fingerprint,
load_enabled_scanner_fingerprints,
)
+from products.replay_vision.backend.tests.helpers import create_experiment
def _live_activity_env() -> ActivityEnvironment:
@@ -236,7 +238,11 @@ class _ReconcileMocks:
async def execute_activity(self, activity_fn: Any, activity_input: Any = None, **_: Any) -> Any:
self.calls.append(activity_fn)
- if activity_fn in (reap_childless_inline_scanners_activity, reap_backfill_schedules_activity):
+ if activity_fn in (
+ reap_childless_inline_scanners_activity,
+ reap_backfill_schedules_activity,
+ start_launched_scanners_activity,
+ ):
return 0
if activity_fn is reap_orphaned_observations_activity:
self.reap_calls += 1
@@ -627,3 +633,39 @@ async def test_reap_childless_inline_scanners_activity(org_team) -> None:
assert rows["childless_old"].id not in surviving
for key in ("childless_fresh", "has_observation", "configured", "childless_but_claimed"):
assert rows[key].id in surviving, key
+
+
[email protected]_db(transaction=True)
+async def test_start_launched_scanners_activity(org_team) -> None:
+ # The launch signal's receiver never fails a launch, so a failure there leaves the scanner off
+ # after the launch has committed. The reconciler starts it on its next tick. A scanner on a
+ # draft keeps waiting.
+ _, team = org_team
+
+ def _setup() -> tuple[ReplayScanner, ReplayScanner]:
+ launched = create_experiment(team, "launched-flag", launched=True, variants=["control", "test"])
+ draft = create_experiment(team, "draft-flag", variants=["control", "test"])
+
+ def waiting(name: str, experiment_id: int) -> ReplayScanner:
+ return _make_scanner(
+ team,
+ name=name,
+ scanner_type=ScannerType.EXPERIMENT,
+ enabled=False,
+ scanner_config={"prompt": "p", "experiment_id": experiment_id, "start_on_launch": True},
+ )
+
+ return waiting("missed-launch", launched.id), waiting("still-draft", draft.id)
+
+ missed, still_waiting = await sync_to_async(_setup)()
+
+ started = await _live_activity_env().run(start_launched_scanners_activity)
+
+ assert started == 1
+ await sync_to_async(missed.refresh_from_db)()
+ await sync_to_async(still_waiting.refresh_from_db)()
+ assert missed.enabled is True
+ assert "start_on_launch" not in missed.scanner_config
+ assert still_waiting.enabled is False
+ assert await _live_activity_env().run(start_launched_scanners_activity) == 0
diff --git a/products/replay_vision/backend/tests/test_scout_writes.py b/products/replay_vision/backend/tests/test_scout_writes.py
index cb29635fe270..8c83cc919cfe 100644
--- a/products/replay_vision/backend/tests/test_scout_writes.py
+++ b/products/replay_vision/backend/tests/test_scout_writes.py
@@ -115,6 +115,39 @@ class TestScoutScannerCreditLimit(SimpleTestCase):
{"enabled": True, "credit_limit": 500},
True,
),
+ (
+ "arming_an_uncapped_experiment_scanner_to_start_on_launch",
+ {
+ "credit_limit": None,
+ "enabled": False,
+ "scanner_type": "experiment",
+ "scanner_config": {"experiment_id": 1},
+ },
+ {"scanner_config": {"experiment_id": 1, "start_on_launch": True}},
+ False,
+ ),
+ (
+ "arming_a_capped_experiment_scanner_to_start_on_launch",
+ {
+ "credit_limit": 500,
+ "enabled": False,
+ "scanner_type": "experiment",
+ "scanner_config": {"experiment_id": 1},
+ },
+ {"scanner_config": {"experiment_id": 1, "start_on_launch": True}},
+ True,
+ ),
+ (
+ "editing_an_uncapped_scanner_someone_else_armed",
+ {
+ "credit_limit": None,
+ "enabled": False,
+ "scanner_type": "experiment",
+ "scanner_config": {"experiment_id": 1, "start_on_launch": True},
+ },
+ {"scanner_config": {"prompt": "p", "experiment_id": 1, "start_on_launch": True}},
+ True,
+ ),
(
"re_sending_enabled_on_an_uncapped_scanner",
{"credit_limit": None, "enabled": True},