#2858·smolagents

BUG: LocalPythonExecutor leaves earlier context entered when a later __enter__ fails

Author: zjyHeartCreated Sep 27, 2026Updated Sep 28, 2026

Problem

LocalPythonExecutor leaves an earlier context manager entered if a later __enter__ fails in the same with statement. Standard Python calls the earlier manager's __exit__ with that exception. This can leave a lock held or a resource open after the agent sees an error.

In evaluate_with, the loop that evaluates and enters with_node.items is outside the try that exits the collected contexts: source at current main. An exception from a later context expression or __enter__ therefore skips cleanup of contexts already entered.

Steps to reproduce

This uses only a local lock and a context manager that raises while entering. No model or external service is needed.

python
import threading
from smolagents.local_python_executor import evaluate_python_code

class Failing:
    def __enter__(self):
        raise RuntimeError("boom")

    def __exit__(self, exc_type, exc, tb):
        return False

code = "with lock, failing:\n    pass"
for label in ("CPython", "smolagents"):
    lock = threading.Lock()
    state = {"lock": lock, "failing": Failing()}
    try:
        if label == "CPython":
            exec(code, state)
        else:
            evaluate_python_code(code, state=state, timeout_seconds=None)
    except Exception as exc:
        print(label, "exception:", type(exc).__name__)
    print(label, "lock still held:", lock.locked())
    if lock.locked():
        lock.release()

Actual behavior and error logs

CPython exception: RuntimeError
CPython lock still held: False
smolagents exception: InterpreterError
smolagents lock still held: True

The relevant traceback on smolagents main is:

Traceback (most recent call last):
  File "src/smolagents/local_python_executor.py", line 1643, in _execute_code
    result = evaluate_ast(node, state, static_tools, custom_tools, authorized_imports)
  File "src/smolagents/local_python_executor.py", line 1558, in evaluate_ast
    return evaluate_with(expression, *common_params)
  File "src/smolagents/local_python_executor.py", line 1246, in evaluate_with
    enter_result = context_expr.__enter__()
  File "<stdin>", line 6, in __enter__
RuntimeError: boom

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 11, in <module>
  File "src/smolagents/local_python_executor.py", line 1667, in evaluate_python_code
    return _execute_code()
  File "src/smolagents/local_python_executor.py", line 1659, in _execute_code
    raise InterpreterError(...)
smolagents.local_python_executor.InterpreterError: Code execution failed at line 'with lock, failing:
    pass' due to: RuntimeError: boom

Expected behavior

The interpreter should call lock.__exit__(RuntimeError, ...) before propagating the failed second enter, leaving lock.locked() == False, as CPython does. The exception should still reach the caller.

Environment

  • OS: macOS 26.6.2 (Apple Silicon)
  • Python: 3.12.13
  • Package: smolagents==1.27.0.dev0, main commit 227ef5e49ddd82339295939072f0223249aa8d38 (verified against remote HEAD)

Additional context

I searched open and closed issues and PRs for evaluate_with, __enter__, multi-context with, and cleanup. #2090 concerns calling __exit__ on the wrong object after a successful enter; #2758 concerns a normal return inside the body. The open PRs I found for those issues do not move the context-entry loop into an exception-safe region. This report was prepared with AI assistance and verified by running the snippet against current main and CPython.

Checklist

  • I have searched the existing issues and have not found the same bug report.
  • I have provided a minimal, reproducible example.
  • I have provided the error traceback.
  • I have provided my environment details.