Debugging Async Shutdown Failures That Mask the Real Error
A Juejin AI author describes three cleanup failures in an AgentScope script after its business flow completed and all seven evaluations passed. Calling run_until_complete() or pydantic-ai's run_sync() inside a running event loop raises “This event loop is already running,” while passing an extra argument to close_models() can raise a TypeError inside finally and hide the original exception. The recommended approach is one top-level asyncio.run() entry point, await internally, catch cleanup errors without rethrowing, and test exit behavior in a subprocess.
The report shows how small errors in asynchronous cleanup can mask the exception that actually explains why an AI agent script failed, while offering a concrete subprocess-based way to test shutdown behavior.
一个线程只有一个事件循环:"同步入口"全在抢所有权
业务跑完,评测 7/7 达标,端到端全通。
然后崩在 finally 里的那一行。
这篇讲三颗"收尾雷",但重点不在怎么修——修法都是一行的事。重点在:它们该按什么顺序修,而这个顺序和直觉相反。
一、三颗雷,两个病
先摆出来: