Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

[mirror] openJiuwen-ai/jiuwenswarm#1721: fix(cron): fix(cron): one-shot job missed trigger within 10s window schedules...

d3002969606c4ed48c132
diff --git a/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.py b/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.py
index ae3d458338..9e0cd73de4 100644
--- a/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.py
+++ b/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.py
@@ -236,8 +236,6 @@ def _extract_legacy_params(
if "schedule" in data or "payload" in data or "delivery" in data:
schedule = data.get("schedule") if isinstance(data.get("schedule"), dict) else {}
kind = str(schedule.get("kind") or "cron").strip().lower()
- if kind and kind != "cron":
- raise ValueError("Only cron schedule is supported by the current gateway bridge")
cron_expr = str(
schedule.get("expr")
@@ -252,12 +250,41 @@ def _extract_legacy_params(
or "Asia/Shanghai"
).strip() or "Asia/Shanghai"
+ if kind == "at":
+ at_raw = str(schedule.get("at") or "").strip()
+ if at_raw:
+ try:
+ from jiuwenswarm.gateway.cron.cron_expr import iso_to_seven_field_cron
+ cron_expr = iso_to_seven_field_cron(at_raw, timezone=timezone)
+ logger.info(
+ "[CronRuntimeBridge] _extract_legacy_params: converted kind=at '%s' to cron_expr='%s'",
+ at_raw, cron_expr,
+ )
+ except Exception as conv_exc:
+ raise ValueError(
+ f"Cannot convert schedule.at='{at_raw}' to cron expression: {conv_exc}"
+ ) from conv_exc
+ else:
+ raise ValueError("schedule.kind='at' requires schedule.at field with ISO datetime")
+ elif kind and kind != "cron":
+ raise ValueError(
+ f"Unsupported schedule.kind='{kind}'. Only 'cron' and 'at' are supported by the gateway bridge"
+ )
+
payload_block = data.get("payload") if isinstance(data.get("payload"), dict) else {}
payload_kind = str(payload_block.get("kind") or "agentTurn").strip()
- if payload_kind and payload_kind != "agentTurn":
- raise ValueError("Only agentTurn cron jobs are supported by the current gateway bridge")
+ if payload_kind == "systemEvent":
+ logger.info(
+ "[CronRuntimeBridge] _extract_legacy_params: converting payload.kind=systemEvent to agentTurn"
+ )
+ payload_kind = "agentTurn"
+ elif payload_kind and payload_kind != "agentTurn":
+ raise ValueError(
+ f"Unsupported payload.kind='{payload_kind}'. Only 'agentTurn' and 'systemEvent' are supported"
+ )
description = str(
payload_block.get("message")
+ or payload_block.get("text")
or data.get("description")
or ""
)
diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.py
index d351a6d8d1..d06825f1f5 100644
--- a/jiuwenswarm/gateway/cron/scheduler.py
+++ b/jiuwenswarm/gateway/cron/scheduler.py
@@ -547,10 +547,36 @@ class CronSchedulerService:
if at_ts <= self._now_fn() + 1.0:
self._reload_event.set()
+ _MISSED_TRIGGER_WINDOW_SECONDS = 10.0
+
def _compute_next_run(self, job: CronJob, *, now_ts: float) -> tuple[datetime, datetime, str]:
tz = ZoneInfo(job.timezone)
base = datetime.fromtimestamp(now_ts, tz=tz)
- push_dt = _cron_next_push_dt(job.cron_expr, base)
+ try:
+ push_dt = _cron_next_push_dt(job.cron_expr, base)
+ except Exception as original_exc:
+ if not self._is_croniter_no_next_date(original_exc):
+ raise original_exc
+ from croniter import croniter
+ field_count = len(job.cron_expr.strip().split())
+ second_at_beginning = field_count == 7
+ it = croniter(job.cron_expr, base, second_at_beginning=second_at_beginning)
+ prev_dt = it.get_prev(datetime)
+ if prev_dt is not None and isinstance(prev_dt, datetime):
+ if prev_dt.tzinfo is None:
+ prev_dt = prev_dt.replace(tzinfo=tz)
+ elapsed = (base.timestamp() - prev_dt.timestamp())
+ if elapsed <= self._MISSED_TRIGGER_WINDOW_SECONDS:
+ logger.info(
+ "[Cron] one-shot job=%s missed trigger by %.1fs (within %ss window), "
+ "scheduling immediate execution instead of marking expired",
+ job.id, elapsed, self._MISSED_TRIGGER_WINDOW_SECONDS,
+ )
+ push_dt = prev_dt
+ else:
+ raise original_exc
+ else:
+ raise original_exc
# proactive.tick 无视 wake_offset——到点就执行,不提前 wake。
# 否则 wake_dt = push_dt - offset 可能在过去,导致 reschedule 后立刻
# 触发 → 每 6 秒循环(实测 14:26-14:28 反复 triggering 同一 run_id)。
@@ -672,6 +698,15 @@ class CronSchedulerService:
# (实测:19:56 tick 完,20:00 整点不触发,因为没 reload)。
try:
push_dt, wake_dt, next_run_id = self._compute_next_run(job, now_ts=self._now_fn())
+ if push_dt.timestamp() <= self._now_fn():
+ logger.info(
+ "[Cron] one-shot job=%s push_dt is in the past (%s), "
+ "marking expired instead of rescheduling",
+ job.id, push_dt.isoformat(),
+ )
+ job.expired = True
+ await self._store.update_job(job.id, {"expired": True})
+ return
self._schedule_event(wake_dt, "wake", job.id, next_run_id)
self._schedule_event(push_dt, "push", job.id, next_run_id)
except Exception as exc: # 兜底:reschedule 失败不阻断本次 tick 结果(下个 reload 会重排)
@@ -769,6 +804,16 @@ class CronSchedulerService:
return
try:
push_dt, wake_dt, next_run_id = self._compute_next_run(job, now_ts=self._now_fn())
+ if push_dt.timestamp() <= self._now_fn():
+ logger.info(
+ "[Cron] one-shot job=%s push_dt is in the past (%s), "
+ "marking expired instead of rescheduling",
+ job.id, push_dt.isoformat(),
+ )
+ job.enabled = False
+ job.expired = True
+ await self._store.update_job(job.id, {"enabled": False, "expired": True})
+ return
self._schedule_event(wake_dt, "wake", job.id, next_run_id)
self._schedule_event(push_dt, "push", job.id, next_run_id)
except Exception as exc: # noqa: BLE001
@@ -861,6 +906,7 @@ class CronSchedulerService:
"run_id": run_id,
"push_at": state.push_at_iso,
"wake_at": state.wake_at_iso,
+ "current_time": datetime.fromtimestamp(self._now_fn(), tz=ZoneInfo(job.timezone)).isoformat(),
}
params: dict[str, Any] = {
"content": job.description,
diff --git a/tests/unit/agentserver/test_cron_runtime.py b/tests/unit/agentserver/test_cron_runtime.py
index 76cb0c0ef5..5a8afecff5 100644
--- a/tests/unit/agentserver/test_cron_runtime.py
+++ b/tests/unit/agentserver/test_cron_runtime.py
@@ -1,6 +1,8 @@
from __future__ import annotations
+from datetime import datetime
from types import SimpleNamespace
+from zoneinfo import ZoneInfo
import pytest
@@ -9,7 +11,33 @@ from jiuwenswarm.agents.harness.common.tools.cron.cron_runtime import (
_extract_legacy_params,
)
from jiuwenswarm.agents.harness.common.tools.cron.cron_tools import CronToolRoute, CronTools
-from jiuwenswarm.gateway.cron.store import CronJobStore
+from jiuwenswarm.gateway.cron.scheduler import CronSchedulerService
+from jiuwenswarm.gateway.cron.store import CronJob, CronJobStore
+
+import time
+
+
+class _TestableScheduler(CronSchedulerService):
+ def compute_next_run(self, job: CronJob, *, now_ts: float):
+ return self._compute_next_run(job, now_ts=now_ts)
+
+
+def _make_job(job_id="job-1", name="test", **overrides):
+ defaults = {
+ "id": job_id,
+ "name": name,
+ "enabled": True,
+ "expired": False,
+ "cron_expr": "0 0 9 * * ? *",
+ "timezone": "Asia/Shanghai",
+ "wake_offset_seconds": 300,
+ "description": "reminder",
+ "targets": "tui",
+ "created_at": time.time(),
+ "updated_at": time.time(),
+ }
+ defaults.update(overrides)
+ return CronJob(**defaults)
class _FakeCronTools:
@@ -523,3 +551,180 @@ async def test_cron_tools_create_job_inherits_session_default_project_id(
assert job["project_id"] == expected_pid
synced = push.payloads[-1]["body"]["data"]
assert synced["project_id"] == expected_pid
+
+
+class TestExtractLegacyParamsKindAt:
+ def test_kind_at_converts_to_cron_expr(self) -> None:
+ context = SimpleNamespace(
+ channel_id="web",
+ session_id="sess-1",
+ metadata={"request_id": "req-1"},
+ )
+ payload = {
+ "schedule": {"kind": "at", "at": "2026-07-24T18:25:31+08:00"},
+ "payload": {"kind": "agentTurn", "message": "喝水提醒"},
+ "delivery": {"mode": "announce"},
+ }
+
+ out = _extract_legacy_params(payload, context=context, require_schedule=True)
+
+ assert out["cron_expr"] == "31 25 18 24 7 ? 2026"
+ assert out["timezone"] == "Asia/Shanghai"
+ assert out["description"] == "喝水提醒"
+ assert "wake_offset_seconds" not in out
+
+ def test_kind_at_without_at_field_raises(self) -> None:
+ context = SimpleNamespace(channel_id="web", session_id="sess-1")
+ payload = {
+ "schedule": {"kind": "at"},
+ "payload": {"kind": "agentTurn", "message": "提醒"},
+ "delivery": {"mode": "announce"},
+ }
+
+ with pytest.raises(ValueError, match="schedule.at"):
+ _extract_legacy_params(payload, context=context, require_schedule=True)
+
+ def test_kind_at_invalid_iso_raises(self) -> None:
+ context = SimpleNamespace(channel_id="web", session_id="sess-1")
+ payload = {
+ "schedule": {"kind": "at", "at": "not-a-date"},
+ "payload": {"kind": "agentTurn", "message": "提醒"},
+ "delivery": {"mode": "announce"},
+ }
+
+ with pytest.raises(ValueError, match="Cannot convert"):
+ _extract_legacy_params(payload, context=context, require_schedule=True)
+
+ def test_kind_at_preserves_timezone(self) -> None:
+ context = SimpleNamespace(channel_id="web", session_id="sess-1")
+ payload = {
+ "schedule": {"kind": "at", "at": "2026-01-01T09:00:00+09:00", "tz": "Asia/Tokyo"},
+ "payload": {"kind": "agentTurn", "message": "朝会"},
+ "delivery": {"mode": "announce"},
+ }
+
+ out = _extract_legacy_params(payload, context=context, require_schedule=True)
+
+ assert out["timezone"] == "Asia/Tokyo"
+ assert out["cron_expr"] == "0 0 9 1 1 ? 2026"
+
+ def test_kind_every_still_raises(self) -> None:
+ context = SimpleNamespace(channel_id="web", session_id="sess-1")
+ payload = {
+ "schedule": {"kind": "every", "interval": "5m"},
+ "payload": {"kind": "agentTurn", "message": "提醒"},
+ "delivery": {"mode": "announce"},
+ }
+
+ with pytest.raises(ValueError, match="Unsupported schedule.kind"):
+ _extract_legacy_params(payload, context=context, require_schedule=True)
+
+
+class TestExtractLegacyParamsSystemEventPayload:
+ def test_system_event_converts_to_agent_turn(self) -> None:
+ context = SimpleNamespace(
+ channel_id="web",
+ session_id="sess-1",
+ metadata={"request_id": "req-1"},
+ )
+ payload = {
+ "schedule": {"kind": "cron", "expr": "0 33 16 24 7 ? 2026"},
+ "payload": {"kind": "systemEvent", "text": "该喝水了!记得补充水分哦"},
+ "delivery": {"mode": "announce"},
+ }
+
+ out = _extract_legacy_params(payload, context=context, require_schedule=True)
+
+ assert out["description"] == "该喝水了!记得补充水分哦"
+ assert out["cron_expr"] == "0 33 16 24 7 ? 2026"
+
+ def test_system_event_text_used_as_description(self) -> None:
+ context = SimpleNamespace(channel_id="web", session_id="sess-1")
+ payload = {
+ "schedule": {"kind": "cron", "expr": "*/5 * * * *"},
+ "payload": {"kind": "systemEvent", "text": "系统消息内容"},
+ "delivery": {"channel": "web"},
+ }
+
+ out = _extract_legacy_params(payload, context=context, require_schedule=True)
+
+ assert out["description"] == "系统消息内容"
+
+ def test_agent_turn_message_takes_priority_over_system_event_text(self) -> None:
+ context = SimpleNamespace(channel_id="web", session_id="sess-1")
+ payload = {
+ "schedule": {"kind": "cron", "expr": "*/5 * * * *"},
+ "payload": {"kind": "agentTurn", "message": "agentTurn消息"},
+ "delivery": {"channel": "web"},
+ }
+
+ out = _extract_legacy_params(payload, context=context, require_schedule=True)
+
+ assert out["description"] == "agentTurn消息"
+
+ def test_other_payload_kind_raises(self) -> None:
+ context = SimpleNamespace(channel_id="web", session_id="sess-1")
+ payload = {
+ "schedule": {"kind": "cron", "expr": "*/5 * * * *"},
+ "payload": {"kind": "unknownType", "text": "提醒"},
+ "delivery": {"channel": "web"},
+ }
+
+ with pytest.raises(ValueError, match="Unsupported payload.kind"):
+ _extract_legacy_params(payload, context=context, require_schedule=True)
+
+
+class TestComputeNextRunMissedTriggerWindow:
+ """When croniter fails on a one-shot job, check if the missed trigger is within
+ the window and schedule immediate execution instead of marking expired."""
+
+ def test_missed_trigger_within_window_schedules_immediate(self) -> None:
+ svc = _TestableScheduler.__new__(_TestableScheduler)
+
+ job = _make_job(
+ job_id="one-shot",
+ cron_expr="31 25 18 24 7 ? 2026",
+ timezone="Asia/Shanghai",
+ wake_offset_seconds=0,
+ )
+
+ trigger_ts = datetime(2026, 7, 24, 18, 25, 31, tzinfo=ZoneInfo("Asia/Shanghai")).timestamp()
+ now_ts = trigger_ts + 2.0
+
+ push_dt, wake_dt, run_id = svc.compute_next_run(job, now_ts=now_ts)
+
+ assert push_dt == datetime(2026, 7, 24, 18, 25, 31, tzinfo=ZoneInfo("Asia/Shanghai"))
+ assert wake_dt == push_dt
+ assert run_id.startswith("one-shot:")
+
+ def test_missed_trigger_beyond_window_raises(self) -> None:
+ svc = _TestableScheduler.__new__(_TestableScheduler)
+
+ job = _make_job(
+ job_id="old-shot",
+ cron_expr="0 0 9 1 1 ? 2025",
+ timezone="Asia/Shanghai",
+ wake_offset_seconds=0,
+ )
+
+ now_ts = datetime(2026, 7, 24, 18, 25, 0, tzinfo=ZoneInfo("Asia/Shanghai")).timestamp()
+
+ with pytest.raises(Exception, match="failed to find next date"):
+ svc.compute_next_run(job, now_ts=now_ts)
+
+ def test_recurring_job_still_works(self) -> None:
+ svc = _TestableScheduler.__new__(_TestableScheduler)
+
+ job = _make_job(
+ job_id="recurring",
+ cron_expr="*/5 * * * *",
+ timezone="Asia/Shanghai",
+ wake_offset_seconds=0,
+ )
+
+ now_ts = datetime(2026, 7, 24, 18, 30, 0, tzinfo=ZoneInfo("Asia/Shanghai")).timestamp()
+
+ push_dt, wake_dt, run_id = svc.compute_next_run(job, now_ts=now_ts)
+
+ assert push_dt.minute == 35
+ assert wake_dt == push_dt