Repository navigation
Expand file tree
/
Copy pathtest_python_interpreter.py
More file actions
1661 lines (1227 loc) · 60.6 KB
/
Copy pathtest_python_interpreter.py
File metadata and controls
1661 lines (1227 loc) · 60.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import dataclasses
import io
import json
import os
import random
import shutil
import subprocess
import sys
import threading
import types
from collections import namedtuple
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import NamedTuple
import pytest
from pydantic import BaseModel, ConfigDict
import dspy.primitives.python_interpreter as python_interpreter
from dspy.primitives.code_interpreter import CodeExecutionError, CodeInterpreterError, FinalOutput, _bind_interpreter
from dspy.primitives.python_interpreter import (
LARGE_VAR_THRESHOLD,
PythonInterpreter,
_deno_subprocess_env,
_find_deno_executable,
_make_jsonable,
_validate_deno_version,
)
class _Hit(BaseModel):
document_id: int
title: str
class _TimestampedHit(_Hit):
created_at: datetime
class _UnserializableValue:
pass
class _UnserializableModel(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
value: _UnserializableValue
pytestmark = pytest.mark.deno
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(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(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(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.
"""
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
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(pooled_interpreter):
"""Test that Python keywords are rejected as variable names."""
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})
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(pooled_interpreter):
interpreter = pooled_interpreter
code = "1+0/0"
with pytest.raises(CodeExecutionError, match="ZeroDivisionError"):
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(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(pooled_interpreter):
"""Test SUBMIT() with a list argument returns FinalOutput with dict format."""
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]}
def test_enable_env_vars_flag():
os.environ["FOO_TEST_ENV"] = "test_value"
with PythonInterpreter(enable_env_vars=None) as interpreter:
code = "import os\nresult = os.getenv('FOO_TEST_ENV')\nresult"
result = interpreter.execute(code)
assert result == "", "Environment variables should be inaccessible without allow-env"
with PythonInterpreter(enable_env_vars=["FOO_TEST_ENV"]) as interpreter:
code = "import os\nresult = os.getenv('FOO_TEST_ENV')\nresult"
result = interpreter.execute(code)
assert result == "test_value", "Environment variables should be accessible with allow-env"
def test_read_file_access_control(tmp_path):
testfile_path = tmp_path / "test_temp_file.txt"
virtual_path = f"/sandbox/{testfile_path.name}"
with open(testfile_path, "w") as f:
f.write("test content")
with PythonInterpreter(enable_read_paths=[str(testfile_path)]) as interpreter:
code = f"with open({virtual_path!r}, 'r') as f:\n data = f.read()\ndata"
result = interpreter.execute(code)
assert result == "test content", "Test file should be accessible with enable_read_paths and specified file"
with PythonInterpreter(enable_read_paths=None) as interpreter:
code = (
f"try:\n"
f" with open({virtual_path!r}, 'r') as f:\n"
f" data = f.read()\n"
f"except Exception as e:\n"
f" data = str(e)\n"
f"data"
)
result = interpreter.execute(code)
assert "PermissionDenied" in result or "denied" in result.lower() or "no such file" in result.lower(), (
"Test file should not be accessible without enable_read_paths"
)
def test_enable_write_flag(tmp_path):
testfile_path = tmp_path / "test_temp_output.txt"
virtual_path = f"/sandbox/{testfile_path.name}"
with PythonInterpreter(enable_write_paths=None) as interpreter:
code = (
f"try:\n"
f" with open({virtual_path!r}, 'w') as f:\n"
f" f.write('blocked')\n"
f" result = 'wrote'\n"
f"except Exception as e:\n"
f" result = str(e)\n"
f"result"
)
result = interpreter.execute(code)
assert "PermissionDenied" in result or "denied" in result.lower() or "no such file" in result.lower(), (
"Test file should not be writable without enable_write_paths"
)
with PythonInterpreter(enable_write_paths=[str(testfile_path)]) as interpreter:
code = f"with open({virtual_path!r}, 'w') as f:\n f.write('allowed')\n'ok'"
result = interpreter.execute(code)
assert result == "ok", "Test file should be writable with enable_write_paths"
assert testfile_path.exists()
with open(testfile_path) as f:
assert f.read() == "allowed", "Test file outputs should match content written during execution"
with open(testfile_path, "w") as f:
f.write("original_content")
with PythonInterpreter(enable_write_paths=[str(testfile_path)], sync_files=False) as interpreter:
code = f"with open({virtual_path!r}, 'w') as f:\n f.write('should_not_sync')\n'done_no_sync'"
result = interpreter.execute(code)
assert result == "done_no_sync"
with open(testfile_path) as f:
assert f.read() == "original_content", "File should not be changed when sync_files is False"
def test_enable_net_flag():
test_url = "https://example.com"
with PythonInterpreter(enable_network_access=None) as interpreter:
code = f"import js\nresp = await js.fetch({test_url!r})\nresp.status"
with pytest.raises(CodeInterpreterError, match="PythonError"):
interpreter.execute(code)
with PythonInterpreter(enable_network_access=["example.com"]) as interpreter:
code = f"import js\nresp = await js.fetch({test_url!r})\nresp.status"
result = interpreter.execute(code)
assert int(result) == 200, "Network access is permitted with enable_network_access"
def test_interpreter_security_filesystem_access(tmp_path):
"""
Verify that the interpreter cannot read arbitrary files from the host system
unless explicitly allowed.
"""
# 1. Create a "secret" file on the host
secret_file = tmp_path / "secret.txt"
secret_content = "This is a secret content"
secret_file.write_text(secret_content)
secret_path_str = str(secret_file.absolute())
# 2. Attempt to read the file WITHOUT permission
malicious_code = f"""
import js
try:
content = js.Deno.readTextFileSync('{secret_path_str}')
print(content)
except Exception as e:
print(f"Error: {{e}}")
"""
with PythonInterpreter() as interpreter:
output = interpreter(malicious_code)
assert "Requires read access" in output
assert secret_content not in output
# 3. Attempt to read the file WITH permission
with PythonInterpreter(enable_read_paths=[secret_path_str]) as interpreter:
output = interpreter(malicious_code)
assert secret_content in output
def test_default_runner_cannot_read_shared_deno_cache(monkeypatch, tmp_path):
shared_cache = tmp_path / "deno"
shared_cache.mkdir()
canary = shared_cache / "secret.txt"
canary.write_text("shared cache secret")
monkeypatch.setenv("DENO_DIR", str(shared_cache))
with PythonInterpreter() as interpreter:
result = interpreter.execute(
f"""import js
try:
js.Deno.readTextFileSync({str(canary)!r})
result = "disclosed"
except Exception as error:
result = str(error)
result"""
)
assert "disclosed" not in result
assert "read access" in result.lower()
def test_default_runner_starts_offline_from_warm_shared_cache(monkeypatch, tmp_path):
shared_cache = tmp_path / "deno"
runner = str(Path(python_interpreter.__file__).with_name("runner.js"))
env = {**_deno_subprocess_env(), "DENO_DIR": str(shared_cache)}
subprocess.run([_find_deno_executable(), "cache", "--no-config", "--no-lock", runner], env=env, check=True)
monkeypatch.setenv("DENO_DIR", str(shared_cache))
with PythonInterpreter() as interpreter:
interpreter.deno_command.insert(interpreter.deno_command.index(os.path.realpath(runner)), "--cached-only")
assert interpreter.execute("1 + 1") == 2
def test_tools_dict_is_copied():
"""Test that tools dict is defensively copied, not stored by reference."""
tools = {"my_tool": lambda: "result"}
sandbox = PythonInterpreter(tools=tools)
# Modify the original dict after construction
tools["new_tool"] = lambda: "new"
# The sandbox should not see the new tool
assert "new_tool" not in sandbox.tools
def test_serialize_tuple(pooled_interpreter):
"""Test that tuples can be serialized as variables."""
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(pooled_interpreter):
"""Test that sets can be serialized as variables."""
interpreter = pooled_interpreter
result = interpreter.execute("sorted(x)", variables={"x": {3, 1, 2}})
assert result == [1, 2, 3]
def test_serialize_set_mixed_types(pooled_interpreter):
"""Test that sets with mixed types can be serialized (fallback to list)."""
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(pooled_interpreter):
"""Pydantic instances passed via variables= should arrive in the sandbox as dicts."""
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(pooled_interpreter):
"""Pydantic instances nested inside list/dict variables should be coerced too."""
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(pooled_interpreter):
"""A list variable whose elements are Pydantic instances should be coerced too."""
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):
"""The large-variable path should serialize Pydantic's JSON-mode values."""
value = _TimestampedHit(
document_id=7,
title="dated",
created_at=datetime(2026, 5, 14, 8, 7, 27),
)
expected = {
"document_id": 7,
"title": "dated",
"created_at": "2026-05-14T08:07:27",
}
interpreter = PythonInterpreter()
assert interpreter._to_json_compatible(value) == expected
monkeypatch.setattr("dspy.primitives.python_interpreter.LARGE_VAR_THRESHOLD", 0)
code = interpreter._inject_variables("hit", {"hit": value})
assert "hit = json.loads" in code
assert json.loads(interpreter._pending_large_vars["hit"]) == expected
def test_json_mode_values_cross_every_host_to_sandbox_path():
"""Bare datetimes/enums/sets (not wrapped in a model) serialize the way they would into a
JSON body on all three host->sandbox paths: variable injection, large-var injection, and
tool results — instead of raising "Unsupported value type" or str()-flattening the result."""
class Color(Enum):
RED = "red"
value = {"t": datetime(2026, 1, 1), "c": Color.RED}
interpreter = PythonInterpreter()
assert interpreter._serialize_value(value) == "{'t': '2026-01-01T00:00:00', 'c': 'red'}"
assert interpreter._to_json_compatible(value) == {"t": "2026-01-01T00:00:00", "c": "red"}
jsonable = _make_jsonable({**value, "s": {3, 1}})
assert jsonable["t"] == "2026-01-01T00:00:00" and jsonable["c"] == "red"
assert sorted(jsonable["s"]) == [1, 3]
def test_json_mode_coercion_preserves_existing_fallbacks():
class P(NamedTuple):
x: int
y: int
assert _make_jsonable(P(1, 2)) == {"x": 1, "y": 2} # namedtuples keep field names, not [1, 2]
obj = object()
assert _make_jsonable(obj) is obj # unknown values still take the json.dumps/str fallback
with pytest.raises(CodeInterpreterError, match="Unsupported value type"):
PythonInterpreter()._serialize_value(object()) # injection still rejects them loudly
def test_unserializable_pydantic_variable_raises_code_interpreter_error():
"""Invalid host variables should fail before the interpreter process starts."""
interpreter = PythonInterpreter()
value = _UnserializableModel(value=_UnserializableValue())
with pytest.raises(CodeInterpreterError, match="Unable to serialize _UnserializableModel as JSON") as exc_info:
interpreter.execute("value", variables={"value": value})
assert type(exc_info.value) is CodeInterpreterError
assert interpreter.deno_process is None
def test_deno_command_dict_raises_type_error():
"""Test that passing a dict as deno_command raises TypeError."""
with pytest.raises(TypeError, match="deno_command must be a list"):
PythonInterpreter(deno_command={"invalid": "dict"})
def test_custom_deno_command_is_unchanged():
command = ["custom-deno", "run", "custom-runner.js", "argument"]
interpreter = PythonInterpreter(deno_command=command)
assert interpreter.deno_command == command
assert interpreter.deno_command is not command
def test_rejects_mounts_with_the_same_guest_basename(tmp_path):
first = tmp_path / "first" / "shared.txt"
second = tmp_path / "second" / "shared.txt"
first.parent.mkdir()
second.parent.mkdir()
with pytest.raises(CodeInterpreterError, match="unique basenames"):
PythonInterpreter(deno_command=["deno"], enable_read_paths=[first], enable_write_paths=[second])
def test_allows_same_canonical_file_as_read_and_write_mount(tmp_path):
path = tmp_path / "shared.txt"
PythonInterpreter(deno_command=["deno"], enable_read_paths=[path], enable_write_paths=[path])
def test_rejects_alias_basename_colliding_with_another_file(tmp_path):
first = tmp_path / "first.txt"
second = tmp_path / "second" / "shared.txt"
alias = tmp_path / "alias" / "shared.txt"
second.parent.mkdir()
alias.parent.mkdir()
alias.symlink_to(first)
with pytest.raises(CodeInterpreterError, match="unique basenames"):
PythonInterpreter(deno_command=["deno"], enable_read_paths=[first, alias, second])
def test_custom_deno_command_preserves_environment(monkeypatch):
monkeypatch.setenv("DENO_NO_PACKAGE_JSON", "0")
captured = {}
interpreter = PythonInterpreter(deno_command=["custom-deno", "run"])
def fake_popen(command, **kwargs):
captured["command"] = command
captured["env"] = kwargs["env"]
return object()
monkeypatch.setattr(python_interpreter.subprocess, "Popen", fake_popen)
monkeypatch.setattr(interpreter, "_health_check", lambda: None)
interpreter._spawn_process()
assert captured["command"] == ["custom-deno", "run"]
assert captured["env"]["DENO_NO_PACKAGE_JSON"] == "0"
def test_deno_subprocess_env_disables_package_json(monkeypatch):
monkeypatch.setenv("DENO_NO_PACKAGE_JSON", "0")
monkeypatch.setenv("DSPY_DENO_TEST_VALUE", "preserved")
env = _deno_subprocess_env()
assert env["DENO_NO_PACKAGE_JSON"] == "1"
assert env["DSPY_DENO_TEST_VALUE"] == "preserved"
assert os.environ["DENO_NO_PACKAGE_JSON"] == "0"
def test_managed_deno_package_is_preferred(monkeypatch):
managed_deno = types.SimpleNamespace(find_deno_bin=lambda: "/managed/bin/deno")
monkeypatch.setitem(sys.modules, "deno", managed_deno)
assert _find_deno_executable() == "/managed/bin/deno"
def test_missing_managed_deno_binary_falls_back_to_path(monkeypatch):
def missing_binary():
raise FileNotFoundError
managed_deno = types.SimpleNamespace(find_deno_bin=missing_binary)
monkeypatch.setitem(sys.modules, "deno", managed_deno)
monkeypatch.setattr(shutil, "which", lambda executable: "/system/bin/deno" if executable == "deno" else None)
assert _find_deno_executable() == "/system/bin/deno"
def test_default_command_uses_managed_deno_for_info_and_run(monkeypatch, tmp_path):
deno_executable = str(tmp_path / "managed-deno")
seen_operations = []
monkeypatch.setattr(python_interpreter, "_find_deno_executable", lambda: deno_executable)
monkeypatch.setattr(
python_interpreter,
"_validate_deno_version",
lambda executable: seen_operations.append(("version", executable)),
)
monkeypatch.setattr(
PythonInterpreter,
"_get_deno_dir",
staticmethod(lambda executable: seen_operations.append(("info", executable)) or str(tmp_path / "cache")),
)
interpreter = PythonInterpreter()
assert seen_operations == [("info", deno_executable)]
assert interpreter.deno_command[:5] == [
deno_executable,
"run",
"--no-config",
"--no-lock",
"--node-modules-dir=false",
]
runner_index = interpreter.deno_command.index(os.path.realpath(interpreter._get_runner_path()))
assert all(interpreter.deno_command.index(flag) < runner_index for flag in interpreter.deno_command[2:5])
monkeypatch.setattr(python_interpreter.subprocess, "Popen", lambda *args, **kwargs: object())
monkeypatch.setattr(interpreter, "_health_check", lambda: None)
interpreter._spawn_process()
assert seen_operations == [("info", deno_executable), ("version", deno_executable)]
def test_default_command_revokes_shared_cache_after_startup(monkeypatch, tmp_path):
shared_cache = tmp_path / "deno"
monkeypatch.setattr(PythonInterpreter, "_get_deno_dir", staticmethod(lambda executable: str(shared_cache)))
interpreter = PythonInterpreter()
assert str(shared_cache) in next(arg for arg in interpreter.deno_command if arg.startswith("--allow-read="))
assert f"--dspy-deno-dir={shared_cache}" in interpreter.deno_command
def test_rejects_write_paths_overlapping_runtime_files(monkeypatch, tmp_path):
cache = tmp_path / "deno"
monkeypatch.setattr(PythonInterpreter, "_get_deno_dir", staticmethod(lambda executable: str(cache)))
with pytest.raises(CodeInterpreterError, match="runtime files"):
PythonInterpreter(enable_write_paths=[cache])
@pytest.mark.parametrize("version", [(2, 0, 0), (2, 4, 5), (2, 9, 5)])
def test_accepts_supported_deno_2_versions(monkeypatch, version):
monkeypatch.setattr(python_interpreter, "_get_deno_version", lambda executable: version)
_validate_deno_version("/system/bin/deno")
@pytest.mark.parametrize("version", [(1, 46, 3), (3, 0, 0)])
def test_rejects_unsupported_system_deno(monkeypatch, version):
monkeypatch.setattr(python_interpreter, "_get_deno_version", lambda executable: version)
version_text = "\\.".join(map(str, version))
with pytest.raises(CodeInterpreterError, match=rf"Unsupported Deno version {version_text}"):
_validate_deno_version("/system/bin/deno")
@pytest.mark.parametrize(
("returncode", "stdout", "stderr"),
[
(0, "not a Deno version", ""),
(0, "", "deno 2.9.5"),
(1, "deno 2.9.5", "version probe failed"),
],
)
def test_rejects_invalid_deno_version_probe(monkeypatch, returncode, stdout, stderr):
result = types.SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)
monkeypatch.setattr(python_interpreter.subprocess, "run", lambda *args, **kwargs: result)
with pytest.raises(CodeInterpreterError, match="Unable to determine the Deno version"):
_validate_deno_version("/fake/bin/deno")
def test_deno_version_probe_is_bounded_and_not_cached(monkeypatch):
results = iter(
[
types.SimpleNamespace(returncode=0, stdout="deno 2.9.5", stderr=""),
types.SimpleNamespace(returncode=0, stdout="deno 2.9.4", stderr=""),
]
)
seen_timeouts = []
def fake_run(*args, **kwargs):
seen_timeouts.append(kwargs["timeout"])
return next(results)
monkeypatch.setattr(python_interpreter.subprocess, "run", fake_run)
assert python_interpreter._get_deno_version("/fake/bin/deno") == (2, 9, 5)
assert python_interpreter._get_deno_version("/fake/bin/deno") == (2, 9, 4)
assert seen_timeouts == [python_interpreter.DENO_PROBE_TIMEOUT_SECONDS] * 2
def test_deno_version_probe_timeout_is_reported_as_indeterminate(monkeypatch):
def timeout(*args, **kwargs):
raise subprocess.TimeoutExpired(args[0], kwargs["timeout"])
monkeypatch.setattr(python_interpreter.subprocess, "run", timeout)
with pytest.raises(CodeInterpreterError, match="Unable to determine the Deno version"):
_validate_deno_version("/hanging/bin/deno")
def test_deno_info_probe_is_bounded(monkeypatch):
captured = {}
def fake_run(*args, **kwargs):
captured.update(kwargs)
return types.SimpleNamespace(returncode=0, stdout=json.dumps({"denoDir": "/cache"}))
monkeypatch.setattr(python_interpreter.subprocess, "run", fake_run)
PythonInterpreter._query_deno_dir.cache_clear()
assert PythonInterpreter._query_deno_dir("/bounded/bin/deno") == "/cache"
assert captured["timeout"] == python_interpreter.DENO_PROBE_TIMEOUT_SECONDS
def test_explicit_deno_dir_skips_info_query(monkeypatch, tmp_path):
deno_dir = str(tmp_path / "deno-cache")
monkeypatch.setenv("DENO_DIR", deno_dir)
monkeypatch.setattr(
PythonInterpreter,
"_query_deno_dir",
staticmethod(lambda executable: pytest.fail(f"unexpected Deno info query for {executable}")),
)
assert PythonInterpreter._get_deno_dir("/managed/bin/deno") == deno_dir
def test_ignores_parent_package_json_and_node_modules(monkeypatch, tmp_path):
"""A parent Node project must not redirect runner.js's Pyodide import."""
project_dir = tmp_path / "node-project"
runner_dir = project_dir / "runtime"
fake_pyodide_dir = project_dir / "node_modules" / "pyodide"
runner_dir.mkdir(parents=True)
fake_pyodide_dir.mkdir(parents=True)
runner_path = runner_dir / "runner.js"
shutil.copyfile(Path(python_interpreter.__file__).with_name("runner.js"), runner_path)
(project_dir / "package.json").write_text(json.dumps({"dependencies": {"pyodide": "0.29.4"}}))
(fake_pyodide_dir / "package.json").write_text(
json.dumps(
{
"name": "pyodide",
"version": "0.29.4",
"type": "module",
"exports": {"./pyodide.js": "./pyodide.js"},
}
)
)
(fake_pyodide_dir / "blocked.txt").write_text("ambient package was selected")
(fake_pyodide_dir / "pyodide.js").write_text(
'Deno.readTextFileSync(new URL("./blocked.txt", import.meta.url));\n'
'export default { loadPyodide() { throw new Error("DSPy loaded Pyodide from parent node_modules"); } };\n'
)
class ParentProjectInterpreter(PythonInterpreter):
def _get_runner_path(self):
return str(runner_path)
monkeypatch.chdir(runner_dir)
monkeypatch.delenv("DENO_NO_PACKAGE_JSON", raising=False)
with ParentProjectInterpreter() as interpreter:
assert interpreter.execute("6 * 7") == 42
assert not (project_dir / "deno.lock").exists()
# =============================================================================
# Typed Tool Signature Tests
# =============================================================================
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}"
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_none_type_and_nested_json_default():
def tool(value: type(None) = None, items: list = [None]): # noqa: B006
return [value, items]
with PythonInterpreter(tools={"tool": tool}) as interpreter:
assert interpreter.execute("tool()") == [None, [None]]
@pytest.mark.parametrize(
("field", "code", "expected"),
[
({"name": "nothing", "type": "NoneType"}, "SUBMIT(nothing=None)", {"nothing": None}),
({"name": "FinalOutput", "type": "str"}, "SUBMIT(FinalOutput='ok')", {"FinalOutput": "ok"}),
],
)
def test_submit_valid_runtime_edge_cases(field, code, expected):
with PythonInterpreter(output_fields=[field]) as interpreter:
assert interpreter.execute(code) == FinalOutput(expected)
def test_bind_replaces_tools_and_submit_shape_without_resetting_state(pooled_interpreter):
tools = {"tool": lambda: "ok"}
fields = [{"name": "answer", "type": "str"}]
pooled_interpreter.execute("state = 41")
pooled_interpreter.bind(tools=tools, output_fields=fields)
tools.clear()
fields[0]["name"] = "changed"
assert pooled_interpreter.execute("tool()") == "ok"
assert pooled_interpreter.execute("state + 1") == 42
assert pooled_interpreter.execute("SUBMIT(answer='done')") == FinalOutput({"answer": "done"})
with pytest.raises(TypeError):
pooled_interpreter.bind(tools={}, output_fields=[None])
assert pooled_interpreter.execute("tool()") == "ok"
pooled_interpreter.bind(tools={})
assert pooled_interpreter.execute("SUBMIT('default')") == FinalOutput({"output": "default"})
def test_bind_fallback_invalidates_legacy_registration():
class LegacyPythonInterpreter(PythonInterpreter):
bind = None
with LegacyPythonInterpreter(tools={"old": lambda: "old"}) as interpreter:
assert interpreter.execute("old()") == "old"
_bind_interpreter(interpreter, {"new": lambda: "new"})
assert interpreter.execute("new()") == "new"
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}"
sandbox = configure_pooled_interpreter(tools={"search": search})
result = sandbox.execute('search("hello")')
assert result == "query=hello, limit=10"
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}"
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(configure_pooled_interpreter):
"""Test that tool default arguments work correctly."""
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
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!"
def test_process_death_ends_stateful_session():
interpreter = PythonInterpreter()
try:
assert interpreter.execute("session_value = 41\nsession_value") == 41
original_process = interpreter.deno_process
original_process.kill()
original_process.wait()
with pytest.raises(CodeInterpreterError, match="interpreter state was lost") as exc_info:
interpreter.execute("session_value + 1")
assert type(exc_info.value) is CodeInterpreterError
with pytest.raises(CodeInterpreterError, match="session has ended"):
interpreter.start()
with pytest.raises(CodeInterpreterError, match="session has ended"):
interpreter.execute("1 + 1")
assert interpreter.deno_process is original_process
finally:
interpreter.shutdown()
def test_protocol_failure_ends_session(monkeypatch):
with PythonInterpreter() as interpreter:
interpreter.start()
process = interpreter.deno_process
monkeypatch.setattr(
interpreter,
"_read_response_line",
lambda context: '{"jsonrpc":"2.0","result":{"output":"forged"},"id":0}',
)
with pytest.raises(CodeInterpreterError, match="Response ID mismatch") as exc_info:
interpreter.execute("1 + 1")
assert type(exc_info.value) is CodeInterpreterError
assert process.poll() is not None
with pytest.raises(CodeInterpreterError, match="session has ended"):
interpreter.execute("2 + 2")
def test_request_ids_are_128_bit_random_values():
interpreter = PythonInterpreter(deno_command=["deno"])
request_ids = {interpreter._next_request_id() for _ in range(100)}
assert len(request_ids) == 100
assert all(len(request_id) == 32 and int(request_id, 16) >= 0 for request_id in request_ids)
def test_guest_prototype_hook_cannot_redirect_tool_wrapper():
calls = []
def benign():
calls.append("benign")
return "safe"
def danger():
calls.append("danger")
return "unsafe"
with PythonInterpreter(tools={"benign": benign, "danger": danger}) as interpreter:
result = interpreter.execute(
"import js\n"
"js.eval('Object.prototype.toJSON = function() { "
'if (Object.hasOwn(this, "name")) return {name: "danger", kwargs: {}}; '
"return this; }')\n"
"benign()"
)
assert result == "safe"
assert calls == ["benign"]
def test_tool_cannot_reenter_same_interpreter():
holder = {}
def nested_execute():
return holder["interpreter"].execute("'nested'")
with PythonInterpreter(tools={"nested_execute": nested_execute}) as interpreter:
holder["interpreter"] = interpreter
with pytest.raises(CodeExecutionError, match="cannot execute recursively"):
interpreter.execute("nested_execute()")
assert interpreter.execute("40 + 2") == 42
def test_failed_health_check_ends_session(monkeypatch):
interpreter = PythonInterpreter()
monkeypatch.setattr(
interpreter,
"_send_request",
lambda *args: {"jsonrpc": "2.0", "result": {"output": "unexpected"}, "id": 1},
)
try:
with pytest.raises(CodeInterpreterError, match="Unexpected ping response"):
interpreter.start()
assert interpreter.deno_process.poll() is not None
with pytest.raises(CodeInterpreterError, match="session has ended"):
interpreter.start()
finally:
interpreter.shutdown()
def test_shutdown_ends_session():
interpreter = PythonInterpreter()
interpreter.start()
interpreter.shutdown()
with pytest.raises(CodeInterpreterError, match="session has ended") as exc_info:
interpreter.start()
assert type(exc_info.value) is CodeInterpreterError
with pytest.raises(CodeInterpreterError, match="session has ended"):
interpreter.execute("1 + 1")
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}"
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"
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}")
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(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}"
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(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}")
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
# =============================================================================
# Tool Return Type Tests
# =============================================================================
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: