DSPy: The framework for programming—not prompting—language models
Python
fix(dspy): propagate LocalInterpreter host-tool cancellation (#10379)
Isaac Miller453823209f78
diff --git a/dspy/primitives/local_interpreter.py b/dspy/primitives/local_interpreter.pyindex 0793cd563..bc12ba614 100644--- a/dspy/primitives/local_interpreter.py+++ b/dspy/primitives/local_interpreter.py@@ -86,7 +86,7 @@ class LocalInterpreter:self.execution_timeout = execution_timeoutself.callbacks = list(callbacks or [])self._process: subprocess.Popen[str] | None = None- self._responses: queue.Queue[str | None] = queue.Queue()+ self._responses: queue.Queue[str | BaseException | None] = queue.Queue()self._lock = threading.Lock()self._send_lock = threading.Lock()self._ended = False@@ -168,6 +168,9 @@ class LocalInterpreter:self._raise_terminal_error(timeout_message)if line is None:self._raise_terminal_error("Python worker exited unexpectedly.")+ if isinstance(line, BaseException):+ self.shutdown()+ raise linetry:message = json.loads(line)except json.JSONDecodeError as exc:@@ -220,6 +223,11 @@ class LocalInterpreter:response = {"type": "tool_result", "id": request["id"], "value": value}except Exception as exc:response = {"type": "tool_error", "id": request["id"], "error": f"{type(exc).__name__}: {exc}"}+ except BaseException as exc:+ # Like PythonInterpreter, propagate cancellation/interrupts to the caller.+ # Wake execute(): the worker cannot reply while this tool is unanswered.+ self._responses.put(exc)+ returnself._send(response, process)@with_callbacksdiff --git a/tests/primitives/test_release_interpreter_robustness.py b/tests/primitives/test_release_interpreter_robustness.pynew file mode 100644index 000000000..9c848a8ef--- /dev/null+++ b/tests/primitives/test_release_interpreter_robustness.py@@ -0,0 +1,54 @@+import asyncio+from concurrent.futures import ThreadPoolExecutor++import pytest++import dspy+from dspy.primitives.code_interpreter import CodeExecutionError, CodeInterpreterError+++ "interpreter_type",+ [dspy.LocalInterpreter, pytest.param(dspy.PythonInterpreter, marks=pytest.mark.deno)],+)[email protected]("error_type", [asyncio.CancelledError, KeyboardInterrupt, SystemExit, ValueError])+def test_host_tool_failures_match_deno(interpreter_type, error_type):+ error = error_type("host tool stopped")++ async def fail():+ raise error++ kwargs = {"execution_timeout": 1} if interpreter_type is dspy.LocalInterpreter else {}+ interpreter = interpreter_type(tools={"fail": fail}, **kwargs)+ try:+ if error_type is ValueError:+ with pytest.raises(CodeExecutionError, match="host tool stopped"):+ interpreter.execute("fail()")+ assert str(interpreter.execute("6 * 7")).strip() == "42"+ else:+ # Python 3.10's asyncio.run replaces task cancellation with an empty CancelledError.+ with pytest.raises(error_type) as expected:+ asyncio.run(fail())+ with pytest.raises(error_type) as caught:+ interpreter.execute("fail()")+ assert type(caught.value) is type(expected.value)+ assert caught.value.args == expected.value.args+ if interpreter_type is dspy.LocalInterpreter:+ assert interpreter._process is None+ with pytest.raises(CodeInterpreterError, match="shut down"):+ interpreter.execute("6 * 7")+ finally:+ interpreter.shutdown()+++def test_cancelled_host_tool_wakes_execution_without_timeout():+ async def fail():+ raise asyncio.CancelledError("host tool stopped")++ interpreter = dspy.LocalInterpreter(tools={"fail": fail})+ with ThreadPoolExecutor(max_workers=1) as executor:+ try:+ with pytest.raises(asyncio.CancelledError):+ executor.submit(interpreter.execute, "fail()").result(timeout=5)+ finally:+ interpreter.shutdown()