ReMe/tests/unit/test_agent_cron.py
jinliyl ae55e2e570
Some checks are pending
CI / Python packages / Build and verify distributions (push) Waiting to run
CI / Python quality / GitHub Actions (push) Waiting to run
CI / Python quality / Pre-commit (push) Waiting to run
CI / Python tests / Hermes embedded - ubuntu-latest (push) Waiting to run
CI / Python tests / Hermes embedded - windows-latest (push) Waiting to run
CI / Python tests / Unit Tests - py3.11 (push) Waiting to run
CI / Python tests / Unit Tests - py3.12 (push) Waiting to run
CI / Python tests / Unit Tests - py3.13 (push) Waiting to run
CI / Python tests / Unit Tests - py3.14 (push) Waiting to run
CI / ReMe Studio / Studio checks (push) Waiting to run
CI / Windows / CLI smoke - py3.11 (push) Waiting to run
Deploy / Documentation / Build documentation (push) Waiting to run
Deploy / Documentation / deploy (push) Blocked by required conditions
Security / CodeQL / Analyze javascript-typescript (push) Waiting to run
Security / CodeQL / Analyze python (push) Waiting to run
feat!: split proactive runtimes and add Studio backend management (#776)
* refactor(proactive)!: separate runtime ownership and unify delivery

* refactor(proactive): finish runtime and Studio migration

* test(proactive): make scheduled skip coverage deterministic

* refactor(studio): unify navigation and notebook resource loading

* feat(studio): edit workspace documents and update proactive task names

* refactor(studio): simplify task settings and navigation

* feat(studio): secure and supervise backend settings

* feat(studio): unify workbench timelines and refine desktop updates

Use shared timeline panes for notebook, memory, and resources. Add Todo creation ordering, persist companion visibility, and align desktop update handling and release artifacts.

Recheck editor file versions at read and publication boundaries. Retry reminder detail requests from the resource view.

* fix(studio): support unsigned GitHub preview releases

* fix: verify container state and isolate proactive view errors

Mount private supervisor state in Docker smoke tests and verify token and settings persistence. Exercise Studio startup with a loopback-only model fixture, and exclude packaged desktop output from Docker contexts.

Keep Remy subscriptions and healthy tasks available when an individual task has an invalid workspace path or session history.

* fix(home): align candidate Docker context exclusions

* chore(deps): update openai-codex dependency to v0.172.0

- Bump openai-codex from version 0.169.0 to 0.172.0 in pyproject.toml
- Keep other dependencies unchanged
- Ensure compatibility with latest openai-codex features and fixes

* fix(daemon): discover parent dotenv and isolate listeners

Restore parent-directory environment discovery in workers while retaining system precedence. Partition the default supervisor profile and lock by the configured bind address and port.
2026-11-25 21:33:16 +08:00

260 lines
13 KiB
Python

"""Reject unusable schedules before writes and isolate retained, exhausted schedules."""
# pylint: disable=missing-function-docstring,protected-access
import asyncio
from datetime import datetime
from importlib.resources import files
import json
import sys
from unittest.mock import AsyncMock, Mock
from zoneinfo import ZoneInfo
import pytest
from reme.schema import Event, Response
from reme.utils import timezone_utils
from .test_proactive_runtime import running_manager
INVALID_SCHEDULES = ("0 0 31 2 *", "0 0 1 1 * 0 2025")
NOW = datetime(2026, 11, 19, tzinfo=ZoneInfo("Asia/Shanghai"))
@pytest.mark.parametrize(
"zone_name,instant,cron,next_trigger",
[
("America/New_York", "2026-03-08T01:30:00-05:00", "30 2 * * *", "2026-03-08T03:00:00-04:00"),
("America/New_York", "2026-03-08T01:45:00-05:00", "30 * * * *", "2026-03-08T03:30:00-04:00"),
("America/New_York", "2026-11-01T01:45:00-04:00", "30 1 * * *", "2026-11-01T01:30:00-05:00"),
("America/New_York", "2026-11-01T01:29:00-05:00", "30 1 * * *", "2026-11-01T01:30:00-05:00"),
("Australia/Lord_Howe", "2026-04-05T01:45:00+11:00", "*/20 1 * * *", "2026-04-05T01:40:00+10:30"),
],
)
@pytest.mark.parametrize("explicit_timezone", [True, False], ids=["configured", "system"])
@pytest.mark.asyncio
async def test_proactive_cron_uses_local_timezone_rules(
tmp_path,
monkeypatch,
zone_name,
instant,
cron,
next_trigger,
explicit_timezone,
):
monkeypatch.setenv("TZ", zone_name)
async with running_manager(tmp_path) as (runtime, context, _):
context.app_config.timezone = zone_name if explicit_timezone else None
clock = [datetime.fromisoformat(instant).astimezone(ZoneInfo(zone_name))]
monkeypatch.setattr(runtime, "now", lambda: clock[0])
await runtime.create({"agent_name": "timer", "task_description": "Report", "cron": cron})
assert (await runtime.status("timer"))["next_trigger_at"] == next_trigger
agent = await runtime.definition("timer")
await runtime.runtimes[agent.agent_name]._schedule_cron(agent)
clock[0] = datetime.fromisoformat(next_trigger)
await runtime.runtimes[agent.agent_name]._schedule_cron(agent)
assert (await runtime.inbox.snapshot("timer"))["pending_count"] == 1
@pytest.mark.asyncio
@pytest.mark.skipif(sys.platform == "win32", reason="Unix localtime file")
@pytest.mark.parametrize("host_name", [None, "Etc/UTC"], ids=["nameless", "stale-name"])
async def test_local_cron_uses_active_host_rules(tmp_path, monkeypatch, host_name):
monkeypatch.delenv("TZ", raising=False)
localtime = tmp_path / "localtime"
localtime.write_bytes(files("tzdata.zoneinfo.America").joinpath("New_York").read_bytes())
with localtime.open("rb") as source:
rules = ZoneInfo.from_file(source, key="local")
monkeypatch.setattr(timezone_utils, "_LOCALTIME_PATHS", (localtime,))
monkeypatch.setattr(timezone_utils, "get_localzone_name", lambda: host_name)
monkeypatch.setattr(timezone_utils, "get_localzone", lambda: ZoneInfo("Etc/UTC"))
async with running_manager(tmp_path / "workspace") as (runtime, context, _):
context.app_config.timezone = None
anchor = datetime(2026, 11, 25, 8, tzinfo=rules)
monkeypatch.setattr(runtime, "now", lambda: anchor)
await runtime.create({"agent_name": "timer", "task_description": "Report", "cron": "0 9 * * *"})
scheduled = datetime.fromisoformat((await runtime.status("timer"))["next_trigger_at"])
assert scheduled.isoformat() == "2026-11-25T09:00:00-05:00"
assert scheduled.timestamp() - anchor.timestamp() == 3600
@pytest.mark.parametrize("cron", INVALID_SCHEDULES)
@pytest.mark.asyncio
async def test_unusable_cron_is_rejected_before_creating_files(tmp_path, monkeypatch, cron):
async with running_manager(tmp_path) as (runtime, _, _):
monkeypatch.setattr(runtime, "now", lambda: NOW)
with pytest.raises(ValueError, match="next date"):
await runtime.create({"agent_name": "timer", "task_description": "Report", "cron": cron})
assert not (runtime.registry.directory / "timer").exists()
assert [item["agent_name"] for item in (await runtime.list_views())["items"]] == ["Remy"]
@pytest.mark.parametrize("cron", INVALID_SCHEDULES)
@pytest.mark.asyncio
async def test_unusable_cron_update_preserves_existing_files(tmp_path, monkeypatch, cron):
async with running_manager(tmp_path) as (runtime, _, _):
monkeypatch.setattr(runtime, "now", lambda: NOW)
await runtime.create({"agent_name": "timer", "task_description": "Report", "cron": "* * * * *"})
directory = runtime.registry.path("timer")
before = {path: (path.read_bytes(), path.stat().st_mtime_ns) for path in directory.iterdir() if path.is_file()}
with pytest.raises(ValueError, match="next date"):
await runtime.update("timer", {"cron": cron})
assert {path: (path.read_bytes(), path.stat().st_mtime_ns) for path in before} == before
assert (await runtime.status("timer"))["config"]["cron"] == "* * * * *"
@pytest.mark.parametrize("cron", INVALID_SCHEDULES)
@pytest.mark.asyncio
async def test_retained_unusable_cron_survives_restart_without_blocking_other_tasks(tmp_path, monkeypatch, cron):
async with running_manager(tmp_path) as (runtime, _, _):
monkeypatch.setattr(runtime, "now", lambda: NOW)
await runtime.create({"agent_name": "aaa_bad", "task_description": "Report", "cron": "* * * * *"})
path = runtime.registry.path("aaa_bad") / "config.json"
config = json.loads(path.read_text())
runtime.files.write_json(path, {**config, "cron": cron})
saved = path.read_bytes()
async with running_manager(tmp_path) as (runtime, _, _):
monkeypatch.setattr(runtime, "now", lambda: NOW)
await runtime.create({"agent_name": "healthy", "task_description": "Report"})
await runtime.append_events("healthy", [Event(event_ts=NOW, source="test", description="Finished")])
execute = AsyncMock(return_value=(None, "session-test"))
async def run_job(name, **kwargs):
assert name == "run_proactive_agent" and kwargs["agent_name"] == "healthy"
return Response(answer=await runtime.run_round("healthy", execute))
await runtime.tick(run_job)
await asyncio.wait_for(asyncio.gather(*runtime.workers.values()), 2)
execute.assert_awaited_once()
assert (await runtime.status("healthy"))["pending_events"] == 0
status = await runtime.status("aaa_bad")
assert status["next_trigger_at"] is None and status["error"]
views = {item["agent_name"]: item for item in (await runtime.list_views())["items"]}
assert set(views) == {"Remy", "aaa_bad", "healthy"}
assert views["aaa_bad"]["status"] == "error"
assert path.read_bytes() == saved
updated = await runtime.update("aaa_bad", {"min_trigger_interval_seconds": 30})
assert updated["config"]["min_trigger_interval_seconds"] == 30
assert updated["next_trigger_at"] is None
await runtime.update("aaa_bad", {"enabled": False})
paused = path.read_bytes()
with pytest.raises(ValueError, match="next date"):
await runtime.update("aaa_bad", {"enabled": True})
assert path.read_bytes() == paused
repaired = await runtime.update("aaa_bad", {"enabled": True, "cron": "* * * * *"})
assert repaired["next_trigger_at"] is not None and repaired["error"] is None
@pytest.mark.asyncio
async def test_final_cached_cron_trigger_is_delivered_once_after_schedule_expires(tmp_path, monkeypatch):
async with running_manager(tmp_path) as (runtime, _, _):
clock = [datetime(2026, 12, 31, 23, 59, tzinfo=NOW.tzinfo)]
monkeypatch.setattr(runtime, "now", lambda: clock[0])
await runtime.create(
{"agent_name": "timer", "task_description": "Report", "cron": "0 0 1 1 * 0 2027"},
)
agent = await runtime.definition("timer")
await runtime.runtimes[agent.agent_name]._schedule_cron(agent)
clock[0] = runtime.runtimes["timer"].schedule[1]
await runtime.runtimes[agent.agent_name]._schedule_cron(agent)
await runtime.runtimes[agent.agent_name]._schedule_cron(agent)
assert (await runtime.inbox.snapshot("timer"))["pending_count"] == 1
assert (await runtime.status("timer"))["next_trigger_at"] is None
execute = AsyncMock(return_value=(None, "session-test"))
async def run_job(_name, **_kwargs):
return Response(answer=await runtime.run_round("timer", execute))
await runtime.tick(run_job)
await asyncio.wait_for(asyncio.gather(*runtime.workers.values()), 2)
await runtime.tick(run_job)
execute.assert_awaited_once()
assert (await runtime.inbox.snapshot("timer"))["pending_count"] == 0
assert not runtime.workers
assert runtime.runtimes["timer"].schedule[1] is None
@pytest.mark.asyncio
async def test_date_limited_cron_delivers_both_folds_before_exhaustion(tmp_path, monkeypatch):
zone = ZoneInfo("America/New_York")
first = datetime(2026, 11, 1, 1, 30, tzinfo=zone)
second = first.replace(fold=1)
async with running_manager(tmp_path) as (runtime, context, _):
context.app_config.timezone = zone.key
clock = [first.replace(minute=29)]
monkeypatch.setattr(runtime, "now", lambda: clock[0])
await runtime.create(
{"agent_name": "timer", "task_description": "Report", "cron": "30 1 1 11 * 0 2026"},
)
agent = await runtime.definition("timer")
await runtime.runtimes[agent.agent_name]._schedule_cron(agent)
clock[0] = first
await runtime.runtimes[agent.agent_name]._schedule_cron(agent)
assert (await runtime.status("timer"))["next_trigger_at"] == second.isoformat()
assert (await runtime.inbox.snapshot("timer"))["pending_count"] == 1
clock[0] = second
await runtime.runtimes[agent.agent_name]._schedule_cron(agent)
assert (await runtime.inbox.snapshot("timer"))["pending_count"] == 2
assert (await runtime.status("timer"))["next_trigger_at"] is None
await runtime.runtimes[agent.agent_name]._schedule_cron(agent)
assert (await runtime.inbox.snapshot("timer"))["pending_count"] == 2
@pytest.mark.asyncio
async def test_invalid_inbox_path_does_not_block_other_runtimes(tmp_path, monkeypatch):
async with running_manager(tmp_path) as (runtime, _, _):
monkeypatch.setattr(runtime, "now", lambda: NOW)
for name in ("aaa_bad", "healthy"):
await runtime.create({"agent_name": name, "task_description": "Report"})
inbox = runtime.registry.path("aaa_bad") / "inbox"
inbox.rmdir()
inbox.symlink_to(runtime.registry.path("healthy") / "inbox", target_is_directory=True)
await runtime.append_events("healthy", [Event(event_ts=NOW, source="test", description="Finished")])
started = asyncio.Event()
async def execute(*_args, **_kwargs):
started.set()
return Response()
run_job = AsyncMock(side_effect=execute)
await runtime.tick(run_job)
await asyncio.wait_for(started.wait(), 2)
run_job.assert_awaited_once_with("run_proactive_agent", agent_name="healthy")
assert "without symlinks" in runtime.runtimes["aaa_bad"].scheduler_error
entries = {item["agent_name"]: item for item in (await runtime.list_views())["items"]}
assert set(entries) == {"Remy", "aaa_bad", "healthy"}
assert entries["aaa_bad"]["status"] == "error"
assert "without symlinks" in entries["aaa_bad"]["error"]
inbox.unlink()
inbox.mkdir()
await runtime.tick(run_job)
assert runtime.runtimes["aaa_bad"].scheduler_error is None
@pytest.mark.asyncio
async def test_schedule_calculation_runs_only_when_needed(tmp_path, monkeypatch):
async with running_manager(tmp_path) as (runtime, _, _):
clock = [NOW]
monkeypatch.setattr(runtime, "now", lambda: clock[0])
await runtime.create({"agent_name": "timer", "task_description": "Report", "cron": "* * * * *"})
agent = await runtime.definition("timer")
calculate = Mock(wraps=runtime.runtimes["timer"]._next_cron_time)
monkeypatch.setattr(runtime.runtimes["timer"], "_next_cron_time", calculate)
await runtime.runtimes[agent.agent_name]._schedule_cron(agent)
next_trigger = runtime.runtimes["timer"].schedule[1]
await runtime.runtimes[agent.agent_name]._schedule_cron(agent)
await runtime.update("timer", {"min_trigger_interval_seconds": 30})
assert (await runtime.status("timer"))["next_trigger_at"] == next_trigger.isoformat()
calculate.assert_called_once()
clock[0] = next_trigger
await runtime.runtimes["timer"]._schedule_cron(await runtime.definition("timer"))
assert calculate.call_count == 2
assert (await runtime.inbox.snapshot("timer"))["pending_count"] == 1