Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(scheduler): a slot the app slept through is missed, never caught up at boot (BUG-212)

rubenluetke10-beep0b66f51fcec0
diff --git a/conductor/core/scheduler.py b/conductor/core/scheduler.py
index ae11faa1a4..6077d3db83 100644
--- a/conductor/core/scheduler.py
+++ b/conductor/core/scheduler.py
@@ -13,7 +13,12 @@ import contextlib
import logging
import time
from datetime import datetime
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Final
+
+#: Misfire grace — a slot later than this is skipped, not caught up (BUG-212).
+#: Conductor is a standalone package, so this mirrors ``jarvis.core.misfire``
+#: instead of importing it; ``tests/unit/conductor`` pins the two together.
+MISFIRE_GRACE_NS: Final[int] = 30 * 60 * 1_000_000_000
try:
from croniter import croniter # type: ignore
@@ -88,6 +93,21 @@ class Scheduler:
await self._store.set_next_run(row["id"], stored_next)
if stored_next <= now_ns:
+ if stored_next + MISFIRE_GRACE_NS < now_ns:
+ # BUG-212: the slot passed while the app was not
+ # running — skip to the next occurrence, never catch
+ # up a stale slot hours later.
+ log.warning(
+ "Conductor job %r missed its slot (%.0f min late) — "
+ "skipped, not caught up",
+ row.get("name") or row["id"],
+ (now_ns - stored_next) / 60e9,
+ )
+ next_after = _compute_next(sched_type, expr, now_ns)
+ await self._store.set_next_run(row["id"], next_after)
+ if next_after and (upcoming_min is None or next_after < upcoming_min):
+ upcoming_min = next_after
+ continue
due_ids.append(row["id"])
# Set a new next_run_at_ns before we trigger, so slow
# execution doesn't cause a double trigger.
diff --git a/docs/adr/0005-lightweight-scheduler.md b/docs/adr/0005-lightweight-scheduler.md
index db3be1eb69..40bee58d2d 100644
--- a/docs/adr/0005-lightweight-scheduler.md
+++ b/docs/adr/0005-lightweight-scheduler.md
@@ -69,3 +69,19 @@ The event subscriber routes events matching the `event_selector` of an `on_event
- Time zone: all `due_at_ns` are UTC in the DB. User input "in two hours" is computed relative to `time.time_ns()` → no TZ questions. "Tomorrow 9am" comes via `zoneinfo.ZoneInfo` from the system zone — the trigger parser translates it.
- Drift on long delays (days): not relevant, as long as `await asyncio.wait_for` with TimeoutError tolerance covers it.
+
+## Amendment 2026-09-02 — misfire handling (BUG-212)
+
+"Misfire handling" above was listed as not required. It was: a slot the app
+was not running for (box off, asleep, restarted hours later) was caught up at
+the first tick after boot, which put a 07:30 routine at 15:04 and 20:49 on
+different days. The rule now lives in `jarvis/core/misfire.py` and binds every
+scheduler in the repo (tasks, workflows, Conductor):
+
+- a recurring slot late by at most `MISFIRE_GRACE_S` (30 min) still fires;
+- an older slot is **missed**: recorded (a `missed` workflow run / a `missed`
+ task step), never run, and the schedule continues from the next occurrence
+ relative to now — for `every` tasks on their `start_at` grid, never
+ `now + interval`;
+- one-shot triggers (`after_delay`, `at_time`) are exempt and keep firing late:
+ a reminder survives a crash (H9) and has no next occurrence to skip to.
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index a4619ce46c..f7b758aab5 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -1438,7 +1438,9 @@ class WorkflowScheduled(Event):
"""
workflow_id: str = ""
next_run_ns: int = 0
- reason: str = "cron_next" # "cron_next" | "registered" | "toggled_on"
+ # "cron_next" | "registered" | "toggled_on" | "missed" — the last one says
+ # the previous slot passed while the app was down and was skipped (BUG-212).
+ reason: str = "cron_next"
@dataclass(frozen=True, slots=True)
diff --git a/jarvis/core/misfire.py b/jarvis/core/misfire.py
new file mode 100644
index 0000000000..be74995d5d
--- /dev/null
+++ b/jarvis/core/misfire.py
@@ -0,0 +1,41 @@
+"""Misfire policy shared by every scheduler in the app (BUG-212).
+
+A scheduled slot the app was not running for — the box was off, asleep, or
+the process was restarted hours later — must NOT be "caught up" whenever the
+process next comes up. That is how the 07:30 Morning Briefing arrived at
+10:15, 15:04 and 20:49 on different days: the slot was stored the evening
+before, the app was not up at 07:30, and the first scheduler tick after boot
+fired the stale slot immediately.
+
+The rule, the same for the workflow cron scheduler (``jarvis/workflows``),
+the recurring task scheduler (``jarvis/tasks``) and the Conductor:
+
+* a slot that is late by at most :data:`MISFIRE_GRACE_S` still fires — a
+ routine due at 07:30 on a machine that took ten minutes to boot is still a
+ morning routine;
+* a slot older than that is **missed**: it is recorded as such, never run,
+ and the schedule continues from the NEXT occurrence relative to now.
+
+One-shot triggers (a reminder "in 30 seconds", an ``at_time`` task) are not
+covered by this rule and keep firing late: a reminder must survive a crash
+(ADR-0005, H9) and there is no next occurrence to skip to.
+"""
+from __future__ import annotations
+
+from typing import Final
+
+#: How late a recurring slot may fire before it counts as missed. Thirty
+#: minutes covers a slow boot or a short sleep; anything longer is no longer
+#: the slot the user asked for (a "morning" briefing at 15:00 is not one).
+MISFIRE_GRACE_S: Final[float] = 30 * 60.0
+MISFIRE_GRACE_NS: Final[int] = int(MISFIRE_GRACE_S * 1e9)
+
+
+def is_missed(due_ns: int, now_ns: int, *, grace_ns: int = MISFIRE_GRACE_NS) -> bool:
+ """True when a slot due at ``due_ns`` is too old to still fire at ``now_ns``."""
+ return due_ns + grace_ns < now_ns
+
+
+def late_by_s(due_ns: int, now_ns: int) -> float:
+ """Seconds between the slot and now — for the missed-run record."""
+ return max(0.0, (now_ns - due_ns) / 1e9)
diff --git a/jarvis/tasks/scheduler.py b/jarvis/tasks/scheduler.py
index 745b2ac8ff..87ea3f53d0 100644
--- a/jarvis/tasks/scheduler.py
+++ b/jarvis/tasks/scheduler.py
@@ -28,6 +28,7 @@ from typing import TYPE_CHECKING, Any, Protocol
from jarvis.core.bus import EventBus
from jarvis.core.events import Event, TaskScheduled
+from jarvis.core.misfire import is_missed, late_by_s
from jarvis.tasks.schema import PAUSABLE_TRIGGER_TYPES, TERMINAL_STATES, TaskSpec
if TYPE_CHECKING:
@@ -384,15 +385,52 @@ class TaskScheduler:
if self._hydrated:
return
rows = await self._store.all_pending_scheduled()
+ now_ns = time.time_ns()
for row in rows:
spec = await self._store.get_spec(row["id"])
if spec is None:
continue
stored_due = row.get("due_at_ns")
+ if (
+ spec.trigger.type == "every"
+ and stored_due is not None
+ and is_missed(int(stored_due), now_ns)
+ ):
+ # BUG-212: a recurring slot that passed while the app was
+ # down is missed, not caught up at boot. Skip to the next
+ # occurrence on the task's own grid.
+ stored_due = await self._skip_missed_every(
+ row["id"], spec, int(stored_due), now_ns,
+ )
self._register_in_memory(spec, row["id"],
stored_due_at_ns=stored_due)
self._hydrated = True
+ async def _skip_missed_every(
+ self, task_id: str, spec: TaskSpec, due_ns: int, now_ns: int,
+ ) -> int:
+ """Record a missed recurring slot and return the next due time."""
+ next_due = next_every_due_ns(spec, now_ns)
+ late_s = late_by_s(due_ns, now_ns)
+ log.warning(
+ "Task %r missed its slot (%.0f min late) — skipped to the next "
+ "occurrence, not caught up", spec.title, late_s / 60,
+ )
+ try:
+ await self._store.append_step(
+ task_id, "log",
+ {
+ "event": "missed",
+ "due_at_ns": due_ns,
+ "late_by_s": int(late_s),
+ "next_due_at_ns": next_due,
+ },
+ )
+ except Exception: # noqa: BLE001
+ log.exception("Could not record the missed slot for task %s", task_id)
+ await self._store.set_next_due(task_id, next_due)
+ return next_due
+
def _register_in_memory(
self,
spec: TaskSpec,
@@ -497,18 +535,33 @@ class TaskScheduler:
blocks the scheduler loop.
"""
while self._heap and self._heap[0][0] <= now_ns:
- _due, tid = heapq.heappop(self._heap)
+ due, tid = heapq.heappop(self._heap)
self._known.discard(tid)
spec = await self._store.get_spec(tid)
- await self._dispatch_runner(tid)
if spec is not None and spec.trigger.type == "every":
+ if is_missed(due, now_ns):
+ # The process lived but did not tick (machine asleep,
+ # loop blocked): same rule as at boot — skip, never
+ # catch up (BUG-212).
+ next_due = await self._skip_missed_every(tid, spec, due, now_ns)
+ heapq.heappush(self._heap, (next_due, tid))
+ self._known.add(tid)
+ continue
+ await self._dispatch_runner(tid)
await self._rearm_every(tid, spec, now_ns)
+ continue
+ await self._dispatch_runner(tid)
async def _rearm_every(self, task_id: str, spec: TaskSpec, now_ns: int) -> None:
- """Re-insert a recurring task at ``now + interval`` and persist the
+ """Re-insert a recurring task at its next occurrence and persist the
new due time so a restart picks the schedule back up.
+
+ Anchored tasks stay on their wall-clock grid (``start_at + k *
+ interval``); ``now + interval`` used to be the rule for every task,
+ so one late firing shifted a daily 07:30 automation permanently
+ (BUG-212). Unanchored tasks still re-arm one interval from now.
"""
- next_due = now_ns + int(spec.trigger.interval_seconds * 1e9)
+ next_due = next_every_due_ns(spec, now_ns)
heapq.heappush(self._heap, (next_due, task_id))
self._known.add(task_id)
await self._store.set_next_due(task_id, next_due)
diff --git a/jarvis/workflows/scheduler.py b/jarvis/workflows/scheduler.py
index 88b35d3994..0a1a747997 100644
--- a/jarvis/workflows/scheduler.py
+++ b/jarvis/workflows/scheduler.py
@@ -5,6 +5,10 @@ A single ``asyncio`` loop polls the workflow list, computes the next
``next_run_at_ns`` for each active cron workflow, and sleeps until the
earliest one. On firing: ``runner.trigger(workflow_id, trigger_reason="cron")``.
+A slot that passed while the app was not running is NOT caught up: past the
+shared misfire grace (``jarvis.core.misfire``) it is recorded as a ``missed``
+run and the schedule continues from the next occurrence (BUG-212).
+
This is deliberately not the same code-path architecture as skills-cron
(``skills/trigger_matcher.run_cron_scheduler``) — skills yield an
``AsyncIterator`` that the supervisor consumes; here the scheduler fires
@@ -28,6 +32,7 @@ except Exception: # pragma: no cover
from jarvis.core.bus import EventBus
from jarvis.core.events import AnnouncementRequested, WorkflowScheduled
+from jarvis.core.misfire import is_missed, late_by_s
from jarvis.voice.action_phrases import action_phrase, resolve_ambient_language
from .runner import FailureAnnouncer
@@ -145,6 +150,20 @@ class WorkflowScheduler:
)
if stored_next <= now_ns:
+ if is_missed(stored_next, now_ns):
+ # BUG-212: the slot passed while the app was not running.
+ # Catching it up hours later is what put the 07:30
+ # Morning Briefing at 15:04 and 20:49. Record the miss,
+ # skip to the next occurrence from NOW, never run it.
+ next_after = await self._skip_missed(
+ wid, cron_expr, stored_next, now_ns,
+ name=_name_for(rows, wid),
+ )
+ if next_after is not None and (
+ upcoming_min_ns is None or next_after < upcoming_min_ns
+ ):
+ upcoming_min_ns = next_after
+ continue
due.append((stored_next, wid))
else:
if upcoming_min_ns is None or stored_next < upcoming_min_ns:
@@ -187,6 +206,47 @@ class WorkflowScheduler:
delta_s = max(1.0, (upcoming_min_ns - time.time_ns()) / 1e9)
return min(delta_s, 60.0)
+ async def _skip_missed(
+ self,
+ wid: str,
+ cron_expr: str,
+ stored_next: int,
+ now_ns: int,
+ *,
+ name: str,
+ ) -> int | None:
+ """Record a missed slot and move the workflow to its next occurrence.
+
+ Returns the new ``next_run_at_ns`` (``None`` for a broken cron
+ expression). The missed run row is best effort: a store without
+ ``record_missed_run`` (older fakes) still gets rescheduled, so a
+ bookkeeping failure can never turn back into a catch-up firing.
+ """
+ late_s = late_by_s(stored_next, now_ns)
+ log.warning(
+ "Workflow %r missed its slot at %s (%.0f min late) — skipped, "
+ "not caught up",
+ name, _iso_local(stored_next), late_s / 60,
+ )
+ record = getattr(self._store, "record_missed_run", None)
+ if callable(record):
+ try:
+ await record(wid, due_at_ns=stored_next, late_by_s=late_s)
+ except Exception: # noqa: BLE001
+ log.exception("Could not record the missed run for workflow %s", wid)
+ next_after = _compute_next_cron_ns(cron_expr, now_ns)
+ await self._store.set_next_run(wid, next_after)
+ if next_after is not None:
+ await self._bus.publish(
+ WorkflowScheduled(
+ workflow_id=wid,
+ next_run_ns=next_after,
+ reason="missed",
+ source_layer="workflows.scheduler",
+ )
+ )
+ return next_after
+
# ------------------------------------------------------------------
async def _announce(self, key: str, phrase_key: str, **fmt: object) -> None:
@@ -226,6 +286,14 @@ class WorkflowScheduler:
# Helpers
# ----------------------------------------------------------------------
+def _iso_local(ns: int) -> str:
+ """Local wall-clock rendering of a ns timestamp for log lines."""
+ try:
+ return datetime.fromtimestamp(ns / 1e9).astimezone().isoformat(timespec="minutes")
+ except (OverflowError, OSError, ValueError):
+ return str(ns)
+
+
def _compute_next_cron_ns(cron_expr: str, base_ns: int) -> int | None:
"""Next fire time in ns, or None if the cron syntax is broken."""
if not _HAVE_CRONITER:
diff --git a/jarvis/workflows/schema.py b/jarvis/workflows/schema.py
index 6662a9970a..19cbb43951 100644
--- a/jarvis/workflows/schema.py
+++ b/jarvis/workflows/schema.py
@@ -75,6 +75,15 @@ class BrainPromptStep(BaseModel):
label: str = Field(default="", max_length=128)
prompt: str = Field(min_length=1, max_length=16_384)
max_output_chars: int = Field(default=2000, ge=100, le=50_000)
+ #: Tool allowlist for the isolated turn — the same grant names the
+ #: Automations use (``search_web``, ``gmail``, ``google_calendar``,
+ #: ``wiki-recall``, a plugin prefix like ``github``). A granted tool that
+ #: is not connected on this install is skipped, so the step degrades to
+ #: whatever is live instead of failing (BUG-212: the seed briefing had no
+ #: tools at all and could only greet).
+ tools: tuple[str, ...] = Field(default_factory=tuple, max_length=32)
+ #: ``fast``/``auto`` = the provider's fast model, ``deep`` = its deep one.
+ model_tier: Literal["fast", "deep", "auto"] = "auto"
class HarnessDispatchStep(BaseModel):
@@ -182,8 +191,12 @@ WorkflowRunState = Literal[
"completed", # all steps succeeded
"failed", # a step raised
"cancelled", # manually cancelled
+ "missed", # the cron slot passed while the app was not running (BUG-212)
]
+#: Run states that never change again. Mirrored in ``hooks/useWorkflows.ts``.
+WORKFLOW_RUN_TERMINAL_STATES: tuple[str, ...] = ("completed", "failed", "cancelled", "missed")
+
class WorkflowRun(BaseModel):
"""A concrete run of a WorkflowDef. Persisted in ``workflow_runs``.
diff --git a/jarvis/workflows/store.py b/jarvis/workflows/store.py
index 565f88eb6a..b6ed3de3ff 100644
--- a/jarvis/workflows/store.py
+++ b/jarvis/workflows/store.py
@@ -13,7 +13,7 @@ from typing import Any
import aiosqlite
-from .schema import WorkflowDef
+from .schema import WORKFLOW_RUN_TERMINAL_STATES, WorkflowDef
SCHEMA_FILE = Path(__file__).parent / "schema.sql"
@@ -199,7 +199,7 @@ class WorkflowStore:
) -> None:
conn = self._require_conn()
now = time.time_ns()
- if state in ("completed", "failed", "cancelled"):
+ if state in WORKFLOW_RUN_TERMINAL_STATES:
await conn.execute(
"""
UPDATE workflow_runs
@@ -214,6 +214,45 @@ class WorkflowStore:
(state, error, run_id),
)
+ async def record_missed_run(
+ self,
+ workflow_id: str,
+ *,
+ due_at_ns: int,
+ late_by_s: float,
+ ) -> str:
+ """Persist a cron slot that passed while the app was not running.
+
+ A terminal ``missed`` run row, timestamped at the slot it stands for,
+ so the Runs list says WHY there was no 07:30 briefing instead of
+ showing nothing (BUG-212). The workflow's ``last_run`` is updated the
+ same way a real run would, so the card reads "missed" until the next
+ occurrence ran.
+ """
+ conn = self._require_conn()
+ from uuid import uuid4
+ run_id = str(uuid4())
+ now = time.time_ns()
+ minutes = int(late_by_s // 60)
+ await conn.execute(
+ """
+ INSERT INTO workflow_runs
+ (id, workflow_id, state, trigger, started_at_ns, finished_at_ns,
+ error, input_json)
+ VALUES (?, ?, 'missed', 'cron', ?, ?, ?, '{}')
+ """,
+ (
+ run_id,
+ workflow_id,
+ due_at_ns,
+ now,
+ f"Slot missed: the app was not running at the scheduled time "
+ f"({minutes} min late when it came up); skipped to the next occurrence.",
+ ),
+ )
+ await self.set_last_run(workflow_id, due_at_ns, "missed")
+ return run_id
+
async def list_runs(
self,
workflow_id: str | None = None,
diff --git a/tests/unit/conductor/test_misfire.py b/tests/unit/conductor/test_misfire.py
new file mode 100644
index 0000000000..214ec353f6
--- /dev/null
+++ b/tests/unit/conductor/test_misfire.py
@@ -0,0 +1,67 @@
+"""BUG-212 — the Conductor skips a stale slot instead of catching it up.
+
+The Conductor is a standalone package and carries its own copy of the
+misfire grace; the first test pins it to ``jarvis.core.misfire`` so the two
+schedulers can never disagree about what "too late" means.
+"""
+from __future__ import annotations
+
+import time
+from typing import Any
+
+from conductor.core.scheduler import MISFIRE_GRACE_NS, Scheduler
+from jarvis.core.misfire import MISFIRE_GRACE_NS as JARVIS_GRACE_NS
+
+_HOUR_NS = 3_600 * 1_000_000_000
+
+
+def test_the_conductor_grace_matches_the_app_wide_policy() -> None:
+ assert MISFIRE_GRACE_NS == JARVIS_GRACE_NS
+
+
+class _Store:
+ def __init__(self, next_run_at_ns: int) -> None:
+ self.rows: list[dict[str, Any]] = [{
+ "id": "job-1", "name": "Daily Standup", "enabled": 1,
+ "schedule_type": "cron", "schedule_expr": "0 9 * * 1-5",
+ "next_run_at_ns": next_run_at_ns,
+ }]
+
+ async def list_jobs(self) -> list[dict[str, Any]]:
+ return list(self.rows)
+
+ async def set_next_run(self, jid: str, ns: int | None) -> None:
+ self.rows[0]["next_run_at_ns"] = ns
+
+
+class _Runner:
+ def __init__(self) -> None:
+ self.triggered: list[str] = []
+
+ async def trigger(self, jid: str, *, trigger: str) -> str:
+ self.triggered.append(jid)
+ return "run"
+
+
+async def test_a_stale_slot_is_skipped_not_run() -> None:
+ now = time.time_ns()
+ store = _Store(now - 6 * _HOUR_NS) # 09:00 seen at 15:00
+ runner = _Runner()
+ scheduler = Scheduler(store, runner) # type: ignore[arg-type]
+
+ await scheduler._tick()
+
+ assert runner.triggered == []
+ assert store.rows[0]["next_run_at_ns"] > now
+
+
+async def test_a_slot_inside_the_grace_window_runs() -> None:
+ now = time.time_ns()
+ store = _Store(now - 5 * 60 * 1_000_000_000)
+ runner = _Runner()
+ scheduler = Scheduler(store, runner) # type: ignore[arg-type]
+
+ await scheduler._tick()
+
+ assert runner.triggered == ["job-1"]
+ assert store.rows[0]["next_run_at_ns"] > now
diff --git a/tests/unit/tasks/test_scheduler_misfire.py b/tests/unit/tasks/test_scheduler_misfire.py
new file mode 100644
index 0000000000..3771e9584e
--- /dev/null
+++ b/tests/unit/tasks/test_scheduler_misfire.py
@@ -0,0 +1,211 @@
+"""BUG-212 — recurring automations stay on their grid and never catch up.
+
+Two defects in the recurring (``every``) path:
+
+* ``hydrate()`` re-inserted a stale ``due_at_ns`` as-is, so a daily 07:30
+ automation the app slept through fired the moment the app came up;
+* ``_rearm_every`` re-armed at ``now + interval`` instead of the wall-clock
+ grid, so that one late firing shifted the schedule permanently.
+
+One-shot triggers keep their ADR-0005 H9 behaviour: a reminder due while the
+app was down still fires at boot — there is no next occurrence to skip to.
+"""
+from __future__ import annotations
+
+import asyncio
+import heapq
+import json
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.core.bus import EventBus
+from jarvis.core.misfire import MISFIRE_GRACE_NS
+from jarvis.tasks.scheduler import TaskScheduler, parse_iso_timestamp_to_ns
+from jarvis.tasks.schema import SpeakAction, TaskSpec, TriggerAtTime, TriggerEvery
+from jarvis.tasks.store import TaskStore
+
+_DAY_S = 86_400.0
+_DAY_NS = int(_DAY_S * 1e9)
+
+
+class RecordingRunner:
+ def __init__(self) -> None:
+ self.dispatched: list[str] = []
+ self.gate = asyncio.Event()
+
+ async def run(self, task_id: str, *_a: Any, **_k: Any) -> None:
+ self.dispatched.append(task_id)
+ self.gate.set()
+
+
+async def store(tmp_path: Path):
+ s = TaskStore(tmp_path / "misfire.db")
+ await s.init()
+ try:
+ yield s
+ finally:
+ await s.close()
+
+
+def _daily_at(anchor: datetime) -> TaskSpec:
+ return TaskSpec(
+ title="Morning Brief",
+ trigger=TriggerEvery(
+ interval_seconds=_DAY_S,
+ start_at=anchor.isoformat(timespec="seconds"),
+ ),
+ action=SpeakAction(text="brief"),
+ )
+
+
+async def _missed_steps(store: TaskStore, task_id: str) -> list[dict[str, Any]]:
+ conn = store._require_conn()
+ cur = await conn.execute(
+ "SELECT payload_json FROM task_steps WHERE task_id = ? ORDER BY seq", (task_id,)
+ )
+ rows = await cur.fetchall()
+ await cur.close()
+ payloads = [json.loads(r["payload_json"]) for r in rows]
+ return [p for p in payloads if p.get("event") == "missed"]
+
+
+# ----------------------------------------------------------------------
+# hydrate — the boot path
+# ----------------------------------------------------------------------
+
+async def test_hydrate_skips_a_stale_daily_slot_to_the_next_grid_point(
+ store: TaskStore,
+) -> None:
+ """The 07:30 automation the app slept through does not fire at 15:04."""
+ now = datetime.now(UTC).replace(microsecond=0)
+ # Daily grid anchored days ago; the slot two days in is nine hours old.
+ anchor = now - timedelta(days=2, hours=9)
+ spec = _daily_at(anchor)
+ task_id = await store.insert(spec)
+ stale_due = parse_iso_timestamp_to_ns(anchor.isoformat()) + 2 * _DAY_NS
+ assert stale_due < parse_iso_timestamp_to_ns(now.isoformat()) - MISFIRE_GRACE_NS
+ await store.set_next_due(task_id, stale_due)
+
+ runner = RecordingRunner()
+ scheduler = TaskScheduler(store=store, bus=EventBus(), runner=runner)
+ await scheduler.hydrate()
+
+ assert scheduler._heap, "the task is still scheduled"
+ due_ns, tid = scheduler._heap[0]
+ assert tid == task_id
+ expected = parse_iso_timestamp_to_ns(anchor.isoformat()) + 3 * _DAY_NS
+ assert due_ns == expected, "next occurrence on the anchor's grid, not now+interval"
+ assert due_ns > parse_iso_timestamp_to_ns(now.isoformat())
+
+ row = await store.get(task_id)
+ assert row is not None and row["due_at_ns"] == expected
+ missed = await _missed_steps(store, task_id)
+ assert len(missed) == 1
+ assert missed[0]["due_at_ns"] == stale_due
+ assert missed[0]["next_due_at_ns"] == expected
+ assert runner.dispatched == []
+
+
+async def test_hydrate_keeps_a_slot_inside_the_grace_window(
+ store: TaskStore,
+) -> None:
+ now = datetime.now(UTC).replace(microsecond=0)
+ spec = _daily_at(now - timedelta(days=2))
+ task_id = await store.insert(spec)
+ recent = parse_iso_timestamp_to_ns(now.isoformat()) - MISFIRE_GRACE_NS // 2
+ await store.set_next_due(task_id, recent)
+
+ scheduler = TaskScheduler(store=store, bus=EventBus(), runner=RecordingRunner())
+ await scheduler.hydrate()
+
+ assert scheduler._heap[0] == (recent, task_id)
+ assert await _missed_steps(store, task_id) == []
+
+
+async def test_hydrate_still_fires_a_stale_one_shot_reminder(
+ store: TaskStore,
+) -> None:
+ """ADR-0005 H9: a reminder must survive a crash, however late."""
+ past = datetime.now(UTC) - timedelta(hours=3)
+ spec = TaskSpec(
+ title="reminder",
+ trigger=TriggerAtTime(iso_timestamp=past.isoformat(timespec="seconds")),
+ action=SpeakAction(text="x"),
+ )
+ task_id = await store.insert(spec)
+
+ runner = RecordingRunner()
+ scheduler = TaskScheduler(store=store, bus=EventBus(), runner=runner)
+ await scheduler.hydrate()
+ await scheduler._drain_due_tasks(parse_iso_timestamp_to_ns(datetime.now(UTC).isoformat()))
+ await asyncio.wait_for(runner.gate.wait(), timeout=1.0)
+
+ assert runner.dispatched == [task_id]
+
+
+# ----------------------------------------------------------------------
+# re-arm — the running path
+# ----------------------------------------------------------------------
+
+async def test_rearm_stays_on_the_wall_clock_grid(store: TaskStore) -> None:
+ """Firing five minutes late must not move tomorrow's slot by five minutes."""
+ now = datetime.now(UTC).replace(microsecond=0)
+ anchor = now - timedelta(minutes=5)
+ spec = _daily_at(anchor)
+ task_id = await store.insert(spec)
+ anchor_ns = parse_iso_timestamp_to_ns(anchor.isoformat())
+ await store.set_next_due(task_id, anchor_ns)
+
+ runner = RecordingRunner()
+ scheduler = TaskScheduler(store=store, bus=EventBus(), runner=runner)
+ await scheduler.hydrate()
+ await scheduler._drain_due_tasks(anchor_ns + 5 * 60 * 1_000_000_000)
+ await asyncio.wait_for(runner.gate.wait(), timeout=1.0)
+
+ assert runner.dispatched == [task_id]
+ assert scheduler._heap[0] == (anchor_ns + _DAY_NS, task_id)
+ row = await store.get(task_id)
+ assert row is not None and row["due_at_ns"] == anchor_ns + _DAY_NS
+
+
+async def test_drain_skips_a_slot_the_loop_slept_through(store: TaskStore) -> None:
+ """The process lived but did not tick (laptop lid closed): same rule."""
+ now = datetime.now(UTC).replace(microsecond=0)
+ anchor = now - timedelta(hours=9)
+ spec = _daily_at(anchor)
+ task_id = await store.insert(spec)
+ anchor_ns = parse_iso_timestamp_to_ns(anchor.isoformat())
+
+ runner = RecordingRunner()
+ scheduler = TaskScheduler(store=store, bus=EventBus(), runner=runner)
+ heapq.heappush(scheduler._heap, (anchor_ns, task_id))
+ scheduler._known.add(task_id)
+
+ await scheduler._drain_due_tasks(parse_iso_timestamp_to_ns(now.isoformat()))
+
+ assert runner.dispatched == []
+ assert scheduler._heap[0] == (anchor_ns + _DAY_NS, task_id)
+ assert len(await _missed_steps(store, task_id)) == 1
+
+
+async def test_unanchored_task_rearms_one_interval_from_now(store: TaskStore) -> None:
+ spec = TaskSpec(
+ title="hourly",
+ trigger=TriggerEvery(interval_seconds=3600.0),
+ action=SpeakAction(text="x"),
+ )
+ task_id = await store.insert(spec)
+ runner = RecordingRunner()
+ scheduler = TaskScheduler(store=store, bus=EventBus(), runner=runner)
+ now_ns = parse_iso_timestamp_to_ns(datetime.now(UTC).isoformat())
+ heapq.heappush(scheduler._heap, (now_ns - 1, task_id))
+ scheduler._known.add(task_id)
+
+ await scheduler._drain_due_tasks(now_ns)
+ await asyncio.wait_for(runner.gate.wait(), timeout=1.0)
+
+ assert scheduler._heap[0] == (now_ns + 3600 * 1_000_000_000, task_id)
diff --git a/tests/unit/workflows/test_misfire.py b/tests/unit/workflows/test_misfire.py
new file mode 100644
index 0000000000..c244fadf33
--- /dev/null
+++ b/tests/unit/workflows/test_misfire.py
@@ -0,0 +1,185 @@
+"""BUG-212 — a cron slot the app slept through is missed, not caught up.
+
+Forensics (data-dev/workflows.sqlite, 2026-08-25 … 2026-09-02): every
+"Morning Briefing" run started at the exact second the app booted — 10:15,
+20:49, 15:04, 11:18 — because the scheduler fired any stored ``next_run_at_ns``
+that was ``<= now``, however stale. One briefing a day, at a random hour.
+
+The rule now: within :data:`jarvis.core.misfire.MISFIRE_GRACE_S` the slot
+still fires (a slow boot at 07:31 is still the morning); older than that it
+is recorded as a ``missed`` run, the schedule continues from the NEXT
+occurrence, and the runner is never called.
+
+Fakes throughout — a real store on tmp_path, a recording runner, no network.
+"""
+from __future__ import annotations
+
+import time
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import WorkflowScheduled
+from jarvis.core.misfire import MISFIRE_GRACE_NS, is_missed, late_by_s
+from jarvis.workflows.scheduler import WorkflowScheduler
+from jarvis.workflows.schema import CronTrigger, SpeakStep, WorkflowDef
+from jarvis.workflows.store import WorkflowStore
+
+_HOUR_NS = 3_600 * 1_000_000_000
+
+
+async def store(tmp_path: Path) -> WorkflowStore:
+ s = WorkflowStore(tmp_path / "wf.sqlite")
+ await s.init()
+ yield s
+ await s.close()
+
+
+class _RecordingRunner:
+ def __init__(self) -> None:
+ self.triggered: list[str] = []
+
+ async def trigger(self, workflow_id: str, *, trigger_reason: str) -> str:
+ self.triggered.append(workflow_id)
+ return "run-1"
+
+
+def _scheduled_events(bus: EventBus) -> list[WorkflowScheduled]:
+ seen: list[WorkflowScheduled] = []
+ bus.subscribe(WorkflowScheduled, seen.append)
+ return seen
+
+
+async def _daily_briefing(store: WorkflowStore, *, next_run_at_ns: int) -> str:
+ wf = WorkflowDef(
+ name="Morning Briefing",
+ trigger=CronTrigger(expression="30 7 * * *"),
+ steps=(SpeakStep(text="good morning"),),
+ )
+ wid = await store.upsert_workflow(wf)
+ await store.set_next_run(wid, next_run_at_ns)
+ return wid
+
+
+# ----------------------------------------------------------------------
+# The policy itself
+# ----------------------------------------------------------------------
+
+def test_a_slot_inside_the_grace_window_is_not_missed() -> None:
+ now = time.time_ns()
+ assert not is_missed(now - MISFIRE_GRACE_NS // 2, now)
+ assert not is_missed(now, now)
+
+
+def test_a_slot_older_than_the_grace_window_is_missed() -> None:
+ now = time.time_ns()
+ assert is_missed(now - MISFIRE_GRACE_NS - 1, now)
+ assert is_missed(now - 8 * _HOUR_NS, now) # 07:30 seen at 15:30
+
+
+def test_late_by_is_in_seconds_and_never_negative() -> None:
+ now = time.time_ns()
+ assert late_by_s(now - 90 * 1_000_000_000, now) == pytest.approx(90.0)
+ assert late_by_s(now + _HOUR_NS, now) == 0.0
+
+
+# ----------------------------------------------------------------------
+# The scheduler
+# ----------------------------------------------------------------------
+
+async def test_a_stale_slot_is_skipped_and_recorded_as_missed(
+ store: WorkflowStore,
+) -> None:
+ """The 07:30 seen at 15:04 must not speak at 15:04."""
+ bus = EventBus()
+ events = _scheduled_events(bus)
+ runner = _RecordingRunner()
+ now = time.time_ns()
+ stale = now - 8 * _HOUR_NS
+ wid = await _daily_briefing(store, next_run_at_ns=stale)
+
+ scheduler = WorkflowScheduler(store=store, runner=runner, bus=bus)
+ await scheduler._tick()
+
+ assert runner.triggered == [], "a missed slot must never reach the runner"
+
+ row = await store.get_workflow(wid)
+ assert row is not None
+ assert row["next_run_at_ns"] > now, "the schedule continues from the next slot"
+ assert row["last_run_state"] == "missed"
+ assert row["last_run_at_ns"] == stale, "the miss is dated at the slot, not now"
+
+ runs = await store.list_runs(wid)
+ assert [r["state"] for r in runs] == ["missed"]
+ assert runs[0]["started_at_ns"] == stale
+ assert runs[0]["finished_at_ns"] >= now
+ assert "not running" in (runs[0]["error"] or "")
+
+ missed = [e for e in events if e.reason == "missed"]
+ assert len(missed) == 1 and missed[0].workflow_id == wid
+ assert missed[0].next_run_ns == row["next_run_at_ns"]
+
+
+async def test_a_slot_inside_the_grace_window_still_fires(
+ store: WorkflowStore,
+) -> None:
+ """A machine that took ten minutes to boot still gets its briefing."""
+ bus = EventBus()
+ runner = _RecordingRunner()
+ now = time.time_ns()
+ wid = await _daily_briefing(store, next_run_at_ns=now - 10 * 60 * 1_000_000_000)
+
+ scheduler = WorkflowScheduler(store=store, runner=runner, bus=bus)
+ await scheduler._tick()
+
+ assert runner.triggered == [wid]
+ runs = await store.list_runs(wid)
+ assert all(r["state"] != "missed" for r in runs)
+
+
+async def test_a_missed_slot_is_recorded_once_and_the_next_one_fires_on_time(
+ store: WorkflowStore,
+) -> None:
+ """Second tick: nothing new to skip, nothing to fire yet."""
+ bus = EventBus()
+ runner = _RecordingRunner()
+ now = time.time_ns()
+ wid = await _daily_briefing(store, next_run_at_ns=now - 8 * _HOUR_NS)
+
+ scheduler = WorkflowScheduler(store=store, runner=runner, bus=bus)
+ await scheduler._tick()
+ await scheduler._tick()
+
+ assert runner.triggered == []
+ assert len(await store.list_runs(wid)) == 1
+
+
+async def test_a_store_without_missed_run_bookkeeping_still_reschedules() -> None:
+ """The reschedule must never depend on the record being writable —
+ a bookkeeping failure that turned back into a catch-up firing would be
+ the original bug again."""
+
+ class _BareStore:
+ def __init__(self) -> None:
+ self.rows: list[dict[str, Any]] = [{
+ "id": "wf-1", "name": "Morning Briefing", "enabled": 1,
+ "trigger_type": "cron", "cron_expression": "30 7 * * *",
+ "next_run_at_ns": time.time_ns() - 8 * _HOUR_NS,
+ }]
+
+ async def list_workflows(self) -> list[dict[str, Any]]:
+ return list(self.rows)
+
+ async def set_next_run(self, wid: str, ns: int | None) -> None:
+ self.rows[0]["next_run_at_ns"] = ns
+
+ bare = _BareStore()
+ runner = _RecordingRunner()
+ scheduler = WorkflowScheduler(store=bare, runner=runner, bus=EventBus()) # type: ignore[arg-type]
+ await scheduler._tick()
+
+ assert runner.triggered == []
+ assert bare.rows[0]["next_run_at_ns"] > time.time_ns()