99import tarfile
1010import threading
1111import time
12+ from collections .abc import Coroutine
1213from contextlib import suppress
1314from pathlib import Path
1415from types import SimpleNamespace
1718import pytest
1819
1920from agents .sandbox import SandboxPathGrant
20- from agents .sandbox .errors import PtySessionNotFoundError
21+ from agents .sandbox .errors import ExecTransportError , PtySessionNotFoundError
2122from agents .sandbox .manifest import Environment , Manifest
2223from agents .sandbox .sandboxes import unix_local as unix_local_module
2324from agents .sandbox .sandboxes .unix_local import (
@@ -371,6 +372,41 @@ def record_close(fd: int | None) -> None:
371372 assert len (closed_fds ) == len (set (closed_fds ))
372373
373374
375+ @pytest .mark .asyncio
376+ async def test_unix_local_exec_closes_all_fds_when_process_launch_fails (
377+ tmp_path : Path , monkeypatch : pytest .MonkeyPatch
378+ ) -> None :
379+ workspace = tmp_path / "workspace"
380+ workspace .mkdir ()
381+ closed_fds : list [int ] = []
382+
383+ async def create_subprocess (* _args : object , ** _kwargs : object ) -> object :
384+ raise OSError ("launch failed" )
385+
386+ close_fd = unix_local_module ._close_fd_quietly
387+
388+ def record_close (fd : int | None ) -> None :
389+ if fd is not None :
390+ closed_fds .append (fd )
391+ close_fd (fd )
392+
393+ monkeypatch .setattr (unix_local_module .asyncio , "create_subprocess_exec" , create_subprocess )
394+ monkeypatch .setattr (unix_local_module , "_close_fd_quietly" , record_close )
395+ session = UnixLocalSandboxSession (
396+ state = UnixLocalSandboxSessionState (
397+ manifest = Manifest (root = str (workspace )),
398+ snapshot = NoopSnapshot (id = "noop" ),
399+ )
400+ )
401+
402+ with pytest .raises (ExecTransportError ) as exc_info :
403+ await session ._exec_internal ("echo" , "hello" )
404+
405+ assert str (exc_info .value .__cause__ ) == "launch failed"
406+ assert len (closed_fds ) == 8
407+ assert len (closed_fds ) == len (set (closed_fds ))
408+
409+
374410@pytest .mark .parametrize (
375411 ("command" , "expected_user" ),
376412 [
@@ -385,6 +421,113 @@ def test_unix_local_exec_extracts_target_user_only_from_command_prefix(
385421 assert unix_local_module ._sudo_user_from_command (command ) == expected_user
386422
387423
424+ @pytest .mark .asyncio
425+ async def test_unix_local_exec_discovers_process_group_before_startup_cancellation (
426+ tmp_path : Path , monkeypatch : pytest .MonkeyPatch
427+ ) -> None :
428+ process = SimpleNamespace (pid = 123 , returncode = None )
429+ cleanup_kwargs : dict [str , object ] = {}
430+
431+ async def settle (awaitable : object ) -> tuple [object , bool ]:
432+ cast (Coroutine [object , object , object ], awaitable ).close ()
433+ return process , True
434+
435+ async def read_info (_fd : int ) -> tuple [int , int ]:
436+ return 456 , 789
437+
438+ async def cleanup (_process : object , ** kwargs : object ) -> None :
439+ cleanup_kwargs .update (kwargs )
440+ info_task = cast (asyncio .Task [tuple [int , int ]], kwargs ["process_info_task" ])
441+ assert await info_task == (456 , 789 )
442+
443+ monkeypatch .setattr (unix_local_module , "_settle_subprocess_awaitable" , settle )
444+ monkeypatch .setattr (unix_local_module , "_read_process_group_info" , read_info )
445+ monkeypatch .setattr (unix_local_module , "_terminate_process_group_and_reap" , cleanup )
446+ session = UnixLocalSandboxSession (
447+ state = UnixLocalSandboxSessionState (
448+ manifest = Manifest (root = str (tmp_path )),
449+ snapshot = NoopSnapshot (id = "noop" ),
450+ )
451+ )
452+
453+ with pytest .raises (asyncio .CancelledError ):
454+ await session ._exec_internal ("echo" , "hello" )
455+
456+ assert cleanup_kwargs ["process_info_task" ] is not None
457+
458+
459+ @pytest .mark .asyncio
460+ async def test_unix_local_exec_does_not_signal_released_group_after_target_completion (
461+ tmp_path : Path , monkeypatch : pytest .MonkeyPatch
462+ ) -> None :
463+ wait_started = asyncio .Event ()
464+ release_wait = asyncio .Event ()
465+ killpg_calls : list [tuple [int , int ]] = []
466+
467+ class _Transport :
468+ def close (self ) -> None :
469+ return
470+
471+ class _Process :
472+ pid = 123
473+ returncode = None
474+ _transport = _Transport ()
475+ wait_calls = 0
476+
477+ async def wait (self ) -> int :
478+ self .wait_calls += 1
479+ if self .wait_calls == 1 :
480+ wait_started .set ()
481+ await release_wait .wait ()
482+ self .returncode = 0
483+ return 0
484+
485+ async def communicate (self ) -> tuple [bytes , bytes ]:
486+ return b"" , b""
487+
488+ def kill (self ) -> None :
489+ raise AssertionError ("completed target cleanup should not kill the supervisor" )
490+
491+ process = _Process ()
492+
493+ async def create_subprocess (* _args : object , ** _kwargs : object ) -> _Process :
494+ return process
495+
496+ async def read_status (_fd : int ) -> int :
497+ return 0
498+
499+ async def read_info (_fd : int ) -> tuple [int , int ]:
500+ return 456 , 789
501+
502+ async def read_output (_process : object ) -> tuple [bytes , bytes ]:
503+ return b"" , b""
504+
505+ def record_killpg (group_id : int , signum : int ) -> None :
506+ killpg_calls .append ((group_id , signum ))
507+
508+ monkeypatch .setattr (unix_local_module .asyncio , "create_subprocess_exec" , create_subprocess )
509+ monkeypatch .setattr (unix_local_module , "_read_process_exit_code" , read_status )
510+ monkeypatch .setattr (unix_local_module , "_read_process_group_info" , read_info )
511+ monkeypatch .setattr (unix_local_module , "_read_process_output" , read_output )
512+ monkeypatch .setattr (unix_local_module .os , "killpg" , record_killpg )
513+ session = UnixLocalSandboxSession (
514+ state = UnixLocalSandboxSessionState (
515+ manifest = Manifest (root = str (tmp_path )),
516+ snapshot = NoopSnapshot (id = "noop" ),
517+ )
518+ )
519+
520+ task = asyncio .create_task (session ._exec_internal ("echo" , "hello" ))
521+ await wait_started .wait ()
522+ task .cancel ()
523+ release_wait .set ()
524+
525+ with pytest .raises (asyncio .CancelledError ):
526+ await task
527+
528+ assert killpg_calls == []
529+
530+
388531@pytest .mark .asyncio
389532async def test_unix_local_exec_keeps_command_out_of_host_session (
390533 tmp_path : Path , monkeypatch : pytest .MonkeyPatch
0 commit comments