:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): add alert action mode to the sweep engine (#69565)
Kim Svatos Dugan0ab2f3cc42ec
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 4b2ae35d4af6..8b4456777840 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -571,6 +571,7 @@ SPECTACULAR_SETTINGS = {"ObservationTriggerEnum": "products.replay_vision.backend.models.replay_observation.ObservationTrigger","ExportedRecordingStatusEnum": "products.replay.backend.models.exported_recording.ExportedRecording.Status","VisionActionRunStatusEnum": "products.replay_vision.backend.models.vision_action.VisionActionRunStatus",+ "VisionAlertMetricEnum": "products.replay_vision.backend.models.vision_action.AlertMetric","AutonomyPriorityEnum": "products.signals.backend.models.AutonomyPriority","UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.facade.enums.SEARCH_DOCUMENT_TYPES","BatchExportRunStatusEnum": "products.batch_exports.backend.models.batch_export.BatchExportRun.Status",diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.pyindex 3768e579f313..40f2ef971e42 100644--- a/products/replay_vision/backend/api/vision_actions.py+++ b/products/replay_vision/backend/api/vision_actions.py@@ -24,15 +24,18 @@ from products.replay_vision.backend.feature_flag import (ReplayVisionEnabledPermission,)from products.replay_vision.backend.models.replay_observation import ReplayObservation-from products.replay_vision.backend.models.replay_scanner import ReplayScanner+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerTypefrom products.replay_vision.backend.models.vision_action import (ActionMode,+ AlertFrequency,+ AlertMetric,TriggerType,VisionAction,VisionActionRun,VisionActionRunStatus,)from products.replay_vision.backend.rrule import validate_rrule, validate_timezone+from products.replay_vision.backend.scanner_access import readable_scanner_idsfrom products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdictlogger = structlog.get_logger(__name__)@@ -89,6 +92,65 @@ class SelectionSerializer(serializers.Serializer):return attrs+class AlertConfigSerializer(serializers.Serializer):+ """The alert condition for mode='alert', applied after `selection` targeting. 'every_match'+ notifies about each new match since the previous check; 'on_breach' compares a metric to a+ threshold over a rolling window and notifies on the transition into breach."""++ frequency = serializers.ChoiceField(+ choices=AlertFrequency.choices,+ required=False,+ default=AlertFrequency.ON_BREACH,+ help_text=(+ "'every_match' notifies about every new matching observation (batched per check); "+ "'on_breach' notifies once when the threshold condition starts holding. Defaults to 'on_breach'."+ ),+ )+ metric = serializers.ChoiceField(+ choices=AlertMetric.choices,+ required=False,+ default=AlertMetric.COUNT,+ help_text=(+ "What to measure over the window: 'count' of targeted observations, or 'avg_score' "+ "(the mean scorer score; scorer scanners only). every_match supports 'count' only."+ ),+ )+ threshold = serializers.FloatField(+ required=False,+ help_text=(+ "The alert fires when the metric is at or above this value. Required for on_breach; "+ "ignored for every_match."+ ),+ )+ window_days = serializers.ChoiceField(+ choices=[(d, f"{d} day{'s' if d != 1 else ''}") for d in (1, 3, 7, 14, 30)],+ required=False,+ help_text=(+ "Rolling lookback window for on_breach conditions, ending at each check. Defaults to 1 day. "+ "every_match ignores it (each check covers what's new since the previous one)."+ ),+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ frequency = attrs.get("frequency", AlertFrequency.ON_BREACH)+ if frequency == AlertFrequency.EVERY_MATCH:+ if attrs.get("metric", AlertMetric.COUNT) == AlertMetric.AVG_SCORE:+ raise serializers.ValidationError(+ {"metric": "every_match alerts count new matches; avg_score requires on_breach."}+ )+ else:+ if attrs.get("threshold") is None:+ raise serializers.ValidationError({"threshold": "on_breach alerts require a threshold."})+ return attrs++ def to_representation(self, instance: dict[str, Any]) -> dict[str, Any]:+ # Non-alert actions store the {} default; represent it as-is rather than KeyErroring on the+ # required fields. Writes still validate the full shape whenever alert_config is provided.+ if not instance:+ return {}+ return cast(dict[str, Any], super().to_representation(instance))++class SynthesisConfigSerializer(serializers.Serializer):"""Options for the group-summary synthesis step."""@@ -115,6 +177,11 @@ class DeliveryTargetSerializer(serializers.Serializer):)+# Alerts ride the scanner's sweep, so each enabled alert adds evaluation work to every sweep tick —+# cap the fan-out one scanner can accumulate.+MAX_ENABLED_ALERTS_PER_SCANNER = 10++class VisionActionSerializer(serializers.ModelSerializer):name = serializers.CharField(max_length=255,@@ -157,6 +224,10 @@ class VisionActionSerializer(serializers.ModelSerializer):required=False,help_text="Synthesis options for the group summary, e.g. {prompt_guide}.",)+ alert_config = AlertConfigSerializer(+ required=False,+ help_text="Alert condition; required when mode is 'alert', ignored otherwise.",+ )delivery_config = DeliveryTargetSerializer(many=True,required=False,@@ -197,6 +268,7 @@ class VisionActionSerializer(serializers.ModelSerializer):"trigger_config","selection","synthesis_config",+ "alert_config","delivery_config","next_run_at","last_run_at",@@ -222,7 +294,9 @@ class VisionActionSerializer(serializers.ModelSerializer):def validate_mode(self, value: str) -> str:if value == ActionMode.PER_OBSERVATION:- raise serializers.ValidationError("Per-observation mode is not supported yet. Use 'group_summary'.")+ raise serializers.ValidationError(+ "Per-observation mode is not supported yet. Use 'group_summary' or 'alert'."+ )return valuedef validate_delivery_config(self, value: list[dict[str, Any]]) -> list[dict[str, Any]]:@@ -242,8 +316,64 @@ class VisionActionSerializer(serializers.ModelSerializer):self._validate_schedule(attrs)self._validate_unique_name(attrs)self._validate_unique_digest(attrs)+ self._validate_alert(attrs)+ self._validate_scanner_access(attrs)return attrs+ def _validate_scanner_access(self, attrs: dict[str, Any]) -> None:+ # The engine reads observations as the action's CREATOR (fail-closed run-time gate in+ # scanner_access.readable_scanner_ids). Without this write-time check, an editor with less+ # scanner access than the creator could re-point a creator-privileged action at data the+ # editor can't read and receive it via the delivery channel. Only re-check when the+ # targeting actually changes, so unrelated edits (rename, disable) don't require it.+ if "scanner" not in attrs and "selection" not in attrs:+ return+ scanner = attrs.get("scanner", getattr(self.instance, "scanner", None))+ selection = attrs.get("selection", getattr(self.instance, "selection", None)) or {}+ requested = [str(s) for s in (selection.get("scanner_ids") or ([scanner.id] if scanner else []))]+ if not requested:+ return+ request = self.context.get("request")+ if request is None or not getattr(request.user, "is_authenticated", False):+ return+ team = self.context["get_team"]()+ readable = set(readable_scanner_ids(request.user, team, requested))+ if set(requested) - readable:+ raise serializers.ValidationError(+ {"scanner": "You don't have access to one or more scanners this action targets."}+ )++ def _validate_alert(self, attrs: dict[str, Any]) -> None:+ mode = attrs.get("mode", getattr(self.instance, "mode", ActionMode.GROUP_SUMMARY))+ if mode != ActionMode.ALERT:+ return+ alert_config = attrs.get("alert_config", getattr(self.instance, "alert_config", None)) or {}+ if not alert_config:+ raise serializers.ValidationError({"alert_config": "Alert actions require an alert_config."})+ if alert_config.get("metric") == AlertMetric.AVG_SCORE:+ scanner = attrs.get("scanner", getattr(self.instance, "scanner", None))+ if scanner is not None and scanner.scanner_type != ScannerType.SCORER:+ raise serializers.ValidationError(+ {"alert_config": "The avg_score metric only applies to scorer scanners."}+ )+ self._validate_alert_cap(attrs)++ def _validate_alert_cap(self, attrs: dict[str, Any]) -> None:+ # Alerts evaluate on the scanner's sweep, so unbounded alert fan-out multiplies sweep work.+ # Cap enabled alerts per scanner; disabled ones don't cost anything and don't count.+ enabled = attrs.get("enabled", getattr(self.instance, "enabled", True))+ scanner = attrs.get("scanner", getattr(self.instance, "scanner", None))+ if not enabled or scanner is None:+ return+ team = self.context["get_team"]()+ others = VisionAction.objects.for_team(team.id).filter(scanner=scanner, mode=ActionMode.ALERT, enabled=True)+ if self.instance is not None:+ others = others.exclude(pk=self.instance.pk)+ if others.count() >= MAX_ENABLED_ALERTS_PER_SCANNER:+ raise serializers.ValidationError(+ {"mode": f"A scanner can have at most {MAX_ENABLED_ALERTS_PER_SCANNER} enabled alerts."}+ )+def _validate_schedule(self, attrs: dict[str, Any]) -> None:trigger_type = attrs.get("trigger_type", getattr(self.instance, "trigger_type", TriggerType.SCHEDULE))trigger_config = attrs.get("trigger_config", getattr(self.instance, "trigger_config", None)) or {}@@ -398,7 +528,10 @@ class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# so the abort reasons read correctly under the "failed" banner they actually carry._RUN_REASON_LABELS = {"skipped_empty": "No new observations in this window to summarize.",+ "skipped_not_breached": "The alert condition wasn't met in this window.","skipped_over_budget": "The team is over its AI-credit budget.",+ "not_breached": "The alert condition wasn't met in this window.",+ "still_breached": "The condition is still met; an earlier check already sent the notification.",# Legacy: the engine no longer skips actions with no delivery_config (digest runs are in-app only).# Keep both keys so historical run rows still display a readable reason rather than the raw enum."no_delivery": "No delivery destination is configured for this action.",@@ -584,4 +717,15 @@ class VisionActionRunViewSet(def safely_get_queryset(self, queryset: QuerySet[VisionActionRun]) -> QuerySet[VisionActionRun]:action = self._action_for_url()- return queryset.filter(team_id=self.team_id, vision_action_id=action.id).order_by("-created_at", "id")+ return (+ queryset.filter(team_id=self.team_id, vision_action_id=action.id)+ # Alert-state bookkeeping runs exist so the engine can resolve breach transitions+ # (alerts._EVALUATED_SKIP_REASONS — literals duplicated here to keep the temporal+ # package off the API import path). They aren't user-facing outcomes: run history+ # shows actual firings, failures, and summary skips, not every quiet check.+ .exclude(+ status=VisionActionRunStatus.SKIPPED,+ error__skip_reason__in=["not_breached", "still_breached"],+ )+ .order_by("-created_at", "id")+ )diff --git a/products/replay_vision/backend/migrations/0045_visionaction_alert_config_alter_visionaction_mode.py b/products/replay_vision/backend/migrations/0045_visionaction_alert_config_alter_visionaction_mode.pynew file mode 100644index 000000000000..35c6360fe536--- /dev/null+++ b/products/replay_vision/backend/migrations/0045_visionaction_alert_config_alter_visionaction_mode.py@@ -0,0 +1,33 @@+# Generated by Django 5.2.14 on 2026-07-09 05:43++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("replay_vision", "0044_replayscanner_feedback_themes")]++ operations = [+ migrations.AddField(+ model_name="visionaction",+ name="alert_config",+ field=models.JSONField(+ blank=True,+ default=dict,+ help_text="Alert condition for mode='alert': {metric: count|avg_score, operator: gt|gte|lt|lte|eq, threshold: number}, evaluated over the run's observation window after `selection` targeting.",+ ),+ ),+ migrations.AlterField(+ model_name="visionaction",+ name="mode",+ field=models.CharField(+ choices=[+ ("group_summary", "Group summary"),+ ("alert", "Alert"),+ ("per_observation", "Per observation"),+ ],+ default="group_summary",+ help_text="What the action produces: a scheduled group summary, or an alert that only delivers when its condition holds.",+ max_length=20,+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/0046_alter_visionaction_alert_config.py b/products/replay_vision/backend/migrations/0046_alter_visionaction_alert_config.pynew file mode 100644index 000000000000..312c3c3d5794--- /dev/null+++ b/products/replay_vision/backend/migrations/0046_alter_visionaction_alert_config.py@@ -0,0 +1,19 @@+# Generated by Django 5.2.14 on 2026-07-09 07:07++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("replay_vision", "0045_visionaction_alert_config_alter_visionaction_mode")]++ operations = [+ migrations.AlterField(+ model_name="visionaction",+ name="alert_config",+ field=models.JSONField(+ blank=True,+ default=dict,+ help_text="Alert condition for mode='alert': {metric: count|avg_score, operator: gt|gte|lt|lte|eq, threshold: number, window_days: 1|3|7|14|30}, evaluated over a rolling window ending at each check, after `selection` targeting.",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/0047_alter_visionaction_alert_config.py b/products/replay_vision/backend/migrations/0047_alter_visionaction_alert_config.pynew file mode 100644index 000000000000..43cfb52d5124--- /dev/null+++ b/products/replay_vision/backend/migrations/0047_alter_visionaction_alert_config.py@@ -0,0 +1,19 @@+# Generated by Django 5.2.14 on 2026-07-09 16:29++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("replay_vision", "0046_alter_visionaction_alert_config")]++ operations = [+ migrations.AlterField(+ model_name="visionaction",+ name="alert_config",+ field=models.JSONField(+ blank=True,+ default=dict,+ help_text="Alert condition for mode='alert': {frequency: every_match|on_breach, metric, operator, threshold, window_days}. every_match notifies about each new match since the previous check; on_breach compares the metric to the threshold over a rolling window, after `selection` targeting.",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/0048_alter_visionaction_alert_config.py b/products/replay_vision/backend/migrations/0048_alter_visionaction_alert_config.pynew file mode 100644index 000000000000..0e3f2e94159c--- /dev/null+++ b/products/replay_vision/backend/migrations/0048_alter_visionaction_alert_config.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.14 on 2026-07-13 18:35++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0047_alter_visionaction_alert_config"),+ ]++ operations = [+ migrations.AlterField(+ model_name="visionaction",+ name="alert_config",+ field=models.JSONField(+ blank=True,+ default=dict,+ help_text="Alert condition for mode='alert': {frequency: every_match|on_breach, metric, threshold, window_days}. every_match notifies about each new match since the previous check; on_breach fires when the metric reaches the threshold over a rolling window, after `selection` targeting.",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex 665614d23a67..4380c5369d44 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0044_replayscanner_feedback_themes+0048_alter_visionaction_alert_configdiff --git a/products/replay_vision/backend/models/vision_action.py b/products/replay_vision/backend/models/vision_action.pyindex e677f464bf0c..a94cfb7ff1c2 100644--- a/products/replay_vision/backend/models/vision_action.py+++ b/products/replay_vision/backend/models/vision_action.py@@ -22,9 +22,22 @@ class TriggerType(models.TextChoices):class ActionMode(models.TextChoices):GROUP_SUMMARY = "group_summary", "Group summary" # one summary synthesized from a group of observations+ ALERT = "alert", "Alert" # deliver only when the alert condition holds over the windowPER_OBSERVATION = "per_observation", "Per observation" # reserved; rejected at the API for now+class AlertFrequency(models.TextChoices):+ # Notify about every new match since the previous check (tiled windows, batched per check).+ EVERY_MATCH = "every_match", "Every new match"+ # Notify when the metric crosses the threshold over a rolling window; re-arms after it clears.+ ON_BREACH = "on_breach", "When a threshold is crossed"+++class AlertMetric(models.TextChoices):+ COUNT = "count", "Count of matching observations"+ AVG_SCORE = "avg_score", "Average score" # scorer scanners only++class VisionAction(TeamScopedRootMixin, UUIDModel):"""An "and then…" automation over a scanner's observations: gather, (optionally) synthesize, deliver.@@ -58,7 +71,7 @@ class VisionAction(TeamScopedRootMixin, UUIDModel):max_length=20,choices=ActionMode.choices,default=ActionMode.GROUP_SUMMARY,- help_text="What the action produces. MVP supports 'group_summary' only.",+ help_text="What the action produces: a scheduled group summary, or an alert that only delivers when its condition holds.",)next_run_at = models.DateTimeField(@@ -81,6 +94,15 @@ class VisionAction(TeamScopedRootMixin, UUIDModel):),)synthesis_config = models.JSONField(default=dict, help_text="Synthesis options, e.g. {prompt_guide}.")+ alert_config = models.JSONField(+ default=dict,+ blank=True,+ help_text=(+ "Alert condition for mode='alert': {frequency: every_match|on_breach, metric, threshold, "+ "window_days}. every_match notifies about each new match since the previous check; on_breach "+ "fires when the metric reaches the threshold over a rolling window, after `selection` targeting."+ ),+ )# How many observations may feed one group summary. When the window holds more, they're sampled# evenly across it (not just the newest). Not exposed in the API/UI yet — tune via Django admin.max_observations = models.PositiveIntegerField(diff --git a/products/replay_vision/backend/scanner_access.py b/products/replay_vision/backend/scanner_access.pynew file mode 100644index 000000000000..8f41cf2a312a--- /dev/null+++ b/products/replay_vision/backend/scanner_access.py@@ -0,0 +1,45 @@+"""Scanner-level RBAC helper shared by the vision-action engine (run-time creator gate) and the+API serializer (write-time editor gate). Lives outside `temporal/` so the API can import it without+pulling the temporal package onto its import path."""++import uuid+from typing import TYPE_CHECKING++from posthog.models.team import Team+from posthog.rbac.user_access_control import UserAccessControl++from products.replay_vision.backend.models.replay_scanner import ReplayScanner++if TYPE_CHECKING:+ from posthog.models.user import User+++def is_uuid(value: str) -> bool:+ try:+ uuid.UUID(str(value))+ except (ValueError, TypeError):+ return False+ return True+++def readable_scanner_ids(user: "User", team: Team, scanner_ids: list[str]) -> list[str]:+ """Restrict an action's bound scanner ids to the ones the given user may actually read.++ A vision action's scanner binding is user-supplied, so without this a user could point an action+ at a same-team scanner they lack `replay_scanner` viewer access to and receive its recording-derived+ reasoning and outcome in the synthesized report. The engine applies it to the action's creator on+ every run; the serializer applies it to the requesting user whenever the targeting changes. Mirrors+ the scanner-access gate `max_tools` applies on interactive reads (object-level access control; note+ the underlying queryset filter is a no-op for orgs without the access-control feature, where no+ per-scanner restriction exists anyway).+ """+ # Drop non-UUID ids before querying: `selection.scanner_ids` is a user-supplied CharField list, and a+ # malformed value would raise ValidationError inside the Temporal activity on every run (a permanent+ # retry loop). Mirrors the UUID pre-validation in `max_tools._resolve_scanner_scope`.+ valid_ids = [scanner_id for scanner_id in scanner_ids if is_uuid(scanner_id)]+ if not valid_ids:+ return []+ readable = UserAccessControl(user=user, team=team).filter_queryset_by_access_level(+ ReplayScanner.objects.filter(team_id=team.id, id__in=valid_ids)+ )+ return [str(scanner_id) for scanner_id in readable.values_list("id", flat=True)]diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex e3403f8242e8..1965c50bb463 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -44,6 +44,7 @@ from products.replay_vision.backend.temporal.vision_actions import (ProcessVisionActionWorkflow,create_vision_action_run_activity,emit_action_ready_activity,+ evaluate_alert_activity,evaluate_due_vision_actions_activity,synthesize_group_summary_activity,update_vision_action_run_activity,@@ -91,6 +92,7 @@ ACTIVITIES: list[Callable[..., Any]] = [refresh_scanner_estimate_activity,reap_orphaned_observations_activity,sweep_gemini_files_activity,+ evaluate_alert_activity,evaluate_due_vision_actions_activity,create_vision_action_run_activity,validate_vision_action_activity,@@ -111,6 +113,7 @@ __all__ = ["SweepScannerWorkflow","create_vision_action_run_activity","emit_action_ready_activity",+ "evaluate_alert_activity","evaluate_due_vision_actions_activity","synthesize_group_summary_activity","update_vision_action_run_activity",diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.pyindex 5509539884b0..5d163bc6d769 100644--- a/products/replay_vision/backend/temporal/sweep_workflow.py+++ b/products/replay_vision/backend/temporal/sweep_workflow.py@@ -168,7 +168,10 @@ class SweepScannerWorkflow(PostHogWorkflow):await wf.start_child_workflow(PROCESS_VISION_ACTION_WORKFLOW_NAME,ProcessVisionActionInputs(- vision_action_id=d.vision_action_id, team_id=d.team_id, scheduled_at=d.scheduled_at+ vision_action_id=d.vision_action_id,+ team_id=d.team_id,+ scheduled_at=d.scheduled_at,+ mode=d.mode,),id=build_process_vision_action_workflow_id(d.vision_action_id),task_queue=settings.REPLAY_VISION_TASK_QUEUE,diff --git a/products/replay_vision/backend/temporal/vision_actions/__init__.py b/products/replay_vision/backend/temporal/vision_actions/__init__.pyindex b85e84ef11b3..472881723744 100644--- a/products/replay_vision/backend/temporal/vision_actions/__init__.py+++ b/products/replay_vision/backend/temporal/vision_actions/__init__.py@@ -5,6 +5,7 @@ from products.replay_vision.backend.temporal.vision_actions.activities import (update_vision_action_run_activity,validate_vision_action_activity,)+from products.replay_vision.backend.temporal.vision_actions.alerts import evaluate_alert_activityfrom products.replay_vision.backend.temporal.vision_actions.synthesis import synthesize_group_summary_activityfrom products.replay_vision.backend.temporal.vision_actions.types import (SynthesisStatus,@@ -20,6 +21,7 @@ __all__ = ["SynthesizeGroupSummaryResult","create_vision_action_run_activity","emit_action_ready_activity",+ "evaluate_alert_activity","evaluate_due_vision_actions_activity","synthesize_group_summary_activity","update_vision_action_run_activity",diff --git a/products/replay_vision/backend/temporal/vision_actions/activities.py b/products/replay_vision/backend/temporal/vision_actions/activities.pyindex f4781a3932c0..29b49d9968e4 100644--- a/products/replay_vision/backend/temporal/vision_actions/activities.py+++ b/products/replay_vision/backend/temporal/vision_actions/activities.py@@ -1,10 +1,11 @@"""Supporting activities for the vision-action engine: per-scanner eligibility/claim, run lifecycle, and emit."""-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom uuid import UUIDfrom django.conf import settingsfrom django.db import transaction+from django.db.models import Qimport structlogfrom temporalio import activity@@ -12,7 +13,10 @@ from temporalio import activityfrom posthog.cdp.internal_events import InternalEventEvent, produce_internal_eventfrom posthog.sync import database_sync_to_async+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservationfrom products.replay_vision.backend.models.vision_action import (+ ActionMode,+ AlertFrequency,TriggerType,VisionAction,VisionActionRun,@@ -33,6 +37,26 @@ logger = structlog.get_logger(__name__)_EVENT_NAME = "$replay_vision_action_ready"+# How far behind last_run_at the new-observation probe looks. Covers commit lag (an observation+# committing just after a tick's probe ran) at the cost of an occasional no-op evaluation.+_NEW_OBSERVATION_OVERLAP = timedelta(minutes=10)+++def _has_new_observations(action: VisionAction, now: datetime) -> bool:+ """Whether the scanner completed any observation since this action's last check (with overlap)."""+ since = (action.last_run_at or action.created_at or now) - _NEW_OBSERVATION_OVERLAP+ return ReplayObservation.objects.filter(+ team_id=action.team_id,+ scanner_id=action.scanner_id,+ status=ObservationStatus.SUCCEEDED,+ completed_at__gte=since,+ ).exists()+++def _is_every_match_alert(action: VisionAction) -> bool:+ alert_config = action.alert_config if isinstance(action.alert_config, dict) else {}+ return action.mode == ActionMode.ALERT and alert_config.get("frequency") == AlertFrequency.EVERY_MATCH+@activity.defn@track_activity()@@ -59,12 +83,28 @@ def _evaluate_due(inputs: EvaluateDueVisionActionsInputs) -> list[DueVisionActioscanner_id=inputs.scanner_id,enabled=True,trigger_type=TriggerType.SCHEDULE,- next_run_at__isnull=False,- next_run_at__lte=now,+ )+ # Every-match alerts check on every sweep, so their stored rrule cursor never gates+ # them — a fresh match should notify within minutes. Threshold (on_breach) alerts read+ # rolling windows of days, where hourly resolution loses nothing, so they keep the+ # cursor gate — bounding how much window-scanning one tenant's alerts can add per sweep.+ .filter(+ Q(mode=ActionMode.ALERT, alert_config__frequency=AlertFrequency.EVERY_MATCH)+ | Q(next_run_at__isnull=False, next_run_at__lte=now)))for action in actions:- scheduled_at = action.next_run_at+ every_match_alert = _is_every_match_alert(action)+ if every_match_alert and not _has_new_observations(action, now):+ # Quiet tick: stamp the check time (feeds "Last checked") but skip the claim — no+ # child workflow, no run row, no window query. One indexed EXISTS is the whole cost.+ VisionAction.objects.for_team(inputs.team_id).filter(pk=action.id).update(+ last_run_at=now, updated_at=now+ )+ continue+ # A summary's or threshold alert's tick is its schedule cursor; an every-match alert's+ # tick is simply this sweep (its cursor can sit in the future and is ignored).+ scheduled_at = now if every_match_alert else action.next_run_at# Claim via a direct .update() rather than save(): VisionAction.save() re-derives# next_run_at when the schedule key changed, and we've already advanced it here — going# through .update() bypasses that override so the claim can't double-recompute the cursor.@@ -72,7 +112,11 @@ def _evaluate_due(inputs: EvaluateDueVisionActionsInputs) -> list[DueVisionActioVisionAction.objects.for_team(inputs.team_id).filter(pk=action.id).update(next_run_at=action.next_run_at, last_run_at=now, updated_at=now)- due.append(DueVisionAction(vision_action_id=action.id, team_id=action.team_id, scheduled_at=scheduled_at))+ due.append(+ DueVisionAction(+ vision_action_id=action.id, team_id=action.team_id, scheduled_at=scheduled_at, mode=action.mode+ )+ )return duediff --git a/products/replay_vision/backend/temporal/vision_actions/alerts.py b/products/replay_vision/backend/temporal/vision_actions/alerts.pynew file mode 100644index 000000000000..10b10561af49--- /dev/null+++ b/products/replay_vision/backend/temporal/vision_actions/alerts.py@@ -0,0 +1,267 @@+"""Evaluate a VisionAction's alert condition over its observation window and persist the message.++Runs as a Temporal activity, mirroring the group-summary synthesis activity: all blocking ORM work+happens in one sync function, and the alert message is written onto `VisionActionRun` inside the+activity — it never crosses the Temporal wire. Unlike synthesis there is no LLM call: the message is+deterministic (metric, threshold, and a few example outcomes), so alerts don't bill AI credits and+don't require the AI data-processing consent gate.+"""++import re+from datetime import UTC, datetime, timedelta+from typing import Any++from django.db.models import Avg, FloatField+from django.db.models.fields.json import KeyTextTransform+from django.db.models.functions import Cast++import structlog+from temporalio import activity++from posthog.helpers.markdown_safety import strip_external_links_markdown+from posthog.sync import database_sync_to_async++from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation+from products.replay_vision.backend.models.vision_action import (+ AlertFrequency,+ AlertMetric,+ VisionActionRun,+ VisionActionRunStatus,+)+from products.replay_vision.backend.observation_formatting import describe_output+from products.replay_vision.backend.scanner_access import readable_scanner_ids+from products.replay_vision.backend.temporal.decorators import track_activity+from products.replay_vision.backend.temporal.vision_actions.synthesis import (+ MAX_OBSERVATIONS,+ _markdown_to_slack,+ apply_observation_predicate,+)+from products.replay_vision.backend.temporal.vision_actions.types import (+ AlertStatus,+ EvaluateAlertInputs,+ EvaluateAlertResult,+)++logger = structlog.get_logger(__name__)++# How many matching observations the alert message lists as examples.+EXAMPLE_LINES = 5+# Rolling evaluation windows the condition may look back over, in days.+ALERT_WINDOW_DAYS = (1, 3, 7, 14, 30)+DEFAULT_ALERT_WINDOW_DAYS = 1+# Skip reasons that mean a check ran to completion and observed the alert's state.+_EVALUATED_SKIP_REASONS = {"not_breached", "still_breached"}+# How many prior runs to scan for the last meaningful evaluation before giving up (an alert with+# this many consecutive failed checks has bigger problems than firing state).+_STATE_SCAN_LIMIT = 20+++@track_activity()+async def evaluate_alert_activity(inputs: EvaluateAlertInputs) -> EvaluateAlertResult:+ return await database_sync_to_async(_evaluate, thread_sensitive=False)(inputs)+++def _evaluate(inputs: EvaluateAlertInputs) -> EvaluateAlertResult:+ run = (+ VisionActionRun.objects.for_team(inputs.team_id)+ .select_related("vision_action", "vision_action__scanner", "team", "vision_action__created_by")+ .get(pk=inputs.run_id)+ )+ action = run.vision_action+ team = run.team++ # Idempotency: a retry after the message was already persisted must re-report FIRED, not re-evaluate+ # against a window that may have shifted.+ if run.synthesized_markdown:+ return EvaluateAlertResult(status=AlertStatus.FIRED, observation_count=run.observation_count)++ selection: dict[str, Any] = action.selection or {}+ requested_scanner_ids = selection.get("scanner_ids") or ([str(action.scanner_id)] if action.scanner_id else [])+ # Same creator-RBAC gate as synthesis: the alert surfaces observation outcomes, so it must not read+ # a scanner its creator can't access.+ creator = action.created_by+ scanner_ids = readable_scanner_ids(creator, team, requested_scanner_ids) if creator is not None else []+ if not scanner_ids:+ return EvaluateAlertResult(status=AlertStatus.NOT_BREACHED, observation_count=0)++ alert_config: dict[str, Any] = action.alert_config or {}+ frequency = alert_config.get("frequency", AlertFrequency.ON_BREACH)+ metric = alert_config.get("metric", AlertMetric.COUNT)+ threshold = alert_config.get("threshold")+ window_days = alert_config.get("window_days", DEFAULT_ALERT_WINDOW_DAYS)+ every_match = frequency == AlertFrequency.EVERY_MATCH+ if not every_match and (+ not isinstance(threshold, int | float)+ or isinstance(threshold, bool)+ or not isinstance(window_days, int)+ or window_days not in ALERT_WINDOW_DAYS+ ):+ # Malformed config (serializer-validated, so only reachable via direct writes). Don't fire.+ logger.warning("vision_action.alert.invalid_config", vision_action_id=str(action.id))+ return EvaluateAlertResult(status=AlertStatus.NOT_BREACHED, observation_count=0)++ previous, previous_breached = _last_evaluated_run(team.id, action.id, run.pk)++ window_end = run.scheduled_at or datetime.now(UTC)+ if every_match:+ # Every-match alerts tile their windows between checks (like summaries) so each new match is+ # reported exactly once; the first check starts at the alert's creation, never dumping history.+ window_start = (previous.scheduled_at or previous.created_at) if previous else action.created_at+ else:+ # Threshold conditions look back over a rolling window ending at the run's tick, so+ # "over the last 7 days" means the same thing on every check.+ window_start = window_end - timedelta(days=window_days)++ # Windows bound on completed_at, not created_at: an observation takes minutes to process, and a+ # row created in one tick's window but succeeding during the next would never land in either if+ # windows tiled on creation time. completed_at is only set on success, so it can't move backward.+ observations_qs = apply_observation_predicate(+ ReplayObservation.objects.filter(+ team_id=team.id,+ scanner_id__in=scanner_ids,+ status=ObservationStatus.SUCCEEDED,+ completed_at__gte=window_start,+ completed_at__lt=window_end,+ ),+ selection,+ )++ matched_count = observations_qs.count()+ if every_match:+ # Any new match notifies; there's no threshold state to arm or clear.+ if matched_count == 0:+ return EvaluateAlertResult(status=AlertStatus.NOT_BREACHED, observation_count=0)+ return _persist_fired(run, action, alert_config, float(matched_count), matched_count, observations_qs, team)++ # Only on_breach flows reach here, and the config guard above validated the threshold.+ assert isinstance(threshold, int | float)++ if metric == AlertMetric.AVG_SCORE:+ # Cast the JSONB score to float and average it; observations without a score (non-scorers)+ # are NULL and fall out of the average.+ metric_value = observations_qs.annotate(+ _score=Cast(+ KeyTextTransform("score", KeyTextTransform("model_output", "scanner_result")),+ output_field=FloatField(),+ )+ ).aggregate(avg=Avg("_score"))["avg"]+ else:+ metric_value = float(matched_count)++ # No measurable data (e.g. avg over an empty window) can't breach anything — including a+ # "count lt N" condition, which zero observations WOULD satisfy; count is always measurable (0).+ # The only condition shape is "metric at or above threshold" — see AlertConfigSerializer.+ if metric_value is None or metric_value < threshold:+ return EvaluateAlertResult(+ status=AlertStatus.NOT_BREACHED, observation_count=matched_count, metric_value=metric_value+ )++ # Fire on the transition into breach only: a rolling window can stay breached across many checks,+ # and re-notifying every tick would be spam. The last meaningful evaluation's outcome is the state.+ if previous is not None and previous_breached:+ return EvaluateAlertResult(+ status=AlertStatus.STILL_BREACHED, observation_count=matched_count, metric_value=metric_value+ )++ return _persist_fired(run, action, alert_config, metric_value, matched_count, observations_qs, team)+++def _last_evaluated_run(team_id: int, action_id: Any, exclude_pk: Any) -> tuple[VisionActionRun | None, bool]:+ """The most recent prior run whose outcome reflects the alert's state, and whether it observed a+ breach: a fired run (message persisted, even if delivery later failed) or an evaluated skip.+ Failed or interrupted checks are walked past so a transient failure can't re-arm a still-breached+ alert, and so an every-match window that a failed check never covered gets re-covered."""+ runs = (+ VisionActionRun.objects.for_team(team_id)+ .filter(vision_action_id=action_id)+ .exclude(pk=exclude_pk)+ .order_by("-created_at")[:_STATE_SCAN_LIMIT]+ )+ for prev in runs:+ if prev.synthesized_markdown:+ return prev, True+ error = prev.error if isinstance(prev.error, dict) else {}+ if prev.status == VisionActionRunStatus.SKIPPED and error.get("skip_reason") in _EVALUATED_SKIP_REASONS:+ return prev, error.get("skip_reason") == "still_breached"+ return None, False+++def _persist_fired(+ run: VisionActionRun,+ action: Any,+ alert_config: dict[str, Any],+ metric_value: float,+ matched_count: int,+ observations_qs: Any,+ team: Any,+) -> EvaluateAlertResult:+ markdown = strip_external_links_markdown(+ _alert_markdown(action, alert_config, metric_value, matched_count, observations_qs)+ )+ observation_ids = [+ str(observation_id)+ for observation_id in observations_qs.order_by("-created_at", "-id").values_list("id", flat=True)[+ :MAX_OBSERVATIONS+ ]+ ]+ run.synthesized_markdown = markdown+ # Alert messages carry no `[obs N]` citations, so the ids only feed the (no-op) citation pass.+ run.output = {"slack": _markdown_to_slack(markdown, team_id=team.id, observation_ids=observation_ids)}+ run.observation_count = matched_count+ run.observation_ids = observation_ids+ run.save(update_fields=["synthesized_markdown", "output", "observation_count", "observation_ids", "updated_at"])++ return EvaluateAlertResult(status=AlertStatus.FIRED, observation_count=matched_count, metric_value=metric_value)+++def _format_number(value: float) -> str:+ return str(int(value)) if float(value).is_integer() else f"{value:.2f}"+++def _alert_markdown(+ action: Any,+ alert_config: dict[str, Any],+ metric_value: float,+ matched_count: int,+ observations_qs: Any,+) -> str:+ """Deterministic alert report: what fired, the measured value vs the threshold, and a few example+ observation outcomes (verdict/score/tags via `describe_output` — outcomes only, no+ recording-derived prose, so nothing here needs an LLM or invites prompt injection)."""+ # Scanner name is free text; strip markdown/mrkdwn control chars so it can't garble the bold header.+ raw_name = action.scanner.name if action.scanner_id else ""+ scanner_name = re.sub(r"\s+", " ", re.sub(r"[*_`#]", "", raw_name)).strip() or "your scanner"++ noun = "observation" if matched_count == 1 else "observations"+ if alert_config.get("frequency", AlertFrequency.ON_BREACH) == AlertFrequency.EVERY_MATCH:+ lines = [+ f"**Alert: {scanner_name}** — {matched_count} new matching {noun} since the last check.",+ ]+ else:+ metric = alert_config.get("metric", AlertMetric.COUNT)+ threshold = alert_config.get("threshold", 0)+ window_days = alert_config.get("window_days", DEFAULT_ALERT_WINDOW_DAYS)+ metric_label = "average score" if metric == AlertMetric.AVG_SCORE else "matching observations"+ window_label = "24 hours" if window_days == 1 else f"{window_days} days"+ lines = [+ f"**Alert: {scanner_name}** — {metric_label} over the last {window_label} was "+ f"{_format_number(metric_value)}, at or above the threshold of {_format_number(threshold)}.",+ "",+ f"{matched_count} {noun} matched in this window.",+ ]++ examples: list[str] = []+ for scanner_result, created_at in observations_qs.order_by("-created_at", "-id").values_list(+ "scanner_result", "created_at"+ )[:EXAMPLE_LINES]:+ output = scanner_result.get("model_output") if isinstance(scanner_result, dict) else None+ if not isinstance(output, dict):+ continue+ descriptor = describe_output(output)+ if descriptor:+ examples.append(f"- ({created_at:%Y-%m-%d}) {descriptor}")+ if examples:+ lines.extend(["", "Most recent matches:", *examples])++ return "\n".join(lines)diff --git a/products/replay_vision/backend/temporal/vision_actions/synthesis.py b/products/replay_vision/backend/temporal/vision_actions/synthesis.pyindex d7d05b2cf2fb..0d0aa4649b5b 100644--- a/products/replay_vision/backend/temporal/vision_actions/synthesis.py+++ b/products/replay_vision/backend/temporal/vision_actions/synthesis.py@@ -6,7 +6,6 @@ is written onto `VisionActionRun` inside the activity — it never crosses the T"""import re-import uuidfrom datetime import UTC, datetime, timedelta, tzinfofrom typing import TYPE_CHECKING, Any, NamedTuplefrom zoneinfo import ZoneInfo@@ -22,13 +21,12 @@ from temporalio import activityfrom posthog.event_usage import groupsfrom posthog.helpers.markdown_safety import strip_external_links_markdownfrom posthog.models.team import Team-from posthog.rbac.user_access_control import UserAccessControlfrom posthog.sync import database_sync_to_asyncfrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation-from products.replay_vision.backend.models.replay_scanner import ReplayScannerfrom products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun, VisionActionRunStatusfrom products.replay_vision.backend.observation_formatting import EVENT_ID_CITATION_RE, describe_output+from products.replay_vision.backend.scanner_access import readable_scanner_idsfrom products.replay_vision.backend.temporal.constants import replay_vision_distinct_idfrom products.replay_vision.backend.temporal.decorators import track_activityfrom products.replay_vision.backend.temporal.vision_actions.types import (@@ -41,7 +39,7 @@ from ee.billing.quota_limiting import is_team_over_ai_credit_budgetfrom ee.hogai.utils.untrusted import as_untrusted_dataif TYPE_CHECKING:- from posthog.models.user import User+ passlogger = structlog.get_logger(__name__)@@ -254,36 +252,6 @@ class _ObservationBatch(NamedTuple):window_total: int-def _is_uuid(value: str) -> bool:- try:- uuid.UUID(str(value))- except (ValueError, TypeError):- return False- return True---def _readable_scanner_ids(user: "User", team: Team, scanner_ids: list[str]) -> list[str]:- """Restrict an action's bound scanner ids to the ones its creator may actually read.-- A vision action's scanner binding is user-supplied, so without this a creator could point an action- at a same-team scanner they lack `replay_scanner` viewer access to and receive its recording-derived- reasoning and outcome in the synthesized summary. Filtering through the creator's RBAC keeps synthesis- from surfacing a scanner the creator can't see, mirroring the scanner-access gate `max_tools` applies- on interactive reads (object-level access control; note the underlying queryset filter is a no-op for- orgs without the access-control feature, where no per-scanner restriction exists anyway).- """- # Drop non-UUID ids before querying: `selection.scanner_ids` is a user-supplied CharField list, and a- # malformed value would raise ValidationError inside the Temporal activity on every run (a permanent- # retry loop). Mirrors the UUID pre-validation in `max_tools._resolve_scanner_scope`.- valid_ids = [scanner_id for scanner_id in scanner_ids if _is_uuid(scanner_id)]- if not valid_ids:- return []- readable = UserAccessControl(user=user, team=team).filter_queryset_by_access_level(- ReplayScanner.objects.filter(team_id=team.id, id__in=valid_ids)- )- return [str(scanner_id) for scanner_id in readable.values_list("id", flat=True)]--def _fetch_observations(team: Team, action: VisionAction, run: VisionActionRun) -> _ObservationBatch:"""Fetch the bound scanner's observations since the last run and format them as untrusted-data lines.@@ -296,7 +264,7 @@ def _fetch_observations(team: Team, action: VisionAction, run: VisionActionRun)# same-team scanner's recording-derived reasoning/outcome that its creator can't access. Mirrors the# scanner-access gate `max_tools` applies when reading observations. Upstream guarantees a creator.creator = action.created_by- scanner_ids = _readable_scanner_ids(creator, team, requested_scanner_ids) if creator is not None else []+ scanner_ids = readable_scanner_ids(creator, team, requested_scanner_ids) if creator is not None else []if len(scanner_ids) < len(requested_scanner_ids):# RBAC (or a malformed id) dropped some bound scanners. Log it so a silently shrinking summary is# diagnosable rather than reading like "no observations this period".@@ -467,10 +435,18 @@ def _citations_to_slack_links(markdown: str, team_id: int, observation_ids: listreturn _OBS_CITATION_RE.sub(_link, markdown)+def _escape_slack_specials(text: str) -> str:+ """Slack mrkdwn treats &, < and > as control characters (`<!channel>`, `<@user>`, `<url|label>`).+ The report body carries untrusted scanner/observation-derived text, so escape it BEFORE our own+ `<url|[N]>` citation links are injected — a hostile tag or title must render as text, never ping+ a channel or smuggle a link. Slack renders the entities back as the literal characters."""+ return text.replace("&", "&").replace("<", "<").replace(">", ">")++def _markdown_to_slack(markdown: str, *, team_id: int, observation_ids: list[str]) -> str:"""Light Markdown→Slack-mrkdwn pass: headings and **bold** become *bold*, and `[obs N]` citations become`[N]` links to each observation. Truncates long reports."""- text = _citations_to_slack_links(markdown, team_id, observation_ids)+ text = _citations_to_slack_links(_escape_slack_specials(markdown), team_id, observation_ids)text = _MARKDOWN_HEADING_RE.sub(lambda m: f"*{m.group(1)}*", text)text = _MARKDOWN_BOLD_RE.sub(lambda m: f"*{m.group(1)}*", text)if len(text) > SLACK_TEXT_MAX:diff --git a/products/replay_vision/backend/temporal/vision_actions/types.py b/products/replay_vision/backend/temporal/vision_actions/types.pyindex 15bf1af3e7f6..d27e0a155fad 100644--- a/products/replay_vision/backend/temporal/vision_actions/types.py+++ b/products/replay_vision/backend/temporal/vision_actions/types.py@@ -38,12 +38,35 @@ class DueVisionAction(BaseModel, frozen=True):team_id: int# The next_run_at that fired this action, captured before the claim advanced it.scheduled_at: datetime | None = None+ # ActionMode value; defaulted so payloads produced before the field existed still parse.+ mode: str = "group_summary"class ProcessVisionActionInputs(BaseModel, frozen=True):vision_action_id: UUIDteam_id: intscheduled_at: datetime | None = None+ # ActionMode value picking the evaluation step (group-summary synthesis vs alert condition).+ mode: str = "group_summary"+++class AlertStatus(str, Enum):+ FIRED = "fired" # condition held; message persisted on the run — deliver it+ NOT_BREACHED = "not_breached" # condition did not hold; nothing to deliver+ STILL_BREACHED = "still_breached" # condition holds but the previous check already notified+++class EvaluateAlertInputs(BaseModel, frozen=True):+ # The run already references its action (run.vision_action); team_id scopes the fail-closed read.+ run_id: UUID+ team_id: int+++class EvaluateAlertResult(BaseModel, frozen=True):+ status: AlertStatus+ observation_count: int = 0+ # The measured metric (count or average score); None when nothing was measurable in the window.+ metric_value: float | None = Noneclass CreateVisionActionRunInputs(BaseModel, frozen=True):diff --git a/products/replay_vision/backend/temporal/vision_actions/workflows.py b/products/replay_vision/backend/temporal/vision_actions/workflows.pyindex 3edb64a8abfe..a18827cf2531 100644--- a/products/replay_vision/backend/temporal/vision_actions/workflows.py+++ b/products/replay_vision/backend/temporal/vision_actions/workflows.py@@ -15,8 +15,10 @@ from posthog.temporal.common.base import PostHogWorkflowfrom products.replay_vision.backend.temporal.constants import PROCESS_VISION_ACTION_WORKFLOW_NAMEfrom products.replay_vision.backend.temporal.vision_actions.types import (+ AlertStatus,CreateVisionActionRunInputs,EmitActionReadyInputs,+ EvaluateAlertInputs,ProcessVisionActionInputs,SynthesisStatus,SynthesizeGroupSummaryInputs,@@ -24,7 +26,7 @@ from products.replay_vision.backend.temporal.vision_actions.types import (ValidateVisionActionInputs,)-# `activities` + the synthesis activity pull in Django/ee, which the workflow sandbox can't re-import.+# `activities` + the synthesis/alert activities pull in Django/ee, which the workflow sandbox can't re-import.with wf.unsafe.imports_passed_through():from products.replay_vision.backend.models.vision_action import VisionActionRunStatusfrom products.replay_vision.backend.temporal.vision_actions.activities import (@@ -33,6 +35,7 @@ with wf.unsafe.imports_passed_through():update_vision_action_run_activity,validate_vision_action_activity,)+ from products.replay_vision.backend.temporal.vision_actions.alerts import evaluate_alert_activityfrom products.replay_vision.backend.temporal.vision_actions.synthesis import synthesize_group_summary_activity_RECORD_RETRY = common.RetryPolicy(initial_interval=dt.timedelta(seconds=5), maximum_attempts=3)@@ -80,20 +83,34 @@ class ProcessVisionActionWorkflow(PostHogWorkflow):error_info = {"skip_reason": skip_reason}return- synth = await wf.execute_activity(- synthesize_group_summary_activity,- SynthesizeGroupSummaryInputs(run_id=run_id, team_id=inputs.team_id),- start_to_close_timeout=dt.timedelta(minutes=10),- retry_policy=_SYNTH_RETRY,- )- if synth.status in (SynthesisStatus.ABORTED_NO_CONSENT, SynthesisStatus.ABORTED_NO_USER):- final_status = VisionActionRunStatus.FAILED.value- error_info = {"aborted": synth.status.value}- return- if synth.status in (SynthesisStatus.SKIPPED_EMPTY, SynthesisStatus.SKIPPED_OVER_BUDGET):- # final_status stays SKIPPED; record why so the run isn't an unexplained skip.- error_info = {"skip_reason": synth.status.value}- return+ if inputs.mode == "alert":+ # Alerts evaluate a deterministic condition (no LLM); the message is persisted on the+ # run by the activity, so a non-breach simply records a skip and delivers nothing.+ alert = await wf.execute_activity(+ evaluate_alert_activity,+ EvaluateAlertInputs(run_id=run_id, team_id=inputs.team_id),+ start_to_close_timeout=dt.timedelta(minutes=5),+ retry_policy=_SYNTH_RETRY,+ )+ if alert.status in (AlertStatus.NOT_BREACHED, AlertStatus.STILL_BREACHED):+ # final_status stays SKIPPED; record why so the run isn't an unexplained skip.+ error_info = {"skip_reason": alert.status.value}+ return+ else:+ synth = await wf.execute_activity(+ synthesize_group_summary_activity,+ SynthesizeGroupSummaryInputs(run_id=run_id, team_id=inputs.team_id),+ start_to_close_timeout=dt.timedelta(minutes=10),+ retry_policy=_SYNTH_RETRY,+ )+ if synth.status in (SynthesisStatus.ABORTED_NO_CONSENT, SynthesisStatus.ABORTED_NO_USER):+ final_status = VisionActionRunStatus.FAILED.value+ error_info = {"aborted": synth.status.value}+ return+ if synth.status in (SynthesisStatus.SKIPPED_EMPTY, SynthesisStatus.SKIPPED_OVER_BUDGET):+ # final_status stays SKIPPED; record why so the run isn't an unexplained skip.+ error_info = {"skip_reason": synth.status.value}+ returnawait wf.execute_activity(emit_action_ready_activity,diff --git a/products/replay_vision/backend/tests/test_vision_action_alerts.py b/products/replay_vision/backend/tests/test_vision_action_alerts.pynew file mode 100644index 000000000000..f1f2855bb587--- /dev/null+++ b/products/replay_vision/backend/tests/test_vision_action_alerts.py@@ -0,0 +1,282 @@+from datetime import timedelta++from posthog.test.base import BaseTest++from django.utils import timezone++from parameterized import parameterized++from products.replay_vision.backend.models.replay_observation import (+ ObservationStatus,+ ObservationTrigger,+ ReplayObservation,+)+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.models.vision_action import (+ ActionMode,+ VisionAction,+ VisionActionRun,+ VisionActionRunStatus,+)+from products.replay_vision.backend.temporal.vision_actions.alerts import _evaluate+from products.replay_vision.backend.temporal.vision_actions.types import AlertStatus, EvaluateAlertInputs+from products.replay_vision.backend.tests.helpers import snapshot_for++DAILY = {"rrule": "FREQ=DAILY", "timezone": "UTC"}+++class TestVisionActionAlerts(BaseTest):+ def _scanner(self, scanner_type: str = ScannerType.MONITOR, name: str = "watcher") -> ReplayScanner:+ return ReplayScanner.objects.create(+ team=self.team,+ name=name,+ scanner_type=scanner_type,+ scanner_config={"prompt": "watch"},+ model=ScannerModel.GEMINI_3_FLASH,+ )++ def _observation(+ self, scanner: ReplayScanner, output: dict, session_id: str = "s1", age_days: float = 0+ ) -> ReplayObservation:+ obs = ReplayObservation.objects.create(+ scanner=scanner,+ session_id=session_id,+ scanner_snapshot=snapshot_for(scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ scanner_result={"model_output": {"scanner_type": scanner.scanner_type, **output}},+ )+ if age_days:+ # Windows bound on completed_at; backdate created_at too so display ordering matches.+ aged = timezone.now() - timedelta(days=age_days)+ ReplayObservation.objects.filter(pk=obs.pk).update(created_at=aged, completed_at=aged)+ return obs++ def _alert(self, scanner: ReplayScanner, alert_config: dict, selection: dict | None = None) -> VisionAction:+ action = VisionAction(+ team=self.team,+ name=f"alert-{scanner.name}",+ scanner=scanner,+ created_by=self.user,+ mode=ActionMode.ALERT,+ trigger_config=DAILY,+ selection=selection or {},+ alert_config=alert_config,+ )+ action.save()+ return action++ def _evaluate(self, action: VisionAction, key: str = "k1"):+ run = VisionActionRun(vision_action=action, team=self.team, idempotency_key=key)+ run.save()+ return _evaluate(EvaluateAlertInputs(run_id=run.id, team_id=self.team.id)), run++ def _record(self, run: VisionActionRun, status: str, error: dict | None = None) -> None:+ # Mirror the workflow's final run update so state resolution sees what production would.+ VisionActionRun.objects.for_team(self.team.id).filter(pk=run.pk).update(status=status, error=error)++ def test_count_alert_fires_and_persists_deterministic_message(self) -> None:+ scanner = self._scanner()+ self._observation(scanner, {"verdict": "yes", "reasoning": "user hit the bug"})+ self._observation(scanner, {"verdict": "yes", "reasoning": "again"}, session_id="s2")+ action = self._alert(scanner, {"metric": "count", "threshold": 2})++ result, run = self._evaluate(action)++ self.assertEqual(result.status, AlertStatus.FIRED)+ self.assertEqual(result.observation_count, 2)+ self.assertEqual(result.metric_value, 2.0)+ run.refresh_from_db()+ self.assertIn("Alert: watcher", run.synthesized_markdown)+ self.assertIn("over the last 24 hours", run.synthesized_markdown)+ self.assertIn("at or above the threshold of 2", run.synthesized_markdown)+ self.assertIn("2 observations matched", run.synthesized_markdown)+ self.assertTrue(run.output["slack"])+ self.assertEqual(len(run.observation_ids), 2)++ @parameterized.expand(+ [+ ("below_threshold", 3, AlertStatus.NOT_BREACHED),+ ("at_threshold", 2, AlertStatus.FIRED),+ ]+ )+ def test_threshold_semantics_over_count(self, _label: str, threshold: float, expected: AlertStatus) -> None:+ # The only condition shape is "metric at or above threshold" — the operator knob was dropped.+ scanner = self._scanner(name=f"ops-{_label}")+ self._observation(scanner, {"verdict": "yes"})+ self._observation(scanner, {"verdict": "no"}, session_id="s2")+ action = self._alert(scanner, {"metric": "count", "threshold": threshold})++ result, run = self._evaluate(action)++ self.assertEqual(result.status, expected)+ if expected == AlertStatus.NOT_BREACHED:+ run.refresh_from_db()+ self.assertEqual(run.synthesized_markdown, "")++ def test_slack_output_escapes_mrkdwn_control_sequences(self) -> None:+ # Freeform tags are observation-derived untrusted text that the alert message interpolates+ # verbatim; Slack treats <...> as control sequences, so an unescaped `<!channel>` tag would+ # ping the whole channel from inside a report.+ scanner = self._scanner(scanner_type=ScannerType.CLASSIFIER, name="tagger-evil")+ action = self._alert(scanner, {"frequency": "every_match", "metric": "count"})+ self._observation(scanner, {"tags": [], "tags_freeform": ["<!channel> pwned"]})++ result, run = self._evaluate(action)++ self.assertEqual(result.status, AlertStatus.FIRED)+ run.refresh_from_db()+ self.assertIn("<!channel>", run.output["slack"])+ self.assertNotIn("<!channel>", run.output["slack"])++ def test_selection_predicate_gates_what_counts(self) -> None:+ # "Alert me whenever a user gets tag X": the shared targeting predicate is the match; a+ # dropped predicate would make every alert fire on all observations.+ scanner = self._scanner(scanner_type=ScannerType.CLASSIFIER, name="tagger")+ self._observation(scanner, {"tags": ["rage-click"]})+ self._observation(scanner, {"tags": ["happy-path"]}, session_id="s2")+ action = self._alert(+ scanner,+ {"metric": "count", "threshold": 1},+ selection={"tags": ["rage-click"]},+ )++ result, _ = self._evaluate(action)++ self.assertEqual(result.status, AlertStatus.FIRED)+ self.assertEqual(result.observation_count, 1)++ # The same window with a non-matching tag filter must not fire.+ other = self._alert(+ self._scanner(scanner_type=ScannerType.CLASSIFIER, name="tagger2"),+ {"metric": "count", "threshold": 1},+ selection={"tags": ["missing"]},+ )+ result, _ = self._evaluate(other, key="k2")+ self.assertEqual(result.status, AlertStatus.NOT_BREACHED)++ def test_avg_score_metric(self) -> None:+ scanner = self._scanner(scanner_type=ScannerType.SCORER, name="scorer")+ self._observation(scanner, {"score": 2})+ self._observation(scanner, {"score": 4}, session_id="s2")+ action = self._alert(scanner, {"metric": "avg_score", "threshold": 3})++ result, run = self._evaluate(action)++ self.assertEqual(result.status, AlertStatus.FIRED)+ self.assertEqual(result.metric_value, 3.0)+ run.refresh_from_db()+ self.assertIn("average score over the last 24 hours was 3", run.synthesized_markdown)++ def test_avg_over_empty_window_never_fires(self) -> None:+ # An unmeasurable metric must not breach — a None average must not be coerced to a comparable 0.+ scanner = self._scanner(scanner_type=ScannerType.SCORER, name="quiet-scorer")+ action = self._alert(scanner, {"metric": "avg_score", "threshold": 0})++ result, _ = self._evaluate(action)++ self.assertEqual(result.status, AlertStatus.NOT_BREACHED)+ self.assertIsNone(result.metric_value)++ def test_retry_after_persist_reports_fired_without_reevaluating(self) -> None:+ scanner = self._scanner(name="idem")+ self._observation(scanner, {"verdict": "yes"})+ action = self._alert(scanner, {"metric": "count", "threshold": 1})++ first, run = self._evaluate(action)+ self.assertEqual(first.status, AlertStatus.FIRED)++ # New observations arriving between attempts must not change the already-persisted outcome.+ self._observation(scanner, {"verdict": "yes"}, session_id="s9")+ second = _evaluate(EvaluateAlertInputs(run_id=run.id, team_id=self.team.id))+ self.assertEqual(second.status, AlertStatus.FIRED)+ self.assertEqual(second.observation_count, 1)++ def test_rolling_window_excludes_older_observations(self) -> None:+ # window_days=1 must not count what a longer window would; window_days=7 must.+ scanner = self._scanner(name="windowed")+ self._observation(scanner, {"verdict": "yes"}, age_days=3)+ short = self._alert(scanner, {"metric": "count", "threshold": 1, "window_days": 1})+ result, _ = self._evaluate(short)+ self.assertEqual(result.status, AlertStatus.NOT_BREACHED)++ wide = self._alert(+ self._scanner(name="windowed2"),+ {"metric": "count", "threshold": 1, "window_days": 7},+ )+ self._observation(wide.scanner, {"verdict": "yes"}, session_id="s7", age_days=3)+ result, _ = self._evaluate(wide, key="k7")+ self.assertEqual(result.status, AlertStatus.FIRED)++ def test_breach_fires_once_until_it_clears(self) -> None:+ # A rolling window stays breached across checks; only the transition into breach notifies.+ # Each check's outcome is recorded the way the workflow records it.+ scanner = self._scanner(name="steady")+ self._observation(scanner, {"verdict": "yes"})+ action = self._alert(scanner, {"metric": "count", "threshold": 1, "window_days": 7})++ first, first_run = self._evaluate(action)+ self.assertEqual(first.status, AlertStatus.FIRED)+ self._record(first_run, VisionActionRunStatus.COMPLETED)++ second, second_run = self._evaluate(action, key="k2")+ self.assertEqual(second.status, AlertStatus.STILL_BREACHED)+ self._record(second_run, VisionActionRunStatus.SKIPPED, {"skip_reason": "still_breached"})++ # Once a check observes the condition clear (window emptied), the next breach notifies again.+ cleared_run = VisionActionRun(vision_action=action, team=self.team, idempotency_key="k3")+ cleared_run.save()+ self._record(cleared_run, VisionActionRunStatus.SKIPPED, {"skip_reason": "not_breached"})++ fourth, _ = self._evaluate(action, key="k4")+ self.assertEqual(fourth.status, AlertStatus.FIRED)++ def test_transient_failure_does_not_rearm_a_breached_alert(self) -> None:+ # A crashed check between two breached checks must not cause a duplicate notification: the+ # state comes from the last check that meaningfully evaluated, walking past FAILED runs.+ scanner = self._scanner(name="flaky-check")+ self._observation(scanner, {"verdict": "yes"})+ action = self._alert(scanner, {"metric": "count", "threshold": 1, "window_days": 7})++ first, first_run = self._evaluate(action)+ self.assertEqual(first.status, AlertStatus.FIRED)+ self._record(first_run, VisionActionRunStatus.COMPLETED)++ failed_run = VisionActionRun(vision_action=action, team=self.team, idempotency_key="k-fail")+ failed_run.save()+ self._record(failed_run, VisionActionRunStatus.FAILED, {"message": "boom"})++ third, _ = self._evaluate(action, key="k3")+ self.assertEqual(third.status, AlertStatus.STILL_BREACHED)++ def test_every_match_failed_check_does_not_lose_its_window(self) -> None:+ # A crashed every-match check must not advance the coverage cursor: its window's matches are+ # picked up by the next successful check instead of being silently dropped.+ scanner = self._scanner(name="lossless")+ action = self._alert(scanner, {"frequency": "every_match"}, selection={"verdict": ["yes"]})++ self._observation(scanner, {"verdict": "yes"})+ first, first_run = self._evaluate(action)+ self.assertEqual(first.status, AlertStatus.FIRED)+ self._record(first_run, VisionActionRunStatus.COMPLETED)++ self._observation(scanner, {"verdict": "yes"}, session_id="s2")+ failed_run = VisionActionRun(vision_action=action, team=self.team, idempotency_key="k-fail")+ failed_run.save()+ self._record(failed_run, VisionActionRunStatus.FAILED, {"message": "boom"})++ third, _ = self._evaluate(action, key="k3")+ self.assertEqual(third.status, AlertStatus.FIRED)+ self.assertEqual(third.observation_count, 1)++ def test_malformed_config_never_fires(self) -> None:+ scanner = self._scanner(name="broken")+ self._observation(scanner, {"verdict": "yes"})+ action = self._alert(scanner, {"metric": "count", "threshold": "high"})++ result, run = self._evaluate(action)++ self.assertEqual(result.status, AlertStatus.NOT_BREACHED)+ run.refresh_from_db()+ self.assertEqual(run.synthesized_markdown, "")diff --git a/products/replay_vision/backend/tests/test_vision_action_engine.py b/products/replay_vision/backend/tests/test_vision_action_engine.pyindex 86ab975772ca..30e64ba063d1 100644--- a/products/replay_vision/backend/tests/test_vision_action_engine.py+++ b/products/replay_vision/backend/tests/test_vision_action_engine.py@@ -10,13 +10,21 @@ from django.utils import timezonefrom parameterized import parameterizedfrom products.replay_vision.backend.models import ReplayScanner, VisionAction, VisionActionRun+from products.replay_vision.backend.models.replay_observation import (+ ObservationStatus,+ ObservationTrigger,+ ReplayObservation,+)from products.replay_vision.backend.models.replay_scanner import ScannerModel, ScannerType-from products.replay_vision.backend.models.vision_action import TriggerType, VisionActionRunStatus+from products.replay_vision.backend.models.vision_action import ActionMode, TriggerType, VisionActionRunStatusfrom products.replay_vision.backend.temporal.vision_actions import activities as act+from products.replay_vision.backend.temporal.vision_actions.alerts import evaluate_alert_activityfrom products.replay_vision.backend.temporal.vision_actions.synthesis import synthesize_group_summary_activityfrom products.replay_vision.backend.temporal.vision_actions.types import (+ AlertStatus,CreateVisionActionRunInputs,EmitActionReadyInputs,+ EvaluateAlertResult,EvaluateDueVisionActionsInputs,ProcessVisionActionInputs,SynthesisStatus,@@ -25,6 +33,7 @@ from products.replay_vision.backend.temporal.vision_actions.types import (ValidateVisionActionInputs,)from products.replay_vision.backend.temporal.vision_actions.workflows import ProcessVisionActionWorkflow+from products.replay_vision.backend.tests.helpers import snapshot_forDAILY = "FREQ=DAILY;BYHOUR=9"@@ -59,6 +68,21 @@ def _make_due(action) -> None:VisionAction.all_teams.filter(pk=action.pk).update(next_run_at=timezone.now() - timedelta(hours=1))+EVERY_MATCH = {"frequency": "every_match", "metric": "count"}+++def _completed_observation(scanner) -> ReplayObservation:+ return ReplayObservation.objects.create(+ scanner=scanner,+ session_id="s1",+ scanner_snapshot=snapshot_for(scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ scanner_result={"model_output": {"scanner_type": scanner.scanner_type, "summary": "s"}},+ )++class TestEvaluateDue(BaseTest):def _inputs(self, scanner) -> EvaluateDueVisionActionsInputs:return EvaluateDueVisionActionsInputs(scanner_id=scanner.id, team_id=self.team.id)@@ -85,6 +109,62 @@ class TestEvaluateDue(BaseTest):self.assertEqual([d.vision_action_id for d in result], [due.id])self.assertEqual(result[0].team_id, self.team.id)+ def test_every_match_alerts_are_due_on_every_sweep_when_observations_exist(self) -> None:+ # every_match alerts ignore their rrule cursor: a fresh match should notify within minutes,+ # not wait for an hourly tick — so one whose cursor sits in the future is still claimed, with+ # this sweep's time (not the future cursor) as the window-anchoring tick. Disabled stay out.+ scanner = _scanner(self.team)+ _completed_observation(scanner)+ alert = _action(self.team, name="alert", scanner=scanner, mode=ActionMode.ALERT, alert_config=EVERY_MATCH)+ VisionAction.all_teams.filter(pk=alert.pk).update(next_run_at=timezone.now() + timedelta(hours=1))++ disabled = _action(+ self.team, name="off", scanner=scanner, mode=ActionMode.ALERT, alert_config=EVERY_MATCH, enabled=False+ )+ VisionAction.all_teams.filter(pk=disabled.pk).update(next_run_at=timezone.now() + timedelta(hours=1))++ result = act._evaluate_due(self._inputs(scanner))++ self.assertEqual([d.vision_action_id for d in result], [alert.id])+ assert result[0].scheduled_at is not None+ self.assertLessEqual(result[0].scheduled_at, timezone.now())++ # And the next sweep claims it again — no hourly gate between checks.+ self.assertEqual([d.vision_action_id for d in act._evaluate_due(self._inputs(scanner))], [alert.id])++ def test_every_match_alert_skips_quiet_ticks_but_stamps_last_checked(self) -> None:+ # With no new observations there's nothing an every_match alert could report, so the sweep+ # must not spawn its child workflow — but "Last checked" still has to move.+ scanner = _scanner(self.team)+ alert = _action(self.team, name="alert", scanner=scanner, mode=ActionMode.ALERT, alert_config=EVERY_MATCH)++ self.assertEqual(act._evaluate_due(self._inputs(scanner)), [])+ alert.refresh_from_db()+ self.assertIsNotNone(alert.last_run_at)++ def test_on_breach_alerts_keep_the_schedule_cursor_gate(self) -> None:+ # Threshold alerts read rolling windows of days; hourly resolution loses nothing, and the+ # cursor gate bounds how much window-scanning alert fan-out can add to every sweep.+ scanner = _scanner(self.team)+ _completed_observation(scanner)+ on_breach = _action(+ self.team,+ name="threshold-alert",+ scanner=scanner,+ mode=ActionMode.ALERT,+ alert_config={"frequency": "on_breach", "metric": "count", "threshold": 1},+ )+ VisionAction.all_teams.filter(pk=on_breach.pk).update(next_run_at=timezone.now() + timedelta(hours=1))++ self.assertEqual(act._evaluate_due(self._inputs(scanner)), [])++ _make_due(on_breach)+ on_breach.refresh_from_db()+ result = act._evaluate_due(self._inputs(scanner))+ self.assertEqual([d.vision_action_id for d in result], [on_breach.id])+ # The tick is the schedule cursor (like summaries), not the sweep time.+ self.assertEqual(result[0].scheduled_at, on_breach.next_run_at)+def test_claims_by_advancing_next_run_at(self) -> None:scanner = _scanner(self.team)action = _action(self.team, scanner=scanner)@@ -294,6 +374,38 @@ async def test_process_maps_synthesis_status(assert act.evaluate_due_vision_actions_activity not in call_fns+ "alert_status, expected_final, expect_emit, expected_error",+ [+ (AlertStatus.FIRED, VisionActionRunStatus.COMPLETED.value, True, None),+ (AlertStatus.NOT_BREACHED, VisionActionRunStatus.SKIPPED.value, False, {"skip_reason": "not_breached"}),+ ],+)+async def test_process_routes_alert_mode_to_alert_evaluation(+ alert_status: AlertStatus, expected_final: str, expect_emit: bool, expected_error: dict | None+) -> None:+ # The routing regression: an alert action must evaluate its condition, never synthesize.+ mocks = _Mocks(+ results={+ act.create_vision_action_run_activity: uuid.uuid4(),+ act.validate_vision_action_activity: None,+ evaluate_alert_activity: EvaluateAlertResult(status=alert_status, observation_count=1),+ }+ )+ await _run_process(+ ProcessVisionActionInputs(vision_action_id=uuid.uuid4(), team_id=1, mode="alert"),+ mocks,+ )++ call_fns = mocks.calls()+ assert evaluate_alert_activity in call_fns+ assert synthesize_group_summary_activity not in call_fns+ assert (act.emit_action_ready_activity in call_fns) is expect_emit+ assert _final_status(mocks) == expected_final+ assert _final_error(mocks) == expected_error++@pytest.mark.asyncioasync def test_process_skips_when_validate_returns_reason() -> None:mocks = _Mocks(diff --git a/products/replay_vision/backend/tests/test_vision_actions_api.py b/products/replay_vision/backend/tests/test_vision_actions_api.pyindex 27adc82fe031..881214e8e00a 100644--- a/products/replay_vision/backend/tests/test_vision_actions_api.py+++ b/products/replay_vision/backend/tests/test_vision_actions_api.py@@ -10,6 +10,7 @@ from posthog.cdp.templates.slack.template_slack import template as template_slacfrom posthog.models import Organization, Teamfrom posthog.models.integration import Integration+from products.replay_vision.backend.api.vision_actions import MAX_ENABLED_ALERTS_PER_SCANNERfrom products.replay_vision.backend.models.replay_observation import ReplayObservationfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerTypefrom products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun, VisionActionRunStatus@@ -97,6 +98,62 @@ class TestVisionActionViewSet(_VisionActionAPITestCase):self.assertEqual(action.delivery_config[0]["integration_id"], self.integration.id)self.assertIsNotNone(action.next_run_at)+ def test_targeting_a_scanner_the_editor_cannot_read_is_rejected(self) -> None:+ # The engine reads observations as the action's CREATOR, so a lower-privileged editor+ # re-pointing an action at a scanner they can't read would exfiltrate that scanner's data+ # via the delivery channel. Targeting writes must be checked against the requesting user.+ hidden = self._create_scanner(name="restricted")+ with patch(+ "products.replay_vision.backend.scanner_access.UserAccessControl.filter_queryset_by_access_level",+ side_effect=lambda qs, **_: qs.exclude(pk=hidden.pk),+ ):+ resp = self.client.post(self.actions_url, data=self._create_payload(scanner=str(hidden.id)), format="json")+ self.assertEqual(resp.status_code, 400, resp.content)+ self.assertIn("access", resp.json()["detail"])++ # An action a privileged creator already pointed at the hidden scanner: an edit that+ # doesn't touch targeting (rename) stays allowed, but touching targeting re-checks.+ theirs = VisionAction.all_teams.create(+ team=self.team,+ scanner=hidden,+ name="theirs",+ trigger_config={"rrule": "FREQ=DAILY", "timezone": "UTC"},+ )+ resp = self.client.patch(f"{self.actions_url}{theirs.id}/", data={"name": "renamed"}, format="json")+ self.assertEqual(resp.status_code, 200, resp.content)+ resp = self.client.patch(+ f"{self.actions_url}{theirs.id}/", data={"selection": {"verdict": ["yes"]}}, format="json"+ )+ self.assertEqual(resp.status_code, 400, resp.content)++ def test_enabled_alert_cap_per_scanner(self) -> None:+ # Alerts evaluate on every scanner sweep, so unbounded fan-out multiplies sweep work — the+ # cap must reject the N+1th enabled alert while still allowing a disabled one.+ for i in range(MAX_ENABLED_ALERTS_PER_SCANNER):+ VisionAction.all_teams.create(+ team=self.team,+ scanner=self.scanner,+ name=f"alert-{i}",+ mode="alert",+ alert_config={"frequency": "every_match", "metric": "count"},+ trigger_config={"rrule": "FREQ=HOURLY", "timezone": "UTC"},+ )+ payload = self._create_payload(+ name="one-too-many",+ mode="alert",+ alert_config={"frequency": "every_match", "metric": "count"},+ selection={},+ )+ resp = self.client.post(self.actions_url, data=payload, format="json")+ self.assertEqual(resp.status_code, 400, resp.content)+ self.assertIn("at most", resp.json()["detail"])++ resp = self.client.post(self.actions_url, data={**payload, "enabled": False}, format="json")+ self.assertEqual(resp.status_code, 201, resp.content)+ # Re-enabling it later must hit the same cap.+ resp = self.client.patch(f"{self.actions_url}{resp.json()['id']}/", data={"enabled": True}, format="json")+ self.assertEqual(resp.status_code, 400, resp.content)+def test_second_digest_for_scanner_rejected(self) -> None:first = self.client.post(self.actions_url, data=self._create_payload(name="digest-1", is_scanner_digest=True), format="json"@@ -329,6 +386,19 @@ class TestVisionActionRunViewSet(_VisionActionAPITestCase):self.assertNotIn("synthesized_markdown", completed)self.assertNotIn("observations", completed)+ def test_hides_alert_state_bookkeeping_runs(self) -> None:+ # Quiet alert checks (not_breached/still_breached skips) are engine state, not user-facing+ # outcomes — run history must show only actual firings, failures, and summary skips.+ fired = self._create_run(status=VisionActionRunStatus.COMPLETED, synthesized_markdown="3 new matches")+ failed = self._create_run(status=VisionActionRunStatus.FAILED, error={"message": "boom"})+ quiet = self._create_run(status=VisionActionRunStatus.SKIPPED, error={"skip_reason": "not_breached"})+ suppressed = self._create_run(status=VisionActionRunStatus.SKIPPED, error={"skip_reason": "still_breached"})++ results = self.client.get(self.runs_url()).json()["results"]+ self.assertEqual({r["id"] for r in results}, {str(fired.id), str(failed.id)})+ self.assertEqual(self.client.get(f"{self.runs_url()}{quiet.id}/").status_code, 404)+ self.assertEqual(self.client.get(f"{self.runs_url()}{suppressed.id}/").status_code, 404)+def test_retrieve_returns_summary_and_observations_in_stored_order(self) -> None:obs_a = self._create_observation("sess-a", title="Checkout")obs_b = self._create_observation("sess-b", title="Onboarding")diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 514df99d2d74..976bb8a6b217 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -20,12 +20,14 @@ export const TriggerTypeEnumApi = {/*** * `group_summary` - Group summary+ * * `alert` - Alert* * `per_observation` - Per observation*/export type VisionActionModeEnumApi = (typeof VisionActionModeEnumApi)[keyof typeof VisionActionModeEnumApi]export const VisionActionModeEnumApi = {GroupSummary: 'group_summary',+ Alert: 'alert',PerObservation: 'per_observation',} as const@@ -80,6 +82,73 @@ export interface SynthesisConfigApi {prompt_guide?: string}+/**+ * * `every_match` - Every new match+ * * `on_breach` - When a threshold is crossed+ */+export type AlertConfigFrequencyEnumApi = (typeof AlertConfigFrequencyEnumApi)[keyof typeof AlertConfigFrequencyEnumApi]++export const AlertConfigFrequencyEnumApi = {+ EveryMatch: 'every_match',+ OnBreach: 'on_breach',+} as const++/**+ * * `count` - Count of matching observations+ * * `avg_score` - Average score+ */+export type VisionAlertMetricEnumApi = (typeof VisionAlertMetricEnumApi)[keyof typeof VisionAlertMetricEnumApi]++export const VisionAlertMetricEnumApi = {+ Count: 'count',+ AvgScore: 'avg_score',+} as const++/**+ * * `1` - 1 day+ * * `3` - 3 days+ * * `7` - 7 days+ * * `14` - 14 days+ * * `30` - 30 days+ */+export type WindowDaysEnumApi = (typeof WindowDaysEnumApi)[keyof typeof WindowDaysEnumApi]++export const WindowDaysEnumApi = {+ Number1: 1,+ Number3: 3,+ Number7: 7,+ Number14: 14,+ Number30: 30,+} as const++/**+ * The alert condition for mode='alert', applied after `selection` targeting. 'every_match'+ * notifies about each new match since the previous check; 'on_breach' compares a metric to a+ * threshold over a rolling window and notifies on the transition into breach.+ */+export interface AlertConfigApi {+ /** 'every_match' notifies about every new matching observation (batched per check); 'on_breach' notifies once when the threshold condition starts holding. Defaults to 'on_breach'.+ *+ * * `every_match` - Every new match+ * * `on_breach` - When a threshold is crossed */+ frequency?: AlertConfigFrequencyEnumApi+ /** What to measure over the window: 'count' of targeted observations, or 'avg_score' (the mean scorer score; scorer scanners only). every_match supports 'count' only.+ *+ * * `count` - Count of matching observations+ * * `avg_score` - Average score */+ metric?: VisionAlertMetricEnumApi+ /** The alert fires when the metric is at or above this value. Required for on_breach; ignored for every_match. */+ threshold?: number+ /** Rolling lookback window for on_breach conditions, ending at each check. Defaults to 1 day. every_match ignores it (each check covers what's new since the previous one).+ *+ * * `1` - 1 day+ * * `3` - 3 days+ * * `7` - 7 days+ * * `14` - 14 days+ * * `30` - 30 days */+ window_days?: WindowDaysEnumApi+}+/*** * `slack` - Slack*/@@ -179,6 +248,7 @@ export interface VisionActionApi {/** What the action produces. MVP supports 'group_summary' only.** * `group_summary` - Group summary+ * * `alert` - Alert* * `per_observation` - Per observation */mode?: VisionActionModeEnumApi/** Trigger parameters. For schedule triggers: {rrule, timezone}. */@@ -187,6 +257,8 @@ export interface VisionActionApi {selection?: SelectionApi/** Synthesis options for the group summary, e.g. {prompt_guide}. */synthesis_config?: SynthesisConfigApi+ /** Alert condition; required when mode is 'alert', ignored otherwise. */+ alert_config?: AlertConfigApi/** List of delivery destinations the synthesized summary is sent to. */delivery_config?: DeliveryTargetApi[]/**@@ -240,6 +312,7 @@ export interface PatchedVisionActionApi {/** What the action produces. MVP supports 'group_summary' only.** * `group_summary` - Group summary+ * * `alert` - Alert* * `per_observation` - Per observation */mode?: VisionActionModeEnumApi/** Trigger parameters. For schedule triggers: {rrule, timezone}. */@@ -248,6 +321,8 @@ export interface PatchedVisionActionApi {selection?: SelectionApi/** Synthesis options for the group summary, e.g. {prompt_guide}. */synthesis_config?: SynthesisConfigApi+ /** Alert condition; required when mode is 'alert', ignored otherwise. */+ alert_config?: AlertConfigApi/** List of delivery destinations the synthesized summary is sent to. */delivery_config?: DeliveryTargetApi[]/**diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 44ea74c5ae98..d94951333163 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -17,6 +17,9 @@ export const visionActionsCreateBodyNameMax = 255export const visionActionsCreateBodyTriggerConfigOneTimezoneDefault = `UTC`export const visionActionsCreateBodySynthesisConfigOnePromptGuideMax = 500+export const visionActionsCreateBodyAlertConfigOneFrequencyDefault = `on_breach`+export const visionActionsCreateBodyAlertConfigOneMetricDefault = `count`+export const VisionActionsCreateBody = /* @__PURE__ */ zod.object({name: zod.string()@@ -38,11 +41,11 @@ export const VisionActionsCreateBody = /* @__PURE__ */ zod.object({"What fires the action. MVP supports 'schedule' only.\n\n\* `schedule` - Schedule\n\* `threshold` - Threshold"),mode: zod- .enum(['group_summary', 'per_observation'])- .describe('\* `group_summary` - Group summary\n\* `per_observation` - Per observation')+ .enum(['group_summary', 'alert', 'per_observation'])+ .describe('\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation').optional().describe(- "What the action produces. MVP supports 'group_summary' only.\n\n\* `group_summary` - Group summary\n\* `per_observation` - Per observation"+ "What the action produces. MVP supports 'group_summary' only.\n\n\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation"),trigger_config: zod.object({@@ -103,6 +106,41 @@ export const VisionActionsCreateBody = /* @__PURE__ */ zod.object({.describe('Options for the group-summary synthesis step.').optional().describe('Synthesis options for the group summary, e.g. {prompt_guide}.'),+ alert_config: zod+ .object({+ frequency: zod+ .enum(['every_match', 'on_breach'])+ .describe('\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed')+ .default(visionActionsCreateBodyAlertConfigOneFrequencyDefault)+ .describe(+ "'every_match' notifies about every new matching observation (batched per check); 'on_breach' notifies once when the threshold condition starts holding. Defaults to 'on_breach'.\n\n\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed"+ ),+ metric: zod+ .enum(['count', 'avg_score'])+ .describe('\* `count` - Count of matching observations\n\* `avg_score` - Average score')+ .default(visionActionsCreateBodyAlertConfigOneMetricDefault)+ .describe(+ "What to measure over the window: 'count' of targeted observations, or 'avg_score' (the mean scorer score; scorer scanners only). every_match supports 'count' only.\n\n\* `count` - Count of matching observations\n\* `avg_score` - Average score"+ ),+ threshold: zod+ .number()+ .optional()+ .describe(+ 'The alert fires when the metric is at or above this value. Required for on_breach; ignored for every_match.'+ ),+ window_days: zod+ .union([zod.literal(1), zod.literal(3), zod.literal(7), zod.literal(14), zod.literal(30)])+ .describe('\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days')+ .optional()+ .describe(+ "Rolling lookback window for on_breach conditions, ending at each check. Defaults to 1 day. every_match ignores it (each check covers what's new since the previous one).\n\n\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days"+ ),+ })+ .describe(+ "The alert condition for mode='alert', applied after `selection` targeting. 'every_match'\nnotifies about each new match since the previous check; 'on_breach' compares a metric to a\nthreshold over a rolling window and notifies on the transition into breach."+ )+ .optional()+ .describe("Alert condition; required when mode is 'alert', ignored otherwise."),delivery_config: zod.array(zod@@ -130,6 +168,9 @@ export const visionActionsPartialUpdateBodyNameMax = 255export const visionActionsPartialUpdateBodyTriggerConfigOneTimezoneDefault = `UTC`export const visionActionsPartialUpdateBodySynthesisConfigOnePromptGuideMax = 500+export const visionActionsPartialUpdateBodyAlertConfigOneFrequencyDefault = `on_breach`+export const visionActionsPartialUpdateBodyAlertConfigOneMetricDefault = `count`+export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod.object({name: zod.string()@@ -155,11 +196,11 @@ export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod.object({"What fires the action. MVP supports 'schedule' only.\n\n\* `schedule` - Schedule\n\* `threshold` - Threshold"),mode: zod- .enum(['group_summary', 'per_observation'])- .describe('\* `group_summary` - Group summary\n\* `per_observation` - Per observation')+ .enum(['group_summary', 'alert', 'per_observation'])+ .describe('\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation').optional().describe(- "What the action produces. MVP supports 'group_summary' only.\n\n\* `group_summary` - Group summary\n\* `per_observation` - Per observation"+ "What the action produces. MVP supports 'group_summary' only.\n\n\* `group_summary` - Group summary\n\* `alert` - Alert\n\* `per_observation` - Per observation"),trigger_config: zod.object({@@ -220,6 +261,41 @@ export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Options for the group-summary synthesis step.').optional().describe('Synthesis options for the group summary, e.g. {prompt_guide}.'),+ alert_config: zod+ .object({+ frequency: zod+ .enum(['every_match', 'on_breach'])+ .describe('\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed')+ .default(visionActionsPartialUpdateBodyAlertConfigOneFrequencyDefault)+ .describe(+ "'every_match' notifies about every new matching observation (batched per check); 'on_breach' notifies once when the threshold condition starts holding. Defaults to 'on_breach'.\n\n\* `every_match` - Every new match\n\* `on_breach` - When a threshold is crossed"+ ),+ metric: zod+ .enum(['count', 'avg_score'])+ .describe('\* `count` - Count of matching observations\n\* `avg_score` - Average score')+ .default(visionActionsPartialUpdateBodyAlertConfigOneMetricDefault)+ .describe(+ "What to measure over the window: 'count' of targeted observations, or 'avg_score' (the mean scorer score; scorer scanners only). every_match supports 'count' only.\n\n\* `count` - Count of matching observations\n\* `avg_score` - Average score"+ ),+ threshold: zod+ .number()+ .optional()+ .describe(+ 'The alert fires when the metric is at or above this value. Required for on_breach; ignored for every_match.'+ ),+ window_days: zod+ .union([zod.literal(1), zod.literal(3), zod.literal(7), zod.literal(14), zod.literal(30)])+ .describe('\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days')+ .optional()+ .describe(+ "Rolling lookback window for on_breach conditions, ending at each check. Defaults to 1 day. every_match ignores it (each check covers what's new since the previous one).\n\n\* `1` - 1 day\n\* `3` - 3 days\n\* `7` - 7 days\n\* `14` - 14 days\n\* `30` - 30 days"+ ),+ })+ .describe(+ "The alert condition for mode='alert', applied after `selection` targeting. 'every_match'\nnotifies about each new match since the previous check; 'on_breach' compares a metric to a\nthreshold over a rolling window and notifies on the transition into breach."+ )+ .optional()+ .describe("Alert condition; required when mode is 'alert', ignored otherwise."),delivery_config: zod.array(zoddiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3d458cb9bc8b..22b5a941c11c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9396,6 +9396,76 @@ export namespace Schemas {readonly search_match_type: SearchMatchTypeEnum | null;}+ /**+ * * `every_match` - Every new match+ * * `on_breach` - When a threshold is crossed+ */+ export type AlertConfigFrequencyEnum = typeof AlertConfigFrequencyEnum[keyof typeof AlertConfigFrequencyEnum];+++ export const AlertConfigFrequencyEnum = {+ EveryMatch: 'every_match',+ OnBreach: 'on_breach',+ } as const;++ /**+ * * `count` - Count of matching observations+ * * `avg_score` - Average score+ */+ export type VisionAlertMetricEnum = typeof VisionAlertMetricEnum[keyof typeof VisionAlertMetricEnum];+++ export const VisionAlertMetricEnum = {+ Count: 'count',+ AvgScore: 'avg_score',+ } as const;++ /**+ * * `1` - 1 day+ * * `3` - 3 days+ * * `7` - 7 days+ * * `14` - 14 days+ * * `30` - 30 days+ */+ export type WindowDaysEnum = typeof WindowDaysEnum[keyof typeof WindowDaysEnum];+++ export const WindowDaysEnum = {+ Number1: 1,+ Number3: 3,+ Number7: 7,+ Number14: 14,+ Number30: 30,+ } as const;++ /**+ * The alert condition for mode='alert', applied after `selection` targeting. 'every_match'+ * notifies about each new match since the previous check; 'on_breach' compares a metric to a+ * threshold over a rolling window and notifies on the transition into breach.+ */+ export interface AlertConfig {+ /** 'every_match' notifies about every new matching observation (batched per check); 'on_breach' notifies once when the threshold condition starts holding. Defaults to 'on_breach'.+ *+ * * `every_match` - Every new match+ * * `on_breach` - When a threshold is crossed */+ frequency?: AlertConfigFrequencyEnum;+ /** What to measure over the window: 'count' of targeted observations, or 'avg_score' (the mean scorer score; scorer scanners only). every_match supports 'count' only.+ *+ * * `count` - Count of matching observations+ * * `avg_score` - Average score */+ metric?: VisionAlertMetricEnum;+ /** The alert fires when the metric is at or above this value. Required for on_breach; ignored for every_match. */+ threshold?: number;+ /** Rolling lookback window for on_breach conditions, ending at each check. Defaults to 1 day. every_match ignores it (each check covers what's new since the previous one).+ *+ * * `1` - 1 day+ * * `3` - 3 days+ * * `7` - 7 days+ * * `14` - 14 days+ * * `30` - 30 days */+ window_days?: WindowDaysEnum;+ }+export interface AlertSimulate {/** Insight ID to simulate the detector on. */insight: number;@@ -39329,6 +39399,7 @@ export namespace Schemas {/*** * `group_summary` - Group summary+ * * `alert` - Alert* * `per_observation` - Per observation*/export type VisionActionModeEnum = typeof VisionActionModeEnum[keyof typeof VisionActionModeEnum];@@ -39336,6 +39407,7 @@ export namespace Schemas {export const VisionActionModeEnum = {GroupSummary: 'group_summary',+ Alert: 'alert',PerObservation: 'per_observation',} as const;@@ -39412,6 +39484,7 @@ export namespace Schemas {/** What the action produces. MVP supports 'group_summary' only.** * `group_summary` - Group summary+ * * `alert` - Alert* * `per_observation` - Per observation */mode?: VisionActionModeEnum;/** Trigger parameters. For schedule triggers: {rrule, timezone}. */@@ -39420,6 +39493,8 @@ export namespace Schemas {selection?: Selection;/** Synthesis options for the group summary, e.g. {prompt_guide}. */synthesis_config?: SynthesisConfig;+ /** Alert condition; required when mode is 'alert', ignored otherwise. */+ alert_config?: AlertConfig;/** List of delivery destinations the synthesized summary is sent to. */delivery_config?: DeliveryTarget[];/**@@ -46710,6 +46785,7 @@ export namespace Schemas {/** What the action produces. MVP supports 'group_summary' only.** * `group_summary` - Group summary+ * * `alert` - Alert* * `per_observation` - Per observation */mode?: VisionActionModeEnum;/** Trigger parameters. For schedule triggers: {rrule, timezone}. */@@ -46718,6 +46794,8 @@ export namespace Schemas {selection?: Selection;/** Synthesis options for the group summary, e.g. {prompt_guide}. */synthesis_config?: SynthesisConfig;+ /** Alert condition; required when mode is 'alert', ignored otherwise. */+ alert_config?: AlertConfig;/** List of delivery destinations the synthesized summary is sent to. */delivery_config?: DeliveryTarget[];/**