asta-code-execution 1.0.1__tar.gz → 2.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: asta-code-execution
3
- Version: 1.0.1
3
+ Version: 2.0.1
4
4
  Summary: Add your description here
5
5
  Author: Allen Institute for Artificial Intelligence
6
6
  License-Expression: Apache-2.0
7
7
  License-File: LICENSE
8
8
  Requires-Dist: ipython>=9.9.0
9
- Requires-Python: >=3.13
9
+ Requires-Python: >=3.12
10
10
  Description-Content-Type: text/markdown
11
11
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "asta-code-execution"
3
- version = "1.0.1"
3
+ version = "2.0.1"
4
4
  description = "Add your description here"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -8,7 +8,7 @@ license-files = ["LICENSE"]
8
8
  authors = [
9
9
  { name = "Allen Institute for Artificial Intelligence" }
10
10
  ]
11
- requires-python = ">=3.13"
11
+ requires-python = ">=3.12"
12
12
  dependencies = [
13
13
  "ipython>=9.9.0",
14
14
  ]
@@ -1,10 +1,12 @@
1
1
  """IPython-backed execution helpers with optional subprocess isolation."""
2
2
 
3
3
  import base64
4
+ import sys
4
5
  import traceback
5
6
  from collections.abc import Iterable
6
7
  from dataclasses import dataclass
7
8
  from multiprocessing import get_context
9
+ from time import monotonic
8
10
  from typing import Any, cast
9
11
 
10
12
  from IPython.core.formatters import DisplayFormatter
@@ -69,14 +71,60 @@ def _format_error(exc: BaseException | None) -> dict[str, str] | None:
69
71
  }
70
72
 
71
73
 
74
+ def _flush_open_figures(formatted_object_ids: set[int]) -> None:
75
+ """Emit any matplotlib figures the cell left open as display data.
76
+
77
+ The inline backend only publishes a figure when the code calls
78
+ ``plt.show()``, which also closes it. Anything still open once the cell
79
+ finishes was therefore never published -- a figure the code built but
80
+ saved, or simply forgot to show. Publishing it here means a caller's view
81
+ of the figures a cell produced does not depend on the cell calling
82
+ ``plt.show()``.
83
+
84
+ Only touches pyplot if the cell actually imported it, so a cell that draws
85
+ nothing pays no import cost.
86
+ """
87
+ pyplot = sys.modules.get("matplotlib.pyplot")
88
+ if pyplot is None:
89
+ return
90
+ from IPython.display import display
91
+
92
+ for fig_num in pyplot.get_fignums():
93
+ figure = pyplot.figure(fig_num)
94
+ try:
95
+ if id(figure) not in formatted_object_ids:
96
+ display(figure)
97
+ except Exception:
98
+ # A figure that cannot be rendered must not fail the cell it came
99
+ # from or prevent later figures from being published.
100
+ pass
101
+ finally:
102
+ pyplot.close(figure)
103
+
104
+
72
105
  def _run_cell_with_shell(
73
106
  shell: InteractiveShell,
74
107
  code_str: str,
75
108
  allow_mime: frozenset[str],
76
109
  ) -> dict[str, Any]:
77
110
  # Execute in-process to preserve state between calls when isolation isn't needed.
78
- with capture_output() as captured:
79
- result = shell.run_cell(code_str)
111
+ formatted_object_ids: set[int] = set()
112
+ formatter = cast(DisplayFormatter, shell.display_formatter)
113
+ original_format = formatter.format
114
+
115
+ def tracking_format(obj: Any, *args: Any, **kwargs: Any):
116
+ formatted_object_ids.add(id(obj))
117
+ return original_format(obj, *args, **kwargs)
118
+
119
+ formatter.format = tracking_format
120
+ try:
121
+ with capture_output() as captured:
122
+ result = shell.run_cell(code_str)
123
+ # Inside the capture block so newly flushed figures land in
124
+ # captured.outputs alongside figures the cell published itself.
125
+ _flush_open_figures(formatted_object_ids)
126
+ finally:
127
+ formatter.format = original_format
80
128
 
81
129
  error = result.error_before_exec or result.error_in_exec
