Skip to content

fix(hooks): keep a strong reference to fire-and-forget hook triggers - #2565

Open
LHMQ878 wants to merge 1 commit into
MoonshotAI:mainfrom
LHMQ878:fix/hook-fire-and-forget-gc
Open

fix(hooks): keep a strong reference to fire-and-forget hook triggers#2565
LHMQ878 wants to merge 1 commit into
MoonshotAI:mainfrom
LHMQ878:fix/hook-fire-and-forget-gc

Conversation

@LHMQ878

@LHMQ878 LHMQ878 commented Jul 28, 2026

Copy link
Copy Markdown

Fixes #2564.

Problem

asyncio holds running tasks in a WeakSet. Writing

_hook_task = asyncio.create_task(self._hook_engine.trigger(...))
_hook_task.add_done_callback(lambda t: t.exception() if not t.cancelled() else None)
return ToolResult(...)   # <- _hook_task goes out of scope here

lets the GC collect the still-pending task, so the hook subprocess is never
awaited and the hook silently does not run. It fires non-deterministically,
depending on when a collection happens.

HookEngine.fire_and_forget_trigger() already exists for exactly this pattern —
its docstring describes this bug — and keeps the task in
_pending_fire_and_forget until it completes. Only SubagentStop had been
migrated to it.

What changed

Five call sites still rolled their own create_task:

file hook events
soul/toolset.py PostToolUse, PostToolUseFailure
soul/kimisoul.py StopFailure, Notification, PostCompact

#2564 reports the two in toolset.py. The three in kimisoul.py are the same
defect, so they are fixed here too.

Two side benefits of using the helper: the task is discarded from the pending set
on completion (no leak), and a failing task is reported through
logger.warning("Fire-and-forget hook task failed") instead of having its
exception fetched purely for the side effect and dropped.

SessionEnd in cli/__init__.py:697 is deliberately left as-is — it runs under
await asyncio.wait_for(..., timeout=5), so it is not fire-and-forget.

Tests

fire_and_forget_trigger had no test coverage at all, which is plausibly how
the migration got missed. New tests/hooks/test_fire_and_forget.py:

  • the task survives a gc.collect() when the caller keeps no reference, and its
    command still runs to completion (asserted via a file the hook touches)
  • the strong reference is released once the task finishes
  • a hook whose command cannot be executed does not leak its reference
  • an AST guard over toolset.py and kimisoul.py asserting that no
    create_task call wraps a hook trigger(...) call, so a future fire-and-forget
    site cannot silently reintroduce this

Control experiment — reverting only src/ and rerunning:

FAILED tests/hooks/test_fire_and_forget.py::test_no_bare_create_task_around_hook_triggers[kimi_cli.soul.toolset]
FAILED tests/hooks/test_fire_and_forget.py::test_no_bare_create_task_around_hook_triggers[kimi_cli.soul.kimisoul]
2 failed, 3 passed

With the fix applied: 5 passed.

ruff check and ruff format --check are clean on all three files.

Note on the pre-existing failures

pytest tests/hooks/ tests/core/test_dynamic_injection_hooks.py reports
5 failed, 38 passed on this branch. Those 5 (test_integration.py::test_pre_tool_use_block_flow,
::test_stop_hook_feedback, ::test_user_prompt_submit_block,
test_runner.py::test_exit_2_blocks, ::test_json_deny_decision) fail
identically on unmodified main — they rely on POSIX shell semantics and I ran
this on Windows. Baseline is 5 failed, 33 passed; the only difference is my 5
new tests passing.


Open in Devin Review

`asyncio` holds tasks in a `WeakSet`, so `asyncio.create_task(engine.trigger(...))`
followed by discarding the local variable lets the GC collect a still-pending
task. The hook subprocess is then never awaited and the hook silently does not
run — non-deterministically, depending on when a collection happens.

`HookEngine.fire_and_forget_trigger()` was added for exactly this pattern and
holds the task in `_pending_fire_and_forget` until it completes, but only
`SubagentStop` was migrated to it. Five call sites still rolled their own
`create_task` + `add_done_callback`:

- `soul/toolset.py`  — `PostToolUse`, `PostToolUseFailure`
- `soul/kimisoul.py` — `StopFailure`, `Notification`, `PostCompact`

Reported for `PostToolUse` / `PostToolUseFailure` in MoonshotAI#2564; the other three are
the same defect and are fixed here too. The helper also logs a failing task via
`logger.warning` instead of calling `task.exception()` for its side effect, so
hook failures stop being swallowed silently.

`SessionEnd` in `cli/__init__.py` is left alone — it is awaited under
`asyncio.wait_for`, so it is not fire-and-forget.

Tests: `fire_and_forget_trigger` had no coverage at all, which is how the
migration got missed. Added tests that the task survives a `gc.collect()` with
no caller reference and still runs its command to completion, that the reference
is released once done, and an AST guard asserting no `create_task` wraps a hook
`trigger` call in either module. Reverting the fix fails the two guard tests.

Fixes MoonshotAI#2564

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

@devin-ai-integration devin-ai-integration 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.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Open in Devin Review

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(hooks): PostToolUse / PostToolUseFailure tasks collected by GC before completion

1 participant