Skip to content

"Vibe-Trading: Your Personal Trading Agent"

refactor(scheduling): extract trigger grammar and next-due math

shadowinlife5e09ef15ef2e
diff --git a/agent/src/scheduled_research/executor.py b/agent/src/scheduled_research/executor.py
index b14fcb118..26886af9a 100644
--- a/agent/src/scheduled_research/executor.py
+++ b/agent/src/scheduled_research/executor.py
@@ -11,21 +11,16 @@ from __future__ import annotations
import asyncio
import logging
import time
-from datetime import date, datetime, timedelta, timezone, tzinfo
from typing import Awaitable, Callable, Optional
-from zoneinfo import ZoneInfo
from src.config.accessor import get_env_config
from src.channels.bus.events import DeliveryReceipt
from src.scheduled_research.models import (
- CRON_BOUNDS,
DeliveryRecord,
DeliveryStatus,
JobStatus,
ScheduledResearchJob,
- parse_cron_field,
validate_schedule,
- validate_timezone,
)
from src.scheduled_research.store import ScheduledResearchJobStore
from src.scheduled_research.verdict import (
@@ -37,6 +32,24 @@ from src.scheduled_research.verdict import (
from dataclasses import replace as _dc_replace
from src.tools.redaction import redact_internal_paths, redact_text
+# --- Schedule math, moved to src.scheduling.triggers (scheduler unification) ---
+# Re-exported here so existing ``from src.scheduled_research.executor import ...``
+# keeps working (same convention as src/agent/loop.py's llm_usage re-export).
+from src.scheduling.triggers import (
+ CRON_BOUNDS as CRON_BOUNDS,
+ CRON_SEARCH_LIMIT_DAYS as CRON_SEARCH_LIMIT_DAYS,
+ _CRON_SEARCH_LIMIT_DAYS as _CRON_SEARCH_LIMIT_DAYS,
+ _day_matches as _day_matches,
+ _local_wall_time_to_epoch_ms as _local_wall_time_to_epoch_ms,
+ _next_cron_due as _next_cron_due,
+ day_matches as day_matches,
+ local_wall_time_to_epoch_ms as local_wall_time_to_epoch_ms,
+ next_cron_due as next_cron_due,
+ next_due as next_due,
+ parse_cron_field as parse_cron_field,
+ validate_timezone as validate_timezone,
+)
+
logger = logging.getLogger(__name__)
DEFAULT_TICK_INTERVAL_MS = 60 * 1000
@@ -57,12 +70,6 @@ BriefingReader = Callable[[str], Optional[tuple[str, str]]]
ChannelSender = Callable[..., Awaitable[DeliveryReceipt | 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; the extra headroom absorbs a
-# yearly occurrence landing in a DST spring-forward gap (skipped by policy)
-# several years in a row before a real instant exists again.
-_CRON_SEARCH_LIMIT_DAYS = 6 * 366 + 1
def _now_ms() -> int:
@@ -118,79 +125,6 @@ def _persisted_error(exc: Exception) -> str:
return f"{safe[: _MAX_PERSISTED_ERROR_CHARS - 3]}..."
-def next_due(schedule: str, after_ms: int, tz: str | None = None) -> 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.
- Cron is evaluated on the wall clock of *tz* (an IANA timezone key) when
- one is given, in UTC otherwise — the semantics every job had before the
- field existed. Interval schedules ignore *tz* entirely.
- """
- validate_schedule(schedule)
- spec = schedule.strip()
- if spec.isdigit():
- # Before the timezone check: interval schedules must keep advancing
- # even when the stored key cannot resolve on this host.
- return after_ms + int(spec)
- validate_timezone(tz)
- return _next_cron_due(spec, after_ms, tz)
-
-
-def _next_cron_due(schedule: str, after_ms: int, tz: str | None = None) -> int:
- minutes, hours, doms, months, dows = (
- parse_cron_field(part, low, high) for part, (low, high) in zip(schedule.split(), CRON_BOUNDS)
- )
- zone = timezone.utc if tz is None else ZoneInfo(tz)
- # Walk candidates on the *local* calendar of ``zone`` so field matching —
- # the weekday in particular — follows the authoring wall clock. Ascending
- # wall order maps to ascending UTC order under a fixed fold policy, so
- # "strictly after" stays a plain epoch comparison.
- day = datetime.fromtimestamp(after_ms / 1000.0, zone).date()
- 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_ms = _local_wall_time_to_epoch_ms(candidate_day, hour, minute, zone)
- if fire_ms is not None and fire_ms > after_ms:
- return fire_ms
- raise ValueError(f"cron schedule has no matching time within search window: {schedule!r}")
-
-
-def _local_wall_time_to_epoch_ms(day: date, hour: int, minute: int, zone: tzinfo) -> int | None:
- """Resolve one local wall time to a UTC epoch-ms instant.
-
- DST policy (#953): a nonexistent wall time — the spring-forward gap —
- returns ``None`` so the occurrence is skipped; ``ZoneInfo`` would
- otherwise silently map it past the transition (PEP 495) and run it. An
- ambiguous wall time — the fall-back fold — resolves with ``fold=0``, the
- first occurrence, so it runs exactly once.
- """
- local = datetime(day.year, day.month, day.day, hour, minute, tzinfo=zone)
- as_utc = local.astimezone(timezone.utc)
- if as_utc.astimezone(zone).replace(tzinfo=None) != local.replace(tzinfo=None):
- return None # wall time does not exist in this zone (DST gap)
- return int(as_utc.timestamp() * 1000)
-
-
-def _day_matches(dt: date, doms: set[int] | None, months: set[int] | None, dows: set[int] | None) -> bool:
- if months is not None and dt.month not in months:
- return False
-
- cron_day_of_week = (dt.weekday() + 1) % 7 # cron convention: Sunday == 0
- day_of_month_matches = doms is None or dt.day in doms
- day_of_week_matches = dows is None or cron_day_of_week in dows
-
- # Standard five-field cron treats day-of-month and day-of-week as an OR
- # when both fields are restricted. A wildcard in either field keeps the
- # other field authoritative.
- if doms is not None and dows is not None:
- return day_of_month_matches or day_of_week_matches
- return day_of_month_matches and day_of_week_matches
-
-
class ScheduledResearchExecutor:
"""Background poller that dispatches due scheduled research jobs."""
diff --git a/agent/src/scheduled_research/models.py b/agent/src/scheduled_research/models.py
index 523290b19..dd5fa097a 100644
--- a/agent/src/scheduled_research/models.py
+++ b/agent/src/scheduled_research/models.py
@@ -9,172 +9,26 @@ to a follow-up PR once the product shape is confirmed.
from __future__ import annotations
import logging
-import re
import time
from dataclasses import dataclass, field
from enum import Enum
-from typing import Any, Dict, Optional, Set
-from zoneinfo import ZoneInfo
+from typing import Any, Dict, Optional
from .verdict import VerdictRecord
-logger = logging.getLogger(__name__)
-
-# ---------------------------------------------------------------------------
-# Schedule validation
-# ---------------------------------------------------------------------------
-
-# Accept either:
-# * a bare positive integer (interval in milliseconds), e.g. "60000"
-# * a simplified cron expression with 5 fields, e.g. "0 */6 * * *"
-# Fields: minute hour day-of-month month day-of-week
-# Each field may be: *, */n, or a comma-separated list of numbers and
-# low-high ranges (e.g. "1-5", "1,3,5", "1,3-5")
-_INTERVAL_MS_RE = re.compile(r"^[1-9][0-9]*$")
-_CRON_STEP_RE = re.compile(r"^\*/[1-9][0-9]*$")
-_CRON_ATOM_RE = re.compile(r"^([0-9]+)(?:-([0-9]+))?$")
-_CRON_PARTS = 5
-# Inclusive (low, high) bounds per cron field: minute hour day-of-month month
-# day-of-week. Every number in a field — a bare value, a ``*/n`` step, or
-# either end of a range — is validated against these bounds so out-of-range
-# values (e.g. minute ``99``) are rejected. Day-of-week uses the cron
-# convention Sunday == 0; ``7`` is not accepted as a Sunday alias.
-CRON_BOUNDS = ((0, 59), (0, 23), (1, 31), (1, 12), (0, 6))
-
-
-def _validate_cron_field(part: str, low: int, high: int) -> None:
- """Raise ``ValueError`` when one cron field is malformed or out of range."""
- if part == "*":
- return
- if _CRON_STEP_RE.fullmatch(part):
- value = int(part[2:])
- if not low <= value <= high:
- raise ValueError(f"cron field {part!r} is out of range; expected {low}-{high}")
- return
- for atom in part.split(","):
- match = _CRON_ATOM_RE.fullmatch(atom)
- if match is None:
- raise ValueError(
- f"cron field {part!r} is not valid; each field must be *, */n, "
- f"or a comma-separated list of numbers and low-high ranges"
- )
- start = int(match.group(1))
- end = int(match.group(2)) if match.group(2) is not None else start
- if start > end:
- raise ValueError(f"cron range {atom!r} is reversed; expected low-high")
- if start < low or end > high:
- raise ValueError(f"cron field {atom!r} is out of range; expected {low}-{high}")
-
-
-def parse_cron_field(part: str, low: int, high: int) -> Optional[Set[int]]:
- """Expand one validated cron field into its matching values.
-
- Kept beside :func:`validate_schedule` so the accepted grammar and the
- executor's evaluation of it can never drift apart.
-
- Args:
- part: One whitespace-delimited cron field (already validated).
- low: Inclusive lower bound of the field.
- high: Inclusive upper bound of the field.
-
- Returns:
- The set of matching integer values, or ``None`` for the ``*`` wildcard.
- """
- if part == "*":
- return None
- if part.startswith("*/"):
- step = int(part[2:])
- return set(range(low, high + 1, step))
- values: Set[int] = set()
- for atom in part.split(","):
- start, _, end = atom.partition("-")
- if end:
- values.update(range(int(start), int(end) + 1))
- else:
- values.add(int(start))
- return values
-
-
-def is_interval_schedule(schedule: str) -> bool:
- """Return whether *schedule* is the interval-milliseconds form.
-
- The one place that answers "interval or cron?", so callers that treat the
- two forms differently — the executor's advancement path, the create route's
- timezone handling — cannot disagree about which is which.
-
- Args:
- schedule: A schedule string in either accepted form.
-
- Returns:
- ``True`` for a bare positive-integer interval, ``False`` otherwise
- (including malformed input, which the validators reject separately).
- """
- return bool(_INTERVAL_MS_RE.fullmatch(str(schedule).strip()))
-
-
-def validate_schedule(schedule: str) -> None:
- """Raise ``ValueError`` when *schedule* is malformed.
-
- Args:
- schedule: Either a positive integer string (interval-ms) or a
- simplified 5-field cron expression.
-
- Raises:
- ValueError: When the schedule does not match either accepted form.
- """
- if not schedule or not isinstance(schedule, str):
- raise ValueError("schedule must be a non-empty string")
-
- if _INTERVAL_MS_RE.fullmatch(schedule.strip()):
- # 15 digits ≈ 31,000 years in milliseconds — anything longer is not a
- # usable interval and would only feed int() conversion of huge strings.
- if len(schedule.strip()) > 15:
- raise ValueError("interval is too large; expected at most 15 digits of milliseconds")
- return # valid interval
-
- parts = schedule.strip().split()
- if len(parts) != _CRON_PARTS:
- raise ValueError(f"schedule must be a positive integer (ms) or a 5-field cron string; got: {schedule!r}")
- for part, (low, high) in zip(parts, CRON_BOUNDS):
- _validate_cron_field(part, low, high)
-
-
-def validate_timezone_shape(tz: Optional[str]) -> None:
- """Raise ``ValueError`` when *tz* is not ``None`` or a non-empty string.
-
- This is the persistence-level check: it deliberately does NOT resolve the
- key, because resolvability depends on the host's timezone database. A
- store written where a key resolved must keep loading and persisting on a
- host where it does not; the executor surfaces the unresolvable key as a
- per-job schedule failure instead.
- """
- if tz is None:
- return
- if not isinstance(tz, str) or not tz.strip():
- raise ValueError("timezone must be a non-empty IANA timezone key or null")
-
-
-def validate_timezone(tz: Optional[str]) -> None:
- """Raise ``ValueError`` when *tz* is not a resolvable IANA timezone key.
-
- ``None`` is always valid and means legacy UTC semantics. Resolution goes
- through :class:`zoneinfo.ZoneInfo`, so whatever validates here is exactly
- what the executor can evaluate later.
-
- Args:
- tz: An IANA timezone key such as ``"Pacific/Auckland"``, or ``None``.
-
- Raises:
- ValueError: When *tz* is not ``None`` and cannot be resolved.
- """
- validate_timezone_shape(tz)
- if tz is None:
- return
- try:
- ZoneInfo(tz)
- except Exception as exc:
- raise ValueError(f"timezone {tz!r} is not a recognized IANA timezone key") from exc
+# --- Schedule grammar, moved to src.scheduling.triggers (scheduler unification) ---
+# Re-exported here so existing ``from src.scheduled_research.models import ...``
+# keeps working (same convention as src/agent/loop.py's llm_usage re-export).
+from src.scheduling.triggers import (
+ CRON_BOUNDS as CRON_BOUNDS,
+ is_interval_schedule as is_interval_schedule,
+ parse_cron_field as parse_cron_field,
+ validate_schedule as validate_schedule,
+ validate_timezone as validate_timezone,
+ validate_timezone_shape as validate_timezone_shape,
+)
+logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Status enum
diff --git a/agent/src/scheduling/__init__.py b/agent/src/scheduling/__init__.py
new file mode 100644
index 000000000..0f68bcd1b
--- /dev/null
+++ b/agent/src/scheduling/__init__.py
@@ -0,0 +1,50 @@
+"""Shared scheduling kernel (scheduler unification).
+
+This package is the single home of the trigger vocabulary 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).
+
+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.
+"""
+
+from src.scheduling.triggers import (
+ CRON_BOUNDS,
+ CRON_SEARCH_LIMIT_DAYS,
+ DEFAULT_TRIGGER_INTERVAL_MS,
+ ONCE_SPEC,
+ day_matches,
+ is_interval_schedule,
+ local_wall_time_to_epoch_ms,
+ next_cron_due,
+ next_due,
+ next_once_due,
+ parse_cron_field,
+ trigger_interval_ms,
+ validate_schedule,
+ validate_timezone,
+ validate_timezone_shape,
+)
+
+__all__ = [
+ "CRON_BOUNDS",
+ "CRON_SEARCH_LIMIT_DAYS",
+ "DEFAULT_TRIGGER_INTERVAL_MS",
+ "ONCE_SPEC",
+ "day_matches",
+ "is_interval_schedule",
+ "local_wall_time_to_epoch_ms",
+ "next_cron_due",
+ "next_due",
+ "next_once_due",
+ "parse_cron_field",
+ "trigger_interval_ms",
+ "validate_schedule",
+ "validate_timezone",
+ "validate_timezone_shape",
+]
diff --git a/agent/src/scheduling/triggers.py b/agent/src/scheduling/triggers.py
new file mode 100644
index 000000000..5ec3ab3ea
--- /dev/null
+++ b/agent/src/scheduling/triggers.py
@@ -0,0 +1,379 @@
+"""Trigger grammar and next-run math for the shared scheduling kernel.
+
+Extracted verbatim (scheduler-unification T1) from two prior owners so every
+scheduler in the repo can share one trigger vocabulary:
+
+* the schedule grammar — interval-ms strings and simplified 5-field cron with
+ ``CRON_BOUNDS`` validation — moved from ``src/scheduled_research/models.py``;
+* the next-run math — :func:`next_due`, :func:`next_cron_due`,
+ :func:`local_wall_time_to_epoch_ms`, :func:`day_matches` — moved from
+ ``src/scheduled_research/executor.py``.
+
+Algorithms are line-for-line equivalent to the pre-move implementation; the
+golden vectors in ``agent/tests/scheduling/golden_next_due.json`` (captured
+mechanically from the old code *before* the move) pin that equivalence. Only
+the spelling of the moved private names changed: the public names drop the
+leading underscore (``next_cron_due`` / ``local_wall_time_to_epoch_ms`` /
+``day_matches``) and underscore aliases are kept so every existing import
+path keeps working.
+
+This module also introduces the ``once`` trigger kind — a pure next-run
+function absorbing the ``"once"`` / ``"interval:<ms>"`` semantics of the live
+runtime scheduler (``agent/src/live/runtime/scheduler.py``, read-only
+reference; nothing is imported from ``src.live`` and no live behavior is
+changed). It is provided for future adoption only and is NOT wired anywhere
+in this batch.
+
+Everything here is pure and clock-injected: callers pass explicit epoch-ms
+references (``after_ms``), so no function reads the wall clock.
+"""
+
+from __future__ import annotations
+
+import re
+from datetime import date, datetime, timedelta, timezone, tzinfo
+from typing import Optional, Set
+from zoneinfo import ZoneInfo
+
+# ---------------------------------------------------------------------------
+# Schedule validation (moved from src/scheduled_research/models.py)
+# ---------------------------------------------------------------------------
+
+# Accept either:
+# * a bare positive integer (interval in milliseconds), e.g. "60000"
+# * a simplified cron expression with 5 fields, e.g. "0 */6 * * *"
+# Fields: minute hour day-of-month month day-of-week
+# Each field may be: *, */n, or a comma-separated list of numbers and
+# low-high ranges (e.g. "1-5", "1,3,5", "1,3-5")
+_INTERVAL_MS_RE = re.compile(r"^[1-9][0-9]*$")
+_CRON_STEP_RE = re.compile(r"^\*/[1-9][0-9]*$")
+_CRON_ATOM_RE = re.compile(r"^([0-9]+)(?:-([0-9]+))?$")
+_CRON_PARTS = 5
+# Inclusive (low, high) bounds per cron field: minute hour day-of-month month
+# day-of-week. Every number in a field — a bare value, a ``*/n`` step, or
+# either end of a range — is validated against these bounds so out-of-range
+# values (e.g. minute ``99``) are rejected. Day-of-week uses the cron
+# convention Sunday == 0; ``7`` is not accepted as a Sunday alias.
+CRON_BOUNDS = ((0, 59), (0, 23), (1, 31), (1, 12), (0, 6))
+
+
+def _validate_cron_field(part: str, low: int, high: int) -> None:
+ """Raise ``ValueError`` when one cron field is malformed or out of range."""
+ if part == "*":
+ return
+ if _CRON_STEP_RE.fullmatch(part):
+ value = int(part[2:])
+ if not low <= value <= high:
+ raise ValueError(f"cron field {part!r} is out of range; expected {low}-{high}")
+ return
+ for atom in part.split(","):
+ match = _CRON_ATOM_RE.fullmatch(atom)
+ if match is None:
+ raise ValueError(
+ f"cron field {part!r} is not valid; each field must be *, */n, "
+ f"or a comma-separated list of numbers and low-high ranges"
+ )
+ start = int(match.group(1))
+ end = int(match.group(2)) if match.group(2) is not None else start
+ if start > end:
+ raise ValueError(f"cron range {atom!r} is reversed; expected low-high")
+ if start < low or end > high:
+ raise ValueError(f"cron field {atom!r} is out of range; expected {low}-{high}")
+
+
+def parse_cron_field(part: str, low: int, high: int) -> Optional[Set[int]]:
+ """Expand one validated cron field into its matching values.
+
+ Kept beside :func:`validate_schedule` so the accepted grammar and the
+ executor's evaluation of it can never drift apart.
+
+ Args:
+ part: One whitespace-delimited cron field (already validated).
+ low: Inclusive lower bound of the field.
+ high: Inclusive upper bound of the field.
+
+ Returns:
+ The set of matching integer values, or ``None`` for the ``*`` wildcard.
+ """
+ if part == "*":
+ return None
+ if part.startswith("*/"):
+ step = int(part[2:])
+ return set(range(low, high + 1, step))
+ values: Set[int] = set()
+ for atom in part.split(","):
+ start, _, end = atom.partition("-")
+ if end:
+ values.update(range(int(start), int(end) + 1))
+ else:
+ values.add(int(start))
+ return values
+
+
+def is_interval_schedule(schedule: str) -> bool:
+ """Return whether *schedule* is the interval-milliseconds form.
+
+ The one place that answers "interval or cron?", so callers that treat the
+ two forms differently — the executor's advancement path, the create route's
+ timezone handling — cannot disagree about which is which.
+
+ Args:
+ schedule: A schedule string in either accepted form.
+
+ Returns:
+ ``True`` for a bare positive-integer interval, ``False`` otherwise
+ (including malformed input, which the validators reject separately).
+ """
+ return bool(_INTERVAL_MS_RE.fullmatch(str(schedule).strip()))
+
+
+def validate_schedule(schedule: str) -> None:
+ """Raise ``ValueError`` when *schedule* is malformed.
+
+ Args:
+ schedule: Either a positive integer string (interval-ms) or a
+ simplified 5-field cron expression.
+
+ Raises:
+ ValueError: When the schedule does not match either accepted form.
+ """
+ if not schedule or not isinstance(schedule, str):
+ raise ValueError("schedule must be a non-empty string")
+
+ if _INTERVAL_MS_RE.fullmatch(schedule.strip()):
+ # 15 digits ≈ 31,000 years in milliseconds — anything longer is not a
+ # usable interval and would only feed int() conversion of huge strings.
+ if len(schedule.strip()) > 15:
+ raise ValueError("interval is too large; expected at most 15 digits of milliseconds")
+ return # valid interval
+
+ parts = schedule.strip().split()
+ if len(parts) != _CRON_PARTS:
+ raise ValueError(f"schedule must be a positive integer (ms) or a 5-field cron string; got: {schedule!r}")
+ for part, (low, high) in zip(parts, CRON_BOUNDS):
+ _validate_cron_field(part, low, high)
+
+
+def validate_timezone_shape(tz: Optional[str]) -> None:
+ """Raise ``ValueError`` when *tz* is not ``None`` or a non-empty string.
+
+ This is the persistence-level check: it deliberately does NOT resolve the
+ key, because resolvability depends on the host's timezone database. A
+ store written where a key resolved must keep loading and persisting on a
+ host where it does not; the executor surfaces the unresolvable key as a
+ per-job schedule failure instead.
+ """
+ if tz is None:
+ return
+ if not isinstance(tz, str) or not tz.strip():
+ raise ValueError("timezone must be a non-empty IANA timezone key or null")
+
+
+def validate_timezone(tz: Optional[str]) -> None:
+ """Raise ``ValueError`` when *tz* is not a resolvable IANA timezone key.
+
+ ``None`` is always valid and means legacy UTC semantics. Resolution goes
+ through :class:`zoneinfo.ZoneInfo`, so whatever validates here is exactly
+ what the executor can evaluate later.
+
+ Args:
+ tz: An IANA timezone key such as ``"Pacific/Auckland"``, or ``None``.
+
+ Raises:
+ ValueError: When *tz* is not ``None`` and cannot be resolved.
+ """
+ validate_timezone_shape(tz)
+ if tz is None:
+ return
+ try:
+ ZoneInfo(tz)
+ except Exception as exc:
+ raise ValueError(f"timezone {tz!r} is not a recognized IANA timezone key") from exc
+
+
+# ---------------------------------------------------------------------------
+# Next-run math (moved from src/scheduled_research/executor.py)
+# ---------------------------------------------------------------------------
+
+# 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; the extra headroom absorbs a
+# yearly occurrence landing in a DST spring-forward gap (skipped by policy)
+# several years in a row before a real instant exists again.
+CRON_SEARCH_LIMIT_DAYS = 6 * 366 + 1
+
+
+def next_due(schedule: str, after_ms: int, tz: str | None = None) -> 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.
+ Cron is evaluated on the wall clock of *tz* (an IANA timezone key) when
+ one is given, in UTC otherwise — the semantics every job had before the
+ field existed. Interval schedules ignore *tz* entirely.
+ """
+ validate_schedule(schedule)
+ spec = schedule.strip()
+ if spec.isdigit():
+ # Before the timezone check: interval schedules must keep advancing
+ # even when the stored key cannot resolve on this host.
+ return after_ms + int(spec)
+ validate_timezone(tz)
+ return next_cron_due(spec, after_ms, tz)
+
+
+def next_cron_due(schedule: str, after_ms: int, tz: str | None = None) -> int:
+ minutes, hours, doms, months, dows = (
+ parse_cron_field(part, low, high) for part, (low, high) in zip(schedule.split(), CRON_BOUNDS)
+ )
+ zone = timezone.utc if tz is None else ZoneInfo(tz)
+ # Walk candidates on the *local* calendar of ``zone`` so field matching —
+ # the weekday in particular — follows the authoring wall clock. Ascending
+ # wall order maps to ascending UTC order under a fixed fold policy, so
+ # "strictly after" stays a plain epoch comparison.
+ day = datetime.fromtimestamp(after_ms / 1000.0, zone).date()
+ 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_ms = local_wall_time_to_epoch_ms(candidate_day, hour, minute, zone)
+ if fire_ms is not None and fire_ms > after_ms:
+ return fire_ms
+ raise ValueError(f"cron schedule has no matching time within search window: {schedule!r}")
+
+
+def local_wall_time_to_epoch_ms(day: date, hour: int, minute: int, zone: tzinfo) -> int | None:
+ """Resolve one local wall time to a UTC epoch-ms instant.
+
+ DST policy (#953): a nonexistent wall time — the spring-forward gap —
+ returns ``None`` so the occurrence is skipped; ``ZoneInfo`` would
+ otherwise silently map it past the transition (PEP 495) and run it. An
+ ambiguous wall time — the fall-back fold — resolves with ``fold=0``, the
+ first occurrence, so it runs exactly once.
+ """
+ local = datetime(day.year, day.month, day.day, hour, minute, tzinfo=zone)
+ as_utc = local.astimezone(timezone.utc)
+ if as_utc.astimezone(zone).replace(tzinfo=None) != local.replace(tzinfo=None):
+ return None # wall time does not exist in this zone (DST gap)
+ return int(as_utc.timestamp() * 1000)
+
+
+def day_matches(dt: date, doms: set[int] | None, months: set[int] | None, dows: set[int] | None) -> bool:
+ if months is not None and dt.month not in months:
+ return False
+
+ cron_day_of_week = (dt.weekday() + 1) % 7 # cron convention: Sunday == 0
+ day_of_month_matches = doms is None or dt.day in doms
+ day_of_week_matches = dows is None or cron_day_of_week in dows
+
+ # Standard five-field cron treats day-of-month and day-of-week as an OR
+ # when both fields are restricted. A wildcard in either field keeps the
+ # other field authoritative.
+ if doms is not None and dows is not None:
+ return day_of_month_matches or day_of_week_matches
+ return day_of_month_matches and day_of_week_matches
+
+
+# Legacy private spellings from ``src/scheduled_research/executor.py``, kept as
+# aliases so every existing import path (and every monkeypatch-free test that
+# references them) keeps working unchanged.
+_CRON_SEARCH_LIMIT_DAYS = CRON_SEARCH_LIMIT_DAYS
+_next_cron_due = next_cron_due
+_local_wall_time_to_epoch_ms = local_wall_time_to_epoch_ms
+_day_matches = day_matches
+
+
+# ---------------------------------------------------------------------------
+# once / interval:<ms> trigger kind (live-runtime dialect, NEW — not wired)
+# ---------------------------------------------------------------------------
+
+#: The one-shot trigger spec of the live runtime scheduler: fires exactly once
+#: and is then removed. Compared case-insensitively after stripping.
+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).
+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``:
+
+ * ``"once"`` → ``None``: a one-shot trigger with no recurrence;
+ * ``"interval:<ms>"`` → ``<ms>`` when it parses as a positive integer,
+ otherwise :data:`DEFAULT_TRIGGER_INTERVAL_MS`;
+ * any other bare/empty/unknown non-empty spec →
+ :data:`DEFAULT_TRIGGER_INTERVAL_MS`, so a misconfigured job still
+ watches on a sane cadence rather than silently never recurring.
+
+ Note this is the live-runtime spec dialect (``"interval:<ms>"`` /
+ ``"once"``), distinct from the scheduled-research grammar handled by
+ :func:`next_due` (a bare ``"<ms>"`` interval string or a 5-field cron).
+ """
+ spec = (schedule or "").strip().lower()
+ if spec == ONCE_SPEC:
+ return None
+ if spec.startswith("interval:"):
+ raw = spec.split(":", 1)[1].strip()
+ try:
+ ms = int(raw)
+ except ValueError:
+ return DEFAULT_TRIGGER_INTERVAL_MS
+ return ms if ms > 0 else DEFAULT_TRIGGER_INTERVAL_MS
+ return DEFAULT_TRIGGER_INTERVAL_MS
+
+
+def next_once_due(schedule: str | None, after_ms: int) -> int | None:
+ """Return the next run epoch-ms for a ``once``/``interval:<ms>`` trigger.
+
+ ``None`` means the trigger is one-shot (``"once"``): it fires exactly once
+ and has no next run — the live scheduler removes such a job after firing.
+ A recurring spec advances one interval past ``after_ms`` (not past a stale
+ ``next_run_at``), so a trigger that fired late — because the host was
+ suspended or the loop was busy — does not immediately re-fire a backlog of
+ missed slots.
+
+ Args:
+ schedule: A live-style trigger spec (see :func:`trigger_interval_ms`).
+ after_ms: Reference time in epoch ms — typically the fire time.
+
+ Returns:
+ The next run in epoch ms, or ``None`` for the one-shot kind.
+ """
+ interval = trigger_interval_ms(schedule)
+ if interval is None:
+ return None
+ return after_ms + interval
+
+
+__all__ = [
+ "CRON_BOUNDS",
+ "CRON_SEARCH_LIMIT_DAYS",
+ "DEFAULT_TRIGGER_INTERVAL_MS",
+ "ONCE_SPEC",
+ "day_matches",
+ "is_interval_schedule",
+ "local_wall_time_to_epoch_ms",
+ "next_cron_due",
+ "next_due",
+ "next_once_due",
+ "parse_cron_field",
+ "trigger_interval_ms",
+ "validate_schedule",
+ "validate_timezone",
+ "validate_timezone_shape",
+ # legacy private aliases
+ "_CRON_SEARCH_LIMIT_DAYS",
+ "_day_matches",
+ "_local_wall_time_to_epoch_ms",
+ "_next_cron_due",
+]
diff --git a/agent/tests/scheduling/__init__.py b/agent/tests/scheduling/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/agent/tests/scheduling/golden_next_due.json b/agent/tests/scheduling/golden_next_due.json
new file mode 100644
index 000000000..9fd1cfc9f
--- /dev/null
+++ b/agent/tests/scheduling/golden_next_due.json
@@ -0,0 +1,1812 @@
+{
+ "meta": {
+ "captured_from": [
+ "src.scheduled_research.executor (next_due, _next_cron_due, _local_wall_time_to_epoch_ms, _day_matches)",
+ "src.scheduled_research.models (CRON_BOUNDS, parse_cron_field, validate_schedule, validate_timezone, validate_timezone_shape, is_interval_schedule)"
+ ],
+ "source_commit": "fb29ed13c2d62391ea9dd8b87129cc2b08fe5813",
+ "base_commit_origin_main": "29aa084fb7866087c612ddd55ef5449824374e22",
+ "captured_files_identical_to_base": true,
+ "source_tree_clean_for_captured_files": true,
+ "python": "3.12.8",
+ "note": "Captured mechanically from the PRE-MOVE implementation before any code was moved to src/scheduling/triggers.py (scheduler-unification T1). Values are raw function outputs; 'error' entries record exception type + str(exc). tz='__DEFAULT__' means next_due was called without the tz argument."
+ },
+ "vectors": [
+ {
+ "id": "next_due/interval/basic-60000",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "60000",
+ "after_ms": 5000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 65000
+ }
+ },
+ {
+ "id": "next_due/interval/basic-21600000",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "21600000",
+ "after_ms": 1000000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 22600000
+ }
+ },
+ {
+ "id": "next_due/interval/ignores-valid-tz",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "60000",
+ "after_ms": 5000,
+ "tz": "Pacific/Auckland"
+ },
+ "expect": {
+ "ok": 65000
+ }
+ },
+ {
+ "id": "next_due/interval/advances-under-unresolvable-tz",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "60000",
+ "after_ms": 5000,
+ "tz": "Not/AZone"
+ },
+ "expect": {
+ "ok": 65000
+ }
+ },
+ {
+ "id": "next_due/interval/minimal-1ms",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "1",
+ "after_ms": 0,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1
+ }
+ },
+ {
+ "id": "next_due/interval/15-digit-upper-bound-ok",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "999999999999999",
+ "after_ms": 0,
+ "tz": null
+ },
+ "expect": {
+ "ok": 999999999999999
+ }
+ },
+ {
+ "id": "next_due/interval/16-digit-rejected",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "1000000000000000",
+ "after_ms": 0,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "interval is too large; expected at most 15 digits of milliseconds"
+ }
+ },
+ {
+ "id": "next_due/interval/zero-rejected",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0",
+ "after_ms": 0,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "schedule must be a positive integer (ms) or a 5-field cron string; got: '0'"
+ }
+ },
+ {
+ "id": "next_due/interval/surrounding-whitespace-stripped",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": " 60000 ",
+ "after_ms": 5000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 65000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/every-6h-before-due",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 */6 * * *",
+ "after_ms": 1781935140000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781935200000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/every-6h-strictly-after",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 */6 * * *",
+ "after_ms": 1781935200000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781956800000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/every-15m-on-boundary",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "*/15 * * * *",
+ "after_ms": 1773489600000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1773490500000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/every-15m-mid-window",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "*/15 * * * *",
+ "after_ms": 1773490440000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1773490500000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/every-15m-hour-rollover",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "*/15 * * * *",
+ "after_ms": 1773492300000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1773493200000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/weekday-2000-same-day",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 20 * * 1-5",
+ "after_ms": 1781121540000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781121600000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/weekday-2000-fri-to-mon",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 20 * * 1-5",
+ "after_ms": 1781294400000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781553600000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/weekday-0830-fri-to-mon",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "30 8 * * 1-5",
+ "after_ms": 1781253000000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781512200000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/playbook-cadence-from-jan1",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 9 15 2,5,8,11 *",
+ "after_ms": 1767225600000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1771146000000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/playbook-cadence-feb-to-may",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 9 15 2,5,8,11 *",
+ "after_ms": 1771146000000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1778835600000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/new-year-midnight",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 1 1 *",
+ "after_ms": 1780272000000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1798761600000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/sunday-is-zero",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 12 * * 0",
+ "after_ms": 1781049600000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781438400000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/saturday-is-six",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 12 * * 6",
+ "after_ms": 1781049600000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781352000000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/dow-7-rejected",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 12 * * 7",
+ "after_ms": 1781049600000,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron field '7' is out of range; expected 0-6"
+ }
+ },
+ {
+ "id": "next_due/cron-utc/comma-range-mix-at-0",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "1,3-5 * * * *",
+ "after_ms": 1781049600000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781049660000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/comma-range-mix-skips-2",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "1,3-5 * * * *",
+ "after_ms": 1781049720000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781049780000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/reversed-range-rejected",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "5-1 * * * *",
+ "after_ms": 0,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron range '5-1' is reversed; expected low-high"
+ }
+ },
+ {
+ "id": "next_due/cron-utc/feb-31-window-exhausted",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 31 2 *",
+ "after_ms": 1767225600000,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron schedule has no matching time within search window: '0 0 31 2 *'"
+ }
+ },
+ {
+ "id": "next_due/cron-utc/feb-30-window-exhausted",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 30 2 *",
+ "after_ms": 1767225600000,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron schedule has no matching time within search window: '0 0 30 2 *'"
+ }
+ },
+ {
+ "id": "next_due/cron-utc/apr-31-window-exhausted",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 31 4 *",
+ "after_ms": 1767225600000,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron schedule has no matching time within search window: '0 0 31 4 *'"
+ }
+ },
+ {
+ "id": "next_due/cron-utc/feb-29-leap-day-2028",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 29 2 *",
+ "after_ms": 1772323200000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1835395200000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/feb-29-leap-day-2032-deep-search",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 29 2 *",
+ "after_ms": 1835481600000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1961625600000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/dom-dow-or-dow-wins",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 13 * 5",
+ "after_ms": 1781136060000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781222400000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/dom-dow-or-dom-wins",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 13 * 5",
+ "after_ms": 1781222460000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781308800000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/dom-wildcard-dow",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 13 * *",
+ "after_ms": 1781136060000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781308800000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/dow-wildcard-dom",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 * * 5",
+ "after_ms": 1781136060000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781222400000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/weekday-1130-fri-to-mon",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "30 11 * * 1-5",
+ "after_ms": 1785497400000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1785756600000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/sunday-noon-strictly-after",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 * * 0",
+ "after_ms": 1781438400000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1782000000000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/unresolvable-tz-rejected",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 12 * * *",
+ "after_ms": 0,
+ "tz": "Not/AZone"
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "timezone 'Not/AZone' is not a recognized IANA timezone key"
+ }
+ },
+ {
+ "id": "next_due/cron-utc/empty-schedule-rejected",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "",
+ "after_ms": 0,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "schedule must be a non-empty string"
+ }
+ },
+ {
+ "id": "next_due/cron-utc/four-fields-rejected",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 12 * *",
+ "after_ms": 0,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "schedule must be a positive integer (ms) or a 5-field cron string; got: '0 12 * *'"
+ }
+ },
+ {
+ "id": "next_due/cron-utc/minute-99-rejected",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "99 * * * *",
+ "after_ms": 0,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron field '99' is out of range; expected 0-59"
+ }
+ },
+ {
+ "id": "next_due/cron-utc/step-60-rejected",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "*/60 * * * *",
+ "after_ms": 0,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron field '*/60' is out of range; expected 0-59"
+ }
+ },
+ {
+ "id": "next_due/cron-utc/dow-range-6-7-rejected",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 * * 6-7",
+ "after_ms": 0,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron field '6-7' is out of range; expected 0-6"
+ }
+ },
+ {
+ "id": "next_due/cron-utc/surrounding-whitespace",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": " 0 12 * * * ",
+ "after_ms": 1781049600000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781092800000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/legacy-signature-parity-6h",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 */6 * * *",
+ "after_ms": 1781136060000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781157600000
+ }
+ },
+ {
+ "id": "next_due/cron-utc/legacy-signature-parity-interval",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "60000",
+ "after_ms": 1781136060000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781136120000
+ }
+ },
+ {
+ "id": "next_due/dst-ny/spring-gap-skipped",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "30 2 * * *",
+ "after_ms": 1772868600000,
+ "tz": "America/New_York"
+ },
+ "expect": {
+ "ok": 1773037800000
+ }
+ },
+ {
+ "id": "next_due/dst-ny/fall-fold-first-occurrence",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "30 1 * * *",
+ "after_ms": 1793424600000,
+ "tz": "America/New_York"
+ },
+ "expect": {
+ "ok": 1793511000000
+ }
+ },
+ {
+ "id": "next_due/dst-ny/fall-fold-fires-once",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "30 1 * * *",
+ "after_ms": 1793511000000,
+ "tz": "America/New_York"
+ },
+ "expect": {
+ "ok": 1793601000000
+ }
+ },
+ {
+ "id": "next_due/dst-akl/weekday-2330-across-spring",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "30 23 * * 1-5",
+ "after_ms": 1790335800000,
+ "tz": "Pacific/Auckland"
+ },
+ "expect": {
+ "ok": 1790591400000
+ }
+ },
+ {
+ "id": "next_due/dst-akl/weekday-2330-across-fall",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "30 23 * * 1-5",
+ "after_ms": 1775212200000,
+ "tz": "Pacific/Auckland"
+ },
+ "expect": {
+ "ok": 1775475000000
+ }
+ },
+ {
+ "id": "next_due/dst-akl/spring-gap-skipped",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "30 2 * * *",
+ "after_ms": 1790346600000,
+ "tz": "Pacific/Auckland"
+ },
+ "expect": {
+ "ok": 1790515800000
+ }
+ },
+ {
+ "id": "next_due/dst-akl/fall-fold-first-occurrence",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "30 2 * * *",
+ "after_ms": 1775223000000,
+ "tz": "Pacific/Auckland"
+ },
+ "expect": {
+ "ok": 1775309400000
+ }
+ },
+ {
+ "id": "next_due/dst-akl/monday-0030-is-sunday-in-utc",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "30 0 * * 1",
+ "after_ms": 1781395200000,
+ "tz": "Pacific/Auckland"
+ },
+ "expect": {
+ "ok": 1781440200000
+ }
+ },
+ {
+ "id": "next_due/dst-akl/strictly-after-in-local-zone",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 12 * * *",
+ "after_ms": 1781481600000,
+ "tz": "Pacific/Auckland"
+ },
+ "expect": {
+ "ok": 1781568000000
+ }
+ },
+ {
+ "id": "next_due/tz-adl/half-hour-offset-daily",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 9 * * *",
+ "after_ms": 1781047800000,
+ "tz": "Australia/Adelaide"
+ },
+ "expect": {
+ "ok": 1781134200000
+ }
+ },
+ {
+ "id": "next_due/tz-adl/across-spring-forward",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 9 * * *",
+ "after_ms": 1790983800000,
+ "tz": "Australia/Adelaide"
+ },
+ "expect": {
+ "ok": 1791066600000
+ }
+ },
+ {
+ "id": "next_due/tz-sha/noon-local-from-utc-ref",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 12 * * *",
+ "after_ms": 1781063940000,
+ "tz": "Asia/Shanghai"
+ },
+ "expect": {
+ "ok": 1781064000000
+ }
+ },
+ {
+ "id": "next_due/tz-sha/new-year-local",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 0 1 1 *",
+ "after_ms": 1767225600000,
+ "tz": "Asia/Shanghai"
+ },
+ "expect": {
+ "ok": 1798732800000
+ }
+ },
+ {
+ "id": "next_due/tz-sha/no-fold-no-dst",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "30 1 * * *",
+ "after_ms": 1793467800000,
+ "tz": "Asia/Shanghai"
+ },
+ "expect": {
+ "ok": 1793554200000
+ }
+ },
+ {
+ "id": "next_due/default-tz-parity/cron",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "0 */6 * * *",
+ "after_ms": 1781136060000,
+ "tz": "__DEFAULT__"
+ },
+ "expect": {
+ "ok": 1781157600000
+ }
+ },
+ {
+ "id": "next_due/default-tz-parity/interval",
+ "kind": "next_due",
+ "inputs": {
+ "schedule": "60000",
+ "after_ms": 1781136060000,
+ "tz": "__DEFAULT__"
+ },
+ "expect": {
+ "ok": 1781136120000
+ }
+ },
+ {
+ "id": "next_cron_due/direct/utc-noon",
+ "kind": "next_cron_due",
+ "inputs": {
+ "schedule": "0 12 * * *",
+ "after_ms": 1781049600000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781092800000
+ }
+ },
+ {
+ "id": "next_cron_due/direct/ny-spring-gap",
+ "kind": "next_cron_due",
+ "inputs": {
+ "schedule": "30 2 * * *",
+ "after_ms": 1772868600000,
+ "tz": "America/New_York"
+ },
+ "expect": {
+ "ok": 1773037800000
+ }
+ },
+ {
+ "id": "next_cron_due/direct/feb-31-window-exhausted",
+ "kind": "next_cron_due",
+ "inputs": {
+ "schedule": "0 0 31 2 *",
+ "after_ms": 1767225600000,
+ "tz": null
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron schedule has no matching time within search window: '0 0 31 2 *'"
+ }
+ },
+ {
+ "id": "next_cron_due/direct/dom-dow-or",
+ "kind": "next_cron_due",
+ "inputs": {
+ "schedule": "0 0 13 * 5",
+ "after_ms": 1781136060000,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781222400000
+ }
+ },
+ {
+ "id": "next_cron_due/direct/unresolvable-tz-raw-zoneinfo-error",
+ "kind": "next_cron_due",
+ "inputs": {
+ "schedule": "0 12 * * *",
+ "after_ms": 0,
+ "tz": "Not/AZone"
+ },
+ "expect": {
+ "error": "ZoneInfoNotFoundError",
+ "message": "'No time zone found with key Not/AZone'"
+ }
+ },
+ {
+ "id": "local_wall/utc/plain",
+ "kind": "local_wall",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 10
+ ],
+ "hour": 12,
+ "minute": 0,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1781092800000
+ }
+ },
+ {
+ "id": "local_wall/shanghai/plain",
+ "kind": "local_wall",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 10
+ ],
+ "hour": 12,
+ "minute": 0,
+ "tz": "Asia/Shanghai"
+ },
+ "expect": {
+ "ok": 1781064000000
+ }
+ },
+ {
+ "id": "local_wall/ny/spring-gap-none",
+ "kind": "local_wall",
+ "inputs": {
+ "day": [
+ 2026,
+ 3,
+ 8
+ ],
+ "hour": 2,
+ "minute": 30,
+ "tz": "America/New_York"
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "local_wall/ny/fall-fold-first",
+ "kind": "local_wall",
+ "inputs": {
+ "day": [
+ 2026,
+ 11,
+ 1
+ ],
+ "hour": 1,
+ "minute": 30,
+ "tz": "America/New_York"
+ },
+ "expect": {
+ "ok": 1793511000000
+ }
+ },
+ {
+ "id": "local_wall/akl/spring-gap-none",
+ "kind": "local_wall",
+ "inputs": {
+ "day": [
+ 2026,
+ 9,
+ 27
+ ],
+ "hour": 2,
+ "minute": 30,
+ "tz": "Pacific/Auckland"
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "local_wall/akl/fall-fold-first",
+ "kind": "local_wall",
+ "inputs": {
+ "day": [
+ 2026,
+ 4,
+ 5
+ ],
+ "hour": 2,
+ "minute": 30,
+ "tz": "Pacific/Auckland"
+ },
+ "expect": {
+ "ok": 1775309400000
+ }
+ },
+ {
+ "id": "local_wall/adl/spring-gap-none",
+ "kind": "local_wall",
+ "inputs": {
+ "day": [
+ 2026,
+ 10,
+ 4
+ ],
+ "hour": 2,
+ "minute": 30,
+ "tz": "Australia/Adelaide"
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "local_wall/shanghai/no-dst-fold-date",
+ "kind": "local_wall",
+ "inputs": {
+ "day": [
+ 2026,
+ 11,
+ 1
+ ],
+ "hour": 1,
+ "minute": 30,
+ "tz": "Asia/Shanghai"
+ },
+ "expect": {
+ "ok": 1793467800000
+ }
+ },
+ {
+ "id": "local_wall/utc/leap-day",
+ "kind": "local_wall",
+ "inputs": {
+ "day": [
+ 2028,
+ 2,
+ 29
+ ],
+ "hour": 0,
+ "minute": 0,
+ "tz": null
+ },
+ "expect": {
+ "ok": 1835395200000
+ }
+ },
+ {
+ "id": "day_matches/sunday-dow-zero",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 14
+ ],
+ "doms": null,
+ "months": null,
+ "dows": [
+ 0
+ ]
+ },
+ "expect": {
+ "ok": true
+ }
+ },
+ {
+ "id": "day_matches/sunday-not-saturday",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 14
+ ],
+ "doms": null,
+ "months": null,
+ "dows": [
+ 6
+ ]
+ },
+ "expect": {
+ "ok": false
+ }
+ },
+ {
+ "id": "day_matches/friday-dow-five",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 12
+ ],
+ "doms": null,
+ "months": null,
+ "dows": [
+ 5
+ ]
+ },
+ "expect": {
+ "ok": true
+ }
+ },
+ {
+ "id": "day_matches/or-dow-wins",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 12
+ ],
+ "doms": [
+ 13
+ ],
+ "months": null,
+ "dows": [
+ 5
+ ]
+ },
+ "expect": {
+ "ok": true
+ }
+ },
+ {
+ "id": "day_matches/or-dom-wins",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 13
+ ],
+ "doms": [
+ 13
+ ],
+ "months": null,
+ "dows": [
+ 5
+ ]
+ },
+ "expect": {
+ "ok": true
+ }
+ },
+ {
+ "id": "day_matches/or-neither-matches",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 11
+ ],
+ "doms": [
+ 13
+ ],
+ "months": null,
+ "dows": [
+ 5
+ ]
+ },
+ "expect": {
+ "ok": false
+ }
+ },
+ {
+ "id": "day_matches/month-set-feb",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 2,
+ 15
+ ],
+ "doms": null,
+ "months": [
+ 2,
+ 5,
+ 8,
+ 11
+ ],
+ "dows": null
+ },
+ "expect": {
+ "ok": true
+ }
+ },
+ {
+ "id": "day_matches/month-set-mar",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 3,
+ 15
+ ],
+ "doms": null,
+ "months": [
+ 2,
+ 5,
+ 8,
+ 11
+ ],
+ "dows": null
+ },
+ "expect": {
+ "ok": false
+ }
+ },
+ {
+ "id": "day_matches/month-gate-beats-or",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 3,
+ 13
+ ],
+ "doms": [
+ 13
+ ],
+ "months": [
+ 2
+ ],
+ "dows": [
+ 5
+ ]
+ },
+ "expect": {
+ "ok": false
+ }
+ },
+ {
+ "id": "day_matches/dom-only-match",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 13
+ ],
+ "doms": [
+ 13
+ ],
+ "months": null,
+ "dows": null
+ },
+ "expect": {
+ "ok": true
+ }
+ },
+ {
+ "id": "day_matches/dow-only-match",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 12
+ ],
+ "doms": null,
+ "months": null,
+ "dows": [
+ 5
+ ]
+ },
+ "expect": {
+ "ok": true
+ }
+ },
+ {
+ "id": "day_matches/all-wildcards",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 11
+ ],
+ "doms": null,
+ "months": null,
+ "dows": null
+ },
+ "expect": {
+ "ok": true
+ }
+ },
+ {
+ "id": "day_matches/weekday-set-sunday-out",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 14
+ ],
+ "doms": null,
+ "months": null,
+ "dows": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5
+ ]
+ },
+ "expect": {
+ "ok": false
+ }
+ },
+ {
+ "id": "day_matches/weekday-set-monday-in",
+ "kind": "day_matches",
+ "inputs": {
+ "day": [
+ 2026,
+ 6,
+ 15
+ ],
+ "doms": null,
+ "months": null,
+ "dows": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5
+ ]
+ },
+ "expect": {
+ "ok": true
+ }
+ },
+ {
+ "id": "parse_cron_field/wildcard-minute",
+ "kind": "parse_cron_field",
+ "inputs": {
+ "part": "*",
+ "low": 0,
+ "high": 59
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "parse_cron_field/step-15-minute",
+ "kind": "parse_cron_field",
+ "inputs": {
+ "part": "*/15",
+ "low": 0,
+ "high": 59
+ },
+ "expect": {
+ "ok": [
+ 0,
+ 15,
+ 30,
+ 45
+ ]
+ }
+ },
+ {
+ "id": "parse_cron_field/comma-range-mix",
+ "kind": "parse_cron_field",
+ "inputs": {
+ "part": "1,3-5",
+ "low": 0,
+ "high": 59
+ },
+ "expect": {
+ "ok": [
+ 1,
+ 3,
+ 4,
+ 5
+ ]
+ }
+ },
+ {
+ "id": "parse_cron_field/range-dow",
+ "kind": "parse_cron_field",
+ "inputs": {
+ "part": "1-5",
+ "low": 0,
+ "high": 6
+ },
+ "expect": {
+ "ok": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5
+ ]
+ }
+ },
+ {
+ "id": "parse_cron_field/comma-list-months",
+ "kind": "parse_cron_field",
+ "inputs": {
+ "part": "2,5,8,11",
+ "low": 1,
+ "high": 12
+ },
+ "expect": {
+ "ok": [
+ 2,
+ 5,
+ 8,
+ 11
+ ]
+ }
+ },
+ {
+ "id": "parse_cron_field/bare-zero-dow",
+ "kind": "parse_cron_field",
+ "inputs": {
+ "part": "0",
+ "low": 0,
+ "high": 6
+ },
+ "expect": {
+ "ok": [
+ 0
+ ]
+ }
+ },
+ {
+ "id": "parse_cron_field/step-2-dom",
+ "kind": "parse_cron_field",
+ "inputs": {
+ "part": "*/2",
+ "low": 1,
+ "high": 31
+ },
+ "expect": {
+ "ok": [
+ 1,
+ 3,
+ 5,
+ 7,
+ 9,
+ 11,
+ 13,
+ 15,
+ 17,
+ 19,
+ 21,
+ 23,
+ 25,
+ 27,
+ 29,
+ 31
+ ]
+ }
+ },
+ {
+ "id": "parse_cron_field/full-range-dow",
+ "kind": "parse_cron_field",
+ "inputs": {
+ "part": "0-6",
+ "low": 0,
+ "high": 6
+ },
+ "expect": {
+ "ok": [
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6
+ ]
+ }
+ },
+ {
+ "id": "parse_cron_field/step-6-hour",
+ "kind": "parse_cron_field",
+ "inputs": {
+ "part": "*/6",
+ "low": 0,
+ "high": 23
+ },
+ "expect": {
+ "ok": [
+ 0,
+ 6,
+ 12,
+ 18
+ ]
+ }
+ },
+ {
+ "id": "validate_schedule/interval-ok",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "60000"
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "validate_schedule/cron-ok",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "0 */6 * * *"
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "validate_schedule/dow-7-rejected",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "0 12 * * 7"
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron field '7' is out of range; expected 0-6"
+ }
+ },
+ {
+ "id": "validate_schedule/reversed-range-rejected",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "5-1 * * * *"
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron range '5-1' is reversed; expected low-high"
+ }
+ },
+ {
+ "id": "validate_schedule/empty-rejected",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": ""
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "schedule must be a non-empty string"
+ }
+ },
+ {
+ "id": "validate_schedule/interval-16-digits-rejected",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "1000000000000000"
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "interval is too large; expected at most 15 digits of milliseconds"
+ }
+ },
+ {
+ "id": "validate_schedule/interval-15-digits-ok",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "999999999999999"
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "validate_schedule/garbage-rejected",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "abc"
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "schedule must be a positive integer (ms) or a 5-field cron string; got: 'abc'"
+ }
+ },
+ {
+ "id": "validate_schedule/feb-29-grammar-ok",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "0 0 29 2 *"
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "validate_schedule/dow-full-range-ok",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "0 12 * * 0-6"
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "validate_schedule/step-zero-rejected",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "*/0 * * * *"
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron field '*/0' is not valid; each field must be *, */n, or a comma-separated list of numbers and low-high ranges"
+ }
+ },
+ {
+ "id": "validate_schedule/dow-name-rejected",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "0 12 * * MON"
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "cron field 'MON' is not valid; each field must be *, */n, or a comma-separated list of numbers and low-high ranges"
+ }
+ },
+ {
+ "id": "validate_schedule/non-string-rejected",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": 12345
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "schedule must be a non-empty string"
+ }
+ },
+ {
+ "id": "validate_schedule/six-fields-rejected",
+ "kind": "validate_schedule",
+ "inputs": {
+ "schedule": "0 12 * * 0 2026"
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "schedule must be a positive integer (ms) or a 5-field cron string; got: '0 12 * * 0 2026'"
+ }
+ },
+ {
+ "id": "validate_timezone/none-ok",
+ "kind": "validate_timezone",
+ "inputs": {
+ "tz": null
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "validate_timezone/shanghai-ok",
+ "kind": "validate_timezone",
+ "inputs": {
+ "tz": "Asia/Shanghai"
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "validate_timezone/new-york-ok",
+ "kind": "validate_timezone",
+ "inputs": {
+ "tz": "America/New_York"
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "validate_timezone/unknown-key-rejected",
+ "kind": "validate_timezone",
+ "inputs": {
+ "tz": "Not/AZone"
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "timezone 'Not/AZone' is not a recognized IANA timezone key"
+ }
+ },
+ {
+ "id": "validate_timezone/empty-rejected",
+ "kind": "validate_timezone",
+ "inputs": {
+ "tz": ""
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "timezone must be a non-empty IANA timezone key or null"
+ }
+ },
+ {
+ "id": "validate_timezone_shape/none-ok",
+ "kind": "validate_timezone_shape",
+ "inputs": {
+ "tz": null
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "validate_timezone_shape/unresolvable-key-shape-ok",
+ "kind": "validate_timezone_shape",
+ "inputs": {
+ "tz": "Not/AZone"
+ },
+ "expect": {
+ "ok": null
+ }
+ },
+ {
+ "id": "validate_timezone_shape/empty-rejected",
+ "kind": "validate_timezone_shape",
+ "inputs": {
+ "tz": ""
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "timezone must be a non-empty IANA timezone key or null"
+ }
+ },
+ {
+ "id": "validate_timezone_shape/whitespace-rejected",
+ "kind": "validate_timezone_shape",
+ "inputs": {
+ "tz": " "
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "timezone must be a non-empty IANA timezone key or null"
+ }
+ },
+ {
+ "id": "validate_timezone_shape/non-string-rejected",
+ "kind": "validate_timezone_shape",
+ "inputs": {
+ "tz": 123
+ },
+ "expect": {
+ "error": "ValueError",
+ "message": "timezone must be a non-empty IANA timezone key or null"
+ }
+ },
+ {
+ "id": "is_interval_schedule/plain-interval",
+ "kind": "is_interval_schedule",
+ "inputs": {
+ "schedule": "60000"
+ },
+ "expect": {
+ "ok": true
+ }
+ },
+ {
+ "id": "is_interval_schedule/cron",
+ "kind": "is_interval_schedule",
+ "inputs": {
+ "schedule": "0 */6 * * *"
+ },
+ "expect": {
+ "ok": false
+ }
+ },
+ {
+ "id": "is_interval_schedule/zero",
+ "kind": "is_interval_schedule",
+ "inputs": {
+ "schedule": "0"
+ },
+ "expect": {
+ "ok": false
+ }
+ },
+ {
+ "id": "is_interval_schedule/whitespace-padded",
+ "kind": "is_interval_schedule",
+ "inputs": {
+ "schedule": " 60000 "
+ },
+ "expect": {
+ "ok": true
+ }
+ },
+ {
+ "id": "is_interval_schedule/garbage",
+ "kind": "is_interval_schedule",
+ "inputs": {
+ "schedule": "abc"
+ },
+ "expect": {
+ "ok": false
+ }
+ },
+ {
+ "id": "is_interval_schedule/negative",
+ "kind": "is_interval_schedule",
+ "inputs": {
+ "schedule": "-5"
+ },
+ "expect": {
+ "ok": false
+ }
+ },
+ {
+ "id": "is_interval_schedule/leading-zeros",
+ "kind": "is_interval_schedule",
+ "inputs": {
+ "schedule": "007"
+ },
+ "expect": {
+ "ok": false
+ }
+ },
+ {
+ "id": "is_interval_schedule/empty",
+ "kind": "is_interval_schedule",
+ "inputs": {
+ "schedule": ""
+ },
+ "expect": {
+ "ok": false
+ }
+ },
+ {
+ "id": "const/CRON_BOUNDS",
+ "kind": "const",
+ "inputs": {
+ "name": "CRON_BOUNDS"
+ },
+ "expect": {
+ "ok": [
+ [
+ 0,
+ 59
+ ],
+ [
+ 0,
+ 23
+ ],
+ [
+ 1,
+ 31
+ ],
+ [
+ 1,
+ 12
+ ],
+ [
+ 0,
+ 6
+ ]
+ ]
+ }
+ },
+ {
+ "id": "const/_CRON_SEARCH_LIMIT_DAYS",
+ "kind": "const",
+ "inputs": {
+ "name": "_CRON_SEARCH_LIMIT_DAYS"
+ },
+ "expect": {
+ "ok": 2197
+ }
+ }
+ ]
+}
diff --git a/agent/tests/scheduling/test_triggers_equivalence.py b/agent/tests/scheduling/test_triggers_equivalence.py
new file mode 100644
index 000000000..8a93cefbd
--- /dev/null
+++ b/agent/tests/scheduling/test_triggers_equivalence.py
@@ -0,0 +1,234 @@
+"""Golden-vector equivalence proof for the extracted scheduling kernel (T1).
+
+The vectors in ``golden_next_due.json`` were captured mechanically from the
+PRE-MOVE implementation (``src.scheduled_research.executor`` /
+``src.scheduled_research.models``, byte-identical to origin/main 29aa084f)
+*before* any code moved into ``src/scheduling/triggers.py``. This file replays
+every vector against BOTH the new kernel and the legacy import paths, asserts
+the legacy names are the identical objects the kernel defines, and covers the
+new ``once`` trigger kind whose semantics were copied (not imported) from
+``agent/src/live/runtime/scheduler.py``.
+"""
+
+from __future__ import annotations
+
+import json
+from collections import Counter
+from datetime import date, timezone
+from pathlib import Path
+from zoneinfo import ZoneInfo
+
+import pytest
+
+from src.scheduled_research import executor as legacy_executor
+from src.scheduled_research import models as legacy_models
+from src.scheduling import triggers
+
+_GOLDEN = json.loads((Path(__file__).parent / "golden_next_due.json").read_text())
+_VECTORS = _GOLDEN["vectors"]
+
+_DEFAULT_TZ_SENTINEL = "__DEFAULT__"
+
+
+def _norm(value):
+ if isinstance(value, (set, frozenset)):
+ return sorted(value)
+ return value
+
+
+def _actual(fn, args):
+ try:
+ return {"ok": _norm(fn(*args))}
+ except Exception as exc: # noqa: BLE001 - golden records type + message verbatim
+ return {"error": type(exc).__name__, "message": str(exc)}
+
+
+def _as_set(values):
+ return None if values is None else set(values)
+
+
+def _call_args(vector):
+ kind = vector["kind"]
+ inputs = vector["inputs"]
+ if kind in ("next_due", "next_cron_due"):
+ if inputs["tz"] == _DEFAULT_TZ_SENTINEL:
+ return (inputs["schedule"], inputs["after_ms"])
+ return (inputs["schedule"], inputs["after_ms"], inputs["tz"])
+ if kind == "local_wall":
+ zone = timezone.utc if inputs["tz"] is None else ZoneInfo(inputs["tz"])
+ return (date(*inputs["day"]), inputs["hour"], inputs["minute"], zone)
+ if kind == "day_matches":
+ return (
+ date(*inputs["day"]),
+ _as_set(inputs["doms"]),
+ _as_set(inputs["months"]),
+ _as_set(inputs["dows"]),
+ )
+ if kind == "parse_cron_field":
+ return (inputs["part"], inputs["low"], inputs["high"])
+ if kind in ("validate_schedule", "is_interval_schedule"):
+ return (inputs["schedule"],)
+ if kind in ("validate_timezone", "validate_timezone_shape"):
+ return (inputs["tz"],)
+ raise AssertionError(f"unknown vector kind: {kind}")
+
+
+_KERNEL_FNS = {
+ "next_due": lambda: triggers.next_due,
+ "next_cron_due": lambda: triggers.next_cron_due,
+ "local_wall": lambda: triggers.local_wall_time_to_epoch_ms,
+ "day_matches": lambda: triggers.day_matches,
+ "parse_cron_field": lambda: triggers.parse_cron_field,
+ "validate_schedule": lambda: triggers.validate_schedule,
+ "validate_timezone": lambda: triggers.validate_timezone,
+ "validate_timezone_shape": lambda: triggers.validate_timezone_shape,
+ "is_interval_schedule": lambda: triggers.is_interval_schedule,
+}
+_LEGACY_FNS = {
+ "next_due": lambda: legacy_executor.next_due,
+ "next_cron_due": lambda: legacy_executor._next_cron_due,
+ "local_wall": lambda: legacy_executor._local_wall_time_to_epoch_ms,
+ "day_matches": lambda: legacy_executor._day_matches,
+ "parse_cron_field": lambda: legacy_models.parse_cron_field,
+ "validate_schedule": lambda: legacy_models.validate_schedule,
+ "validate_timezone": lambda: legacy_models.validate_timezone,
+ "validate_timezone_shape": lambda: legacy_models.validate_timezone_shape,
+ "is_interval_schedule": lambda: legacy_models.is_interval_schedule,
+}
+_CONSTS = {
+ "CRON_BOUNDS": (
+ lambda: [list(b) for b in triggers.CRON_BOUNDS],
+ lambda: [list(b) for b in legacy_models.CRON_BOUNDS],
+ ),
+ "_CRON_SEARCH_LIMIT_DAYS": (
+ lambda: triggers._CRON_SEARCH_LIMIT_DAYS,
+ lambda: legacy_executor._CRON_SEARCH_LIMIT_DAYS,
+ ),
+}
+
+
[email protected]("vector", _VECTORS, ids=[v["id"] for v in _VECTORS])
+def test_golden_vector_equivalence(vector):
+ if vector["kind"] == "const":
+ kernel_get, legacy_get = _CONSTS[vector["inputs"]["name"]]
+ assert kernel_get() == vector["expect"]["ok"]
+ assert legacy_get() == vector["expect"]["ok"]
+ return
+ args = _call_args(vector)
+ assert _actual(_KERNEL_FNS[vector["kind"]](), args) == vector["expect"]
+ assert _actual(_LEGACY_FNS[vector["kind"]](), args) == vector["expect"]
+
+
+def test_golden_matrix_meets_plan_coverage():
+ assert len(_VECTORS) >= 60
+ kinds = Counter(v["kind"] for v in _VECTORS)
+ assert kinds["next_due"] >= 40
+ ids = {v["id"] for v in _VECTORS}
+ required = {
+ "next_due/cron-utc/weekday-2000-fri-to-mon",
+ "next_due/cron-utc/every-15m-hour-rollover",
+ "next_due/cron-utc/playbook-cadence-from-jan1",
+ "next_due/cron-utc/weekday-0830-fri-to-mon",
+ "next_due/cron-utc/new-year-midnight",
+ "next_due/cron-utc/sunday-is-zero",
+ "next_due/cron-utc/dow-7-rejected",
+ "next_due/cron-utc/comma-range-mix-skips-2",
+ "next_due/cron-utc/feb-31-window-exhausted",
+ "next_due/cron-utc/feb-29-leap-day-2028",
+ "next_due/cron-utc/reversed-range-rejected",
+ "next_due/interval/basic-60000",
+ "next_due/interval/basic-21600000",
+ "next_due/interval/15-digit-upper-bound-ok",
+ "next_due/interval/16-digit-rejected",
+ "next_due/interval/advances-under-unresolvable-tz",
+ "next_due/dst-ny/spring-gap-skipped",
+ "next_due/dst-ny/fall-fold-first-occurrence",
+ "next_due/dst-ny/fall-fold-fires-once",
+ "next_due/dst-akl/spring-gap-skipped",
+ "next_due/dst-akl/fall-fold-first-occurrence",
+ "next_due/cron-utc/dom-dow-or-dow-wins",
+ "next_due/cron-utc/dom-dow-or-dom-wins",
+ "next_due/cron-utc/dom-wildcard-dow",
+ "next_due/cron-utc/dow-wildcard-dom",
+ "next_due/tz-sha/noon-local-from-utc-ref",
+ }
+ missing = required - ids
+ assert not missing, f"golden matrix lost required plan dimensions: {sorted(missing)}"
+
+
+ "name",
+ [
+ "next_due",
+ "next_cron_due",
+ "_next_cron_due",
+ "local_wall_time_to_epoch_ms",
+ "_local_wall_time_to_epoch_ms",
+ "day_matches",
+ "_day_matches",
+ "_CRON_SEARCH_LIMIT_DAYS",
+ ],
+)
+def test_executor_reexports_are_the_kernel_objects(name):
+ assert getattr(legacy_executor, name) is getattr(triggers, name)
+
+
+ "name",
+ [
+ "CRON_BOUNDS",
+ "parse_cron_field",
+ "validate_schedule",
+ "validate_timezone",
+ "validate_timezone_shape",
+ "is_interval_schedule",
+ ],
+)
+def test_models_reexports_are_the_kernel_objects(name):
+ assert getattr(legacy_models, name) is getattr(triggers, name)
+
+
+def test_underscore_aliases_are_the_public_functions():
+ assert triggers._next_cron_due is triggers.next_cron_due
+ assert triggers._local_wall_time_to_epoch_ms is triggers.local_wall_time_to_epoch_ms
+ assert triggers._day_matches is triggers.day_matches
+ assert triggers._CRON_SEARCH_LIMIT_DAYS == triggers.CRON_SEARCH_LIMIT_DAYS == 6 * 366 + 1
+
+
+def test_dow_seven_still_rejected_by_kernel_and_legacy_path():
+ for fn in (triggers.next_due, legacy_executor.next_due, triggers.validate_schedule):
+ with pytest.raises(ValueError, match=r"cron field '7' is out of range; expected 0-6"):
+ if fn is triggers.validate_schedule:
+ fn("0 12 * * 7")
+ else:
+ fn("0 12 * * 7", 0, None)
+
+
+class TestOnceTriggerKind:
+ """Semantics copied from live/runtime/scheduler.py Job.interval_ms() (read-only
+ reference; nothing imported from src.live and no live behavior changed)."""
+
+ def test_once_spec_has_no_next_run(self):
+ assert triggers.trigger_interval_ms("once") is None
+ assert triggers.next_once_due("once", 1_000) is None
+
+ def test_once_spec_is_case_insensitive_and_stripped(self):
+ assert triggers.trigger_interval_ms(" ONCE ") is None
+ assert triggers.next_once_due("Once", 1_000) is None
+
+ def test_interval_spec_advances_one_interval_past_reference(self):
+ assert triggers.trigger_interval_ms("interval:5000") == 5000
+ assert triggers.next_once_due("interval:5000", 1_000) == 6_000
+
+ def test_unusable_interval_spec_falls_back_to_default_cadence(self):
+ for spec in ("interval:0", "interval:-5", "interval:abc", "interval:"):
+ assert triggers.trigger_interval_ms(spec) == triggers.DEFAULT_TRIGGER_INTERVAL_MS
+
+ def test_bare_or_unknown_spec_uses_default_cadence(self):
+ for spec in ("", None, "garbage", "60000"):
+ assert triggers.trigger_interval_ms(spec) == triggers.DEFAULT_TRIGGER_INTERVAL_MS
+ assert triggers.next_once_due(None, 1_000) == 1_000 + triggers.DEFAULT_TRIGGER_INTERVAL_MS
+
+ def test_default_cadence_value_mirrors_live_scheduler(self):
+ assert triggers.DEFAULT_TRIGGER_INTERVAL_MS == 60 * 1000
+ assert triggers.ONCE_SPEC == "once"