Skip to content

Conversation

@ConnectionFailedd
Copy link
Contributor

When bot exits, it sets _should_exit (1), so that Bot._handle_should_exit will be executed, which calls cancel_scope.cancel() (2):

class Bot:
    async def _run(self) -> None:
        """运行 AliceBot。"""
        logger.info("Running AliceBot...")

        for bot_run_hook_func in self._bot_run_hooks:
            await bot_run_hook_func(self)

        try:
            for _adapter in self.adapters:
                for adapter_startup_hook_func in self._adapter_startup_hooks:
                    await adapter_startup_hook_func(_adapter)
                try:
                    await _adapter.startup()
                except Exception:
                    logger.exception("Startup adapter failed", adapter=_adapter)

            async with anyio.create_task_group() as tg:
                for _adapter in self.adapters:
                    for adapter_run_hook_func in self._adapter_run_hooks:
                        await adapter_run_hook_func(_adapter)
                    tg.start_soon(_adapter.safe_run)

            await self._should_exit.wait()
        finally: # (3)
            for _adapter in self.adapters:
                for adapter_shutdown_hook_func in self._adapter_shutdown_hooks:
                    await adapter_shutdown_hook_func(_adapter)
                await _adapter.shutdown()

            for bot_exit_hook_func in self._bot_exit_hooks:
                await bot_exit_hook_func(self)

            self.adapters.clear()
            self.plugins_priority_dict.clear()
            self._module_path_finder.path.clear()

    def _handle_exit(self, *_args: Any) -> None:  # pragma: no cover
        """当机器人收到退出信号时,根据情况进行处理。"""
        logger.info("Stopping AliceBot...")
        if self._should_exit.is_set():
            logger.warning("Force Exit AliceBot...")
            sys.exit()
        else:
            self._should_exit.set() # (1)

    async def _handle_should_exit(self, cancel_scope: anyio.CancelScope) -> None:
        """当 should_exit 被设置时取消当前的 task group。"""
        await self._should_exit.wait()
        cancel_scope.cancel() # (2)

This makes the finally block in _run (3) not executed properly. According to my observation, the execution stops AFTER THE FIRST await.

Added with anyio.CancelScope(shield=True): line to fix this bug. It works on me.

@codecov
Copy link

codecov bot commented Sep 26, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (06afa44) to head (5c03934).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #176   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           12        12           
  Lines          932       933    +1     
=========================================
+ Hits           932       933    +1     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@st1020
Copy link
Member

st1020 commented Sep 26, 2025

LGTM, and we can add a test for this case.

@st1020 st1020 merged commit 4e03bbd into AliceBotProject:main Sep 26, 2025
26 of 27 checks passed
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.

2 participants