Python
Fix automation scheduling: DST-correct 'local' times and off-by-one weekday labels
asklokeshc2adf7320c52
diff --git a/coworker/automation/models.py b/coworker/automation/models.pyindex 4118e88a..186e158f 100644--- a/coworker/automation/models.py+++ b/coworker/automation/models.py@@ -10,7 +10,10 @@ import uuidfrom dataclasses import dataclass, fieldfrom typing import Any, Optional-_DOW = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]+# Indexed by cron day-of-week: 0 and 7 are Sunday, 1 is Monday … 6 is Saturday. Must start+# at Sunday — indexing a Monday-first list by the cron dow labelled every weekly schedule one+# day late (dow 1/Monday rendered "Tuesday", dow 0/Sunday rendered "Monday").+_DOW = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]def _now() -> float:diff --git a/coworker/automation/store.py b/coworker/automation/store.pyindex 116cec75..3c0a558a 100644--- a/coworker/automation/store.py+++ b/coworker/automation/store.py@@ -32,8 +32,12 @@ def compute_next_run(dt = datetime.fromisoformat(sched.fire_at)except ValueError:return None- if dt.tzinfo is None:- dt = dt.replace(tzinfo=_tz(sched.timezone))+ tz = _tz(sched.timezone)+ if dt.tzinfo is None and tz is not None:+ dt = dt.replace(tzinfo=tz)+ # Naive local dt: datetime.timestamp() interprets it in the machine's zone and is+ # DST-aware for the actual fire DATE (via the C library), so a "once" task set in+ # summer for a winter date fires at the right wall-clock instead of an hour off.ts = dt.timestamp()return ts if (task.run_count == 0 and ts > now) else None# cron@@ -43,19 +47,25 @@ def compute_next_run(return Noneif task.max_runs is not None and task.run_count >= task.max_runs:return None- base = datetime.fromtimestamp(now, tz=_tz(sched.timezone))+ tz = _tz(sched.timezone)+ # Local: a naive base makes croniter compute in local wall-clock and .timestamp() apply+ # the correct DST offset per occurrence. A named zone anchors the base in that zone.+ base = datetime.fromtimestamp(now) if tz is None else datetime.fromtimestamp(now, tz=tz)return croniter(sched.cron, base).get_next(datetime).timestamp()def _tz(name: str):- """Resolve a schedule timezone. 'local'/empty → the machine's local zone (right for a- local-first tool: when you say '8:05 PM' you mean *your* clock, not UTC)."""+ """Resolve a schedule timezone to a DST-aware tzinfo, or None for the machine's local+ zone. None (not a fixed-offset tzinfo) is deliberate: naive datetimes let .timestamp()/+ the C library apply local DST at the fire date. A frozen `datetime.now().astimezone()`+ offset baked in whatever offset was in effect at compute time and misfired across a DST+ boundary. An unknown IANA name falls back to local (None) rather than raising."""if not name or name.lower() == "local":- return datetime.now().astimezone().tzinfo+ return Nonetry:return ZoneInfo(name)except Exception:- return datetime.now().astimezone().tzinfo+ return Nonedef _epoch_now() -> float:diff --git a/tests/test_automation.py b/tests/test_automation.pyindex 4fa38a43..80de0e85 100644--- a/tests/test_automation.py+++ b/tests/test_automation.py@@ -34,11 +34,27 @@ def _task(**kw) -> ScheduledTask:# -- model / schedule ----------------------------------------------------------def test_schedule_human():assert Schedule("cron", cron="10 19 * * *").human() == "Every day at ~7:10 PM"- assert "Monday" in Schedule("cron", cron="0 9 * * 0").human()+ # Cron day-of-week: 0 (and 7) = Sunday, 1 = Monday … 6 = Saturday.+ assert "Sunday" in Schedule("cron", cron="0 9 * * 0").human()+ assert "Monday" in Schedule("cron", cron="0 9 * * 1").human()+ assert "Saturday" in Schedule("cron", cron="0 9 * * 6").human()+ assert "Sunday" in Schedule("cron", cron="0 9 * * 7").human() # 7 also Sundayassert Schedule("cron", cron="0 9 5 * *").human() == "Monthly on day 5 at ~9:00 AM"assert Schedule("once", fire_at="2026-07-01T09:00:00").human().startswith("Once at")+def test_weekly_label_matches_croniter_fire_day():+ """The rendered weekday must equal the day croniter actually fires on (regression: a+ Monday-first name list indexed by cron dow labelled every weekly schedule a day late)."""+ from croniter import croniter++ for dow in range(7):+ label = Schedule("cron", cron=f"0 9 * * {dow}").human()+ base = datetime(2026, 7, 20, 0, 0) # a Monday+ fires = croniter(f"0 9 * * {dow}", base).get_next(datetime)+ assert fires.strftime("%A") in label, (dow, label, fires.strftime("%A"))++def test_task_gets_own_thread_id():t = _task()assert t.task_session_id == f"__task__{t.id}"@@ -69,6 +85,27 @@ def test_compute_next_run_once_in_past_is_none():assert compute_next_run(t) is None+def test_compute_next_run_once_local_is_dst_aware(monkeypatch):+ """A one-time 'local' task set while EDT is in effect but firing on a winter EST date must+ fire at the requested wall-clock, not an hour off. Binding the naive datetime to the+ offset in effect at compute time (the old bug) misfired by the DST delta."""+ import time as _time++ monkeypatch.setenv("TZ", "America/New_York")+ _time.tzset()+ try:+ # Compute "now" during summer (EDT, -04:00); the task fires on a winter date (EST).+ summer_now = datetime(2026, 7, 1, 12, 0).timestamp()+ t = _task(schedule=Schedule(kind="once", fire_at="2026-12-25T08:00:00"))+ nxt = compute_next_run(t, after=summer_now)+ fires_local = datetime.fromtimestamp(nxt)+ assert (fires_local.hour, fires_local.minute) == (8, 0)+ assert fires_local.date() == datetime(2026, 12, 25, 8, 0).date()+ finally:+ monkeypatch.delenv("TZ", raising=False)+ _time.tzset()++# -- store ---------------------------------------------------------------------def test_store_crud_and_due(tmp_path):store = TaskStore(tmp_path / "auto.db")