: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): compare platform verdicts against a source's own stack (#109570)
Jimmy Zhufadbb4907d4f
diff --git a/products/alerts_platform/backend/comparison/__init__.py b/products/alerts_platform/backend/comparison/__init__.pynew file mode 100644index 000000000000..43cd74d0c9f8--- /dev/null+++ b/products/alerts_platform/backend/comparison/__init__.py@@ -0,0 +1,8 @@+"""Reads a platform verdict and the verdict a source's own stack produced for the same check,+and says whether they agree.++Every source adopts the platform by evaluating in parallel while the product's own stack keeps+notifying. That posture is only worth its query cost if something reads both verdicts. This+package is that reader and its classifier. The contract a source implements to supply its own half+is in `facade.contracts`.+"""diff --git a/products/alerts_platform/backend/comparison/divergence.py b/products/alerts_platform/backend/comparison/divergence.pynew file mode 100644index 000000000000..940090fc894c--- /dev/null+++ b/products/alerts_platform/backend/comparison/divergence.py@@ -0,0 +1,115 @@+"""Why two stacks disagreed, in the three classes a reader can act on.++A harness that cannot separate these is noise.++**Real.** The same alert, the same check, a different verdict. This is the output the whole+exercise exists for.++**Timing.** One stack had not reached the evaluation the other made. Report it as a lag rather+than as a difference.++**Intentional.** The platform behaves differently on purpose, so a design decision shows up as+data. A source declares those on its correspondence, each with a recognizer `compare` asks, and+`facade.testing.undeclared_policy_divergences` names any way a source's platform policy departs+from its production policy that nobody declared.+"""++from __future__ import annotations++from enum import StrEnum++from posthog.dataclasses import frozen++from products.alerts_platform.backend.facade.contracts import (+ CheckRef,+ PlatformCheck,+ SourceCorrespondence,+ SourceCoverage,+ SourceVerdict,+ SuppressionReason,+)++# A source that excludes an alert for one of these would never have checked it, and neither would+# the platform. A mute is not one: the platform evaluates through a mute on purpose.+_EXCLUDED_BY_BOTH = frozenset({SuppressionReason.DISABLED, SuppressionReason.BROKEN})+++class DivergenceClass(StrEnum):+ REAL = "real"+ TIMING = "timing"+ INTENTIONAL = "intentional"+++class Agreement(StrEnum):+ AGREED = "agreed"+ DIVERGED = "diverged"+ UNCOMPARABLE = "uncomparable"+++@frozen+class Comparison:+ """One platform check set against what the source's own stack held.++ `coverage` rides along so a report can separate an agreement rate from how much of the window+ the source could answer for at all.+ """++ ref: CheckRef+ coverage: SourceCoverage+ platform_state: str+ source_state: str | None+ divergence: DivergenceClass | None = None+ # The declared divergence's policy flag, or a short statement of why nothing could be compared.+ reason: str = ""++ @property+ def agreement(self) -> Agreement:+ if self.coverage is SourceCoverage.UNKNOWN:+ return Agreement.UNCOMPARABLE+ return Agreement.AGREED if self.divergence is None else Agreement.DIVERGED+++def compare(check: PlatformCheck, verdict: SourceVerdict, *, correspondence: SourceCorrespondence) -> Comparison:+ """Classifies one platform check against the source's verdict for the same check.++ Takes the correspondence rather than a source kind, so a caller cannot classify one source's+ verdict under another source's declarations.++ The order matters. A declared divergence is asked before a timing one, because the mute that+ explains a difference also stalls the source's own schedule and would otherwise read as a lag.+ A timing difference is asked before a real one, because a source that never reached this+ evaluation cannot have disagreed about it.+ """++ def result(divergence: DivergenceClass | None = None, reason: str = "") -> Comparison:+ return Comparison(+ ref=check.ref,+ coverage=verdict.coverage,+ platform_state=check.state,+ source_state=verdict.state,+ divergence=divergence,+ reason=reason,+ )++ if verdict.coverage is SourceCoverage.UNKNOWN:+ return result(reason=verdict.detail)++ if verdict.coverage is SourceCoverage.SUPPRESSED and verdict.suppressed_by in _EXCLUDED_BY_BOTH:+ # Asked before the states are compared, because both stacks exclude a disabled or broken+ # alert outright. The platform checking one at all is the drift, whatever state each holds,+ # and a disabled alert rests in the state a quiet check also records.+ return result(+ DivergenceClass.REAL, f"platform checked an alert its source suppressed ({verdict.suppressed_by})"+ )++ if verdict.state == check.state:+ return result()++ declared = next((d for d in correspondence.intentional_divergences if d.recognizes(check, verdict)), None)+ if declared is not None:+ return result(DivergenceClass.INTENTIONAL, declared.cause)++ if verdict.coverage is SourceCoverage.BEHIND:+ return result(DivergenceClass.TIMING, "source has not reached this check")++ return result(DivergenceClass.REAL)diff --git a/products/alerts_platform/backend/comparison/platform_history.py b/products/alerts_platform/backend/comparison/platform_history.pynew file mode 100644index 000000000000..dc9d9a1a76c0--- /dev/null+++ b/products/alerts_platform/backend/comparison/platform_history.py@@ -0,0 +1,102 @@+"""The platform half of a comparison: the checks the platform recorded in a window.++The history row carries `configuration_id`, and a correspondence needs `legacy_configuration_id`,+which lives on `PlatformAlertConfiguration` in Postgres. So a read is a Postgres query followed by+a ClickHouse one, and that stays true whatever columns the row grows.++Restricting the ClickHouse read to one source's configurations is what selects a source. The row's+own `source_kind` column would select the same rows, but the Postgres query has to run first anyway+for the legacy ids, so the configuration list costs nothing extra.+"""++from __future__ import annotations++from collections.abc import Sequence+from dataclasses import fields+from datetime import datetime+from uuid import UUID++from posthog.clickhouse.client import query_with_columns+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries++from products.alerts_platform.backend.facade.contracts import PlatformCheck, SourceKind+from products.alerts_platform.backend.models import PlatformAlertConfiguration+from products.alerts_platform.backend.models.platform_alert_events_sql import PLATFORM_ALERT_EVENTS_TABLE++# Refused rather than cut short, because an agreement rate over a silently truncated window+# is worse than no rate at all.+MAX_CHECKS_PER_WINDOW = 200_000++# Derived from the contract, so a field added there cannot be left out of the SELECT.+_COLUMNS = tuple(f.name for f in fields(PlatformCheck) if f.name not in ("team_id", "legacy_configuration_id"))++# `LIMIT 1 BY` deduplicates on the pair the writer names, because the insert token only covers a+# retry of the same batch and the engine remembers a bounded window of tokens. The ORDER BY is the+# table's sort key with `team_id` fixed, so rows stream in order and arrive grouped by alert.+_SELECT_SQL = f"""+SELECT {", ".join(_COLUMNS)}+FROM {PLATFORM_ALERT_EVENTS_TABLE}+WHERE team_id = %(team_id)s+ AND configuration_id IN %(configuration_ids)s+ AND occurred_at >= %(since)s+ AND occurred_at < %(until)s+ORDER BY configuration_id, alert_id, occurred_at, evaluation_key+LIMIT 1 BY alert_id, evaluation_key+LIMIT %(limit)s+"""+++class ComparisonWindowTooLarge(Exception):+ """The window holds more checks than one read will return."""+++class UnregisteredSource(Exception):+ """The configuration model has no `source_kind` for this source."""+++def read_platform_checks(+ *,+ team_id: int,+ source: SourceKind,+ since: datetime,+ until: datetime,+) -> Sequence[PlatformCheck]:+ """Every check the platform recorded for one source and team in `[since, until)`.++ A window wider than the shorter of the two retentions is not available: the platform's rows+ expire on a 90-day ClickHouse TTL, and each source ages its own history on its own schedule.+ """+ if source.value not in PlatformAlertConfiguration.SourceKind.values:+ # Two SourceKind enums exist and have already drifted. Without this an unregistered source+ # reads as a source that made no checks, which is the answer a comparison must never give.+ raise UnregisteredSource(f"{source.value} is not a source_kind the configuration model accepts")++ legacy_ids: dict[UUID, UUID | None] = dict(+ PlatformAlertConfiguration.objects.for_team(team_id)+ .filter(source_kind=source.value)+ .values_list("id", "legacy_configuration_id")+ )+ if not legacy_ids:+ return ()++ tag_queries(product=Product.PLATFORM_AND_SUPPORT, feature=Feature.ALERTING)+ rows = query_with_columns(+ _SELECT_SQL,+ {+ "team_id": team_id,+ "configuration_ids": list(legacy_ids),+ "since": since,+ "until": until,+ "limit": MAX_CHECKS_PER_WINDOW + 1,+ },+ team_id=team_id,+ )+ if len(rows) > MAX_CHECKS_PER_WINDOW:+ raise ComparisonWindowTooLarge(+ f"{since.isoformat()} to {until.isoformat()} holds over {MAX_CHECKS_PER_WINDOW} checks; narrow it"+ )++ return tuple(+ PlatformCheck(team_id=team_id, legacy_configuration_id=legacy_ids[row["configuration_id"]], **row)+ for row in rows+ )diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex cc79033da275..81e9dc607490 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -7,16 +7,20 @@ contract check watches this file to decide whether they must retest.from __future__ import annotations-from collections.abc import Collection+from collections.abc import Callable, Collection, Mapping, Sequencefrom dataclasses import fieldfrom datetime import datetimefrom enum import StrEnum-from typing import Any, Final, NotRequired, Protocol, TypedDict+from typing import TYPE_CHECKING, Any, Final, NotRequired, Protocol, TypedDictfrom uuid import UUIDfrom posthog.dataclasses import frozenfrom posthog.enums import LabeledStrEnum+if TYPE_CHECKING:+ # facade.lifecycle imports this module, so the policy type stays off the runtime import path.+ from products.alerts_platform.backend.facade.lifecycle import AlertPolicy+class SourceKind(StrEnum):LOGS = "logs"@@ -528,3 +532,159 @@ class DestinationResolver(Protocol):def __call__(self, *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]) -> list[AlertDestinationGroup]: ...+++# Comparison against a source's own stack.+#+# What a comparison reads, and what a source must supply for one.+#+# A comparison joins one platform check to the check a source's own stack made of the same alert+# at the same due time. The platform side of that join is uniform: `legacy_configuration_id` on+# the configuration names the source's own row, and `evaluation_key` on the history row names the+# evaluation. The source side is not uniform. Logs keys its own checks on the window, insight will+# key on the scheduled run, and neither shape is reconstructible from the platform row alone. So a+# source supplies the correspondence through `SourceCorrespondence` rather than the harness+# guessing it.+#+# A source declares everything about itself on that one object: how to find its own verdicts, the+# two policies its stacks run, and which differences between them are deliberate. A second+# registration point in the shared package would let a source change one and not the other.+#+# Two stacks never evaluate at the same instant. The key is what corresponds; a timestamp is only+# a bound on how far apart two corresponding checks may sit.+++@frozen+class CheckRef:+ """Addresses one platform check.++ `evaluation_key` is minted by the source and names the evaluation the check answered, so the+ pair survives a retry that recomputes the same check.+ """++ alert_id: UUID+ evaluation_key: str+++@frozen+class PlatformCheck:+ """One row of the platform's check history, as a comparison reads it.++ A comparison is over `state`, not over `kind`, because a check that moved the alert while a+ cooldown or a mute held the notification back records `AlertEventKind.CHECK`. Counting kinds+ misses every suppressed move. `kind` and `previous_state` are carried so a report can say what+ the platform announced and what it moved from.++ `muted_notification` is the announcement a mute held back, as a `NotificationAction` value.+ It is the platform's only record that an alert was muted at the moment of a check, because a+ muted check that decided nothing holds nothing and leaves no other trace.+ """++ team_id: int+ configuration_id: UUID+ # None for a configuration no source backfilled, which nothing can be compared against.+ legacy_configuration_id: UUID | None+ alert_id: UUID+ grouping_key: str+ evaluation_key: str+ kind: str+ previous_state: str+ state: str+ muted_notification: str+ error_message: str+ occurred_at: datetime++ @property+ def ref(self) -> CheckRef:+ return CheckRef(alert_id=self.alert_id, evaluation_key=self.evaluation_key)+++class SourceCoverage(StrEnum):+ """How far the source's own stack had got when the platform made this check.++ A source that cannot answer returns `UNKNOWN` rather than a guess, because a guess turns+ into a disagreement nobody can act on.+ """++ EVALUATED = "evaluated"+ SUPPRESSED = "suppressed"+ # The source's own stack had not reached this evaluation yet.+ BEHIND = "behind"+ UNKNOWN = "unknown"+++class SuppressionReason(StrEnum):+ """Why a source's own stack made no check.++ `MUTED` covers a snooze and a schedule restriction together, because one platform policy flag+ covers both.+ """++ MUTED = "muted"+ DISABLED = "disabled"+ BROKEN = "broken"+++@frozen+class SourceVerdict:+ """What a source's own stack held for the check that corresponds to one platform check.++ `state` is an `AlertState` value as `facade.lifecycle` spells it, which is the vocabulary the+ platform records. A source whose own tables spell its states differently translates here, at+ its own edge: insight stores the `posthog.schema_enums` spelling ("Firing", "Not firing"), and+ returning that raw would read as a disagreement on every check.+ """++ coverage: SourceCoverage+ state: str | None+ suppressed_by: SuppressionReason | None = None+ # When the source's evidence was written, so a report can show how far apart the two sit.+ observed_at: datetime | None = None+ # Addresses the source's own row, so a person reading a disagreement can open both sides.+ evidence_id: str | None = None+ detail: str = ""+++@frozen+class IntentionalDivergence:+ """One difference a source's platform stack makes on purpose.++ `recognizes` is what makes this a mechanism rather than a note: the classifier asks each+ declared divergence whether it explains the pair in front of it. A declaration without a+ working recognizer leaves its differences classified as real, which is the safe direction.++ `policy_flag` names the `AlertPolicy` field that causes it, and is what the ratchet matches+ against, so a source cannot configure a deliberate difference and leave it undeclared. Not+ every deliberate difference comes from a flag: insight collapses four failure kinds into two+ skip reasons, which no flag describes, so a declaration may leave it None and still be asked.++ The recognizer belongs to the source because the same flag shows up differently per source.+ Production logs stops checking a muted alert and its schedule stalls; insight keeps checking+ one and its schedule does not.+ """++ cause: str+ recognizes: Callable[[PlatformCheck, SourceVerdict], bool]+ why: str+ policy_flag: str | None = None+++class SourceCorrespondence(Protocol):+ """How a source says which of its own history corresponds to a platform check.++ `verdicts_for` is batched rather than per check, because a source answers from its own tables+ and a per-check call would issue one query per row of a comparison window.++ A correspondence returns a verdict for every ref it was given. A check it cannot answer gets+ `SourceCoverage.UNKNOWN`, never a missing entry, so a caller cannot mistake silence for+ agreement.+ """++ source: SourceKind+ # What the source's own stack runs, against what its platform adapter runs. Declared here so+ # it stays next to the code that passes them to the machine.+ production_policy: AlertPolicy+ platform_policy: AlertPolicy+ intentional_divergences: tuple[IntentionalDivergence, ...]++ def verdicts_for(self, checks: Sequence[PlatformCheck]) -> Mapping[CheckRef, SourceVerdict]: ...diff --git a/products/alerts_platform/backend/facade/testing.py b/products/alerts_platform/backend/facade/testing.pyindex 8c74462d0959..7faa9c34471f 100644--- a/products/alerts_platform/backend/facade/testing.py+++ b/products/alerts_platform/backend/facade/testing.py@@ -1,17 +1,23 @@-"""Test doors onto the platform's rows, for a source's own tests.+"""Test doors for a source's own tests.A source's tests set a configuration up and read back what a check decided. Both are rows this-product owns, so they cross as snapshots and ids rather than as model instances.+product owns, so they cross as snapshots and ids rather than as model instances. A source's tests+also check its comparison correspondence here, because the platform cannot list its sources."""from __future__ import annotationsfrom collections.abc import Iterable+from dataclasses import fieldsfrom datetime import datetimefrom typing import Anyfrom uuid import UUID-from products.alerts_platform.backend.facade.contracts import PlatformAlertSnapshot, PlatformConfigurationSnapshot+from products.alerts_platform.backend.facade.contracts import (+ PlatformAlertSnapshot,+ PlatformConfigurationSnapshot,+ SourceCorrespondence,+)from products.alerts_platform.backend.logic.platform_reads import instance_viewfrom products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration@@ -54,3 +60,15 @@ def alert_for(configuration_id: UUID, *, grouping_key: str = "") -> PlatformAler"""The instance row a check wrote, or None when no check has written one."""row = PlatformAlert.objects.filter(configuration_id=configuration_id, grouping_key=grouping_key).first()return None if row is None else instance_view(row)+++def undeclared_policy_divergences(correspondence: SourceCorrespondence) -> frozenset[str]:+ """The `AlertPolicy` flags on which a source's two stacks differ and it declares no divergence.++ A source's own tests assert this is empty.+ """+ production, platform = correspondence.production_policy, correspondence.platform_policy+ configured = {f.name for f in fields(production) if getattr(production, f.name) != getattr(platform, f.name)}+ # Coverage rather than equality: a source may also declare a deliberate difference no flag+ # describes, and must not be forced to invent one to hang the declaration on.+ return frozenset(configured - {divergence.policy_flag for divergence in correspondence.intentional_divergences})diff --git a/products/alerts_platform/backend/tests/test_comparison_divergence.py b/products/alerts_platform/backend/tests/test_comparison_divergence.pynew file mode 100644index 000000000000..63bcac021328--- /dev/null+++ b/products/alerts_platform/backend/tests/test_comparison_divergence.py@@ -0,0 +1,156 @@+from collections.abc import Mapping, Sequence+from datetime import UTC, datetime+from uuid import uuid4++from unittest import TestCase++from parameterized import parameterized++from products.alerts_platform.backend.comparison.divergence import Agreement, DivergenceClass, compare+from products.alerts_platform.backend.facade.contracts import (+ CheckRef,+ IntentionalDivergence,+ PlatformCheck,+ SourceCoverage,+ SourceKind,+ SourceVerdict,+ SuppressionReason,+)+from products.alerts_platform.backend.facade.lifecycle import LOGS_ALERT_POLICY, PLATFORM_LOGS_ALERT_POLICY++AT = datetime(2026, 9, 30, 12, 0, tzinfo=UTC)+++def _check(state: str, muted_notification: str = "none") -> PlatformCheck:+ return PlatformCheck(+ team_id=1,+ configuration_id=uuid4(),+ legacy_configuration_id=uuid4(),+ alert_id=uuid4(),+ grouping_key="",+ evaluation_key="window:2026-09-30T11:55:00+00:00",+ previous_state="not_firing",+ state=state,+ kind="check",+ muted_notification=muted_notification,+ error_message="",+ occurred_at=AT,+ )+++class _Correspondence:+ source = SourceKind.LOGS+ production_policy = LOGS_ALERT_POLICY+ platform_policy = PLATFORM_LOGS_ALERT_POLICY+ intentional_divergences: tuple[IntentionalDivergence, ...] = (+ IntentionalDivergence(+ cause="held_announcement",+ policy_flag="mute_gates_notification_only",+ recognizes=lambda check, _verdict: check.muted_notification != "none",+ why="",+ ),+ )++ def verdicts_for(self, checks: Sequence[PlatformCheck]) -> Mapping[CheckRef, SourceVerdict]:+ return {}+++class TestDivergenceClassification(TestCase):+ @parameterized.expand(+ [+ (+ "agreed",+ _check("firing"),+ SourceVerdict(coverage=SourceCoverage.EVALUATED, state="firing"),+ Agreement.AGREED,+ None,+ ),+ (+ "differing verdicts on an evaluated check",+ _check("firing"),+ SourceVerdict(coverage=SourceCoverage.EVALUATED, state="not_firing"),+ Agreement.DIVERGED,+ DivergenceClass.REAL,+ ),+ (+ "a declared divergence explains the difference",+ _check("firing", muted_notification="fire"),+ SourceVerdict(coverage=SourceCoverage.EVALUATED, state="not_firing"),+ Agreement.DIVERGED,+ DivergenceClass.INTENTIONAL,+ ),+ (+ "a declared divergence is asked before a lag",+ _check("firing", muted_notification="fire"),+ SourceVerdict(coverage=SourceCoverage.BEHIND, state="not_firing"),+ Agreement.DIVERGED,+ DivergenceClass.INTENTIONAL,+ ),+ (+ "a declared divergence does not excuse checking an alert the source had disabled",+ _check("firing", muted_notification="fire"),+ SourceVerdict(+ coverage=SourceCoverage.SUPPRESSED,+ state="not_firing",+ suppressed_by=SuppressionReason.DISABLED,+ ),+ Agreement.DIVERGED,+ DivergenceClass.REAL,+ ),+ (+ "the source has not reached this check",+ _check("firing"),+ SourceVerdict(coverage=SourceCoverage.BEHIND, state="not_firing"),+ Agreement.DIVERGED,+ DivergenceClass.TIMING,+ ),+ (+ "the platform checked an alert the source had disabled",+ _check("firing"),+ SourceVerdict(+ coverage=SourceCoverage.SUPPRESSED,+ state="not_firing",+ suppressed_by=SuppressionReason.DISABLED,+ ),+ Agreement.DIVERGED,+ DivergenceClass.REAL,+ ),+ (+ "the platform checked an alert the source had disabled, and both read not firing",+ _check("not_firing"),+ SourceVerdict(+ coverage=SourceCoverage.SUPPRESSED,+ state="not_firing",+ suppressed_by=SuppressionReason.DISABLED,+ ),+ Agreement.DIVERGED,+ DivergenceClass.REAL,+ ),+ (+ "the source cannot say",+ _check("firing"),+ SourceVerdict(coverage=SourceCoverage.UNKNOWN, state=None, detail="no such alert"),+ Agreement.UNCOMPARABLE,+ None,+ ),+ (+ "a lagging source that happens to hold the same verdict",+ _check("firing"),+ SourceVerdict(coverage=SourceCoverage.BEHIND, state="firing"),+ Agreement.AGREED,+ None,+ ),+ ]+ )+ def test_classification(+ self,+ _name: str,+ check: PlatformCheck,+ verdict: SourceVerdict,+ agreement: Agreement,+ divergence: DivergenceClass | None,+ ) -> None:+ comparison = compare(check, verdict, correspondence=_Correspondence())++ assert comparison.agreement == agreement+ assert comparison.divergence == divergencediff --git a/products/alerts_platform/backend/tests/test_comparison_platform_history.py b/products/alerts_platform/backend/tests/test_comparison_platform_history.pynew file mode 100644index 000000000000..1311dee2d100--- /dev/null+++ b/products/alerts_platform/backend/tests/test_comparison_platform_history.py@@ -0,0 +1,127 @@+from datetime import UTC, datetime, timedelta+from uuid import uuid4++import pytest+from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from posthog.clickhouse.client import sync_execute+from posthog.models.scoping import team_scope++from products.alerts_platform.backend.comparison.platform_history import UnregisteredSource, read_platform_checks+from products.alerts_platform.backend.facade.contracts import SourceKind+from products.alerts_platform.backend.logic.platform_alert_events import PlatformAlertEventRow, insert_events+from products.alerts_platform.backend.models import PlatformAlertConfiguration+from products.alerts_platform.backend.models.platform_alert_events_sql import PLATFORM_ALERT_EVENTS_TABLE++OCCURRED_AT = datetime(2026, 9, 30, 12, tzinfo=UTC)+WINDOW = (OCCURRED_AT - timedelta(hours=1), OCCURRED_AT + timedelta(hours=1))+++def _key(window_end: str) -> str:+ return f"slot:{OCCURRED_AT.isoformat()}|window:{window_end}"+++class TestReadPlatformChecks(ClickhouseTestMixin, APIBaseTest):+ def _configuration(self, **overrides) -> PlatformAlertConfiguration:+ with team_scope(self.team.id):+ return PlatformAlertConfiguration.objects.create(+ team=self.team,+ name="API errors",+ source_config={},+ threshold_count=10,+ threshold_operator="above",+ window_minutes=5,+ check_interval_minutes=5,+ **{"source_kind": PlatformAlertConfiguration.SourceKind.LOGS, **overrides},+ )++ def _row(+ self, configuration: PlatformAlertConfiguration, *, evaluation_key: str, **overrides+ ) -> PlatformAlertEventRow:+ return PlatformAlertEventRow(+ team_id=self.team.id,+ configuration_id=configuration.id,+ alert_id=overrides.pop("alert_id", uuid4()),+ grouping_key="",+ evaluation_key=evaluation_key,+ kind="firing",+ alert_name=configuration.name,+ previous_state="not_firing",+ state="firing",+ episode_started_at=OCCURRED_AT,+ value=47.0,+ labels={},+ condition_snapshot={},+ source_config_snapshot={},+ query_duration_ms=None,+ error_message=None,+ consecutive_failures=0,+ muted_notification="",+ occurred_at=OCCURRED_AT,+ **overrides,+ )++ def _record(self, configuration: PlatformAlertConfiguration, *, evaluation_key: str, **overrides) -> None:+ insert_events(self.team.id, [self._row(configuration, evaluation_key=evaluation_key, **overrides)])++ def _stored(self, configuration: PlatformAlertConfiguration) -> int:+ # Scoped to one configuration: ClickHouse is not rolled back, so a count over the team+ # sees rows other tests and earlier runs left.+ return sync_execute(+ f"SELECT count() FROM {PLATFORM_ALERT_EVENTS_TABLE} "+ "WHERE team_id = %(team_id)s AND configuration_id = %(configuration_id)s",+ {"team_id": self.team.id, "configuration_id": configuration.id},+ team_id=self.team.id,+ )[0][0]++ def _read(self) -> list:+ since, until = WINDOW+ return list(read_platform_checks(team_id=self.team.id, source=SourceKind.LOGS, since=since, until=until))++ def test_a_check_carries_the_legacy_id_its_configuration_holds(self) -> None:+ legacy_id = uuid4()+ configuration = self._configuration(legacy_configuration_id=legacy_id)+ self._record(configuration, evaluation_key=_key("2026-09-30T11:59:00+00:00"))++ checks = self._read()++ assert len(checks) == 1+ assert checks[0].legacy_configuration_id == legacy_id+ assert checks[0].configuration_id == configuration.id+ assert checks[0].state == "firing"+ assert checks[0].previous_state == "not_firing"+ assert checks[0].kind == "firing"++ def test_a_pair_recorded_twice_reads_as_one_check(self) -> None:+ configuration = self._configuration(legacy_configuration_id=uuid4())+ alert_id = uuid4()+ retried = self._row(configuration, evaluation_key=_key("2026-09-30T11:59:00+00:00"), alert_id=alert_id)+ insert_events(self.team.id, [retried])+ # The second batch carries another key so it takes a different insert token and lands.+ # An identical batch is dropped by the engine, leaving no duplicate to collapse.+ insert_events(+ self.team.id,+ [retried, self._row(configuration, evaluation_key=_key("2026-09-30T12:04:00+00:00"))],+ )+ assert self._stored(configuration) == 3++ checks = self._read()++ assert len(checks) == 2+ assert len({check.evaluation_key for check in checks}) == 2++ def test_a_source_the_configuration_model_does_not_accept_is_an_error(self) -> None:+ # Without this an unregistered source reads as one that made no checks, and whoever runs+ # the first insight comparison concludes the parallel run is quiet.+ since, until = WINDOW++ with pytest.raises(UnregisteredSource):+ read_platform_checks(team_id=self.team.id, source=SourceKind.INSIGHT, since=since, until=until)++ def test_another_source_is_not_in_a_logs_comparison(self) -> None:+ self._record(+ self._configuration(source_kind="insight", legacy_configuration_id=uuid4()),+ evaluation_key="run:2026-09-30T11:59:00+00:00",+ )++ assert self._read() == []diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.pyindex f8568156da11..e1535a82c0e5 100644--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py@@ -126,8 +126,11 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):)rows = sync_execute(- "SELECT state, episode_started_at FROM platform_alert_events WHERE team_id = %(team_id)s",- {"team_id": self.team.id},+ # Scoped to this configuration, not the team: ClickHouse is not rolled back between+ # runs while Postgres team ids restart, so a team id arrives carrying older rows.+ "SELECT state, 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": self.configuration.id},)assert rows == [("not_firing", self.cutoff)]diff --git a/products/logs/backend/alert_comparison.py b/products/logs/backend/alert_comparison.pynew file mode 100644index 000000000000..2b37b965f2d1--- /dev/null+++ b/products/logs/backend/alert_comparison.py@@ -0,0 +1,256 @@+"""The logs side of the alerts platform comparison contract.++Answers what the production logs stack held for the check that corresponds to one platform+check. The correspondence is reconstructed rather than looked up, because production logs keeps+no per-check row: `LogsAlertEvent` is written only when a check moves the alert or errors, plus+the control-plane rows a user action writes.++So the walk runs backwards from the present. The configuration's current `state` and `enabled`+are known, and every event row carries the state on both sides of itself, which makes the state+at any past instant the `state_before` of the first event after it. An alert that never moved+has no rows at all and resolves to its current state, which is the common case and the one a+forward walk would have to give up on.+"""++from __future__ import annotations++from collections import defaultdict+from collections.abc import Mapping, Sequence+from datetime import datetime+from uuid import UUID++from django.db.models import QuerySet++import structlog++from posthog.models import Team++from products.alerts_platform.backend.facade.contracts import (+ CheckRef,+ IntentionalDivergence,+ PlatformCheck,+ SourceCorrespondence,+ SourceCoverage,+ SourceKind,+ SourceVerdict,+ SuppressionReason,+)+from products.alerts_platform.backend.facade.lifecycle import (+ LOGS_ALERT_POLICY,+ PLATFORM_LOGS_ALERT_POLICY,+ AlertState,+ NotificationAction,+)+from products.logs.backend.alert_source_cycle import is_in_quiet_hours, window_end_of+from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent++logger = structlog.get_logger(__name__)++# An alert that flaps holds many transitions in one window. Past this bound the chain is not+# worth holding in memory, and a truncated chain would date checks wrongly.+MAX_EVENTS_PER_WINDOW = 5000++# The bound the per-alert one does not give: alerts each under their own ceiling still add up.+MAX_EVENTS_PER_BATCH = 100_000++_TOGGLE_KINDS = frozenset({LogsAlertEvent.Kind.ENABLE, LogsAlertEvent.Kind.DISABLE})+_CHAIN_FIELDS = ("id", "alert_id", "kind", "created_at", "state_before")+++def _mute_gates_notification_only(check: PlatformCheck, verdict: SourceVerdict) -> bool:+ """True when this difference is the platform evaluating an alert production logs would not.++ Two shapes, because production logs leaves two different traces. A mute it knows about parks+ the alert in SNOOZED, which the walk reports as suppressed. A schedule restriction reschedules+ the check instead, writing nothing and stalling `last_checked_at`, which the walk reports as+ behind. The platform's held announcement is what separates that stall from a real lag.+ """+ if verdict.coverage is SourceCoverage.SUPPRESSED:+ return verdict.suppressed_by is SuppressionReason.MUTED+ return verdict.coverage is SourceCoverage.BEHIND and check.muted_notification not in (+ "",+ NotificationAction.NONE.value,+ )+++LOGS_INTENTIONAL_DIVERGENCES: tuple[IntentionalDivergence, ...] = (+ IntentionalDivergence(+ cause="mute_gates_notification_only",+ policy_flag="mute_gates_notification_only",+ recognizes=_mute_gates_notification_only,+ why=(+ "The platform evaluates a muted alert and holds the announcement, so the alert keeps "+ "tracking reality through a snooze or a schedule restriction. Production logs excludes "+ "a snoozed alert from discovery and reschedules a restricted one, so it makes no check "+ "at all. Without this entry every snoozed logs alert reads as divergent."+ ),+ ),+)+++class LogsCorrespondence(SourceCorrespondence):+ source = SourceKind.LOGS+ production_policy = LOGS_ALERT_POLICY+ platform_policy = PLATFORM_LOGS_ALERT_POLICY+ intentional_divergences = LOGS_INTENTIONAL_DIVERGENCES++ def verdicts_for(self, checks: Sequence[PlatformCheck]) -> Mapping[CheckRef, SourceVerdict]:+ verdicts: dict[CheckRef, SourceVerdict] = {}+ by_alert: dict[tuple[int, UUID], list[PlatformCheck]] = defaultdict(list)+ for check in checks:+ if check.legacy_configuration_id is None:+ verdicts[check.ref] = _unknown("the platform configuration names no logs alert")+ else:+ by_alert[(check.team_id, check.legacy_configuration_id)].append(check)++ if not by_alert:+ return verdicts++ configurations = {+ (configuration.team_id, configuration.id): configuration+ for configuration in LogsAlertConfiguration.objects.filter(+ id__in=[alert_id for _, alert_id in by_alert],+ team_id__in={team_id for team_id, _ in by_alert},+ ).only("id", "team_id", "state", "enabled", "schedule_restriction", "last_checked_at")+ }+ # One narrow row per team, rather than the Team row `select_related` attaches to every+ # configuration to reach one field.+ timezones = dict(+ Team.objects.filter(id__in={team_id for team_id, _ in configurations}).values_list("id", "timezone")+ )+ instants = [check.occurred_at for group in by_alert.values() for check in group]+ events = self._chains(set(configurations), since=min(instants), until=max(instants))++ for key, group in by_alert.items():+ configuration = configurations.get(key)+ chain = events.get(key[1])+ for check in group:+ if configuration is None:+ verdicts[check.ref] = _unknown("no logs alert with that id in this project")+ elif chain is None:+ verdicts[check.ref] = _unknown("too many logs transitions to date this check against")+ else:+ verdicts[check.ref] = _verdict_at(configuration, chain, check, tz_name=timezones[key[0]])++ return verdicts++ def _chains(+ self, keys: set[tuple[int, UUID]], *, since: datetime, until: datetime+ ) -> dict[UUID, list[LogsAlertEvent]]:+ """Every transition each alert made after `since`, oldest first, keyed by alert.++ Bounded by the window being compared rather than by wall-clock time, plus the one later+ transition that dates the state a check at the end of the window was in. Reading to the+ present instead would spend the per-alert bound on transitions no check asks about.++ An alert whose chain could not be read whole is left out, so a caller cannot read a+ truncated chain as a complete one.+ """+ alert_ids = [alert_id for _, alert_id in keys]+ team_ids = {team_id for team_id, _ in keys}+ in_window = list(+ self._events(alert_ids, team_ids)+ .filter(created_at__gt=since, created_at__lte=until)+ .order_by("alert_id", "-created_at")[: MAX_EVENTS_PER_BATCH + 1]+ )++ held = in_window[:MAX_EVENTS_PER_BATCH]+ chains: dict[UUID, list[LogsAlertEvent]] = {alert_id: [] for alert_id in alert_ids}+ for row in held:+ chains[row.alert_id].append(row)++ incomplete = {alert_id for alert_id, chain in chains.items() if len(chain) > MAX_EVENTS_PER_WINDOW}+ if len(in_window) > MAX_EVENTS_PER_BATCH:+ # Ordered by alert, so the batch bound cut one alert short and left the rest unread.+ incomplete |= set(alert_ids) - {row.alert_id for row in held}+ incomplete.add(held[-1].alert_id)+ if incomplete:+ logger.warning(+ "Logs alert comparison could not read every transition it needs",+ since=since.isoformat(),+ alerts=len(incomplete),+ )++ complete = {alert_id: chain for alert_id, chain in chains.items() if alert_id not in incomplete}+ for chain in complete.values():+ chain.reverse()+ for row in self._first_after(list(complete), team_ids, until):+ complete[row.alert_id].append(row)+ # `enabled` is dated by the first toggle after a check, which can sit past that first row.+ # Without it an alert disabled after the window reads as disabled throughout it, and every+ # check in the window becomes a disagreement.+ for row in self._first_after(list(complete), team_ids, until, kinds=_TOGGLE_KINDS):+ chain = complete[row.alert_id]+ if not chain or chain[-1].id != row.id:+ chain.append(row)+ return complete++ def _first_after(+ self, alert_ids: list[UUID], team_ids: set[int], moment: datetime, *, kinds: frozenset | None = None+ ) -> QuerySet[LogsAlertEvent]:+ """The earliest transition each alert made after `moment`, optionally of certain kinds."""+ rows = self._events(alert_ids, team_ids).filter(created_at__gt=moment)+ if kinds is not None:+ rows = rows.filter(kind__in=kinds)+ return rows.order_by("alert_id", "created_at").distinct("alert_id")++ def _events(self, alert_ids: list[UUID], team_ids: set[int]) -> QuerySet[LogsAlertEvent]:+ return LogsAlertEvent.objects.filter(+ alert_id__in=alert_ids,+ # Restated, so a reader never meets a query on this table without a team term.+ alert__team_id__in=team_ids,+ ).only(*_CHAIN_FIELDS)+++def _unknown(detail: str) -> SourceVerdict:+ return SourceVerdict(coverage=SourceCoverage.UNKNOWN, state=None, detail=detail)+++def _verdict_at(+ configuration: LogsAlertConfiguration,+ chain: Sequence[LogsAlertEvent],+ check: PlatformCheck,+ *,+ tz_name: str,+) -> SourceVerdict:+ at = check.occurred_at+ after = [event for event in chain if event.created_at > at]+ boundary = after[0] if after else None+ state = boundary.state_before if boundary is not None else configuration.state++ toggle = next((event for event in after if event.kind in _TOGGLE_KINDS), None)+ enabled = toggle.kind == LogsAlertEvent.Kind.DISABLE if toggle is not None else configuration.enabled++ # The boundary is the transition that ended the state being reported, so it dates that state+ # rather than the check. None means the state still holds.+ observed_at = boundary.created_at if boundary is not None else None+ evidence_id = str(boundary.id) if boundary is not None else None++ def verdict(coverage: SourceCoverage, *, suppressed_by: SuppressionReason | None = None) -> SourceVerdict:+ return SourceVerdict(+ coverage=coverage,+ state=state,+ suppressed_by=suppressed_by,+ observed_at=observed_at,+ evidence_id=evidence_id,+ )++ if not enabled:+ return verdict(SourceCoverage.SUPPRESSED, suppressed_by=SuppressionReason.DISABLED)+ if state == AlertState.BROKEN:+ return verdict(SourceCoverage.SUPPRESSED, suppressed_by=SuppressionReason.BROKEN)+ if state == AlertState.SNOOZED:+ # No history of `snooze_until` is kept, so the state overstates the snooze by up to the+ # one check interval production logs takes to write the transition out of it.+ return verdict(SourceCoverage.SUPPRESSED, suppressed_by=SuppressionReason.MUTED)+ # The platform's parse, not production's, which reschedules past a blocked window rather than+ # testing one. A disagreement between the two parses is invisible here.+ if is_in_quiet_hours(configuration.schedule_restriction, at, tz_name, alert_id=configuration.id):+ return verdict(SourceCoverage.SUPPRESSED, suppressed_by=SuppressionReason.MUTED)++ # Production logs must have reached this data before it can have disagreed about it.+ bound = window_end_of(check.evaluation_key) or at+ if configuration.last_checked_at is None or configuration.last_checked_at < bound:+ return verdict(SourceCoverage.BEHIND)++ return verdict(SourceCoverage.EVALUATED)diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex 726eae5e06fc..2b718ac197e3 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -110,6 +110,9 @@ _NOTIFICATION_OUTCOME_KINDS: dict[NotificationAction, AlertEventKind] = {}+_WINDOW_MARKER = "window:"++def _evaluation_key(check: PlatformAlertCheckInput, window_end: datetime) -> str:"""Names the scheduled check, and the window it answered for.@@ -122,7 +125,22 @@ def _evaluation_key(check: PlatformAlertCheckInput, window_end: datetime) -> strshape across sources. Both parts are read before anything is written, so a retry recomputesthe same key."""- return f"slot:{slot_of(check.next_check_at, window_end)}|window:{window_end.isoformat()}"+ return f"slot:{slot_of(check.next_check_at, window_end)}|{_WINDOW_MARKER}{window_end.isoformat()}"+++def window_end_of(evaluation_key: str) -> datetime | None:+ """The window end `_evaluation_key` put in a key, for a reader that has only the key.++ The inverse lives next to the minter so a change to one breaks the round trip rather than+ silently returning None to a reader in another module.+ """+ _, marker, tail = evaluation_key.rpartition(_WINDOW_MARKER)+ if not marker:+ return None+ try:+ return datetime.fromisoformat(tail)+ except ValueError:+ return Nonedef _cohort_key(check: PlatformAlertCheckInput, checkpoint: datetime | None, now: datetime) -> tuple:@@ -135,20 +153,20 @@ def _cohort_key(check: PlatformAlertCheckInput, checkpoint: datetime | None, now)-def _is_in_quiet_hours(check: PlatformAlertCheckInput, now: datetime, tz_name: str) -> bool:- """True when the alert's schedule restriction mutes an announcement at the batch instant.+def is_in_quiet_hours(schedule_restriction: dict | None, now: datetime, tz_name: str, *, alert_id: UUID) -> bool:+ """True when the alert's schedule restriction mutes an announcement at `now`.The check still runs, so an incident wholly inside the window is still recorded."""- if not check.schedule_restriction:+ if not schedule_restriction:return Falsetry:- return is_utc_datetime_blocked(now, tz_name, parse_blocked_windows_tuples(check.schedule_restriction))+ return is_utc_datetime_blocked(now, tz_name, parse_blocked_windows_tuples(schedule_restriction))except Exception as error:# A restriction we cannot parse must not decide the alert either way, so the check# proceeds and the production stack keeps ownership of the broken configuration.logger.exception(- "Unparseable schedule restriction; evaluating anyway", check_id=str(check.id), error=str(error)+ "Unparseable schedule restriction; evaluating anyway", alert_id=str(alert_id), error=str(error))return False@@ -470,7 +488,7 @@ def _triage(checks: Sequence[PlatformAlertCheckInput], *, now: datetime, tz_name))continue- if _is_in_quiet_hours(check, now, tz_name):+ if is_in_quiet_hours(check.schedule_restriction, now, tz_name, alert_id=check.id):muted_ids.add(check.id)evaluable.append(check)return _Triage(decided=decided, evaluable=evaluable, muted_ids=frozenset(muted_ids))diff --git a/products/logs/backend/test/test_alert_comparison.py b/products/logs/backend/test/test_alert_comparison.pynew file mode 100644index 000000000000..4461f5998793--- /dev/null+++ b/products/logs/backend/test/test_alert_comparison.py@@ -0,0 +1,293 @@+from dataclasses import replace+from datetime import UTC, datetime, timedelta+from uuid import UUID, uuid4++from posthog.test.base import BaseTest+from unittest import TestCase+from unittest.mock import patch++from parameterized import parameterized++from products.alerts_platform.backend.facade.contracts import (+ PlatformAlertCheckInput,+ PlatformCheck,+ SourceCoverage,+ SourceVerdict,+ SuppressionReason,+)+from products.alerts_platform.backend.facade.testing import undeclared_policy_divergences+from products.logs.backend.alert_comparison import LOGS_INTENTIONAL_DIVERGENCES, LogsCorrespondence+from products.logs.backend.alert_source_cycle import _evaluation_key, window_end_of+from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent++CHECKED_AT = datetime(2026, 9, 30, 12, 0, tzinfo=UTC)+WINDOW_END = CHECKED_AT - timedelta(minutes=1)+++def _check_input(alert_id, *, next_check_at) -> PlatformAlertCheckInput:+ return PlatformAlertCheckInput(+ id=alert_id,+ team_id=1,+ name="API errors",+ source_config={},+ threshold_count=10,+ threshold_operator="above",+ window_minutes=5,+ check_interval_minutes=5,+ evaluation_periods=1,+ datapoints_to_alarm=1,+ cooldown_minutes=0,+ schedule_restriction=None,+ next_check_at=next_check_at,+ consecutive_failures=0,+ legacy_configuration_id=None,+ state="not_firing",+ last_notified_at=None,+ snooze_until=None,+ )+++EVALUATION_KEY = _evaluation_key(_check_input(uuid4(), next_check_at=CHECKED_AT), WINDOW_END)+++def _platform_check(+ *,+ team_id: int = 1,+ legacy_configuration_id: UUID | None = None,+ at: datetime = CHECKED_AT,+ muted_notification: str = "none",+) -> PlatformCheck:+ return PlatformCheck(+ team_id=team_id,+ configuration_id=uuid4(),+ legacy_configuration_id=legacy_configuration_id,+ alert_id=uuid4(),+ grouping_key="",+ evaluation_key=EVALUATION_KEY,+ previous_state="not_firing",+ state="firing",+ kind="check",+ muted_notification=muted_notification,+ error_message="",+ occurred_at=at,+ )+++class TestLogsDivergenceDeclarations(TestCase):+ def test_every_policy_divergence_is_declared(self) -> None:+ assert undeclared_policy_divergences(LogsCorrespondence()) == frozenset()++ @parameterized.expand(+ [+ (+ "the source made no check because it was muted",+ _platform_check(),+ SourceVerdict(+ coverage=SourceCoverage.SUPPRESSED, state="snoozed", suppressed_by=SuppressionReason.MUTED+ ),+ True,+ ),+ (+ "the platform held an announcement while the source fell behind",+ _platform_check(muted_notification="fire"),+ SourceVerdict(coverage=SourceCoverage.BEHIND, state="not_firing"),+ True,+ ),+ (+ "the platform held an announcement the source was not muted for",+ _platform_check(muted_notification="fire"),+ SourceVerdict(coverage=SourceCoverage.EVALUATED, state="not_firing"),+ False,+ ),+ ]+ )+ def test_mute_divergence_recognizes(+ self, _name: str, check: PlatformCheck, verdict: SourceVerdict, recognized: bool+ ) -> None:+ (mute,) = LOGS_INTENTIONAL_DIVERGENCES++ assert mute.recognizes(check, verdict) is recognized+++class TestLogsCorrespondence(BaseTest):+ def _alert(self, **overrides) -> LogsAlertConfiguration:+ return LogsAlertConfiguration.objects.create(+ team=self.team,+ name="API errors",+ created_by=self.user,+ threshold_count=10,+ **{"last_checked_at": CHECKED_AT, **overrides},+ )++ def _event(self, alert: LogsAlertConfiguration, *, at: datetime, **overrides) -> LogsAlertEvent:+ event = LogsAlertEvent.objects.create(+ alert=alert,+ threshold_breached=False,+ state_before=overrides.pop("state_before", LogsAlertConfiguration.State.NOT_FIRING),+ state_after=overrides.pop("state_after", LogsAlertConfiguration.State.FIRING),+ **overrides,+ )+ LogsAlertEvent.objects.filter(pk=event.pk).update(created_at=at)+ event.refresh_from_db()+ return event++ def _check(self, alert: LogsAlertConfiguration, *, at: datetime = CHECKED_AT) -> PlatformCheck:+ return _platform_check(team_id=self.team.id, legacy_configuration_id=alert.id, at=at)++ def _verdict(self, alert: LogsAlertConfiguration):+ check = self._check(alert)+ return LogsCorrespondence().verdicts_for([check])[check.ref]++ def test_an_alert_that_never_transitioned_reports_its_current_state(self) -> None:+ alert = self._alert(state=LogsAlertConfiguration.State.FIRING)++ verdict = self._verdict(alert)++ assert verdict.state == LogsAlertConfiguration.State.FIRING+ assert verdict.coverage is SourceCoverage.EVALUATED++ def test_the_state_comes_from_the_transition_after_the_check(self) -> None:+ alert = self._alert(state=LogsAlertConfiguration.State.FIRING)+ self._event(+ alert,+ at=CHECKED_AT + timedelta(minutes=5),+ state_before=LogsAlertConfiguration.State.NOT_FIRING,+ state_after=LogsAlertConfiguration.State.FIRING,+ )++ verdict = self._verdict(alert)++ assert verdict.state == LogsAlertConfiguration.State.NOT_FIRING+ assert verdict.observed_at == CHECKED_AT + timedelta(minutes=5)++ @parameterized.expand(+ [+ (+ "snoozed",+ {"state": LogsAlertConfiguration.State.SNOOZED},+ SourceCoverage.SUPPRESSED,+ SuppressionReason.MUTED,+ ),+ (+ "broken",+ {"state": LogsAlertConfiguration.State.BROKEN},+ SourceCoverage.SUPPRESSED,+ SuppressionReason.BROKEN,+ ),+ (+ "inside a schedule restriction",+ {"schedule_restriction": {"blocked_windows": [{"start": "11:00", "end": "13:00"}]}},+ SourceCoverage.SUPPRESSED,+ SuppressionReason.MUTED,+ ),+ (+ "disabled",+ {"enabled": False},+ SourceCoverage.SUPPRESSED,+ SuppressionReason.DISABLED,+ ),+ (+ "never checked",+ {"last_checked_at": None},+ SourceCoverage.BEHIND,+ None,+ ),+ (+ "stalled before the window the platform answered for",+ {"last_checked_at": WINDOW_END - timedelta(minutes=1)},+ SourceCoverage.BEHIND,+ None,+ ),+ ]+ )+ def test_coverage(+ self,+ _name: str,+ overrides: dict,+ coverage: SourceCoverage,+ suppressed_by: SuppressionReason | None,+ ) -> None:+ alert = self._alert(**overrides)++ verdict = self._verdict(alert)++ assert verdict.coverage is coverage+ assert verdict.suppressed_by is suppressed_by++ def test_a_disable_after_the_check_means_the_alert_was_enabled_at_it(self) -> None:+ alert = self._alert(enabled=False)+ self._event(+ alert,+ at=CHECKED_AT + timedelta(minutes=5),+ kind=LogsAlertEvent.Kind.DISABLE,+ state_before=LogsAlertConfiguration.State.NOT_FIRING,+ state_after=LogsAlertConfiguration.State.NOT_FIRING,+ )++ verdict = self._verdict(alert)++ assert verdict.coverage is SourceCoverage.EVALUATED++ def test_one_flapping_alert_does_not_cost_the_batch_its_answers(self) -> None:+ flapping = self._alert()+ quiet = self._alert()+ window_start = CHECKED_AT - timedelta(hours=1)+ for minute in range(3):+ self._event(flapping, at=window_start + timedelta(minutes=minute + 1))+ # Two instants, so the compared window has room to hold the transitions between them.+ checks = [self._check(flapping, at=window_start), self._check(flapping)]+ checks += [self._check(quiet, at=window_start), self._check(quiet)]++ with patch("products.logs.backend.alert_comparison.MAX_EVENTS_PER_WINDOW", 2):+ verdicts = LogsCorrespondence().verdicts_for(checks)++ assert verdicts[checks[0].ref].coverage is SourceCoverage.UNKNOWN+ assert verdicts[checks[2].ref].coverage is SourceCoverage.EVALUATED++ def test_a_transition_after_the_window_still_dates_the_last_check(self) -> None:+ # The read is bounded by the window, so this row sits outside it and is fetched on purpose.+ alert = self._alert(state=LogsAlertConfiguration.State.FIRING)+ self._event(+ alert,+ at=CHECKED_AT + timedelta(hours=2),+ state_before=LogsAlertConfiguration.State.NOT_FIRING,+ state_after=LogsAlertConfiguration.State.FIRING,+ )++ assert self._verdict(alert).state == LogsAlertConfiguration.State.NOT_FIRING++ def test_the_window_bound_round_trips_through_the_key_the_source_mints(self) -> None:+ # A key the minter no longer produces would silently cost every check its window bound.+ check = _check_input(uuid4(), next_check_at=CHECKED_AT)++ assert window_end_of(_evaluation_key(check, WINDOW_END)) == WINDOW_END++ def test_an_alert_disabled_after_the_window_was_still_enabled_during_it(self) -> None:+ # The read is bounded by the window, so a toggle can sit past the first transition after+ # it. Missing it reads the whole window as disabled, and every check as a disagreement.+ alert = self._alert(enabled=False)+ self._event(+ alert,+ at=CHECKED_AT + timedelta(hours=2),+ state_before=LogsAlertConfiguration.State.NOT_FIRING,+ state_after=LogsAlertConfiguration.State.FIRING,+ )+ self._event(+ alert,+ at=CHECKED_AT + timedelta(hours=3),+ kind=LogsAlertEvent.Kind.DISABLE,+ state_before=LogsAlertConfiguration.State.FIRING,+ state_after=LogsAlertConfiguration.State.NOT_FIRING,+ )++ verdict = self._verdict(alert)++ assert verdict.coverage is SourceCoverage.EVALUATED+ assert verdict.suppressed_by is None++ def test_a_check_whose_configuration_names_no_logs_alert_cannot_be_answered(self) -> None:+ orphan = replace(self._check(self._alert()), legacy_configuration_id=None)++ verdicts = LogsCorrespondence().verdicts_for([orphan])++ assert verdicts[orphan.ref].coverage is SourceCoverage.UNKNOWN