Skip to content

fix: a cron tool deleting its own running job cancels and stalls that run - #11071

Closed
lhjl-j wants to merge 2 commits into
AstrBotDevs:masterfrom
lhjl-j:fix/cron-self-delete-owner-task-11063
Closed

lhjl-j wants to merge 2 commits into
AstrBotDevs:masterfrom
lhjl-j:fix/cron-self-delete-owner-task-11063

Conversation

@lhjl-j

@lhjl-j lhjl-j commented Nov 10, 2026 •

Copy link
Copy Markdown

Closes #11063

Modifications / 改动点

Only astrbot/core/cron/manager.py is changed:

  • Add a module-level _ACTIVE_JOB_TASK ContextVar (stdlib contextvars).
  • _run_job() sets it to the run's own task and resets it in finally.
  • delete_job() excludes that owning run task in addition to
    asyncio.current_task() when choosing which active runs to cancel and drain.

No new dependency, no API/schema/config change, no other file changed.

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

Backend-only change, so there is no WebUI screenshot. Test log from a pure-stdlib
asyncio harness that AST-extracts the real delete_job() from upstream main
(base) and from this patch, and reproduces the nested-task tool-call shape:

== scenario 1: a cron tool deletes the very job it is running (issue #11063) ==
  base    : outcome=outer-cancelled    events=['run:start', 'run:cancelled'] db.deleted=['756ae0cc-...']
  patched : outcome=outer-completed    events=['run:start', 'run:completed'] db.deleted=['756ae0cc-...']
== scenario 2: patched delete_job on a DIFFERENT job still cancels its run ==
  other run cancelled=['yes'] db.deleted=['other-job'] task.done=True

Verification steps to reproduce locally:

  1. Read astrbot/core/cron/manager.py from upstream main and from this branch.
  2. ast.parse both, extract CronJobManager.delete_job, de-indent to a module-level
    function, exec it with asyncio and _ACTIVE_JOB_TASK in the namespace.
  3. Build a stub manager with _running_tasks, _deleting_jobs, _basic_handlers,
    _remove_scheduled() and an async db.delete_cron_job(); create an outer task that
    registers 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 is
    still in progress.
  4. Base cancels the owning run (outer-cancelled); patched lets it finish
    (outer-completed) and still deletes the row.
  5. Repeat with a different job id to prove cross-job cancellation is preserved.

Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
    N/A - this is a bug fix for existing behaviour, discussed in [Bug] cron active_agent 任务用 future_task 删除自身时死锁,行永久停在 status='running' #11063; no new feature.
  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
    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.
  • 📚 I checked the affected WebUI instructions and screenshots in docs/zh and docs/en ...
    N/A - no navigation, page structure, label or WebUI change; no docs page describes
    the internal cron task registry.
  • 🤓 I have ensured that no new dependencies are introduced ...
    contextvars is part of the Python standard library; no requirements change.
  • 😮 My changes do not introduce malicious code.

What Problem This Solves

An active_agent cron job that uses the future_task tool to delete itself deadlocks.
_run_job() registers its own task in _running_tasks, but since
iterate_in_task() (introduced in #10474) tool generators are advanced in child
tasks, 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, so
the run never reaches its finally block and the cron_jobs row stays at
status='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 finally writes back the status, and the row is
deleted. 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. A ContextVar set by
_run_job() is copied into every child task created by the tool chain, so it reliably
identifies 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

  • red-on-base / green-on-fix above, using the real extracted delete_job bodies.
  • Regression guard above: deleting another job still cancels its task, so the
    exclusion is not over-broad.
  • ast.parse and compile pass on the whole patched manager.py; AST check confirms
    _run_job sets and resets the ContextVar token; 14 changed lines in 1 file;
    UTF-8 without BOM, LF only.

Limitations: this is a pure-stdlib asyncio harness with a stub manager/DB, not a
live AstrBot deployment. I did not run make pr-test-neo / make pr-test-full, the
pytest 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 stated
here 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:

  • Prevent cron jobs from cancelling and deadlocking their own active run when a tool deletes the job currently being executed.
  • Preserve cancellation and draining of active runs when deleting a different cron job.

Tests:

  • Add regression verification covering self-deletion and cancellation of a separate running job.

@sourcery-ai

sourcery-ai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit fe9e4e0

#11063 [Bug] cron active_agent 任务用 future_task 删除自身时死锁,行永久停在 `status='running'` · 1 of 1 met

# Requirement Status Notes
1 Prevent self-deleting active_agent cron jobs from deadlocking; delete the job or let the run finish its cleanup. ✅ Met delete_job() excludes the owning run task, allowing it to delete the row without cancelling and awaiting itself.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread astrbot/core/cron/manager.py Resolved
Comment thread astrbot/core/cron/manager.py Resolved
Comment thread astrbot/core/cron/manager.py Resolved
@Soulter Soulter moved this to In Progress in AstrBot Roadmap Nov 10, 2026
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.
@lhjl-j

lhjl-j commented Nov 10, 2026

Copy link
Copy Markdown
Author

Follow-up to the Sourcery review

Pushed fe9e4e08 to the same branch (fix/cron-self-delete-owner-task-11063). PR is now 2 commits / 1 file / +20 -3; no new PR, no force push.

Handled in this commit

  • Type annotation (Medium): _ACTIVE_JOB_TASK: ContextVar[asyncio.Task | None] so pyright/basic accepts .set(task).
  • Docstring (Low): delete_job() now says the run owning the current call chain is excluded and may still be executing when the method returns.

Not changed (High): the queued-wakeup path needs the owning task identity carried across agent_wakeup.py, the event object and the queue consumer - a cross-module design change outside this PR's one-file scope. I verified the source paths and left a detailed reply on that thread; happy to follow up if maintainers want it here.

Local verification (pure stdlib, no project deps installed)

  • ast.parse / compile on the full patched manager.py: pass.
  • ruff format --check: pass. ruff check with this repo's own rules (F,W,E,ASYNC,C4,Q,I,UP, py310): head and patched produce identical results (one pre-existing I001 import-order warning in both), so the patch adds no new lint finding. Note: local ruff is 0.17.4 while the repo pins 0.15.22.
  • Behaviour-equivalence harness AST-extracts the real delete_job() from upstream master, the previous head and the patched file: base = outer-cancelled, previous head = outer-completed, patched = outer-completed (identical events and DB deletes). Regression guard: deleting a different job still cancels its run (cancelled=['yes']). The two edits are annotation + docstring only; delete_job() behaviour is unchanged.
  • Remote readback: 19205 bytes byte-identical, blob sha verified, UTF-8 without BOM, LF only.

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, make pr-test-neo / make pr-test-full, pytest, or a real cron/agent session (no Docker/uv stack here); the repo's CI workflows are still action_required awaiting maintainer approval, so no CI job has executed. No test assertion was changed and no check was skipped.

Ready for re-review - thank you for the review and for maintaining AstrBot.

@Soulter Soulter closed this Nov 10, 2026
@github-project-automation github-project-automation Bot moved this from In Progress to Done in AstrBot Roadmap Nov 10, 2026
@Soulter

Soulter commented Nov 10, 2026

Copy link
Copy Markdown
Member

Hi, #11063 has been resolved in #11071

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

[Bug] cron active_agent 任务用 future_task 删除自身时死锁,行永久停在 status='running'

2 participants