:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): read and reset platform state for moved logs alerts (#117318)
Jimmy Zhu5c58b85cc30d
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.pyindex fb1d2184018c..ffd7dc4f3996 100644--- a/products/alerts_platform/backend/facade/api.py+++ b/products/alerts_platform/backend/facade/api.py@@ -17,6 +17,7 @@ from products.alerts_platform.backend.facade.contracts import (PlatformAlertConfigurationPage,PlatformAlertConfigurationView,PlatformAlertOutcome,+ PlatformAlertRuntime,PlatformAlertUpsert,PlatformHandback,PlatformOwnershipHandover,@@ -81,6 +82,11 @@ def give_back_ownership()+def reset_broken(*, team_id: int, legacy_configuration_id: UUID, at: datetime) -> int | None:+ """Clears a broken alert the platform owns. Returns the failure count it cleared, or None when not broken."""+ return platform_lifecycle.reset_broken(team_id=team_id, legacy_configuration_id=legacy_configuration_id, at=at)++def disable_configurations(source_kind: SourceKind, *, team_id: int | None = None, legacy_configuration_ids: Collection[UUID] | None = None) -> int:@@ -104,3 +110,10 @@ def get_configuration(return platform_reads.get_configuration(team_id=team_id, source_kinds=source_kinds, configuration_id=configuration_id)+++def runtime_by_legacy_id(+ *, team_id: int, legacy_configuration_ids: Collection[UUID]+) -> dict[UUID, PlatformAlertRuntime]:+ """The runtime state of each named alert the platform owns, keyed by the source's id."""+ return platform_reads.runtime_by_legacy_id(team_id=team_id, legacy_configuration_ids=legacy_configuration_ids)diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex 401df1112478..10283a9f4c2e 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -339,6 +339,16 @@ class PlatformHandback:next_check_at: datetime | None+@frozen+class PlatformAlertRuntime:+ """Where an alert the platform owns stands, for a source whose API still shows the alert."""++ state: PlatformAlertState+ last_notified_at: datetime | None+ consecutive_failures: int+ next_check_at: datetime | None++class SkipReason(StrEnum):"""Why a check reached an outcome without a query answering it.diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.pyindex e4e015ae14bf..9a577461d48c 100644--- a/products/alerts_platform/backend/logic/platform_lifecycle.py+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py@@ -748,6 +748,35 @@ def give_back_ownership(return handback+def reset_broken(*, team_id: int, legacy_configuration_id: UUID, at: datetime) -> int | None:+ """Clears a broken alert the platform owns so the next tick checks it again, from rest.++ Returns the failure count it cleared, or None when the alert is not broken. Discovery skips a+ broken alert, so without this it never runs again. The caller holds the source's row lock.+ """+ with transaction.atomic():+ configuration = (+ PlatformAlertConfiguration.objects.for_team(team_id)+ .select_for_update()+ .get(legacy_configuration_id=legacy_configuration_id)+ )+ if configuration.owner != PlatformAlertOwner.PLATFORM:+ raise ValueError("the platform does not own this alert, so its source resets it")+ if configuration.check_status != PlatformAlertConfiguration.CheckStatus.BROKEN:+ return None+ cleared = configuration.consecutive_failures+ configuration.check_status = PlatformAlertConfiguration.CheckStatus.OK+ configuration.consecutive_failures = 0+ configuration.next_check_at = at+ configuration.save(update_fields=["check_status", "consecutive_failures", "next_check_at"])+ # A failed check keeps a firing so a recovery continues it. A reset starts clean instead, or+ # the next breach would find the old episode open and announce nothing.+ PlatformAlert.objects.for_team(team_id).filter(configuration=configuration).update(+ state=PlatformAlertState.NOT_FIRING.value, firing_started_at=None+ )+ return cleared++def disable_configurations(source_kind: str, *, team_id: int | None = None, legacy_configuration_ids: Collection[UUID] | None = None) -> int:diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.pyindex 73b9fd29c31e..7c1686e72d57 100644--- a/products/alerts_platform/backend/logic/platform_reads.py+++ b/products/alerts_platform/backend/logic/platform_reads.py@@ -4,17 +4,19 @@ Separate from `platform_lifecycle`, which serves the source adapters. These servoutside the product, so they return views rather than rows and never change one."""-from collections.abc import Sequence+from collections.abc import Collection, Sequencefrom uuid import UUID-from django.db.models import Prefetch, QuerySet+from django.db.models import OuterRef, Prefetch, QuerySet, Subqueryfrom products.alerts_platform.backend.facade.contracts import (InstanceCheckState,PlatformAlertConfigurationPage,PlatformAlertConfigurationView,+ PlatformAlertRuntime,PlatformAlertSnapshot,)+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, PlatformAlertStatefrom products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration@@ -113,3 +115,50 @@ def alert_snapshot(team_id: int, configuration_id: str, grouping_key: str) -> Pl.first())return instance_view(alert, alert.configuration) if alert is not None else None+++def runtime_by_legacy_id(+ *, team_id: int, legacy_configuration_ids: Collection[UUID]+) -> dict[UUID, PlatformAlertRuntime]:+ """The runtime state of each named alert the platform owns, keyed by the source's id, in one query.++ An alert the platform does not own is left out, because its source's own row is then the one+ that moves. Only the ungrouped instance is read: a source that shows one state per alert has+ no groups, and a copy with no instance yet has not been checked since the handover.+ """+ if not legacy_configuration_ids:+ return {}+ ungrouped = PlatformAlert.objects.for_team(team_id).filter(configuration=OuterRef("pk"), grouping_key="")+ rows = (+ PlatformAlertConfiguration.objects.for_team(team_id)+ .filter(legacy_configuration_id__in=list(legacy_configuration_ids), owner=PlatformAlertOwner.PLATFORM)+ .annotate(+ instance_state=Subquery(ungrouped.values("state")[:1]),+ instance_last_notified_at=Subquery(ungrouped.values("last_notified_at")[:1]),+ )+ .values_list(+ "legacy_configuration_id",+ "instance_state",+ "check_status",+ "instance_last_notified_at",+ "consecutive_failures",+ "next_check_at",+ )+ )+ return {+ legacy_id: PlatformAlertRuntime(+ state=PlatformAlertState(+ InstanceCheckState.composed(+ grouping_key="",+ state=state or PlatformAlertState.NOT_FIRING,+ check_status=check_status,+ configuration_snooze_until=None,+ ).state+ ),+ last_notified_at=last_notified_at,+ consecutive_failures=consecutive_failures,+ next_check_at=next_check_at,+ )+ for legacy_id, state, check_status, last_notified_at, consecutive_failures, next_check_at in rows+ if legacy_id is not None+ }diff --git a/products/logs/backend/facade/api.py b/products/logs/backend/facade/api.pyindex 18c5be49ea6a..896d7990a45a 100644--- a/products/logs/backend/facade/api.py+++ b/products/logs/backend/facade/api.py@@ -12,6 +12,7 @@ from products.logs.backend.natural_language_query import (is_valid_date,translate_natural_language_query,)+from products.logs.backend.platform_alert_backfill import logs_state_of_platformfrom products.logs.backend.tasks.tasks import follow_logs_alert_task__all__ = [@@ -21,6 +22,7 @@ __all__ = ["close_incident_on_commit","follow_logs_alert","is_valid_date",+ "logs_state_of_platform","next_allowed_check_at","translate_natural_language_query",]diff --git a/products/logs/backend/platform_alert_backfill.py b/products/logs/backend/platform_alert_backfill.pyindex 8a5f906bc0df..912f2ff24b43 100644--- a/products/logs/backend/platform_alert_backfill.py+++ b/products/logs/backend/platform_alert_backfill.py@@ -76,25 +76,25 @@ PLATFORM_HANDOVER_STATE: Final[dict[str, PlatformAlertState]] = {}-def logs_state_after_handback(- alert: LogsAlertConfiguration, platform_state: PlatformAlertState, at: datetime+def logs_state_of_platform(+ platform_state: PlatformAlertState, *, logs_state: str, snooze_until: datetime | None, at: datetime) -> AlertState:- """The logs state for an alert the platform hands back, the inverse of `PLATFORM_HANDOVER_STATE`.+ """The logs state for a platform state, the inverse of `PLATFORM_HANDOVER_STATE`.++ A handback and the API's read of an alert the platform owns both use it. Only the read can+ see a firing, because the platform keeps a firing alert until it resolves.The platform keeps a mute on `snooze_until` rather than as a state, and the logs API keptwriting snoozes to the logs row, so an active one stays the logs state."""- if (- alert.state == LogsAlertConfiguration.State.SNOOZED- and alert.snooze_until is not None- and alert.snooze_until > at- ):+ if logs_state == LogsAlertConfiguration.State.SNOOZED and snooze_until is not None and snooze_until > at:return AlertState.SNOOZED- return _LOGS_STATE_AFTER_HANDBACK[platform_state]+ return _LOGS_STATE_OF_PLATFORM[platform_state]-_LOGS_STATE_AFTER_HANDBACK: Final[dict[PlatformAlertState, AlertState]] = {+_LOGS_STATE_OF_PLATFORM: Final[dict[PlatformAlertState, AlertState]] = {PlatformAlertState.NOT_FIRING: AlertState.NOT_FIRING,+ PlatformAlertState.FIRING: AlertState.FIRING,PlatformAlertState.SNOOZED: AlertState.NOT_FIRING,PlatformAlertState.ERRORED: AlertState.ERRORED,PlatformAlertState.BROKEN: AlertState.BROKEN,diff --git a/products/logs/backend/platform_cutover.py b/products/logs/backend/platform_cutover.pyindex 3096a8a231d3..287f210fc002 100644--- a/products/logs/backend/platform_cutover.py+++ b/products/logs/backend/platform_cutover.py@@ -24,7 +24,7 @@ from products.logs.backend.cutover_gate import CutoverRefused, TeamGatefrom products.logs.backend.models import LogsAlertConfiguration, LogsAlertEventfrom products.logs.backend.platform_alert_backfill import (PLATFORM_HANDOVER_STATE,- logs_state_after_handback,+ logs_state_of_platform,platform_upsert_of,)@@ -174,7 +174,9 @@ def _roll_back_alert(alert_id: UUID, now: datetime | None) -> RollbackSkip | Nonupdate_fields = apply_outcome(alert,ControlPlaneOutcome(- new_state=logs_state_after_handback(alert, handback.state, at),+ new_state=logs_state_of_platform(+ handback.state, logs_state=alert.state, snooze_until=alert.snooze_until, at=at+ ),consecutive_failures=handback.consecutive_failures,),kind=LogsAlertEvent.Kind.HANDBACK,diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.pyindex 1c6ee2473e76..fd33844c6e91 100644--- a/products/logs/backend/presentation/views/alerts_api.py+++ b/products/logs/backend/presentation/views/alerts_api.py@@ -2,10 +2,11 @@ import osimport datetime as dtfrom datetime import UTC, datetimefrom typing import Any, Final, Literal, TypedDict, cast+from uuid import UUIDfrom zoneinfo import ZoneInfofrom django.db import transaction-from django.db.models import F, OuterRef, Prefetch, Q, QuerySet, Subquery+from django.db.models import F, Manager, OuterRef, Prefetch, Q, QuerySet, Subqueryfrom django.shortcuts import get_object_or_404from django.utils import timezone@@ -41,12 +42,14 @@ from products.alerts.backend.facade.destinations import (soft_delete_all_alert_destinations,validate_destination_data,)+from products.alerts_platform.backend.facade.api import reset_broken, runtime_by_legacy_idfrom products.alerts_platform.backend.facade.contracts import (AlertDestinationData,AlertDestinationValidationError,DestinationType,PagerDutyRegion,PagerDutySeverity,+ PlatformAlertRuntime,)from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_restrictionfrom products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionField@@ -79,6 +82,7 @@ from products.logs.backend.facade.api import (close_incident_before_delete,close_incident_on_commit,follow_logs_alert,+ logs_state_of_platform,next_allowed_check_at,)from products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfiguration, LogsAlertEvent@@ -204,6 +208,24 @@ class LogsAlertDestinationConfigSerializer(LogsAlertDestinationResponseSerialize)+_PLATFORM_RUNTIME_CONTEXT_KEY: Final = "platform_runtime"+++def _platform_runtime_of(alerts: list[LogsAlertConfiguration]) -> dict[UUID, PlatformAlertRuntime]:+ owned = [alert for alert in alerts if alert.platform_owned]+ if not owned:+ return {}+ return runtime_by_legacy_id(team_id=owned[0].team_id, legacy_configuration_ids=[alert.id for alert in owned])+++class LogsAlertConfigurationListSerializer(serializers.ListSerializer):+ def to_representation(self, data: Any) -> list[dict[str, Any]]:+ alerts = list(data.all() if isinstance(data, Manager) else data)+ # One platform read for the page, which the child serializer finds in the shared context.+ self.context[_PLATFORM_RUNTIME_CONTEXT_KEY] = _platform_runtime_of(alerts)+ return super().to_representation(alerts)++class LogsAlertConfigurationSerializer(serializers.ModelSerializer):id = serializers.UUIDField(read_only=True,@@ -453,8 +475,28 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):.first())+ def to_representation(self, instance: LogsAlertConfiguration) -> dict[str, Any]:+ data = super().to_representation(instance)+ if not instance.platform_owned:+ return data+ # The platform evaluates an alert it owns, so the logs row stops moving once the shadow ends.+ runtimes = self.context.get(_PLATFORM_RUNTIME_CONTEXT_KEY)+ if runtimes is None:+ runtimes = _platform_runtime_of([instance])+ runtime = runtimes.get(instance.id)+ if runtime is None:+ return data+ data["state"] = logs_state_of_platform(+ runtime.state, logs_state=instance.state, snooze_until=instance.snooze_until, at=timezone.now()+ ).value+ data["consecutive_failures"] = runtime.consecutive_failures+ data["next_check_at"] = self.fields["next_check_at"].to_representation(runtime.next_check_at)+ data["last_notified_at"] = self.fields["last_notified_at"].to_representation(runtime.last_notified_at)+ return data+class Meta:model = LogsAlertConfiguration+ list_serializer_class = LogsAlertConfigurationListSerializerfields = ["id","name",@@ -1190,16 +1232,30 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)@action(detail=True, methods=["POST"], url_path="reset", required_scopes=["logs:write"])def reset(self, request: Request, *args: object, **kwargs: object) -> Response:- alert = self.get_object()- previous_failures = alert.consecutive_failures- try:- outcome = apply_user_reset(alert.to_snapshot())- except InvalidTransition:- raise ValidationError({"state": "Only broken alerts can be reset."})with transaction.atomic():- update_fields = apply_outcome(alert, outcome, kind=LogsAlertEvent.Kind.RESET)- update_fields.extend(alert.clear_next_check())- alert.save(update_fields=update_fields)+ # The logs row first, then the platform copy: the cutover and rollback take the two+ # locks in that order, and the opposite order deadlocks against them.+ alert = self._get_locked_alert()+ previous_failures = alert.consecutive_failures+ if alert.platform_owned:+ # The platform skips a broken alert, so the reset has to reach its copy. Its state+ # decides, because the logs row stops moving once the shadow ends.+ platform_failures = reset_broken(+ team_id=alert.team_id, legacy_configuration_id=alert.id, at=timezone.now()+ )+ if platform_failures is None:+ raise ValidationError({"state": "Only broken alerts can be reset."})+ previous_failures = platform_failures+ try:+ outcome = apply_user_reset(alert.to_snapshot())+ except InvalidTransition:+ if not alert.platform_owned:+ raise ValidationError({"state": "Only broken alerts can be reset."})+ outcome = None+ if outcome is not None:+ update_fields = apply_outcome(alert, outcome, kind=LogsAlertEvent.Kind.RESET)+ update_fields.extend(alert.clear_next_check())+ alert.save(update_fields=update_fields)# The model's auto-signal skips these fields (signal_exclusions silences# engine-driven churn) so we log the user-initiated reset explicitly.log_activity(diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex 3d13fafc6b39..c1f9dcd6ca89 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -8,7 +8,8 @@ import time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import MagicMock, patch-from django.db import OperationalError+from django.db import OperationalError, connection+from django.test.utils import CaptureQueriesContextfrom celery.exceptions import Retryfrom parameterized import parameterized@@ -20,6 +21,7 @@ from posthog.models.scoping import team_scopefrom posthog.models.team.team import Teamfrom posthog.models.user import User+from products.alerts_platform.backend.facade import testing as platform_testingfrom products.alerts_platform.backend.facade.api import list_configurationsfrom products.alerts_platform.backend.facade.contracts import SourceKindfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplate@@ -33,6 +35,7 @@ from products.logs.backend.platform_alert_backfill import (backfill_platform_alert_configurations,disable_platform_alert_configurations,)+from products.logs.backend.platform_cutover import cut_over_teamfrom products.logs.backend.presentation.views.alerts_api import (ALLOWED_WINDOW_MINUTES,MAX_ALERTS_PER_TEAM,@@ -163,6 +166,42 @@ class TestLogsAlertAPI(APIBaseTest):assert results[0]["name"] == "Alert 2"assert results[1]["name"] == "Alert 1"+ @parameterized.expand([("list",), ("retrieve",)])+ def test_a_platform_owned_alert_reports_the_platform_state(self, action: str) -> None:+ now = datetime.now(UTC)+ alerts = [+ LogsAlertConfiguration.objects.create(+ team=self.team,+ name=f"Errors {i}",+ filters={"severityLevels": ["error"]},+ next_check_at=now + timedelta(minutes=3),+ last_notified_at=now - timedelta(days=1),+ )+ for i in range(2)+ ]+ cut_over_team(self.team.id, now=now)+ platform_due_at = now + timedelta(minutes=7)+ with team_scope(self.team.id):+ for alert in alerts:+ copy_id = platform_testing.copy_of(alert.id).id+ platform_testing.start_firing(copy_id, team_id=self.team.id, at=now)+ platform_testing.set_due_at(copy_id, platform_due_at)++ with CaptureQueriesContext(connection) as queries:+ if action == "list":+ response = self.client.get(self.base_url)+ rows = response.json()["results"]+ else:+ response = self.client.get(f"{self.base_url}{alerts[0].id}/")+ rows = [response.json()]++ assert response.status_code == status.HTTP_200_OK+ assert [(row["state"], row["next_check_at"]) for row in rows] == [+ ("firing", platform_due_at.isoformat().replace("+00:00", "Z"))+ ] * len(rows)+ platform_reads = [q for q in queries.captured_queries if "alerts_platformalertconfiguration" in q["sql"]]+ assert len(platform_reads) == 1+def test_list_filters_by_created_by(self):other_user = User.objects.create_and_join(self.organization, "[email protected]", None)self._create_via_api(name="My alert")@@ -1561,6 +1600,54 @@ class TestLogsAlertAPI(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "Only broken alerts can be reset." in str(response.json())+ @parameterized.expand(+ [+ ("both_broken_inside_the_shadow", "broken", "broken", False, status.HTTP_200_OK),+ ("platform_broke_after_the_shadow", "broken", "not_firing", False, status.HTTP_200_OK),+ ("broke_while_firing", "broken", "not_firing", True, status.HTTP_200_OK),+ ("only_the_frozen_logs_row_is_broken", "not_firing", "broken", False, status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_reset_of_a_platform_owned_alert_clears_the_platform_copy(+ self,+ _name: str,+ state_at_cutover: str,+ logs_state_after: str,+ fired_before_breaking: bool,+ expected_status: int,+ ) -> None:+ now = datetime.now(UTC)+ alert = LogsAlertConfiguration.objects.create(+ team=self.team,+ name="Errors",+ filters={"severityLevels": ["error"]},+ state=state_at_cutover,+ consecutive_failures=5 if state_at_cutover == "broken" else 0,+ next_check_at=now + timedelta(minutes=3),+ )+ cut_over_team(self.team.id, now=now)+ LogsAlertConfiguration.objects.filter(pk=alert.id).update(state=logs_state_after)+ if fired_before_breaking:+ with team_scope(self.team.id):+ platform_testing.start_firing(platform_testing.copy_of(alert.id).id, team_id=self.team.id, at=now)++ response = self.client.post(self._reset_url(str(alert.id)))++ assert response.status_code == expected_status, response.json()+ if expected_status != status.HTTP_200_OK:+ return+ assert (response.json()["state"], response.json()["consecutive_failures"]) == ("not_firing", 0)+ with team_scope(self.team.id):+ copy = platform_testing.copy_of(alert.id)+ platform_alert = platform_testing.alert_for(copy.id)+ assert platform_alert is not None+ assert (platform_alert.state, platform_alert.firing_started_at, copy.consecutive_failures) == (+ "not_firing",+ None,+ 0,+ )+ assert self.client.post(self._reset_url(str(alert.id))).status_code == status.HTTP_400_BAD_REQUEST+def test_reset_other_teams_alert_returns_404(self):other_team = Team.objects.create(organization=self.organization, name="Other")other_alert = LogsAlertConfiguration.objects.create(