82
130
  outputs = {
@@ -176,6 +224,13 @@ def _ensure_pip_available() -> None:
176
224
  return
177
225
 
178
226
 
227
+ def _remaining(deadline: float | None) -> float | None:
228
+ """Seconds left until ``deadline``, or None for no deadline."""
229
+ if deadline is None:
230
+ return None
231
+ return max(0.0, deadline - monotonic())
232
+
233
+
179
234
  def _run_cell_in_subprocess(
180
235
  code_str: str,
181
236
  allow_mime: frozenset[str],
@@ -228,12 +283,34 @@ class IPythonSession:
228
283
  )
229
284
  process.start()
230
285
  child_conn.close()
231
- process.join(timeout=self._config.timeout_s)
232
286
 
287
+ # Read the result before waiting for the child to exit. The child sends
288
+ # its outputs as a single pickled frame, which runs to megabytes once
289
+ # figures are attached, while a pipe buffers only ~64KB. Joining first
290
+ # would leave the child blocked in send() with nobody draining the pipe,
291
+ # and the parent blocked in join() waiting for an exit that send() is
292
+ # preventing -- a deadlock that only shows up on cells big enough to
293
+ # overflow the buffer. recv() is what drains it, so it has to come first.
294
+ timeout_s = self._config.timeout_s
295
+ deadline = None if timeout_s is None else monotonic() + timeout_s
296
+ result: dict[str, Any] | None = None
297
+ try:
298
+ if parent_conn.poll(_remaining(deadline)):
299
+ result = parent_conn.recv()
300
+ except EOFError:
301
+ # Child exited without sending; reported below as a missing result.
302
+ pass
303
+
304
+ process.join(timeout=_remaining(deadline))
233
305
  if process.is_alive():
234
306
  process.terminate()
235
307
  process.join()
236
- parent_conn.close()
308
+ parent_conn.close()
309
+
310
+ if result is not None:
311
+ return result
312
+
313
+ if deadline is not None and monotonic() >= deadline:
237
314
  return {
238
315
  "stdout": "",
239
316
  "stderr": "",
@@ -241,18 +318,11 @@ class IPythonSession:
241
318
  "success": False,
242
319
  "error": {
243
320
  "type": "TimeoutError",
244
- "message": f"Execution exceeded {self._config.timeout_s} seconds",
321
+ "message": f"Execution exceeded {timeout_s} seconds",
245
322
  "traceback": "",
246
323
  },
247
324
  }
248
325
 
249
- if parent_conn.poll():
250
- result = parent_conn.recv()
251
- parent_conn.close()
252
- return result
253
-
254
- parent_conn.close()
255
-
256
326
  return {
257
327
  "stdout": "",
258
328
  "stderr": "",
@@ -9,6 +9,7 @@ import shutil
9
9
  import subprocess
10
10
  import sys
11
11
  import tempfile
12
+ import threading
12
13
  from collections.abc import Iterable
13
14
  from pathlib import Path
14
15
  from typing import Any
@@ -73,20 +74,66 @@ if __name__ == "__main__":
73
74
  """
74
75
 
75
76
 
76
- def _find_uv() -> str:
77
- """Return path to the ``uv`` binary, or raise if not found."""
78
- uv = shutil.which("uv")
79
- if uv is None:
77
+ _WINDOWS = os.name == "nt"
78
+
79
+ # Experiment code installs a package by running this command (a JSON list) with
80
+ # the package name appended. It is run without a shell, so it works the same on
81
+ # Windows.
82
+ INSTALL_COMMAND_ENV = "CODE_EXECUTION_INSTALL_COMMAND"
83
+
84
+ # Records what a sandbox venv was built with, so a venv shared by several
85
+ # backends is built once.
86
+ _SANDBOX_MARKER = ".code-execution-sandbox.json"
87
+ _SANDBOX_LOCK = threading.Lock()
88
+
89
+
90
+ def _find_uv() -> str | None:
91
+ """Return the path to ``uv`` if it is installed, else None.
92
+
93
+ ``uv run`` and ``uv tool run`` set ``UV`` to the binary they were started
94
+ from, which finds uv even when it is not on PATH.
95
+ """
96
+ uv = shutil.which("uv") or os.environ.get("UV")
97
+ return uv if uv and os.path.exists(uv) else None
98
+
99
+
100
+ def _venv_bin(venv_path: Path) -> Path:
101
+ """Return a venv's scripts directory: ``Scripts`` on Windows, ``bin`` elsewhere."""
102
+ return venv_path / ("Scripts" if _WINDOWS else "bin")
103
+
104
+
105
+ def _venv_python(venv_path: Path) -> Path:
106
+ """Return the path to a venv's Python interpreter."""
107
+ return _venv_bin(venv_path) / ("python.exe" if _WINDOWS else "python")
108
+
109
+
110
+ def _pip_install(uv: str | None, python_bin: Path) -> list[str]:
111
+ """Return the command that installs packages into the venv of ``python_bin``.
112
+
113
+ uv when it is installed, because it is much faster; otherwise the venv's own
114
+ pip, so the backend needs nothing beyond Python itself.
115
+ """
116
+ if uv:
117
+ return [uv, "pip", "install", "--python", str(python_bin)]
118
+ return [str(python_bin), "-m", "pip", "install", "--disable-pip-version-check"]
119
+
120
+
121
+ def _run(command: list[str]) -> None:
122
+ """Run a setup command; on failure, raise with the command's own error output."""
123
+ # errors="replace": the output is in whatever encoding the tool chose, and a
124
+ # byte the locale codec rejects must not hide the real failure.
125
+ proc = subprocess.run(command, capture_output=True, text=True, errors="replace")
126
+ if proc.returncode != 0:
127
+ output = (proc.stderr or proc.stdout).strip()
80
128
  raise RuntimeError(
81
- "uv is required for ProcessIPythonBackend but was not found on PATH"
129
+ f"Setting up the process backend's sandbox failed: {' '.join(command)}\n{output}"
82
130
  )
83
- return uv
84
131
 
85
132
 
86
133
  # TODO: Transplant this implementation onto asta_sandbox.SandboxBase (making run_cell
87
134
  # async via asyncio.to_thread) and move it into the asta-sandbox library as a first-class
88
135
  # local process backend alongside InProcessExecutor and ModalEphemeralExecutor. Once done,
89
- # _ProcessBackendAdapter in agents.py can be removed and ProcessIPythonBackend can be used
136
+ # _IPythonBackendAdapter in agents.py can be removed and ProcessIPythonBackend can be used
90
137
  # directly wherever a SandboxBase is expected.
91
138
  class ProcessIPythonBackend:
92
139
  """Backend that executes IPython cells in isolated subprocesses.
@@ -94,7 +141,7 @@ class ProcessIPythonBackend:
94
141
  Each backend instance lazily creates a *base sandbox venv* with a curated
95
142
  set of packages (mirroring the Modal sandbox image). Individual
96
143
  ``run_cell`` invocations get a per-process temporary directory so that any
97
- ``uv pip install`` executed by experiment code does **not** mutate the
144
+ ``pip install`` executed by experiment code does **not** mutate the
98
145
  base venv.
99
146
  """
100
147
 
@@ -114,6 +161,7 @@ class ProcessIPythonBackend:
114
161
  Path(sandbox_venv_path) if sandbox_venv_path else None
115
162
  )
116
163
  self._sandbox_ready = False
164
+ self._uv: str | None = None
117
165
  self._owned_venv_dir: tempfile.TemporaryDirectory[str] | None = None
118
166
 
119
167
  # -- lazy venv setup -----------------------------------------------------
@@ -122,7 +170,11 @@ class ProcessIPythonBackend:
122
170
  """Create the base sandbox venv if it doesn't already exist."""
123
171
  if self._sandbox_ready and self._sandbox_venv_path is not None:
124
172
  return self._sandbox_venv_path
173
+ # One build at a time: backends on several threads may share a venv.
174
+ with _SANDBOX_LOCK:
175
+ return self._build_sandbox()
125
176
 
177
+ def _build_sandbox(self) -> Path:
126
178
  uv = _find_uv()
127
179
 
128
180
  if self._sandbox_venv_path is None:
@@ -130,24 +182,7 @@ class ProcessIPythonBackend:
130
182
  self._sandbox_venv_path = Path(self._owned_venv_dir.name)
131
183
 
132
184
  venv_path = self._sandbox_venv_path
133
- python_bin = venv_path / "bin" / "python"
134
-
135
- if not python_bin.exists():
136
- subprocess.run(
137
- [uv, "venv", str(venv_path), "--seed", "--python", sys.executable],
138
- check=True,
139
- capture_output=True,
140
- text=True,
141
- )
142
-
143
- # Install curated packages
144
- if self._packages:
145
- subprocess.run(
146
- [uv, "pip", "install", "--python", str(python_bin), *self._packages],
147
- check=True,
148
- capture_output=True,
149
- text=True,
150
- )
185
+ python_bin = _venv_python(venv_path)
151
186
 
152
187
  # Install code_execution package so the sandbox runner can import it.
153
188
  code_exec_pkg = Path(__file__).resolve().parent.parent.parent
@@ -158,13 +193,31 @@ class ProcessIPythonBackend:
158
193
  # Running from pip-installed cli
159
194
  version = importlib.metadata.version("asta-code-execution")
160
195
  install_spec = [f"asta-code-execution=={version}"]
161
- subprocess.run(
162
- [uv, "pip", "install", "--python", str(python_bin), *install_spec],
163
- check=True,
164
- capture_output=True,
165
- text=True,
166
- )
167
196
 
197
+ # A venv another backend already built with the same contents is ready.
198
+ marker = venv_path / _SANDBOX_MARKER
199
+ built_with = json.dumps({"packages": self._packages, "code_execution": install_spec})
200
+ if python_bin.exists() and marker.is_file() and marker.read_text() == built_with:
201
+ self._uv = uv
202
+ self._sandbox_ready = True
203
+ return venv_path
204
+
205
+ if not python_bin.exists():
206
+ if uv:
207
+ _run([uv, "venv", str(venv_path), "--seed", "--python", sys.executable])
208
+ else:
209
+ _run([sys.executable, "-m", "venv", str(venv_path)])
210
+
211
+ install = _pip_install(uv, python_bin)
212
+
213
+ # Install curated packages
214
+ if self._packages:
215
+ _run([*install, *self._packages])
216
+
217
+ _run([*install, *install_spec])
218
+ marker.write_text(built_with)
219
+
220
+ self._uv = uv
168
221
  self._sandbox_ready = True
169
222
  return venv_path
170
223
 
@@ -172,7 +225,7 @@ class ProcessIPythonBackend:
172
225
  def sandbox_python(self) -> str:
173
226
  """Return the path to the sandbox venv's Python interpreter."""
174
227
  venv = self._ensure_sandbox()
175
- return str(venv / "bin" / "python")
228
+ return str(_venv_python(venv))
176
229
 
177
230
  # -- cell execution ------------------------------------------------------
178
231
 
@@ -187,7 +240,7 @@ class ProcessIPythonBackend:
187
240
  ) -> dict[str, Any]:
