chuckfinca Claude Opus 4.6 (1M context) commited on
Commit
1ed0433
·
1 Parent(s): 2bc2348

Auto-retry on stale E2B sandbox — recreate and re-execute

Browse files

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Files changed (1) hide show
  1. sandbox_e2b.py +49 -30
sandbox_e2b.py CHANGED
@@ -52,6 +52,32 @@ def close_sandbox() -> None:
52
  _active_sandbox = None
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  def run_python(
56
  code: str,
57
  *,
@@ -63,33 +89,26 @@ def run_python(
63
  sandbox = get_or_create_sandbox(workspace, scratch_dir)
64
 
65
  try:
66
- execution = sandbox.run_code(code, timeout=timeout)
67
-
68
- stdout = "\n".join(
69
- line if isinstance(line, str) else line.text
70
- for line in execution.logs.stdout
71
- )
72
- stderr = "\n".join(
73
- line if isinstance(line, str) else line.text
74
- for line in execution.logs.stderr
75
- )
76
-
77
- if execution.error:
78
- stderr += f"\n{execution.error.name}: {execution.error.value}"
79
- exit_code = 1
80
- else:
81
- exit_code = 0
82
-
83
- return {
84
- "stdout": stdout,
85
- "stderr": stderr,
86
- "exit_code": exit_code,
87
- "timed_out": False,
88
- }
89
- except TimeoutError:
90
- return {
91
- "stdout": "",
92
- "stderr": "Execution timed out.",
93
- "exit_code": -1,
94
- "timed_out": True,
95
- }
 
52
  _active_sandbox = None
53
 
54
 
55
+ def _execute(sandbox: Sandbox, code: str, timeout: int) -> dict:
56
+ execution = sandbox.run_code(code, timeout=timeout)
57
+
58
+ stdout = "\n".join(
59
+ line if isinstance(line, str) else line.text
60
+ for line in execution.logs.stdout
61
+ )
62
+ stderr = "\n".join(
63
+ line if isinstance(line, str) else line.text
64
+ for line in execution.logs.stderr
65
+ )
66
+
67
+ if execution.error:
68
+ stderr += f"\n{execution.error.name}: {execution.error.value}"
69
+ exit_code = 1
70
+ else:
71
+ exit_code = 0
72
+
73
+ return {
74
+ "stdout": stdout,
75
+ "stderr": stderr,
76
+ "exit_code": exit_code,
77
+ "timed_out": False,
78
+ }
79
+
80
+
81
  def run_python(
82
  code: str,
83
  *,
 
89
  sandbox = get_or_create_sandbox(workspace, scratch_dir)
90
 
91
  try:
92
+ return _execute(sandbox, code, timeout)
93
+ except Exception as exc:
94
+ if "sandbox" in str(exc).lower() and "not found" in str(exc).lower():
95
+ # Stale sandbox recreate and retry
96
+ close_sandbox()
97
+ sandbox = get_or_create_sandbox(workspace, scratch_dir)
98
+ try:
99
+ return _execute(sandbox, code, timeout)
100
+ except TimeoutError:
101
+ return {
102
+ "stdout": "",
103
+ "stderr": "Execution timed out.",
104
+ "exit_code": -1,
105
+ "timed_out": True,
106
+ }
107
+ if isinstance(exc, TimeoutError):
108
+ return {
109
+ "stdout": "",
110
+ "stderr": "Execution timed out.",
111
+ "exit_code": -1,
112
+ "timed_out": True,
113
+ }
114
+ raise