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(logs): shard alert checks by team so a team's alerts share a query (#109850)

Jon McCallume450ffe16a17
diff --git a/products/logs/backend/alert_utils.py b/products/logs/backend/alert_utils.py
index 053cf55f0b9d..2feb70a2c1c9 100644
--- a/products/logs/backend/alert_utils.py
+++ b/products/logs/backend/alert_utils.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import os
from datetime import UTC, datetime, timedelta
-from uuid import UUID
+from uuid import UUID, uuid5
from django.db.models import Q
@@ -42,9 +42,16 @@ SCHEDULE_INTERVAL_SECONDS = 60
MAX_BYTES_TO_READ = int(os.environ.get("LOGS_ALERTING_MAX_BYTES_TO_READ", "5368709120"))
-def compute_shard_offset_seconds(alert_id: UUID, check_interval_minutes: int) -> int:
+# 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")
+
+
+def compute_shard_offset_seconds(team_id: int, check_interval_minutes: int) -> int:
return shared_compute_shard_offset_seconds(
- alert_id,
+ uuid5(_TEAM_SHARD_NAMESPACE, str(team_id)),
check_interval_minutes,
schedule_interval_seconds=SCHEDULE_INTERVAL_SECONDS,
)
diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.py
index 37c6690d831c..df99b73dc4f0 100644
--- a/products/logs/backend/temporal/activities.py
+++ b/products/logs/backend/temporal/activities.py
@@ -1126,7 +1126,7 @@ def _stage_alert_for_save(dispatched: _DispatchedAlert, now: datetime) -> tuple[
alert.next_check_at,
alert.check_interval_minutes,
now,
- shard_offset_seconds=compute_shard_offset_seconds(alert.id, alert.check_interval_minutes),
+ shard_offset_seconds=compute_shard_offset_seconds(alert.team_id, alert.check_interval_minutes),
)
try:
alert.next_check_at = next_allowed_check_at(
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index 19f634f74868..ffdfc6aca7ba 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -21,7 +21,6 @@ from posthog.models.user import User
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCount
-from products.logs.backend.alert_utils import compute_shard_offset_seconds
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
from products.logs.backend.presentation.views.alerts_api import (
ALLOWED_WINDOW_MINUTES,
@@ -2135,6 +2134,16 @@ class TestSimulateEvaluatorLifecycleParity(ClickhouseTestMixin, APIBaseTest):
)
self._checkpoint_patcher.start()
self.addCleanup(self._checkpoint_patcher.stop)
+ # Pin the shard offset to 0 so evaluator NCAs align with the simulator's
+ # canonical-grid bucket boundaries. Without this, the evaluator advances NCAs
+ # onto the team's shard offset (e.g. :02/:07 instead of :00/:05) and the
+ # simulator's :00/:05 bucket evaluations disagree on event timing.
+ self._shard_patcher = patch(
+ "products.logs.backend.temporal.activities.compute_shard_offset_seconds",
+ return_value=0,
+ )
+ self._shard_patcher.start()
+ self.addCleanup(self._shard_patcher.stop)
# A None return would read as "enqueue failed" and roll back every
# notification, so the fake must return a (mock) ProduceResult.
self._kafka_patcher = patch(
@@ -2180,17 +2189,6 @@ class TestSimulateEvaluatorLifecycleParity(ClickhouseTestMixin, APIBaseTest):
"state": AlertState.NOT_FIRING.value,
}
defaults.update(overrides)
- # Pin the test alert to shard 0 so its evaluator NCAs align with the
- # simulator's canonical-grid bucket boundaries. Without this, the
- # evaluator advances NCAs onto the alert's shard offset (e.g. :02/:07
- # instead of :00/:05) and the simulator's :00/:05 bucket evaluations
- # disagree on event timing.
- cadence = int(defaults["check_interval_minutes"])
- while True:
- candidate = uuid4()
- if compute_shard_offset_seconds(candidate, cadence) == 0:
- defaults["id"] = candidate
- break
return LogsAlertConfiguration.objects.create(**defaults)
def _drive_evaluator(
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index 4c0d6ebde678..5a36b24b50c8 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -770,14 +770,20 @@ class TestEvaluateSingleAlert(APIBaseTest):
@patch("products.logs.backend.temporal.activities.produce_alert_internal_event")
def test_advances_next_check_at(self, mock_produce, mock_query_cls):
_mock_buckets(mock_query_cls, [5])
- alert = self._make_alert(next_check_at=datetime(2025, 1, 1, 0, 0, 0, tzinfo=UTC))
+ # Alert IDs are random, so with per-alert sharding two alerts usually land in
+ # different slots. Team sharding puts every alert of a team in the same slot.
+ alerts = [self._make_alert(next_check_at=datetime(2025, 1, 1, 0, 0, 0, tzinfo=UTC)) for _ in range(6)]
stats = {"checked": 0, "fired": 0, "resolved": 0, "errored": 0}
now = datetime(2025, 1, 1, 0, 1, 0, tzinfo=UTC)
- _evaluate_and_save_one(alert, now, stats)
+ for alert in alerts:
+ _evaluate_and_save_one(alert, now, stats)
+ alert.refresh_from_db()
- alert.refresh_from_db()
- assert alert.next_check_at is not None and alert.next_check_at > now
+ next_checks = {alert.next_check_at for alert in alerts}
+ assert len(next_checks) == 1
+ (next_check_at,) = next_checks
+ assert next_check_at is not None and next_check_at > now
@time_machine.travel("2025-01-01T21:58:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
diff --git a/products/logs/backend/test/test_shard_offset.py b/products/logs/backend/test/test_shard_offset.py
new file mode 100644
index 000000000000..e3f0f570ab4e
--- /dev/null
+++ b/products/logs/backend/test/test_shard_offset.py
@@ -0,0 +1,12 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.logs.backend.alert_utils import compute_shard_offset_seconds
+
+
+class TestComputeShardOffsetSeconds(SimpleTestCase):
+ @parameterized.expand([(1,), (5,), (15,), (60,)])
+ def test_team_offsets_cover_every_minute_slot_of_the_cadence(self, cadence: int) -> None:
+ offsets = {compute_shard_offset_seconds(team_id, cadence) for team_id in range(1, 2001)}
+ assert offsets == {slot * 60 for slot in range(cadence)}