: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): drive a comparison across a window and report what it found (#109679)
Jimmy Zhu7a0bf5fe2e85
diff --git a/products/alerts_platform/backend/comparison/orchestration.py b/products/alerts_platform/backend/comparison/orchestration.pynew file mode 100644index 000000000000..4e5320bd261f--- /dev/null+++ b/products/alerts_platform/backend/comparison/orchestration.py@@ -0,0 +1,284 @@+"""What drives a comparison: choose a window, read both sides, classify every pair.++## Running one++Nothing schedules this. Until something does, a run is a Django shell away, on a pod or locally.+Both reads are read-only, so this cannot change what either stack does.++ from datetime import UTC, datetime, timedelta++ from products.alerts_platform.backend.comparison.orchestration import run_comparison+ from products.alerts_platform.backend.comparison.platform_history import teams_with_configurations+ from products.alerts_platform.backend.facade.contracts import SourceKind+ from products.logs.backend.alert_comparison import LogsCorrespondence++ until = datetime.now(UTC)+ run = run_comparison(+ correspondence=LogsCorrespondence(),+ team_ids=teams_with_configurations(SourceKind.LOGS),+ since=until - timedelta(hours=24),+ until=until,+ )+ print(run.checks, run.agreement_rate, run.by_agreement, run.by_coverage)+ print(run.by_divergence, run.real_caught_up_within)++Read the breakdowns together or the headline misleads. `by_coverage` says how much of the window+the source could answer for: a large `unknown` share means the backfill is incomplete, not that+the stacks disagree. `by_divergence` splits the disagreements.++Then read `real_caught_up_within`, which is the one a first run exists to produce. It takes every+`REAL` divergence and asks how long after that check the source reached the platform's verdict. A+`real` count sitting in the `60s` and `5m` buckets is two cadences out of phase; the `never` bucket+is where the two stacks actually disagreed. Compare the buckets against the source's own check+interval: for logs that is `check_interval_minutes` on the configuration, commonly 5.++`pending` is the window's own edge: checks too recent for the source to have had its next check+yet. A large `pending` share means the window is too short or ends too close to now, not that+anything disagrees. Widen it, or pass a `settle_for` matching the source's cadence.++`run.divergences` holds up to `MAX_SAMPLED_DIVERGENCES` of them, each naming its alert and both+states, which is where to start reading individual cases.++Widen the window past 90 days and the platform's rows have expired; `ComparisonWindowTooLarge`+means narrow it rather than retry.++## How a pair is chosen++The join is one-directional, so there is no set-matching problem to solve. `read_platform_checks`+returns platform checks, and each one asks the source what state it held at that check's+`occurred_at`. The source side is not a set of checks at all: it is a state reconstruction that+answers for any instant. Five platform checks against three source checks in one window gives five+comparisons, not an alignment problem.++Two joins, both exact. `legacy_configuration_id` names the alert. `occurred_at` names the moment.++## The decision this leaves open++Neither join handles phase skew between the two cadences. The only defense is `SourceCoverage`+`BEHIND`, which asks whether the source had *seen* the data, by testing its own last check against+the window end in the evaluation key. It does not ask whether the source has had a check *since*+that data, so two stacks a few minutes out of phase produce a false `REAL`:++- The platform checks at 12:00 over a window ending 11:59, sees a breach, goes firing.+- Production logs last checked at 11:59, so the `BEHIND` test passes and coverage reads `EVALUATED`.+- Its own next check is 12:04, so at 12:00 it is still not firing.+- The states differ under `EVALUATED` coverage, which classifies as `REAL`.++The N-of-M window is a second route to the same false positive, independent of scheduling: each+stack builds its recent-breach history from its own rows, so two stacks reading the same data can+sit at different points in their own counts.++No tolerance is applied here, on purpose. Narrowing the comparison to instants where both stacks+have settled would discard comparisons to buy precision, and the rate being bought is unknown. A+run reports its classes separately so the first one measures how much `REAL` is really phase skew,+and the tolerance is chosen against that number rather than ahead of it.++So do not read the first run's `real` count as the number of genuine disagreements. Read it as an+upper bound, and spend the first run working out what share of it is two cadences out of phase.++## What a run cannot see++Every comparison starts from a platform row, so a check the source made and the platform never did+is invisible. A run measures what the platform decided and whether the source agreed, not whether+the two made the same checks.++## Why the correspondence is a parameter++`products.alerts_platform` may not import `products.logs`, so a registry of correspondences cannot live+here. The caller supplies one, which also keeps a run from classifying one source's verdicts under+another source's declarations.+"""++from __future__ import annotations++from collections import Counter+from collections.abc import Mapping, Sequence+from dataclasses import field+from datetime import datetime, timedelta+from typing import Final++import structlog++from posthog.dataclasses import frozen++from products.alerts_platform.backend.comparison.divergence import Agreement, Comparison, DivergenceClass, compare+from products.alerts_platform.backend.comparison.platform_history import ComparisonWindowTooLarge, read_platform_checks+from products.alerts_platform.backend.facade.contracts import (+ CheckRef,+ PlatformCheck,+ SourceCorrespondence,+ SourceCoverage,+ SourceKind,+ SourceVerdict,+)++logger = structlog.get_logger(__name__)++# A run reports a rate and a sample, not every row. Past this the sample stops growing and the+# counts carry on, because the counts are what the rate is built from.+MAX_SAMPLED_DIVERGENCES = 200++# How long after a platform check the source reached the same verdict. A real disagreement that+# the source caught up to within a check interval or two is two cadences out of phase, not a+# disagreement. The buckets are wide and in seconds so they stay source-agnostic: read them+# against the cadence of whichever source was swept.+_CAUGHT_UP_BUCKETS: Final[tuple[tuple[str, float], ...]] = (+ ("60s", 60),+ ("5m", 300),+ ("15m", 900),+ ("1h", 3600),+)+_NEVER_CAUGHT_UP = "never"+_CAUGHT_UP_LATER = "beyond_1h"+_PENDING = "pending"+_SOURCE_SUPPRESSED = "source_suppressed"++# How long a check needs to sit before "the source never caught up" means anything. Three times+# the five-minute cadence logs runs at; pass a source's own interval when it differs.+DEFAULT_SETTLE_FOR = timedelta(minutes=15)+++@frozen+class ComparisonRun:+ """What one sweep found.++ The three breakdowns answer different questions and a reader needs all of them. `by_divergence`+ is the output the exercise exists for. `by_coverage` says how much of the window the source+ could answer for at all, which measures how complete the backfill is as much as it measures+ agreement. `teams_unread` says where the sweep saw nothing, which is neither.++ `real_caught_up_within` is what makes a first run worth reading. For every `REAL` divergence it+ asks whether the source went on to reach the platform's verdict, and how long after. A run+ whose `real` sits mostly in the short buckets is measuring phase skew rather than disagreement.+ `never` is the share worth chasing. `pending` is neither: those checks are too recent for the+ source to have answered them, and a shorter window makes that share larger. `source_suppressed`+ is the platform checking an alert its source excluded, which is drift rather than a lag.+ """++ source: SourceKind+ since: datetime+ until: datetime+ teams_read: int+ checks: int+ by_agreement: dict[str, int] = field(default_factory=dict)+ by_divergence: dict[str, int] = field(default_factory=dict)+ by_coverage: dict[str, int] = field(default_factory=dict)+ real_caught_up_within: dict[str, int] = field(default_factory=dict)+ teams_unread: dict[int, str] = field(default_factory=dict)+ divergences: tuple[Comparison, ...] = ()++ @property+ def agreement_rate(self) -> float | None:+ """Agreed over what could be compared at all.++ `UNCOMPARABLE` is excluded rather than counted against agreement, because a source that+ cannot answer has not disagreed. None when nothing was comparable, which is a different+ answer from zero.+ """+ comparable = self.by_agreement.get(Agreement.AGREED, 0) + self.by_agreement.get(Agreement.DIVERGED, 0)+ if not comparable:+ return None+ return self.by_agreement.get(Agreement.AGREED, 0) / comparable+++def run_comparison(+ *,+ correspondence: SourceCorrespondence,+ team_ids: Sequence[int],+ since: datetime,+ until: datetime,+ settle_for: timedelta = DEFAULT_SETTLE_FOR,+) -> ComparisonRun:+ """Every platform check in the window, set against what the source held at the same moment.++ One team at a time, because the platform read is per team. A team the platform cannot be read+ for is recorded and the sweep continues, so one oversized window does not cost the rest.+ """+ # A repeated team would otherwise count its checks twice, and leave `teams_read` claiming a+ # team the sweep only failed to read.+ teams = list(dict.fromkeys(team_ids))+ agreements: Counter[str] = Counter()+ divergence_classes: Counter[str] = Counter()+ coverages: Counter[str] = Counter()+ caught_up: Counter[str] = Counter()+ unread: dict[int, str] = {}+ sampled: list[Comparison] = []+ checks = 0++ for team_id in teams:+ try:+ platform_checks = read_platform_checks(+ team_id=team_id, source=correspondence.source, since=since, until=until+ )+ except ComparisonWindowTooLarge as error:+ unread[team_id] = str(error)+ logger.warning(+ "Comparison skipped a team whose window is too large",+ team_id=team_id,+ source=correspondence.source.value,+ )+ continue+ if not platform_checks:+ continue++ verdicts = correspondence.verdicts_for(platform_checks)+ for check in platform_checks:+ verdict = _verdict_for(verdicts, check.ref)+ comparison = compare(check, verdict, correspondence=correspondence)+ checks += 1+ agreements[comparison.agreement.value] += 1+ coverages[comparison.coverage.value] += 1+ if comparison.divergence is not None:+ divergence_classes[comparison.divergence.value] += 1+ if comparison.divergence is DivergenceClass.REAL:+ caught_up[_caught_up_bucket(check, verdict, settles_by=until - settle_for)] += 1+ if len(sampled) < MAX_SAMPLED_DIVERGENCES:+ sampled.append(comparison)++ return ComparisonRun(+ source=correspondence.source,+ since=since,+ until=until,+ teams_read=len(teams) - len(unread),+ checks=checks,+ by_agreement=dict(agreements),+ by_divergence=dict(divergence_classes),+ by_coverage=dict(coverages),+ real_caught_up_within=dict(caught_up),+ teams_unread=unread,+ divergences=tuple(sampled),+ )+++def _verdict_for(verdicts: Mapping[CheckRef, SourceVerdict], ref: CheckRef) -> SourceVerdict:+ """The source's answer for one check, or an unanswered one.++ The contract obliges a correspondence to answer every ref it was given. Nothing enforced that+ until there was a caller holding both sides, and a missing ref must not read as agreement.+ """+ return verdicts.get(ref) or SourceVerdict(+ caught_up_at=None,+ coverage=SourceCoverage.UNKNOWN,+ state=None,+ detail="the source returned no verdict for this check",+ )+++def _caught_up_bucket(check: PlatformCheck, verdict: SourceVerdict, *, settles_by: datetime) -> str:+ """How long after this check the source reached the platform's verdict.++ A check later than `settles_by` has not had long enough for the source to answer it, so its+ silence is pending rather than disagreement. Without that split, every run of a window ending+ now books its last few minutes of checks into the one bucket worth acting on.+ """+ if verdict.coverage is SourceCoverage.SUPPRESSED:+ # The source made no check to catch up with, so its next move into the state dates nothing.+ return _SOURCE_SUPPRESSED+ if verdict.caught_up_at is None:+ return _PENDING if check.occurred_at > settles_by else _NEVER_CAUGHT_UP+ lag = (verdict.caught_up_at - check.occurred_at).total_seconds()+ if lag < 0:+ # Reaching the verdict before the check is not catching up to it, and counting the gap+ # would read a disagreement as the shortest possible lag.+ return _NEVER_CAUGHT_UP+ return next((label for label, bound in _CAUGHT_UP_BUCKETS if lag <= bound), _CAUGHT_UP_LATER)diff --git a/products/alerts_platform/backend/comparison/platform_history.py b/products/alerts_platform/backend/comparison/platform_history.pyindex dc9d9a1a76c0..b184be4d3ccf 100644--- a/products/alerts_platform/backend/comparison/platform_history.py+++ b/products/alerts_platform/backend/comparison/platform_history.py@@ -54,6 +54,33 @@ class UnregisteredSource(Exception):"""The configuration model has no `source_kind` for this source."""+def _refuse_unregistered(source: SourceKind) -> None:+ """Two SourceKind enums exist and have already drifted. An unregistered source would otherwise+ read as one that made no checks, which is the answer a comparison must never give."""+ if source.value not in PlatformAlertConfiguration.SourceKind.values:+ raise UnregisteredSource(f"{source.value} is not a source_kind the configuration model accepts")+++def teams_with_configurations(source: SourceKind) -> list[int]:+ """The teams a sweep is worth running for, in one query.++ A team with no configuration for this source has no checks either, and asking per team costs a+ Postgres round trip each to learn it. Cross-team on purpose: this reads which tenants exist+ rather than any tenant's data, and every read after it is scoped to one team.++ Not filtered on `enabled`, because a configuration disabled today still has history in a+ window that predates the change.+ """+ _refuse_unregistered(source)+ return list(+ PlatformAlertConfiguration.objects.unscoped()+ .filter(source_kind=source.value)+ .values_list("team_id", flat=True)+ .distinct()+ .order_by("team_id")+ )++def read_platform_checks(*,team_id: int,@@ -66,10 +93,7 @@ def read_platform_checks(A window wider than the shorter of the two retentions is not available: the platform's rowsexpire 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")+ _refuse_unregistered(source)legacy_ids: dict[UUID, UUID | None] = dict(PlatformAlertConfiguration.objects.for_team(team_id)diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex 81e9dc607490..e8f2e60a0151 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -638,8 +638,14 @@ class SourceVerdict:coverage: SourceCoveragestate: str | Nonesuppressed_by: SuppressionReason | None = None- # When the source's evidence was written, so a report can show how far apart the two sit.+ # When the source left `state`, so a report can date the state it is reporting.observed_at: datetime | None = None+ # When the source reached the state this check decided, which separates two cadences out of+ # phase from a real disagreement. The source answers it because it holds the check, and the+ # path there may take several transitions: not firing, errored, firing has reached firing.+ # Required, because None means the source never got there: a source that left it unset would+ # book every lag as a disagreement and nothing would fail.+ caught_up_at: datetime | None# Addresses the source's own row, so a person reading a disagreement can open both sides.evidence_id: str | None = Nonedetail: str = ""diff --git a/products/alerts_platform/backend/tests/test_comparison_divergence.py b/products/alerts_platform/backend/tests/test_comparison_divergence.pyindex 63bcac021328..ad15d62baa26 100644--- a/products/alerts_platform/backend/tests/test_comparison_divergence.py+++ b/products/alerts_platform/backend/tests/test_comparison_divergence.py@@ -61,28 +61,28 @@ class TestDivergenceClassification(TestCase):("agreed",_check("firing"),- SourceVerdict(coverage=SourceCoverage.EVALUATED, state="firing"),+ SourceVerdict(caught_up_at=None, coverage=SourceCoverage.EVALUATED, state="firing"),Agreement.AGREED,None,),("differing verdicts on an evaluated check",_check("firing"),- SourceVerdict(coverage=SourceCoverage.EVALUATED, state="not_firing"),+ SourceVerdict(caught_up_at=None, 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"),+ SourceVerdict(caught_up_at=None, 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"),+ SourceVerdict(caught_up_at=None, coverage=SourceCoverage.BEHIND, state="not_firing"),Agreement.DIVERGED,DivergenceClass.INTENTIONAL,),@@ -90,6 +90,7 @@ class TestDivergenceClassification(TestCase):"a declared divergence does not excuse checking an alert the source had disabled",_check("firing", muted_notification="fire"),SourceVerdict(+ caught_up_at=None,coverage=SourceCoverage.SUPPRESSED,state="not_firing",suppressed_by=SuppressionReason.DISABLED,@@ -100,7 +101,7 @@ class TestDivergenceClassification(TestCase):("the source has not reached this check",_check("firing"),- SourceVerdict(coverage=SourceCoverage.BEHIND, state="not_firing"),+ SourceVerdict(caught_up_at=None, coverage=SourceCoverage.BEHIND, state="not_firing"),Agreement.DIVERGED,DivergenceClass.TIMING,),@@ -108,6 +109,7 @@ class TestDivergenceClassification(TestCase):"the platform checked an alert the source had disabled",_check("firing"),SourceVerdict(+ caught_up_at=None,coverage=SourceCoverage.SUPPRESSED,state="not_firing",suppressed_by=SuppressionReason.DISABLED,@@ -119,6 +121,7 @@ class TestDivergenceClassification(TestCase):"the platform checked an alert the source had disabled, and both read not firing",_check("not_firing"),SourceVerdict(+ caught_up_at=None,coverage=SourceCoverage.SUPPRESSED,state="not_firing",suppressed_by=SuppressionReason.DISABLED,@@ -129,14 +132,14 @@ class TestDivergenceClassification(TestCase):("the source cannot say",_check("firing"),- SourceVerdict(coverage=SourceCoverage.UNKNOWN, state=None, detail="no such alert"),+ SourceVerdict(caught_up_at=None, 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"),+ SourceVerdict(caught_up_at=None, coverage=SourceCoverage.BEHIND, state="firing"),Agreement.AGREED,None,),diff --git a/products/alerts_platform/backend/tests/test_comparison_orchestration.py b/products/alerts_platform/backend/tests/test_comparison_orchestration.pynew file mode 100644index 000000000000..b3ee9b8e8dc5--- /dev/null+++ b/products/alerts_platform/backend/tests/test_comparison_orchestration.py@@ -0,0 +1,175 @@+from collections.abc import Mapping, Sequence+from datetime import UTC, datetime, timedelta+from uuid import uuid4++from unittest import TestCase+from unittest.mock import patch++from products.alerts_platform.backend.comparison.orchestration import run_comparison+from products.alerts_platform.backend.comparison.platform_history import ComparisonWindowTooLarge+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++SINCE = datetime(2026, 10, 1, 12, 0, tzinfo=UTC)+UNTIL = SINCE + timedelta(hours=1)+READER = "products.alerts_platform.backend.comparison.orchestration.read_platform_checks"+++def _check(state: str) -> PlatformCheck:+ return PlatformCheck(+ team_id=1,+ configuration_id=uuid4(),+ legacy_configuration_id=uuid4(),+ alert_id=uuid4(),+ grouping_key="",+ evaluation_key="window:2026-10-01T12:59:00+00:00",+ kind="check",+ previous_state="not_firing",+ state=state,+ muted_notification="none",+ error_message="",+ occurred_at=SINCE,+ )+++class _Correspondence:+ source = SourceKind.LOGS+ production_policy = LOGS_ALERT_POLICY+ platform_policy = LOGS_ALERT_POLICY+ intentional_divergences: tuple[IntentionalDivergence, ...] = ()++ def __init__(+ self,+ states: dict[CheckRef, str] | None = None,+ *,+ verdicts: dict[CheckRef, SourceVerdict] | None = None,+ ) -> None:+ self._verdicts = verdicts or {+ ref: SourceVerdict(caught_up_at=None, coverage=SourceCoverage.EVALUATED, state=state)+ for ref, state in (states or {}).items()+ }++ def verdicts_for(self, checks: Sequence[PlatformCheck]) -> Mapping[CheckRef, SourceVerdict]:+ return {check.ref: self._verdicts[check.ref] for check in checks if check.ref in self._verdicts}+++class TestRunComparison(TestCase):+ def test_a_check_the_source_left_unanswered_is_not_counted_as_agreement(self) -> None:+ # The contract obliges a correspondence to answer every ref. A source that under-answers+ # would otherwise lift the agreement rate by shrinking its own denominator.+ checks = [_check("firing"), _check("firing")]+ answered = {checks[0].ref: "firing"}++ with patch(READER, autospec=True, return_value=checks):+ run = run_comparison(correspondence=_Correspondence(answered), team_ids=[1], since=SINCE, until=UNTIL)++ assert run.checks == 2+ assert run.by_coverage[SourceCoverage.UNKNOWN] == 1+ assert run.agreement_rate == 1.0++ def test_a_team_whose_window_is_too_large_does_not_cost_the_sweep(self) -> None:+ checks = [_check("firing")]++ def read(*, team_id: int, **_: object) -> Sequence[PlatformCheck]:+ if team_id == 1:+ raise ComparisonWindowTooLarge("narrow it")+ return checks++ with patch(READER, autospec=True, side_effect=read):+ run = run_comparison(+ correspondence=_Correspondence({checks[0].ref: "firing"}),+ team_ids=[1, 2],+ since=SINCE,+ until=UNTIL,+ )++ assert set(run.teams_unread) == {1}+ assert run.teams_read == 1+ assert run.checks == 1++ def test_a_team_named_twice_is_swept_once(self) -> None:+ # A sweep built from a query missing a DISTINCT would otherwise count a team's checks+ # twice, into both halves of the rate.+ checks = [_check("firing")]++ with patch(READER, autospec=True, return_value=checks):+ run = run_comparison(+ correspondence=_Correspondence({checks[0].ref: "firing"}),+ team_ids=[1, 1],+ since=SINCE,+ until=UNTIL,+ )++ assert run.checks == 1+ assert run.teams_read == 1++ def test_a_real_divergence_records_how_long_the_source_took_to_reach_the_same_verdict(self) -> None:+ # The number a first run exists to produce: a REAL the source caught up to four minutes+ # later is two cadences out of phase, and one it never caught up to is a disagreement.+ lagging, disagreeing, misdated, drifted = (_check("firing") for _ in range(4))+ verdicts = {+ lagging.ref: SourceVerdict(+ coverage=SourceCoverage.EVALUATED,+ state="not_firing",+ caught_up_at=SINCE + timedelta(minutes=4),+ ),+ disagreeing.ref: SourceVerdict(caught_up_at=None, coverage=SourceCoverage.EVALUATED, state="not_firing"),+ # A correspondence that dated its own scan wrong, which must not read as a short lag.+ misdated.ref: SourceVerdict(+ coverage=SourceCoverage.EVALUATED,+ state="not_firing",+ caught_up_at=SINCE - timedelta(minutes=4),+ ),+ # A disabled alert the platform still checked. Its next move into the state is no lag.+ drifted.ref: SourceVerdict(+ coverage=SourceCoverage.SUPPRESSED,+ state="not_firing",+ suppressed_by=SuppressionReason.DISABLED,+ caught_up_at=SINCE + timedelta(minutes=4),+ ),+ }++ with patch(READER, autospec=True, return_value=[lagging, disagreeing, misdated, drifted]):+ run = run_comparison(+ correspondence=_Correspondence(verdicts=verdicts), team_ids=[1], since=SINCE, until=UNTIL+ )++ assert run.by_divergence == {"real": 4}+ assert run.real_caught_up_within == {"5m": 1, "never": 2, "source_suppressed": 1}++ def test_a_check_too_recent_to_have_settled_is_pending_rather_than_a_disagreement(self) -> None:+ # Booking these as disagreement inflates the one bucket worth acting on.+ recent = _check("firing")+ verdicts = {recent.ref: SourceVerdict(caught_up_at=None, coverage=SourceCoverage.EVALUATED, state="not_firing")}++ with patch(READER, autospec=True, return_value=[recent]):+ run = run_comparison(+ correspondence=_Correspondence(verdicts=verdicts),+ team_ids=[1],+ since=SINCE - timedelta(hours=1),+ until=SINCE + timedelta(minutes=1),+ settle_for=timedelta(minutes=15),+ )++ assert run.real_caught_up_within == {"pending": 1}++ def test_the_rate_measures_agreement_rather_than_how_much_the_source_could_answer(self) -> None:+ # Counting UNCOMPARABLE against agreement would make the headline number track backfill+ # completeness instead, which is the trap this run reports `by_coverage` separately to avoid.+ checks = [_check("firing"), _check("firing"), _check("not_firing")]+ answered = {checks[0].ref: "firing", checks[2].ref: "firing"}++ with patch(READER, autospec=True, return_value=checks):+ run = run_comparison(correspondence=_Correspondence(answered), team_ids=[1], since=SINCE, until=UNTIL)++ assert run.agreement_rate == 0.5+ assert run.by_coverage[SourceCoverage.UNKNOWN] == 1+ assert len(run.divergences) == 1diff --git a/products/alerts_platform/backend/tests/test_comparison_platform_history.py b/products/alerts_platform/backend/tests/test_comparison_platform_history.pyindex 1311dee2d100..2d3a606a39fe 100644--- a/products/alerts_platform/backend/tests/test_comparison_platform_history.py+++ b/products/alerts_platform/backend/tests/test_comparison_platform_history.py@@ -7,7 +7,11 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom posthog.clickhouse.client import sync_executefrom posthog.models.scoping import team_scope-from products.alerts_platform.backend.comparison.platform_history import UnregisteredSource, read_platform_checks+from products.alerts_platform.backend.comparison.platform_history import (+ UnregisteredSource,+ read_platform_checks,+ teams_with_configurations,+)from products.alerts_platform.backend.facade.contracts import SourceKindfrom products.alerts_platform.backend.logic.platform_alert_events import PlatformAlertEventRow, insert_eventsfrom products.alerts_platform.backend.models import PlatformAlertConfiguration@@ -118,6 +122,13 @@ class TestReadPlatformChecks(ClickhouseTestMixin, APIBaseTest):with pytest.raises(UnregisteredSource):read_platform_checks(team_id=self.team.id, source=SourceKind.INSIGHT, since=since, until=until)+ def test_only_teams_holding_a_configuration_for_the_source_are_worth_sweeping(self) -> None:+ # A sweep over every team pays a Postgres round trip each to learn most have nothing.+ self._configuration(legacy_configuration_id=uuid4())+ self._configuration(source_kind="insight", legacy_configuration_id=uuid4())++ assert teams_with_configurations(SourceKind.LOGS) == [self.team.id]+def test_another_source_is_not_in_a_logs_comparison(self) -> None:self._record(self._configuration(source_kind="insight", legacy_configuration_id=uuid4()),diff --git a/products/logs/backend/alert_comparison.py b/products/logs/backend/alert_comparison.pyindex 2b37b965f2d1..384ac07cd884 100644--- a/products/logs/backend/alert_comparison.py+++ b/products/logs/backend/alert_comparison.py@@ -54,7 +54,7 @@ MAX_EVENTS_PER_WINDOW = 5000MAX_EVENTS_PER_BATCH = 100_000_TOGGLE_KINDS = frozenset({LogsAlertEvent.Kind.ENABLE, LogsAlertEvent.Kind.DISABLE})-_CHAIN_FIELDS = ("id", "alert_id", "kind", "created_at", "state_before")+_CHAIN_FIELDS = ("id", "alert_id", "kind", "created_at", "state_before", "state_after")def _mute_gates_notification_only(check: PlatformCheck, verdict: SourceVerdict) -> bool:@@ -139,9 +139,9 @@ class LogsCorrespondence(SourceCorrespondence):) -> 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.+ Bounded by the window being compared rather than by wall-clock time, plus the few later+ transitions a check at the end of the window is dated by. 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 atruncated chain as a complete one.@@ -174,25 +174,29 @@ class LogsCorrespondence(SourceCorrespondence):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):+ for row in self._first_of_each_kind_and_state_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)+ for chain in complete.values():+ # Only the rows past the window arrive out of order, and they all follow the window's rows.+ chain.sort(key=lambda row: row.created_at)return complete- def _first_after(- self, alert_ids: list[UUID], team_ids: set[int], moment: datetime, *, kinds: frozenset | None = None+ def _first_of_each_kind_and_state_after(+ self, alert_ids: list[UUID], team_ids: set[int], moment: datetime) -> 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")+ """Each alert's earliest transition after `moment` of every kind and resulting state.++ A check is dated by the next transition of any kind, `enabled` by the next toggle, and+ `caught_up_at` by the next move into the check's state. Each of those is the earliest row+ of some (kind, state) pair, so one read answers all three. The pairs are few: a handful of+ kinds times a handful of states.+ """+ return (+ self._events(alert_ids, team_ids)+ .filter(created_at__gt=moment)+ .order_by("alert_id", "kind", "state_after", "created_at")+ .distinct("alert_id", "kind", "state_after")+ )def _events(self, alert_ids: list[UUID], team_ids: set[int]) -> QuerySet[LogsAlertEvent]:return LogsAlertEvent.objects.filter(@@ -203,7 +207,7 @@ class LogsCorrespondence(SourceCorrespondence):def _unknown(detail: str) -> SourceVerdict:- return SourceVerdict(coverage=SourceCoverage.UNKNOWN, state=None, detail=detail)+ return SourceVerdict(caught_up_at=None, coverage=SourceCoverage.UNKNOWN, state=None, detail=detail)def _verdict_at(@@ -225,6 +229,8 @@ def _verdict_at(# rather than the check. None means the state still holds.observed_at = boundary.created_at if boundary is not None else Noneevidence_id = str(boundary.id) if boundary is not None else None+ # The first transition *into* the state this check decided, not merely the next one.+ caught_up = next((event for event in after if event.state_after == check.state), None)def verdict(coverage: SourceCoverage, *, suppressed_by: SuppressionReason | None = None) -> SourceVerdict:return SourceVerdict(@@ -232,6 +238,7 @@ def _verdict_at(state=state,suppressed_by=suppressed_by,observed_at=observed_at,+ caught_up_at=caught_up.created_at if caught_up is not None else None,evidence_id=evidence_id,)diff --git a/products/logs/backend/test/test_alert_comparison.py b/products/logs/backend/test/test_alert_comparison.pyindex 4461f5998793..f65d450c9a67 100644--- a/products/logs/backend/test/test_alert_comparison.py+++ b/products/logs/backend/test/test_alert_comparison.py@@ -83,20 +83,23 @@ class TestLogsDivergenceDeclarations(TestCase):"the source made no check because it was muted",_platform_check(),SourceVerdict(- coverage=SourceCoverage.SUPPRESSED, state="snoozed", suppressed_by=SuppressionReason.MUTED+ caught_up_at=None,+ 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"),+ SourceVerdict(caught_up_at=None, 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"),+ SourceVerdict(caught_up_at=None, coverage=SourceCoverage.EVALUATED, state="not_firing"),False,),]@@ -285,6 +288,39 @@ class TestLogsCorrespondence(BaseTest):assert verdict.coverage is SourceCoverage.EVALUATEDassert verdict.suppressed_by is None+ @parameterized.expand(+ [+ # A later check bounds the read past both transitions.+ ("both transitions inside the window", True),+ # The read reaches past the window only for the rows it asks for by name.+ ("both transitions after the last check", False),+ ]+ )+ def test_catching_up_is_the_first_move_into_the_state_not_merely_the_next_move(+ self, _name: str, later_check: bool+ ) -> None:+ # Reading only the next transition would book this lag as a genuine disagreement.+ alert = self._alert(state=LogsAlertConfiguration.State.FIRING)+ early = CHECKED_AT - timedelta(minutes=10)+ self._event(+ alert,+ at=early + timedelta(minutes=2),+ state_before=LogsAlertConfiguration.State.NOT_FIRING,+ state_after=LogsAlertConfiguration.State.ERRORED,+ )+ self._event(+ alert,+ at=early + timedelta(minutes=6),+ state_before=LogsAlertConfiguration.State.ERRORED,+ state_after=LogsAlertConfiguration.State.FIRING,+ )+ checks = [self._check(alert, at=early), *([self._check(alert)] if later_check else [])]++ verdicts = LogsCorrespondence().verdicts_for(checks)++ assert verdicts[checks[0].ref].state == LogsAlertConfiguration.State.NOT_FIRING+ assert verdicts[checks[0].ref].caught_up_at == early + timedelta(minutes=6)+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)