: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): centralize scheduling in alerts product (#71593)
Matt Pua4756d47a887a
diff --git a/common/alerting/scheduling.py b/common/alerting/scheduling.pydeleted file mode 100644index e128a1ed4883..000000000000--- a/common/alerting/scheduling.py+++ /dev/null@@ -1,110 +0,0 @@-"""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/posthog/api/test/test_alert_15_minute_interval.py b/posthog/api/test/test_alert_15_minute_interval.pyindex 7a4f3828d973..7639d1b9f5b2 100644--- a/posthog/api/test/test_alert_15_minute_interval.py+++ b/posthog/api/test/test_alert_15_minute_interval.py@@ -11,11 +11,7 @@ from rest_framework import statusfrom posthog.schema import AlertCalculationInterval, AlertConditionType, InsightThresholdTypefrom posthog.constants import AvailableFeature-from posthog.tasks.alerts.utils import (- alert_calculation_interval_to_relativedelta,- calculation_interval_to_order,- next_check_time,-)+from posthog.tasks.alerts.utils import calculation_interval_to_order, next_check_timefrom products.alerts.backend.models.alert import AlertConfiguration@@ -103,10 +99,6 @@ class TestAlert15MinuteScheduling:AlertCalculationInterval.HOURLY)- def test_alert_calculation_interval_to_relativedelta_every_15_minutes(self) -> None:- delta = alert_calculation_interval_to_relativedelta(AlertCalculationInterval.EVERY_15_MINUTES)- assert delta.minutes == 15-def test_next_check_time_advances_by_15_minutes(self) -> None:alert = MagicMock(spec=AlertConfiguration)alert.calculation_interval = AlertCalculationInterval.EVERY_15_MINUTES@@ -126,7 +118,3 @@ class TestAlert15MinuteScheduling:def test_calculation_interval_to_order_raises_for_unknown_interval(self) -> None:with pytest.raises(ValueError, match="Unhandled alert calculation interval"):calculation_interval_to_order(cast(AlertCalculationInterval, "every_5_minutes"))-- def test_alert_calculation_interval_to_relativedelta_raises_for_unknown_interval(self) -> None:- with pytest.raises(ValueError, match="Unhandled alert calculation interval"):- alert_calculation_interval_to_relativedelta(cast(AlertCalculationInterval, "every_5_minutes"))diff --git a/posthog/api/test/test_alert_real_time_interval.py b/posthog/api/test/test_alert_real_time_interval.pyindex 0e7caff43121..5a2380ff4832 100644--- a/posthog/api/test/test_alert_real_time_interval.py+++ b/posthog/api/test/test_alert_real_time_interval.py@@ -10,11 +10,7 @@ from rest_framework import statusfrom posthog.schema import AlertCalculationInterval, AlertConditionType, InsightThresholdTypefrom posthog.constants import AvailableFeature-from posthog.tasks.alerts.utils import (- alert_calculation_interval_to_relativedelta,- calculation_interval_to_order,- next_check_time,-)+from posthog.tasks.alerts.utils import calculation_interval_to_order, next_check_timefrom products.alerts.backend.models.alert import AlertConfiguration@@ -174,10 +170,6 @@ class TestAlertRealTimeScheduling:AlertCalculationInterval.EVERY_15_MINUTES)- def test_alert_calculation_interval_to_relativedelta_real_time(self) -> None:- delta = alert_calculation_interval_to_relativedelta(AlertCalculationInterval.REAL_TIME)- assert delta.minutes == 2-def test_next_check_time_advances_by_2_minutes(self) -> None:alert = MagicMock(spec=AlertConfiguration)alert.calculation_interval = AlertCalculationInterval.REAL_TIMEdiff --git a/posthog/tasks/alerts/schedule_restriction.py b/posthog/tasks/alerts/schedule_restriction.pyindex 5029362c7b26..6c68a1b7cd8f 100644--- a/posthog/tasks/alerts/schedule_restriction.py+++ b/posthog/tasks/alerts/schedule_restriction.py@@ -1,231 +1,54 @@-"""Schedule restrictions (blocked local time windows) for insight alerts."""+"""Schedule restrictions (blocked local time windows) for insight alerts.++The pure minute-math and validation live in products/alerts/backend/scheduling.py; this+module keeps the AlertConfiguration-aware entry points plus the cap-exceeded+retry/logging fallback.+"""from __future__ import annotationsfrom datetime import UTC, datetime, timedelta-from typing import Any-import pytzimport structlogfrom products.alerts.backend.models.alert import AlertConfiguration+from products.alerts.backend.scheduling import (+ MAX_BLOCKED_WINDOWS,+ MAX_UNBLOCK_STEPS,+ MIN_BLOCKED_WINDOW_MINUTES,+ MINUTES_PER_DAY,+ is_local_minute_blocked,+ is_utc_datetime_blocked as _is_utc_datetime_blocked_pure,+ merged_intervals_cover_full_day,+ normalize_schedule_restriction_value,+ parse_blocked_windows_tuples,+ scan_next_unblocked_utc,+ validate_and_normalize_schedule_restriction,+)logger = structlog.get_logger(__name__)-MAX_BLOCKED_WINDOWS = 5-MINUTES_PER_DAY = 1440-# Minimum length of each declared blocked window on the local daily timeline (half-open; same rules as expand).-MIN_BLOCKED_WINDOW_MINUTES = 30-# When quiet hours hit an unusual corner case, computing the next allowed send time must not-# run indefinitely or hold up other alerts; we cap how long we spend on that lookup.-_MAX_UNBLOCK_STEPS = MINUTES_PER_DAY * 14---def _hhmm(minutes: int) -> str:- return f"{minutes // 60:02d}:{minutes % 60:02d}"---def normalize_schedule_restriction_value(raw: Any) -> dict[str, Any] | None:- """Coerce payloads that mean 'off' to None. Returns dict ready to validate or None."""- if raw is None:- return None- if raw == {}:- return None- if not isinstance(raw, dict):- raise ValueError("schedule_restriction must be an object or null")- windows = raw.get("blocked_windows")- if windows is None:- return None- if windows == []:- return None- if not isinstance(windows, list):- raise ValueError("blocked_windows must be an array")- return raw---def _parse_hhmm(value: str) -> int:- if not isinstance(value, str):- raise ValueError("Time must be a string HH:MM")- s = value.strip()- if s.count(":") != 1:- raise ValueError("Time must be HH:MM (seconds not allowed)")- parts = s.split(":")- try:- h = int(parts[0], 10)- m = int(parts[1], 10)- except ValueError as e:- raise ValueError("Invalid HH:MM") from e- if h < 0 or h > 23 or m < 0 or m > 59:- raise ValueError("Invalid HH:MM")- return h * 60 + m---def _parse_window_pair(start_s: str, end_s: str) -> tuple[int, int, bool]:- start = _parse_hhmm(start_s)- end = _parse_hhmm(end_s)- if start == end:- raise ValueError("Start and end must differ for a blocked window")- overnight = start > end- return start, end, overnight---def _blocked_window_span_minutes(start: int, end: int, overnight: bool) -> int:- """Total minutes blocked in one local 24h cycle for this window (matches _expand_windows_for_coverage)."""- if not overnight:- return end - start- if end == 0:- return MINUTES_PER_DAY - start- return (MINUTES_PER_DAY - start) + end---def _expand_windows_for_coverage(windows: list[tuple[int, int, bool]]) -> list[tuple[int, int]]:- """Half-open intervals within [0, MINUTES_PER_DAY) for one synthetic day."""- out: list[tuple[int, int]] = []- for start, end, overnight in windows:- if not overnight:- if start < end:- out.append((start, end))- else:- raise ValueError("Invalid window")- else:- if end == 0:- # e.g. 19:00–00:00 = block from 19:00 through end of local calendar day (end exclusive at midnight)- out.append((start, MINUTES_PER_DAY))- else:- out.append((start, MINUTES_PER_DAY))- out.append((0, end))- return out---def _merge_intervals_sorted(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:- if not intervals:- return []- intervals = sorted(intervals, key=lambda x: (x[0], x[1]))- merged: list[tuple[int, int]] = []- for a, b in intervals:- if b <= a:- continue- if not merged or merged[-1][1] < a:- merged.append((a, b))- else:- prev_a, prev_b = merged[-1]- merged[-1] = (prev_a, max(prev_b, b))- return merged-+# Module-level so tests can monkeypatch the cap; passed through to the pure scan.+_MAX_UNBLOCK_STEPS = MAX_UNBLOCK_STEPS-def merged_intervals_cover_full_day(merged: list[tuple[int, int]]) -> bool:- return bool(merged) and merged[0][0] == 0 and merged[0][1] >= MINUTES_PER_DAY---def _encode_merged_to_blocked_windows(merged: list[tuple[int, int]]) -> list[dict[str, str]]:- """Round-trip merged [0,1440) half-open segments to stored window dicts."""- if not merged:- return []- if len(merged) == 1:- a, b = merged[0]- if a < b:- if b == MINUTES_PER_DAY and a > 0:- return [{"start": _hhmm(a), "end": "00:00"}]- return [{"start": _hhmm(a), "end": _hhmm(b)}]- raise ValueError("Invalid merged interval")- if len(merged) == 2:- a1, b1 = merged[0]- a2, b2 = merged[1]- # Overnight split into [0, morning_end) and [evening_start, 1440) after sorting by start- if a1 == 0 and b2 == MINUTES_PER_DAY and a2 > b1:- return [{"start": _hhmm(a2), "end": _hhmm(b1)}]- out: list[dict[str, str]] = []- for a, b in merged:- if not a < b:- continue- if b == MINUTES_PER_DAY and a > 0:- out.append({"start": _hhmm(a), "end": "00:00"})- else:- out.append({"start": _hhmm(a), "end": _hhmm(b)})- return out---def validate_and_normalize_schedule_restriction(raw: Any) -> dict[str, Any] | None:- """- Validate API/store shape; merge overlaps on the daily timeline; return normalized dict or None.- Raises ValueError on invalid input.- """- normalized_in = normalize_schedule_restriction_value(raw)- if normalized_in is None:- return None-- windows_in = normalized_in.get("blocked_windows")- if not isinstance(windows_in, list):- raise ValueError("blocked_windows must be an array")- if len(windows_in) > MAX_BLOCKED_WINDOWS:- raise ValueError(f"At most {MAX_BLOCKED_WINDOWS} blocked time windows are allowed")-- parsed: list[tuple[int, int, bool]] = []- for idx, w in enumerate(windows_in):- if not isinstance(w, dict):- raise ValueError(f"blocked_windows[{idx}] must be an object")- start_s = w.get("start")- end_s = w.get("end")- if start_s is None or end_s is None:- raise ValueError(f"blocked_windows[{idx}] must have start and end (HH:MM)")- start_i, end_i, overnight = _parse_window_pair(str(start_s), str(end_s))- span = _blocked_window_span_minutes(start_i, end_i, overnight)- if span < MIN_BLOCKED_WINDOW_MINUTES:- raise ValueError(- f"blocked_windows[{idx}] must span at least {MIN_BLOCKED_WINDOW_MINUTES} minutes "- f"(half-open local window [start, end))"- )- parsed.append((start_i, end_i, overnight))-- expanded = _expand_windows_for_coverage(parsed)- merged = _merge_intervals_sorted(expanded)- if merged_intervals_cover_full_day(merged):- raise ValueError("Leave at least one time in the day when this alert can run")-- encoded = _encode_merged_to_blocked_windows(merged)- if not encoded:- return None- return {"blocked_windows": encoded}---def parse_blocked_windows_tuples(schedule_restriction: dict[str, Any] | None) -> list[tuple[int, int, bool]] | None:- if not schedule_restriction:- return None- windows = schedule_restriction.get("blocked_windows")- if not windows:- return None- out: list[tuple[int, int, bool]] = []- for w in windows:- if isinstance(w, dict) and "start" in w and "end" in w:- out.append(_parse_window_pair(str(w["start"]), str(w["end"])))- return out or None---def is_local_minute_blocked(minute: int, windows: list[tuple[int, int, bool]]) -> bool:- for start, end, overnight in windows:- if not overnight:- if start <= minute < end:- return True- else:- if end == 0:- if minute >= start:- return True- elif minute >= start or minute < end:- return True- return False---def _minute_of_local_datetime(dt_local: datetime) -> int:- return dt_local.hour * 60 + dt_local.minute+__all__ = [+ "MAX_BLOCKED_WINDOWS",+ "MINUTES_PER_DAY",+ "MIN_BLOCKED_WINDOW_MINUTES",+ "is_local_minute_blocked",+ "is_utc_datetime_blocked",+ "merged_intervals_cover_full_day",+ "next_unblocked_utc",+ "normalize_schedule_restriction_value",+ "parse_blocked_windows_tuples",+ "snap_candidate_utc_to_schedule_restriction",+ "validate_and_normalize_schedule_restriction",+]def is_utc_datetime_blocked(alert: AlertConfiguration, dt_utc: datetime) -> bool:windows = parse_blocked_windows_tuples(alert.schedule_restriction)- if not windows:- return False- tz = pytz.timezone(alert.team.timezone)- local = dt_utc.astimezone(tz).replace(second=0, microsecond=0)- return is_local_minute_blocked(_minute_of_local_datetime(local), windows)+ return _is_utc_datetime_blocked_pure(dt_utc, alert.team.timezone, windows)def next_unblocked_utc(alert: AlertConfiguration, from_utc: datetime) -> datetime:@@ -240,23 +63,13 @@ def _next_unblocked_utc(recursion_depth: int,) -> datetime:windows = parse_blocked_windows_tuples(alert.schedule_restriction)- if not windows:- return from_utc.astimezone(UTC).replace(microsecond=0)-- tz = pytz.timezone(alert.team.timezone)- cur = from_utc.astimezone(tz).replace(second=0, microsecond=0)- steps = 0- while steps < _MAX_UNBLOCK_STEPS:- m = _minute_of_local_datetime(cur)- if not is_local_minute_blocked(m, windows):- return cur.astimezone(pytz.UTC)- cur = cur + timedelta(minutes=1)- steps += 1+ found = scan_next_unblocked_utc(from_utc, alert.team.timezone, windows, max_steps=_MAX_UNBLOCK_STEPS)+ if found is not None:+ return foundlogger.warning("schedule_restriction.next_unblocked_utc_exceeded_cap",alert_id=str(alert.id),- steps=steps,recursion_depth=recursion_depth,)if recursion_depth >= 1:diff --git a/posthog/tasks/alerts/test/test_schedule_restriction.py b/posthog/tasks/alerts/test/test_schedule_restriction.pyindex 63643ebfb198..8dca597c738b 100644--- a/posthog/tasks/alerts/test/test_schedule_restriction.py+++ b/posthog/tasks/alerts/test/test_schedule_restriction.py@@ -5,113 +5,13 @@ import pytestfrom freezegun import freeze_timefrom unittest.mock import MagicMock-from parameterized import parameterized-from posthog.tasks.alerts import schedule_restriction as schedule_restriction_module-from posthog.tasks.alerts.schedule_restriction import (- is_utc_datetime_blocked,- next_unblocked_utc,- validate_and_normalize_schedule_restriction,-)+from posthog.tasks.alerts.schedule_restriction import is_utc_datetime_blocked, next_unblocked_utcfrom posthog.tasks.alerts.utils import next_check_at_after_schedule_restriction_changefrom products.alerts.backend.models.alert import AlertConfiguration-class TestValidateAndNormalizeScheduleRestriction:- @parameterized.expand(- [- (None, None),- ({}, None),- ({"blocked_windows": []}, None),- (- {"blocked_windows": [{"start": "22:00", "end": "07:00"}]},- {"blocked_windows": [{"start": "22:00", "end": "07:00"}]},- ),- ]- )- def test_normalize_feature_off_or_valid_overnight(self, raw: Any, expected: dict[str, Any] | None) -> None:- assert validate_and_normalize_schedule_restriction(raw) == expected-- def test_merges_overlapping_same_day_windows(self) -> None:- raw = {- "blocked_windows": [- {"start": "10:30", "end": "11:00"},- {"start": "10:40", "end": "11:15"},- ]- }- out = validate_and_normalize_schedule_restriction(raw)- assert out == {"blocked_windows": [{"start": "10:30", "end": "11:15"}]}-- def test_adjacent_half_open_windows_merge(self) -> None:- raw = {- "blocked_windows": [- {"start": "12:00", "end": "13:00"},- {"start": "13:00", "end": "14:00"},- ]- }- out = validate_and_normalize_schedule_restriction(raw)- assert out == {"blocked_windows": [{"start": "12:00", "end": "14:00"}]}-- def test_rejects_full_day_coverage(self) -> None:- raw = {- "blocked_windows": [- {"start": "00:00", "end": "12:00"},- {"start": "12:00", "end": "00:00"},- ]- }- with pytest.raises(ValueError, match="at least one time"):- validate_and_normalize_schedule_restriction(raw)-- def test_rejects_too_many_windows_before_merge(self) -> None:- raw = {"blocked_windows": [{"start": f"{i:02d}:00", "end": f"{i:02d}:30"} for i in range(6)]}- with pytest.raises(ValueError, match="At most 5"):- validate_and_normalize_schedule_restriction(raw)-- @parameterized.expand(- [- ("12:00:00",),- ("not_a_time",),- ]- )- def test_rejects_malformed_times(self, bad_time: str) -> None:- raw = {"blocked_windows": [{"start": bad_time, "end": "13:00"}]}- with pytest.raises(ValueError):- validate_and_normalize_schedule_restriction(raw)-- def test_rejects_equal_start_and_end(self) -> None:- raw = {"blocked_windows": [{"start": "10:00", "end": "10:00"}]}- with pytest.raises(ValueError, match="differ"):- validate_and_normalize_schedule_restriction(raw)-- def test_rejects_same_day_window_shorter_than_30_minutes(self) -> None:- raw = {"blocked_windows": [{"start": "10:00", "end": "10:29"}]}- with pytest.raises(ValueError, match="at least 30 minutes"):- validate_and_normalize_schedule_restriction(raw)-- def test_accepts_same_day_window_exactly_30_minutes(self) -> None:- raw = {"blocked_windows": [{"start": "10:00", "end": "10:30"}]}- assert validate_and_normalize_schedule_restriction(raw) == {- "blocked_windows": [{"start": "10:00", "end": "10:30"}],- }-- def test_rejects_overnight_window_shorter_than_30_minutes(self) -> None:- raw = {"blocked_windows": [{"start": "23:50", "end": "00:09"}]}- with pytest.raises(ValueError, match="at least 30 minutes"):- validate_and_normalize_schedule_restriction(raw)-- def test_accepts_overnight_window_exactly_30_minutes(self) -> None:- raw = {"blocked_windows": [{"start": "23:40", "end": "00:10"}]}- assert validate_and_normalize_schedule_restriction(raw) == {- "blocked_windows": [{"start": "23:40", "end": "00:10"}],- }-- def test_evening_until_midnight_encodes_as_end_00_00(self) -> None:- raw = {"blocked_windows": [{"start": "19:00", "end": "00:00"}]}- out = validate_and_normalize_schedule_restriction(raw)- assert out == {"blocked_windows": [{"start": "19:00", "end": "00:00"}]}--class TestIsUtcDatetimeBlockedAndNextUnblocked:def _alert(self, tz: str, restriction: dict[str, Any] | None) -> MagicMock:alert = MagicMock(spec=AlertConfiguration)@@ -121,31 +21,12 @@ class TestIsUtcDatetimeBlockedAndNextUnblocked:alert.schedule_restriction = restrictionreturn alert- @parameterized.expand(- [- ("2024-06-01T10:30:00+00:00", True),- ("2024-06-01T10:00:00+00:00", True),- ("2024-06-01T12:00:00+00:00", False),- ("2024-06-01T09:59:00+00:00", False),- ]- )- def test_same_day_window_half_open_utc_team(self, iso: str, blocked: bool) -> None:+ def test_is_blocked_reads_alert_timezone_and_restriction(self) -> None:alert = self._alert(- "UTC",+ "America/Los_Angeles",{"blocked_windows": [{"start": "10:00", "end": "12:00"}]},)- dt = datetime.fromisoformat(iso)- assert is_utc_datetime_blocked(alert, dt) is blocked-- def test_overnight_block_covers_local_night_utc_team(self) -> None:- alert = self._alert(- "UTC",- {"blocked_windows": [{"start": "22:00", "end": "07:00"}]},- )- assert is_utc_datetime_blocked(alert, datetime(2024, 6, 1, 23, 0, tzinfo=UTC)) is True- assert is_utc_datetime_blocked(alert, datetime(2024, 6, 1, 3, 0, tzinfo=UTC)) is True- assert is_utc_datetime_blocked(alert, datetime(2024, 6, 1, 7, 0, tzinfo=UTC)) is False- assert is_utc_datetime_blocked(alert, datetime(2024, 6, 1, 21, 59, tzinfo=UTC)) is False+ assert is_utc_datetime_blocked(alert, datetime(2024, 6, 1, 18, 0, tzinfo=UTC)) is Truedef test_next_unblocked_advances_to_end_of_window(self) -> None:alert = self._alert(@@ -156,31 +37,32 @@ class TestIsUtcDatetimeBlockedAndNextUnblocked:nxt = next_unblocked_utc(alert, fro)assert nxt == datetime(2024, 6, 1, 12, 0, tzinfo=UTC)- def test_next_unblocked_retries_next_day_when_minute_walk_hits_cap(self, monkeypatch: pytest.MonkeyPatch) -> None:+ def test_next_unblocked_retries_and_logs_when_scan_hits_cap(self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(schedule_restriction_module, "_MAX_UNBLOCK_STEPS", 5)+ warning = MagicMock()+ error = MagicMock()+ monkeypatch.setattr(schedule_restriction_module.logger, "warning", warning)+ monkeypatch.setattr(schedule_restriction_module.logger, "error", error)alert = self._alert("UTC",{"blocked_windows": [{"start": "10:00", "end": "12:00"}]},)fro = datetime(2024, 6, 1, 11, 0, tzinfo=UTC)nxt = next_unblocked_utc(alert, fro)- # First walk stops early; retry from next day also hits cap with same limit; last resort +1 day from bump.assert nxt == datetime(2024, 6, 3, 11, 0, tzinfo=UTC)-- def test_next_unblocked_second_cap_returns_day_after_bump(self, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(schedule_restriction_module, "_MAX_UNBLOCK_STEPS", 5)- alert = self._alert(- "UTC",- {"blocked_windows": [{"start": "10:00", "end": "12:00"}]},+ assert warning.call_count == 2+ warning.assert_any_call(+ "schedule_restriction.next_unblocked_utc_exceeded_cap",+ alert_id="test-id",+ recursion_depth=0,+ )+ error.assert_called_once_with(+ "schedule_restriction.next_unblocked_utc_giving_up_after_retry",+ alert_id="test-id",)- fro = datetime(2024, 6, 1, 11, 0, tzinfo=UTC)- nxt = schedule_restriction_module._next_unblocked_utc(alert, fro, recursion_depth=1)- assert nxt == datetime(2024, 6, 2, 11, 0, tzinfo=UTC)class TestNextCheckAtAfterScheduleRestrictionChange:- """``next_check_at_after_schedule_restriction_change`` (API PATCH path) matches worker scheduling rules."""-def _hourly_alert(self, **kwargs: Any) -> MagicMock:alert = MagicMock(spec=AlertConfiguration)alert.team = MagicMock()@@ -190,16 +72,13 @@ class TestNextCheckAtAfterScheduleRestrictionChange:setattr(alert, k, v)return alert- def _every_15_minutes_alert(self, **kwargs: Any) -> MagicMock:- alert = self._hourly_alert(**kwargs)- alert.calculation_interval = "every_15_minutes"- return alert-- def test_cleared_restriction_delegates_to_next_check_time(self) -> None:+ def test_cleared_restriction_schedules_from_now_and_restores_existing_value(self) -> None:with freeze_time("2026-04-06T14:00:00Z"):- alert = self._hourly_alert(schedule_restriction=None, next_check_at=None)+ existing = datetime(2026, 4, 7, 18, 30, tzinfo=UTC)+ alert = self._hourly_alert(schedule_restriction=None, next_check_at=existing)out = next_check_at_after_schedule_restriction_change(alert)assert out == datetime(2026, 4, 6, 15, 0, 0, tzinfo=UTC)+ assert alert.next_check_at == existingdef test_future_next_check_inside_blocked_window_snaps_to_first_unblocked_minute(self) -> None:with freeze_time("2026-04-06T14:00:00Z"):@@ -210,8 +89,7 @@ class TestNextCheckAtAfterScheduleRestrictionChange:out = next_check_at_after_schedule_restriction_change(alert)assert out == datetime(2026, 4, 6, 16, 0, 0, tzinfo=UTC)- def test_does_not_keep_stale_snap_at_quiet_end_when_earlier_runs_are_allowed(self) -> None:- """12:44 Toronto, quiet 14:00–16:00 local; stale next_check_at at 4pm must not block 1:44pm next hourly."""+ def test_does_not_keep_stale_snap_when_earlier_runs_are_allowed(self) -> None:with freeze_time("2026-04-06T16:44:00Z"):alert = self._hourly_alert(team=MagicMock(timezone="America/Toronto"),@@ -220,42 +98,3 @@ class TestNextCheckAtAfterScheduleRestrictionChange:)out = next_check_at_after_schedule_restriction_change(alert)assert out == datetime(2026, 4, 6, 17, 44, 0, tzinfo=UTC)-- def test_null_next_check_at_with_restriction_uses_interval_then_snap(self) -> None:- with freeze_time("2026-04-06T14:00:00Z"):- alert = self._hourly_alert(- schedule_restriction={"blocked_windows": [{"start": "11:00", "end": "16:00"}]},- next_check_at=None,- )- out = next_check_at_after_schedule_restriction_change(alert)- assert out == datetime(2026, 4, 6, 16, 0, 0, tzinfo=UTC)-- def test_every_15_minutes_future_next_check_inside_blocked_window_snaps_to_first_unblocked_minute(- self,- ) -> None:- with freeze_time("2026-04-06T14:00:00Z"):- alert = self._every_15_minutes_alert(- schedule_restriction={"blocked_windows": [{"start": "11:00", "end": "16:00"}]},- next_check_at=datetime(2026, 4, 6, 15, 30, tzinfo=UTC),- )- out = next_check_at_after_schedule_restriction_change(alert)- assert out == datetime(2026, 4, 6, 16, 0, 0, tzinfo=UTC)-- def test_every_15_minutes_does_not_keep_stale_snap_when_earlier_runs_are_allowed(self) -> None:- with freeze_time("2026-04-06T16:44:00Z"):- alert = self._every_15_minutes_alert(- team=MagicMock(timezone="America/Toronto"),- schedule_restriction={"blocked_windows": [{"start": "14:00", "end": "16:00"}]},- next_check_at=datetime(2026, 4, 6, 20, 0, 0, tzinfo=UTC),- )- out = next_check_at_after_schedule_restriction_change(alert)- assert out == datetime(2026, 4, 6, 16, 59, 0, tzinfo=UTC)-- def test_every_15_minutes_null_next_check_at_with_restriction_uses_interval_then_snap(self) -> None:- with freeze_time("2026-04-06T14:00:00Z"):- alert = self._every_15_minutes_alert(- schedule_restriction={"blocked_windows": [{"start": "11:00", "end": "16:00"}]},- next_check_at=None,- )- out = next_check_at_after_schedule_restriction_change(alert)- assert out == datetime(2026, 4, 6, 16, 0, 0, tzinfo=UTC)diff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.pyindex 846abab5434e..0460fe81fd2a 100644--- a/posthog/tasks/alerts/test/test_utils.py+++ b/posthog/tasks/alerts/test/test_utils.py@@ -5,11 +5,7 @@ from unittest.mock import MagicMockfrom posthog.schema import AlertCalculationInterval-from posthog.tasks.alerts.utils import (- alert_calculation_interval_to_relativedelta,- calculation_interval_to_order,- next_check_time,-)+from posthog.tasks.alerts.utils import calculation_interval_to_order, next_check_timefrom products.alerts.backend.models.alert import AlertConfiguration@@ -20,10 +16,6 @@ class TestAlertUtils:AlertCalculationInterval.EVERY_15_MINUTES)- def test_alert_calculation_interval_to_relativedelta_real_time(self) -> None:- delta = alert_calculation_interval_to_relativedelta(AlertCalculationInterval.REAL_TIME)- assert delta.minutes == 2-def test_next_check_time_advances_by_2_minutes(self) -> None:alert = MagicMock(spec=AlertConfiguration)alert.calculation_interval = AlertCalculationInterval.REAL_TIMEdiff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex 224fa0621cf4..7a293784fe3b 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -5,7 +5,6 @@ from django.utils import timezoneimport pytzimport structlog-from dateutil.relativedelta import MO, relativedeltafrom posthog.schema import AlertCalculationInterval, AlertState, ChartDisplayType, NodeKind, TrendsQuery@@ -15,6 +14,13 @@ from posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schefrom products.alerts.backend.facade.api import send_alert_emailfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, derive_detector_event_fields+from products.alerts.backend.scheduling import (+ EVERY_15_MINUTES_CADENCE_MINUTES as EVERY_15_MINUTES_CADENCE_MINUTES,+ REAL_TIME_CADENCE_MINUTES as REAL_TIME_CADENCE_MINUTES,+ is_weekend,+ next_calendar_check_time,+ to_calendar_interval,+)logger = structlog.get_logger(__name__)@@ -46,9 +52,6 @@ def is_non_time_series_trend(query: TrendsQuery) -> bool:return display in NON_TIME_SERIES_DISPLAY_TYPES-REAL_TIME_CADENCE_MINUTES = 2-EVERY_15_MINUTES_CADENCE_MINUTES = 15-# Cheaper, more time-sensitive checks get workers first when the due batch is large.# Single source for both the Python ordering and the ORM Case in# posthog/temporal/alerts/activities.py retrieve_due_alerts.@@ -71,69 +74,20 @@ def calculation_interval_to_order(interval: AlertCalculationInterval | None) ->raise ValueError(f"Unhandled alert calculation interval: {interval!r}")-def alert_calculation_interval_to_relativedelta(alert_calculation_interval: AlertCalculationInterval) -> relativedelta:- match alert_calculation_interval:- case AlertCalculationInterval.REAL_TIME:- return relativedelta(minutes=REAL_TIME_CADENCE_MINUTES)- case AlertCalculationInterval.EVERY_15_MINUTES:- return relativedelta(minutes=EVERY_15_MINUTES_CADENCE_MINUTES)- case AlertCalculationInterval.HOURLY:- return relativedelta(hours=1)- case AlertCalculationInterval.DAILY:- return relativedelta(days=1)- case AlertCalculationInterval.WEEKLY:- return relativedelta(weeks=1)- case AlertCalculationInterval.MONTHLY:- return relativedelta(months=1)- case _ as unreachable:- raise ValueError(f"Unhandled alert calculation interval: {unreachable!r}")--def skip_because_of_weekend(alert: AlertConfiguration) -> bool:if not alert.skip_weekend:return False-- now = datetime.now(pytz.UTC)- team_timezone = pytz.timezone(alert.team.timezone)-- now_local = now.astimezone(team_timezone)- return now_local.isoweekday() in [6, 7]+ return is_weekend(datetime.now(pytz.UTC), alert.team.timezone)def _next_check_time_core(alert: AlertConfiguration) -> datetime:"""Nominal next check instant before schedule_restriction snapping."""- now = datetime.now(pytz.UTC)- team_timezone = pytz.timezone(alert.team.timezone)-- match alert.calculation_interval:- case AlertCalculationInterval.REAL_TIME:- return (alert.next_check_at or now) + relativedelta(minutes=REAL_TIME_CADENCE_MINUTES)- case AlertCalculationInterval.EVERY_15_MINUTES:- return (alert.next_check_at or now) + relativedelta(minutes=15)- case AlertCalculationInterval.HOURLY:- return (alert.next_check_at or now) + relativedelta(hours=1)- case AlertCalculationInterval.DAILY:- # Get the next date in the specified timezone- tomorrow_local = datetime.now(team_timezone) + relativedelta(days=1)- # set hour to 1 AM- # only replacing hour and not minute/second... to distribute execution of all daily alerts- one_am_local = tomorrow_local.replace(hour=1)- # Convert to UTC- return one_am_local.astimezone(pytz.utc)- case AlertCalculationInterval.WEEKLY:- next_monday_local = datetime.now(team_timezone) + relativedelta(days=1, weekday=MO(1))- # Set the hour to around 3 AM on next Monday- next_monday_1am_local = next_monday_local.replace(hour=3)- # Convert to UTC- return next_monday_1am_local.astimezone(pytz.utc)- case AlertCalculationInterval.MONTHLY:- next_month_local = datetime.now(team_timezone) + relativedelta(months=1)- # Set hour to 4 AM on first day of next month- next_month_1am_local = next_month_local.replace(day=1, hour=4)- # Convert to UTC- return next_month_1am_local.astimezone(pytz.utc)- case _ as unreachable:- raise ValueError(f"Unhandled alert calculation interval: {unreachable!r}")+ return next_calendar_check_time(+ to_calendar_interval(alert.calculation_interval),+ now=datetime.now(pytz.UTC),+ tz_name=alert.team.timezone,+ next_check_at=alert.next_check_at,+ )def next_check_time(alert: AlertConfiguration) -> datetime:diff --git a/products/alerts/backend/scheduling.py b/products/alerts/backend/scheduling.pynew file mode 100644index 000000000000..1e361d3f9843--- /dev/null+++ b/products/alerts/backend/scheduling.py@@ -0,0 +1,441 @@+"""Scheduling math for alert checks.++Sub-daily checks preserve their existing cadence. Daily, weekly, and monthly+checks anchor to calendar instants in the team's local timezone. Quiet hours+and weekend skipping layer local-time restrictions on top of those schedules.++Pure Python with no Django or model imports. Timezones are passed as IANA+names, quiet-hours windows as parsed tuples.+"""++from __future__ import annotations++from collections.abc import Callable+from datetime import UTC, date, datetime, timedelta+from enum import StrEnum+from typing import Any, cast+from uuid import UUID++import pytz+from dateutil.relativedelta import relativedelta+from pytz.exceptions import AmbiguousTimeError, NonExistentTimeError+from pytz.tzinfo import BaseTzInfo++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. 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+ across cron fires. Existing drifted alerts heal lazily on their next run.+ """+ 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++ 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(timestamp: datetime, cadence_minutes: int) -> datetime:+ total_minutes = timestamp.hour * 60 + timestamp.minute+ floored_minutes = (total_minutes // cadence_minutes) * cadence_minutes+ return timestamp.replace(+ hour=floored_minutes // 60,+ minute=floored_minutes % 60,+ second=0,+ microsecond=0,+ )+++class CalendarInterval(StrEnum):+ """Mirrors posthog.schema.AlertCalculationInterval values; wrappers convert."""++ REAL_TIME = "real_time"+ EVERY_15_MINUTES = "every_15_minutes"+ HOURLY = "hourly"+ DAILY = "daily"+ WEEKLY = "weekly"+ MONTHLY = "monthly"+++REAL_TIME_CADENCE_MINUTES = 2+EVERY_15_MINUTES_CADENCE_MINUTES = 15+++def to_calendar_interval(value: str | None) -> CalendarInterval:+ if value is None:+ raise ValueError("Unhandled alert calculation interval: None")+ try:+ return CalendarInterval(value)+ except ValueError:+ raise ValueError(f"Unhandled alert calculation interval: {value!r}") from None+++def is_weekend(now: datetime, tz_name: str) -> bool:+ team_timezone = pytz.timezone(tz_name)+ now_local = now.astimezone(team_timezone)+ return now_local.isoweekday() in [6, 7]+++def _localize_wall_time(team_timezone: BaseTzInfo, naive_local: datetime) -> datetime:+ localize = cast(Callable[[datetime, bool | None], datetime], team_timezone.localize)+ try:+ return localize(naive_local, None)+ except AmbiguousTimeError:+ return localize(naive_local, True)+ except NonExistentTimeError:+ return team_timezone.normalize(localize(naive_local, False))+++def _calendar_anchor_utc(+ local_now: datetime,+ team_timezone: BaseTzInfo,+ *,+ target_date: date,+ hour: int,+) -> datetime:+ naive_local = datetime.combine(target_date, local_now.timetz().replace(tzinfo=None)).replace(hour=hour)+ return _localize_wall_time(team_timezone, naive_local).astimezone(UTC)+++def next_calendar_check_time(+ interval: CalendarInterval,+ *,+ now: datetime,+ tz_name: str,+ next_check_at: datetime | None,+) -> datetime:+ """Nominal next check instant, before quiet-hours snapping.++ Sub-daily intervals advance from the previous next_check_at (falling back to+ now) so per-alert spread from creation time is preserved. Daily/weekly/monthly+ anchor to fixed local instants: 1am tomorrow, 3am next Monday, 4am on the 1st+ of next month. Hour-only replacement keeps the minute/second spread.+ """+ team_timezone = pytz.timezone(tz_name)+ local_now = now.astimezone(team_timezone)++ match interval:+ case CalendarInterval.REAL_TIME:+ return (next_check_at or now) + relativedelta(minutes=REAL_TIME_CADENCE_MINUTES)+ case CalendarInterval.EVERY_15_MINUTES:+ return (next_check_at or now) + relativedelta(minutes=EVERY_15_MINUTES_CADENCE_MINUTES)+ case CalendarInterval.HOURLY:+ return (next_check_at or now) + relativedelta(hours=1)+ case CalendarInterval.DAILY:+ return _calendar_anchor_utc(+ local_now,+ team_timezone,+ target_date=local_now.date() + timedelta(days=1),+ hour=1,+ )+ case CalendarInterval.WEEKLY:+ return _calendar_anchor_utc(+ local_now,+ team_timezone,+ target_date=local_now.date() + timedelta(days=7 - local_now.weekday()),+ hour=3,+ )+ case CalendarInterval.MONTHLY:+ if local_now.month == 12:+ target_date = date(local_now.year + 1, 1, 1)+ else:+ target_date = date(local_now.year, local_now.month + 1, 1)+ return _calendar_anchor_utc(local_now, team_timezone, target_date=target_date, hour=4)+ case _ as unreachable:+ raise ValueError(f"Unhandled alert calculation interval: {unreachable!r}")+++# --- Quiet hours (blocked local time windows) ---++MAX_BLOCKED_WINDOWS = 5+MINUTES_PER_DAY = 1440+# Minimum length of each declared blocked window on the local daily timeline (half-open; same rules as expand).+MIN_BLOCKED_WINDOW_MINUTES = 30+# When quiet hours hit an unusual corner case, computing the next allowed send time must not+# run indefinitely or hold up other alerts; we cap how long we spend on that lookup.+MAX_UNBLOCK_STEPS = MINUTES_PER_DAY * 14++# (start_minute, end_minute, overnight)+BlockedWindow = tuple[int, int, bool]+++def _hhmm(minutes: int) -> str:+ return f"{minutes // 60:02d}:{minutes % 60:02d}"+++def normalize_schedule_restriction_value(raw: Any) -> dict[str, Any] | None:+ """Coerce payloads that mean 'off' to None. Returns dict ready to validate or None."""+ if raw is None:+ return None+ if raw == {}:+ return None+ if not isinstance(raw, dict):+ raise ValueError("schedule_restriction must be an object or null")+ windows = raw.get("blocked_windows")+ if windows is None:+ return None+ if windows == []:+ return None+ if not isinstance(windows, list):+ raise ValueError("blocked_windows must be an array")+ return raw+++def _parse_hhmm(value: str) -> int:+ if not isinstance(value, str):+ raise ValueError("Time must be a string HH:MM")+ s = value.strip()+ if s.count(":") != 1:+ raise ValueError("Time must be HH:MM (seconds not allowed)")+ parts = s.split(":")+ try:+ h = int(parts[0], 10)+ m = int(parts[1], 10)+ except ValueError as e:+ raise ValueError("Invalid HH:MM") from e+ if h < 0 or h > 23 or m < 0 or m > 59:+ raise ValueError("Invalid HH:MM")+ return h * 60 + m+++def _parse_window_pair(start_s: str, end_s: str) -> BlockedWindow:+ start = _parse_hhmm(start_s)+ end = _parse_hhmm(end_s)+ if start == end:+ raise ValueError("Start and end must differ for a blocked window")+ overnight = start > end+ return start, end, overnight+++def _blocked_window_span_minutes(start: int, end: int, overnight: bool) -> int:+ """Total minutes blocked in one local 24h cycle for this window (matches _expand_windows_for_coverage)."""+ if not overnight:+ return end - start+ if end == 0:+ return MINUTES_PER_DAY - start+ return (MINUTES_PER_DAY - start) + end+++def _expand_windows_for_coverage(windows: list[BlockedWindow]) -> list[tuple[int, int]]:+ """Half-open intervals within [0, MINUTES_PER_DAY) for one synthetic day."""+ out: list[tuple[int, int]] = []+ for start, end, overnight in windows:+ if not overnight:+ if start < end:+ out.append((start, end))+ else:+ raise ValueError("Invalid window")+ else:+ if end == 0:+ # e.g. 19:00–00:00 = block from 19:00 through end of local calendar day (end exclusive at midnight)+ out.append((start, MINUTES_PER_DAY))+ else:+ out.append((start, MINUTES_PER_DAY))+ out.append((0, end))+ return out+++def _merge_intervals_sorted(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:+ if not intervals:+ return []+ intervals = sorted(intervals, key=lambda x: (x[0], x[1]))+ merged: list[tuple[int, int]] = []+ for a, b in intervals:+ if b <= a:+ continue+ if not merged or merged[-1][1] < a:+ merged.append((a, b))+ else:+ prev_a, prev_b = merged[-1]+ merged[-1] = (prev_a, max(prev_b, b))+ return merged+++def merged_intervals_cover_full_day(merged: list[tuple[int, int]]) -> bool:+ return bool(merged) and merged[0][0] == 0 and merged[0][1] >= MINUTES_PER_DAY+++def _encode_merged_to_blocked_windows(merged: list[tuple[int, int]]) -> list[dict[str, str]]:+ """Round-trip merged [0,1440) half-open segments to stored window dicts."""+ if not merged:+ return []+ if len(merged) == 1:+ a, b = merged[0]+ if a < b:+ if b == MINUTES_PER_DAY and a > 0:+ return [{"start": _hhmm(a), "end": "00:00"}]+ return [{"start": _hhmm(a), "end": _hhmm(b)}]+ raise ValueError("Invalid merged interval")+ if len(merged) == 2:+ a1, b1 = merged[0]+ a2, b2 = merged[1]+ # Overnight split into [0, morning_end) and [evening_start, 1440) after sorting by start+ if a1 == 0 and b2 == MINUTES_PER_DAY and a2 > b1:+ return [{"start": _hhmm(a2), "end": _hhmm(b1)}]+ out: list[dict[str, str]] = []+ for a, b in merged:+ if not a < b:+ continue+ if b == MINUTES_PER_DAY and a > 0:+ out.append({"start": _hhmm(a), "end": "00:00"})+ else:+ out.append({"start": _hhmm(a), "end": _hhmm(b)})+ return out+++def validate_and_normalize_schedule_restriction(raw: Any) -> dict[str, Any] | None:+ """+ Validate API/store shape; merge overlaps on the daily timeline; return normalized dict or None.+ Raises ValueError on invalid input.+ """+ normalized_in = normalize_schedule_restriction_value(raw)+ if normalized_in is None:+ return None++ windows_in = normalized_in.get("blocked_windows")+ if not isinstance(windows_in, list):+ raise ValueError("blocked_windows must be an array")+ if len(windows_in) > MAX_BLOCKED_WINDOWS:+ raise ValueError(f"At most {MAX_BLOCKED_WINDOWS} blocked time windows are allowed")++ parsed: list[BlockedWindow] = []+ for idx, w in enumerate(windows_in):+ if not isinstance(w, dict):+ raise ValueError(f"blocked_windows[{idx}] must be an object")+ start_s = w.get("start")+ end_s = w.get("end")+ if start_s is None or end_s is None:+ raise ValueError(f"blocked_windows[{idx}] must have start and end (HH:MM)")+ start_i, end_i, overnight = _parse_window_pair(str(start_s), str(end_s))+ span = _blocked_window_span_minutes(start_i, end_i, overnight)+ if span < MIN_BLOCKED_WINDOW_MINUTES:+ raise ValueError(+ f"blocked_windows[{idx}] must span at least {MIN_BLOCKED_WINDOW_MINUTES} minutes "+ f"(half-open local window [start, end))"+ )+ parsed.append((start_i, end_i, overnight))++ expanded = _expand_windows_for_coverage(parsed)+ merged = _merge_intervals_sorted(expanded)+ if merged_intervals_cover_full_day(merged):+ raise ValueError("Leave at least one time in the day when this alert can run")++ encoded = _encode_merged_to_blocked_windows(merged)+ if not encoded:+ return None+ return {"blocked_windows": encoded}+++def parse_blocked_windows_tuples(schedule_restriction: dict[str, Any] | None) -> list[BlockedWindow] | None:+ if not schedule_restriction:+ return None+ windows = schedule_restriction.get("blocked_windows")+ if not windows:+ return None+ out: list[BlockedWindow] = []+ for w in windows:+ if isinstance(w, dict) and "start" in w and "end" in w:+ out.append(_parse_window_pair(str(w["start"]), str(w["end"])))+ return out or None+++def is_local_minute_blocked(minute: int, windows: list[BlockedWindow]) -> bool:+ for start, end, overnight in windows:+ if not overnight:+ if start <= minute < end:+ return True+ else:+ if end == 0:+ if minute >= start:+ return True+ elif minute >= start or minute < end:+ return True+ return False+++def _minute_of_local_datetime(dt_local: datetime) -> int:+ return dt_local.hour * 60 + dt_local.minute+++def is_utc_datetime_blocked(dt_utc: datetime, tz_name: str, windows: list[BlockedWindow] | None) -> bool:+ if not windows:+ return False+ tz = pytz.timezone(tz_name)+ local = dt_utc.astimezone(tz).replace(second=0, microsecond=0)+ return is_local_minute_blocked(_minute_of_local_datetime(local), windows)+++def scan_next_unblocked_utc(+ from_utc: datetime,+ tz_name: str,+ windows: list[BlockedWindow] | None,+ *,+ max_steps: int = MAX_UNBLOCK_STEPS,+) -> datetime | None:+ """Smallest UTC instant >= from_utc (minute precision) outside every blocked window.++ Returns None when no unblocked minute is found within max_steps. Callers own+ the fallback (insight alerts bump a day and retry, with logging).+ """+ if not windows:+ return from_utc.astimezone(UTC).replace(microsecond=0)++ tz = pytz.timezone(tz_name)+ cur = from_utc.astimezone(UTC).replace(second=0, microsecond=0)+ steps = 0+ while steps < max_steps:+ m = _minute_of_local_datetime(cur.astimezone(tz))+ if not is_local_minute_blocked(m, windows):+ return cur+ cur = cur + timedelta(minutes=1)+ steps += 1+ return Nonediff --git a/products/logs/backend/test/test_alert_utils.py b/products/alerts/backend/test/test_grid_scheduling.pysimilarity index 98%rename from products/logs/backend/test/test_alert_utils.pyrename to products/alerts/backend/test/test_grid_scheduling.pyindex 15fe6e5cb2fc..cff7abf75ea0 100644--- a/products/logs/backend/test/test_alert_utils.py+++ b/products/alerts/backend/test/test_grid_scheduling.py@@ -12,8 +12,8 @@ from hypothesis import ()from parameterized import parameterized-from products.logs.backend.alert_utils import (- SCHEDULE_INTERVAL_SECONDS,+from products.alerts.backend.scheduling import (+ DEFAULT_SCHEDULE_INTERVAL_SECONDS,advance_next_check_at,compute_shard_offset_seconds,)@@ -336,10 +336,10 @@ class TestComputeShardOffsetSeconds(TestCase):@parameterized.expand([(c,) for c in (1, 5, 10, 15, 30, 60)])def test_offset_is_minute_aligned_and_within_cadence(self, cadence: int) -> None:- # Offset must be a multiple of SCHEDULE_INTERVAL_SECONDS and < cadence.+ # Offset must be a schedule-sized slot within the cadence.alert_id = UUID("019dec00-0000-0000-0000-000000000042")offset = compute_shard_offset_seconds(alert_id, cadence)- assert offset % SCHEDULE_INTERVAL_SECONDS == 0+ assert offset % DEFAULT_SCHEDULE_INTERVAL_SECONDS == 0assert 0 <= offset < cadence * 60def test_distribution_across_many_alerts_is_roughly_uniform(self) -> None:@@ -432,8 +432,8 @@ class TestAdvanceNextCheckAtWithShard(TestCase):def test_steady_state_gap_equals_cadence_with_shard(self, cadence: int, shard_index: int) -> None:# Same property as the non-sharded test: inter-eval gaps stay exactly# `cadence` minutes once on grid, regardless of shard offset.- shard_count = max(1, (cadence * 60) // SCHEDULE_INTERVAL_SECONDS)- offset = (shard_index % shard_count) * SCHEDULE_INTERVAL_SECONDS+ shard_count = max(1, (cadence * 60) // DEFAULT_SCHEDULE_INTERVAL_SECONDS)+ offset = (shard_index % shard_count) * DEFAULT_SCHEDULE_INTERVAL_SECONDSanchor = datetime(2026, 3, 19, 12, 0, tzinfo=UTC)# Heal once to land on shard grid.diff --git a/products/alerts/backend/test/test_scheduling.py b/products/alerts/backend/test/test_scheduling.pynew file mode 100644index 000000000000..d4ebfc89b1cd--- /dev/null+++ b/products/alerts/backend/test/test_scheduling.py@@ -0,0 +1,255 @@+from datetime import UTC, datetime+from typing import Any++import pytest++from parameterized import parameterized++from products.alerts.backend.scheduling import (+ BlockedWindow,+ CalendarInterval,+ is_weekend,+ next_calendar_check_time,+ parse_blocked_windows_tuples,+ scan_next_unblocked_utc,+ validate_and_normalize_schedule_restriction,+)++# Wednesday 2026-03-18 12:00 UTC+NOW = datetime(2026, 3, 18, 12, 0, tzinfo=UTC)+PREV_CHECK = datetime(2026, 3, 18, 11, 47, tzinfo=UTC)+++class TestValidateAndNormalizeScheduleRestriction:+ @parameterized.expand(+ [+ (None, None),+ ({}, None),+ ({"blocked_windows": []}, None),+ (+ {"blocked_windows": [{"start": "22:00", "end": "07:00"}]},+ {"blocked_windows": [{"start": "22:00", "end": "07:00"}]},+ ),+ ]+ )+ def test_normalize_feature_off_or_valid_overnight(self, raw: Any, expected: dict[str, Any] | None) -> None:+ assert validate_and_normalize_schedule_restriction(raw) == expected++ def test_merges_overlapping_same_day_windows(self) -> None:+ raw = {+ "blocked_windows": [+ {"start": "10:30", "end": "11:00"},+ {"start": "10:40", "end": "11:15"},+ ]+ }+ assert validate_and_normalize_schedule_restriction(raw) == {+ "blocked_windows": [{"start": "10:30", "end": "11:15"}]+ }++ def test_adjacent_half_open_windows_merge(self) -> None:+ raw = {+ "blocked_windows": [+ {"start": "12:00", "end": "13:00"},+ {"start": "13:00", "end": "14:00"},+ ]+ }+ assert validate_and_normalize_schedule_restriction(raw) == {+ "blocked_windows": [{"start": "12:00", "end": "14:00"}]+ }++ def test_rejects_full_day_coverage(self) -> None:+ raw = {+ "blocked_windows": [+ {"start": "00:00", "end": "12:00"},+ {"start": "12:00", "end": "00:00"},+ ]+ }+ with pytest.raises(ValueError, match="at least one time"):+ validate_and_normalize_schedule_restriction(raw)++ def test_rejects_too_many_windows_before_merge(self) -> None:+ raw = {"blocked_windows": [{"start": f"{i:02d}:00", "end": f"{i:02d}:30"} for i in range(6)]}+ with pytest.raises(ValueError, match="At most 5"):+ validate_and_normalize_schedule_restriction(raw)++ @parameterized.expand(+ [+ ("12:00:00",),+ ("not_a_time",),+ ]+ )+ def test_rejects_malformed_times(self, bad_time: str) -> None:+ raw = {"blocked_windows": [{"start": bad_time, "end": "13:00"}]}+ with pytest.raises(ValueError):+ validate_and_normalize_schedule_restriction(raw)++ def test_rejects_equal_start_and_end(self) -> None:+ raw = {"blocked_windows": [{"start": "10:00", "end": "10:00"}]}+ with pytest.raises(ValueError, match="differ"):+ validate_and_normalize_schedule_restriction(raw)++ @parameterized.expand(+ [+ ("same_day_too_short", "10:00", "10:29", False),+ ("same_day_minimum", "10:00", "10:30", True),+ ("overnight_too_short", "23:50", "00:09", False),+ ("overnight_minimum", "23:40", "00:10", True),+ ]+ )+ def test_enforces_minimum_window_length(self, _name: str, start: str, end: str, is_valid: bool) -> None:+ raw = {"blocked_windows": [{"start": start, "end": end}]}+ if is_valid:+ assert validate_and_normalize_schedule_restriction(raw) == raw+ else:+ with pytest.raises(ValueError, match="at least 30 minutes"):+ validate_and_normalize_schedule_restriction(raw)++ def test_evening_until_midnight_preserves_end_at_midnight(self) -> None:+ raw = {"blocked_windows": [{"start": "19:00", "end": "00:00"}]}+ assert validate_and_normalize_schedule_restriction(raw) == raw+++class TestNextCalendarCheckTime:+ @parameterized.expand(+ [+ # Sub-daily intervals advance from the prior next_check_at, preserving per-alert spread+ ("real_time_from_prev", CalendarInterval.REAL_TIME, PREV_CHECK, datetime(2026, 3, 18, 11, 49, tzinfo=UTC)),+ ("real_time_first_check", CalendarInterval.REAL_TIME, None, datetime(2026, 3, 18, 12, 2, tzinfo=UTC)),+ (+ "15min_from_prev",+ CalendarInterval.EVERY_15_MINUTES,+ PREV_CHECK,+ datetime(2026, 3, 18, 12, 2, tzinfo=UTC),+ ),+ ("hourly_from_prev", CalendarInterval.HOURLY, PREV_CHECK, datetime(2026, 3, 18, 12, 47, tzinfo=UTC)),+ ]+ )+ def test_sub_daily_advances_from_previous(+ self, _name: str, interval: CalendarInterval, next_check_at: datetime | None, expected: datetime+ ) -> None:+ result = next_calendar_check_time(interval, now=NOW, tz_name="UTC", next_check_at=next_check_at)+ assert result == expected++ @parameterized.expand(+ [+ # Daily anchors to ~1am local tomorrow; minute preserved for spread. US/Pacific is UTC-7 on this date.+ ("daily_pacific", CalendarInterval.DAILY, "US/Pacific", (2026, 3, 19, 8, 0)),+ # Weekly anchors to ~3am next Monday local (Mon 2026-03-23), 3am PDT = 10:00 UTC+ ("weekly_pacific", CalendarInterval.WEEKLY, "US/Pacific", (2026, 3, 23, 10, 0)),+ # Monthly anchors to ~4am on the 1st of next month, 4am PDT = 11:00 UTC+ ("monthly_pacific", CalendarInterval.MONTHLY, "US/Pacific", (2026, 4, 1, 11, 0)),+ ]+ )+ def test_calendar_anchors_in_team_timezone(+ self, _name: str, interval: CalendarInterval, tz_name: str, expected_utc: tuple+ ) -> None:+ result = next_calendar_check_time(interval, now=NOW, tz_name=tz_name, next_check_at=PREV_CHECK)+ assert (result.year, result.month, result.day, result.hour, result.minute) == expected_utc+ assert result.tzinfo is not None++ def test_daily_across_dst_spring_forward(self) -> None:+ # US spring-forward was 2026-03-08: local 1am tomorrow maps PST(-8) -> PDT(-7),+ # so the UTC anchor shifts from 09:00 to 08:00 across the transition.+ before = next_calendar_check_time(+ CalendarInterval.DAILY,+ now=datetime(2026, 3, 7, 12, 0, tzinfo=UTC),+ tz_name="US/Pacific",+ next_check_at=None,+ )+ after = next_calendar_check_time(+ CalendarInterval.DAILY,+ now=datetime(2026, 3, 8, 12, 0, tzinfo=UTC),+ tz_name="US/Pacific",+ next_check_at=None,+ )+ assert before.hour == 9+ assert after.hour == 8++ @parameterized.expand(+ [+ (+ "weekly_spring_forward",+ CalendarInterval.WEEKLY,+ datetime(2026, 3, 6, 12, 0, tzinfo=UTC),+ datetime(2026, 3, 9, 7, 0, tzinfo=UTC),+ ),+ (+ "monthly_fall_back",+ CalendarInterval.MONTHLY,+ datetime(2026, 10, 31, 12, 0, tzinfo=UTC),+ datetime(2026, 11, 1, 9, 0, tzinfo=UTC),+ ),+ ]+ )+ def test_calendar_anchors_keep_local_wall_time_across_dst(+ self, _name: str, interval: CalendarInterval, now: datetime, expected: datetime+ ) -> None:+ assert next_calendar_check_time(interval, now=now, tz_name="America/New_York", next_check_at=None) == expected+++class TestIsWeekend:+ @parameterized.expand(+ [+ # Friday 23:00 UTC is already Saturday 08:00 in Tokyo+ ("tokyo_saturday", datetime(2026, 3, 20, 23, 0, tzinfo=UTC), "Asia/Tokyo", True),+ ("utc_friday", datetime(2026, 3, 20, 23, 0, tzinfo=UTC), "UTC", False),+ # Sunday 05:00 UTC is still Saturday 22:00 in Pacific+ ("pacific_saturday", datetime(2026, 3, 22, 5, 0, tzinfo=UTC), "US/Pacific", True),+ ]+ )+ def test_weekend_is_local(self, _name: str, now: datetime, tz_name: str, expected: bool) -> None:+ assert is_weekend(now, tz_name) == expected+++class TestScanNextUnblockedUtc:+ def _windows(self, *pairs: tuple[str, str]) -> list[BlockedWindow] | None:+ raw = {"blocked_windows": [{"start": s, "end": e} for s, e in pairs]}+ return parse_blocked_windows_tuples(validate_and_normalize_schedule_restriction(raw))++ @parameterized.expand(+ [+ # Candidate inside a same-day window snaps to the window end (half-open)+ ("inside_window", ("09:00", "17:00"), datetime(2026, 3, 18, 12, 30, tzinfo=UTC), "UTC", (17, 0)),+ # Candidate outside any window is returned unchanged (minute precision)+ ("outside_window", ("09:00", "17:00"), datetime(2026, 3, 18, 18, 15, tzinfo=UTC), "UTC", (18, 15)),+ # Overnight window (22:00-06:00): a 23:00 candidate snaps to 06:00 next day+ ("overnight_window", ("22:00", "06:00"), datetime(2026, 3, 18, 23, 0, tzinfo=UTC), "UTC", (6, 0)),+ ]+ )+ def test_snapping(+ self, _name: str, window: tuple[str, str], candidate: datetime, tz_name: str, expected_hm: tuple+ ) -> None:+ result = scan_next_unblocked_utc(candidate, tz_name, self._windows(window))+ assert result is not None+ assert (result.hour, result.minute) == expected_hm++ def test_window_is_evaluated_in_local_time(self) -> None:+ # Blocked 09:00-17:00 in Pacific (PDT, UTC-7). 12:00 UTC = 05:00 local -> not blocked.+ windows = self._windows(("09:00", "17:00"))+ result = scan_next_unblocked_utc(datetime(2026, 3, 18, 12, 0, tzinfo=UTC), "US/Pacific", windows)+ assert result == datetime(2026, 3, 18, 12, 0, tzinfo=UTC)+ # 18:00 UTC = 11:00 local -> blocked until 17:00 local = 00:00 UTC next day.+ result = scan_next_unblocked_utc(datetime(2026, 3, 18, 18, 0, tzinfo=UTC), "US/Pacific", windows)+ assert result is not None+ assert result == datetime(2026, 3, 19, 0, 0, tzinfo=UTC)++ @parameterized.expand(+ [+ (+ "spring_forward",+ ("01:30", "03:30"),+ datetime(2026, 3, 8, 6, 30, tzinfo=UTC),+ datetime(2026, 3, 8, 7, 30, tzinfo=UTC),+ ),+ (+ "fall_back",+ ("00:30", "02:00"),+ datetime(2026, 11, 1, 5, 0, tzinfo=UTC),+ datetime(2026, 11, 1, 7, 0, tzinfo=UTC),+ ),+ ]+ )+ def test_scan_respects_dst_offset_changes(+ self, _name: str, window: tuple[str, str], candidate: datetime, expected: datetime+ ) -> None:+ assert scan_next_unblocked_utc(candidate, "America/New_York", self._windows(window)) == expecteddiff --git a/products/logs/backend/alert_utils.py b/products/logs/backend/alert_utils.pyindex 4f5f54d1a4cf..dda290f90663 100644--- a/products/logs/backend/alert_utils.py+++ b/products/logs/backend/alert_utils.py@@ -6,7 +6,7 @@ from uuid import UUIDfrom django.db.models import Q-from common.alerting.scheduling import (+from products.alerts.backend.scheduling import (advance_next_check_at,compute_shard_offset_seconds as shared_compute_shard_offset_seconds,)