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): record when a firing began (#108083)

Jimmy Zhu49c15abd0b3e
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index 4853dfd91a28..c27077ca604d 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -109,6 +109,7 @@ class PlatformAlertCheckInput:
state: str
last_notified_at: datetime | None
snooze_until: datetime | None
+ firing_started_at: datetime | None = None
@property
def filters(self) -> dict[str, Any]:
@@ -157,6 +158,22 @@ class MuteReason(StrEnum):
QUIET_HOURS = "quiet_hours"
+@frozen
+class FiringEpisode:
+ """The firing a check concerns, and whether that check is the one that ended it.
+
+ Two readers want different things from it. An alert's current state wants the firing it is in
+ now, which is nothing once a check ends one. A history row and a delivery want the firing the
+ check was about, which on a resolve is the firing that just ended. Both come from here, so
+ neither has to work the difference out from the states.
+
+ `started_at` is None for a firing that began before the platform recorded starts.
+ """
+
+ started_at: datetime | None
+ ended: bool
+
+
@frozen
class PlatformAlertOutcome:
"""What one check decided. The platform turns this into rows.
@@ -169,6 +186,7 @@ class PlatformAlertOutcome:
new_state: str
notified: bool
consecutive_failures: int
+ firing_episode: FiringEpisode | None = None
# Recording an outcome without it leaves a configuration discovery keeps handing back to an
# evaluation that cannot succeed.
disable: bool = False
diff --git a/products/alerts/backend/facade/lifecycle.py b/products/alerts/backend/facade/lifecycle.py
index d154b8702b6b..1df3e31b84f7 100644
--- a/products/alerts/backend/facade/lifecycle.py
+++ b/products/alerts/backend/facade/lifecycle.py
@@ -25,6 +25,8 @@ from datetime import datetime, timedelta
from enum import Enum, StrEnum
from typing import Protocol
+from products.alerts.backend.facade.contracts import FiringEpisode
+
MAX_CONSECUTIVE_FAILURES = 5
@@ -137,6 +139,7 @@ class AlertSnapshot:
datapoints_to_alarm: int = 1
# Breach flags of the most recent prior checks, newest first (excludes the current one).
recent_events_breached: tuple[bool, ...] = ()
+ firing_started_at: datetime | None = None
class StatefulSnapshot(Protocol):
@@ -176,6 +179,10 @@ class ControlPlaneOutcome:
Outcome = AlertCheckOutcome | ControlPlaneOutcome
+# States that mean the alert is inside a firing. PENDING_RESOLVE is one: the condition has
+# cleared but the resolution is not announced yet, so the firing has not ended.
+FIRING_STATES = (AlertState.FIRING, AlertState.PENDING_RESOLVE)
+
def _stay(snapshot: AlertSnapshot) -> AlertCheckOutcome:
return AlertCheckOutcome(
@@ -207,6 +214,37 @@ def _muted(outcome: AlertCheckOutcome) -> AlertCheckOutcome:
)
+def decide_firing_episode(
+ snapshot: AlertSnapshot, outcome: Outcome, now: datetime, *, policy: AlertPolicy
+) -> FiringEpisode | None:
+ """The firing this check concerns, or None when no firing is involved at all.
+
+ A check that leaves the state where it found it keeps the same firing, so an alert rides
+ through a failed or inconclusive check without starting a second one.
+
+ The rule lives here rather than in a product's persistence layer, because only a policy says
+ whether two states belong to one firing. Under `clear_check_ends_snooze` a breached alert
+ parks in SNOOZED with the firing still running underneath the mute, so a caller reading the
+ two state strings cannot tell that state from a resolve.
+ """
+ was_firing = snapshot.state in FIRING_STATES or (
+ policy.clear_check_ends_snooze and snapshot.state == AlertState.SNOOZED
+ )
+ if outcome.new_state == AlertState.SNOOZED:
+ if not (policy.clear_check_ends_snooze and was_firing):
+ return None
+ return FiringEpisode(started_at=snapshot.firing_started_at, ended=False)
+ if outcome.new_state in FIRING_STATES:
+ # A firing that began before the platform recorded starts keeps an unknown one rather
+ # than taking `now`, because a start later than `last_notified_at` would read as never
+ # announced.
+ started_at = snapshot.firing_started_at if was_firing else now
+ return FiringEpisode(started_at=started_at, ended=False)
+ if not was_firing:
+ return None
+ return FiringEpisode(started_at=snapshot.firing_started_at, ended=True)
+
+
def evaluate_alert_check(
snapshot: AlertSnapshot,
check: CheckInput,
@@ -296,7 +334,7 @@ def evaluate_alert_check(
else:
new_state = AlertState.NOT_FIRING
- elif effective_state in (AlertState.FIRING, AlertState.PENDING_RESOLVE):
+ elif effective_state in FIRING_STATES:
if breached:
new_state = AlertState.FIRING
if policy.renotify_while_firing:
diff --git a/products/alerts/backend/logic/platform_lifecycle.py b/products/alerts/backend/logic/platform_lifecycle.py
index d0f1c27d10d0..6029b45cd251 100644
--- a/products/alerts/backend/logic/platform_lifecycle.py
+++ b/products/alerts/backend/logic/platform_lifecycle.py
@@ -113,6 +113,7 @@ def _check(c: PlatformAlertConfiguration, alert: PlatformAlert | None) -> Platfo
state=alert.state if alert else PlatformAlert.State.NOT_FIRING.value,
last_notified_at=alert.last_notified_at if alert else None,
snooze_until=alert.snooze_until if alert else None,
+ firing_started_at=alert.firing_started_at if alert else None,
)
@@ -156,6 +157,10 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
for configuration in configurations:
outcome = by_id[str(configuration.id)]
alert = alerts[str(configuration.id)]
+ episode = outcome.firing_episode
+ # The row holds the firing the alert is in, so a check that ended one clears it. The
+ # ended firing stays on the history row instead.
+ alert.firing_started_at = episode.started_at if episode and not episode.ended else None
alert.state = outcome.new_state
if outcome.notified:
alert.last_notified_at = now
@@ -172,7 +177,9 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
),
)
- PlatformAlert.objects.for_team(team_id).bulk_update(list(alerts.values()), ["state", "last_notified_at"])
+ PlatformAlert.objects.for_team(team_id).bulk_update(
+ list(alerts.values()), ["state", "last_notified_at", "firing_started_at"]
+ )
PlatformAlertConfiguration.objects.for_team(team_id).bulk_update(
configurations, ["consecutive_failures", "enabled", "next_check_at"]
)
diff --git a/products/alerts/backend/migrations/0008_platformalert_firing_started_at_and_uuid7_pk.py b/products/alerts/backend/migrations/0008_platformalert_firing_started_at_and_uuid7_pk.py
new file mode 100644
index 000000000000..171ce25d8308
--- /dev/null
+++ b/products/alerts/backend/migrations/0008_platformalert_firing_started_at_and_uuid7_pk.py
@@ -0,0 +1,47 @@
+# Generated by Django 5.2.17 on 2026-09-29 00:43
+
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts", "0007_platformalertconfiguration_platformalert_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="platformalert",
+ name="firing_started_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ # State only: `default` is applied in `Model.__init__` and never reaches Postgres, so the
+ # column keeps its type and no DDL runs. Declaring that rather than leaving a bare
+ # `AlterField` also keeps the risk analyzer from reading it as a column alteration.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AlterField(
+ model_name="platformalert",
+ name="id",
+ field=models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="platformalertconfiguration",
+ name="id",
+ field=models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/alerts/backend/migrations/max_migration.txt b/products/alerts/backend/migrations/max_migration.txt
index 1e366de471c1..ca67245bba67 100644
--- a/products/alerts/backend/migrations/max_migration.txt
+++ b/products/alerts/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0007_platformalertconfiguration_platformalert_and_more
+0008_platformalert_firing_started_at_and_uuid7_pk
diff --git a/products/alerts/backend/models/platform_alert.py b/products/alerts/backend/models/platform_alert.py
index fae66148fc7a..64eb8bd183a1 100644
--- a/products/alerts/backend/models/platform_alert.py
+++ b/products/alerts/backend/models/platform_alert.py
@@ -11,10 +11,10 @@ source configures on the shared platform, rather than one product's own table.
from django.db import models
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
-from posthog.models.utils import UUIDTModel
+from posthog.models.utils import UUIDModel
-class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDTModel):
+class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
"""What to evaluate, how often, and against what bound.
Evaluation-level state lives here rather than on `PlatformAlert`, because a failed check
@@ -74,7 +74,7 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDTModel):
]
-class PlatformAlert(TeamScopedRootMixin, UUIDTModel):
+class PlatformAlert(TeamScopedRootMixin, UUIDModel):
"""Runtime state for one instance of a configuration.
`grouping_key` is empty until a source groups its results. The unique constraint is what
@@ -95,6 +95,10 @@ class PlatformAlert(TeamScopedRootMixin, UUIDTModel):
state = models.CharField(max_length=32, choices=State.choices, default=State.NOT_FIRING, db_default="not_firing")
last_notified_at = models.DateTimeField(null=True, blank=True)
snooze_until = models.DateTimeField(null=True, blank=True)
+ # Identifies one firing, from the transition into FIRING to the transition out. A timestamp
+ # rather than an opaque id, because `last_notified_at >= firing_started_at` is then how a
+ # reader knows whether this firing was ever announced.
+ firing_started_at = models.DateTimeField(null=True, blank=True)
class Meta:
constraints = [
diff --git a/products/alerts/backend/test/test_platform_lifecycle.py b/products/alerts/backend/test/test_platform_lifecycle.py
index 3b17f2408fe9..6893108ebf74 100644
--- a/products/alerts/backend/test/test_platform_lifecycle.py
+++ b/products/alerts/backend/test/test_platform_lifecycle.py
@@ -6,7 +6,12 @@ from posthog.test.base import APIBaseTest
from posthog.models.scoping import team_scope
-from products.alerts.backend.facade.contracts import PlatformAlertOutcome, PlatformAlertUpsert, SourceKind
+from products.alerts.backend.facade.contracts import (
+ FiringEpisode,
+ PlatformAlertOutcome,
+ PlatformAlertUpsert,
+ SourceKind,
+)
from products.alerts.backend.facade.platform_alerts import due_checks, record_outcomes, upsert_configuration
from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration
@@ -29,7 +34,7 @@ class TestPlatformAlertLifecycle(APIBaseTest):
)
self.slot = (self.cutoff - timedelta(minutes=1)).isoformat()
- def _record(self, **overrides) -> None:
+ def _record(self, now: datetime | None = None, **overrides) -> None:
fields = {
"configuration_id": self.configuration.id,
"new_state": "firing",
@@ -37,7 +42,23 @@ class TestPlatformAlertLifecycle(APIBaseTest):
"consecutive_failures": 0,
}
fields.update(overrides)
- record_outcomes(self.team.id, [PlatformAlertOutcome(**fields)], self.cutoff)
+ record_outcomes(self.team.id, [PlatformAlertOutcome(**fields)], now or self.cutoff)
+
+ def _alert(self) -> PlatformAlert:
+ with team_scope(self.team.id):
+ return PlatformAlert.objects.get(configuration=self.configuration)
+
+ def test_the_row_holds_the_firing_the_alert_is_in_and_drops_the_one_that_ended(self) -> None:
+ # A field missing from the `bulk_update` list is never persisted and nothing else notices.
+ self._record(firing_episode=FiringEpisode(started_at=self.cutoff, ended=False))
+ assert self._alert().firing_started_at == self.cutoff
+
+ self._record(
+ new_state="not_firing",
+ firing_episode=FiringEpisode(started_at=self.cutoff, ended=True),
+ now=self.cutoff + timedelta(hours=1),
+ )
+ assert self._alert().firing_started_at is None
def test_a_disabling_outcome_stops_the_configuration_being_discovered(self) -> None:
self._record(new_state="broken", notified=False, consecutive_failures=5, disable=True)
diff --git a/products/alerts/backend/test/test_state_machine.py b/products/alerts/backend/test/test_state_machine.py
index b4ac435aa82a..fd7978a0ab44 100644
--- a/products/alerts/backend/test/test_state_machine.py
+++ b/products/alerts/backend/test/test_state_machine.py
@@ -10,7 +10,9 @@ from products.alerts.backend.facade.lifecycle import (
AlertSnapshot,
AlertState,
CheckInput,
+ FiringEpisode,
NotificationAction,
+ decide_firing_episode,
evaluate_alert_check,
)
@@ -347,3 +349,108 @@ class TestPolicyDecisionTable:
error_message="query failed",
disable=expected_disable,
)
+
+
+STARTED = NOW - timedelta(hours=2)
+
+
+def outcome(state: AlertState) -> AlertCheckOutcome:
+ return AlertCheckOutcome(
+ new_state=state,
+ notification=NotificationAction.NONE,
+ consecutive_failures=0,
+ update_last_notified_at=False,
+ error_message=None,
+ )
+
+
+def episode(started_at: datetime | None, *, ended: bool = False) -> FiringEpisode:
+ return FiringEpisode(started_at=started_at, ended=ended)
+
+
+class TestFiringEpisode:
+ @parameterized.expand(
+ [
+ ("first_fire", LOGS_ALERT_POLICY, AlertState.NOT_FIRING, None, AlertState.FIRING, episode(NOW)),
+ (
+ "same_firing",
+ LOGS_ALERT_POLICY,
+ AlertState.FIRING,
+ STARTED,
+ AlertState.FIRING,
+ episode(STARTED),
+ ),
+ # A resolve keeps the firing it ended, which is what a history row and a thread key name.
+ (
+ "resolved",
+ LOGS_ALERT_POLICY,
+ AlertState.FIRING,
+ STARTED,
+ AlertState.NOT_FIRING,
+ episode(STARTED, ended=True),
+ ),
+ (
+ "errored",
+ LOGS_ALERT_POLICY,
+ AlertState.FIRING,
+ STARTED,
+ AlertState.ERRORED,
+ episode(STARTED, ended=True),
+ ),
+ ("never_fired", LOGS_ALERT_POLICY, AlertState.NOT_FIRING, None, AlertState.NOT_FIRING, None),
+ (
+ "firing_without_a_start",
+ LOGS_ALERT_POLICY,
+ AlertState.FIRING,
+ None,
+ AlertState.FIRING,
+ episode(None),
+ ),
+ # clear_check_ends_snooze parks a breached alert in SNOOZED, so the firing continues
+ # underneath the mute and resumes as the same one.
+ ("parked", SNOOZE_UNTIL_CLEAR, AlertState.FIRING, STARTED, AlertState.SNOOZED, episode(STARTED)),
+ (
+ "resumed",
+ SNOOZE_UNTIL_CLEAR,
+ AlertState.SNOOZED,
+ STARTED,
+ AlertState.FIRING,
+ episode(STARTED),
+ ),
+ ("snoozed_at_rest", LOGS_ALERT_POLICY, AlertState.FIRING, STARTED, AlertState.SNOOZED, None),
+ ("snoozed_while_clear", SNOOZE_UNTIL_CLEAR, AlertState.NOT_FIRING, None, AlertState.SNOOZED, None),
+ # PENDING_RESOLVE is inside the firing: the condition cleared and the resolution is
+ # not announced yet, so neither leaving nor entering it starts a second firing.
+ (
+ "awaiting_resolve",
+ LOGS_ALERT_POLICY,
+ AlertState.FIRING,
+ STARTED,
+ AlertState.PENDING_RESOLVE,
+ episode(STARTED),
+ ),
+ (
+ "refired_while_awaiting",
+ LOGS_ALERT_POLICY,
+ AlertState.PENDING_RESOLVE,
+ STARTED,
+ AlertState.FIRING,
+ episode(STARTED),
+ ),
+ ]
+ )
+ def test_which_firing_a_check_concerns(
+ self,
+ _name: str,
+ policy: AlertPolicy,
+ state: AlertState,
+ started_at: datetime | None,
+ new_state: AlertState,
+ expected: FiringEpisode | None,
+ ) -> None:
+ assert (
+ decide_firing_episode(
+ snapshot(state=state, firing_started_at=started_at), outcome(new_state), NOW, policy=policy
+ )
+ == expected
+ )
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 38d7035b71c0..8a7ccdf917d4 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -44,7 +44,9 @@ from products.alerts.backend.facade.lifecycle import (
CheckInput,
ControlPlaneOutcome,
NotificationAction,
+ Outcome,
apply_broken_config,
+ decide_firing_episode,
evaluate_alert_check,
)
from products.alerts.backend.facade.platform_alerts import due_checks
@@ -142,6 +144,7 @@ def _snapshot(check: PlatformAlertCheckInput, prior_breached: tuple[bool, ...])
evaluation_periods=check.evaluation_periods,
datapoints_to_alarm=check.datapoints_to_alarm,
recent_events_breached=prior_breached,
+ firing_started_at=check.firing_started_at,
)
@@ -216,24 +219,33 @@ def _verdict(
def _recorded(
- check: PlatformAlertCheckInput, *, new_state: str, notified: bool, consecutive_failures: int, disable: bool = False
+ check: PlatformAlertCheckInput,
+ *,
+ outcome: Outcome,
+ notified: bool,
+ now: datetime,
+ disable: bool = False,
) -> PlatformAlertOutcome:
+ """The one place a recorded outcome is built, so every path states the firing the same way."""
return PlatformAlertOutcome(
configuration_id=check.id,
- new_state=new_state,
+ new_state=outcome.new_state.value,
notified=notified,
- consecutive_failures=consecutive_failures,
+ consecutive_failures=outcome.consecutive_failures,
+ firing_episode=decide_firing_episode(_snapshot(check, ()), outcome, now, policy=PLATFORM_LOGS_ALERT_POLICY),
disable=disable,
)
-def _delivery(check: PlatformAlertCheckInput, outcome: AlertCheckOutcome, *, window_end: datetime) -> Decision:
+def _delivery(
+ check: PlatformAlertCheckInput, outcome: AlertCheckOutcome, *, window_end: datetime, now: datetime
+) -> Decision:
"""What the platform records for a verdict, and what delivery would announce for it."""
recorded = _recorded(
check,
- new_state=outcome.new_state.value,
+ outcome=outcome,
notified=outcome.update_last_notified_at,
- consecutive_failures=outcome.consecutive_failures,
+ now=now,
disable=outcome.disable,
)
if outcome.notification == NotificationAction.NONE:
@@ -296,12 +308,7 @@ def _failed(check: PlatformAlertCheckInput, error: Exception, *, now: datetime,
def _held(check: PlatformAlertCheckInput, outcome: ControlPlaneOutcome, *, skip: SkipReason, now: datetime) -> Decision:
"""A control-plane transition the check machine cannot express. The outcome advances the schedule."""
- recorded = _recorded(
- check,
- new_state=outcome.new_state.value,
- notified=False,
- consecutive_failures=outcome.consecutive_failures,
- )
+ recorded = _recorded(check, outcome=outcome, notified=False, now=now)
_record_check_metrics(
check, new_state=outcome.new_state.value, notification=NotificationAction.NONE, skip=skip, now=now
)
@@ -342,7 +349,7 @@ def _evaluate_cohort(
# batch would advance every other check's schedule and leave this one due with its failure
# counter unmoved, never reaching the escalation that stops it.
return [
- _delivery(check, _failed(check, error, now=now, muted=check.id in muted_ids), window_end=date_to)
+ _delivery(check, _failed(check, error, now=now, muted=check.id in muted_ids), window_end=date_to, now=now)
for check in checks
]
@@ -356,7 +363,7 @@ def _evaluate_cohort(
outcome = _failed(check, error, now=now, muted=muted)
# Outside the block above on purpose. Resolving a destination reads the database, and a
# failure there is not this check's failure.
- decided.append(_delivery(check, outcome, window_end=date_to))
+ decided.append(_delivery(check, outcome, window_end=date_to, now=now))
return decided