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): read a platform-owned alert's check events from platform history (#119970)

Jimmy Zhu1321ba28df48
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index 06f967efdce8..023c76de0367 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -21,6 +21,7 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformAlertOutcome,
PlatformAlertRuntime,
PlatformAlertUpsert,
+ PlatformCheckEventPage,
PlatformHandback,
PlatformOwnershipHandover,
SourceKind,
@@ -133,6 +134,19 @@ def history_by_legacy_id(
)
+def notable_checks_by_legacy_id(
+ *, team_id: int, legacy_configuration_id: UUID, since: datetime, limit: int
+) -> PlatformCheckEventPage | None:
+ """The newest `limit` checks since `since` that moved a named alert's state or failed, with
+ their total, or None when the platform does not own the alert.
+
+ Raises when ClickHouse fails, so a caller can fall back to what it shows without the platform.
+ """
+ return platform_reads.notable_checks_by_legacy_id(
+ team_id=team_id, legacy_configuration_id=legacy_configuration_id, since=since, limit=limit
+ )
+
+
def update_configuration(
*,
team_id: int,
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index b265729cf9b8..a5343772f8ee 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -426,6 +426,28 @@ class PlatformAlertHistory:
last_error_message: str | None
+@frozen
+class PlatformCheckEvent:
+ """One check of an alert the platform owns that moved its state or failed."""
+
+ occurred_at: datetime
+ evaluation_key: str
+ previous_state: PlatformAlertState
+ state: PlatformAlertState
+ value: float | None
+ condition: dict[str, Any]
+ query_duration_ms: int | None
+ error_message: str | None
+
+
+@frozen
+class PlatformCheckEventPage:
+ """The newest checks of an alert that moved its state or failed, and how many there are in all."""
+
+ events: tuple[PlatformCheckEvent, ...]
+ total: int
+
+
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.py
index 6256c48a49c3..dc9f7d86ac3b 100644
--- a/products/alerts_platform/backend/facade/testing.py
+++ b/products/alerts_platform/backend/facade/testing.py
@@ -108,6 +108,9 @@ def record_check(
previous_state: str,
state: str,
error_message: str | None = None,
+ value: float | None = None,
+ condition: dict[str, Any] | None = None,
+ query_duration_ms: int | None = None,
) -> None:
"""Write one ungrouped check to the platform's ClickHouse history, as a check that ran at `at`."""
insert_events(
@@ -125,11 +128,11 @@ def record_check(
previous_state=previous_state,
state=state,
episode_started_at=None,
- value=None,
+ value=value,
labels={},
- condition_snapshot={},
+ condition_snapshot=condition or {},
source_config_snapshot={},
- query_duration_ms=None,
+ query_duration_ms=query_duration_ms,
error_message=error_message,
consecutive_failures=0,
muted_notification="",
diff --git a/products/alerts_platform/backend/logic/platform_alert_events.py b/products/alerts_platform/backend/logic/platform_alert_events.py
index c72317a5c546..47e187041f3b 100644
--- a/products/alerts_platform/backend/logic/platform_alert_events.py
+++ b/products/alerts_platform/backend/logic/platform_alert_events.py
@@ -31,6 +31,8 @@ from products.alerts_platform.backend.facade.contracts import (
AnnouncedTransition,
EvaluationAnnouncement,
PlatformAlertHistory,
+ PlatformCheckEvent,
+ PlatformCheckEventPage,
PlatformStateChange,
SourceKind,
)
@@ -350,3 +352,58 @@ def history(
)
for configuration_id, (last_checked_at, error_message) in latest.items()
}
+
+
+# Deduplicated as `_HISTORY_SQL` is. The quiet checks are dropped before the deduplication, which
+# is safe because two copies of one check are identical rows. The total is a window over every
+# matching check, so one query answers both the page and the count a paginated list needs.
+_NOTABLE_CHECKS_SQL = f"""
+SELECT occurred_at, evaluation_key, previous_state, state, value, condition_snapshot, query_duration_ms,
+ error_message, count() OVER () AS total
+FROM (
+ SELECT alert_id, evaluation_key, occurred_at, previous_state, state, value, condition_snapshot,
+ query_duration_ms, error_message
+ FROM {PLATFORM_ALERT_EVENTS_TABLE}
+ WHERE team_id = %(team_id)s
+ AND configuration_id = %(configuration_id)s
+ AND grouping_key = ''
+ AND occurred_at >= %(since)s
+ AND (previous_state != state OR error_message != '')
+ ORDER BY alert_id, occurred_at, evaluation_key
+ LIMIT 1 BY alert_id, evaluation_key
+)
+ORDER BY occurred_at DESC, evaluation_key DESC
+LIMIT %(limit)s
+"""
+
+
+def notable_checks(team_id: int, configuration_id: UUID, *, since: datetime, limit: int) -> PlatformCheckEventPage:
+ """The newest `limit` checks since `since` that moved the configuration's state or failed.
+
+ A check that confirmed the state it found is left out, because a source that lists events
+ shows what changed. Only the ungrouped instance is read, as in `history`.
+
+ Raises on a ClickHouse failure, because only the caller knows what it can show instead.
+ """
+ tag_queries(product=Product.PLATFORM_AND_SUPPORT, feature=Feature.ALERTING)
+ rows = sync_execute(
+ _NOTABLE_CHECKS_SQL,
+ {"team_id": team_id, "configuration_id": configuration_id, "since": since, "limit": limit},
+ team_id=team_id,
+ )
+ return PlatformCheckEventPage(
+ events=tuple(
+ PlatformCheckEvent(
+ occurred_at=occurred_at,
+ evaluation_key=evaluation_key,
+ previous_state=PlatformAlertState(previous_state),
+ state=PlatformAlertState(state),
+ value=value,
+ condition=_snapshot(condition_snapshot),
+ query_duration_ms=query_duration_ms,
+ error_message=error_message or None,
+ )
+ for occurred_at, evaluation_key, previous_state, state, value, condition_snapshot, query_duration_ms, error_message, _ in rows
+ ),
+ total=rows[0][-1] if rows else 0,
+ )
diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.py
index 8511f1871fc0..2e1f88b8613b 100644
--- a/products/alerts_platform/backend/logic/platform_reads.py
+++ b/products/alerts_platform/backend/logic/platform_reads.py
@@ -18,6 +18,7 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformAlertHistory,
PlatformAlertRuntime,
PlatformAlertSnapshot,
+ PlatformCheckEventPage,
)
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, PlatformAlertState
from products.alerts_platform.backend.logic import platform_alert_events
@@ -192,3 +193,19 @@ def history_by_legacy_id(
}
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()}
+
+
+def notable_checks_by_legacy_id(
+ *, team_id: int, legacy_configuration_id: UUID, since: datetime, limit: int
+) -> PlatformCheckEventPage | None:
+ """The newest checks since `since` that moved the named alert's state or failed, or None when
+ the platform does not own it."""
+ platform_id = (
+ PlatformAlertConfiguration.objects.for_team(team_id)
+ .filter(legacy_configuration_id=legacy_configuration_id, owner=PlatformAlertOwner.PLATFORM)
+ .values_list("id", flat=True)
+ .first()
+ )
+ if platform_id is None:
+ return None
+ return platform_alert_events.notable_checks(team_id, platform_id, since=since, limit=limit)
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index f8f1519aedea..af7e054e70cc 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -162,13 +162,21 @@ class LogsAlertCondition:
@classmethod
def of(cls, check: PlatformAlertCheckInput) -> "LogsAlertCondition":
- condition = check.condition
+ return cls.from_condition(check.condition)
+
+ @classmethod
+ def from_condition(cls, condition: Mapping[str, Any]) -> "LogsAlertCondition":
return cls(
threshold_count=condition["threshold_count"],
threshold_operator=condition["threshold_operator"],
window_minutes=condition["window_minutes"],
)
+ def breached(self, count: float) -> bool:
+ if self.threshold_operator == LogsAlertConfiguration.ThresholdOperator.ABOVE:
+ return count > self.threshold_count
+ return count < self.threshold_count
+
@frozen
class _QuerySubject:
diff --git a/products/logs/backend/facade/api.py b/products/logs/backend/facade/api.py
index 87b71221b4bd..e63339dcc729 100644
--- a/products/logs/backend/facade/api.py
+++ b/products/logs/backend/facade/api.py
@@ -13,13 +13,22 @@ from products.logs.backend.natural_language_query import (
translate_natural_language_query,
)
from products.logs.backend.platform_alert_backfill import logs_state_of_platform
+from products.logs.backend.platform_alert_event_history import (
+ MAX_MERGED_EVENT_ROWS,
+ PlatformCheckRow,
+ PlatformCheckRows,
+ platform_check_rows,
+)
from products.logs.backend.platform_source_config import ALLOWED_WINDOW_MINUTES, has_any_filter
from products.logs.backend.tasks.tasks import follow_logs_alert_task
__all__ = [
"ALLOWED_WINDOW_MINUTES",
+ "MAX_MERGED_EVENT_ROWS",
"NaturalLanguageQueryFailed",
"NaturalLanguageQueryUnavailable",
+ "PlatformCheckRow",
+ "PlatformCheckRows",
"close_incident_before_delete",
"close_incident_on_commit",
"follow_logs_alert",
@@ -27,6 +36,7 @@ __all__ = [
"is_valid_date",
"logs_state_of_platform",
"next_allowed_check_at",
+ "platform_check_rows",
"translate_natural_language_query",
]
diff --git a/products/logs/backend/platform_alert_event_history.py b/products/logs/backend/platform_alert_event_history.py
new file mode 100644
index 000000000000..3771f8c3e60c
--- /dev/null
+++ b/products/logs/backend/platform_alert_event_history.py
@@ -0,0 +1,86 @@
+"""The checks of a logs alert the platform owns, as the logs events API lists them.
+
+The logs API keeps writing the control-plane events (toggles, snoozes, resets, threshold changes),
+so those come from `LogsAlertEvent`. The checks come from the platform's history once it owns the
+alert, and from `LogsAlertEvent` before then.
+"""
+
+from datetime import datetime
+from typing import Final
+from uuid import UUID, uuid5
+
+from posthog.dataclasses import frozen
+
+from products.alerts_platform.backend.facade.api import notable_checks_by_legacy_id
+from products.alerts_platform.backend.facade.contracts import PlatformCheckEvent
+from products.alerts_platform.backend.facade.enums import PlatformAlertState
+from products.logs.backend.alert_source_cycle import LogsAlertCondition
+from products.logs.backend.platform_alert_backfill import logs_state_of_platform
+
+# A merged page loads every row up to its end from both sources, so the end is bounded. The events
+# tab loads pages of 100 and never comes near it.
+MAX_MERGED_EVENT_ROWS: Final = 10_000
+
+
+@frozen
+class PlatformCheckRow:
+ """One check of a logs alert the platform owns, in the shape of a logs alert event."""
+
+ # Derived from the check, so the same check keeps its id from one page load to the next.
+ id: UUID
+ created_at: datetime
+ state_before: str
+ state_after: str
+ threshold_breached: bool
+ result_count: int | None
+ error_message: str | None
+ query_duration_ms: int | None
+
+
+@frozen
+class PlatformCheckRows:
+ """The newest checks of an alert that moved its state or failed, and how many there are in all."""
+
+ rows: tuple[PlatformCheckRow, ...]
+ total: int
+
+
+def platform_check_rows(*, team_id: int, alert_id: UUID, since: datetime, limit: int) -> PlatformCheckRows | None:
+ """The newest `limit` checks since `since` that moved the alert's state or failed, or None when
+ the platform does not own the alert.
+
+ Raises when ClickHouse fails, so the caller can fall back to the logs rows.
+ """
+ page = notable_checks_by_legacy_id(team_id=team_id, legacy_configuration_id=alert_id, since=since, limit=limit)
+ if page is None:
+ return None
+ return PlatformCheckRows(rows=tuple(_as_row(alert_id, check) for check in page.events), total=page.total)
+
+
+def _as_row(alert_id: UUID, check: PlatformCheckEvent) -> PlatformCheckRow:
+ return PlatformCheckRow(
+ id=uuid5(alert_id, check.evaluation_key),
+ created_at=check.occurred_at,
+ state_before=_logs_state(check.previous_state, check.occurred_at),
+ state_after=_logs_state(check.state, check.occurred_at),
+ threshold_breached=_breached(check),
+ result_count=round(check.value) if check.value is not None else None,
+ error_message=check.error_message,
+ query_duration_ms=check.query_duration_ms,
+ )
+
+
+def _logs_state(state: PlatformAlertState, at: datetime) -> str:
+ # With no snooze the alert's own state cannot change the mapping, so none is passed.
+ return logs_state_of_platform(state, logs_state="", snooze_until=None, at=at).value
+
+
+def _breached(check: PlatformCheckEvent) -> bool:
+ if check.value is None:
+ return False
+ try:
+ condition = LogsAlertCondition.from_condition(check.condition)
+ except (KeyError, TypeError, ValueError):
+ # A row whose snapshot holds no valid logs bound has nothing to compare against.
+ return False
+ return condition.breached(check.value)
diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.py
index 2d0cb6291f9d..3bcc6891fc90 100644
--- a/products/logs/backend/presentation/views/alerts_api.py
+++ b/products/logs/backend/presentation/views/alerts_api.py
@@ -2,7 +2,7 @@ import os
import datetime as dt
from collections.abc import Sequence
from datetime import UTC, datetime
-from typing import Any, Final, Literal, TypedDict, cast
+from typing import Any, Final, Literal, TypedDict, cast, overload
from uuid import UUID
from zoneinfo import ZoneInfo
@@ -16,11 +16,13 @@ from pydantic import ValidationError as PydanticValidationError
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
+from rest_framework.pagination import LimitOffsetPagination
from rest_framework.request import Request
from rest_framework.response import Response
from posthog.schema import LogsAlertFilters
+from posthog.api.pagination import stable_queryset_ordering
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.dataclasses import frozen
@@ -87,11 +89,14 @@ from products.logs.backend.alert_state_machine import (
)
from products.logs.backend.facade.api import (
ALLOWED_WINDOW_MINUTES,
+ MAX_MERGED_EVENT_ROWS,
+ PlatformCheckRow,
close_incident_on_commit,
follow_logs_alert,
has_any_filter,
logs_state_of_platform,
next_allowed_check_at,
+ platform_check_rows,
)
from products.logs.backend.facade.platform_ownership import before_delete, on_created, on_deleted, on_updated
from products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfiguration, LogsAlertEvent
@@ -1177,6 +1182,77 @@ def _fill_empty_buckets(
return result
+@frozen
+class _EventWindow(Sequence[LogsAlertEvent]):
+ """The newest rows of a history merged from two sources, sized as the whole history.
+
+ `LimitOffsetPagination` pages it as it pages a list: it takes its length, then slices one page.
+ It holds only the rows up to the end of the page the request asked for.
+ """
+
+ newest: Sequence[LogsAlertEvent]
+ total: int
+
+ def __len__(self) -> int:
+ return self.total
+
+ @overload
+ def __getitem__(self, index: int) -> LogsAlertEvent: ...
+
+ @overload
+ def __getitem__(self, index: slice) -> Sequence[LogsAlertEvent]: ...
+
+ def __getitem__(self, index: int | slice) -> LogsAlertEvent | Sequence[LogsAlertEvent]:
+ return self.newest[index]
+
+
+def _with_platform_checks(
+ alert: LogsAlertConfiguration, events: QuerySet[LogsAlertEvent], *, kind: str | None, rows_needed: int
+) -> QuerySet[LogsAlertEvent] | _EventWindow:
+ """`events` with the platform's checks in place of the shadow ones, newest first.
+
+ A logs check row written after the cutover is the shadow evaluation, so it is left out.
+ `rows_needed` is the end of the requested page, because a merged page needs that many rows
+ from each source.
+
+ Returns `events` unchanged for an alert the logs stack owns, and when ClickHouse fails, because
+ the shadow checks are a better answer than a failed list.
+ """
+ cutover_at = alert.owner_changed_at
+ if not alert.platform_owned or cutover_at is None:
+ return events
+ if kind is not None and kind != LogsAlertEvent.Kind.CHECK:
+ return events
+ # The viewset adds the same tie-break to a queryset it pages, which this merge bypasses.
+ logs_events = stable_queryset_ordering(events.exclude(kind=LogsAlertEvent.Kind.CHECK, created_at__gte=cutover_at))
+ try:
+ checks = platform_check_rows(team_id=alert.team_id, alert_id=alert.id, since=cutover_at, limit=rows_needed)
+ except Exception as error:
+ capture_exception(error)
+ return events
+ if checks is None:
+ return events
+ merged = [*logs_events[:rows_needed], *(_as_logs_event(alert, row) for row in checks.rows)]
+ merged.sort(key=lambda event: event.created_at, reverse=True)
+ return _EventWindow(newest=merged[:rows_needed], total=logs_events.count() + checks.total)
+
+
+def _as_logs_event(alert: LogsAlertConfiguration, row: PlatformCheckRow) -> LogsAlertEvent:
+ """An unsaved row in the shape `LogsAlertEventSerializer` reads."""
+ return LogsAlertEvent(
+ id=row.id,
+ alert=alert,
+ kind=LogsAlertEvent.Kind.CHECK,
+ created_at=row.created_at,
+ state_before=row.state_before,
+ state_after=row.state_after,
+ threshold_breached=row.threshold_breached,
+ result_count=row.result_count,
+ error_message=row.error_message,
+ query_duration_ms=row.query_duration_ms,
+ )
+
+
@extend_schema_view(list=extend_schema(parameters=[LogsAlertListQuerySerializer]))
class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "logs"
@@ -1370,7 +1446,9 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"errored checks, and user-initiated control-plane rows (reset, enable/disable, "
"snooze/unsnooze, threshold change) — quiet no-op check rows (where state didn't "
"change and there was no error) are filtered out since only the last 10 are kept "
- "and they carry no forensic value. Optional `?kind=...` narrows to a single kind."
+ "and they carry no forensic value. Optional `?kind=...` narrows to a single kind. "
+ "For an alert the alerts platform evaluates, checks since it took the alert over come "
+ "from the platform's check history."
),
)
@action(detail=True, methods=["GET"], url_path="events", required_scopes=["logs:read"])
@@ -1391,12 +1469,17 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
raise ValidationError({"kind": f"Must be one of {sorted(valid_kinds)}."})
queryset = queryset.filter(kind=kind)
- page = self.paginate_queryset(queryset)
+ paginator = cast(LimitOffsetPagination, self.paginator)
+ rows_needed = paginator.get_offset(request) + (paginator.get_limit(request) or 0)
+ if alert.platform_owned and rows_needed > MAX_MERGED_EVENT_ROWS:
+ raise ValidationError({"offset": f"Offset plus limit must be at most {MAX_MERGED_EVENT_ROWS}."})
+ history = _with_platform_checks(alert, queryset, kind=kind, rows_needed=rows_needed)
+ page = self.paginate_queryset(history)
if page is not None:
serializer = LogsAlertEventSerializer(page, many=True)
return self.get_paginated_response(serializer.data)
- serializer = LogsAlertEventSerializer(queryset, many=True)
+ serializer = LogsAlertEventSerializer(history, many=True)
return Response(serializer.data)
@extend_schema(
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index eb21fb13ac08..9b7e0839c599 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -3147,6 +3147,14 @@ class TestLogsAlertAPIPersonalAPIKeyScopes(APIBaseTest):
assert response.status_code == 403, response.json()
+# (kind, state_before, state_after, result_count, threshold_breached, error_message) of the events
+# `_record_events_history` leaves.
+_ERRORED = ("check", "firing", "errored", None, False, "Query timed out")
+_DISABLED = ("disable", "not_firing", "not_firing", None, False, None)
+_FIRED = ("check", "not_firing", "firing", 150, True, None)
+_LOGS_ERRORED = ("check", "not_firing", "errored", None, False, "Logs stack timeout")
+
+
class TestPlatformOwnedAlertHistory(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
@@ -3296,3 +3304,84 @@ class TestPlatformOwnedAlertHistory(ClickhouseTestMixin, APIBaseTest):
assert row["last_checked_at"] == (self.now - timedelta(hours=2)).isoformat().replace("+00:00", "Z")
assert row["last_error_message"] == "Logs stack timeout"
+
+ def _record_events_history(self) -> None:
+ def at(minutes_after_cutover: int) -> datetime:
+ return self.now + timedelta(minutes=minutes_after_cutover)
+
+ with team_scope(self.team.id):
+ copy_id = platform_testing.copy_of(self.alert.id).id
+ condition = {"threshold_count": 100, "threshold_operator": "above", "window_minutes": 5}
+ checks = [
+ # Before the cutover the platform only shadowed the logs stack.
+ (at(-30), "not_firing", "firing", None, 150.0),
+ (at(10), "not_firing", "firing", None, 150.0),
+ (at(20), "firing", "firing", None, 160.0),
+ (at(40), "firing", "errored", "Query timed out", None),
+ ]
+ for occurred_at, previous_state, state, error_message, value 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,
+ value=value,
+ condition=condition,
+ query_duration_ms=42,
+ )
+ # After the cutover a logs check is the shadow evaluation.
+ self._logs_event(LogsAlertEvent.Kind.CHECK, hours_ago=-25 / 60, state_after="firing")
+ self._logs_event(LogsAlertEvent.Kind.DISABLE, hours_ago=-0.5, state_after="not_firing")
+
+ @parameterized.expand(
+ [
+ ("all", "", 4, [_ERRORED, _DISABLED, _FIRED, _LOGS_ERRORED]),
+ ("second_page", "?limit=2&offset=1", 4, [_DISABLED, _FIRED]),
+ ("control_plane_kind", "?kind=disable", 1, [_DISABLED]),
+ ("check_kind", "?kind=check", 3, [_ERRORED, _FIRED, _LOGS_ERRORED]),
+ ]
+ )
+ def test_events_take_checks_since_the_cutover_from_platform_history(
+ self, _name: str, query: str, count: int, expected: list[tuple[Any, ...]]
+ ) -> None:
+ self._record_events_history()
+
+ response = self.client.get(f"{self.base_url}{self.alert.id}/events/{query}")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["count"] == count
+ assert [
+ (
+ e["kind"],
+ e["state_before"],
+ e["state_after"],
+ e["result_count"],
+ e["threshold_breached"],
+ e["error_message"],
+ )
+ for e in response.json()["results"]
+ ] == expected
+
+ def test_events_fall_back_to_logs_rows_when_clickhouse_fails(self) -> None:
+ self._record_events_history()
+
+ with patch(
+ "products.logs.backend.presentation.views.alerts_api.platform_check_rows",
+ side_effect=Exception("ClickHouse is down"),
+ ):
+ response = self.client.get(f"{self.base_url}{self.alert.id}/events/")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert [(e["kind"], e["state_after"]) for e in response.json()["results"]] == [
+ ("disable", "not_firing"),
+ ("check", "firing"),
+ ("check", "errored"),
+ ]
+
+ def test_events_reject_a_page_ending_past_the_merge_bound(self) -> None:
+ response = self.client.get(f"{self.base_url}{self.alert.id}/events/?offset=10000&limit=1")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "offset"
diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.ts
index 0210cdf49deb..ca97ca3c7884 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -308,7 +308,7 @@ export const getLogsAlertsEventsListUrl = (projectId: string, id: string, params
}
/**
- * Paginated event history for this alert, newest first. Returns state transitions, errored checks, and user-initiated control-plane rows (reset, enable/disable, snooze/unsnooze, threshold change) — quiet no-op check rows (where state didn't change and there was no error) are filtered out since only the last 10 are kept and they carry no forensic value. Optional `?kind=...` narrows to a single kind.
+ * Paginated event history for this alert, newest first. Returns state transitions, errored checks, and user-initiated control-plane rows (reset, enable/disable, snooze/unsnooze, threshold change) — quiet no-op check rows (where state didn't change and there was no error) are filtered out since only the last 10 are kept and they carry no forensic value. Optional `?kind=...` narrows to a single kind. For an alert the alerts platform evaluates, checks since it took the alert over come from the platform's check history.
*/
export const logsAlertsEventsList = async (
projectId: string,
diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.ts
index f86e80991141..805b7a5cf80f 100644
--- a/services/mcp/src/generated/logs/api.ts
+++ b/services/mcp/src/generated/logs/api.ts
@@ -3719,7 +3719,7 @@ export const LogsAlertsDestinationsDeleteCreateBody = () => zod.object({
})
/**
- * Paginated event history for this alert, newest first. Returns state transitions, errored checks, and user-initiated control-plane rows (reset, enable/disable, snooze/unsnooze, threshold change) — quiet no-op check rows (where state didn't change and there was no error) are filtered out since only the last 10 are kept and they carry no forensic value. Optional `?kind=...` narrows to a single kind.
+ * Paginated event history for this alert, newest first. Returns state transitions, errored checks, and user-initiated control-plane rows (reset, enable/disable, snooze/unsnooze, threshold change) — quiet no-op check rows (where state didn't change and there was no error) are filtered out since only the last 10 are kept and they carry no forensic value. Optional `?kind=...` narrows to a single kind. For an alert the alerts platform evaluates, checks since it took the alert over come from the platform's check history.
*/
export const LogsAlertsEventsListParams = () => zod.object({
id: zod.string().describe('A UUID string identifying this logs alert configuration.'),