Skip to content

Commit 66ee71c

Browse files
asg017claude
andcommitted
Delete the rrule schedule type and its dateutil dependency
RRuleSchedule was the most intricate code in the package -- embedded-DTSTART detection, bounded-rule rejection, walking dateutil's private _rrule/_rset internals, and two separate timezone branches -- and it had no users. Nothing in samples/, no external consumer and nothing outside this repo's own tests ever constructed one, yet it absorbed two rounds of bug fixes (dtstart re-anchoring, timezone handling). Two schedule types, cron and interval, cover every real case and drop python-dateutil as a direct dependency. Rows written by 0.0.1a2 may still hold schedule_type='rrule'. No migration is added: per-task tick isolation already disables such a row with last_status="error" and leaves the rest of the tick alone, so an unrecognised type degrades exactly as any other unparseable schedule does. The README's schedule-type section says so, for the operator who finds a disabled task. The telemetry conformance test's schedule sentinel becomes a distinctive cron expression, keeping its "schedule_config never reaches a span or metric" coverage intact. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent 35e46fb commit 66ee71c

8 files changed

Lines changed: 15 additions & 244 deletions

File tree

‎CLAUDE.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ datasette_cron/
3737
├── page_data.py # Pydantic models (page data + API contracts)
3838
├── internal_db.py # Database operations wrapper
3939
├── internal_migrations.py # sqlite-migrate schema
40-
├── schedules.py # CronSchedule, IntervalSchedule, RRuleSchedule
40+
├── schedules.py # CronSchedule, IntervalSchedule
4141
├── scheduler.py # Scheduler class: loop, execution, retry, CRUD API
4242
├── telemetry.py # OTel tracer/meter, instruments, gauge callbacks
4343
├── telemetry_registry.py # Every span/metric name (docs + conformance test read it)
@@ -62,7 +62,7 @@ frontend/src/
6262

6363
**Tasks:** DB rows in `datasette_cron_tasks`. Reference a handler by name + JSON config + schedule. Created via `datasette._cron_scheduler.add_task(...)`.
6464

65-
**Schedules:** Three types — cron string (`"0 8 * * *"`), interval (`{"interval": 60}`), rrule (`{"rrule": "FREQ=WEEKLY;BYDAY=MO"}`). All support timezone.
65+
**Schedules:** Two types — cron string (`"0 8 * * *"`) and interval (`{"interval": 60}`). Both support timezone.
6666

6767
## Routes
6868

