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.

fix(alerts): shard platform logs checks by query shape to share queries (#116691)

Jimmy Zhu0463fee63ddc
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index fc7eccaa0c93..4914b3f89f91 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -230,6 +230,11 @@ Flooring to the minute loses nothing that load spreading provides: `compute_shar
whole multiples of the 60-second schedule interval, so spreading moves an alert between minutes rather
than within one.
+A source can set `schedule_group` on an outcome to spread by team and group instead of by configuration, through `compute_team_shard_offset_seconds`.
+A team's alerts with one group and one cadence then share a batch key.
+Logs sets the group to the query shape (window, evaluation periods, projection eligibility), so alerts that can share a cohort query land in one batch, and alerts that cannot spread across slots.
+That keeps a batch under `MAX_COHORTS_PER_CYCLE` in the common case, where one slot per team would push a team with many shapes over it.
+
## Source evaluation bindings
`products/alerts_platform/backend/temporal/sources.py` maps a `SourceKind` to the workflow name that evaluates it.
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 8fd54c9f6b8f..db73988a98ae 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -242,6 +242,9 @@ class PlatformAlertOutcome:
# Recording an outcome without it leaves a configuration discovery keeps handing back to an
# evaluation that cannot succeed.
disable: bool = False
+ # A team's checks with the same group are due in one slot, so a source that answers them with
+ # one query can do so. None spreads the configuration by its own id.
+ schedule_group: str | None = None
@frozen
diff --git a/products/alerts_platform/backend/facade/scheduling.py b/products/alerts_platform/backend/facade/scheduling.py
index fae8709dbdfa..544fe23f496b 100644
--- a/products/alerts_platform/backend/facade/scheduling.py
+++ b/products/alerts_platform/backend/facade/scheduling.py
@@ -17,7 +17,7 @@ from datetime import UTC, date, datetime, time, timedelta
from enum import StrEnum
from math import ceil
from typing import Any, Final, cast
-from uuid import UUID
+from uuid import UUID, uuid5
import pytz
from dateutil.relativedelta import relativedelta
@@ -53,6 +53,30 @@ def compute_shard_offset_seconds(
return shard_index * schedule_interval_seconds
+# uuid5 keeps sequential team IDs from filling the slots in a pattern. Production logs alerting
+# keys on this namespace too, so changing it moves every logs alert to a new slot.
+_TEAM_SHARD_NAMESPACE = UUID("4f2c9a1e-5b7d-4e8a-9c3f-6d1b2a7e8f90")
+
+
+def compute_team_shard_offset_seconds(
+ team_id: int,
+ check_interval_minutes: int,
+ *,
+ group: str | None = None,
+ schedule_interval_seconds: int = DEFAULT_SCHEDULE_INTERVAL_SECONDS,
+) -> int:
+ """One slot for all of a team's alerts in `group` on a cadence, for a source that answers them
+ with one query per slot. A per-alert offset splits them across slots, and each slot then runs
+ its own query. Different groups spread across slots, so one slot does not collect every
+ query the team needs."""
+ key = str(team_id) if group is None else f"{team_id}:{group}"
+ return compute_shard_offset_seconds(
+ uuid5(_TEAM_SHARD_NAMESPACE, key),
+ check_interval_minutes,
+ schedule_interval_seconds=schedule_interval_seconds,
+ )
+
+
def advance_next_check_at(
current_next_check_at: datetime | None,
check_interval_minutes: int,
@@ -67,7 +91,7 @@ def advance_next_check_at(
it. Snapping to the cadence grid aligns every alert sharing a cadence onto
the same canonical grid regardless of when it was created.
- `shard_offset_seconds` shifts the canonical grid per-alert to spread load
+ `shard_offset_seconds` shifts the canonical grid per alert or per team to spread load
across cron fires. Existing drifted alerts heal lazily on their next run.
"""
if check_interval_minutes <= 0:
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 47e629aaf172..c8c6bd55bf9b 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -23,6 +23,7 @@ from products.alerts_platform.backend.facade.platform_metrics import increment_h
from products.alerts_platform.backend.facade.scheduling import (
advance_schedule,
compute_shard_offset_seconds,
+ compute_team_shard_offset_seconds,
to_recurrence_interval,
validate_and_normalize_schedule_start_time,
)
@@ -208,6 +209,14 @@ def _record_history(team_id: int, rows: Sequence[PlatformAlertEventRow]) -> None
safe_record(increment_history_rows_dropped, len(rows) - recorded)
+def _shard_offset_seconds(configuration: PlatformAlertConfiguration, outcome: PlatformAlertOutcome) -> int:
+ if outcome.schedule_group is None:
+ return compute_shard_offset_seconds(configuration.id, configuration.check_interval_minutes)
+ return compute_team_shard_offset_seconds(
+ configuration.team_id, configuration.check_interval_minutes, group=outcome.schedule_group
+ )
+
+
def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now: datetime) -> int:
"""Persists a batch's decisions and advances each configuration's schedule.
@@ -267,9 +276,7 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
tz_name=team_timezone,
now=now,
configuration_id=configuration.id,
- shard_offset_seconds=compute_shard_offset_seconds(
- configuration.id, configuration.check_interval_minutes
- ),
+ shard_offset_seconds=_shard_offset_seconds(configuration, outcome),
)
PlatformAlert.objects.for_team(team_id).bulk_update(
diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index 78ba56f58e5e..cfa60e734986 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -143,6 +143,45 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
assert rows == [("not_firing", self.cutoff)]
assert self._alert().firing_started_at is None
+ @parameterized.expand([("one_schedule_group", "5:1:True", 1), ("no_schedule_group", None, 2)])
+ def test_a_team_checks_share_a_slot_only_when_the_source_groups_them(
+ self, _name: str, schedule_group: str | None, expected_slots: int
+ ) -> None:
+ # Ids 1 and 2 fall in different slots of a 5-minute cadence when the offset is per configuration.
+ with team_scope(self.team.id):
+ configurations = [
+ PlatformAlertConfiguration.objects.create(
+ id=UUID(int=n),
+ team=self.team,
+ name=f"Alert {n}",
+ source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
+ source_config={},
+ check_interval_minutes=5,
+ next_check_at=self.cutoff - timedelta(minutes=1),
+ )
+ for n in (1, 2)
+ ]
+ outcomes = [
+ PlatformAlertOutcome(
+ configuration_id=c.id,
+ evaluation_key=f"window:{self.cutoff.isoformat()}",
+ kind=AlertEventKind.CHECK,
+ new_state="not_firing",
+ notified=False,
+ consecutive_failures=0,
+ schedule_group=schedule_group,
+ )
+ for c in configurations
+ ]
+ record_outcomes(self.team.id, outcomes, self.cutoff)
+
+ with team_scope(self.team.id):
+ due = {
+ c.next_check_at
+ for c in PlatformAlertConfiguration.objects.filter(id__in=[c.id for c in configurations])
+ }
+ assert len(due) == expected_slots
+
def _copy(self, legacy_id: UUID, **overrides: Any) -> None:
fields: dict[str, Any] = {
"legacy_configuration_id": legacy_id,
diff --git a/products/logs/backend/alert_check_query.py b/products/logs/backend/alert_check_query.py
index 127148f5f7c8..e8921a5f02b5 100644
--- a/products/logs/backend/alert_check_query.py
+++ b/products/logs/backend/alert_check_query.py
@@ -649,7 +649,10 @@ def is_projection_eligible(filters: dict) -> bool:
return True
if not isinstance(filter_group, dict):
return False
- for group in filter_group.get("values", []):
+ groups = filter_group.get("values", [])
+ if not isinstance(groups, list):
+ return False
+ for group in groups:
if not isinstance(group, dict):
return False
if group.get("values"):
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index a8fcb150b426..9d0efebed255 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -185,12 +185,37 @@ def window_end_of(evaluation_key: str) -> datetime | None:
return None
+@frozen
+class _QueryShape:
+ """The part of `_cohort_key` a configuration fixes. Checks that differ here never share a query."""
+
+ window_minutes: object
+ evaluation_periods: int
+ projection_eligible: bool
+
+ @classmethod
+ def of(cls, check: PlatformAlertCheckInput) -> "_QueryShape":
+ return cls(
+ window_minutes=check.condition.get("window_minutes"),
+ evaluation_periods=check.evaluation_periods,
+ projection_eligible=is_projection_eligible(check.source_config),
+ )
+
+
+def _schedule_group(check: PlatformAlertCheckInput) -> str:
+ # The platform puts a team's checks with one group in one slot and spreads different groups
+ # across slots, so one batch rarely holds more cohorts than `MAX_COHORTS_PER_CYCLE`.
+ shape = _QueryShape.of(check)
+ return f"{shape.window_minutes}:{shape.evaluation_periods}:{shape.projection_eligible}"
+
+
def _cohort_key(check: PlatformAlertCheckInput, checkpoint: datetime | None, now: datetime) -> tuple:
+ shape = _QueryShape.of(check)
return (
- LogsAlertCondition.of(check).window_minutes,
- check.evaluation_periods,
+ shape.window_minutes,
+ shape.evaluation_periods,
check.check_interval_minutes,
- is_projection_eligible(check.source_config),
+ shape.projection_eligible,
resolve_alert_date_to(check.next_check_at or now, checkpoint),
)
@@ -325,6 +350,8 @@ def _recorded(
query_duration_ms=query_duration_ms,
muted_notification=muted_notification,
disable=disable,
+ # A broken alert is never discovered again, so its slot does not matter.
+ schedule_group=None if outcome.new_state == AlertState.BROKEN else _schedule_group(check),
)
diff --git a/products/logs/backend/alert_utils.py b/products/logs/backend/alert_utils.py
index d92bc1b41018..ae0cda896bc4 100644
--- a/products/logs/backend/alert_utils.py
+++ b/products/logs/backend/alert_utils.py
@@ -2,7 +2,6 @@ from __future__ import annotations
import os
from datetime import UTC, datetime, timedelta
-from uuid import UUID, uuid5
from django.db.models import Q
@@ -10,7 +9,7 @@ import structlog
from products.alerts_platform.backend.facade.scheduling import (
advance_next_check_at,
- compute_shard_offset_seconds as shared_compute_shard_offset_seconds,
+ compute_team_shard_offset_seconds,
parse_blocked_windows_tuples,
scan_next_unblocked_utc,
)
@@ -44,16 +43,10 @@ MAX_BYTES_TO_READ = int(os.environ.get("LOGS_ALERTING_MAX_BYTES_TO_READ", "53687
# Shard by team, not by alert. The cohort key includes `date_to`, which comes from
# `next_check_at`, so two alerts from one team share a ClickHouse query only when they
-# land in the same slot. The team ID goes through uuid5 so that sequential IDs do not
-# fill the slots in a pattern.
-_TEAM_SHARD_NAMESPACE = UUID("4f2c9a1e-5b7d-4e8a-9c3f-6d1b2a7e8f90")
-
-
+# land in the same slot.
def compute_shard_offset_seconds(team_id: int, check_interval_minutes: int) -> int:
- return shared_compute_shard_offset_seconds(
- uuid5(_TEAM_SHARD_NAMESPACE, str(team_id)),
- check_interval_minutes,
- schedule_interval_seconds=SCHEDULE_INTERVAL_SECONDS,
+ return compute_team_shard_offset_seconds(
+ team_id, check_interval_minutes, schedule_interval_seconds=SCHEDULE_INTERVAL_SECONDS
)
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index 7686dbf403d8..58e2d4967821 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -133,6 +133,18 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert configuration.next_check_at is not None
assert configuration.next_check_at > self.cutoff
+ def test_checks_that_can_share_a_query_carry_one_schedule_group(self) -> None:
+ same_a = self._configuration(name="A")
+ same_b = self._configuration(name="B")
+ longer_window = self._configuration(name="C", source_config={"condition": {**CONDITION, "window_minutes": 60}})
+ more_periods = self._configuration(name="D", evaluation_periods=3, datapoints_to_alarm=1)
+
+ evaluation, _ = self._run(same_a, same_b, longer_window, more_periods)
+
+ group = {o.configuration_id: o.schedule_group for o in evaluation.outcomes}
+ assert group[same_a.id] == group[same_b.id]
+ assert len({group[same_a.id], group[longer_window.id], group[more_periods.id]}) == 3
+
@parameterized.expand([("below_a_high_bound", 1000, "below"), ("above_zero", 0, "above")])
def test_a_backfilled_alert_evaluates_against_the_bound_it_was_copied_with(
self, _name: str, threshold_count: int, threshold_operator: str
@@ -274,15 +286,18 @@ class TestLogsAlertEvaluation(APIBaseTest):
("unknown_operator", {"condition": {**CONDITION, "threshold_operator": "equals"}}),
("non_numeric_window", {"condition": {**CONDITION, "window_minutes": "5"}}),
("zero_window", {"condition": {**CONDITION, "window_minutes": 0}}),
+ ("null_filter_values", {"condition": CONDITION, "filterGroup": {"type": "AND", "values": None}}),
]
)
def test_a_broken_config_stops_being_discovered(self, _name: str, source_config: dict[str, Any]) -> None:
configuration = self._configuration(source_config=source_config)
+ healthy = self._configuration(name="Healthy")
- evaluation, query = self._run(configuration)
+ evaluation, query = self._run(configuration, healthy)
self._record(evaluation)
- query.assert_not_called()
+ queried = {check.id for call in query.call_args_list for check in call.kwargs["alerts"]}
+ assert queried == {healthy.id}
with team_scope(self.team.id):
alert = platform_testing.alert_for(configuration.id)
assert alert is not None