@@ -2561,6 +2561,71 @@ async def wf(x: int) -> str:
25612561 response = await stream .get_final_response ()
25622562 assert len (response .messages ) >= 1
25632563
2564+ @pytest .mark .parametrize ("consume" , ["none" , "first" , "all" ])
2565+ async def test_as_agent_stream_close_releases_workflow (self , consume : str ):
2566+ @built_workflow
2567+ async def wf (x : int ) -> str :
2568+ return f"result: { x } "
2569+
2570+ agent = wf .as_agent ()
2571+ stream = agent .run (1 , stream = True )
2572+ if consume == "first" :
2573+ assert (await anext (stream )).text == "result: 1"
2574+ elif consume == "all" :
2575+ assert (await stream .get_final_response ()).text == "result: 1"
2576+
2577+ await stream .close ()
2578+ assert (await agent .run (2 )).text == "result: 2"
2579+
2580+ # Closing an old stream again must not release a newer run's guard.
2581+ next_stream = agent .run (3 , stream = True )
2582+ try :
2583+ await stream .close ()
2584+ with pytest .raises (RuntimeError , match = "already running" ):
2585+ await agent .run (4 )
2586+ assert (await next_stream .get_final_response ()).text == "result: 3"
2587+ finally :
2588+ await next_stream .close ()
2589+
2590+ @pytest .mark .parametrize ("cancel" , [False , True ])
2591+ async def test_as_agent_stream_failure_releases_workflow (self , cancel : bool ):
2592+ started = asyncio .Event ()
2593+ stopped = asyncio .Event ()
2594+
2595+ @built_workflow
2596+ async def wf (x : int ) -> str :
2597+ if x == 1 :
2598+ try :
2599+ started .set ()
2600+ if cancel :
2601+ await asyncio .Event ().wait ()
2602+ raise ValueError ("workflow failure" )
2603+ finally :
2604+ stopped .set ()
2605+ return f"result: { x } "
2606+
2607+ agent = wf .as_agent ()
2608+ stream = agent .run (1 , stream = True )
2609+ pull = asyncio .create_task (anext (stream ))
2610+ try :
2611+ await asyncio .wait_for (started .wait (), timeout = 5 )
2612+ if cancel :
2613+ pull .cancel ()
2614+ with pytest .raises (asyncio .CancelledError ):
2615+ await pull
2616+ else :
2617+ with pytest .raises (ValueError , match = "workflow failure" ):
2618+ await pull
2619+ assert stopped .is_set ()
2620+ await stream .close ()
2621+ assert (await agent .run (2 )).text == "result: 2"
2622+ finally :
2623+ if not pull .done ():
2624+ pull .cancel ()
2625+ with suppress (asyncio .CancelledError ):
2626+ await pull
2627+ await stream .close ()
2628+
25642629 async def test_as_agent_has_id_and_description (self ):
25652630 @built_workflow (description = "A test workflow" )
25662631 async def wf (x : int ) -> int :
0 commit comments