Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(scheduled-research): add executor that fires due jobs on schedule (#278)

Matt Van Horn974ad59a68af
diff --git a/agent/api_server.py b/agent/api_server.py
index 17cddb116..7f14c51bc 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -631,6 +631,13 @@ async def _run_startup_preflight() -> None:
from src.preflight import run_preflight
run_preflight(console)
+ _start_scheduled_research_executor()
+
+
[email protected]_event("shutdown")
+async def _stop_scheduled_research_on_shutdown() -> None:
+ """Stop the scheduled research executor on server shutdown."""
+ await _stop_scheduled_research_executor()
# ============================================================================
@@ -3272,12 +3279,16 @@ register_alpha_routes(app)
# Scheduled Research Routes
# ============================================================================
#
-# Three lightweight CRUD endpoints backed by ScheduledResearchJobStore.
-# Execution wiring is intentionally deferred: these endpoints only record
-# and expose scheduled-research jobs; no run is triggered here.
+# Lightweight CRUD endpoints backed by ScheduledResearchJobStore. The endpoint
+# handlers only record and expose jobs; the optional executor lifecycle is
+# guarded separately by VIBE_TRADING_ENABLE_SCHEDULER.
+
+_SCHEDULED_RESEARCH_SCHEDULER_ENV = "VIBE_TRADING_ENABLE_SCHEDULER"
+_SCHEDULED_RESEARCH_TRUE_VALUES = {"1", "true", "yes", "on"}
_scheduled_research_store: Optional["ScheduledResearchJobStore"] = None
+_scheduled_research_executor: Optional["ScheduledResearchExecutor"] = None
def _get_scheduled_research_store() -> "ScheduledResearchJobStore":
@@ -3290,6 +3301,56 @@ def _get_scheduled_research_store() -> "ScheduledResearchJobStore":
return _scheduled_research_store
+def _scheduled_research_scheduler_enabled() -> bool:
+ """Return whether scheduled research execution is enabled."""
+ return os.getenv(_SCHEDULED_RESEARCH_SCHEDULER_ENV, "").strip().lower() in _SCHEDULED_RESEARCH_TRUE_VALUES
+
+
+async def _dispatch_scheduled_research_job(job: "ScheduledResearchJob") -> None:
+ """Enqueue one scheduled research job through the session runtime.
+
+ ``send_message`` queues the agent attempt and returns once accepted; it
+ does not wait for that agent run to reach a terminal status. The executor's
+ ``COMPLETED`` state for this dispatch path means "successfully enqueued."
+ """
+ svc = _get_session_service()
+ if not svc:
+ raise RuntimeError("Session runtime not enabled")
+ # Pass a copy so the session runtime's internal config writes (e.g.
+ # include_shell_tools) do not mutate the persisted scheduled-run config.
+ session = svc.create_session(title=f"scheduled-research:{job.id}", config=dict(job.config))
+ logger.info("dispatching scheduled research job %s via session %s", job.id, session.session_id)
+ await svc.send_message(session.session_id, job.prompt)
+
+
+def _get_scheduled_research_executor() -> "ScheduledResearchExecutor":
+ """Return the singleton scheduled research executor."""
+ global _scheduled_research_executor
+ if _scheduled_research_executor is None:
+ from src.scheduled_research.executor import ScheduledResearchExecutor
+
+ _scheduled_research_executor = ScheduledResearchExecutor(
+ _get_scheduled_research_store(),
+ _dispatch_scheduled_research_job,
+ enabled=_scheduled_research_scheduler_enabled(),
+ )
+ return _scheduled_research_executor
+
+
+def _start_scheduled_research_executor() -> None:
+ """Start scheduled research execution when explicitly enabled."""
+ if not _scheduled_research_scheduler_enabled():
+ return
+ _get_scheduled_research_executor().start()
+
+
+async def _stop_scheduled_research_executor() -> None:
+ """Stop scheduled research execution if it was started."""
+ executor = _scheduled_research_executor
+ if executor is not None:
+ await executor.stop()
+
+
class CreateScheduledRunRequest(BaseModel):
"""Request body for POST /scheduled-runs."""
diff --git a/agent/src/scheduled_research/executor.py b/agent/src/scheduled_research/executor.py
new file mode 100644
index 000000000..fbe9d7303
--- /dev/null
+++ b/agent/src/scheduled_research/executor.py
@@ -0,0 +1,320 @@
+"""Executor for persisted scheduled research jobs.
+
+The executor polls :class:`ScheduledResearchJobStore`, dispatches due jobs via
+an injected async callable, and persists lifecycle/next-run updates after each
+attempt. Schedule math is intentionally pure and clock-injected so tests can
+exercise it without sleeping or reading wall-clock time.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+import time
+from datetime import datetime, timedelta, timezone
+from typing import Awaitable, Callable
+
+from src.scheduled_research.models import JobStatus, ScheduledResearchJob, validate_schedule
+from src.scheduled_research.store import ScheduledResearchJobStore
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_TICK_INTERVAL_MS = 60 * 1000
+SCHEDULER_ENABLED_ENV = "VIBE_TRADING_ENABLE_SCHEDULER"
+
+NowFn = Callable[[], int]
+DispatchCallback = Callable[[ScheduledResearchJob], Awaitable[None]]
+
+_TRUE_VALUES = {"1", "true", "yes", "on"}
+# Search by day, not by minute, so an impossible date (e.g. Feb 31) fails fast
+# instead of scanning years of minutes on the event loop. Four years covers any
+# real recurrence, including a Feb-29 leap day.
+_CRON_SEARCH_LIMIT_DAYS = 4 * 366 + 1
+_CRON_BOUNDS = ((0, 59), (0, 23), (1, 31), (1, 12), (0, 6))
+
+
+def _now_ms() -> int:
+ """Return current wall-clock time in epoch milliseconds."""
+ return int(time.time() * 1000)
+
+
+def scheduler_enabled_from_env(value: str | None = None) -> bool:
+ """Return whether the scheduled-research executor should run.
+
+ The feature is disabled by default. Pass *value* in tests to avoid mutating
+ process environment.
+ """
+ raw = os.getenv(SCHEDULER_ENABLED_ENV, "") if value is None else value
+ return raw.strip().lower() in _TRUE_VALUES
+
+
+def is_due(job: ScheduledResearchJob, now_ms: int) -> bool:
+ """Return whether *job* should fire at ``now_ms``.
+
+ Cancelled and failed jobs are terminal and never re-dispatched; a failed
+ job in particular keeps its old ``next_run_at`` (advancement may itself be
+ what failed), so excluding it here prevents a re-dispatch loop every tick.
+ Already-running jobs are left alone during live polling. Executor startup
+ recovers stale persisted ``RUNNING`` jobs separately.
+ """
+ if job.status in {JobStatus.CANCELLED, JobStatus.RUNNING, JobStatus.FAILED}:
+ return False
+ return job.next_run_at <= now_ms
+
+
+def next_due(schedule: str, after_ms: int) -> int:
+ """Return the first due epoch-ms strictly after ``after_ms``.
+
+ Supports the scheduled-research schedule format: a bare positive integer
+ string for interval milliseconds, or a simplified 5-field cron expression
+ interpreted in UTC.
+ """
+ validate_schedule(schedule)
+ spec = schedule.strip()
+ if spec.isdigit():
+ return after_ms + int(spec)
+ return _next_cron_due(spec, after_ms)
+
+
+def _next_cron_due(schedule: str, after_ms: int) -> int:
+ minutes, hours, doms, months, dows = (
+ _parse_cron_field(part, low, high) for part, (low, high) in zip(schedule.split(), _CRON_BOUNDS)
+ )
+ start = datetime.fromtimestamp(after_ms / 1000.0, timezone.utc) + timedelta(milliseconds=1)
+ # Round up to the next whole minute; cron has minute resolution.
+ if start.second or start.microsecond:
+ start = (start + timedelta(minutes=1)).replace(second=0, microsecond=0)
+
+ day = start.replace(hour=0, minute=0, second=0, microsecond=0)
+ for offset in range(_CRON_SEARCH_LIMIT_DAYS):
+ candidate_day = day + timedelta(days=offset)
+ if not _day_matches(candidate_day, doms, months, dows):
+ continue
+ for hour in sorted(hours) if hours is not None else range(24):
+ for minute in sorted(minutes) if minutes is not None else range(60):
+ fire = candidate_day.replace(hour=hour, minute=minute)
+ if fire >= start:
+ return int(fire.timestamp() * 1000)
+ raise ValueError(f"cron schedule has no matching time within search window: {schedule!r}")
+
+
+def _parse_cron_field(part: str, low: int, high: int) -> set[int] | None:
+ if part == "*":
+ return None
+ if part.startswith("*/"):
+ step = int(part[2:])
+ return set(range(low, high + 1, step))
+ return {int(part)}
+
+
+def _day_matches(dt: datetime, doms: set[int] | None, months: set[int] | None, dows: set[int] | None) -> bool:
+ cron_day_of_week = (dt.weekday() + 1) % 7 # cron convention: Sunday == 0
+ return (
+ (doms is None or dt.day in doms)
+ and (months is None or dt.month in months)
+ and (dows is None or cron_day_of_week in dows)
+ )
+
+
+class ScheduledResearchExecutor:
+ """Background poller that dispatches due scheduled research jobs."""
+
+ def __init__(
+ self,
+ store: ScheduledResearchJobStore,
+ dispatch: DispatchCallback,
+ *,
+ tick_interval_ms: int = DEFAULT_TICK_INTERVAL_MS,
+ now_fn: NowFn = _now_ms,
+ enabled: bool = True,
+ ) -> None:
+ """Initialize the executor.
+
+ Args:
+ store: Durable scheduled job store.
+ dispatch: Async callable invoked once for each due job.
+ tick_interval_ms: Poll interval for the background loop.
+ now_fn: Injectable wall-clock source returning epoch milliseconds.
+ enabled: When false, :meth:`start` and :meth:`stop` are no-ops.
+ """
+ self._store = store
+ self._dispatch = dispatch
+ self._tick_interval_ms = tick_interval_ms
+ self._now_fn = now_fn
+ self._enabled = enabled
+ self._task: asyncio.Task | None = None
+ self._wakeup: asyncio.Event | None = None
+ self._stopping = False
+ self._recovered_stale_running = False
+
+ @property
+ def is_running(self) -> bool:
+ """Return whether the background loop task is active."""
+ return self._task is not None and not self._task.done()
+
+ def start(self) -> None:
+ """Start the background loop.
+
+ Idempotent. When disabled, this is a no-op.
+ """
+ if not self._enabled or self.is_running:
+ return
+ self._stopping = False
+ self.recover_stale_running()
+ self._wakeup = asyncio.Event()
+ loop = asyncio.get_running_loop()
+ self._task = loop.create_task(self._run(), name="scheduled-research-executor")
+
+ async def stop(self) -> None:
+ """Stop the background loop and wait for it to finish.
+
+ Idempotent. When disabled or not started, this is a no-op.
+ """
+ if not self._enabled:
+ return
+ task = self._task
+ if task is None:
+ return
+ self._stopping = True
+ if self._wakeup is not None:
+ self._wakeup.set()
+ # The set() above wakes a sleeping loop in the common case. Cancel as a
+ # fallback so shutdown never blocks for a full tick if the wakeup raced
+ # the loop's sleep, then await the task to let it unwind cleanly.
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ self._task = None
+
+ async def tick(self, now_ms: int | None = None) -> None:
+ """Run one poll/dispatch pass.
+
+ Args:
+ now_ms: Optional explicit reference time. Defaults to ``now_fn``.
+ """
+ self.recover_stale_running()
+ now = self._now_fn() if now_ms is None else now_ms
+ jobs = sorted(
+ (job for job in self._store.load().values() if is_due(job, now)),
+ key=lambda job: job.next_run_at,
+ )
+ for job in jobs:
+ await self._run_job(job, now)
+
+ def recover_stale_running(self) -> int:
+ """Reset jobs left ``RUNNING`` by a previous executor process.
+
+ This runs at most once per executor instance. Jobs that become
+ ``RUNNING`` after this recovery step are treated as live in-flight work
+ and remain skipped by :func:`is_due`.
+ """
+ if self._recovered_stale_running:
+ return 0
+
+ jobs = self._store.load()
+ recovered = 0
+ for job in jobs.values():
+ if job.status != JobStatus.RUNNING:
+ continue
+ job.status = JobStatus.PENDING
+ recovered += 1
+ logger.warning("recovering stale scheduled research job %s from running to pending", job.id)
+
+ if recovered:
+ self._store.save(jobs)
+ self._recovered_stale_running = True
+ return recovered
+
+ async def _run(self) -> None:
+ while not self._stopping:
+ try:
+ await self.tick(self._now_fn())
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.error("scheduled research executor tick failed", exc_info=True)
+ if self._stopping:
+ break
+ await self._sleep_or_wake(self._tick_interval_ms)
+
+ async def _sleep_or_wake(self, sleep_ms: int) -> None:
+ wakeup = self._wakeup
+ if wakeup is None:
+ await asyncio.sleep(sleep_ms / 1000.0)
+ return
+ # Re-check after re-entering: if stop() flipped _stopping and set the
+ # event between the loop's check and here, return at once rather than
+ # clearing the wakeup and blocking for a full tick on shutdown.
+ if self._stopping:
+ return
+ wakeup.clear()
+ try:
+ await asyncio.wait_for(wakeup.wait(), timeout=sleep_ms / 1000.0)
+ except asyncio.TimeoutError:
+ pass
+
+ async def _run_job(self, job: ScheduledResearchJob, now_ms: int) -> None:
+ # The tick snapshot may be stale by the time we reach this job (an
+ # earlier dispatch was awaited). Re-read and confirm identity before
+ # marking it RUNNING so a job the user deleted or replaced in the
+ # meantime is not resurrected or dispatched.
+ current = self._store.get(job.id)
+ if current is None or not self._same_record(current, job) or not is_due(current, now_ms):
+ return
+ job = current
+
+ job.status = JobStatus.RUNNING
+ self._store.upsert(job)
+
+ try:
+ await self._dispatch(job)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.error("scheduled research dispatch failed for job %s", job.id, exc_info=True)
+ final_status = JobStatus.FAILED
+ else:
+ final_status = JobStatus.COMPLETED
+
+ job.last_run_at = now_ms
+ try:
+ job.next_run_at = next_due(job.schedule, now_ms)
+ except Exception:
+ logger.error("scheduled research schedule advancement failed for job %s", job.id, exc_info=True)
+ job.status = JobStatus.FAILED
+ self._persist_completion(job)
+ return
+
+ job.status = final_status
+ self._persist_completion(job)
+
+ @staticmethod
+ def _same_record(current: ScheduledResearchJob, job: ScheduledResearchJob) -> bool:
+ """Return whether *current* is the same scheduled run we started.
+
+ ``created_at`` is assigned once at creation, so a replacement POST for
+ the same id (which the API stamps with a fresh ``created_at``) is
+ distinguishable even when the schedule is unchanged.
+ """
+ return current.id == job.id and current.created_at == job.created_at
+
+ def _persist_completion(self, job: ScheduledResearchJob) -> None:
+ """Write a finished job back, unless it was changed during dispatch.
+
+ Dispatch is awaited, so a concurrent DELETE or POST for the same id can
+ land while a run is in flight. Reload first: if the record is gone the
+ user cancelled it (do not resurrect), and if it is a different record
+ (replaced via POST) let the new definition own its lifecycle. Only
+ persist our completion when it still refers to the same scheduled run.
+ """
+ current = self._store.get(job.id)
+ if current is None:
+ logger.info("scheduled research job %s deleted during dispatch; skipping completion write", job.id)
+ return
+ if not self._same_record(current, job):
+ logger.info("scheduled research job %s replaced during dispatch; skipping completion write", job.id)
+ return
+ self._store.upsert(job)
diff --git a/agent/src/scheduled_research/models.py b/agent/src/scheduled_research/models.py
index 26baeafd5..ce746fa78 100644
--- a/agent/src/scheduled_research/models.py
+++ b/agent/src/scheduled_research/models.py
@@ -12,7 +12,7 @@ import re
import time
from dataclasses import dataclass, field
from enum import Enum
-from typing import Any, Dict
+from typing import Any, Dict, Optional
# ---------------------------------------------------------------------------
# Schedule validation
@@ -93,6 +93,8 @@ class ScheduledResearchJob:
execution. Defaults to the current time when the job is created.
status: Current lifecycle status.
created_at: Epoch-millisecond timestamp of job creation.
+ last_run_at: Epoch-millisecond timestamp of the most recent executor
+ attempt, or ``None`` when the job has not fired yet.
config: Opaque dict for future backtest parameters.
"""
@@ -102,6 +104,7 @@ class ScheduledResearchJob:
next_run_at: int = field(default_factory=lambda: int(time.time() * 1000))
status: JobStatus = JobStatus.PENDING
created_at: int = field(default_factory=lambda: int(time.time() * 1000))
+ last_run_at: Optional[int] = None
config: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
@@ -118,6 +121,7 @@ class ScheduledResearchJob:
"next_run_at": self.next_run_at,
"status": self.status.value,
"created_at": self.created_at,
+ "last_run_at": self.last_run_at,
"config": self.config,
}
@@ -145,6 +149,9 @@ class ScheduledResearchJob:
created_at = data["created_at"]
if not isinstance(next_run_at, int) or not isinstance(created_at, int):
raise TypeError("'next_run_at' and 'created_at' must be integers (epoch ms)")
+ last_run_at = data.get("last_run_at")
+ if last_run_at is not None and not isinstance(last_run_at, int):
+ raise TypeError("'last_run_at' must be an integer (epoch ms) or null")
status = JobStatus(data["status"])
raw_config = data.get("config")
config: Dict[str, Any] = raw_config if isinstance(raw_config, dict) else {}
@@ -155,5 +162,6 @@ class ScheduledResearchJob:
next_run_at=next_run_at,
status=status,
created_at=created_at,
+ last_run_at=last_run_at,
config=config,
)
diff --git a/agent/tests/test_scheduled_research_executor.py b/agent/tests/test_scheduled_research_executor.py
new file mode 100644
index 000000000..9bc9cb043
--- /dev/null
+++ b/agent/tests/test_scheduled_research_executor.py
@@ -0,0 +1,319 @@
+"""Tests for the scheduled research executor."""
+
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime, timezone
+from pathlib import Path
+
+import pytest
+from src.scheduled_research.executor import (
+ ScheduledResearchExecutor,
+ is_due,
+ next_due,
+ scheduler_enabled_from_env,
+)
+from src.scheduled_research.models import JobStatus, ScheduledResearchJob
+from src.scheduled_research.store import ScheduledResearchJobStore
+
+
+def _ms(year: int, month: int, day: int, hour: int, minute: int) -> int:
+ return int(datetime(year, month, day, hour, minute, tzinfo=timezone.utc).timestamp() * 1000)
+
+
+def _store(tmp_path: Path) -> ScheduledResearchJobStore:
+ return ScheduledResearchJobStore(path=tmp_path / "jobs.json")
+
+
+def _job(
+ job_id: str = "job-001",
+ *,
+ schedule: str = "1000",
+ next_run_at: int = 0,
+ status: JobStatus = JobStatus.PENDING,
+ created_at: int = 0,
+) -> ScheduledResearchJob:
+ return ScheduledResearchJob(
+ id=job_id,
+ prompt=f"prompt for {job_id}",
+ schedule=schedule,
+ next_run_at=next_run_at,
+ status=status,
+ created_at=created_at,
+ )
+
+
+def test_interval_job_fires_and_persists_completion(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job(schedule="5000", next_run_at=1000))
+ calls: list[tuple[str, JobStatus]] = []
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ calls.append((job.id, job.status))
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(store, dispatch)
+ await executor.tick(1500)
+
+ asyncio.run(scenario())
+
+ saved = store.get("job-001")
+ assert saved is not None
+ assert calls == [("job-001", JobStatus.RUNNING)]
+ assert saved.status == JobStatus.COMPLETED
+ assert saved.last_run_at == 1500
+ assert saved.next_run_at == 6500
+
+
+def test_cron_job_next_due_and_not_before_due_time(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ before_due = _ms(2026, 6, 20, 5, 59)
+ due_at = _ms(2026, 6, 20, 6, 0)
+ following_due = _ms(2026, 6, 20, 12, 0)
+ assert next_due("0 */6 * * *", before_due) == due_at
+
+ store.upsert(_job(schedule="0 */6 * * *", next_run_at=due_at))
+ calls: list[str] = []
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ calls.append(job.id)
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(store, dispatch)
+ await executor.tick(due_at - 1)
+ assert calls == []
+ await executor.tick(due_at)
+
+ asyncio.run(scenario())
+
+ saved = store.get("job-001")
+ assert saved is not None
+ assert calls == ["job-001"]
+ assert saved.status == JobStatus.COMPLETED
+ assert saved.last_run_at == due_at
+ assert saved.next_run_at == following_due
+
+
+def test_dispatch_failure_marks_failed_and_tick_continues(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job("bad", next_run_at=10))
+ store.upsert(_job("good", next_run_at=20))
+ calls: list[str] = []
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ calls.append(job.id)
+ if job.id == "bad":
+ raise RuntimeError("boom")
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(store, dispatch)
+ await executor.tick(100)
+
+ asyncio.run(scenario())
+
+ bad = store.get("bad")
+ good = store.get("good")
+ assert bad is not None
+ assert good is not None
+ assert calls == ["bad", "good"]
+ assert bad.status == JobStatus.FAILED
+ assert good.status == JobStatus.COMPLETED
+
+
+def test_stale_running_job_recovers_to_pending_and_fires_on_next_tick(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job("stale", schedule="1000", next_run_at=10, status=JobStatus.RUNNING))
+ calls: list[tuple[str, JobStatus]] = []
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ calls.append((job.id, job.status))
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(store, dispatch)
+ assert executor.recover_stale_running() == 1
+ recovered = store.get("stale")
+ assert recovered is not None
+ assert recovered.status == JobStatus.PENDING
+ await executor.tick(100)
+
+ asyncio.run(scenario())
+
+ saved = store.get("stale")
+ assert saved is not None
+ assert calls == [("stale", JobStatus.RUNNING)]
+ assert saved.status == JobStatus.COMPLETED
+ assert saved.last_run_at == 100
+ assert saved.next_run_at == 1100
+
+
+def test_impossible_cron_marks_failed_and_tick_continues(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ now = _ms(2026, 2, 1, 0, 0)
+ store.upsert(_job("bad", schedule="0 0 31 2 *", next_run_at=10))
+ store.upsert(_job("good", schedule="1000", next_run_at=20))
+ calls: list[str] = []
+
+ with pytest.raises(ValueError):
+ next_due("0 0 31 2 *", now)
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ calls.append(job.id)
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(store, dispatch)
+ await executor.tick(now)
+
+ asyncio.run(scenario())
+
+ bad = store.get("bad")
+ good = store.get("good")
+ assert bad is not None
+ assert good is not None
+ assert calls == ["bad", "good"]
+ assert bad.status == JobStatus.FAILED
+ assert bad.last_run_at == now
+ assert bad.next_run_at == 10
+ assert good.status == JobStatus.COMPLETED
+
+
+def test_cancelled_and_running_jobs_are_skipped(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job("cancelled", next_run_at=0, status=JobStatus.CANCELLED))
+ store.upsert(_job("pending", next_run_at=0, status=JobStatus.PENDING))
+ calls: list[str] = []
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ calls.append(job.id)
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(store, dispatch)
+ assert executor.recover_stale_running() == 0
+ store.upsert(_job("running", next_run_at=0, status=JobStatus.RUNNING))
+ await executor.tick(100)
+
+ asyncio.run(scenario())
+
+ assert is_due(store.get("cancelled"), 100) is False # type: ignore[arg-type]
+ assert is_due(store.get("running"), 100) is False # type: ignore[arg-type]
+ assert calls == ["pending"]
+ assert store.get("cancelled").status == JobStatus.CANCELLED # type: ignore[union-attr]
+ assert store.get("running").status == JobStatus.RUNNING # type: ignore[union-attr]
+ assert store.get("pending").status == JobStatus.COMPLETED # type: ignore[union-attr]
+
+
+def test_failed_job_is_not_redispatched(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ # A terminal FAILED job whose next_run_at is still in the past must not be
+ # re-dispatched on the next tick (it would otherwise fire every poll).
+ store.upsert(_job("failed", next_run_at=0, status=JobStatus.FAILED))
+ calls: list[str] = []
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ calls.append(job.id)
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(store, dispatch)
+ await executor.tick(100)
+
+ asyncio.run(scenario())
+
+ assert is_due(store.get("failed"), 100) is False # type: ignore[arg-type]
+ assert calls == []
+ assert store.get("failed").status == JobStatus.FAILED # type: ignore[union-attr]
+
+
+def test_job_deleted_during_dispatch_is_not_resurrected(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job("job-001", schedule="1000", next_run_at=0))
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ # Simulate a user DELETE landing while the run is in flight.
+ store.delete(job.id)
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(store, dispatch)
+ await executor.tick(100)
+
+ asyncio.run(scenario())
+
+ # The deleted job must not reappear after dispatch completes.
+ assert store.get("job-001") is None
+
+
+def test_job_replaced_during_dispatch_is_not_overwritten(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job("job-001", schedule="1000", next_run_at=0))
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ # Simulate a user POST replacing the job mid-run. The API stamps a fresh
+ # created_at on every create, which is how a replacement is told apart
+ # from the in-flight original (even when the schedule is unchanged).
+ store.upsert(_job("job-001", schedule="5000", next_run_at=900, created_at=999))
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(store, dispatch)
+ await executor.tick(100)
+
+ asyncio.run(scenario())
+
+ saved = store.get("job-001")
+ assert saved is not None
+ # The replacement definition is preserved, not clobbered by the old run.
+ assert saved.schedule == "5000"
+ assert saved.next_run_at == 900
+ assert saved.created_at == 999
+ assert saved.status == JobStatus.PENDING
+
+
+def test_restart_after_missed_window_honors_persisted_next_run_at(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job(schedule="5000", next_run_at=1000))
+ calls: list[str] = []
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ calls.append(job.id)
+
+ async def scenario() -> None:
+ first = ScheduledResearchExecutor(store, dispatch)
+ await first.tick(20_000)
+ assert calls == ["job-001"]
+
+ restarted = ScheduledResearchExecutor(store, dispatch)
+ await restarted.tick(20_000)
+
+ asyncio.run(scenario())
+
+ saved = store.get("job-001")
+ assert saved is not None
+ assert calls == ["job-001"]
+ assert saved.status == JobStatus.COMPLETED
+ assert saved.last_run_at == 20_000
+ assert saved.next_run_at == 25_000
+
+
+def test_disabled_executor_start_stop_are_noops(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ store.upsert(_job(next_run_at=0))
+ calls: list[str] = []
+
+ async def dispatch(job: ScheduledResearchJob) -> None:
+ calls.append(job.id)
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(
+ store,
+ dispatch,
+ tick_interval_ms=1,
+ now_fn=lambda: 100,
+ enabled=False,
+ )
+ executor.start()
+ assert executor.is_running is False
+ await executor.stop()
+
+ asyncio.run(scenario())
+
+ assert scheduler_enabled_from_env("") is False
+ assert scheduler_enabled_from_env("true") is True
+ assert calls == []
+ assert store.get("job-001").status == JobStatus.PENDING # type: ignore[union-attr]