@@ -833,6 +833,62 @@ async def test_thread_run_raises_on_stream_error() -> None:
833833 await thread .run ("hello" )
834834
835835
836+ @pytest .mark .asyncio
837+ @pytest .mark .parametrize (
838+ "event, error_message" ,
839+ [
840+ ({"type" : "turn.failed" , "error" : {"message" : "boom" }}, "boom" ),
841+ ({"type" : "error" , "message" : "boom" }, "Codex stream error: boom" ),
842+ (
843+ {
844+ "type" : "turn.completed" ,
845+ "usage" : {"input_tokens" : 2 , "cached_input_tokens" : 1 , "output_tokens" : 3 },
846+ },
847+ None ,
848+ ),
849+ ],
850+ ids = ["turn-failed" , "stream-error" , "success" ],
851+ )
852+ async def test_thread_run_cleans_up_owned_resources (
853+ monkeypatch : pytest .MonkeyPatch , event : dict [str , Any ], error_message : str | None
854+ ) -> None :
855+ # Keep the subprocess live after its event to exercise ownership at Thread.run().
856+ process = FakeProcess (stdout_lines = [json .dumps (event ) + "\n " ], returncode = None )
857+ schema_path : Path | None = None
858+
859+ async def fake_create_subprocess_exec (* args : Any , ** kwargs : Any ) -> FakeProcess :
860+ nonlocal schema_path
861+ schema_path = Path (args [args .index ("--output-schema" ) + 1 ])
862+ assert schema_path .is_file ()
863+ return process
864+
865+ monkeypatch .setattr (exec_module .asyncio , "create_subprocess_exec" , fake_create_subprocess_exec )
866+ thread = Thread (
867+ exec_client = CodexExec (executable_path = "/bin/codex" ),
868+ options = CodexOptions (),
869+ thread_options = ThreadOptions (),
870+ )
871+ options = TurnOptions (output_schema = {"type" : "object" })
872+ generator = thread ._run_streamed_internal ("hello" , options )
873+ # Retain the owned iterator so garbage collection cannot stand in for explicit cleanup.
874+ monkeypatch .setattr (thread , "_run_streamed_internal" , lambda * args : generator )
875+
876+ try :
877+ if error_message is not None :
878+ with pytest .raises (RuntimeError , match = error_message ):
879+ await thread .run ("hello" , options )
880+ else :
881+ result = await thread .run ("hello" , options )
882+ assert result .usage == Usage (input_tokens = 2 , cached_input_tokens = 1 , output_tokens = 3 )
883+
884+ assert process .killed is (error_message is not None )
885+ assert process .returncode == 0
886+ assert schema_path is not None
887+ assert not schema_path .exists ()
888+ finally :
889+ await generator .aclose ()
890+
891+
836892@pytest .mark .asyncio
837893async def test_thread_run_streamed_raises_on_parse_error (
838894 monkeypatch : pytest .MonkeyPatch ,
0 commit comments