Skip to content

Commit be4b1b5

Browse files
asg017claude
andcommitted
Delete schedule jitter; single-process scheduling has no herd to spread
add_jitter smeared every computed next-run by a random offset to avoid a thundering herd, but datasette-cron is single-process by contract (see the multi-worker warning in the README), so there is no herd to spread out. The protection bought nothing and cost precision: "0 8 * * *" did not fire at 08:00:00, a 60-second interval meant 60-66 seconds, the UI countdown was approximate, and three tests carried timing tolerances to accommodate it. Both call sites (add_task and _tick) now use sched.next_run(now) directly, and the tolerance assertions are tightened to exact comparisons, which makes those tests stronger rather than weaker. The jitter in _backoff_delay stays: retry jitter is defensible for a different reason -- it decorrelates repeated failures against a flaky dependency -- and is untouched here. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent a6619a6 commit be4b1b5

5 files changed

Lines changed: 19 additions & 47 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -243,9 +243,9 @@ durations, retry attempts and error messages:
243243
not coordinate across processes. Handlers should tolerate being invoked
244244
twice for the same scheduled slot.
245245
- **Scheduling is best-effort, not real-time.** `next_run_at` is recomputed
246-
from the wall-clock time the scheduler observes the task as due, plus a
247-
small jitter, so intervals mean "at least N seconds between scheduled
248-
starts" rather than exact phase-locked boundaries.
246+
from the wall-clock time the scheduler observes the task as due, so
247+
intervals mean "at least N seconds between scheduled starts" rather than
248+
exact phase-locked boundaries.
249249

250250
## OpenTelemetry
251251

