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(alerts): extract shared alert lifecycle state machine (1/6) (#68936)

Matt Puaf34776e4e4ff
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
new file mode 100644
index 000000000000..9d4d1e1e20aa
--- /dev/null
+++ b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
@@ -0,0 +1,56 @@
+# Enforces the invariant that ALL writes to an alert configuration's `state` and
+# `consecutive_failures` go through the product's alert state machine module.
+#
+# The decision logic is shared across products in common/alerting/state_machine.py;
+# each product owns one module that is the single legal mutator of its alert model:
+# - products/logs/backend/alert_state_machine.py (apply_outcome)
+#
+# There are dedicated helpers for every legal control-plane transition
+# (apply_user_reset, apply_enable, apply_disable, apply_snooze, apply_unsnooze,
+# apply_threshold_change), and the check-driven path goes through evaluate_alert_check.
+#
+# If you need a new transition, add a helper in common/alerting/state_machine.py (or
+# the product's state machine module) rather than bypassing this rule — the point is
+# to keep the legal-transitions table readable in one place.
+#
+# When a new product adopts the shared machine, add its backend to paths.include and
+# its state machine module + tests to paths.exclude below.
+rules:
+ - id: alert-state-direct-mutation
+ patterns:
+ - pattern-either:
+ - pattern: $ALERT.state = $VALUE
+ - pattern: $ALERT.consecutive_failures = $VALUE
+ message: |
+ Direct mutation of an alert configuration's .state / .consecutive_failures
+ bypasses the product's alert state machine module, which is the single
+ source of truth for alert state transitions.
+
+ Route state changes through the state machine instead, e.g. for logs:
+
+ from products.logs.backend.alert_state_machine import (
+ apply_outcome, apply_user_reset, apply_disable, ...
+ )
+
+ outcome = apply_user_reset(alert.to_snapshot())
+ update_fields = apply_outcome(alert, outcome)
+ alert.save(update_fields=update_fields)
+
+ If you need a new transition type, add a helper in
+ common/alerting/state_machine.py (e.g. apply_<your_action>) and a
+ ControlPlaneOutcome return — do not mutate these fields directly.
+ languages: [python]
+ severity: ERROR
+ metadata:
+ category: correctness
+ subcategory: audit
+ confidence: HIGH
+ paths:
+ include:
+ - '/products/logs/backend/**/*.py'
+ exclude:
+ # The state machine itself — apply_outcome is the one legal mutator.
+ - '/products/logs/backend/alert_state_machine.py'
+ # Test files — fixtures and parametrized snapshots set state directly.
+ - '/products/logs/backend/test/**'
+ - '/products/logs/backend/**/test_*.py'
diff --git a/.semgrep/rules/security/logs-alert-state-must-go-through-state-machine.yaml b/.semgrep/rules/security/logs-alert-state-must-go-through-state-machine.yaml
deleted file mode 100644
index cf698d813ab8..000000000000
--- a/.semgrep/rules/security/logs-alert-state-must-go-through-state-machine.yaml
+++ /dev/null
@@ -1,52 +0,0 @@
-# Enforces the invariant that ALL writes to LogsAlertConfiguration.state and
-# LogsAlertConfiguration.consecutive_failures go through alert_state_machine.apply_outcome.
-#
-# See products/logs/backend/alert_state_machine.py for the full transition API —
-# there are dedicated helpers for every legal control-plane transition
-# (apply_user_reset, apply_enable, apply_disable, apply_snooze, apply_unsnooze,
-# apply_threshold_change), and the check-driven path goes through evaluate_alert_check.
-# Every outcome flows through apply_outcome, which is the ONLY mutator in the
-# codebase allowed to assign these fields.
-#
-# If you need a new transition, add a helper in alert_state_machine.py rather than
-# bypassing this rule — the point is to keep the legal-transitions table readable
-# in one file.
-rules:
- - id: logs-alert-state-direct-mutation
- patterns:
- - pattern-either:
- - pattern: $ALERT.state = $VALUE
- - pattern: $ALERT.consecutive_failures = $VALUE
- message: |
- Direct mutation of LogsAlertConfiguration.state / .consecutive_failures
- bypasses alert_state_machine.py, which is the single source of truth for
- alert state transitions.
-
- Route state changes through the state machine instead:
-
- from products.logs.backend.alert_state_machine import (
- apply_outcome, apply_user_reset, apply_disable, ...
- )
-
- outcome = apply_user_reset(alert.to_snapshot())
- update_fields = apply_outcome(alert, outcome)
- alert.save(update_fields=update_fields)
-
- If you need a new transition type, add a helper in alert_state_machine.py
- (e.g. apply_<your_action>) and a ControlPlaneOutcome return — do not
- mutate these fields directly.
- languages: [python]
- severity: ERROR
- metadata:
- category: correctness
- subcategory: audit
- confidence: HIGH
- paths:
- include:
- - '/products/logs/backend/**/*.py'
- exclude:
- # The state machine itself — apply_outcome is the one legal mutator.
- - '/products/logs/backend/alert_state_machine.py'
- # Test files — fixtures and parametrized snapshots set state directly.
- - '/products/logs/backend/test/**'
- - '/products/logs/backend/**/test_*.py'
diff --git a/common/alerting/__init__.py b/common/alerting/__init__.py
new file mode 100644
index 000000000000..39f10338ba34
--- /dev/null
+++ b/common/alerting/__init__.py
@@ -0,0 +1,43 @@
+from common.alerting.state_machine import (
+ LOGS_ALERT_POLICY,
+ MAX_CONSECUTIVE_FAILURES,
+ AlertCheckOutcome,
+ AlertPolicy,
+ AlertSnapshot,
+ AlertState,
+ CheckInput,
+ ControlPlaneOutcome,
+ InvalidTransition,
+ NotificationAction,
+ Outcome,
+ apply_disable,
+ apply_enable,
+ apply_snooze,
+ apply_threshold_change,
+ apply_unsnooze,
+ apply_user_reset,
+ evaluate_alert_check,
+ evaluate_alert_failure,
+)
+
+__all__ = [
+ "LOGS_ALERT_POLICY",
+ "MAX_CONSECUTIVE_FAILURES",
+ "AlertCheckOutcome",
+ "AlertPolicy",
+ "AlertSnapshot",
+ "AlertState",
+ "CheckInput",
+ "ControlPlaneOutcome",
+ "InvalidTransition",
+ "NotificationAction",
+ "Outcome",
+ "apply_disable",
+ "apply_enable",
+ "apply_snooze",
+ "apply_threshold_change",
+ "apply_unsnooze",
+ "apply_user_reset",
+ "evaluate_alert_check",
+ "evaluate_alert_failure",
+]
diff --git a/common/alerting/state_machine.py b/common/alerting/state_machine.py
new file mode 100644
index 000000000000..ab21a66704c7
--- /dev/null
+++ b/common/alerting/state_machine.py
@@ -0,0 +1,378 @@
+"""Shared alert lifecycle state machine.
+
+Products (logs, billing, ...) each evaluate their own domain data, but the alert
+lifecycle — firing, resolving, erroring, breaking, snoozing, cooldown suppression —
+is the same machine everywhere. This module is that machine, following the
+Prometheus/Alertmanager split: evaluation stays domain-specific in each product,
+lifecycle decisions live here, and the contract between them is `CheckInput` in and
+`AlertCheckOutcome` out.
+
+Product semantics differ in deliberate, documented ways (e.g. logs never re-notifies
+while an alert stays firing; billing re-notifies once per cooldown window). Those
+differences are expressed as an `AlertPolicy` so each product is a configuration of
+the same decision table rather than a fork of it.
+
+This module is pure Python — no Django, no product imports. Products own persistence:
+they build a snapshot from their model, call the machine, and apply the outcome through
+their product-local `apply_outcome` (the single legal mutator, enforced by semgrep —
+see `.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml`).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from enum import Enum, StrEnum
+from typing import Protocol
+
+MAX_CONSECUTIVE_FAILURES = 5
+
+
+class AlertState(StrEnum):
+ NOT_FIRING = "not_firing"
+ FIRING = "firing"
+ # Input-only: accepted from adopters whose models persist it, never produced here.
+ PENDING_RESOLVE = "pending_resolve"
+ ERRORED = "errored"
+ SNOOZED = "snoozed"
+ BROKEN = "broken"
+
+
+class NotificationAction(Enum):
+ NONE = "none"
+ FIRE = "fire"
+ RESOLVE = "resolve"
+ ERROR = "error"
+ BROKEN = "broken"
+
+
+class InvalidTransition(Exception):
+ """Raised by control-plane transitions when the pre-condition isn't met."""
+
+
+@dataclass(frozen=True)
+class AlertPolicy:
+ """Per-product lifecycle semantics. Defaults are the logs alerting behavior.
+
+ Every flag encodes a real, observed divergence between products — do not add a
+ flag speculatively, and do not change a default without checking every adopter.
+ """
+
+ max_consecutive_failures: int = MAX_CONSECUTIVE_FAILURES
+ # True (logs): BROKEN is terminal until an explicit user reset. False (billing):
+ # a successful check on a BROKEN alert re-evaluates it from scratch — manual
+ # check-now is billing's only un-break path.
+ broken_is_terminal: bool = True
+ # Whether transient errors (e.g. query timeouts) count toward BROKEN.
+ transient_errors_count_toward_broken: bool = False
+ # False: notify ERROR only on the first transition into ERRORED. True: every failure.
+ notify_error_on_every_failure: bool = False
+ # False: cooldown only suppresses the re-FIRE of an already-FIRING alert;
+ # the first FIRE after a resolve is never suppressed.
+ cooldown_gates_initial_fire: bool = True
+ cooldown_gates_resolve: bool = True
+ # True: an alert that stays breached re-notifies once per cooldown window.
+ renotify_while_firing: bool = False
+ # True (billing): snooze only mutes while breached — a clear check resolves and
+ # un-snoozes; a breached check parks the alert in SNOOZED without notifying.
+ # False (logs): a snoozed alert stays snoozed untouched until snooze_until passes.
+ clear_check_ends_snooze: bool = False
+ # True: reaching BROKEN also disables the alert (outcome.disable is set).
+ disable_when_broken: bool = False
+
+
+LOGS_ALERT_POLICY = AlertPolicy()
+
+
+@dataclass(frozen=True)
+class CheckInput:
+ """Normalized result of one domain evaluation — all the machine needs to know."""
+
+ threshold_breached: bool
+ # Evaluation couldn't reach a verdict (e.g. source data not settled yet): state
+ # and failure counter are left unchanged and no notification is emitted.
+ is_inconclusive: bool = False
+ error_message: str | None = None
+ is_transient_error: bool = False
+
+
+@dataclass(frozen=True)
+class AlertSnapshot:
+ """The fields the machine reads to decide a transition."""
+
+ state: AlertState
+ cooldown: timedelta
+ last_notified_at: datetime | None
+ snooze_until: datetime | None
+ consecutive_failures: int
+ # N-of-M sliding window (CloudWatch-style). 1-of-1 means "fire on any breach".
+ evaluation_periods: int = 1
+ datapoints_to_alarm: int = 1
+ # Breach flags of the most recent prior checks, newest first (excludes the current one).
+ recent_events_breached: tuple[bool, ...] = ()
+
+
+class StatefulSnapshot(Protocol):
+ """What control-plane transitions need — satisfied by any product snapshot type."""
+
+ @property
+ def state(self) -> AlertState: ...
+
+ @property
+ def consecutive_failures(self) -> int: ...
+
+
+@dataclass(frozen=True)
+class AlertCheckOutcome:
+ new_state: AlertState
+ notification: NotificationAction
+ consecutive_failures: int
+ update_last_notified_at: bool
+ error_message: str | None
+ # Set when policy.disable_when_broken kicks in — the adapter must persist enabled=False.
+ disable: bool = False
+
+
+@dataclass(frozen=True)
+class ControlPlaneOutcome:
+ """Outcome of a user-initiated or serializer-driven transition.
+
+ Shares `new_state` + `consecutive_failures` with `AlertCheckOutcome` so both
+ can flow through a product's `apply_outcome` uniformly.
+ """
+
+ new_state: AlertState
+ consecutive_failures: int
+
+
+Outcome = AlertCheckOutcome | ControlPlaneOutcome
+
+
+def _stay(snapshot: AlertSnapshot) -> AlertCheckOutcome:
+ return AlertCheckOutcome(
+ new_state=snapshot.state,
+ notification=NotificationAction.NONE,
+ consecutive_failures=snapshot.consecutive_failures,
+ update_last_notified_at=False,
+ error_message=None,
+ )
+
+
+def evaluate_alert_check(
+ snapshot: AlertSnapshot,
+ check: CheckInput,
+ now: datetime,
+ *,
+ policy: AlertPolicy,
+) -> AlertCheckOutcome:
+ """Decide the transition for one scheduled/manual check.
+
+ N-of-M sliding-window trigger for firing, immediate resolution on the first OK
+ window, cooldown suppression per policy, and error escalation to BROKEN.
+
+ Under default (logs-style) snooze semantics, a future `snooze_until` only
+ suppresses evaluation when state is also SNOOZED — adopters must set both
+ together on snooze (as logs' apply_snooze path does); a stray future
+ `snooze_until` on a non-SNOOZED alert is not honored here.
+ """
+ if snapshot.state == AlertState.BROKEN and policy.broken_is_terminal:
+ # Terminal until a user reset — schedulers already exclude BROKEN alerts,
+ # this is belt-and-braces against a race.
+ return _stay(snapshot)
+
+ snoozing = snapshot.snooze_until is not None and snapshot.snooze_until > now
+
+ if snapshot.state == AlertState.SNOOZED and snoozing and not policy.clear_check_ends_snooze:
+ return _stay(snapshot)
+
+ if check.error_message is not None:
+ return evaluate_alert_failure(
+ snapshot,
+ error_message=check.error_message,
+ is_transient_error=check.is_transient_error,
+ policy=policy,
+ )
+
+ if check.is_inconclusive:
+ return AlertCheckOutcome(
+ new_state=snapshot.state,
+ notification=NotificationAction.NONE,
+ consecutive_failures=snapshot.consecutive_failures,
+ update_last_notified_at=False,
+ error_message=None,
+ )
+
+ if snoozing and check.threshold_breached and policy.clear_check_ends_snooze:
+ # Breach while muted: park in SNOOZED without notifying, whatever the prior state.
+ return AlertCheckOutcome(
+ new_state=AlertState.SNOOZED,
+ notification=NotificationAction.NONE,
+ consecutive_failures=0,
+ update_last_notified_at=False,
+ error_message=None,
+ )
+
+ if snapshot.state == AlertState.SNOOZED:
+ # clear_check_ends_snooze: a snoozed alert was breached when parked, so a clear
+ # check resolves it (FIRING-like). Otherwise the snooze simply expired and the
+ # alert re-evaluates from scratch.
+ effective_state = AlertState.FIRING if policy.clear_check_ends_snooze else AlertState.NOT_FIRING
+ elif snapshot.state in (AlertState.ERRORED, AlertState.BROKEN):
+ # BROKEN is only reachable here when the policy allows checks to un-break.
+ effective_state = AlertState.NOT_FIRING
+ else:
+ effective_state = snapshot.state
+
+ window = [check.threshold_breached, *snapshot.recent_events_breached][: snapshot.evaluation_periods]
+ breach_count = sum(1 for b in window if b)
+ breached = breach_count >= snapshot.datapoints_to_alarm
+
+ notification = NotificationAction.NONE
+
+ if effective_state == AlertState.NOT_FIRING:
+ if breached:
+ new_state = AlertState.FIRING
+ notification = NotificationAction.FIRE
+ else:
+ new_state = AlertState.NOT_FIRING
+
+ elif effective_state in (AlertState.FIRING, AlertState.PENDING_RESOLVE):
+ if breached:
+ new_state = AlertState.FIRING
+ if policy.renotify_while_firing:
+ notification = NotificationAction.FIRE
+ else:
+ new_state = AlertState.NOT_FIRING
+ notification = NotificationAction.RESOLVE
+
+ else:
+ new_state = AlertState.NOT_FIRING
+
+ update_last_notified_at = False
+ if notification != NotificationAction.NONE:
+ if notification == NotificationAction.FIRE:
+ # Raw state, not effective_state: a snooze-expiry refire counts as an
+ # initial fire, so it's only gated when the policy gates initial fires.
+ gated = policy.cooldown_gates_initial_fire or snapshot.state == AlertState.FIRING
+ else:
+ gated = policy.cooldown_gates_resolve
+ if gated and _is_within_cooldown(snapshot.last_notified_at, snapshot.cooldown, now):
+ notification = NotificationAction.NONE
+ else:
+ update_last_notified_at = True
+
+ return AlertCheckOutcome(
+ new_state=new_state,
+ notification=notification,
+ consecutive_failures=0,
+ update_last_notified_at=update_last_notified_at,
+ error_message=None,
+ )
+
+
+def evaluate_alert_failure(
+ snapshot: AlertSnapshot,
+ *,
+ error_message: str,
+ is_transient_error: bool = False,
+ policy: AlertPolicy,
+) -> AlertCheckOutcome:
+ """Decide the transition for a failed evaluation (query error, upstream outage, ...).
+
+ Callable directly by products whose evaluators raise instead of returning an
+ error CheckInput; `evaluate_alert_check` routes here for the rest.
+
+ Errors never move firing state — only threshold checks do (CloudWatch's
+ INSUFFICIENT_DATA doesn't clear ALARM). A FIRING alert rides through a failed
+ check so recovery continues the episode instead of re-firing it. The failure
+ counter carries the escalation-to-BROKEN signal; the persisted state is kept.
+ """
+ if is_transient_error and not policy.transient_errors_count_toward_broken:
+ # Transient errors (cluster blips, `unknown`) hit whole cohorts at once, so
+ # notifying broadcasts noise to every destination. Skip the cycle entirely —
+ # keep state and counter untouched; the next check retries naturally.
+ return AlertCheckOutcome(
+ new_state=snapshot.state,
+ notification=NotificationAction.NONE,
+ consecutive_failures=snapshot.consecutive_failures,
+ update_last_notified_at=False,
+ error_message=error_message,
+ )
+
+ consecutive_failures = snapshot.consecutive_failures + 1
+
+ if consecutive_failures >= policy.max_consecutive_failures:
+ return AlertCheckOutcome(
+ new_state=AlertState.BROKEN,
+ notification=NotificationAction.BROKEN,
+ consecutive_failures=consecutive_failures,
+ update_last_notified_at=False,
+ error_message=error_message,
+ disable=policy.disable_when_broken,
+ )
+
+ # Notify once per error streak (0 -> 1), not on every failed check. Using the
+ # counter (not the state) means a SNOOZED auto-expiry can't re-trigger it.
+ if policy.notify_error_on_every_failure or snapshot.consecutive_failures == 0:
+ notification = NotificationAction.ERROR
+ else:
+ notification = NotificationAction.NONE
+
+ return AlertCheckOutcome(
+ new_state=snapshot.state,
+ notification=notification,
+ consecutive_failures=consecutive_failures,
+ update_last_notified_at=False,
+ error_message=error_message,
+ )
+
+
+def apply_user_reset(snapshot: StatefulSnapshot) -> ControlPlaneOutcome:
+ if snapshot.state != AlertState.BROKEN:
+ raise InvalidTransition(f"Only broken alerts can be reset. Current state is {snapshot.state.value}.")
+ return ControlPlaneOutcome(new_state=AlertState.NOT_FIRING, consecutive_failures=0)
+
+
+def apply_disable(snapshot: StatefulSnapshot) -> ControlPlaneOutcome:
+ # Preserve consecutive_failures so re-enable without reset doesn't silently
+ # wipe forensic state.
+ return ControlPlaneOutcome(
+ new_state=AlertState.NOT_FIRING,
+ consecutive_failures=snapshot.consecutive_failures,
+ )
+
+
+def apply_enable(snapshot: StatefulSnapshot) -> ControlPlaneOutcome:
+ return ControlPlaneOutcome(new_state=AlertState.NOT_FIRING, consecutive_failures=0)
+
+
+def apply_snooze(snapshot: StatefulSnapshot) -> ControlPlaneOutcome:
+ return ControlPlaneOutcome(
+ new_state=AlertState.SNOOZED,
+ consecutive_failures=snapshot.consecutive_failures,
+ )
+
+
+def apply_unsnooze(snapshot: StatefulSnapshot) -> ControlPlaneOutcome:
+ return ControlPlaneOutcome(new_state=AlertState.NOT_FIRING, consecutive_failures=0)
+
+
+def apply_threshold_change(snapshot: StatefulSnapshot) -> ControlPlaneOutcome:
+ # Snoozed alerts stay snoozed on edit — editing configuration must not wake a
+ # silenced alert.
+ if snapshot.state == AlertState.SNOOZED:
+ return ControlPlaneOutcome(
+ new_state=AlertState.SNOOZED,
+ consecutive_failures=snapshot.consecutive_failures,
+ )
+ return ControlPlaneOutcome(new_state=AlertState.NOT_FIRING, consecutive_failures=0)
+
+
+def _is_within_cooldown(
+ last_notified_at: datetime | None,
+ cooldown: timedelta,
+ now: datetime,
+) -> bool:
+ if cooldown <= timedelta(0) or last_notified_at is None:
+ return False
+ return now < last_notified_at + cooldown
diff --git a/common/alerting/test/test_state_machine.py b/common/alerting/test/test_state_machine.py
new file mode 100644
index 000000000000..e7a255b37929
--- /dev/null
+++ b/common/alerting/test/test_state_machine.py
@@ -0,0 +1,263 @@
+from datetime import UTC, datetime, timedelta
+
+from parameterized import parameterized
+
+from common.alerting.state_machine import (
+ LOGS_ALERT_POLICY,
+ AlertCheckOutcome,
+ AlertPolicy,
+ AlertSnapshot,
+ AlertState,
+ CheckInput,
+ NotificationAction,
+ evaluate_alert_check,
+)
+
+NOW = datetime(2026, 3, 19, 12, 0, tzinfo=UTC)
+
+BREACH = CheckInput(threshold_breached=True)
+CLEAR = CheckInput(threshold_breached=False)
+ERROR = CheckInput(threshold_breached=False, error_message="query failed")
+TRANSIENT_ERROR = CheckInput(threshold_breached=False, error_message="timeout", is_transient_error=True)
+INCONCLUSIVE = CheckInput(threshold_breached=False, is_inconclusive=True)
+
+# Non-default flags one at a time, so a broken flag branch fails its own row.
+UNBREAKABLE = AlertPolicy(broken_is_terminal=False)
+TRANSIENT_BREAKS = AlertPolicy(transient_errors_count_toward_broken=True)
+NOISY_ERRORS = AlertPolicy(notify_error_on_every_failure=True)
+UNGATED_FIRST_FIRE = AlertPolicy(cooldown_gates_initial_fire=False)
+UNGATED_RESOLVE = AlertPolicy(cooldown_gates_resolve=False)
+RENOTIFY = AlertPolicy(renotify_while_firing=True)
+SNOOZE_UNTIL_CLEAR = AlertPolicy(clear_check_ends_snooze=True)
+DISABLE_ON_BROKEN = AlertPolicy(disable_when_broken=True)
+BREAKS_EARLY = AlertPolicy(max_consecutive_failures=2)
+
+
+def snapshot(**overrides) -> AlertSnapshot:
+ defaults: dict = {
+ "state": AlertState.NOT_FIRING,
+ "cooldown": timedelta(minutes=30),
+ "last_notified_at": None,
+ "snooze_until": None,
+ "consecutive_failures": 0,
+ }
+ return AlertSnapshot(**{**defaults, **overrides})
+
+
+IN_COOLDOWN = NOW - timedelta(minutes=5)
+SNOOZING = NOW + timedelta(hours=1)
+
+
+class TestPolicyDecisionTable:
+ @parameterized.expand(
+ [
+ # broken_is_terminal=False: a check on a BROKEN alert re-evaluates from scratch
+ (
+ "unbreak_clear",
+ UNBREAKABLE,
+ snapshot(state=AlertState.BROKEN),
+ CLEAR,
+ AlertState.NOT_FIRING,
+ NotificationAction.NONE,
+ ),
+ (
+ "unbreak_breach",
+ UNBREAKABLE,
+ snapshot(state=AlertState.BROKEN),
+ BREACH,
+ AlertState.FIRING,
+ NotificationAction.FIRE,
+ ),
+ (
+ "terminal_broken_ignores_breach",
+ LOGS_ALERT_POLICY,
+ snapshot(state=AlertState.BROKEN),
+ BREACH,
+ AlertState.BROKEN,
+ NotificationAction.NONE,
+ ),
+ # transient_errors_count_toward_broken
+ (
+ "transient_error_spared",
+ LOGS_ALERT_POLICY,
+ snapshot(state=AlertState.ERRORED, consecutive_failures=4),
+ TRANSIENT_ERROR,
+ AlertState.ERRORED,
+ NotificationAction.NONE,
+ ),
+ (
+ "transient_error_breaks",
+ TRANSIENT_BREAKS,
+ snapshot(state=AlertState.ERRORED, consecutive_failures=4),
+ TRANSIENT_ERROR,
+ AlertState.BROKEN,
+ NotificationAction.BROKEN,
+ ),
+ # max_consecutive_failures: breaks at the policy's threshold, not the default constant
+ (
+ "custom_failure_threshold_breaks",
+ BREAKS_EARLY,
+ snapshot(state=AlertState.ERRORED, consecutive_failures=1),
+ ERROR,
+ AlertState.BROKEN,
+ NotificationAction.BROKEN,
+ ),
+ # notify_error_on_every_failure
+ (
+ "repeat_error_quiet",
+ LOGS_ALERT_POLICY,
+ snapshot(state=AlertState.ERRORED, consecutive_failures=1),
+ ERROR,
+ AlertState.ERRORED,
+ NotificationAction.NONE,
+ ),
+ (
+ "repeat_error_notifies",
+ NOISY_ERRORS,
+ snapshot(state=AlertState.ERRORED, consecutive_failures=1),
+ ERROR,
+ AlertState.ERRORED,
+ NotificationAction.ERROR,
+ ),
+ # cooldown_gates_initial_fire
+ (
+ "initial_fire_gated",
+ LOGS_ALERT_POLICY,
+ snapshot(last_notified_at=IN_COOLDOWN),
+ BREACH,
+ AlertState.FIRING,
+ NotificationAction.NONE,
+ ),
+ (
+ "initial_fire_ungated",
+ UNGATED_FIRST_FIRE,
+ snapshot(last_notified_at=IN_COOLDOWN),
+ BREACH,
+ AlertState.FIRING,
+ NotificationAction.FIRE,
+ ),
+ # cooldown never spares the re-fire of an already-FIRING alert, even ungated
+ (
+ "refire_still_gated",
+ AlertPolicy(cooldown_gates_initial_fire=False, renotify_while_firing=True),
+ snapshot(state=AlertState.FIRING, last_notified_at=IN_COOLDOWN),
+ BREACH,
+ AlertState.FIRING,
+ NotificationAction.NONE,
+ ),
+ # cooldown_gates_resolve
+ (
+ "resolve_gated",
+ LOGS_ALERT_POLICY,
+ snapshot(state=AlertState.FIRING, last_notified_at=IN_COOLDOWN),
+ CLEAR,
+ AlertState.NOT_FIRING,
+ NotificationAction.NONE,
+ ),
+ (
+ "resolve_ungated",
+ UNGATED_RESOLVE,
+ snapshot(state=AlertState.FIRING, last_notified_at=IN_COOLDOWN),
+ CLEAR,
+ AlertState.NOT_FIRING,
+ NotificationAction.RESOLVE,
+ ),
+ # renotify_while_firing
+ (
+ "refire_quiet",
+ LOGS_ALERT_POLICY,
+ snapshot(state=AlertState.FIRING),
+ BREACH,
+ AlertState.FIRING,
+ NotificationAction.NONE,
+ ),
+ (
+ "refire_notifies",
+ RENOTIFY,
+ snapshot(state=AlertState.FIRING),
+ BREACH,
+ AlertState.FIRING,
+ NotificationAction.FIRE,
+ ),
+ # clear_check_ends_snooze
+ (
+ "snoozed_stays_untouched",
+ LOGS_ALERT_POLICY,
+ snapshot(state=AlertState.SNOOZED, snooze_until=SNOOZING),
+ CLEAR,
+ AlertState.SNOOZED,
+ NotificationAction.NONE,
+ ),
+ (
+ "breach_parks_in_snooze",
+ SNOOZE_UNTIL_CLEAR,
+ snapshot(state=AlertState.FIRING, snooze_until=SNOOZING),
+ BREACH,
+ AlertState.SNOOZED,
+ NotificationAction.NONE,
+ ),
+ (
+ "clear_ends_snooze_and_resolves",
+ SNOOZE_UNTIL_CLEAR,
+ snapshot(state=AlertState.SNOOZED, snooze_until=SNOOZING, cooldown=timedelta(0)),
+ CLEAR,
+ AlertState.NOT_FIRING,
+ NotificationAction.RESOLVE,
+ ),
+ # snooze expiry under defaults: re-evaluates from scratch, breach is an initial fire
+ (
+ "expired_snooze_refires",
+ LOGS_ALERT_POLICY,
+ snapshot(state=AlertState.SNOOZED, snooze_until=NOW - timedelta(minutes=1)),
+ BREACH,
+ AlertState.FIRING,
+ NotificationAction.FIRE,
+ ),
+ # inconclusive: state and failure counter untouched
+ (
+ "inconclusive_preserves_state",
+ LOGS_ALERT_POLICY,
+ snapshot(state=AlertState.ERRORED, consecutive_failures=3),
+ INCONCLUSIVE,
+ AlertState.ERRORED,
+ NotificationAction.NONE,
+ ),
+ ]
+ )
+ def test_decision(
+ self,
+ _name: str,
+ policy: AlertPolicy,
+ snap: AlertSnapshot,
+ check: CheckInput,
+ expected_state: AlertState,
+ expected_notification: NotificationAction,
+ ) -> None:
+ outcome = evaluate_alert_check(snap, check, NOW, policy=policy)
+ assert outcome.new_state == expected_state
+ assert outcome.notification == expected_notification
+
+ def test_inconclusive_preserves_failure_counter(self) -> None:
+ outcome = evaluate_alert_check(
+ snapshot(state=AlertState.ERRORED, consecutive_failures=3), INCONCLUSIVE, NOW, policy=LOGS_ALERT_POLICY
+ )
+ assert outcome.consecutive_failures == 3
+
+ @parameterized.expand(
+ [
+ ("default_keeps_enabled", LOGS_ALERT_POLICY, False),
+ ("policy_disables", DISABLE_ON_BROKEN, True),
+ ]
+ )
+ def test_disable_when_broken(self, _name: str, policy: AlertPolicy, expected_disable: bool) -> None:
+ outcome = evaluate_alert_check(
+ snapshot(state=AlertState.ERRORED, consecutive_failures=4), ERROR, NOW, policy=policy
+ )
+ assert outcome == AlertCheckOutcome(
+ new_state=AlertState.BROKEN,
+ notification=NotificationAction.BROKEN,
+ consecutive_failures=5,
+ update_last_notified_at=False,
+ error_message="query failed",
+ disable=expected_disable,
+ )
diff --git a/products/logs/backend/alert_state_machine.py b/products/logs/backend/alert_state_machine.py
index 3e1fd3cdc8dc..694c30116781 100644
--- a/products/logs/backend/alert_state_machine.py
+++ b/products/logs/backend/alert_state_machine.py
@@ -6,42 +6,62 @@ control-plane path goes through one of the `apply_*` helpers, and every caller a
the resulting outcome via `apply_outcome`, which is the only function in the codebase
that mutates those two fields.
-The semgrep rule at `.semgrep/rules/security/logs-alert-state-must-go-through-state-machine.yaml`
+The semgrep rule at `.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml`
enforces this invariant in CI.
+
+The decision logic itself lives in the shared machine at `common/alerting/state_machine.py`
+(configured here with `LOGS_ALERT_POLICY`); this module owns the logs-shaped inputs
+(`AlertSnapshot`, `CheckResult`) and the model mutation (`apply_outcome`).
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta
-from enum import Enum, StrEnum
-from typing import TYPE_CHECKING, Union
+from typing import TYPE_CHECKING
+
+from common.alerting.state_machine import (
+ LOGS_ALERT_POLICY,
+ MAX_CONSECUTIVE_FAILURES,
+ AlertCheckOutcome,
+ 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.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
-MAX_CONSECUTIVE_FAILURES = 5
-
-
-class AlertState(StrEnum):
- NOT_FIRING = "not_firing"
- FIRING = "firing"
- PENDING_RESOLVE = "pending_resolve"
- ERRORED = "errored"
- SNOOZED = "snoozed"
- BROKEN = "broken"
-
-
-class NotificationAction(Enum):
- NONE = "none"
- FIRE = "fire"
- RESOLVE = "resolve"
- ERROR = "error"
- BROKEN = "broken"
-
-
-class InvalidTransition(Exception):
- """Raised by control-plane transitions when the pre-condition isn't met."""
+__all__ = [
+ "MAX_CONSECUTIVE_FAILURES",
+ "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",
+]
@dataclass(frozen=True)
@@ -65,30 +85,6 @@ class AlertSnapshot:
recent_events_breached: tuple[bool, ...]
-@dataclass(frozen=True)
-class AlertCheckOutcome:
- new_state: AlertState
- notification: NotificationAction
- consecutive_failures: int
- update_last_notified_at: bool
- error_message: str | None
-
-
-@dataclass(frozen=True)
-class ControlPlaneOutcome:
- """Outcome of a user-initiated or serializer-driven transition.
-
- Shares `new_state` + `consecutive_failures` with `AlertCheckOutcome` so both
- can flow through `apply_outcome` uniformly.
- """
-
- new_state: AlertState
- consecutive_failures: int
-
-
-Outcome = Union[AlertCheckOutcome, ControlPlaneOutcome]
-
-
def evaluate_alert_check(
snapshot: AlertSnapshot,
check: CheckResult,
@@ -98,149 +94,27 @@ def evaluate_alert_check(
(CloudWatch-style) for firing, immediate resolution on the first OK
check, and cooldown suppression.
"""
- if snapshot.state == AlertState.BROKEN:
- # Terminal until a user reset — the scheduler already excludes BROKEN alerts,
- # this is belt-and-braces against a race.
- return AlertCheckOutcome(
- new_state=AlertState.BROKEN,
- notification=NotificationAction.NONE,
+ 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,
- update_last_notified_at=False,
- error_message=None,
- )
-
- if snapshot.state == AlertState.SNOOZED:
- if snapshot.snooze_until is not None and snapshot.snooze_until > now:
- return AlertCheckOutcome(
- new_state=AlertState.SNOOZED,
- notification=NotificationAction.NONE,
- consecutive_failures=snapshot.consecutive_failures,
- update_last_notified_at=False,
- error_message=None,
- )
- effective_state = AlertState.NOT_FIRING
- else:
- effective_state = snapshot.state
-
- if check.error_message is not None:
- # Errors never move firing state — only threshold checks do (CloudWatch's
- # INSUFFICIENT_DATA doesn't clear ALARM). A FIRING alert rides through a
- # failed check, so recovery continues the episode instead of re-firing it.
- if check.is_transient_error:
- # Transient errors (cluster blips, `unknown`) hit whole cohorts at
- # once; notifying would broadcast noise to every destination. Skip
- # the cycle entirely — the next check retries naturally.
- return AlertCheckOutcome(
- new_state=snapshot.state,
- notification=NotificationAction.NONE,
- consecutive_failures=snapshot.consecutive_failures,
- update_last_notified_at=False,
- error_message=check.error_message,
- )
- consecutive_failures = snapshot.consecutive_failures + 1
- if consecutive_failures >= MAX_CONSECUTIVE_FAILURES:
- new_state = AlertState.BROKEN
- notification = NotificationAction.BROKEN
- else:
- new_state = snapshot.state
- # Notify once per error streak (0 → 1), not on every failed check.
- notification = NotificationAction.ERROR if snapshot.consecutive_failures == 0 else NotificationAction.NONE
- return AlertCheckOutcome(
- new_state=new_state,
- notification=notification,
- consecutive_failures=consecutive_failures,
- update_last_notified_at=False,
+ 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,
- )
-
- consecutive_failures = 0
-
- window = [check.threshold_breached, *snapshot.recent_events_breached]
- m = snapshot.evaluation_periods
- window = window[:m]
-
- breach_count = sum(1 for b in window if b)
- n = snapshot.datapoints_to_alarm
-
- if effective_state == AlertState.ERRORED:
- effective_state = AlertState.NOT_FIRING
-
- notification = NotificationAction.NONE
-
- if effective_state == AlertState.NOT_FIRING:
- if breach_count >= n:
- new_state = AlertState.FIRING
- notification = NotificationAction.FIRE
- else:
- new_state = AlertState.NOT_FIRING
-
- elif effective_state in (AlertState.FIRING, AlertState.PENDING_RESOLVE):
- if breach_count >= n:
- new_state = AlertState.FIRING
- else:
- new_state = AlertState.NOT_FIRING
- notification = NotificationAction.RESOLVE
-
- else:
- new_state = AlertState.NOT_FIRING
-
- update_last_notified_at = False
- if notification != NotificationAction.NONE:
- if _is_within_cooldown(snapshot.last_notified_at, snapshot.cooldown_minutes, now):
- notification = NotificationAction.NONE
- else:
- update_last_notified_at = True
-
- return AlertCheckOutcome(
- new_state=new_state,
- notification=notification,
- consecutive_failures=consecutive_failures,
- update_last_notified_at=update_last_notified_at,
- error_message=None,
- )
-
-
-def apply_user_reset(snapshot: AlertSnapshot) -> ControlPlaneOutcome:
- if snapshot.state != AlertState.BROKEN:
- raise InvalidTransition(f"Only broken alerts can be reset. Current state is {snapshot.state.value}.")
- return ControlPlaneOutcome(new_state=AlertState.NOT_FIRING, consecutive_failures=0)
-
-
-def apply_disable(snapshot: AlertSnapshot) -> ControlPlaneOutcome:
- # Preserve consecutive_failures so re-enable without reset doesn't silently
- # wipe forensic state.
- return ControlPlaneOutcome(
- new_state=AlertState.NOT_FIRING,
- consecutive_failures=snapshot.consecutive_failures,
- )
-
-
-def apply_enable(snapshot: AlertSnapshot) -> ControlPlaneOutcome:
- return ControlPlaneOutcome(new_state=AlertState.NOT_FIRING, consecutive_failures=0)
-
-
-def apply_snooze(snapshot: AlertSnapshot) -> ControlPlaneOutcome:
- return ControlPlaneOutcome(
- new_state=AlertState.SNOOZED,
- consecutive_failures=snapshot.consecutive_failures,
+ is_transient_error=check.is_transient_error,
+ ),
+ now,
+ policy=LOGS_ALERT_POLICY,
)
-def apply_unsnooze(snapshot: AlertSnapshot) -> ControlPlaneOutcome:
- return ControlPlaneOutcome(new_state=AlertState.NOT_FIRING, consecutive_failures=0)
-
-
-def apply_threshold_change(snapshot: AlertSnapshot) -> ControlPlaneOutcome:
- # Snoozed alerts stay snoozed on edit — editing configuration must not wake a
- # silenced alert.
- if snapshot.state == AlertState.SNOOZED:
- return ControlPlaneOutcome(
- new_state=AlertState.SNOOZED,
- consecutive_failures=snapshot.consecutive_failures,
- )
- return ControlPlaneOutcome(new_state=AlertState.NOT_FIRING, consecutive_failures=0)
-
-
def apply_outcome(
alert: LogsAlertConfiguration,
outcome: Outcome,
@@ -271,13 +145,3 @@ def apply_outcome(
)
return ["state", "consecutive_failures"]
-
-
-def _is_within_cooldown(
- last_notified_at: datetime | None,
- cooldown_minutes: int,
- now: datetime,
-) -> bool:
- if cooldown_minutes <= 0 or last_notified_at is None:
- return False
- return now < last_notified_at + timedelta(minutes=cooldown_minutes)
diff --git a/tach.toml b/tach.toml
index 7bb163091ff6..ff2270b3373d 100644
--- a/tach.toml
+++ b/tach.toml
@@ -31,6 +31,12 @@ depends_on = [
layer = "modules"
utility = true
+[[modules]]
+path = "common.alerting"
+depends_on = []
+layer = "modules"
+utility = true
+
[[modules]]
path = "ee"
depends_on = [