Skip to content

Personal AI, On Personal Devices

Python

fix: make managed schedules deterministic (#883)

Elliot Sluskye6eb76d90c59
diff --git a/pyproject.toml b/pyproject.toml
index 1719c1db..3eae3562 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -29,6 +29,7 @@ classifiers = [
]
dependencies = [
"click>=8",
+ "croniter>=2.0",
"datasets>=4.5.0",
"ddgs>=9.11.4",
"httpx>=0.27",
@@ -148,6 +149,8 @@ browser = ["playwright>=1.40"]
media = ["openai>=1.30"]
mining-pearl-vllm = ["docker>=7.0", "httpx>=0.27"]
pdf = ["pdfplumber>=0.10"]
+# Kept as a compatibility extra for existing install commands. Cron support is
+# a core scheduler contract now, so croniter is also installed unconditionally.
scheduler = ["croniter>=2.0"]
security-signing = ["cryptography>=43"]
sandbox-wasm = ["wasmtime>=25"]
diff --git a/src/openjarvis/agents/executor.py b/src/openjarvis/agents/executor.py
index 14b70601..f0f438d5 100644
--- a/src/openjarvis/agents/executor.py
+++ b/src/openjarvis/agents/executor.py
@@ -36,6 +36,46 @@ _MAX_RETRIES = 3
_AGENT_TICK_DEFAULT_MODEL = "gemma4:31b"
+def _resolve_tick_model(config: dict[str, Any], system: Any) -> str:
+ """Resolve a managed tick model without hiding the system default."""
+
+ return (
+ config.get("model")
+ or (getattr(system, "model", "") if system is not None else "")
+ or _AGENT_TICK_DEFAULT_MODEL
+ )
+
+
+def _available_tick_models(engine: Any, resolved_model: str) -> list[str]:
+ """Return every model the active engine can actually route to.
+
+ Keep the resolved default first when the engine confirms it is available,
+ preserving the existing fallback behavior. Some remote engines cannot list
+ models, so retain the resolved model as a last-resort singleton when model
+ discovery fails or returns no usable identifiers.
+ """
+
+ try:
+ listed = engine.list_models()
+ except Exception as exc:
+ logger.warning("Could not list models for managed-agent routing: %s", exc)
+ return [resolved_model] if resolved_model else []
+
+ candidates = [listed] if isinstance(listed, str) else listed or []
+ available: list[str] = []
+ for candidate in candidates:
+ normalized = candidate.strip() if isinstance(candidate, str) else ""
+ if normalized and normalized not in available:
+ available.append(normalized)
+
+ if not available:
+ return [resolved_model] if resolved_model else []
+ if resolved_model in available:
+ available.remove(resolved_model)
+ available.insert(0, resolved_model)
+ return available
+
+
def _tool_calls_for_storage(result: AgentResult) -> list[dict[str, Any]] | None:
"""Convert executor tool results to the managed-message storage contract."""
@@ -288,11 +328,7 @@ class AgentExecutor:
engine = self._system.engine if self._system else None
if engine is None:
raise FatalError("No engine available in JarvisSystem")
- model = (
- config.get("model")
- or _AGENT_TICK_DEFAULT_MODEL
- or (self._system.model if self._system else "")
- )
+ model = _resolve_tick_model(config, self._system)
if not model:
raise FatalError("No model configured for agent")
@@ -316,7 +352,7 @@ class AgentExecutor:
policy = RouterPolicyRegistry.create(
router_policy_key,
- available_models=[model],
+ available_models=_available_tick_models(engine, model),
)
instruction = config.get("instruction", "")
ctx = build_routing_context(instruction)
diff --git a/src/openjarvis/agents/manager.py b/src/openjarvis/agents/manager.py
index 38fa71aa..50ec03d7 100644
--- a/src/openjarvis/agents/manager.py
+++ b/src/openjarvis/agents/manager.py
@@ -188,16 +188,7 @@ class AgentManager:
) -> Dict[str, Any]:
agent_id = uuid.uuid4().hex[:12]
now = time.time()
- # Pin the model the executor will actually use into the agent's config
- # so the UI reflects what runs. Without this, config has no "model" and
- # the executor silently falls back to _AGENT_TICK_DEFAULT_MODEL while
- # the Overview shows a stale/default value. Lazy import avoids any
- # import-order coupling with the executor module.
- from openjarvis.agents.executor import _AGENT_TICK_DEFAULT_MODEL
-
config = dict(config or {})
- if not config.get("model"):
- config["model"] = _AGENT_TICK_DEFAULT_MODEL
config_json = json.dumps(config)
self._conn.execute(
"INSERT INTO managed_agents"
diff --git a/src/openjarvis/agents/scheduler.py b/src/openjarvis/agents/scheduler.py
index 5ac6f72e..edda4d8e 100644
--- a/src/openjarvis/agents/scheduler.py
+++ b/src/openjarvis/agents/scheduler.py
@@ -5,7 +5,9 @@ from __future__ import annotations
import logging
import threading
import time
+from datetime import datetime
from typing import TYPE_CHECKING, Any
+from zoneinfo import ZoneInfo
from openjarvis.core.events import EventType
@@ -16,25 +18,33 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-def _next_cron_fire(cron_expr: str, now: float | None = None) -> float:
+def _next_cron_fire(
+ cron_expr: str,
+ now: float | None = None,
+ timezone_name: str | None = None,
+) -> float:
"""Calculate the next fire time for a cron expression.
- Uses croniter if available, otherwise falls back to a simple
- interval-based approximation.
+ ``timezone_name`` is an optional IANA timezone. Without one, preserve the
+ historical host-local interpretation. Missing cron support is fatal: an
+ hourly approximation would silently change the schedule's meaning.
"""
try:
from croniter import croniter
- except ImportError:
- # Fallback: treat as hourly interval
- logger.warning("croniter not installed, treating cron as 3600s interval")
- return (now or time.time()) + 3600
-
- base = now or time.time()
- import datetime
-
- dt = datetime.datetime.fromtimestamp(base)
+ except ImportError as exc:
+ raise RuntimeError(
+ "croniter is required for cron schedules; reinstall OpenJarvis"
+ ) from exc
+
+ base = time.time() if now is None else now
+ tz = ZoneInfo(timezone_name) if timezone_name else None
+ dt = (
+ datetime.fromtimestamp(base, tz=tz)
+ if tz is not None
+ else datetime.fromtimestamp(base).astimezone()
+ )
cron = croniter(cron_expr, dt)
- next_dt = cron.get_next(datetime.datetime)
+ next_dt = cron.get_next(datetime)
return next_dt.timestamp()
@@ -81,10 +91,11 @@ class AgentScheduler:
config = agent.get("config", {})
schedule_type = config.get("schedule_type", "manual")
schedule_value = config.get("schedule_value", 0)
+ timezone_name = config.get("timezone") or None
now = time.time()
if schedule_type == "cron":
- next_fire = _next_cron_fire(str(schedule_value), now)
+ next_fire = _next_cron_fire(str(schedule_value), now, timezone_name)
elif schedule_type == "interval":
next_fire = now + float(schedule_value)
else:
@@ -94,6 +105,7 @@ class AgentScheduler:
self._agents[agent_id] = {
"schedule_type": schedule_type,
"schedule_value": schedule_value,
+ "timezone": timezone_name,
"next_fire": next_fire,
}
@@ -205,6 +217,7 @@ class AgentScheduler:
self._agents[agent_id]["next_fire"] = _next_cron_fire(
str(info["schedule_value"]),
now,
+ info.get("timezone"),
)
elif info["schedule_type"] == "interval":
self._agents[agent_id]["next_fire"] = now + float(
diff --git a/src/openjarvis/cli/digest_cmd.py b/src/openjarvis/cli/digest_cmd.py
index c1406dda..d755d7b2 100644
--- a/src/openjarvis/cli/digest_cmd.py
+++ b/src/openjarvis/cli/digest_cmd.py
@@ -81,12 +81,13 @@ def _save_digest_schedule(enabled: bool, cron: str) -> None:
config_path.write_text("\n".join(new_lines))
-def _create_scheduler_task(cron: str) -> Optional[str]:
+def _create_scheduler_task(cron: str, timezone_name: str = "") -> Optional[str]:
"""Create a digest task in the TaskScheduler. Returns task ID or None."""
try:
from openjarvis.scheduler.scheduler import TaskScheduler
from openjarvis.scheduler.store import SchedulerStore
+ timezone_name = timezone_name or load_config().digest.timezone
db_path = DEFAULT_CONFIG_PATH.parent / "scheduler.db"
store = SchedulerStore(db_path)
scheduler = TaskScheduler(store)
@@ -101,6 +102,7 @@ def _create_scheduler_task(cron: str) -> Optional[str]:
schedule_type="cron",
schedule_value=cron,
agent="morning_digest",
+ metadata={"timezone": timezone_name},
)
store.close()
return task.id
@@ -279,7 +281,7 @@ def _handle_schedule(console: Console, schedule: str) -> None:
# Set a new cron schedule
_save_digest_schedule(enabled=True, cron=schedule)
- task_id = _create_scheduler_task(schedule)
+ task_id = _create_scheduler_task(schedule, digest_cfg.timezone)
console.print(f"[green]Digest schedule set:[/green] {schedule}")
if task_id:
console.print(f" Scheduler task created: {task_id}")
diff --git a/src/openjarvis/scheduler/scheduler.py b/src/openjarvis/scheduler/scheduler.py
index ebbfe4ed..76e2c6f3 100644
--- a/src/openjarvis/scheduler/scheduler.py
+++ b/src/openjarvis/scheduler/scheduler.py
@@ -8,6 +8,7 @@ import uuid
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional
+from zoneinfo import ZoneInfo
from openjarvis.scheduler.store import SchedulerStore
@@ -300,48 +301,36 @@ class TaskScheduler:
return next_time.isoformat()
if task.schedule_type == "cron":
- return self._compute_next_cron(task.schedule_value, now)
+ timezone_name = str((task.metadata or {}).get("timezone") or "") or None
+ return self._compute_next_cron(task.schedule_value, now, timezone_name)
return None
@staticmethod
- def _compute_next_cron(cron_expr: str, now: datetime) -> Optional[str]:
+ def _compute_next_cron(
+ cron_expr: str,
+ now: datetime,
+ timezone_name: str | None = None,
+ ) -> Optional[str]:
"""Compute the next run time from a cron expression.
- Uses ``croniter`` if available, otherwise falls back to a basic
- minute-granularity parser for simple expressions.
+ Evaluate in the configured IANA timezone and persist the result in UTC.
+ Missing cron support is fatal instead of silently changing semantics.
"""
try:
from croniter import croniter # type: ignore[import-untyped]
-
- it = croniter(cron_expr, now)
- return it.get_next(datetime).isoformat()
- except ImportError:
- pass
-
- # Basic fallback: parse "minute hour * * *" style expressions
- parts = cron_expr.strip().split()
- if len(parts) < 5:
- logger.warning(
- "Cannot parse cron without croniter: %s",
- cron_expr,
- )
- return (now + timedelta(hours=1)).isoformat()
-
- minute_part, hour_part = parts[0], parts[1]
-
- try:
- target_minute = int(minute_part) if minute_part != "*" else now.minute
- target_hour = int(hour_part) if hour_part != "*" else now.hour
- except ValueError:
- return (now + timedelta(hours=1)).isoformat()
-
- candidate = now.replace(
- hour=target_hour, minute=target_minute, second=0, microsecond=0
- )
- if candidate <= now:
- candidate += timedelta(days=1)
- return candidate.isoformat()
+ except ImportError as exc:
+ raise RuntimeError(
+ "croniter is required for cron schedules; reinstall OpenJarvis"
+ ) from exc
+
+ if now.tzinfo is None:
+ now = now.replace(tzinfo=timezone.utc)
+ local_now = now.astimezone(ZoneInfo(timezone_name)) if timezone_name else now
+ next_local = croniter(cron_expr, local_now).get_next(datetime)
+ if next_local.tzinfo is None:
+ next_local = next_local.replace(tzinfo=local_now.tzinfo)
+ return next_local.astimezone(timezone.utc).isoformat()
__all__ = [
diff --git a/src/openjarvis/server/digest_routes.py b/src/openjarvis/server/digest_routes.py
index abcf86ae..04e27ef8 100644
--- a/src/openjarvis/server/digest_routes.py
+++ b/src/openjarvis/server/digest_routes.py
@@ -112,7 +112,7 @@ def create_digest_router(*, db_path: str = "") -> APIRouter:
# Sync with the TaskScheduler
if body.enabled:
- _create_scheduler_task(cron)
+ _create_scheduler_task(cron, cfg.digest.timezone)
else:
_cancel_scheduler_tasks()
diff --git a/tests/agents/test_executor.py b/tests/agents/test_executor.py
index 800ddb27..1f108135 100644
--- a/tests/agents/test_executor.py
+++ b/tests/agents/test_executor.py
@@ -163,3 +163,65 @@ def test_finalize_tick_reads_agent_result_metadata(tmp_path):
assert updated["total_cost"] == 0.05
assert updated["stall_retries"] == 0
mgr.close()
+
+
+def test_tick_model_prefers_system_default_before_legacy_fallback() -> None:
+ from openjarvis.agents.executor import _resolve_tick_model
+
+ system = MagicMock(model="qwen3:8b")
+
+ assert _resolve_tick_model({}, system) == "qwen3:8b"
+ assert _resolve_tick_model({"model": "agent-model"}, system) == "agent-model"
+
+
+def test_managed_router_receives_every_actual_engine_model() -> None:
+ from openjarvis.agents.executor import _available_tick_models
+ from openjarvis.learning.routing.router import (
+ HeuristicRouter,
+ build_routing_context,
+ )
+
+ engine = MagicMock()
+ engine.list_models.return_value = [
+ "qwen3:8b",
+ "tiny:1b",
+ "code-coder:32b",
+ "qwen3:8b",
+ "",
+ ]
+
+ available = _available_tick_models(engine, "qwen3:8b")
+ selected = HeuristicRouter(available_models=available).select_model(
+ build_routing_context("Write a Python function with tests")
+ )
+
+ assert available == ["qwen3:8b", "tiny:1b", "code-coder:32b"]
+ assert selected == "code-coder:32b"
+ engine.list_models.assert_called_once_with()
+
+
+def test_managed_router_excludes_unavailable_fallback_model() -> None:
+ from openjarvis.agents.executor import _available_tick_models
+
+ engine = MagicMock()
+ engine.list_models.return_value = ["tiny:1b", "large:32b"]
+
+ assert _available_tick_models(engine, "missing:legacy") == [
+ "tiny:1b",
+ "large:32b",
+ ]
+
+
+def test_managed_router_retains_resolved_model_when_discovery_fails() -> None:
+ from openjarvis.agents.executor import _available_tick_models
+
+ engine = MagicMock()
+ engine.list_models.side_effect = RuntimeError("offline")
+
+ assert _available_tick_models(engine, "remote:model") == ["remote:model"]
+
+
+def test_new_agent_without_model_keeps_system_default_unpinned(manager) -> None:
+ agent = manager.create_agent("inherits-system-model", config={})
+
+ assert "model" not in agent["config"]
diff --git a/tests/agents/test_scheduler.py b/tests/agents/test_scheduler.py
index 7a7b41da..bebd8442 100644
--- a/tests/agents/test_scheduler.py
+++ b/tests/agents/test_scheduler.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import tempfile
import threading
import time
+from datetime import datetime, timezone
from pathlib import Path
from unittest.mock import MagicMock
@@ -57,6 +58,44 @@ class TestSchedulerBasic:
scheduler.register_agent(agent["id"])
assert agent["id"] in scheduler.registered_agents
+ def test_cron_uses_agent_timezone(self, manager, monkeypatch):
+ from openjarvis.agents import scheduler as scheduler_module
+ from openjarvis.agents.scheduler import AgentScheduler
+
+ fixed_now = datetime(2026, 1, 15, 12, 0, tzinfo=timezone.utc).timestamp()
+ monkeypatch.setattr(scheduler_module.time, "time", lambda: fixed_now)
+ scheduler = AgentScheduler(manager=manager, executor=MagicMock())
+ agent = manager.create_agent(
+ name="timezone-agent",
+ config={
+ "schedule_type": "cron",
+ "schedule_value": "0 5 * * *",
+ "timezone": "America/Los_Angeles",
+ },
+ )
+
+ scheduler.register_agent(agent["id"])
+
+ expected = datetime(2026, 1, 15, 13, 0, tzinfo=timezone.utc).timestamp()
+ assert scheduler._agents[agent["id"]]["next_fire"] == expected
+ assert scheduler._agents[agent["id"]]["timezone"] == "America/Los_Angeles"
+
+ def test_missing_croniter_fails_loudly(self, monkeypatch):
+ import builtins
+
+ from openjarvis.agents.scheduler import _next_cron_fire
+
+ real_import = builtins.__import__
+
+ def without_croniter(name, *args, **kwargs):
+ if name == "croniter":
+ raise ImportError("blocked for test")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", without_croniter)
+ with pytest.raises(RuntimeError, match="croniter is required"):
+ _next_cron_fire("0 5 * * *", now=0)
+
def test_deregister_agent(self, manager):
from openjarvis.agents.scheduler import AgentScheduler
diff --git a/tests/scheduler/test_digest_schedule.py b/tests/scheduler/test_digest_schedule.py
index d87d50ca..6a75dbc2 100644
--- a/tests/scheduler/test_digest_schedule.py
+++ b/tests/scheduler/test_digest_schedule.py
@@ -2,7 +2,9 @@
from __future__ import annotations
+from datetime import datetime
from unittest.mock import MagicMock, patch
+from zoneinfo import ZoneInfo
import pytest
from click.testing import CliRunner
@@ -62,7 +64,7 @@ class TestDigestScheduleCLI:
assert result.exit_code == 0
assert "0 7 * * *" in result.output
assert "abc123" in result.output
- mock_create.assert_called_once_with("0 7 * * *")
+ mock_create.assert_called_once_with("0 7 * * *", "America/Los_Angeles")
# Verify config was written
content = config_path.read_text()
@@ -94,6 +96,28 @@ class TestDigestScheduleCLI:
assert "disabled" in result.output.lower()
mock_save.assert_called_once_with(enabled=False, cron="0 6 * * *")
+ def test_scheduler_task_persists_digest_timezone(self, tmp_path):
+ from openjarvis.cli import digest_cmd
+ from openjarvis.scheduler.store import SchedulerStore
+
+ config_path = tmp_path / "config.toml"
+ with patch("openjarvis.cli.digest_cmd.DEFAULT_CONFIG_PATH", config_path):
+ task_id = digest_cmd._create_scheduler_task(
+ "0 6 * * *",
+ "America/Los_Angeles",
+ )
+
+ assert task_id is not None
+ store = SchedulerStore(tmp_path / "scheduler.db")
+ task = store.get_task(task_id)
+ store.close()
+
+ assert task is not None
+ assert task["metadata"] == {"timezone": "America/Los_Angeles"}
+ next_run = datetime.fromisoformat(task["next_run"])
+ local_next_run = next_run.astimezone(ZoneInfo("America/Los_Angeles"))
+ assert (local_next_run.hour, local_next_run.minute) == (6, 0)
+
# ---------------------------------------------------------------------------
# API endpoint tests
@@ -139,6 +163,7 @@ class TestDigestScheduleEndpoints:
mock_cfg = MagicMock()
mock_cfg.digest.enabled = False
mock_cfg.digest.schedule = "0 6 * * *"
+ mock_cfg.digest.timezone = "America/Los_Angeles"
with (
patch(
@@ -161,7 +186,10 @@ class TestDigestScheduleEndpoints:
assert data["enabled"] is True
assert data["cron"] == "30 7 * * 1-5"
mock_save.assert_called_once_with(enabled=True, cron="30 7 * * 1-5")
- mock_create.assert_called_once_with("30 7 * * 1-5")
+ mock_create.assert_called_once_with(
+ "30 7 * * 1-5",
+ "America/Los_Angeles",
+ )
def test_schedule_endpoint_disable(self, client):
"""POST /api/digest/schedule with enabled=false cancels tasks."""
diff --git a/tests/scheduler/test_scheduler.py b/tests/scheduler/test_scheduler.py
index 0643bc15..d60baef3 100644
--- a/tests/scheduler/test_scheduler.py
+++ b/tests/scheduler/test_scheduler.py
@@ -194,6 +194,44 @@ class TestComputeNextRun:
next_run = scheduler._compute_next_run(task)
assert next_run is not None
+ def test_cron_honors_metadata_timezone(self, scheduler, monkeypatch):
+ fixed_now = datetime(2026, 1, 15, 12, 0, tzinfo=timezone.utc)
+
+ class FixedDatetime(datetime):
+ @classmethod
+ def now(cls, tz=None):
+ return fixed_now if tz is not None else fixed_now.replace(tzinfo=None)
+
+ task = ScheduledTask(
+ id="t",
+ prompt="p",
+ schedule_type="cron",
+ schedule_value="0 5 * * *",
+ metadata={"timezone": "America/Los_Angeles"},
+ )
+ monkeypatch.setattr("openjarvis.scheduler.scheduler.datetime", FixedDatetime)
+
+ next_run = scheduler._compute_next_run(task)
+
+ assert next_run == "2026-01-15T13:00:00+00:00"
+
+ def test_cron_without_dependency_fails_loudly(self, scheduler, monkeypatch):
+ import builtins
+
+ real_import = builtins.__import__
+
+ def without_croniter(name, *args, **kwargs):
+ if name == "croniter":
+ raise ImportError("blocked for test")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", without_croniter)
+ with pytest.raises(RuntimeError, match="croniter is required"):
+ scheduler._compute_next_cron(
+ "0 5 * * *",
+ datetime(2026, 1, 15, tzinfo=timezone.utc),
+ )
+
def test_unknown_type(self, scheduler):
task = ScheduledTask(
id="t", prompt="p", schedule_type="unknown", schedule_value="x"
diff --git a/uv.lock b/uv.lock
index 2f4d3f32..987c9fc1 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4270,6 +4270,7 @@ name = "openjarvis"
source = { editable = "." }
dependencies = [
{ name = "click" },
+ { name = "croniter" },
{ name = "datasets" },
{ name = "ddgs" },
{ name = "httpx" },
@@ -4503,6 +4504,7 @@ requires-dist = [
{ name = "apple-fm-sdk", marker = "sys_platform == 'darwin' and extra == 'afm'", specifier = ">=0.2.1" },
{ name = "click", specifier = ">=8" },
{ name = "colbert-ai", marker = "extra == 'memory-colbert'", specifier = ">=0.2" },
+ { name = "croniter", specifier = ">=2.0" },
{ name = "croniter", marker = "extra == 'scheduler'", specifier = ">=2.0" },
{ name = "cryptography", marker = "extra == 'security-signing'", specifier = ">=43" },
{ name = "datasets", specifier = ">=4.5.0" },