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(logs): evaluate platform logs checks against the logs alert as it is now (#114798)

Jimmy Zhu14404eb83c94
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index 442560bbfef0..fb37036bfcfa 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -55,7 +55,7 @@ writes a source product's rows. What it does cost is the evaluation queries its
ones the source's own production fleet is already running for the same alerts.
The tick's work is whatever `PlatformAlertConfiguration` rows exist, and nothing creates those on its own:
-`python manage.py backfill_platform_alert_configurations [--team-id N]` for logs and `python manage.py backfill_platform_insight_alert_configurations [--team-id N]` for insight are the only writers, and both are manual.
+`python manage.py backfill_platform_alert_configurations [--team-id N]` for logs and `python manage.py backfill_platform_insight_alert_configurations [--team-id N]` for insight are the only bulk writers, and both are manual. The logs alerts API also copies one alert when it is created or turned back on, but only in a team that already has an enabled logs copy.
So the order below puts the schedule in place while there is no demand, and load arrives when the backfill
is run, one cohort at a time.
@@ -464,7 +464,10 @@ python manage.py backfill_platform_alert_configurations
Pass `--team-id` to copy one team's configurations only.
Pass `--sample-percent` to copy a sample of teams. Logs samples whole teams, not alerts, because one query checks a cohort of a team's alerts, so a sample of alerts spread across every team costs nearly as many queries as copying all of them. The sample is chosen by team id, so a rerun copies the same teams and a larger percentage only adds teams.
An alert the copy rejects is logged and counted as failed, and the run carries on.
-It is a seed, not a sync: the logs product keeps the control plane, and a later change to a logs alert reaches these tables only on the next run.
+It is a seed, not a sync: the logs product keeps the control plane.
+Each logs check reads its logs alert's current filters, threshold, window, N-of-M, cooldown, quiet hours and snooze, so an edit counts from the next check without a rerun.
+A copy whose logs alert is deleted or disabled switches itself off on its next check.
+A logs alert created or turned back on is copied when the logs API commits it, but only in a team that already has an enabled logs copy. So a write in the logs product never widens a sample or undoes `--disable`, and those teams still wait for the next run.
A second run updates rather than duplicates, because `legacy_configuration_id` carries the row each copy came from.
A second run of either backfill, logs or insight, leaves an enabled copy's `next_check_at` alone unless it has none yet or its cadence changed, because the platform owns its schedule once the row exists. The logs product parks its own next check at the end of quiet hours, while the platform checks through them and only mutes. A new or re-enabled copy still takes the source's due time, which spreads a large copy's first checks the way the source spreads them.
Each run also copies the logs alert's snooze onto its platform alert row, so a snoozed alert stays silent, and an alert unsnoozed since the last run is unsnoozed here too.
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index 34644aaf5920..f948954a3462 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -47,9 +47,22 @@ def slot_of(next_check_at: datetime | None, cutoff: datetime) -> str:
return platform_lifecycle.slot_of(next_check_at, cutoff)
-def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
+def upsert_configuration(upsert: PlatformAlertUpsert, *, revive: bool = False) -> bool:
"""Copy one of a source's own configurations in. True when it created the row."""
- return platform_lifecycle.upsert_configuration(upsert)
+ return platform_lifecycle.upsert_configuration(upsert, revive=revive)
+
+
+def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False) -> None:
+ """Copy one configuration in only when its team already runs that source here.
+
+ `revive` says the source alert was just created or turned back on, so the copy starts clean.
+ """
+ platform_lifecycle.upsert_if_running(upsert, revive=revive)
+
+
+def refresh_settings(team_id: int, configuration_id: UUID, upsert: PlatformAlertUpsert) -> None:
+ """Write a source's current settings onto its copy, leaving the schedule and state alone."""
+ platform_lifecycle.refresh_settings(team_id, configuration_id, upsert)
def take_ownership(handover: PlatformOwnershipHandover) -> bool:
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 01664a150d3b..004fd650c5c7 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -7,9 +7,11 @@ and every write to these rows, stays here. A source never holds one of these mod
from collections.abc import Collection, Sequence
from datetime import datetime, timedelta
from typing import Final
+from uuid import UUID
-from django.db import transaction
+from django.db import connection, transaction
from django.db.models import Exists, OuterRef, Q, QuerySet
+from django.utils import timezone as django_timezone
from posthog.models import Team
@@ -186,10 +188,11 @@ def _condition_snapshot(configuration: PlatformAlertConfiguration) -> dict[str,
a source's copy would cost Temporal payload on every batch.
One path can write a configuration between an evaluation and its record, so the snapshot is
- evaluation-time by convention rather than by construction: `upsert_configuration`, reached
- only through a hand-run backfill command, and only for a configuration already copied whose
- source row changed since. The row then states the new condition beside a verdict measured
- against the old one. Carry the snapshot on the outcome if that stops being acceptable.
+ evaluation-time by convention rather than by construction: a hand-run backfill's
+ `upsert_configuration`, for a configuration already copied whose source row changed since. The
+ row then states the new condition beside a verdict measured against the old one. Carry the
+ snapshot on the outcome if that stops being acceptable. A logs evaluation also upserts a drifted
+ copy, but before it evaluates, so its snapshot matches its verdict.
The source's bound is flattened in beside the platform's own fields, so a reader finds it at
the top level whatever shape the source gives it.
@@ -329,9 +332,14 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
_CADENCE_FIELDS: Final = ("check_interval_minutes", "recurrence_unit", "anchor_time")
+_REVIVE_FENCE: Final = timedelta(minutes=1)
+_ADMISSION_LOCK_SQL: Final = {
+ True: "SELECT pg_advisory_xact_lock(hashtext(%s))",
+ False: "SELECT pg_advisory_xact_lock_shared(hashtext(%s))",
+}
-def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
+def upsert_configuration(upsert: PlatformAlertUpsert, *, revive: bool = False) -> bool:
"""Copies one source configuration in. Returns True when it created a row.
Keyed on the row it came from, so a second run updates rather than duplicates.
@@ -343,6 +351,9 @@ def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
The recurrence is checked here rather than where the schedule advances, because an
unparseable unit or anchor raised there would fail a whole batch of unrelated checks.
+
+ `revive` says the source alert was just created or turned back on, which resets the copy
+ even when it stayed enabled, for example a BROKEN copy that discovery skips.
"""
if upsert.recurrence_unit is not None:
to_recurrence_interval(upsert.recurrence_unit)
@@ -377,16 +388,79 @@ def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
or any(existing[key] != defaults[key] for key in _CADENCE_FIELDS)
):
defaults["next_check_at"] = upsert.next_check_at
+ # A copy that comes back on starts clean, as a source's own enable does. The state it was
+ # switched off in is stale, and a firing kept from then would end in a resolve for an
+ # episode nobody was told about.
+ revived = existing is not None and upsert.enabled and (revive or not existing["enabled"])
+ if revived:
+ defaults["consecutive_failures"] = 0
+ # After any check already running, so an outcome it read before the source came back
+ # on, such as a stop, finds the row no longer due and records nothing.
+ defaults["next_check_at"] = max(
+ upsert.next_check_at or django_timezone.now(), django_timezone.now() + _REVIVE_FENCE
+ )
configuration, created = PlatformAlertConfiguration.objects.unscoped().update_or_create(
legacy_configuration_id=upsert.legacy_configuration_id, defaults=defaults
)
alert = _alerts_for_write(upsert.team_id, [configuration])[str(configuration.id)]
- # State is left alone because a muted alert keeps tracking reality.
+ # Otherwise state is left alone, because a muted alert keeps tracking reality.
alert.snooze_until = upsert.snooze_until
- alert.save(update_fields=["snooze_until"])
+ update_fields = ["snooze_until"]
+ if revived:
+ alert.state = PlatformAlert.State.NOT_FIRING.value
+ alert.firing_started_at = None
+ update_fields += ["state", "firing_started_at"]
+ alert.save(update_fields=update_fields)
return created
+def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False) -> None:
+ """Copies one configuration in when its team already runs that source here.
+
+ A team runs a source here while any of its copies of that source is enabled. A team the backfill
+ left out of its sample, or one `disable_configurations` switched off, gets nothing, so a write
+ in the source never widens a sample or undoes an operator's switch-off.
+ """
+ with transaction.atomic():
+ _hold_admission(upsert.source_kind.value, exclusive=False)
+ running = (
+ PlatformAlertConfiguration.objects.for_team(upsert.team_id)
+ .filter(source_kind=upsert.source_kind.value, enabled=True)
+ .exists()
+ )
+ if running:
+ upsert_configuration(upsert, revive=revive)
+
+
+def _hold_admission(source_kind: str, *, exclusive: bool) -> None:
+ """Orders admitting a copy against an operator's switch-off, so neither reads the other half done.
+
+ An admission shares the lock, so admissions never wait on each other. A switch-off takes it
+ alone, so it waits for admissions in flight and a later admission sees the copies off.
+ """
+ with connection.cursor() as cursor:
+ cursor.execute(_ADMISSION_LOCK_SQL[exclusive], [f"alerts-platform-admission:{source_kind}"])
+
+
+def refresh_settings(team_id: int, configuration_id: UUID, upsert: PlatformAlertUpsert) -> None:
+ """Writes a source's current settings onto its copy, so history and messages state what a check
+ evaluated.
+
+ Settings only. The schedule, `enabled` and the alert rows stay as they are, so an evaluation can
+ call this before it decides and a retried attempt still finds the same checks due.
+ """
+ PlatformAlertConfiguration.objects.for_team(team_id).filter(id=configuration_id).update(
+ name=upsert.name,
+ source_config=upsert.source_config,
+ evaluation_periods=upsert.evaluation_periods,
+ datapoints_to_alarm=upsert.datapoints_to_alarm,
+ cooldown_minutes=upsert.cooldown_minutes,
+ schedule_restriction=upsert.schedule_restriction,
+ # `update()` skips `auto_now`.
+ updated_at=django_timezone.now(),
+ )
+
+
# Firing episodes are keyed per stack, so a firing alert stays with its source until it resolves.
_HANDOVER_STATES: Final = frozenset(
{PlatformAlertState.NOT_FIRING, PlatformAlertState.ERRORED, PlatformAlertState.BROKEN}
@@ -434,12 +508,14 @@ def disable_configurations(source_kind: str, *, team_id: int | None = None) -> i
Rows, state and history stay, so a comparison can still read what ran. Discovery and the batch
read both skip a disabled row, so no new check starts after this. Checks already running finish.
"""
- # Cross-team on purpose, for an operator stopping a whole source at once. Only copies the source
- # still owns: once the platform owns an alert, its copy is the production alert, and switching it
- # off would silence real notifications rather than stop a parallel check.
- rows = PlatformAlertConfiguration.objects.unscoped().filter(
- source_kind=source_kind, enabled=True, owner=PlatformAlertOwner.SOURCE
- )
- if team_id is not None:
- rows = rows.filter(team_id=team_id)
- return rows.update(enabled=False)
+ with transaction.atomic():
+ _hold_admission(source_kind, exclusive=True)
+ # Cross-team on purpose, for an operator stopping a whole source at once. Only copies the
+ # source still owns: once the platform owns an alert, its copy is the production alert, and
+ # switching it off would silence real notifications rather than stop a parallel check.
+ rows = PlatformAlertConfiguration.objects.unscoped().filter(
+ source_kind=source_kind, enabled=True, owner=PlatformAlertOwner.SOURCE
+ )
+ if team_id is not None:
+ rows = rows.filter(team_id=team_id)
+ return rows.update(enabled=False)
diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index 07f2a1c2ad4d..429a50f4c5d4 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -251,7 +251,7 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
}
assert len(due) == expected_slots
- def _copy(self, legacy_id: UUID, **overrides: Any) -> None:
+ def _copy(self, legacy_id: UUID, *, revive: bool = False, **overrides: Any) -> None:
fields: dict[str, Any] = {
"legacy_configuration_id": legacy_id,
"team_id": self.team.id,
@@ -268,7 +268,7 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
"snooze_until": None,
}
fields.update(overrides)
- upsert_configuration(PlatformAlertUpsert(**fields))
+ upsert_configuration(PlatformAlertUpsert(**fields), revive=revive)
@parameterized.expand(
[
@@ -283,7 +283,7 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
("a_new_cadence_takes_the_source_schedule", False, 60, timedelta(minutes=-1), timedelta(minutes=34)),
]
)
- def test_a_second_copy_keeps_the_schedule_the_platform_owns(
+ def test_a_second_copy_keeps_what_the_platform_owns_until_the_copy_comes_back_on(
self,
_name: str,
disabled_between: bool,
@@ -299,18 +299,29 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
schedule_restriction=quiet_hours,
next_check_at=None if first_offset is None else self.cutoff + first_offset,
)
+ with team_scope(self.team.id):
+ PlatformAlertConfiguration.objects.filter(legacy_configuration_id=legacy_id).update(consecutive_failures=3)
+ PlatformAlert.objects.filter(configuration__legacy_configuration_id=legacy_id).update(
+ state="firing", firing_started_at=self.cutoff
+ )
if disabled_between:
disable_configurations(SourceKind.LOGS, team_id=self.team.id)
- self._copy(
- legacy_id,
- schedule_restriction=quiet_hours,
- next_check_at=self.cutoff + timedelta(minutes=34),
- check_interval_minutes=interval_on_rerun,
- )
+ with time_machine.travel(self.cutoff, tick=False):
+ self._copy(
+ legacy_id,
+ schedule_restriction=quiet_hours,
+ next_check_at=self.cutoff + timedelta(minutes=34),
+ check_interval_minutes=interval_on_rerun,
+ )
with team_scope(self.team.id):
copied = PlatformAlertConfiguration.objects.get(legacy_configuration_id=legacy_id)
+ alert = PlatformAlert.objects.get(configuration=copied)
assert copied.next_check_at == self.cutoff + expected_offset
+ # A copy that comes back on starts clean, as the source's own enable does.
+ assert (alert.state, alert.firing_started_at, copied.consecutive_failures) == (
+ ("not_firing", None, 0) if disabled_between else ("firing", self.cutoff, 3)
+ )
def test_a_copied_snooze_mutes_without_holding_back_the_check(self) -> None:
legacy_id = uuid4()
@@ -339,3 +350,37 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
copy(None)
assert snooze_seen_by_check() == ("firing", None)
+
+ def test_a_source_turned_back_on_restarts_a_broken_copy_past_any_check_in_flight(self) -> None:
+ legacy_id = uuid4()
+ self._copy(legacy_id)
+ with team_scope(self.team.id):
+ copied = PlatformAlertConfiguration.objects.get(legacy_configuration_id=legacy_id)
+ PlatformAlertConfiguration.objects.filter(id=copied.id).update(consecutive_failures=5)
+ PlatformAlert.objects.filter(configuration=copied).update(state="broken")
+
+ with time_machine.travel(self.cutoff, tick=False):
+ self._copy(legacy_id, revive=True)
+ # A check that read the source as off before it came back on reports a stop.
+ with self.captureOnCommitCallbacks(execute=True):
+ recorded = record_outcomes(
+ self.team.id,
+ [
+ PlatformAlertOutcome(
+ configuration_id=copied.id,
+ evaluation_key="window:stale",
+ kind=AlertEventKind.CHECK,
+ new_state="broken",
+ notified=False,
+ consecutive_failures=5,
+ disable=True,
+ )
+ ],
+ self.cutoff,
+ )
+
+ assert recorded == 0
+ with team_scope(self.team.id):
+ copied = PlatformAlertConfiguration.objects.get(id=copied.id)
+ alert = PlatformAlert.objects.get(configuration=copied)
+ assert (copied.enabled, copied.consecutive_failures, alert.state) == (True, 0, "not_firing")
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 52a961ac3b3a..a276518a3786 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -16,6 +16,7 @@ the shared machine configured with this source's policy, not from the logs produ
import time
from collections.abc import Sequence
+from dataclasses import replace
from datetime import datetime, timedelta
from itertools import batched
from typing import Final, cast
@@ -29,7 +30,7 @@ from posthog.models import Team
from posthog.utils import absolute_uri
from products.alerts.backend.facade.destinations import configured_destination_template_ids
-from products.alerts_platform.backend.facade.api import due_checks, slot_of
+from products.alerts_platform.backend.facade.api import due_checks, refresh_settings, slot_of
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertEventKind,
@@ -78,6 +79,7 @@ from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EventKin
from products.logs.backend.alert_error_classifier import classify as classify_alert_error
from products.logs.backend.alert_evaluation_key import WINDOW_MARKER
from products.logs.backend.models import LogsAlertConfiguration
+from products.logs.backend.platform_alert_backfill import platform_upsert_of
# 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.
@@ -134,12 +136,19 @@ class LogsAlertCondition:
window_minutes=condition["window_minutes"],
)
- def as_source_config(self) -> dict[str, int | str]:
- return {
- "threshold_count": self.threshold_count,
- "threshold_operator": self.threshold_operator,
- "window_minutes": self.window_minutes,
- }
+
+# The copy's settings a check takes from the logs alert as it is now. The schedule stays the
+# platform's own once the copy exists.
+_SETTINGS_FIELDS: Final = (
+ "name",
+ "source_config",
+ "evaluation_periods",
+ "datapoints_to_alarm",
+ "cooldown_minutes",
+ "schedule_restriction",
+)
+# The snooze lives on the alert row rather than the copy, and no history row states it.
+_LIVE_FIELDS: Final = (*_SETTINGS_FIELDS, "snooze_until")
def _broken_condition(check: PlatformAlertCheckInput) -> str | None:
@@ -147,8 +156,6 @@ def _broken_condition(check: PlatformAlertCheckInput) -> str | None:
every check in the batch, so one malformed row would otherwise stop the whole batch."""
try:
LogsAlertCondition.of(check)
- except (KeyError, TypeError):
- return "The alert's threshold is missing from its configuration"
except ValueError as error:
return f"The alert's threshold is invalid: {error}"
return None
@@ -376,7 +383,7 @@ def _request(
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 or check.id)
+ destination_alert_id = str(check.legacy_configuration_id)
incident_action = decide_incident_action(
AlertState(check.state), outcome.new_state, policy=PLATFORM_LOGS_ALERT_POLICY
)
@@ -555,6 +562,72 @@ def _evaluate_cohort(
return decided
+def _as_configured_now(
+ checks: Sequence[PlatformAlertCheckInput], *, team_id: int, now: datetime
+) -> tuple[list[PlatformAlertCheckInput], list[Decision]]:
+ """Reads each check's logs alert, so the check evaluates what the logs stack evaluates.
+
+ The copy is a seed, so an edit made in the logs product since the backfill lives only on the
+ logs row. Evaluating the copy as stored would read that drift as disagreement. A drifted copy's
+ settings are written back before it is evaluated, because history and messages read the stored
+ copy, so a message would otherwise quote the old threshold. The write leaves the schedule alone,
+ so a retried attempt finds the same checks due. A changed check interval still needs a backfill.
+
+ A copy whose logs alert is gone or disabled stops: the logs stack runs no check for it, so it
+ switches itself off, and the next backfill turns it back on if the alert is enabled again.
+ """
+ legacy_ids = [check.legacy_configuration_id for check in checks]
+ alerts = {alert.id: alert for alert in LogsAlertConfiguration.objects.filter(team_id=team_id, id__in=legacy_ids)}
+ current: list[PlatformAlertCheckInput] = []
+ stopped: list[Decision] = []
+ for check in checks:
+ alert = alerts.get(check.legacy_configuration_id)
+ if alert is None or not alert.enabled:
+ stopped.append(_stopped(check, now=now))
+ continue
+ if not isinstance(alert.filters, dict):
+ # The copy cannot be built, and raising would stop every other check in the batch.
+ stopped.append(
+ _held(
+ check,
+ apply_broken_config(_snapshot(check, ())),
+ skip=SkipReason.BROKEN_CONFIG,
+ now=now,
+ error_message="The alert's filters are not an object.",
+ )
+ )
+ continue
+ upsert = platform_upsert_of(alert)
+ if any(getattr(check, field) != getattr(upsert, field) for field in _SETTINGS_FIELDS):
+ try:
+ refresh_settings(team_id, check.id, upsert)
+ except Exception:
+ # History records the stored copy, so the check evaluates that copy and stays true to it.
+ logger.exception("Failed to bring a platform logs copy up to date", check_id=str(check.id))
+ current.append(check)
+ continue
+ current.append(replace(check, **{field: getattr(upsert, field) for field in _LIVE_FIELDS}))
+ return current, stopped
+
+
+def _stopped(check: PlatformAlertCheckInput, *, now: datetime) -> Decision:
+ """A check whose logs alert no longer runs. It leaves the state alone and disables the copy."""
+ unchanged = ControlPlaneOutcome(new_state=AlertState(check.state), consecutive_failures=check.consecutive_failures)
+ recorded = _recorded(
+ check,
+ outcome=unchanged,
+ evaluation_key=_evaluation_key(check, now),
+ kind=AlertEventKind.CHECK,
+ notified=False,
+ now=now,
+ disable=True,
+ )
+ _record_check_metrics(
+ check, new_state=check.state, notification=NotificationAction.NONE, skip=SkipReason.SOURCE_RULE, now=now
+ )
+ return recorded, None
+
+
def _triage(checks: Sequence[PlatformAlertCheckInput], *, now: datetime, tz_name: str) -> _Triage:
"""Splits a batch into the checks a query can answer, the ones already decided, and the muted.
@@ -636,11 +709,12 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatc
if team is None:
return SourceBatchEvaluation(outcomes=(), deliveries=())
- triage = _triage(checks, now=cutoff, tz_name=team.timezone)
+ current, stopped = _as_configured_now(checks, team_id=team_id, now=cutoff)
+ triage = _triage(current, 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)
+ return _collect([*stopped, *triage.decided], team_id, slot, started_at)
+ decided = [*stopped, *triage.decided]
# One checkpoint for the pass, matching the production discovery activity. A failure falls
# back to wall-clock rather than ending the batch.
diff --git a/products/logs/backend/facade/api.py b/products/logs/backend/facade/api.py
index 815a9fda32a1..18c5be49ea6a 100644
--- a/products/logs/backend/facade/api.py
+++ b/products/logs/backend/facade/api.py
@@ -1,3 +1,5 @@
+from uuid import UUID
+
from django.db import transaction
from products.logs.backend import alert_incidents
@@ -10,12 +12,14 @@ from products.logs.backend.natural_language_query import (
is_valid_date,
translate_natural_language_query,
)
+from products.logs.backend.tasks.tasks import follow_logs_alert_task
__all__ = [
"NaturalLanguageQueryFailed",
"NaturalLanguageQueryUnavailable",
"close_incident_before_delete",
"close_incident_on_commit",
+ "follow_logs_alert",
"is_valid_date",
"next_allowed_check_at",
"translate_natural_language_query",
@@ -42,6 +46,12 @@ def close_incident_on_commit(
)
+def follow_logs_alert(*, team_id: int, alert_id: UUID) -> None:
+ """Queue the copy of a logs alert that was just created or turned back on, if its team runs logs
+ on the platform. The task retries a transient failure."""
+ follow_logs_alert_task.delay(team_id, str(alert_id))
+
+
def close_incident_before_delete(*, team_id: int, alert_id: str, state: str) -> None:
"""Close a firing alert's incident before the delete removes the functions that deliver it.
diff --git a/products/logs/backend/platform_alert_backfill.py b/products/logs/backend/platform_alert_backfill.py
index 60dd9d501a7e..8a73cac40c68 100644
--- a/products/logs/backend/platform_alert_backfill.py
+++ b/products/logs/backend/platform_alert_backfill.py
@@ -1,7 +1,9 @@
"""One-way copy of logs alert configurations into the skeleton shared tables.
-The control plane stays with the logs product: this reads, never writes back, and nothing
-keeps the copy in sync afterwards. Run it again to pick up changes.
+The control plane stays with the logs product: this reads, never writes back. Each check reads the
+logs alert's current settings, so an edit counts without a rerun. A check can only see a copy that
+is enabled, so the logs API copies an alert created or turned back on in a team that already runs
+logs on the platform.
`legacy_configuration_id` carries the row each copy came from, so a second run updates
rather than duplicates, and a later comparison can line the two stacks up per alert.
@@ -13,10 +15,9 @@ import structlog
from posthog.dataclasses import frozen
-from products.alerts_platform.backend.facade.api import disable_configurations, upsert_configuration
+from products.alerts_platform.backend.facade.api import disable_configurations, upsert_configuration, upsert_if_running
from products.alerts_platform.backend.facade.contracts import SOURCE_CONDITION_KEY, PlatformAlertUpsert, SourceKind
from products.alerts_platform.backend.facade.enums import PlatformAlertState
-from products.logs.backend.alert_source_cycle import LogsAlertCondition
from products.logs.backend.models import LogsAlertConfiguration
logger = structlog.get_logger(__name__)
@@ -31,7 +32,11 @@ class BackfillCounts:
def platform_upsert_of(alert: LogsAlertConfiguration) -> PlatformAlertUpsert:
- """The platform copy of a logs alert, which the backfill writes and every check reads again."""
+ """The platform copy of a logs alert, which the backfill writes and every check reads again.
+
+ The bound is not validated here, so a bound the query cannot read reaches triage and marks the
+ alert BROKEN.
+ """
return PlatformAlertUpsert(
legacy_configuration_id=alert.id,
team_id=alert.team_id,
@@ -40,11 +45,11 @@ def platform_upsert_of(alert: LogsAlertConfiguration) -> PlatformAlertUpsert:
source_kind=SourceKind.LOGS,
source_config={
**alert.filters,
- SOURCE_CONDITION_KEY: LogsAlertCondition(
- threshold_count=alert.threshold_count,
- threshold_operator=alert.threshold_operator,
- window_minutes=alert.window_minutes,
- ).as_source_config(),
+ SOURCE_CONDITION_KEY: {
+ "threshold_count": alert.threshold_count,
+ "threshold_operator": alert.threshold_operator,
+ "window_minutes": alert.window_minutes,
+ },
},
check_interval_minutes=alert.check_interval_minutes,
evaluation_periods=alert.evaluation_periods,
@@ -67,7 +72,7 @@ PLATFORM_HANDOVER_STATE: Final[dict[str, PlatformAlertState]] = {
}
-def is_team_sampled(team_id: int, sample_percent: int) -> bool:
+def _is_team_sampled(team_id: int, sample_percent: int) -> bool:
"""Whether a team falls inside a sample.
Logs samples teams, not alerts, because one query checks a whole cohort of a team's alerts.
@@ -94,7 +99,7 @@ def backfill_platform_alert_configurations(*, team_id: int | None = None, sample
skipped = 0
failed = 0
for configuration in source.iterator():
- if not is_team_sampled(configuration.team_id, sample_percent):
+ if not _is_team_sampled(configuration.team_id, sample_percent):
skipped += 1
continue
# One alert the copy rejects must not stop the rest.
@@ -130,3 +135,12 @@ def disable_platform_alert_configurations(*, team_id: int | None = None) -> int:
disabled = disable_configurations(SourceKind.LOGS, team_id=team_id)
logger.info("platform_alert_backfill.disabled", disabled=disabled, team_id=team_id)
return disabled
+
+
+def follow_logs_alert(alert: LogsAlertConfiguration) -> None:
+ """Copies a logs alert that was just created or turned back on, if its team runs logs on the platform.
+
+ Checks only read enabled copies, so no check would ever see this alert otherwise, and it would
+ stay off the platform until the next backfill.
+ """
+ upsert_if_running(platform_upsert_of(alert), revive=True)
diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.py
index d920df88c46e..1c6ee2473e76 100644
--- a/products/logs/backend/presentation/views/alerts_api.py
+++ b/products/logs/backend/presentation/views/alerts_api.py
@@ -78,6 +78,7 @@ from products.logs.backend.alert_state_machine import (
from products.logs.backend.facade.api import (
close_incident_before_delete,
close_incident_on_commit,
+ follow_logs_alert,
next_allowed_check_at,
)
from products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfiguration, LogsAlertEvent
@@ -619,7 +620,12 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
else:
instance.clear_next_check()
- return super().update(instance, validated_data)
+ updated = super().update(instance, validated_data)
+ if enabled_change is True:
+ transaction.on_commit(
+ lambda: follow_logs_alert(team_id=updated.team_id, alert_id=updated.id), robust=True
+ )
+ return updated
def create(self, validated_data: dict) -> LogsAlertConfiguration:
validated_data["team_id"] = self.context["team_id"]
@@ -646,7 +652,12 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
team_timezone=team.timezone,
schedule_restriction=schedule_restriction,
)
- return super().create(validated_data)
+ created = super().create(validated_data)
+ if created.enabled:
+ transaction.on_commit(
+ lambda: follow_logs_alert(team_id=created.team_id, alert_id=created.id), robust=True
+ )
+ return created
def _validate_filters(filters: dict) -> None:
diff --git a/products/logs/backend/tasks/tasks.py b/products/logs/backend/tasks/tasks.py
index 32ea3bf1a7f5..52f8f8b4eb91 100644
--- a/products/logs/backend/tasks/tasks.py
+++ b/products/logs/backend/tasks/tasks.py
@@ -8,9 +8,42 @@ retention window. That's slow-moving data, daily cadence is fine.
from celery import shared_task
+from posthog.models.scoping import with_team_scope
+from posthog.tasks.utils import CeleryQueue
+
@shared_task(ignore_result=True, name="products.logs.backend.tasks.logs_alert_events_cleanup_task")
def logs_alert_events_cleanup_task() -> None:
from products.logs.backend.models import LogsAlertEvent
LogsAlertEvent.clean_up_old_events()
+
+
+@shared_task(
+ ignore_result=True,
+ queue=CeleryQueue.DEFAULT.value,
+ max_retries=5,
+ autoretry_for=(Exception,),
+ retry_backoff=True,
+ soft_time_limit=60,
+ time_limit=90,
+ name="products.logs.backend.tasks.follow_logs_alert_task",
+)
+@with_team_scope()
+def follow_logs_alert_task(team_id: int, alert_id: str) -> None:
+ """Copies a logs alert that was just created or turned back on onto the platform.
+
+ A task rather than a call in the request, so a transient failure retries. Nothing else
+ discovers a missing copy before the next backfill run. It reads the alert as it is when it
+ runs, so a retry after a later edit copies the edit.
+ """
+ from products.logs.backend.models import (
+ LogsAlertConfiguration, # noqa: PLC0415 — keeps models off the Celery import path
+ )
+ from products.logs.backend.platform_alert_backfill import (
+ follow_logs_alert, # noqa: PLC0415 — keeps the platform off the Celery import path
+ )
+
+ alert = LogsAlertConfiguration.objects.filter(team_id=team_id, id=alert_id).first()
+ if alert is not None:
+ follow_logs_alert(alert)
diff --git a/products/logs/backend/test/test_alert_comparison.py b/products/logs/backend/test/test_alert_comparison.py
index 503ee1db77b0..07ff959d101b 100644
--- a/products/logs/backend/test/test_alert_comparison.py
+++ b/products/logs/backend/test/test_alert_comparison.py
@@ -19,7 +19,7 @@ from products.alerts_platform.backend.facade.contracts import (
from products.alerts_platform.backend.facade.testing import undeclared_policy_divergences
from products.logs.backend.alert_comparison import LOGS_INTENTIONAL_DIVERGENCES, LogsCorrespondence
from products.logs.backend.alert_evaluation_key import window_end_of
-from products.logs.backend.alert_source_cycle import LogsAlertCondition, _evaluation_key
+from products.logs.backend.alert_source_cycle import _evaluation_key
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
CHECKED_AT = datetime(2026, 9, 30, 12, 0, tzinfo=UTC)
@@ -32,9 +32,7 @@ def _check_input(alert_id, *, next_check_at) -> PlatformAlertCheckInput:
team_id=1,
name="API errors",
source_config={
- SOURCE_CONDITION_KEY: LogsAlertCondition(
- threshold_count=10, threshold_operator="above", window_minutes=5
- ).as_source_config()
+ SOURCE_CONDITION_KEY: {"threshold_count": 10, "threshold_operator": "above", "window_minutes": 5}
},
check_interval_minutes=5,
evaluation_periods=1,
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index e44d435a64b4..4d9511422c84 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -15,7 +15,7 @@ from posthog.hogql.errors import ExposedHogQLError
from posthog.models.scoping import team_scope
from products.alerts_platform.backend.facade import testing as platform_testing
-from products.alerts_platform.backend.facade.api import due_checks, record_outcomes, slot_of
+from products.alerts_platform.backend.facade.api import due_checks, list_configurations, record_outcomes, slot_of
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertEventKind,
@@ -43,25 +43,42 @@ from products.logs.backend.temporal.alert_evaluate import (
_MODULE = "products.logs.backend.alert_source_cycle"
CONDITION = {"threshold_count": 10, "threshold_operator": "above", "window_minutes": 5}
_LOGS_OWNED_FIELDS = ("state", "consecutive_failures", "next_check_at", "last_notified_at", "snooze_until")
+# Settings a check reads from the logs alert rather than from its platform copy.
+_LEGACY_ALERT_FIELDS = ("evaluation_periods", "datapoints_to_alarm", "cooldown_minutes", "schedule_restriction")
class TestLogsAlertEvaluation(APIBaseTest):
def setUp(self) -> None:
super().setUp()
self.cutoff = datetime(2026, 9, 16, 10, tzinfo=UTC)
+ # A backfilled copy delivers to the logs alert it came from, so its destinations name that id.
+ self._legacy_ids: dict[UUID, UUID] = {}
+
+ def _legacy_alert(self, source_config: dict[str, Any], **fields: Any) -> LogsAlertConfiguration:
+ filters = {key: value for key, value in source_config.items() if key != "condition"}
+ return LogsAlertConfiguration.objects.create(
+ team=self.team, name="API errors", filters=filters, **source_config["condition"], **fields
+ )
def _configuration(self, **overrides: Any) -> PlatformConfigurationSnapshot:
+ """A platform copy, with the logs alert it was copied from, since every check reads that alert."""
+ source_config = overrides.pop("source_config", {"condition": CONDITION})
+ if "legacy_configuration_id" not in overrides:
+ legacy_fields = {field: overrides[field] for field in _LEGACY_ALERT_FIELDS if field in overrides}
+ overrides["legacy_configuration_id"] = self._legacy_alert(source_config, **legacy_fields).id
defaults: dict[str, Any] = {
"team_id": self.team.id,
"name": "API errors",
"source_kind": SourceKind.LOGS,
- "source_config": {"condition": CONDITION},
+ "source_config": source_config,
"check_interval_minutes": 10,
"next_check_at": self.cutoff - timedelta(minutes=1),
}
defaults.update(overrides)
with team_scope(self.team.id):
- return platform_testing.create_configuration(**defaults)
+ configuration = platform_testing.create_configuration(**defaults)
+ self._legacy_ids[configuration.id] = defaults["legacy_configuration_id"]
+ return configuration
def _run(
self,
@@ -97,7 +114,12 @@ class TestLogsAlertEvaluation(APIBaseTest):
"source": "internal-events",
"events": [{"id": "$logs_alert_incident_closed", "type": "events"}],
"properties": [
- {"key": "alert_id", "value": str(configuration.id), "operator": "exact", "type": "event"}
+ {
+ "key": "alert_id",
+ "value": str(self._legacy_ids[configuration.id]),
+ "operator": "exact",
+ "type": "event",
+ }
],
},
)
@@ -115,16 +137,15 @@ class TestLogsAlertEvaluation(APIBaseTest):
@parameterized.expand(
[
- ("without_a_paging_destination", False, "source", None),
- ("with_a_paging_destination", True, "source", None),
- ("owned_by_the_platform", False, "platform", None),
- ("copied_from_a_logs_alert", False, "source", UUID("01936a2e-0000-7000-8000-00000000abcd")),
+ ("without_a_paging_destination", False, "source"),
+ ("with_a_paging_destination", True, "source"),
+ ("owned_by_the_platform", False, "platform"),
]
)
def test_a_breaching_configuration_fires_and_records_its_own_state(
- self, _name: str, paged: bool, owner: str, legacy_id: UUID | None
+ self, _name: str, paged: bool, owner: str
) -> None:
- configuration = self._configuration(owner=owner, legacy_configuration_id=legacy_id)
+ configuration = self._configuration(owner=owner)
if paged:
self._add_incident_destination(configuration)
@@ -137,11 +158,9 @@ class TestLogsAlertEvaluation(APIBaseTest):
]
# The event a PagerDuty destination subscribes to, so the trigger reaches it.
assert evaluation.deliveries[0].event_ids_by_incident_action["trigger"] == "$logs_alert_incident_opened"
- # Only an alert copied from a logs alert has a logs alert page to link to.
source_alert_url = evaluation.deliveries[0].source_alert_url
- assert (source_alert_url.endswith(f"/logs/alerts/{legacy_id}") if source_alert_url else None) == (
- True if legacy_id else None
- )
+ assert source_alert_url is not None
+ assert source_alert_url.endswith(f"/logs/alerts/{self._legacy_ids[configuration.id]}")
with team_scope(self.team.id):
alert = platform_testing.alert_for(configuration.id)
assert alert is not None
@@ -300,10 +319,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
@parameterized.expand(
[
("filter_group", {"condition": CONDITION, "filterGroup": {"type": "nonsense"}}),
- ("missing_condition", {}),
- ("null_condition", {"condition": None}),
("unknown_operator", {"condition": {**CONDITION, "threshold_operator": "equals"}}),
- ("non_numeric_window", {"condition": {**CONDITION, "window_minutes": "5"}}),
("zero_window", {"condition": {**CONDITION, "window_minutes": 0}}),
("null_filter_values", {"condition": CONDITION, "filterGroup": {"type": "AND", "values": None}}),
]
@@ -358,6 +374,58 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert platform_testing.alert_for(configuration.id) is None
assert configuration.next_check_at == self.cutoff - timedelta(minutes=1)
+ @parameterized.expand(
+ [
+ ("edited_since_the_backfill", "edit", True, 1000),
+ ("disabled_since_the_backfill", "disable", False, 10),
+ ("deleted_since_the_backfill", "delete", False, 10),
+ ]
+ )
+ def test_a_check_follows_the_logs_alert_as_it_is_now(
+ self, _name: str, change: str, still_runs: bool, stored_threshold: int
+ ) -> None:
+ configuration = self._configuration()
+ legacy = LogsAlertConfiguration.objects.get(id=self._legacy_ids[configuration.id])
+ if change == "edit":
+ # Copied as "above 10", which 500 logs breach. The logs alert now asks for over 1000.
+ LogsAlertConfiguration.objects.filter(id=legacy.id).update(threshold_count=1000)
+ elif change == "disable":
+ LogsAlertConfiguration.objects.filter(id=legacy.id).update(enabled=False)
+ else:
+ legacy.delete()
+
+ evaluation, query = self._run(configuration)
+ self._record(evaluation)
+
+ assert [o.kind for o in evaluation.outcomes] == [AlertEventKind.CHECK]
+ assert query.called is still_runs
+ with team_scope(self.team.id):
+ (copy,) = list_configurations(
+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], limit=10, offset=0
+ ).configurations
+ assert copy.enabled is still_runs
+ # History and messages read the stored copy, so it has to state what the check evaluated.
+ assert copy.source_config["condition"]["threshold_count"] == stored_threshold
+
+ def test_a_logs_alert_with_unreadable_filters_breaks_alone(self) -> None:
+ unreadable, healthy = self._configuration(), self._configuration()
+ LogsAlertConfiguration.objects.filter(id=self._legacy_ids[unreadable.id]).update(filters=[])
+
+ evaluation, _ = self._run(unreadable, healthy)
+
+ states = {o.configuration_id: o.new_state for o in evaluation.outcomes}
+ assert states == {unreadable.id: "broken", healthy.id: "firing"}
+
+ def test_a_check_whose_copy_cannot_be_updated_evaluates_the_stored_copy(self) -> None:
+ configuration = self._configuration()
+ # Copied as "above 10", which 500 logs breach. The logs alert now asks for over 1000.
+ LogsAlertConfiguration.objects.filter(id=self._legacy_ids[configuration.id]).update(threshold_count=1000)
+
+ with patch(f"{_MODULE}.refresh_settings", side_effect=RuntimeError("database blip")):
+ evaluation, _ = self._run(configuration)
+
+ assert [o.new_state for o in evaluation.outcomes] == ["firing"]
+
def test_the_logs_product_rows_are_never_written(self) -> None:
legacy = LogsAlertConfiguration.objects.create(
team=self.team,
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index 890eaf7790b6..49bca12a2896 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -3,18 +3,25 @@ from datetime import UTC, datetime, timedelta
from typing import Any
from uuid import uuid4
+import pytest
import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
+from django.db import OperationalError
+
+from celery.exceptions import Retry
from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
from posthog.clickhouse.client import sync_execute
+from posthog.models.scoping import team_scope
from posthog.models.team.team import Team
from posthog.models.user import User
+from products.alerts_platform.backend.facade.api import list_configurations
+from products.alerts_platform.backend.facade.contracts import SourceKind
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cdp.backend.templates.fixtures import template_pagerduty, template_slack
@@ -22,12 +29,17 @@ from products.cdp.backend.templates.hog_function_template import sync_template_t
from products.cdp.backend.templates.microsoft_teams.template_microsoft_teams import template as template_microsoft_teams
from products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCount
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
+from products.logs.backend.platform_alert_backfill import (
+ backfill_platform_alert_configurations,
+ disable_platform_alert_configurations,
+)
from products.logs.backend.presentation.views.alerts_api import (
ALLOWED_WINDOW_MINUTES,
MAX_ALERTS_PER_TEAM,
MAX_DESTINATION_IDS_PER_DELETE_REQUEST,
LogsAlertViewSet,
)
+from products.logs.backend.tasks.tasks import follow_logs_alert_task
PAGERDUTY_ROUTING_KEY = "0123456789abcdef0123456789abcdef"
@@ -378,6 +390,63 @@ class TestLogsAlertAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["attr"] == "filters"
+ @parameterized.expand(
+ [
+ ("created_in_a_team_running_logs_on_the_platform", "create", "running", True),
+ ("created_in_a_team_outside_the_sample", "create", "not_backfilled", None),
+ ("turned_back_on_in_a_team_running_logs_on_the_platform", "enable", "running", True),
+ ("turned_back_on_after_the_team_was_switched_off", "enable", "switched_off", False),
+ ]
+ )
+ def test_a_created_or_reenabled_alert_follows_its_team_onto_the_platform(
+ self, _name: str, write: str, team_run: str, copy_enabled: bool | None
+ ) -> None:
+ self._create_via_api(name="Already on the platform")
+ dormant = self._create_via_api(name="Turned back on", enabled=False)
+ if team_run != "not_backfilled":
+ backfill_platform_alert_configurations(team_id=self.team.id)
+ if team_run == "switched_off":
+ disable_platform_alert_configurations(team_id=self.team.id)
+
+ with self.captureOnCommitCallbacks(execute=True):
+ if write == "create":
+ alert_id = self._create_via_api(name="New alert")["id"]
+ else:
+ alert_id = dormant["id"]
+ response = self.client.patch(f"{self.base_url}{alert_id}/", {"enabled": True}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ with team_scope(self.team.id):
+ copies = list_configurations(
+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], limit=10, offset=0
+ ).configurations
+ copy = next((view for view in copies if str(view.legacy_configuration_id) == alert_id), None)
+ assert (copy.enabled if copy else None) is copy_enabled
+
+ def test_a_copy_that_fails_is_handed_to_celery_to_retry(self) -> None:
+ self._create_via_api(name="Already on the platform")
+ backfill_platform_alert_configurations(team_id=self.team.id)
+ alert_id = self._create_via_api(name="New alert", enabled=False)["id"]
+ LogsAlertConfiguration.objects.filter(id=alert_id).update(enabled=True)
+
+ with (
+ patch(
+ "products.logs.backend.platform_alert_backfill.upsert_if_running",
+ side_effect=OperationalError("connection reset"),
+ ),
+ pytest.raises(Retry),
+ ):
+ follow_logs_alert_task.apply(args=[self.team.id, alert_id])
+ # Celery's eager mode stops at the retry, so the second attempt runs by hand.
+ retried = follow_logs_alert_task.apply(args=[self.team.id, alert_id])
+
+ with team_scope(self.team.id):
+ copies = list_configurations(
+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], limit=10, offset=0
+ ).configurations
+ assert retried.state == "SUCCESS"
+ assert {str(view.legacy_configuration_id): view.enabled for view in copies}.get(alert_id) is True
+
# --- first_enabled_at stamping ---
def test_first_enabled_at_stamped_on_first_enable(self):