fix(tools): fix resource leak and double socket close in code_execution_tool (#2381)

Two fixes:
1. Use a single open(os.devnull) handle for both stdout and stderr
   suppression, preventing a file handle leak if the second open() fails.
2. Set server_sock = None after closing it in the try block to prevent
   the finally block from closing it again (causing an OSError).

Closes #2136

Co-authored-by: dieutx <dangtc94@gmail.com>
This commit is contained in:
Teknium
2026-03-21 15:55:25 -07:00
committed by GitHub
parent 135448f513
commit 36079c6646

View File

@@ -300,16 +300,16 @@ def _rpc_server_loop(
# their status prints don't leak into the CLI spinner.
try:
_real_stdout, _real_stderr = sys.stdout, sys.stderr
sys.stdout = open(os.devnull, "w")
sys.stderr = open(os.devnull, "w")
devnull = open(os.devnull, "w")
try:
sys.stdout = devnull
sys.stderr = devnull
result = handle_function_call(
tool_name, tool_args, task_id=task_id
)
finally:
sys.stdout.close()
sys.stderr.close()
sys.stdout, sys.stderr = _real_stdout, _real_stderr
devnull.close()
except Exception as exc:
logger.error("Tool call failed in sandbox: %s", exc, exc_info=True)
result = json.dumps({"error": str(exc)})
@@ -574,6 +574,7 @@ def execute_code(
# Wait for RPC thread to finish
server_sock.close() # break accept() so thread exits promptly
server_sock = None # prevent double close in finally
rpc_thread.join(timeout=3)
# Build response