: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 timeline and last check from platform history for moved alerts (#117332)
Jimmy Zhu7af1a5d2a451
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.pyindex ffd7dc4f3996..945e8f6d61d4 100644--- a/products/alerts_platform/backend/facade/api.py+++ b/products/alerts_platform/backend/facade/api.py@@ -16,6 +16,7 @@ from products.alerts_platform.backend.facade.contracts import (PlatformAlertCheckInput,PlatformAlertConfigurationPage,PlatformAlertConfigurationView,+ PlatformAlertHistory,PlatformAlertOutcome,PlatformAlertRuntime,PlatformAlertUpsert,@@ -117,3 +118,15 @@ def runtime_by_legacy_id() -> 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)+++def history_by_legacy_id(+ *, team_id: int, legacy_configuration_ids: Collection[UUID], since: datetime, until: datetime+) -> dict[UUID, PlatformAlertHistory]:+ """The check history in a window of each named alert the platform owns, keyed by the source's id.++ Raises when ClickHouse fails, so a caller can fall back to what it shows without the platform.+ """+ return platform_reads.history_by_legacy_id(+ team_id=team_id, legacy_configuration_ids=legacy_configuration_ids, since=since, until=until+ )diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex 10283a9f4c2e..810e7472a485 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -349,6 +349,29 @@ class PlatformAlertRuntime:next_check_at: datetime | None+@frozen+class PlatformStateChange:+ """One check that moved an alert the platform owns from one state to another."""++ occurred_at: datetime+ previous_state: PlatformAlertState+ state: PlatformAlertState+++@frozen+class PlatformAlertHistory:+ """What the platform's check history says about an alert it owns, over one window.++ An alert the platform did not check in the window has no history at all, so a source can+ tell "not checked here" from "checked and succeeded".+ """++ state_changes: tuple[PlatformStateChange, ...]+ last_checked_at: datetime+ # None when the last check in the window succeeded.+ last_error_message: str | None++class SkipReason(StrEnum):"""Why a check reached an outcome without a query answering it.diff --git a/products/alerts_platform/backend/facade/testing.py b/products/alerts_platform/backend/facade/testing.pyindex 75385768031e..2811ebdae122 100644--- a/products/alerts_platform/backend/facade/testing.py+++ b/products/alerts_platform/backend/facade/testing.py@@ -17,7 +17,9 @@ from products.alerts_platform.backend.facade.contracts import (PlatformAlertSnapshot,PlatformConfigurationSnapshot,SourceCorrespondence,+ SourceKind,)+from products.alerts_platform.backend.logic.platform_alert_events import PlatformAlertEventRow, insert_eventsfrom products.alerts_platform.backend.logic.platform_reads import instance_viewfrom products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration@@ -78,6 +80,51 @@ def start_firing(configuration_id: UUID, *, team_id: int, at: datetime) -> None:)+def set_check_status(configuration_id: UUID, check_status: str) -> None:+ """Mark a configuration's checks as failing or not, as checks outside the test can leave it."""+ # nosemgrep: idor-lookup-without-team — fail-closed model; the caller holds the team scope+ PlatformAlertConfiguration.objects.filter(id=configuration_id).update(check_status=check_status)+++def record_check(+ configuration_id: UUID,+ *,+ team_id: int,+ at: datetime,+ previous_state: str,+ state: str,+ error_message: str | None = None,+) -> None:+ """Write one ungrouped check to the platform's ClickHouse history, as a check that ran at `at`."""+ insert_events(+ team_id,+ [+ PlatformAlertEventRow(+ team_id=team_id,+ source_kind=SourceKind.LOGS.value,+ configuration_id=configuration_id,+ alert_id=configuration_id,+ grouping_key="",+ evaluation_key=f"slot:{at.isoformat()}",+ kind="check",+ alert_name="",+ previous_state=previous_state,+ state=state,+ episode_started_at=None,+ value=None,+ labels={},+ condition_snapshot={},+ source_config_snapshot={},+ query_duration_ms=None,+ error_message=error_message,+ consecutive_failures=0,+ muted_notification="",+ occurred_at=at,+ )+ ],+ )++def alert_for(configuration_id: UUID, *, grouping_key: str = "") -> PlatformAlertSnapshot | None:"""The instance row a check wrote, or None when no check has written one."""row = (diff --git a/products/alerts_platform/backend/logic/platform_alert_events.py b/products/alerts_platform/backend/logic/platform_alert_events.pyindex bc3d1ed1b3ab..b0309e6c8f81 100644--- a/products/alerts_platform/backend/logic/platform_alert_events.py+++ b/products/alerts_platform/backend/logic/platform_alert_events.py@@ -29,8 +29,11 @@ from products.alerts_platform.backend.facade.contracts import (AlertEventKind,AnnouncedTransition,EvaluationAnnouncement,+ PlatformAlertHistory,+ PlatformStateChange,SourceKind,)+from products.alerts_platform.backend.facade.enums import PlatformAlertStatefrom products.alerts_platform.backend.models.platform_alert_events_sql import PLATFORM_ALERT_EVENTS_TABLElogger = structlog.get_logger(__name__)@@ -228,3 +231,69 @@ def _snapshot(raw: str) -> dict[str, Any]:except ValueError:return {}return loaded if isinstance(loaded, dict) else {}+++# The inner read deduplicates on the pair the writer names, as `announcement` does. The outer one+# keeps the checks that moved the alert and the newest check, so a page of alerts that check every+# minute returns a few rows each rather than a day of them.+_HISTORY_SQL = f"""+SELECT configuration_id, occurred_at, previous_state, state, error_message, is_latest+FROM (+ SELECT configuration_id, occurred_at, previous_state, state, error_message,+ occurred_at = max(occurred_at) OVER (PARTITION BY configuration_id) AS is_latest+ FROM (+ SELECT configuration_id, alert_id, evaluation_key, occurred_at, previous_state, state, error_message+ FROM {PLATFORM_ALERT_EVENTS_TABLE}+ WHERE team_id = %(team_id)s+ AND configuration_id IN %(configuration_ids)s+ AND grouping_key = ''+ AND occurred_at >= %(since)s+ AND occurred_at < %(until)s+ ORDER BY configuration_id, alert_id, occurred_at, evaluation_key+ LIMIT 1 BY alert_id, evaluation_key+ )+)+WHERE previous_state != state OR is_latest+ORDER BY configuration_id, occurred_at+"""+++def history(+ team_id: int, configuration_ids: Collection[UUID], *, since: datetime, until: datetime+) -> dict[UUID, PlatformAlertHistory]:+ """Each configuration's state changes and last check in `[since, until)`, in one query.++ Only the ungrouped instance is read, because a source that shows one state per alert has no+ groups. A configuration with no check in the window is left out.++ Raises on a ClickHouse failure, because only the caller knows what it can show instead.+ """+ if not configuration_ids:+ return {}+ tag_queries(product=Product.PLATFORM_AND_SUPPORT, feature=Feature.ALERTING)+ rows = sync_execute(+ _HISTORY_SQL,+ {"team_id": team_id, "configuration_ids": list(configuration_ids), "since": since, "until": until},+ team_id=team_id,+ )+ changes: dict[UUID, list[PlatformStateChange]] = {}+ latest: dict[UUID, tuple[datetime, str]] = {}+ for configuration_id, occurred_at, previous_state, state, error_message, is_latest in rows:+ if previous_state != state:+ changes.setdefault(configuration_id, []).append(+ PlatformStateChange(+ occurred_at=occurred_at,+ previous_state=PlatformAlertState(previous_state),+ state=PlatformAlertState(state),+ )+ )+ if is_latest:+ latest[configuration_id] = (occurred_at, error_message)+ return {+ configuration_id: PlatformAlertHistory(+ state_changes=tuple(changes.get(configuration_id, ())),+ last_checked_at=last_checked_at,+ last_error_message=error_message or None,+ )+ for configuration_id, (last_checked_at, error_message) in latest.items()+ }diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.pyindex 7c1686e72d57..931da5f5778a 100644--- a/products/alerts_platform/backend/logic/platform_reads.py+++ b/products/alerts_platform/backend/logic/platform_reads.py@@ -5,6 +5,7 @@ outside the product, so they return views rather than rows and never change one."""from collections.abc import Collection, Sequence+from datetime import datetimefrom uuid import UUIDfrom django.db.models import OuterRef, Prefetch, QuerySet, Subquery@@ -13,10 +14,12 @@ from products.alerts_platform.backend.facade.contracts import (InstanceCheckState,PlatformAlertConfigurationPage,PlatformAlertConfigurationView,+ PlatformAlertHistory,PlatformAlertRuntime,PlatformAlertSnapshot,)from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, PlatformAlertState+from products.alerts_platform.backend.logic import platform_alert_eventsfrom products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration@@ -162,3 +165,25 @@ def runtime_by_legacy_id(for legacy_id, state, check_status, last_notified_at, consecutive_failures, next_check_at in rowsif legacy_id is not None}+++def history_by_legacy_id(+ *, team_id: int, legacy_configuration_ids: Collection[UUID], since: datetime, until: datetime+) -> dict[UUID, PlatformAlertHistory]:+ """The check history in `[since, until)` of each named alert the platform owns, keyed by the+ source's id.++ One Postgres query finds the platform's ids and one ClickHouse query reads the history. An+ alert the platform does not own is left out, as in `runtime_by_legacy_id`.+ """+ if not legacy_configuration_ids:+ return {}+ legacy_by_platform_id = {+ platform_id: legacy_id+ for platform_id, legacy_id in PlatformAlertConfiguration.objects.for_team(team_id)+ .filter(legacy_configuration_id__in=list(legacy_configuration_ids), owner=PlatformAlertOwner.PLATFORM)+ .values_list("id", "legacy_configuration_id")+ if legacy_id is not None+ }+ histories = platform_alert_events.history(team_id, legacy_by_platform_id, since=since, until=until)+ return {legacy_by_platform_id[platform_id]: history for platform_id, history in histories.items()}diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.pyindex fd33844c6e91..b7d55ef79bc0 100644--- a/products/logs/backend/presentation/views/alerts_api.py+++ b/products/logs/backend/presentation/views/alerts_api.py@@ -1,5 +1,6 @@import osimport datetime as dt+from collections.abc import Sequencefrom datetime import UTC, datetimefrom typing import Any, Final, Literal, TypedDict, castfrom uuid import UUID@@ -22,8 +23,10 @@ from posthog.schema import LogsAlertFiltersfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer+from posthog.dataclasses import frozenfrom posthog.event_usage import report_user_actionfrom posthog.exceptions import as_drf_validation_error+from posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.team.team import Team@@ -42,15 +45,17 @@ 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_id+from products.alerts_platform.backend.facade.api import history_by_legacy_id, reset_broken, runtime_by_legacy_idfrom products.alerts_platform.backend.facade.contracts import (AlertDestinationData,AlertDestinationValidationError,DestinationType,PagerDutyRegion,PagerDutySeverity,+ PlatformAlertHistory,PlatformAlertRuntime,)+from products.alerts_platform.backend.facade.enums import PlatformAlertStatefrom products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_restrictionfrom products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionFieldfrom products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCount@@ -209,6 +214,7 @@ class LogsAlertDestinationConfigSerializer(LogsAlertDestinationResponseSerialize_PLATFORM_RUNTIME_CONTEXT_KEY: Final = "platform_runtime"+_PLATFORM_HISTORY_CONTEXT_KEY: Final = "platform_history"def _platform_runtime_of(alerts: list[LogsAlertConfiguration]) -> dict[UUID, PlatformAlertRuntime]:@@ -218,14 +224,60 @@ def _platform_runtime_of(alerts: list[LogsAlertConfiguration]) -> dict[UUID, Plareturn runtime_by_legacy_id(team_id=owned[0].team_id, legacy_configuration_ids=[alert.id for alert in owned])+def _platform_history_of(+ alerts: list[LogsAlertConfiguration], window: tuple[datetime, datetime]+) -> dict[UUID, PlatformAlertHistory] | None:+ """None when ClickHouse fails. The logs row then stands in, because a stale timeline is a+ better answer than a failed list."""+ owned = [alert for alert in alerts if alert.platform_owned]+ if not owned:+ return {}+ try:+ return history_by_legacy_id(+ team_id=owned[0].team_id,+ legacy_configuration_ids=[alert.id for alert in owned],+ since=window[0],+ until=window[1],+ )+ except Exception as error:+ capture_exception(error)+ return None++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.+ # One platform read of each kind for the page, which the child serializer finds in the+ # shared context.self.context[_PLATFORM_RUNTIME_CONTEXT_KEY] = _platform_runtime_of(alerts)+ self.context[_PLATFORM_HISTORY_CONTEXT_KEY] = _platform_history_of(+ alerts, self.context.get("state_timeline_window") or _state_timeline_window_bounds()+ )return super().to_representation(alerts)+# Kinds of the boundaries a moved alert's timeline adds to the logs event kinds.+_PLATFORM_CHANGE: Final = "platform_change"+_SNOOZE_EXPIRY: Final = "snooze_expiry"+_SNOOZE_KINDS: Final = (LogsAlertEvent.Kind.SNOOZE, LogsAlertEvent.Kind.UNSNOOZE)+_PLATFORM_TIMELINE_LOGS_KINDS: Final = (+ LogsAlertEvent.Kind.ENABLE,+ LogsAlertEvent.Kind.DISABLE,+ LogsAlertEvent.Kind.RESET,+ *_SNOOZE_KINDS,+)+++@frozen+class _TimelineEvent:+ """A boundary of a moved alert's timeline, in the shape the timeline walk reads."""++ kind: str+ created_at: datetime+ state_before: str+ state_after: str++class LogsAlertConfigurationSerializer(serializers.ModelSerializer):id = serializers.UUIDField(read_only=True,@@ -325,7 +377,8 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):help_text=("Error message from the most recent errored check, or null if the alert's ""most recent check was successful. Sourced from LogsAlertEvent without "- "denormalization so retention-aware cleanup rules stay the only source of truth."+ "denormalization so retention-aware cleanup rules stay the only source of truth. "+ "For an alert the alerts platform evaluates, sourced from the platform's check history."),)created_at = serializers.DateTimeField(@@ -343,7 +396,8 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):f"Continuous state intervals over the last {STATE_TIMELINE_LOOKBACK_HOURS}h, ordered oldest-first. ""Each interval covers a span during which (state, enabled) was constant. Derived from ""LogsAlertEvent rows walked in chronological order; consecutive identical intervals are "- "collapsed. Drives the 'Last 24h' status bar on the alert list."+ "collapsed. For an alert the alerts platform evaluates, state changes come from the "+ "platform's check history instead. Drives the 'Last 24h' status bar on the alert list."),)destination_types = serializers.SerializerMethodField(@@ -357,8 +411,9 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):@extend_schema_field(LogsAlertStateIntervalSerializer(many=True))def get_state_timeline(self, obj: LogsAlertConfiguration) -> list[StateInterval]:window = self.context.get("state_timeline_window") or _state_timeline_window_bounds()- window_start, window_end = window+ return self._state_intervals(obj, self._timeline_events(obj, window[0]), obj.state, window)+ def _timeline_events(self, obj: LogsAlertConfiguration, window_start: datetime) -> list[LogsAlertEvent]:# Events are prefetched as `_state_timeline_events` on the list endpoint; fall# back to a direct query for callers that build this serializer outside the viewset# (admin, tests).@@ -369,11 +424,92 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):.order_by("created_at").only("kind", "created_at", "state_before", "state_after"))+ return events++ def _platform_state_timeline(+ self,+ obj: LogsAlertConfiguration,+ history: PlatformAlertHistory | None,+ platform_state: PlatformAlertState,+ window: tuple[datetime, datetime],+ ) -> list[StateInterval]:+ """The timeline of an alert the platform owns.++ The platform's history holds the state changes. The logs API still writes the toggles, the+ snoozes and the resets, so they come from LogsAlertEvent. A reset writes no platform history,+ so its logs row is the only record that the platform state went back to not firing. Logs+ check rows are left out, because the logs stack only shadows an alert the platform owns.++ Each logs event keeps its own time, and the state shown at any moment is snoozed while a+ snooze holds, else the platform's state. A snooze that expired leaves no event, so only+ the current snooze's `snooze_until` can end one inside the window.+ """+ window_start, window_end = window+ logs_events = [+ event for event in self._timeline_events(obj, window_start) if event.kind in _PLATFORM_TIMELINE_LOGS_KINDS+ ]+ snooze_events = [event for event in logs_events if event.kind in _SNOOZE_KINDS]++ # Each boundary is (time, kind, the platform state it moves to or None).+ boundaries: list[tuple[datetime, str, PlatformAlertState | None]] = [+ (change.occurred_at, _PLATFORM_CHANGE, change.state)+ for change in (history.state_changes if history is not None else ())+ ]+ boundaries.extend((event.created_at, event.kind, None) for event in logs_events)+ snooze_until = obj.snooze_until+ if (+ snooze_until is not None+ and window_start < snooze_until < window_end+ and not any(event.created_at >= snooze_until for event in snooze_events)+ ):+ boundaries.append((snooze_until, _SNOOZE_EXPIRY, None))+ boundaries.sort(key=lambda boundary: boundary[0])++ if history is not None and history.state_changes:+ platform_state = history.state_changes[0].previous_state+ if snooze_events:+ snoozed = snooze_events[0].kind == LogsAlertEvent.Kind.UNSNOOZE+ else:+ snoozed = (+ obj.state == LogsAlertConfiguration.State.SNOOZED+ and snooze_until is not None+ and snooze_until > window_start+ )++ def shown() -> str:+ if snoozed:+ return LogsAlertConfiguration.State.SNOOZED+ return logs_state_of_platform(+ platform_state, logs_state=obj.state, snooze_until=None, at=window_start+ ).value++ events: list[_TimelineEvent] = []+ for at, kind, moved_to in boundaries:+ before = shown()+ if moved_to is not None:+ platform_state = moved_to+ elif kind == LogsAlertEvent.Kind.RESET:+ platform_state = PlatformAlertState.NOT_FIRING+ elif kind == LogsAlertEvent.Kind.SNOOZE:+ snoozed = True+ elif kind in (LogsAlertEvent.Kind.UNSNOOZE, _SNOOZE_EXPIRY):+ snoozed = False+ events.append(_TimelineEvent(kind=kind, created_at=at, state_before=before, state_after=shown()))+ return self._state_intervals(obj, events, shown(), window)++ def _state_intervals(+ self,+ obj: LogsAlertConfiguration,+ events: Sequence[LogsAlertEvent | _TimelineEvent],+ fallback_state: str,+ window: tuple[datetime, datetime],+ ) -> list[StateInterval]:+ window_start, window_end = window# Seed state at window_start: the first in-window event tells us what state was# active just before it fired. Fallback to the alert's current state when there are# no events at all in the window.- seed_state = events[0].state_before if events else obj.state+ seed_state = events[0].state_before if events else fallback_state# Seed enabled at window_start: prefer the latest ENABLE/DISABLE at-or-before# window_start (annotated on the queryset), then infer from the first in-window@@ -492,6 +628,19 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):data["consecutive_failures"] = runtime.consecutive_failuresdata["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)++ histories = self.context.get(_PLATFORM_HISTORY_CONTEXT_KEY, _NOT_ANNOTATED)+ window = self.context.get("state_timeline_window") or _state_timeline_window_bounds()+ if histories is _NOT_ANNOTATED:+ histories = _platform_history_of([instance], window)+ if histories is None:+ return data+ history = cast(dict[UUID, PlatformAlertHistory], histories).get(instance.id)+ data["state_timeline"] = self._platform_state_timeline(instance, history, runtime.state, window)+ # With no platform check in the window, the logs row is the newest check anyone made.+ if history is not None:+ data["last_checked_at"] = self.fields["last_checked_at"].to_representation(history.last_checked_at)+ data["last_error_message"] = history.last_error_messagereturn dataclass Meta:@@ -1256,6 +1405,16 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):update_fields = apply_outcome(alert, outcome, kind=LogsAlertEvent.Kind.RESET)update_fields.extend(alert.clear_next_check())alert.save(update_fields=update_fields)+ else:+ # The logs row did not move, so nothing else records the reset that the alert's+ # timeline needs. The platform's history writes no row for it either.+ LogsAlertEvent.objects.create(+ alert=alert,+ kind=LogsAlertEvent.Kind.RESET,+ threshold_breached=False,+ state_before=LogsAlertConfiguration.State.BROKEN,+ state_after=LogsAlertConfiguration.State.NOT_FIRING,+ )# 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 c1f9dcd6ca89..cdaaef033036 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -199,8 +199,9 @@ class TestLogsAlertAPI(APIBaseTest):assert [(row["state"], row["next_check_at"]) for row in rows] == [("firing", platform_due_at.isoformat().replace("+00:00", "Z"))] * len(rows)+ # One for the runtime and one for the history's ids, whatever the page size.platform_reads = [q for q in queries.captured_queries if "alerts_platformalertconfiguration" in q["sql"]]- assert len(platform_reads) == 1+ assert len(platform_reads) == 2def test_list_filters_by_created_by(self):other_user = User.objects.create_and_join(self.organization, "[email protected]", None)@@ -2798,3 +2799,154 @@ class TestLogsAlertAPIPersonalAPIKeyScopes(APIBaseTest):url = f"{self.base_url}{uuid4()}/reset/"response = self.client.post(url, {}, format="json", **self._auth(key))assert response.status_code == 403, response.json()+++class TestPlatformOwnedAlertHistory(ClickhouseTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ self.base_url = f"/api/projects/{self.team.pk}/logs/alerts/"+ patcher = patch("posthoganalytics.feature_enabled", return_value=True)+ patcher.start()+ self.addCleanup(patcher.stop)+ self.now = datetime.now(UTC)+ self.alert = LogsAlertConfiguration.objects.create(+ team=self.team,+ name="Errors",+ filters={"severityLevels": ["error"]},+ last_checked_at=self.now - timedelta(hours=2),+ next_check_at=self.now + timedelta(minutes=3),+ )+ self._logs_event(+ LogsAlertEvent.Kind.CHECK, hours_ago=3, state_after="errored", error_message="Logs stack timeout"+ )+ [cutover] = cut_over_team(self.team.id, now=self.now)+ assert cutover.skipped is None++ def _logs_event(self, kind: str, *, hours_ago: float, state_after: str, error_message: str | None = None) -> None:+ event = LogsAlertEvent.objects.create(+ alert=self.alert,+ kind=kind,+ threshold_breached=False,+ state_before="not_firing",+ state_after=state_after,+ error_message=error_message,+ )+ LogsAlertEvent.objects.filter(pk=event.pk).update(created_at=self.now - timedelta(hours=hours_ago))++ def _rows(self, action: str) -> list[dict[str, Any]]:+ if action == "list":+ response = self.client.get(self.base_url)+ assert response.status_code == status.HTTP_200_OK+ return response.json()["results"]+ response = self.client.get(f"{self.base_url}{self.alert.id}/")+ assert response.status_code == status.HTTP_200_OK+ return [response.json()]++ @parameterized.expand([("list",), ("retrieve",)])+ def test_timeline_and_last_check_come_from_platform_history(self, action: str) -> None:+ def at(minutes_ago: int) -> datetime:+ return self.now - timedelta(minutes=minutes_ago)++ with team_scope(self.team.id):+ copy_id = platform_testing.copy_of(self.alert.id).id+ checks = [+ (at(90), "not_firing", "firing", None),+ (at(60), "firing", "errored", "Query timed out"),+ (at(30), "errored", "errored", "Query hit the memory limit"),+ ]+ for occurred_at, previous_state, state, error_message in checks:+ platform_testing.record_check(+ copy_id,+ team_id=self.team.id,+ at=occurred_at,+ previous_state=previous_state,+ state=state,+ error_message=error_message,+ )+ # The logs API still records toggles, and they carry the logs row's frozen state.+ self._logs_event(LogsAlertEvent.Kind.DISABLE, hours_ago=0.75, state_after="not_firing")+ self._logs_event(LogsAlertEvent.Kind.ENABLE, hours_ago=2 / 3, state_after="not_firing")++ [row] = self._rows(action)++ assert row["last_checked_at"] == at(30).isoformat().replace("+00:00", "Z")+ assert row["last_error_message"] == "Query hit the memory limit"+ assert [(i["start"], i["state"], i["enabled"]) for i in row["state_timeline"][1:]] == [+ (at(90).isoformat().replace("+00:00", "Z"), "firing", True),+ (at(60).isoformat().replace("+00:00", "Z"), "errored", True),+ (at(45).isoformat().replace("+00:00", "Z"), "errored", False),+ (at(40).isoformat().replace("+00:00", "Z"), "errored", True),+ ]+ assert row["state_timeline"][0]["state"] == "not_firing"++ @parameterized.expand(+ [+ ("still_snoozed", [(60, LogsAlertEvent.Kind.SNOOZE)], -60, [(60, "snoozed")]),+ (+ "unsnoozed",+ [(90, LogsAlertEvent.Kind.SNOOZE), (30, LogsAlertEvent.Kind.UNSNOOZE)],+ None,+ [(90, "snoozed"), (30, "not_firing")],+ ),+ (+ "expired",+ [(90, LogsAlertEvent.Kind.SNOOZE)],+ 30,+ [(90, "snoozed"), (30, "not_firing")],+ ),+ ]+ )+ def test_timeline_keeps_snooze_boundaries(+ self,+ _name: str,+ snoozes: list[tuple[int, str]],+ snooze_until_minutes_ago: int | None,+ expected: list[tuple[int, str]],+ ) -> None:+ def iso(minutes_ago: int) -> str:+ return (self.now - timedelta(minutes=minutes_ago)).isoformat().replace("+00:00", "Z")++ for minutes_ago, kind in snoozes:+ self._logs_event(kind, hours_ago=minutes_ago / 60, state_after="not_firing")+ snooze_until = (+ None if snooze_until_minutes_ago is None else self.now - timedelta(minutes=snooze_until_minutes_ago)+ )+ LogsAlertConfiguration.objects.filter(pk=self.alert.pk).update(+ state="snoozed" if snooze_until is not None else "not_firing", snooze_until=snooze_until+ )++ [row] = self._rows("retrieve")++ assert [(i["start"], i["state"]) for i in row["state_timeline"]][1:] == [+ (iso(minutes_ago), state) for minutes_ago, state in expected+ ]+ assert row["state_timeline"][0]["state"] == "not_firing"++ def test_timeline_shows_a_reset_of_a_platform_broken_alert(self) -> None:+ with team_scope(self.team.id):+ copy_id = platform_testing.copy_of(self.alert.id).id+ platform_testing.set_check_status(copy_id, "broken")+ platform_testing.record_check(+ copy_id,+ team_id=self.team.id,+ at=self.now - timedelta(minutes=60),+ previous_state="not_firing",+ state="broken",+ error_message="Query failed",+ )++ response = self.client.post(f"{self.base_url}{self.alert.id}/reset/")+ assert response.status_code == status.HTTP_200_OK, response.json()+ [row] = self._rows("retrieve")++ assert [interval["state"] for interval in row["state_timeline"]] == ["not_firing", "broken", "not_firing"]++ def test_falls_back_to_the_logs_row_when_clickhouse_fails(self) -> None:+ with patch(+ "products.logs.backend.presentation.views.alerts_api.history_by_legacy_id",+ side_effect=Exception("ClickHouse is down"),+ ):+ [row] = self._rows("list")++ assert row["last_checked_at"] == (self.now - timedelta(hours=2)).isoformat().replace("+00:00", "Z")+ assert row["last_error_message"] == "Logs stack timeout"diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 576ca0951ce8..f1da0dc6c5dd 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -650,11 +650,11 @@ export interface LogsAlertConfigurationApi {/** Number of consecutive evaluation failures. Resets on success. Server-managed. */readonly consecutive_failures: number/**- * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth.+ * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth. For an alert the alerts platform evaluates, sourced from the platform's check history.* @nullable*/readonly last_error_message: string | null- /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */+ /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. For an alert the alerts platform evaluates, state changes come from the platform's check history instead. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline: readonly LogsAlertStateIntervalApi[]/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */readonly destination_types: readonly LogsAlertDestinationTypeEnumApi[]@@ -820,11 +820,11 @@ export interface LogsAlertConfigurationDetailApi {/** Number of consecutive evaluation failures. Resets on success. Server-managed. */readonly consecutive_failures: number/**- * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth.+ * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth. For an alert the alerts platform evaluates, sourced from the platform's check history.* @nullable*/readonly last_error_message: string | null- /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */+ /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. For an alert the alerts platform evaluates, state changes come from the platform's check history instead. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline: readonly LogsAlertStateIntervalApi[]/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */readonly destination_types: readonly LogsAlertDestinationTypeEnumApi[]@@ -922,11 +922,11 @@ export interface PatchedLogsAlertConfigurationApi {/** Number of consecutive evaluation failures. Resets on success. Server-managed. */readonly consecutive_failures?: number/**- * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth.+ * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth. For an alert the alerts platform evaluates, sourced from the platform's check history.* @nullable*/readonly last_error_message?: string | null- /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */+ /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. For an alert the alerts platform evaluates, state changes come from the platform's check history instead. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline?: readonly LogsAlertStateIntervalApi[]/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */readonly destination_types?: readonly LogsAlertDestinationTypeEnumApi[]diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9f8cfcfb1daa..8483c3aab4bc 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -62804,11 +62804,11 @@ export namespace Schemas {/** Number of consecutive evaluation failures. Resets on success. Server-managed. */readonly consecutive_failures: number;/**- * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth.+ * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth. For an alert the alerts platform evaluates, sourced from the platform's check history.* @nullable*/readonly last_error_message: string | null;- /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */+ /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. For an alert the alerts platform evaluates, state changes come from the platform's check history instead. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline: readonly LogsAlertStateInterval[];/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */readonly destination_types: readonly LogsAlertDestinationTypeEnum[];@@ -62967,11 +62967,11 @@ export namespace Schemas {/** Number of consecutive evaluation failures. Resets on success. Server-managed. */readonly consecutive_failures: number;/**- * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth.+ * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth. For an alert the alerts platform evaluates, sourced from the platform's check history.* @nullable*/readonly last_error_message: string | null;- /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */+ /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. For an alert the alerts platform evaluates, state changes come from the platform's check history instead. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline: readonly LogsAlertStateInterval[];/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */readonly destination_types: readonly LogsAlertDestinationTypeEnum[];@@ -82296,11 +82296,11 @@ export namespace Schemas {/** Number of consecutive evaluation failures. Resets on success. Server-managed. */readonly consecutive_failures?: number;/**- * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth.+ * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth. For an alert the alerts platform evaluates, sourced from the platform's check history.* @nullable*/readonly last_error_message?: string | null;- /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */+ /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. For an alert the alerts platform evaluates, state changes come from the platform's check history instead. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline?: readonly LogsAlertStateInterval[];/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */readonly destination_types?: readonly LogsAlertDestinationTypeEnum[];