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): deliver match alerts through a transactional outbox (#88405)

Tue Haulund01b8c1ecaef6
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index e0939e0aa225..7bc348765ffa 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -66,6 +66,7 @@ from products.replay_vision.backend.temporal.vision_alerts import (
VisionAlertCheckWorkflow,
cleanup_vision_alert_history_activity,
discover_due_vision_alerts_activity,
+ drain_vision_alert_matches_activity,
evaluate_vision_alert_batch_activity,
)
from products.replay_vision.backend.temporal.workflow import ApplyScannerWorkflow
@@ -85,6 +86,7 @@ WORKFLOWS = [
ACTIVITIES: list[Callable[..., Any]] = [
discover_due_vision_alerts_activity,
evaluate_vision_alert_batch_activity,
+ drain_vision_alert_matches_activity,
cleanup_vision_alert_history_activity,
create_observation_activity,
mark_observation_running_activity,
diff --git a/products/replay_vision/backend/temporal/activities/observation_state.py b/products/replay_vision/backend/temporal/activities/observation_state.py
index cd25682625b1..50e1072f307d 100644
--- a/products/replay_vision/backend/temporal/activities/observation_state.py
+++ b/products/replay_vision/backend/temporal/activities/observation_state.py
@@ -29,6 +29,7 @@ from products.replay_vision.backend.temporal.types import (
MarkObservationRunningInputs,
MarkObservationSucceededInputs,
)
+from products.replay_vision.backend.temporal.vision_alerts.match_hook import record_alert_matches_guarded
logger = structlog.get_logger(__name__)
@@ -158,6 +159,12 @@ def mark_observation_succeeded_activity(inputs: MarkObservationSucceededInputs)
"credits": credits,
},
)
+ record_alert_matches_guarded(
+ observation_id=inputs.observation_id,
+ team_id=obs["team_id"],
+ scanner_id=obs["scanner_id"],
+ model_output=inputs.scanner_result.model_output.model_dump(mode="json"),
+ )
record_observation("succeeded", inputs.scanner_type)
record_observation_e2e(inputs.scanner_type, (timezone.now() - obs["created_at"]).total_seconds())
if receipt_created:
diff --git a/products/replay_vision/backend/temporal/vision_alerts/__init__.py b/products/replay_vision/backend/temporal/vision_alerts/__init__.py
index 702227684458..e484ee1fc63e 100644
--- a/products/replay_vision/backend/temporal/vision_alerts/__init__.py
+++ b/products/replay_vision/backend/temporal/vision_alerts/__init__.py
@@ -1,6 +1,7 @@
from products.replay_vision.backend.temporal.vision_alerts.activities import (
cleanup_vision_alert_history_activity,
discover_due_vision_alerts_activity,
+ drain_vision_alert_matches_activity,
evaluate_vision_alert_batch_activity,
)
from products.replay_vision.backend.temporal.vision_alerts.workflow import VisionAlertCheckWorkflow
@@ -9,6 +10,7 @@ WORKFLOWS = [VisionAlertCheckWorkflow]
ACTIVITIES = [
discover_due_vision_alerts_activity,
evaluate_vision_alert_batch_activity,
+ drain_vision_alert_matches_activity,
cleanup_vision_alert_history_activity,
]
diff --git a/products/replay_vision/backend/temporal/vision_alerts/activities.py b/products/replay_vision/backend/temporal/vision_alerts/activities.py
index 34af24dee36a..2b220c833de8 100644
--- a/products/replay_vision/backend/temporal/vision_alerts/activities.py
+++ b/products/replay_vision/backend/temporal/vision_alerts/activities.py
@@ -12,7 +12,7 @@ from typing import Any
from uuid import NAMESPACE_URL, uuid5
from django.db import IntegrityError, OperationalError, transaction
-from django.db.models import Avg, FloatField, QuerySet
+from django.db.models import Avg, FloatField, Min, QuerySet
from django.db.models.fields.json import KeyTextTransform
from django.db.models.functions import Cast
@@ -30,6 +30,7 @@ from products.alerts.backend.destinations import (
flush_alert_internal_events,
produce_alert_internal_event,
)
+from products.alerts.backend.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuples
from products.replay_vision.backend.alert_destinations import escape_slack_mrkdwn
from products.replay_vision.backend.alert_state_machine import (
AlertCheckOutcome,
@@ -57,12 +58,17 @@ from products.replay_vision.backend.models.vision_alert import (
VisionAlertMatch,
VisionAlertMetric,
)
+from products.replay_vision.backend.observation_formatting import describe_output
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.vision_actions.synthesis import apply_observation_predicate
from products.replay_vision.backend.temporal.vision_alerts.constants import (
CLEANUP_BATCH_SIZE,
+ MATCH_DESCRIPTOR_MAX_CHARS,
+ MATCH_SUMMARY_LINES,
MAX_ALERTS_PER_BATCH,
MAX_ALERTS_PER_TICK,
+ MAX_DRAIN_ALERTS_PER_TICK,
+ MAX_MATCHES_PER_BUNDLE,
NOTIFICATION_FLUSH_TIMEOUT_SECONDS,
)
@@ -601,3 +607,146 @@ def _cleanup_history(inputs: CleanupAlertHistoryInput) -> int:
deleted += VisionAlertMatch.all_teams.filter(id__in=match_ids).delete()[0]
return deleted
+
+
+class DrainMatchesInput(BaseModel):
+ pass
+
+
+class DrainMatchesOutput(BaseModel):
+ alerts_notified: int = 0
+ matches_delivered: int = 0
+
+
+@track_activity()
+async def drain_vision_alert_matches_activity(inputs: DrainMatchesInput) -> DrainMatchesOutput:
+ return await database_sync_to_async(_drain_matches, thread_sensitive=False)(inputs)
+
+
+@frozen
+class _DrainedBundle:
+ alert: VisionAlertConfiguration
+ match_ids: list[Any]
+ produce_result: ProduceResult | None
+
+
+def _drain_matches(inputs: DrainMatchesInput) -> DrainMatchesOutput:
+ """Bundle undelivered match rows into one notification per alert and stamp them
+ delivered only after the producer acks.
+
+ No alert-row locks are taken here: match alerts have no lifecycle state to mutate,
+ and holding one across produce/flush would stall the observation-completion hook's
+ FK inserts against the same alert row. Stamping targets the explicitly drained row
+ IDs, never `delivered_at IS NULL`, so rows inserted mid-drain wait for the next tick.
+ """
+ now = datetime.now(UTC)
+ # Per-alert fairness: pick the alerts with the oldest undelivered rows, then bound
+ # each bundle separately, so one high-volume alert cannot fill a global slice and
+ # starve the rest. Disabled and snoozed alerts are excluded in SQL so their held
+ # rows cannot occupy the alert budget either.
+ due_alert_ids = list(
+ VisionAlertMatch.all_teams.filter(delivered_at__isnull=True, alert__enabled=True)
+ .exclude(alert__snooze_until__gt=now)
+ .values("alert_id")
+ .annotate(oldest=Min("created_at"))
+ .order_by("oldest")
+ .values_list("alert_id", flat=True)[:MAX_DRAIN_ALERTS_PER_TICK]
+ )
+ if not due_alert_ids:
+ return DrainMatchesOutput()
+
+ alerts = (
+ VisionAlertConfiguration.all_teams.filter(id__in=due_alert_ids, kind=VisionAlertKind.MATCH)
+ .select_related("team", "scanner")
+ .order_by("id")
+ )
+
+ bundles: list[_DrainedBundle] = []
+ for alert in alerts:
+ if not alert.enabled:
+ continue # Cleanup reaps the rows; delivering for a disabled alert is wrong.
+ if alert.snooze_until is not None and alert.snooze_until > now:
+ continue # Hold: matches accumulate and deliver as one bundle after the snooze.
+ try:
+ if is_utc_datetime_blocked(
+ now, alert.team.timezone, parse_blocked_windows_tuples(alert.schedule_restriction)
+ ):
+ continue # Quiet hours: hold until the window ends.
+ except Exception as e:
+ logger.exception("vision_alert.drain_invalid_quiet_hours", alert_id=str(alert.id), error=str(e))
+ continue
+
+ # A huge backlog splits across ticks: an oversized event payload would fail the
+ # produce forever, and the leftovers keep their created_at order.
+ rows = list(
+ VisionAlertMatch.all_teams.filter(alert_id=alert.id, delivered_at__isnull=True)
+ .order_by("created_at", "id")
+ .values_list("id", "observation_id")[:MAX_MATCHES_PER_BUNDLE]
+ )
+ if not rows:
+ continue
+ produce_result = _emit_match_event(alert, rows, now)
+ bundles.append(
+ _DrainedBundle(
+ alert=alert,
+ match_ids=[row_id for row_id, _ in rows],
+ produce_result=produce_result,
+ )
+ )
+
+ if any(b.produce_result is not None for b in bundles):
+ flush_alert_internal_events(NOTIFICATION_FLUSH_TIMEOUT_SECONDS)
+
+ output = DrainMatchesOutput()
+ for bundle in bundles:
+ if bundle.produce_result is None:
+ continue # Enqueue failed; rows stay undelivered and re-emit next tick.
+ if not alert_internal_event_delivered(
+ bundle.produce_result,
+ team_id=bundle.alert.team_id,
+ alert_id=str(bundle.alert.id),
+ event_name="$replay_vision_alert_match",
+ ):
+ continue
+ VisionAlertMatch.all_teams.filter(id__in=bundle.match_ids).update(delivered_at=now)
+ output.alerts_notified += 1
+ output.matches_delivered += len(bundle.match_ids)
+ return output
+
+
+def _emit_match_event(
+ alert: VisionAlertConfiguration, rows: list[tuple[Any, Any]], now: datetime
+) -> ProduceResult | None:
+ observation_ids = [str(observation_id) for _, observation_id in rows]
+ summary_rows = ReplayObservation.objects.filter(
+ team_id=alert.team_id, id__in=observation_ids[:MATCH_SUMMARY_LINES]
+ ).values_list("id", "scanner_result", "completed_at")
+ by_id = {str(row_id): (scanner_result, completed_at) for row_id, scanner_result, completed_at in summary_rows}
+ lines: list[str] = []
+ for observation_id in observation_ids[:MATCH_SUMMARY_LINES]:
+ scanner_result, completed_at = by_id.get(observation_id, (None, None))
+ model_output = (scanner_result or {}).get("model_output") or {}
+ descriptor = escape_slack_mrkdwn((describe_output(model_output) or "observation")[:MATCH_DESCRIPTOR_MAX_CHARS])
+ stamp = f"({completed_at:%Y-%m-%d %H:%M} UTC) " if completed_at else ""
+ lines.append(f"- {stamp}{descriptor}")
+ if len(observation_ids) > MATCH_SUMMARY_LINES:
+ lines.append(f"- and {len(observation_ids) - MATCH_SUMMARY_LINES} more")
+
+ # Deterministic uuid over the drained row set: an identical-batch retry (crash
+ # after ack, before the stamp, with no new rows) dedupes at ingestion.
+ event_uuid = uuid5(NAMESPACE_URL, f"vision-alert-match:{alert.id}:{','.join(sorted(str(m) for m, _ in rows))}")
+
+ properties = {
+ **_base_properties(alert, now),
+ "matched_count": len(rows),
+ "observation_ids": observation_ids,
+ "summary": "\n".join(lines),
+ }
+ return produce_alert_internal_event(
+ team_id=alert.team_id,
+ event_name="$replay_vision_alert_match",
+ properties=properties,
+ timestamp=now,
+ uuid=str(event_uuid),
+ )
diff --git a/products/replay_vision/backend/temporal/vision_alerts/constants.py b/products/replay_vision/backend/temporal/vision_alerts/constants.py
index f406e857707a..f4785d882f17 100644
--- a/products/replay_vision/backend/temporal/vision_alerts/constants.py
+++ b/products/replay_vision/backend/temporal/vision_alerts/constants.py
@@ -19,3 +19,9 @@ MAX_ALERTS_PER_BATCH = 25
MAX_ALERTS_PER_TICK = 500
NOTIFICATION_FLUSH_TIMEOUT_SECONDS = 10.0
CLEANUP_BATCH_SIZE = 1000
+MATCH_SUMMARY_LINES = 10
+# Caps one bundled event so a backlog can never build an unproducible payload.
+MAX_MATCHES_PER_BUNDLE = 500
+# Caps the rows one drain tick loads into memory; a larger backlog drains over later ticks.
+MAX_DRAIN_ALERTS_PER_TICK = 100
+MATCH_DESCRIPTOR_MAX_CHARS = 200
diff --git a/products/replay_vision/backend/temporal/vision_alerts/match_hook.py b/products/replay_vision/backend/temporal/vision_alerts/match_hook.py
new file mode 100644
index 000000000000..20e1acc36bbc
--- /dev/null
+++ b/products/replay_vision/backend/temporal/vision_alerts/match_hook.py
@@ -0,0 +1,124 @@
+"""Observation-completion hook for match-kind vision alerts.
+
+Called from inside the observation success transaction, after the conditional status
+UPDATE has actually transitioned the row (the exactly-once guard). Inserts one
+VisionAlertMatch outbox row per matching enabled match alert; the alert-check workflow
+drains undelivered rows into one bundled notification per alert per tick.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from uuid import UUID
+
+from django.db import transaction
+
+import structlog
+
+from posthog.exceptions_capture import capture_exception
+
+from products.replay_vision.backend.models.vision_alert import (
+ VisionAlertConfiguration,
+ VisionAlertKind,
+ VisionAlertMatch,
+ selection_has_predicate,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+def record_alert_matches_guarded(
+ *,
+ observation_id: UUID,
+ team_id: int,
+ scanner_id: UUID,
+ model_output: dict[str, Any],
+) -> None:
+ """Match the observation against enabled match alerts inside a savepoint.
+
+ A hook failure must not roll back the observation's status transition, so the
+ insert runs in a nested atomic block and any exception is swallowed after logging:
+ a lost match beats a broken scan.
+ """
+ try:
+ with transaction.atomic():
+ _record_alert_matches(
+ observation_id=observation_id,
+ team_id=team_id,
+ scanner_id=scanner_id,
+ model_output=model_output,
+ )
+ except Exception as e:
+ capture_exception(e, {"observation_id": str(observation_id), "phase": "vision_alert_match_hook"})
+ logger.exception("vision_alert.match_hook_failed", observation_id=str(observation_id))
+
+
+def selection_matches(model_output: dict[str, Any], selection: dict[str, Any]) -> bool:
+ """Python mirror of `apply_observation_predicate` for one in-memory model output.
+
+ Keeps the hot success path free of per-alert single-row queries. Semantics must
+ stay aligned with the queryset version in vision_actions.synthesis.
+ """
+ verdicts = selection.get("verdict")
+ if verdicts:
+ if isinstance(verdicts, str):
+ verdicts = [verdicts]
+ if model_output.get("verdict") not in verdicts:
+ return False
+
+ tags = selection.get("tags")
+ if tags:
+ carried = set(model_output.get("tags") or []) | set(model_output.get("tags_freeform") or [])
+ if not carried.intersection(tags):
+ return False
+
+ for key, opposite in (("min_score", False), ("max_score", True)):
+ bound = selection.get(key)
+ # Mirror apply_observation_predicate: non-numeric bounds (bool included) are ignored.
+ if not isinstance(bound, int | float) or isinstance(bound, bool):
+ continue
+ score = model_output.get("score")
+ if not isinstance(score, int | float) or isinstance(score, bool):
+ return False
+ if (score > bound) if opposite else (score < bound):
+ return False
+
+ return True
+
+
+def _record_alert_matches(
+ *,
+ observation_id: UUID,
+ team_id: int,
+ scanner_id: UUID,
+ model_output: dict[str, Any],
+) -> int:
+ alerts = list(
+ VisionAlertConfiguration.all_teams.filter(
+ team_id=team_id,
+ scanner_id=scanner_id,
+ kind=VisionAlertKind.MATCH,
+ enabled=True,
+ ).only("id", "selection")
+ )
+ if not alerts:
+ return 0
+
+ rows: list[VisionAlertMatch] = []
+ for alert in alerts:
+ selection = alert.selection or {}
+ if selection_has_predicate(selection) and not selection_matches(model_output, selection):
+ continue
+ rows.append(
+ VisionAlertMatch(
+ alert_id=alert.id,
+ observation_id=observation_id,
+ team_id=team_id,
+ )
+ )
+
+ if rows:
+ # ignore_conflicts: the unique (alert, observation) constraint makes a
+ # double insert structurally impossible even if the exactly-once guard slips.
+ VisionAlertMatch.all_teams.bulk_create(rows, ignore_conflicts=True)
+ return len(rows)
diff --git a/products/replay_vision/backend/temporal/vision_alerts/workflow.py b/products/replay_vision/backend/temporal/vision_alerts/workflow.py
index 5b9314f9a8fa..53441687bcc2 100644
--- a/products/replay_vision/backend/temporal/vision_alerts/workflow.py
+++ b/products/replay_vision/backend/temporal/vision_alerts/workflow.py
@@ -17,10 +17,12 @@ with workflow.unsafe.imports_passed_through():
CleanupAlertHistoryInput,
DiscoverDueAlertsInput,
DiscoverDueAlertsOutput,
+ DrainMatchesInput,
EvaluateAlertBatchInput,
EvaluateAlertBatchOutput,
cleanup_vision_alert_history_activity,
discover_due_vision_alerts_activity,
+ drain_vision_alert_matches_activity,
evaluate_vision_alert_batch_activity,
)
@@ -79,6 +81,18 @@ class VisionAlertCheckWorkflow(PostHogWorkflow):
output.alerts_resolved += result.alerts_resolved
output.alerts_errored += result.alerts_errored
+ # Patched: added after the workflow first shipped; pre-patch histories skip it.
+ if workflow.patched("vision-alert-match-drain-2026-08"):
+ try:
+ await workflow.execute_activity(
+ drain_vision_alert_matches_activity,
+ DrainMatchesInput(),
+ start_to_close_timeout=ACTIVITY_TIMEOUT,
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+ except ActivityError:
+ workflow.logger.warning("Match drain failed; alert cycle continues")
+
# Best-effort retention sweep; never fails the alert cycle.
try:
await workflow.execute_activity(
diff --git a/products/replay_vision/backend/tests/test_vision_alerts_match_outbox.py b/products/replay_vision/backend/tests/test_vision_alerts_match_outbox.py
new file mode 100644
index 000000000000..130b15af2860
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_vision_alerts_match_outbox.py
@@ -0,0 +1,274 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.utils import uuid7
+
+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_alert import (
+ VisionAlertConfiguration,
+ VisionAlertKind,
+ VisionAlertMatch,
+)
+from products.replay_vision.backend.temporal.activities.observation_state import (
+ mark_observation_failed_activity,
+ mark_observation_ineligible_activity,
+ mark_observation_succeeded_activity,
+)
+from products.replay_vision.backend.temporal.scanners.monitor import MonitorOutput
+from products.replay_vision.backend.temporal.types import (
+ MarkObservationFailedInputs,
+ MarkObservationIneligibleInputs,
+ MarkObservationSucceededInputs,
+ ScannerResult,
+)
+from products.replay_vision.backend.temporal.vision_alerts.activities import (
+ CleanupAlertHistoryInput,
+ DrainMatchesInput,
+ _cleanup_history,
+ _drain_matches,
+)
+from products.replay_vision.backend.temporal.vision_alerts.constants import MATCH_SUMMARY_LINES
+from products.replay_vision.backend.temporal.vision_alerts.match_hook import selection_matches
+from products.replay_vision.backend.tests.helpers import snapshot_for
+
+_ACTIVITIES = "products.replay_vision.backend.temporal.vision_alerts.activities"
+
+
+class TestVisionAlertMatchOutbox(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="Checkout monitor",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "did the user check out?"},
+ model=ScannerModel.GEMINI_3_7_FLASH,
+ )
+
+ def _make_match_alert(self, **overrides: Any) -> VisionAlertConfiguration:
+ fields: dict[str, Any] = {
+ "team": self.team,
+ "scanner": self.scanner,
+ "name": f"match-{uuid7()}",
+ "kind": VisionAlertKind.MATCH,
+ "selection": {"verdict": ["yes"]},
+ "first_enabled_at": timezone.now(),
+ }
+ fields.update(overrides)
+ return VisionAlertConfiguration.objects.for_team(self.team.id).create(**fields)
+
+ def _make_pending_observation(self) -> ReplayObservation:
+ return ReplayObservation.objects.create(
+ scanner=self.scanner,
+ team=self.team,
+ session_id=f"s-{uuid7()}",
+ status=ObservationStatus.RUNNING,
+ scanner_snapshot=snapshot_for(self.scanner),
+ triggered_by=ObservationTrigger.SCHEDULE,
+ )
+
+ def _succeed(self, observation: ReplayObservation, verdict: str = "yes") -> None:
+ result = ScannerResult(
+ model_output=MonitorOutput(
+ scanner_type=ScannerType.MONITOR,
+ verdict=verdict,
+ reasoning="checkout broke",
+ confidence=0.9,
+ )
+ )
+ with patch("products.replay_vision.backend.temporal.activities.observation_state.posthoganalytics"):
+ mark_observation_succeeded_activity(
+ MarkObservationSucceededInputs(
+ observation_id=observation.id, scanner_type=ScannerType.MONITOR, scanner_result=result
+ )
+ )
+
+ def _outbox_rows(self) -> list[VisionAlertMatch]:
+ return list(VisionAlertMatch.all_teams.filter(team_id=self.team.id))
+
+ def test_succeeded_observation_inserts_one_row_per_matching_alert(self) -> None:
+ matching = self._make_match_alert()
+ self._make_match_alert(name="second matcher", selection={})
+ self._make_match_alert(name="wrong verdict", selection={"verdict": ["no"]})
+ self._make_match_alert(name="disabled", enabled=False)
+
+ observation = self._make_pending_observation()
+ self._succeed(observation)
+
+ rows = self._outbox_rows()
+ alert_names = {VisionAlertConfiguration.all_teams.get(id=row.alert_id).name for row in rows}
+ assert matching.name in alert_names
+ assert "second matcher" in alert_names
+ assert len(rows) == 2
+ assert all(row.observation_id == observation.id and row.delivered_at is None for row in rows)
+
+ def test_retry_after_transition_inserts_nothing(self) -> None:
+ self._make_match_alert(selection={})
+ observation = self._make_pending_observation()
+ self._succeed(observation)
+ assert len(self._outbox_rows()) == 1
+ self._succeed(observation)
+ assert len(self._outbox_rows()) == 1
+
+ def test_failed_observation_inserts_nothing(self) -> None:
+ self._make_match_alert(name="catch all", selection={})
+
+ observation = self._make_pending_observation()
+ mark_observation_failed_activity(
+ MarkObservationFailedInputs(
+ observation_id=observation.id, scanner_type=ScannerType.MONITOR, error_reason="provider_error:boom"
+ )
+ )
+
+ assert self._outbox_rows() == []
+
+ def test_ineligible_observation_inserts_nothing(self) -> None:
+ self._make_match_alert(selection={})
+ observation = self._make_pending_observation()
+ mark_observation_ineligible_activity(
+ MarkObservationIneligibleInputs(
+ observation_id=observation.id, scanner_type=ScannerType.MONITOR, error_reason="no_recording:none"
+ )
+ )
+ assert self._outbox_rows() == []
+
+ def _drain(self, *, delivered: bool = True, produce_side_effect: Any = None):
+ produce_result = MagicMock()
+ with (
+ patch(
+ f"{_ACTIVITIES}.produce_alert_internal_event",
+ return_value=produce_result,
+ side_effect=produce_side_effect,
+ ) as produce,
+ patch(f"{_ACTIVITIES}.flush_alert_internal_events"),
+ patch(f"{_ACTIVITIES}.alert_internal_event_delivered", return_value=delivered),
+ ):
+ output = _drain_matches(DrainMatchesInput())
+ return output, produce
+
+ def test_drain_bundles_and_stamps_only_after_ack(self) -> None:
+ alert = self._make_match_alert(selection={})
+ for _ in range(3):
+ self._succeed(self._make_pending_observation())
+
+ output, produce = self._drain(delivered=True)
+ assert output.alerts_notified == 1
+ assert output.matches_delivered == 3
+ assert produce.call_count == 1
+ props = produce.call_args.kwargs["properties"]
+ assert props["matched_count"] == 3
+ assert len(props["observation_ids"]) == 3
+ assert props["summary"].count("verdict=yes") == 3
+ assert produce.call_args.kwargs["uuid"] is not None
+ assert not VisionAlertMatch.all_teams.filter(alert_id=alert.id, delivered_at__isnull=True).exists()
+
+ # Nothing pending -> next drain emits nothing.
+ output, produce = self._drain(delivered=True)
+ assert produce.call_count == 0
+
+ def test_unacked_bundle_stays_pending_and_retries(self) -> None:
+ alert = self._make_match_alert(selection={})
+ self._succeed(self._make_pending_observation())
+
+ output, _ = self._drain(delivered=False)
+ assert output.alerts_notified == 0
+ assert VisionAlertMatch.all_teams.filter(alert_id=alert.id, delivered_at__isnull=True).count() == 1
+
+ output, _ = self._drain(delivered=True)
+ assert output.alerts_notified == 1
+
+ def test_mid_drain_insert_is_not_stamped(self) -> None:
+ alert = self._make_match_alert(selection={})
+ self._succeed(self._make_pending_observation())
+
+ late_observation = self._make_pending_observation()
+
+ def insert_late_row(**kwargs: Any) -> MagicMock:
+ # A row landing between the drain read and the stamp must survive it.
+ self._succeed(late_observation)
+ return MagicMock()
+
+ output, _ = self._drain(delivered=True, produce_side_effect=insert_late_row)
+ assert output.matches_delivered == 1
+ assert VisionAlertMatch.all_teams.filter(alert_id=alert.id, delivered_at__isnull=True).count() == 1
+
+ def test_drain_skips_disabled_and_holds_snoozed(self) -> None:
+ disabled = self._make_match_alert(name="disabled later", selection={})
+ snoozed = self._make_match_alert(name="snoozed", selection={})
+ for _ in range(2):
+ self._succeed(self._make_pending_observation())
+ VisionAlertConfiguration.all_teams.filter(id=disabled.id).update(enabled=False)
+ VisionAlertConfiguration.all_teams.filter(id=snoozed.id).update(
+ snooze_until=datetime.now(UTC) + timedelta(hours=1)
+ )
+
+ output, produce = self._drain(delivered=True)
+ assert output.alerts_notified == 0
+ assert produce.call_count == 0
+ assert VisionAlertMatch.all_teams.filter(delivered_at__isnull=True).count() == 4
+
+ def test_summary_caps_lines_but_stamps_all_rows(self) -> None:
+ alert = self._make_match_alert(selection={})
+ for _ in range(MATCH_SUMMARY_LINES + 2):
+ self._succeed(self._make_pending_observation())
+
+ output, produce = self._drain(delivered=True)
+ assert output.matches_delivered == MATCH_SUMMARY_LINES + 2
+ props = produce.call_args.kwargs["properties"]
+ assert f"and 2 more" in props["summary"]
+ assert not VisionAlertMatch.all_teams.filter(alert_id=alert.id, delivered_at__isnull=True).exists()
+
+ @parameterized.expand(
+ [
+ ("min_score_zero_matches_zero", {"min_score": 0}, {"score": 0.0}, True),
+ ("min_score_zero_needs_a_score", {"min_score": 0}, {}, False),
+ ("max_score_excludes_above", {"max_score": 2}, {"score": 2.5}, False),
+ ("legacy_single_verdict_string", {"verdict": "yes"}, {"verdict": "yes"}, True),
+ ("verdict_list_excludes_other", {"verdict": ["no"]}, {"verdict": "yes"}, False),
+ ("freeform_tag_counts", {"tags": ["checkout"]}, {"tags_freeform": ["checkout"]}, True),
+ ]
+ )
+ def test_selection_matches_semantics(self, _name: str, selection: dict, model_output: dict, expected: bool) -> None:
+ assert selection_matches(model_output, selection) is expected
+
+ def test_backlogged_alert_does_not_starve_another_alerts_bundle(self) -> None:
+ loud = self._make_match_alert(name="loud", selection={"verdict": ["yes"]})
+ quiet = self._make_match_alert(name="quiet", selection={"verdict": ["no"]})
+ for _ in range(3):
+ self._succeed(self._make_pending_observation(), verdict="yes")
+ self._succeed(self._make_pending_observation(), verdict="no")
+
+ with patch(f"{_ACTIVITIES}.MAX_MATCHES_PER_BUNDLE", 2):
+ output, produce = self._drain(delivered=True)
+
+ assert output.alerts_notified == 2
+ assert output.matches_delivered == 3
+ assert produce.call_count == 2
+ assert VisionAlertMatch.all_teams.filter(alert_id=loud.id, delivered_at__isnull=True).count() == 1
+ assert not VisionAlertMatch.all_teams.filter(alert_id=quiet.id, delivered_at__isnull=True).exists()
+
+ def test_cleanup_reaps_delivered_and_stale_rows(self) -> None:
+ self._make_match_alert(selection={})
+ self._succeed(self._make_pending_observation())
+ self._succeed(self._make_pending_observation())
+ rows = VisionAlertMatch.all_teams.filter(team_id=self.team.id)
+ old = timezone.now() - timedelta(days=40)
+ first, second = list(rows)
+ VisionAlertMatch.all_teams.filter(id=first.id).update(delivered_at=old, created_at=old)
+ VisionAlertMatch.all_teams.filter(id=second.id).update(created_at=old)
+
+ deleted = _cleanup_history(CleanupAlertHistoryInput())
+ assert deleted == 2
+ assert not VisionAlertMatch.all_teams.filter(team_id=self.team.id).exists()