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(metrics): resolve a missing metrics alert series once ingestion catches up (#127783)

Jimmy Zhua6956a94f9af
diff --git a/products/metrics/backend/alerts/evaluation.py b/products/metrics/backend/alerts/evaluation.py
index a7f0b76f3d52..bb30c073b012 100644
--- a/products/metrics/backend/alerts/evaluation.py
+++ b/products/metrics/backend/alerts/evaluation.py
@@ -5,16 +5,19 @@ held back to where the team's ingestion has reached. Each series the query retur
condition. Under grouping by result labels, each distinct set of grouping label values is a group.
Without grouping, the alert has one group that breaches when any series does.
-A series the query no longer returns keeps its group's state, and so does a series whose value is
-not a number. Prometheus resolves a missing series, but a team's samples spread over ingestion
-partitions, and the freshness read cannot tell that every partition has caught up. So a missing
-series could be one a lagging partition has not written yet, and resolving it would read lag as
-recovery. The hold is bounded: a group missing for `ABSENT_RESOLVE_AFTER` while the team's
-ingestion is fresh resolves, which no lag that leaves the team fresh explains, and which frees its
-slot under `max_instances`. A watermark covering every partition would let it resolve at once.
-
-This reads and decides. It writes nothing, so a retried attempt reads the same due checks and makes
-the same decisions. The platform records the outcomes in its own activity.
+A series the query no longer returns resolves its group, as in Prometheus, once the partition
+checkpoint shows every ingestion partition has passed the instant the check read. A team's samples
+spread over those partitions, so without the checkpoint a missing series could be one a lagging
+partition has not written yet, and resolving it would read lag as recovery. Then the group keeps its
+state, bounded: a group missing for `ABSENT_RESOLVE_AFTER` while the team's ingestion is fresh
+resolves, which no lag that leaves the team fresh explains, and which frees its slot under
+`max_instances`. A series whose value is not a number always keeps its group's state.
+
+A check never reads behind the instant its configuration last read, because a breach between the
+two instants would read as recovery. A check behind that floor waits for a later tick.
+
+This reads and decides. It writes only the read floors, which a retried attempt reads at, not
+behind, so it makes the same decisions. The platform records the outcomes in its own activity.
"""
import json
@@ -76,7 +79,12 @@ from products.alerts_platform.backend.facade.platform_metrics import (
)
from products.alerts_platform.backend.facade.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuples
from products.metrics.backend.alerts.destinations import EVENT_IDS_BY_INCIDENT_ACTION, EVENT_IDS_BY_KIND
-from products.metrics.backend.alerts.freshness import evaluation_time, fetch_metrics_freshness
+from products.metrics.backend.alerts.freshness import (
+ IngestionReach,
+ fetch_metrics_freshness,
+ fetch_partition_checkpoint,
+)
+from products.metrics.backend.alerts.read_floor import raise_read_floors, read_floors
from products.metrics.backend.alerts.source_config import MetricsPlatformAlertCondition, MetricsPlatformAlertConfig
from products.metrics.backend.alerts.wording import alert_url
from products.metrics.backend.promql import PromQLQueryError, snuffle_payload
@@ -101,8 +109,8 @@ BATCH_SLOT_LEASE_SECONDS: Final = 90
# Ten times the most groups a configuration can hold. A query past it is refused before its series
# are judged, so one high-cardinality expression cannot exhaust the worker.
MAX_SERIES: Final = 1000
-# Far past any partition lag that leaves the team fresh, and short enough that groups which stopped
-# reporting cannot hold every instance slot.
+# Applies only without a partition checkpoint. Far past any partition lag that leaves the team fresh,
+# and short enough that groups which stopped reporting cannot hold every instance slot.
ABSENT_RESOLVE_AFTER: Final = timedelta(hours=1)
_UNEXPECTED_ERROR: Final = "Alert check failed unexpectedly. PostHog has been notified."
@@ -161,36 +169,69 @@ def evaluate_metrics_alert_batch(team_id: int, slot: str, cutoff: datetime) -> S
def _evaluate_admitted(
team: Team, slot: str, checks: Sequence[PlatformAlertCheckInput], *, cutoff: datetime, started_at: float
) -> SourceBatchEvaluation:
- freshness = _freshness(team)
+ checkpoint = _read_instant(fetch_partition_checkpoint, team)
+ reach = IngestionReach(
+ checkpoint=checkpoint,
+ newest_point=None if checkpoint is not None else _read_instant(fetch_metrics_freshness, team),
+ )
+ floors = read_floors(team.id, [str(check.id) for check in checks])
deadline = started_at + BATCH_QUERY_BUDGET_SECONDS
decided: list[Decision] = []
+ reads: dict[str, datetime] = {}
+ behind_floor = 0
for check in checks:
+ at = reach.evaluation_time(check.next_check_at or cutoff)
+ floor = floors.get(str(check.id))
+ if floor is not None and at < floor:
+ behind_floor += 1
+ continue
remaining = deadline - time.monotonic()
if remaining < MIN_QUERY_SECONDS:
break
- at = evaluation_time(check.next_check_at or cutoff, freshness)
decided.append(
_evaluate(
team,
check,
at=at,
now=cutoff,
- ingestion_fresh=freshness is not None,
+ reach=reach,
query_seconds=min(MAX_QUERY_SECONDS, remaining),
muted=_in_quiet_hours(check, cutoff, team.timezone),
)
)
- evaluation = _collect(decided, team_id=team.id, slot=slot, past_budget=len(checks) - len(decided))
+ reads[str(check.id)] = at
+ evaluation = _collect(
+ decided,
+ team_id=team.id,
+ slot=slot,
+ past_budget=len(checks) - len(decided) - behind_floor,
+ behind_floor=behind_floor,
+ )
+ # Only a recorded verdict sets a floor. A failed query read nothing, and a check cut from the
+ # payload keeps its due time.
+ raise_read_floors(
+ team.id,
+ {
+ key: reads[key]
+ for outcome in evaluation.outcomes
+ if outcome.failure is None and (key := str(outcome.configuration_id)) in reads
+ },
+ now=cutoff,
+ )
safe_record(record_batch_duration, SOURCE.value, int((time.monotonic() - started_at) * 1000))
return evaluation
-def _freshness(team: Team) -> datetime | None:
+def _read_instant(fetch: Callable[..., datetime | None], team: Team) -> datetime | None:
try:
- return fetch_metrics_freshness(team, max_execution_time=FRESHNESS_QUERY_SECONDS)
+ return fetch(team, max_execution_time=FRESHNESS_QUERY_SECONDS)
except Exception:
- # Without a freshness the batch still runs, at its due time.
- logger.exception("Failed to fetch the metrics ingestion freshness", team_id=team.id)
+ # Without the read the batch still runs, at its due time or the other read's instant.
+ logger.exception(
+ "Failed to fetch how far metrics ingestion has reached",
+ team_id=team.id,
+ read=getattr(fetch, "__name__", repr(fetch)),
+ )
return None
@@ -209,7 +250,7 @@ def _evaluate(
*,
at: datetime,
now: datetime,
- ingestion_fresh: bool,
+ reach: IngestionReach,
query_seconds: float,
muted: bool,
) -> Decision:
@@ -236,7 +277,7 @@ def _evaluate(
policy=POLICY,
now=now,
muted=muted,
- absent=lambda key: _absent(check, key, unknown=unknown, now=now, ingestion_fresh=ingestion_fresh),
+ absent=lambda key: _absent(check, key, unknown=unknown, now=now, reach=reach),
)
for verdict in decision.verdicts:
safe_record(increment_checks, SOURCE.value, verdict.outcome.notification.value)
@@ -308,13 +349,16 @@ def _breached(condition: MetricsPlatformAlertCondition, value: float | None) ->
def _absent(
- check: PlatformAlertCheckInput, key: str, *, unknown: frozenset[str], now: datetime, ingestion_fresh: bool
+ check: PlatformAlertCheckInput, key: str, *, unknown: frozenset[str], now: datetime, reach: IngestionReach
) -> GroupObservation | None:
- """A missing group's verdict: None holds its state, as the module docstring explains, until the hold runs out."""
- last_seen_at = check.instance(key).last_seen_at
- if key in unknown or not ingestion_fresh or last_seen_at is None or now - last_seen_at < ABSENT_RESOLVE_AFTER:
+ """A missing group's verdict, as the module docstring explains. None holds its state."""
+ if key in unknown:
return None
- return not_breaching(key)
+ last_seen_at = check.instance(key).last_seen_at
+ held_long_enough = (
+ reach.newest_point is not None and last_seen_at is not None and now - last_seen_at >= ABSENT_RESOLVE_AFTER
+ )
+ return not_breaching(key) if reach.checkpoint is not None or held_long_enough else None
def _observations(
@@ -452,8 +496,11 @@ def _request(
)
-def _collect(decided: Sequence[Decision], *, team_id: int, slot: str, past_budget: int) -> SourceBatchEvaluation:
- """The batch, held to one payload. A check past the query budget or the payload keeps its due time."""
+def _collect(
+ decided: Sequence[Decision], *, team_id: int, slot: str, past_budget: int, behind_floor: int
+) -> SourceBatchEvaluation:
+ """The batch, held to one payload. A check past the query budget or the payload, or behind its
+ read floor, keeps its due time."""
outcomes: list[PlatformAlertOutcome] = []
deliveries: list[AlertDeliveryRequest] = []
deferred = 0
@@ -467,9 +514,15 @@ def _collect(decided: Sequence[Decision], *, team_id: int, slot: str, past_budge
outcomes.append(outcome)
if delivery is not None:
deliveries.append(delivery)
- if past_budget or deferred:
+ omitted = past_budget + deferred + behind_floor
+ if omitted:
logger.warning(
- "Deferred metrics alert checks", team_id=team_id, slot=slot, past_budget=past_budget, over_payload=deferred
+ "Deferred metrics alert checks",
+ team_id=team_id,
+ slot=slot,
+ past_budget=past_budget,
+ over_payload=deferred,
+ behind_floor=behind_floor,
)
- safe_record(increment_checks_deferred, SOURCE.value, past_budget + deferred)
- return SourceBatchEvaluation(outcomes=tuple(outcomes), deliveries=tuple(deliveries), omitted=past_budget + deferred)
+ safe_record(increment_checks_deferred, SOURCE.value, omitted)
+ return SourceBatchEvaluation(outcomes=tuple(outcomes), deliveries=tuple(deliveries), omitted=omitted)
diff --git a/products/metrics/backend/alerts/freshness.py b/products/metrics/backend/alerts/freshness.py
index dc293ee16931..97d501f4b9d5 100644
--- a/products/metrics/backend/alerts/freshness.py
+++ b/products/metrics/backend/alerts/freshness.py
@@ -1,8 +1,10 @@
-"""How far metrics ingestion has reached for a team, so an alert never reads a window still being written.
+"""How far metrics ingestion has reached, so an alert never reads a window still being written.
A series the pipeline has not written yet is absent from an instant query, and an absent series
-resolves its group. So a consumer lag would read as recovery. The newest point the team's services
-sent shows how far ingestion has reached: a lag delays every service at once.
+resolves its group. So a consumer lag would read as recovery. Two reads show how far ingestion has
+reached. The newest point the team's services sent moves while any partition flows. The partition
+checkpoint is the oldest of each Kafka partition's newest capture time, so it moves only when every
+partition does.
"""
import datetime as dt
@@ -12,6 +14,7 @@ from zoneinfo import ZoneInfo
from posthog.schema import HogQLQueryModifiers
+from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.parser import parse_select
from posthog.hogql.query import HogQLQueryExecutor
@@ -27,6 +30,7 @@ from posthog.clickhouse.client.connection import (
make_ch_pool,
)
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
from posthog.models import Team
# The shared pool's socket reads never time out, so a stalled connection would outlive the activity.
@@ -49,13 +53,50 @@ _TEAM_FRESHNESS_QUERY: Final = parse_select(
)
+# Not scoped to a team, because every team's samples spread over every partition. A floor more than
+# 5 minutes old is a stalled partition or a dead writer, so it gets none.
+_PARTITION_CHECKPOINT_QUERY: Final = parse_select(
+ """
+ SELECT least(min(partition_checkpoint), now()) AS checkpoint FROM (
+ SELECT _topic, _partition, max(max_observed_timestamp) AS partition_checkpoint
+ FROM posthog.metrics_kafka_metrics
+ GROUP BY _topic, _partition
+ )
+ HAVING checkpoint >= now() - toIntervalMinute(5)
+ """
+)
+
+# The checkpoint is a capture time, and a query reads by sample time. A sample reaches capture after
+# its sender stamps it, so the read is held back by the sender delay to cover. 30s is the offset
+# VictoriaMetrics reads with by default, so a sender slower than that is exposed here as in Grafana.
+CHECKPOINT_EVAL_DELAY: Final = dt.timedelta(seconds=30)
+
+
def fetch_metrics_freshness(team: Team, *, max_execution_time: int) -> dt.datetime | None:
"""The newest point the team's ingestion has written, or None when it is more than 15 minutes behind."""
+ return _fetch_instant(
+ team, _TEAM_FRESHNESS_QUERY, query_type="metrics_alert_freshness", max_execution_time=max_execution_time
+ )
+
+
+def fetch_partition_checkpoint(team: Team, *, max_execution_time: int) -> dt.datetime | None:
+ """The capture time every ingestion partition has passed, or None when it is more than 5 minutes behind."""
+ return _fetch_instant(
+ team,
+ _PARTITION_CHECKPOINT_QUERY,
+ query_type="metrics_alert_partition_checkpoint",
+ max_execution_time=max_execution_time,
+ )
+
+
+def _fetch_instant(
+ team: Team, query: ast.SelectQuery | ast.SelectSetQuery, *, query_type: str, max_execution_time: int
+) -> dt.datetime | None:
tag_queries(product=Product.METRICS, feature=Feature.ALERTING, source="metrics_alert", team_id=str(team.id))
sql, context = HogQLQueryExecutor(
- query_type="metrics_alert_freshness",
+ query_type=query_type,
# The executor edits the node it is given, and this one is shared by every call.
- query=clone_expr(_TEAM_FRESHNESS_QUERY, True),
+ query=clone_expr(query, True),
team=team,
workload=Workload.LOGS,
modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),
@@ -67,8 +108,8 @@ def fetch_metrics_freshness(team: Team, *, max_execution_time: int) -> dt.dateti
)
if not rows or rows[0][0] is None:
return None
- freshness: dt.datetime = rows[0][0]
- return freshness if freshness.tzinfo is not None else freshness.replace(tzinfo=ZoneInfo("UTC"))
+ instant: dt.datetime = rows[0][0]
+ return instant if instant.tzinfo is not None else instant.replace(tzinfo=ZoneInfo("UTC"))
def _bounded_logs_client(send_receive_timeout: int) -> AbstractContextManager:
@@ -89,10 +130,25 @@ def _bounded_logs_client(send_receive_timeout: int) -> AbstractContextManager:
return pool.get_client()
-def evaluation_time(due_at: dt.datetime, freshness: dt.datetime | None) -> dt.datetime:
- """The instant a check reads: its due time, held back to where ingestion has reached.
+@frozen
+class IngestionReach:
+ """How far a team's ingestion has reached, from the two reads in this module.
- Anchored on the due time rather than the clock, so a retried check sends the same query. Without
- a freshness the check reads at its due time, and the caller treats a missing series as unknown.
+ `checkpoint` is the capture time every partition has passed. When it is known, the newest point
+ is not read.
"""
- return due_at if freshness is None else min(due_at, freshness)
+
+ checkpoint: dt.datetime | None
+ newest_point: dt.datetime | None
+
+ def evaluation_time(self, due_at: dt.datetime) -> dt.datetime:
+ """The instant a check reads: its due time, held back to where ingestion has reached.
+
+ Anchored on the due time rather than the clock, so a retried check sends the same query. A
+ checkpoint is held back by `CHECKPOINT_EVAL_DELAY`, so every sample stamped before the instant
+ is written. Without either read the check reads at its due time, and the caller treats a
+ missing series as unknown.
+ """
+ if self.checkpoint is not None:
+ return min(due_at, self.checkpoint - CHECKPOINT_EVAL_DELAY)
+ return due_at if self.newest_point is None else min(due_at, self.newest_point)
diff --git a/products/metrics/backend/alerts/read_floor.py b/products/metrics/backend/alerts/read_floor.py
new file mode 100644
index 000000000000..832e7538ff36
--- /dev/null
+++ b/products/metrics/backend/alerts/read_floor.py
@@ -0,0 +1,69 @@
+"""The latest instant each metrics alert has read, so a check never reads behind its last verdict.
+
+The instant a check reads moves back when its ingestion read changes: a failed checkpoint read
+falls back to the newest point, which is later, and the next checkpoint read comes back earlier.
+A breach that started between the two instants then reads as recovery. A check whose instant is
+behind its configuration's floor records nothing, so it stays due and reads once ingestion passes
+the floor.
+
+The floor lives in Redis, one sorted set per team scored by epoch seconds. Losing it costs only the
+protection, so a Redis error is logged and the batch runs without a floor.
+"""
+
+from collections.abc import Mapping, Sequence
+from datetime import UTC, datetime, timedelta
+from typing import Final
+
+import structlog
+from redis import Redis
+
+from posthog import redis
+
+logger = structlog.get_logger(__name__)
+
+# Far past the longest rewind, which a checkpoint more than 5 minutes old bounds, so a floor that
+# matters is never pruned.
+_RETENTION: Final = timedelta(days=1)
+# The batch spends its time budget on queries, so the shared client's long default timeout on a
+# stalled Redis would push the activity past its deadline and lose every verdict. One second is far
+# above a healthy call, and a call that runs out of it costs only the floor.
+_REDIS_TIMEOUT_SECONDS: Final = 1.0
+
+
+def _client() -> Redis:
+ return redis.get_client(socket_timeout=_REDIS_TIMEOUT_SECONDS, socket_connect_timeout=_REDIS_TIMEOUT_SECONDS)
+
+
+def _key(team_id: int) -> str:
+ return f"alerts:platform:metrics:read_floor:{team_id}"
+
+
+def read_floors(team_id: int, configuration_ids: Sequence[str]) -> dict[str, datetime]:
+ """Each configuration's floor, leaving out configurations without one."""
+ if not configuration_ids:
+ return {}
+ try:
+ scores = _client().zmscore(_key(team_id), list(configuration_ids))
+ except Exception:
+ logger.exception("Failed to read metrics alert read floors", team_id=team_id)
+ return {}
+ return {
+ configuration_id: datetime.fromtimestamp(score, UTC)
+ for configuration_id, score in zip(configuration_ids, scores)
+ if score is not None
+ }
+
+
+def raise_read_floors(team_id: int, reads: Mapping[str, datetime], *, now: datetime) -> None:
+ """Raise each configuration's floor to the instant it read. A floor never moves back."""
+ if not reads:
+ return
+ key = _key(team_id)
+ try:
+ pipeline = _client().pipeline(transaction=False)
+ pipeline.zadd(key, {configuration_id: at.timestamp() for configuration_id, at in reads.items()}, gt=True)
+ pipeline.zremrangebyscore(key, "-inf", (now - _RETENTION).timestamp())
+ pipeline.expire(key, _RETENTION)
+ pipeline.execute()
+ except Exception:
+ logger.exception("Failed to raise metrics alert read floors", team_id=team_id)
diff --git a/products/metrics/backend/tests/test_alerts.py b/products/metrics/backend/tests/test_alerts.py
index 9b40fadecff1..09b239ca6397 100644
--- a/products/metrics/backend/tests/test_alerts.py
+++ b/products/metrics/backend/tests/test_alerts.py
@@ -15,6 +15,7 @@ from parameterized import parameterized
from pydantic import ValidationError
from rest_framework import status
+from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.models import Team
from posthog.models.integration import Integration
@@ -39,7 +40,12 @@ from products.alerts_platform.backend.facade.contracts import (
SourceKind,
)
from products.metrics.backend.alerts.evaluation import ABSENT_RESOLVE_AFTER, INFLIGHT_KEY, evaluate_metrics_alert_batch
-from products.metrics.backend.alerts.freshness import evaluation_time, fetch_metrics_freshness
+from products.metrics.backend.alerts.freshness import (
+ CHECKPOINT_EVAL_DELAY,
+ IngestionReach,
+ fetch_metrics_freshness,
+ fetch_partition_checkpoint,
+)
from products.metrics.backend.alerts.source_config import MetricsPlatformAlertConfig
from products.metrics.backend.tests._seeder import seed_metric, truncate_metrics_tables
@@ -98,19 +104,28 @@ class TestMetricsAlertCreate(APIBaseTest):
class TestEvaluationTime(SimpleTestCase):
@parameterized.expand(
[
- ("ingestion_slightly_behind", timedelta(seconds=-30), timedelta(seconds=-30)),
- ("ingestion_lagging", timedelta(minutes=-20), timedelta(minutes=-20)),
- ("ingestion_past_the_due_time", timedelta(seconds=30), timedelta(0)),
- ("freshness_unknown", None, timedelta(0)),
+ ("ingestion_slightly_behind", timedelta(seconds=-30), None, timedelta(seconds=-30)),
+ ("ingestion_lagging", timedelta(minutes=-20), None, timedelta(minutes=-20)),
+ ("ingestion_past_the_due_time", timedelta(seconds=30), None, timedelta(0)),
+ ("freshness_unknown", None, None, timedelta(0)),
+ ("checkpoint_overrides_freshness", timedelta(0), timedelta(0), -CHECKPOINT_EVAL_DELAY),
+ ("checkpoint_well_past_the_due_time", None, timedelta(minutes=5), timedelta(0)),
]
)
def test_a_check_reads_no_later_than_ingestion_reached(
- self, _name: str, freshness_offset: timedelta | None, expected_offset: timedelta
+ self,
+ _name: str,
+ freshness_offset: timedelta | None,
+ checkpoint_offset: timedelta | None,
+ expected_offset: timedelta,
) -> None:
due_at = datetime(2026, 1, 1, 12, 0, tzinfo=UTC)
freshness = None if freshness_offset is None else due_at + freshness_offset
+ checkpoint = None if checkpoint_offset is None else due_at + checkpoint_offset
+
+ reach = IngestionReach(checkpoint=checkpoint, newest_point=freshness)
- assert evaluation_time(due_at, freshness) == due_at + expected_offset
+ assert reach.evaluation_time(due_at) == due_at + expected_offset
def _vector(*series: tuple[dict[str, str], str]) -> dict[str, Any]:
@@ -159,6 +174,37 @@ class TestMetricsFreshnessRead(ClickhouseTestMixin, APIBaseTest):
assert now - timedelta(seconds=5) <= freshness <= datetime.now(UTC)
+class TestPartitionCheckpointRead(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ sync_execute("TRUNCATE TABLE IF EXISTS metrics_kafka_metrics")
+
+ def _deliver(self, partition: int, observed: datetime) -> None:
+ sync_execute(
+ "INSERT INTO metrics_kafka_metrics (_partition, _topic, max_offset, max_observed_timestamp) VALUES",
+ [(partition, "clickhouse_metrics", 1, observed)],
+ )
+
+ @parameterized.expand(
+ [
+ ("every_partition_recent", timedelta(seconds=40), timedelta(seconds=40)),
+ ("one_partition_stalled", timedelta(minutes=6), None),
+ ]
+ )
+ def test_reads_the_oldest_partitions_newest_capture(
+ self, _name: str, slowest_age: timedelta, expected_age: timedelta | None
+ ) -> None:
+ now = datetime.now(UTC).replace(microsecond=0)
+ # A partition's older block must not lower its checkpoint.
+ self._deliver(0, now - timedelta(minutes=30))
+ self._deliver(0, now - timedelta(seconds=10))
+ self._deliver(1, now - slowest_age)
+
+ checkpoint = fetch_partition_checkpoint(self.team, max_execution_time=5)
+
+ assert checkpoint == (None if expected_age is None else now - expected_age)
+
+
class TestMetricsAlertEvaluation(APIBaseTest):
def setUp(self) -> None:
super().setUp()
@@ -169,6 +215,9 @@ class TestMetricsAlertEvaluation(APIBaseTest):
self.freshness = self.enterContext(
patch("products.metrics.backend.alerts.evaluation.fetch_metrics_freshness", return_value=None)
)
+ self.checkpoint = self.enterContext(
+ patch("products.metrics.backend.alerts.evaluation.fetch_partition_checkpoint", return_value=None)
+ )
with team_scope(self.team.id):
self.configuration_id = create_configuration(
team_id=self.team.id,
@@ -240,7 +289,7 @@ class TestMetricsAlertEvaluation(APIBaseTest):
assert self._kinds(self._evaluate()) == {}
- self.freshness.return_value = self.due_at - timedelta(seconds=30)
+ self.freshness.return_value = self.due_at
resolved = self._evaluate()
assert self._kinds(resolved) == {"a": AlertEventKind.RESOLVED}
@@ -251,6 +300,40 @@ class TestMetricsAlertEvaluation(APIBaseTest):
assert self._kinds(self._evaluate()) == {}
+ def test_a_missing_series_resolves_at_once_when_every_partition_has_caught_up(self) -> None:
+ self.checkpoint.return_value = self.due_at
+ self.snuffle.return_value = _response(200, _vector(({"group": "a"}, "2000"), ({"group": "b"}, "2000")))
+ first = self._evaluate()
+
+ assert self._kinds(first) == {"a": AlertEventKind.FIRING, "b": AlertEventKind.FIRING}
+ assert self.snuffle.call_args.kwargs["data"]["time"] == str((self.due_at - CHECKPOINT_EVAL_DELAY).timestamp())
+
+ self._next_check(first)
+ self.checkpoint.return_value = self.due_at
+ self.snuffle.return_value = _response(200, _vector(({"group": "b"}, "NaN")))
+
+ assert self._kinds(self._evaluate()) == {"a": AlertEventKind.RESOLVED}
+
+ def test_a_check_behind_its_last_read_waits_until_ingestion_passes_it(self) -> None:
+ self.freshness.return_value = self.due_at
+ self.snuffle.return_value = _response(200, _vector(({"group": "a"}, "2000")))
+ first = self._evaluate()
+
+ assert self._kinds(first) == {"a": AlertEventKind.FIRING}
+
+ last_read = self.due_at
+ self._next_check(first)
+ self.checkpoint.return_value = last_read + CHECKPOINT_EVAL_DELAY - timedelta(seconds=15)
+ deferred = self._evaluate_batch()
+
+ assert (deferred.outcomes, deferred.omitted) == ((), 1)
+
+ self.checkpoint.return_value = self.due_at
+ self.snuffle.return_value = _response(200, _vector(({"group": "a"}, "10")))
+
+ assert self._kinds(self._evaluate()) == {"a": AlertEventKind.RESOLVED}
+ assert self.snuffle.call_args.kwargs["data"]["time"] == str((self.due_at - CHECKPOINT_EVAL_DELAY).timestamp())
+
def test_a_firing_held_back_by_a_mute_is_not_announced_on_a_value_with_no_number(self) -> None:
self.snuffle.return_value = _response(200, _vector(({"group": "a"}, "2000")))
first = self._evaluate()