: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(alerts): extract shared alert sweep scheduling helpers (3/7) (#68938)
Matt Pua5442ef0285ba
diff --git a/common/alerting/scheduling.py b/common/alerting/scheduling.pynew file mode 100644index 000000000000..e128a1ed4883--- /dev/null+++ b/common/alerting/scheduling.py@@ -0,0 +1,110 @@+"""Scheduling math for alerts with fixed, minute-based check intervals.++This is compatible with the real-time, 15-minute, and hourly insight alert+cadences. Daily, weekly, and monthly insight alerts remain product-specific+because they align checks to the team's timezone and apply schedule restrictions.+"""++from __future__ import annotations++from datetime import datetime, timedelta+from uuid import UUID++# How often a sweep schedule typically fires. Drives shard granularity in+# `compute_shard_offset_seconds`: schedule fires every N seconds, so a+# cadence of M seconds has `M // N` shard slots available.+DEFAULT_SCHEDULE_INTERVAL_SECONDS = 60+++def compute_shard_offset_seconds(+ alert_id: UUID,+ check_interval_minutes: int,+ *,+ schedule_interval_seconds: int = DEFAULT_SCHEDULE_INTERVAL_SECONDS,+) -> int:+ """Deterministic per-alert offset within the cadence period.++ Spreads alerts across `cadence / schedule_interval_seconds` slots so cron+ fires pick up roughly equal slices instead of the whole fleet at once. With+ a 60s schedule interval and a 5-min cadence, alerts distribute over+ 5 buckets at offsets [0, 60, 120, 180, 240] seconds.++ `alert_id.int` is stable across pod restarts (process-local `hash()` is not).+ For UUIDv7 IDs, the low bits are the random portion, so the modulus operation+ produces a uniform distribution.+ Cadences ≤ schedule interval get 1 shard (no spread possible).+ """+ cadence_seconds = check_interval_minutes * 60+ shard_count = max(1, cadence_seconds // schedule_interval_seconds)+ shard_index = alert_id.int % shard_count+ return shard_index * schedule_interval_seconds+++def advance_next_check_at(+ current_next_check_at: datetime | None,+ check_interval_minutes: int,+ now: datetime,+ *,+ shard_offset_seconds: int = 0,+) -> datetime:+ """Schedule-relative advancement, snapped to the canonical cadence grid.++ The scheduler cron fires every minute. A sub-minute offset on the returned+ `next_check_at` (e.g. 12:05:30) makes the cron skip a full tick waiting for+ it — the alert is picked up at 12:06:00, ~30s late, every cycle. Snapping+ to the cadence grid (every 5-min alert lands on :00/:05/:10/..., every+ 10-min on :00/:10/:20/..., etc.) eliminates that lag AND 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+ across cron fires (see `compute_shard_offset_seconds`). With offset=120 and+ a 5-min cadence, the alert lands on :02/:07/:12/... instead of :00/:05/:10.+ Default 0 = no shard, alert sits on the canonical grid.++ Any drifted `next_check_at` — sub-minute drift OR minute-level offset (e.g.+ legacy alerts on a per-creation-time grid) self-heals to canonical on its+ next return. Existing alerts heal lazily, one transient short-gap each (the+ state machine handles the brief overlap window via N-of-M dedup).++ Inter-eval gaps are exactly `check_interval_minutes` in steady state. The+ only "shorter than cadence" gaps are (1) creation-to-first-eval and (2)+ the one-time heal cycle for a previously-drifted alert. Both are+ cosmetic because alert eval windows tile correctly and are anchored+ on `date_to`, not on prior eval time.+ """+ if check_interval_minutes <= 0:+ raise ValueError(f"check_interval_minutes must be positive, got {check_interval_minutes}")+ interval = timedelta(minutes=check_interval_minutes)++ if current_next_check_at is None:+ next_at = now + interval+ else:+ next_at = current_next_check_at + interval+ if next_at <= now:+ elapsed = (now - next_at).total_seconds()+ intervals_to_skip = int(elapsed // interval.total_seconds()) + 1+ next_at += interval * intervals_to_skip++ # Bump by full interval (not 1 cadence-grid slot upward) when the floor+ # lands at/before `now`, so the alert stays on its canonical cadence grid.+ snapped = _floor_to_cadence_grid(next_at, check_interval_minutes) + timedelta(seconds=shard_offset_seconds)+ if snapped <= now:+ snapped += interval+ return snapped+++def _floor_to_cadence_grid(t: datetime, cadence_minutes: int) -> datetime:+ """Floor to the previous cadence-grid slot, anchored at midnight of `t`.++ For divisors of 60 (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60), this is+ "every cadence minutes within the hour", the grid an operator expects+ (5-min alerts on :00/:05/:10, 15-min on :00/:15/:30/:45, etc.). Cadences+ > 60 that divide 1440 (90, 120, 240, 360, 480, 720, 1440) also tile+ cleanly. Cadences that divide neither 60 nor 1440 (e.g. 7, 11, 100) get+ a discontinuity at midnight where the grid re-anchors. This is fine in practice+ because alert UI almost certainly constrains cadence to common values.+ """+ total_minutes = t.hour * 60 + t.minute+ floored_minutes = (total_minutes // cadence_minutes) * cadence_minutes+ return t.replace(hour=floored_minutes // 60, minute=floored_minutes % 60, second=0, microsecond=0)diff --git a/products/logs/backend/alert_utils.py b/products/logs/backend/alert_utils.pyindex 9a29b271d14f..4f5f54d1a4cf 100644--- a/products/logs/backend/alert_utils.py+++ b/products/logs/backend/alert_utils.py@@ -1,11 +1,26 @@from __future__ import annotationsimport os-from datetime import datetime, timedelta+from datetime import datetimefrom uuid import UUID+from django.db.models import Q++from common.alerting.scheduling import (+ advance_next_check_at,+ compute_shard_offset_seconds as shared_compute_shard_offset_seconds,+)++__all__ = [+ "MAX_BYTES_TO_READ",+ "SCHEDULE_INTERVAL_SECONDS",+ "advance_next_check_at",+ "compute_shard_offset_seconds",+ "due_alerts_q",+]+# How often the Temporal schedule fires. Drives shard granularity in-# `compute_shard_offset_seconds` — schedule fires every N seconds, so a+# `compute_shard_offset_seconds`: schedule fires every N seconds, so a# cadence of M seconds has `M // N` shard slots available.SCHEDULE_INTERVAL_SECONDS = 60@@ -15,95 +30,23 @@ SCHEDULE_INTERVAL_SECONDS = 60# redeploying. Aligns to CH's GiB-based reporting (1024^3) so the value here matches# the "max bytes: N GiB" in CH error messages. Default 5 GiB (5,368,709,120).# Lives here, not in `temporal/constants.py`, because `alert_check_query.py` (the-# consumer) is outside the temporal package — importing it from temporal would create-# a circular import via `temporal/__init__.py` → activities → alert_check_query.+# consumer) is outside the temporal package. Importing it from temporal would create+# a circular import via `temporal/__init__.py` to activities to alert_check_query.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:- """Deterministic per-alert offset within the cadence period.-- Spreads alerts across `cadence / SCHEDULE_INTERVAL_SECONDS` slots so cron- fires pick up roughly equal slices instead of the whole fleet at once. With- `SCHEDULE_INTERVAL_SECONDS=60` and a 5-min cadence, alerts distribute over- 5 buckets at offsets [0, 60, 120, 180, 240] seconds.-- `alert_id.int` is stable across pod restarts (process-local `hash()` is not).- For UUIDv7 IDs, the low bits are the random portion — the modulus operation- naturally lands on those bits, so distribution is uniform.- Cadences ≤ schedule interval get 1 shard (no spread possible).- """- cadence_seconds = check_interval_minutes * 60- shard_count = max(1, cadence_seconds // SCHEDULE_INTERVAL_SECONDS)- shard_index = alert_id.int % shard_count- return shard_index * SCHEDULE_INTERVAL_SECONDS---def advance_next_check_at(- current_next_check_at: datetime | None,- check_interval_minutes: int,- now: datetime,- *,- shard_offset_seconds: int = 0,-) -> datetime:- """Schedule-relative advancement, snapped to the canonical cadence grid.-- The scheduler cron fires every minute. A sub-minute offset on the returned- `next_check_at` (e.g. 12:05:30) makes the cron skip a full tick waiting for- it — the alert is picked up at 12:06:00, ~30s late, every cycle. Snapping- to the cadence grid (every 5-min alert lands on :00/:05/:10/..., every- 10-min on :00/:10/:20/..., etc.) eliminates that lag AND 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- across cron fires (see `compute_shard_offset_seconds`). With offset=120 and- a 5-min cadence, the alert lands on :02/:07/:12/... instead of :00/:05/:10.- Default 0 = no shard, alert sits on the canonical grid.-- Any drifted `next_check_at` — sub-minute drift OR minute-level offset (e.g.- legacy alerts on a per-creation-time grid) — self-heals to canonical on its- next return. Existing alerts heal lazily, one transient short-gap each (the- state machine handles the brief overlap window via N-of-M dedup).-- Inter-eval gaps are exactly `check_interval_minutes` in steady state. The- only "shorter than cadence" gaps are (1) creation-to-first-eval and (2)- the one-time heal cycle for a previously-drifted alert. Both are- cosmetic — alert eval windows tile correctly because they're anchored- on `date_to`, not on prior eval time.- """- if check_interval_minutes <= 0:- raise ValueError(f"check_interval_minutes must be positive, got {check_interval_minutes}")- interval = timedelta(minutes=check_interval_minutes)-- if current_next_check_at is None:- next_at = now + interval- else:- next_at = current_next_check_at + interval- if next_at <= now:- elapsed = (now - next_at).total_seconds()- intervals_to_skip = int(elapsed // interval.total_seconds()) + 1- next_at += interval * intervals_to_skip-- # Bump by full interval (not 1 cadence-grid slot upward) when the floor- # lands at/before `now`, so the alert stays on its canonical cadence grid.- snapped = _floor_to_cadence_grid(next_at, check_interval_minutes) + timedelta(seconds=shard_offset_seconds)- if snapped <= now:- snapped += interval- return snapped---def _floor_to_cadence_grid(t: datetime, cadence_minutes: int) -> datetime:- """Floor to the previous cadence-grid slot, anchored at midnight of `t`.-- For divisors of 60 (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60), this is- "every cadence minutes within the hour" — the grid an operator expects- (5-min alerts on :00/:05/:10, 15-min on :00/:15/:30/:45, etc.). Cadences- > 60 that divide 1440 (90, 120, 240, 360, 480, 720, 1440) also tile- cleanly. Cadences that divide neither 60 nor 1440 (e.g. 7, 11, 100) get- a discontinuity at midnight where the grid re-anchors — fine in practice- because alert UI almost certainly constrains cadence to common values.- """- total_minutes = t.hour * 60 + t.minute- floored_minutes = (total_minutes // cadence_minutes) * cadence_minutes- return t.replace(hour=floored_minutes // 60, minute=floored_minutes % 60, second=0, microsecond=0)+ return shared_compute_shard_offset_seconds(+ alert_id,+ check_interval_minutes,+ schedule_interval_seconds=SCHEDULE_INTERVAL_SECONDS,+ )+++def due_alerts_q(now: datetime, *, broken_state: str, snoozed_state: str) -> Q:+ return (+ Q(enabled=True)+ & (Q(next_check_at__lte=now) | Q(next_check_at__isnull=True))+ & ~Q(state=broken_state)+ & ~Q(state=snoozed_state, snooze_until__gt=now)+ )diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.pyindex 8d083ea62a59..5e4a9e059aa8 100644--- a/products/logs/backend/temporal/activities.py+++ b/products/logs/backend/temporal/activities.py@@ -11,7 +11,6 @@ from datetime import UTC, datetime, timedeltafrom itertools import batchedfrom django.db import transaction-from django.db.models import Qfrom django.db.utils import IntegrityErrorimport structlog@@ -58,7 +57,7 @@ from products.logs.backend.alert_state_machine import (apply_outcome,evaluate_alert_check,)-from products.logs.backend.alert_utils import advance_next_check_at, compute_shard_offset_seconds+from products.logs.backend.alert_utils import advance_next_check_at, compute_shard_offset_seconds, due_alerts_qfrom products.logs.backend.logs_url_params import build_logs_url_paramsfrom products.logs.backend.models import LogsAlertConfiguration, LogsAlertEventfrom products.logs.backend.temporal.constants import (@@ -341,13 +340,12 @@ class EmitAlertSignalsInput:def _due_alerts_qs(now: datetime):- return (- LogsAlertConfiguration.objects.filter(- Q(enabled=True),- Q(next_check_at__lte=now) | Q(next_check_at__isnull=True),+ return LogsAlertConfiguration.objects.filter(+ due_alerts_q(+ now,+ broken_state=LogsAlertConfiguration.State.BROKEN,+ snoozed_state=LogsAlertConfiguration.State.SNOOZED,)- .exclude(state=LogsAlertConfiguration.State.SNOOZED, snooze_until__gt=now)- .exclude(state=LogsAlertConfiguration.State.BROKEN))diff --git a/products/logs/backend/test/test_due_alerts_q.py b/products/logs/backend/test/test_due_alerts_q.pynew file mode 100644index 000000000000..f6027970d64c--- /dev/null+++ b/products/logs/backend/test/test_due_alerts_q.py@@ -0,0 +1,42 @@+from datetime import UTC, datetime, timedelta++from posthog.test.base import BaseTest++from parameterized import parameterized++from products.logs.backend.alert_utils import due_alerts_q+from products.logs.backend.models import LogsAlertConfiguration++NOW = datetime(2026, 3, 19, 12, 0, tzinfo=UTC)+PAST = NOW - timedelta(minutes=5)+FUTURE = NOW + timedelta(minutes=5)++State = LogsAlertConfiguration.State+++class TestDueAlertsQ(BaseTest):+ def _is_due(self, alert: LogsAlertConfiguration) -> bool:+ q = due_alerts_q(NOW, broken_state=State.BROKEN, snoozed_state=State.SNOOZED)+ return LogsAlertConfiguration.objects.filter(q, id=alert.id).exists()++ @parameterized.expand(+ [+ ("due_past_next_check", {"next_check_at": PAST}, True),+ ("due_never_checked", {"next_check_at": None}, True),+ ("not_due_future_next_check", {"next_check_at": FUTURE}, False),+ ("disabled", {"enabled": False}, False),+ ("broken", {"state": State.BROKEN}, False),+ ("snoozed_state_active_snooze", {"state": State.SNOOZED, "snooze_until": FUTURE}, False),+ ("snoozed_state_expired_snooze", {"state": State.SNOOZED, "snooze_until": PAST}, True),+ ("snoozed_state_null_snooze", {"state": State.SNOOZED, "snooze_until": None}, True),+ (+ "non_snoozed_state_ignores_snooze_until",+ {"state": State.FIRING, "snooze_until": FUTURE},+ True,+ ),+ ]+ )+ def test_due_alerts_q(self, _name: str, overrides: dict, expected_due: bool) -> None:+ fields: dict = {"team": self.team, "name": "alert", "next_check_at": PAST, **overrides}+ alert = LogsAlertConfiguration.objects.create(**fields)+ assert self._is_due(alert) == expected_due