diff --git a/nanobot/cron/service.py b/nanobot/cron/service.py index 14f04c15d..399b2cf03 100644 --- a/nanobot/cron/service.py +++ b/nanobot/cron/service.py @@ -70,6 +70,26 @@ def _compute_next_run(schedule: CronSchedule, now_ms: int) -> int | None: return None +def _resume_next_run(schedule: CronSchedule, persisted_ms: int | None, now_ms: int) -> int | None: + """Return the next run for a reloaded job, keeping a pending interval run. + + ``every`` schedules are relative to the previous run, so recomputing them + from ``now`` on every startup postpones the job by a full interval each + time the gateway restarts. A persisted next run is kept while it is still + in the future and no more than one interval away; anything else falls back + to :func:`_compute_next_run`. + """ + if ( + schedule.kind == "every" + and schedule.every_ms + and schedule.every_ms > 0 + and persisted_ms is not None + and now_ms < persisted_ms <= now_ms + schedule.every_ms + ): + return persisted_ms + return _compute_next_run(schedule, now_ms) + + def _validate_schedule_for_add(schedule: CronSchedule) -> None: """Validate schedule fields that would otherwise create non-runnable jobs.""" if schedule.tz and schedule.kind != "cron": @@ -489,7 +509,9 @@ class CronService: if self._enforce_agent_binding(job): continue if job.enabled: - job.state.next_run_at_ms = _compute_next_run(job.schedule, now) + job.state.next_run_at_ms = _resume_next_run( + job.schedule, job.state.next_run_at_ms, now + ) def _get_next_wake_ms(self) -> int | None: """Get the earliest next run time across all jobs.""" @@ -772,7 +794,13 @@ class CronService: """Register an internal system job (idempotent on restart).""" store = self._require_store() now = _now_ms() - job.state = CronJobState(next_run_at_ms=_compute_next_run(job.schedule, now)) + existing = next((j for j in store.jobs if j.id == job.id), None) + persisted_ms = ( + existing.state.next_run_at_ms + if existing is not None and existing.enabled and existing.schedule == job.schedule + else None + ) + job.state = CronJobState(next_run_at_ms=_resume_next_run(job.schedule, persisted_ms, now)) job.created_at_ms = now job.updated_at_ms = now store.jobs = [j for j in store.jobs if j.id != job.id] diff --git a/tests/cron/test_cron_service.py b/tests/cron/test_cron_service.py index 324184b04..b016fee3c 100644 --- a/tests/cron/test_cron_service.py +++ b/tests/cron/test_cron_service.py @@ -1450,3 +1450,65 @@ def test_load_jobs_skips_null_run_history_elements(tmp_path) -> None: assert len(jobs[0].state.run_history) == 1 assert jobs[0].state.run_history[0].run_at_ms == 1 assert jobs[0].state.run_history[0].status == "ok" + + +def _dream_job(every_ms: int) -> CronJob: + return CronJob( + id="dream", + name="dream", + schedule=CronSchedule(kind="every", every_ms=every_ms), + payload=CronPayload(kind="system_event"), + ) + + +@pytest.mark.asyncio +async def test_restart_keeps_pending_every_job_run(tmp_path, monkeypatch) -> None: + store_path = tmp_path / "cron" / "jobs.json" + t0 = 1_800_000_000_000 + hour = 3_600_000 + monkeypatch.setattr("nanobot.cron.service._now_ms", lambda: t0) + service = CronService(store_path) + await service.start() + job = service.add_job( + name="daily", + schedule=CronSchedule(kind="every", every_ms=24 * hour), + message="hello", + **_bound_chat(), + ) + service.stop() + assert job.state.next_run_at_ms == t0 + 24 * hour + + monkeypatch.setattr("nanobot.cron.service._now_ms", lambda: t0 + 23 * hour) + restarted = CronService(store_path) + await restarted.start() + try: + reloaded = restarted.get_job(job.id) + assert reloaded is not None + assert reloaded.state.next_run_at_ms == t0 + 24 * hour + finally: + restarted.stop() + + +@pytest.mark.asyncio +async def test_reregistering_system_job_keeps_pending_every_run(tmp_path, monkeypatch) -> None: + store_path = tmp_path / "cron" / "jobs.json" + t0 = 1_800_000_000_000 + minute = 60_000 + + async def boot(now: int, every_ms: int) -> int | None: + monkeypatch.setattr("nanobot.cron.service._now_ms", lambda: now) + service = CronService(store_path) + service.register_system_job(_dream_job(every_ms)) + await service.start() + try: + job = service.get_job("dream") + assert job is not None + return job.state.next_run_at_ms + finally: + service.stop() + + assert await boot(t0, 120 * minute) == t0 + 120 * minute + # A gateway restart before the interval elapses must not push Dream back. + assert await boot(t0 + 90 * minute, 120 * minute) == t0 + 120 * minute + # A changed interval is a new schedule and is computed from now. + assert await boot(t0 + 100 * minute, 60 * minute) == t0 + 160 * minute