Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(alerts): give every check an outcome and mute instead of skipping (#103180)

Jimmy Zhub21c83ad223d
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index 1955c348c378..b00ddda87db2 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -253,7 +253,60 @@ Going to the shared machine directly keeps the platform's lifecycle out of a sou
It evaluates against the tick cutoff rather than the clock, so a retried attempt selects the same alerts,
resolves the same windows and derives the same evaluation keys as the attempt it replaced.
The due predicate is applied a second time here, because discovery ran earlier in the tick and a configuration
-can have been disabled, snoozed or broken since.
+can have been disabled or broken since.
+
+### Every check produces an outcome
+
+A check the source cannot evaluate still records what it decided, and the two cases decide differently.
+
+| Case | State | Schedule |
+| ------------------------------- | --------------------------------------- | ---------------------------------------------------------- |
+| Filter config no data satisfies | BROKEN | The next cadence step, though discovery stops selecting it |
+| Query failed | The shared machine's error path decides | The next cadence step |
+
+A skip that records nothing leaves its due time where it was, so discovery hands the same check back every tick.
+That is the whole reason these exist: the work is not lost, it is repeated, and a permanently broken alert repeats it forever.
+The source reports the skip; the platform stays the only writer of `next_check_at`.
+
+The failure case goes through `evaluate_alert_check` with an errored `CheckInput`, so the shared machine raises
+`consecutive_failures` and escalates to BROKEN at five, and `classify_alert_error` decides whether the error is
+transient. A transient error advances the schedule but holds the counter, because a cluster outage must not
+disable every alert that ran during it.
+
+`suppressed` is the single definition of what holds a configuration back, and it is BROKEN alone.
+Both `discover_demand` and `due_checks` exclude on it. Discovery has to, because a broken alert that still mints
+a batch key spends the manifest bound on work its own evaluation then drops.
+It is one correlated `Exists` rather than a lookup across the relation: Django splits an excluded multi-valued
+lookup into a subquery per leaf, which would let the conditions match different alert rows once a source writes
+a real grouping key, and would bury them where Postgres cannot lift them into an anti-join.
+
+`alerts_platform_checks_skipped_total{source,reason}` counts these by reason.
+
+### A mute holds the announcement, not the check
+
+A snooze and a schedule restriction both mute. Neither stops a check.
+The alert evaluates on its cadence, transitions as its data says, and records what happened; only the
+announcement is held. `enabled=False` and BROKEN are the only states that stop a check.
+
+This is how a muted alert keeps telling the truth. Under the older behavior an incident that started and ended
+inside a quiet-hours window left no trace at all, and the alert's state stayed at whatever the last check before
+the window decided.
+
+The semantics arrive as `AlertPolicy.mute_gates_notification_only`, which the platform's
+`PLATFORM_LOGS_ALERT_POLICY` sets and production logs does not. The two stacks therefore disagree about a muted
+alert on purpose, and a comparison against the logs stack has to expect it.
+
+Three consequences worth stating:
+
+- `update_last_notified_at` is held with the announcement, so the cooldown keeps measuring real notifications.
+ An alert is never gated by a send that did not happen.
+- A mute holds FIRE and RESOLVE only. ERROR and BROKEN describe the alert's health rather than its condition,
+ and BROKEN stops future checks, so an announcement held there would never be released.
+- `next_check_at` stays on the cadence through a blocked window. Parking it at the end of the window is what the
+ older skip behavior did, and it also made every restricted alert for a team come due in the same minute.
+
+`AlertCheckOutcome.muted_notification` carries what was held, and
+`alerts_platform_notifications_muted_total{source,reason}` counts it by `snooze` or `quiet_hours`.
### Evaluating and writing are separate activities
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index a06a3a6a7ae4..c009054f470b 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -138,9 +138,32 @@ class PlatformAlertUpsert:
snooze_until: datetime | None
+class SkipReason(StrEnum):
+ """Why a check reached an outcome without a query answering it.
+
+ A label on the platform's own counters. It never reaches an alert's state or schedule. A check
+ that was evaluated has no skip reason, which is `None` rather than a member here.
+ """
+
+ BROKEN_CONFIG = "broken_config"
+ QUERY_FAILED = "query_failed"
+
+
+class MuteReason(StrEnum):
+ """Why an announcement was held. A muted check is evaluated like any other, so this labels the
+ held announcement rather than a skip."""
+
+ SNOOZE = "snooze"
+ QUIET_HOURS = "quiet_hours"
+
+
@frozen
class PlatformAlertOutcome:
- """What one check decided. The platform turns this into rows."""
+ """What one check decided. The platform turns this into rows.
+
+ Every check produces one, including a check a source skipped. A skip that records nothing
+ leaves its due time where it was, so discovery finds the same work every tick.
+ """
configuration_id: UUID
new_state: str
diff --git a/products/alerts/backend/facade/lifecycle.py b/products/alerts/backend/facade/lifecycle.py
index bb5776bd330e..d154b8702b6b 100644
--- a/products/alerts/backend/facade/lifecycle.py
+++ b/products/alerts/backend/facade/lifecycle.py
@@ -20,7 +20,7 @@ see `.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml`).
from __future__ import annotations
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from datetime import datetime, timedelta
from enum import Enum, StrEnum
from typing import Protocol
@@ -84,10 +84,17 @@ class AlertPolicy:
clear_check_ends_snooze: bool = False
# True: reaching BROKEN also disables the alert (outcome.disable is set).
disable_when_broken: bool = False
+ # True: a mute holds the announcement and the check still runs, so `enabled=False` and
+ # BROKEN become the only states that stop one.
+ mute_gates_notification_only: bool = False
LOGS_ALERT_POLICY = AlertPolicy()
+# Two constants rather than one changed default, because production logs keeps its own mute
+# semantics until it migrates.
+PLATFORM_LOGS_ALERT_POLICY = replace(LOGS_ALERT_POLICY, mute_gates_notification_only=True)
+
BILLING_ALERT_POLICY = AlertPolicy(
broken_is_terminal=False,
transient_errors_count_toward_broken=True,
@@ -110,6 +117,10 @@ class CheckInput:
is_inconclusive: bool = False
error_message: str | None = None
is_transient_error: bool = False
+ # A mute the machine cannot see for itself, such as a schedule restriction the source
+ # resolves against the team's timezone. Read only under `mute_gates_notification_only`, so a
+ # source that sets it against another policy is silently unmuted.
+ muted: bool = False
@dataclass(frozen=True)
@@ -147,6 +158,8 @@ class AlertCheckOutcome:
error_message: str | None
# Set when policy.disable_when_broken kicks in — the adapter must persist enabled=False.
disable: bool = False
+ # What a mute held back, so a muted fire is distinguishable from a check that said nothing.
+ muted_notification: NotificationAction = NotificationAction.NONE
@dataclass(frozen=True)
@@ -174,6 +187,26 @@ def _stay(snapshot: AlertSnapshot) -> AlertCheckOutcome:
)
+# A mute is about the alert's condition, not its health.
+_MUTABLE_NOTIFICATIONS = frozenset({NotificationAction.FIRE, NotificationAction.RESOLVE})
+
+
+def _muted(outcome: AlertCheckOutcome) -> AlertCheckOutcome:
+ """Holds an announcement without changing what the check decided.
+
+ `update_last_notified_at` is held with it, so the cooldown keeps measuring real
+ notifications and an unmuted alert is not gated by a send that never happened.
+ """
+ if outcome.notification not in _MUTABLE_NOTIFICATIONS:
+ return outcome
+ return replace(
+ outcome,
+ notification=NotificationAction.NONE,
+ update_last_notified_at=False,
+ muted_notification=outcome.notification,
+ )
+
+
def evaluate_alert_check(
snapshot: AlertSnapshot,
check: CheckInput,
@@ -190,6 +223,10 @@ def evaluate_alert_check(
suppresses evaluation when state is also SNOOZED — adopters must set both
together on snooze (as logs' apply_snooze path does); a stray future
`snooze_until` on a non-SNOOZED alert is not honored here.
+
+ Under `mute_gates_notification_only` a future `snooze_until` needs no companion state,
+ because it no longer decides whether the check runs. The check runs either way and the
+ announcement is held.
"""
if snapshot.state == AlertState.BROKEN and policy.broken_is_terminal:
# Terminal until a user reset — schedulers already exclude BROKEN alerts,
@@ -198,10 +235,17 @@ def evaluate_alert_check(
snoozing = snapshot.snooze_until is not None and snapshot.snooze_until > now
- if snapshot.state == AlertState.SNOOZED and snoozing and not policy.clear_check_ends_snooze:
- return _stay(snapshot)
+ if policy.mute_gates_notification_only:
+ muted = snoozing or check.muted
+ else:
+ muted = False
+ if snapshot.state == AlertState.SNOOZED and snoozing and not policy.clear_check_ends_snooze:
+ return _stay(snapshot)
if check.error_message is not None:
+ # Not muted: a failure announces ERROR or BROKEN, which describe the alert's health rather
+ # than its condition, and BROKEN stops further checks so a held announcement would never
+ # be released.
return evaluate_alert_failure(
snapshot,
error_message=check.error_message,
@@ -278,13 +322,14 @@ def evaluate_alert_check(
else:
update_last_notified_at = True
- return AlertCheckOutcome(
+ outcome = AlertCheckOutcome(
new_state=new_state,
notification=notification,
consecutive_failures=0,
update_last_notified_at=update_last_notified_at,
error_message=None,
)
+ return _muted(outcome) if muted else outcome
def evaluate_alert_failure(
@@ -351,6 +396,18 @@ def apply_user_reset(snapshot: StatefulSnapshot) -> ControlPlaneOutcome:
return ControlPlaneOutcome(new_state=AlertState.NOT_FIRING, consecutive_failures=0)
+def apply_broken_config(snapshot: StatefulSnapshot) -> ControlPlaneOutcome:
+ """A configuration that cannot be evaluated at all, whatever the data says.
+
+ The failure counter survives, because it records checks that ran and failed. A user who
+ fixes the configuration resets it through `apply_user_reset`.
+ """
+ return ControlPlaneOutcome(
+ new_state=AlertState.BROKEN,
+ consecutive_failures=snapshot.consecutive_failures,
+ )
+
+
def apply_disable(snapshot: StatefulSnapshot) -> ControlPlaneOutcome:
# Preserve consecutive_failures so re-enable without reset doesn't silently
# wipe forensic state.
diff --git a/products/alerts/backend/facade/platform_metrics.py b/products/alerts/backend/facade/platform_metrics.py
index d0a72413c620..87c4b72bea28 100644
--- a/products/alerts/backend/facade/platform_metrics.py
+++ b/products/alerts/backend/facade/platform_metrics.py
@@ -7,7 +7,9 @@ from `facade/temporal.py`, which pulls in the workflow module.
from products.alerts.backend.temporal.metrics import (
increment_checks,
+ increment_checks_skipped,
increment_deliveries_deferred,
+ increment_notifications_muted,
increment_state_transition,
record_batch_duration,
record_scheduler_lag,
@@ -16,7 +18,9 @@ from products.alerts.backend.temporal.metrics import (
__all__ = [
"increment_checks",
+ "increment_checks_skipped",
"increment_deliveries_deferred",
+ "increment_notifications_muted",
"increment_state_transition",
"record_batch_duration",
"record_scheduler_lag",
diff --git a/products/alerts/backend/facade/scheduling.py b/products/alerts/backend/facade/scheduling.py
index 4b59b0ad59e6..eb304cf7eda0 100644
--- a/products/alerts/backend/facade/scheduling.py
+++ b/products/alerts/backend/facade/scheduling.py
@@ -520,12 +520,16 @@ def _minute_of_local_datetime(dt_local: datetime) -> int:
return dt_local.hour * 60 + dt_local.minute
+def local_minute_of(dt_utc: datetime, tz_name: str) -> int:
+ """The minute of the local day, for a caller testing many windows against one instant."""
+ local = dt_utc.astimezone(pytz.timezone(tz_name)).replace(second=0, microsecond=0)
+ return _minute_of_local_datetime(local)
+
+
def is_utc_datetime_blocked(dt_utc: datetime, tz_name: str, windows: list[BlockedWindow] | None) -> bool:
if not windows:
return False
- tz = pytz.timezone(tz_name)
- local = dt_utc.astimezone(tz).replace(second=0, microsecond=0)
- return is_local_minute_blocked(_minute_of_local_datetime(local), windows)
+ return is_local_minute_blocked(local_minute_of(dt_utc, tz_name), windows)
def scan_next_unblocked_utc(
diff --git a/products/alerts/backend/logic/demand.py b/products/alerts/backend/logic/demand.py
index 70134b8c902e..abf8f94f7714 100644
--- a/products/alerts/backend/logic/demand.py
+++ b/products/alerts/backend/logic/demand.py
@@ -1,9 +1,7 @@
import datetime as dt
-from django.db.models import Q
-
from products.alerts.backend.facade.contracts import AlertBatchKey, AlertDemand, SourceKind
-from products.alerts.backend.logic.platform_lifecycle import slot_of
+from products.alerts.backend.logic.platform_lifecycle import due_q, slot_of, suppressed
from products.alerts.backend.models import PlatformAlertConfiguration
# Keys per source in one manifest. A key is a team id and a minute, so unlike an id list it does not
@@ -23,7 +21,11 @@ def discover_demand(cutoff: str, limit_per_source: int = DISCOVERY_LIMIT_PER_SOU
# later tick; any stable ordering that is not by due time starves the same keys every tick.
due = (
PlatformAlertConfiguration.objects.unscoped()
- .filter(Q(enabled=True) & (Q(next_check_at__lte=cutoff_time) | Q(next_check_at__isnull=True)))
+ .filter(enabled=True)
+ .filter(due_q(cutoff_time))
+ # A broken or snoozed alert would otherwise mint a key every tick that its own evaluation
+ # then drops.
+ .exclude(suppressed())
.order_by("next_check_at", "id")
.values_list("source_kind", "team_id", "next_check_at")
)
diff --git a/products/alerts/backend/logic/platform_lifecycle.py b/products/alerts/backend/logic/platform_lifecycle.py
index 39f2d125e929..400b4c04ce2c 100644
--- a/products/alerts/backend/logic/platform_lifecycle.py
+++ b/products/alerts/backend/logic/platform_lifecycle.py
@@ -8,16 +8,10 @@ from collections.abc import Sequence
from datetime import datetime
from django.db import transaction
-from django.db.models import Q
-from django.utils import timezone
+from django.db.models import Exists, OuterRef, Q
from products.alerts.backend.facade.contracts import PlatformAlertCheck, PlatformAlertOutcome, PlatformAlertUpsert
-from products.alerts.backend.facade.scheduling import (
- advance_next_check_at,
- compute_shard_offset_seconds,
- parse_blocked_windows_tuples,
- scan_next_unblocked_utc,
-)
+from products.alerts.backend.facade.scheduling import advance_next_check_at, compute_shard_offset_seconds
from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration
@@ -56,12 +50,38 @@ def _alerts_for_write(team_id: int, configurations: Sequence[PlatformAlertConfig
return existing
+def suppressed() -> Exists:
+ """Configurations a runtime state holds back.
+
+ BROKEN only. A mute holds an announcement rather than a check, so a snoozed alert is
+ discovered and evaluated like any other and its state keeps tracking reality.
+
+ The state lives on `PlatformAlert`, so discovery and the batch read both reach for this
+ rather than each writing the predicate out. If the two disagreed, a broken alert would be
+ dispatched by one and dropped by the other, every tick, in silence.
+
+ Excluded as one `Exists` rather than as a lookup across the relation. Django splits an
+ excluded multi-valued lookup into a subquery per leaf, which lets the conditions match
+ different alert rows once a source writes a real grouping key, and buries them where
+ Postgres cannot lift them into an anti-join.
+ """
+ # `unscoped` because the subquery runs without ambient scope in both callers, and it is
+ # correlated to a configuration the outer query has already scoped, so the foreign key keeps
+ # it inside that team.
+ return Exists(
+ PlatformAlert.objects.unscoped().filter(
+ configuration=OuterRef("pk"), grouping_key="", state=PlatformAlert.State.BROKEN
+ )
+ )
+
+
def due_checks(team_id: int, source_kind: str, slot: str, cutoff: datetime) -> tuple[PlatformAlertCheck, ...]:
"""Every configuration in one batch key, with its runtime state, ready to evaluate."""
configurations = list(
PlatformAlertConfiguration.objects.for_team(team_id)
.filter(enabled=True, source_kind=source_kind)
.filter(due_q(cutoff))
+ .exclude(suppressed())
# Ordered so a retried attempt keeps the same alerts under any downstream cap.
.order_by("id")
)
@@ -106,15 +126,14 @@ def slot_of(next_check_at: datetime | None, cutoff: datetime) -> str:
return (next_check_at or cutoff).replace(second=0, microsecond=0).isoformat()
-def record_outcomes(
- team_id: int, outcomes: Sequence[PlatformAlertOutcome], now: datetime, *, team_timezone: str
-) -> int:
+def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now: datetime) -> int:
"""Persists a batch's decisions and advances each configuration's schedule.
Two statements rather than two per alert, in one transaction, so a crash between them cannot
leave an alert marked as notified while its schedule still says the check is due. The schedule
- advances the way the source's own stack advances it: sharded across the cadence so a fleet does
- not converge on one minute, then pushed past any blocked window.
+ advances the way the source's own stack advances it, sharded across the cadence so a fleet does
+ not converge on one minute. A schedule restriction does not move it, because a restricted check
+ still runs and only its announcement is held.
Safe to run twice on the same batch. An attempt that commits leaves every configuration due
after `now`, and a replay of that attempt skips those rows rather than advancing them a second
@@ -144,7 +163,7 @@ def record_outcomes(
configuration.consecutive_failures = outcome.consecutive_failures
if outcome.disable:
configuration.enabled = False
- next_check_at = advance_next_check_at(
+ configuration.next_check_at = advance_next_check_at(
configuration.next_check_at,
configuration.check_interval_minutes,
now,
@@ -152,10 +171,6 @@ def record_outcomes(
configuration.id, configuration.check_interval_minutes
),
)
- windows = parse_blocked_windows_tuples(configuration.schedule_restriction)
- configuration.next_check_at = (
- scan_next_unblocked_utc(next_check_at, team_timezone, windows) or next_check_at
- )
PlatformAlert.objects.for_team(team_id).bulk_update(list(alerts.values()), ["state", "last_notified_at"])
PlatformAlertConfiguration.objects.for_team(team_id).bulk_update(
@@ -190,11 +205,7 @@ def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
},
)
alert = _alerts_for_write(upsert.team_id, [configuration])[str(configuration.id)]
- # Logs-style evaluation honors `snooze_until` only while the state is SNOOZED.
- if upsert.snooze_until is not None and upsert.snooze_until > timezone.now():
- alert.state = PlatformAlert.State.SNOOZED
- elif alert.state == PlatformAlert.State.SNOOZED:
- alert.state = PlatformAlert.State.NOT_FIRING
+ # State is left alone because a muted alert keeps tracking reality.
alert.snooze_until = upsert.snooze_until
- alert.save(update_fields=["state", "snooze_until"])
+ alert.save(update_fields=["snooze_until"])
return created
diff --git a/products/alerts/backend/temporal/metrics.py b/products/alerts/backend/temporal/metrics.py
index b0c583582efe..39abbe6d5b68 100644
--- a/products/alerts/backend/temporal/metrics.py
+++ b/products/alerts/backend/temporal/metrics.py
@@ -48,6 +48,30 @@ def increment_checks(source: str, outcome: str) -> None:
).add(1)
+def increment_checks_skipped(source: str, reason: str) -> None:
+ """Checks that reached an outcome without a query answering them.
+
+ A rising reason means the platform is spending ticks on work it cannot do: a blocked window,
+ a configuration no data satisfies, or a query that keeps failing.
+ """
+ get_metric_meter({"source": source, "reason": reason}).create_counter(
+ "alerts_platform_checks_skipped_total",
+ "Checks decided without an evaluation, by reason",
+ ).add(1)
+
+
+def increment_notifications_muted(source: str, reason: str) -> None:
+ """Announcements a mute held back.
+
+ The alert still transitioned, so this is the only signal that a person was not told. A
+ rising count with no matching unmute announcement means mutes are swallowing alerts.
+ """
+ get_metric_meter({"source": source, "reason": reason}).create_counter(
+ "alerts_platform_notifications_muted_total",
+ "Announcements held by a mute, by reason",
+ ).add(1)
+
+
def increment_state_transition(source: str, from_state: str, to_state: str) -> None:
get_metric_meter({"source": source, "from": from_state, "to": to_state}).create_counter(
"alerts_platform_state_transitions_total",
diff --git a/products/alerts/backend/temporal/outcomes.py b/products/alerts/backend/temporal/outcomes.py
index 75e27a2e6165..68921cd6847d 100644
--- a/products/alerts/backend/temporal/outcomes.py
+++ b/products/alerts/backend/temporal/outcomes.py
@@ -22,7 +22,6 @@ async def alerts_platform_record_outcomes_activity(inputs: SourceOutcomeInputs)
"""Records one batch's decisions. Returns how many reached the tables."""
# Imported in the activity body, not at module scope: a Django model import trips Temporal's
# workflow sandbox, and the worker registration that reaches this module runs through one.
- from posthog.models import Team
from posthog.sync import database_sync_to_async_pool
from products.alerts.backend.facade.platform_alerts import record_outcomes
@@ -31,15 +30,7 @@ async def alerts_platform_record_outcomes_activity(inputs: SourceOutcomeInputs)
return 0
def _record() -> int:
- timezone = Team.objects.filter(id=inputs.team_id).values_list("timezone", flat=True).first()
- if timezone is None:
- return 0
- return record_outcomes(
- inputs.team_id,
- inputs.outcomes,
- dt.datetime.fromisoformat(inputs.cutoff),
- team_timezone=timezone,
- )
+ return record_outcomes(inputs.team_id, inputs.outcomes, dt.datetime.fromisoformat(inputs.cutoff))
recorded = await database_sync_to_async_pool(_record)()
safe_record(increment_outcomes_recorded, recorded)
diff --git a/products/alerts/backend/test/test_platform_lifecycle.py b/products/alerts/backend/test/test_platform_lifecycle.py
index d4fc7685b3e3..3b17f2408fe9 100644
--- a/products/alerts/backend/test/test_platform_lifecycle.py
+++ b/products/alerts/backend/test/test_platform_lifecycle.py
@@ -37,7 +37,7 @@ class TestPlatformAlertLifecycle(APIBaseTest):
"consecutive_failures": 0,
}
fields.update(overrides)
- record_outcomes(self.team.id, [PlatformAlertOutcome(**fields)], self.cutoff, team_timezone=self.team.timezone)
+ record_outcomes(self.team.id, [PlatformAlertOutcome(**fields)], self.cutoff)
def test_a_disabling_outcome_stops_the_configuration_being_discovered(self) -> None:
self._record(new_state="broken", notified=False, consecutive_failures=5, disable=True)
@@ -60,7 +60,7 @@ class TestPlatformAlertLifecycle(APIBaseTest):
self.configuration.refresh_from_db()
assert self.configuration.next_check_at == after_first
- def test_a_copied_snooze_reaches_the_check_and_a_later_unsnooze_clears_it(self) -> None:
+ def test_a_copied_snooze_mutes_without_holding_back_the_check(self) -> None:
legacy_id = uuid4()
snoozed_until = self.cutoff + timedelta(hours=2)
@@ -96,13 +96,13 @@ class TestPlatformAlertLifecycle(APIBaseTest):
with time_machine.travel(self.cutoff, tick=False):
copy(snoozed_until)
- assert snooze_seen_by_check() == ("snoozed", snoozed_until)
-
- copy(None)
- assert snooze_seen_by_check() == ("not_firing", None)
+ assert snooze_seen_by_check() == ("not_firing", snoozed_until)
with team_scope(self.team.id):
PlatformAlert.objects.filter(configuration__legacy_configuration_id=legacy_id).update(state="firing")
- expired = self.cutoff - timedelta(hours=1)
- copy(expired)
- assert snooze_seen_by_check() == ("firing", expired)
+ with time_machine.travel(self.cutoff, tick=False):
+ copy(snoozed_until)
+ assert snooze_seen_by_check() == ("firing", snoozed_until)
+
+ copy(None)
+ assert snooze_seen_by_check() == ("firing", None)
diff --git a/products/alerts/backend/test/test_state_machine.py b/products/alerts/backend/test/test_state_machine.py
index 6c9c49b95ddc..b4ac435aa82a 100644
--- a/products/alerts/backend/test/test_state_machine.py
+++ b/products/alerts/backend/test/test_state_machine.py
@@ -4,6 +4,7 @@ from parameterized import parameterized
from products.alerts.backend.facade.lifecycle import (
LOGS_ALERT_POLICY,
+ PLATFORM_LOGS_ALERT_POLICY,
AlertCheckOutcome,
AlertPolicy,
AlertSnapshot,
@@ -248,6 +249,66 @@ class TestPolicyDecisionTable:
assert outcome.new_state == expected_state
assert outcome.notification == expected_notification
+ @parameterized.expand(
+ [
+ (
+ "snooze_mutes_a_fire",
+ snapshot(snooze_until=SNOOZING),
+ BREACH,
+ AlertState.FIRING,
+ NotificationAction.NONE,
+ NotificationAction.FIRE,
+ ),
+ (
+ "quiet_hours_mutes_a_fire",
+ snapshot(),
+ CheckInput(threshold_breached=True, muted=True),
+ AlertState.FIRING,
+ NotificationAction.NONE,
+ NotificationAction.FIRE,
+ ),
+ (
+ "snooze_mutes_a_resolve",
+ snapshot(state=AlertState.FIRING, snooze_until=SNOOZING, cooldown=timedelta(0)),
+ CLEAR,
+ AlertState.NOT_FIRING,
+ NotificationAction.NONE,
+ NotificationAction.RESOLVE,
+ ),
+ (
+ "a_mute_does_not_hold_an_error",
+ snapshot(snooze_until=SNOOZING),
+ ERROR,
+ AlertState.NOT_FIRING,
+ NotificationAction.ERROR,
+ NotificationAction.NONE,
+ ),
+ (
+ "an_unmuted_check_still_announces",
+ snapshot(),
+ BREACH,
+ AlertState.FIRING,
+ NotificationAction.FIRE,
+ NotificationAction.NONE,
+ ),
+ ]
+ )
+ def test_a_mute_holds_the_announcement_without_changing_the_transition(
+ self,
+ _name: str,
+ snap: AlertSnapshot,
+ check: CheckInput,
+ expected_state: AlertState,
+ expected_notification: NotificationAction,
+ expected_muted: NotificationAction,
+ ) -> None:
+ outcome = evaluate_alert_check(snap, check, NOW, policy=PLATFORM_LOGS_ALERT_POLICY)
+ assert outcome.new_state == expected_state
+ assert outcome.notification == expected_notification
+ assert outcome.muted_notification == expected_muted
+ if expected_muted is not NotificationAction.NONE:
+ assert outcome.update_last_notified_at is False
+
def test_inconclusive_preserves_failure_counter(self) -> None:
outcome = evaluate_alert_check(
snapshot(state=AlertState.ERRORED, consecutive_failures=3), INCONCLUSIVE, NOW, policy=LOGS_ALERT_POLICY
diff --git a/products/alerts/backend/tests/test_temporal_workflows.py b/products/alerts/backend/tests/test_temporal_workflows.py
index 38e67ef991d5..f03b8635686b 100644
--- a/products/alerts/backend/tests/test_temporal_workflows.py
+++ b/products/alerts/backend/tests/test_temporal_workflows.py
@@ -53,7 +53,7 @@ from products.alerts.backend.facade.temporal import (
AlertsPlatformTelemetryInterceptor,
)
from products.alerts.backend.logic import demand
-from products.alerts.backend.models import PlatformAlertConfiguration
+from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration
from products.alerts.backend.temporal import postgres
from products.alerts.backend.temporal.workflows import (
AlertsPlatformEvaluateWorkflow,
@@ -451,14 +451,39 @@ class TestDemandDiscovery(APIBaseTest):
def _key(self, minutes_ago: int) -> AlertBatchKey:
return AlertBatchKey(team_id=self.team.id, slot=(self.tick - dt.timedelta(minutes=minutes_ago)).isoformat())
- def test_only_enabled_and_due_configurations_become_keys(self) -> None:
+ def _alert(
+ self, configuration, *, state: str, snooze_until: dt.datetime | None = None, grouping_key: str = ""
+ ) -> None:
+ with team_scope(self.team.id):
+ PlatformAlert.objects.create(
+ team=self.team,
+ configuration=configuration,
+ grouping_key=grouping_key,
+ state=state,
+ snooze_until=snooze_until,
+ )
+
+ def test_only_enabled_due_and_unbroken_configurations_become_keys(self) -> None:
self._configuration(minutes_ago=1, name="due")
self._configuration(minutes_ago=-1, name="not yet due")
self._configuration(minutes_ago=1, enabled=False, name="disabled")
+ self._alert(self._configuration(minutes_ago=2, name="broken"), state=PlatformAlert.State.BROKEN)
+ # Excluding a muted alert here would stop its state tracking reality for the whole snooze.
+ self._alert(
+ self._configuration(minutes_ago=3, name="snoozed"),
+ state=PlatformAlert.State.NOT_FIRING,
+ snooze_until=self.tick + dt.timedelta(hours=1),
+ )
+ # Two rows on one configuration, neither suppressing on its own. Written as a lookup across
+ # the relation instead of one correlated subquery, the empty group and the broken state match
+ # different rows and this configuration silently stops being checked.
+ grouped = self._configuration(minutes_ago=4, name="broken in one group only")
+ self._alert(grouped, state=PlatformAlert.State.NOT_FIRING)
+ self._alert(grouped, state=PlatformAlert.State.BROKEN, grouping_key="/api/checkout")
discovered = demand.discover_demand(self.tick.isoformat())
- assert discovered.batch_keys_by_source == {SourceKind.LOGS: [self._key(1)]}
+ assert discovered.batch_keys_by_source == {SourceKind.LOGS: [self._key(4), self._key(3), self._key(1)]}
def test_configurations_due_in_one_minute_share_one_key(self) -> None:
self._configuration(minutes_ago=1, name="first")
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 33e910199a9a..80c7de8d1480 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -18,37 +18,47 @@ import time
from collections.abc import Sequence
from datetime import datetime, timedelta
from itertools import batched
+from uuid import UUID
import structlog
+from posthog.dataclasses import frozen
from posthog.models import Team
from products.alerts.backend.facade.contracts import (
AlertDeliveryPreview,
GroupTransition,
+ MuteReason,
PlatformAlertCheck,
PlatformAlertOutcome,
+ SkipReason,
SourceBatchEvaluation,
SourceKind,
)
from products.alerts.backend.facade.destinations import list_active_alert_destinations
from products.alerts.backend.facade.lifecycle import (
- LOGS_ALERT_POLICY,
+ PLATFORM_LOGS_ALERT_POLICY,
+ AlertCheckOutcome,
AlertSnapshot,
AlertState,
CheckInput,
+ ControlPlaneOutcome,
NotificationAction,
+ apply_broken_config,
evaluate_alert_check,
)
from products.alerts.backend.facade.platform_alerts import due_checks
from products.alerts.backend.facade.platform_metrics import (
increment_checks,
+ increment_checks_skipped,
increment_deliveries_deferred,
+ increment_notifications_muted,
increment_state_transition,
record_batch_duration,
record_scheduler_lag,
safe_record,
)
+from products.alerts.backend.facade.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuples
from products.logs.backend.alert_check_query import (
BatchedAlertCheckQuery,
BucketedCount,
@@ -58,7 +68,7 @@ from products.logs.backend.alert_check_query import (
rolling_check_lookback_minutes,
)
from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EventKind
-from products.logs.backend.alert_utils import next_allowed_check_at
+from products.logs.backend.alert_error_classifier import classify as classify_alert_error
# Private to the production activity. Reimplementing either would let this path drift from
# what the logs stack evaluates. Promoting them to a shared home is the deeper fix.
@@ -104,15 +114,15 @@ def _cohort_key(check: PlatformAlertCheck, checkpoint: datetime | None, now: dat
)
-def _is_in_quiet_hours(check: PlatformAlertCheck, team: Team, now: datetime) -> bool:
- """True when the alert's schedule restriction blocks a check at `now`."""
+def _is_in_quiet_hours(check: PlatformAlertCheck, now: datetime, tz_name: str) -> bool:
+ """True when the alert's schedule restriction mutes an announcement at the batch instant.
+
+ The check still runs, so an incident wholly inside the window is still recorded.
+ """
if not check.schedule_restriction:
return False
try:
- return (
- next_allowed_check_at(now, team_timezone=team.timezone, schedule_restriction=check.schedule_restriction)
- > now
- )
+ return is_utc_datetime_blocked(now, tz_name, parse_blocked_windows_tuples(check.schedule_restriction))
except Exception as error:
# A restriction we cannot parse must not decide the alert either way, so the check
# proceeds and the production stack keeps ownership of the broken configuration.
@@ -135,35 +145,97 @@ def _snapshot(check: PlatformAlertCheck, prior_breached: tuple[bool, ...]) -> Al
)
-def _evaluate_one(
- check: PlatformAlertCheck, buckets: list[BucketedCount], *, window_end: datetime, now: datetime
-) -> tuple[PlatformAlertOutcome, AlertDeliveryPreview | None]:
- current_breached, *prior_windows_breached = _derive_breaches(
- buckets, check.threshold_count, check.threshold_operator, check.evaluation_periods
- ) or (False,)
+Decision = tuple[PlatformAlertOutcome, AlertDeliveryPreview | None]
+
+
+@frozen
+class _Triage:
+ """What a batch splits into before any query runs."""
+
+ decided: list[Decision]
+ evaluable: list[PlatformAlertCheck]
+ muted_ids: frozenset[UUID]
+
+
+def _record_check_metrics(
+ check: PlatformAlertCheck,
+ *,
+ new_state: str,
+ notification: NotificationAction,
+ muted_notification: NotificationAction = NotificationAction.NONE,
+ skip: SkipReason | None = None,
+ muted_by_quiet_hours: bool = False,
+ now: datetime,
+) -> None:
+ safe_record(increment_checks, SourceKind.LOGS.value, notification.value)
+ if skip is not None:
+ safe_record(increment_checks_skipped, SourceKind.LOGS.value, skip.value)
+ if muted_notification != NotificationAction.NONE:
+ # The machine owns the snooze predicate, so the source's flag is what separates the two.
+ mute_reason = MuteReason.QUIET_HOURS if muted_by_quiet_hours else MuteReason.SNOOZE
+ safe_record(increment_notifications_muted, SourceKind.LOGS.value, mute_reason.value)
+ if check.state != new_state:
+ safe_record(increment_state_transition, SourceKind.LOGS.value, check.state, new_state)
+ if 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)
+
- # `LOGS_ALERT_POLICY` is how the shared machine expresses this source's semantics, so the
- # decision is the one the logs stack reaches without routing through the logs product.
+def _verdict(
+ check: PlatformAlertCheck,
+ check_input: CheckInput,
+ prior_breached: tuple[bool, ...],
+ *,
+ now: datetime,
+ skip: SkipReason | None,
+) -> AlertCheckOutcome:
+ """Runs one check through the shared machine.
+
+ `PLATFORM_LOGS_ALERT_POLICY` is how the shared machine expresses this source's semantics. It
+ is the logs stack's lifecycle with one difference: a mute holds the announcement rather than
+ the check, so a snoozed or schedule-restricted alert still tracks reality.
+
+ Separate from `_delivery` because a caller that catches evaluation errors must not also
+ catch a destination lookup. A lookup failure would otherwise be recorded as a failed check
+ and raise the alert's failure counter, after a query that succeeded.
+ """
outcome = evaluate_alert_check(
- _snapshot(check, tuple(prior_windows_breached)),
- CheckInput(threshold_breached=current_breached),
- now,
- policy=LOGS_ALERT_POLICY,
+ _snapshot(check, prior_breached), check_input, now, policy=PLATFORM_LOGS_ALERT_POLICY
)
- recorded = PlatformAlertOutcome(
+ _record_check_metrics(
+ check,
+ new_state=outcome.new_state.value,
+ notification=outcome.notification,
+ muted_notification=outcome.muted_notification,
+ skip=skip,
+ muted_by_quiet_hours=check_input.muted,
+ now=now,
+ )
+ return outcome
+
+
+def _recorded(
+ check: PlatformAlertCheck, *, new_state: str, notified: bool, consecutive_failures: int, disable: bool = False
+) -> PlatformAlertOutcome:
+ return PlatformAlertOutcome(
configuration_id=check.id,
+ new_state=new_state,
+ notified=notified,
+ consecutive_failures=consecutive_failures,
+ disable=disable,
+ )
+
+
+def _delivery(check: PlatformAlertCheck, outcome: AlertCheckOutcome, *, window_end: datetime) -> Decision:
+ """What the platform records for a verdict, and what delivery would announce for it."""
+ recorded = _recorded(
+ check,
new_state=outcome.new_state.value,
notified=outcome.update_last_notified_at,
consecutive_failures=outcome.consecutive_failures,
disable=outcome.disable,
)
- safe_record(increment_checks, SourceKind.LOGS.value, outcome.notification.value)
- if check.state != outcome.new_state.value:
- safe_record(increment_state_transition, SourceKind.LOGS.value, check.state, outcome.new_state.value)
- if 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)
if outcome.notification == NotificationAction.NONE:
return recorded, None
@@ -185,9 +257,66 @@ def _evaluate_one(
)
+def _evaluate_one(
+ check: PlatformAlertCheck, buckets: list[BucketedCount], *, now: datetime, muted: bool
+) -> AlertCheckOutcome:
+ current_breached, *prior_windows_breached = _derive_breaches(
+ buckets, check.threshold_count, check.threshold_operator, check.evaluation_periods
+ ) or (False,)
+ return _verdict(
+ check,
+ CheckInput(threshold_breached=current_breached, muted=muted),
+ tuple(prior_windows_breached),
+ now=now,
+ skip=None,
+ )
+
+
+def _failed(check: PlatformAlertCheck, error: Exception, *, now: datetime, muted: bool) -> AlertCheckOutcome:
+ """A check that could not reach a verdict, as the shared machine's error path sees it.
+
+ The machine raises `consecutive_failures` and escalates to BROKEN, so an alert that fails
+ every check stops being evaluated instead of failing forever. A transient error is classified
+ as one so the policy can hold the counter.
+ """
+ classified = classify_alert_error(error)
+ return _verdict(
+ check,
+ CheckInput(
+ threshold_breached=False,
+ error_message=classified.user_message,
+ is_transient_error=classified.is_transient,
+ muted=muted,
+ ),
+ (),
+ now=now,
+ skip=SkipReason.QUERY_FAILED,
+ )
+
+
+def _held(check: PlatformAlertCheck, outcome: ControlPlaneOutcome, *, skip: SkipReason, now: datetime) -> Decision:
+ """A control-plane transition the check machine cannot express. The outcome advances the schedule."""
+ recorded = _recorded(
+ check,
+ new_state=outcome.new_state.value,
+ notified=False,
+ consecutive_failures=outcome.consecutive_failures,
+ )
+ _record_check_metrics(
+ check, new_state=outcome.new_state.value, notification=NotificationAction.NONE, skip=skip, now=now
+ )
+ return recorded, None
+
+
def _evaluate_cohort(
- team: Team, checks: Sequence[PlatformAlertCheck], key: tuple, *, now: datetime, query_seconds: int
-) -> list[tuple[PlatformAlertOutcome, AlertDeliveryPreview | None]]:
+ team: Team,
+ checks: Sequence[PlatformAlertCheck],
+ key: tuple,
+ *,
+ now: datetime,
+ query_seconds: int,
+ muted_ids: frozenset[UUID],
+) -> list[Decision]:
window_minutes, evaluation_periods, cadence_minutes, projection_eligible, date_to = key
lookback = rolling_check_lookback_minutes(window_minutes, cadence_minutes, evaluation_periods)
@@ -204,22 +333,94 @@ def _evaluate_cohort(
# One cohort's query must not end the batch, which is how the production cohort runner
# contains the same failure.
logger.exception(
- "Logs alert cohort query failed; skipping the cohort",
+ "Logs alert cohort query failed",
team_id=team.id,
cohort_size=len(checks),
error=str(error),
)
- return []
-
- decided: list[tuple[PlatformAlertOutcome, AlertDeliveryPreview | None]] = []
+ # Deliberately not caught per check below. A check dropped there carries no outcome, so the
+ # batch would advance every other check's schedule and leave this one due with its failure
+ # counter unmoved, never reaching the escalation that stops it.
+ return [
+ _delivery(check, _failed(check, error, now=now, muted=check.id in muted_ids), window_end=date_to)
+ for check in checks
+ ]
+
+ decided: list[Decision] = []
for check in checks:
+ muted = check.id in muted_ids
try:
- decided.append(_evaluate_one(check, result.per_alert.get(str(check.id), []), window_end=date_to, now=now))
+ outcome = _evaluate_one(check, result.per_alert.get(str(check.id), []), now=now, muted=muted)
except Exception as error:
- logger.exception("Failed to evaluate a logs alert; skipping it", check_id=str(check.id), error=str(error))
+ logger.exception("Failed to evaluate a logs alert", check_id=str(check.id), error=str(error))
+ outcome = _failed(check, error, now=now, muted=muted)
+ # Outside the block above on purpose. Resolving a destination reads the database, and a
+ # failure there is not this check's failure.
+ decided.append(_delivery(check, outcome, window_end=date_to))
return decided
+def _triage(checks: Sequence[PlatformAlertCheck], *, now: datetime, tz_name: str) -> _Triage:
+ """Splits a batch into the checks a query can answer, the ones already decided, and the muted.
+
+ A skip is a decision, not an omission. Dropping one records nothing, so its due time stays
+ where it was and discovery hands the same check back on the next tick, forever.
+
+ A schedule restriction decides nothing here. It mutes an announcement, so the check goes to the
+ query like any other and its id lands in the muted set.
+ """
+ decided: list[Decision] = []
+ evaluable: list[PlatformAlertCheck] = []
+ muted_ids: set[UUID] = set()
+ for check in checks:
+ broken_reason = _detect_broken_filter_config(check.source_config)
+ if broken_reason is not None:
+ logger.warning(
+ "Marking a logs alert BROKEN for an invalid filter config",
+ check_id=str(check.id),
+ reason=broken_reason,
+ )
+ decided.append(
+ _held(
+ check,
+ apply_broken_config(_snapshot(check, ())),
+ skip=SkipReason.BROKEN_CONFIG,
+ now=now,
+ )
+ )
+ continue
+ if _is_in_quiet_hours(check, now, tz_name):
+ muted_ids.add(check.id)
+ evaluable.append(check)
+ return _Triage(decided=decided, evaluable=evaluable, muted_ids=frozenset(muted_ids))
+
+
+def _collect(decided: Sequence[Decision], team_id: int, slot: str, started_at: float) -> SourceBatchEvaluation:
+ """Applies the payload bound and reports the batch."""
+ outcomes: list[PlatformAlertOutcome] = []
+ previews: list[AlertDeliveryPreview] = []
+ omitted = 0
+ for outcome, preview in decided:
+ if preview is not None and len(previews) >= MAX_PREVIEWS_PER_CYCLE:
+ omitted += 1
+ continue
+ outcomes.append(outcome)
+ if preview is not None:
+ previews.append(preview)
+
+ if omitted:
+ logger.warning(
+ "Deferred logs alert deliveries over the batch payload bound",
+ team_id=team_id,
+ slot=slot,
+ delivered=len(previews),
+ deferred=omitted,
+ )
+ safe_record(increment_deliveries_deferred, SourceKind.LOGS.value, omitted)
+ safe_record(record_batch_duration, SourceKind.LOGS.value, int((time.monotonic() - started_at) * 1000))
+ return SourceBatchEvaluation(outcomes=tuple(outcomes), previews=tuple(previews), omitted=omitted)
+
+
def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatchEvaluation:
"""Evaluates one batch key: a team's alerts due in one minute, against the tick's cutoff.
@@ -232,18 +433,18 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatc
"""
started_at = time.monotonic()
checks = due_checks(team_id, SourceKind.LOGS.value, slot, cutoff)
- # Production excludes a structurally broken filter before evaluating, so including one
- # would record a transition production would never record.
- checks = tuple(c for c in checks if _detect_broken_filter_config(c.source_config) is None)
if not checks:
return SourceBatchEvaluation(outcomes=(), previews=())
team = Team.objects.filter(id=team_id).first()
if team is None:
return SourceBatchEvaluation(outcomes=(), previews=())
- checks = tuple(c for c in checks if not _is_in_quiet_hours(c, team, cutoff))
- if not checks:
- return SourceBatchEvaluation(outcomes=(), previews=())
+
+ triage = _triage(checks, now=cutoff, tz_name=team.timezone)
+ if not triage.evaluable:
+ # Returns before the checkpoint query below, which nothing left would use.
+ return _collect(triage.decided, team_id, slot, started_at)
+ decided = list(triage.decided)
# One checkpoint for the pass, matching the production discovery activity. A failure falls
# back to wall-clock rather than ending the batch.
@@ -254,7 +455,7 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatc
checkpoint = None
cohorts: dict[tuple, list[PlatformAlertCheck]] = {}
- for check in checks:
+ for check in triage.evaluable:
cohorts.setdefault(_cohort_key(check, checkpoint, cutoff), []).append(check)
if len(cohorts) > MAX_COHORTS_PER_CYCLE:
@@ -264,9 +465,6 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatc
evaluated=MAX_COHORTS_PER_CYCLE,
)
- outcomes: list[PlatformAlertOutcome] = []
- previews: list[AlertDeliveryPreview] = []
- omitted = 0
deadline = started_at + BATCH_QUERY_BUDGET_SECONDS
unqueried = 0
# Capped the way the production cohort query requires: one batched query carries one countIf
@@ -279,15 +477,15 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatc
for cohort_key, chunk in chunks:
query_seconds = min(MAX_QUERY_SECONDS, int(deadline - time.monotonic()))
if query_seconds < MIN_QUERY_SECONDS:
+ # No outcome, deliberately. A skipped check was decided; these were never asked, so
+ # advancing their schedule would drop a real check. They keep their due time.
unqueried += len(chunk)
continue
- for outcome, preview in _evaluate_cohort(team, chunk, cohort_key, now=cutoff, query_seconds=query_seconds):
- if preview is not None and len(previews) >= MAX_PREVIEWS_PER_CYCLE:
- omitted += 1
- continue
- outcomes.append(outcome)
- if preview is not None:
- previews.append(preview)
+ decided.extend(
+ _evaluate_cohort(
+ team, chunk, cohort_key, now=cutoff, query_seconds=query_seconds, muted_ids=triage.muted_ids
+ )
+ )
if unqueried:
logger.warning(
@@ -297,14 +495,4 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatc
unqueried=unqueried,
budget_seconds=BATCH_QUERY_BUDGET_SECONDS,
)
- if omitted:
- logger.warning(
- "Deferred logs alert deliveries over the batch payload bound",
- team_id=team_id,
- slot=slot,
- delivered=len(previews),
- deferred=omitted,
- )
- safe_record(increment_deliveries_deferred, SourceKind.LOGS.value, omitted)
- safe_record(record_batch_duration, SourceKind.LOGS.value, int((time.monotonic() - started_at) * 1000))
- return SourceBatchEvaluation(outcomes=tuple(outcomes), previews=tuple(previews), omitted=omitted)
+ return _collect(decided, team_id, slot, started_at)
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index 36f8e86d7366..8d322de9cb23 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -1,5 +1,6 @@
from datetime import UTC, datetime, timedelta
+import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -7,10 +8,12 @@ from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.hogql.errors import ExposedHogQLError
+
from posthog.models.scoping import team_scope
-from products.alerts.backend.facade.contracts import SourceBatchEvaluation
-from products.alerts.backend.facade.platform_alerts import record_outcomes
+from products.alerts.backend.facade.contracts import SourceBatchEvaluation, SourceKind
+from products.alerts.backend.facade.platform_alerts import due_checks, record_outcomes
from products.alerts.backend.facade.temporal import SOURCE_EVALUATION_TIMEOUT
from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration
from products.logs.backend.alert_check_query import BatchedBucketedResult, BucketedCount
@@ -47,25 +50,31 @@ class TestLogsAlertEvaluation(APIBaseTest):
with team_scope(self.team.id):
return PlatformAlertConfiguration.objects.create(**defaults)
- def _run(self, *configurations: PlatformAlertConfiguration):
+ def _run(self, *configurations: PlatformAlertConfiguration, query_error: Exception | None = None):
breaching = {str(c.id): [BucketedCount(timestamp=self.cutoff, count=500)] for c in configurations}
with (
patch(f"{_MODULE}.fetch_live_logs_checkpoint", return_value=None),
patch(f"{_MODULE}.BatchedAlertCheckQuery") as query,
):
- query.return_value.execute_rolling_checks.return_value = BatchedBucketedResult(
- per_alert=breaching, query_duration_ms=1
- )
+ if query_error is not None:
+ query.return_value.execute_rolling_checks.side_effect = query_error
+ else:
+ query.return_value.execute_rolling_checks.return_value = BatchedBucketedResult(
+ per_alert=breaching, query_duration_ms=1
+ )
slot = (configurations[0].next_check_at or self.cutoff).replace(second=0, microsecond=0).isoformat()
return evaluate_logs_batch(self.team.id, slot, self.cutoff), query
+ def _slot(self) -> str:
+ return (self.cutoff - timedelta(minutes=1)).isoformat()
+
def _record(self, evaluation: SourceBatchEvaluation) -> None:
"""The write the platform's own activity runs after the evaluation returns.
Deliberately outside `team_scope`: that activity has no ambient scope, and these models
are fail-closed, so a write here through a bare manager raises.
"""
- record_outcomes(self.team.id, evaluation.outcomes, self.cutoff, team_timezone=self.team.timezone)
+ record_outcomes(self.team.id, evaluation.outcomes, self.cutoff)
def test_a_breaching_configuration_fires_and_records_its_own_state(self) -> None:
configuration = self._configuration()
@@ -118,6 +127,87 @@ class TestLogsAlertEvaluation(APIBaseTest):
).count()
assert still_due == 1
+ def test_a_check_inside_quiet_hours_runs_and_holds_its_announcement(self) -> None:
+ configuration = self._configuration(
+ schedule_restriction={"blocked_windows": [{"start": "09:00", "end": "12:00"}]}
+ )
+
+ evaluation, query = self._run(configuration)
+ self._record(evaluation)
+
+ query.assert_called_once()
+ assert evaluation.previews == ()
+ with team_scope(self.team.id):
+ alert = PlatformAlert.objects.get(configuration=configuration, grouping_key="")
+ configuration.refresh_from_db()
+ # An incident wholly inside the window must still leave a trace, and must not move the cooldown.
+ assert alert.state == PlatformAlert.State.FIRING
+ assert alert.last_notified_at is None
+ # Parked at the end of the window would leave the alert unevaluated until noon.
+ assert configuration.next_check_at is not None
+ assert self.cutoff < configuration.next_check_at < datetime(2026, 9, 16, 11, tzinfo=UTC)
+
+ def test_a_broken_filter_config_stops_being_discovered(self) -> None:
+ configuration = self._configuration(source_config={"filterGroup": {"type": "nonsense"}})
+
+ evaluation, query = self._run(configuration)
+ self._record(evaluation)
+
+ query.assert_not_called()
+ with team_scope(self.team.id):
+ alert = PlatformAlert.objects.get(configuration=configuration, grouping_key="")
+ assert alert.state == PlatformAlert.State.BROKEN
+ assert due_checks(self.team.id, SourceKind.LOGS.value, self._slot(), self.cutoff + timedelta(hours=1)) == ()
+
+ @parameterized.expand(
+ [
+ ("a_transient_error_holds_the_counter", ValueError("cluster busy"), 4, "not_firing"),
+ ("an_invalid_query_escalates", ExposedHogQLError("unknown field"), 5, "broken"),
+ ]
+ )
+ def test_a_failed_query_advances_the_schedule_instead_of_leaving_the_check_due(
+ self, _name: str, error: Exception, expected_failures: int, expected_state: str
+ ) -> None:
+ configuration = self._configuration(consecutive_failures=4)
+
+ evaluation, _ = self._run(configuration, query_error=error)
+ self._record(evaluation)
+
+ assert [o.consecutive_failures for o in evaluation.outcomes] == [expected_failures]
+ with team_scope(self.team.id):
+ alert = PlatformAlert.objects.get(configuration=configuration, grouping_key="")
+ configuration.refresh_from_db()
+ assert alert.state == expected_state
+ assert configuration.next_check_at is not None
+ assert configuration.next_check_at > self.cutoff
+
+ def test_a_failure_the_batch_cannot_record_leaves_the_whole_batch_due(self) -> None:
+ configuration = self._configuration(consecutive_failures=4)
+
+ with patch(f"{_MODULE}.list_active_alert_destinations", side_effect=RuntimeError("destinations unreachable")):
+ with pytest.raises(RuntimeError):
+ self._run(configuration, query_error=ExposedHogQLError("unknown field"))
+
+ with team_scope(self.team.id):
+ configuration.refresh_from_db()
+ assert not PlatformAlert.objects.filter(configuration=configuration).exists()
+ assert configuration.next_check_at == self.cutoff - timedelta(minutes=1)
+
+ def test_a_destination_lookup_failure_is_not_the_checks_own_failure(self) -> None:
+ configuration = self._configuration()
+
+ # The second answer is what a retry inside the evaluation would reach. Reaching it means
+ # a lookup failure was recorded as a failed check, after a query that succeeded.
+ with patch(f"{_MODULE}.list_active_alert_destinations", side_effect=[RuntimeError("unreachable"), []]):
+ with pytest.raises(RuntimeError):
+ self._run(configuration)
+
+ with team_scope(self.team.id):
+ configuration.refresh_from_db()
+ assert not PlatformAlert.objects.filter(configuration=configuration).exists()
+ assert configuration.consecutive_failures == 0
+ assert configuration.next_check_at == self.cutoff - timedelta(minutes=1)
+
def test_the_logs_product_rows_are_never_written(self) -> None:
legacy = LogsAlertConfiguration.objects.create(
team=self.team,