‎datasette_cron/scheduler.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from .events import RunFinishedEvent
1818
from .internal_db import InternalDB
1919
from .models import CronTask
20-
from .schedules import add_jitter, parse_schedule, schedule_from_db
20+
from .schedules import parse_schedule, schedule_from_db
2121
from .telemetry import tracer
2222
from .telemetry_registry import (
2323
ATTEMPT,
@@ -213,7 +213,7 @@ async def add_task(
213213
retry = retry or {}
214214
sched = parse_schedule(schedule, tz_str=timezone)
215215
now = _utcnow()
216-
next_run = add_jitter(sched.next_run(now), sched)
216+
next_run = sched.next_run(now)
217217

218218
await self.internal_db.upsert_task(
219219
name=name,
@@ -383,7 +383,7 @@ async def _tick(self, now: datetime | None = None) -> TickStats:
383383
sched = schedule_from_db(
384384
task.schedule_type, task.schedule_config, task.timezone
385385
)
386-
next_run = add_jitter(sched.next_run(now), sched)
386+
next_run = sched.next_run(now)
387387
await self.internal_db.update_next_run(name, next_run.isoformat())
388388

389389
return stats

‎datasette_cron/schedules.py‎

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import abc
44
import json
5-
import random
65
from datetime import datetime, timedelta, timezone
76
from zoneinfo import ZoneInfo
87

@@ -262,13 +261,3 @@ def describe_schedule(
262261
return sched.describe(), seconds
263262
except Exception:
264263
return f"{schedule_type}: {schedule_config}", None
265-
266-
267-
def add_jitter(next_run: datetime, schedule: Schedule) -> datetime:
268-
"""Add jitter to prevent thundering herd."""
269-
if isinstance(schedule, IntervalSchedule):
270-
max_jitter = min(schedule.seconds * 0.1, 30.0)
271-
else:
272-
max_jitter = 5.0 # Small jitter for cron/rrule
273-
jitter = random.uniform(0, max_jitter)
274-
return next_run + timedelta(seconds=jitter)

‎tests/test_cron.py‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ async def noop(datasette, config):
100100

101101
@pytest.mark.asyncio
102102
async def test_add_task_upsert_schedule_change_recomputes_next_run_at():
103-
from datetime import datetime, timezone
103+
from datetime import datetime, timedelta, timezone
104104

105105
ds, scheduler = await _make_scheduler()
106106

@@ -119,19 +119,21 @@ async def noop(datasette, config):
119119

120120
# Re-add with a different schedule -- next_run_at must be recomputed
121121
# from the new schedule, not left ~300s out.
122+
before = datetime.now(timezone.utc).replace(tzinfo=None)
122123
await scheduler.add_task(
123124
name="reschedule-task",
124125
handler="test:handler",
125126
schedule={"interval": 1},
126127
)
128+
after = datetime.now(timezone.utc).replace(tzinfo=None)
127129

128130
task2 = await scheduler.internal_db.get_task("reschedule-task")
129131
assert json.loads(task2.schedule_config)["seconds"] == 1
130132
assert task2.next_run_at != original_next_run
131-
now = datetime.now(timezone.utc).replace(tzinfo=None)
132-
delta = (datetime.fromisoformat(task2.next_run_at) - now).total_seconds()
133-
# Derived from the new 1s interval (plus ≤0.1s jitter), not the old 300s
134-
assert -1 < delta < 5
133+
next_run = datetime.fromisoformat(task2.next_run_at)
134+
# Exactly one new-interval second past the add_task call -- derived from
135+
# the new 1s interval, not the old 300s.
136+
assert before + timedelta(seconds=1) <= next_run <= after + timedelta(seconds=1)
135137

136138
await scheduler.shutdown()
137139

@@ -1439,9 +1441,8 @@ async def noop(datasette, config):
14391441

14401442
task = await idb.get_task("drifty")
14411443
next_run = datetime.fromisoformat(task.next_run_at)
1442-
# Anchored to tick-time: now + 60s (+ up to 10% interval jitter = 6s).
1443-
assert tick_now + timedelta(seconds=60) <= next_run
1444-
assert next_run <= tick_now + timedelta(seconds=66)
1444+
# Anchored to tick-time: exactly now + 60s.
1445+
assert next_run == tick_now + timedelta(seconds=60)
14451446
# NOT catch-up scheduling: nowhere near the missed 12:01:00 boundary.
14461447
assert next_run > past + timedelta(hours=1)
14471448

@@ -1454,7 +1455,7 @@ async def test_tick_late_in_slot_does_not_skip_next_cron_boundary():
14541455
every-minute cron) still schedules the very next boundary -- croniter
14551456
computes strictly-after `now`, so a slot is only skipped when the tick
14561457
itself is more than a full period late."""
1457-
from datetime import datetime, timedelta
1458+
from datetime import datetime
14581459

14591460
ds, scheduler = await _make_scheduler()
14601461

@@ -1478,9 +1479,8 @@ async def noop(datasette, config):
14781479
task = await idb.get_task("every-minute")
14791480
next_run = datetime.fromisoformat(task.next_run_at)
14801481
boundary = datetime(2026, 1, 1, 12, 1, 0)
1481-
# Next fire is the immediately-following boundary (+ up to 5s cron jitter),
1482-
# not two minutes out.
1483-
assert boundary <= next_run
1484-
assert next_run <= boundary + timedelta(seconds=5)
1482+
# Next fire is exactly the immediately-following boundary, not two
1483+
# minutes out.
1484+
assert next_run == boundary
14851485

14861486
await scheduler.shutdown()

‎tests/test_schedules.py‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
CronSchedule,
1212
IntervalSchedule,
1313
RRuleSchedule,
14-
add_jitter,
1514
parse_schedule,
1615
schedule_from_db,
1716
)
@@ -249,22 +248,6 @@ def test_rrule_no_tz_still_returns_naive(self):
249248
assert next_run == datetime(2026, 7, 2, 8, 0)
250249

251250

252-
class TestJitter:
253-
def test_jitter_adds_time(self):
254-
sched = IntervalSchedule(60)
255-
base = datetime(2026, 1, 1, 0, 0, 0)
256-
jittered = add_jitter(base, sched)
257-
assert jittered >= base
258-
# Max jitter for 60s interval is min(6, 30) = 6 seconds
259-
assert jittered <= base + timedelta(seconds=6.1)
260-
261-
def test_jitter_capped_at_30(self):
262-
sched = IntervalSchedule(86400)
263-
base = datetime(2026, 1, 1, 0, 0, 0)
264-
jittered = add_jitter(base, sched)
265-
assert jittered <= base + timedelta(seconds=30.1)
266-
267-
268251
def test_describe_schedule_helper():
269252
from datasette_cron.schedules import describe_schedule
270253

0 commit comments

Comments
 (0)