Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

test(deno): pool Deno/Pyodide interpreters across tests (#10089)

Isaac Miller629d1e3c8b58
diff --git a/tests/conftest.py b/tests/conftest.py
index aabbe43fa..4c514713f 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -76,3 +76,78 @@ def lm_for_test():
if model is None:
pytest.skip("LM_FOR_TEST is not set in the environment variables")
return model
+
+
+# Booting a Deno/Pyodide interpreter costs ~2.5s, which dominates the deno-marked
+# test suite. Tests that only exercise execute() semantics share one interpreter
+# per pytest process and restore its global namespace between tests. Tests that
+# configure Deno *process-level* permissions (enable_env_vars/enable_read_paths/
+# enable_write_paths/enable_network_access/deno_command/sync_files) or exercise
+# session lifecycle (shutdown, process death, protocol failure) must keep
+# creating their own instances.
+_POOL_SETUP_CODE = """
+def _pool_reset():
+ g = globals()
+ for name in [n for n in g if n not in _POOL_SAVED]:
+ del g[name]
+ g.update(_POOL_SAVED)
+
+_POOL_SAVED = dict(globals())
+_POOL_SAVED["_POOL_SAVED"] = _POOL_SAVED
+"""
+
+
[email protected](scope="session")
+def _interpreter_pool() -> Iterator[dict[str, Any]]:
+ holder: dict[str, Any] = {"interpreter": None}
+ yield holder
+ if holder["interpreter"] is not None:
+ holder["interpreter"].shutdown()
+
+
+def pooled_interpreter(_interpreter_pool: dict[str, Any]):
+ """A shared PythonInterpreter with per-test namespace restoration.
+
+ Per-test tools and output_fields may be set by mutating ``.tools`` /
+ ``.output_fields`` and clearing ``_tools_registered`` (the same protocol
+ RLM uses for caller-owned interpreters); teardown restores both along
+ with the sandbox's global namespace.
+ """
+ from dspy.primitives.code_interpreter import CodeInterpreterError
+ from dspy.primitives.python_interpreter import PythonInterpreter
+
+ interpreter = _interpreter_pool["interpreter"]
+ if interpreter is None:
+ interpreter = PythonInterpreter()
+ interpreter.execute(_POOL_SETUP_CODE)
+ _interpreter_pool["interpreter"] = interpreter
+
+ yield interpreter
+
+ try:
+ interpreter.tools.clear()
+ interpreter.output_fields = None
+ interpreter._tools_registered = False
+ interpreter.execute("_pool_reset()")
+ except CodeInterpreterError:
+ # The test that just ran killed the session. Surface that loudly on
+ # this test and boot a fresh interpreter for the next consumer.
+ _interpreter_pool["interpreter"] = None
+ interpreter.shutdown()
+ raise
+
+
+def configure_pooled_interpreter(pooled_interpreter):
+ """Configure the pooled interpreter with per-test tools/output_fields."""
+
+ def configure(tools: dict[str, Any] | None = None, output_fields: list[dict[str, Any]] | None = None):
+ if tools:
+ pooled_interpreter.tools.update(tools)
+ if output_fields is not None:
+ pooled_interpreter.output_fields = output_fields
+ pooled_interpreter._tools_registered = False
+ return pooled_interpreter
+
+ return configure
diff --git a/tests/predict/test_code_act.py b/tests/predict/test_code_act.py
index a9df7ecdd..471b16a07 100644
--- a/tests/predict/test_code_act.py
+++ b/tests/predict/test_code_act.py
@@ -35,7 +35,7 @@ def add(a: float, b: float) -> float:
"add two numbers"
return a + b
-def test_codeact_code_generation():
+def test_codeact_code_generation(pooled_interpreter):
lm = DummyLM(
[
{
@@ -48,7 +48,7 @@ def test_codeact_code_generation():
)
dspy.configure(lm=lm)
program = CodeAct(BasicQA, tools=[add])
- res = program(question="What is 1+1?")
+ res = program(pooled_interpreter, question="What is 1+1?")
assert res.answer == "2"
assert res.trajectory == {
"code_output_0": '"2\\n"',
@@ -65,7 +65,7 @@ def extract_maximum_minimum(input_list: str) -> dict[str, float]:
numbers = list(map(float, input_list.split(",")))
return {"maximum": max(numbers), "minimum": min(numbers)}
-def test_codeact_support_multiple_fields():
+def test_codeact_support_multiple_fields(pooled_interpreter):
lm = DummyLM(
[
{
@@ -78,7 +78,7 @@ def test_codeact_support_multiple_fields():
)
dspy.configure(lm=lm)
program = CodeAct(ExtremumFinder, tools=[extract_maximum_minimum])
- res = program(input_list="2, 3, 5, 6")
+ res = program(pooled_interpreter, input_list="2, 3, 5, 6")
assert res.maximum == "6"
assert res.minimum == "2"
assert res.trajectory == {
@@ -87,7 +87,7 @@ def test_codeact_support_multiple_fields():
}
-def test_codeact_code_parse_failure():
+def test_codeact_code_parse_failure(pooled_interpreter):
lm = DummyLM(
[
{
@@ -105,7 +105,7 @@ def test_codeact_code_parse_failure():
)
dspy.configure(lm=lm)
program = CodeAct(BasicQA, tools=[add])
- res = program(question="What is 1+1?")
+ res = program(pooled_interpreter, question="What is 1+1?")
assert res.answer == "2"
assert res.trajectory == {
"generated_code_0": "parse(error",
@@ -115,7 +115,7 @@ def test_codeact_code_parse_failure():
}
-def test_codeact_code_execution_failure():
+def test_codeact_code_execution_failure(pooled_interpreter):
lm = DummyLM(
[
{
@@ -133,7 +133,7 @@ def test_codeact_code_execution_failure():
)
dspy.configure(lm=lm)
program = CodeAct(BasicQA, tools=[add])
- res = program(question="What is 1+1?")
+ res = program(pooled_interpreter, question="What is 1+1?")
assert res.answer == "2"
assert res.trajectory == {
"generated_code_0": "unknown+1",
diff --git a/tests/predict/test_program_of_thought.py b/tests/predict/test_program_of_thought.py
index d02ee5dbd..3b4084a11 100644
--- a/tests/predict/test_program_of_thought.py
+++ b/tests/predict/test_program_of_thought.py
@@ -40,7 +40,7 @@ class RecordingPythonInterpreterFactory:
@pytest.mark.deno
-def test_pot_code_generation():
+def test_pot_code_generation(pooled_interpreter):
lm = DummyLM(
[
{
@@ -52,13 +52,13 @@ def test_pot_code_generation():
)
dspy.configure(lm=lm)
pot = ProgramOfThought(BasicQA)
- res = pot(question="What is 1+1?")
+ res = pot(pooled_interpreter, question="What is 1+1?")
assert res.answer == "2"
# This test ensures the old finetuned saved models still work
@pytest.mark.deno
-def test_old_style_pot():
+def test_old_style_pot(pooled_interpreter):
lm = DummyLM(
[
{"reasoning": "Reason_A", "generated_code": "```python\nresult = 1+1\n```"},
@@ -67,7 +67,7 @@ def test_old_style_pot():
)
dspy.configure(lm=lm)
pot = ProgramOfThought(BasicQA)
- res = pot(question="What is 1+1?")
+ res = pot(pooled_interpreter, question="What is 1+1?")
assert res.answer == "2"
@@ -78,7 +78,7 @@ class ExtremumFinder(Signature):
@pytest.mark.deno
-def test_pot_support_multiple_fields():
+def test_pot_support_multiple_fields(pooled_interpreter):
lm = DummyLM(
[
{
@@ -90,13 +90,13 @@ def test_pot_support_multiple_fields():
)
dspy.configure(lm=lm)
pot = ProgramOfThought(ExtremumFinder)
- res = pot(input_list="2, 3, 5, 6")
+ res = pot(pooled_interpreter, input_list="2, 3, 5, 6")
assert res.maximum == "6"
assert res.minimum == "2"
@pytest.mark.deno
-def test_pot_code_generation_with_one_error():
+def test_pot_code_generation_with_one_error(pooled_interpreter):
lm = DummyLM(
[
{
@@ -112,7 +112,7 @@ def test_pot_code_generation_with_one_error():
)
dspy.configure(lm=lm)
pot = ProgramOfThought(BasicQA)
- res = pot(question="What is 1+1?")
+ res = pot(pooled_interpreter, question="What is 1+1?")
assert res.answer == "2"
diff --git a/tests/predict/test_rlm.py b/tests/predict/test_rlm.py
index 8aeccf985..09c0ef8ac 100644
--- a/tests/predict/test_rlm.py
+++ b/tests/predict/test_rlm.py
@@ -952,64 +952,64 @@ class TestPythonInterpreter:
finally:
interp.shutdown()
- def test_basic_execution(self):
+ def test_basic_execution(self, pooled_interpreter):
"""Test basic code execution."""
- with PythonInterpreter() as interp:
- result = interp.execute("print(1 + 1)")
- assert "2" in result
+ interp = pooled_interpreter
+ result = interp.execute("print(1 + 1)")
+ assert "2" in result
- def test_variable_injection(self):
+ def test_variable_injection(self, pooled_interpreter):
"""Test variable injection."""
- with PythonInterpreter(tools={}) as interp:
- result = interp.execute(
- "print(x + y)",
- variables={"x": 10, "y": 5}
- )
- assert "15" in result
-
- def test_variable_injection_with_none_values(self):
+ interp = pooled_interpreter
+ result = interp.execute(
+ "print(x + y)",
+ variables={"x": 10, "y": 5}
+ )
+ assert "15" in result
+
+ def test_variable_injection_with_none_values(self, pooled_interpreter):
"""Test variable injection with None values in dicts/lists (JSON null -> Python None)."""
- with PythonInterpreter(tools={}) as interp:
- # Test None in dict
- result = interp.execute(
- "print(data['key'] is None)",
- variables={"data": {"key": None, "other": "value"}}
- )
- assert "True" in result
-
- # Test None in list
- result = interp.execute(
- "print(items[1] is None)",
- variables={"items": [1, None, 3]}
- )
- assert "True" in result
-
- # Test nested None
- result = interp.execute(
- "print(nested['inner']['value'] is None)",
- variables={"nested": {"inner": {"value": None}}}
- )
- assert "True" in result
-
- def test_tool_call_kwargs(self):
+ interp = pooled_interpreter
+ # Test None in dict
+ result = interp.execute(
+ "print(data['key'] is None)",
+ variables={"data": {"key": None, "other": "value"}}
+ )
+ assert "True" in result
+
+ # Test None in list
+ result = interp.execute(
+ "print(items[1] is None)",
+ variables={"items": [1, None, 3]}
+ )
+ assert "True" in result
+
+ # Test nested None
+ result = interp.execute(
+ "print(nested['inner']['value'] is None)",
+ variables={"nested": {"inner": {"value": None}}}
+ )
+ assert "True" in result
+
+ def test_tool_call_kwargs(self, configure_pooled_interpreter):
"""Test tool call with keyword arguments."""
def echo(message: str = "") -> str:
return f"Echo: {message}"
- with PythonInterpreter(tools={"echo": echo}) as interp:
- result = interp.execute('print(echo(message="hello"))')
- assert "Echo: hello" in result
+ interp = configure_pooled_interpreter(tools={"echo": echo})
+ result = interp.execute('print(echo(message="hello"))')
+ assert "Echo: hello" in result
- def test_tool_call_positional(self):
+ def test_tool_call_positional(self, configure_pooled_interpreter):
"""Test tool call with positional arguments."""
def greet(name: str) -> str:
return f"Hello: {name}"
- with PythonInterpreter(tools={"greet": greet}) as interp:
- result = interp.execute('print(greet("world"))')
- assert "Hello: world" in result
+ interp = configure_pooled_interpreter(tools={"greet": greet})
+ result = interp.execute('print(greet("world"))')
+ assert "Hello: world" in result
- def test_multiple_tools(self):
+ def test_multiple_tools(self, configure_pooled_interpreter):
"""Test multiple tools."""
def add(a: int = 0, b: int = 0) -> str:
return str(a + b)
@@ -1017,95 +1017,95 @@ class TestPythonInterpreter:
def multiply(a: int = 0, b: int = 0) -> str:
return str(a * b)
- with PythonInterpreter(tools={"add": add, "multiply": multiply}) as interp:
- result = interp.execute("""
+ interp = configure_pooled_interpreter(tools={"add": add, "multiply": multiply})
+ result = interp.execute("""
sum_result = add(a=3, b=4)
prod_result = multiply(a=3, b=4)
print(f"Sum: {sum_result}, Product: {prod_result}")
""")
- assert "Sum: 7" in result
- assert "Product: 12" in result
+ assert "Sum: 7" in result
+ assert "Product: 12" in result
- def test_tool_returns_list(self):
+ def test_tool_returns_list(self, configure_pooled_interpreter):
"""Test tool that returns a list (like llm_query_batched)."""
def batch_process(items: list | None = None) -> list:
items = items or []
return [f"processed_{item}" for item in items]
- with PythonInterpreter(tools={"batch_process": batch_process}) as interp:
- result = interp.execute("""
+ interp = configure_pooled_interpreter(tools={"batch_process": batch_process})
+ result = interp.execute("""
results = batch_process(items=["a", "b", "c"])
print(f"Type: {type(results).__name__}")
print(f"Length: {len(results)}")
print(f"First: {results[0]}")
print(f"All: {results}")
""")
- assert "Type: list" in result
- assert "Length: 3" in result
- assert "First: processed_a" in result
+ assert "Type: list" in result
+ assert "Length: 3" in result
+ assert "First: processed_a" in result
- def test_tool_returns_dict(self):
+ def test_tool_returns_dict(self, configure_pooled_interpreter):
"""Test tool that returns a dict."""
def get_info() -> dict:
return {"name": "test", "count": 42}
- with PythonInterpreter(tools={"get_info": get_info}) as interp:
- result = interp.execute("""
+ interp = configure_pooled_interpreter(tools={"get_info": get_info})
+ result = interp.execute("""
info = get_info()
print(f"Type: {type(info).__name__}")
print(f"Name: {info['name']}")
print(f"Count: {info['count']}")
""")
- assert "Type: dict" in result
- assert "Name: test" in result
- assert "Count: 42" in result
+ assert "Type: dict" in result
+ assert "Name: test" in result
+ assert "Count: 42" in result
- def test_state_persists(self):
+ def test_state_persists(self, pooled_interpreter):
"""Test that state persists across executions."""
- with PythonInterpreter(tools={}) as interp:
- interp.execute("x = 10")
- result = interp.execute("print(x + 5)")
- assert "15" in result
+ interp = pooled_interpreter
+ interp.execute("x = 10")
+ result = interp.execute("print(x + 5)")
+ assert "15" in result
- def test_syntax_error(self):
+ def test_syntax_error(self, pooled_interpreter):
"""Test syntax error handling."""
- with PythonInterpreter(tools={}) as interp:
- with pytest.raises(SyntaxError):
- interp.execute("def incomplete(")
+ interp = pooled_interpreter
+ with pytest.raises(SyntaxError):
+ interp.execute("def incomplete(")
- def test_runtime_error(self):
+ def test_runtime_error(self, pooled_interpreter):
"""Test runtime error handling."""
- with PythonInterpreter(tools={}) as interp:
- with pytest.raises(CodeExecutionError):
- interp.execute("undefined_variable")
+ interp = pooled_interpreter
+ with pytest.raises(CodeExecutionError):
+ interp.execute("undefined_variable")
@pytest.mark.deno
class TestSandboxSecurity:
"""Integration tests for sandbox security restrictions."""
- def test_no_network_access(self):
+ def test_no_network_access(self, pooled_interpreter):
"""Test that network access is blocked."""
- with PythonInterpreter(tools={}) as interp:
- with pytest.raises(CodeInterpreterError) as exc_info:
- interp.execute("""
+ interp = pooled_interpreter
+ with pytest.raises(CodeInterpreterError) as exc_info:
+ interp.execute("""
from pyodide.http import pyfetch
import asyncio
asyncio.get_event_loop().run_until_complete(pyfetch("https://example.com"))
""")
- assert "net access" in str(exc_info.value).lower() or "allow-net" in str(exc_info.value).lower()
+ assert "net access" in str(exc_info.value).lower() or "allow-net" in str(exc_info.value).lower()
- def test_imports_work(self):
+ def test_imports_work(self, pooled_interpreter):
"""Test that standard library imports work."""
- with PythonInterpreter(tools={}) as interp:
- result = interp.execute("""
+ interp = pooled_interpreter
+ result = interp.execute("""
import json
import re
from collections import Counter
data = {"key": "value"}
print(json.dumps(data))
""")
- assert "key" in result
+ assert "key" in result
# ============================================================================
@@ -1229,25 +1229,25 @@ class TestRLMTypeCoercion:
("data", "dict[str, str]", 'SUBMIT({"key": "value"})', {"key": "value"}, dict),
("answer", "Literal['yes', 'no']", 'SUBMIT("yes")', "yes", str),
])
- def test_type_coercion(self, output_field, output_type, code, expected, expected_type):
+ def test_type_coercion(self, output_field, output_type, code, expected, expected_type, pooled_interpreter):
"""Test RLM type coercion for various types with PythonInterpreter."""
rlm = RLM(f"query -> {output_field}: {output_type}", max_iters=3)
rlm.generate_action = make_mock_predictor([
{"reasoning": "Return value", "code": code},
])
- result = rlm.forward(query="test")
+ result = rlm.forward(pooled_interpreter, query="test")
assert getattr(result, output_field) == expected
assert isinstance(getattr(result, output_field), expected_type)
- def test_submit_extracts_typed_value(self):
+ def test_submit_extracts_typed_value(self, pooled_interpreter):
"""Test RLM SUBMIT correctly extracts typed value."""
rlm = RLM("query -> count: int", max_iters=3)
rlm.generate_action = make_mock_predictor([
{"reasoning": "Compute and return", "code": "result = 42\nSUBMIT(result)"},
])
- result = rlm.forward(query="count items")
+ result = rlm.forward(pooled_interpreter, query="count items")
assert result.count == 42
assert isinstance(result.count, int)
@@ -1264,42 +1264,42 @@ class TestRLMMultipleOutputs:
Tests SUBMIT() calling patterns with multi-output signatures.
"""
- def test_multi_output_final_kwargs(self):
+ def test_multi_output_final_kwargs(self, pooled_interpreter):
"""SUBMIT(field1=val1, field2=val2) with keyword args."""
rlm = RLM("query -> name: str, count: int", max_iters=3)
rlm.generate_action = make_mock_predictor([
{"reasoning": "Return both outputs", "code": 'SUBMIT(name="alice", count=5)'},
])
- result = rlm.forward(query="test")
+ result = rlm.forward(pooled_interpreter, query="test")
assert result.name == "alice"
assert result.count == 5
assert isinstance(result.count, int)
- def test_multi_output_final_positional(self):
+ def test_multi_output_final_positional(self, pooled_interpreter):
"""SUBMIT(val1, val2) with positional args mapped to field order."""
rlm = RLM("query -> name: str, count: int", max_iters=3)
rlm.generate_action = make_mock_predictor([
{"reasoning": "Return both outputs positionally", "code": 'SUBMIT("bob", 10)'},
])
- result = rlm.forward(query="test")
+ result = rlm.forward(pooled_interpreter, query="test")
assert result.name == "bob"
assert result.count == 10
- def test_multi_output_three_fields(self):
+ def test_multi_output_three_fields(self, pooled_interpreter):
"""Signature with 3+ output fields of different types."""
rlm = RLM("query -> name: str, age: int, active: bool", max_iters=3)
rlm.generate_action = make_mock_predictor([
{"reasoning": "Return all three", "code": 'SUBMIT(name="carol", age=30, active=True)'},
])
- result = rlm.forward(query="test")
+ result = rlm.forward(pooled_interpreter, query="test")
assert result.name == "carol"
assert result.age == 30
assert result.active is True
- def test_multi_output_final_missing_field_errors(self):
+ def test_multi_output_final_missing_field_errors(self, pooled_interpreter):
"""SUBMIT() with missing field should return error in output."""
rlm = RLM("query -> name: str, count: int", max_iters=3)
rlm.generate_action = make_mock_predictor([
@@ -1308,29 +1308,29 @@ class TestRLMMultipleOutputs:
])
# RLM should retry after getting error for missing field
- result = rlm.forward(query="test")
+ result = rlm.forward(pooled_interpreter, query="test")
assert result.name == "alice"
assert result.count == 5
- def test_multi_output_submit_vars(self):
+ def test_multi_output_submit_vars(self, pooled_interpreter):
"""SUBMIT can pass variables directly for multiple outputs."""
rlm = RLM("query -> name: str, count: int", max_iters=3)
rlm.generate_action = make_mock_predictor([
{"reasoning": "Use SUBMIT", "code": 'n = "dave"\nc = 15\nSUBMIT(n, c)'},
])
- result = rlm.forward(query="test")
+ result = rlm.forward(pooled_interpreter, query="test")
assert result.name == "dave"
assert result.count == 15
- def test_multi_output_type_coercion(self):
+ def test_multi_output_type_coercion(self, pooled_interpreter):
"""Each output field is coerced to its declared type."""
rlm = RLM("query -> count: int, ratio: float, flag: bool", max_iters=3)
rlm.generate_action = make_mock_predictor([
{"reasoning": "Return mixed types", "code": "SUBMIT(count=42, ratio=3.14, flag=True)"},
])
- result = rlm.forward(query="test")
+ result = rlm.forward(pooled_interpreter, query="test")
assert result.count == 42
assert isinstance(result.count, int)
assert result.ratio == 3.14
@@ -1352,40 +1352,40 @@ class TestRLMWithDummyLM:
typed output_fields for SUBMIT based on the signature.
"""
- def test_simple_computation_e2e(self):
+ def test_simple_computation_e2e(self, pooled_interpreter):
"""Test full RLM pipeline: DummyLM -> RLM -> PythonInterpreter -> result."""
with dummy_lm_context([
{"reasoning": "I need to compute 2 + 3", "code": "result = 2 + 3\nSUBMIT(result)"},
]):
rlm = RLM("query -> answer: int", max_iters=3)
- result = rlm.forward(query="What is 2 + 3?")
+ result = rlm.forward(pooled_interpreter, query="What is 2 + 3?")
assert result.answer == 5
assert isinstance(result.answer, int)
- def test_multi_turn_computation_e2e(self):
+ def test_multi_turn_computation_e2e(self, pooled_interpreter):
"""Test RLM with multiple turns before SUBMIT."""
with dummy_lm_context([
{"reasoning": "First explore the data", "code": "x = 10\nprint(f'x = {x}')"},
{"reasoning": "Now compute and return", "code": "y = x * 2\nSUBMIT(y)"},
]):
rlm = RLM("query -> answer: int", max_iters=5)
- result = rlm.forward(query="Double ten")
+ result = rlm.forward(pooled_interpreter, query="Double ten")
assert result.answer == 20
assert len(result.trajectory) == 2
- def test_with_input_variables_e2e(self):
+ def test_with_input_variables_e2e(self, pooled_interpreter):
"""Test RLM with input variables passed to sandbox."""
with dummy_lm_context([
{"reasoning": "Sum the numbers in the list", "code": "SUBMIT(sum(numbers))"},
]):
rlm = RLM("numbers: list[int] -> total: int", max_iters=3)
- result = rlm.forward(numbers=[1, 2, 3, 4, 5])
+ result = rlm.forward(pooled_interpreter, numbers=[1, 2, 3, 4, 5])
assert result.total == 15
- def test_with_tool_e2e(self):
+ def test_with_tool_e2e(self, pooled_interpreter):
"""Test RLM calling a host-side tool through the sandbox."""
def lookup(key: str) -> str:
return {"apple": "red", "banana": "yellow"}.get(key, "unknown")
@@ -1394,11 +1394,11 @@ class TestRLMWithDummyLM:
{"reasoning": "Look up the color of apple", "code": 'color = lookup(key="apple")\nSUBMIT(color)'},
]):
rlm = RLM("fruit -> color: str", max_iters=3, tools=[lookup])
- result = rlm.forward(fruit="apple")
+ result = rlm.forward(pooled_interpreter, fruit="apple")
assert result.color == "red"
- def test_dspy_tool_execution_semantics_e2e(self):
+ def test_dspy_tool_execution_semantics_e2e(self, pooled_interpreter):
import inspect
from pydantic import BaseModel
@@ -1437,7 +1437,7 @@ class TestRLMWithDummyLM:
},
]):
with dspy.context(callbacks=[Recorder()]):
- result = rlm.forward(query="test")
+ result = rlm.forward(pooled_interpreter, query="test")
assert result.answer == 6
assert len(received) == 1
@@ -1692,7 +1692,7 @@ class TestPrepareSerializableVars:
class TestLargeSerializableRoundTrip:
"""End-to-end test that large SandboxSerializable payloads survive the sandbox."""
- def test_large_payload_round_trips_through_real_sandbox(self):
+ def test_large_payload_round_trips_through_real_sandbox(self, pooled_interpreter):
"""A multi-MB payload should be reconstructable inside the real interpreter."""
large_text = "abc123" * (200 * 1024) # ~1.2 MB UTF-8
@@ -1709,11 +1709,11 @@ class TestLargeSerializableRoundTrip:
def rlm_preview(self, max_chars: int = 500) -> str:
return f"LargeText({len(large_text)} chars)"
- with PythonInterpreter(tools={}) as interp:
- rlm = RLM("data -> answer")
- rlm._inject_execution_context(interp, rlm._prepare_execution_tools())
- rlm._prepare_serializable_vars({"data": _LargeText()}, interp)
- result = interp.execute("print(len(data)); print(data[:6])")
+ interp = pooled_interpreter
+ rlm = RLM("data -> answer")
+ rlm._inject_execution_context(interp, rlm._prepare_execution_tools())
+ rlm._prepare_serializable_vars({"data": _LargeText()}, interp)
+ result = interp.execute("print(len(data)); print(data[:6])")
assert str(len(large_text)) in result
assert "abc123" in result
diff --git a/tests/primitives/test_python_interpreter.py b/tests/primitives/test_python_interpreter.py
index 5f170dde5..90a3a53fe 100644
--- a/tests/primitives/test_python_interpreter.py
+++ b/tests/primitives/test_python_interpreter.py
@@ -35,98 +35,98 @@ class _UnserializableModel(BaseModel):
pytestmark = pytest.mark.deno
-def test_execute_simple_code():
- with PythonInterpreter() as interpreter:
- code = "print('Hello, World!')"
- result = interpreter.execute(code)
- assert result == "Hello, World!\n", "Simple print statement should return 'Hello World!\n'"
+def test_execute_simple_code(pooled_interpreter):
+ interpreter = pooled_interpreter
+ code = "print('Hello, World!')"
+ result = interpreter.execute(code)
+ assert result == "Hello, World!\n", "Simple print statement should return 'Hello World!\n'"
-def test_import():
- with PythonInterpreter() as interpreter:
- code = "import math\nresult = math.sqrt(4)\nresult"
- result = interpreter.execute(code)
- assert result == 2, "Should be able to import and use math.sqrt"
+def test_import(pooled_interpreter):
+ interpreter = pooled_interpreter
+ code = "import math\nresult = math.sqrt(4)\nresult"
+ result = interpreter.execute(code)
+ assert result == 2, "Should be able to import and use math.sqrt"
-def test_user_variable_definitions():
- with PythonInterpreter() as interpreter:
- code = "result = number + 1\nresult"
- result = interpreter.execute(code, variables={"number": 4})
- assert result == 5, "User variable assignment should work"
+def test_user_variable_definitions(pooled_interpreter):
+ interpreter = pooled_interpreter
+ code = "result = number + 1\nresult"
+ result = interpreter.execute(code, variables={"number": 4})
+ assert result == 5, "User variable assignment should work"
-def test_non_finite_float_variables():
+def test_non_finite_float_variables(pooled_interpreter):
"""Regression test: inf/-inf/nan variables must be injected as valid Python literals.
str(float("inf")) is the bare word "inf", which is not a valid Python name, so
injecting it as `x = inf` previously raised NameError in the sandbox.
"""
- with PythonInterpreter() as interpreter:
- inf_code = "result = 1 if x == float('inf') else 0\nresult"
- assert interpreter.execute(inf_code, variables={"x": float("inf")}) == 1
+ interpreter = pooled_interpreter
+ inf_code = "result = 1 if x == float('inf') else 0\nresult"
+ assert interpreter.execute(inf_code, variables={"x": float("inf")}) == 1
- neg_inf_code = "result = 1 if x == float('-inf') else 0\nresult"
- assert interpreter.execute(neg_inf_code, variables={"x": float("-inf")}) == 1
+ neg_inf_code = "result = 1 if x == float('-inf') else 0\nresult"
+ assert interpreter.execute(neg_inf_code, variables={"x": float("-inf")}) == 1
- nan_code = "import math\nresult = 1 if math.isnan(x) else 0\nresult"
- assert interpreter.execute(nan_code, variables={"x": float("nan")}) == 1
+ nan_code = "import math\nresult = 1 if math.isnan(x) else 0\nresult"
+ assert interpreter.execute(nan_code, variables={"x": float("nan")}) == 1
-def test_rejects_python_keywords_as_variable_names():
+def test_rejects_python_keywords_as_variable_names(pooled_interpreter):
"""Test that Python keywords are rejected as variable names."""
- with PythonInterpreter() as interpreter:
- # These are valid Python identifiers but reserved keywords
- # Using them as variable names would cause syntax errors
- keywords_to_test = ["for", "class", "import", "def", "return", "if", "while"]
+ interpreter = pooled_interpreter
+ # These are valid Python identifiers but reserved keywords
+ # Using them as variable names would cause syntax errors
+ keywords_to_test = ["for", "class", "import", "def", "return", "if", "while"]
- for keyword in keywords_to_test:
- with pytest.raises(CodeInterpreterError, match="Invalid variable name"):
- interpreter.execute("print(x)", variables={keyword: 42})
+ for keyword in keywords_to_test:
+ with pytest.raises(CodeInterpreterError, match="Invalid variable name"):
+ interpreter.execute("print(x)", variables={keyword: 42})
-def test_failure_syntax_error():
- with PythonInterpreter() as interpreter:
- code = "+++"
- with pytest.raises(SyntaxError, match="Invalid Python syntax"):
- interpreter.execute(code)
+def test_failure_syntax_error(pooled_interpreter):
+ interpreter = pooled_interpreter
+ code = "+++"
+ with pytest.raises(SyntaxError, match="Invalid Python syntax"):
+ interpreter.execute(code)
-def test_failure_zero_division():
- with PythonInterpreter() as interpreter:
- code = "1+0/0"
- with pytest.raises(CodeExecutionError, match="ZeroDivisionError"):
- interpreter.execute(code)
+def test_failure_zero_division(pooled_interpreter):
+ interpreter = pooled_interpreter
+ code = "1+0/0"
+ with pytest.raises(CodeExecutionError, match="ZeroDivisionError"):
+ interpreter.execute(code)
-def test_exception_args():
- with PythonInterpreter() as interpreter:
- token = random.randint(1, 10**9)
- code = f"raise ValueError({token})"
- with pytest.raises(CodeExecutionError, match=rf"ValueError: \[{token}\]"):
- interpreter.execute(code)
+def test_exception_args(pooled_interpreter):
+ interpreter = pooled_interpreter
+ token = random.randint(1, 10**9)
+ code = f"raise ValueError({token})"
+ with pytest.raises(CodeExecutionError, match=rf"ValueError: \[{token}\]"):
+ interpreter.execute(code)
-def test_generated_exception_name_cannot_spoof_interpreter_failure():
- with PythonInterpreter() as interpreter:
- with pytest.raises(CodeExecutionError, match="CodeInterpreterError"):
- interpreter.execute(
- "class CodeInterpreterError(Exception):\n pass\nraise CodeInterpreterError('generated failure')"
- )
- assert interpreter.execute("2 + 2") == 4
+def test_generated_exception_name_cannot_spoof_interpreter_failure(pooled_interpreter):
+ interpreter = pooled_interpreter
+ with pytest.raises(CodeExecutionError, match="CodeInterpreterError"):
+ interpreter.execute(
+ "class CodeInterpreterError(Exception):\n pass\nraise CodeInterpreterError('generated failure')"
+ )
+ assert interpreter.execute("2 + 2") == 4
-def test_submit_with_list():
+def test_submit_with_list(pooled_interpreter):
"""Test SUBMIT() with a list argument returns FinalOutput with dict format."""
- with PythonInterpreter() as interpreter:
- token = random.randint(1, 10**9)
- code = f"SUBMIT(['The result is', {token}])"
- result = interpreter(code)
+ interpreter = pooled_interpreter
+ token = random.randint(1, 10**9)
+ code = f"SUBMIT(['The result is', {token}])"
+ result = interpreter(code)
- assert isinstance(result, FinalOutput)
- # SUBMIT now always returns a dict with "output" key for single-output default
- assert result.output == {"output": ["The result is", token]}
+ assert isinstance(result, FinalOutput)
+ # SUBMIT now always returns a dict with "output" key for single-output default
+ assert result.output == {"output": ["The result is", token]}
def test_enable_env_vars_flag():
@@ -264,58 +264,58 @@ def test_tools_dict_is_copied():
assert "new_tool" not in sandbox.tools
-def test_serialize_tuple():
+def test_serialize_tuple(pooled_interpreter):
"""Test that tuples can be serialized as variables."""
- with PythonInterpreter() as interpreter:
- result = interpreter.execute("x", variables={"x": (1, 2, 3)})
- assert result == [1, 2, 3] # Tuples become lists in JSON
+ interpreter = pooled_interpreter
+ result = interpreter.execute("x", variables={"x": (1, 2, 3)})
+ assert result == [1, 2, 3] # Tuples become lists in JSON
-def test_serialize_set():
+def test_serialize_set(pooled_interpreter):
"""Test that sets can be serialized as variables."""
- with PythonInterpreter() as interpreter:
- result = interpreter.execute("sorted(x)", variables={"x": {3, 1, 2}})
- assert result == [1, 2, 3]
+ interpreter = pooled_interpreter
+ result = interpreter.execute("sorted(x)", variables={"x": {3, 1, 2}})
+ assert result == [1, 2, 3]
-def test_serialize_set_mixed_types():
+def test_serialize_set_mixed_types(pooled_interpreter):
"""Test that sets with mixed types can be serialized (fallback to list)."""
- with PythonInterpreter() as interpreter:
- # Mixed types can't be sorted, so they serialize as a list in arbitrary order
- # We verify the list contains the expected elements
- result = interpreter.execute("x", variables={"x": {1, "a"}})
- assert isinstance(result, list)
- assert set(result) == {1, "a"}
+ interpreter = pooled_interpreter
+ # Mixed types can't be sorted, so they serialize as a list in arbitrary order
+ # We verify the list contains the expected elements
+ result = interpreter.execute("x", variables={"x": {1, "a"}})
+ assert isinstance(result, list)
+ assert set(result) == {1, "a"}
-def test_serialize_pydantic_variable():
+def test_serialize_pydantic_variable(pooled_interpreter):
"""Pydantic instances passed via variables= should arrive in the sandbox as dicts."""
- with PythonInterpreter() as interpreter:
- result = interpreter.execute(
- "hit['document_id']",
- variables={"hit": _Hit(document_id=7, title="abc")},
- )
- assert result == 7
+ interpreter = pooled_interpreter
+ result = interpreter.execute(
+ "hit['document_id']",
+ variables={"hit": _Hit(document_id=7, title="abc")},
+ )
+ assert result == 7
-def test_serialize_pydantic_nested_in_dict():
+def test_serialize_pydantic_nested_in_dict(pooled_interpreter):
"""Pydantic instances nested inside list/dict variables should be coerced too."""
- with PythonInterpreter() as interpreter:
- result = interpreter.execute(
- "(data['hit']['document_id'], data['hit']['title'])",
- variables={"data": {"hit": _Hit(document_id=11, title="nested")}},
- )
- assert result == [11, "nested"]
+ interpreter = pooled_interpreter
+ result = interpreter.execute(
+ "(data['hit']['document_id'], data['hit']['title'])",
+ variables={"data": {"hit": _Hit(document_id=11, title="nested")}},
+ )
+ assert result == [11, "nested"]
-def test_serialize_pydantic_in_list_variable():
+def test_serialize_pydantic_in_list_variable(pooled_interpreter):
"""A list variable whose elements are Pydantic instances should be coerced too."""
- with PythonInterpreter() as interpreter:
- result = interpreter.execute(
- "sum(h['document_id'] for h in hits)",
- variables={"hits": [_Hit(document_id=1, title="a"), _Hit(document_id=2, title="b")]},
- )
- assert result == 3
+ interpreter = pooled_interpreter
+ result = interpreter.execute(
+ "sum(h['document_id'] for h in hits)",
+ variables={"hits": [_Hit(document_id=1, title="a"), _Hit(document_id=2, title="b")]},
+ )
+ assert result == 3
def test_pydantic_json_values_are_compatible_with_large_variable_injection(monkeypatch):
@@ -363,54 +363,54 @@ def test_deno_command_dict_raises_type_error():
# =============================================================================
-def test_tool_with_typed_signature():
+def test_tool_with_typed_signature(configure_pooled_interpreter):
"""Test that tools get proper typed signatures from inspect."""
def my_tool(query: str, limit: int = 10) -> str:
return f"searched '{query}' with limit {limit}"
- with PythonInterpreter(tools={"my_tool": my_tool}) as sandbox:
- # Tool should be callable with typed signature
- result = sandbox.execute('my_tool(query="test", limit=5)')
- assert result == "searched 'test' with limit 5"
+ sandbox = configure_pooled_interpreter(tools={"my_tool": my_tool})
+ # Tool should be callable with typed signature
+ result = sandbox.execute('my_tool(query="test", limit=5)')
+ assert result == "searched 'test' with limit 5"
-def test_tool_positional_args():
+def test_tool_positional_args(configure_pooled_interpreter):
"""Test that tools work with positional arguments."""
def search(query: str, limit: int = 10) -> str:
return f"query={query}, limit={limit}"
- with PythonInterpreter(tools={"search": search}) as sandbox:
- result = sandbox.execute('search("hello")')
- assert result == "query=hello, limit=10"
+ sandbox = configure_pooled_interpreter(tools={"search": search})
+ result = sandbox.execute('search("hello")')
+ assert result == "query=hello, limit=10"
-def test_tool_keyword_args():
+def test_tool_keyword_args(configure_pooled_interpreter):
"""Test that tools work with keyword arguments."""
def search(query: str, limit: int = 10) -> str:
return f"query={query}, limit={limit}"
- with PythonInterpreter(tools={"search": search}) as sandbox:
- result = sandbox.execute('search(query="hello", limit=5)')
- assert result == "query=hello, limit=5"
+ sandbox = configure_pooled_interpreter(tools={"search": search})
+ result = sandbox.execute('search(query="hello", limit=5)')
+ assert result == "query=hello, limit=5"
-def test_tool_default_args():
+def test_tool_default_args(configure_pooled_interpreter):
"""Test that tool default arguments work correctly."""
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
- with PythonInterpreter(tools={"greet": greet}) as sandbox:
- # Without default
- result = sandbox.execute('greet("World")')
- assert result == "Hello, World!"
+ sandbox = configure_pooled_interpreter(tools={"greet": greet})
+ # Without default
+ result = sandbox.execute('greet("World")')
+ assert result == "Hello, World!"
- # Overriding default
- result = sandbox.execute('greet("World", "Hi")')
- assert result == "Hi, World!"
+ # Overriding default
+ result = sandbox.execute('greet("World", "Hi")')
+ assert result == "Hi, World!"
def test_process_death_ends_stateful_session():
@@ -484,70 +484,70 @@ def test_shutdown_ends_session():
interpreter.execute("1 + 1")
-def test_tool_all_positional_args():
+def test_tool_all_positional_args(configure_pooled_interpreter):
"""Test that tools work when all arguments are passed positionally."""
def add(a: int, b: int, c: int) -> str:
return f"{a + b + c}"
- with PythonInterpreter(tools={"add": add}) as sandbox:
- result = sandbox.execute("add(1, 2, 3)")
- assert result == "6"
+ sandbox = configure_pooled_interpreter(tools={"add": add})
+ result = sandbox.execute("add(1, 2, 3)")
+ assert result == "6"
- # Mixed: some positional, some keyword
- result = sandbox.execute("add(10, 20, c=30)")
- assert result == "60"
+ # Mixed: some positional, some keyword
+ result = sandbox.execute("add(10, 20, c=30)")
+ assert result == "60"
-def test_tool_error_surfaces_as_runtime_error():
+def test_tool_error_surfaces_as_runtime_error(configure_pooled_interpreter):
"""Test that exceptions raised by a tool surface as RuntimeError in the sandbox."""
def failing_tool(x: int) -> str:
raise ValueError(f"bad value: {x}")
- with PythonInterpreter(tools={"failing_tool": failing_tool}) as sandbox:
- result = sandbox.execute(
- "try:\n"
- " failing_tool(42)\n"
- " output = 'no error'\n"
- "except RuntimeError as e:\n"
- " output = str(e)\n"
- "output"
- )
- assert "ValueError" in result
- assert "bad value: 42" in result
+ sandbox = configure_pooled_interpreter(tools={"failing_tool": failing_tool})
+ result = sandbox.execute(
+ "try:\n"
+ " failing_tool(42)\n"
+ " output = 'no error'\n"
+ "except RuntimeError as e:\n"
+ " output = str(e)\n"
+ "output"
+ )
+ assert "ValueError" in result
+ assert "bad value: 42" in result
-def test_tool_async_def_function():
+def test_tool_async_def_function(configure_pooled_interpreter):
"""async def tools should be awaited so the sandbox sees the resolved value."""
async def slow_search(query: str) -> str:
await asyncio.sleep(0)
return f"answer:{query}"
- with PythonInterpreter(tools={"slow_search": slow_search}) as sandbox:
- result = sandbox.execute("slow_search(query='hello')")
- assert result == "answer:hello"
+ sandbox = configure_pooled_interpreter(tools={"slow_search": slow_search})
+ result = sandbox.execute("slow_search(query='hello')")
+ assert result == "answer:hello"
-def test_tool_async_def_raises_propagates():
+def test_tool_async_def_raises_propagates(configure_pooled_interpreter):
"""Exceptions raised inside an async tool should surface as RuntimeError in the sandbox."""
async def failing_async(x: int) -> str:
await asyncio.sleep(0)
raise ValueError(f"boom:{x}")
- with PythonInterpreter(tools={"failing_async": failing_async}) as sandbox:
- result = sandbox.execute(
- "try:\n"
- " failing_async(7)\n"
- " output = 'no error'\n"
- "except RuntimeError as e:\n"
- " output = str(e)\n"
- "output"
- )
- assert "ValueError" in result
- assert "boom:7" in result
+ sandbox = configure_pooled_interpreter(tools={"failing_async": failing_async})
+ result = sandbox.execute(
+ "try:\n"
+ " failing_async(7)\n"
+ " output = 'no error'\n"
+ "except RuntimeError as e:\n"
+ " output = str(e)\n"
+ "output"
+ )
+ assert "ValueError" in result
+ assert "boom:7" in result
# =============================================================================
@@ -555,55 +555,55 @@ def test_tool_async_def_raises_propagates():
# =============================================================================
-def test_tool_returning_int():
+def test_tool_returning_int(configure_pooled_interpreter):
"""Test that tools returning int preserve the type in the sandbox."""
def count_items(label: str) -> int:
return 4
- with PythonInterpreter(tools={"count_items": count_items}) as sandbox:
- result = sandbox.execute(
- 'n = count_items(label="pages")\n'
- 'print(type(n).__name__)\n'
- 'print(n + 1)'
- )
- assert "int" in result
- assert "5" in result
+ sandbox = configure_pooled_interpreter(tools={"count_items": count_items})
+ result = sandbox.execute(
+ 'n = count_items(label="pages")\n'
+ 'print(type(n).__name__)\n'
+ 'print(n + 1)'
+ )
+ assert "int" in result
+ assert "5" in result
-def test_tool_returning_float():
+def test_tool_returning_float(configure_pooled_interpreter):
"""Test that tools returning float preserve the type in the sandbox."""
def get_score() -> float:
return 0.95
- with PythonInterpreter(tools={"get_score": get_score}) as sandbox:
- result = sandbox.execute(
- "x = get_score()\n"
- "print(type(x).__name__)\n"
- "print(x * 2)"
- )
- assert "float" in result
- assert "1.9" in result
+ sandbox = configure_pooled_interpreter(tools={"get_score": get_score})
+ result = sandbox.execute(
+ "x = get_score()\n"
+ "print(type(x).__name__)\n"
+ "print(x * 2)"
+ )
+ assert "float" in result
+ assert "1.9" in result
-def test_tool_returning_bool():
+def test_tool_returning_bool(configure_pooled_interpreter):
"""Test that tools returning bool preserve the type in the sandbox."""
def is_valid() -> bool:
return True
- with PythonInterpreter(tools={"is_valid": is_valid}) as sandbox:
- result = sandbox.execute(
- 'v = is_valid()\n'
- 'print(type(v).__name__)\n'
- 'print(v and "yes")'
- )
- assert "bool" in result
- assert "yes" in result
+ sandbox = configure_pooled_interpreter(tools={"is_valid": is_valid})
+ result = sandbox.execute(
+ 'v = is_valid()\n'
+ 'print(type(v).__name__)\n'
+ 'print(v and "yes")'
+ )
+ assert "bool" in result
+ assert "yes" in result
-def test_tool_returning_none():
+def test_tool_returning_none(configure_pooled_interpreter):
"""Test that tools returning None yield an empty string in the sandbox.
Pyodide does not map JS null to Python None (it becomes JsNull), so
@@ -613,49 +613,49 @@ def test_tool_returning_none():
def do_nothing() -> None:
return None
- with PythonInterpreter(tools={"do_nothing": do_nothing}) as sandbox:
- result = sandbox.execute(
- "v = do_nothing()\n"
- "print(type(v).__name__)\n"
- "print(repr(v))"
- )
- assert "str" in result
- assert "''" in result
+ sandbox = configure_pooled_interpreter(tools={"do_nothing": do_nothing})
+ result = sandbox.execute(
+ "v = do_nothing()\n"
+ "print(type(v).__name__)\n"
+ "print(repr(v))"
+ )
+ assert "str" in result
+ assert "''" in result
-def test_tool_returning_list():
+def test_tool_returning_list(configure_pooled_interpreter):
"""Test that tools returning list preserve the type in the sandbox."""
def get_pages() -> list:
return [1, 2, 3]
- with PythonInterpreter(tools={"get_pages": get_pages}) as sandbox:
- result = sandbox.execute(
- "pages = get_pages()\n"
- "print(type(pages).__name__)\n"
- "print(pages[0] + 10)"
- )
- assert "list" in result
- assert "11" in result
+ sandbox = configure_pooled_interpreter(tools={"get_pages": get_pages})
+ result = sandbox.execute(
+ "pages = get_pages()\n"
+ "print(type(pages).__name__)\n"
+ "print(pages[0] + 10)"
+ )
+ assert "list" in result
+ assert "11" in result
-def test_tool_returning_dict():
+def test_tool_returning_dict(configure_pooled_interpreter):
"""Test that tools returning dict preserve the type in the sandbox."""
def get_info() -> dict:
return {"count": 4, "label": "pages"}
- with PythonInterpreter(tools={"get_info": get_info}) as sandbox:
- result = sandbox.execute(
- 'info = get_info()\n'
- 'print(type(info).__name__)\n'
- 'print(info["count"] + 1)'
- )
- assert "dict" in result
- assert "5" in result
+ sandbox = configure_pooled_interpreter(tools={"get_info": get_info})
+ result = sandbox.execute(
+ 'info = get_info()\n'
+ 'print(type(info).__name__)\n'
+ 'print(info["count"] + 1)'
+ )
+ assert "dict" in result
+ assert "5" in result
-def test_tool_returning_non_json_serializable():
+def test_tool_returning_non_json_serializable(configure_pooled_interpreter):
"""Test that tools returning non-JSON-serializable objects fall back to string."""
class Custom:
@@ -665,15 +665,15 @@ def test_tool_returning_non_json_serializable():
def get_custom() -> object:
return Custom()
- with PythonInterpreter(tools={"get_custom": get_custom}) as sandbox:
- result = sandbox.execute(
- "v = get_custom()\n"
- "print(v)"
- )
- assert "custom-object" in result
+ sandbox = configure_pooled_interpreter(tools={"get_custom": get_custom})
+ result = sandbox.execute(
+ "v = get_custom()\n"
+ "print(v)"
+ )
+ assert "custom-object" in result
-def test_tool_returning_nan_falls_back_to_string():
+def test_tool_returning_nan_falls_back_to_string(configure_pooled_interpreter):
"""Test that tools returning float('nan') or float('inf') fall back to string.
These values are not valid JSON, so they should go through the str()
@@ -686,25 +686,25 @@ def test_tool_returning_nan_falls_back_to_string():
def get_inf() -> float:
return float("inf")
- with PythonInterpreter(tools={"get_nan": get_nan, "get_inf": get_inf}) as sandbox:
- result = sandbox.execute(
- "n = get_nan()\n"
- "print(type(n).__name__)\n"
- "print(n)"
- )
- assert "str" in result
- assert "nan" in result
+ sandbox = configure_pooled_interpreter(tools={"get_nan": get_nan, "get_inf": get_inf})
+ result = sandbox.execute(
+ "n = get_nan()\n"
+ "print(type(n).__name__)\n"
+ "print(n)"
+ )
+ assert "str" in result
+ assert "nan" in result
- result = sandbox.execute(
- "i = get_inf()\n"
- "print(type(i).__name__)\n"
- "print(i)"
- )
- assert "str" in result
- assert "inf" in result
+ result = sandbox.execute(
+ "i = get_inf()\n"
+ "print(type(i).__name__)\n"
+ "print(i)"
+ )
+ assert "str" in result
+ assert "inf" in result
-def test_tool_returns_pydantic_model():
+def test_tool_returns_pydantic_model(configure_pooled_interpreter):
"""Pydantic models returned from a tool should arrive in the sandbox as dicts."""
def search() -> _TimestampedHit:
@@ -714,36 +714,36 @@ def test_tool_returns_pydantic_model():
created_at=datetime(2026, 5, 14, 8, 7, 27),
)
- with PythonInterpreter(tools={"search": search}) as sandbox:
- result = sandbox.execute("r = search()\n(r['document_id'], r['title'], r['created_at'])")
- assert result == [42, "example", "2026-05-14T08:07:27"]
+ sandbox = configure_pooled_interpreter(tools={"search": search})
+ result = sandbox.execute("r = search()\n(r['document_id'], r['title'], r['created_at'])")
+ assert result == [42, "example", "2026-05-14T08:07:27"]
-def test_tool_returns_list_of_pydantic_models():
+def test_tool_returns_list_of_pydantic_models(configure_pooled_interpreter):
"""Lists of Pydantic models from a tool should round-trip as lists of dicts."""
def search_many() -> list[_Hit]:
return [_Hit(document_id=1, title="a"), _Hit(document_id=2, title="b")]
- with PythonInterpreter(tools={"search_many": search_many}) as sandbox:
- result = sandbox.execute(
- "hits = search_many()\nsum(h['document_id'] for h in hits)"
- )
- assert result == 3
+ sandbox = configure_pooled_interpreter(tools={"search_many": search_many})
+ result = sandbox.execute(
+ "hits = search_many()\nsum(h['document_id'] for h in hits)"
+ )
+ assert result == 3
-def test_tool_returning_unserializable_pydantic_model_raises_execution_error():
+def test_tool_returning_unserializable_pydantic_model_raises_execution_error(configure_pooled_interpreter):
"""A BaseModel that cannot honor JSON transport should remain a visible tool error."""
def get_value() -> _UnserializableModel:
return _UnserializableModel(value=_UnserializableValue())
- with PythonInterpreter(tools={"get_value": get_value}) as sandbox:
- with pytest.raises(
- CodeExecutionError,
- match="CodeInterpreterError.*Unable to serialize _UnserializableModel as JSON",
- ):
- sandbox.execute("get_value()")
+ sandbox = configure_pooled_interpreter(tools={"get_value": get_value})
+ with pytest.raises(
+ CodeExecutionError,
+ match="CodeInterpreterError.*Unable to serialize _UnserializableModel as JSON",
+ ):
+ sandbox.execute("get_value()")
# -- dataclass tool returns --------------------------------------------------
@@ -764,29 +764,29 @@ class _PageTable:
strategy: str
-def test_tool_returns_dataclass():
+def test_tool_returns_dataclass(configure_pooled_interpreter):
"""Dataclass instances returned from a tool should arrive as dicts."""
def get_bbox() -> _BBox:
return _BBox(x0=18.2, top=108.0, x1=554.4, bottom=748.8)
- with PythonInterpreter(tools={"get_bbox": get_bbox}) as sandbox:
- result = sandbox.execute("b = get_bbox()\n(b['x0'], b['bottom'])")
- assert result == [18.2, 748.8]
+ sandbox = configure_pooled_interpreter(tools={"get_bbox": get_bbox})
+ result = sandbox.execute("b = get_bbox()\n(b['x0'], b['bottom'])")
+ assert result == [18.2, 748.8]
-def test_tool_returns_nested_dataclass():
+def test_tool_returns_nested_dataclass(configure_pooled_interpreter):
"""Nested dataclass instances should be recursively converted to dicts."""
def get_table() -> _PageTable:
return _PageTable(index=0, bbox=_BBox(x0=1.0, top=2.0, x1=3.0, bottom=4.0), strategy="lines")
- with PythonInterpreter(tools={"get_table": get_table}) as sandbox:
- result = sandbox.execute("t = get_table()\n(t['bbox']['x0'], t['strategy'])")
- assert result == [1.0, "lines"]
+ sandbox = configure_pooled_interpreter(tools={"get_table": get_table})
+ result = sandbox.execute("t = get_table()\n(t['bbox']['x0'], t['strategy'])")
+ assert result == [1.0, "lines"]
-def test_tool_returns_list_of_dataclasses():
+def test_tool_returns_list_of_dataclasses(configure_pooled_interpreter):
"""Lists of dataclass instances should round-trip as lists of dicts."""
def get_tables() -> list[_PageTable]:
@@ -795,9 +795,9 @@ def test_tool_returns_list_of_dataclasses():
_PageTable(index=1, bbox=_BBox(x0=5.0, top=6.0, x1=7.0, bottom=8.0), strategy="text"),
]
- with PythonInterpreter(tools={"get_tables": get_tables}) as sandbox:
- result = sandbox.execute("ts = get_tables()\n[t['index'] for t in ts]")
- assert result == [0, 1]
+ sandbox = configure_pooled_interpreter(tools={"get_tables": get_tables})
+ result = sandbox.execute("ts = get_tables()\n[t['index'] for t in ts]")
+ assert result == [0, 1]
# -- namedtuple tool returns -------------------------------------------------
@@ -814,29 +814,29 @@ from collections import namedtuple
_Point = namedtuple("_Point", ["x", "y"])
-def test_tool_returns_typing_namedtuple():
+def test_tool_returns_typing_namedtuple(configure_pooled_interpreter):
"""typing.NamedTuple instances should arrive as dicts."""
def get_point() -> _TypedPoint:
return _TypedPoint(x=10.5, y=20.3, label="origin")
- with PythonInterpreter(tools={"get_point": get_point}) as sandbox:
- result = sandbox.execute("p = get_point()\n(p['x'], p['label'])")
- assert result == [10.5, "origin"]
+ sandbox = configure_pooled_interpreter(tools={"get_point": get_point})
+ result = sandbox.execute("p = get_point()\n(p['x'], p['label'])")
+ assert result == [10.5, "origin"]
-def test_tool_returns_collections_namedtuple():
+def test_tool_returns_collections_namedtuple(configure_pooled_interpreter):
"""collections.namedtuple instances should arrive as dicts."""
def get_point() -> _Point:
return _Point(x=3.0, y=4.0)
- with PythonInterpreter(tools={"get_point": get_point}) as sandbox:
- result = sandbox.execute("p = get_point()\np['x'] + p['y']")
- assert result == 7.0
+ sandbox = configure_pooled_interpreter(tools={"get_point": get_point})
+ result = sandbox.execute("p = get_point()\np['x'] + p['y']")
+ assert result == 7.0
-def test_tool_returns_dataclass_with_unserializable_field_falls_back():
+def test_tool_returns_dataclass_with_unserializable_field_falls_back(configure_pooled_interpreter):
"""Dataclass with non-serializable fields should fall back to str() gracefully."""
import threading
@@ -848,9 +848,9 @@ def test_tool_returns_dataclass_with_unserializable_field_falls_back():
def get_holder() -> _Holder:
return _Holder(name="test", lock=threading.Lock())
- with PythonInterpreter(tools={"get_holder": get_holder}) as sandbox:
- result = sandbox.execute("h = get_holder()\ntype(h).__name__")
- assert result == "str"
+ sandbox = configure_pooled_interpreter(tools={"get_holder": get_holder})
+ result = sandbox.execute("h = get_holder()\ntype(h).__name__")
+ assert result == "str"
# =============================================================================
@@ -858,7 +858,7 @@ def test_tool_returns_dataclass_with_unserializable_field_falls_back():
# =============================================================================
-def test_submit_with_typed_signature():
+def test_submit_with_typed_signature(configure_pooled_interpreter):
"""Test SUBMIT with typed output signature."""
output_fields = [
@@ -866,14 +866,14 @@ def test_submit_with_typed_signature():
{"name": "confidence", "type": "float"},
]
- with PythonInterpreter(output_fields=output_fields) as sandbox:
- result = sandbox.execute('SUBMIT(answer="the answer", confidence=0.95)')
+ sandbox = configure_pooled_interpreter(output_fields=output_fields)
+ result = sandbox.execute('SUBMIT(answer="the answer", confidence=0.95)')
- assert isinstance(result, FinalOutput)
- assert result.output == {"answer": "the answer", "confidence": 0.95}
+ assert isinstance(result, FinalOutput)
+ assert result.output == {"answer": "the answer", "confidence": 0.95}
-def test_submit_positional_args():
+def test_submit_positional_args(configure_pooled_interpreter):
"""Test SUBMIT with positional arguments."""
output_fields = [
@@ -881,14 +881,14 @@ def test_submit_positional_args():
{"name": "confidence", "type": "float"},
]
- with PythonInterpreter(output_fields=output_fields) as sandbox:
- result = sandbox.execute('SUBMIT("the answer", 0.95)')
+ sandbox = configure_pooled_interpreter(output_fields=output_fields)
+ result = sandbox.execute('SUBMIT("the answer", 0.95)')
- assert isinstance(result, FinalOutput)
- assert result.output == {"answer": "the answer", "confidence": 0.95}
+ assert isinstance(result, FinalOutput)
+ assert result.output == {"answer": "the answer", "confidence": 0.95}
-def test_submit_multi_output():
+def test_submit_multi_output(configure_pooled_interpreter):
"""Test SUBMIT with multiple output fields using positional args."""
output_fields = [
@@ -896,20 +896,20 @@ def test_submit_multi_output():
{"name": "score", "type": "int"},
]
- with PythonInterpreter(output_fields=output_fields) as sandbox:
- # Positional args: values mapped to output fields in order
- code = """
+ sandbox = configure_pooled_interpreter(output_fields=output_fields)
+ # Positional args: values mapped to output fields in order
+ code = """
a = "my answer"
s = 42
SUBMIT(a, s)
"""
- result = sandbox.execute(code)
+ result = sandbox.execute(code)
- assert isinstance(result, FinalOutput)
- assert result.output == {"answer": "my answer", "score": 42}
+ assert isinstance(result, FinalOutput)
+ assert result.output == {"answer": "my answer", "score": 42}
-def test_submit_wrong_arg_count():
+def test_submit_wrong_arg_count(configure_pooled_interpreter):
"""Test SUBMIT with wrong number of args gives clear error."""
output_fields = [
@@ -917,10 +917,10 @@ def test_submit_wrong_arg_count():
{"name": "score", "type": "int"},
]
- with PythonInterpreter(output_fields=output_fields) as sandbox:
- with pytest.raises(CodeInterpreterError) as exc_info:
- sandbox.execute("x = 1; SUBMIT(x)") # Only 1 arg, expects 2
- assert "missing 1 required positional argument" in str(exc_info.value)
+ sandbox = configure_pooled_interpreter(output_fields=output_fields)
+ with pytest.raises(CodeInterpreterError) as exc_info:
+ sandbox.execute("x = 1; SUBMIT(x)") # Only 1 arg, expects 2
+ assert "missing 1 required positional argument" in str(exc_info.value)
def test_extract_parameters():
@@ -958,19 +958,19 @@ def test_extract_parameters_complex_types():
# =============================================================================
-def test_large_variable_injection():
+def test_large_variable_injection(pooled_interpreter):
"""Test that large strings are injected via filesystem to avoid Pyodide's FFI size limit."""
from dspy.primitives.python_interpreter import LARGE_VAR_THRESHOLD
# Create a string just over the threshold
large_data = "x" * (LARGE_VAR_THRESHOLD + 1024)
- with PythonInterpreter() as interpreter:
- result = interpreter.execute("len(data)", variables={"data": large_data})
- assert result == len(large_data), "Large variable should be correctly injected and accessible"
+ interpreter = pooled_interpreter
+ result = interpreter.execute("len(data)", variables={"data": large_data})
+ assert result == len(large_data), "Large variable should be correctly injected and accessible"
-def test_large_variable_content_integrity():
+def test_large_variable_content_integrity(pooled_interpreter):
"""Test that large variable content is preserved exactly through filesystem injection."""
from dspy.primitives.python_interpreter import LARGE_VAR_THRESHOLD
@@ -978,46 +978,46 @@ def test_large_variable_content_integrity():
pattern = "ABCDEFGHIJ" * 100
large_data = pattern * ((LARGE_VAR_THRESHOLD // len(pattern)) + 1)
- with PythonInterpreter() as interpreter:
- # Check first and last parts to verify content integrity
- code = """
+ interpreter = pooled_interpreter
+ # Check first and last parts to verify content integrity
+ code = """
first_100 = data[:100]
last_100 = data[-100:]
(first_100, last_100)
"""
- result = interpreter.execute(code, variables={"data": large_data})
- assert result[0] == large_data[:100], "First 100 chars should match"
- assert result[1] == large_data[-100:], "Last 100 chars should match"
+ result = interpreter.execute(code, variables={"data": large_data})
+ assert result[0] == large_data[:100], "First 100 chars should match"
+ assert result[1] == large_data[-100:], "Last 100 chars should match"
-def test_mixed_small_and_large_variables():
+def test_mixed_small_and_large_variables(pooled_interpreter):
"""Test that small and large variables can be used together."""
from dspy.primitives.python_interpreter import LARGE_VAR_THRESHOLD
small_var = "hello"
large_var = "x" * (LARGE_VAR_THRESHOLD + 1024)
- with PythonInterpreter() as interpreter:
- code = "f'{small} has {len(small)} chars, large has {len(large)} chars'"
- result = interpreter.execute(code, variables={"small": small_var, "large": large_var})
- expected = f"{small_var} has {len(small_var)} chars, large has {len(large_var)} chars"
- assert result == expected, "Both small and large variables should work together"
+ interpreter = pooled_interpreter
+ code = "f'{small} has {len(small)} chars, large has {len(large)} chars'"
+ result = interpreter.execute(code, variables={"small": small_var, "large": large_var})
+ expected = f"{small_var} has {len(small_var)} chars, large has {len(large_var)} chars"
+ assert result == expected, "Both small and large variables should work together"
-def test_multiple_large_variables():
+def test_multiple_large_variables(pooled_interpreter):
"""Test that multiple large variables can be injected."""
from dspy.primitives.python_interpreter import LARGE_VAR_THRESHOLD
large_a = "a" * (LARGE_VAR_THRESHOLD + 100)
large_b = "b" * (LARGE_VAR_THRESHOLD + 200)
- with PythonInterpreter() as interpreter:
- code = "(len(var_a), len(var_b), var_a[0], var_b[0])"
- result = interpreter.execute(code, variables={"var_a": large_a, "var_b": large_b})
- assert result == [len(large_a), len(large_b), "a", "b"], "Multiple large variables should work"
+ interpreter = pooled_interpreter
+ code = "(len(var_a), len(var_b), var_a[0], var_b[0])"
+ result = interpreter.execute(code, variables={"var_a": large_a, "var_b": large_b})
+ assert result == [len(large_a), len(large_b), "a", "b"], "Multiple large variables should work"
-def test_large_list_variable():
+def test_large_list_variable(pooled_interpreter):
"""Test that large list variables are injected via filesystem and JSON parsed."""
from dspy.primitives.python_interpreter import LARGE_VAR_THRESHOLD
@@ -1025,22 +1025,22 @@ def test_large_list_variable():
num_elements = LARGE_VAR_THRESHOLD // 3
large_list = ["x"] * num_elements
- with PythonInterpreter() as interpreter:
- code = "(len(data), data[0], data[-1], type(data).__name__)"
- result = interpreter.execute(code, variables={"data": large_list})
- assert result == [num_elements, "x", "x", "list"]
+ interpreter = pooled_interpreter
+ code = "(len(data), data[0], data[-1], type(data).__name__)"
+ result = interpreter.execute(code, variables={"data": large_list})
+ assert result == [num_elements, "x", "x", "list"]
-def test_nested_sets_and_tuples():
+def test_nested_sets_and_tuples(pooled_interpreter):
"""Test that nested structures with sets and tuples are converted to JSON-compatible types."""
complex_data = {"tags": {1, 2, 3}, "coords": (10, 20), "nested": [{"inner_set": {"a", "b"}}]}
- with PythonInterpreter() as interpreter:
- result = interpreter.execute("data", variables={"data": complex_data})
- # Sets become sorted lists, tuples become lists
- assert result["tags"] == [1, 2, 3]
- assert result["coords"] == [10, 20]
- assert result["nested"][0]["inner_set"] == ["a", "b"]
+ interpreter = pooled_interpreter
+ result = interpreter.execute("data", variables={"data": complex_data})
+ # Sets become sorted lists, tuples become lists
+ assert result["tags"] == [1, 2, 3]
+ assert result["coords"] == [10, 20]
+ assert result["nested"][0]["inner_set"] == ["a", "b"]
def test_small_variable_not_using_filesystem():