‎README.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -132,11 +132,11 @@ schedule="0 8 * * *" # daily at 8am
132132
schedule="*/5 * * * *" # every 5 minutes
133133
```
134134

135-
**RFC 5545 RRULE**:
136-
137-
```python
138-
schedule={"rrule": "FREQ=WEEKLY;BYDAY=MO"}
139-
```
135+
Interval and cron are the only schedule types. An `rrule` type existed in
136+
0.0.1a2 and was removed: a task whose stored row still has
137+
`schedule_type="rrule"` can no longer be scheduled, so the scheduler disables
138+
it with `last_status="error"` on the next tick. Re-create it with a cron
139+
schedule.
140140

141141
### Other Methods
142142

@@ -168,7 +168,7 @@ for run in runs:
168168
| `name` | `str` | Unique task identifier |
169169
| `handler` | `str` | Handler reference (e.g., `"myplugin:my-handler"`) |
170170
| `config` | `dict` | JSON config passed to handler |
171-
| `schedule_type` | `str` | `"interval"`, `"cron"`, or `"rrule"` |
171+
| `schedule_type` | `str` | `"interval"` or `"cron"` |
172172
| `schedule_config` | `str` | JSON schedule parameters |
173173
| `timezone` | `str \| None` | IANA timezone |
174174
| `overlap_policy` | `str` | `"skip"` or `"allow"` |

‎datasette_cron/scheduler.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,7 @@ async def _tick(self, now: datetime | None = None) -> TickStats:
375375
# means a scheduler that was down never tries to catch up on
376376
# missed slots (no burst of back-to-back runs after
377377
# downtime).
378-
# - cron/rrule next-runs are absolute wall-clock times, so a
378+
# - cron next-runs are absolute wall-clock times, so a
379379
# slot is only skipped when the tick itself is more than a
380380
# full period late — acceptable for a best-effort scheduler.
381381
sched = schedule_from_db(

‎datasette_cron/schedules.py‎

Lines changed: 1 addition & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from zoneinfo import ZoneInfo
77

88
from croniter import croniter
9-
from dateutil.rrule import rrulestr
109

1110

1211
class Schedule(abc.ABC):
@@ -31,7 +30,7 @@ def to_dict(self) -> dict:
3130
@property
3231
@abc.abstractmethod
3332
def schedule_type(self) -> str:
34-
"""Return 'cron', 'interval', or 'rrule'."""
33+
"""Return 'cron' or 'interval'."""
3534

3635

3736
class CronSchedule(Schedule):
@@ -95,125 +94,13 @@ def to_dict(self) -> dict:
9594
return {"seconds": self.seconds}
9695

9796

98-
class RRuleSchedule(Schedule):
99-
def __init__(self, rrule_str: str, tz: ZoneInfo | None = None):
100-
self.rrule_str = rrule_str
101-
self.tz = tz
102-
# Parse once and keep the rule. An embedded DTSTART is authoritative:
103-
# reusing the parsed rule preserves COUNT/UNTIL semantics instead of
104-
# re-anchoring the rule at "now" on every next_run call.
105-
self._rule = rrulestr(rrule_str) # also validates
106-
self._has_dtstart = "DTSTART" in rrule_str.upper()
107-
if not self._has_dtstart and self._is_bounded(self._rule):
108-
# Without an anchor, a COUNT/UNTIL rule would be re-anchored at
109-
# "now" on every scheduler tick — COUNT would never exhaust and
110-
# UNTIL would drift. Fail at construction with a clear message
111-
# rather than silently mis-scheduling.
112-
raise ValueError(
113-
"rrule with COUNT or UNTIL requires an explicit DTSTART "
114-
"(otherwise the rule would be re-anchored at every check)"
115-
)
116-
117-
@staticmethod
118-
def _is_bounded(rule) -> bool:
119-
# rrulestr returns either an rrule or an rruleset wrapping rrules.
120-
inner = getattr(rule, "_rrule", None)
121-
rules = list(inner) if inner is not None else [rule]
122-
return any(
123-
getattr(r, "_count", None) is not None
124-
or getattr(r, "_until", None) is not None
125-
for r in rules
126-
)
127-
128-
@staticmethod
129-
def _rule_dtstart(rule) -> datetime | None:
130-
dt = getattr(rule, "_dtstart", None)
131-
if dt is None:
132-
for r in getattr(rule, "_rrule", None) or []:
133-
dt = getattr(r, "_dtstart", None)
134-
if dt is not None:
135-
break
136-
return dt
137-
138-
@property
139-
def schedule_type(self) -> str:
140-
return "rrule"
141-
142-
def next_run(self, after: datetime) -> datetime:
143-
if self._has_dtstart:
144-
return self._next_run_anchored(after)
145-
146-
# No DTSTART: relative-to-now scheduling. Re-parse with the current
147-
# time as the anchor (dateutil would otherwise anchor at parse time,
148-
# i.e. process start). Only valid for unbounded rules — bounded ones
149-
# are rejected in __init__.
150-
if self.tz:
151-
local_after = after.replace(tzinfo=timezone.utc).astimezone(self.tz)
152-
else:
153-
local_after = after
154-
155-
rule = rrulestr(self.rrule_str, dtstart=local_after)
156-
next_dt = rule.after(local_after)
157-
if next_dt is None:
158-
# Fallback: far future
159-
return after + timedelta(days=365)
160-
161-
if self.tz:
162-
return next_dt.astimezone(timezone.utc).replace(tzinfo=None)
163-
return next_dt.replace(tzinfo=None) if next_dt.tzinfo else next_dt
164-
165-
def _next_run_anchored(self, after: datetime) -> datetime:
166-
"""next_run for rules with an embedded DTSTART, using the stored rule.
167-
168-
Compares in the same naive/aware space as the rule's occurrences so
169-
dateutil never mixes naive and aware datetimes.
170-
"""
171-
anchor = self._rule_dtstart(self._rule)
172-
if anchor is not None and anchor.tzinfo is not None:
173-
# Aware DTSTART (e.g. DTSTART;TZID=...): compare in aware UTC.
174-
next_dt = self._rule.after(after.replace(tzinfo=timezone.utc))
175-
if next_dt is None:
176-
return after + timedelta(days=365)
177-
return next_dt.astimezone(timezone.utc).replace(tzinfo=None)
178-
179-
# Naive DTSTART: occurrences are naive, interpreted in the schedule's
180-
# timezone (or UTC when no timezone is configured).
181-
if self.tz:
182-
local_after = (
183-
after.replace(tzinfo=timezone.utc)
184-
.astimezone(self.tz)
185-
.replace(tzinfo=None)
186-
)
187-
next_dt = self._rule.after(local_after)
188-
if next_dt is None:
189-
return after + timedelta(days=365)
190-
return (
191-
next_dt.replace(tzinfo=self.tz)
192-
.astimezone(timezone.utc)
193-
.replace(tzinfo=None)
194-
)
195-
196-
next_dt = self._rule.after(after)
197-
if next_dt is None:
198-
return after + timedelta(days=365)
199-
return next_dt
200-
201-
def describe(self) -> str:
202-
tz_str = f" ({self.tz})" if self.tz else ""
203-
return f"rrule: {self.rrule_str}{tz_str}"
204-
205-
def to_dict(self) -> dict:
206-
return {"rrule": self.rrule_str}
207-
208-
20997
def parse_schedule(schedule, tz_str: str | None = None) -> Schedule:
21098
"""Parse a schedule definition into a Schedule object.
21199
212100
Args:
213101
schedule: One of:
214102
- A cron string like "0 8 * * *"
215103
- A dict with "interval" key (seconds)
216-
- A dict with "rrule" key (RFC 5545 string)
217104
tz_str: Optional IANA timezone string
218105
"""
219106
tz = ZoneInfo(tz_str) if tz_str else None
@@ -223,8 +110,6 @@ def parse_schedule(schedule, tz_str: str | None = None) -> Schedule:
223110
elif isinstance(schedule, dict):
224111
if "interval" in schedule:
225112
return IntervalSchedule(schedule["interval"])
226-
elif "rrule" in schedule:
227-
return RRuleSchedule(schedule["rrule"], tz=tz)
228113
raise ValueError(f"Cannot parse schedule: {schedule!r}")
229114

230115

@@ -239,8 +124,6 @@ def schedule_from_db(
239124
return CronSchedule(config["expression"], tz=tz)
240125
elif schedule_type == "interval":
241126
return IntervalSchedule(config["seconds"])
242-
elif schedule_type == "rrule":
243-
return RRuleSchedule(config["rrule"], tz=tz)
244127
else:
245128
raise ValueError(f"Unknown schedule type: {schedule_type}")
246129

‎pyproject.toml‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ dependencies = [
1919
"sqlite-migrate>=0.1b0",
2020
"sqlite-utils>=3.38",
2121
"croniter",
22-
"python-dateutil",
2322
]
2423

2524
[dependency-groups]

‎tests/test_routes.py‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -229,9 +229,6 @@ async def handler(datasette, config):
229229
name="interval-task", handler="test:h", schedule={"interval": 300}
230230
)
231231
await scheduler.add_task(name="cron-task", handler="test:h", schedule="0 8 * * *")
232-
await scheduler.add_task(
233-
name="rrule-task", handler="test:h", schedule={"rrule": "FREQ=DAILY"}
234-
)
235232
# A row with unparseable schedule_config, as if written by a buggy or
236233
# future version -- exercises the except-fallback branch.
237234
await scheduler.internal_db.upsert_task(
@@ -245,7 +242,6 @@ async def handler(datasette, config):
245242
expected = {
246243
"interval-task": ("every 5m", 300),
247244
"cron-task": ("cron: 0 8 * * *", None),
248-
"rrule-task": ("rrule: FREQ=DAILY", None),
249245
"broken-task": ("interval: not json", None),
250246
}
251247

‎tests/test_schedules.py‎

Lines changed: 1 addition & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,14 @@
22
import sys
33
import time
44
from contextlib import contextmanager
5-
from datetime import datetime, timedelta
5+
from datetime import datetime
66
from zoneinfo import ZoneInfo
77

88
import pytest
99

1010
from datasette_cron.schedules import (
1111
CronSchedule,
1212
IntervalSchedule,
13-
RRuleSchedule,
1413
parse_schedule,
1514
schedule_from_db,
1615
)
@@ -77,80 +76,6 @@ def test_to_dict(self):
7776
assert sched.to_dict() == {"seconds": 120}
7877

7978

80-
class TestRRuleSchedule:
81-
def test_next_run_weekly(self):
82-
sched = RRuleSchedule("FREQ=WEEKLY;BYDAY=MO")
83-
# Tuesday
84-
after = datetime(2026, 3, 31, 10, 0, 0)
85-
next_run = sched.next_run(after)
86-
# Next Monday
87-
assert next_run.weekday() == 0 # Monday
88-
assert next_run > after
89-
90-
def test_describe(self):
91-
sched = RRuleSchedule("FREQ=DAILY")
92-
assert "FREQ=DAILY" in sched.describe()
93-
94-
def test_to_dict(self):
95-
sched = RRuleSchedule("FREQ=DAILY")
96-
assert sched.to_dict() == {"rrule": "FREQ=DAILY"}
97-
98-
def test_embedded_dtstart_is_authoritative(self):
99-
sched = RRuleSchedule("DTSTART:20260101T080000\nRRULE:FREQ=DAILY")
100-
# Before the anchor: first occurrence is DTSTART itself
101-
assert sched.next_run(datetime(2025, 12, 1)) == datetime(2026, 1, 1, 8, 0)
102-
# After the anchor: occurrences stay phased on the 8:00 anchor
103-
assert sched.next_run(datetime(2026, 1, 5, 12, 0)) == datetime(2026, 1, 6, 8, 0)
104-
# Deterministic: same `after` gives the same answer (no re-anchoring)
105-
assert sched.next_run(datetime(2026, 1, 5, 12, 0)) == sched.next_run(
106-
datetime(2026, 1, 5, 12, 0)
107-
)
108-
109-
def test_bounded_count_with_dtstart_exhausts(self):
110-
sched = RRuleSchedule("DTSTART:20260101T080000\nRRULE:FREQ=DAILY;COUNT=2")
111-
first = sched.next_run(datetime(2025, 12, 31))
112-
assert first == datetime(2026, 1, 1, 8, 0)
113-
second = sched.next_run(first)
114-
assert second == datetime(2026, 1, 2, 8, 0)
115-
# Exhausted: falls back to far-future instead of repeating forever
116-
after_last = sched.next_run(second)
117-
assert after_last == second + timedelta(days=365)
118-
119-
def test_bounded_rule_without_dtstart_rejected(self):
120-
with pytest.raises(ValueError, match="DTSTART"):
121-
RRuleSchedule("FREQ=DAILY;COUNT=3")
122-
with pytest.raises(ValueError, match="DTSTART"):
123-
RRuleSchedule("FREQ=DAILY;UNTIL=20270101T000000")
124-
125-
def test_embedded_naive_dtstart_with_tz(self):
126-
# Naive DTSTART is interpreted in the schedule's timezone
127-
sched = RRuleSchedule(
128-
"DTSTART:20260101T080000\nRRULE:FREQ=DAILY",
129-
tz=ZoneInfo("America/New_York"),
130-
)
131-
# 2026-01-05 12:00 UTC is 07:00 EST; next 8am ET is 13:00 UTC same day
132-
next_run = sched.next_run(datetime(2026, 1, 5, 12, 0))
133-
assert next_run.tzinfo is None
134-
assert next_run == datetime(2026, 1, 5, 13, 0)
135-
136-
def test_embedded_aware_dtstart_returns_naive_utc(self):
137-
# Aware DTSTART (TZID) with no schedule tz configured
138-
sched = RRuleSchedule(
139-
"DTSTART;TZID=America/New_York:20260101T080000\nRRULE:FREQ=DAILY"
140-
)
141-
# Next 8am ET after 2026-01-05 00:00 UTC is 2026-01-05 13:00 UTC
142-
next_run = sched.next_run(datetime(2026, 1, 5, 0, 0))
143-
assert next_run.tzinfo is None
144-
assert next_run == datetime(2026, 1, 5, 13, 0)
145-
146-
def test_unbounded_no_dtstart_stays_relative(self):
147-
# Regression guard for the no-DTSTART path: still relative to `after`
148-
sched = RRuleSchedule("FREQ=WEEKLY;BYDAY=MO")
149-
after = datetime(2026, 3, 31, 10, 0, 0) # Tuesday
150-
next_run = sched.next_run(after)
151-
assert next_run == datetime(2026, 4, 6, 10, 0, 0) # next Monday
152-
153-
15479
class TestParseSchedule:
15580
def test_parse_cron_string(self):
15681
sched = parse_schedule("0 8 * * *")
@@ -161,10 +86,6 @@ def test_parse_interval_dict(self):
16186
assert isinstance(sched, IntervalSchedule)
16287
assert sched.seconds == 60
16388

164-
def test_parse_rrule_dict(self):
165-
sched = parse_schedule({"rrule": "FREQ=DAILY"})
166-
assert isinstance(sched, RRuleSchedule)
167-
16889
def test_parse_with_timezone(self):
16990
sched = parse_schedule("0 8 * * *", tz_str="America/New_York")
17091
assert isinstance(sched, CronSchedule)
@@ -186,10 +107,6 @@ def test_interval_from_db(self):
186107
assert isinstance(sched, IntervalSchedule)
187108
assert sched.seconds == 300
188109

189-
def test_rrule_from_db(self):
190-
sched = schedule_from_db("rrule", '{"rrule": "FREQ=WEEKLY"}')
191-
assert isinstance(sched, RRuleSchedule)
192-
193110
def test_unknown_type_raises(self):
194111
with pytest.raises(ValueError):
195112
schedule_from_db("unknown", "{}")
@@ -227,26 +144,6 @@ def test_cron_tz_schedule_ignores_process_tz(self):
227144
assert next_run == datetime(2026, 7, 2, 12, 0)
228145
assert next_run > now
229146

230-
def test_rrule_tz_schedule_ignores_process_tz(self):
231-
with _forced_process_tz("Asia/Tokyo"):
232-
sched = parse_schedule(
233-
{"rrule": "FREQ=DAILY;BYHOUR=8;BYMINUTE=0;BYSECOND=0"},
234-
tz_str="America/New_York",
235-
)
236-
now = datetime(2026, 7, 1, 20, 36)
237-
next_run = sched.next_run(now)
238-
assert next_run.tzinfo is None
239-
assert next_run == datetime(2026, 7, 2, 12, 0)
240-
assert next_run > now
241-
242-
def test_rrule_no_tz_still_returns_naive(self):
243-
with _forced_process_tz("Asia/Tokyo"):
244-
sched = RRuleSchedule("FREQ=DAILY;BYHOUR=8;BYMINUTE=0;BYSECOND=0")
245-
now = datetime(2026, 7, 1, 20, 36)
246-
next_run = sched.next_run(now)
247-
assert next_run.tzinfo is None
248-
assert next_run == datetime(2026, 7, 2, 8, 0)
249-
250147

251148
def test_describe_schedule_helper():
252149
from datasette_cron.schedules import describe_schedule
@@ -256,10 +153,6 @@ def test_describe_schedule_helper():
256153
"cron: 0 8 * * *",
257154
None,
258155
)
259-
assert describe_schedule("rrule", '{"rrule": "FREQ=DAILY"}') == (
260-
"rrule: FREQ=DAILY",
261-
None,
262-
)
263156
# Timezone is included in the description for tz-aware schedules
264157
desc, seconds = describe_schedule(
265158
"cron", '{"expression": "0 8 * * *"}', "America/New_York"

0 commit comments

Comments
 (0)