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.

fix(alerts): evict the least recently seen resting group at the cap (#118237)

Jimmy Zhu7526748b4b28
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 810e7472a485..c522d37a4567 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -9,7 +9,7 @@ from __future__ import annotations
from collections.abc import Callable, Collection, Mapping, Sequence
from dataclasses import field
-from datetime import datetime
+from datetime import UTC, datetime
from enum import StrEnum
from typing import TYPE_CHECKING, Any, Final, NotRequired, Protocol, TypedDict
from uuid import UUID
@@ -160,10 +160,12 @@ class Grouping:
@frozen
class GroupAdmission:
- """Which of a check's groups the configuration has room for, and how many it turned away."""
+ """Which of a check's groups the configuration has room for, which resting instances gave up
+ their slot to make that room, and how many groups it turned away."""
admitted: frozenset[str]
overflowed: int
+ evicted: frozenset[str] = frozenset()
@frozen
@@ -175,6 +177,13 @@ class InstanceCheckState:
last_notified_at: datetime | None = None
snooze_until: datetime | None = None
firing_started_at: datetime | None = None
+ last_seen_at: datetime | None = None
+
+ def at_rest(self, now: datetime) -> bool:
+ """Holds a slot and nothing else: not firing, failing or muted."""
+ return self.state == PlatformAlertState.NOT_FIRING.value and (
+ self.snooze_until is None or self.snooze_until <= now
+ )
@classmethod
def composed(
@@ -187,6 +196,7 @@ class InstanceCheckState:
snooze_until: datetime | None = None,
last_notified_at: datetime | None = None,
firing_started_at: datetime | None = None,
+ last_seen_at: datetime | None = None,
) -> InstanceCheckState:
"""An instance as a check, history and the read API all see it.
@@ -202,9 +212,13 @@ class InstanceCheckState:
last_notified_at=last_notified_at,
snooze_until=max(snoozes, default=None),
firing_started_at=firing_started_at,
+ last_seen_at=last_seen_at,
)
+_NEVER_SEEN: Final = datetime.min.replace(tzinfo=UTC)
+
+
@frozen
class PlatformAlertCheckInput:
"""One configuration and its runtime state, as a source adapter reads it.
@@ -233,25 +247,51 @@ class PlatformAlertCheckInput:
instances: tuple[InstanceCheckState, ...] = ()
grouping: Grouping = field(default_factory=Grouping)
- def admit(self, grouping_keys: Sequence[str]) -> GroupAdmission:
+ def admit(self, grouping_keys: Sequence[str], *, now: datetime) -> GroupAdmission:
"""The groups a check may report, from keys in the source's priority order.
A group that already has an instance is always admitted, so an open group can still
- resolve. New groups fill what `max_instances` leaves, front first.
+ resolve. New groups fill what `max_instances` leaves, front first. When that is not enough,
+ a new group takes the slot of the least recently seen instance at rest, so resolved groups
+ cannot lock a new breach out until they are reaped. An instance this check reports is
+ never evicted, and only a group past every resting instance overflows.
"""
+ keys = dict.fromkeys(grouping_keys)
existing = {instance.grouping_key for instance in self.instances}
- room = max(self.grouping.max_instances - len(existing), 0)
+ held = len(existing)
+ # An ungrouped configuration's one instance is its whole alert, so it never gives up its slot.
+ victims = (
+ []
+ if self.grouping.mode == GroupingMode.SINGLE
+ else sorted(
+ (
+ instance
+ for instance in self.instances
+ if instance.grouping_key not in keys and instance.at_rest(now)
+ ),
+ key=lambda instance: (instance.last_seen_at or _NEVER_SEEN, instance.grouping_key),
+ )
+ )
admitted: set[str] = set()
+ evicted: set[str] = set()
overflowed = 0
- for key in dict.fromkeys(grouping_keys):
+ for key in keys:
if key in existing:
admitted.add(key)
- elif room > 0:
- admitted.add(key)
- room -= 1
- else:
+ continue
+ # The write creates a row only below the cap. After the cap is lowered, one new group can
+ # need several resting slots, and it takes none when there are not enough of them.
+ needed = held + 1 - self.grouping.max_instances
+ if needed > len(victims):
overflowed += 1
- return GroupAdmission(admitted=frozenset(admitted), overflowed=overflowed)
+ continue
+ if needed > 0:
+ evicted.update(victim.grouping_key for victim in victims[:needed])
+ victims = victims[needed:]
+ held -= needed
+ admitted.add(key)
+ held += 1
+ return GroupAdmission(admitted=frozenset(admitted), overflowed=overflowed, evicted=frozenset(evicted))
def instance(self, grouping_key: str = "") -> InstanceCheckState:
"""The instance for a group, or the state a group with no instance starts from."""
@@ -266,7 +306,7 @@ class PlatformAlertCheckInput:
)
def open_keys(self) -> list[str]:
- """The groups whose instance is not at rest. A check judges each one, returned or not."""
+ """The groups whose instance state is not NOT_FIRING. A check judges each one, returned or not."""
return [
instance.grouping_key
for instance in self.instances
@@ -489,6 +529,8 @@ class PlatformAlertOutcome:
skipped: bool = False
# New groups `max_instances` had no room for, which the delivery names so a cap is never silent.
overflowed: int = 0
+ # Resting instances whose slot a new group took. The write deletes them before it creates rows.
+ evicted: tuple[str, ...] = ()
error_message: str | None = None
query_duration_ms: int | None = None
# Recording an outcome without it leaves a configuration discovery keeps handing back to an
@@ -564,6 +606,8 @@ class PlatformAlertOutcome:
keys = [group.grouping_key for group in self.groups]
if len(set(keys)) != len(keys):
raise ValueError("an outcome names each group once")
+ if set(self.evicted) & set(keys):
+ raise ValueError("an outcome cannot evict a group it reports")
@frozen
diff --git a/products/alerts_platform/backend/facade/grouping.py b/products/alerts_platform/backend/facade/grouping.py
index eccbb917d417..9f5bf3710516 100644
--- a/products/alerts_platform/backend/facade/grouping.py
+++ b/products/alerts_platform/backend/facade/grouping.py
@@ -71,10 +71,12 @@ class GroupVerdict:
@frozen
class GroupDecision:
- """The admitted groups, firing first, and how many new groups the cap turned away."""
+ """The admitted groups, firing first, the resting instances evicted to admit them, and how many
+ new groups the cap turned away."""
verdicts: tuple[GroupVerdict, ...]
overflowed: int
+ evicted: frozenset[str] = frozenset()
def as_outcome(
self, *, configuration_id: UUID, evaluation_key: str, query_duration_ms: int | None
@@ -87,6 +89,7 @@ class GroupDecision:
groups=tuple(verdict.group for verdict in self.verdicts),
query_duration_ms=query_duration_ms,
overflowed=self.overflowed,
+ evicted=tuple(sorted(self.evicted)),
)
@@ -147,7 +150,7 @@ def decide_groups(
# 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])
+ admission = check.admit([observation.grouping_key for observation, _, _ in judged], now=now)
verdicts = tuple(
GroupVerdict(
observation=observation,
@@ -167,4 +170,4 @@ def decide_groups(
for observation, snapshot, outcome in judged
if observation.grouping_key in admission.admitted
)
- return GroupDecision(verdicts=verdicts, overflowed=admission.overflowed)
+ return GroupDecision(verdicts=verdicts, overflowed=admission.overflowed, evicted=admission.evicted)
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 9a577461d48c..dba9072fe778 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -130,6 +130,11 @@ def _alerts_for_write(
return loaded
+def _at_rest(now: datetime) -> Q:
+ """Rows that hold a slot and nothing else, as `InstanceCheckState.at_rest` reads an instance."""
+ return Q(state=PlatformAlert.State.NOT_FIRING) & (Q(snooze_until__isnull=True) | Q(snooze_until__lte=now))
+
+
# Long enough that a group which resolves and fires again inside a day keeps its cooldown.
REAP_AFTER: Final = timedelta(hours=24)
@@ -154,10 +159,7 @@ def _reap(
return
candidates = (
PlatformAlert.objects.for_team(team_id)
- .filter(
- configuration_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))
+ .filter(_at_rest(now), configuration_id__in=list(healthy), last_seen_at__lt=now - REAP_AFTER)
.values_list("id", "configuration_id", "grouping_key", "last_seen_at")
)
reaped: dict[str, list[UUID]] = {}
@@ -175,6 +177,33 @@ def _reap(
safe_record(increment_instances_reaped, source_kind, len(ids))
+def _evict(
+ team_id: int,
+ configurations: Sequence[PlatformAlertConfiguration],
+ by_id: dict[str, PlatformAlertOutcome],
+ now: datetime,
+) -> None:
+ """Deletes the resting instances a check evicted, so the groups that took their slots pass the cap.
+
+ The filter repeats the check's notion of at rest, because the row may have changed since the
+ check read it, and deleting a firing or muted instance would lose its state.
+ """
+ doomed: dict[str, Q] = {}
+ for configuration in configurations:
+ evicted = by_id[str(configuration.id)].evicted
+ if not evicted or Grouping.from_stored(configuration.grouping).mode == GroupingMode.SINGLE:
+ continue
+ if configuration.snooze_until is not None and configuration.snooze_until > now:
+ continue
+ doomed[configuration.source_kind] = doomed.get(configuration.source_kind, Q()) | Q(
+ configuration_id=configuration.id, grouping_key__in=evicted
+ )
+ for source_kind, rows in doomed.items():
+ deleted, _ = PlatformAlert.objects.for_team(team_id).filter(rows, _at_rest(now)).delete()
+ if deleted:
+ safe_record(increment_instances_reaped, source_kind, deleted)
+
+
def suppressed() -> Q:
"""Configurations a check status holds back.
@@ -273,6 +302,7 @@ def _composed(configuration: PlatformAlertConfiguration, alert: PlatformAlert |
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,
+ last_seen_at=alert.last_seen_at if alert else None,
)
@@ -430,18 +460,14 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
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,
- [
- configuration
- for configuration in configurations
- if _check_status(configuration, by_id[str(configuration.id)])
- == PlatformAlertConfiguration.CheckStatus.OK
- ],
- now,
- returned=frozenset(returned),
- )
+ healthy = [
+ configuration
+ for configuration in configurations
+ if _check_status(configuration, by_id[str(configuration.id)]) == PlatformAlertConfiguration.CheckStatus.OK
+ ]
+ # Before the cap is counted, so a slot a stale or evicted group held is free for a new one this check.
+ _reap(team_id, healthy, now, returned=frozenset(returned))
+ _evict(team_id, healthy, by_id, now)
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
diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index 29c99ebff0c8..b5d3546cdcbf 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -374,7 +374,10 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
"web": ("not_firing", due + timedelta(hours=2)),
"new": ("not_firing", muted_until),
}
- assert check.instance("api").firing_started_at == self.cutoff
+ assert (check.instance("api").firing_started_at, check.instance("web").last_seen_at) == (
+ self.cutoff,
+ self.cutoff,
+ )
def _group(self, key: str, *, state: str = "not_firing") -> GroupOutcome:
return GroupOutcome(grouping_key=key, kind=AlertEventKind.CHECK, new_state=state, notified=False)
@@ -435,6 +438,39 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
PlatformAlert.objects.filter(configuration=self.configuration, grouping_key="api").exists() is not kept
)
+ @parameterized.expand(
+ [
+ ("at_rest", {}, False),
+ ("fired_since_the_check_read_it", {"state": "firing"}, True),
+ ("snoozed_since_the_check_read_it", {"snoozed": True}, True),
+ ("ungrouped", {"grouping": Grouping(max_instances=1)}, True),
+ ]
+ )
+ def test_an_evicted_group_gives_up_its_slot_only_while_it_is_at_rest(
+ self, _name: str, case: dict[str, Any], kept: bool
+ ) -> None:
+ grouping = case.get(
+ "grouping", Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service",), max_instances=1)
+ )
+ with team_scope(self.team.id):
+ PlatformAlertConfiguration.objects.filter(id=self.configuration.id).update(grouping=grouping.to_stored())
+ PlatformAlert.objects.create(
+ team=self.team,
+ configuration=self.configuration,
+ grouping_key="old",
+ state=case.get("state", "not_firing"),
+ last_seen_at=self.cutoff - timedelta(hours=1),
+ snooze_until=self.cutoff + timedelta(hours=1) if case.get("snoozed") else None,
+ )
+
+ self._record(groups=(self._group("new", state="firing"),), evicted=("old",))
+
+ with team_scope(self.team.id):
+ keys = set(
+ PlatformAlert.objects.filter(configuration=self.configuration).values_list("grouping_key", flat=True)
+ )
+ assert keys == ({"old"} if kept else {"new"})
+
def test_a_resolve_row_keeps_the_firing_it_ended(self) -> None:
# The alert row clears the firing on a resolve, so history is the only place left holding
# the start a delivery needs to reply under the message that fired.
@@ -641,16 +677,81 @@ def _group(grouping_key: str) -> GroupOutcome:
return GroupOutcome(grouping_key=grouping_key, kind=AlertEventKind.CHECK, new_state="not_firing", notified=False)
+_ADMITTED_AT = datetime(2026, 9, 16, 10, tzinfo=UTC)
+_GROUPED = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service",), max_instances=3)
+
+
+def _resting(key: str, *, seen_hours_ago: int = 1) -> InstanceCheckState:
+ return InstanceCheckState(
+ grouping_key=key, state="not_firing", last_seen_at=_ADMITTED_AT - timedelta(hours=seen_hours_ago)
+ )
+
+
@pytest.mark.parametrize(
- "existing, returned, expected",
+ "existing, returned, expected, grouping",
[
- ((), ("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)),
+ ((), ("a", "b", "c", "d"), GroupAdmission(admitted=frozenset({"a", "b", "c"}), overflowed=1), _GROUPED),
+ (
+ (_resting("x"),),
+ ("x", "a", "a", "b"),
+ GroupAdmission(admitted=frozenset({"x", "a", "b"}), overflowed=0),
+ _GROUPED,
+ ),
+ # The least recently seen resting instance gives up its slot. "x" is older still, but this
+ # check reports it, so it keeps its row.
+ (
+ (_resting("x", seen_hours_ago=3), _resting("y", seen_hours_ago=1), _resting("z", seen_hours_ago=2)),
+ ("q", "x"),
+ GroupAdmission(admitted=frozenset({"x", "q"}), overflowed=0, evicted=frozenset({"z"})),
+ _GROUPED,
+ ),
+ (
+ tuple(InstanceCheckState(grouping_key=key, state="firing") for key in ("x", "y", "z")),
+ ("q", "x"),
+ GroupAdmission(admitted=frozenset({"x"}), overflowed=1),
+ _GROUPED,
+ ),
+ (
+ (
+ InstanceCheckState(grouping_key="x", state="firing"),
+ InstanceCheckState(
+ grouping_key="y", state="not_firing", snooze_until=_ADMITTED_AT + timedelta(minutes=1)
+ ),
+ _resting("z"),
+ ),
+ ("q", "r"),
+ GroupAdmission(admitted=frozenset({"q"}), overflowed=1, evicted=frozenset({"z"})),
+ _GROUPED,
+ ),
+ (
+ (InstanceCheckState(grouping_key="x", state="firing"), _resting("y"), _resting("z")),
+ ("q",),
+ GroupAdmission(admitted=frozenset({"q"}), overflowed=0, evicted=frozenset({"y", "z"})),
+ Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service",), max_instances=2),
+ ),
+ (
+ (
+ InstanceCheckState(grouping_key="x", state="firing"),
+ InstanceCheckState(grouping_key="y", state="firing"),
+ _resting("z"),
+ ),
+ ("q",),
+ GroupAdmission(admitted=frozenset(), overflowed=1),
+ Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service",), max_instances=2),
+ ),
+ (
+ (_resting(""),),
+ ("other",),
+ GroupAdmission(admitted=frozenset(), overflowed=1),
+ Grouping(max_instances=1),
+ ),
],
)
def test_a_check_admits_existing_groups_and_new_ones_up_to_the_cap(
- existing: tuple[str, ...], returned: tuple[str, ...], expected: GroupAdmission
+ existing: tuple[InstanceCheckState, ...],
+ returned: tuple[str, ...],
+ expected: GroupAdmission,
+ grouping: Grouping,
) -> None:
check = PlatformAlertCheckInput(
id=uuid4(),
@@ -667,11 +768,11 @@ def test_a_check_admits_existing_groups_and_new_ones_up_to_the_cap(
legacy_configuration_id=None,
check_status="ok",
snooze_until=None,
- instances=tuple(InstanceCheckState(grouping_key=key, state="not_firing") for key in existing),
- grouping=Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service",), max_instances=3),
+ instances=existing,
+ grouping=grouping,
)
- assert check.admit(returned) == expected
+ assert check.admit(returned, now=_ADMITTED_AT) == expected
@pytest.mark.parametrize(
@@ -693,6 +794,7 @@ def test_a_grouping_rejects_keys_its_mode_cannot_use(fields: dict[str, Any]) ->
[
{"failure": CheckFailure(kind=AlertEventKind.ERRORED, new_state="errored", notified=True)},
{"groups": (_group("api"), _group("api"))},
+ {"groups": (_group("api"),), "evicted": ("api",)},
],
)
def test_an_outcome_rejects_an_invalid_shape(overrides: dict[str, Any]) -> None:
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index 9398c1400d5c..8f3c9ba31a09 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -379,7 +379,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert run_after({"api": 600, "web": 550}) == {}
assert run_after({"api": 600}) == {"sha256:": AlertEventKind.RESOLVED}
- def test_a_grouped_alert_fires_per_group_resolves_a_vanished_one_and_reports_overflow(self) -> None:
+ def test_a_grouped_alert_overflows_at_its_cap_until_a_resolved_group_gives_up_its_slot(self) -> None:
grouping = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service_name",), max_instances=2)
configuration = self._configuration(grouping=grouping.to_stored())
@@ -404,6 +404,30 @@ class TestLogsAlertEvaluation(APIBaseTest):
"api": AlertEventKind.CHECK,
"worker": AlertEventKind.RESOLVED,
}
+ self._record(second)
+
+ def run_after(counts: dict[str, int]) -> tuple[dict[str, AlertEventKind], int]:
+ with team_scope(self.team.id):
+ platform_testing.set_due_at(configuration.id, self.cutoff - timedelta(minutes=1))
+ evaluation = self._run_grouped(configuration, counts)
+ self._record(evaluation)
+ (outcome,) = evaluation.outcomes
+ return {group.labels["service_name"]: group.kind for group in outcome.groups}, outcome.overflowed
+
+ # The resolved group is in this check's results, so it keeps its slot and the new breach overflows.
+ assert run_after({"api": 500, "worker": 3, "cron": 300}) == (
+ {"api": AlertEventKind.CHECK, "worker": AlertEventKind.CHECK},
+ 1,
+ )
+ assert run_after({"api": 500, "cron": 300}) == (
+ {"api": AlertEventKind.CHECK, "cron": AlertEventKind.FIRING},
+ 0,
+ )
+ with team_scope(self.team.id):
+ evicted = platform_testing.alert_for(
+ configuration.id, grouping_key=grouping_key_of({"service_name": "worker"})
+ )
+ assert evicted is None
def test_a_grouped_alert_switched_off_in_logs_keeps_its_open_groups(self) -> None:
grouping = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service_name",))