Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions astrbot/core/cron/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
import re
from collections.abc import Awaitable, Callable
from contextvars import ContextVar
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any
from zoneinfo import ZoneInfo
Expand All @@ -21,6 +22,13 @@
_CRONTAB_WEEKDAY_NAMES = ("sun", "mon", "tue", "wed", "thu", "fri", "sat")
_CRONTAB_WEEKDAY_PATTERN = re.compile(r"^(?:(\*)|(\d+)(?:-(\d+))?)(?:/(\d+))?$")

# The task that owns the currently executing cron run. Tool generators are
# advanced in child tasks (astrbot.core.utils.async_generator.iterate_in_task),
# so asyncio.current_task() inside a tool is not the task registered by _run_job.
_ACTIVE_JOB_TASK: ContextVar[asyncio.Task | None] = ContextVar(
"active_cron_job_task", default=None
)


PROACTIVE_AGENT_CRON_WOKE_USER_PROMPT = (
"<system_reminder>\n"
Expand Down Expand Up @@ -235,8 +243,11 @@ async def update_job(self, job_id: str, **kwargs) -> CronJob | None:
async def delete_job(self, job_id: str) -> None:
"""Remove a schedule and drain its active runs before deleting its row.

Runs that have already started are cancelled and drained. Runs that
start after deletion begins return without executing.
Runs that have already started are cancelled and drained, except the
run that owns the current call chain: that run is excluded so a tool
deleting its own job does not cancel and await itself, and it may
still be executing when this method returns. Runs that start after
deletion begins return without executing.

Args:
job_id: Job to delete, including any currently executing run.
Expand All @@ -245,10 +256,14 @@ async def delete_job(self, job_id: str) -> None:
try:
self._remove_scheduled(job_id)
self._basic_handlers.pop(job_id, None)
# A tool runs in a child task; cancelling the run we are inside
# and awaiting it here deadlocks, so exclude its owning task too.
owner = _ACTIVE_JOB_TASK.get()
current = asyncio.current_task()
tasks = [
task
for task in self._running_tasks.get(job_id, set())
if task is not asyncio.current_task() and not task.done()
if task is not current and task is not owner and not task.done()
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
]
for task in tasks:
task.cancel()
Expand Down Expand Up @@ -386,6 +401,7 @@ async def _run_job(
# Register before the first await so delete_job always snapshots a run
# that has passed the deletion-marker check.
self._running_tasks.setdefault(job_id, set()).add(task)
owner_token = _ACTIVE_JOB_TASK.set(task)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
try:
job = await self.db.get_cron_job(job_id)
if not job or (not job.enabled and not ignore_enabled):
Expand Down Expand Up @@ -424,6 +440,7 @@ async def _run_job(
# One-shot runs remove themselves, excluding their own task.
await self.delete_job(job_id)
finally:
_ACTIVE_JOB_TASK.reset(owner_token)
running = self._running_tasks.get(job_id)
if running is not None:
running.discard(task)
Expand Down