: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): record every check as a ClickHouse history row (#104857)
Jimmy Zhua771abfbb349
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.mdindex b00ddda87db2..edf109826573 100644--- a/docs/internal/alerts-platform-temporal.md+++ b/docs/internal/alerts-platform-temporal.md@@ -282,6 +282,41 @@ a real grouping key, and would bury them where Postgres cannot lift them into an`alerts_platform_checks_skipped_total{source,reason}` counts these by reason.+### What a check leaves behind++Every check writes one row to `platform_alert_events` in ClickHouse, including a check that+confirmed the alert.+Postgres could not take that volume without a per-check retention flag, and a TTL'd ClickHouse+table needs no such flag, so nothing has to decide which checks are worth keeping.++The row is self-sufficient.+`alert_name`, `condition_snapshot` and `source_config_snapshot` are read when the outcome is+recorded, so a threshold edited between a check and a retried send cannot change what a message+claims was breached, and a rename cannot make one thread contradict itself.+The snapshots are taken at write time rather than shipped with the outcome, because a source's copy+of `source_config` is a filter tree and shipping one per outcome would cost Temporal payload on+every batch.++The write happens after the Postgres transaction commits, not inside it.+`insert_events` never raises: the alert's state and schedule are already written by then, so a+ClickHouse outage costs a gap in history rather than an alert left due with its state unwritten.+`alerts_platform_history_rows_dropped_total` counts that gap.++`platform_alert_events` is a plain `ReplicatedMergeTree`, because every row is a distinct check+and nothing supersedes anything.+A `ReplacingMergeTree` would have made every count over the table wrong on any part a merge had+not reached, and ClickHouse never promises a merge will run.++ClickHouse has no unique constraint, so the insert carries an `insert_deduplication_token` naming+the batch by its contents.+A retried batch arrives under a token the engine has already seen and is dropped.+A reader still deduplicates on `(alert_id, evaluation_key)`, because the token only covers a retry+of the same batch and the engine only remembers a bounded window of them.++`labels` lands empty and stays empty until a source groups its results.+It is the group's identity, not the alert's filter scope; service and severity live in+`source_config_snapshot`, which is where a message should read them.+### A mute holds the announcement, not the checkA snooze and a schedule restriction both mute. Neither stops a check.diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.pyindex dbc60a333df7..33c95c2aff8f 100644--- a/products/alerts/backend/facade/contracts.py+++ b/products/alerts/backend/facade/contracts.py@@ -159,6 +159,25 @@ class MuteReason(StrEnum):QUIET_HOURS = "quiet_hours"+class AlertEventKind(StrEnum):+ """What one evaluation announced about an alert.++ `CHECK` is an evaluation that announced nothing, which includes one that moved the alert while+ a cooldown or a mute held the notification back. Read `previous_state` and `state` to find the+ moves, because counting `RESOLVED` rows misses every recovery that was suppressed.++ A source reports the kind rather than the platform deriving it: the machine already decided+ what to announce, and deriving it again from the states would be a second implementation of+ that decision.+ """++ CHECK = "check"+ FIRING = "firing"+ RESOLVED = "resolved"+ ERRORED = "errored"+ BROKEN = "broken"++@frozenclass FiringEpisode:"""The firing a check concerns, and whether that check is the one that ended it.@@ -184,10 +203,18 @@ class PlatformAlertOutcome:"""configuration_id: UUID+ evaluation_key: str+ kind: AlertEventKindnew_state: strnotified: boolconsecutive_failures: intfiring_episode: FiringEpisode | None = None+ value: float | None = None+ labels: dict[str, str] = field(default_factory=dict)+ error_message: str | None = None+ query_duration_ms: int | None = None+ # What a mute held back, so history separates a muted fire from a check that said nothing.+ muted_notification: str = ""# Recording an outcome without it leaves a configuration discovery keeps handing back to an# evaluation that cannot succeed.disable: bool = Falsediff --git a/products/alerts/backend/facade/platform_metrics.py b/products/alerts/backend/facade/platform_metrics.pyindex 87c4b72bea28..9950453ffc43 100644--- a/products/alerts/backend/facade/platform_metrics.py+++ b/products/alerts/backend/facade/platform_metrics.py@@ -9,6 +9,7 @@ from products.alerts.backend.temporal.metrics import (increment_checks,increment_checks_skipped,increment_deliveries_deferred,+ increment_history_rows_dropped,increment_notifications_muted,increment_state_transition,record_batch_duration,@@ -20,6 +21,7 @@ __all__ = ["increment_checks","increment_checks_skipped","increment_deliveries_deferred",+ "increment_history_rows_dropped","increment_notifications_muted","increment_state_transition","record_batch_duration",diff --git a/products/alerts/backend/logic/platform_alert_events.py b/products/alerts/backend/logic/platform_alert_events.pynew file mode 100644index 000000000000..919fef8fdbf7--- /dev/null+++ b/products/alerts/backend/logic/platform_alert_events.py@@ -0,0 +1,138 @@+"""Writes the shared platform's check history to ClickHouse.++One row per check. The table is append-only and TTL'd, so a check that confirmed the alert is+recorded alongside the ones that moved it, and nothing has to decide which checks are worth+keeping.++ClickHouse has no unique constraint, so the insert carries a deduplication token instead. The+token names the batch by its contents, and the replicated engine drops a second insert that+arrives under a token it has already seen. A reader still deduplicates on+`(alert_id, evaluation_key)`, because the token only covers a retry of the same batch and the+engine only remembers a bounded window of them.+"""++import json+import hashlib+from collections.abc import Sequence+from dataclasses import fields+from datetime import datetime+from typing import Any+from uuid import UUID++import structlog++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.dataclasses import frozen++from products.alerts.backend.models.platform_alert_events_sql import PLATFORM_ALERT_EVENTS_TABLE++logger = structlog.get_logger(__name__)+++@frozen+class PlatformAlertEventRow:+ """One check, as the history table stores it.++ The three snapshots make the row self-sufficient: a threshold edited between a check and a+ retried send cannot change what the message claims was breached, and a rename cannot make one+ thread contradict itself.+ """++ team_id: int+ configuration_id: UUID+ alert_id: UUID+ grouping_key: str+ evaluation_key: str+ kind: str+ alert_name: str+ previous_state: str+ state: str+ # The firing this check concerned, which on a resolve is the one it ended. The alert row+ # holds the firing it is in now, so the two differ on exactly that check.+ episode_started_at: datetime | None+ value: float | None+ labels: dict[str, str]+ condition_snapshot: dict[str, Any]+ source_config_snapshot: dict[str, Any]+ query_duration_ms: int | None+ error_message: str | None+ consecutive_failures: int+ muted_notification: str+ occurred_at: datetime++ def as_row(self) -> dict[str, Any]:+ """The row as ClickHouse takes it, derived from the fields so a new one cannot be missed.++ Only the three the wire needs in another shape are named.+ """+ return {f.name: getattr(self, f.name) for f in fields(self)} | {+ "condition_snapshot": json.dumps(self.condition_snapshot),+ "source_config_snapshot": json.dumps(self.source_config_snapshot),+ "error_message": self.error_message or "",+ }+++# Derived from the row rather than listed again, so a new column cannot reach the dataclass and+# miss the insert.+_COLUMNS = tuple(f.name for f in fields(PlatformAlertEventRow))+_INSERT_SQL = f"INSERT INTO {PLATFORM_ALERT_EVENTS_TABLE} ({', '.join(_COLUMNS)}) VALUES"+++def _deduplication_token(team_id: int, rows: Sequence[PlatformAlertEventRow]) -> str:+ """Names a batch by the evaluations in it, so a retry of that batch carries the same name.++ The activity is retried by Temporal, and a retry that follows a committed transaction can+ reach an insert the first attempt had already landed. `insert_deduplication_token` makes the+ replicated engine drop the second one.++ Built from the batch's contents rather than from `(team_id, cutoff)`, because two sources can+ record for one team at one cutoff and a token those two shared would silently drop the second+ source's rows.++ The grouping key is in the digest because one configuration writes one row per group once a+ source groups its results. Without it, two batches that hold the same configurations and+ evaluation keys but different groups take the same name, and the engine drops the second one+ whole.+ """+ digest = hashlib.sha256(str(team_id).encode())+ for configuration_id, grouping_key, evaluation_key in sorted(+ (str(row.configuration_id), row.grouping_key, row.evaluation_key) for row in rows+ ):+ digest.update(b"\0")+ digest.update(configuration_id.encode())+ digest.update(b"\0")+ digest.update(grouping_key.encode())+ digest.update(b"\0")+ digest.update(evaluation_key.encode())+ return digest.hexdigest()+++def insert_events(team_id: int, rows: Sequence[PlatformAlertEventRow]) -> int:+ """Records a batch's history. Returns how many rows it wrote.++ Never raises. History is a record of what the platform decided, not a step in deciding it, so+ a ClickHouse outage must not fail a batch whose state and schedule are already written. The+ cost of a failure is a gap a comparison sees, which is what the counter here is for.+ """+ if not rows:+ return 0+ try:+ # `sync_execute` requires both tags. The platform product rather than a source's, because+ # the table serves every source and the write is the platform's own bookkeeping.+ tag_queries(product=Product.PLATFORM_AND_SUPPORT, feature=Feature.ALERTING)+ sync_execute(+ _INSERT_SQL,+ [row.as_row() for row in rows],+ settings={"insert_deduplication_token": _deduplication_token(team_id, rows)},+ team_id=team_id,+ )+ except Exception as error:+ logger.exception(+ "Failed to record platform alert check history",+ team_id=team_id,+ rows=len(rows),+ error=str(error),+ )+ return 0+ return len(rows)diff --git a/products/alerts/backend/logic/platform_lifecycle.py b/products/alerts/backend/logic/platform_lifecycle.pyindex 6029b45cd251..69a6305ac63b 100644--- a/products/alerts/backend/logic/platform_lifecycle.py+++ b/products/alerts/backend/logic/platform_lifecycle.py@@ -11,7 +11,9 @@ from django.db import transactionfrom django.db.models import Exists, OuterRef, Qfrom products.alerts.backend.facade.contracts import PlatformAlertCheckInput, PlatformAlertOutcome, PlatformAlertUpsert+from products.alerts.backend.facade.platform_metrics import increment_history_rows_dropped, safe_recordfrom products.alerts.backend.facade.scheduling import advance_next_check_at, compute_shard_offset_seconds+from products.alerts.backend.logic.platform_alert_events import PlatformAlertEventRow, insert_eventsfrom products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration@@ -127,6 +129,66 @@ def slot_of(next_check_at: datetime | None, cutoff: datetime) -> str:return (next_check_at or cutoff).replace(second=0, microsecond=0).isoformat()+def _condition_snapshot(configuration: PlatformAlertConfiguration) -> dict[str, object]:+ """What the check was evaluated against, as a message and a comparison need to read it.++ Taken from the configuration when the outcome is recorded rather than shipped with it, because+ a source's copy would cost Temporal payload on every batch.++ One path can write a configuration between an evaluation and its record, so the snapshot is+ evaluation-time by convention rather than by construction: `upsert_configuration`, reached+ only through a hand-run backfill command, and only for a configuration already copied whose+ source row changed since. The row then states the new condition beside a verdict measured+ against the old one. Carry the snapshot on the outcome if that stops being acceptable.+ """+ return {+ "threshold_count": configuration.threshold_count,+ "threshold_operator": configuration.threshold_operator,+ "window_minutes": configuration.window_minutes,+ "evaluation_periods": configuration.evaluation_periods,+ "datapoints_to_alarm": configuration.datapoints_to_alarm,+ "cooldown_minutes": configuration.cooldown_minutes,+ }+++def _event_row(+ configuration: PlatformAlertConfiguration,+ alert: PlatformAlert,+ outcome: PlatformAlertOutcome,+ previous_state: str,+ now: datetime,+) -> PlatformAlertEventRow:+ return PlatformAlertEventRow(+ team_id=configuration.team_id,+ configuration_id=configuration.id,+ alert_id=alert.id,+ grouping_key=alert.grouping_key,+ evaluation_key=outcome.evaluation_key,+ kind=outcome.kind.value,+ alert_name=configuration.name,+ previous_state=previous_state,+ state=outcome.new_state,+ # The whole episode, ended or not. A resolve names the firing it closed, which is what a+ # thread key needs and what the alert row no longer holds.+ episode_started_at=outcome.firing_episode.started_at if outcome.firing_episode else None,+ value=outcome.value,+ labels=outcome.labels,+ condition_snapshot=_condition_snapshot(configuration),+ source_config_snapshot=configuration.source_config,+ query_duration_ms=outcome.query_duration_ms,+ error_message=outcome.error_message,+ consecutive_failures=outcome.consecutive_failures,+ muted_notification=outcome.muted_notification,+ occurred_at=now,+ )+++def _record_history(team_id: int, rows: Sequence[PlatformAlertEventRow]) -> None:+ recorded = insert_events(team_id, rows)+ if recorded < len(rows):+ safe_record(increment_history_rows_dropped, len(rows) - recorded)++def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now: datetime) -> int:"""Persists a batch's decisions and advances each configuration's schedule.@@ -141,6 +203,10 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:time and skipping a cycle.Returns how many configurations it wrote, which is fewer than it was given when a replayfinds rows an earlier attempt already advanced.++ History is written after the transaction commits, not inside it. A row the platform cannot+ record is a gap a comparison sees; a transaction that rolled back on a ClickHouse outage would+ instead leave the alert due with its state unwritten, which is worse."""if not outcomes:return 0@@ -154,9 +220,12 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:return 0alerts = _alerts_for_write(team_id, configurations)+ rows: list[PlatformAlertEventRow] = []for configuration in configurations:outcome = by_id[str(configuration.id)]alert = alerts[str(configuration.id)]+ # Before the row is mutated, so the history row keeps the state the check found.+ rows.append(_event_row(configuration, alert, outcome, alert.state, now))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.@@ -183,7 +252,10 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:PlatformAlertConfiguration.objects.for_team(team_id).bulk_update(configurations, ["consecutive_failures", "enabled", "next_check_at"])- return len(configurations)+ # `on_commit` rather than a statement after the block, so a caller that wraps this in its+ # own `atomic()` cannot leave history for state its rollback removed.+ transaction.on_commit(lambda: _record_history(team_id, rows))+ return len(configurations)def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:diff --git a/products/alerts/backend/temporal/metrics.py b/products/alerts/backend/temporal/metrics.pyindex 39abbe6d5b68..6505c0fb9690 100644--- a/products/alerts/backend/temporal/metrics.py+++ b/products/alerts/backend/temporal/metrics.py@@ -72,6 +72,19 @@ def increment_notifications_muted(source: str, reason: str) -> None:).add(1)+def increment_history_rows_dropped(count: int) -> None:+ """Check rows the platform decided but could not record.++ The alert's state and schedule are already written when this rises, so the cost is a gap in+ history rather than a lost evaluation. A comparison against a source's own stack reads as a+ disagreement where the gap falls.+ """+ get_metric_meter().create_counter(+ "alerts_platform_history_rows_dropped_total",+ "Check history rows lost to a failed ClickHouse write",+ ).add(count)++def increment_state_transition(source: str, from_state: str, to_state: str) -> None:get_metric_meter({"source": source, "from": from_state, "to": to_state}).create_counter("alerts_platform_state_transitions_total",diff --git a/products/alerts/backend/test/test_platform_alert_events.py b/products/alerts/backend/test/test_platform_alert_events.pynew file mode 100644index 000000000000..9d57c6082384--- /dev/null+++ b/products/alerts/backend/test/test_platform_alert_events.py@@ -0,0 +1,46 @@+from datetime import UTC, datetime+from uuid import uuid4++from products.alerts.backend.logic.platform_alert_events import PlatformAlertEventRow, _deduplication_token++CONFIGURATION_ID = uuid4()+EVALUATION_KEY = "slot:2026-09-16T10:00:00+00:00|window:2026-09-16T09:59:00+00:00"+++def _row(grouping_key: str) -> PlatformAlertEventRow:+ return PlatformAlertEventRow(+ team_id=2,+ configuration_id=CONFIGURATION_ID,+ alert_id=uuid4(),+ grouping_key=grouping_key,+ evaluation_key=EVALUATION_KEY,+ kind="firing",+ alert_name="API errors",+ previous_state="not_firing",+ state="firing",+ episode_started_at=datetime(2026, 9, 16, 10, tzinfo=UTC),+ value=47.0,+ labels={},+ condition_snapshot={},+ source_config_snapshot={},+ query_duration_ms=None,+ error_message=None,+ consecutive_failures=0,+ muted_notification="",+ occurred_at=datetime(2026, 9, 16, 10, tzinfo=UTC),+ )+++class TestDeduplicationToken:+ def test_batches_holding_different_groups_take_different_names(self) -> None:+ first = [_row("api"), _row("web")]+ second = [_row("api"), _row("billing")]++ # Same configuration and evaluation key, so a token blind to the group would name both+ # batches alike and ClickHouse would drop the second insert whole.+ assert _deduplication_token(2, first) != _deduplication_token(2, second)++ def test_the_same_batch_keeps_its_name_across_a_retry(self) -> None:+ rows = [_row("api"), _row("web")]++ assert _deduplication_token(2, rows) == _deduplication_token(2, list(reversed(rows)))diff --git a/products/alerts/backend/test/test_platform_lifecycle.py b/products/alerts/backend/test/test_platform_lifecycle.pyindex 6893108ebf74..76c0b826f2d0 100644--- a/products/alerts/backend/test/test_platform_lifecycle.py+++ b/products/alerts/backend/test/test_platform_lifecycle.py@@ -2,11 +2,13 @@ from datetime import UTC, datetime, timedeltafrom uuid import uuid4import time_machine-from posthog.test.base import APIBaseTest+from posthog.test.base import APIBaseTest, ClickhouseTestMixin+from posthog.clickhouse.client import sync_executefrom posthog.models.scoping import team_scopefrom products.alerts.backend.facade.contracts import (+ AlertEventKind,FiringEpisode,PlatformAlertOutcome,PlatformAlertUpsert,@@ -16,7 +18,7 @@ from products.alerts.backend.facade.platform_alerts import due_checks, record_oufrom products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration-class TestPlatformAlertLifecycle(APIBaseTest):+class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):def setUp(self) -> None:super().setUp()self.cutoff = datetime(2026, 9, 16, 10, tzinfo=UTC)@@ -37,12 +39,16 @@ class TestPlatformAlertLifecycle(APIBaseTest):def _record(self, now: datetime | None = None, **overrides) -> None:fields = {"configuration_id": self.configuration.id,+ "evaluation_key": f"window:{self.cutoff.isoformat()}",+ "kind": AlertEventKind.FIRING,"new_state": "firing","notified": True,"consecutive_failures": 0,}fields.update(overrides)- record_outcomes(self.team.id, [PlatformAlertOutcome(**fields)], now or self.cutoff)+ # History rides `transaction.on_commit`, which a `TestCase` transaction never reaches.+ with self.captureOnCommitCallbacks(execute=True):+ record_outcomes(self.team.id, [PlatformAlertOutcome(**fields)], now or self.cutoff)def _alert(self) -> PlatformAlert:with team_scope(self.team.id):@@ -81,6 +87,45 @@ class TestPlatformAlertLifecycle(APIBaseTest):self.configuration.refresh_from_db()assert self.configuration.next_check_at == after_first+ def test_a_recorded_check_lands_in_history_with_what_it_measured(self) -> None:+ self._record(+ new_state="firing",+ value=47.0,+ query_duration_ms=12,+ muted_notification="fire",+ firing_episode=FiringEpisode(started_at=self.cutoff, ended=False),+ )++ rows = sync_execute(+ """+ SELECT kind, previous_state, state, value, alert_name, muted_notification,+ JSONExtractInt(condition_snapshot, 'threshold_count'), episode_started_at+ FROM platform_alert_events+ WHERE team_id = %(team_id)s AND configuration_id = %(configuration_id)s+ """,+ {"team_id": self.team.id, "configuration_id": str(self.configuration.id)},+ )++ # `insert_events` never raises, so without reading a row back a broken write is invisible.+ assert rows == [("firing", "not_firing", "firing", 47.0, "API errors", "fire", 10, self.cutoff)]++ def test_a_resolve_row_keeps_the_firing_it_ended(self) -> None:+ # The alert row clears the firing on a resolve, so history is the only place left holding+ # the start a delivery needs to reply under the message that fired.+ self._record(+ new_state="not_firing",+ kind=AlertEventKind.RESOLVED,+ firing_episode=FiringEpisode(started_at=self.cutoff, ended=True),+ )++ rows = sync_execute(+ "SELECT state, episode_started_at FROM platform_alert_events WHERE team_id = %(team_id)s",+ {"team_id": self.team.id},+ )++ assert rows == [("not_firing", self.cutoff)]+ assert self._alert().firing_started_at is None+def test_a_copied_snooze_mutes_without_holding_back_the_check(self) -> None:legacy_id = uuid4()snoozed_until = self.cutoff + timedelta(hours=2)diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex 8a7ccdf917d4..654948a78e50 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -18,6 +18,7 @@ import timefrom collections.abc import Sequencefrom datetime import datetime, timedeltafrom itertools import batched+from typing import castfrom uuid import UUIDimport structlog@@ -27,6 +28,7 @@ from posthog.models import Teamfrom products.alerts.backend.facade.contracts import (AlertDeliveryPreview,+ AlertEventKind,GroupTransition,MuteReason,PlatformAlertCheckInput,@@ -49,7 +51,7 @@ from products.alerts.backend.facade.lifecycle import (decide_firing_episode,evaluate_alert_check,)-from products.alerts.backend.facade.platform_alerts import due_checks+from products.alerts.backend.facade.platform_alerts import due_checks, slot_offrom products.alerts.backend.facade.platform_metrics import (increment_checks,increment_checks_skipped,@@ -98,14 +100,33 @@ MAX_QUERY_SECONDS = 20# Below this there is no point starting another query; the cohort keeps its due time instead.MIN_QUERY_SECONDS = 2-_NOTIFICATION_EVENT_KINDS: dict[NotificationAction, EventKind] = {- NotificationAction.FIRE: "firing",- NotificationAction.RESOLVE: "resolved",- NotificationAction.ERROR: "errored",- NotificationAction.BROKEN: "broken",+# A check that announced nothing is a CHECK even when it moved the alert; the row's two states+# carry the move. `AlertEventKind`'s other four values are the `EventKind` strings the destination+# config is keyed on, so this is also the only table mapping an action to a destination.+_NOTIFICATION_OUTCOME_KINDS: dict[NotificationAction, AlertEventKind] = {+ NotificationAction.NONE: AlertEventKind.CHECK,+ NotificationAction.FIRE: AlertEventKind.FIRING,+ NotificationAction.RESOLVE: AlertEventKind.RESOLVED,+ NotificationAction.ERROR: AlertEventKind.ERRORED,+ NotificationAction.BROKEN: AlertEventKind.BROKEN,}+def _evaluation_key(check: PlatformAlertCheckInput, window_end: datetime) -> str:+ """Names the scheduled check, and the window it answered for.++ The slot is in the key because `resolve_alert_date_to` clamps the window end to the ingestion+ checkpoint. Two consecutive scheduled checks reach the same window end whenever the checkpoint+ has not moved, and a key built from the window alone would make them one evaluation to any+ reader deduplicating on it.++ Scoped to the alert by the row's own columns rather than by the string, so the key keeps one+ shape across sources. Both parts are read before anything is written, so a retry recomputes+ the same key.+ """+ return f"slot:{slot_of(check.next_check_at, window_end)}|window:{window_end.isoformat()}"++def _cohort_key(check: PlatformAlertCheckInput, checkpoint: datetime | None, now: datetime) -> tuple:return (check.window_minutes,@@ -222,36 +243,63 @@ def _recorded(check: PlatformAlertCheckInput,*,outcome: Outcome,+ evaluation_key: str,+ kind: AlertEventKind,notified: bool,now: datetime,+ value: float | None = None,+ error_message: str | None = None,+ query_duration_ms: int | None = None,+ muted_notification: str = "",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,+ evaluation_key=evaluation_key,+ kind=kind,new_state=outcome.new_state.value,notified=notified,consecutive_failures=outcome.consecutive_failures,firing_episode=decide_firing_episode(_snapshot(check, ()), outcome, now, policy=PLATFORM_LOGS_ALERT_POLICY),+ value=value,+ error_message=error_message,+ query_duration_ms=query_duration_ms,+ muted_notification=muted_notification,disable=disable,)def _delivery(- check: PlatformAlertCheckInput, outcome: AlertCheckOutcome, *, window_end: datetime, now: datetime+ check: PlatformAlertCheckInput,+ outcome: AlertCheckOutcome,+ *,+ window_end: datetime,+ now: datetime,+ value: float | None = None,+ query_duration_ms: int | None = None,) -> Decision:"""What the platform records for a verdict, and what delivery would announce for it."""recorded = _recorded(check,outcome=outcome,+ evaluation_key=_evaluation_key(check, window_end),+ kind=_NOTIFICATION_OUTCOME_KINDS[outcome.notification],notified=outcome.update_last_notified_at,now=now,+ value=value,+ error_message=outcome.error_message,+ query_duration_ms=query_duration_ms,+ muted_notification=(+ "" if outcome.muted_notification == NotificationAction.NONE else outcome.muted_notification.value+ ),disable=outcome.disable,)if outcome.notification == NotificationAction.NONE:return recorded, None- spec = EVENT_KIND_CONFIG[_NOTIFICATION_EVENT_KINDS[outcome.notification]]+ kind = _NOTIFICATION_OUTCOME_KINDS[outcome.notification]+ spec = EVENT_KIND_CONFIG[cast(EventKind, kind.value)]destinations = list_active_alert_destinations(team_id=check.team_id,alert_id=str(check.legacy_configuration_id or check.id),@@ -261,7 +309,10 @@ def _delivery(source=SourceKind.LOGS,alert_id=str(check.id),alert_name=check.name,- evaluation_key=f"{check.id}:window:{window_end.isoformat()}",+ # The recorded key, not a second construction of one. This becomes the delivery child+ # workflow id, so a key without the slot lets two scheduled checks that clamped to the+ # same window end collide and drops the later announcement.+ evaluation_key=f"{check.id}:{recorded.evaluation_key}",destination_names=tuple(destination.name for destination in destinations),# One transition with an empty grouping key. Logs does not group yet, and delivery# reads a list either way, so fan-out changes this call and nothing downstream.@@ -306,9 +357,25 @@ def _failed(check: PlatformAlertCheckInput, error: Exception, *, now: datetime,)-def _held(check: PlatformAlertCheckInput, outcome: ControlPlaneOutcome, *, skip: SkipReason, now: datetime) -> Decision:+def _held(+ check: PlatformAlertCheckInput,+ outcome: ControlPlaneOutcome,+ *,+ skip: SkipReason,+ now: datetime,+ error_message: str,+) -> Decision:"""A control-plane transition the check machine cannot express. The outcome advances the schedule."""- recorded = _recorded(check, outcome=outcome, notified=False, now=now)+ recorded = _recorded(+ check,+ outcome=outcome,+ evaluation_key=_evaluation_key(check, now),+ # The notification is NONE here only because the check machine never ran.+ kind=AlertEventKind.BROKEN,+ notified=False,+ now=now,+ error_message=error_message,+ )_record_check_metrics(check, new_state=outcome.new_state.value, notification=NotificationAction.NONE, skip=skip, now=now)@@ -356,14 +423,23 @@ def _evaluate_cohort(decided: list[Decision] = []for check in checks:muted = check.id in muted_ids+ buckets = result.per_alert.get(str(check.id), [])+ # ClickHouse emits no bucket for an empty window, so no buckets is a measured zero.+ value: float | None = float(buckets[-1].count) if buckets else 0.0+ # One query serves the cohort, so every check in it records the same duration.+ duration_ms: int | None = result.query_duration_mstry:- outcome = _evaluate_one(check, result.per_alert.get(str(check.id), []), now=now, muted=muted)+ outcome = _evaluate_one(check, buckets, now=now, muted=muted)except Exception as error:logger.exception("Failed to evaluate a logs alert", check_id=str(check.id), error=str(error))outcome = _failed(check, error, now=now, muted=muted)+ # A check that reached no verdict measured nothing.+ value, duration_ms = None, None# 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, now=now))+ decided.append(+ _delivery(check, outcome, window_end=date_to, now=now, value=value, query_duration_ms=duration_ms)+ )return decided@@ -393,6 +469,7 @@ def _triage(checks: Sequence[PlatformAlertCheckInput], *, now: datetime, tz_nameapply_broken_config(_snapshot(check, ())),skip=SkipReason.BROKEN_CONFIG,now=now,+ error_message=broken_reason,))continuediff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.pyindex 8d322de9cb23..4dc6a5de8f69 100644--- a/products/logs/backend/test/test_alert_evaluate.py+++ b/products/logs/backend/test/test_alert_evaluate.py@@ -127,6 +127,36 @@ class TestLogsAlertEvaluation(APIBaseTest):).count()assert still_due == 1+ def test_two_scheduled_checks_clamped_to_one_window_keep_distinct_keys(self) -> None:+ # `resolve_alert_date_to` clamps the window end to the ingestion checkpoint, so a+ # checkpoint that has not moved gives two consecutive checks the same window. Keyed on the+ # window alone they read as one evaluation, and a reader deduplicating on the key drops+ # the second.+ configuration = self._configuration()+ # Inside CHECKPOINT_MAX_STALENESS and behind both scheduled times, so both checks clamp+ # their window end to it.+ frozen_checkpoint = self.cutoff - timedelta(minutes=3)++ def run_at(next_check_at: datetime) -> str:+ with team_scope(self.team.id):+ PlatformAlertConfiguration.objects.filter(id=configuration.id).update(next_check_at=next_check_at)+ with (+ patch(f"{_MODULE}.fetch_live_logs_checkpoint", return_value=frozen_checkpoint),+ patch(f"{_MODULE}.BatchedAlertCheckQuery") as query,+ ):+ query.return_value.execute_rolling_checks.return_value = BatchedBucketedResult(+ per_alert={str(configuration.id): [BucketedCount(timestamp=self.cutoff, count=500)]},+ query_duration_ms=1,+ )+ slot = next_check_at.replace(second=0, microsecond=0).isoformat()+ evaluation = evaluate_logs_batch(self.team.id, slot, self.cutoff)+ return evaluation.outcomes[0].evaluation_key++ first = run_at(self.cutoff - timedelta(minutes=2))+ second = run_at(self.cutoff - timedelta(minutes=1))++ assert first != second+def test_a_check_inside_quiet_hours_runs_and_holds_its_announcement(self) -> None:configuration = self._configuration(schedule_restriction={"blocked_windows": [{"start": "09:00", "end": "12:00"}]}@@ -244,8 +274,11 @@ class TestLogsAlertEvaluation(APIBaseTest):evaluation, _ = self._run(configuration)+ # The preview key is the recorded key, so the slot travels with it. It becomes the+ # delivery workflow id, and a window-only id lets two checks that clamped to the same+ # window end collide and drops the later announcement.assert [p.evaluation_key for p in evaluation.previews] == [- f"{configuration.id}:window:{self.cutoff.isoformat()}"+ f"{configuration.id}:slot:{self.cutoff.isoformat()}|window:{self.cutoff.isoformat()}"]