Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(scheduling): add SchedulerKernel with injectable clock and backoff

shadowinlife2c6d4670dda9
diff --git a/agent/src/scheduling/__init__.py b/agent/src/scheduling/__init__.py
index 0f68bcd1b..909364a12 100644
--- a/agent/src/scheduling/__init__.py
+++ b/agent/src/scheduling/__init__.py
@@ -1,18 +1,32 @@
"""Shared scheduling kernel (scheduler unification).
-This package is the single home of the trigger vocabulary every scheduler in
-the repo can adopt:
+This package is the single home of the scheduling machinery every scheduler
+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).
+* :mod:`src.scheduling.types` — the shared vocabulary: ``ExecutorKind``,
+ the minimal ``JobLike`` protocol, ``TriggerSpec`` 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 callback seams for domain logic (nothing is wired to it yet).
-Later todos of the scheduler-unification plan add ``types.py`` (protocols),
-``kernel.py`` (tick loop), ``registry.py`` (internal callable allowlist) and
-``system_jobs.py`` (protected system jobs) beside this module.
+Later todos of the scheduler-unification plan add ``registry.py`` (internal
+callable allowlist) and ``system_jobs.py`` (protected system jobs) beside
+these modules.
"""
+from src.scheduling.kernel import (
+ DEFAULT_MAX_CONSECUTIVE_FAILURES,
+ DEFAULT_RETRY_BASE_DELAY_MS,
+ DEFAULT_RETRY_MAX_DELAY_MS,
+ DEFAULT_TICK_INTERVAL_MS,
+ DEFAULT_TASK_NAME,
+ SchedulerKernel,
+)
from src.scheduling.triggers import (
CRON_BOUNDS,
CRON_SEARCH_LIMIT_DAYS,
@@ -30,13 +44,41 @@ from src.scheduling.triggers import (
validate_timezone,
validate_timezone_shape,
)
+from src.scheduling.types import (
+ EXECUTOR_KINDS,
+ AdvanceFn,
+ ExecutorKind,
+ IsDueFn,
+ JobErrorFn,
+ JobLike,
+ NowFn,
+ OnTickFn,
+ TriggerSpec,
+ is_executor_kind,
+)
__all__ = [
"CRON_BOUNDS",
"CRON_SEARCH_LIMIT_DAYS",
+ "DEFAULT_MAX_CONSECUTIVE_FAILURES",
+ "DEFAULT_RETRY_BASE_DELAY_MS",
+ "DEFAULT_RETRY_MAX_DELAY_MS",
+ "DEFAULT_TASK_NAME",
+ "DEFAULT_TICK_INTERVAL_MS",
"DEFAULT_TRIGGER_INTERVAL_MS",
+ "EXECUTOR_KINDS",
"ONCE_SPEC",
+ "AdvanceFn",
+ "ExecutorKind",
+ "IsDueFn",
+ "JobErrorFn",
+ "JobLike",
+ "NowFn",
+ "OnTickFn",
+ "SchedulerKernel",
+ "TriggerSpec",
"day_matches",
+ "is_executor_kind",
"is_interval_schedule",
"local_wall_time_to_epoch_ms",
"next_cron_due",
diff --git a/agent/src/scheduling/kernel.py b/agent/src/scheduling/kernel.py
new file mode 100644
index 000000000..26ad53e00
--- /dev/null
+++ b/agent/src/scheduling/kernel.py
@@ -0,0 +1,324 @@
+"""Generic scheduler kernel: tick loop, wakeup, backoff, injectable clock.
+
+Extracted (scheduler-unification T2) from the loop machinery of
+``src/scheduled_research/executor.py`` so every scheduler in the repo can
+share one tick/wakeup/backoff implementation. The kernel is strictly
+generic: it knows nothing about delivery outboxes, verdicts, briefings or
+playbooks — domain logic attaches through the constructor's callback seams
+(``on_tick`` / ``is_due_fn`` / ``advance_fn`` / ``on_job_error``) and stays
+in the consumer's module.
+
+Responsibilities (the complete list):
+
+* :meth:`SchedulerKernel.start` / :meth:`SchedulerKernel.stop` /
+ :attr:`SchedulerKernel.is_running` — lifecycle of the background task,
+ with a ``task.cancel()`` fallback so shutdown never waits a full tick;
+* :meth:`SchedulerKernel._run` / :meth:`SchedulerKernel._sleep_or_wake` —
+ the tick loop with per-tick exception isolation and an ``asyncio.Event``
+ wakeup that shortens the inter-tick sleep;
+* :meth:`SchedulerKernel.request_wake` — thread-safe, coalescing request to
+ cut the current sleep short;
+* :meth:`SchedulerKernel.retry_delay_ms` — bounded exponential backoff;
+* constructor parameter validation.
+
+The kernel never reads the environment: retry knobs are plain constructor
+arguments whose defaults mirror ``AgentTuningConfig`` in
+``src/config/env_schema.py`` (``max_consecutive_failures=3``,
+``retry_base_delay_ms=60_000``, ``retry_max_delay_ms=3_600_000``); callers
+inject configured values.
+
+Single-writer invariant: one kernel instance is owned by exactly one
+composition root (the FastAPI lifespan for the scheduled-research executor).
+The kernel does not coordinate multiple owners and must not be started from
+two loops.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+from typing import Optional
+
+from src.scheduling.types import (
+ AdvanceFn,
+ IsDueFn,
+ JobErrorFn,
+ NowFn,
+ OnTickFn,
+)
+
+logger = logging.getLogger(__name__)
+
+#: Default poll interval of the background loop (mirrors the executor's
+#: ``DEFAULT_TICK_INTERVAL_MS``; consumers may override per instance).
+DEFAULT_TICK_INTERVAL_MS = 60 * 1000
+
+#: Default ``asyncio`` task name; injectable so consumers keep their own
+#: observable task identity (e.g. ``"scheduled-research-executor"``).
+DEFAULT_TASK_NAME = "scheduler-kernel"
+
+#: Mirrors of the env-schema defaults — see the module docstring. The kernel
+#: itself never touches ``os.environ``.
+DEFAULT_MAX_CONSECUTIVE_FAILURES = 3
+DEFAULT_RETRY_BASE_DELAY_MS = 60 * 1000
+DEFAULT_RETRY_MAX_DELAY_MS = 3_600_000
+
+
+def _now_ms() -> int:
+ """Return current wall-clock time in epoch milliseconds."""
+ return int(time.time() * 1000)
+
+
+class SchedulerKernel:
+ """Background tick loop with wakeup, backoff and an injectable clock.
+
+ The loop calls ``on_tick(now_ms)`` once per tick, isolates its exceptions
+ (one failing tick never kills the loop; ``asyncio.CancelledError``
+ propagates so :meth:`stop` stays bounded), then sleeps
+ ``tick_interval_ms`` unless a :meth:`request_wake` shortens the sleep.
+
+ ``is_due_fn`` / ``advance_fn`` / ``on_job_error`` are stored injection
+ seams, exposed as read-only properties: the kernel never interprets them
+ itself, but carrying the full callback set on one instance lets a
+ consumer compose its ``on_tick`` chain (due-job pass, per-job isolation,
+ error recording) against a single wiring point without reaching into
+ kernel internals.
+ """
+
+ def __init__(
+ self,
+ *,
+ tick_interval_ms: int = DEFAULT_TICK_INTERVAL_MS,
+ now_fn: NowFn = _now_ms,
+ enabled: bool = True,
+ max_consecutive_failures: int = DEFAULT_MAX_CONSECUTIVE_FAILURES,
+ retry_base_delay_ms: int = DEFAULT_RETRY_BASE_DELAY_MS,
+ retry_max_delay_ms: int = DEFAULT_RETRY_MAX_DELAY_MS,
+ on_tick: Optional[OnTickFn] = None,
+ is_due_fn: Optional[IsDueFn] = None,
+ advance_fn: Optional[AdvanceFn] = None,
+ on_job_error: Optional[JobErrorFn] = None,
+ task_name: str = DEFAULT_TASK_NAME,
+ ) -> None:
+ """Initialize the kernel.
+
+ Args:
+ 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.
+ max_consecutive_failures: Failures allowed before a consumer
+ treats a job as terminal (stored policy; the kernel itself
+ does not enforce it — see the class docstring).
+ retry_base_delay_ms: Base delay for exponential retry backoff.
+ retry_max_delay_ms: Upper bound for exponential retry backoff.
+ on_tick: Async callable invoked once per tick with ``now_ms``.
+ is_due_fn: ``(job, now_ms) -> bool`` due-ness predicate seam.
+ advance_fn: ``(job, from_ms) -> next_run_at | None`` seam.
+ on_job_error: ``(job, now_ms, exc)`` per-job failure hook seam.
+ task_name: Name of the background ``asyncio`` task.
+
+ Raises:
+ ValueError: If the retry policy is invalid.
+ """
+ if max_consecutive_failures < 1:
+ raise ValueError("max_consecutive_failures must be at least 1")
+ if retry_base_delay_ms < 0:
+ raise ValueError("retry_base_delay_ms must be non-negative")
+ if retry_max_delay_ms < retry_base_delay_ms:
+ raise ValueError("retry_max_delay_ms must be at least retry_base_delay_ms")
+ self._tick_interval_ms = tick_interval_ms
+ self._now_fn = now_fn
+ self._enabled = enabled
+ self._max_consecutive_failures = max_consecutive_failures
+ self._retry_base_delay_ms = retry_base_delay_ms
+ self._retry_max_delay_ms = retry_max_delay_ms
+ self._on_tick = on_tick
+ self._is_due_fn = is_due_fn
+ self._advance_fn = advance_fn
+ self._on_job_error = on_job_error
+ self._task_name = task_name
+ self._loop: asyncio.AbstractEventLoop | None = None
+ self._task: asyncio.Task | None = None
+ self._wakeup: asyncio.Event | None = None
+ self._stopping = False
+
+ # -- policy surface (read-only) -----------------------------------------
+
+ @property
+ def tick_interval_ms(self) -> int:
+ """Return the poll interval of the background loop."""
+ return self._tick_interval_ms
+
+ @property
+ def enabled(self) -> bool:
+ """Return whether start/stop manage a background task at all."""
+ return self._enabled
+
+ @property
+ def max_consecutive_failures(self) -> int:
+ """Return the stored failure budget of the retry policy."""
+ return self._max_consecutive_failures
+
+ @property
+ def retry_base_delay_ms(self) -> int:
+ """Return the base delay of the retry policy."""
+ return self._retry_base_delay_ms
+
+ @property
+ def retry_max_delay_ms(self) -> int:
+ """Return the upper bound of the retry policy."""
+ return self._retry_max_delay_ms
+
+ @property
+ def task_name(self) -> str:
+ """Return the name given to the background task on :meth:`start`."""
+ return self._task_name
+
+ @property
+ def on_tick(self) -> Optional[OnTickFn]:
+ """Return the injected per-tick callback (the only one the loop calls)."""
+ return self._on_tick
+
+ @property
+ def is_due_fn(self) -> Optional[IsDueFn]:
+ """Return the injected due-ness predicate seam."""
+ return self._is_due_fn
+
+ @property
+ def advance_fn(self) -> Optional[AdvanceFn]:
+ """Return the injected next-run advancement seam."""
+ return self._advance_fn
+
+ @property
+ def on_job_error(self) -> Optional[JobErrorFn]:
+ """Return the injected per-job error hook seam."""
+ return self._on_job_error
+
+ # -- lifecycle ------------------------------------------------------------
+
+ @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. Must be called from the
+ event loop that will own the task.
+ """
+ if not self._enabled or self.is_running:
+ return
+ self._stopping = False
+ self._wakeup = asyncio.Event()
+ loop = asyncio.get_running_loop()
+ self._task = loop.create_task(self._run(), name=self._task_name)
+
+ 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. Bounded
+ even when a tick is wedged: the wakeup set below releases a sleeping
+ loop in the common case, and ``task.cancel()`` is the fallback so
+ shutdown never blocks for a full tick (or forever) if the wakeup
+ raced the loop's sleep or the tick itself is stuck.
+ """
+ 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()
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ self._task = None
+
+ # -- loop internals -------------------------------------------------------
+
+ async def _run(self) -> None:
+ # Captured here rather than at construction: the kernel is built
+ # before the owner's loop exists, and request_wake needs a loop that
+ # is actually running to schedule onto.
+ self._loop = asyncio.get_running_loop()
+ while not self._stopping:
+ try:
+ if self._on_tick is not None:
+ await self._on_tick(self._now_fn())
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ # Per-tick isolation: one failing tick must not kill the
+ # loop; the next tick runs on schedule.
+ logger.error("scheduler kernel 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
+
+ # -- cross-thread wakeup ----------------------------------------------------
+
+ def request_wake(self) -> None:
+ """Ask the loop to cut its current sleep short, as soon as it can.
+
+ Thread-safe: called from whichever thread an event arrives on, so it
+ must not block and must not touch the loop directly. Wakes coalesce:
+ a wakeup already pending (set but not yet consumed by the loop)
+ covers anything that arrives while it is pending, so a second request
+ is a no-op. Without a running loop this is a no-op — the periodic
+ tick is what makes the consumer correct, and this only makes it
+ prompt.
+ """
+ loop = self._loop
+ if loop is None or not loop.is_running():
+ return
+ wakeup = self._wakeup
+ if wakeup is None or wakeup.is_set():
+ return
+ try:
+ loop.call_soon_threadsafe(self._set_wakeup)
+ except RuntimeError:
+ # The loop closed between the check and the call; the next tick
+ # (or the owner's shutdown path) picks the work up.
+ pass
+
+ def _set_wakeup(self) -> None:
+ """Set the wakeup event; runs on the loop thread via call_soon."""
+ if self._wakeup is not None:
+ self._wakeup.set()
+
+ # -- retry policy -----------------------------------------------------------
+
+ def retry_delay_ms(self, consecutive_failures: int) -> int:
+ """Return bounded exponential backoff for a failure count.
+
+ ``1 -> base``, ``2 -> 2*base``, ``3 -> 4*base`` … clamped by
+ ``retry_max_delay_ms``; a zero base disables backoff entirely. The
+ exponent is capped at 62 so absurd failure counts cannot overflow
+ into slow big-int arithmetic.
+ """
+ exponent = max(0, consecutive_failures - 1)
+ if self._retry_base_delay_ms == 0:
+ return 0
+ delay = self._retry_base_delay_ms * (2 ** min(exponent, 62))
+ return min(delay, self._retry_max_delay_ms)
diff --git a/agent/src/scheduling/types.py b/agent/src/scheduling/types.py
new file mode 100644
index 000000000..42c3a0db6
--- /dev/null
+++ b/agent/src/scheduling/types.py
@@ -0,0 +1,176 @@
+"""Shared vocabulary types for the scheduling kernel (scheduler-unification T2).
+
+Three pieces live here, all pure and domain-free:
+
+* :data:`ExecutorKind` — how a job is executed (``"prompt"`` dispatches an
+ agent session; ``"internal"`` runs a registered in-process callable). The
+ value domain is defined here once so job models and registries cannot
+ drift apart.
+* :class:`JobLike` — the structural job surface a generic scheduler may rely
+ on. Deliberately minimal: delivery / verdict / briefing / playbook fields
+ belong to the ``scheduled_research`` domain and are NOT part of this
+ protocol.
+* :class:`TriggerSpec` — one trigger specification (schedule string plus the
+ IANA timezone a cron schedule is evaluated in) behind a single value
+ object, unifying the scheduled-research grammar with the ``once`` kind
+ absorbed from the live runtime (see :mod:`src.scheduling.triggers`).
+
+The callback type aliases at the bottom are the injection seams of
+:class:`src.scheduling.kernel.SchedulerKernel`; they are declared here so the
+kernel module stays free of domain imports.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Awaitable, Callable, Literal, Optional, Protocol, runtime_checkable
+
+from src.scheduling.triggers import (
+ ONCE_SPEC,
+ next_due,
+ next_once_due,
+ validate_schedule,
+ validate_timezone,
+)
+
+# ---------------------------------------------------------------------------
+# Executor kind
+# ---------------------------------------------------------------------------
+
+#: How a job is executed: ``"prompt"`` dispatches an agent session (the only
+#: kind that exists today), ``"internal"`` runs a callable from the explicit
+#: in-process registry (added by later todos of the scheduler-unification
+#: plan; nothing consumes it yet).
+ExecutorKind = Literal["prompt", "internal"]
+
+#: The closed value domain of :data:`ExecutorKind`, for runtime validation.
+EXECUTOR_KINDS: tuple[str, ...] = ("prompt", "internal")
+
+
+def is_executor_kind(value: object) -> bool:
+ """Return whether *value* is a member of :data:`EXECUTOR_KINDS`."""
+ return value in EXECUTOR_KINDS
+
+
+# ---------------------------------------------------------------------------
+# Job protocol
+# ---------------------------------------------------------------------------
+
+
+@runtime_checkable
+class JobLike(Protocol):
+ """The structural job surface the kernel and its callbacks may rely on.
+
+ Only the attributes a generic scheduler needs to decide due-ness, advance
+ the next run and reason about retries are required here. Domain fields
+ (delivery outbox, verdict records, briefing text, playbook provenance)
+ stay in ``scheduled_research`` — consumers that need them accept the
+ concrete job type in their own callbacks.
+
+ ``isinstance`` checks work structurally (``runtime_checkable`` verifies
+ attribute presence, not types), so existing dataclass jobs satisfy this
+ protocol without inheriting from it.
+ """
+
+ #: Stable job identifier.
+ id: str
+ #: Epoch-millisecond timestamp of the next intended run.
+ next_run_at: int
+ #: Lifecycle status. Domain status enums are ``str``-valued and satisfy
+ #: this annotation without the kernel importing them.
+ status: str
+ #: Trigger schedule string (see :mod:`src.scheduling.triggers`).
+ schedule: str
+ #: IANA timezone key a cron schedule is evaluated in, or ``None`` (UTC).
+ timezone: Optional[str]
+ #: Consecutive dispatch failures, driving retry backoff.
+ consecutive_failures: int
+
+
+# ---------------------------------------------------------------------------
+# Trigger specification
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True, slots=True)
+class TriggerSpec:
+ """One trigger specification: a schedule string plus its timezone.
+
+ Wraps the two trigger kinds of the shared vocabulary behind a single
+ value object:
+
+ * the scheduled-research grammar — a bare ``"<ms>"`` interval string or a
+ simplified 5-field cron expression evaluated on the wall clock of
+ ``timezone`` (UTC when ``None``);
+ * the ``once`` kind absorbed from the live runtime — fires exactly once
+ and has no next run, so :meth:`next_due_after` returns ``None``.
+
+ The live runtime's ``"interval:<ms>"`` spelling is intentionally out of
+ scope for this value object; callers that need it use
+ :func:`src.scheduling.triggers.next_once_due` directly.
+
+ Construction is tolerant (no implicit validation), mirroring the repo's
+ forgiving ``from_dict`` philosophy; call :meth:`validate` explicitly to
+ reject an unusable spec.
+ """
+
+ schedule: str
+ timezone: Optional[str] = None
+
+ @property
+ def is_once(self) -> bool:
+ """Return whether this is the one-shot ``once`` kind."""
+ return self.schedule.strip().lower() == ONCE_SPEC
+
+ def validate(self) -> None:
+ """Raise when the spec cannot be used to compute next runs.
+
+ Delegates to :func:`src.scheduling.triggers.validate_schedule` and
+ :func:`src.scheduling.triggers.validate_timezone` for the research
+ grammar. The ``once`` kind carries no grammar to validate and is
+ always accepted (its timezone is ignored, as for interval schedules).
+ """
+ if self.is_once:
+ return
+ validate_schedule(self.schedule)
+ validate_timezone(self.timezone)
+
+ def next_due_after(self, after_ms: int) -> Optional[int]:
+ """Return the next due epoch-ms strictly after *after_ms*.
+
+ ``None`` means the trigger never fires again (the one-shot ``once``
+ kind). Cron window exhaustion propagates the ``ValueError`` raised by
+ :func:`src.scheduling.triggers.next_due` rather than being swallowed.
+ """
+ if self.is_once:
+ return next_once_due(self.schedule, after_ms)
+ return next_due(self.schedule, after_ms, self.timezone)
+
+
+# ---------------------------------------------------------------------------
+# Kernel callback seams
+# ---------------------------------------------------------------------------
+
+#: Injectable wall-clock source returning epoch milliseconds.
+NowFn = Callable[[], int]
+
+#: Called by the kernel loop once per tick with the current epoch-ms. The
+#: kernel isolates exceptions per tick (one failing tick never kills the
+#: loop); ``asyncio.CancelledError`` propagates so ``stop()`` stays bounded.
+OnTickFn = Callable[[int], Awaitable[None]]
+
+#: ``(job, now_ms) -> due?`` Pure predicate deciding whether *job* should
+#: fire at *now_ms*. The domain owns the gates (terminal statuses, end
+#: boundaries, in-flight deliveries); the kernel never interprets them.
+IsDueFn = Callable[[JobLike, int], bool]
+
+#: ``(job, from_ms) -> next_run_at | None`` Pure computation of the next run
+#: epoch-ms strictly after *from_ms*, or ``None`` when the trigger does not
+#: fire again. Grammar errors (e.g. cron window exhaustion) surface as
+#: ``ValueError`` for the domain's error hook to record.
+AdvanceFn = Callable[[JobLike, int], Optional[int]]
+
+#: ``(job, now_ms, exc)`` Hook for per-job failures, invoked by the domain's
+#: tick composition inside its per-job isolation. Synchronous by contract:
+#: it records (log / persist) and must not re-raise.
+JobErrorFn = Callable[[JobLike, int, Exception], None]
diff --git a/agent/tests/scheduling/test_kernel.py b/agent/tests/scheduling/test_kernel.py
new file mode 100644
index 000000000..bba8d900d
--- /dev/null
+++ b/agent/tests/scheduling/test_kernel.py
@@ -0,0 +1,465 @@
+"""Tests for the generic scheduler kernel (src/scheduling/kernel.py) and the
+shared vocabulary types (src/scheduling/types.py), scheduler-unification T2.
+
+House style (see test_runtime_scheduler.py): async scenarios are driven with
+``asyncio.run`` — no pytest-asyncio in this repo — with an injected ``now_fn``
+instead of the wall clock, ``asyncio.sleep(0)`` yield loops or ``asyncio.Event``
+handshakes instead of real waiting, and ``asyncio.wait_for`` timeouts so a wedged
+kernel fails the test instead of hanging the suite.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import itertools
+import threading
+import time
+from dataclasses import dataclass
+from datetime import datetime, timezone
+
+import pytest
+
+from src.scheduling.kernel import (
+ DEFAULT_TASK_NAME,
+ SchedulerKernel,
+ _now_ms,
+)
+from src.scheduling.types import (
+ EXECUTOR_KINDS,
+ JobLike,
+ TriggerSpec,
+ is_executor_kind,
+)
+
+# ---- happy path: tick ordering with an injected clock ----------------------
+
+
+def test_three_ticks_run_in_order_with_injected_clock() -> None:
+ """QA happy: 3 ticks, on_tick receives strictly increasing now_ms."""
+ ticks: list[int] = []
+ clock = itertools.count(1000, 1000)
+
+ async def scenario() -> None:
+ done = asyncio.Event()
+
+ async def on_tick(now_ms: int) -> None:
+ ticks.append(now_ms)
+ if len(ticks) >= 3:
+ done.set()
+
+ kernel = SchedulerKernel(tick_interval_ms=1, now_fn=lambda: next(clock), on_tick=on_tick)
+ kernel.start()
+ await asyncio.wait_for(done.wait(), timeout=5.0)
+ assert kernel.is_running
+ await asyncio.wait_for(kernel.stop(), timeout=5.0)
+
+ asyncio.run(scenario())
+
+ assert len(ticks) >= 3
+ assert ticks[:3] == [1000, 2000, 3000]
+ assert all(b > a for a, b in zip(ticks, ticks[1:]))
+
+
+def test_start_stop_roundtrip_is_idempotent() -> None:
+ async def scenario() -> None:
+ ticks: list[int] = []
+
+ async def on_tick(now_ms: int) -> None:
+ ticks.append(now_ms)
+
+ kernel = SchedulerKernel(tick_interval_ms=5, on_tick=on_tick)
+ kernel.start()
+ kernel.start() # idempotent: still exactly one task
+ assert kernel.is_running
+ await asyncio.sleep(0.02)
+ await asyncio.wait_for(kernel.stop(), timeout=5.0)
+ assert not kernel.is_running
+ assert kernel._task is None
+ assert ticks # the loop really ticked
+ await asyncio.wait_for(kernel.stop(), timeout=5.0) # idempotent
+
+ asyncio.run(scenario())
+
+
+def test_task_name_is_injectable() -> None:
+ async def scenario() -> None:
+ kernel = SchedulerKernel(tick_interval_ms=60_000, task_name="my-kernel")
+ kernel.start()
+ assert kernel._task is not None
+ assert kernel._task.get_name() == "my-kernel"
+ await asyncio.wait_for(kernel.stop(), timeout=5.0)
+
+ default = SchedulerKernel(tick_interval_ms=60_000)
+ default.start()
+ assert default._task is not None
+ assert default._task.get_name() == DEFAULT_TASK_NAME == "scheduler-kernel"
+ await asyncio.wait_for(default.stop(), timeout=5.0)
+
+ asyncio.run(scenario())
+
+
+def test_disabled_kernel_start_and_stop_are_noops() -> None:
+ async def scenario() -> None:
+ called: list[int] = []
+
+ async def on_tick(now_ms: int) -> None:
+ called.append(now_ms)
+
+ kernel = SchedulerKernel(enabled=False, on_tick=on_tick)
+ kernel.start()
+ assert not kernel.is_running
+ await asyncio.wait_for(kernel.stop(), timeout=0.5)
+ assert called == []
+
+ asyncio.run(scenario())
+
+
+def test_default_now_fn_is_wall_clock_ms() -> None:
+ before = time.time() * 1000
+ assert abs(_now_ms() - before) < 2000
+ assert SchedulerKernel()._now_fn is _now_ms
+
+
+# ---- wakeup shortens the inter-tick sleep ----------------------------------
+
+
+def test_request_wake_shortens_a_long_sleep() -> None:
+ """Without the wake the second tick would be a full 60s away."""
+ ticks: list[int] = []
+
+ async def scenario() -> None:
+ second = asyncio.Event()
+
+ async def on_tick(now_ms: int) -> None:
+ ticks.append(now_ms)
+ if len(ticks) >= 2:
+ second.set()
+
+ kernel = SchedulerKernel(tick_interval_ms=60_000, on_tick=on_tick)
+ kernel.start()
+ for _ in range(1000):
+ await asyncio.sleep(0)
+ if ticks:
+ break
+ assert ticks, "first tick did not run"
+ kernel.request_wake()
+ await asyncio.wait_for(second.wait(), timeout=2.0)
+ await asyncio.wait_for(kernel.stop(), timeout=5.0)
+
+ asyncio.run(scenario())
+
+ assert len(ticks) >= 2
+
+
+def test_request_wake_from_another_thread_wakes_the_loop() -> None:
+ """The real cross-thread path: call_soon_threadsafe onto the running loop."""
+ ticks: list[int] = []
+
+ async def scenario() -> None:
+ second = asyncio.Event()
+
+ async def on_tick(now_ms: int) -> None:
+ ticks.append(now_ms)
+ if len(ticks) >= 2:
+ second.set()
+
+ kernel = SchedulerKernel(tick_interval_ms=60_000, on_tick=on_tick)
+ kernel.start()
+ for _ in range(1000):
+ await asyncio.sleep(0)
+ if ticks:
+ break
+ assert ticks, "first tick did not run"
+ thread = threading.Thread(target=kernel.request_wake)
+ thread.start()
+ await asyncio.wait_for(second.wait(), timeout=2.0)
+ thread.join(timeout=2.0)
+ assert not thread.is_alive()
+ await asyncio.wait_for(kernel.stop(), timeout=5.0)
+
+ asyncio.run(scenario())
+
+ assert len(ticks) >= 2
+
+
+# ---- request_wake: no-loop no-op, coalescing, closed-loop tolerance ---------
+
+
+class _RecordingLoop:
+ """Stand-in exposing exactly the loop surface request_wake touches."""
+
+ def __init__(self, *, running: bool = True, raise_on_schedule: bool = False) -> None:
+ self._running = running
+ self._raise_on_schedule = raise_on_schedule
+ self.scheduled: list[tuple] = []
+
+ def is_running(self) -> bool:
+ return self._running
+
+ def call_soon_threadsafe(self, fn, *args) -> None:
+ if self._raise_on_schedule:
+ raise RuntimeError("Event loop is closed")
+ self.scheduled.append((fn, args))
+
+
+def test_request_wake_without_a_running_loop_is_a_noop() -> None:
+ """Construction happens before the owner's loop exists."""
+ kernel = SchedulerKernel()
+
+ kernel.request_wake() # must not raise
+
+ assert kernel._loop is None
+ assert kernel._wakeup is None
+
+
+def test_request_wake_coalesces_and_tolerates_a_closed_loop() -> None:
+ async def scenario() -> None:
+ kernel = SchedulerKernel()
+ loop = _RecordingLoop()
+ kernel._loop = loop
+ kernel._wakeup = asyncio.Event()
+
+ # Nothing pending -> exactly one wake is scheduled.
+ kernel.request_wake()
+ assert len(loop.scheduled) == 1
+ fn, args = loop.scheduled[0]
+ fn(*args)
+ assert kernel._wakeup.is_set()
+
+ # A wake is pending (set but unconsumed) -> coalesced, nothing new.
+ kernel.request_wake()
+ kernel.request_wake()
+ assert len(loop.scheduled) == 1
+
+ # Once consumed, the next request schedules again.
+ kernel._wakeup.clear()
+ kernel.request_wake()
+ assert len(loop.scheduled) == 2
+
+ # Loop not running -> no-op.
+ stopped = _RecordingLoop(running=False)
+ kernel._loop = stopped
+ kernel._wakeup.clear()
+ kernel.request_wake()
+ assert stopped.scheduled == []
+
+ # Loop closes between the check and the call -> RuntimeError tolerated.
+ closing = _RecordingLoop(raise_on_schedule=True)
+ kernel._loop = closing
+ kernel.request_wake() # must not raise
+
+ asyncio.run(scenario())
+
+
+# ---- _sleep_or_wake ---------------------------------------------------------
+
+
+def test_sleep_or_wake_without_a_wakeup_event_uses_bare_sleep() -> None:
+ async def scenario() -> None:
+ kernel = SchedulerKernel()
+ assert kernel._wakeup is None
+ started = time.monotonic()
+ await asyncio.wait_for(kernel._sleep_or_wake(20), timeout=1.0)
+ assert time.monotonic() - started >= 0.015
+
+ asyncio.run(scenario())
+
+
+def test_sleep_or_wake_returns_at_once_when_stopping() -> None:
+ """stop() between the loop's check and the sleep must not wait a tick."""
+ async def scenario() -> None:
+ kernel = SchedulerKernel()
+ kernel._wakeup = asyncio.Event()
+ kernel._stopping = True
+ started = time.monotonic()
+ await asyncio.wait_for(kernel._sleep_or_wake(60_000), timeout=0.5)
+ assert time.monotonic() - started < 0.5
+
+ asyncio.run(scenario())
+
+
+# ---- failure isolation and bounded stop -------------------------------------
+
+
+def test_on_tick_exception_does_not_kill_the_loop() -> None:
+ """QA (a): the first two ticks raise; the kernel survives and keeps ticking."""
+ attempts: list[int] = []
+ clock = itertools.count(1000, 1000)
+
+ async def on_tick(now_ms: int) -> None:
+ attempts.append(now_ms)
+ if len(attempts) <= 2:
+ raise RuntimeError("boom")
+
+ async def scenario() -> None:
+ kernel = SchedulerKernel(tick_interval_ms=1, now_fn=lambda: next(clock), on_tick=on_tick)
+ kernel.start()
+
+ async def wait_for_third_attempt() -> None:
+ while len(attempts) < 3:
+ await asyncio.sleep(0.005)
+
+ await asyncio.wait_for(wait_for_third_attempt(), timeout=5.0)
+ assert kernel.is_running # survived both exceptions
+ await asyncio.wait_for(kernel.stop(), timeout=5.0)
+
+ asyncio.run(scenario())
+
+ assert len(attempts) >= 3
+ assert attempts[:3] == [1000, 2000, 3000]
+
+
+def test_stop_is_bounded_when_a_tick_blocks() -> None:
+ """QA (b): on_tick wedges forever; stop() returns via cancel() within 1s."""
+
+ async def scenario() -> None:
+ entered = asyncio.Event()
+
+ async def on_tick(_now_ms: int) -> None:
+ entered.set()
+ await asyncio.Event().wait() # wedge forever
+
+ kernel = SchedulerKernel(tick_interval_ms=5, on_tick=on_tick)
+ kernel.start()
+ await asyncio.wait_for(entered.wait(), timeout=5.0)
+ # If cancel() did not break the wedged tick, wait_for raises
+ # TimeoutError and this test FAILs.
+ await asyncio.wait_for(kernel.stop(), timeout=1.0)
+ assert not kernel.is_running
+
+ asyncio.run(scenario())
+
+
+# ---- retry backoff ------------------------------------------------------------
+
+
+def test_retry_delay_backoff_sequence_is_clamped() -> None:
+ kernel = SchedulerKernel(retry_base_delay_ms=1000, retry_max_delay_ms=5000)
+ assert kernel.retry_delay_ms(1) == 1000
+ assert kernel.retry_delay_ms(2) == 2000
+ assert kernel.retry_delay_ms(3) == 4000
+ assert kernel.retry_delay_ms(4) == 5000 # 8000 clamped to max
+ assert kernel.retry_delay_ms(5) == 5000
+ assert kernel.retry_delay_ms(100) == 5000 # exponent capped, still clamped
+ assert kernel.retry_delay_ms(0) == 1000 # exponent floors at 0
+
+
+def test_retry_delay_zero_base_disables_backoff() -> None:
+ kernel = SchedulerKernel(retry_base_delay_ms=0, retry_max_delay_ms=0)
+ assert kernel.retry_delay_ms(1) == 0
+ assert kernel.retry_delay_ms(10) == 0
+
+
+# ---- constructor validation ----------------------------------------------------
+
+
+def test_ctor_rejects_invalid_retry_policy() -> None:
+ """QA (c): invalid knobs raise ValueError with the executor's messages."""
+ with pytest.raises(ValueError, match="max_consecutive_failures must be at least 1"):
+ SchedulerKernel(max_consecutive_failures=0)
+ with pytest.raises(ValueError, match="retry_base_delay_ms must be non-negative"):
+ SchedulerKernel(retry_base_delay_ms=-1)
+ with pytest.raises(ValueError, match="retry_max_delay_ms must be at least retry_base_delay_ms"):
+ SchedulerKernel(retry_base_delay_ms=1000, retry_max_delay_ms=999)
+
+
+# ---- callback seams and policy surface ------------------------------------------
+
+
+def test_callback_seams_and_knobs_are_exposed_read_only() -> None:
+ async def on_tick(now_ms: int) -> None:
+ return None
+
+ def is_due(job, now_ms: int) -> bool:
+ return True
+
+ def advance(job, from_ms: int) -> int | None:
+ return None
+
+ def on_err(job, now_ms: int, exc: Exception) -> None:
+ return None
+
+ kernel = SchedulerKernel(
+ tick_interval_ms=1234,
+ enabled=False,
+ max_consecutive_failures=5,
+ retry_base_delay_ms=10,
+ retry_max_delay_ms=20,
+ on_tick=on_tick,
+ is_due_fn=is_due,
+ advance_fn=advance,
+ on_job_error=on_err,
+ task_name="k",
+ )
+
+ assert kernel.on_tick is on_tick
+ assert kernel.is_due_fn is is_due
+ assert kernel.advance_fn is advance
+ assert kernel.on_job_error is on_err
+ assert kernel.tick_interval_ms == 1234
+ assert kernel.max_consecutive_failures == 5
+ assert (kernel.retry_base_delay_ms, kernel.retry_max_delay_ms) == (10, 20)
+ assert kernel.enabled is False
+ assert kernel.task_name == "k"
+ with pytest.raises(AttributeError):
+ kernel.tick_interval_ms = 1 # read-only property
+
+
+# ---- types: ExecutorKind / JobLike / TriggerSpec --------------------------------
+
+
+def test_executor_kind_domain_is_closed() -> None:
+ assert EXECUTOR_KINDS == ("prompt", "internal")
+ assert is_executor_kind("prompt")
+ assert is_executor_kind("internal")
+ assert not is_executor_kind("shell")
+ assert not is_executor_kind(None)
+ assert not is_executor_kind("")
+
+
+def test_joblike_matches_structurally_and_rejects_partial_jobs() -> None:
+ @dataclass
+ class DummyJob:
+ id: str
+ next_run_at: int
+ status: str
+ schedule: str
+ timezone: str | None
+ consecutive_failures: int
+
+ assert isinstance(DummyJob("j1", 1000, "pending", "5000", None, 0), JobLike)
+
+ class Partial:
+ id = "x"
+ next_run_at = 0
+
+ assert not isinstance(Partial(), JobLike)
+
+
+def test_trigger_spec_once_has_no_next_run() -> None:
+ spec = TriggerSpec("once")
+ assert spec.is_once
+ spec.validate() # the once kind is always accepted
+ assert spec.next_due_after(5000) is None
+ assert TriggerSpec(" ONCE ").is_once # compared stripped + case-insensitively
+
+
+def test_trigger_spec_interval_and_cron_next_due() -> None:
+ assert TriggerSpec("5000").next_due_after(1000) == 6000
+
+ spec = TriggerSpec("0 4 * * *", "UTC")
+ spec.validate()
+ after = 1_760_000_000_000 # 2025-10-09T08:53:20Z
+ nxt = spec.next_due_after(after)
+ assert nxt is not None and nxt > after
+ fired = datetime.fromtimestamp(nxt / 1000, tz=timezone.utc)
+ assert (fired.hour, fired.minute) == (4, 0)
+
+
+def test_trigger_spec_validate_rejects_bad_grammar_and_timezone() -> None:
+ with pytest.raises(ValueError):
+ TriggerSpec("bogus").validate()
+ with pytest.raises(ValueError):
+ TriggerSpec("0 4 * * *", "Mars/Olympus_Mons").validate()
+ # Construction itself stays tolerant; only validate() rejects.
+ TriggerSpec("bogus")