Repository navigation
Conversation
Linked issuesChecked at commit fe9e4e0 #11063 [Bug] cron active_agent 任务用 future_task 删除自身时死锁,行永久停在 `status='running'` · 1 of 1 met
|
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="astrbot/core/cron/manager.py" line_range="399" />
<code_context>
# 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)
try:
job = await self.db.get_cron_job(job_id)
</code_context>
<issue_to_address>
**Self-deleting jobs still get cancelled**
When an agent handles a queued wakeup and deletes its job before the cron run exits, the queued event runs in a separate task without `_ACTIVE_JOB_TASK`, so `delete_job()` does not recognize the owning run and cancels and awaits it while it is still registered. This interrupts finalization or leaves self-deletion hanging.
Carry the owning-task identity through the queued wakeup, or otherwise make `delete_job()` recognize and exclude the originating run.
Also at `astrbot/core/cron/manager.py:256`.
</issue_to_address>
### Comment 2
<location path="astrbot/core/cron/manager.py" line_range="399" />
<code_context>
# 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)
try:
job = await self.db.get_cron_job(job_id)
</code_context>
<issue_to_address>
**Cron task context fails type checking**
When pyright checks this module, pyright infers `_ACTIVE_JOB_TASK` as `ContextVar[None]` from its unannotated `default=None`, so `_ACTIVE_JOB_TASK.set(task)` rejects the run’s `asyncio.Task` and static checking fails.
Annotate the variable as `ContextVar[asyncio.Task | None]` (or an equivalent task type).
</issue_to_address>
### Comment 3
<location path="astrbot/core/cron/manager.py" line_range="261" />
<code_context>
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()
]
for task in tasks:
</code_context>
<issue_to_address>
**Deletion completion guarantee is inaccurate**
When a caller relies on `delete_job()`'s docstring or calls it from a child task of the active run for the same job, `delete_job()` excludes the owning run from cancellation and draining, so it can return while that run is still executing despite the docstring promising that started runs are cancelled and drained.
Update the docstring to clarify that the owning run is excluded and may continue after `delete_job()` returns.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 2 findings to address first, and a cron run that deletes its own job is now allowed to keep executing instead of being cancelled; if that run sends a notification or performs another irreversible action afterward, reverting cannot undo it. The job deletion itself is unchanged.
Blocking findings: astrbot/core/cron/manager.py:399, astrbot/core/cron/manager.py:399
Address the type-annotation and docstring findings from the Sourcery review on PR AstrBotDevs#11071. No runtime behaviour changes. - Annotate _ACTIVE_JOB_TASK as ContextVar[asyncio.Task | None] so a basic-mode type checker accepts _ACTIVE_JOB_TASK.set(task). - Clarify that delete_job() excludes the run owning the current call chain, which may still be executing when the method returns.
Follow-up to the Sourcery reviewPushed Handled in this commit
Not changed (High): the queued-wakeup path needs the owning task identity carried across Local verification (pure stdlib, no project deps installed)
Limitations, stated plainly: this is a pure-stdlib asyncio harness with a stub manager/DB, not a live AstrBot deployment. I did not run pyright, Ready for re-review - thank you for the review and for maintaining AstrBot. |
Closes #11063
Modifications / 改动点
Only
astrbot/core/cron/manager.pyis changed:_ACTIVE_JOB_TASKContextVar(stdlibcontextvars)._run_job()sets it to the run's own task and resets it infinally.delete_job()excludes that owning run task in addition toasyncio.current_task()when choosing which active runs to cancel and drain.No new dependency, no API/schema/config change, no other file changed.
Screenshots or Test Results / 运行截图或测试结果
Backend-only change, so there is no WebUI screenshot. Test log from a pure-stdlib
asyncioharness that AST-extracts the realdelete_job()from upstreammain(base) and from this patch, and reproduces the nested-task tool-call shape:
Verification steps to reproduce locally:
astrbot/core/cron/manager.pyfrom upstreammainand from this branch.ast.parseboth, extractCronJobManager.delete_job, de-indent to a module-levelfunction,
execit withasyncioand_ACTIVE_JOB_TASKin the namespace._running_tasks,_deleting_jobs,_basic_handlers,_remove_scheduled()and an asyncdb.delete_cron_job(); create an outer task thatregisters itself for the job, set the ContextVar, and from a child task created
inside that outer task call
delete_job(<same job id>)while the outer run isstill in progress.
outer-cancelled); patched lets it finish(
outer-completed) and still deletes the row.Checklist / 检查清单
N/A - this is a bug fix for existing behaviour, discussed in [Bug] cron active_agent 任务用 future_task 删除自身时死锁,行永久停在
status='running'#11063; no new feature.Verification steps and test logs are provided above; no screenshot because this
is a backend concurrency fix with no UI change. I did not run
make pr-test-full(the full Docker/uv stack is not available in my Windows environment) - see
Evidence for the exact limit.
docs/zhanddocs/en...N/A - no navigation, page structure, label or WebUI change; no docs page describes
the internal cron task registry.
contextvarsis part of the Python standard library; no requirements change.What Problem This Solves
An
active_agentcron job that uses thefuture_tasktool to delete itself deadlocks._run_job()registers its own task in_running_tasks, but sinceiterate_in_task()(introduced in #10474) tool generators are advanced in childtasks,
asyncio.current_task()inside the tool is not that registered task.delete_job()therefore cancels the run it is executing inside and then awaits it, sothe run never reaches its
finallyblock and thecron_jobsrow stays atstatus='running'forever. Full root-cause chain is in #11063.User Impact
Self-deleting one-shot/agent cron tasks currently wedge permanently and stop being
scheduled. With this change
delete_job()no longer cancels the run that called it;the run completes normally, its
finallywrites back the status, and the row isdeleted. Deleting a different, still-running job continues to cancel and drain it.
Why This Change Was Made
asyncio.Task.cancel()cannot identify an ancestor task. AContextVarset by_run_job()is copied into every child task created by the tool chain, so it reliablyidentifies the owning run regardless of how many nested tasks the agent creates. This
is option A ("minimal") from the issue's suggested fixes: it keeps the existing
"cancel and drain active runs" contract for all other runs and needs no change to the
tool layer, the database, or the scheduler.
Evidence
delete_jobbodies.exclusion is not over-broad.
ast.parseandcompilepass on the whole patchedmanager.py; AST check confirms_run_jobsets and resets the ContextVar token; 14 changed lines in 1 file;UTF-8 without BOM, LF only.
Limitations: this is a pure-stdlib
asyncioharness with a stub manager/DB, not alive AstrBot deployment. I did not run
make pr-test-neo/make pr-test-full, thepytest suite, ruff, or a real cron/agent session (no Docker/uv stack or APScheduler
here). The harness models the owning run being cancelled rather than reproducing the
exact production hang: in the real code the child awaits its ancestor directly, which
produces an unbounded
Task.cancel()recursion / wait cycle. These limits are statedhere rather than hidden; CI and a maintainer-side live run are the first full checks.
Summary by Sourcery
Prevent self-deleting cron jobs from cancelling their owning run so they can finish cleanup and be removed successfully.
Bug Fixes:
Tests: