Skip to content

Commit 35e46fb

Browse files
asg017claude
andcommitted
Isolate per-task failures in the tick loop; compute next_run before spawning
The per-task body of _tick had no exception handling, so any task whose stored schedule no longer reconstructed took the whole tick down with it. get_due_tasks is ORDER BY next_run_at, which means one unusable row starved every task queued behind it: run() logged the exception, slept five seconds and hit the same row again. It was also worse than a stall. The old order spawned the execution first and only then recomputed next_run_at, so a task that raised while being rescheduled had already been started and was still due — re-firing on every tick, forever. Computing next_run before the spawn means we never start work we cannot reschedule. Failures now disable the task with last_status="error", mirroring the handler-not-found path directly above: whatever is wrong with the row will still be wrong next tick, and disabling drops it out of get_due_tasks so it cannot spin. This is also what lets a row written by an older release survive the removal of a schedule type — its unrecognised schedule_type disables that one task instead of crashing the scheduler. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent 05a6acb commit 35e46fb

2 files changed

Lines changed: 273 additions & 46 deletions

File tree

‎datasette_cron/scheduler.py‎

Lines changed: 77 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -333,59 +333,90 @@ async def _tick(self, now: datetime | None = None) -> TickStats:
333333

334334
for task in due_tasks:
335335
name = task.name
336-
handler_fn = self.get_handler(task.handler)
336+
# Every task is evaluated inside its own try/except: get_due_tasks
337+
# is ORDER BY next_run_at, so without this one unusable row (a
338+
# schedule that no longer parses, a missing timezone, a
339+
# hand-edited next_run_at) would abort the whole tick and starve
340+
# every task queued behind it.
341+
try:
342+
handler_fn = self.get_handler(task.handler)
343+
344+
# Lag is recorded for every due task, spawned or not, so an
345+
# overlap-starved task still shows its slot drifting.
346+
if task.next_run_at:
347+
telemetry.run_lag.record(
348+
_lag_seconds(task.next_run_at, now), {TASK: name}
349+
)
337350

