: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): fire platform insight alerts per breakdown value (#114284)
Jimmy Zhu22913c44e8f4
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.mdindex c68c1d2d5a07..c6ecac0b3b08 100644--- a/docs/internal/alerts-platform-temporal.md+++ b/docs/internal/alerts-platform-temporal.md@@ -299,7 +299,7 @@ The check input and the read API show each instance the later of the two.A configuration's `grouping` holds `max_instances` (100 by default), the most instance rows it keeps.A source calls `check.admit(keys)` with its groups in priority order: a group that already has an instance is always admitted, so it can resolve, and new groups fill the remaining room front first.-The count it turned away travels on the delivery as `overflowed`, and the last message of that delivery says how many groups were not tracked.+The count it turned away travels on the delivery as `overflowed`, and the first message of that delivery says how many groups were not tracked.`record_outcomes` enforces the cap again and drops a group past it, counted on `alerts_platform_groups_over_cap_total`.An instance that is not firing, not muted, and that no check returned for longer than both 24 hours and its cooldown is deleted, which frees its slot.Nothing is reaped while the configuration's checks fail, because a failed check returns no groups and every instance would look gone.@@ -308,6 +308,10 @@ Logs is the first source that groups, by `service_name` and `severity_text` onlyA grouped logs alert leaves the batched cohort and runs `GroupedAlertCheckQuery`, one query per alert, with its open groups ordered first and the rest worst first.A group with no instance whose check decides nothing is left out, so a quiet service costs no row, and an open group the query does not return is checked against a zero count so it can resolve.+Insight groups by breakdown value, with `keys` set to `["breakdown"]`.+`check_alert_per_series` judges every series on its own, where production's `check_alert_for_insight` stops at the first series that breaches, and the adapter runs each value through the shared machine against its own instance.+Only threshold alerts can group; a detector scores its series together.+`alerts_platform_checks_skipped_total{source,reason}` counts these by reason.### What a check leaves behinddiff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.pyindex 0c8926a646e6..de775caebd4f 100644--- a/products/alerts/backend/evaluation/dispatcher.py+++ b/products/alerts/backend/evaluation/dispatcher.py@@ -1,8 +1,14 @@+from collections.abc import Iterator+from contextlib import contextmanager+from dataclasses import replace+from typing import Any+from rest_framework.exceptions import ValidationError as DRFValidationErrorfrom posthog.schema import AlertCondition, InsightThreshold, IntervalType, NodeKindfrom posthog.api.services.query import ExecutionMode+from posthog.dataclasses import frozenfrom posthog.hogql_queries.validation.validate_query import rule_violation_messagefrom posthog.schema_migrations.upgrade_manager import upgrade_insightfrom posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult@@ -11,6 +17,7 @@ from posthog.utils import get_from_dict_or_attrfrom products.alerts.backend.evaluation.comparator import evaluate_thresholdfrom products.alerts.backend.evaluation.contract import (AlertExtractionError,+ ComparableSeries,DetectorExtractor,ExtractionResult,Extractor,@@ -108,13 +115,18 @@ def check_detector_alert()-def _check_alert_for_insight(alert: AlertConfiguration, *, evaluation_id: str | None = None) -> AlertEvaluationResult:- """Dispatch an alert to its insight-kind extractor, then run the shared comparator.+@frozen+class _ResolvedQuery:+ insight: Insight+ query: Any+ kind: Any- If ``detector_config`` is set, routes through the anomaly-detector registry (one extractor per- supported insight kind); each detector extractor shares the ``ComparableSeries`` contract, so the- dispatch shape mirrors the threshold path. Otherwise the extractor normalizes the query result into an- ``ExtractionResult`` and the comparator evaluates it against the threshold.++@contextmanager+def _resolved_query(alert: AlertConfiguration) -> Iterator[_ResolvedQuery]:+ """The alert's insight query, upgraded, unwrapped and checked against its evaluation delay.++ A context manager, because the upgrade holds only while the query runs."""insight = alert.insightif insight.query is None:@@ -132,22 +144,100 @@ def _check_alert_for_insight(alert: AlertConfiguration, *, evaluation_id: str |validate_evaluation_delay(query, alert.config, alert.evaluation_delay_intervals)except ValueError as err:raise AlertExtractionError(str(err)) from err+ yield _ResolvedQuery(insight=insight, query=query, kind=kind)- if alert.detector_config:- return check_detector_alert(alert, insight, query, evaluation_id=evaluation_id)- extractor = EXTRACTORS.get(kind)- if extractor is None:- raise NotImplementedError(f"AlertCheckError: Alerts for {kind} are not supported yet")+def _check_alert_for_insight(alert: AlertConfiguration, *, evaluation_id: str | None = None) -> AlertEvaluationResult:+ """Dispatch an alert to its insight-kind extractor, then run the shared comparator.++ If ``detector_config`` is set, routes through the anomaly-detector registry (one extractor per+ supported insight kind); each detector extractor shares the ``ComparableSeries`` contract, so the+ dispatch shape mirrors the threshold path. Otherwise the extractor normalizes the query result into an+ ``ExtractionResult`` and the comparator evaluates it against the threshold.+ """+ with _resolved_query(alert) as resolved:+ if alert.detector_config:+ return check_detector_alert(alert, resolved.insight, resolved.query, evaluation_id=evaluation_id)- # Short-circuit before the (potentially expensive) query: no bounds means nothing to breach.- threshold = InsightThreshold.model_validate(alert.threshold.configuration) if alert.threshold else None- if not threshold or not threshold.bounds:+ extracted = _extract_for_threshold(alert, resolved.insight, resolved.query, resolved.kind)+ if extracted is None:return AlertEvaluationResult(value=0, breaches=[])+ return describe_delayed_evaluation(+ evaluate_threshold(extracted.result, extracted.condition, extracted.threshold), extracted.result+ )- condition = AlertCondition.model_validate(alert.condition)- result = run_extractor(extractor, alert, insight, query, _resolve_execution_mode(alert, kind, query))- return describe_delayed_evaluation(evaluate_threshold(result, condition, threshold), result)++@frozen+class _ThresholdExtraction:+ result: ExtractionResult+ condition: AlertCondition+ threshold: InsightThreshold+++def _extract_for_threshold(+ alert: AlertConfiguration, insight: Insight, query: object, kind: NodeKind+) -> _ThresholdExtraction | None:+ """Run a threshold alert's query. None when the alert has no bounds, so there is nothing to breach."""+ extractor = EXTRACTORS.get(kind)+ if extractor is None:+ raise NotImplementedError(f"AlertCheckError: Alerts for {kind} are not supported yet")++ # Short-circuit before the (potentially expensive) query: no bounds means nothing to breach.+ threshold = InsightThreshold.model_validate(alert.threshold.configuration) if alert.threshold else None+ if not threshold or not threshold.bounds:+ return None++ condition = AlertCondition.model_validate(alert.condition)+ result = run_extractor(extractor, alert, insight, query, _resolve_execution_mode(alert, kind, query))+ return _ThresholdExtraction(result=result, condition=condition, threshold=threshold)+++def _one_series(result: ExtractionResult, series: ComparableSeries) -> ExtractionResult:+ """One series as its own result. Not a breakdown any more, so a series that does not breach+ still reports its value, and the label stays in a breach message."""+ return replace(+ result,+ series=[series],+ is_breakdown=False,+ include_series_label=result.is_breakdown or result.include_series_label,+ )+++@frozen+class SeriesEvaluation:+ label: str+ result: AlertEvaluationResult+++def check_alert_per_series(+ alert: AlertConfiguration,+) -> tuple[SeriesEvaluation, ...] | AlertEvaluationResult:+ """Each series' own verdict for a threshold alert, rather than one verdict for the insight.++ `check_alert_for_insight` stops at the first series that breaches, because one alert holds one+ state. A caller that keeps state per breakdown value needs every series judged on its own.+ Returns the skipped result instead when the evaluation delay leaves no complete interval.+ Detector alerts are not supported, because a detector scores the series together.+ """+ if alert.detector_config:+ raise AlertExtractionError("Per-series evaluation supports threshold alerts only")+ try:+ with _resolved_query(alert) as resolved:+ extracted = _extract_for_threshold(alert, resolved.insight, resolved.query, resolved.kind)+ except DelayedEvaluationUnavailable as err:+ return AlertEvaluationResult(value=None, breaches=[], skipped_reason=str(err))+ if extracted is None:+ return ()+ return tuple(+ SeriesEvaluation(+ label=series.label,+ result=describe_delayed_evaluation(+ evaluate_threshold(_one_series(extracted.result, series), extracted.condition, extracted.threshold),+ extracted.result,+ ),+ )+ for series in extracted.result.series+ )def check_alert_for_insight(alert: AlertConfiguration, *, evaluation_id: str | None = None) -> AlertEvaluationResult:diff --git a/products/alerts/backend/evaluation/test/test_dispatcher.py b/products/alerts/backend/evaluation/test/test_dispatcher.pyindex 7137c039f7ff..498217517cb2 100644--- a/products/alerts/backend/evaluation/test/test_dispatcher.py+++ b/products/alerts/backend/evaluation/test/test_dispatcher.py@@ -1,17 +1,25 @@+from contextlib import nullcontextfrom datetime import UTC, datetime, timedeltafrom typing import Anyimport pytest-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patchfrom rest_framework.exceptions import ValidationError as DRFValidationError+from posthog.schema import NodeKind+from posthog.api.services.query import ExecutionModefrom posthog.hogql_queries.query_failure_handling import build_failure_exceptionfrom posthog.query_cache.failures import QueryFailureRecord-from products.alerts.backend.evaluation.contract import AlertExtractionError, ExtractionResult-from products.alerts.backend.evaluation.dispatcher import run_extractor+from products.alerts.backend.evaluation.contract import (+ AlertExtractionError,+ ComparableSeries,+ ExtractionResult,+ SeriesPoint,+)+from products.alerts.backend.evaluation.dispatcher import EXTRACTORS, check_alert_per_series, run_extractorIF_STALE = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE@@ -64,3 +72,31 @@ def test_a_breaker_replay_keeps_the_ordinary_failure_path() -> None:def test_a_successful_extraction_passes_through() -> None:result = ExtractionResult(series=[])assert _run(result) is result+++def test_per_series_judges_every_breakdown_value_where_the_alert_stops_at_the_first() -> None:+ series = [+ ComparableSeries(label=label, points=[SeriesPoint(date="2026-09-16", value=value)], current_index=0)+ for label, value in (("Chrome", 150.0), ("Safari", 40.0), ("Firefox", 120.0))+ ]+ alert = MagicMock(+ detector_config=None,+ threshold=MagicMock(configuration={"type": "absolute", "bounds": {"upper": 100}}),+ condition={"type": "absolute_value"},+ )+ alert.insight.query = {"kind": "TrendsQuery"}+ extractor = _Extractor(ExtractionResult(series=series, is_breakdown=True))+ with (+ patch.dict(EXTRACTORS, {NodeKind.TRENDS_QUERY: extractor}),+ patch("products.alerts.backend.evaluation.dispatcher.upgrade_insight", return_value=nullcontext()),+ patch("products.alerts.backend.evaluation.dispatcher.validate_evaluation_delay"),+ patch("products.alerts.backend.evaluation.dispatcher._resolve_execution_mode", return_value=IF_STALE),+ ):+ evaluated = check_alert_per_series(alert)++ assert isinstance(evaluated, tuple)+ assert [(s.label, s.result.value, bool(s.result.breaches)) for s in evaluated] == [+ ("Chrome", 150.0, True),+ ("Safari", 40.0, False),+ ("Firefox", 120.0, True),+ ]diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.pyindex 8531df765a1a..724aea1f435c 100644--- a/products/alerts/backend/platform_source_cycle.py+++ b/products/alerts/backend/platform_source_cycle.py@@ -35,6 +35,7 @@ from posthog.temporal.alerts.admission import admit_evaluation_slots, release_evfrom products.alerts.backend.evaluation import check_alert_for_insightfrom products.alerts.backend.evaluation.contract import AlertExtractionError+from products.alerts.backend.evaluation.dispatcher import check_alert_per_seriesfrom products.alerts.backend.insight_alert_state_machine import INSIGHT_ALERT_POLICY, insight_snapshotfrom products.alerts.backend.logic.alert_email import INSIGHT_ALERT_ERRORED_EVENT_IDfrom products.alerts.backend.models.alert import AlertConfiguration@@ -42,14 +43,20 @@ from products.alerts_platform.backend.facade.api import due_check_ids, due_checkfrom products.alerts_platform.backend.facade.contracts import (AlertDeliveryRequest,AlertEventKind,- CheckFailure,- GroupOutcome,+ GroupingMode,+ InstanceCheckState,PlatformAlertCheckInput,PlatformAlertOutcome,SkipReason,SourceBatchEvaluation,SourceKind,)+from products.alerts_platform.backend.facade.grouping import (+ GroupObservation,+ bounded_grouping_key,+ decide_groups,+ is_hashed_grouping_key,+)from products.alerts_platform.backend.facade.lifecycle import (NOTIFICATION_EVENT_KINDS,AlertSnapshot,@@ -213,6 +220,7 @@ def _delivery(check: PlatformAlertCheckInput, outcome: PlatformAlertOutcome) ->evaluation_key=outcome.evaluation_key,destination_alert_id=legacy_id,event_ids_by_kind=_EVENT_IDS_BY_KIND,+ overflowed=outcome.overflowed,)@@ -226,8 +234,8 @@ def _legacy_alert(check: PlatformAlertCheckInput) -> AlertConfiguration | None:)-def _snapshot(check: PlatformAlertCheckInput) -> AlertSnapshot:- instance = check.instance()+def _snapshot(check: PlatformAlertCheckInput, instance: InstanceCheckState | None = None) -> AlertSnapshot:+ instance = instance or check.instance()return insight_snapshot(AlertState(instance.state),last_notified_at=instance.last_notified_at,@@ -288,38 +296,15 @@ def _decide(check: PlatformAlertCheckInput, now: datetime, *, evaluation_id: stralert_calculation_interval=alert.calculation_interval,alert_config_type=(alert.config or {}).get("type"),)+ if check.grouping.mode != GroupingMode.SINGLE:+ return _decide_grouped(check, snapshot, alert, now=now)started_at = time.monotonic()try:result = check_alert_for_insight(alert, evaluation_id=evaluation_id)except AlertExtractionError as error:- return _recorded(- check,- snapshot,- ControlPlaneOutcome(new_state=AlertState.ERRORED, consecutive_failures=0),- now=now,- notification=NotificationAction.ERROR,- notified=True,- error_message=str(error),- skip=SkipReason.BROKEN_CONFIG,- disable=True,- failed=True,- )+ return _broken(check, snapshot, now=now, message=str(error))except Exception as error:- if classify_query_error(error) == QueryErrorCategory.RATE_LIMITED:- return _skipped(check, snapshot, now=now, skip=SkipReason.CAPACITY, error_message=CAPACITY_REJECTED)- if not isinstance(error, CH_TRANSIENT_ERRORS):- logger.exception("Platform insight check failed", check_id=str(check.id), error=str(error))- return _verdict(- check,- snapshot,- CheckInput(- threshold_breached=False,- error_message=str(error),- is_transient_error=isinstance(error, CH_TRANSIENT_ERRORS),- ),- now=now,- skip=SkipReason.QUERY_FAILED,- )+ return _query_failed(check, snapshot, error, now=now)duration_ms = int((time.monotonic() - started_at) * 1000)if result.skipped_reason is not None:@@ -334,6 +319,98 @@ def _decide(check: PlatformAlertCheckInput, now: datetime, *, evaluation_id: str)+def _broken(+ check: PlatformAlertCheckInput, snapshot: AlertSnapshot, *, now: datetime, message: str+) -> PlatformAlertOutcome:+ """An alert production cannot evaluate as configured. It errors and is disabled, as production does."""+ return _recorded(+ check,+ snapshot,+ ControlPlaneOutcome(new_state=AlertState.ERRORED, consecutive_failures=0),+ now=now,+ notification=NotificationAction.ERROR,+ notified=True,+ error_message=message,+ skip=SkipReason.BROKEN_CONFIG,+ disable=True,+ )+++def _query_failed(+ check: PlatformAlertCheckInput, snapshot: AlertSnapshot, error: Exception, *, now: datetime+) -> PlatformAlertOutcome:+ """A query that did not finish. A refusal for load is a skip; anything else is a failed check."""+ if classify_query_error(error) == QueryErrorCategory.RATE_LIMITED:+ return _skipped(check, snapshot, now=now, skip=SkipReason.CAPACITY, error_message=CAPACITY_REJECTED)+ if not isinstance(error, CH_TRANSIENT_ERRORS):+ logger.exception("Platform insight check failed", check_id=str(check.id), error=str(error))+ return _verdict(+ check,+ snapshot,+ CheckInput(+ threshold_breached=False,+ error_message=str(error),+ is_transient_error=isinstance(error, CH_TRANSIENT_ERRORS),+ ),+ now=now,+ skip=SkipReason.QUERY_FAILED,+ )+++# Skips that mean the check could not evaluate, as opposed to a check the source chose not to run.+_FAILED_CHECKS: Final = frozenset({SkipReason.QUERY_FAILED, SkipReason.BROKEN_CONFIG})++# The one label a grouped insight alert splits on: each breakdown value is a group.+BREAKDOWN_GROUPING_KEY = "breakdown"+++def _decide_grouped(+ check: PlatformAlertCheckInput, snapshot: AlertSnapshot, alert: AlertConfiguration, *, now: datetime+) -> PlatformAlertOutcome:+ """One check of a breakdown alert, judged per breakdown value through the platform's decision.++ An open value the query no longer returns is judged as not breaching, so it can resolve.+ """+ if tuple(check.grouping.keys) != (BREAKDOWN_GROUPING_KEY,):+ return _broken(check, snapshot, now=now, message=f"An insight alert can only group by {BREAKDOWN_GROUPING_KEY}")+ started_at = time.monotonic()+ try:+ evaluated = check_alert_per_series(alert)+ except AlertExtractionError as error:+ return _broken(check, snapshot, now=now, message=str(error))+ except Exception as error:+ return _query_failed(check, snapshot, error, now=now)+ if not isinstance(evaluated, tuple):+ return _skipped(check, snapshot, now=now)+ duration_ms = int((time.monotonic() - started_at) * 1000)++ decision = decide_groups(+ check,+ [+ GroupObservation(+ grouping_key=bounded_grouping_key(series.label),+ current_breached=bool(series.result.breaches),+ value=series.result.value,+ labels={BREAKDOWN_GROUPING_KEY: series.label},+ )+ for series in evaluated+ ],+ snapshot_of=lambda instance, _prior: _snapshot(check, instance),+ policy=INSIGHT_ALERT_POLICY,+ now=now,+ absent=lambda key: GroupObservation(+ grouping_key=key,+ current_breached=False,+ labels={} if is_hashed_grouping_key(key) else {BREAKDOWN_GROUPING_KEY: key},+ ),+ )+ for verdict in decision.verdicts:+ _record_metrics(verdict.outcome.notification, verdict.snapshot.state.value, verdict.group.new_state)+ return decision.as_outcome(+ configuration_id=check.id, evaluation_key=_evaluation_key(check, now), query_duration_ms=duration_ms+ )++def _verdict(check: PlatformAlertCheckInput,snapshot: AlertSnapshot,@@ -357,7 +434,6 @@ def _verdict(query_duration_ms=query_duration_ms,skip=skip,disable=outcome.disable,- failed=skip == SkipReason.QUERY_FAILED,)@@ -375,6 +451,17 @@ def _skipped(return _recorded(check, snapshot, unchanged, now=now, skip=skip, error_message=error_message, disable=disable)+def _record_metrics(+ notification: NotificationAction, previous_state: str, new_state: str, *, skip: SkipReason | None = None+) -> None:+ source = SourceKind.INSIGHT.value+ safe_record(increment_checks, source, notification.value)+ if skip is not None:+ safe_record(increment_checks_skipped, source, skip.value)+ if previous_state != new_state:+ safe_record(increment_state_transition, source, previous_state, new_state)++def _recorded(check: PlatformAlertCheckInput,snapshot: AlertSnapshot,@@ -388,41 +475,34 @@ def _recorded(query_duration_ms: int | None = None,skip: SkipReason | None = None,disable: bool = False,- failed: bool = False,) -> PlatformAlertOutcome:"""The one place an outcome is built. Every path goes through the firing decision, becausean outcome without an episode clears the start of a firing the alert is still in."""- source = SourceKind.INSIGHT.value- safe_record(increment_checks, source, notification.value)- if skip is not None:- safe_record(increment_checks_skipped, source, skip.value)- previous_state = check.instance().state- if previous_state != outcome.new_state.value:- safe_record(increment_state_transition, source, previous_state, outcome.new_state.value)- kind = NOTIFICATION_EVENT_KINDS[notification]- firing_episode = decide_firing_episode(snapshot, outcome, now, policy=INSIGHT_ALERT_POLICY)- return PlatformAlertOutcome(+ _record_metrics(notification, check.instance().state, outcome.new_state.value, skip=skip)+ failed = skip in _FAILED_CHECKS+ skipped = skip is not None and not failed+ if check.grouping.mode != GroupingMode.SINGLE and not failed:+ # A grouped check that ran reports through `_decide_grouped`; this one evaluated no group.+ return PlatformAlertOutcome(+ configuration_id=check.id,+ evaluation_key=_evaluation_key(check, now),+ consecutive_failures=outcome.consecutive_failures,+ error_message=error_message,+ disable=disable,+ skipped=skipped,+ )+ return PlatformAlertOutcome.ungrouped(configuration_id=check.id,evaluation_key=_evaluation_key(check, now),consecutive_failures=outcome.consecutive_failures,- groups=()- if failed- else (- GroupOutcome(- grouping_key="",- kind=kind,- new_state=outcome.new_state.value,- notified=notified,- firing_episode=firing_episode,- value=value,- ),- ),- failure=CheckFailure(- kind=kind, new_state=outcome.new_state.value, notified=notified, firing_episode=firing_episode- )- if failed- else None,+ kind=NOTIFICATION_EVENT_KINDS[notification],+ new_state=outcome.new_state.value,+ notified=notified,+ failed=failed,+ firing_episode=decide_firing_episode(snapshot, outcome, now, policy=INSIGHT_ALERT_POLICY),+ value=value,error_message=error_message,query_duration_ms=query_duration_ms,disable=disable,+ skipped=skipped,)diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.pyindex c7a3d7a24c35..ef59b4f1b3b2 100644--- a/products/alerts/backend/test/test_platform_source_cycle.py+++ b/products/alerts/backend/test/test_platform_source_cycle.py@@ -18,6 +18,7 @@ from posthog.schema_enums import AlertCalculationIntervalfrom posthog.tasks.alerts.utils import AlertEvaluationResultfrom products.alerts.backend.evaluation.contract import AlertExtractionError+from products.alerts.backend.evaluation.dispatcher import SeriesEvaluationfrom products.alerts.backend.logic.alert_email import INSIGHT_ALERT_ERRORED_EVENT_IDfrom products.alerts.backend.models.alert import AlertCheck, AlertConfigurationfrom products.alerts.backend.platform_source_cycle import (@@ -36,6 +37,8 @@ from products.alerts_platform.backend.facade.api import record_outcomes, slot_offrom products.alerts_platform.backend.facade.contracts import (AlertBatchKey,AlertEventKind,+ Grouping,+ GroupingMode,PlatformAlertOutcome,PlatformConfigurationSnapshot,SourceEvaluationInputs,@@ -56,7 +59,7 @@ class TestPlatformInsightEvaluation(APIBaseTest):def _alert(self, **overrides: Any) -> AlertConfiguration:return create_insight_alert(self.team, **{"next_check_at": CUTOFF - timedelta(minutes=1), **overrides})- def _copy(self, alert: AlertConfiguration | None) -> PlatformConfigurationSnapshot:+ def _copy(self, alert: AlertConfiguration | None, **overrides: Any) -> PlatformConfigurationSnapshot:with team_scope(self.team.id):return platform_testing.create_configuration(team_id=self.team.id,@@ -67,8 +70,49 @@ class TestPlatformInsightEvaluation(APIBaseTest):recurrence_unit="day",next_check_at=CUTOFF - timedelta(minutes=1),legacy_configuration_id=alert.id if alert else None,+ **overrides,)+ def _evaluate_per_series(+ self, configuration: PlatformConfigurationSnapshot, values: dict[str, float]+ ) -> PlatformAlertOutcome:+ slot = slot_of(configuration.next_check_at, CUTOFF)+ expires_at = time.time() + 3600+ assert plan_insight_batch(self.team.id, slot, CUTOFF, expires_at=expires_at) == (str(configuration.id),)+ evaluated = tuple(+ SeriesEvaluation(+ label=label, result=AlertEvaluationResult(value=value, breaches=["above 100"] if value > 100 else [])+ )+ for label, value in values.items()+ )+ with patch(f"{_MODULE}.check_alert_per_series", return_value=evaluated):+ evaluation = evaluate_insight_check(+ self.team.id, slot, CUTOFF, str(configuration.id), held_until=expires_at, evaluation_id="test"+ )+ assert evaluation is not None+ (outcome,) = evaluation.outcomes+ return outcome++ def test_each_breakdown_value_fires_and_resolves_on_its_own(self) -> None:+ grouping = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("breakdown",))+ configuration = self._copy(self._alert(), grouping=grouping.to_stored())++ fired = self._evaluate_per_series(configuration, {"Chrome": 150.0, "Safari": 40.0, "Firefox": 120.0})+ record_outcomes(self.team.id, (fired,), CUTOFF)+ assert {group.grouping_key: group.kind for group in fired.groups} == {+ "Chrome": AlertEventKind.FIRING,+ "Firefox": AlertEventKind.FIRING,+ }++ with team_scope(self.team.id):+ platform_testing.set_due_at(configuration.id, CUTOFF - timedelta(minutes=1))+ resolved = self._evaluate_per_series(configuration, {"Chrome": 150.0})++ assert {group.grouping_key: group.new_state for group in resolved.groups} == {+ "Chrome": "firing",+ "Firefox": "not_firing",+ }+def _evaluate(self, configuration: PlatformConfigurationSnapshot, *, result: Any = None) -> tuple[PlatformAlertOutcome | None, MagicMock]:diff --git a/products/alerts_platform/backend/comparison/platform_history.py b/products/alerts_platform/backend/comparison/platform_history.pyindex b184be4d3ccf..b4f48c89a852 100644--- a/products/alerts_platform/backend/comparison/platform_history.py+++ b/products/alerts_platform/backend/comparison/platform_history.py@@ -19,7 +19,7 @@ from uuid import UUIDfrom posthog.clickhouse.client import query_with_columnsfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries-from products.alerts_platform.backend.facade.contracts import PlatformCheck, SourceKind+from products.alerts_platform.backend.facade.contracts import GroupingMode, PlatformCheck, SourceKindfrom products.alerts_platform.backend.models import PlatformAlertConfigurationfrom products.alerts_platform.backend.models.platform_alert_events_sql import PLATFORM_ALERT_EVENTS_TABLE@@ -95,9 +95,11 @@ def read_platform_checks("""_refuse_unregistered(source)+ # A grouped configuration writes a row per group, and the source's own stack has one verdict per+ # check, so the two cannot be compared check for check.legacy_ids: dict[UUID, UUID | None] = dict(PlatformAlertConfiguration.objects.for_team(team_id)- .filter(source_kind=source.value)+ .filter(source_kind=source.value, grouping__mode=GroupingMode.SINGLE.value).values_list("id", "legacy_configuration_id"))if not legacy_ids:diff --git a/products/alerts_platform/backend/delivery/dispatch.py b/products/alerts_platform/backend/delivery/dispatch.pyindex 5fb51c7ab071..00e28d55060a 100644--- a/products/alerts_platform/backend/delivery/dispatch.py+++ b/products/alerts_platform/backend/delivery/dispatch.py@@ -42,15 +42,9 @@ def deliver(busy = 0for transition in announcement.transitions:- is_last = transition is announcement.transitions[-1]- message = build_message(- announcement,- transition,- team_id=team_id,- incident_action=incident_action,- source_alert_url=source_alert_url,- overflowed=announcement.overflowed if is_last else 0,- )+ # On the first transition, because a retry skips a message already delivered and waits out+ # a held one, so the overflow notice is sent once, and with the message that opens the batch.+ overflowed = announcement.overflowed if transition is announcement.transitions[0] else 0key = _thread_key(configuration_id=configuration_id,provider=transport.provider,@@ -63,7 +57,14 @@ def deliver(team_id=team_id,configuration_id=configuration_id,target=target,- message=message,+ message=build_message(+ announcement,+ transition,+ team_id=team_id,+ incident_action=incident_action,+ source_alert_url=source_alert_url,+ overflowed=overflowed,+ ),in_reply_to=None,)continue@@ -85,7 +86,14 @@ def deliver(team_id=team_id,configuration_id=configuration_id,target=target,- message=message,+ message=build_message(+ announcement,+ transition,+ team_id=team_id,+ incident_action=incident_action,+ source_alert_url=source_alert_url,+ overflowed=overflowed,+ ),in_reply_to=claim.handle,)except Exception:diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.pyindex 72db2ee5c913..9525f086b192 100644--- a/products/alerts_platform/backend/delivery/evaluation.py+++ b/products/alerts_platform/backend/delivery/evaluation.py@@ -4,6 +4,7 @@ The layer that knows a transport exists. `dispatch.deliver` handles one destinatis what decides which destinations there are and which transport each one takes."""+import jsonfrom collections.abc import Callablefrom dataclasses import replacefrom typing import Any, Final@@ -186,8 +187,16 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:event_id: IncidentAction(action) for action, event_id in request.event_ids_by_incident_action.items()}webhook_transports = _WebhookTransports(team, request, announced)+ message_event_ids = set(request.event_ids_by_kind.values())+ # Destinations already told about the overflow, so each hears it once, on its first message.+ noticed: set[str] = set()for event_id, transitions in _by_subscription(request, announced).items():for target in _destinations(request, event_id):+ overflowed = 0+ destination = json.dumps(target, sort_keys=True)+ if request.overflowed and event_id in message_event_ids and destination not in noticed:+ overflowed = request.overflowed+ noticed.add(destination)transport_class = _TRANSPORTS.get(target["type"])if transport_class is None:skipped += 1@@ -214,7 +223,7 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:configuration_id=request.configuration_id,evaluation_key=request.evaluation_key,target=target,- announcement=replace(announced, transitions=transitions, overflowed=request.overflowed),+ announcement=replace(announced, transitions=transitions, overflowed=overflowed),incident_action=action_by_event_id.get(event_id),source_alert_url=request.source_alert_url,)diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex 20ffc74d4992..7eb1ea171f00 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -162,7 +162,7 @@ class Grouping:class GroupAdmission:"""Which of a check's groups the configuration has room for, and how many it turned away."""- admitted: tuple[str, ...]+ admitted: frozenset[str]overflowed: int@@ -176,6 +176,34 @@ class InstanceCheckState:snooze_until: datetime | None = Nonefiring_started_at: datetime | None = None+ @classmethod+ def composed(+ cls,+ *,+ grouping_key: str,+ state: str,+ check_status: str,+ configuration_snooze_until: datetime | None,+ snooze_until: datetime | None = None,+ last_notified_at: datetime | None = None,+ firing_started_at: datetime | None = None,+ ) -> InstanceCheckState:+ """An instance as a check, history and the read API all see it.++ The machine reads ERRORED and BROKEN from the same field as firing, so a failing check status+ takes the place of the instance's state. A configuration mute extends every instance's, and+ the later of the two holds. The single definition, so what a check judges, what history+ records and what a reader sees cannot drift apart.+ """+ snoozes = [moment for moment in (configuration_snooze_until, snooze_until) if moment is not None]+ return cls(+ grouping_key=grouping_key,+ state=state if check_status == PlatformAlertCheckStatus.OK else check_status,+ last_notified_at=last_notified_at,+ snooze_until=max(snoozes, default=None),+ firing_started_at=firing_started_at,+ )+@frozenclass PlatformAlertCheckInput:@@ -213,31 +241,38 @@ class PlatformAlertCheckInput:"""existing = {instance.grouping_key for instance in self.instances}room = max(self.grouping.max_instances - len(existing), 0)- admitted: list[str] = []+ admitted: set[str] = set()overflowed = 0for key in dict.fromkeys(grouping_keys):if key in existing:- admitted.append(key)+ admitted.add(key)elif room > 0:- admitted.append(key)+ admitted.add(key)room -= 1else:overflowed += 1- return GroupAdmission(admitted=tuple(admitted), overflowed=overflowed)+ return GroupAdmission(admitted=frozenset(admitted), overflowed=overflowed)def instance(self, grouping_key: str = "") -> InstanceCheckState:"""The instance for a group, or the state a group with no instance starts from."""for instance in self.instances:if instance.grouping_key == grouping_key:return instance- return InstanceCheckState(+ return InstanceCheckState.composed(grouping_key=grouping_key,- state=PlatformAlertState.NOT_FIRING.value- if self.check_status == PlatformAlertCheckStatus.OK- else self.check_status,- snooze_until=self.snooze_until,+ state=PlatformAlertState.NOT_FIRING.value,+ check_status=self.check_status,+ configuration_snooze_until=self.snooze_until,)+ def open_keys(self) -> list[str]:+ """The groups whose instance is not at rest. A check judges each one, returned or not."""+ return [+ instance.grouping_key+ for instance in self.instances+ if instance.state != PlatformAlertState.NOT_FIRING.value+ ]+@propertydef filters(self) -> dict[str, Any]:"""Satisfies the logs query layer, which names this field `filters`."""@@ -397,6 +432,9 @@ class PlatformAlertOutcome:consecutive_failures: intgroups: tuple[GroupOutcome, ...] = ()failure: CheckFailure | None = None+ skipped: bool = False+ # New groups `max_instances` had no room for, which the delivery names so a cap is never silent.+ overflowed: int = 0error_message: str | None = Nonequery_duration_ms: int | None = None# Recording an outcome without it leaves a configuration discovery keeps handing back to an@@ -406,6 +444,66 @@ class PlatformAlertOutcome:# one query can do so. None spreads the configuration by its own id.schedule_group: str | None = None+ @classmethod+ def ungrouped(+ cls,+ *,+ configuration_id: UUID,+ evaluation_key: str,+ consecutive_failures: int,+ kind: AlertEventKind,+ new_state: str,+ notified: bool,+ failed: bool,+ firing_episode: FiringEpisode | None = None,+ value: float | None = None,+ muted_notification: str = "",+ error_message: str | None = None,+ query_duration_ms: int | None = None,+ disable: bool = False,+ skipped: bool = False,+ schedule_group: str | None = None,+ ) -> PlatformAlertOutcome:+ """A check of a source that does not group: its one verdict on the empty key, or its failure."""+ failure = (+ CheckFailure(+ kind=kind,+ new_state=new_state,+ notified=notified,+ firing_episode=firing_episode,+ muted_notification=muted_notification,+ )+ if failed+ else None+ )+ groups = (+ ()+ if failed+ else (+ GroupOutcome(+ grouping_key="",+ kind=kind,+ new_state=new_state,+ notified=notified,+ firing_episode=firing_episode,+ value=value,+ muted_notification=muted_notification,+ ),+ )+ )+ return cls(+ configuration_id=configuration_id,+ evaluation_key=evaluation_key,+ consecutive_failures=consecutive_failures,+ groups=groups,+ failure=failure,+ error_message=error_message,+ query_duration_ms=query_duration_ms,+ disable=disable,+ skipped=skipped,+ schedule_group=schedule_group,+ )+def __post_init__(self) -> None:if self.failure is not None and self.groups:raise ValueError("a failed check reports no groups")@@ -477,7 +575,7 @@ class EvaluationAnnouncement:# whole evaluation, and every group in one announcement saw the same count.consecutive_failures: inttransitions: tuple[AnnouncedTransition, ...]- # Groups the configuration had no room for. The last message names them, so a cap never drops+ # Groups the configuration had no room for. The first message names them, so a cap never drops# a group without anyone being told.overflowed: int = 0diff --git a/products/alerts_platform/backend/facade/grouping.py b/products/alerts_platform/backend/facade/grouping.pynew file mode 100644index 000000000000..eccbb917d417--- /dev/null+++ b/products/alerts_platform/backend/facade/grouping.py@@ -0,0 +1,170 @@+"""How a grouped check turns per-group observations into the groups an outcome reports.++A source measures each group and builds its machine snapshot. Everything after that is the same for+every source, so it lives here once: run the machine per group, leave out a new group that decided+nothing, put firing groups first, and admit what `max_instances` has room for.+"""++import hashlib+from collections.abc import Callable, Sequence+from dataclasses import field+from datetime import datetime+from typing import Final+from uuid import UUID++from posthog.dataclasses import frozen++from products.alerts_platform.backend.facade.contracts import (+ GroupOutcome,+ InstanceCheckState,+ PlatformAlertCheckInput,+ PlatformAlertOutcome,+)+from products.alerts_platform.backend.facade.lifecycle import (+ NOTIFICATION_EVENT_KINDS,+ AlertCheckOutcome,+ AlertPolicy,+ AlertSnapshot,+ AlertState,+ CheckInput,+ NotificationAction,+ Outcome,+ decide_firing_episode,+ evaluate_alert_check,+)++# `PlatformAlert.grouping_key` holds at most this many characters, so a longer key is hashed.+MAX_GROUPING_KEY_LENGTH: Final = 255+_HASHED_PREFIX: Final = "sha256:"+++def bounded_grouping_key(key: str) -> str:+ """A key that fits the column. Stable across checks, so a group keeps its row."""+ if len(key) <= MAX_GROUPING_KEY_LENGTH:+ return key+ return f"{_HASHED_PREFIX}{hashlib.sha256(key.encode()).hexdigest()}"+++def is_hashed_grouping_key(key: str) -> bool:+ """Whether `bounded_grouping_key` hashed this key, so the value it came from is gone."""+ return key.startswith(_HASHED_PREFIX)+++@frozen+class GroupObservation:+ """What a source measured for one group. `prior_breached` is newest first, as the machine reads it."""++ grouping_key: str+ current_breached: bool+ prior_breached: tuple[bool, ...] = ()+ value: float | None = None+ labels: dict[str, str] = field(default_factory=dict)+++@frozen+class GroupVerdict:+ observation: GroupObservation+ snapshot: AlertSnapshot+ outcome: AlertCheckOutcome+ group: GroupOutcome+++@frozen+class GroupDecision:+ """The admitted groups, firing first, and how many new groups the cap turned away."""++ verdicts: tuple[GroupVerdict, ...]+ overflowed: int++ def as_outcome(+ self, *, configuration_id: UUID, evaluation_key: str, query_duration_ms: int | None+ ) -> PlatformAlertOutcome:+ """The outcome of a grouped check that ran. A query that ran reset the failure count."""+ return PlatformAlertOutcome(+ configuration_id=configuration_id,+ evaluation_key=evaluation_key,+ consecutive_failures=0,+ groups=tuple(verdict.group for verdict in self.verdicts),+ query_duration_ms=query_duration_ms,+ overflowed=self.overflowed,+ )+++def muted_value(outcome: Outcome) -> str:+ """The stored form of what a mute held back: empty when nothing was held."""+ muted = getattr(outcome, "muted_notification", NotificationAction.NONE)+ return "" if muted == NotificationAction.NONE else muted.value+++def _not_breaching(grouping_key: str) -> GroupObservation:+ return GroupObservation(grouping_key=grouping_key, current_breached=False)+++def _decided_nothing(outcome: AlertCheckOutcome) -> bool:+ return (+ outcome.new_state == AlertState.NOT_FIRING+ and outcome.notification == NotificationAction.NONE+ and outcome.muted_notification == NotificationAction.NONE+ )+++def decide_groups(+ check: PlatformAlertCheckInput,+ observations: Sequence[GroupObservation],+ *,+ snapshot_of: Callable[[InstanceCheckState, tuple[bool, ...]], AlertSnapshot],+ policy: AlertPolicy,+ now: datetime,+ muted: bool = False,+ absent: Callable[[str], GroupObservation | None] = _not_breaching,+) -> GroupDecision:+ """Each observed group run through the machine against its own instance.++ A new group that decided nothing is left out, so a quiet group costs no row. An open group the+ check did not return is judged through `absent`, as not breaching unless a source says what it+ measured, so a group that vanished resolves. `absent` returns None for a group the source cannot+ judge from its absence.+ """+ existing = {instance.grouping_key for instance in check.instances}+ # One observation per key. Two results can share a label, and a breaching one must not be lost.+ by_key: dict[str, GroupObservation] = {}+ for observation in observations:+ kept = by_key.get(observation.grouping_key)+ if kept is None or (observation.current_breached and not kept.current_breached):+ by_key[observation.grouping_key] = observation+ for key in check.open_keys():+ if key not in by_key and (missing := absent(key)) is not None:+ by_key[key] = missing+ judged: list[tuple[GroupObservation, AlertSnapshot, AlertCheckOutcome]] = []+ for observation in by_key.values():+ snapshot = snapshot_of(check.instance(observation.grouping_key), observation.prior_breached)+ outcome = evaluate_alert_check(+ snapshot, CheckInput(threshold_breached=observation.current_breached, muted=muted), now, policy=policy+ )+ if observation.grouping_key not in existing and _decided_nothing(outcome):+ continue+ judged.append((observation, snapshot, outcome))++ # Firing groups first, so a cap keeps the groups that announce something.+ judged.sort(key=lambda item: item[2].new_state == AlertState.NOT_FIRING)+ admission = check.admit([observation.grouping_key for observation, _, _ in judged])+ verdicts = tuple(+ GroupVerdict(+ observation=observation,+ snapshot=snapshot,+ outcome=outcome,+ group=GroupOutcome(+ grouping_key=observation.grouping_key,+ kind=NOTIFICATION_EVENT_KINDS[outcome.notification],+ new_state=outcome.new_state.value,+ notified=outcome.update_last_notified_at,+ firing_episode=decide_firing_episode(snapshot, outcome, now, policy=policy),+ value=observation.value,+ labels=observation.labels,+ muted_notification=muted_value(outcome),+ ),+ )+ for observation, snapshot, outcome in judged+ if observation.grouping_key in admission.admitted+ )+ return GroupDecision(verdicts=verdicts, overflowed=admission.overflowed)diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.pyindex 6c55bcff1d02..2dcf111cf3e4 100644--- a/products/alerts_platform/backend/logic/platform_lifecycle.py+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py@@ -4,7 +4,7 @@ A source decides whether its data breached; everything about what that means forand every write to these rows, stays here. A source never holds one of these models."""-from collections.abc import Collection, Mapping, Sequence+from collections.abc import Collection, Sequencefrom datetime import datetime, timedeltafrom typing import Finalfrom uuid import UUID@@ -19,6 +19,7 @@ from posthog.models import Teamfrom products.alerts_platform.backend.facade.contracts import (CheckFailure,Grouping,+ GroupingMode,GroupOutcome,InstanceCheckState,PlatformAlertCheckInput,@@ -81,28 +82,29 @@ def _instances(team_id: int, keys: Collection[_InstanceKey]) -> dict[_InstanceKedef _alerts_for_write(- team_id: int, wanted: Mapping[_InstanceKey, PlatformAlertConfiguration]+ team_id: int, configurations: Sequence[PlatformAlertConfiguration], wanted: Collection[_InstanceKey]) -> dict[_InstanceKey, PlatformAlert]:- """The runtime rows, creating any group that has none yet while its configuration has room.+ """Every runtime row these configurations have, plus a new one for each wanted group with room.- A group past `max_instances` gets no row, and so no write and no history. A source admits+ One read serves the existing rows, the counts the cap needs, and the empty-key row a failure+ states. A group past `max_instances` gets no row, and so no write and no history. A source admitsgroups before it reports them, so this is the backstop for one that did not."""- configuration_ids = {key.configuration_id for key in wanted}+ loaded = {+ _InstanceKey(configuration_id=configuration_id, grouping_key=alert.grouping_key): alert+ for configuration_id, alerts in _instances_by_configuration(team_id, configurations).items()+ for alert in alerts+ }+ by_id = {str(configuration.id): configuration for configuration in configurations}held: dict[str, int] = {}- for configuration_id in (- PlatformAlert.objects.for_team(team_id)- .filter(configuration_id__in=configuration_ids)- .values_list("configuration_id", flat=True)- ):- held[str(configuration_id)] = held.get(str(configuration_id), 0) + 1- existing = _instances(team_id, wanted.keys())+ for key in loaded:+ held[key.configuration_id] = held.get(key.configuration_id, 0) + 1missing: list[_InstanceKey] = []over_cap: dict[str, int] = {}for key in wanted:- if key in existing:+ if key in loaded:continue- configuration = wanted[key]+ configuration = by_id[key.configuration_id]if held.get(key.configuration_id, 0) >= Grouping.from_stored(configuration.grouping).max_instances:over_cap[configuration.source_kind] = over_cap.get(configuration.source_kind, 0) + 1continue@@ -117,27 +119,35 @@ def _alerts_for_write(# because a queryset filter does not propagate into row creation.PlatformAlert.objects.for_team(team_id).bulk_create([- PlatformAlert(team_id=team_id, configuration=wanted[key], grouping_key=key.grouping_key)+ PlatformAlert(team_id=team_id, configuration=by_id[key.configuration_id], grouping_key=key.grouping_key)for key in missing],ignore_conflicts=True,)- existing.update(_instances(team_id, missing))- return existing+ loaded.update(_instances(team_id, missing))+ return loaded# Long enough that a group which resolves and fires again inside a day keeps its cooldown.REAP_AFTER: Final = timedelta(hours=24)-def _reap(team_id: int, configurations: Sequence[PlatformAlertConfiguration], now: datetime) -> None:+def _reap(+ team_id: int,+ configurations: Sequence[PlatformAlertConfiguration],+ now: datetime,+ *,+ returned: Collection[_InstanceKey],+) -> None:"""Deletes instances that hold a slot and nothing else, so a stale group frees its place.Only an instance that is not firing, not muted, and that no check returned for longer than both`REAP_AFTER` and its cooldown. A configuration whose checks fail returns no groups, so its- instances look unseen without being gone, and none of them is reaped while it is not OK.+ instances look unseen without being gone. The caller passes only configurations whose check+ succeeded."""- healthy = {str(c.id): c for c in configurations if c.check_status == PlatformAlertConfiguration.CheckStatus.OK}+ # An ungrouped configuration's one instance is returned by every check, so it has nothing to reap.+ healthy = {str(c.id): c for c in configurations if Grouping.from_stored(c.grouping).mode != GroupingMode.SINGLE}if not healthy:returncandidates = (@@ -146,10 +156,12 @@ def _reap(team_id: int, configurations: Sequence[PlatformAlertConfiguration], noconfiguration_id__in=list(healthy), state=PlatformAlert.State.NOT_FIRING, last_seen_at__lt=now - REAP_AFTER).filter(Q(snooze_until__isnull=True) | Q(snooze_until__lte=now))- .values_list("id", "configuration_id", "last_seen_at")+ .values_list("id", "configuration_id", "grouping_key", "last_seen_at"))reaped: dict[str, list[UUID]] = {}- for alert_id, configuration_id, last_seen_at in candidates:+ for alert_id, configuration_id, grouping_key, last_seen_at in candidates:+ if _InstanceKey(configuration_id=str(configuration_id), grouping_key=grouping_key) in returned:+ continueconfiguration = healthy[str(configuration_id)]if configuration.snooze_until is not None and configuration.snooze_until > now:continue@@ -244,31 +256,22 @@ def _check(c: PlatformAlertConfiguration, alerts: Sequence[PlatformAlert]) -> Pllegacy_configuration_id=c.legacy_configuration_id,check_status=c.check_status,snooze_until=c.snooze_until,- instances=tuple(- InstanceCheckState(- grouping_key=alert.grouping_key,- state=_check_state(c, alert),- last_notified_at=alert.last_notified_at,- snooze_until=_later(c.snooze_until, alert.snooze_until),- firing_started_at=alert.firing_started_at,- )- for alert in alerts- ),+ instances=tuple(_composed(c, alert) for alert in alerts),grouping=Grouping.from_stored(c.grouping),owned_by_platform=c.owner == PlatformAlertConfiguration.Owner.PLATFORM,)-def _later(first: datetime | None, second: datetime | None) -> datetime | None:- return max((moment for moment in (first, second) if moment is not None), default=None)---def _check_state(configuration: PlatformAlertConfiguration, alert: PlatformAlert | None) -> str:- """The state the shared machine expects. It reads ERRORED and BROKEN from the same field as- firing, so the configuration's status takes the place of the instance's while it is not OK."""- if configuration.check_status != PlatformAlertConfiguration.CheckStatus.OK:- return configuration.check_status- return alert.state if alert else PlatformAlert.State.NOT_FIRING.value+def _composed(configuration: PlatformAlertConfiguration, alert: PlatformAlert | None) -> InstanceCheckState:+ return InstanceCheckState.composed(+ grouping_key=alert.grouping_key if alert else "",+ state=alert.state if alert else PlatformAlert.State.NOT_FIRING.value,+ check_status=configuration.check_status,+ configuration_snooze_until=configuration.snooze_until,+ snooze_until=alert.snooze_until if alert else None,+ last_notified_at=alert.last_notified_at if alert else None,+ firing_started_at=alert.firing_started_at if alert else None,+ )def slot_of(next_check_at: datetime | None, cutoff: datetime) -> str:@@ -361,9 +364,9 @@ def _shard_offset_seconds(configuration: PlatformAlertConfiguration, outcome: Pl)-_CHECK_STATUSES: Final = frozenset(- {PlatformAlertConfiguration.CheckStatus.ERRORED.value, PlatformAlertConfiguration.CheckStatus.BROKEN.value}-)+_CHECK_STATUSES: Final = frozenset(PlatformAlertConfiguration.CheckStatus.values) - {+ PlatformAlertConfiguration.CheckStatus.OK.value+}def _check_status(configuration: PlatformAlertConfiguration, outcome: PlatformAlertOutcome) -> str:@@ -375,6 +378,8 @@ def _check_status(configuration: PlatformAlertConfiguration, outcome: PlatformAlif outcome.failure is not None:failed = outcome.failure.new_statereturn failed if failed in _CHECK_STATUSES else configuration.check_status+ if outcome.skipped:+ return configuration.check_statusstates = {group.new_state for group in outcome.groups}for status in (PlatformAlertConfiguration.CheckStatus.BROKEN, PlatformAlertConfiguration.CheckStatus.ERRORED):if status.value in states:@@ -417,27 +422,26 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:)if not configurations:return 0- alerts = _alerts_for_write(+ # In outcome order, because the source put the groups it most wants kept first.+ returned = [+ _InstanceKey(configuration_id=str(configuration.id), grouping_key=group.grouping_key)+ for configuration in configurations+ for group in by_id[str(configuration.id)].groups+ ]+ # Before the cap is counted, so a slot a stale group held is free for a new one this check.+ _reap(team_id,- {- _InstanceKey(configuration_id=str(configuration.id), grouping_key=group.grouping_key): configuration+ [+ configurationfor configuration in configurations- for group in by_id[str(configuration.id)].groups- },+ if _check_status(configuration, by_id[str(configuration.id)])+ == PlatformAlertConfiguration.CheckStatus.OK+ ],+ now,+ returned=frozenset(returned),)- # The empty-key instance of each failed configuration, so a failure row states the state- # an ungrouped check found.- alerts_by_configuration = {- key.configuration_id: alert- for key, alert in _instances(- team_id,- [- _InstanceKey(configuration_id=str(configuration.id), grouping_key="")- for configuration in configurations- if by_id[str(configuration.id)].failure is not None- ],- ).items()- }+ alerts = _alerts_for_write(team_id, configurations, returned)+ touched: list[PlatformAlert] = []# One read for the batch. Every configuration in it belongs to this team, and a# calendar recurrence resolves its anchor against the team's zone.team_timezone = Team.objects.filter(id=team_id).values_list("timezone", flat=True).first() or "UTC"@@ -451,6 +455,7 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:)if alert is None:continue+ touched.append(alert)alert.last_seen_at = now# Before either row is mutated, so the history row keeps the state the check found.rows.append(@@ -459,7 +464,7 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:outcome,group,alert=alert,- previous_state=_check_state(configuration, alert),+ previous_state=_composed(configuration, alert).state,now=now,))@@ -474,14 +479,15 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:alert.state = group.new_stateif outcome.failure is not None:- ungrouped = alerts_by_configuration.get(str(configuration.id))+ # The empty-key row, so a failure row states the state an ungrouped check found.+ ungrouped = alerts.get(_InstanceKey(configuration_id=str(configuration.id), grouping_key=""))rows.append(_event_row(configuration,outcome,outcome.failure,alert=None,- previous_state=_check_state(configuration, ungrouped),+ previous_state=_composed(configuration, ungrouped).state,now=now,))@@ -500,13 +506,13 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:shard_offset_seconds=_shard_offset_seconds(configuration, outcome),)+ # Batched, because a grouped check writes a row per group rather than one per configuration.PlatformAlert.objects.for_team(team_id).bulk_update(- list(alerts.values()), ["state", "last_notified_at", "firing_started_at", "last_seen_at"]+ touched, ["state", "last_notified_at", "firing_started_at", "last_seen_at"], batch_size=500)PlatformAlertConfiguration.objects.for_team(team_id).bulk_update(configurations, ["check_status", "consecutive_failures", "enabled", "next_check_at"])- _reap(team_id, configurations, now)# `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))@@ -675,7 +681,7 @@ def take_ownership(handover: PlatformOwnershipHandover) -> bool:.get(legacy_configuration_id=handover.legacy_configuration_id))key = _InstanceKey(configuration_id=str(configuration.id), grouping_key="")- alert = _alerts_for_write(handover.team_id, {key: configuration})[key]+ alert = _alerts_for_write(handover.team_id, [configuration], [key])[key]if alert.state == PlatformAlertState.FIRING or alert.firing_started_at is not None:return False# ERRORED and BROKEN are the configuration's check status, so the instance starts at rest.diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.pyindex e16aaec9e524..73b9fd29c31e 100644--- a/products/alerts_platform/backend/logic/platform_reads.py+++ b/products/alerts_platform/backend/logic/platform_reads.py@@ -10,6 +10,7 @@ from uuid import UUIDfrom django.db.models import Prefetch, QuerySetfrom products.alerts_platform.backend.facade.contracts import (+ InstanceCheckState,PlatformAlertConfigurationPage,PlatformAlertConfigurationView,PlatformAlertSnapshot,@@ -24,15 +25,20 @@ def instance_view(alert: PlatformAlert, configuration: PlatformAlertConfiguratiowhich group caused the failure. The row keeps its own state so a recovery continues its firing.A configuration mute shows on every instance for the same reason a check reads it there."""- check_status = configuration.check_status- snoozes = [moment for moment in (configuration.snooze_until, alert.snooze_until) if moment is not None]+ seen = InstanceCheckState.composed(+ grouping_key=alert.grouping_key,+ state=alert.state,+ check_status=configuration.check_status,+ configuration_snooze_until=configuration.snooze_until,+ snooze_until=alert.snooze_until,+ )return PlatformAlertSnapshot(id=alert.id,grouping_key=alert.grouping_key,- state=alert.state if check_status == PlatformAlertConfiguration.CheckStatus.OK else check_status,+ state=seen.state,firing_started_at=alert.firing_started_at,last_notified_at=alert.last_notified_at,- snooze_until=max(snoozes, default=None),+ snooze_until=seen.snooze_until,)diff --git a/products/alerts_platform/backend/migrations/0015_backfill_platformalert_last_seen_at.py b/products/alerts_platform/backend/migrations/0015_backfill_platformalert_last_seen_at.pynew file mode 100644index 000000000000..129a7ceac62c--- /dev/null+++ b/products/alerts_platform/backend/migrations/0015_backfill_platformalert_last_seen_at.py@@ -0,0 +1,18 @@+from django.db import migrations++# Rows from before `last_seen_at` existed get the migration time, so a stale one becomes reapable after+# the usual window rather than holding its slot forever. A second run matches nothing.+BACKFILL_LAST_SEEN_AT = """+-- migration-analyzer: safe reason=holds only the instances the logs and insight parallel runs wrote, and nothing reads it on a request path+UPDATE alerts_platformalert SET last_seen_at = now() WHERE last_seen_at IS NULL+"""+++class Migration(migrations.Migration):+ dependencies = [+ ("alerts_platform", "0014_platformalert_last_seen_at"),+ ]++ operations = [+ migrations.RunSQL(BACKFILL_LAST_SEEN_AT, reverse_sql=migrations.RunSQL.noop),+ ]diff --git a/products/alerts_platform/backend/migrations/max_migration.txt b/products/alerts_platform/backend/migrations/max_migration.txtindex bc18f089c09a..15b4175ff23a 100644--- a/products/alerts_platform/backend/migrations/max_migration.txt+++ b/products/alerts_platform/backend/migrations/max_migration.txt@@ -1 +1 @@-0014_platformalert_last_seen_at+0015_backfill_platformalert_last_seen_atdiff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.pyindex 6549fbaea8b6..24df3e302ce8 100644--- a/products/alerts_platform/backend/models/platform_alert.py+++ b/products/alerts_platform/backend/models/platform_alert.py@@ -13,6 +13,7 @@ from django.db import modelsfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import UUIDModel+from products.alerts_platform.backend.facade.contracts import Groupingfrom products.alerts_platform.backend.facade.enums import (PlatformAlertCheckStatus,PlatformAlertConfigurationRecurrenceUnit,@@ -23,7 +24,7 @@ from products.alerts_platform.backend.facade.enums import (def single_instance_grouping() -> dict[str, object]:- return {"mode": "single", "keys": []}+ return Grouping().to_stored()# nosemgrep: tuple-return-prefer-dataclass -- Django's `choices` contract is (value, label) pairs.diff --git a/products/alerts_platform/backend/tests/test_comparison_platform_history.py b/products/alerts_platform/backend/tests/test_comparison_platform_history.pyindex 21c24c27e7e4..2199044655f1 100644--- a/products/alerts_platform/backend/tests/test_comparison_platform_history.py+++ b/products/alerts_platform/backend/tests/test_comparison_platform_history.py@@ -1,10 +1,13 @@from datetime import UTC, datetime, timedelta+from typing import Anyfrom uuid import uuid4import pytestfrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import patch+from parameterized import parameterized+from posthog.clickhouse.client import sync_executefrom posthog.enums import LabeledStrEnumfrom posthog.models.scoping import team_scope@@ -141,9 +144,17 @@ class TestReadPlatformChecks(ClickhouseTestMixin, APIBaseTest):assert teams_with_configurations(SourceKind.LOGS) == [self.team.id]- def test_another_source_is_not_in_a_logs_comparison(self) -> None:+ @parameterized.expand(+ [+ ("another_source", {"source_kind": "insight"}),+ ("a_grouped_configuration", {"grouping": {"mode": "by_result_labels", "keys": ["service_name"]}}),+ ]+ )+ def test_a_check_with_no_comparable_verdict_is_not_in_a_logs_comparison(+ self, _name: str, overrides: dict[str, Any]+ ) -> None:self._record(- self._configuration(source_kind="insight", legacy_configuration_id=uuid4()),+ self._configuration(legacy_configuration_id=uuid4(), **overrides),evaluation_key="run:2026-09-30T11:59:00+00:00",)diff --git a/products/alerts_platform/backend/tests/test_delivery_dispatch.py b/products/alerts_platform/backend/tests/test_delivery_dispatch.pyindex 8536aaff2abb..d6a9e594805f 100644--- a/products/alerts_platform/backend/tests/test_delivery_dispatch.py+++ b/products/alerts_platform/backend/tests/test_delivery_dispatch.py@@ -239,7 +239,7 @@ class TestDeliveryDispatch(SimpleTestCase):assert [[detail.value for detail in message.details if detail.label == "Untracked groups"]for message, _ in transport.sends- ] == [[], ["3 more groups not tracked because this alert is at its group limit"]]+ ] == [["3 more groups not tracked because this alert is at its group limit"], []]def test_a_retried_evaluation_does_not_send_a_second_copy(self) -> None:store = RecordingThreadStore()diff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.pyindex 09b7b7631752..d75050b07a49 100644--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py@@ -90,6 +90,7 @@ def _request(sends_messages: bool = True,incident_actions: dict[str, IncidentAction] | None = None,owned_by_platform: bool = False,+ overflowed: int = 0,) -> AlertDeliveryRequest:return AlertDeliveryRequest(source=SourceKind.LOGS,@@ -102,6 +103,7 @@ def _request(incident_actions=incident_actions or {},event_ids_by_incident_action={"trigger": OPENED_EVENT, "resolve": CLOSED_EVENT},owned_by_platform=owned_by_platform,+ overflowed=overflowed,)@@ -147,6 +149,7 @@ class TestDeliverEvaluation(APIBaseTest):sends_messages: bool = True,incident_actions: dict[str, IncidentAction] | None = None,owned_by_platform: bool = False,+ overflowed: int = 0,) -> Any:def groups(*, team_id: int, alert_id: str, allowed_event_ids: list[str]) -> list[AlertDestinationGroup]:return by_event.get(allowed_event_ids[0], [])@@ -174,6 +177,7 @@ class TestDeliverEvaluation(APIBaseTest):sends_messages=sends_messages,incident_actions=incident_actions,owned_by_platform=owned_by_platform,+ overflowed=overflowed,))@@ -200,12 +204,16 @@ class TestDeliverEvaluation(APIBaseTest):_transition(AlertEventKind.RESOLVED, "search"),)- self._run(announced, {FIRING_EVENT: [_group(SLACK)], RESOLVED_EVENT: [_group(SLACK)]})+ self._run(announced, {FIRING_EVENT: [_group(SLACK)], RESOLVED_EVENT: [_group(SLACK)]}, overflowed=3)assert sorted(m.headline for _, m in RecordingTransport.sends) == ["Log alert 'API errors' is firing","Log alert 'API errors' is resolved",]+ overflow_notices = [+ detail for _, m in RecordingTransport.sends for detail in m.details if detail.label == "Untracked groups"+ ]+ assert len(overflow_notices) == 1def test_a_delivery_that_exists_only_for_its_incident_sends_no_message(self) -> None:# Even a kind its destinations subscribe to reaches none of them when the source announced nothing.diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.pyindex 5b9ce41f6c38..b84419dd2ee2 100644--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py@@ -214,6 +214,10 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):(check,) = due_checks(self.team.id, SourceKind.LOGS.value, slot_of(due, due), due)assert check.instance().state == "errored"+ self._record(at=due, groups=(), skipped=True)+ due = self._next_due()+ assert self.configuration.check_status == "errored"+self._record(at=due, kind=AlertEventKind.CHECK, new_state="not_firing", notified=False)self._next_due()@@ -338,14 +342,15 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):("firing", {"state": "firing"}, True),("seen_recently", {"last_seen_hours_ago": 2}, True),("still_snoozed", {"snoozed": True}, True),- ("checks_failing", {"recorded_state": "errored"}, True),+ ("check_failed", {"failed": True}, True),("cooldown_outlasts_the_window", {"cooldown_minutes": 48 * 60}, True),])def test_an_idle_group_is_reaped_so_its_slot_frees(self, _name: str, case: dict[str, Any], kept: bool) -> None:with team_scope(self.team.id):PlatformAlertConfiguration.objects.filter(id=self.configuration.id).update(- cooldown_minutes=case.get("cooldown_minutes", 0)+ cooldown_minutes=case.get("cooldown_minutes", 0),+ grouping=Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service",), max_instances=1).to_stored(),)PlatformAlert.objects.create(team=self.team,@@ -356,10 +361,18 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):snooze_until=self.cutoff + timedelta(hours=1) if case.get("snoozed") else None,)- self._record(groups=(self._group("api", state=case.get("recorded_state", "not_firing")),))+ if case.get("failed"):+ self._record(+ groups=(), failure=CheckFailure(kind=AlertEventKind.ERRORED, new_state="errored", notified=False)+ )+ else:+ self._record(groups=(self._group("api"),))with team_scope(self.team.id):assert PlatformAlert.objects.filter(configuration=self.configuration, grouping_key="old").exists() is kept+ assert (+ PlatformAlert.objects.filter(configuration=self.configuration, grouping_key="api").exists() is not kept+ )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@@ -570,9 +583,9 @@ def _group(grouping_key: str) -> GroupOutcome:@pytest.mark.parametrize("existing, returned, expected",[- ((), ("a", "b", "c", "d"), GroupAdmission(admitted=("a", "b", "c"), overflowed=1)),- (("x", "y", "z"), ("q", "x"), GroupAdmission(admitted=("x",), overflowed=1)),- (("x",), ("x", "a", "a", "b"), GroupAdmission(admitted=("x", "a", "b"), overflowed=0)),+ ((), ("a", "b", "c", "d"), GroupAdmission(admitted=frozenset({"a", "b", "c"}), overflowed=1)),+ (("x", "y", "z"), ("q", "x"), GroupAdmission(admitted=frozenset({"x"}), overflowed=1)),+ (("x",), ("x", "a", "a", "b"), GroupAdmission(admitted=frozenset({"x", "a", "b"}), overflowed=0)),],)def test_a_check_admits_existing_groups_and_new_ones_up_to_the_cap(diff --git a/products/logs/backend/alert_check_query.py b/products/logs/backend/alert_check_query.pyindex 4b3e3fbee63b..61ad1ede8a09 100644--- a/products/logs/backend/alert_check_query.py+++ b/products/logs/backend/alert_check_query.py@@ -125,6 +125,37 @@ def _timestamp_in_range(start: dt.datetime, end: dt.datetime) -> ast.Expr:)+def _period_count_columns(ranges: list[tuple[dt.datetime, dt.datetime]]) -> list[ast.Expr]:+ """One `period_<i>` count per range, oldest first."""+ return [+ ast.Alias(alias=f"period_{i}", expr=ast.Call(name="countIf", args=[_timestamp_in_range(start, end)]))+ for i, (start, end) in enumerate(ranges)+ ]+++def _run_alert_query(+ team: Team, query: ast.SelectQuery, *, ch_user: ClickHouseUser, settings: HogQLGlobalSettings+) -> HogQLQueryResponse:+ return execute_hogql_query(+ query_type="alert_check",+ query=query,+ team=team,+ workload=Workload.LOGS,+ ch_user=ch_user,+ settings=settings,+ limit_context=LimitContext.QUERY,+ modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),+ )+++def _bounded_settings(max_execution_time: int) -> HogQLGlobalSettings:+ # Throw rather than break: a partial count could resolve an alert that is actually breaching,+ # and the caller already handles a failed query.+ return AlertCheckQuery.SETTINGS.model_copy(+ update={"max_execution_time": max_execution_time, "timeout_overflow_mode": "throw"}+ )++def _tag_alert_query(*, team: Team, alert_config_id: str, source: str) -> None:tag_queries(product=Product.LOGS,@@ -314,16 +345,8 @@ class AlertCheckQuery:return self._execute_count_per_range(ranges)def _execute_count_per_range(self, ranges: list[tuple[dt.datetime, dt.datetime]]) -> list[BucketedCount]:- select_columns: list[ast.Expr] = [- ast.Alias(- alias=f"period_{i}",- expr=ast.Call(name="countIf", args=[_timestamp_in_range(start, end)]),- )- for i, (start, end) in enumerate(ranges)- ]-query = ast.SelectQuery(- select=select_columns,+ select=_period_count_columns(ranges),select_from=ast.JoinExpr(table=ast.Field(chain=["logs"])),where=self.where_expr,)@@ -399,15 +422,8 @@ class BatchedAlertCheckQuery:self.date_to = date_toself._ch_user = ch_user# A caller that runs several of these inside one deadline needs each query to end before- # the deadline does. Throw rather than break: a partial count could resolve an alert that- # is actually breaching, and the caller already handles a failed cohort.- self._settings = (- self.SETTINGS- if max_execution_time is None- else self.SETTINGS.model_copy(- update={"max_execution_time": max_execution_time, "timeout_overflow_mode": "throw"}- )- )+ # the deadline does.+ self._settings = self.SETTINGS if max_execution_time is None else _bounded_settings(max_execution_time)self._alert_where_exprs: list[ast.Expr] = [build_alert_where_expr(team=team, alert=alert, date_from=date_from, date_to=date_to)for alert in self.alerts@@ -567,16 +583,7 @@ class BatchedAlertCheckQuery:)def _run_query(self, query: ast.SelectQuery) -> HogQLQueryResponse:- return execute_hogql_query(- query_type="alert_check",- query=query,- team=self.team,- workload=Workload.LOGS,- ch_user=self._ch_user,- settings=self._settings,- limit_context=LimitContext.QUERY,- modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),- )+ return _run_alert_query(self.team, query, ch_user=self._ch_user, settings=self._settings)def _tag(self) -> None:# `QueryTags` doesn't allow per-batch custom fields, so we tag the first@@ -648,9 +655,7 @@ class GroupedAlertCheckQuery:self.worst_is_highest = worst_is_highestself.limit = limitself._ch_user = ch_user- self._settings = AlertCheckQuery.SETTINGS.model_copy(- update={"max_execution_time": max_execution_time, "timeout_overflow_mode": "throw"}- )+ self._settings = _bounded_settings(max_execution_time)self.where_expr = build_alert_where_expr(team=team, alert=alert, date_from=date_from, date_to=date_to)def execute_rolling_checks(@@ -661,16 +666,7 @@ class GroupedAlertCheckQuery:query = self._build_query(ranges)start_ms = time.monotonic_ns() // 1_000_000- response = execute_hogql_query(- query_type="alert_check",- query=query,- team=self.team,- workload=Workload.LOGS,- ch_user=self._ch_user,- settings=self._settings,- limit_context=LimitContext.QUERY,- modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),- )+ response = _run_alert_query(self.team, query, ch_user=self._ch_user, settings=self._settings)duration_ms = time.monotonic_ns() // 1_000_000 - start_mswidth = len(self.group_by)@@ -687,10 +683,7 @@ class GroupedAlertCheckQuery:def _build_query(self, ranges: list[tuple[dt.datetime, dt.datetime]]) -> ast.SelectQuery:columns: list[ast.Expr] = [ast.Field(chain=[column]) for column in self.group_by]- periods: list[ast.Expr] = [- ast.Alias(alias=f"period_{i}", expr=ast.Call(name="countIf", args=[_timestamp_in_range(start, end)]))- for i, (start, end) in enumerate(ranges)- ]+ periods = _period_count_columns(ranges)order_by = [ast.OrderExpr(expr=ast.Field(chain=[f"period_{len(ranges) - 1}"]), order="DESC" if self.worst_is_highest else "ASC"diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex a5ba6755c790..308907404908 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -16,8 +16,7 @@ the shared machine configured with this source's policy, not from the logs produimport jsonimport time-import hashlib-from collections.abc import Sequence+from collections.abc import Mapping, Sequencefrom dataclasses import replacefrom datetime import datetime, timedeltafrom itertools import batched@@ -39,9 +38,8 @@ from products.alerts_platform.backend.facade.api import due_checks, refresh_settfrom products.alerts_platform.backend.facade.contracts import (AlertDeliveryRequest,AlertEventKind,- CheckFailure,GroupingMode,- GroupOutcome,+ InstanceCheckState,MuteReason,PlatformAlertCheckInput,PlatformAlertOutcome,@@ -49,6 +47,13 @@ from products.alerts_platform.backend.facade.contracts import (SourceBatchEvaluation,SourceKind,)+from products.alerts_platform.backend.facade.grouping import (+ GroupObservation,+ bounded_grouping_key,+ decide_groups,+ is_hashed_grouping_key,+ muted_value,+)from products.alerts_platform.backend.facade.lifecycle import (NOTIFICATION_EVENT_KINDS,PLATFORM_LOGS_ALERT_POLICY,@@ -249,9 +254,9 @@ def is_in_quiet_hours(schedule_restriction: dict | None, now: datetime, tz_name:def _snapshot(- check: PlatformAlertCheckInput, prior_breached: tuple[bool, ...], grouping_key: str = ""+ check: PlatformAlertCheckInput, prior_breached: tuple[bool, ...], instance: InstanceCheckState | None = None) -> AlertSnapshot:- instance = check.instance(grouping_key)+ instance = instance or check.instance()return AlertSnapshot(state=AlertState(instance.state),cooldown=timedelta(minutes=check.cooldown_minutes),@@ -287,6 +292,7 @@ def _record_check_metrics(muted_by_quiet_hours: bool = False,now: datetime,grouping_key: str = "",+ record_lag: bool = True,) -> None:safe_record(increment_checks, SourceKind.LOGS.value, notification.value)if skip is not None:@@ -298,7 +304,7 @@ def _record_check_metrics(previous_state = check.instance(grouping_key).stateif previous_state != new_state:safe_record(increment_state_transition, SourceKind.LOGS.value, previous_state, new_state)- if check.next_check_at is not None:+ if record_lag and check.next_check_at is not None:lag_ms = int((now - check.next_check_at).total_seconds() * 1000)if lag_ms > 0:safe_record(record_scheduler_lag, SourceKind.LOGS.value, lag_ms)@@ -353,39 +359,17 @@ def _recorded(failed: bool = False,) -> PlatformAlertOutcome:"""The one place a recorded outcome is built, so every path states the firing the same way."""- firing_episode = decide_firing_episode(_snapshot(check, ()), outcome, now, policy=PLATFORM_LOGS_ALERT_POLICY)- failure = (- CheckFailure(- kind=kind,- new_state=outcome.new_state.value,- notified=notified,- firing_episode=firing_episode,- muted_notification=muted_notification,- )- if failed- else None- )- groups = (- ()- if failed- else (- GroupOutcome(- grouping_key="",- kind=kind,- new_state=outcome.new_state.value,- notified=notified,- firing_episode=firing_episode,- value=value,- muted_notification=muted_notification,- ),- )- )- return PlatformAlertOutcome(+ return PlatformAlertOutcome.ungrouped(configuration_id=check.id,evaluation_key=evaluation_key,consecutive_failures=outcome.consecutive_failures,- groups=groups,- failure=failure,+ kind=kind,+ new_state=outcome.new_state.value,+ notified=notified,+ failed=failed,+ firing_episode=decide_firing_episode(_snapshot(check, ()), outcome, now, policy=PLATFORM_LOGS_ALERT_POLICY),+ value=value,+ muted_notification=muted_notification,error_message=error_message,query_duration_ms=query_duration_ms,disable=disable,@@ -415,31 +399,46 @@ def _delivery(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- ),+ muted_notification=muted_value(outcome),disable=outcome.disable,failed=failed,)- return recorded, _request(check, recorded, outcome, sends_messages=outcome.notification != NotificationAction.NONE)+ return recorded, _request(+ check, recorded, _ungrouped_move(check, outcome), sends_messages=outcome.notification != NotificationAction.NONE+ )+++@frozen+class _Move:+ """The state a group left and the state it reached in one check."""++ before: AlertState+ after: AlertStatedef _request(- check: PlatformAlertCheckInput, recorded: PlatformAlertOutcome, outcome: Outcome, *, sends_messages: bool+ check: PlatformAlertCheckInput,+ recorded: PlatformAlertOutcome,+ moves: Mapping[str, _Move],+ *,+ sends_messages: bool,) -> AlertDeliveryRequest | None:"""The delivery for a recorded outcome, or None when it neither announces nor moves a firing.- A firing that opens or closes needs a delivery even when cooldown or mute held the- announcement, because a paging destination needs one resolve for every trigger. An alert- with no such destination gets no incident action, so its edges start no delivery.+ `moves` maps each group's key to the state it left and the state it reached. A firing that opens+ or closes needs a delivery even when cooldown or mute held the announcement, because a paging+ destination needs one resolve for every trigger. An alert with no such destination gets no+ incident action, so its edges start no delivery."""destination_alert_id = str(check.legacy_configuration_id)- incident_action = decide_incident_action(- AlertState(check.instance().state), outcome.new_state, policy=PLATFORM_LOGS_ALERT_POLICY- )- if incident_action is not None and not _has_incident_destination(check.team_id, destination_alert_id):- incident_action = None- if not sends_messages and incident_action is None:+ actions = {+ key: action+ for key, move in moves.items()+ if (action := decide_incident_action(move.before, move.after, policy=PLATFORM_LOGS_ALERT_POLICY)) is not None+ }+ if actions and not _has_incident_destination(check.team_id, destination_alert_id):+ actions = {}+ if not sends_messages and not actions:return Nonereturn AlertDeliveryRequest(source=SourceKind.LOGS,@@ -451,17 +450,21 @@ def _request(destination_alert_id=destination_alert_id,event_ids_by_kind=_EVENT_IDS_BY_KIND,event_ids_by_incident_action=_EVENT_IDS_BY_INCIDENT_ACTION,- # Logs does not group, so its one row has the empty grouping key.- incident_actions={"": incident_action} if incident_action is not None else {},+ incident_actions=actions,sends_messages=sends_messages,# The logs alert page, as the HogFunction messages linked. An alert with no logs row has none.source_alert_url=absolute_uri(f"/project/{check.team_id}/logs/alerts/{check.legacy_configuration_id}")if check.legacy_configuration_id is not Noneelse None,owned_by_platform=check.owned_by_platform,+ overflowed=recorded.overflowed,)+def _ungrouped_move(check: PlatformAlertCheckInput, outcome: Outcome) -> dict[str, _Move]:+ return {"": _Move(before=AlertState(check.instance().state), after=outcome.new_state)}++def _has_incident_destination(team_id: int, destination_alert_id: str) -> bool:"""Whether a destination of this alert follows the incident events. Read only on a firing edge."""return bool(@@ -548,7 +551,7 @@ def _held(_record_check_metrics(check, new_state=outcome.new_state.value, notification=NotificationAction.NONE, skip=skip, now=now)- return recorded, _request(check, recorded, outcome, sends_messages=False)+ return recorded, _request(check, recorded, _ungrouped_move(check, outcome), sends_messages=False)def _evaluate_cohort(@@ -706,21 +709,14 @@ def _stopped(check: PlatformAlertCheckInput, *, now: datetime) -> Decision:return recorded, None-# A grouping key is a stored column of at most 255 characters, so a longer label set is hashed.-_MAX_GROUPING_KEY_LENGTH: Final = 255--def grouping_key_of(labels: dict[str, str]) -> str:- """The instance key for one group's label values. Stable across checks, so a group keeps its row."""- key = json.dumps(labels, sort_keys=True, separators=(",", ":"))- if len(key) <= _MAX_GROUPING_KEY_LENGTH:- return key- return f"sha256:{hashlib.sha256(key.encode()).hexdigest()}"+ """The instance key for one group's label values."""+ return bounded_grouping_key(json.dumps(labels, sort_keys=True, separators=(",", ":")))def _labels_of(grouping_key: str) -> dict[str, str] | None:"""The labels `grouping_key_of` encoded, or None for a hashed key, which keeps no labels."""- if grouping_key.startswith("sha256:"):+ if is_hashed_grouping_key(grouping_key):return Nonetry:labels = json.loads(grouping_key)@@ -741,14 +737,6 @@ def _broken_grouping(check: PlatformAlertCheckInput) -> str | None:return None-@frozen-class _GroupVerdict:- grouping_key: str- labels: dict[str, str]- outcome: AlertCheckOutcome- value: float--def _evaluate_grouped(team: Team,check: PlatformAlertCheckInput,@@ -758,18 +746,18 @@ def _evaluate_grouped(query_seconds: int,muted: bool,) -> Decision:- """One grouped alert: its own query, then the shared machine once per group.+ """One grouped alert: its own query, then the platform's per-group decision.- A group with no instance whose check decides nothing is left out, so a quiet group costs no- row. An open group the query did not return had no matching log, so it is checked against a- zero count and can resolve.+ An open group the query did not return had no matching log, so it is checked against a zero+ count and can resolve."""condition = LogsAlertCondition.of(check)date_to = resolve_alert_date_to(check.next_check_at or now, checkpoint)lookback = rolling_check_lookback_minutes(condition.window_minutes, check.check_interval_minutes, check.evaluation_periods)- open_keys = [instance.grouping_key for instance in check.instances if instance.state != AlertState.NOT_FIRING.value]+ open_keys = check.open_keys()+ limit = len(open_keys) + check.grouping.max_instancestry:result = GroupedAlertCheckQuery(team=team,@@ -780,7 +768,7 @@ def _evaluate_grouped(open_groups=[labels for key in open_keys if (labels := _labels_of(key)) is not None],worst_is_highest=condition.threshold_operator == LogsAlertConfiguration.ThresholdOperator.ABOVE,# Room for every open group and a full cap of new ones, so admission sees the worst.- limit=len(open_keys) + check.grouping.max_instances,+ limit=limit,max_execution_time=query_seconds,ch_user=ClickHouseUser.ALERTS_PLATFORM_LOGS,).execute_rolling_checks(@@ -791,121 +779,61 @@ def _evaluate_grouped(return _delivery(check, _failed(check, error, now=now, muted=muted), window_end=date_to, now=now, failed=True)counts = {grouping_key_of(group.labels): group for group in result.groups}- existing = {instance.grouping_key for instance in check.instances}- verdicts: list[_GroupVerdict] = []# A hashed key keeps no labels, so the query cannot put that open group first, and the limit can# cut it while it still breaches. Its absence means no matching log only when nothing was cut.- truncated = len(result.groups) >= len(open_keys) + check.grouping.max_instances- absent = [key for key in open_keys if key not in counts and not (truncated and _labels_of(key) is None)]- for key in [*counts, *absent]:- group = counts.get(key)- buckets = group.counts if group is not None else result.zero_counts()- current_breached, *prior_windows_breached = _derive_breaches(+ truncated = len(result.groups) >= limit++ def observe(key: str, buckets: list[BucketedCount], labels: dict[str, str]) -> GroupObservation:+ current_breached, *prior_breached = _derive_breaches(buckets, condition.threshold_count, condition.threshold_operator, check.evaluation_periods) or (False,)- # The machine alone, without `_verdict`'s metrics, so a quiet group left out below counts nothing.- outcome = evaluate_alert_check(- _snapshot(check, tuple(prior_windows_breached), key),- CheckInput(threshold_breached=current_breached, muted=muted),- now,- policy=PLATFORM_LOGS_ALERT_POLICY,- )- decided_nothing = (- outcome.new_state == AlertState.NOT_FIRING- and outcome.notification == NotificationAction.NONE- and outcome.muted_notification == NotificationAction.NONE+ return GroupObservation(+ grouping_key=key,+ current_breached=current_breached,+ prior_breached=tuple(prior_breached),+ value=float(buckets[-1].count) if buckets else 0.0,+ labels=labels,)- if decided_nothing and key not in existing:- continue++ def absent(key: str) -> GroupObservation | None:+ labels = _labels_of(key)+ if truncated and labels is None:+ return None+ return observe(key, result.zero_counts(), labels or {})++ decision = decide_groups(+ check,+ [observe(key, group.counts, group.labels) for key, group in counts.items()],+ snapshot_of=lambda instance, prior: _snapshot(check, prior, instance),+ policy=PLATFORM_LOGS_ALERT_POLICY,+ now=now,+ muted=muted,+ absent=absent,+ )+ for index, verdict in enumerate(decision.verdicts):_record_check_metrics(check,- new_state=outcome.new_state.value,- notification=outcome.notification,- muted_notification=outcome.muted_notification,+ new_state=verdict.group.new_state,+ notification=verdict.outcome.notification,+ muted_notification=verdict.outcome.muted_notification,muted_by_quiet_hours=muted,now=now,- grouping_key=key,- )- verdicts.append(- _GroupVerdict(- grouping_key=key,- labels=group.labels if group is not None else (_labels_of(key) or {}),- outcome=outcome,- value=float(buckets[-1].count) if buckets else 0.0,- )+ grouping_key=verdict.group.grouping_key,+ record_lag=index == 0,)-- # Firing verdicts first, so a cap keeps the groups that announce something.- verdicts.sort(key=lambda verdict: verdict.outcome.new_state == AlertState.NOT_FIRING)- admission = check.admit([verdict.grouping_key for verdict in verdicts])- admitted = [verdict for verdict in verdicts if verdict.grouping_key in set(admission.admitted)]- recorded = PlatformAlertOutcome(+ recorded = decision.as_outcome(configuration_id=check.id,evaluation_key=_evaluation_key(check, date_to),- consecutive_failures=0,- groups=tuple(- GroupOutcome(- grouping_key=verdict.grouping_key,- kind=NOTIFICATION_EVENT_KINDS[verdict.outcome.notification],- new_state=verdict.outcome.new_state.value,- notified=verdict.outcome.update_last_notified_at,- firing_episode=decide_firing_episode(- _snapshot(check, (), verdict.grouping_key),- verdict.outcome,- now,- policy=PLATFORM_LOGS_ALERT_POLICY,- ),- value=verdict.value,- labels=verdict.labels,- muted_notification=(- ""- if verdict.outcome.muted_notification == NotificationAction.NONE- else verdict.outcome.muted_notification.value- ),- )- for verdict in admitted- ),query_duration_ms=result.query_duration_ms,)- return recorded, _grouped_request(check, recorded, admitted, overflowed=admission.overflowed)---def _grouped_request(- check: PlatformAlertCheckInput,- recorded: PlatformAlertOutcome,- admitted: Sequence[_GroupVerdict],- *,- overflowed: int,-) -> AlertDeliveryRequest | None:- destination_alert_id = str(check.legacy_configuration_id or check.id)- actions = {- verdict.grouping_key: action- for verdict in admitted- if (- action := decide_incident_action(- AlertState(check.instance(verdict.grouping_key).state),- verdict.outcome.new_state,- policy=PLATFORM_LOGS_ALERT_POLICY,- )- )- is not None- }- if actions and not _has_incident_destination(check.team_id, destination_alert_id):- actions = {}- sends_messages = any(verdict.outcome.notification != NotificationAction.NONE for verdict in admitted)- if not sends_messages and not actions:- return None- return AlertDeliveryRequest(- source=SourceKind.LOGS,- team_id=check.team_id,- configuration_id=str(check.id),- evaluation_key=recorded.evaluation_key,- destination_alert_id=destination_alert_id,- event_ids_by_kind=_EVENT_IDS_BY_KIND,- event_ids_by_incident_action=_EVENT_IDS_BY_INCIDENT_ACTION,- incident_actions=actions,- sends_messages=sends_messages,- overflowed=overflowed,+ return recorded, _request(+ check,+ recorded,+ {+ verdict.group.grouping_key: _Move(before=verdict.snapshot.state, after=verdict.outcome.new_state)+ for verdict in decision.verdicts+ },+ sends_messages=any(verdict.outcome.notification != NotificationAction.NONE for verdict in decision.verdicts),)