Skip to content

"Vibe-Trading: Your Personal Trading Agent"

refactor(live): run the runtime scheduler on the shared kernel

shadowinlifef6285146bff8
diff --git a/agent/src/live/runtime/scheduler.py b/agent/src/live/runtime/scheduler.py
index fcac9bfeb..a9eddec01 100644
--- a/agent/src/live/runtime/scheduler.py
+++ b/agent/src/live/runtime/scheduler.py
@@ -1,15 +1,23 @@
"""Wall-clock scheduler for the live runtime (SPEC.md §7.5 #1).
-Follows the reference ``cron/service.py`` shape: an asyncio timer that sleeps until
-the earliest ``next_run_at`` across all jobs, fires the due jobs, advances each
-fired job's ``next_run_at``, then re-sleeps. The sleep is **capped** at a
-re-check interval (default 5 min) so a far-future job still wakes the loop
-periodically — defending against wall-clock jumps, a job added while asleep, and
-host suspend/resume drift.
+A thin façade over the shared :class:`src.scheduling.kernel.SchedulerKernel`
+(scheduler unification, step 2): the kernel owns the loop task, the
+``asyncio.Event`` wakeup and the sleep machinery, while this module keeps the
+live-runtime vocabulary — :class:`Job`, the ``"interval:<ms>"`` / ``"once"``
+trigger dialect and the pure decision helpers — and composes them into the
+kernel's ``on_tick`` / ``sleep_hint_fn`` seams.
+
+The sleep is **adaptive**: after each tick the kernel asks
+:meth:`Scheduler._sleep_hint` for the next deadline, which returns
+``min(earliest next_run_at - now, max_recheck)`` (see :func:`compute_sleep_ms`)
+so the loop wakes at the earliest job's due time, **capped** at a re-check
+interval (default 5 min) so a far-future job still wakes the loop
+periodically — defending against wall-clock jumps, a job added while asleep,
+and host suspend/resume drift.
Time is epoch-milliseconds throughout. Every pure decision helper takes
``now_ms`` explicitly (no wall-clock read inside) so scheduling logic is unit
-testable without sleeping or freezing the clock. Only the async run loop reads
+testable without sleeping or freezing the clock. Only the kernel's loop reads
the real clock, via an injectable ``now_fn``.
The scheduler holds the live job set in memory and invokes an async
@@ -25,6 +33,14 @@ import time
from dataclasses import dataclass, field
from typing import Awaitable, Callable
+from src.scheduling.kernel import SchedulerKernel
+from src.scheduling.triggers import (
+ DEFAULT_TRIGGER_INTERVAL_MS,
+ next_once_due,
+ trigger_interval_ms,
+)
+from src.scheduling.types import NowFn
+
logger = logging.getLogger(__name__)
#: Hard cap on how long the loop sleeps before re-checking, even when the next
@@ -32,10 +48,14 @@ logger = logging.getLogger(__name__)
DEFAULT_MAX_RECHECK_MS = 5 * 60 * 1000
#: Default cadence applied when a job's ``schedule`` is a bare/empty/unknown
-#: spec — the watch still fires on a sane interval rather than never.
-DEFAULT_INTERVAL_MS = 60 * 1000
+#: spec — the watch still fires on a sane interval rather than never. The
+#: value lives in the shared trigger grammar; alias kept for import stability.
+DEFAULT_INTERVAL_MS = DEFAULT_TRIGGER_INTERVAL_MS
+
+#: Observable ``asyncio`` task name of the scheduler loop (kept stable across
+#: the kernel adoption so log/task introspection does not change).
+TASK_NAME = "live-scheduler"
-NowFn = Callable[[], int]
FireCallback = Callable[["Job"], Awaitable[None]]
@@ -78,23 +98,17 @@ class Job:
def interval_ms(self) -> int | None:
"""Return the recurrence interval in ms, or ``None`` for one-shot jobs.
+ Delegates to the shared trigger grammar
+ (:func:`src.scheduling.triggers.trigger_interval_ms`), which absorbs
+ this method's original semantics verbatim.
+
Returns:
The interval for an ``"interval:<ms>"`` schedule, ``None`` for a
``"once"`` schedule, and :data:`DEFAULT_INTERVAL_MS` for any other
(non-empty) recognized-but-bare spec so a misconfigured job still
watches on a sane cadence rather than silently never recurring.
"""
- spec = (self.schedule or "").strip().lower()
- if spec == "once":
- return None
- if spec.startswith("interval:"):
- raw = spec.split(":", 1)[1].strip()
- try:
- ms = int(raw)
- except ValueError:
- return DEFAULT_INTERVAL_MS
- return ms if ms > 0 else DEFAULT_INTERVAL_MS
- return DEFAULT_INTERVAL_MS
+ return trigger_interval_ms(self.schedule)
def earliest_next_run(jobs: list[Job]) -> int | None:
@@ -155,8 +169,10 @@ def compute_sleep_ms(jobs: list[Job], now_ms: int, max_recheck_ms: int) -> int:
def advance_after_fire(job: Job, now_ms: int) -> bool:
"""Advance a fired job's ``next_run_at``; report whether it should remain.
- Recurring jobs are re-scheduled one interval past ``now_ms`` (not past the
- old ``next_run_at``), so a job that fired late — because the host was
+ Delegates to the shared next-run math
+ (:func:`src.scheduling.triggers.next_once_due`): recurring jobs are
+ re-scheduled one interval past ``now_ms`` (not past the old
+ ``next_run_at``), so a job that fired late — because the host was
suspended or the loop was busy — does not immediately re-fire a backlog of
missed slots. One-shot jobs are not advanced.
@@ -168,26 +184,29 @@ def advance_after_fire(job: Job, now_ms: int) -> bool:
``True`` if the job recurs and should stay in the set, ``False`` if it
was one-shot and should be removed.
"""
- interval = job.interval_ms()
- if interval is None:
+ next_run = next_once_due(job.schedule, now_ms)
+ if next_run is None:
return False
- job.next_run_at = now_ms + interval
+ job.next_run_at = next_run
return True
class Scheduler:
"""Async wall-clock scheduler over an in-memory job set.
- Lifecycle: :meth:`start` spawns the loop task on the running event loop;
- :meth:`stop` cancels and awaits it. :meth:`add_job` / :meth:`remove_job`
- mutate the live set and wake the loop so a newly-added near-term job is not
- blocked behind a long sleep.
+ A façade: the loop itself is a :class:`~src.scheduling.kernel.SchedulerKernel`
+ whose ``on_tick`` is :meth:`_fire_due` and whose ``sleep_hint_fn`` is
+ :meth:`_sleep_hint` (the adaptive next-deadline sleep). This class keeps
+ the job set, the ``on_fire`` dispatch with per-job exception isolation and
+ the public surface the live runtime is built against.
+
+ Lifecycle: :meth:`start` spawns the kernel loop task on the running event
+ loop; :meth:`stop` cancels and awaits it. :meth:`add_job` /
+ :meth:`remove_job` mutate the live set and wake the loop so a newly-added
+ near-term job is not blocked behind a long sleep.
The scheduler does not persist anything itself — pair it with a
:class:`src.live.runtime.jobstore.JobStore` at the runner layer.
-
- Attributes:
- on_fire: Async callback invoked once per due job each tick.
"""
def __init__(
@@ -212,9 +231,22 @@ class Scheduler:
self._max_recheck_ms = max_recheck_ms
self._now_fn = now_fn
self._jobs: dict[str, Job] = {}
- self._task: asyncio.Task | None = None
- self._wakeup: asyncio.Event = asyncio.Event()
- self._stopping = False
+ self._kernel = SchedulerKernel(
+ now_fn=now_fn,
+ on_tick=self._fire_due,
+ sleep_hint_fn=self._sleep_hint,
+ task_name=TASK_NAME,
+ )
+
+ @property
+ def _task(self) -> asyncio.Task | None:
+ """Return the kernel's loop task (read by the live-routes driver).
+
+ ``src/api/live_routes.py`` parks the runner's driver coroutine on this
+ task and treats ``None``/done as "nothing to await"; the property keeps
+ that contract stable across the kernel adoption.
+ """
+ return self._kernel.task
def jobs(self) -> list[Job]:
"""Return a snapshot list of the current jobs.
@@ -233,7 +265,7 @@ class Scheduler:
replaced (idempotent re-registration on restart).
"""
self._jobs[job.id] = job
- self._wakeup.set()
+ self._kernel.request_wake()
def remove_job(self, job_id: str) -> bool:
"""Remove a job by id and wake the loop.
@@ -246,7 +278,7 @@ class Scheduler:
"""
existed = self._jobs.pop(job_id, None) is not None
if existed:
- self._wakeup.set()
+ self._kernel.request_wake()
return existed
def start(self) -> None:
@@ -257,11 +289,7 @@ class Scheduler:
Raises:
RuntimeError: If there is no running event loop.
"""
- if self._task is not None and not self._task.done():
- return
- self._stopping = False
- loop = asyncio.get_running_loop()
- self._task = loop.create_task(self._run(), name="live-scheduler")
+ self._kernel.start()
async def stop(self) -> None:
"""Stop the scheduler loop and await its teardown.
@@ -269,50 +297,27 @@ class Scheduler:
Idempotent: calling :meth:`stop` when not running is a no-op. Safe to
call from within the same event loop the loop runs on.
"""
- self._stopping = True
- self._wakeup.set()
- task = self._task
- self._task = None
- if task is None:
- return
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
-
- async def _run(self) -> None:
- """Core loop: sleep until the earliest due job, fire it, repeat.
-
- Sleeps are interruptible by :attr:`_wakeup`, so ``add_job`` /
- ``remove_job`` / ``stop`` take effect immediately rather than after the
- current sleep expires.
- """
- while not self._stopping:
- now = self._now_fn()
- sleep_ms = compute_sleep_ms(self.jobs(), now, self._max_recheck_ms)
- if sleep_ms > 0:
- await self._sleep_or_wake(sleep_ms)
- if self._stopping:
- break
- continue
- await self._fire_due(now)
-
- async def _sleep_or_wake(self, sleep_ms: int) -> None:
- """Sleep for ``sleep_ms`` or until woken by a set mutation / stop.
+ await self._kernel.stop()
+
+ def _sleep_hint(self, now_ms: int) -> int:
+ """Return the adaptive inter-tick sleep for the kernel loop.
Args:
- sleep_ms: Duration to sleep, in milliseconds.
+ now_ms: The kernel's freshly read reference time in epoch ms.
+
+ Returns:
+ The sleep duration from :func:`compute_sleep_ms` — the earliest
+ job's due delta, clamped to ``[0, max_recheck_ms]``.
"""
- self._wakeup.clear()
- try:
- await asyncio.wait_for(self._wakeup.wait(), timeout=sleep_ms / 1000.0)
- except asyncio.TimeoutError:
- pass
+ return compute_sleep_ms(self.jobs(), now_ms, self._max_recheck_ms)
async def _fire_due(self, now_ms: int) -> None:
"""Fire every job due at ``now_ms`` and reschedule/remove each.
+ Per-job isolation lives here (not in the kernel's per-tick catch) so
+ one raising ``on_fire`` neither kills the loop nor starves the other
+ due jobs in the same tick.
+
Args:
now_ms: The reference time for due-ness, in epoch ms.
"""
diff --git a/agent/src/scheduling/__init__.py b/agent/src/scheduling/__init__.py
index a4428d31b..a003f6bba 100644
--- a/agent/src/scheduling/__init__.py
+++ b/agent/src/scheduling/__init__.py
@@ -6,13 +6,14 @@ in the repo can adopt:
* :mod:`src.scheduling.triggers` — pure, clock-injected trigger grammar
(interval-ms + 5-field cron + IANA timezones with the DST gap-skip /
fold=0 policy) and next-run math, plus the ``once`` trigger kind absorbed
- from the live runtime scheduler (provided for future adoption; not wired).
+ from the live runtime scheduler (consumed by its kernel-backed façade).
* :mod:`src.scheduling.types` — the shared vocabulary: ``ExecutorKind`` with
its closed runtime domain, and the kernel callback type aliases.
* :mod:`src.scheduling.kernel` — ``SchedulerKernel``: the generic tick loop
with ``asyncio.Event`` wakeup, bounded exponential backoff, an injectable
- clock and the ``on_tick`` seam for domain logic (consumed by the scheduled
- research executor).
+ clock, the ``on_tick`` seam for domain logic and an optional
+ ``sleep_hint_fn`` seam for adaptive-sleep consumers (together consumed by
+ the scheduled-research executor and the live runtime scheduler).
* :mod:`src.scheduling.registry` — the internal-callable allowlist: an
explicit module-level dict mapping literal registry keys to zero-arg
sync/async callables, with exact-key resolution only (no dynamic import,
@@ -64,6 +65,7 @@ from src.scheduling.types import (
ExecutorKind,
NowFn,
OnTickFn,
+ SleepHintFn,
is_executor_kind,
)
@@ -84,6 +86,7 @@ __all__ = [
"NowFn",
"OnTickFn",
"SchedulerKernel",
+ "SleepHintFn",
"day_matches",
"is_executor_kind",
"is_interval_schedule",
diff --git a/agent/src/scheduling/triggers.py b/agent/src/scheduling/triggers.py
index 65fcd4b5b..eb5486d95 100644
--- a/agent/src/scheduling/triggers.py
+++ b/agent/src/scheduling/triggers.py
@@ -295,18 +295,19 @@ ONCE_SPEC = "once"
#: Default cadence applied when a live-style trigger ``schedule`` is a
#: bare/empty/unknown spec — the watch still fires on a sane interval rather
-#: than never. Mirrors ``DEFAULT_INTERVAL_MS`` in
-#: ``agent/src/live/runtime/scheduler.py`` (semantics absorbed here so the
-#: kernel is adoptable by the live runtime later; nothing is imported from
-#: ``src.live`` and no live behavior changes in this batch).
+#: than never. Single home of the semantics ``Job.interval_ms()`` in
+#: ``agent/src/live/runtime/scheduler.py`` originally carried; the live
+#: scheduler's kernel-backed façade delegates here (nothing is imported from
+#: ``src.live`` in the other direction).
DEFAULT_TRIGGER_INTERVAL_MS = 60 * 1000
def trigger_interval_ms(schedule: str | None) -> int | None:
"""Return the recurrence interval in ms for a live-style trigger spec.
- Absorbs the semantics of ``Job.interval_ms()`` in
- ``agent/src/live/runtime/scheduler.py``:
+ Single home of the semantics ``Job.interval_ms()`` in
+ ``agent/src/live/runtime/scheduler.py`` originally carried; that method is
+ now a delegate to this function:
* ``"once"`` → ``None``: a one-shot trigger with no recurrence;
* ``"interval:<ms>"`` → ``<ms>`` when it parses as a positive integer,
diff --git a/agent/tests/test_runtime_scheduler_kernel.py b/agent/tests/test_runtime_scheduler_kernel.py
new file mode 100644
index 000000000..045a19df7
--- /dev/null
+++ b/agent/tests/test_runtime_scheduler_kernel.py
@@ -0,0 +1,183 @@
+"""Tests for the live-runtime scheduler's kernel adoption (step 2 of the
+scheduler unification): ``src/live/runtime/scheduler.py`` is now a thin façade
+over ``src.scheduling.kernel.SchedulerKernel``.
+
+The pre-move behavior battery (``test_runtime_scheduler.py``) is unmodified and
+still green; this file pins the *new* structural facts: kernel ownership, the
+stable task name and ``_task`` handle, delegation to the shared trigger
+grammar, the adaptive sleep hint, and wake-on-mutation.
+
+House style: ``asyncio.run`` scenarios with an injected ``now_fn`` instead of
+the wall clock, yield loops / ``asyncio.Event`` handshakes instead of real
+waiting, and ``asyncio.wait_for`` timeouts so a wedged scheduler fails the
+test instead of hanging the suite.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+from src.live.runtime.scheduler import (
+ DEFAULT_MAX_RECHECK_MS,
+ TASK_NAME,
+ Job,
+ Scheduler,
+ advance_after_fire,
+ compute_sleep_ms,
+)
+from src.scheduling.kernel import SchedulerKernel
+from src.scheduling.triggers import next_once_due, trigger_interval_ms
+
+
+def _job(jid: str, next_run_at: int, schedule: str = "interval:1000") -> Job:
+ return Job(id=jid, next_run_at=next_run_at, schedule=schedule)
+
+
+# ---- kernel ownership and the stable task handle ----------------------------
+
+
+def test_scheduler_owns_a_kernel_with_the_live_task_name() -> None:
+ async def on_fire(job: Job) -> None: # pragma: no cover - never fires here
+ pass
+
+ sched = Scheduler(on_fire)
+ assert isinstance(sched._kernel, SchedulerKernel)
+ assert sched._kernel.task_name == TASK_NAME == "live-scheduler"
+ assert sched._kernel.on_tick == sched._fire_due
+ assert sched._kernel.sleep_hint_fn == sched._sleep_hint
+
+
+def test_task_property_tracks_the_kernel_task_lifecycle() -> None:
+ """``live_routes._runner_scheduler_task`` reads ``scheduler._task`` and
+ treats None/done as "nothing to await" — the property must keep that
+ contract across the kernel adoption."""
+
+ async def scenario() -> None:
+ sched = Scheduler(_noop_fire)
+ assert sched._task is None
+ sched.start()
+ task = sched._task
+ assert task is not None and not task.done()
+ assert task.get_name() == "live-scheduler"
+ await asyncio.wait_for(sched.stop(), timeout=5.0)
+ assert sched._task is None
+
+ asyncio.run(scenario())
+
+
+async def _noop_fire(job: Job) -> None: # pragma: no cover - never fires here
+ pass
+
+
+# ---- delegation to the shared trigger grammar --------------------------------
+
+
+def test_interval_ms_matches_the_shared_grammar_on_every_spec_shape() -> None:
+ specs = [
+ "interval:5000",
+ "interval:0",
+ "interval:-5",
+ "interval:nope",
+ "interval:",
+ "once",
+ "ONCE",
+ " Once ",
+ "weird",
+ "",
+ " ",
+ ]
+ for spec in specs:
+ assert _job("a", 0, spec).interval_ms() == trigger_interval_ms(spec)
+
+
+def test_advance_after_fire_matches_the_shared_next_run_math() -> None:
+ for spec in ("interval:1000", "interval:bad", "once", "weird", ""):
+ job = _job("a", next_run_at=100, schedule=spec)
+ keep = advance_after_fire(job, now_ms=5000)
+ expected = next_once_due(spec, 5000)
+ if expected is None:
+ assert keep is False
+ assert job.next_run_at == 100 # untouched
+ else:
+ assert keep is True
+ assert job.next_run_at == expected
+
+
+# ---- adaptive sleep hint ------------------------------------------------------
+
+
+def test_sleep_hint_is_compute_sleep_ms_over_the_live_set() -> None:
+ sched = Scheduler(_noop_fire, max_recheck_ms=5000)
+ assert sched._sleep_hint(0) == 5000 # no jobs -> idle poll at the cap
+ sched.add_job(_job("a", 800))
+ assert sched._sleep_hint(300) == 500
+ assert sched._sleep_hint(300) == compute_sleep_ms(sched.jobs(), 300, 5000)
+ assert sched._sleep_hint(900) == 0 # due now -> fire immediately
+
+
+def test_loop_does_not_fire_before_the_deadline_and_wakes_on_add() -> None:
+ """The kernel sleeps the hint, not a fixed tick: with the clock pinned
+ before the deadline nothing fires, and an add_job (which requests a wake)
+ re-evaluates at once instead of waiting the sleep out."""
+ fired: list[str] = []
+ now = [0]
+
+ async def on_fire(job: Job) -> None:
+ fired.append(job.id)
+
+ async def scenario() -> None:
+ sched = Scheduler(on_fire, now_fn=lambda: now[0], max_recheck_ms=60_000)
+ sched.add_job(_job("a", 10_000, "once"))
+ sched.start()
+ for _ in range(200):
+ await asyncio.sleep(0)
+ assert fired == [] # slept adaptively; deadline not reached
+ assert sched._task is not None and not sched._task.done()
+
+ now[0] = 10_000
+ sched.add_job(_job("b", 10_000, "once")) # mutation wakes the loop
+
+ async def wait_for_both() -> None:
+ while sorted(fired) != ["a", "b"]:
+ await asyncio.sleep(0.005)
+
+ await asyncio.wait_for(wait_for_both(), timeout=2.0)
+ assert sched.jobs() == [] # both one-shots removed
+ await asyncio.wait_for(sched.stop(), timeout=5.0)
+
+ asyncio.run(scenario())
+
+ assert sorted(fired) == ["a", "b"]
+
+
+def test_add_and_remove_job_request_a_wake() -> None:
+ """add_job / remove_job must cut a long adaptive sleep short — pinned via
+ a recording stand-in over the kernel's request_wake."""
+
+ class _RecordingKernel(SchedulerKernel):
+ def __init__(self) -> None:
+ super().__init__(tick_interval_ms=60_000)
+ self.wakes = 0
+
+ def request_wake(self) -> None:
+ self.wakes += 1
+
+ async def scenario() -> None:
+ sched = Scheduler(_noop_fire)
+ kernel = _RecordingKernel()
+ sched._kernel = kernel
+ sched.add_job(_job("a", 10**12))
+ assert kernel.wakes == 1
+ assert sched.remove_job("a") is True
+ assert kernel.wakes == 2
+ assert sched.remove_job("a") is False
+ assert kernel.wakes == 2 # a miss does not wake
+
+ asyncio.run(scenario())
+
+
+def test_default_max_recheck_is_unchanged() -> None:
+ sched = Scheduler(_noop_fire)
+ assert sched._max_recheck_ms == DEFAULT_MAX_RECHECK_MS == 5 * 60 * 1000
+ # No jobs: the hinted sleep is the idle-poll cap.
+ assert sched._sleep_hint(0) == DEFAULT_MAX_RECHECK_MS