: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
fix(data-modeling): anchor monthly tiers to the 30-day source grid (#82585)
Jovan Sakovicd920a9de0632
diff --git a/products/data_modeling/backend/management/commands/set_schedule_anchor.py b/products/data_modeling/backend/management/commands/set_schedule_anchor.pyindex 2a4efbdc1c29..6a16f5870c5d 100644--- a/products/data_modeling/backend/management/commands/set_schedule_anchor.py+++ b/products/data_modeling/backend/management/commands/set_schedule_anchor.py@@ -52,7 +52,7 @@ class Command(BaseCommand):"--at",type=str,default=None,- help="UTC time to anchor to, HH:MM (e.g. 00:00). Monthly-cadence nodes keep their hash-picked day of month",+ help="UTC time to anchor to, HH:MM (e.g. 00:00). Monthly-cadence nodes run every 30 days at this time, on the same 30-day grid their sources sync on",)parser.add_argument("--on",diff --git a/products/data_modeling/backend/schedule.py b/products/data_modeling/backend/schedule.pyindex f0542d6f877b..47f490398911 100644--- a/products/data_modeling/backend/schedule.py+++ b/products/data_modeling/backend/schedule.py@@ -17,7 +17,13 @@ from collections.abc import Collectionfrom datetime import timedeltafrom asgiref.sync import async_to_sync-from temporalio.client import ScheduleCalendarSpec, ScheduleListActionStartWorkflow, ScheduleRange, ScheduleSpec+from temporalio.client import (+ ScheduleCalendarSpec,+ ScheduleIntervalSpec,+ ScheduleListActionStartWorkflow,+ ScheduleRange,+ ScheduleSpec,+)from temporalio.common import SearchAttributePair, TypedSearchAttributesfrom posthog.temporal.common.client import async_connect@@ -256,13 +262,16 @@ def _monthly_spec(entity_id: uuid.UUID, timezone: str) -> ScheduleSpec:)-def _anchored_spec(entity_id: uuid.UUID, interval: timedelta, anchor_minutes: int) -> ScheduleSpec:+def _anchored_spec(interval: timedelta, anchor_minutes: int) -> ScheduleSpec:"""Pinned-phase spec: fires at times t ≡ anchor (mod interval), t counted from Monday 00:00 UTC.Always UTC (a fixed instant that does not shift with DST) and 1min jitter — an operatorpinning 00:00 means 00:00, not the hash paths' up-to-1hr spread. Every sub-weekly bucketdivides the day, so only the time-of-day part of the anchor matters there; weekly reads the- full value for its day. Monthly keeps its hash-picked day-of-month with the time pinned.+ full value for its day. Monthly reads only the time of day too, and fires on the 30-day+ epoch grid rather than a day of the month.++ Nothing here depends on the entity: an anchored cohort shares one phase by definition."""time_of_day = anchor_minutes % (24 * 60)anchor_hour, anchor_min = divmod(time_of_day, 60)@@ -296,12 +305,15 @@ def _anchored_spec(entity_id: uuid.UUID, interval: timedelta, anchor_minutes: inminute=[ScheduleRange(start=anchor_min, end=anchor_min)],)else:- day_of_month = (_deterministic_int(entity_id, "day") % 28) + 1- calendar = ScheduleCalendarSpec(- comment=f"Anchored: monthly (hash-picked day {day_of_month}) at {anchor_hour:02d}:{anchor_min:02d}",- day_of_month=[ScheduleRange(start=day_of_month, end=day_of_month)],- hour=[ScheduleRange(start=anchor_hour, end=anchor_hour)],- minute=[ScheduleRange(start=anchor_min, end=anchor_min)],+ # Calendar months are 28-31 days, so no day_of_month holds a 30-day cycle. Warehouse+ # sources run epoch-anchored interval schedules whose offset is a time of day, so a+ # 30-day source always syncs on a day where days_since_epoch % 30 == 0. Sharing that+ # grid is what lets an anchored model read the sync it was meant to read; a calendar+ # day drifts against the grid and leaves the model a whole cycle in arrears.+ return ScheduleSpec(+ intervals=[ScheduleIntervalSpec(every=interval, offset=timedelta(minutes=time_of_day))],+ jitter=timedelta(minutes=1),+ time_zone_name="UTC",)return ScheduleSpec(calendars=[calendar], jitter=timedelta(minutes=1), time_zone_name="UTC")@@ -326,7 +338,7 @@ def build_schedule_spec(A ScheduleSpec ready to be used with Temporal's Schedule API."""if anchor_minutes is not None:- return _anchored_spec(entity_id, interval, anchor_minutes)+ return _anchored_spec(interval, anchor_minutes)total_hours = interval.total_seconds() / 3600diff --git a/products/data_modeling/backend/test/test_schedule.py b/products/data_modeling/backend/test/test_schedule.pyindex 5ce52a89d553..32bf55190847 100644--- a/products/data_modeling/backend/test/test_schedule.py+++ b/products/data_modeling/backend/test/test_schedule.py@@ -1,6 +1,6 @@import uuidfrom collections import Counter-from datetime import timedelta+from datetime import UTC, datetime, timedeltaimport pytestfrom posthog.test.base import BaseTest@@ -490,6 +490,9 @@ class TestGetV2ScheduledDagIds:connect.assert_not_called()+EPOCH = datetime(1970, 1, 1, tzinfo=UTC)++class TestAnchoredSpec:# anchored specs fire at t ≡ anchor (mod interval), t in minutes from Monday 00:00 UTC@pytest.mark.parametrize(@@ -529,16 +532,22 @@ class TestAnchoredSpec:assert [(r.start, r.end) for r in calendar.hour] == [(2, 2)]assert [(r.start, r.end) for r in calendar.minute] == [(0, 0)]- def test_monthly_anchor_pins_time_but_keeps_hashed_day(self):- entity_id = uuid.uuid4()- spec = build_schedule_spec(entity_id, timedelta(days=30), anchor_minutes=150)- calendar = spec.calendars[0]- assert [(r.start, r.end) for r in calendar.hour] == [(2, 2)]- assert [(r.start, r.end) for r in calendar.minute] == [(30, 30)]- day = calendar.day_of_month[0].start- assert 1 <= day <= 28- again = build_schedule_spec(entity_id, timedelta(days=30), anchor_minutes=150)- assert again.calendars[0].day_of_month == calendar.day_of_month+ def test_monthly_anchor_fires_on_the_source_30_day_grid(self):+ # a 30-day warehouse source syncs on days where days_since_epoch % 30 == 0, so an+ # anchored monthly tier has to land on that grid to read the sync it was pinned for+ spec = build_schedule_spec(uuid.uuid4(), timedelta(days=30), anchor_minutes=150)+ every, offset = spec.intervals[0].every, spec.intervals[0].offset+ assert every == timedelta(days=30)+ assert offset is not None # a missing offset would drop the pin back to grid midnight+ fires = [EPOCH + offset + n * every for n in range(6)]+ assert {(fire - EPOCH).days % 30 for fire in fires} == {0}+ assert {(fire.hour, fire.minute) for fire in fires} == {(2, 30)}++ def test_monthly_ignores_the_anchors_day_component(self):+ # a 30-day cycle has no fixed weekday, so Tuesday 02:30 can only mean 02:30+ tuesday = build_schedule_spec(uuid.uuid4(), timedelta(days=30), anchor_minutes=1590)+ time_only = build_schedule_spec(uuid.uuid4(), timedelta(days=30), anchor_minutes=150)+ assert tuesday.intervals == time_only.intervals@pytest.mark.parametrize("interval",