From 36079c66464589d137634e9f06301092139dd961 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Sat, 21 Mar 2026 15:55:25 -0700 Subject: [PATCH] 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 --- tools/code_execution_tool.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.py index 1e97156ec..5d3a80ae7 100644 --- a/tools/code_execution_tool.py +++ b/tools/code_execution_tool.py @@ -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