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.

chore(devex): stop celery beat schedules drawing their minute at random (#98119)

Julian Bez178eca7de55a
diff --git a/.semgrep/rules/devex/beat-schedule-must-not-be-random.py b/.semgrep/rules/devex/beat-schedule-must-not-be-random.py
new file mode 100644
index 000000000000..c6bc7c88bbf5
--- /dev/null
+++ b/.semgrep/rules/devex/beat-schedule-must-not-be-random.py
@@ -0,0 +1,20 @@
+# Test cases for beat-schedule-must-not-be-random.
+# ruff: noqa
+
+# ruleid: beat-schedule-must-not-be-random
+sender.add_periodic_task(crontab(hour="0", minute=str(randrange(0, 40))), send_usage_report.s())
+
+# ruleid: beat-schedule-must-not-be-random
+sender.add_periodic_task(crontab(minute=str(random.randint(0, 59))), refresh_cache.s())
+
+# ruleid: beat-schedule-must-not-be-random
+schedule = crontab(hour=str(random.choice(["1", "2"])), minute="0")
+
+# ok: beat-schedule-must-not-be-random
+sender.add_periodic_task(crontab(hour="2", minute="23"), sweep_retention.s())
+
+# ok: beat-schedule-must-not-be-random
+sender.add_periodic_task(crontab(hour="0", minute=instance_spread_minute("send license usage", 40)), send_license.s())
+
+# ok: beat-schedule-must-not-be-random
+jitter = randrange(0, 40)
diff --git a/.semgrep/rules/devex/beat-schedule-must-not-be-random.yaml b/.semgrep/rules/devex/beat-schedule-must-not-be-random.yaml
new file mode 100644
index 000000000000..97c19bec5991
--- /dev/null
+++ b/.semgrep/rules/devex/beat-schedule-must-not-be-random.yaml
@@ -0,0 +1,36 @@
+rules:
+ - id: beat-schedule-must-not-be-random
+ message: |
+ A celery beat schedule must not draw its time at random.
+
+ The schedule is built when a beat process starts, so a random draw runs once
+ per process and not once per day. Beat processes restart every few minutes,
+ and each restart both draws a new time and forgets what already ran, so the
+ task runs twice on one day and skips another.
+
+ Write a fixed minute, `crontab(hour="2", minute="23")`. Where separate
+ installations must not share a minute, call `instance_spread_minute` in
+ `posthog/tasks/scheduled.py`. Its docstring carries the rules for both.
+ languages: [python]
+ severity: ERROR
+ patterns:
+ - pattern-inside: crontab(...)
+ - pattern-either:
+ - pattern: randrange(...)
+ - pattern: randint(...)
+ - pattern: choice(...)
+ - pattern: uniform(...)
+ - pattern: random.randrange(...)
+ - pattern: random.randint(...)
+ - pattern: random.choice(...)
+ - pattern: random.uniform(...)
+ - pattern: random.random()
+ paths:
+ include:
+ - ee/**/*.py
+ - posthog/**/*.py
+ - products/**/*.py
+ metadata:
+ category: correctness
+ subcategory: audit
+ confidence: HIGH
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 5039ad207558..65226c6c3d20 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -1,4 +1,4 @@
-from random import randrange
+import zlib
from typing import Any
from django.conf import settings
@@ -187,6 +187,33 @@ def estimate_crontab_interval_seconds(schedule: crontab) -> int:
return 86400
+def instance_spread_minute(key: str, window_minutes: int) -> str:
+ """Pick a minute inside the window that holds still for this installation.
+
+ Beat rebuilds its schedule every time a beat process starts, and the new
+ schedule has no record of what already ran. A minute that comes from a random
+ draw therefore changes on every restart: a restart inside the scheduled hour
+ runs the task a second time that day, and a restart that draws an earlier
+ minute skips the day. This is why no periodic schedule in this file draws its
+ time at random, and why the beat-schedule-must-not-be-random semgrep rule
+ blocks it.
+
+ Use this helper only where separate installations must not share a minute,
+ such as a task that calls an endpoint PostHog hosts. A minute derived from
+ SITE_URL holds still across restarts and still differs between
+ installations. Installations that leave SITE_URL at its default share a
+ minute with each other. SECRET_KEY would serve as well but is deliberately
+ not used: `.agents/security.md` keeps new code off it, and this value ends
+ up observable in the schedule.
+
+ Every other task takes a fixed minute written at the call site, because a
+ reader can then tell when it runs. Pick an odd minute that is not a multiple
+ of 5 and that no other task in the same hour holds, which keeps it off both
+ the */2 and */5 entries and off its neighbours.
+ """
+ return str(zlib.crc32(f"{settings.SITE_URL}:{key}".encode()) % window_minutes)
+
+
def add_periodic_task_with_expiry(
sender: Celery,
schedule: crontab,
@@ -838,11 +865,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
if settings.EE_AVAILABLE:
sender.add_periodic_task(
- crontab(hour="0", minute=str(randrange(0, 40))),
+ # The minute differs between installations so that they do not all call
+ # license.posthog.com in the same minute past midnight.
+ crontab(hour="0", minute=instance_spread_minute("send license usage", 40)),
clickhouse_send_license_usage.s(),
- ) # every day at a random minute past midnight. Randomize to avoid overloading license.posthog.com
+ )
sender.add_periodic_task(
- crontab(hour="4", minute=str(randrange(0, 40))),
+ crontab(hour="4", minute=instance_spread_minute("send license usage retry", 40)),
clickhouse_send_license_usage.s(),
) # again a few hours later just to make sure
@@ -862,8 +891,7 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
)
sender.add_periodic_task(
- # once a day a random minute after midnight
- crontab(hour="0", minute=str(randrange(0, 40))),
+ crontab(hour="0", minute="7"),
delete_expired_exported_assets.s(),
name="delete expired exported assets",
)
@@ -871,7 +899,7 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
# Hourly rather than daily: until this runs, a dead video export still reads as in progress
# to whoever is waiting on it.
sender.add_periodic_task(
- crontab(minute=str(randrange(0, 60))),
+ crontab(minute="33"),
fail_stuck_video_exports.s(),
name="fail stuck video exports",
)
@@ -880,7 +908,7 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
# the delegator's onboarding, so a missed sweep strands delegators on the "waiting
# for teammate" screen forever.
sender.add_periodic_task(
- crontab(hour="1", minute=str(randrange(0, 40))),
+ crontab(hour="1", minute="9"),
delete_expired_delegation_invites.s(),
name="delete expired delegation invites",
)
@@ -903,7 +931,7 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
)
sender.add_periodic_task(
- crontab(hour="0", minute=str(randrange(0, 40))),
+ crontab(hour="0", minute="13"),
sync_all_remote_configs.s(),
name="sync all remote configs",
)
@@ -915,14 +943,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
)
sender.add_periodic_task(
- crontab(hour="0", minute=str(randrange(0, 40))),
+ crontab(hour="0", minute="19"),
sync_all_surveys_cache.s(),
name="sync all surveys cache",
)
add_periodic_task_with_expiry(
sender,
- crontab(hour="1", minute=str(randrange(0, 40))),
+ crontab(hour="1", minute="27"),
cleanup_canvas_builds.s(),
name="apply canvas build artifact retention",
)
@@ -1021,11 +1049,6 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="prune old streamlit app versions",
)
- # The minute is fixed because beat rebuilds its schedule on every start. A
- # randrange minute draws a new value on each restart, so a restart inside the
- # scheduled hour makes the sweep run a second time that night, and a restart
- # that draws an earlier minute can make it skip the night. Minute 23 is odd,
- # which also keeps the sweep off the minutes the */2 heartbeat tasks use.
add_periodic_task_with_expiry(
sender,
crontab(hour="2", minute="23"),
diff --git a/posthog/tasks/test/test_scheduled.py b/posthog/tasks/test/test_scheduled.py
index 687aad922d05..93c5c86190e3 100644
--- a/posthog/tasks/test/test_scheduled.py
+++ b/posthog/tasks/test/test_scheduled.py
@@ -1,7 +1,7 @@
-from django.test import TestCase
+from django.test import SimpleTestCase, TestCase
from posthog.celery import app
-from posthog.tasks.scheduled import setup_periodic_tasks
+from posthog.tasks.scheduled import instance_spread_minute, setup_periodic_tasks
class TestScheduledTasks(TestCase):
@@ -13,3 +13,19 @@ class TestScheduledTasks(TestCase):
setup_periodic_tasks(app)
except Exception as exc:
assert exc is None, exc
+
+
+class TestInstanceSpreadMinute(SimpleTestCase):
+ def test_one_installation_keeps_its_minute_in_every_process(self) -> None:
+ # A literal, because the minute has to survive a beat restart. A hash that
+ # is only stable inside one process, such as the built-in hash(), passes an
+ # equality check between two calls and still moves the schedule on restart.
+ with self.settings(SITE_URL="https://an-installation.example.com"):
+ assert instance_spread_minute("send license usage", 40) == "18"
+
+ def test_installations_do_not_all_get_the_same_minute(self) -> None:
+ minutes = set()
+ for site_url in ("site-one", "site-two", "site-three", "site-four"):
+ with self.settings(SITE_URL=site_url):
+ minutes.add(instance_spread_minute("send license usage", 40))
+ assert len(minutes) > 1