@@ -160,3 +160,77 @@ async def consumer() -> None:
160160 timeout = 1 ,
161161 )
162162 assert consumer_cancelled .is_set ()
163+
164+
165+ @pytest .mark .asyncio
166+ @pytest .mark .parametrize ("producer_consumer" , [False , True ])
167+ async def test_closing_task_helper_leaves_child_cleanup_to_owner (producer_consumer : bool ) -> None :
168+ children = [asyncio .create_task (asyncio .Event ().wait ()) for _ in range (2 )]
169+ child_failure_reported = asyncio .Event ()
170+ coro = (
171+ run_producer_consumer (* children , on_failure = child_failure_reported .set )
172+ if producer_consumer
173+ else gather_with_cancel (* children , on_child_failure = child_failure_reported .set )
174+ )
175+ try :
176+ # Drive the coroutine as its owner; do not close a live asyncio Task's coroutine.
177+ coro .send (None )
178+ coro .close ()
179+ await asyncio .sleep (0 )
180+ assert all (not child .done () for child in children )
181+ assert not child_failure_reported .is_set ()
182+ finally :
183+ for child in children :
184+ child .cancel ()
185+ await asyncio .gather (* children , return_exceptions = True )
186+ coro .close ()
187+
188+
189+ @pytest .mark .asyncio
190+ async def test_closing_agent_tool_lookup_leaves_enabled_check_cleanup_to_owner () -> None :
191+ from agents import Agent , RunContextWrapper
192+ from agents .decorators import tool
193+
194+ started = asyncio .Event ()
195+ finished = asyncio .Event ()
196+ release = asyncio .Event ()
197+
198+ async def is_enabled (context : RunContextWrapper [None ], agent : Agent [None ]) -> bool :
199+ started .set ()
200+ try :
201+ await release .wait ()
202+ finally :
203+ finished .set ()
204+ return True
205+
206+ @tool (is_enabled = is_enabled )
207+ def example () -> str :
208+ return "example"
209+
210+ agent = Agent [None ](name = "test" , tools = [example ])
211+ coro = agent .get_all_tools (RunContextWrapper (context = None ))
212+ try :
213+ coro .send (None )
214+ await started .wait ()
215+ coro .close ()
216+ await asyncio .sleep (0 )
217+ assert not finished .is_set ()
218+ finally :
219+ release .set ()
220+ await finished .wait ()
221+ coro .close ()
222+
223+
224+ @pytest .mark .asyncio
225+ async def test_run_producer_consumer_drains_children_on_parent_cancellation () -> None :
226+ children = [asyncio .create_task (asyncio .Event ().wait ()) for _ in range (2 )]
227+ parent = asyncio .create_task (run_producer_consumer (* children ))
228+ try :
229+ await asyncio .sleep (0 )
230+ parent .cancel ()
231+ with pytest .raises (asyncio .CancelledError ):
232+ await parent
233+ assert all (child .cancelled () for child in children )
234+ finally :
235+ parent .cancel ()
236+ await asyncio .gather (parent , * children , return_exceptions = True )
0 commit comments