338-
# Lag is recorded for every due task, spawned or not, so an
339-
# overlap-starved task still shows its slot drifting.
340-
if task.next_run_at:
341-
telemetry.run_lag.record(
342-
_lag_seconds(task.next_run_at, now), {TASK: name}
351+
if not handler_fn:
352+
logger.error(
353+
"Handler %r not found for task %r (available: %s), disabling",
354+
task.handler,
355+
name,
356+
list(self._handler_registry.keys()),
357+
)
358+
await self.internal_db.update_task(
359+
name, enabled=0, last_status="error"
360+
)
361+
stats.disabled += 1
362+
continue
363+
364+
# The next run is computed *before* spawning: if the stored
365+
# schedule cannot be reconstructed we must not start work we
366+
# would then be unable to reschedule, because next_run_at
367+
# would stay in the past and the task would re-fire on every
368+
# tick.
369+
#
370+
# The new next_run is deliberately anchored to the tick's
371+
# wall-clock `now`, not the task's stored (scheduled)
372+
# next_run_at:
373+
# - intervals mean "at least N seconds between scheduled
374+
# starts", so their phase drifts by tick latency; this also
375+
# means a scheduler that was down never tries to catch up on
376+
# missed slots (no burst of back-to-back runs after
377+
# downtime).
378+
# - cron/rrule next-runs are absolute wall-clock times, so a
379+
# slot is only skipped when the tick itself is more than a
380+
# full period late — acceptable for a best-effort scheduler.
381+
sched = schedule_from_db(
382+
task.schedule_type, task.schedule_config, task.timezone
343383
)
384+
next_run = sched.next_run(now)
344385

345-
if not handler_fn:
346-
logger.error(
347-
"Handler %r not found for task %r (available: %s), disabling",
348-
task.handler,
349-
name,
350-
list(self._handler_registry.keys()),
386+
outcome = self._spawn_execution(
387+
task, handler_fn, scheduled_at=task.next_run_at, now=now
351388
)
352-
await self.internal_db.update_task(name, enabled=0, last_status="error")
389+
if outcome == "skipped":
390+
stats.skipped += 1
391+
logger.debug(
392+
"Skipped %r: overlap_policy=%s and a run is in flight",
393+
name,
394+
task.overlap_policy,
395+
)
396+
else:
397+
stats.spawned += 1
398+
if outcome == "cancelled":
399+
stats.cancelled += 1
400+
401+
# Advance next_run_at regardless of whether we spawned — a
402+
# skipped run still consumes its scheduling slot.
403+
await self.internal_db.update_next_run(name, next_run.isoformat())
404+
except Exception:
405+
# Disable rather than retry: whatever is wrong with this row
406+
# will still be wrong next tick, and leaving it enabled means
407+
# re-spawning it every five seconds forever. Disabling drops
408+
# it out of get_due_tasks, and the error status surfaces on
409+
# the task's detail page.
410+
logger.exception("Error evaluating task %r in tick, disabling", name)
411+
try:
412+
await self.internal_db.update_task(
413+
name, enabled=0, last_status="error"
414+
)
415+
except Exception:
416+
logger.exception("Could not disable broken task %r", name)
353417
stats.disabled += 1
354418
continue
355419

356-
outcome = self._spawn_execution(
357-
task, handler_fn, scheduled_at=task.next_run_at, now=now
358-
)
359-
if outcome == "skipped":
360-
stats.skipped += 1
361-
logger.debug(
362-
"Skipped %r: overlap_policy=%s and a run is in flight",
363-
name,
364-
task.overlap_policy,
365-
)
366-
else:
367-
stats.spawned += 1
368-
if outcome == "cancelled":
369-
stats.cancelled += 1
370-
371-
# Advance next_run_at regardless of whether we spawned — a skipped
372-
# run still consumes its scheduling slot.
373-
#
374-
# The new next_run is deliberately anchored to the tick's
375-
# wall-clock `now`, not the task's stored (scheduled) next_run_at:
376-
# - intervals mean "at least N seconds between scheduled starts",
377-
# so their phase drifts by tick latency; this also means a
378-
# scheduler that was down never tries to catch up on missed
379-
# slots (no burst of back-to-back runs after downtime).
380-
# - cron/rrule next-runs are absolute wall-clock times, so a slot
381-
# is only skipped when the tick itself is more than a full
382-
# period late — acceptable for a best-effort scheduler.
383-
sched = schedule_from_db(
384-
task.schedule_type, task.schedule_config, task.timezone
385-
)
386-
next_run = sched.next_run(now)
387-
await self.internal_db.update_next_run(name, next_run.isoformat())
388-
389420
return stats
390421

391422
async def _execute_task(

‎tests/test_cron.py‎

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1485,3 +1485,199 @@ async def noop(datasette, config):
14851485
assert next_run == boundary
14861486

14871487
await scheduler.shutdown()
1488+
1489+
1490+
# ---------------------------------------------------------------------------
1491+
# _tick per-task isolation: one unusable row must not starve the others
1492+
# ---------------------------------------------------------------------------
1493+
1494+
1495+
async def _write_broken_schedule(scheduler, name, **columns):
1496+
"""Force a task row into a state add_task would have rejected.
1497+
1498+
add_task validates the schedule on the way in, so the only way to
1499+
reproduce a row written by an older version (or hand-edited) is to update
1500+
the columns directly.
1501+
"""
1502+
await scheduler.internal_db.update_task(name, **columns)
1503+
1504+
1505+
@pytest.mark.asyncio
1506+
async def test_tick_isolates_task_with_unparseable_schedule():
1507+
"""A stored schedule that no longer parses disables its own task and
1508+
leaves every other due task alone.
1509+
1510+
get_due_tasks is ORDER BY next_run_at, so the broken row is evaluated
1511+
first: before per-task isolation its exception escaped _tick and the
1512+
healthy task queued behind it never ran."""
1513+
ds, scheduler = await _make_scheduler()
1514+
1515+
ran = asyncio.Event()
1516+
1517+
async def ok_handler(datasette, config):
1518+
ran.set()
1519+
1520+
async def never(datasette, config): # pragma: no cover - must not be called
1521+
raise AssertionError("broken task should not have been spawned")
1522+
1523+
scheduler.register_handlers("test", {"ok": ok_handler, "never": never})
1524+
await scheduler.add_task(
1525+
name="broken", handler="test:never", schedule={"interval": 60}
1526+
)
1527+
await scheduler.add_task(
1528+
name="healthy", handler="test:ok", schedule={"interval": 60}
1529+
)
1530+
1531+
idb = scheduler.internal_db
1532+
# An unrecognised schedule_type is exactly what a row written by an older
1533+
# release looks like once that schedule type is removed from the code.
1534+
await _write_broken_schedule(
1535+
scheduler,
1536+
"broken",
1537+
schedule_type="no-such-schedule-type",
1538+
schedule_config="{}",
1539+
next_run_at="2000-01-01T00:00:00",
1540+
)
1541+
# Ordered after the broken row, so it is the one that used to be starved.
1542+
await idb.update_next_run("healthy", "2000-01-01T00:00:01")
1543+
1544+
stats = await scheduler._tick()
1545+
1546+
assert stats.due == 2
1547+
assert stats.disabled == 1
1548+
assert stats.spawned == 1
1549+
1550+
await asyncio.wait_for(ran.wait(), timeout=2.0)
1551+
1552+
broken = await idb.get_task("broken")
1553+
assert broken.enabled is False
1554+
assert broken.last_status == "error"
1555+
1556+
healthy = await idb.get_task("healthy")
1557+
assert healthy.enabled is True
1558+
# Its slot was consumed and advanced past the stale 2000 value.
1559+
assert healthy.next_run_at > "2001"
1560+
1561+
await scheduler.shutdown()
1562+
1563+
1564+
@pytest.mark.asyncio
1565+
async def test_tick_disables_broken_task_instead_of_respawning_it():
1566+
"""The broken task is never spawned, and repeated ticks do not retry it.
1567+
1568+
Before this change the tick spawned the handler and only then tried to
1569+
recompute next_run_at -- so the row stayed due and re-fired on every tick,
1570+
forever."""
1571+
ds, scheduler = await _make_scheduler()
1572+
1573+
calls = 0
1574+
1575+
async def counting(datasette, config):
1576+
nonlocal calls
1577+
calls += 1
1578+
1579+
scheduler.register_handlers("test", {"counting": counting})
1580+
await scheduler.add_task(
1581+
name="loop-forever", handler="test:counting", schedule={"interval": 60}
1582+
)
1583+
await _write_broken_schedule(
1584+
scheduler,
1585+
"loop-forever",
1586+
schedule_type="no-such-schedule-type",
1587+
schedule_config="{}",
1588+
next_run_at="2000-01-01T00:00:00",
1589+
)
1590+
1591+
for _ in range(3):
1592+
stats = await scheduler._tick()
1593+
assert stats.spawned == 0
1594+
1595+
# Disabled on the first tick, so the following two ticks saw nothing due.
1596+
assert calls == 0
1597+
task = await scheduler.internal_db.get_task("loop-forever")
1598+
assert task.enabled is False
1599+
assert task.last_status == "error"
1600+
1601+
await scheduler.shutdown()
1602+
1603+
1604+
@pytest.mark.asyncio
1605+
async def test_tick_survives_malformed_next_run_at():
1606+
"""A next_run_at that isn't a valid ISO timestamp fails in _lag_seconds,
1607+
before any spawn. The tick must still run the other due task."""
1608+
ds, scheduler = await _make_scheduler()
1609+
1610+
ran = asyncio.Event()
1611+
1612+
async def ok_handler(datasette, config):
1613+
ran.set()
1614+
1615+
async def never(datasette, config): # pragma: no cover - must not be called
1616+
raise AssertionError("task with a malformed next_run_at should not spawn")
1617+
1618+
scheduler.register_handlers("test", {"ok": ok_handler, "never": never})
1619+
await scheduler.add_task(
1620+
name="bad-timestamp", handler="test:never", schedule={"interval": 60}
1621+
)
1622+
await scheduler.add_task(name="fine", handler="test:ok", schedule={"interval": 60})
1623+
1624+
idb = scheduler.internal_db
1625+
# Sorts before the healthy row (so it is evaluated first) but is not a
1626+
# timestamp datetime.fromisoformat can read.
1627+
await idb.update_task("bad-timestamp", next_run_at="2000-01-01 nonsense")
1628+
await idb.update_next_run("fine", "2000-01-01T00:00:01")
1629+
1630+
stats = await scheduler._tick()
1631+
1632+
assert stats.due == 2
1633+
assert stats.disabled == 1
1634+
assert stats.spawned == 1
1635+
1636+
await asyncio.wait_for(ran.wait(), timeout=2.0)
1637+
1638+
bad = await idb.get_task("bad-timestamp")
1639+
assert bad.enabled is False
1640+
assert bad.last_status == "error"
1641+
1642+
await scheduler.shutdown()
1643+
1644+
1645+
@pytest.mark.asyncio
1646+
async def test_tick_does_not_spawn_when_next_run_cannot_be_computed():
1647+
"""next_run is computed before the spawn: a schedule that parses but
1648+
cannot produce a next run must leave the handler untouched rather than
1649+
starting work the tick cannot reschedule."""
1650+
ds, scheduler = await _make_scheduler()
1651+
1652+
calls = 0
1653+
1654+
async def counting(datasette, config):
1655+
nonlocal calls
1656+
calls += 1
1657+
1658+
scheduler.register_handlers("test", {"counting": counting})
1659+
await scheduler.add_task(
1660+
name="exhausted", handler="test:counting", schedule={"interval": 60}
1661+
)
1662+
# Valid type, corrupt config: schedule_from_db raises on the missing key.
1663+
await _write_broken_schedule(
1664+
scheduler,
1665+
"exhausted",
1666+
schedule_config="{}",
1667+
next_run_at="2000-01-01T00:00:00",
1668+
)
1669+
1670+
stats = await scheduler._tick()
1671+
1672+
assert stats.spawned == 0
1673+
assert stats.disabled == 1
1674+
assert calls == 0
1675+
1676+
task = await scheduler.internal_db.get_task("exhausted")
1677+
assert task.enabled is False
1678+
assert task.last_status == "error"
1679+
# next_run_at was never advanced -- but the task is disabled, so it is no
1680+
# longer due and cannot re-fire.
1681+
assert task.next_run_at == "2000-01-01T00:00:00"
1682+
1683+
await scheduler.shutdown()

0 commit comments

Comments
 (0)