188
241
  """Execute a code cell in an isolated subprocess and return normalized outputs."""
189
242
  venv_path = self._ensure_sandbox()
190
- python_bin = str(venv_path / "bin" / "python")
243
+ python_bin = str(_venv_python(venv_path))
191
244
 
192
245
  payload = {
193
246
  "code_str": code_str,
@@ -202,8 +255,8 @@ class ProcessIPythonBackend:
202
255
  child_env.update(self._env)
203
256
 
204
257
  # Per-cell temp directory for any packages installed by experiment code.
205
- # An `install-package` script on PATH installs into this directory
206
- # via `uv pip install --target`, keeping the base sandbox venv clean.
258
+ # The command in INSTALL_COMMAND_ENV installs into this directory with
259
+ # `pip install --target`, keeping the base sandbox venv clean.
207
260
  cell_tmp = tempfile.mkdtemp(prefix="cell_pkgs_")
208
261
  try:
209
262
  cell_install_dir = os.path.join(cell_tmp, "lib")
@@ -211,24 +264,17 @@ class ProcessIPythonBackend:
211
264
 
212
265
  existing_pp = child_env.get("PYTHONPATH", "")
213
266
  child_env["PYTHONPATH"] = (
214
- f"{cell_install_dir}:{existing_pp}" if existing_pp else cell_install_dir
267
+ f"{cell_install_dir}{os.pathsep}{existing_pp}" if existing_pp else cell_install_dir
268
+ )
269
+
270
+ install = _pip_install(self._uv, Path(python_bin))
271
+ child_env[INSTALL_COMMAND_ENV] = json.dumps(
272
+ [*install, "--target", cell_install_dir, "--quiet"]
215
273
  )
216
274
 
217
- # Create an install-package script that experiment code calls
218
- # to install packages into the per-process temp directory.
219
- script_dir = os.path.join(cell_tmp, "bin")
220
- os.makedirs(script_dir, exist_ok=True)
221
- real_uv = _find_uv()
222
- script_path = os.path.join(script_dir, "install-package")
223
- with open(script_path, "w") as f:
224
- f.write(f"""#!/bin/sh
225
- # Install a Python package into the per-process temp directory.
226
- exec "{real_uv}" pip install --target "{cell_install_dir}" --quiet "$@"
227
- """)
228
- os.chmod(script_path, 0o755)
229
-
230
- venv_bin = str(venv_path / "bin")
231
- child_env["PATH"] = f"{script_dir}:{venv_bin}:{child_env.get('PATH', '')}"
275
+ child_env["PATH"] = os.pathsep.join(
276
+ [str(_venv_bin(venv_path)), child_env.get("PATH", "")]
277
+ )
232
278
  child_env["VIRTUAL_ENV"] = str(venv_path)
233
279
 
234
280
  try:
@@ -237,6 +283,7 @@ exec "{real_uv}" pip install --target "{cell_install_dir}" --quiet "$@"
237
283
  input=json.dumps(payload),
238
284
  capture_output=True,
239
285
  text=True,
286
+ errors="replace",
240
287
  timeout=timeout_s,
241
288
  cwd=self._cwd,
242
289
  env=child_env,