Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay-vision): add VisionAction + VisionActionRun models (#64168)

Kim Svatos Duganecd17391c43d
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 37d81901e01b..843bb96bce9e 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -252,6 +252,8 @@ rules:
|UserInterview
|UserInterviewTopic
|UserRepoPreference
+ |VisionAction
+ |VisionActionRun
|WebAnalyticsAchievementProgress
|WebAnalyticsFilterPreset
|WebAnalyticsInteraction
@@ -506,6 +508,8 @@ rules:
|UserInterview
|UserInterviewTopic
|UserRepoPreference
+ |VisionAction
+ |VisionActionRun
|WebAnalyticsAchievementProgress
|WebAnalyticsFilterPreset
|WebAnalyticsInteraction
diff --git a/products/replay_vision/backend/admin.py b/products/replay_vision/backend/admin.py
index 9d3e6eff23e7..71180bfbaf1e 100644
--- a/products/replay_vision/backend/admin.py
+++ b/products/replay_vision/backend/admin.py
@@ -4,7 +4,13 @@ from typing import Any
from django.contrib import admin
from django.http import HttpRequest
-from products.replay_vision.backend.models import ReplayObservation, ReplayQuotaGrant, ReplayScanner
+from products.replay_vision.backend.models import (
+ ReplayObservation,
+ ReplayQuotaGrant,
+ ReplayScanner,
+ VisionAction,
+ VisionActionRun,
+)
from products.replay_vision.backend.quota import next_month_start
@@ -59,3 +65,39 @@ class ReplayQuotaGrantAdmin(admin.ModelAdmin):
initial.setdefault("expires_at", next_month_start(datetime.now(UTC)))
initial.setdefault("granted_by", request.user.pk)
return initial
+
+
[email protected](VisionAction)
+class VisionActionAdmin(admin.ModelAdmin):
+ list_display = ("name", "team", "scanner", "trigger_type", "mode", "enabled", "next_run_at", "created_at")
+ list_filter = ("trigger_type", "mode", "enabled")
+ search_fields = ("name",)
+ raw_id_fields = ("team", "scanner", "hog_flow", "created_by")
+ readonly_fields = ("id", "next_run_at", "last_run_at", "created_at", "updated_at")
+
+
[email protected](VisionActionRun)
+class VisionActionRunAdmin(admin.ModelAdmin):
+ list_display = ("id", "vision_action", "team", "status", "observation_count", "scheduled_at", "created_at")
+ list_filter = ("status",)
+ search_fields = ("idempotency_key", "temporal_workflow_id")
+ raw_id_fields = ("vision_action", "team")
+ readonly_fields = (
+ "id",
+ "vision_action",
+ "team",
+ "temporal_workflow_id",
+ "idempotency_key",
+ "scheduled_at",
+ "status",
+ "synthesized_markdown",
+ "output",
+ "observation_count",
+ "error",
+ "created_at",
+ "updated_at",
+ )
+
+ def has_add_permission(self, request: HttpRequest) -> bool:
+ # Created by the vision-action workflow, never via admin.
+ return False
diff --git a/products/replay_vision/backend/migrations/0014_visionaction_visionactionrun_and_more.py b/products/replay_vision/backend/migrations/0014_visionaction_visionactionrun_and_more.py
new file mode 100644
index 000000000000..6c1b3f99cdca
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0014_visionaction_visionactionrun_and_more.py
@@ -0,0 +1,222 @@
+# Generated by Django 5.2.14 on 2026-06-17 18:42
+
+import django.db.models.manager
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+import products.replay_vision.backend.models.vision_action
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1224_columnconfiguration_properties"),
+ ("replay_vision", "0013_replayscanner_estimated_at_and_more"),
+ ("workflows", "0008_teamworkflowsconfig"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="VisionAction",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(max_length=255)),
+ ("enabled", models.BooleanField(default=True)),
+ (
+ "trigger_type",
+ models.CharField(
+ choices=[("schedule", "Schedule"), ("threshold", "Threshold")],
+ default="schedule",
+ help_text="What fires the action. MVP supports 'schedule' only.",
+ max_length=20,
+ ),
+ ),
+ (
+ "mode",
+ models.CharField(
+ choices=[
+ ("group_summary", "Group summary"),
+ ("per_observation", "Per observation"),
+ ],
+ default="group_summary",
+ help_text="What the action produces. MVP supports 'group_summary' only.",
+ max_length=20,
+ ),
+ ),
+ (
+ "next_run_at",
+ models.DateTimeField(
+ blank=True,
+ help_text="Computed next fire time for schedule triggers; the scheduler scans this.",
+ null=True,
+ ),
+ ),
+ ("last_run_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "trigger_config",
+ models.JSONField(
+ default=dict,
+ help_text="Trigger parameters. Schedule: {rrule, timezone}. Threshold (reserved): {metric, window, op, value}.",
+ ),
+ ),
+ (
+ "selection",
+ models.JSONField(
+ default=products.replay_vision.backend.models.vision_action.default_selection,
+ help_text="Observation filter applied at synthesis time (scanner_ids, verdict, tags, scores, status, window_days).",
+ ),
+ ),
+ (
+ "synthesis_config",
+ models.JSONField(
+ default=dict,
+ help_text="Synthesis options, e.g. {prompt_guide}.",
+ ),
+ ),
+ (
+ "delivery_config",
+ models.JSONField(
+ default=list,
+ help_text="List of destination targets, e.g. [{type: 'slack', integration_id, channel}].",
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "hog_flow",
+ models.ForeignKey(
+ blank=True,
+ help_text="Delivery flow provisioned by the API; the action emits an event this flow delivers.",
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="workflows.hogflow",
+ ),
+ ),
+ (
+ "scanner",
+ models.ForeignKey(
+ help_text="Scanner whose observations this action operates on. An action runs as a child of this scanner's sweep.",
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="vision_actions",
+ to="replay_vision.replayscanner",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="vision_actions",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "default_manager_name": "all_teams",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="VisionActionRun",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "temporal_workflow_id",
+ models.CharField(blank=True, max_length=255, null=True),
+ ),
+ ("idempotency_key", models.CharField(max_length=255, unique=True)),
+ ("scheduled_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("running", "Running"),
+ ("completed", "Completed"),
+ ("failed", "Failed"),
+ ("skipped", "Skipped"),
+ ],
+ default="running",
+ max_length=20,
+ ),
+ ),
+ ("synthesized_markdown", models.TextField(blank=True, default="")),
+ ("output", models.JSONField(default=dict)),
+ ("observation_count", models.PositiveIntegerField(default=0)),
+ ("error", models.JSONField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "vision_action",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="runs",
+ to="replay_vision.visionaction",
+ ),
+ ),
+ ],
+ options={
+ "default_manager_name": "all_teams",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.AddIndex(
+ model_name="visionaction",
+ index=models.Index(
+ condition=models.Q(("enabled", True)),
+ fields=["team", "next_run_at"],
+ name="vision_action_due_idx",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="visionaction",
+ constraint=models.UniqueConstraint(fields=("team", "name"), name="vision_action_unique_team_name"),
+ ),
+ migrations.AddIndex(
+ model_name="visionactionrun",
+ index=models.Index(
+ fields=["vision_action", "-created_at"],
+ name="vision_action_run_recent_idx",
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0015_alter_visionaction_selection.py b/products/replay_vision/backend/migrations/0015_alter_visionaction_selection.py
new file mode 100644
index 000000000000..f116fd0bed93
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0015_alter_visionaction_selection.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.14 on 2026-06-17 23:32
+
+from django.db import migrations, models
+
+import products.replay_vision.backend.models.vision_action
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0014_visionaction_visionactionrun_and_more"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="visionaction",
+ name="selection",
+ field=models.JSONField(
+ default=products.replay_vision.backend.models.vision_action.default_selection,
+ help_text="Observation filter applied at synthesis time. Supported keys: scanner_type (string — filters observations by scanner type, independent of the bound `scanner` FK which scopes scheduling), scanner_ids (list[str]), verdict, tags, scores, status, window_days.",
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 8ba37f153725..7299a7e54aed 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0013_replayscanner_estimated_at_and_more
+0015_alter_visionaction_selection
diff --git a/products/replay_vision/backend/models/__init__.py b/products/replay_vision/backend/models/__init__.py
index 0e64f93e98f5..294c9cfaa815 100644
--- a/products/replay_vision/backend/models/__init__.py
+++ b/products/replay_vision/backend/models/__init__.py
@@ -1,5 +1,6 @@
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrant
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun
-__all__ = ["ReplayObservation", "ReplayQuotaGrant", "ReplayScanner"]
+__all__ = ["ReplayObservation", "ReplayQuotaGrant", "ReplayScanner", "VisionAction", "VisionActionRun"]
diff --git a/products/replay_vision/backend/models/vision_action.py b/products/replay_vision/backend/models/vision_action.py
new file mode 100644
index 000000000000..06ebae8fc8e2
--- /dev/null
+++ b/products/replay_vision/backend/models/vision_action.py
@@ -0,0 +1,196 @@
+from typing import Any
+
+from django.db import models
+from django.utils import timezone
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+from products.replay_vision.backend.rrule import compute_next_occurrences
+
+
+def default_selection() -> dict[str, Any]:
+ # Past-day summarizer observations — the most common "and then" group summary.
+ return {"scanner_type": "summarizer", "window_days": 1}
+
+
+class TriggerType(models.TextChoices):
+ SCHEDULE = "schedule", "Schedule"
+ THRESHOLD = "threshold", "Threshold" # reserved for alerts; rejected at the API for now
+
+
+class ActionMode(models.TextChoices):
+ GROUP_SUMMARY = "group_summary", "Group summary" # one summary synthesized from a group of observations
+ PER_OBSERVATION = "per_observation", "Per observation" # reserved; rejected at the API for now
+
+
+class VisionAction(TeamScopedRootMixin, UUIDModel):
+ """An "and then…" automation over a scanner's observations: gather, (optionally) synthesize, deliver.
+
+ MVP is schedule-triggered group summaries; the trigger_type/mode enums leave room for
+ threshold alerts and per-observation reactions without a schema change.
+ """
+
+ all_teams = models.Manager() # noqa: DJ012 — escape hatch for cross-team Temporal/admin access
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="vision_actions")
+ scanner = models.ForeignKey(
+ "replay_vision.ReplayScanner",
+ on_delete=models.CASCADE,
+ related_name="vision_actions",
+ help_text="Scanner whose observations this action operates on. An action runs as a child of this scanner's sweep.",
+ )
+ name = models.CharField(max_length=255)
+ enabled = models.BooleanField(default=True)
+
+ trigger_type = models.CharField(
+ max_length=20,
+ choices=TriggerType.choices,
+ default=TriggerType.SCHEDULE,
+ help_text="What fires the action. MVP supports 'schedule' only.",
+ )
+ mode = models.CharField(
+ max_length=20,
+ choices=ActionMode.choices,
+ default=ActionMode.GROUP_SUMMARY,
+ help_text="What the action produces. MVP supports 'group_summary' only.",
+ )
+
+ next_run_at = models.DateTimeField(
+ null=True,
+ blank=True,
+ help_text="Computed next fire time for schedule triggers; the scheduler scans this.",
+ )
+ last_run_at = models.DateTimeField(null=True, blank=True)
+
+ trigger_config = models.JSONField(
+ default=dict,
+ help_text="Trigger parameters. Schedule: {rrule, timezone}. Threshold (reserved): {metric, window, op, value}.",
+ )
+ selection = models.JSONField(
+ default=default_selection,
+ help_text=(
+ "Observation filter applied at synthesis time. "
+ "Supported keys: scanner_type (string — filters observations by scanner type, "
+ "independent of the bound `scanner` FK which scopes scheduling), "
+ "scanner_ids (list[str]), verdict, tags, scores, status, window_days."
+ ),
+ )
+ synthesis_config = models.JSONField(default=dict, help_text="Synthesis options, e.g. {prompt_guide}.")
+ delivery_config = models.JSONField(
+ default=list,
+ help_text="List of destination targets, e.g. [{type: 'slack', integration_id, channel}].",
+ )
+
+ hog_flow = models.ForeignKey(
+ "workflows.HogFlow",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ help_text="Delivery flow provisioned by the API; the action emits an event this flow delivers.",
+ )
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ default_manager_name = "all_teams"
+ constraints = [
+ models.UniqueConstraint(fields=["team", "name"], name="vision_action_unique_team_name"),
+ ]
+ indexes = [
+ models.Index(
+ fields=["team", "next_run_at"],
+ name="vision_action_due_idx",
+ condition=models.Q(enabled=True),
+ ),
+ ]
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ # Cache the schedule key so save() can detect cadence changes. Guard against deferred-field
+ # recursion the same way Subscription does (accessing a deferred field triggers a reload).
+ if not ({"trigger_type", "trigger_config"} & self.get_deferred_fields()):
+ self._cached_schedule_key = self._schedule_key()
+
+ def _schedule_key(self) -> tuple[str, str] | None:
+ # Both the rrule AND the timezone determine the next fire time, so a change to either must
+ # trigger a recompute — keying on the rrule alone would miss a timezone-only edit.
+ if self.trigger_type != TriggerType.SCHEDULE:
+ return None
+ cfg = self.trigger_config or {}
+ rrule = cfg.get("rrule")
+ if not rrule:
+ return None
+ return (rrule, cfg.get("timezone", "UTC"))
+
+ def _recompute_next_run_at(self) -> None:
+ key = self._schedule_key()
+ if key is None:
+ self.next_run_at = None
+ return
+ rrule, timezone_str = key
+ starts_at = self.created_at or timezone.now()
+ occurrences = compute_next_occurrences(
+ rrule_string=rrule, starts_at=starts_at, timezone_str=timezone_str, count=1
+ )
+ self.next_run_at = occurrences[0] if occurrences else None
+
+ def save(self, *args: Any, **kwargs: Any) -> None:
+ # UUIDModel assigns `id` at __init__, so `not self.id` never detects a create —
+ # `_state.adding` is the correct new-vs-persisted signal here.
+ current_key = self._schedule_key()
+ if self._state.adding or getattr(self, "_cached_schedule_key", None) != current_key:
+ self._recompute_next_run_at()
+ update_fields = kwargs.get("update_fields")
+ if update_fields is not None:
+ kwargs["update_fields"] = [*update_fields, "next_run_at"]
+ super().save(*args, **kwargs)
+ self._cached_schedule_key = current_key
+
+ def __str__(self) -> str:
+ return f"{self.name} ({self.trigger_type})"
+
+
+class VisionActionRunStatus(models.TextChoices):
+ RUNNING = "running", "Running"
+ COMPLETED = "completed", "Completed"
+ FAILED = "failed", "Failed"
+ SKIPPED = "skipped", "Skipped"
+
+
+class VisionActionRun(TeamScopedRootMixin, UUIDModel):
+ """History of a single VisionAction execution. The full synthesized report lives here (not on
+ the Temporal wire) and backs the 'view full group summary' link."""
+
+ all_teams = models.Manager() # noqa: DJ012 — escape hatch for cross-team Temporal/admin access
+
+ vision_action = models.ForeignKey(VisionAction, on_delete=models.CASCADE, related_name="runs")
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
+
+ temporal_workflow_id = models.CharField(max_length=255, null=True, blank=True)
+ idempotency_key = models.CharField(max_length=255, unique=True)
+ scheduled_at = models.DateTimeField(null=True, blank=True)
+ status = models.CharField(
+ max_length=20, choices=VisionActionRunStatus.choices, default=VisionActionRunStatus.RUNNING
+ )
+ synthesized_markdown = models.TextField(blank=True, default="")
+ # Channel-formatted delivery payloads keyed by channel, e.g. {"slack": "...", "email": "..."} —
+ # generic so new channels don't each add a column. synthesized_markdown stays the canonical report.
+ output = models.JSONField(default=dict)
+ observation_count = models.PositiveIntegerField(default=0)
+ error = models.JSONField(null=True, blank=True)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ default_manager_name = "all_teams"
+ indexes = [
+ models.Index(fields=["vision_action", "-created_at"], name="vision_action_run_recent_idx"),
+ ]
+
+ def __str__(self) -> str:
+ return f"Run {self.id} of {self.vision_action_id} ({self.status})"
diff --git a/products/replay_vision/backend/rrule.py b/products/replay_vision/backend/rrule.py
new file mode 100644
index 000000000000..fc2469ca9c9f
--- /dev/null
+++ b/products/replay_vision/backend/rrule.py
@@ -0,0 +1,58 @@
+"""Local rrule helpers for scheduled vision actions.
+
+Behaviorally identical to `products/workflows/backend/utils/rrule_utils.py` — copied rather
+than imported so replay_vision doesn't take a cross-product dependency on the Workflows
+backend just for date math. If these ever need to share an implementation, lift them into a
+common module rather than wiring a product-to-product import.
+"""
+
+from datetime import UTC, datetime
+from zoneinfo import ZoneInfo
+
+from dateutil.rrule import rrulestr
+
+
+def validate_rrule(rrule_string: str) -> None:
+ """Validate an RRULE string. Raises ValueError if invalid."""
+ # Case-insensitive: dateutil normalizes property names to uppercase, so a lowercase
+ # `dtstart:` would otherwise slip past and override the managed start.
+ if "DTSTART" in rrule_string.upper():
+ raise ValueError("RRULE must not contain DTSTART (starts_at is managed separately)")
+ try:
+ rrulestr(rrule_string)
+ except (TypeError, ValueError) as e:
+ # rrulestr raises ValueError for most malformed input (bad FREQ/BYDAY/INTERVAL, empty
+ # string) and TypeError only for the missing-FREQ case — normalize both to ValueError.
+ raise ValueError(str(e)) from e
+
+
+def compute_next_occurrences(
+ rrule_string: str,
+ starts_at: datetime,
+ timezone_str: str = "UTC",
+ after: datetime | None = None,
+ count: int = 1,
+) -> list[datetime]:
+ """Compute the next `count` occurrences from an RRULE string.
+
+ Expands the RRULE in naive local time so that e.g. "9 AM Europe/Prague" stays at 9 AM
+ local across DST changes, then converts to UTC for storage.
+ """
+ tz = ZoneInfo(timezone_str)
+
+ starts_local = starts_at.astimezone(tz).replace(tzinfo=None)
+ rule = rrulestr(rrule_string, dtstart=starts_local, ignoretz=True)
+ after_local = (after or datetime.now(UTC)).astimezone(tz).replace(tzinfo=None)
+
+ occurrences: list[datetime] = []
+ current = after_local
+ for _ in range(count * 10): # safety limit against unbounded gaps
+ next_dt = rule.after(current, inc=False)
+ if next_dt is None:
+ break
+ occurrences.append(next_dt.replace(tzinfo=tz).astimezone(UTC))
+ if len(occurrences) >= count:
+ break
+ current = next_dt
+
+ return occurrences
diff --git a/products/replay_vision/backend/tests/test_vision_action_models.py b/products/replay_vision/backend/tests/test_vision_action_models.py
new file mode 100644
index 000000000000..44c34a329da4
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_vision_action_models.py
@@ -0,0 +1,342 @@
+import uuid
+from datetime import UTC, datetime, timedelta
+from zoneinfo import ZoneInfo
+
+from posthog.test.base import BaseTest
+
+from django.db import IntegrityError
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.scoping.manager import TeamScopeError
+
+from products.replay_vision.backend.models import ReplayScanner, VisionAction, VisionActionRun
+from products.replay_vision.backend.models.replay_scanner import ScannerModel, ScannerType
+from products.replay_vision.backend.models.vision_action import (
+ ActionMode,
+ TriggerType,
+ VisionActionRunStatus,
+ default_selection,
+)
+from products.replay_vision.backend.rrule import compute_next_occurrences, validate_rrule
+
+DAILY_9AM = "FREQ=DAILY;BYHOUR=9;BYMINUTE=0;BYSECOND=0"
+
+
+def _make_action(team, **overrides) -> VisionAction:
+ if "scanner" not in overrides:
+ overrides["scanner"] = ReplayScanner.objects.create(
+ team=team,
+ name=f"scanner-{uuid.uuid4().hex[:8]}",
+ scanner_type=ScannerType.SUMMARIZER,
+ scanner_config={"prompt": "x"},
+ model=ScannerModel.GEMINI_3_FLASH,
+ )
+ defaults: dict = {
+ "team": team,
+ "name": "my-action",
+ "trigger_config": {"rrule": DAILY_9AM, "timezone": "UTC"},
+ }
+ defaults.update(overrides)
+ action = VisionAction(**defaults)
+ action.save()
+ return action
+
+
+class TestVisionActionModel(BaseTest):
+ def _create_action(self, **overrides) -> VisionAction:
+ return _make_action(self.team, **overrides)
+
+ def test_defaults(self) -> None:
+ action = self._create_action()
+ self.assertEqual(action.enabled, True)
+ self.assertEqual(action.trigger_type, TriggerType.SCHEDULE)
+ self.assertEqual(action.mode, ActionMode.GROUP_SUMMARY)
+ self.assertEqual(action.selection, {"scanner_type": "summarizer", "window_days": 1})
+ self.assertEqual(action.synthesis_config, {})
+ self.assertEqual(action.delivery_config, [])
+ self.assertIsNotNone(action.scanner)
+ self.assertIsNone(action.hog_flow)
+
+ def test_default_selection_is_a_fresh_dict_per_instance(self) -> None:
+ # Guards against the classic mutable-default footgun.
+ a = self._create_action(name="a")
+ b = self._create_action(name="b")
+ a.selection["window_days"] = 99
+ self.assertEqual(b.selection["window_days"], 1)
+ self.assertIsNot(default_selection(), default_selection())
+
+ def test_next_run_at_computed_from_rrule_on_create(self) -> None:
+ action = self._create_action()
+ self.assertIsNotNone(action.next_run_at)
+ assert action.next_run_at is not None
+ self.assertGreater(action.next_run_at, timezone.now())
+ # 9am UTC daily — the computed time must land on 09:00.
+ self.assertEqual(action.next_run_at.astimezone(UTC).hour, 9)
+
+ def test_next_run_at_none_without_rrule(self) -> None:
+ action = self._create_action(trigger_config={})
+ self.assertIsNone(action.next_run_at)
+
+ def test_next_run_at_none_for_non_schedule_trigger(self) -> None:
+ action = self._create_action(
+ trigger_type=TriggerType.THRESHOLD,
+ trigger_config={"rrule": DAILY_9AM},
+ )
+ self.assertIsNone(action.next_run_at)
+
+ def test_next_run_at_recomputed_only_when_rrule_changes(self) -> None:
+ action = self._create_action()
+ original = action.next_run_at
+
+ # Non-rrule change → next_run_at untouched.
+ action.name = "renamed"
+ action.save()
+ action.refresh_from_db()
+ self.assertEqual(action.next_run_at, original)
+
+ # rrule change → recomputed (to a different time).
+ action.trigger_config = {"rrule": "FREQ=DAILY;BYHOUR=17;BYMINUTE=0;BYSECOND=0", "timezone": "UTC"}
+ action.save()
+ action.refresh_from_db()
+ self.assertIsNotNone(action.next_run_at)
+ assert action.next_run_at is not None
+ self.assertEqual(action.next_run_at.astimezone(UTC).hour, 17)
+
+ def test_next_run_at_recomputed_on_timezone_change(self) -> None:
+ # Same rrule, different timezone → next_run_at must move (9am UTC vs 9am Tokyo are different
+ # instants). Keying the recompute on the rrule string alone would miss this.
+ action = self._create_action(trigger_config={"rrule": DAILY_9AM, "timezone": "UTC"})
+ original = action.next_run_at
+
+ action.trigger_config = {"rrule": DAILY_9AM, "timezone": "Asia/Tokyo"}
+ action.save()
+ action.refresh_from_db()
+ self.assertIsNotNone(action.next_run_at)
+ self.assertNotEqual(action.next_run_at, original)
+ assert action.next_run_at is not None
+ # 9am Tokyo = 00:00 UTC.
+ self.assertEqual(action.next_run_at.astimezone(UTC).hour, 0)
+
+ def test_recompute_survives_update_fields(self) -> None:
+ action = self._create_action()
+ action.trigger_config = {"rrule": "FREQ=DAILY;BYHOUR=17;BYMINUTE=0;BYSECOND=0", "timezone": "UTC"}
+ # Even with a narrow update_fields, next_run_at must be appended and persisted.
+ action.save(update_fields=["trigger_config"])
+ action.refresh_from_db()
+ assert action.next_run_at is not None
+ self.assertEqual(action.next_run_at.astimezone(UTC).hour, 17)
+
+ def test_loading_with_deferred_fields_does_not_recurse(self) -> None:
+ action = self._create_action()
+ # .only() defers trigger_config/trigger_type — __init__ must not touch them.
+ lite = VisionAction.all_teams.only("id", "name").get(pk=action.pk)
+ self.assertEqual(lite.name, "my-action")
+
+ def test_unique_team_name(self) -> None:
+ self._create_action(name="dup")
+ with self.assertRaises(IntegrityError):
+ self._create_action(name="dup")
+
+ def test_same_name_allowed_across_teams(self) -> None:
+ other = self.organization.teams.create(name="other")
+ self._create_action(name="shared")
+ # Different team → no clash.
+ _make_action(other, name="shared")
+
+ def test_scanner_cascade_delete(self) -> None:
+ scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="scanner",
+ scanner_type=ScannerType.SUMMARIZER,
+ scanner_config={"prompt": "x"},
+ model=ScannerModel.GEMINI_3_FLASH,
+ )
+ action = self._create_action(scanner=scanner)
+ scanner.delete()
+ self.assertFalse(VisionAction.all_teams.filter(pk=action.pk).exists())
+
+ def test_str(self) -> None:
+ action = self._create_action(name="weekly summary")
+ self.assertIn("weekly summary", str(action))
+
+
+class TestVisionActionScoping(BaseTest):
+ def test_for_team_returns_only_that_teams_actions(self) -> None:
+ other = self.organization.teams.create(name="other")
+ mine = _make_action(self.team, name="mine")
+ _make_action(other, name="theirs")
+
+ ids = list(VisionAction.objects.for_team(self.team.id).values_list("id", flat=True))
+ self.assertEqual(ids, [mine.id])
+
+ def test_objects_fail_closed_without_team_context(self) -> None:
+ _make_action(self.team)
+ with self.assertRaises(TeamScopeError):
+ list(VisionAction.objects.all())
+
+ def test_unscoped_sees_all_teams(self) -> None:
+ other = self.organization.teams.create(name="other")
+ _make_action(self.team, name="mine")
+ _make_action(other, name="theirs")
+ self.assertEqual(VisionAction.objects.unscoped().count(), 2)
+
+
+class TestVisionActionRunModel(BaseTest):
+ def _run(self, action: VisionAction | None = None, **overrides) -> VisionActionRun:
+ # Default to a uniquely-named action so repeated calls don't trip the (team, name)
+ # constraint — that would mask the constraint a given test actually means to exercise.
+ if action is None:
+ action = _make_action(self.team, name=f"run-action-{uuid.uuid4().hex[:8]}")
+ defaults: dict = {
+ "vision_action": action,
+ "team": self.team,
+ "idempotency_key": "key-1",
+ }
+ defaults.update(overrides)
+ run = VisionActionRun(**defaults)
+ run.save()
+ return run
+
+ def test_defaults(self) -> None:
+ run = self._run()
+ self.assertEqual(run.status, VisionActionRunStatus.RUNNING)
+ self.assertEqual(run.observation_count, 0)
+ self.assertEqual(run.synthesized_markdown, "")
+ self.assertEqual(run.output, {})
+ self.assertIsNone(run.error)
+
+ def test_idempotency_key_unique(self) -> None:
+ # Both runs share one action, so the only constraint in play is idempotency_key uniqueness.
+ action = _make_action(self.team, name="shared-action")
+ self._run(action=action, idempotency_key="dup")
+ with self.assertRaises(IntegrityError):
+ self._run(action=action, idempotency_key="dup")
+
+ def test_run_cascade_deleted_with_action(self) -> None:
+ action = _make_action(self.team, name="parent")
+ run = VisionActionRun(vision_action=action, team=self.team, idempotency_key="k")
+ run.save()
+ action.delete()
+ self.assertFalse(VisionActionRun.all_teams.filter(pk=run.pk).exists())
+
+
+class TestRruleHelper(BaseTest):
+ def test_validate_rejects_dtstart(self) -> None:
+ with self.assertRaises(ValueError):
+ validate_rrule("DTSTART:20260101T090000\nFREQ=DAILY")
+
+ def test_validate_rejects_lowercase_dtstart(self) -> None:
+ # dateutil uppercases property names, so a lowercase dtstart must not slip past the guard.
+ with self.assertRaises(ValueError):
+ validate_rrule("dtstart:20260101T090000\nFREQ=DAILY")
+
+ @parameterized.expand(
+ [
+ ("bad_freq", "FREQ=NONSENSE;INTERVAL=banana"), # rrulestr -> ValueError
+ ("bad_byday", "FREQ=DAILY;BYDAY=XX"), # rrulestr -> ValueError
+ ("bad_interval", "FREQ=DAILY;INTERVAL=abc"), # rrulestr -> ValueError
+ ("empty", ""), # rrulestr -> ValueError
+ ("not_an_rrule", "not an rrule at all"), # rrulestr -> ValueError
+ ("missing_freq", "COUNT=5"), # rrulestr -> TypeError (the case the narrow catch handled)
+ ]
+ )
+ def test_validate_normalizes_malformed_to_value_error(self, _label: str, rrule: str) -> None:
+ # rrulestr raises ValueError for most malformed input and TypeError only for missing FREQ —
+ # both must surface as the documented ValueError, never leak as an unhandled TypeError.
+ with self.assertRaises(ValueError):
+ validate_rrule(rrule)
+
+ def test_validate_accepts_valid(self) -> None:
+ validate_rrule("FREQ=WEEKLY;BYDAY=MO,WE,FR;BYHOUR=9")
+
+ def test_occurrences_are_future_and_utc(self) -> None:
+ starts = datetime(2026, 1, 1, tzinfo=UTC)
+ after = datetime(2026, 6, 1, 12, 0, tzinfo=UTC)
+ out = compute_next_occurrences(DAILY_9AM, starts_at=starts, after=after, count=3)
+ self.assertEqual(len(out), 3)
+ for dt in out:
+ self.assertEqual(dt.tzinfo, UTC)
+ self.assertGreater(dt, after)
+ # Strictly increasing.
+ self.assertEqual(out, sorted(out))
+
+ def test_exhausted_rrule_returns_empty(self) -> None:
+ starts = datetime(2026, 1, 1, tzinfo=UTC)
+ after = datetime(2030, 1, 1, tzinfo=UTC)
+ # COUNT=1 from 2026 is long exhausted by 2030.
+ out = compute_next_occurrences("FREQ=DAILY;COUNT=1", starts_at=starts, after=after, count=5)
+ self.assertEqual(out, [])
+
+ def test_dst_keeps_local_wall_clock(self) -> None:
+ # 9am Europe/Prague should stay 9am local across the spring DST switch,
+ # which means the UTC hour shifts from 8 (winter, UTC+1) to 7 (summer, UTC+2).
+ tz = "Europe/Prague"
+ starts = datetime(2026, 1, 1, tzinfo=ZoneInfo(tz))
+ winter = compute_next_occurrences(
+ DAILY_9AM, starts_at=starts, timezone_str=tz, after=datetime(2026, 1, 15, tzinfo=UTC), count=1
+ )[0]
+ summer = compute_next_occurrences(
+ DAILY_9AM, starts_at=starts, timezone_str=tz, after=datetime(2026, 7, 15, tzinfo=UTC), count=1
+ )[0]
+ self.assertEqual(winter.astimezone(ZoneInfo(tz)).hour, 9)
+ self.assertEqual(summer.astimezone(ZoneInfo(tz)).hour, 9)
+ self.assertEqual(winter.hour, 8) # UTC
+ self.assertEqual(summer.hour, 7) # UTC
+
+
+class TestVisionActionStress(BaseTest):
+ @parameterized.expand(
+ [
+ ("daily", "FREQ=DAILY;BYHOUR=9", "UTC"),
+ ("weekly_mwf", "FREQ=WEEKLY;BYDAY=MO,WE,FR;BYHOUR=8", "UTC"),
+ ("monthly_first_weekday", "FREQ=MONTHLY;BYDAY=MO;BYSETPOS=1;BYHOUR=7", "America/New_York"),
+ ("biweekly", "FREQ=WEEKLY;INTERVAL=2;BYDAY=TU;BYHOUR=10", "Europe/London"),
+ ("hourly", "FREQ=HOURLY;INTERVAL=6", "Asia/Tokyo"),
+ ("yearly", "FREQ=YEARLY;BYMONTH=1;BYMONTHDAY=1;BYHOUR=0", "UTC"),
+ ]
+ )
+ def test_varied_rrules_all_compute_a_future_run(self, label: str, rrule: str, tz: str) -> None:
+ action = _make_action(self.team, name=label, trigger_config={"rrule": rrule, "timezone": tz})
+ self.assertIsNotNone(action.next_run_at)
+ assert action.next_run_at is not None
+ self.assertGreater(action.next_run_at, timezone.now())
+
+ def test_bulk_create_and_due_scan(self) -> None:
+ # Stand up many actions, half in the past (due) and half in the future, then exercise
+ # the exact predicate the scheduler fan-out will use and assert it returns only the due ones.
+ past = timezone.now() - timedelta(hours=1)
+ future = timezone.now() + timedelta(days=1)
+ due_ids = set()
+ for i in range(200):
+ action = _make_action(self.team, name=f"action-{i}", trigger_config={})
+ if i % 2 == 0:
+ action.next_run_at = past
+ due_ids.add(action.id)
+ else:
+ action.next_run_at = future
+ action.save(update_fields=["next_run_at"])
+
+ scanned = set(
+ VisionAction.objects.for_team(self.team.id)
+ .filter(enabled=True, trigger_type=TriggerType.SCHEDULE, next_run_at__lte=timezone.now())
+ .values_list("id", flat=True)
+ )
+ self.assertEqual(scanned, due_ids)
+
+ def test_disabled_actions_excluded_from_due_scan(self) -> None:
+ past = timezone.now() - timedelta(hours=1)
+ enabled = _make_action(self.team, name="on", trigger_config={})
+ enabled.next_run_at = past
+ enabled.save(update_fields=["next_run_at"])
+ disabled = _make_action(self.team, name="off", trigger_config={}, enabled=False)
+ disabled.next_run_at = past
+ disabled.save(update_fields=["next_run_at"])
+
+ scanned = set(
+ VisionAction.objects.for_team(self.team.id)
+ .filter(enabled=True, next_run_at__lte=timezone.now())
+ .values_list("id", flat=True)
+ )
+ self.assertEqual(scanned, {enabled.id})