mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(scheduler): canonicalize one-time task timestamps at the Gateway boundary (#8675)
Keep explicit instants in UTC and offset-free times in the task zone. Apply the same representation to historical reads while preserving no-op edits and the original execution time. Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com>
This commit is contained in:
parent
af7a6ade13
commit
c0eefedc4f
@ -13,7 +13,7 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
from app.gateway.scheduled_task_errors import scheduler_error
|
||||
from deerflow.persistence.scheduled_task_runs.finalization import is_host_pause_marker
|
||||
from deerflow.scheduler.schedules import MAX_INTERVAL_SECONDS, next_run_at, normalize_cron_expression, parse_interval_seconds, validate_timezone
|
||||
from deerflow.scheduler.schedules import MAX_INTERVAL_SECONDS, canonical_once_run_at, next_run_at, normalize_cron_expression, parse_interval_seconds, validate_timezone
|
||||
from deerflow.scheduler.stop_rule import MAX_STOP_CONDITION_CHARS, normalize_stop_condition
|
||||
from deerflow.utils.goal_objective import MAX_GOAL_OBJECTIVE_CHARS, normalize_goal_objective
|
||||
|
||||
@ -276,7 +276,7 @@ def _recompute_schedule(existing: dict[str, Any], updates: dict[str, Any], *, sc
|
||||
unchanged_definition = (
|
||||
existing["schedule_type"] == "once"
|
||||
and isinstance(previous_spec, dict)
|
||||
and schedule_spec.get("run_at") == previous_spec.get("run_at")
|
||||
and canonical_once_run_at(schedule_spec.get("run_at")) == canonical_once_run_at(previous_spec.get("run_at"))
|
||||
and timezone == existing["timezone"]
|
||||
and existing["status"] not in TERMINAL_TASK_STATUSES
|
||||
and existing.get("next_run_at") is not None
|
||||
|
||||
@ -17,6 +17,7 @@ from deerflow.persistence.scheduled_task_runs.projection import account_launch,
|
||||
from deerflow.persistence.scheduled_tasks.model import ACTIVE_RUN_STATUSES, LIVE_TASK_STATUSES, ONCE_TASK_STATUS_BY_RUN_STATUS, TERMINAL_RUN_STATUSES, TERMINAL_TASK_STATUSES, ScheduledTaskRow
|
||||
from deerflow.runtime.events.terminal import RecoveryTerminalPublisher, RecoveryTerminalTarget
|
||||
from deerflow.scheduler.host_notes import RUN_ERROR_END_REACHED, RUN_ERROR_INTERRUPTED
|
||||
from deerflow.scheduler.schedules import canonical_once_run_at
|
||||
from deerflow.utils.goal_objective import normalize_goal_objective
|
||||
from deerflow.utils.time import coerce_iso
|
||||
|
||||
@ -25,6 +26,12 @@ logger = logging.getLogger(__name__)
|
||||
_TERMINAL_DURABLE_RUN_STATUSES = frozenset({"success", "error", "timeout", "interrupted"})
|
||||
|
||||
|
||||
def _canonical_schedule_spec(schedule_type: str, spec: dict[str, Any]) -> dict[str, Any]:
|
||||
if schedule_type == "once" and isinstance(spec, dict) and "run_at" in spec:
|
||||
return {**spec, "run_at": canonical_once_run_at(spec["run_at"])}
|
||||
return spec
|
||||
|
||||
|
||||
class ScheduledTaskQuotaExceeded(ValueError):
|
||||
"""A tool-created task would exceed its owner's live schedule quota."""
|
||||
|
||||
@ -105,6 +112,7 @@ class ScheduledTaskRepository:
|
||||
@staticmethod
|
||||
def _row_to_dict(row: ScheduledTaskRow) -> dict[str, Any]:
|
||||
data = row.to_dict(exclude={"last_occurrence_seq", "unmet_streak_after_seq"})
|
||||
data["schedule_spec"] = _canonical_schedule_spec(row.schedule_type, row.schedule_spec)
|
||||
for key in _TIMESTAMP_KEYS:
|
||||
if data.get(key) is not None:
|
||||
data[key] = coerce_iso(data[key])
|
||||
@ -181,7 +189,7 @@ class ScheduledTaskRepository:
|
||||
title=title,
|
||||
prompt=prompt,
|
||||
schedule_type=schedule_type,
|
||||
schedule_spec=schedule_spec,
|
||||
schedule_spec=_canonical_schedule_spec(schedule_type, schedule_spec),
|
||||
timezone=timezone,
|
||||
next_run_at=next_run_at,
|
||||
created_at=now,
|
||||
@ -408,6 +416,8 @@ class ScheduledTaskRepository:
|
||||
raise ActiveScheduledTaskMutationConflict(active_status)
|
||||
for key, value in updates.items():
|
||||
if hasattr(row, key):
|
||||
if key == "schedule_spec":
|
||||
value = _canonical_schedule_spec(updates.get("schedule_type", row.schedule_type), value)
|
||||
# Callers pass timestamps back in the serialized form
|
||||
# ``_row_to_dict`` returned (the PATCH route reuses an
|
||||
# interval task's ``next_run_at`` unchanged); bind datetimes.
|
||||
|
||||
@ -31,6 +31,20 @@ def normalize_cron_expression(expr: str) -> str:
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def canonical_once_run_at(value: object) -> object:
|
||||
"""Serialize explicit instants in UTC and wall times without an offset."""
|
||||
if not isinstance(value, str):
|
||||
return value
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value)
|
||||
if parsed.tzinfo is not None:
|
||||
parsed = parsed.astimezone(UTC)
|
||||
except (ValueError, OverflowError):
|
||||
# Admission reports invalid input. Keep malformed old rows readable.
|
||||
return value
|
||||
return parsed.isoformat()
|
||||
|
||||
|
||||
def parse_interval_seconds(schedule_spec: dict[str, object]) -> int:
|
||||
raw = schedule_spec.get("every_seconds")
|
||||
if isinstance(raw, bool) or not isinstance(raw, int) or raw < 1:
|
||||
|
||||
@ -23,6 +23,7 @@ from deerflow.persistence.engine import close_engine, get_session_factory, init_
|
||||
from deerflow.persistence.scheduled_task_runs import ScheduledTaskRunRepository
|
||||
from deerflow.persistence.scheduled_task_runs.finalization import AGENT_STOP_LAST_ERROR_PREFIX
|
||||
from deerflow.persistence.scheduled_tasks import ScheduledTaskRepository
|
||||
from deerflow.persistence.scheduled_tasks.model import ScheduledTaskRow
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@ -1533,6 +1534,76 @@ def _when(body):
|
||||
_CREATE = {"title": "Checklist", "prompt": "Check release-checklist.md.\nList the unchecked items.", "schedule_type": "interval", "schedule_spec": {"every_seconds": 3600}, "timezone": "UTC"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fixed_schedule_clock(monkeypatch):
|
||||
class FixedDatetime(datetime):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return cls(2026, 10, 22, tzinfo=UTC)
|
||||
|
||||
monkeypatch.setattr(scheduled_tasks, "datetime", FixedDatetime)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("clock", "utc_clock"),
|
||||
[
|
||||
("09:30:00+08", "01:30:00"),
|
||||
("09:30:00,5+08", "01:30:00.500000"),
|
||||
("09:30.5+08", "01:30:00.500000"),
|
||||
("09:30:30+08:00:30", "01:30:00"),
|
||||
],
|
||||
)
|
||||
async def test_once_api_stores_explicit_instants_in_utc(http, fixed_schedule_clock, clock, utc_clock):
|
||||
expected = f"2026-12-12T{utc_clock}+00:00"
|
||||
fields = {"schedule_type": "once", "schedule_spec": {"run_at": f"2026-12-12T{clock}"}, "timezone": "Asia/Shanghai"}
|
||||
response = await http.client.post("/api/scheduled-tasks", json={**_CREATE, **fields})
|
||||
assert response.status_code == 200, response.text
|
||||
task = response.json()
|
||||
assert task["schedule_spec"]["run_at"] == task["next_run_at"] == expected
|
||||
async with http.sf() as session:
|
||||
assert (await session.get(ScheduledTaskRow, task["id"])).schedule_spec["run_at"] == expected
|
||||
moved = await http.client.patch(f"/api/scheduled-tasks/{task['id']}", json={"timezone": "UTC"})
|
||||
assert moved.json()["next_run_at"] == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rescheduled_wall_time_follows_the_task_zone(http, fixed_schedule_clock):
|
||||
task = await _seed(http.repo)
|
||||
url = f"/api/scheduled-tasks/{task['id']}"
|
||||
local = "2026-12-12T09:30:00.123456"
|
||||
response = await http.client.patch(url, json={"schedule_type": "once", "schedule_spec": {"run_at": "2026-12-12T09:30,123456"}, "timezone": "Asia/Shanghai"})
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json()["schedule_spec"]["run_at"] == local
|
||||
assert response.json()["next_run_at"] == "2026-12-12T01:30:00.123456+00:00"
|
||||
async with http.sf() as session:
|
||||
assert (await session.get(ScheduledTaskRow, task["id"])).schedule_spec["run_at"] == local
|
||||
moved = await http.client.patch(url, json={"timezone": "UTC"})
|
||||
assert moved.json()["next_run_at"] == local + "+00:00"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_once_reads_work_without_a_next_run_or_a_backfill(http):
|
||||
raw = "20261212T093000+08"
|
||||
expected = "2026-12-12T01:30:00+00:00"
|
||||
for task_id, value in [("old", raw), ("invalid", "unparseable")]:
|
||||
await _seed(http.repo, task_id=task_id)
|
||||
async with http.sf.begin() as session:
|
||||
row = await session.get(ScheduledTaskRow, task_id)
|
||||
row.schedule_type = "once"
|
||||
row.schedule_spec = {"run_at": value}
|
||||
row.status = "completed"
|
||||
row.next_run_at = None
|
||||
url = "/api/scheduled-tasks/old"
|
||||
listed = (await http.client.get("/api/scheduled-tasks")).json()
|
||||
assert {task["id"]: task["schedule_spec"]["run_at"] for task in listed} == {"old": expected, "invalid": "unparseable"}
|
||||
for response in [await http.client.get(url), await http.client.patch(url, json={"title": "Renamed"})]:
|
||||
assert response.json()["schedule_spec"]["run_at"] == expected
|
||||
assert response.json()["next_run_at"] is None
|
||||
async with http.sf() as session:
|
||||
assert (await session.get(ScheduledTaskRow, "old")).schedule_spec["run_at"] == raw
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resume_recomputes_a_past_interval_run_from_now(http):
|
||||
await _seed(http.repo, next_run_at=datetime.now(UTC) - timedelta(hours=5))
|
||||
@ -1742,13 +1813,7 @@ async def test_naive_end_at_is_wall_clock_time_in_the_task_timezone(http):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(("operation", "field"), [("create", "run_at"), ("update", "run_at"), ("create", "end_at"), ("update", "end_at"), ("resume", "end_at")])
|
||||
async def test_http_rejects_nonexistent_local_time_without_writing(http, monkeypatch, operation, field):
|
||||
class FixedDatetime(datetime):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return cls(2026, 10, 22, tzinfo=UTC)
|
||||
|
||||
monkeypatch.setattr(scheduled_tasks, "datetime", FixedDatetime)
|
||||
async def test_http_rejects_nonexistent_local_time_without_writing(http, fixed_schedule_clock, operation, field):
|
||||
wall_time = "2027-03-14T02:30:00"
|
||||
fields = {"schedule_type": "once", "schedule_spec": {"run_at": wall_time}} if field == "run_at" else {"end_at": wall_time}
|
||||
if operation == "create":
|
||||
|
||||
@ -137,14 +137,14 @@ async def test_end_at_past_the_utc_range_is_rejected(operation, end_at):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("status", ["enabled", "paused"])
|
||||
async def test_unchanged_legacy_gap_schedule_keeps_its_already_accepted_instant(status):
|
||||
@pytest.mark.parametrize(("status", "submitted"), [("enabled", "2027-03-14T02:30:00"), ("paused", "20270314T023000")])
|
||||
async def test_unchanged_legacy_gap_schedule_keeps_its_already_accepted_instant(status, submitted):
|
||||
timezone, wall_time = GAPS[0]
|
||||
spec = {"run_at": wall_time}
|
||||
accepted = next_run_at("once", spec, timezone, now=NOW)
|
||||
existing = _existing(timezone, status=status, schedule_spec=spec, next_run_at=accepted)
|
||||
updates = await validate_scheduled_task_update(
|
||||
existing, {"schedule_spec": spec, "timezone": timezone, "title": "Renamed"}, user_id="owner", thread_store=None, scheduler_config=SchedulerConfig(), assistant_resolver=AsyncMock(), used=0, now=NOW
|
||||
existing, {"schedule_spec": {"run_at": submitted}, "timezone": timezone, "title": "Renamed"}, user_id="owner", thread_store=None, scheduler_config=SchedulerConfig(), assistant_resolver=AsyncMock(), used=0, now=NOW
|
||||
)
|
||||
assert updates["next_run_at"] == accepted
|
||||
assert next_run_at("once", spec, timezone, now=accepted) is None
|
||||
|
||||
@ -6,10 +6,12 @@ Editing a one-time task's title or prompt preserves its original execution time,
|
||||
|
||||
An unchanged one-time execution time can still be saved within `scheduler.min_once_delay_seconds` of its run. New execution times and reactivated finished tasks must satisfy that minimum delay.
|
||||
|
||||
One-time local timestamps saved through chat or the API retain their seconds
|
||||
and fractional seconds when the Web UI resolves them in the task's timezone.
|
||||
This includes stored timestamps such as `2026-12-07T09:00.5`, which the
|
||||
scheduler interprets as `09:00:00.5` in that timezone.
|
||||
For one-time tasks, the Gateway returns `schedule_spec.run_at` in calendar
|
||||
date and time format, including seconds and any fractional seconds. A value
|
||||
with an explicit offset is stored and returned in UTC. A value without an
|
||||
offset stays a local time in the task's timezone, so changing just the
|
||||
timezone keeps the same wall-clock time. Older tasks use the same response
|
||||
format, including after their last run.
|
||||
|
||||
Current MVP capabilities:
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user