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): evaluate metric alerts on a temporal check schedule (#88404)

Tue Haulundc2b2446badf9
diff --git a/nodejs/src/cdp/managed-alert-events.ts b/nodejs/src/cdp/managed-alert-events.ts
index 6875776a9c1e..705505b4b8e5 100644
--- a/nodejs/src/cdp/managed-alert-events.ts
+++ b/nodejs/src/cdp/managed-alert-events.ts
@@ -1,6 +1,6 @@
// Mirror of `posthog/cdp/internal_events.py`. The managed-alert event boundary and the legacy
// insight-alert exemption must match the Python side exactly, so keep the two in sync.
-export const MANAGED_ALERT_EVENT_PATTERN = /^\$[a-z0-9_]+_alert_(firing|resolved|errored|auto_disabled)$/
+export const MANAGED_ALERT_EVENT_PATTERN = /^\$[a-z0-9_]+_alert_(firing|resolved|errored|auto_disabled|match)$/
export const LEGACY_INSIGHT_ALERT_EVENT = '$insight_alert_firing'
/** Return whether an internal event is reserved for an alert-owned destination. */
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 4a02e7bccd67..add425c81a48 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -109,6 +109,7 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep import (
)
from products.replay_vision.backend.temporal.read_meter import create_replay_vision_read_meter_schedule
from products.replay_vision.backend.temporal.reconciler import create_replay_vision_reconciler_schedule
+from products.replay_vision.backend.temporal.vision_alerts.schedule import create_vision_alert_check_schedule
from products.review_hog.backend.temporal.outcomes_schedule import create_review_hog_finding_outcomes_schedule
from products.signals.backend.emission.conversations_schedule import create_conversations_signals_coordinator_schedule
from products.signals.backend.temporal.agentic.schedule import create_signals_scout_coordinator_schedule
@@ -904,6 +905,7 @@ schedules = [
create_calendar_sync_coordinator_schedule,
create_replay_vision_reconciler_schedule,
create_replay_vision_estimates_schedule,
+ create_vision_alert_check_schedule,
create_replay_vision_read_meter_schedule,
create_github_job_logs_coordinator_schedule,
create_review_hog_finding_outcomes_schedule,
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
index f6a55dc0a9bd..40cae6b2ee7b 100644
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
@@ -34,7 +34,7 @@
e.`$window_id` AS `$window_id`,
if(equals(e.event, 'user signed up'), 1, 0) AS step_0,
if(equals(e.event, 'user did things'), 1, 0) AS step_1,
- ([replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', '')] AS value) AS prop_basic,
+ ([e__person.properties___fish] AS value) AS prop_basic,
prop_basic AS prop
FROM events AS e
LEFT OUTER JOIN
@@ -44,6 +44,16 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0)), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -111,7 +121,17 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
GROUP BY breakdown
@@ -168,8 +188,8 @@
e.uuid AS uuid,
e.`$session_id` AS `$session_id`,
e.`$window_id` AS `$window_id`,
- if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_0,
- if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_1
+ if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_0,
+ if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_1
FROM events AS e
LEFT OUTER JOIN
(SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
@@ -178,6 +198,16 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up'))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -294,7 +324,24 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
@@ -326,7 +373,24 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
diff --git a/products/replay_vision/backend/alert_destinations.py b/products/replay_vision/backend/alert_destinations.py
index e9148a172435..1d1e1bea9ee3 100644
--- a/products/replay_vision/backend/alert_destinations.py
+++ b/products/replay_vision/backend/alert_destinations.py
@@ -156,6 +156,12 @@ MATCH_EVENT_KINDS: tuple[EventKind, ...] = ("match",)
VISION_ALERT_EVENT_IDS = tuple(spec.event_id for spec in EVENT_KIND_CONFIG.values())
VISION_ALERT_SLACK_CONTEXT_ELEMENTS = (
- "Scanner: {event.properties.scanner_name}",
+ "Scanner: {event.properties.scanner_name_mrkdwn}",
"Project: <{project.url}|{project.name}>",
)
+
+
+def escape_slack_mrkdwn(text: str) -> str:
+ """User-editable values interpolated into Slack mrkdwn must not carry control
+ syntax like <!channel> or <url|label>; webhooks keep the raw value."""
+ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index da51f3439016..e0939e0aa225 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -62,6 +62,12 @@ from products.replay_vision.backend.temporal.vision_actions import (
update_vision_action_run_activity,
validate_vision_action_activity,
)
+from products.replay_vision.backend.temporal.vision_alerts import (
+ VisionAlertCheckWorkflow,
+ cleanup_vision_alert_history_activity,
+ discover_due_vision_alerts_activity,
+ evaluate_vision_alert_batch_activity,
+)
from products.replay_vision.backend.temporal.workflow import ApplyScannerWorkflow
WORKFLOWS = [
@@ -74,8 +80,12 @@ WORKFLOWS = [
ReplayVisionGeminiCleanupSweepWorkflow,
SweepScannerWorkflow,
ProcessVisionActionWorkflow,
+ VisionAlertCheckWorkflow,
]
ACTIVITIES: list[Callable[..., Any]] = [
+ discover_due_vision_alerts_activity,
+ evaluate_vision_alert_batch_activity,
+ cleanup_vision_alert_history_activity,
create_observation_activity,
mark_observation_running_activity,
mark_observation_failed_activity,
diff --git a/products/replay_vision/backend/temporal/vision_alerts/__init__.py b/products/replay_vision/backend/temporal/vision_alerts/__init__.py
new file mode 100644
index 000000000000..702227684458
--- /dev/null
+++ b/products/replay_vision/backend/temporal/vision_alerts/__init__.py
@@ -0,0 +1,19 @@
+from products.replay_vision.backend.temporal.vision_alerts.activities import (
+ cleanup_vision_alert_history_activity,
+ discover_due_vision_alerts_activity,
+ evaluate_vision_alert_batch_activity,
+)
+from products.replay_vision.backend.temporal.vision_alerts.workflow import VisionAlertCheckWorkflow
+
+WORKFLOWS = [VisionAlertCheckWorkflow]
+ACTIVITIES = [
+ discover_due_vision_alerts_activity,
+ evaluate_vision_alert_batch_activity,
+ cleanup_vision_alert_history_activity,
+]
+
+__all__ = [
+ "ACTIVITIES",
+ "WORKFLOWS",
+ "VisionAlertCheckWorkflow",
+]
diff --git a/products/replay_vision/backend/temporal/vision_alerts/activities.py b/products/replay_vision/backend/temporal/vision_alerts/activities.py
new file mode 100644
index 000000000000..34af24dee36a
--- /dev/null
+++ b/products/replay_vision/backend/temporal/vision_alerts/activities.py
@@ -0,0 +1,603 @@
+"""Activities for the replay vision alert check workflow.
+
+Phase layout copies the Logs alert engine: evaluate (no side effects) -> dispatch
+(produce the notification, buffered) -> resolve deliveries (flush + ack, roll back
+outcomes whose notification never reached the broker) -> save (one transaction).
+"""
+
+import dataclasses
+from datetime import UTC, datetime, timedelta
+from itertools import batched
+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.fields.json import KeyTextTransform
+from django.db.models.functions import Cast
+
+import structlog
+import temporalio
+from pydantic import BaseModel
+
+from posthog.dataclasses import frozen
+from posthog.exceptions_capture import capture_exception
+from posthog.sync import database_sync_to_async
+
+from products.alerts.backend.destinations import (
+ ProduceResult,
+ alert_internal_event_delivered,
+ flush_alert_internal_events,
+ produce_alert_internal_event,
+)
+from products.replay_vision.backend.alert_destinations import escape_slack_mrkdwn
+from products.replay_vision.backend.alert_state_machine import (
+ AlertCheckOutcome,
+ AlertState,
+ CheckResult,
+ NotificationAction,
+ apply_outcome,
+ evaluate_alert_check,
+)
+from products.replay_vision.backend.alert_utils import (
+ advance_next_check_at,
+ compute_shard_offset_seconds,
+ due_alerts_q,
+ next_allowed_check_at,
+)
+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.models.vision_alert import (
+ DELIVERED_MATCH_RETENTION_DAYS,
+ EVENT_RETENTION_DAYS,
+ STALE_MATCH_RETENTION_DAYS,
+ VisionAlertConfiguration,
+ VisionAlertDirection,
+ VisionAlertEvent,
+ VisionAlertKind,
+ VisionAlertMatch,
+ VisionAlertMetric,
+)
+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,
+ MAX_ALERTS_PER_BATCH,
+ MAX_ALERTS_PER_TICK,
+ NOTIFICATION_FLUSH_TIMEOUT_SECONDS,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+class CheckVisionAlertsInput(BaseModel):
+ pass
+
+
+class CheckVisionAlertsOutput(BaseModel):
+ alerts_checked: int = 0
+ alerts_fired: int = 0
+ alerts_resolved: int = 0
+ alerts_errored: int = 0
+
+
+class DiscoverDueAlertsInput(BaseModel):
+ pass
+
+
+class DiscoverDueAlertsOutput(BaseModel):
+ batches: list[list[str]] = []
+
+
+class EvaluateAlertBatchInput(BaseModel):
+ alert_ids: list[str]
+
+
+class EvaluateAlertBatchOutput(BaseModel):
+ alerts_checked: int = 0
+ alerts_fired: int = 0
+ alerts_resolved: int = 0
+ alerts_errored: int = 0
+
+
+class CleanupAlertHistoryInput(BaseModel):
+ pass
+
+
+@frozen
+class _AlertEvaluation:
+ """Phase 1 output: per-alert state-machine result. No Kafka, no writes yet."""
+
+ alert: VisionAlertConfiguration
+ outcome: AlertCheckOutcome
+ check_result: CheckResult
+ state_before: str
+
+
+@frozen
+class _DispatchedAlert:
+ """Phase 2 output: notification dispatched (buffered), ready for the save.
+
+ `notification_failed` drives state rollback: the committed outcome reverts to the
+ pre-check state so the next cycle re-evaluates and re-tries the notification. The
+ failure counter may heal downward but never advance, so the 0 -> 1 error-notify
+ edge is not silently consumed.
+ """
+
+ evaluation: _AlertEvaluation
+ notification_failed: bool
+ produce_result: ProduceResult | None = None
+ # Disabled, snoozed, or inside quiet hours at dispatch time: no notification, and the
+ # alert is excluded from the save so a concurrent control-plane change is not clobbered.
+ suppressed: bool = False
+
+ @property
+ def committed_outcome(self) -> AlertCheckOutcome:
+ if self.notification_failed:
+ return dataclasses.replace(
+ self.evaluation.outcome,
+ new_state=AlertState(self.evaluation.alert.state),
+ consecutive_failures=min(
+ self.evaluation.alert.consecutive_failures,
+ self.evaluation.outcome.consecutive_failures,
+ ),
+ )
+ return self.evaluation.outcome
+
+
+@track_activity()
+async def discover_due_vision_alerts_activity(inputs: DiscoverDueAlertsInput) -> DiscoverDueAlertsOutput:
+ return await database_sync_to_async(_discover_due, thread_sensitive=False)(inputs)
+
+
+def _discover_due(inputs: DiscoverDueAlertsInput) -> DiscoverDueAlertsOutput:
+ now = datetime.now(UTC)
+ # Oldest due first, capped so the workflow result stays far below Temporal's payload
+ # limit; the overflow keeps its next_check_at and is picked up next tick.
+ due_ids = list(
+ VisionAlertConfiguration.all_teams.filter(
+ due_alerts_q(now, broken_state=AlertState.BROKEN.value, snoozed_state=AlertState.SNOOZED.value),
+ kind=VisionAlertKind.METRIC,
+ )
+ .order_by("next_check_at", "id")
+ .values_list("id", flat=True)[: MAX_ALERTS_PER_TICK + 1]
+ )
+ if len(due_ids) > MAX_ALERTS_PER_TICK:
+ logger.warning("vision_alert.discovery_truncated", cap=MAX_ALERTS_PER_TICK)
+ due_ids = due_ids[:MAX_ALERTS_PER_TICK]
+ batches = [[str(alert_id) for alert_id in chunk] for chunk in batched(due_ids, MAX_ALERTS_PER_BATCH, strict=False)]
+ return DiscoverDueAlertsOutput(batches=batches)
+
+
+@track_activity()
+async def evaluate_vision_alert_batch_activity(inputs: EvaluateAlertBatchInput) -> EvaluateAlertBatchOutput:
+ return await database_sync_to_async(_evaluate_batch, thread_sensitive=False)(inputs)
+
+
+def _evaluate_batch(inputs: EvaluateAlertBatchInput) -> EvaluateAlertBatchOutput:
+ now = datetime.now(UTC)
+ alerts = list(
+ VisionAlertConfiguration.all_teams.filter(id__in=inputs.alert_ids, kind=VisionAlertKind.METRIC)
+ .select_related("team", "scanner")
+ .order_by("id")
+ )
+
+ dispatched: list[_DispatchedAlert] = []
+ for alert in alerts:
+ evaluation = _evaluate_single_alert(alert, now)
+ dispatched.append(_dispatch_for_alert(evaluation, now))
+
+ dispatched = _resolve_notification_deliveries(dispatched)
+ to_save = [d for d in dispatched if not d.suppressed]
+ saved = _save_outcomes(to_save, now)
+
+ output = EvaluateAlertBatchOutput()
+ for d in saved:
+ output.alerts_checked += 1
+ committed = d.committed_outcome
+ if d.evaluation.outcome.error_message is not None:
+ output.alerts_errored += 1
+ elif not d.notification_failed and committed.notification == NotificationAction.FIRE:
+ output.alerts_fired += 1
+ elif not d.notification_failed and committed.notification == NotificationAction.RESOLVE:
+ output.alerts_resolved += 1
+ return output
+
+
+def _observation_window_qs(
+ alert: VisionAlertConfiguration, window_start: datetime, window_end: datetime
+) -> QuerySet[ReplayObservation]:
+ selection: dict[str, Any] = alert.selection or {}
+ queryset = ReplayObservation.objects.filter(
+ team_id=alert.team_id,
+ scanner_id=alert.scanner_id,
+ status=ObservationStatus.SUCCEEDED,
+ completed_at__gte=window_start,
+ completed_at__lt=window_end,
+ )
+ return apply_observation_predicate(queryset, selection)
+
+
+def _evaluate_single_alert(alert: VisionAlertConfiguration, now: datetime) -> _AlertEvaluation:
+ """Phase 1: run the observation window query, apply the state machine."""
+ window_start = now - timedelta(days=alert.window_days)
+
+ check_result: CheckResult
+ try:
+ queryset = _observation_window_qs(alert, window_start, now)
+ if alert.metric == VisionAlertMetric.AVG_SCORE:
+ # Cast the JSONB score to float and average it; observations without a
+ # score (non-scorers) become NULL and fall out of the average.
+ metric_value = queryset.annotate(
+ _score=Cast(
+ KeyTextTransform("score", KeyTextTransform("model_output", "scanner_result")),
+ output_field=FloatField(),
+ )
+ ).aggregate(avg=Avg("_score"))["avg"]
+ else:
+ metric_value = float(queryset.count())
+
+ if metric_value is None:
+ # An empty window has no average; neither direction can breach.
+ check_result = CheckResult(metric_value=None, threshold_breached=False, is_inconclusive=True)
+ else:
+ threshold = float(alert.threshold or 0)
+ if alert.direction == VisionAlertDirection.BELOW:
+ breached = metric_value <= threshold
+ else:
+ breached = metric_value >= threshold
+ check_result = CheckResult(metric_value=metric_value, threshold_breached=breached)
+ except Exception as e:
+ capture_exception(e, {"alert_id": str(alert.id)})
+ logger.warning("vision_alert.check_query_failed", alert_id=str(alert.id), team_id=alert.team_id, error=str(e))
+ check_result = CheckResult(
+ metric_value=None,
+ threshold_breached=False,
+ error_message="The alert check query failed.",
+ is_transient_error=isinstance(e, OperationalError),
+ )
+
+ outcome = evaluate_alert_check(alert.to_snapshot(), check_result, now)
+ return _AlertEvaluation(alert=alert, outcome=outcome, check_result=check_result, state_before=alert.state)
+
+
+def _dispatch_for_alert(evaluation: _AlertEvaluation, now: datetime) -> _DispatchedAlert:
+ """Phase 2: re-check current state, defer quiet-hours alerts, or dispatch.
+
+ The evaluation ran on a snapshot from discovery; a user may have disabled or snoozed
+ the alert since. Re-read those fields fresh and suppress instead of paging. Any lock
+ closes before the produce: nothing may hold an alert row lock across Kafka work, or
+ every observation-completion insert against that alert's FK stalls.
+ """
+ current = (
+ VisionAlertConfiguration.all_teams.filter(id=evaluation.alert.id)
+ .values("enabled", "snooze_until", "schedule_restriction")
+ .first()
+ )
+ if (
+ current is None
+ or not current["enabled"]
+ or (current["snooze_until"] is not None and current["snooze_until"] > now)
+ ):
+ return _DispatchedAlert(evaluation=evaluation, notification_failed=False, suppressed=True)
+
+ if current["schedule_restriction"]:
+ with transaction.atomic():
+ current_alert = (
+ VisionAlertConfiguration.all_teams.select_for_update(of=("self",))
+ .select_related("team")
+ .get(id=evaluation.alert.id)
+ )
+ try:
+ next_check_at = next_allowed_check_at(
+ now,
+ team_timezone=current_alert.team.timezone,
+ schedule_restriction=current_alert.schedule_restriction,
+ )
+ except Exception as e:
+ logger.exception(
+ "vision_alert.invalid_quiet_hours",
+ alert_id=str(current_alert.id),
+ team_id=current_alert.team_id,
+ error=str(e),
+ )
+ return _DispatchedAlert(evaluation=evaluation, notification_failed=False, suppressed=True)
+ if next_check_at > now:
+ current_alert.next_check_at = next_check_at
+ current_alert.save(update_fields=["next_check_at", "updated_at"])
+ return _DispatchedAlert(evaluation=evaluation, notification_failed=False, suppressed=True)
+
+ produce_result = _dispatch_notification(evaluation, now)
+ enqueue_failed = evaluation.outcome.notification != NotificationAction.NONE and produce_result is None
+ return _DispatchedAlert(evaluation=evaluation, notification_failed=enqueue_failed, produce_result=produce_result)
+
+
+def _notification_uuid(evaluation: _AlertEvaluation) -> str:
+ """Deterministic per check cycle, so an activity retry that re-produces the same
+ notification dedupes at ingestion while the next cycle gets a fresh id. Anchored on
+ pre-advance columns that only move when a cycle saves, so a retry crossing a
+ wall-clock boundary cannot mint a second uuid."""
+ alert = evaluation.alert
+ anchor_dt = alert.next_check_at or alert.last_checked_at or alert.created_at
+ action = evaluation.outcome.notification.value
+ return str(uuid5(NAMESPACE_URL, f"vision-alert:{alert.id}:{action}:{anchor_dt.isoformat()}"))
+
+
+def _dispatch_notification(evaluation: _AlertEvaluation, now: datetime) -> ProduceResult | None:
+ action = evaluation.outcome.notification
+ if action == NotificationAction.NONE:
+ return None
+
+ alert = evaluation.alert
+ event_uuid = _notification_uuid(evaluation)
+ log = logger.bind(alert_id=str(alert.id), alert_name=alert.name, team_id=alert.team_id)
+ if action == NotificationAction.FIRE:
+ result = _emit_alert_event(alert, "$replay_vision_alert_firing", evaluation.check_result, now, event_uuid)
+ log.info("vision_alert.fired", metric_value=evaluation.check_result.metric_value, enqueued=result is not None)
+ elif action == NotificationAction.RESOLVE:
+ result = _emit_alert_event(alert, "$replay_vision_alert_resolved", evaluation.check_result, now, event_uuid)
+ log.info("vision_alert.resolved", enqueued=result is not None)
+ elif action == NotificationAction.ERROR:
+ result = _emit_failure_event(
+ alert, "$replay_vision_alert_errored", evaluation.outcome, now, event_uuid, message_key="error_message"
+ )
+ log.info("vision_alert.errored", consecutive_failures=evaluation.outcome.consecutive_failures)
+ elif action == NotificationAction.BROKEN:
+ result = _emit_failure_event(
+ alert,
+ "$replay_vision_alert_auto_disabled",
+ evaluation.outcome,
+ now,
+ event_uuid,
+ message_key="last_error_message",
+ )
+ log.warning("vision_alert.broken", consecutive_failures=evaluation.outcome.consecutive_failures)
+ else:
+ raise ValueError(f"Unhandled NotificationAction: {action!r}")
+ return result
+
+
+def _resolve_notification_deliveries(dispatched: list[_DispatchedAlert]) -> list[_DispatchedAlert]:
+ """Phase 2.5: flush the producer and fold delivery failures into `notification_failed`.
+
+ Flush failures are swallowed: per-result checks classify each alert individually,
+ and a save with rolled-back state beats no save at all.
+ """
+ if all(d.produce_result is None for d in dispatched):
+ return dispatched
+
+ flush_alert_internal_events(NOTIFICATION_FLUSH_TIMEOUT_SECONDS)
+
+ resolved: list[_DispatchedAlert] = []
+ for d in dispatched:
+ if d.produce_result is None:
+ resolved.append(d)
+ elif alert_internal_event_delivered(
+ d.produce_result,
+ team_id=d.evaluation.alert.team_id,
+ alert_id=str(d.evaluation.alert.id),
+ event_name=d.evaluation.outcome.notification.value,
+ ):
+ resolved.append(d)
+ else:
+ resolved.append(dataclasses.replace(d, notification_failed=True))
+ return resolved
+
+
+def _stage_alert_for_save(dispatched: _DispatchedAlert, now: datetime) -> tuple[list[str], VisionAlertEvent]:
+ """Mutate the in-memory alert for bulk_update; return update fields and the CHECK row.
+
+ Unlike Logs, a CHECK event row is written on every check: it is what feeds the
+ N-of-M window (`get_recent_breaches`) and the history chart, and vision volumes
+ make the rows cheap.
+ """
+ evaluation = dispatched.evaluation
+ alert = evaluation.alert
+ committed = dispatched.committed_outcome
+
+ update_fields = apply_outcome(alert, committed)
+ alert.last_checked_at = now
+ # bulk_update does not apply auto_now; stamp updated_at explicitly.
+ alert.updated_at = now
+ next_check_at = advance_next_check_at(
+ alert.next_check_at,
+ alert.check_interval_minutes,
+ now,
+ shard_offset_seconds=compute_shard_offset_seconds(alert.id, alert.check_interval_minutes),
+ )
+ try:
+ alert.next_check_at = next_allowed_check_at(
+ next_check_at,
+ team_timezone=alert.team.timezone,
+ schedule_restriction=alert.schedule_restriction,
+ )
+ except Exception as e:
+ logger.exception(
+ "vision_alert.invalid_quiet_hours_at_save", alert_id=str(alert.id), team_id=alert.team_id, error=str(e)
+ )
+ alert.next_check_at = next_check_at
+ update_fields.extend(["last_checked_at", "next_check_at", "updated_at"])
+
+ if (
+ not dispatched.notification_failed
+ and evaluation.outcome.notification != NotificationAction.NONE
+ and evaluation.outcome.update_last_notified_at
+ ):
+ alert.last_notified_at = now
+ update_fields.append("last_notified_at")
+
+ event = VisionAlertEvent(
+ alert=alert,
+ metric_value=evaluation.check_result.metric_value,
+ threshold_breached=evaluation.check_result.threshold_breached,
+ state_before=evaluation.state_before,
+ state_after=committed.new_state.value,
+ error_message=evaluation.outcome.error_message,
+ )
+ return update_fields, event
+
+
+_UPDATE_FIELDS: list[str] = [
+ "state",
+ "consecutive_failures",
+ "last_checked_at",
+ "next_check_at",
+ "last_notified_at",
+ "updated_at",
+]
+
+
+def _save_outcomes(dispatched: list[_DispatchedAlert], now: datetime) -> list[_DispatchedAlert]:
+ """Phase 3: persist outcomes via one bulk_create + one bulk_update; on
+ IntegrityError, fall back to per-alert saves with the already-staged data so
+ `next_check_at` is not advanced twice."""
+ if not dispatched:
+ return []
+
+ staged: list[tuple[_DispatchedAlert, list[str], VisionAlertEvent]] = []
+ try:
+ with transaction.atomic():
+ # Ordered locking avoids deadlock with concurrent batches; the fresh re-read
+ # drops alerts a user disabled, snoozed, or reset during the dispatch window,
+ # so the control-plane transition wins over the stale evaluated state.
+ current_rows = {
+ row["id"]: row
+ for row in VisionAlertConfiguration.all_teams.select_for_update()
+ .filter(id__in=[d.evaluation.alert.id for d in dispatched])
+ .order_by("id")
+ .values("id", "enabled", "state", "schedule_restriction")
+ }
+ for d in dispatched:
+ current = current_rows.get(d.evaluation.alert.id)
+ if current is None or not current["enabled"] or current["state"] != d.evaluation.state_before:
+ logger.info(
+ "vision_alert.save_skipped_concurrent_transition",
+ alert_id=str(d.evaluation.alert.id),
+ state_before=d.evaluation.state_before,
+ current_state=current["state"] if current else None,
+ )
+ continue
+ d.evaluation.alert.schedule_restriction = current["schedule_restriction"]
+ update_fields, event = _stage_alert_for_save(d, now)
+ staged.append((d, update_fields, event))
+
+ VisionAlertEvent.objects.bulk_create([event for _, _, event in staged])
+ VisionAlertConfiguration.all_teams.bulk_update(
+ [d.evaluation.alert for d, _, _ in staged], fields=_UPDATE_FIELDS
+ )
+ return [d for d, _, _ in staged]
+ except IntegrityError as e:
+ logger.warning("vision_alert.bulk_save_integrity_error", error=str(e), batch_size=len(dispatched))
+ capture_exception(e, {"batch_size": len(dispatched), "fallback": "per_alert"})
+
+ saved: list[_DispatchedAlert] = []
+ for d, update_fields, event in staged:
+ try:
+ with transaction.atomic():
+ event.save()
+ d.evaluation.alert.save(update_fields=update_fields)
+ saved.append(d)
+ except Exception as e:
+ logger.exception("vision_alert.per_alert_save_failed", alert_id=str(d.evaluation.alert.id))
+ capture_exception(e, {"alert_id": str(d.evaluation.alert.id), "phase": "per_alert_fallback"})
+ return saved
+
+
+def _metric_label(alert: VisionAlertConfiguration) -> str:
+ return "average score" if alert.metric == VisionAlertMetric.AVG_SCORE else "matching observations"
+
+
+def _window_label(alert: VisionAlertConfiguration) -> str:
+ return "24 hours" if alert.window_days == 1 else f"{alert.window_days} days"
+
+
+def _direction_label(alert: VisionAlertConfiguration) -> str:
+ return "at or below" if alert.direction == VisionAlertDirection.BELOW else "at or above"
+
+
+def _base_properties(alert: VisionAlertConfiguration, now: datetime) -> dict:
+ return {
+ "alert_id": str(alert.id),
+ "alert_name": alert.name,
+ "team_id": alert.team_id,
+ "scanner_id": str(alert.scanner_id),
+ "scanner_name": alert.scanner.name,
+ "scanner_name_mrkdwn": escape_slack_mrkdwn(alert.scanner.name),
+ "triggered_at": now.isoformat(),
+ }
+
+
+def _emit_alert_event(
+ alert: VisionAlertConfiguration, event_name: str, check_result: CheckResult, now: datetime, event_uuid: str
+) -> ProduceResult | None:
+ properties = {
+ **_base_properties(alert, now),
+ "metric": alert.metric,
+ "metric_label": _metric_label(alert),
+ "metric_value": check_result.metric_value,
+ "threshold": alert.threshold,
+ "direction": _direction_label(alert),
+ "window_days": alert.window_days,
+ "window_label": _window_label(alert),
+ }
+ return produce_alert_internal_event(
+ team_id=alert.team_id, event_name=event_name, properties=properties, timestamp=now, uuid=event_uuid
+ )
+
+
+def _emit_failure_event(
+ alert: VisionAlertConfiguration,
+ event_name: str,
+ outcome: AlertCheckOutcome,
+ now: datetime,
+ event_uuid: str,
+ *,
+ message_key: str,
+) -> ProduceResult | None:
+ properties = {
+ **_base_properties(alert, now),
+ "consecutive_failures": outcome.consecutive_failures,
+ message_key: outcome.error_message or "",
+ }
+ return produce_alert_internal_event(
+ team_id=alert.team_id, event_name=event_name, properties=properties, timestamp=now, uuid=event_uuid
+ )
+
+
+@track_activity()
+async def cleanup_vision_alert_history_activity(inputs: CleanupAlertHistoryInput) -> int:
+ return await database_sync_to_async(_cleanup_history, thread_sensitive=False)(inputs)
+
+
+def _cleanup_history(inputs: CleanupAlertHistoryInput) -> int:
+ """Bounded retention sweep, one small batch per tick: old check-history rows,
+ delivered outbox rows past retention, and stale undelivered outbox rows
+ (alerts disabled or deleted between insert and drain)."""
+ now = datetime.now(UTC)
+ deleted = 0
+
+ event_ids = list(
+ VisionAlertEvent.objects.filter(created_at__lt=now - timedelta(days=EVENT_RETENTION_DAYS)).values_list(
+ "id", flat=True
+ )[:CLEANUP_BATCH_SIZE]
+ )
+ if event_ids:
+ deleted += VisionAlertEvent.objects.filter(id__in=event_ids).delete()[0]
+
+ delivered_ids = list(
+ VisionAlertMatch.all_teams.filter(
+ delivered_at__lt=now - timedelta(days=DELIVERED_MATCH_RETENTION_DAYS)
+ ).values_list("id", flat=True)[:CLEANUP_BATCH_SIZE]
+ )
+ stale_ids = list(
+ VisionAlertMatch.all_teams.filter(
+ delivered_at__isnull=True, created_at__lt=now - timedelta(days=STALE_MATCH_RETENTION_DAYS)
+ ).values_list("id", flat=True)[:CLEANUP_BATCH_SIZE]
+ )
+ match_ids = delivered_ids + stale_ids
+ if match_ids:
+ deleted += VisionAlertMatch.all_teams.filter(id__in=match_ids).delete()[0]
+
+ return deleted
diff --git a/products/replay_vision/backend/temporal/vision_alerts/constants.py b/products/replay_vision/backend/temporal/vision_alerts/constants.py
new file mode 100644
index 000000000000..f406e857707a
--- /dev/null
+++ b/products/replay_vision/backend/temporal/vision_alerts/constants.py
@@ -0,0 +1,21 @@
+from datetime import timedelta
+
+from temporalio.common import RetryPolicy
+
+WORKFLOW_NAME = "replay-vision-alert-check"
+SCHEDULE_ID = "replay-vision-alert-check-schedule"
+SCHEDULE_CRON = "* * * * *"
+
+ACTIVITY_TIMEOUT = timedelta(minutes=2)
+ACTIVITY_RETRY_POLICY = RetryPolicy(
+ maximum_attempts=3,
+ initial_interval=timedelta(seconds=5),
+ maximum_interval=timedelta(seconds=30),
+ backoff_coefficient=2.0,
+)
+
+MAX_ALERTS_PER_BATCH = 25
+# Caps the discovery result so the workflow payload stays bounded; overflow runs next tick.
+MAX_ALERTS_PER_TICK = 500
+NOTIFICATION_FLUSH_TIMEOUT_SECONDS = 10.0
+CLEANUP_BATCH_SIZE = 1000
diff --git a/products/replay_vision/backend/temporal/vision_alerts/schedule.py b/products/replay_vision/backend/temporal/vision_alerts/schedule.py
new file mode 100644
index 000000000000..53476c1cad2f
--- /dev/null
+++ b/products/replay_vision/backend/temporal/vision_alerts/schedule.py
@@ -0,0 +1,35 @@
+"""Temporal schedule for the replay vision alert check workflow."""
+
+from django.conf import settings
+
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleSpec,
+)
+
+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+
+from products.replay_vision.backend.temporal.vision_alerts.activities import CheckVisionAlertsInput
+from products.replay_vision.backend.temporal.vision_alerts.constants import SCHEDULE_CRON, SCHEDULE_ID, WORKFLOW_NAME
+
+
+async def create_vision_alert_check_schedule(client: Client) -> None:
+ schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ WORKFLOW_NAME,
+ CheckVisionAlertsInput().model_dump(),
+ id=SCHEDULE_ID,
+ task_queue=settings.REPLAY_VISION_TASK_QUEUE,
+ ),
+ spec=ScheduleSpec(cron_expressions=[SCHEDULE_CRON]),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+ if await a_schedule_exists(client, SCHEDULE_ID):
+ await a_update_schedule(client, SCHEDULE_ID, schedule)
+ else:
+ await a_create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=False)
diff --git a/products/replay_vision/backend/temporal/vision_alerts/workflow.py b/products/replay_vision/backend/temporal/vision_alerts/workflow.py
new file mode 100644
index 000000000000..5b9314f9a8fa
--- /dev/null
+++ b/products/replay_vision/backend/temporal/vision_alerts/workflow.py
@@ -0,0 +1,93 @@
+"""Temporal workflow for replay vision alert checking."""
+
+import asyncio
+
+import temporalio
+from temporalio import workflow
+from temporalio.exceptions import ActivityError
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+# Activities and their payloads sit behind Django imports, which Temporal's workflow
+# sandbox blocks; they are only passed as references to execute_activity.
+with workflow.unsafe.imports_passed_through():
+ from products.replay_vision.backend.temporal.vision_alerts.activities import (
+ CheckVisionAlertsInput,
+ CheckVisionAlertsOutput,
+ CleanupAlertHistoryInput,
+ DiscoverDueAlertsInput,
+ DiscoverDueAlertsOutput,
+ EvaluateAlertBatchInput,
+ EvaluateAlertBatchOutput,
+ cleanup_vision_alert_history_activity,
+ discover_due_vision_alerts_activity,
+ evaluate_vision_alert_batch_activity,
+ )
+
+from products.replay_vision.backend.temporal.vision_alerts.constants import (
+ ACTIVITY_RETRY_POLICY,
+ ACTIVITY_TIMEOUT,
+ WORKFLOW_NAME,
+)
+
+
[email protected](name=WORKFLOW_NAME)
+class VisionAlertCheckWorkflow(PostHogWorkflow):
+ """Discover due metric alerts, then evaluate batches in parallel."""
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> CheckVisionAlertsInput:
+ return CheckVisionAlertsInput()
+
+ @temporalio.workflow.run
+ async def run(self, input: CheckVisionAlertsInput) -> CheckVisionAlertsOutput:
+ discovery: DiscoverDueAlertsOutput = await workflow.execute_activity(
+ discover_due_vision_alerts_activity,
+ DiscoverDueAlertsInput(),
+ start_to_close_timeout=ACTIVITY_TIMEOUT,
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+
+ output = CheckVisionAlertsOutput()
+ if discovery.batches:
+ # return_exceptions=True isolates per-batch retry exhaustion: one batch's
+ # failure doesn't abort the cycle.
+ results: list[EvaluateAlertBatchOutput | BaseException] = await asyncio.gather(
+ *(
+ workflow.execute_activity(
+ evaluate_vision_alert_batch_activity,
+ EvaluateAlertBatchInput(alert_ids=batch),
+ start_to_close_timeout=ACTIVITY_TIMEOUT,
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+ for batch in discovery.batches
+ ),
+ return_exceptions=True,
+ )
+
+ for batch, result in zip(discovery.batches, results):
+ if isinstance(result, ActivityError):
+ workflow.logger.warning(
+ "Vision alert batch failed; counting its alerts as errored", batch_size=len(batch)
+ )
+ output.alerts_errored += len(batch)
+ elif isinstance(result, BaseException):
+ raise result
+ else:
+ output.alerts_checked += result.alerts_checked
+ output.alerts_fired += result.alerts_fired
+ output.alerts_resolved += result.alerts_resolved
+ output.alerts_errored += result.alerts_errored
+
+ # Best-effort retention sweep; never fails the alert cycle.
+ try:
+ await workflow.execute_activity(
+ cleanup_vision_alert_history_activity,
+ CleanupAlertHistoryInput(),
+ start_to_close_timeout=ACTIVITY_TIMEOUT,
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+ except ActivityError:
+ workflow.logger.warning("Vision alert history cleanup failed; alert cycle continues")
+
+ return output
diff --git a/products/replay_vision/backend/tests/test_vision_alerts_engine.py b/products/replay_vision/backend/tests/test_vision_alerts_engine.py
new file mode 100644
index 000000000000..bfde5e7bd038
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_vision_alerts_engine.py
@@ -0,0 +1,285 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from freezegun import freeze_time
+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,
+ VisionAlertEvent,
+ VisionAlertKind,
+ VisionAlertMetric,
+ VisionAlertState,
+)
+from products.replay_vision.backend.temporal.vision_alerts.activities import (
+ DiscoverDueAlertsInput,
+ EvaluateAlertBatchInput,
+ _discover_due,
+ _evaluate_batch,
+)
+from products.replay_vision.backend.tests.helpers import snapshot_for
+
+_ACTIVITIES = "products.replay_vision.backend.temporal.vision_alerts.activities"
+
+
+class TestVisionAlertEngine(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_alert(self, **overrides: Any) -> VisionAlertConfiguration:
+ fields: dict[str, Any] = {
+ "team": self.team,
+ "scanner": self.scanner,
+ "name": f"alert-{uuid7()}",
+ "kind": VisionAlertKind.METRIC,
+ "metric": VisionAlertMetric.COUNT,
+ "threshold": 2,
+ "selection": {"verdict": ["fail"]},
+ "window_days": 1,
+ "first_enabled_at": timezone.now(),
+ }
+ fields.update(overrides)
+ return VisionAlertConfiguration.objects.for_team(self.team.id).create(**fields)
+
+ def _make_observation(
+ self,
+ verdict: str = "fail",
+ status: str = ObservationStatus.SUCCEEDED,
+ completed_at: datetime | None = None,
+ score: float | None = None,
+ ) -> ReplayObservation:
+ model_output: dict[str, Any] = {"scanner_type": self.scanner.scanner_type, "verdict": verdict}
+ if score is not None:
+ model_output["score"] = score
+ return ReplayObservation.objects.create(
+ scanner=self.scanner,
+ team=self.team,
+ session_id=f"s-{uuid7()}",
+ status=status,
+ completed_at=completed_at or timezone.now(),
+ scanner_snapshot=snapshot_for(self.scanner),
+ scanner_result={"model_output": model_output} if status == ObservationStatus.SUCCEEDED else {},
+ triggered_by=ObservationTrigger.SCHEDULE,
+ )
+
+ def _run_batch(self, alert: VisionAlertConfiguration, *, delivered: bool = True):
+ produce_result = MagicMock()
+ with (
+ patch(f"{_ACTIVITIES}.produce_alert_internal_event", return_value=produce_result) as produce,
+ patch(f"{_ACTIVITIES}.flush_alert_internal_events"),
+ patch(f"{_ACTIVITIES}.alert_internal_event_delivered", return_value=delivered),
+ ):
+ output = _evaluate_batch(EvaluateAlertBatchInput(alert_ids=[str(alert.id)]))
+ alert.refresh_from_db()
+ return output, produce
+
+ def test_breach_fires_and_resolves(self) -> None:
+ alert = self._make_alert()
+ self._make_observation()
+ self._make_observation()
+
+ output, produce = self._run_batch(alert)
+ assert output.alerts_fired == 1
+ assert alert.state == VisionAlertState.FIRING
+ assert alert.last_notified_at is not None
+ assert alert.next_check_at is not None
+ assert produce.call_args.kwargs["event_name"] == "$replay_vision_alert_firing"
+ props = produce.call_args.kwargs["properties"]
+ assert props["metric_value"] == 2.0
+ assert props["scanner_name"] == "Checkout monitor"
+ check_events = VisionAlertEvent.objects.filter(alert=alert, kind=VisionAlertEvent.Kind.CHECK)
+ assert check_events.count() == 1
+ assert check_events.get().threshold_breached is True
+
+ # Observations age out of the window -> resolve notification on the next check.
+ ReplayObservation.objects.filter(team_id=self.team.id).update(completed_at=timezone.now() - timedelta(days=2))
+ alert.next_check_at = None
+ alert.save(update_fields=["next_check_at"])
+ output, produce = self._run_batch(alert)
+ assert output.alerts_resolved == 1
+ assert alert.state == VisionAlertState.NOT_FIRING
+ assert produce.call_args.kwargs["event_name"] == "$replay_vision_alert_resolved"
+
+ @parameterized.expand(
+ [
+ ("outside_window", {"completed_at_days_ago": 2}, VisionAlertState.NOT_FIRING),
+ ("wrong_verdict", {"verdict": "pass"}, VisionAlertState.NOT_FIRING),
+ ("failed_status_excluded_by_default", {"status": ObservationStatus.FAILED}, VisionAlertState.NOT_FIRING),
+ ]
+ )
+ def test_non_matching_observations_do_not_fire(
+ self, _name: str, observation_kwargs: dict[str, Any], expected_state: str
+ ) -> None:
+ alert = self._make_alert(threshold=1)
+ kwargs = dict(observation_kwargs)
+ days_ago = kwargs.pop("completed_at_days_ago", None)
+ if days_ago is not None:
+ kwargs["completed_at"] = timezone.now() - timedelta(days=days_ago)
+ self._make_observation(**kwargs)
+ _output, produce = self._run_batch(alert)
+ assert alert.state == expected_state
+ produce.assert_not_called()
+
+ def test_avg_score_empty_window_is_inconclusive(self) -> None:
+ alert = self._make_alert(metric=VisionAlertMetric.AVG_SCORE, threshold=3, selection={})
+ _output, produce = self._run_batch(alert)
+ assert alert.state == VisionAlertState.NOT_FIRING
+ assert alert.consecutive_failures == 0
+ produce.assert_not_called()
+
+ def test_avg_score_below_direction_fires(self) -> None:
+ alert = self._make_alert(metric=VisionAlertMetric.AVG_SCORE, threshold=3, direction="below", selection={})
+ self._make_observation(score=1.0)
+ self._make_observation(score=2.0)
+ output, produce = self._run_batch(alert)
+ assert output.alerts_fired == 1
+ assert produce.call_args.kwargs["properties"]["metric_value"] == 1.5
+
+ def test_alert_disabled_after_discovery_is_suppressed(self) -> None:
+ alert = self._make_alert()
+ self._make_observation()
+ self._make_observation()
+ VisionAlertConfiguration.all_teams.filter(id=alert.id).update(enabled=False)
+ output, produce = self._run_batch(alert)
+ assert output.alerts_checked == 0
+ assert alert.state == VisionAlertState.NOT_FIRING
+ assert alert.last_checked_at is None
+ produce.assert_not_called()
+
+ def test_retry_of_the_same_cycle_reuses_the_notification_uuid(self) -> None:
+ cycle_anchor = datetime.now(UTC) - timedelta(minutes=1)
+ alert = self._make_alert(next_check_at=cycle_anchor)
+ self._make_observation()
+ self._make_observation()
+ _, produce = self._run_batch(alert)
+ first_uuid = produce.call_args.kwargs["uuid"]
+
+ # An activity retry re-evaluates the same cycle: nothing saved yet, so the
+ # anchor is unchanged and the uuid must match for ingestion to dedupe.
+ VisionAlertConfiguration.all_teams.filter(id=alert.id).update(
+ state=VisionAlertState.NOT_FIRING, next_check_at=cycle_anchor, last_notified_at=None
+ )
+ alert.refresh_from_db()
+ _, produce = self._run_batch(alert)
+ assert produce.call_args.kwargs["uuid"] == first_uuid
+
+ # The next cycle carries a new anchor and must not dedupe against the old one.
+ VisionAlertConfiguration.all_teams.filter(id=alert.id).update(
+ state=VisionAlertState.NOT_FIRING, next_check_at=cycle_anchor + timedelta(hours=1), last_notified_at=None
+ )
+ alert.refresh_from_db()
+ _, produce = self._run_batch(alert)
+ assert produce.call_args.kwargs["uuid"] != first_uuid
+
+ def test_scanner_name_is_escaped_for_slack_context(self) -> None:
+ self.scanner.name = "<!channel> & <https://example.com|x>"
+ self.scanner.save(update_fields=["name"])
+ alert = self._make_alert()
+ self._make_observation()
+ self._make_observation()
+ _, produce = self._run_batch(alert)
+ props = produce.call_args.kwargs["properties"]
+ assert props["scanner_name_mrkdwn"] == "&lt;!channel&gt; &amp; &lt;https://example.com|x&gt;"
+ assert props["scanner_name"] == "<!channel> & <https://example.com|x>"
+
+ def test_first_cycle_retry_is_uuid_stable_without_next_check_at(self) -> None:
+ start = datetime.now(UTC)
+ with freeze_time(start):
+ alert = self._make_alert(next_check_at=None)
+ # The window bound is completed_at < now, so frozen-now observations need backdating.
+ self._make_observation(completed_at=start - timedelta(minutes=5))
+ self._make_observation(completed_at=start - timedelta(minutes=5))
+ _, produce = self._run_batch(alert)
+ first_uuid = produce.call_args.kwargs["uuid"]
+
+ # A retry of the same unsaved cycle after a wall-clock minute rollover must
+ # still dedupe: the anchor may not depend on now().
+ VisionAlertConfiguration.all_teams.filter(id=alert.id).update(
+ state=VisionAlertState.NOT_FIRING, next_check_at=None, last_checked_at=None, last_notified_at=None
+ )
+ alert.refresh_from_db()
+ with freeze_time(start + timedelta(seconds=61)):
+ _, produce = self._run_batch(alert)
+ assert produce.call_args.kwargs["uuid"] == first_uuid
+
+ @parameterized.expand(
+ [
+ ("snoozed", {"state": VisionAlertState.SNOOZED}, VisionAlertState.SNOOZED),
+ ("disabled", {"enabled": False}, VisionAlertState.NOT_FIRING),
+ ]
+ )
+ def test_concurrent_transition_during_dispatch_wins_over_the_check(
+ self, _name: str, transition: dict[str, Any], expected_state: str
+ ) -> None:
+ alert = self._make_alert()
+ self._make_observation()
+ self._make_observation()
+
+ def transition_mid_dispatch(*args: Any, **kwargs: Any) -> MagicMock:
+ fields = dict(transition)
+ if fields.get("state") == VisionAlertState.SNOOZED:
+ fields["snooze_until"] = datetime.now(UTC) + timedelta(hours=1)
+ VisionAlertConfiguration.all_teams.filter(id=alert.id).update(**fields)
+ return MagicMock()
+
+ with (
+ patch(f"{_ACTIVITIES}.produce_alert_internal_event", side_effect=transition_mid_dispatch),
+ patch(f"{_ACTIVITIES}.flush_alert_internal_events"),
+ patch(f"{_ACTIVITIES}.alert_internal_event_delivered", return_value=True),
+ ):
+ output = _evaluate_batch(EvaluateAlertBatchInput(alert_ids=[str(alert.id)]))
+
+ alert.refresh_from_db()
+ assert output.alerts_checked == 0
+ assert alert.state == expected_state
+ assert alert.last_checked_at is None
+
+ def test_undelivered_notification_rolls_back_state(self) -> None:
+ alert = self._make_alert()
+ self._make_observation()
+ self._make_observation()
+ output, _ = self._run_batch(alert, delivered=False)
+ assert output.alerts_fired == 0
+ assert alert.state == VisionAlertState.NOT_FIRING
+ assert alert.last_notified_at is None
+ # The next check re-evaluates and re-fires instead of assuming "notified".
+ alert.next_check_at = None
+ alert.save(update_fields=["next_check_at"])
+ output, _ = self._run_batch(alert, delivered=True)
+ assert output.alerts_fired == 1
+ assert alert.state == VisionAlertState.FIRING
+
+ def test_discover_skips_match_broken_snoozed_and_future(self) -> None:
+ due = self._make_alert()
+ self._make_alert(name="match", kind=VisionAlertKind.MATCH, threshold=None)
+ self._make_alert(name="broken", state=VisionAlertState.BROKEN)
+ self._make_alert(
+ name="snoozed",
+ state=VisionAlertState.SNOOZED,
+ snooze_until=datetime.now(UTC) + timedelta(hours=1),
+ )
+ self._make_alert(name="future", next_check_at=datetime.now(UTC) + timedelta(hours=1))
+ self._make_alert(name="disabled", enabled=False)
+
+ output = _discover_due(DiscoverDueAlertsInput())
+ assert output.batches == [[str(due.id)]]