asta-code-execution 1.0.0__tar.gz → 2.0.0__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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: asta-code-execution
3
- Version: 1.0.0
3
+ Version: 2.0.0
4
4
  Summary: Add your description here
5
5
  Author: Allen Institute for Artificial Intelligence
6
6
  License-Expression: Apache-2.0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "asta-code-execution"
3
- version = "1.0.0"
3
+ version = "2.0.0"
4
4
  description = "Add your description here"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -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": "",
@@ -77,16 +77,14 @@ def _find_uv() -> str:
77
77
  """Return path to the ``uv`` binary, or raise if not found."""
78
78
  uv = shutil.which("uv")
79
79
  if uv is None:
80
- raise RuntimeError(
81
- "uv is required for ProcessIPythonBackend but was not found on PATH"
82
- )
80
+ raise RuntimeError("uv is required for ProcessIPythonBackend but was not found on PATH")
83
81
  return uv
84
82
 
85
83
 
86
84
  # TODO: Transplant this implementation onto asta_sandbox.SandboxBase (making run_cell
87
85
  # async via asyncio.to_thread) and move it into the asta-sandbox library as a first-class
88
86
  # local process backend alongside InProcessExecutor and ModalEphemeralExecutor. Once done,
89
- # _ProcessBackendAdapter in agents.py can be removed and ProcessIPythonBackend can be used
87
+ # _IPythonBackendAdapter in agents.py can be removed and ProcessIPythonBackend can be used
90
88
  # directly wherever a SandboxBase is expected.
91
89
  class ProcessIPythonBackend:
92
90
  """Backend that executes IPython cells in isolated subprocesses.