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 alert configurations on the shared alerts platform (#88403)

Tue Haulund6b0c50a537ed
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 784651c76b58..c01c67317cad 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -353,6 +353,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"LLMSkillFile", # via LLMSkill
"LogsAlertCheck", # via LogsAlertConfiguration
"LogsAlertEvent", # via LogsAlertConfiguration
+ "VisionAlertEvent", # via VisionAlertConfiguration
"NotificationReadState", # via NotificationEvent
"NotificationArchiveState", # via NotificationEvent
"PluginStorage", # via PluginConfig
diff --git a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
index 10a668b0dbd1..49bfe1230e85 100644
--- a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
+++ b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
@@ -29,6 +29,36 @@ rules:
- '/products/logs/backend/test/**'
- '/products/logs/backend/**/test_*.py'
+ - id: replay-vision-alert-state-direct-mutation
+ patterns:
+ - pattern-either:
+ - pattern: $ALERT.state = $VALUE
+ - pattern: $ALERT.consecutive_failures = $VALUE
+ - pattern: $ALERT.enabled = $VALUE
+ - pattern: $QUERY.update(..., state=$VALUE, ...)
+ - pattern: $QUERY.update(..., consecutive_failures=$VALUE, ...)
+ - pattern: $QUERY.update(..., enabled=$VALUE, ...)
+ message: |
+ Direct mutation of a replay vision alert's lifecycle fields bypasses its
+ state machine adapter. Route the change through
+ products.replay_vision.backend.alert_state_machine.
+ languages: [python]
+ severity: ERROR
+ metadata:
+ category: correctness
+ subcategory: audit
+ confidence: HIGH
+ paths:
+ include:
+ - '/products/replay_vision/backend/**/*.py'
+ - '/.semgrep/rules/security/tests/replay-vision-alert-state-must-go-through-state-machine.py'
+ exclude:
+ - '/products/replay_vision/backend/alert_state_machine.py'
+ - '/products/replay_vision/backend/tests/**'
+ - '/products/replay_vision/backend/**/test_*.py'
+ # Mutates HogFunction.enabled (delivery plumbing), not an alert.
+ - '/products/replay_vision/backend/api/delivery.py'
+
- id: billing-alert-state-direct-mutation
patterns:
- pattern-either:
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 4fdd3aa89bfc..a85e02696691 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -364,6 +364,8 @@ rules:
|UserRepoPreference
|VisionAction
|VisionActionRun
+ |VisionAlertConfiguration
+ |VisionAlertMatch
|WarehouseColumnAnnotation
|WarehouseColumnStatistics
|WebAnalyticsAchievementProgress
@@ -729,6 +731,8 @@ rules:
|UserRepoPreference
|VisionAction
|VisionActionRun
+ |VisionAlertConfiguration
+ |VisionAlertMatch
|WarehouseColumnAnnotation
|WarehouseColumnStatistics
|WebAnalyticsAchievementProgress
diff --git a/.semgrep/rules/security/tests/replay-vision-alert-state-must-go-through-state-machine.py b/.semgrep/rules/security/tests/replay-vision-alert-state-must-go-through-state-machine.py
new file mode 100644
index 000000000000..f10e0da848b2
--- /dev/null
+++ b/.semgrep/rules/security/tests/replay-vision-alert-state-must-go-through-state-machine.py
@@ -0,0 +1,22 @@
+class VisionAlertConfiguration:
+ enabled: bool
+ state: str
+ consecutive_failures: int
+
+
+def direct_mutations(alert: VisionAlertConfiguration) -> None:
+ # ruleid: replay-vision-alert-state-direct-mutation
+ alert.enabled = False
+ # ruleid: replay-vision-alert-state-direct-mutation
+ alert.state = "firing"
+ # ruleid: replay-vision-alert-state-direct-mutation
+ alert.consecutive_failures = 1
+
+
+def queryset_mutations(queryset) -> None:
+ # ruleid: replay-vision-alert-state-direct-mutation
+ queryset.update(enabled=False)
+ # ruleid: replay-vision-alert-state-direct-mutation
+ queryset.update(state="firing")
+ # ruleid: replay-vision-alert-state-direct-mutation
+ queryset.update(consecutive_failures=1)
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
index ba726445a959..09fed4cbf1bf 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
@@ -491,6 +491,7 @@ export interface accessControlsLogicActions {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -660,6 +661,7 @@ export interface accessControlsLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -806,6 +808,7 @@ export interface accessControlsLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -924,6 +927,7 @@ export interface accessControlsLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
index ced36a856e96..4e95e31e92af 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
@@ -312,6 +312,7 @@ export interface accessDetailLogicActions {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
index f816c79724e5..bb97bd53ef1d 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
@@ -162,6 +162,7 @@ export interface addObjectOverrideModalLogicActions {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -278,6 +279,7 @@ export interface addObjectOverrideModalLogicActions {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -415,6 +417,7 @@ export interface addObjectOverrideModalLogicActions {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -536,6 +539,7 @@ export interface addObjectOverrideModalLogicActions {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -656,6 +660,7 @@ export interface addObjectOverrideModalLogicActions {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -797,6 +802,7 @@ export interface addObjectOverrideModalLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
index 781291b9b9a6..b00a82e14bc9 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
@@ -125,6 +125,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -247,6 +248,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -361,6 +363,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -488,6 +491,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -620,6 +624,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -754,6 +759,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -868,6 +874,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -1021,6 +1028,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -1137,6 +1145,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -1252,6 +1261,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -1367,6 +1377,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -1483,6 +1494,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -1598,6 +1610,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -1724,6 +1737,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -1839,6 +1853,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
index 47b222b01d74..9ab1d9692dd1 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
@@ -416,6 +416,7 @@ export interface accessControlLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -634,6 +635,7 @@ export interface accessControlLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
@@ -749,6 +751,7 @@ export interface accessControlLogicMeta {
| 'user'
| 'user_interview'
| 'vision_action'
+ | 'vision_alert'
| 'visual_review'
| 'warehouse_objects'
| 'warehouse_table'
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 2d7e86e74286..59100bfa524f 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -240,6 +240,7 @@ export const API_SCOPES: APIScope[] = [
{ key: 'task', objectName: 'Task', objectPlural: 'tasks' },
{ key: 'user_interview', objectName: 'User interview', objectPlural: 'user interviews' },
{ key: 'vision_action', objectName: 'Vision action', objectPlural: 'vision actions' },
+ { key: 'vision_alert', objectName: 'Vision alert', objectPlural: 'vision alerts' },
{ key: 'visual_review', objectName: 'Visual review', objectPlural: 'visual reviews' },
{
key: 'webhook',
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index aed364cf8cfe..098aa0849231 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5919,6 +5919,7 @@ export const API_SCOPE_OBJECTS = [
'user',
'user_interview',
'vision_action',
+ 'vision_alert',
'visual_review',
'warehouse_objects',
'warehouse_table',
diff --git a/posthog/cdp/internal_events.py b/posthog/cdp/internal_events.py
index 7164ef6c4fd3..a8ab652dba1c 100644
--- a/posthog/cdp/internal_events.py
+++ b/posthog/cdp/internal_events.py
@@ -16,7 +16,7 @@ logger = structlog.get_logger(__name__)
# Single source of truth for the managed-alert event boundary. Also used as a Postgres regex
# filter (products/cdp hog_function queryset) and mirrored in the Node CDP consumer, so keep it
# POSIX-compatible (no (?:...) groups).
-MANAGED_ALERT_EVENT_PATTERN = r"^\$[a-z0-9_]+_alert_(firing|resolved|errored|auto_disabled)$"
+MANAGED_ALERT_EVENT_PATTERN = r"^\$[a-z0-9_]+_alert_(firing|resolved|errored|auto_disabled|match)$"
LEGACY_INSIGHT_ALERT_EVENT = "$insight_alert_firing"
_MANAGED_ALERT_EVENT = re.compile(MANAGED_ALERT_EVENT_PATTERN)
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 7b05cab6d112..69cfc85e4b72 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -121,6 +121,7 @@ APIScopeObject = Literal[
"user",
"user_interview", # Alpha product — access gated by feature flag at the MCP/API layer rather than by hiding the scope.
"vision_action",
+ "vision_alert",
"visual_review",
"warehouse_objects",
"warehouse_table",
diff --git a/products/access_control/backend/facade/user_access_control.py b/products/access_control/backend/facade/user_access_control.py
index 873f94c6bdb2..1b8076e83483 100644
--- a/products/access_control/backend/facade/user_access_control.py
+++ b/products/access_control/backend/facade/user_access_control.py
@@ -119,6 +119,8 @@ RESOURCE_INHERITANCE_MAP: dict[APIScopeObject, APIScopeObject] = {
# scanner's "and then…" automations) — configured via the same single
# replay_scanner rule rather than a separate resource.
"vision_action": "replay_scanner",
+ # Vision alerts follow the same rule: configured via the scanner's access level.
+ "vision_alert": "replay_scanner",
}
# Unlike RESOURCE_INHERITANCE_MAP above, where the child has no access of its own and just uses the
@@ -331,6 +333,8 @@ def model_to_resource(model: Model) -> Optional[APIScopeObject]:
return "replay_scanner"
if name in ("visionaction", "visionactionrun"):
return "vision_action"
+ if name in ("visionalertconfiguration", "visionalertevent"):
+ return "vision_alert"
if name not in API_SCOPE_OBJECTS or name in INTERNAL_API_SCOPE_OBJECTS:
return None
diff --git a/products/access_control/backend/tests/test_user_access_control_pbt.py b/products/access_control/backend/tests/test_user_access_control_pbt.py
index 0db74a53f2d2..3353e2cda227 100644
--- a/products/access_control/backend/tests/test_user_access_control_pbt.py
+++ b/products/access_control/backend/tests/test_user_access_control_pbt.py
@@ -155,11 +155,37 @@ def _build_ticket(team: Team, user: User, model_cls: type[models.Model]) -> mode
)
+def _build_vision_alert(team: Team, user: User, model_cls: type[models.Model]) -> models.Model:
+ # kind drives cross-field CHECK constraints (a metric alert needs a threshold, a
+ # match alert must stay stateless) and is a 10-char choices column, so the generic
+ # field-filler can neither pick a valid kind nor satisfy the constraints.
+ from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+
+ scanner = ReplayScanner.objects.create(
+ team=team,
+ name=f"pbt-scanner-{next(_unique_counter)}",
+ scanner_type="monitor",
+ scanner_config={},
+ model="gemini-3.7-flash",
+ )
+ manager: Any = model_cls._default_manager
+ if hasattr(manager, "for_team"):
+ manager = manager.for_team(team.id)
+ return manager.create(
+ team=team,
+ scanner=scanner,
+ name=f"pbt-vision-alert-{next(_unique_counter)}",
+ kind="match",
+ created_by=user,
+ )
+
+
# resource -> factory for models whose validation the generic build_instance can't
# satisfy. Preferred over EXCLUSIONS so the resource keeps coverage.
FACTORY_OVERRIDES: dict[APIScopeObject, Callable[[Team, User, type[models.Model]], models.Model]] = {
"evaluation": _build_evaluation,
"ticket": _build_ticket,
+ "vision_alert": _build_vision_alert,
}
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 40cae6b2ee7b..f6a55dc0a9bd 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,
- ([e__person.properties___fish] AS value) AS prop_basic,
+ ([replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', '')] AS value) AS prop_basic,
prop_basic AS prop
FROM events AS e
LEFT OUTER JOIN
@@ -44,16 +44,6 @@
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))
@@ -121,17 +111,7 @@
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')), 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))))
+ 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))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
GROUP BY breakdown
@@ -188,8 +168,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(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
+ 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
FROM events AS e
LEFT OUTER JOIN
(SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
@@ -198,16 +178,6 @@
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))
@@ -324,24 +294,7 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- 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)))
+ 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)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
@@ -373,24 +326,7 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- 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)))
+ 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)))
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
new file mode 100644
index 000000000000..e9148a172435
--- /dev/null
+++ b/products/replay_vision/backend/alert_destinations.py
@@ -0,0 +1,161 @@
+"""Build HogFunction configurations for replay vision alert notifications."""
+
+from __future__ import annotations
+
+from typing import Literal
+
+from products.alerts.backend.destination_configs import DestinationType, EventKindSpec
+
+EventKind = Literal["firing", "resolved", "broken", "errored", "match"]
+VISION_DESTINATION_TYPES = (DestinationType.SLACK, DestinationType.WEBHOOK)
+
+_PRODUCT_LABEL = "replay vision alert"
+
+_ALERT_URL = "{project.url}/replay-vision/{event.properties.scanner_id}?tab=alerts"
+_OBSERVATIONS_URL = "{project.url}/replay-vision/{event.properties.scanner_id}?tab=observations"
+
+_FIRE_RESOLVE_DATA: dict[str, str] = {
+ "alert_id": "{event.properties.alert_id}",
+ "alert_name": "{event.properties.alert_name}",
+ "scanner_id": "{event.properties.scanner_id}",
+ "scanner_name": "{event.properties.scanner_name}",
+ "metric": "{event.properties.metric}",
+ "metric_value": "{event.properties.metric_value}",
+ "threshold": "{event.properties.threshold}",
+ "direction": "{event.properties.direction}",
+ "window_days": "{event.properties.window_days}",
+ "observations_url": _OBSERVATIONS_URL,
+ "alert_url": _ALERT_URL,
+}
+
+_BROKEN_ERRORED_BASE_DATA: dict[str, str] = {
+ "alert_id": "{event.properties.alert_id}",
+ "alert_name": "{event.properties.alert_name}",
+ "scanner_id": "{event.properties.scanner_id}",
+ "scanner_name": "{event.properties.scanner_name}",
+ "consecutive_failures": "{event.properties.consecutive_failures}",
+ "alert_url": _ALERT_URL,
+}
+
+
+EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {
+ "firing": EventKindSpec(
+ event_id="$replay_vision_alert_firing",
+ display_kind="firing",
+ header="🔴 Replay vision alert '{event.properties.alert_name}' is firing",
+ details=(
+ (
+ "Threshold breached",
+ "{event.properties.metric_label} is {event.properties.metric_value} over the last "
+ "{event.properties.window_label} (threshold: {event.properties.direction} {event.properties.threshold})",
+ ),
+ ),
+ primary_action_url=_OBSERVATIONS_URL,
+ primary_action_label="View observations",
+ webhook_body={
+ "id": "{event.uuid}",
+ "type": "replay_vision_alert.firing",
+ "timestamp": "{event.properties.triggered_at}",
+ "data": _FIRE_RESOLVE_DATA,
+ },
+ product_label=_PRODUCT_LABEL,
+ ),
+ "resolved": EventKindSpec(
+ event_id="$replay_vision_alert_resolved",
+ display_kind="resolved",
+ header="🟢 Replay vision alert '{event.properties.alert_name}' has resolved",
+ details=(
+ (
+ "Current value",
+ "{event.properties.metric_label} is {event.properties.metric_value} over the last "
+ "{event.properties.window_label} (threshold: {event.properties.direction} {event.properties.threshold})",
+ ),
+ ),
+ primary_action_url=_OBSERVATIONS_URL,
+ primary_action_label="View observations",
+ webhook_body={
+ "id": "{event.uuid}",
+ "type": "replay_vision_alert.resolved",
+ "timestamp": "{event.properties.triggered_at}",
+ "data": _FIRE_RESOLVE_DATA,
+ },
+ product_label=_PRODUCT_LABEL,
+ ),
+ "broken": EventKindSpec(
+ event_id="$replay_vision_alert_auto_disabled",
+ display_kind="auto-disabled",
+ header="⚠️ Replay vision alert '{event.properties.alert_name}' was auto-disabled",
+ details=(
+ ("Reason", "{event.properties.consecutive_failures} consecutive check failures."),
+ ("Last error", "{event.properties.last_error_message}"),
+ ),
+ primary_action_url=_ALERT_URL,
+ primary_action_label="View alert",
+ webhook_body={
+ "id": "{event.uuid}",
+ "type": "replay_vision_alert.auto_disabled",
+ "timestamp": "{event.properties.triggered_at}",
+ "data": {
+ **_BROKEN_ERRORED_BASE_DATA,
+ "last_error_message": "{event.properties.last_error_message}",
+ },
+ },
+ product_label=_PRODUCT_LABEL,
+ ),
+ "errored": EventKindSpec(
+ event_id="$replay_vision_alert_errored",
+ display_kind="errored",
+ header="🟡 Replay vision alert '{event.properties.alert_name}' couldn't evaluate",
+ details=(
+ ("Reason", "{event.properties.error_message}"),
+ ("Failure count", "{event.properties.consecutive_failures}"),
+ ),
+ primary_action_url=_ALERT_URL,
+ primary_action_label="View alert",
+ webhook_body={
+ "id": "{event.uuid}",
+ "type": "replay_vision_alert.errored",
+ "timestamp": "{event.properties.triggered_at}",
+ "data": {
+ **_BROKEN_ERRORED_BASE_DATA,
+ "error_message": "{event.properties.error_message}",
+ },
+ },
+ product_label=_PRODUCT_LABEL,
+ ),
+ "match": EventKindSpec(
+ event_id="$replay_vision_alert_match",
+ display_kind="match",
+ header="🔔 {event.properties.matched_count} new matching observations for '{event.properties.alert_name}'",
+ details=(("Matches", "{event.properties.summary}"),),
+ primary_action_url=_OBSERVATIONS_URL,
+ primary_action_label="View observations",
+ webhook_body={
+ "id": "{event.uuid}",
+ "type": "replay_vision_alert.match",
+ "timestamp": "{event.properties.triggered_at}",
+ "data": {
+ "alert_id": "{event.properties.alert_id}",
+ "alert_name": "{event.properties.alert_name}",
+ "scanner_id": "{event.properties.scanner_id}",
+ "scanner_name": "{event.properties.scanner_name}",
+ "matched_count": "{event.properties.matched_count}",
+ "observation_ids": "{event.properties.observation_ids}",
+ "observations_url": _OBSERVATIONS_URL,
+ "alert_url": _ALERT_URL,
+ },
+ },
+ product_label=_PRODUCT_LABEL,
+ ),
+}
+
+# Lifecycle kinds provisioned as destinations for metric alerts; match alerts get only "match".
+METRIC_EVENT_KINDS: tuple[EventKind, ...] = ("firing", "resolved", "broken", "errored")
+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}",
+ "Project: <{project.url}|{project.name}>",
+)
diff --git a/products/replay_vision/backend/alert_state_machine.py b/products/replay_vision/backend/alert_state_machine.py
new file mode 100644
index 000000000000..17b9fe017920
--- /dev/null
+++ b/products/replay_vision/backend/alert_state_machine.py
@@ -0,0 +1,147 @@
+"""Single source of truth for VisionAlertConfiguration state transitions.
+
+Any write to `VisionAlertConfiguration.state` or `.consecutive_failures` MUST originate
+here — the check-driven path goes through `evaluate_alert_check`, the control-plane path
+goes through one of the shared `apply_*` helpers, and every caller applies the resulting
+outcome via `apply_outcome`, the only function that mutates those two fields. The semgrep
+rule at `.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml` enforces
+this in CI.
+
+The decision logic lives in `products/alerts/backend/state_machine.py`, configured with
+`VISION_ALERT_POLICY`; this module owns the vision-shaped inputs and the model mutation.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from typing import TYPE_CHECKING
+
+from posthog.dataclasses import frozen
+
+from products.alerts.backend.state_machine import (
+ MAX_CONSECUTIVE_FAILURES,
+ AlertCheckOutcome,
+ AlertPolicy,
+ AlertSnapshot as SharedAlertSnapshot,
+ AlertState,
+ CheckInput,
+ ControlPlaneOutcome,
+ InvalidTransition,
+ NotificationAction,
+ Outcome,
+ apply_disable,
+ apply_enable,
+ apply_snooze,
+ apply_threshold_change,
+ apply_unsnooze,
+ apply_user_reset,
+ evaluate_alert_check as shared_evaluate_alert_check,
+)
+
+if TYPE_CHECKING:
+ from products.replay_vision.backend.models.vision_alert import VisionAlertConfiguration, VisionAlertEvent
+
+__all__ = [
+ "MAX_CONSECUTIVE_FAILURES",
+ "VISION_ALERT_POLICY",
+ "AlertCheckOutcome",
+ "AlertSnapshot",
+ "AlertState",
+ "CheckResult",
+ "ControlPlaneOutcome",
+ "InvalidTransition",
+ "NotificationAction",
+ "Outcome",
+ "apply_disable",
+ "apply_enable",
+ "apply_outcome",
+ "apply_snooze",
+ "apply_threshold_change",
+ "apply_unsnooze",
+ "apply_user_reset",
+ "evaluate_alert_check",
+]
+
+# Deliberately the shared defaults (same semantics as logs): fire on transition only,
+# resolve notifications on, BROKEN terminal until user reset. Diverge by setting fields
+# here, never by forking the shared machine.
+VISION_ALERT_POLICY = AlertPolicy()
+
+
+@frozen
+class CheckResult:
+ metric_value: float | None
+ threshold_breached: bool
+ error_message: str | None = None
+ is_inconclusive: bool = False
+ is_transient_error: bool = False
+
+
+@frozen
+class AlertSnapshot:
+ state: AlertState
+ evaluation_periods: int
+ datapoints_to_alarm: int
+ cooldown_minutes: int
+ last_notified_at: datetime | None
+ snooze_until: datetime | None
+ consecutive_failures: int
+ recent_events_breached: tuple[bool, ...]
+
+
+def evaluate_alert_check(
+ snapshot: AlertSnapshot,
+ check: CheckResult,
+ now: datetime,
+) -> AlertCheckOutcome:
+ return shared_evaluate_alert_check(
+ SharedAlertSnapshot(
+ state=snapshot.state,
+ cooldown=timedelta(minutes=snapshot.cooldown_minutes),
+ last_notified_at=snapshot.last_notified_at,
+ snooze_until=snapshot.snooze_until,
+ consecutive_failures=snapshot.consecutive_failures,
+ evaluation_periods=snapshot.evaluation_periods,
+ datapoints_to_alarm=snapshot.datapoints_to_alarm,
+ recent_events_breached=snapshot.recent_events_breached,
+ ),
+ CheckInput(
+ threshold_breached=check.threshold_breached,
+ error_message=check.error_message,
+ is_inconclusive=check.is_inconclusive,
+ is_transient_error=check.is_transient_error,
+ ),
+ now,
+ policy=VISION_ALERT_POLICY,
+ )
+
+
+def apply_outcome(
+ alert: VisionAlertConfiguration,
+ outcome: Outcome,
+ *,
+ kind: VisionAlertEvent.Kind | None = None,
+) -> list[str]:
+ """Mutates `alert.state` and `alert.consecutive_failures` from an outcome.
+ Returns modified field names for `save(update_fields=...)`.
+
+ If `kind` is provided, writes a `VisionAlertEvent` audit row — even when
+ state_before == state_after, because the caller has already decided the action is
+ audit-worthy. Worker CHECK rows are written by the temporal activity, not here.
+ """
+ state_before = alert.state
+ alert.state = outcome.new_state.value
+ alert.consecutive_failures = outcome.consecutive_failures
+
+ if kind is not None:
+ from products.replay_vision.backend.models.vision_alert import VisionAlertEvent
+
+ VisionAlertEvent.objects.create(
+ alert=alert,
+ kind=kind,
+ threshold_breached=False,
+ state_before=state_before,
+ state_after=outcome.new_state.value,
+ )
+
+ return ["state", "consecutive_failures"]
diff --git a/products/replay_vision/backend/alert_utils.py b/products/replay_vision/backend/alert_utils.py
new file mode 100644
index 000000000000..6d5d7262ee72
--- /dev/null
+++ b/products/replay_vision/backend/alert_utils.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from uuid import UUID
+
+from django.db.models import Q
+
+import structlog
+
+from products.alerts.backend.scheduling import (
+ advance_next_check_at,
+ compute_shard_offset_seconds as shared_compute_shard_offset_seconds,
+ parse_blocked_windows_tuples,
+ scan_next_unblocked_utc,
+)
+
+logger = structlog.get_logger(__name__)
+
+__all__ = [
+ "SCHEDULE_INTERVAL_SECONDS",
+ "advance_next_check_at",
+ "compute_shard_offset_seconds",
+ "due_alerts_q",
+ "next_allowed_check_at",
+]
+
+# How often the Temporal schedule fires. Drives shard granularity in
+# `compute_shard_offset_seconds`: a cadence of M seconds has `M // N` shard slots.
+SCHEDULE_INTERVAL_SECONDS = 60
+
+
+def compute_shard_offset_seconds(alert_id: UUID, check_interval_minutes: int) -> int:
+ return shared_compute_shard_offset_seconds(
+ alert_id,
+ check_interval_minutes,
+ schedule_interval_seconds=SCHEDULE_INTERVAL_SECONDS,
+ )
+
+
+def next_allowed_check_at(
+ candidate: datetime,
+ *,
+ team_timezone: str,
+ schedule_restriction: dict[str, object] | None,
+) -> datetime:
+ windows = parse_blocked_windows_tuples(schedule_restriction)
+ allowed_at = scan_next_unblocked_utc(candidate, team_timezone, windows)
+ if allowed_at is not None:
+ return allowed_at
+
+ logger.warning(
+ "vision_alert.schedule_restriction.next_allowed_check_at_exceeded_cap",
+ team_timezone=team_timezone,
+ )
+ retry_candidate = candidate.astimezone(UTC) + timedelta(days=1)
+ allowed_at = scan_next_unblocked_utc(retry_candidate, team_timezone, windows)
+ if allowed_at is not None:
+ return allowed_at
+
+ logger.error(
+ "vision_alert.schedule_restriction.next_allowed_check_at_giving_up_after_retry",
+ team_timezone=team_timezone,
+ )
+ return retry_candidate.replace(second=0, microsecond=0)
+
+
+def due_alerts_q(now: datetime, *, broken_state: str, snoozed_state: str) -> Q:
+ return (
+ Q(enabled=True)
+ & (Q(next_check_at__lte=now) | Q(next_check_at__isnull=True))
+ & ~Q(state=broken_state)
+ & ~Q(state=snoozed_state, snooze_until__gt=now)
+ )
diff --git a/products/replay_vision/backend/api/__init__.py b/products/replay_vision/backend/api/__init__.py
index bab471cc0bb4..d0142e61bcc5 100644
--- a/products/replay_vision/backend/api/__init__.py
+++ b/products/replay_vision/backend/api/__init__.py
@@ -6,6 +6,7 @@ from products.replay_vision.backend.api.scanner_scouts import ScannerScoutViewSe
from products.replay_vision.backend.api.scanners import ReplayScannerViewSet
from products.replay_vision.backend.api.scout_reports import ScannerScoutReportViewSet
from products.replay_vision.backend.api.vision_actions import VisionActionRunViewSet, VisionActionViewSet
+from products.replay_vision.backend.api.vision_alerts import VisionAlertViewSet
__all__ = [
"ReplayObservationViewSet",
@@ -17,5 +18,6 @@ __all__ = [
"SessionReplayObservationViewSet",
"VisionActionRunViewSet",
"VisionActionViewSet",
+ "VisionAlertViewSet",
"VisionQuotaViewSet",
]
diff --git a/products/replay_vision/backend/api/vision_alerts.py b/products/replay_vision/backend/api/vision_alerts.py
new file mode 100644
index 000000000000..15195b16a466
--- /dev/null
+++ b/products/replay_vision/backend/api/vision_alerts.py
@@ -0,0 +1,722 @@
+import os
+from datetime import UTC, datetime
+from typing import Any, Final, cast
+
+from django.db import transaction
+from django.db.models import F, Q, QuerySet
+from django.shortcuts import get_object_or_404
+from django.utils import timezone
+
+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field
+from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import PermissionDenied, ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
+from posthog.api.shared import UserBasicSerializer
+from posthog.event_usage import report_user_action
+from posthog.models.team.team import Team
+
+from products.alerts.backend.destinations import count_active_alert_destinations
+from products.alerts.backend.facade.api import (
+ AlertDestinationData,
+ AlertDestinationValidationError,
+ AlertScheduleRestriction,
+ DestinationType,
+ build_alert_destination_config,
+ create_alert_destination_hog_functions,
+ soft_delete_alert_destinations,
+ soft_delete_all_alert_destinations,
+ validate_and_normalize_schedule_restriction,
+ validate_destination_data,
+)
+from products.replay_vision.backend.alert_destinations import (
+ EVENT_KIND_CONFIG,
+ MATCH_EVENT_KINDS,
+ METRIC_EVENT_KINDS,
+ VISION_ALERT_EVENT_IDS,
+ VISION_ALERT_SLACK_CONTEXT_ELEMENTS,
+ VISION_DESTINATION_TYPES,
+ EventKind,
+)
+from products.replay_vision.backend.alert_state_machine import (
+ InvalidTransition,
+ apply_disable,
+ apply_enable,
+ apply_outcome,
+ apply_snooze,
+ apply_threshold_change,
+ apply_unsnooze,
+ apply_user_reset,
+)
+from products.replay_vision.backend.alert_utils import next_allowed_check_at
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
+from products.replay_vision.backend.models.vision_alert import (
+ ALERT_WINDOW_DAYS,
+ MIN_CHECK_INTERVAL_MINUTES,
+ VisionAlertConfiguration,
+ VisionAlertDirection,
+ VisionAlertEvent,
+ VisionAlertKind,
+ VisionAlertMetric,
+ VisionAlertState,
+)
+
+MAX_ALERTS_PER_TEAM = 20
+MAX_DESTINATIONS_PER_ALERT = 5
+# Comma-separated team IDs that bypass MAX_ALERTS_PER_TEAM, for internal dogfood projects.
+UNCAPPED_ALERT_TEAM_IDS: frozenset[int] = frozenset(
+ int(t) for x in os.environ.get("VISION_ALERTS_UNCAPPED_TEAM_IDS", "").split(",") if (t := x.strip()).isdigit()
+)
+
+_SENTINEL: Final = object()
+
+
+def _any_field_changed(instance: VisionAlertConfiguration, validated_data: dict, fields: set[str]) -> bool:
+ return any(f in validated_data and validated_data[f] != getattr(instance, f) for f in fields)
+
+
+@extend_schema_field(AlertScheduleRestriction) # type: ignore[arg-type]
+class ScheduleRestrictionField(serializers.JSONField):
+ pass
+
+
+class VisionAlertSelectionSerializer(serializers.Serializer):
+ verdict = serializers.ListField(
+ child=serializers.CharField(max_length=100),
+ max_length=10,
+ required=False,
+ help_text="Monitor verdicts to match, e.g. ['yes'].",
+ )
+ tags = serializers.ListField(
+ child=serializers.CharField(max_length=200),
+ max_length=20,
+ required=False,
+ help_text="Classifier tags to match; an observation matches when it carries any of them.",
+ )
+ min_score = serializers.FloatField(
+ required=False,
+ help_text="Minimum scorer score (inclusive).",
+ )
+ max_score = serializers.FloatField(
+ required=False,
+ help_text="Maximum scorer score (inclusive).",
+ )
+
+
+class VisionAlertConfigurationSerializer(serializers.ModelSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier for this alert.")
+ scanner_id = TeamScopedPrimaryKeyRelatedField(
+ source="scanner",
+ queryset=ReplayScanner.objects.all(),
+ help_text="Scanner whose observations this alert watches. Immutable after creation.",
+ )
+ name = serializers.CharField(
+ max_length=255,
+ required=False,
+ allow_blank=True,
+ default="Untitled alert",
+ help_text="Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted.",
+ )
+ enabled = serializers.BooleanField(
+ default=True,
+ help_text="Whether the alert is active. Disabling a metric alert resets its state to not_firing.",
+ )
+ kind = serializers.ChoiceField(
+ choices=VisionAlertKind.choices,
+ help_text="'metric' fires when a metric crosses a threshold over a rolling window; "
+ "'match' fires on every observation that matches the selection. Immutable after creation.",
+ )
+ selection = VisionAlertSelectionSerializer(
+ required=False,
+ help_text="Which observations count. Empty matches every observation of the scanner.",
+ )
+ metric = serializers.ChoiceField(
+ choices=VisionAlertMetric.choices,
+ default=VisionAlertMetric.COUNT,
+ help_text="Metric alerts only: what to measure over the window. 'avg_score' requires a scorer scanner.",
+ )
+ direction = serializers.ChoiceField(
+ choices=VisionAlertDirection.choices,
+ default=VisionAlertDirection.ABOVE,
+ help_text="Metric alerts only: whether the alert fires at or above, or at or below, the threshold.",
+ )
+ threshold = serializers.FloatField(
+ required=False,
+ allow_null=True,
+ help_text="Metric alerts only: the threshold value. Required for metric alerts, must be omitted for match alerts.",
+ )
+ window_days = serializers.IntegerField(
+ default=1,
+ help_text=f"Metric alerts only: rolling window in days. Allowed values: {list(ALERT_WINDOW_DAYS)}.",
+ )
+ check_interval_minutes = serializers.IntegerField(
+ default=60,
+ min_value=MIN_CHECK_INTERVAL_MINUTES,
+ help_text=f"Metric alerts only: evaluation cadence in minutes, at least {MIN_CHECK_INTERVAL_MINUTES}.",
+ )
+ state = serializers.ChoiceField(
+ choices=VisionAlertState.choices,
+ read_only=True,
+ help_text="Current lifecycle state. Always not_firing for match alerts. Server-managed.",
+ )
+ evaluation_periods = serializers.IntegerField(
+ default=1,
+ min_value=1,
+ max_value=10,
+ help_text="Metric alerts only: total check periods in the sliding evaluation window (M in N-of-M).",
+ )
+ datapoints_to_alarm = serializers.IntegerField(
+ default=1,
+ min_value=1,
+ max_value=10,
+ help_text="Metric alerts only: how many periods must breach to fire (N in N-of-M).",
+ )
+ cooldown_minutes = serializers.IntegerField(
+ default=0,
+ min_value=0,
+ help_text="Metric alerts only: minimum minutes between repeated notifications. 0 means no cooldown.",
+ )
+ schedule_restriction = ScheduleRestrictionField(
+ required=False,
+ allow_null=True,
+ help_text="Blocked local time windows when the alert must not notify. Times use the project timezone. Null disables quiet hours.",
+ )
+ snooze_until = serializers.DateTimeField(
+ required=False,
+ allow_null=True,
+ help_text="ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.",
+ )
+ next_check_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the next evaluation is scheduled. Server-managed."
+ )
+ last_notified_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the last notification was sent. Server-managed."
+ )
+ last_checked_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the alert was last evaluated. Server-managed."
+ )
+ consecutive_failures = serializers.IntegerField(
+ read_only=True, help_text="Consecutive evaluation failures. Resets on success. Server-managed."
+ )
+ first_enabled_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the alert was first enabled. Null means still a draft."
+ )
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the alert was created.")
+ created_by = UserBasicSerializer(read_only=True)
+ updated_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the alert was last modified."
+ )
+
+ class Meta:
+ model = VisionAlertConfiguration
+ fields = [
+ "id",
+ "scanner_id",
+ "name",
+ "enabled",
+ "kind",
+ "selection",
+ "metric",
+ "direction",
+ "threshold",
+ "window_days",
+ "check_interval_minutes",
+ "state",
+ "evaluation_periods",
+ "datapoints_to_alarm",
+ "cooldown_minutes",
+ "schedule_restriction",
+ "snooze_until",
+ "next_check_at",
+ "last_notified_at",
+ "last_checked_at",
+ "consecutive_failures",
+ "first_enabled_at",
+ "created_at",
+ "created_by",
+ "updated_at",
+ ]
+
+ def validate_name(self, value: str) -> str:
+ return value.strip() or "Untitled alert"
+
+ def validate(self, attrs: dict) -> dict:
+ instance = self.instance
+ kind = attrs.get("kind", getattr(instance, "kind", None))
+
+ if instance is not None:
+ if "kind" in attrs and attrs["kind"] != instance.kind:
+ raise ValidationError({"kind": "Cannot change the kind of an existing alert."})
+ if "scanner" in attrs and attrs["scanner"].id != instance.scanner_id:
+ raise ValidationError({"scanner_id": "Cannot move an alert to a different scanner."})
+
+ name = attrs.get("name", getattr(instance, "name", None))
+ if name:
+ existing = VisionAlertConfiguration.objects.for_team(self.context["team_id"]).filter(name=name)
+ if instance is not None:
+ existing = existing.exclude(id=instance.id)
+ if existing.exists():
+ raise ValidationError({"name": "An alert with this name already exists."})
+
+ view = self.context.get("view")
+ scanner_for_access = attrs.get("scanner") if instance is None else getattr(instance, "scanner", None)
+ if view is not None and scanner_for_access is not None:
+ # Alerts inherit access from their scanner; a per-scanner grant must gate them.
+ if not view.user_access_control.check_access_level_for_object(scanner_for_access, "editor"):
+ raise PermissionDenied("You don't have access to this scanner.")
+
+ if kind == VisionAlertKind.METRIC:
+ threshold = attrs.get("threshold", getattr(instance, "threshold", None))
+ if threshold is None:
+ raise ValidationError({"threshold": "Metric alerts require a threshold."})
+ window = attrs.get("window_days", getattr(instance, "window_days", 1))
+ if window not in ALERT_WINDOW_DAYS:
+ raise ValidationError({"window_days": f"Must be one of {list(ALERT_WINDOW_DAYS)}."})
+ metric = attrs.get("metric", getattr(instance, "metric", VisionAlertMetric.COUNT))
+ scanner = attrs.get("scanner", getattr(instance, "scanner", None))
+ if metric == VisionAlertMetric.AVG_SCORE and scanner is not None:
+ if scanner.scanner_type != ScannerType.SCORER:
+ raise ValidationError({"metric": "avg_score is only available on scorer scanners."})
+ else:
+ if attrs.get("threshold") is not None:
+ raise ValidationError({"threshold": "Match alerts do not take a threshold."})
+ metric_only = (
+ "metric",
+ "direction",
+ "window_days",
+ "check_interval_minutes",
+ "evaluation_periods",
+ "datapoints_to_alarm",
+ "cooldown_minutes",
+ )
+ provided = [f for f in metric_only if f in (self.initial_data or {})]
+ if provided:
+ raise ValidationError({provided[0]: "Only metric alerts take this field."})
+
+ evaluation_periods = attrs.get("evaluation_periods", getattr(instance, "evaluation_periods", 1))
+ datapoints_to_alarm = attrs.get("datapoints_to_alarm", getattr(instance, "datapoints_to_alarm", 1))
+ if datapoints_to_alarm > evaluation_periods:
+ raise ValidationError({"datapoints_to_alarm": "Cannot exceed evaluation_periods."})
+
+ snooze_until = attrs.get("snooze_until")
+ if snooze_until is not None and snooze_until <= datetime.now(UTC):
+ raise ValidationError({"snooze_until": "Must be a future datetime."})
+
+ if "schedule_restriction" in attrs:
+ try:
+ attrs["schedule_restriction"] = validate_and_normalize_schedule_restriction(
+ attrs["schedule_restriction"]
+ )
+ except ValueError as e:
+ raise ValidationError({"schedule_restriction": str(e)}) from e
+
+ return attrs
+
+ def update(self, instance: VisionAlertConfiguration, validated_data: dict) -> VisionAlertConfiguration:
+ snooze_data = validated_data.pop("snooze_until", _SENTINEL)
+
+ threshold_fields = {
+ "threshold",
+ "direction",
+ "metric",
+ "selection",
+ "datapoints_to_alarm",
+ "evaluation_periods",
+ }
+ threshold_changed = _any_field_changed(instance, validated_data, threshold_fields)
+ window_changed = _any_field_changed(instance, validated_data, {"window_days", "check_interval_minutes"})
+ schedule_restriction_changed = _any_field_changed(instance, validated_data, {"schedule_restriction"})
+
+ enabled_change: bool | None = None
+ if "enabled" in validated_data and validated_data["enabled"] != instance.enabled:
+ enabled_change = validated_data["enabled"]
+
+ # One transaction wraps the state-machine transition, its VisionAlertEvent audit
+ # row, and the save, so a failure can't orphan either side.
+ with transaction.atomic():
+ # Priority order: enable/disable wins over snooze, which wins over
+ # threshold/selection changes. apply_outcome is the single writer of
+ # state/consecutive_failures; match alerts route through it too so control-plane
+ # actions land in the audit trail (their outcomes always resolve to not_firing).
+ snapshot = instance.to_snapshot()
+ if enabled_change is True:
+ if instance.first_enabled_at is None:
+ validated_data.setdefault("first_enabled_at", timezone.now())
+ apply_outcome(instance, apply_enable(snapshot), kind=VisionAlertEvent.Kind.ENABLE)
+ elif enabled_change is False:
+ apply_outcome(instance, apply_disable(snapshot), kind=VisionAlertEvent.Kind.DISABLE)
+ elif snooze_data is not _SENTINEL:
+ snooze_kind = VisionAlertEvent.Kind.UNSNOOZE if snooze_data is None else VisionAlertEvent.Kind.SNOOZE
+ if instance.kind == VisionAlertKind.MATCH:
+ # Match alerts are stateless (DB-enforced); the drain honors snooze_until directly.
+ VisionAlertEvent.objects.create(
+ alert=instance,
+ kind=snooze_kind,
+ threshold_breached=False,
+ state_before=instance.state,
+ state_after=instance.state,
+ )
+ elif snooze_data is None:
+ apply_outcome(instance, apply_unsnooze(snapshot), kind=snooze_kind)
+ else:
+ apply_outcome(instance, apply_snooze(snapshot), kind=snooze_kind)
+ elif threshold_changed:
+ apply_outcome(instance, apply_threshold_change(snapshot), kind=VisionAlertEvent.Kind.THRESHOLD_CHANGE)
+
+ if snooze_data is not _SENTINEL:
+ instance.snooze_until = snooze_data
+
+ if instance.kind == VisionAlertKind.METRIC and (
+ threshold_changed
+ or window_changed
+ or schedule_restriction_changed
+ or (enabled_change is True and instance.schedule_restriction)
+ ):
+ next_schedule_restriction = validated_data.get("schedule_restriction", instance.schedule_restriction)
+ if next_schedule_restriction:
+ validated_data["next_check_at"] = next_allowed_check_at(
+ datetime.now(UTC),
+ team_timezone=instance.team.timezone,
+ schedule_restriction=next_schedule_restriction,
+ )
+ else:
+ instance.clear_next_check()
+
+ return super().update(instance, validated_data)
+
+ def create(self, validated_data: dict) -> VisionAlertConfiguration:
+ validated_data["team_id"] = self.context["team_id"]
+ validated_data["created_by"] = self.context["request"].user
+
+ if validated_data.get("enabled", True):
+ validated_data["first_enabled_at"] = timezone.now()
+
+ with transaction.atomic():
+ # Locking the team row serialises concurrent creates for this team so the
+ # per-team cap can't be raced past.
+ team = Team.objects.select_for_update().get(id=validated_data["team_id"])
+ if validated_data["team_id"] not in UNCAPPED_ALERT_TEAM_IDS:
+ count = VisionAlertConfiguration.objects.for_team(validated_data["team_id"]).count()
+ if count >= MAX_ALERTS_PER_TEAM:
+ raise ValidationError(f"Maximum number of alerts ({MAX_ALERTS_PER_TEAM}) reached for this team.")
+ # The drain, not the scheduler, drives match alerts; only metric alerts get a schedule.
+ if validated_data.get("kind") != VisionAlertKind.MATCH and (
+ schedule_restriction := validated_data.get("schedule_restriction")
+ ):
+ validated_data["next_check_at"] = next_allowed_check_at(
+ datetime.now(UTC),
+ team_timezone=team.timezone,
+ schedule_restriction=schedule_restriction,
+ )
+ return super().create(validated_data)
+
+
+class VisionAlertEventSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = VisionAlertEvent
+ fields = [
+ "id",
+ "created_at",
+ "kind",
+ "state_before",
+ "state_after",
+ "threshold_breached",
+ "metric_value",
+ "error_message",
+ ]
+ read_only_fields = fields
+
+
+class VisionAlertListQuerySerializer(serializers.Serializer):
+ scanner_id = serializers.UUIDField(
+ required=False,
+ help_text="Only return alerts on this scanner.",
+ )
+
+
+class VisionAlertCreateDestinationSerializer(serializers.Serializer):
+ type = serializers.ChoiceField(choices=VISION_DESTINATION_TYPES, help_text="Notification destination type.")
+ slack_workspace_id = serializers.IntegerField(
+ required=False, help_text="Integration ID for the Slack workspace. Required when type=slack."
+ )
+ slack_channel_id = serializers.CharField(required=False, help_text="Slack channel ID. Required when type=slack.")
+ slack_channel_name = serializers.CharField(
+ required=False, allow_blank=True, help_text="Human-readable channel name for display."
+ )
+ webhook_url = serializers.URLField(
+ required=False, help_text="HTTPS endpoint to post to. Required when type=webhook."
+ )
+
+ def validate_webhook_url(self, value: str) -> str:
+ if not value.startswith("https://"):
+ raise ValidationError("Webhook URLs must use https.")
+ return value
+
+ def validate(self, attrs: dict) -> dict:
+ data = cast(AlertDestinationData, attrs)
+ data["type"] = DestinationType(attrs["type"])
+ try:
+ validate_destination_data(data, allowed_destination_types=VISION_DESTINATION_TYPES)
+ except AlertDestinationValidationError as error:
+ if error.field:
+ raise ValidationError({error.field: error.message})
+ raise ValidationError(error.message)
+ return attrs
+
+
+class VisionAlertDeleteDestinationSerializer(serializers.Serializer):
+ hog_function_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ min_length=1,
+ max_length=len(VISION_ALERT_EVENT_IDS),
+ help_text="HogFunction IDs to delete as one atomic destination group.",
+ )
+
+
+class VisionAlertDestinationResponseSerializer(serializers.Serializer):
+ hog_function_ids = serializers.ListField(
+ child=serializers.UUIDField(), help_text="HogFunctions backing the created destination, one per event kind."
+ )
+
+
+class VisionAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ scope_object = "vision_alert"
+ scope_object_read_actions = ["list", "retrieve", "events"]
+ scope_object_write_actions = [
+ "create",
+ "update",
+ "partial_update",
+ "destroy",
+ "create_destination",
+ "delete_destination",
+ "reset",
+ ]
+ # `objects` is fail-closed; `safely_get_queryset` re-scopes to the request team.
+ queryset = VisionAlertConfiguration.objects.unscoped().order_by("-created_at")
+ serializer_class = VisionAlertConfigurationSerializer
+ lookup_field = "id"
+
+ # Configuring an alert or its destinations routes recording-derived content off-platform,
+ # so it needs the same session-recording read gate as vision actions.
+ _CONFIG_ACTIONS = {"create", "update", "partial_update", "create_destination"}
+
+ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:
+ if self.action in self._CONFIG_ACTIONS:
+ return ["vision_alert:write", "session_recording:read"]
+ return None
+
+ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:
+ super().initial(request, *args, **kwargs)
+ if self.action in self._CONFIG_ACTIONS and not self.user_access_control.check_access_level_for_resource(
+ "session_recording", required_level="viewer"
+ ):
+ raise PermissionDenied("Configuring a Replay Vision alert requires session_recording read access.")
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ if self.action == "list":
+ query_serializer = VisionAlertListQuerySerializer(data=self.request.query_params)
+ query_serializer.is_valid(raise_exception=True)
+ scanner_id = query_serializer.validated_data.get("scanner_id")
+ if scanner_id:
+ queryset = queryset.filter(scanner_id=scanner_id)
+ # Alerts carry no object-level rows of their own; a scanner-level restriction
+ # must hide that scanner's alerts from the list.
+ accessible_scanners = self.user_access_control.filter_queryset_by_access_level(
+ ReplayScanner.objects.filter(team_id=self.team_id)
+ )
+ queryset = queryset.filter(scanner_id__in=accessible_scanners.values_list("id", flat=True))
+ return queryset.filter(team_id=self.team_id).select_related("created_by", "scanner")
+
+ def safely_get_object(self, queryset: QuerySet) -> VisionAlertConfiguration:
+ alert = get_object_or_404(
+ queryset, **{self.lookup_field: self.kwargs[self.lookup_url_kwarg or self.lookup_field]}
+ )
+ self._check_scanner_access(alert)
+ return alert
+
+ def _check_scanner_access(self, alert: VisionAlertConfiguration) -> None:
+ # Object-level access rows live on the scanner, not the alert; the generic
+ # object check cannot see them, so check the scanner explicitly.
+ self.check_object_permissions(self.request, alert.scanner)
+
+ def _get_locked_alert(self) -> VisionAlertConfiguration:
+ # No select_related here: FOR UPDATE rejects the outer join a nullable created_by adds.
+ queryset = VisionAlertConfiguration.objects.for_team(self.team_id).select_for_update()
+ lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
+ alert = get_object_or_404(queryset, **{self.lookup_field: self.kwargs[lookup_url_kwarg]})
+ self.check_object_permissions(self.request, alert)
+ self._check_scanner_access(alert)
+ return alert
+
+ def update(self, request: Request, *args: object, **kwargs: Any) -> Response:
+ partial = kwargs.pop("partial", False)
+ with transaction.atomic():
+ instance = self._get_locked_alert()
+ serializer = self.get_serializer(instance, data=request.data, partial=partial)
+ serializer.is_valid(raise_exception=True)
+ self.perform_update(serializer)
+ return Response(serializer.data)
+
+ def _event_kinds_for(self, alert: VisionAlertConfiguration) -> tuple[EventKind, ...]:
+ return MATCH_EVENT_KINDS if alert.kind == VisionAlertKind.MATCH else METRIC_EVENT_KINDS
+
+ @extend_schema(
+ request=VisionAlertCreateDestinationSerializer,
+ responses={201: VisionAlertDestinationResponseSerializer},
+ description="Create a notification destination for this alert. One HogFunction is created per alert event kind atomically.",
+ )
+ @action(detail=True, methods=["POST"], url_path="destinations", required_scopes=["vision_alert:write"])
+ def create_destination(self, request: Request, *args: object, **kwargs: object) -> Response:
+ serializer = VisionAlertCreateDestinationSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = cast(AlertDestinationData, serializer.validated_data)
+
+ with transaction.atomic():
+ alert = self._get_locked_alert()
+ existing = count_active_alert_destinations(
+ team_id=self.team_id, alert_id=str(alert.id), allowed_event_ids=VISION_ALERT_EVENT_IDS
+ )
+ event_kinds = self._event_kinds_for(alert)
+ if existing + len(event_kinds) > MAX_DESTINATIONS_PER_ALERT * len(event_kinds):
+ raise ValidationError(
+ f"Maximum number of destinations ({MAX_DESTINATIONS_PER_ALERT}) reached for this alert."
+ )
+ configs = [
+ build_alert_destination_config(
+ team=alert.team,
+ spec=EVENT_KIND_CONFIG[kind],
+ alert_id=str(alert.id),
+ alert_name=alert.name,
+ data=data,
+ slack_context_elements=VISION_ALERT_SLACK_CONTEXT_ELEMENTS,
+ )
+ for kind in event_kinds
+ ]
+ hog_functions = create_alert_destination_hog_functions(
+ configs,
+ request=self.request,
+ alert_id=str(alert.id),
+ allowed_event_ids=VISION_ALERT_EVENT_IDS,
+ )
+
+ report_user_action(
+ request.user,
+ "replay vision alert destination created",
+ {"alert_id": str(alert.id), "type": data["type"], "event_kinds": list(event_kinds)},
+ request=request,
+ )
+ response = VisionAlertDestinationResponseSerializer({"hog_function_ids": [hf.id for hf in hog_functions]})
+ return Response(response.data, status=201)
+
+ @extend_schema(
+ request=VisionAlertDeleteDestinationSerializer,
+ responses={204: None},
+ description="Delete a notification destination by deleting its HogFunction group atomically.",
+ )
+ @action(detail=True, methods=["POST"], url_path="destinations/delete", required_scopes=["vision_alert:write"])
+ def delete_destination(self, request: Request, *args: object, **kwargs: object) -> Response:
+ serializer = VisionAlertDeleteDestinationSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ hog_function_ids = serializer.validated_data["hog_function_ids"]
+
+ with transaction.atomic():
+ alert = self._get_locked_alert()
+ soft_delete_alert_destinations(
+ team_id=self.team_id,
+ alert_id=str(alert.id),
+ allowed_event_ids=VISION_ALERT_EVENT_IDS,
+ hog_function_ids=hog_function_ids,
+ )
+
+ report_user_action(
+ request.user,
+ "replay vision alert destination deleted",
+ {"alert_id": str(alert.id), "count": len(hog_function_ids)},
+ request=request,
+ )
+ return Response(status=204)
+
+ @extend_schema(
+ request=None,
+ parameters=[
+ OpenApiParameter(
+ name="kind",
+ type=str,
+ enum=VisionAlertEvent.Kind.values,
+ required=False,
+ description="Narrow the history to one event kind.",
+ )
+ ],
+ responses={200: VisionAlertEventSerializer(many=True)},
+ description=(
+ "Paginated event history for this alert, newest first. Quiet no-op check rows "
+ "(no state change, no error) are filtered out. Optional `?kind=...` narrows to one kind."
+ ),
+ )
+ @action(detail=True, methods=["GET"], url_path="events", required_scopes=["vision_alert:read"])
+ def events(self, request: Request, *args: object, **kwargs: object) -> Response:
+ alert = self.get_object()
+ queryset = (
+ VisionAlertEvent.objects.filter(alert=alert)
+ .filter(
+ ~Q(kind=VisionAlertEvent.Kind.CHECK)
+ | Q(error_message__isnull=False)
+ | ~Q(state_before=F("state_after"))
+ )
+ .order_by("-created_at")
+ )
+
+ kind = request.query_params.get("kind")
+ if kind is not None:
+ valid_kinds = VisionAlertEvent.Kind.values
+ if kind not in valid_kinds:
+ raise ValidationError({"kind": f"Must be one of {sorted(valid_kinds)}."})
+ queryset = queryset.filter(kind=kind)
+
+ page = self.paginate_queryset(queryset)
+ if page is not None:
+ serializer = VisionAlertEventSerializer(page, many=True)
+ return self.get_paginated_response(serializer.data)
+
+ serializer = VisionAlertEventSerializer(queryset, many=True)
+ return Response(serializer.data)
+
+ @extend_schema(
+ request=None,
+ responses={200: VisionAlertConfigurationSerializer},
+ description="Reset a broken alert. Clears the consecutive-failure counter and schedules an immediate recheck.",
+ )
+ @action(detail=True, methods=["POST"], url_path="reset", required_scopes=["vision_alert:write"])
+ def reset(self, request: Request, *args: object, **kwargs: object) -> Response:
+ with transaction.atomic():
+ alert = self._get_locked_alert()
+ try:
+ outcome = apply_user_reset(alert.to_snapshot())
+ except InvalidTransition:
+ raise ValidationError({"state": "Only broken alerts can be reset."})
+ update_fields = apply_outcome(alert, outcome, kind=VisionAlertEvent.Kind.RESET)
+ update_fields.extend(alert.clear_next_check())
+ alert.save(update_fields=update_fields)
+ report_user_action(request.user, "replay vision alert reset", {"alert_id": str(alert.id)}, request=request)
+ serializer = self.get_serializer(alert)
+ return Response(serializer.data)
+
+ def destroy(self, request: Request, *args: object, **kwargs: Any) -> Response:
+ # The lock serialises against create_destination, which would otherwise insert
+ # HogFunctions after the cleanup pass and orphan them.
+ with transaction.atomic():
+ instance = self._get_locked_alert()
+ self.perform_destroy(instance)
+ return Response(status=204)
+
+ def perform_destroy(self, instance: VisionAlertConfiguration) -> None:
+ soft_delete_all_alert_destinations(
+ team_id=self.team_id,
+ alert_id=str(instance.id),
+ allowed_event_ids=VISION_ALERT_EVENT_IDS,
+ )
+ instance.delete()
diff --git a/products/replay_vision/backend/migrations/0083_visionalertconfiguration_visionalertevent_and_more.py b/products/replay_vision/backend/migrations/0083_visionalertconfiguration_visionalertevent_and_more.py
new file mode 100644
index 000000000000..a43613dc3f14
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0083_visionalertconfiguration_visionalertevent_and_more.py
@@ -0,0 +1,291 @@
+# Generated by Django 5.2.17 on 2026-08-25 21:54
+
+import django.db.models.manager
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1319_team_posthog_team_widget_token_idx"),
+ ("replay_vision", "0082_admission_budget_cache"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="VisionAlertConfiguration",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(max_length=255)),
+ ("enabled", models.BooleanField(default=True)),
+ (
+ "kind",
+ models.CharField(
+ choices=[("metric", "Metric"), ("match", "Match")],
+ max_length=10,
+ ),
+ ),
+ (
+ "selection",
+ models.JSONField(
+ default=dict,
+ help_text="Observation filter over succeeded scans: verdict (list[str]), tags (list[str]), min_score/max_score (float).",
+ ),
+ ),
+ (
+ "metric",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("count", "Count matching observations"),
+ ("avg_score", "Average score"),
+ ],
+ default="count",
+ max_length=20,
+ ),
+ ),
+ (
+ "direction",
+ models.CharField(
+ blank=True,
+ choices=[("above", "At or above"), ("below", "At or below")],
+ default="above",
+ max_length=10,
+ ),
+ ),
+ ("threshold", models.FloatField(blank=True, null=True)),
+ ("window_days", models.PositiveSmallIntegerField(default=1)),
+ ("check_interval_minutes", models.PositiveIntegerField(default=60)),
+ (
+ "state",
+ models.CharField(
+ choices=[
+ ("not_firing", "Not firing"),
+ ("firing", "Firing"),
+ ("pending_resolve", "Pending resolve"),
+ ("errored", "Errored"),
+ ("snoozed", "Snoozed"),
+ ("broken", "Broken"),
+ ],
+ default="not_firing",
+ max_length=20,
+ ),
+ ),
+ ("consecutive_failures", models.PositiveIntegerField(default=0)),
+ ("last_notified_at", models.DateTimeField(blank=True, null=True)),
+ ("last_checked_at", models.DateTimeField(blank=True, null=True)),
+ ("first_enabled_at", models.DateTimeField(blank=True, null=True)),
+ ("snooze_until", models.DateTimeField(blank=True, null=True)),
+ ("next_check_at", models.DateTimeField(blank=True, null=True)),
+ ("evaluation_periods", models.PositiveSmallIntegerField(default=1)),
+ ("datapoints_to_alarm", models.PositiveSmallIntegerField(default=1)),
+ ("cooldown_minutes", models.PositiveIntegerField(default=0)),
+ (
+ "schedule_restriction",
+ models.JSONField(blank=True, default=None, null=True),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "scanner",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="alerts",
+ to="replay_vision.replayscanner",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="VisionAlertEvent",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "kind",
+ models.CharField(
+ choices=[
+ ("check", "Check"),
+ ("reset", "Reset"),
+ ("enable", "Enable"),
+ ("disable", "Disable"),
+ ("snooze", "Snooze"),
+ ("unsnooze", "Unsnooze"),
+ ("threshold_change", "Threshold change"),
+ ],
+ default="check",
+ max_length=20,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("metric_value", models.FloatField(blank=True, null=True)),
+ ("threshold_breached", models.BooleanField(default=False)),
+ ("state_before", models.CharField(max_length=20)),
+ ("state_after", models.CharField(max_length=20)),
+ ("error_message", models.TextField(blank=True, null=True)),
+ (
+ "alert",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="events",
+ to="replay_vision.visionalertconfiguration",
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="VisionAlertMatch",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("delivered_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "alert",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="matches",
+ to="replay_vision.visionalertconfiguration",
+ ),
+ ),
+ (
+ "observation",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="replay_vision.replayobservation",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.AddIndex(
+ model_name="visionalertconfiguration",
+ index=models.Index(
+ condition=models.Q(("enabled", True), ("kind", "metric")),
+ fields=["next_check_at"],
+ name="vision_alert_scheduler_idx",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="visionalertconfiguration",
+ index=models.Index(
+ fields=["team", "scanner", "kind", "enabled"],
+ name="vision_alert_hook_idx",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="visionalertconfiguration",
+ constraint=models.UniqueConstraint(fields=("team", "name"), name="vision_alert_unique_team_name"),
+ ),
+ migrations.AddConstraint(
+ model_name="visionalertconfiguration",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("kind", "metric"),
+ models.Q(
+ ("state", "not_firing"),
+ ("consecutive_failures", 0),
+ ("next_check_at__isnull", True),
+ ),
+ _connector="OR",
+ ),
+ name="vision_alert_match_kind_stateless",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="visionalertconfiguration",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ models.Q(("kind", "metric"), ("threshold__isnull", False)),
+ models.Q(("kind", "match"), ("threshold__isnull", True)),
+ _connector="OR",
+ ),
+ name="vision_alert_metric_kind_threshold",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="visionalertevent",
+ index=models.Index(fields=["alert", "-created_at"], name="vision_alert_evt_alert_ts_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="visionalertevent",
+ index=models.Index(fields=["created_at"], name="vision_alert_evt_created_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="visionalertmatch",
+ index=models.Index(
+ condition=models.Q(("delivered_at__isnull", True)),
+ fields=["alert", "created_at"],
+ name="vision_alert_match_drain_idx",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="visionalertmatch",
+ index=models.Index(fields=["delivered_at"], name="vision_alert_match_cleanup_idx"),
+ ),
+ migrations.AddConstraint(
+ model_name="visionalertmatch",
+ constraint=models.UniqueConstraint(fields=("alert", "observation"), name="vision_alert_match_unique"),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0084_observation_window_index.py b/products/replay_vision/backend/migrations/0084_observation_window_index.py
new file mode 100644
index 000000000000..f1b02077c70e
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0084_observation_window_index.py
@@ -0,0 +1,23 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # CONCURRENTLY cannot run inside a transaction; replay_observation is large in production.
+ atomic = False
+
+ dependencies = [
+ ("replay_vision", "0083_visionalertconfiguration_visionalertevent_and_more"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="replayobservation",
+ index=models.Index(
+ condition=models.Q(("status", "succeeded")),
+ fields=["scanner", "completed_at"],
+ name="rlo_scanner_completed_idx",
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 8c83bc2c0c8a..81147e75c315 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0082_admission_budget_cache
+0084_observation_window_index
diff --git a/products/replay_vision/backend/models/__init__.py b/products/replay_vision/backend/models/__init__.py
index b006ccce8b63..cda0bb8ba8a9 100644
--- a/products/replay_vision/backend/models/__init__.py
+++ b/products/replay_vision/backend/models/__init__.py
@@ -5,6 +5,11 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.models.replay_scanner_backfill import ReplayScannerBackfill
from products.replay_vision.backend.models.replay_scanner_prompt_suggestion import ReplayScannerPromptSuggestion
from products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun
+from products.replay_vision.backend.models.vision_alert import (
+ VisionAlertConfiguration as VisionAlertConfiguration,
+ VisionAlertEvent as VisionAlertEvent,
+ VisionAlertMatch as VisionAlertMatch,
+)
__all__ = [
"ReplayObservation",
diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.py
index a9f6b39abf53..c1c5b079674a 100644
--- a/products/replay_vision/backend/models/replay_observation.py
+++ b/products/replay_vision/backend/models/replay_observation.py
@@ -131,6 +131,13 @@ class ReplayObservation(UUIDModel):
indexes = [
models.Index(fields=["team", "created_at"], name="rlo_team_created_idx"),
models.Index(fields=["scanner", "status"], name="rlo_scanner_status_idx"),
+ # Serves the alert-engine observation window: succeeded rows per scanner in a
+ # completed_at range. Partial: terminal succeeded rows are the only ones scanned.
+ models.Index(
+ fields=["scanner", "completed_at"],
+ name="rlo_scanner_completed_idx",
+ condition=models.Q(status="succeeded"),
+ ),
# Serves the per-scanner list ordering and the prev/next-neighbor lookups (both order by created_at).
models.Index(fields=["scanner", "created_at"], name="rlo_scanner_created_idx"),
models.Index(
diff --git a/products/replay_vision/backend/models/vision_alert.py b/products/replay_vision/backend/models/vision_alert.py
new file mode 100644
index 000000000000..9565087d60d1
--- /dev/null
+++ b/products/replay_vision/backend/models/vision_alert.py
@@ -0,0 +1,243 @@
+from typing import TYPE_CHECKING
+
+from django.core.exceptions import ValidationError
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+if TYPE_CHECKING:
+ from products.replay_vision.backend.alert_state_machine import AlertSnapshot
+
+ALERT_WINDOW_DAYS = (1, 3, 7, 14, 30)
+# Selection keys that read scanner_result; failed observations never have one.
+PREDICATE_SELECTION_KEYS = ("verdict", "tags", "min_score", "max_score")
+DEFAULT_ALERT_WINDOW_DAYS = 1
+MIN_CHECK_INTERVAL_MINUTES = 15
+DEFAULT_CHECK_INTERVAL_MINUTES = 60
+EVENT_RETENTION_DAYS = 90
+# Undelivered outbox rows normally drain within a minute; rows this old belong to
+# alerts that were disabled or deleted between insert and drain.
+STALE_MATCH_RETENTION_DAYS = 30
+DELIVERED_MATCH_RETENTION_DAYS = 14
+
+
+class VisionAlertKind(models.TextChoices):
+ # Threshold over a rolling window; carries lifecycle state (firing, snoozed, ...).
+ METRIC = "metric", "Metric"
+ # Fires once per matching observation via the VisionAlertMatch outbox; stateless.
+ MATCH = "match", "Match"
+
+
+class VisionAlertState(models.TextChoices):
+ NOT_FIRING = "not_firing", "Not firing"
+ FIRING = "firing", "Firing"
+ PENDING_RESOLVE = "pending_resolve", "Pending resolve"
+ ERRORED = "errored", "Errored"
+ SNOOZED = "snoozed", "Snoozed"
+ BROKEN = "broken", "Broken"
+
+
+class VisionAlertMetric(models.TextChoices):
+ COUNT = "count", "Count matching observations"
+ AVG_SCORE = "avg_score", "Average score" # scorer scanners only
+
+
+class VisionAlertDirection(models.TextChoices):
+ # Which side of the threshold breaches. Both bounds inclusive.
+ ABOVE = "above", "At or above"
+ BELOW = "below", "At or below"
+
+
+class VisionAlertConfiguration(TeamScopedRootMixin, UUIDModel):
+ """One alert on a scanner's observations, on the shared alerts platform.
+
+ Metric alerts evaluate a rolling window on a cadence and own lifecycle state; every
+ state/consecutive_failures write must go through `alert_state_machine.apply_outcome`
+ (enforced by semgrep). Match alerts never leave NOT_FIRING: their delivery is driven
+ by undelivered VisionAlertMatch rows, not by scheduling columns.
+ """
+
+ all_teams = models.Manager() # noqa: DJ012 — escape hatch for cross-team Temporal access
+
+ scanner = models.ForeignKey("replay_vision.ReplayScanner", on_delete=models.CASCADE, related_name="alerts")
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+
+ name = models.CharField(max_length=255)
+ enabled = models.BooleanField(default=True)
+ kind = models.CharField(max_length=10, choices=VisionAlertKind.choices)
+
+ selection = models.JSONField(
+ default=dict,
+ help_text="Observation filter over succeeded scans: verdict (list[str]), tags (list[str]), min_score/max_score (float).",
+ )
+
+ # Metric-kind condition; null/defaults for match kind (enforced by constraints below).
+ metric = models.CharField(
+ max_length=20, choices=VisionAlertMetric.choices, default=VisionAlertMetric.COUNT, blank=True
+ )
+ direction = models.CharField(
+ max_length=10, choices=VisionAlertDirection.choices, default=VisionAlertDirection.ABOVE, blank=True
+ )
+ threshold = models.FloatField(null=True, blank=True)
+ window_days = models.PositiveSmallIntegerField(default=DEFAULT_ALERT_WINDOW_DAYS)
+ check_interval_minutes = models.PositiveIntegerField(default=DEFAULT_CHECK_INTERVAL_MINUTES)
+
+ # Lifecycle (metric kind only). Writes go through alert_state_machine.apply_outcome.
+ state = models.CharField(max_length=20, choices=VisionAlertState.choices, default=VisionAlertState.NOT_FIRING)
+ consecutive_failures = models.PositiveIntegerField(default=0)
+ last_notified_at = models.DateTimeField(null=True, blank=True)
+ last_checked_at = models.DateTimeField(null=True, blank=True)
+ first_enabled_at = models.DateTimeField(null=True, blank=True)
+ snooze_until = models.DateTimeField(null=True, blank=True)
+ next_check_at = models.DateTimeField(null=True, blank=True)
+
+ # Advanced options (metric kind): N-of-M sliding window, cooldown, quiet hours.
+ evaluation_periods = models.PositiveSmallIntegerField(default=1)
+ datapoints_to_alarm = models.PositiveSmallIntegerField(default=1)
+ cooldown_minutes = models.PositiveIntegerField(default=0)
+ schedule_restriction = models.JSONField(null=True, blank=True, default=None)
+
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["team", "name"], name="vision_alert_unique_team_name"),
+ # Match alerts are stateless: a lifecycle write on one is a bug that must fail
+ # loudly instead of confusing the metric evaluator.
+ models.CheckConstraint(
+ condition=models.Q(kind=VisionAlertKind.METRIC)
+ | (
+ models.Q(state=VisionAlertState.NOT_FIRING)
+ & models.Q(consecutive_failures=0)
+ & models.Q(next_check_at__isnull=True)
+ ),
+ name="vision_alert_match_kind_stateless",
+ ),
+ models.CheckConstraint(
+ condition=(
+ models.Q(kind=VisionAlertKind.METRIC, threshold__isnull=False)
+ | models.Q(kind=VisionAlertKind.MATCH, threshold__isnull=True)
+ ),
+ name="vision_alert_metric_kind_threshold",
+ ),
+ ]
+ indexes = [
+ # Scheduler due scan is fleet-wide, so the index must not lead with team.
+ models.Index(
+ fields=["next_check_at"],
+ name="vision_alert_scheduler_idx",
+ condition=models.Q(enabled=True, kind="metric"),
+ ),
+ # Observation-completion hook lookup (match kind).
+ models.Index(fields=["team", "scanner", "kind", "enabled"], name="vision_alert_hook_idx"),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.name} ({self.kind})"
+
+ def clean(self) -> None:
+ if self.datapoints_to_alarm > self.evaluation_periods:
+ raise ValidationError({"datapoints_to_alarm": "Cannot exceed evaluation periods."})
+
+ def clear_next_check(self) -> list[str]:
+ """Nulls `next_check_at` so the scheduler picks this alert up on the next tick."""
+ self.next_check_at = None
+ return ["next_check_at"]
+
+ def to_snapshot(self, recent_events_breached: tuple[bool, ...] | None = None) -> "AlertSnapshot":
+ """Capture the fields the state machine reads for a transition decision."""
+ # Deferred import: this module and alert_state_machine reference each other.
+ from products.replay_vision.backend.alert_state_machine import AlertSnapshot, AlertState
+
+ return AlertSnapshot(
+ state=AlertState(self.state),
+ evaluation_periods=self.evaluation_periods,
+ datapoints_to_alarm=self.datapoints_to_alarm,
+ cooldown_minutes=self.cooldown_minutes,
+ last_notified_at=self.last_notified_at,
+ snooze_until=self.snooze_until,
+ consecutive_failures=self.consecutive_failures,
+ recent_events_breached=(
+ recent_events_breached if recent_events_breached is not None else self.get_recent_breaches()
+ ),
+ )
+
+ def get_recent_breaches(self) -> tuple[bool, ...]:
+ """Breach flags of the most recent CHECK events, newest first, for the N-of-M window."""
+ if self.evaluation_periods <= 1:
+ return ()
+ rows = self.events.filter(kind=VisionAlertEvent.Kind.CHECK).order_by("-created_at")[
+ : self.evaluation_periods - 1
+ ]
+ return tuple(row.threshold_breached for row in rows)
+
+
+class VisionAlertEvent(UUIDModel):
+ """Audit/check history for one VisionAlertConfiguration."""
+
+ class Kind(models.TextChoices):
+ CHECK = "check", "Check"
+ RESET = "reset", "Reset"
+ ENABLE = "enable", "Enable"
+ DISABLE = "disable", "Disable"
+ SNOOZE = "snooze", "Snooze"
+ UNSNOOZE = "unsnooze", "Unsnooze"
+ THRESHOLD_CHANGE = "threshold_change", "Threshold change"
+
+ alert = models.ForeignKey(VisionAlertConfiguration, on_delete=models.CASCADE, related_name="events")
+ kind = models.CharField(max_length=20, choices=Kind.choices, default=Kind.CHECK)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ metric_value = models.FloatField(null=True, blank=True)
+ threshold_breached = models.BooleanField(default=False)
+ state_before = models.CharField(max_length=20)
+ state_after = models.CharField(max_length=20)
+ error_message = models.TextField(null=True, blank=True)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["alert", "-created_at"], name="vision_alert_evt_alert_ts_idx"),
+ # The retention sweep filters on created_at alone.
+ models.Index(fields=["created_at"], name="vision_alert_evt_created_idx"),
+ ]
+
+
+class VisionAlertMatch(TeamScopedRootMixin, UUIDModel):
+ """Transactional outbox row: one matching observation for one match-kind alert.
+
+ Inserted in the observation's terminal-state transaction (exactly-once with the status
+ flip); the alert-check workflow drains undelivered rows into one bundled delivery per
+ alert per tick and stamps `delivered_at` only after the producer acks.
+ """
+
+ all_teams = models.Manager() # noqa: DJ012 — escape hatch for cross-team Temporal access
+
+ alert = models.ForeignKey(VisionAlertConfiguration, on_delete=models.CASCADE, related_name="matches")
+ observation = models.ForeignKey("replay_vision.ReplayObservation", on_delete=models.CASCADE, related_name="+")
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ delivered_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["alert", "observation"], name="vision_alert_match_unique"),
+ ]
+ indexes = [
+ models.Index(
+ fields=["alert", "created_at"],
+ name="vision_alert_match_drain_idx",
+ condition=models.Q(delivered_at__isnull=True),
+ ),
+ models.Index(fields=["delivered_at"], name="vision_alert_match_cleanup_idx"),
+ ]
+
+
+def selection_has_predicate(selection: dict) -> bool:
+ """0 is a valid score bound, so this must not use bare truthiness."""
+ return any(selection.get(key) not in (None, []) for key in PREDICATE_SELECTION_KEYS)
diff --git a/products/replay_vision/backend/routes.py b/products/replay_vision/backend/routes.py
index 7531a4b5dd21..352a898e95ac 100644
--- a/products/replay_vision/backend/routes.py
+++ b/products/replay_vision/backend/routes.py
@@ -10,6 +10,7 @@ from products.replay_vision.backend.api import (
SessionReplayObservationViewSet,
VisionActionRunViewSet,
VisionActionViewSet,
+ VisionAlertViewSet,
VisionQuotaViewSet,
)
@@ -46,6 +47,7 @@ def register_routes(routers: RouterRegistry) -> None:
r"vision/observations", SessionReplayObservationViewSet, "project_vision_observations", ["team_id"]
)
routers.projects.register(r"vision/quota", VisionQuotaViewSet, "project_vision_quota", ["team_id"])
+ routers.projects.register(r"vision/alerts", VisionAlertViewSet, "project_vision_alerts", ["team_id"])
project_vision_actions_router = routers.projects.register(
r"vision/actions", VisionActionViewSet, "project_vision_actions", ["team_id"]
)
diff --git a/products/replay_vision/backend/tests/test_vision_alerts_api.py b/products/replay_vision/backend/tests/test_vision_alerts_api.py
new file mode 100644
index 000000000000..061f57cb0cde
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_vision_alerts_api.py
@@ -0,0 +1,393 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.db import IntegrityError, transaction
+
+from parameterized import parameterized
+
+from posthog.cdp.templates.fixtures import template_slack
+from posthog.cdp.templates.hog_function_template import sync_template_to_db
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, PersonalAPIKey, Team, User
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionTemplate
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
+from products.replay_vision.backend.models.vision_alert import (
+ VisionAlertConfiguration,
+ VisionAlertEvent,
+ VisionAlertState,
+)
+
+
+class _VisionAlertAPITestCase(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.scanner = self._create_scanner()
+ self.base_url = f"/api/projects/{self.team.id}/vision/alerts/"
+
+ def _create_scanner(
+ self, name: str = "Checkout monitor", team: Team | None = None, scanner_type: str = ScannerType.MONITOR
+ ) -> ReplayScanner:
+ return ReplayScanner.objects.create(
+ team=team or self.team,
+ name=name,
+ scanner_type=scanner_type,
+ scanner_config={"prompt": "did the user check out?"},
+ model=ScannerModel.GEMINI_3_7_FLASH,
+ )
+
+ def _metric_payload(self, **overrides: Any) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "scanner_id": str(self.scanner.id),
+ "name": "Too many failures",
+ "kind": "metric",
+ "threshold": 5,
+ "selection": {"verdict": ["fail"]},
+ }
+ payload.update(overrides)
+ return payload
+
+ def _match_payload(self, **overrides: Any) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "scanner_id": str(self.scanner.id),
+ "name": "Every failed checkout",
+ "kind": "match",
+ "selection": {"verdict": ["fail"]},
+ }
+ payload.update(overrides)
+ return payload
+
+ def _create_via_api(self, payload: dict[str, Any] | None = None) -> dict[str, Any]:
+ response = self.client.post(self.base_url, payload or self._metric_payload(), format="json")
+ assert response.status_code == 201, response.json()
+ return response.json()
+
+
+class TestVisionAlertCRUD(_VisionAlertAPITestCase):
+ def test_create_metric_alert_defaults(self) -> None:
+ data = self._create_via_api()
+ assert data["kind"] == "metric"
+ assert data["state"] == "not_firing"
+ assert data["metric"] == "count"
+ assert data["direction"] == "above"
+ assert data["window_days"] == 1
+ assert data["first_enabled_at"] is not None
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).get(id=data["id"])
+ assert alert.created_by == self.user
+ assert alert.scanner_id == self.scanner.id
+
+ def test_create_match_alert_has_no_schedule(self) -> None:
+ data = self._create_via_api(self._match_payload())
+ assert data["kind"] == "match"
+ assert data["state"] == "not_firing"
+ assert data["next_check_at"] is None
+
+ @parameterized.expand(
+ [
+ ("metric_without_threshold", {"kind": "metric", "threshold": None}, "threshold"),
+ ("match_with_threshold", {"kind": "match", "threshold": 5}, "threshold"),
+ ("bad_window", {"kind": "metric", "threshold": 5, "window_days": 2}, "window_days"),
+ (
+ "avg_score_on_monitor_scanner",
+ {"kind": "metric", "threshold": 5, "metric": "avg_score"},
+ "metric",
+ ),
+ (
+ "datapoints_exceed_periods",
+ {"kind": "metric", "threshold": 5, "evaluation_periods": 2, "datapoints_to_alarm": 3},
+ "datapoints_to_alarm",
+ ),
+ (
+ "match_with_metric_config",
+ {"kind": "match", "threshold": None, "window_days": 7},
+ "window_days",
+ ),
+ ]
+ )
+ def test_create_validation_rejected(self, _name: str, overrides: dict[str, Any], error_field: str) -> None:
+ payload = self._metric_payload()
+ payload.pop("threshold")
+ payload.pop("selection")
+ payload.update(overrides)
+ response = self.client.post(self.base_url, payload, format="json")
+ assert response.status_code == 400, response.json()
+ assert response.json()["attr"].startswith(error_field), response.json()
+
+ def test_duplicate_name_is_a_field_error(self) -> None:
+ self._create_via_api()
+ response = self.client.post(self.base_url, self._metric_payload(), format="json")
+ assert response.status_code == 400, response.json()
+ assert response.json()["attr"] == "name"
+
+ def test_create_without_name_gets_default(self) -> None:
+ payload = self._metric_payload()
+ payload.pop("name")
+ response = self.client.post(self.base_url, payload, format="json")
+ assert response.status_code == 201, response.json()
+ assert response.json()["name"] == "Untitled alert"
+
+ def test_kind_and_scanner_are_immutable(self) -> None:
+ data = self._create_via_api()
+ response = self.client.patch(f"{self.base_url}{data['id']}/", {"kind": "match"}, format="json")
+ assert response.status_code == 400
+ other_scanner = self._create_scanner(name="Other scanner")
+ response = self.client.patch(
+ f"{self.base_url}{data['id']}/", {"scanner_id": str(other_scanner.id)}, format="json"
+ )
+ assert response.status_code == 400
+
+ def test_alerts_are_team_scoped(self) -> None:
+ data = self._create_via_api()
+ other_org = Organization.objects.create(name="other org")
+ other_team = Team.objects.create(organization=other_org, name="other team")
+ self.organization_membership.delete()
+ other_url = f"/api/projects/{other_team.id}/vision/alerts/"
+ response = self.client.get(other_url)
+ assert response.status_code in (403, 404)
+ # Same-team retrieval from a different project id must not leak the alert.
+ assert not VisionAlertConfiguration.objects.for_team(other_team.id).filter(id=data["id"]).exists()
+
+ def test_list_filters_by_scanner(self) -> None:
+ self._create_via_api()
+ other_scanner = self._create_scanner(name="Other scanner")
+ self._create_via_api(self._metric_payload(name="Other alert", scanner_id=str(other_scanner.id)))
+ response = self.client.get(self.base_url, {"scanner_id": str(other_scanner.id)})
+ assert response.status_code == 200
+ results = response.json()["results"]
+ assert [r["name"] for r in results] == ["Other alert"]
+
+ def test_match_kind_lifecycle_write_is_rejected_by_db(self) -> None:
+ data = self._create_via_api(self._match_payload())
+ with transaction.atomic():
+ with self.assertRaises(IntegrityError):
+ VisionAlertConfiguration.all_teams.filter(id=data["id"]).update(state=VisionAlertState.FIRING)
+
+
+class TestVisionAlertControlPlane(_VisionAlertAPITestCase):
+ def _patch(self, alert_id: str, body: dict[str, Any]) -> dict[str, Any]:
+ response = self.client.patch(f"{self.base_url}{alert_id}/", body, format="json")
+ assert response.status_code == 200, response.json()
+ return response.json()
+
+ def test_disable_enable_round_trip_writes_audit_rows(self) -> None:
+ data = self._create_via_api()
+ self._patch(data["id"], {"enabled": False})
+ self._patch(data["id"], {"enabled": True})
+ kinds = list(
+ VisionAlertEvent.objects.filter(alert_id=data["id"]).order_by("created_at").values_list("kind", flat=True)
+ )
+ assert kinds == [VisionAlertEvent.Kind.DISABLE, VisionAlertEvent.Kind.ENABLE]
+
+ def test_snooze_and_unsnooze(self) -> None:
+ data = self._create_via_api()
+ until = (datetime.now(UTC) + timedelta(hours=4)).isoformat()
+ snoozed = self._patch(data["id"], {"snooze_until": until})
+ assert snoozed["state"] == "snoozed"
+ unsnoozed = self._patch(data["id"], {"snooze_until": None})
+ assert unsnoozed["state"] == "not_firing"
+ assert unsnoozed["snooze_until"] is None
+
+ def test_snoozing_a_match_alert_keeps_it_stateless(self) -> None:
+ data = self._create_via_api(self._match_payload())
+ until = (datetime.now(UTC) + timedelta(hours=4)).isoformat()
+ snoozed = self._patch(data["id"], {"snooze_until": until})
+ assert snoozed["state"] == "not_firing"
+ assert snoozed["snooze_until"] is not None
+ unsnoozed = self._patch(data["id"], {"snooze_until": None})
+ assert unsnoozed["snooze_until"] is None
+
+ def test_threshold_change_resets_state_and_recheck(self) -> None:
+ data = self._create_via_api()
+ alert = VisionAlertConfiguration.objects.for_team(self.team.id).get(id=data["id"])
+ alert.next_check_at = datetime.now(UTC) + timedelta(hours=1)
+ alert.save(update_fields=["next_check_at"])
+ updated = self._patch(data["id"], {"threshold": 10})
+ assert updated["threshold"] == 10
+ assert updated["next_check_at"] is None
+ kinds = VisionAlertEvent.objects.filter(alert_id=data["id"]).values_list("kind", flat=True)
+ assert VisionAlertEvent.Kind.THRESHOLD_CHANGE in kinds
+
+ def test_reset_requires_broken_state(self) -> None:
+ data = self._create_via_api()
+ response = self.client.post(f"{self.base_url}{data['id']}/reset/")
+ assert response.status_code == 400
+ VisionAlertConfiguration.all_teams.filter(id=data["id"]).update(
+ state=VisionAlertState.BROKEN, consecutive_failures=5
+ )
+ response = self.client.post(f"{self.base_url}{data['id']}/reset/")
+ assert response.status_code == 200, response.json()
+ body = response.json()
+ assert body["state"] == "not_firing"
+ assert body["consecutive_failures"] == 0
+
+ def test_alert_cap_enforced(self) -> None:
+ with patch("products.replay_vision.backend.api.vision_alerts.MAX_ALERTS_PER_TEAM", 1):
+ self._create_via_api()
+ response = self.client.post(self.base_url, self._metric_payload(name="Second"), format="json")
+ assert response.status_code == 400
+
+
+class TestVisionAlertDestinations(_VisionAlertAPITestCase):
+ def _sync_destination_templates(self) -> None:
+ sync_template_to_db(template_slack)
+ HogFunctionTemplate.objects.get_or_create(
+ template_id="template-webhook",
+ defaults={
+ "sha": "1.0.0",
+ "name": "Webhook",
+ "description": "Generic webhook template",
+ "code": "return event",
+ "code_language": "hog",
+ "inputs_schema": [{"key": "url", "type": "string"}, {"key": "body", "type": "json"}],
+ "type": "destination",
+ "status": "stable",
+ "category": ["Integrations"],
+ "free": True,
+ },
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "metric",
+ 4,
+ {
+ "$replay_vision_alert_firing",
+ "$replay_vision_alert_resolved",
+ "$replay_vision_alert_auto_disabled",
+ "$replay_vision_alert_errored",
+ },
+ ),
+ ("match", 1, {"$replay_vision_alert_match"}),
+ ]
+ )
+ def test_webhook_destination_provisions_per_kind(
+ self, kind: str, expected_count: int, expected_event_ids: set[str]
+ ) -> None:
+ self._sync_destination_templates()
+ payload = self._metric_payload() if kind == "metric" else self._match_payload()
+ created = self._create_via_api(payload)
+ response = self.client.post(
+ f"{self.base_url}{created['id']}/destinations/",
+ {"type": "webhook", "webhook_url": "https://example.com/hook"},
+ format="json",
+ )
+ assert response.status_code == 201, response.json()
+ ids = response.json()["hog_function_ids"]
+ assert len(ids) == expected_count
+ hog_functions = HogFunction.objects.filter(id__in=ids)
+ assert {(hf.filters or {})["events"][0]["id"] for hf in hog_functions} == expected_event_ids
+
+ def test_destroy_soft_deletes_destinations(self) -> None:
+ self._sync_destination_templates()
+ created = self._create_via_api(self._match_payload())
+ response = self.client.post(
+ f"{self.base_url}{created['id']}/destinations/",
+ {"type": "webhook", "webhook_url": "https://example.com/hook"},
+ format="json",
+ )
+ ids = response.json()["hog_function_ids"]
+ response = self.client.delete(f"{self.base_url}{created['id']}/")
+ assert response.status_code == 204
+ assert not VisionAlertConfiguration.objects.for_team(self.team.id).filter(id=created["id"]).exists()
+ assert set(HogFunction.objects.filter(id__in=ids).values_list("deleted", flat=True)) == {True}
+
+
+class TestVisionAlertAccessControl(_VisionAlertAPITestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ self.other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+
+ def _set_scanner_default(self, access_level: str) -> None:
+ AccessControl.objects.update_or_create(
+ team=self.team,
+ resource="replay_scanner",
+ resource_id=None,
+ organization_member=None,
+ role=None,
+ defaults={"access_level": access_level},
+ )
+
+ def test_scanner_viewer_cannot_create_or_update_alert(self) -> None:
+ created = self._create_via_api()
+ self._set_scanner_default("viewer")
+ self.client.force_login(self.other_user)
+ create_resp = self.client.post(self.base_url, self._metric_payload(name="Blocked"), format="json")
+ assert create_resp.status_code == 403, create_resp.json()
+ patch_resp = self.client.patch(f"{self.base_url}{created['id']}/", {"threshold": 9}, format="json")
+ assert patch_resp.status_code == 403, patch_resp.json()
+
+ def test_scanner_resource_none_blocks_list_and_retrieve(self) -> None:
+ created = self._create_via_api()
+ self._set_scanner_default("none")
+ self.client.force_login(self.other_user)
+ list_resp = self.client.get(self.base_url)
+ assert list_resp.status_code == 403, list_resp.json()
+ retrieve_resp = self.client.get(f"{self.base_url}{created['id']}/")
+ assert retrieve_resp.status_code == 403, retrieve_resp.json()
+
+ def test_object_level_scanner_restriction_hides_alerts_from_list(self) -> None:
+ visible = self._create_via_api()
+ other_scanner = self._create_scanner(name="Restricted")
+ hidden = self._create_via_api(self._metric_payload(name="Hidden", scanner_id=str(other_scanner.id)))
+ AccessControl.objects.create(
+ team=self.team,
+ resource="replay_scanner",
+ resource_id=str(other_scanner.id),
+ access_level="none",
+ )
+ self.client.force_login(self.other_user)
+ list_resp = self.client.get(self.base_url)
+ assert list_resp.status_code == 200, list_resp.json()
+ assert [a["id"] for a in list_resp.json()["results"]] == [visible["id"]]
+ retrieve_resp = self.client.get(f"{self.base_url}{hidden['id']}/")
+ assert retrieve_resp.status_code == 403, retrieve_resp.json()
+
+ def test_session_recording_resource_none_blocks_config_actions(self) -> None:
+ AccessControl.objects.create(
+ team=self.team, resource="session_recording", resource_id=None, access_level="none"
+ )
+ self.client.force_login(self.other_user)
+ response = self.client.post(self.base_url, self._metric_payload(), format="json")
+ assert response.status_code == 403, response.json()
+ assert "session_recording" in response.json()["detail"]
+
+ def test_config_actions_require_session_recording_read_scope(self) -> None:
+ write_only = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="write-only",
+ user=self.user,
+ secure_value=hash_key_value(write_only),
+ scopes=["vision_alert:write"],
+ )
+ response = self.client.post(
+ self.base_url,
+ self._metric_payload(),
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {write_only}",
+ )
+ assert response.status_code == 403, response.json()
+
+ full = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="full",
+ user=self.user,
+ secure_value=hash_key_value(full),
+ scopes=["vision_alert:write", "session_recording:read"],
+ )
+ response = self.client.post(
+ self.base_url,
+ self._metric_payload(name="Scoped create"),
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {full}",
+ )
+ assert response.status_code == 201, response.json()
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 6e9b4b16d9bb..fd60a4d91970 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -509,6 +509,387 @@ export interface VisionActionRunApi {
readonly observations: readonly RunObservationApi[]
}
+/**
+ * * `metric` - Metric
+ * * `match` - Match
+ */
+export type VisionAlertConfigurationKindEnumApi =
+ (typeof VisionAlertConfigurationKindEnumApi)[keyof typeof VisionAlertConfigurationKindEnumApi]
+
+export const VisionAlertConfigurationKindEnumApi = {
+ Metric: 'metric',
+ Match: 'match',
+} as const
+
+export interface VisionAlertSelectionApi {
+ /**
+ * Monitor verdicts to match, e.g. ['yes'].
+ * @maxItems 10
+ * @items.maxLength 100
+ */
+ verdict?: string[]
+ /**
+ * Classifier tags to match; an observation matches when it carries any of them.
+ * @maxItems 20
+ * @items.maxLength 200
+ */
+ tags?: string[]
+ /** Minimum scorer score (inclusive). */
+ min_score?: number
+ /** Maximum scorer score (inclusive). */
+ max_score?: number
+}
+
+/**
+ * * `count` - Count matching observations
+ * * `avg_score` - Average score
+ */
+export type VisionAlertConfigurationMetricEnumApi =
+ (typeof VisionAlertConfigurationMetricEnumApi)[keyof typeof VisionAlertConfigurationMetricEnumApi]
+
+export const VisionAlertConfigurationMetricEnumApi = {
+ Count: 'count',
+ AvgScore: 'avg_score',
+} as const
+
+/**
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `pending_resolve` - Pending resolve
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken
+ */
+export type LogsAlertConfigurationStateEnumApi =
+ (typeof LogsAlertConfigurationStateEnumApi)[keyof typeof LogsAlertConfigurationStateEnumApi]
+
+export const LogsAlertConfigurationStateEnumApi = {
+ NotFiring: 'not_firing',
+ Firing: 'firing',
+ PendingResolve: 'pending_resolve',
+ Errored: 'errored',
+ Snoozed: 'snoozed',
+ Broken: 'broken',
+} as const
+
+export interface AlertScheduleRestrictionWindowApi {
+ /** Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)). */
+ start: string
+ /** End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally. */
+ end: string
+}
+
+export interface AlertScheduleRestrictionApi {
+ /** Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours. */
+ blocked_windows: AlertScheduleRestrictionWindowApi[]
+}
+
+export interface VisionAlertConfigurationApi {
+ /** Unique identifier for this alert. */
+ readonly id: string
+ /** Scanner whose observations this alert watches. Immutable after creation. */
+ scanner_id: string
+ /**
+ * Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted.
+ * @maxLength 255
+ */
+ name?: string
+ /** Whether the alert is active. Disabling a metric alert resets its state to not_firing. */
+ enabled?: boolean
+ /** 'metric' fires when a metric crosses a threshold over a rolling window; 'match' fires on every observation that matches the selection. Immutable after creation.
+ *
+ * * `metric` - Metric
+ * * `match` - Match */
+ kind: VisionAlertConfigurationKindEnumApi
+ /** Which observations count. Empty matches every observation of the scanner. */
+ selection?: VisionAlertSelectionApi
+ /** Metric alerts only: what to measure over the window. 'avg_score' requires a scorer scanner.
+ *
+ * * `count` - Count matching observations
+ * * `avg_score` - Average score */
+ metric?: VisionAlertConfigurationMetricEnumApi
+ /** Metric alerts only: whether the alert fires at or above, or at or below, the threshold.
+ *
+ * * `above` - At or above
+ * * `below` - At or below */
+ direction?: VisionAlertDirectionEnumApi
+ /**
+ * Metric alerts only: the threshold value. Required for metric alerts, must be omitted for match alerts.
+ * @nullable
+ */
+ threshold?: number | null
+ /** Metric alerts only: rolling window in days. Allowed values: [1, 3, 7, 14, 30]. */
+ window_days?: number
+ /**
+ * Metric alerts only: evaluation cadence in minutes, at least 15.
+ * @minimum 15
+ */
+ check_interval_minutes?: number
+ /** Current lifecycle state. Always not_firing for match alerts. Server-managed.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `pending_resolve` - Pending resolve
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state: LogsAlertConfigurationStateEnumApi
+ /**
+ * Metric alerts only: total check periods in the sliding evaluation window (M in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number
+ /**
+ * Metric alerts only: how many periods must breach to fire (N in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number
+ /**
+ * Metric alerts only: minimum minutes between repeated notifications. 0 means no cooldown.
+ * @minimum 0
+ */
+ cooldown_minutes?: number
+ /** Blocked local time windows when the alert must not notify. Times use the project timezone. Null disables quiet hours. */
+ schedule_restriction?: AlertScheduleRestrictionApi | null
+ /**
+ * ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
+ * @nullable
+ */
+ snooze_until?: string | null
+ /**
+ * When the next evaluation is scheduled. Server-managed.
+ * @nullable
+ */
+ readonly next_check_at: string | null
+ /**
+ * When the last notification was sent. Server-managed.
+ * @nullable
+ */
+ readonly last_notified_at: string | null
+ /**
+ * When the alert was last evaluated. Server-managed.
+ * @nullable
+ */
+ readonly last_checked_at: string | null
+ /** Consecutive evaluation failures. Resets on success. Server-managed. */
+ readonly consecutive_failures: number
+ /**
+ * When the alert was first enabled. Null means still a draft.
+ * @nullable
+ */
+ readonly first_enabled_at: string | null
+ /** When the alert was created. */
+ readonly created_at: string
+ readonly created_by: UserBasicApi
+ /**
+ * When the alert was last modified.
+ * @nullable
+ */
+ readonly updated_at: string | null
+}
+
+export interface PaginatedVisionAlertConfigurationListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: VisionAlertConfigurationApi[]
+}
+
+export interface PatchedVisionAlertConfigurationApi {
+ /** Unique identifier for this alert. */
+ readonly id?: string
+ /** Scanner whose observations this alert watches. Immutable after creation. */
+ scanner_id?: string
+ /**
+ * Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted.
+ * @maxLength 255
+ */
+ name?: string
+ /** Whether the alert is active. Disabling a metric alert resets its state to not_firing. */
+ enabled?: boolean
+ /** 'metric' fires when a metric crosses a threshold over a rolling window; 'match' fires on every observation that matches the selection. Immutable after creation.
+ *
+ * * `metric` - Metric
+ * * `match` - Match */
+ kind?: VisionAlertConfigurationKindEnumApi
+ /** Which observations count. Empty matches every observation of the scanner. */
+ selection?: VisionAlertSelectionApi
+ /** Metric alerts only: what to measure over the window. 'avg_score' requires a scorer scanner.
+ *
+ * * `count` - Count matching observations
+ * * `avg_score` - Average score */
+ metric?: VisionAlertConfigurationMetricEnumApi
+ /** Metric alerts only: whether the alert fires at or above, or at or below, the threshold.
+ *
+ * * `above` - At or above
+ * * `below` - At or below */
+ direction?: VisionAlertDirectionEnumApi
+ /**
+ * Metric alerts only: the threshold value. Required for metric alerts, must be omitted for match alerts.
+ * @nullable
+ */
+ threshold?: number | null
+ /** Metric alerts only: rolling window in days. Allowed values: [1, 3, 7, 14, 30]. */
+ window_days?: number
+ /**
+ * Metric alerts only: evaluation cadence in minutes, at least 15.
+ * @minimum 15
+ */
+ check_interval_minutes?: number
+ /** Current lifecycle state. Always not_firing for match alerts. Server-managed.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `pending_resolve` - Pending resolve
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state?: LogsAlertConfigurationStateEnumApi
+ /**
+ * Metric alerts only: total check periods in the sliding evaluation window (M in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number
+ /**
+ * Metric alerts only: how many periods must breach to fire (N in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number
+ /**
+ * Metric alerts only: minimum minutes between repeated notifications. 0 means no cooldown.
+ * @minimum 0
+ */
+ cooldown_minutes?: number
+ /** Blocked local time windows when the alert must not notify. Times use the project timezone. Null disables quiet hours. */
+ schedule_restriction?: AlertScheduleRestrictionApi | null
+ /**
+ * ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
+ * @nullable
+ */
+ snooze_until?: string | null
+ /**
+ * When the next evaluation is scheduled. Server-managed.
+ * @nullable
+ */
+ readonly next_check_at?: string | null
+ /**
+ * When the last notification was sent. Server-managed.
+ * @nullable
+ */
+ readonly last_notified_at?: string | null
+ /**
+ * When the alert was last evaluated. Server-managed.
+ * @nullable
+ */
+ readonly last_checked_at?: string | null
+ /** Consecutive evaluation failures. Resets on success. Server-managed. */
+ readonly consecutive_failures?: number
+ /**
+ * When the alert was first enabled. Null means still a draft.
+ * @nullable
+ */
+ readonly first_enabled_at?: string | null
+ /** When the alert was created. */
+ readonly created_at?: string
+ readonly created_by?: UserBasicApi
+ /**
+ * When the alert was last modified.
+ * @nullable
+ */
+ readonly updated_at?: string | null
+}
+
+/**
+ * * `slack` - slack
+ * * `webhook` - webhook
+ */
+export type VisionAlertCreateDestinationTypeEnumApi =
+ (typeof VisionAlertCreateDestinationTypeEnumApi)[keyof typeof VisionAlertCreateDestinationTypeEnumApi]
+
+export const VisionAlertCreateDestinationTypeEnumApi = {
+ Slack: 'slack',
+ Webhook: 'webhook',
+} as const
+
+export interface VisionAlertCreateDestinationApi {
+ /** Notification destination type.
+ *
+ * * `slack` - slack
+ * * `webhook` - webhook */
+ type: VisionAlertCreateDestinationTypeEnumApi
+ /** Integration ID for the Slack workspace. Required when type=slack. */
+ slack_workspace_id?: number
+ /** Slack channel ID. Required when type=slack. */
+ slack_channel_id?: string
+ /** Human-readable channel name for display. */
+ slack_channel_name?: string
+ /** HTTPS endpoint to post to. Required when type=webhook. */
+ webhook_url?: string
+}
+
+export interface VisionAlertDestinationResponseApi {
+ /** HogFunctions backing the created destination, one per event kind. */
+ hog_function_ids: string[]
+}
+
+export interface VisionAlertDeleteDestinationApi {
+ /**
+ * HogFunction IDs to delete as one atomic destination group.
+ * @minItems 1
+ * @maxItems 5
+ */
+ hog_function_ids: string[]
+}
+
+/**
+ * * `check` - Check
+ * * `reset` - Reset
+ * * `enable` - Enable
+ * * `disable` - Disable
+ * * `snooze` - Snooze
+ * * `unsnooze` - Unsnooze
+ * * `threshold_change` - Threshold change
+ */
+export type VisionAlertEventKindEnumApi = (typeof VisionAlertEventKindEnumApi)[keyof typeof VisionAlertEventKindEnumApi]
+
+export const VisionAlertEventKindEnumApi = {
+ Check: 'check',
+ Reset: 'reset',
+ Enable: 'enable',
+ Disable: 'disable',
+ Snooze: 'snooze',
+ Unsnooze: 'unsnooze',
+ ThresholdChange: 'threshold_change',
+} as const
+
+export interface VisionAlertEventApi {
+ readonly id: string
+ readonly created_at: string
+ readonly kind: VisionAlertEventKindEnumApi
+ readonly state_before: string
+ readonly state_after: string
+ readonly threshold_breached: boolean
+ /** @nullable */
+ readonly metric_value: number | null
+ /** @nullable */
+ readonly error_message: string | null
+}
+
+export interface PaginatedVisionAlertEventListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: VisionAlertEventApi[]
+}
+
/**
* * `pending` - Pending
* * `running` - Running
@@ -2237,6 +2618,44 @@ export type VisionActionsRunsListParams = {
offset?: number
}
+export type VisionAlertsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type VisionAlertsEventsListParams = {
+ /**
+ * Narrow the history to one event kind.
+ */
+ kind?: VisionAlertsEventsListKind
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type VisionAlertsEventsListKind = (typeof VisionAlertsEventsListKind)[keyof typeof VisionAlertsEventsListKind]
+
+export const VisionAlertsEventsListKind = {
+ Check: 'check',
+ Disable: 'disable',
+ Enable: 'enable',
+ Reset: 'reset',
+ Snooze: 'snooze',
+ ThresholdChange: 'threshold_change',
+ Unsnooze: 'unsnooze',
+} as const
+
export type VisionObservationsListParams = {
/**
* Number of results to return per page.
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index f1bb34d2d026..0d6de8b1e625 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -36,8 +36,11 @@ import type {
PaginatedReplayScannerPromptSuggestionListApi,
PaginatedVisionActionListApi,
PaginatedVisionActionRunListListApi,
+ PaginatedVisionAlertConfigurationListApi,
+ PaginatedVisionAlertEventListApi,
PatchedReplayScannerApi,
PatchedVisionActionApi,
+ PatchedVisionAlertConfigurationApi,
ReplayObservationApi,
ReplayObservationLabelApi,
ReplayScannerApi,
@@ -58,6 +61,12 @@ import type {
VisionActionRunApi,
VisionActionsListParams,
VisionActionsRunsListParams,
+ VisionAlertConfigurationApi,
+ VisionAlertCreateDestinationApi,
+ VisionAlertDeleteDestinationApi,
+ VisionAlertDestinationResponseApi,
+ VisionAlertsEventsListParams,
+ VisionAlertsListParams,
VisionObservationsListParams,
VisionObservationsRetrieveParams,
VisionObservationsSearchRetrieveParams,
@@ -268,6 +277,203 @@ export const visionActionsRunsRetrieve = async (
})
}
+export const getVisionAlertsListUrl = (projectId: string, params?: VisionAlertsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/vision/alerts/?${stringifiedParams}`
+ : `/api/projects/${projectId}/vision/alerts/`
+}
+
+export const visionAlertsList = async (
+ projectId: string,
+ params?: VisionAlertsListParams,
+ options?: RequestInit
+): Promise<PaginatedVisionAlertConfigurationListApi> => {
+ return apiMutator<PaginatedVisionAlertConfigurationListApi>(getVisionAlertsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getVisionAlertsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/vision/alerts/`
+}
+
+export const visionAlertsCreate = async (
+ projectId: string,
+ visionAlertConfigurationApi: NonReadonly<VisionAlertConfigurationApi>,
+ options?: RequestInit
+): Promise<VisionAlertConfigurationApi> => {
+ return apiMutator<VisionAlertConfigurationApi>(getVisionAlertsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(visionAlertConfigurationApi),
+ })
+}
+
+export const getVisionAlertsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/alerts/${id}/`
+}
+
+export const visionAlertsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<VisionAlertConfigurationApi> => {
+ return apiMutator<VisionAlertConfigurationApi>(getVisionAlertsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getVisionAlertsUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/alerts/${id}/`
+}
+
+export const visionAlertsUpdate = async (
+ projectId: string,
+ id: string,
+ visionAlertConfigurationApi: NonReadonly<VisionAlertConfigurationApi>,
+ options?: RequestInit
+): Promise<VisionAlertConfigurationApi> => {
+ return apiMutator<VisionAlertConfigurationApi>(getVisionAlertsUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(visionAlertConfigurationApi),
+ })
+}
+
+export const getVisionAlertsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/alerts/${id}/`
+}
+
+export const visionAlertsPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedVisionAlertConfigurationApi?: NonReadonly<PatchedVisionAlertConfigurationApi>,
+ options?: RequestInit
+): Promise<VisionAlertConfigurationApi> => {
+ return apiMutator<VisionAlertConfigurationApi>(getVisionAlertsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedVisionAlertConfigurationApi),
+ })
+}
+
+export const getVisionAlertsDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/alerts/${id}/`
+}
+
+export const visionAlertsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getVisionAlertsDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getVisionAlertsDestinationsCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/alerts/${id}/destinations/`
+}
+
+/**
+ * Create a notification destination for this alert. One HogFunction is created per alert event kind atomically.
+ */
+export const visionAlertsDestinationsCreate = async (
+ projectId: string,
+ id: string,
+ visionAlertCreateDestinationApi: VisionAlertCreateDestinationApi,
+ options?: RequestInit
+): Promise<VisionAlertDestinationResponseApi> => {
+ return apiMutator<VisionAlertDestinationResponseApi>(getVisionAlertsDestinationsCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(visionAlertCreateDestinationApi),
+ })
+}
+
+export const getVisionAlertsDestinationsDeleteCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/alerts/${id}/destinations/delete/`
+}
+
+/**
+ * Delete a notification destination by deleting its HogFunction group atomically.
+ */
+export const visionAlertsDestinationsDeleteCreate = async (
+ projectId: string,
+ id: string,
+ visionAlertDeleteDestinationApi: VisionAlertDeleteDestinationApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getVisionAlertsDestinationsDeleteCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(visionAlertDeleteDestinationApi),
+ })
+}
+
+export const getVisionAlertsEventsListUrl = (projectId: string, id: string, params?: VisionAlertsEventsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/vision/alerts/${id}/events/?${stringifiedParams}`
+ : `/api/projects/${projectId}/vision/alerts/${id}/events/`
+}
+
+/**
+ * Paginated event history for this alert, newest first. Quiet no-op check rows (no state change, no error) are filtered out. Optional `?kind=...` narrows to one kind.
+ */
+export const visionAlertsEventsList = async (
+ projectId: string,
+ id: string,
+ params?: VisionAlertsEventsListParams,
+ options?: RequestInit
+): Promise<PaginatedVisionAlertEventListApi> => {
+ return apiMutator<PaginatedVisionAlertEventListApi>(getVisionAlertsEventsListUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getVisionAlertsResetCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/alerts/${id}/reset/`
+}
+
+/**
+ * Reset a broken alert. Clears the consecutive-failure counter and schedules an immediate recheck.
+ */
+export const visionAlertsResetCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<VisionAlertConfigurationApi> => {
+ return apiMutator<VisionAlertConfigurationApi>(getVisionAlertsResetCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getVisionObservationsListUrl = (projectId: string, params: VisionObservationsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index 8470699e9caf..4e5d9c8f8c0e 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -383,6 +383,463 @@ export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod
})
.describe('A Replay Vision action: a scheduled \"and then…\" automation over a scanner\'s observations.')
+export const visionAlertsCreateBodyNameDefault = `Untitled alert`
+export const visionAlertsCreateBodyNameMax = 255
+
+export const visionAlertsCreateBodyEnabledDefault = true
+export const visionAlertsCreateBodySelectionOneVerdictItemMax = 100
+
+export const visionAlertsCreateBodySelectionOneVerdictMax = 10
+
+export const visionAlertsCreateBodySelectionOneTagsItemMax = 200
+
+export const visionAlertsCreateBodySelectionOneTagsMax = 20
+
+export const visionAlertsCreateBodyMetricDefault = `count`
+export const visionAlertsCreateBodyDirectionDefault = `above`
+export const visionAlertsCreateBodyWindowDaysDefault = 1
+export const visionAlertsCreateBodyCheckIntervalMinutesDefault = 60
+export const visionAlertsCreateBodyCheckIntervalMinutesMin = 15
+
+export const visionAlertsCreateBodyEvaluationPeriodsDefault = 1
+export const visionAlertsCreateBodyEvaluationPeriodsMax = 10
+
+export const visionAlertsCreateBodyDatapointsToAlarmDefault = 1
+export const visionAlertsCreateBodyDatapointsToAlarmMax = 10
+
+export const visionAlertsCreateBodyCooldownMinutesDefault = 0
+export const visionAlertsCreateBodyCooldownMinutesMin = 0
+
+export const VisionAlertsCreateBody = /* @__PURE__ */ zod.object({
+ scanner_id: zod.uuid().describe('Scanner whose observations this alert watches. Immutable after creation.'),
+ name: zod
+ .string()
+ .max(visionAlertsCreateBodyNameMax)
+ .default(visionAlertsCreateBodyNameDefault)
+ .describe("Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted."),
+ enabled: zod
+ .boolean()
+ .default(visionAlertsCreateBodyEnabledDefault)
+ .describe('Whether the alert is active. Disabling a metric alert resets its state to not_firing.'),
+ kind: zod
+ .enum(['metric', 'match'])
+ .describe('\* `metric` - Metric\n\* `match` - Match')
+ .describe(
+ "'metric' fires when a metric crosses a threshold over a rolling window; 'match' fires on every observation that matches the selection. Immutable after creation.\n\n\* `metric` - Metric\n\* `match` - Match"
+ ),
+ selection: zod
+ .object({
+ verdict: zod
+ .array(zod.string().max(visionAlertsCreateBodySelectionOneVerdictItemMax))
+ .max(visionAlertsCreateBodySelectionOneVerdictMax)
+ .optional()
+ .describe("Monitor verdicts to match, e.g. ['yes']."),
+ tags: zod
+ .array(zod.string().max(visionAlertsCreateBodySelectionOneTagsItemMax))
+ .max(visionAlertsCreateBodySelectionOneTagsMax)
+ .optional()
+ .describe('Classifier tags to match; an observation matches when it carries any of them.'),
+ min_score: zod.number().optional().describe('Minimum scorer score (inclusive).'),
+ max_score: zod.number().optional().describe('Maximum scorer score (inclusive).'),
+ })
+ .optional()
+ .describe('Which observations count. Empty matches every observation of the scanner.'),
+ metric: zod
+ .enum(['count', 'avg_score'])
+ .describe('\* `count` - Count matching observations\n\* `avg_score` - Average score')
+ .default(visionAlertsCreateBodyMetricDefault)
+ .describe(
+ "Metric alerts only: what to measure over the window. 'avg_score' requires a scorer scanner.\n\n\* `count` - Count matching observations\n\* `avg_score` - Average score"
+ ),
+ direction: zod
+ .enum(['above', 'below'])
+ .describe('\* `above` - At or above\n\* `below` - At or below')
+ .default(visionAlertsCreateBodyDirectionDefault)
+ .describe(
+ 'Metric alerts only: whether the alert fires at or above, or at or below, the threshold.\n\n\* `above` - At or above\n\* `below` - At or below'
+ ),
+ threshold: zod
+ .number()
+ .nullish()
+ .describe(
+ 'Metric alerts only: the threshold value. Required for metric alerts, must be omitted for match alerts.'
+ ),
+ window_days: zod
+ .number()
+ .default(visionAlertsCreateBodyWindowDaysDefault)
+ .describe('Metric alerts only: rolling window in days. Allowed values: [1, 3, 7, 14, 30].'),
+ check_interval_minutes: zod
+ .number()
+ .min(visionAlertsCreateBodyCheckIntervalMinutesMin)
+ .default(visionAlertsCreateBodyCheckIntervalMinutesDefault)
+ .describe('Metric alerts only: evaluation cadence in minutes, at least 15.'),
+ evaluation_periods: zod
+ .number()
+ .min(1)
+ .max(visionAlertsCreateBodyEvaluationPeriodsMax)
+ .default(visionAlertsCreateBodyEvaluationPeriodsDefault)
+ .describe('Metric alerts only: total check periods in the sliding evaluation window (M in N-of-M).'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(visionAlertsCreateBodyDatapointsToAlarmMax)
+ .default(visionAlertsCreateBodyDatapointsToAlarmDefault)
+ .describe('Metric alerts only: how many periods must breach to fire (N in N-of-M).'),
+ cooldown_minutes: zod
+ .number()
+ .min(visionAlertsCreateBodyCooldownMinutesMin)
+ .default(visionAlertsCreateBodyCooldownMinutesDefault)
+ .describe('Metric alerts only: minimum minutes between repeated notifications. 0 means no cooldown.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Blocked local time windows when the alert must not notify. Times use the project timezone. Null disables quiet hours.'
+ ),
+ snooze_until: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.'),
+})
+
+export const visionAlertsUpdateBodyNameDefault = `Untitled alert`
+export const visionAlertsUpdateBodyNameMax = 255
+
+export const visionAlertsUpdateBodyEnabledDefault = true
+export const visionAlertsUpdateBodySelectionOneVerdictItemMax = 100
+
+export const visionAlertsUpdateBodySelectionOneVerdictMax = 10
+
+export const visionAlertsUpdateBodySelectionOneTagsItemMax = 200
+
+export const visionAlertsUpdateBodySelectionOneTagsMax = 20
+
+export const visionAlertsUpdateBodyMetricDefault = `count`
+export const visionAlertsUpdateBodyDirectionDefault = `above`
+export const visionAlertsUpdateBodyWindowDaysDefault = 1
+export const visionAlertsUpdateBodyCheckIntervalMinutesDefault = 60
+export const visionAlertsUpdateBodyCheckIntervalMinutesMin = 15
+
+export const visionAlertsUpdateBodyEvaluationPeriodsDefault = 1
+export const visionAlertsUpdateBodyEvaluationPeriodsMax = 10
+
+export const visionAlertsUpdateBodyDatapointsToAlarmDefault = 1
+export const visionAlertsUpdateBodyDatapointsToAlarmMax = 10
+
+export const visionAlertsUpdateBodyCooldownMinutesDefault = 0
+export const visionAlertsUpdateBodyCooldownMinutesMin = 0
+
+export const VisionAlertsUpdateBody = /* @__PURE__ */ zod.object({
+ scanner_id: zod.uuid().describe('Scanner whose observations this alert watches. Immutable after creation.'),
+ name: zod
+ .string()
+ .max(visionAlertsUpdateBodyNameMax)
+ .default(visionAlertsUpdateBodyNameDefault)
+ .describe("Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted."),
+ enabled: zod
+ .boolean()
+ .default(visionAlertsUpdateBodyEnabledDefault)
+ .describe('Whether the alert is active. Disabling a metric alert resets its state to not_firing.'),
+ kind: zod
+ .enum(['metric', 'match'])
+ .describe('\* `metric` - Metric\n\* `match` - Match')
+ .describe(
+ "'metric' fires when a metric crosses a threshold over a rolling window; 'match' fires on every observation that matches the selection. Immutable after creation.\n\n\* `metric` - Metric\n\* `match` - Match"
+ ),
+ selection: zod
+ .object({
+ verdict: zod
+ .array(zod.string().max(visionAlertsUpdateBodySelectionOneVerdictItemMax))
+ .max(visionAlertsUpdateBodySelectionOneVerdictMax)
+ .optional()
+ .describe("Monitor verdicts to match, e.g. ['yes']."),
+ tags: zod
+ .array(zod.string().max(visionAlertsUpdateBodySelectionOneTagsItemMax))
+ .max(visionAlertsUpdateBodySelectionOneTagsMax)
+ .optional()
+ .describe('Classifier tags to match; an observation matches when it carries any of them.'),
+ min_score: zod.number().optional().describe('Minimum scorer score (inclusive).'),
+ max_score: zod.number().optional().describe('Maximum scorer score (inclusive).'),
+ })
+ .optional()
+ .describe('Which observations count. Empty matches every observation of the scanner.'),
+ metric: zod
+ .enum(['count', 'avg_score'])
+ .describe('\* `count` - Count matching observations\n\* `avg_score` - Average score')
+ .default(visionAlertsUpdateBodyMetricDefault)
+ .describe(
+ "Metric alerts only: what to measure over the window. 'avg_score' requires a scorer scanner.\n\n\* `count` - Count matching observations\n\* `avg_score` - Average score"
+ ),
+ direction: zod
+ .enum(['above', 'below'])
+ .describe('\* `above` - At or above\n\* `below` - At or below')
+ .default(visionAlertsUpdateBodyDirectionDefault)
+ .describe(
+ 'Metric alerts only: whether the alert fires at or above, or at or below, the threshold.\n\n\* `above` - At or above\n\* `below` - At or below'
+ ),
+ threshold: zod
+ .number()
+ .nullish()
+ .describe(
+ 'Metric alerts only: the threshold value. Required for metric alerts, must be omitted for match alerts.'
+ ),
+ window_days: zod
+ .number()
+ .default(visionAlertsUpdateBodyWindowDaysDefault)
+ .describe('Metric alerts only: rolling window in days. Allowed values: [1, 3, 7, 14, 30].'),
+ check_interval_minutes: zod
+ .number()
+ .min(visionAlertsUpdateBodyCheckIntervalMinutesMin)
+ .default(visionAlertsUpdateBodyCheckIntervalMinutesDefault)
+ .describe('Metric alerts only: evaluation cadence in minutes, at least 15.'),
+ evaluation_periods: zod
+ .number()
+ .min(1)
+ .max(visionAlertsUpdateBodyEvaluationPeriodsMax)
+ .default(visionAlertsUpdateBodyEvaluationPeriodsDefault)
+ .describe('Metric alerts only: total check periods in the sliding evaluation window (M in N-of-M).'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(visionAlertsUpdateBodyDatapointsToAlarmMax)
+ .default(visionAlertsUpdateBodyDatapointsToAlarmDefault)
+ .describe('Metric alerts only: how many periods must breach to fire (N in N-of-M).'),
+ cooldown_minutes: zod
+ .number()
+ .min(visionAlertsUpdateBodyCooldownMinutesMin)
+ .default(visionAlertsUpdateBodyCooldownMinutesDefault)
+ .describe('Metric alerts only: minimum minutes between repeated notifications. 0 means no cooldown.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Blocked local time windows when the alert must not notify. Times use the project timezone. Null disables quiet hours.'
+ ),
+ snooze_until: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.'),
+})
+
+export const visionAlertsPartialUpdateBodyNameDefault = `Untitled alert`
+export const visionAlertsPartialUpdateBodyNameMax = 255
+
+export const visionAlertsPartialUpdateBodyEnabledDefault = true
+export const visionAlertsPartialUpdateBodySelectionOneVerdictItemMax = 100
+
+export const visionAlertsPartialUpdateBodySelectionOneVerdictMax = 10
+
+export const visionAlertsPartialUpdateBodySelectionOneTagsItemMax = 200
+
+export const visionAlertsPartialUpdateBodySelectionOneTagsMax = 20
+
+export const visionAlertsPartialUpdateBodyMetricDefault = `count`
+export const visionAlertsPartialUpdateBodyDirectionDefault = `above`
+export const visionAlertsPartialUpdateBodyWindowDaysDefault = 1
+export const visionAlertsPartialUpdateBodyCheckIntervalMinutesDefault = 60
+export const visionAlertsPartialUpdateBodyCheckIntervalMinutesMin = 15
+
+export const visionAlertsPartialUpdateBodyEvaluationPeriodsDefault = 1
+export const visionAlertsPartialUpdateBodyEvaluationPeriodsMax = 10
+
+export const visionAlertsPartialUpdateBodyDatapointsToAlarmDefault = 1
+export const visionAlertsPartialUpdateBodyDatapointsToAlarmMax = 10
+
+export const visionAlertsPartialUpdateBodyCooldownMinutesDefault = 0
+export const visionAlertsPartialUpdateBodyCooldownMinutesMin = 0
+
+export const VisionAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ scanner_id: zod
+ .uuid()
+ .optional()
+ .describe('Scanner whose observations this alert watches. Immutable after creation.'),
+ name: zod
+ .string()
+ .max(visionAlertsPartialUpdateBodyNameMax)
+ .default(visionAlertsPartialUpdateBodyNameDefault)
+ .describe("Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted."),
+ enabled: zod
+ .boolean()
+ .default(visionAlertsPartialUpdateBodyEnabledDefault)
+ .describe('Whether the alert is active. Disabling a metric alert resets its state to not_firing.'),
+ kind: zod
+ .enum(['metric', 'match'])
+ .describe('\* `metric` - Metric\n\* `match` - Match')
+ .optional()
+ .describe(
+ "'metric' fires when a metric crosses a threshold over a rolling window; 'match' fires on every observation that matches the selection. Immutable after creation.\n\n\* `metric` - Metric\n\* `match` - Match"
+ ),
+ selection: zod
+ .object({
+ verdict: zod
+ .array(zod.string().max(visionAlertsPartialUpdateBodySelectionOneVerdictItemMax))
+ .max(visionAlertsPartialUpdateBodySelectionOneVerdictMax)
+ .optional()
+ .describe("Monitor verdicts to match, e.g. ['yes']."),
+ tags: zod
+ .array(zod.string().max(visionAlertsPartialUpdateBodySelectionOneTagsItemMax))
+ .max(visionAlertsPartialUpdateBodySelectionOneTagsMax)
+ .optional()
+ .describe('Classifier tags to match; an observation matches when it carries any of them.'),
+ min_score: zod.number().optional().describe('Minimum scorer score (inclusive).'),
+ max_score: zod.number().optional().describe('Maximum scorer score (inclusive).'),
+ })
+ .optional()
+ .describe('Which observations count. Empty matches every observation of the scanner.'),
+ metric: zod
+ .enum(['count', 'avg_score'])
+ .describe('\* `count` - Count matching observations\n\* `avg_score` - Average score')
+ .default(visionAlertsPartialUpdateBodyMetricDefault)
+ .describe(
+ "Metric alerts only: what to measure over the window. 'avg_score' requires a scorer scanner.\n\n\* `count` - Count matching observations\n\* `avg_score` - Average score"
+ ),
+ direction: zod
+ .enum(['above', 'below'])
+ .describe('\* `above` - At or above\n\* `below` - At or below')
+ .default(visionAlertsPartialUpdateBodyDirectionDefault)
+ .describe(
+ 'Metric alerts only: whether the alert fires at or above, or at or below, the threshold.\n\n\* `above` - At or above\n\* `below` - At or below'
+ ),
+ threshold: zod
+ .number()
+ .nullish()
+ .describe(
+ 'Metric alerts only: the threshold value. Required for metric alerts, must be omitted for match alerts.'
+ ),
+ window_days: zod
+ .number()
+ .default(visionAlertsPartialUpdateBodyWindowDaysDefault)
+ .describe('Metric alerts only: rolling window in days. Allowed values: [1, 3, 7, 14, 30].'),
+ check_interval_minutes: zod
+ .number()
+ .min(visionAlertsPartialUpdateBodyCheckIntervalMinutesMin)
+ .default(visionAlertsPartialUpdateBodyCheckIntervalMinutesDefault)
+ .describe('Metric alerts only: evaluation cadence in minutes, at least 15.'),
+ evaluation_periods: zod
+ .number()
+ .min(1)
+ .max(visionAlertsPartialUpdateBodyEvaluationPeriodsMax)
+ .default(visionAlertsPartialUpdateBodyEvaluationPeriodsDefault)
+ .describe('Metric alerts only: total check periods in the sliding evaluation window (M in N-of-M).'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(visionAlertsPartialUpdateBodyDatapointsToAlarmMax)
+ .default(visionAlertsPartialUpdateBodyDatapointsToAlarmDefault)
+ .describe('Metric alerts only: how many periods must breach to fire (N in N-of-M).'),
+ cooldown_minutes: zod
+ .number()
+ .min(visionAlertsPartialUpdateBodyCooldownMinutesMin)
+ .default(visionAlertsPartialUpdateBodyCooldownMinutesDefault)
+ .describe('Metric alerts only: minimum minutes between repeated notifications. 0 means no cooldown.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Blocked local time windows when the alert must not notify. Times use the project timezone. Null disables quiet hours.'
+ ),
+ snooze_until: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.'),
+})
+
+/**
+ * Create a notification destination for this alert. One HogFunction is created per alert event kind atomically.
+ */
+export const VisionAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({
+ type: zod
+ .enum(['slack', 'webhook'])
+ .describe('\* `slack` - slack\n\* `webhook` - webhook')
+ .describe('Notification destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook'),
+ slack_workspace_id: zod
+ .number()
+ .optional()
+ .describe('Integration ID for the Slack workspace. Required when type=slack.'),
+ slack_channel_id: zod.string().optional().describe('Slack channel ID. Required when type=slack.'),
+ slack_channel_name: zod.string().optional().describe('Human-readable channel name for display.'),
+ webhook_url: zod.url().optional().describe('HTTPS endpoint to post to. Required when type=webhook.'),
+})
+
+/**
+ * Delete a notification destination by deleting its HogFunction group atomically.
+ */
+export const visionAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 5
+
+export const VisionAlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({
+ hog_function_ids: zod
+ .array(zod.uuid())
+ .min(1)
+ .max(visionAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax)
+ .describe('HogFunction IDs to delete as one atomic destination group.'),
+})
+
/**
* Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires editor access to the scanner.
*/
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index 4cdfcc571341..9a4d6110b988 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -162,6 +162,36 @@ tools:
- created_by
- updated_at
requires_ai_consent: true
+ vision-alerts-create:
+ operation: vision_alerts_create
+ enabled: false
+ vision-alerts-destinations-create:
+ operation: vision_alerts_destinations_create
+ enabled: false
+ vision-alerts-destinations-delete-create:
+ operation: vision_alerts_destinations_delete_create
+ enabled: false
+ vision-alerts-destroy:
+ operation: vision_alerts_destroy
+ enabled: false
+ vision-alerts-events-list:
+ operation: vision_alerts_events_list
+ enabled: false
+ vision-alerts-list:
+ operation: vision_alerts_list
+ enabled: false
+ vision-alerts-partial-update:
+ operation: vision_alerts_partial_update
+ enabled: false
+ vision-alerts-reset-create:
+ operation: vision_alerts_reset_create
+ enabled: false
+ vision-alerts-retrieve:
+ operation: vision_alerts_retrieve
+ enabled: false
+ vision-alerts-update:
+ operation: vision_alerts_update
+ enabled: false
vision-observations-create-task-create:
operation: vision_observations_create_task_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b37a0658d310..2cc60c1f8517 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -57894,6 +57894,208 @@ export namespace Schemas {
results: VisionActionRunList[];
}
+ /**
+ * * `metric` - Metric
+ * * `match` - Match
+ */
+ export type VisionAlertConfigurationKindEnum = typeof VisionAlertConfigurationKindEnum[keyof typeof VisionAlertConfigurationKindEnum];
+
+
+ export const VisionAlertConfigurationKindEnum = {
+ Metric: 'metric',
+ Match: 'match',
+ } as const;
+
+ export interface VisionAlertSelection {
+ /**
+ * Monitor verdicts to match, e.g. ['yes'].
+ * @maxItems 10
+ * @items.maxLength 100
+ */
+ verdict?: string[];
+ /**
+ * Classifier tags to match; an observation matches when it carries any of them.
+ * @maxItems 20
+ * @items.maxLength 200
+ */
+ tags?: string[];
+ /** Minimum scorer score (inclusive). */
+ min_score?: number;
+ /** Maximum scorer score (inclusive). */
+ max_score?: number;
+ }
+
+ /**
+ * * `count` - Count matching observations
+ * * `avg_score` - Average score
+ */
+ export type VisionAlertConfigurationMetricEnum = typeof VisionAlertConfigurationMetricEnum[keyof typeof VisionAlertConfigurationMetricEnum];
+
+
+ export const VisionAlertConfigurationMetricEnum = {
+ Count: 'count',
+ AvgScore: 'avg_score',
+ } as const;
+
+ export interface VisionAlertConfiguration {
+ /** Unique identifier for this alert. */
+ readonly id: string;
+ /** Scanner whose observations this alert watches. Immutable after creation. */
+ scanner_id: string;
+ /**
+ * Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted.
+ * @maxLength 255
+ */
+ name?: string;
+ /** Whether the alert is active. Disabling a metric alert resets its state to not_firing. */
+ enabled?: boolean;
+ /** 'metric' fires when a metric crosses a threshold over a rolling window; 'match' fires on every observation that matches the selection. Immutable after creation.
+ *
+ * * `metric` - Metric
+ * * `match` - Match */
+ kind: VisionAlertConfigurationKindEnum;
+ /** Which observations count. Empty matches every observation of the scanner. */
+ selection?: VisionAlertSelection;
+ /** Metric alerts only: what to measure over the window. 'avg_score' requires a scorer scanner.
+ *
+ * * `count` - Count matching observations
+ * * `avg_score` - Average score */
+ metric?: VisionAlertConfigurationMetricEnum;
+ /** Metric alerts only: whether the alert fires at or above, or at or below, the threshold.
+ *
+ * * `above` - At or above
+ * * `below` - At or below */
+ direction?: VisionAlertDirectionEnum;
+ /**
+ * Metric alerts only: the threshold value. Required for metric alerts, must be omitted for match alerts.
+ * @nullable
+ */
+ threshold?: number | null;
+ /** Metric alerts only: rolling window in days. Allowed values: [1, 3, 7, 14, 30]. */
+ window_days?: number;
+ /**
+ * Metric alerts only: evaluation cadence in minutes, at least 15.
+ * @minimum 15
+ */
+ check_interval_minutes?: number;
+ /** Current lifecycle state. Always not_firing for match alerts. Server-managed.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `pending_resolve` - Pending resolve
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state: LogsAlertConfigurationStateEnum;
+ /**
+ * Metric alerts only: total check periods in the sliding evaluation window (M in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number;
+ /**
+ * Metric alerts only: how many periods must breach to fire (N in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number;
+ /**
+ * Metric alerts only: minimum minutes between repeated notifications. 0 means no cooldown.
+ * @minimum 0
+ */
+ cooldown_minutes?: number;
+ /** Blocked local time windows when the alert must not notify. Times use the project timezone. Null disables quiet hours. */
+ schedule_restriction?: AlertScheduleRestriction | null;
+ /**
+ * ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
+ * @nullable
+ */
+ snooze_until?: string | null;
+ /**
+ * When the next evaluation is scheduled. Server-managed.
+ * @nullable
+ */
+ readonly next_check_at: string | null;
+ /**
+ * When the last notification was sent. Server-managed.
+ * @nullable
+ */
+ readonly last_notified_at: string | null;
+ /**
+ * When the alert was last evaluated. Server-managed.
+ * @nullable
+ */
+ readonly last_checked_at: string | null;
+ /** Consecutive evaluation failures. Resets on success. Server-managed. */
+ readonly consecutive_failures: number;
+ /**
+ * When the alert was first enabled. Null means still a draft.
+ * @nullable
+ */
+ readonly first_enabled_at: string | null;
+ /** When the alert was created. */
+ readonly created_at: string;
+ readonly created_by: UserBasic;
+ /**
+ * When the alert was last modified.
+ * @nullable
+ */
+ readonly updated_at: string | null;
+ }
+
+ export interface PaginatedVisionAlertConfigurationList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: VisionAlertConfiguration[];
+ }
+
+ /**
+ * * `check` - Check
+ * * `reset` - Reset
+ * * `enable` - Enable
+ * * `disable` - Disable
+ * * `snooze` - Snooze
+ * * `unsnooze` - Unsnooze
+ * * `threshold_change` - Threshold change
+ */
+ export type VisionAlertEventKindEnum = typeof VisionAlertEventKindEnum[keyof typeof VisionAlertEventKindEnum];
+
+
+ export const VisionAlertEventKindEnum = {
+ Check: 'check',
+ Reset: 'reset',
+ Enable: 'enable',
+ Disable: 'disable',
+ Snooze: 'snooze',
+ Unsnooze: 'unsnooze',
+ ThresholdChange: 'threshold_change',
+ } as const;
+
+ export interface VisionAlertEvent {
+ readonly id: string;
+ readonly created_at: string;
+ readonly kind: VisionAlertEventKindEnum;
+ readonly state_before: string;
+ readonly state_after: string;
+ readonly threshold_breached: boolean;
+ /** @nullable */
+ readonly metric_value: number | null;
+ /** @nullable */
+ readonly error_message: string | null;
+ }
+
+ export interface PaginatedVisionAlertEventList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: VisionAlertEvent[];
+ }
+
/**
* Shared serializer for the physical-table and saved-query-view annotation surfaces.
*
@@ -66336,6 +66538,112 @@ export namespace Schemas {
readonly updated_at?: string;
}
+ export interface PatchedVisionAlertConfiguration {
+ /** Unique identifier for this alert. */
+ readonly id?: string;
+ /** Scanner whose observations this alert watches. Immutable after creation. */
+ scanner_id?: string;
+ /**
+ * Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted.
+ * @maxLength 255
+ */
+ name?: string;
+ /** Whether the alert is active. Disabling a metric alert resets its state to not_firing. */
+ enabled?: boolean;
+ /** 'metric' fires when a metric crosses a threshold over a rolling window; 'match' fires on every observation that matches the selection. Immutable after creation.
+ *
+ * * `metric` - Metric
+ * * `match` - Match */
+ kind?: VisionAlertConfigurationKindEnum;
+ /** Which observations count. Empty matches every observation of the scanner. */
+ selection?: VisionAlertSelection;
+ /** Metric alerts only: what to measure over the window. 'avg_score' requires a scorer scanner.
+ *
+ * * `count` - Count matching observations
+ * * `avg_score` - Average score */
+ metric?: VisionAlertConfigurationMetricEnum;
+ /** Metric alerts only: whether the alert fires at or above, or at or below, the threshold.
+ *
+ * * `above` - At or above
+ * * `below` - At or below */
+ direction?: VisionAlertDirectionEnum;
+ /**
+ * Metric alerts only: the threshold value. Required for metric alerts, must be omitted for match alerts.
+ * @nullable
+ */
+ threshold?: number | null;
+ /** Metric alerts only: rolling window in days. Allowed values: [1, 3, 7, 14, 30]. */
+ window_days?: number;
+ /**
+ * Metric alerts only: evaluation cadence in minutes, at least 15.
+ * @minimum 15
+ */
+ check_interval_minutes?: number;
+ /** Current lifecycle state. Always not_firing for match alerts. Server-managed.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `pending_resolve` - Pending resolve
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state?: LogsAlertConfigurationStateEnum;
+ /**
+ * Metric alerts only: total check periods in the sliding evaluation window (M in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number;
+ /**
+ * Metric alerts only: how many periods must breach to fire (N in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number;
+ /**
+ * Metric alerts only: minimum minutes between repeated notifications. 0 means no cooldown.
+ * @minimum 0
+ */
+ cooldown_minutes?: number;
+ /** Blocked local time windows when the alert must not notify. Times use the project timezone. Null disables quiet hours. */
+ schedule_restriction?: AlertScheduleRestriction | null;
+ /**
+ * ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
+ * @nullable
+ */
+ snooze_until?: string | null;
+ /**
+ * When the next evaluation is scheduled. Server-managed.
+ * @nullable
+ */
+ readonly next_check_at?: string | null;
+ /**
+ * When the last notification was sent. Server-managed.
+ * @nullable
+ */
+ readonly last_notified_at?: string | null;
+ /**
+ * When the alert was last evaluated. Server-managed.
+ * @nullable
+ */
+ readonly last_checked_at?: string | null;
+ /** Consecutive evaluation failures. Resets on success. Server-managed. */
+ readonly consecutive_failures?: number;
+ /**
+ * When the alert was first enabled. Null means still a draft.
+ * @nullable
+ */
+ readonly first_enabled_at?: string | null;
+ /** When the alert was created. */
+ readonly created_at?: string;
+ readonly created_by?: UserBasic;
+ /**
+ * When the alert was last modified.
+ * @nullable
+ */
+ readonly updated_at?: string | null;
+ }
+
/**
* Shared serializer for the physical-table and saved-query-view annotation surfaces.
*
@@ -84287,6 +84595,48 @@ export namespace Schemas {
readonly observations: readonly RunObservation[];
}
+ /**
+ * * `slack` - slack
+ * * `webhook` - webhook
+ */
+ export type VisionAlertCreateDestinationTypeEnum = typeof VisionAlertCreateDestinationTypeEnum[keyof typeof VisionAlertCreateDestinationTypeEnum];
+
+
+ export const VisionAlertCreateDestinationTypeEnum = {
+ Slack: 'slack',
+ Webhook: 'webhook',
+ } as const;
+
+ export interface VisionAlertCreateDestination {
+ /** Notification destination type.
+ *
+ * * `slack` - slack
+ * * `webhook` - webhook */
+ type: VisionAlertCreateDestinationTypeEnum;
+ /** Integration ID for the Slack workspace. Required when type=slack. */
+ slack_workspace_id?: number;
+ /** Slack channel ID. Required when type=slack. */
+ slack_channel_id?: string;
+ /** Human-readable channel name for display. */
+ slack_channel_name?: string;
+ /** HTTPS endpoint to post to. Required when type=webhook. */
+ webhook_url?: string;
+ }
+
+ export interface VisionAlertDeleteDestination {
+ /**
+ * HogFunction IDs to delete as one atomic destination group.
+ * @minItems 1
+ * @maxItems 5
+ */
+ hog_function_ids: string[];
+ }
+
+ export interface VisionAlertDestinationResponse {
+ /** HogFunctions backing the created destination, one per event kind. */
+ hog_function_ids: string[];
+ }
+
export interface VisionQuota {
/**
* Credits the org may spend per billing period (1 credit = $0.01). Null when billing has synced the product with no spend limit: uncapped.
@@ -96749,6 +97099,45 @@ export namespace Schemas {
offset?: number;
};
+ export type VisionAlertsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type VisionAlertsEventsListParams = {
+ /**
+ * Narrow the history to one event kind.
+ */
+ kind?: VisionAlertsEventsListKind;
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type VisionAlertsEventsListKind = typeof VisionAlertsEventsListKind[keyof typeof VisionAlertsEventsListKind];
+
+
+ export const VisionAlertsEventsListKind = {
+ Check: 'check',
+ Disable: 'disable',
+ Enable: 'enable',
+ Reset: 'reset',
+ Snooze: 'snooze',
+ ThresholdChange: 'threshold_change',
+ Unsnooze: 'unsnooze',
+ } as const;
+
export type VisionObservationsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index fae772467fca..c2feca2c8aaa 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -203,6 +203,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'user_interview:write',
'vision_action:read',
'vision_action:write',
+ 'vision_alert:read',
+ 'vision_alert:write',
'visual_review:read',
'visual_review:write',
'warehouse_objects:read',
diff --git a/tach.toml b/tach.toml
index a41751ed3b6e..29362e49c3ea 100644
--- a/tach.toml
+++ b/tach.toml
@@ -693,6 +693,7 @@ path = "products.replay_vision"
depends_on = [
"ee",
"posthog",
+ "products.alerts",
"products.cdp",
"products.cohorts",
"products.experiments",