-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Expand file tree
/
Copy pathsandbox.py
More file actions
2036 lines (1810 loc) · 79.7 KB
/
sandbox.py
File metadata and controls
2036 lines (1810 loc) · 79.7 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
"""
Modal sandbox (https://modal.com) implementation.
Run `python -m modal setup` to configure Modal locally.
This module provides a Modal-backed sandbox client/session implementation backed by
`modal.Sandbox`.
Note: The `modal` dependency is intended to be optional (installed via an extra),
so package-level exports should guard imports of this module. Within this module,
we import Modal normally so IDEs can resolve and navigate Modal types.
"""
from __future__ import annotations
import asyncio
import functools
import io
import json
import logging
import math
import os
import shlex
import time
import uuid
from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal, TypeVar, cast
import modal
from modal.config import config as modal_config
from modal.container_process import ContainerProcess
from ....sandbox.config import DEFAULT_PYTHON_SANDBOX_IMAGE
from ....sandbox.entries import Mount
from ....sandbox.errors import (
ExecTimeoutError,
ExecTransportError,
ExposedPortUnavailableError,
MountConfigError,
WorkspaceArchiveReadError,
WorkspaceArchiveWriteError,
WorkspaceReadNotFoundError,
WorkspaceStartError,
WorkspaceStopError,
WorkspaceWriteTypeError,
)
from ....sandbox.manifest import Manifest
from ....sandbox.session import SandboxSession, SandboxSessionState
from ....sandbox.session.base_sandbox_session import BaseSandboxSession
from ....sandbox.session.dependencies import Dependencies
from ....sandbox.session.manager import Instrumentation
from ....sandbox.session.pty_types import (
PTY_PROCESSES_MAX,
PTY_PROCESSES_WARNING,
PtyExecUpdate,
allocate_pty_process_id,
clamp_pty_yield_time_ms,
process_id_to_prune_from_meta,
resolve_pty_write_yield_time_ms,
truncate_text_by_tokens,
)
from ....sandbox.session.runtime_helpers import RESOLVE_WORKSPACE_PATH_HELPER, RuntimeHelperScript
from ....sandbox.session.sandbox_client import BaseSandboxClient, BaseSandboxClientOptions
from ....sandbox.snapshot import SnapshotBase, SnapshotSpec, resolve_snapshot
from ....sandbox.types import ExecResult, ExposedPortEndpoint, User
from ....sandbox.util.retry import (
TRANSIENT_HTTP_STATUS_CODES,
exception_chain_contains_type,
exception_chain_has_status_code,
retry_async,
)
from ....sandbox.util.tar_utils import UnsafeTarMemberError, validate_tar_bytes
from ....sandbox.workspace_paths import (
coerce_posix_path,
posix_path_as_path,
posix_path_for_error,
sandbox_path_str,
)
from .mounts import ModalCloudBucketMountStrategy
_DEFAULT_TIMEOUT_S = 30.0
_DEFAULT_IMAGE_TAG = DEFAULT_PYTHON_SANDBOX_IMAGE
_DEFAULT_IMAGE_BUILDER_VERSION = "2025.06"
_DEFAULT_SNAPSHOT_FILESYSTEM_TIMEOUT_S = 60.0
_MODAL_STDIN_CHUNK_SIZE = 8 * 1024 * 1024
_PTY_POLL_INTERVAL_S = 0.05
WorkspacePersistenceMode = Literal["tar", "snapshot_filesystem", "snapshot_directory"]
_WORKSPACE_PERSISTENCE_TAR: WorkspacePersistenceMode = "tar"
_WORKSPACE_PERSISTENCE_SNAPSHOT_FILESYSTEM: WorkspacePersistenceMode = "snapshot_filesystem"
_WORKSPACE_PERSISTENCE_SNAPSHOT_DIRECTORY: WorkspacePersistenceMode = "snapshot_directory"
# Magic prefixes for snapshot payloads that cannot be represented as tar bytes.
_MODAL_SANDBOX_FS_SNAPSHOT_MAGIC = b"MODAL_SANDBOX_FS_SNAPSHOT_V1\n"
_MODAL_SANDBOX_DIR_SNAPSHOT_MAGIC = b"MODAL_SANDBOX_DIR_SNAPSHOT_V1\n"
logger = logging.getLogger(__name__)
R = TypeVar("R")
@asynccontextmanager
async def _override_modal_image_builder_version(
image_builder_version: str | None,
) -> AsyncIterator[None]:
"""Apply a process-local Modal image builder version for the duration of a build."""
if image_builder_version is None:
yield
return
previous_value = os.environ.get("MODAL_IMAGE_BUILDER_VERSION")
modal_config.override_locally("image_builder_version", image_builder_version)
try:
yield
finally:
if previous_value is None:
os.environ.pop("MODAL_IMAGE_BUILDER_VERSION", None)
else:
os.environ["MODAL_IMAGE_BUILDER_VERSION"] = previous_value
def _maybe_set_sandbox_cmd(
image: modal.Image,
*,
use_sleep_cmd: bool,
) -> modal.Image:
if not use_sleep_cmd:
return image
return image.cmd(["sleep", "infinity"])
async def _write_process_stdin(proc: ContainerProcess[bytes], data: bytes | bytearray) -> None:
"""
Stream stdin to Modal in bounded chunks so command-router backed writers do not overflow.
"""
view = memoryview(data)
for start in range(0, len(view), _MODAL_STDIN_CHUNK_SIZE):
proc.stdin.write(view[start : start + _MODAL_STDIN_CHUNK_SIZE])
await proc.stdin.drain.aio()
proc.stdin.write_eof()
await proc.stdin.drain.aio()
class ModalSandboxClientOptions(BaseSandboxClientOptions):
type: Literal["modal"] = "modal"
app_name: str
sandbox_create_timeout_s: float | None = None
workspace_persistence: WorkspacePersistenceMode = _WORKSPACE_PERSISTENCE_TAR
snapshot_filesystem_timeout_s: float | None = None
snapshot_filesystem_restore_timeout_s: float | None = None
exposed_ports: tuple[int, ...] = ()
gpu: str | None = None # Modal GPU type, e.g. "A100" or "H100:8"
timeout: int = 300 # Lifetime of a sandbox from creation in seconds, defaults to 5 minutes
use_sleep_cmd: bool = True
image_builder_version: str | None = _DEFAULT_IMAGE_BUILDER_VERSION
idle_timeout: int | None = None
def __init__(
self,
app_name: str,
sandbox_create_timeout_s: float | None = None,
workspace_persistence: WorkspacePersistenceMode = _WORKSPACE_PERSISTENCE_TAR,
snapshot_filesystem_timeout_s: float | None = None,
snapshot_filesystem_restore_timeout_s: float | None = None,
exposed_ports: tuple[int, ...] = (),
gpu: str | None = None,
timeout: int = 300, # 5 minutes
use_sleep_cmd: bool = True,
image_builder_version: str | None = _DEFAULT_IMAGE_BUILDER_VERSION,
idle_timeout: int | None = None,
*,
type: Literal["modal"] = "modal",
) -> None:
super().__init__(
type=type,
app_name=app_name,
sandbox_create_timeout_s=sandbox_create_timeout_s,
workspace_persistence=workspace_persistence,
snapshot_filesystem_timeout_s=snapshot_filesystem_timeout_s,
snapshot_filesystem_restore_timeout_s=snapshot_filesystem_restore_timeout_s,
exposed_ports=exposed_ports,
gpu=gpu,
timeout=timeout,
use_sleep_cmd=use_sleep_cmd,
image_builder_version=image_builder_version,
idle_timeout=idle_timeout,
)
def _encode_modal_snapshot_ref(
*,
snapshot_id: str,
workspace_persistence: WorkspacePersistenceMode,
) -> bytes:
# Small JSON envelope so we can round-trip a non-tar snapshot reference
# through Snapshot.persist().
body = json.dumps(
{"snapshot_id": snapshot_id, "workspace_persistence": workspace_persistence},
separators=(",", ":"),
sort_keys=True,
).encode("utf-8")
if workspace_persistence == _WORKSPACE_PERSISTENCE_SNAPSHOT_DIRECTORY:
return _MODAL_SANDBOX_DIR_SNAPSHOT_MAGIC + body
return _MODAL_SANDBOX_FS_SNAPSHOT_MAGIC + body
def _encode_snapshot_filesystem_ref(*, snapshot_id: str) -> bytes:
return _encode_modal_snapshot_ref(
snapshot_id=snapshot_id,
workspace_persistence=_WORKSPACE_PERSISTENCE_SNAPSHOT_FILESYSTEM,
)
def _encode_snapshot_directory_ref(*, snapshot_id: str) -> bytes:
return _encode_modal_snapshot_ref(
snapshot_id=snapshot_id,
workspace_persistence=_WORKSPACE_PERSISTENCE_SNAPSHOT_DIRECTORY,
)
def _decode_modal_snapshot_ref(raw: bytes) -> tuple[WorkspacePersistenceMode, str] | None:
if raw.startswith(_MODAL_SANDBOX_DIR_SNAPSHOT_MAGIC):
prefix = _MODAL_SANDBOX_DIR_SNAPSHOT_MAGIC
default_persistence = _WORKSPACE_PERSISTENCE_SNAPSHOT_DIRECTORY
elif raw.startswith(_MODAL_SANDBOX_FS_SNAPSHOT_MAGIC):
prefix = _MODAL_SANDBOX_FS_SNAPSHOT_MAGIC
default_persistence = _WORKSPACE_PERSISTENCE_SNAPSHOT_FILESYSTEM
else:
return None
body = raw[len(prefix) :]
try:
obj = json.loads(body.decode("utf-8"))
except Exception:
return None
snapshot_id = obj.get("snapshot_id")
workspace_persistence = obj.get("workspace_persistence", default_persistence)
if workspace_persistence not in (
_WORKSPACE_PERSISTENCE_SNAPSHOT_FILESYSTEM,
_WORKSPACE_PERSISTENCE_SNAPSHOT_DIRECTORY,
):
return None
if not isinstance(snapshot_id, str) or not snapshot_id:
return None
return cast(WorkspacePersistenceMode, workspace_persistence), snapshot_id
@dataclass(frozen=True)
class ModalImageSelector:
"""
A single "image selector" type to avoid juggling image/image_id/image_tag separately.
"""
kind: Literal["image", "id", "tag"]
value: modal.Image | str
@classmethod
def from_image(cls, image: modal.Image) -> ModalImageSelector:
return cls(kind="image", value=image)
@classmethod
def from_id(cls, image_id: str) -> ModalImageSelector:
return cls(kind="id", value=image_id)
@classmethod
def from_tag(cls, image_tag: str) -> ModalImageSelector:
return cls(kind="tag", value=image_tag)
@dataclass(frozen=True)
class ModalSandboxSelector:
"""
A single "sandbox selector" type to avoid juggling sandbox/sandbox_id separately.
"""
kind: Literal["sandbox", "id"]
value: modal.Sandbox | str
@classmethod
def from_sandbox(cls, sandbox: modal.Sandbox) -> ModalSandboxSelector:
return cls(kind="sandbox", value=sandbox)
@classmethod
def from_id(cls, sandbox_id: str) -> ModalSandboxSelector:
return cls(kind="id", value=sandbox_id)
class ModalSandboxSessionState(SandboxSessionState):
"""
Serializable state for a Modal-backed session.
We store only values that can be safely persisted and later used by `resume()`.
"""
type: Literal["modal"] = "modal"
app_name: str
# Optional Modal image object id (enables reconstructing a custom image via Image.from_id()).
image_id: str | None = None
# Registry image tag (e.g. "debian:bookworm" or "ghcr.io/org/img:tag").
# Used when `image_id` isn't available and no in-memory image override was provided.
image_tag: str | None = None
# Timeout for creating a sandbox (Modal calls are synchronous from the user's perspective
# and can block; we wrap them in a thread with asyncio timeout).
sandbox_create_timeout_s: float = _DEFAULT_TIMEOUT_S
sandbox_id: str | None = None
# Workspace persistence mode:
# - "tar": create a tar stream in the sandbox via `tar cf - ...` and pull bytes back via stdout.
# - "snapshot_filesystem": use Modal's `Sandbox.snapshot_filesystem()`
# (if available) and persist a snapshot reference.
# - "snapshot_directory": use Modal's `Sandbox.snapshot_directory()` on the workspace root
# and reattach it during resume.
workspace_persistence: WorkspacePersistenceMode = _WORKSPACE_PERSISTENCE_TAR
# Async timeouts for snapshot_filesystem-based persistence and restore.
snapshot_filesystem_timeout_s: float = _DEFAULT_SNAPSHOT_FILESYSTEM_TIMEOUT_S
snapshot_filesystem_restore_timeout_s: float = _DEFAULT_SNAPSHOT_FILESYSTEM_TIMEOUT_S
gpu: str | None = None # Modal GPU type, e.g. "A100" or "H100:8"
# Maximum lifetime of the sandbox in seconds
timeout: int = 300 # 5 minutes
use_sleep_cmd: bool = True
image_builder_version: str | None = _DEFAULT_IMAGE_BUILDER_VERSION
idle_timeout: int | None = None
@dataclass
class _ModalPtyProcessEntry:
process: ContainerProcess[bytes]
tty: bool
last_used: float = field(default_factory=time.monotonic)
stdout_iter: AsyncIterator[object] | None = None
stderr_iter: AsyncIterator[object] | None = None
stdout_read_task: asyncio.Task[object] | None = None
stderr_read_task: asyncio.Task[object] | None = None
class ModalSandboxSession(BaseSandboxSession):
"""
SandboxSession implementation backed by a Modal Sandbox.
"""
state: ModalSandboxSessionState
_sandbox: modal.Sandbox | None
_image: modal.Image | None
_running: bool
_pty_lock: asyncio.Lock
_pty_processes: dict[int, _ModalPtyProcessEntry]
_reserved_pty_process_ids: set[int]
_modal_snapshot_ephemeral_backup: bytes | None
_modal_snapshot_ephemeral_backup_path: Path | None
def __init__(
self,
*,
state: ModalSandboxSessionState,
# Optional in-memory handles. These are not guaranteed to be resumable; state holds ids.
image: modal.Image | None = None,
sandbox: modal.Sandbox | None = None,
) -> None:
self.state = state
self._image = None
if image is not None:
self._image = _maybe_set_sandbox_cmd(
image,
use_sleep_cmd=self.state.use_sleep_cmd,
)
self._sandbox = sandbox
if self._image is not None:
self.state.image_id = getattr(self._image, "object_id", self.state.image_id)
if sandbox is not None:
self.state.sandbox_id = getattr(sandbox, "object_id", self.state.sandbox_id)
self._running = False
self._pty_lock = asyncio.Lock()
self._pty_processes = {}
self._reserved_pty_process_ids = set()
self._modal_snapshot_ephemeral_backup = None
self._modal_snapshot_ephemeral_backup_path = None
async def _validate_path_access(self, path: Path | str, *, for_write: bool = False) -> Path:
return await self._validate_remote_path_access(path, for_write=for_write)
def _runtime_helpers(self) -> tuple[RuntimeHelperScript, ...]:
return (RESOLVE_WORKSPACE_PATH_HELPER,)
def _current_runtime_helper_cache_key(self) -> object | None:
return self.state.sandbox_id
@classmethod
def from_state(
cls,
state: ModalSandboxSessionState,
*,
image: modal.Image | None = None,
sandbox: modal.Sandbox | None = None,
) -> ModalSandboxSession:
return cls(state=state, image=image, sandbox=sandbox)
async def _call_modal(
self,
fn: Callable[..., R],
*args: object,
call_timeout: float | None = None,
**kwargs: object,
) -> R:
"""
Prefer Modal's async interface (`fn.aio(...)`) when available.
Falls back to running the blocking call in a thread to preserve compatibility
with SDK surfaces that do not expose `.aio`.
"""
aio_fn = getattr(fn, "aio", None)
if callable(aio_fn):
coro = cast(Awaitable[R], aio_fn(*args, **kwargs))
else:
loop = asyncio.get_running_loop()
bound = functools.partial(fn, *args, **kwargs)
coro = loop.run_in_executor(None, bound)
if call_timeout is None:
return await coro
return await asyncio.wait_for(coro, timeout=call_timeout)
async def _ensure_backend_started(self) -> None:
await self._ensure_sandbox()
async def _prepare_backend_workspace(self) -> None:
# Ensure workspace root exists before the base workspace flow needs it.
root = self._workspace_path_policy().sandbox_root().as_posix()
await self.exec("mkdir", "-p", "--", root, shell=False)
async def _after_start(self) -> None:
self._running = True
async def _after_start_failed(self) -> None:
self._running = False
def _wrap_start_error(self, error: Exception) -> Exception:
if isinstance(error, WorkspaceStartError):
return error
return WorkspaceStartError(path=self._workspace_root_path(), cause=error)
async def _resolve_exposed_port(self, port: int) -> ExposedPortEndpoint:
await self._ensure_sandbox()
assert self._sandbox is not None
try:
tunnels = await asyncio.wait_for(self._sandbox.tunnels.aio(), timeout=10.0)
except Exception as e:
raise ExposedPortUnavailableError(
port=port,
exposed_ports=self.state.exposed_ports,
reason="backend_unavailable",
context={"backend": "modal", "detail": "tunnels_lookup_failed"},
cause=e,
) from e
if not isinstance(tunnels, dict):
raise ExposedPortUnavailableError(
port=port,
exposed_ports=self.state.exposed_ports,
reason="backend_unavailable",
context={"backend": "modal", "detail": "invalid_tunnels_response"},
)
tunnel = tunnels.get(port)
host = getattr(tunnel, "host", None)
host_port = getattr(tunnel, "port", None)
if not isinstance(host, str) or not host or not isinstance(host_port, int):
raise ExposedPortUnavailableError(
port=port,
exposed_ports=self.state.exposed_ports,
reason="backend_unavailable",
context={"backend": "modal", "detail": "port_not_exposed"},
)
return ExposedPortEndpoint(host=host, port=host_port, tls=True)
def _wrap_stop_error(self, error: Exception) -> Exception:
if isinstance(error, WorkspaceStopError):
return error
return WorkspaceStopError(path=self._workspace_root_path(), cause=error)
async def _shutdown_backend(self) -> None:
try:
sandbox = self._sandbox
if sandbox is not None:
await self._call_modal(
sandbox.terminate,
call_timeout=_DEFAULT_TIMEOUT_S,
)
elif self.state.sandbox_id:
sid = self.state.sandbox_id
assert sid is not None
sb = await self._call_modal(
modal.Sandbox.from_id,
sid,
call_timeout=_DEFAULT_TIMEOUT_S,
)
await self._call_modal(
sb.terminate,
call_timeout=_DEFAULT_TIMEOUT_S,
)
except Exception:
pass
finally:
self.state.sandbox_id = None
self.state.workspace_root_ready = False
self._sandbox = None
self._running = False
async def _ensure_sandbox(self) -> bool:
if self._sandbox is not None:
return False
# If resuming, try to rehydrate the sandbox handle from the persisted id.
sid = self.state.sandbox_id
if sid:
try:
sb = await self._call_modal(
modal.Sandbox.from_id,
sid,
call_timeout=self.state.sandbox_create_timeout_s,
)
# `poll()` returns an exit code when the sandbox is terminated, else None.
poll_result = await self._call_modal(sb.poll, call_timeout=_DEFAULT_TIMEOUT_S)
is_running = poll_result is None
if is_running:
self._sandbox = sb
self._running = True
return True
except Exception:
pass
# Resumed sandbox handle is dead or invalid; clear and create a fresh one.
self._sandbox = None
self.state.sandbox_id = None
app = await self._call_modal(
modal.App.lookup,
self.state.app_name,
create_if_missing=True,
call_timeout=10.0,
)
if not self._image:
image_id = self.state.image_id
if image_id:
self._image = modal.Image.from_id(image_id)
else:
tag = self.state.image_tag
if not isinstance(tag, str) or not tag:
tag = _DEFAULT_IMAGE_TAG
# Record the default for better debuggability/resume.
self.state.image_tag = tag
self._image = await self._call_modal(
modal.Image.from_registry,
tag,
call_timeout=_DEFAULT_TIMEOUT_S,
)
self._image = _maybe_set_sandbox_cmd(
self._image,
use_sleep_cmd=self.state.use_sleep_cmd,
)
manifest_envs = cast(dict[str, str | None], await self.state.manifest.environment.resolve())
volumes = self._modal_cloud_bucket_mounts_for_manifest()
create_coro = modal.Sandbox.create.aio(
app=app,
image=self._image,
workdir=self.state.manifest.root,
env=manifest_envs,
encrypted_ports=self.state.exposed_ports,
volumes=volumes,
gpu=self.state.gpu,
timeout=self.state.timeout,
idle_timeout=self.state.idle_timeout,
)
async with _override_modal_image_builder_version(self.state.image_builder_version):
if self.state.sandbox_create_timeout_s is None:
self._sandbox = await create_coro
else:
self._sandbox = await asyncio.wait_for(
create_coro, timeout=self.state.sandbox_create_timeout_s
)
# Persist sandbox id for future resume.
assert self._sandbox is not None
self.state.sandbox_id = self._sandbox.object_id
self.state.workspace_root_ready = False
assert self._image is not None
self.state.image_id = self._image.object_id
return False
async def snapshot_filesystem(self) -> str:
"""Snapshot the current sandbox filesystem and return the resulting Modal image ID.
The returned ID can be passed as ``image_id`` when creating a new sandbox to boot
from this filesystem state. The image ID is also stored in ``state.image_id`` for future
resume.
"""
await self._ensure_sandbox()
assert self._sandbox is not None
snap_coro = self._sandbox.snapshot_filesystem.aio()
if self.state.snapshot_filesystem_timeout_s is None:
snap = await snap_coro
else:
snap = await asyncio.wait_for(
snap_coro, timeout=self.state.snapshot_filesystem_timeout_s
)
image_id: str | None
if isinstance(snap, str):
image_id = snap
else:
image_id = getattr(snap, "object_id", None) or getattr(snap, "id", None)
if not isinstance(image_id, str) or not image_id:
raise RuntimeError(
f"snapshot_filesystem returned unexpected type: {type(snap).__name__}"
)
self.state.image_id = image_id
self._image = modal.Image.from_id(image_id)
return image_id
async def _exec_internal(
self, *command: str | Path, timeout: float | None = None
) -> ExecResult:
await self._ensure_sandbox()
assert self._sandbox is not None
modal_timeout: int | None = None
if timeout is not None:
# Modal's Sandbox.exec timeout is integer seconds; use ceil so the command
# is guaranteed to be terminated server-side at or before our timeout window
# (modulo 1s granularity).
modal_timeout = int(max(_DEFAULT_TIMEOUT_S, math.ceil(timeout)))
async def _run_async() -> ExecResult:
assert self._sandbox is not None
argv: tuple[str, ...] = tuple(str(part) for part in command)
proc = await self._sandbox.exec.aio(*argv, text=False, timeout=modal_timeout)
# Drain full output; Modal buffers process output server-side.
stdout = await proc.stdout.read.aio()
stderr = await proc.stderr.read.aio()
exit_code = await proc.wait.aio()
return ExecResult(stdout=stdout or b"", stderr=stderr or b"", exit_code=exit_code or 0)
try:
run_coro = _run_async()
if timeout is None:
return await run_coro
return await asyncio.wait_for(run_coro, timeout=timeout)
except asyncio.TimeoutError as e:
sandbox = self._sandbox
if sandbox is not None:
try:
await self._call_modal(sandbox.terminate, call_timeout=_DEFAULT_TIMEOUT_S)
except Exception:
pass
self._sandbox = None
self.state.sandbox_id = None
self._running = False
raise ExecTimeoutError(command=command, timeout_s=timeout, cause=e) from e
except ExecTimeoutError:
raise
except Exception as e:
raise ExecTransportError(command=command, cause=e) from e
def supports_pty(self) -> bool:
return True
async def pty_exec_start(
self,
*command: str | Path,
timeout: float | None = None,
shell: bool | list[str] = True,
user: str | User | None = None,
tty: bool = False,
yield_time_s: float | None = None,
max_output_tokens: int | None = None,
) -> PtyExecUpdate:
await self._ensure_sandbox()
assert self._sandbox is not None
sanitized_command = self._prepare_exec_command(*command, shell=shell, user=user)
argv: tuple[str, ...] = tuple(str(part) for part in sanitized_command)
modal_timeout: int | None = None
if timeout is not None:
modal_timeout = int(max(_DEFAULT_TIMEOUT_S, math.ceil(timeout)))
entry: _ModalPtyProcessEntry | None = None
registered = False
pruned_entry: _ModalPtyProcessEntry | None = None
process_id = 0
process_count = 0
try:
process = cast(
Any,
await self._call_modal(
self._sandbox.exec,
*argv,
text=False,
timeout=modal_timeout,
pty=tty,
),
)
entry = _ModalPtyProcessEntry(process=process, tty=tty)
async with self._pty_lock:
process_id = allocate_pty_process_id(self._reserved_pty_process_ids)
self._reserved_pty_process_ids.add(process_id)
pruned_entry = await self._prune_pty_processes_if_needed()
self._pty_processes[process_id] = entry
registered = True
process_count = len(self._pty_processes)
except asyncio.TimeoutError as e:
if entry is not None and not registered:
await self._terminate_pty_entry(entry)
raise ExecTimeoutError(command=command, timeout_s=timeout, cause=e) from e
except asyncio.CancelledError:
if entry is not None and not registered:
await self._terminate_pty_entry(entry)
raise
except Exception as e:
if entry is not None and not registered:
await self._terminate_pty_entry(entry)
raise ExecTransportError(command=command, cause=e) from e
if pruned_entry is not None:
await self._terminate_pty_entry(pruned_entry)
if process_count >= PTY_PROCESSES_WARNING:
logger.warning(
"PTY process count reached warning threshold: %s active sessions",
process_count,
)
yield_time_ms = 10_000 if yield_time_s is None else int(yield_time_s * 1000)
output, original_token_count = await self._collect_pty_output(
entry=entry,
yield_time_ms=clamp_pty_yield_time_ms(yield_time_ms),
max_output_tokens=max_output_tokens,
)
return await self._finalize_pty_update(
process_id=process_id,
entry=entry,
output=output,
original_token_count=original_token_count,
)
async def pty_write_stdin(
self,
*,
session_id: int,
chars: str,
yield_time_s: float | None = None,
max_output_tokens: int | None = None,
) -> PtyExecUpdate:
async with self._pty_lock:
entry = self._resolve_pty_session_entry(
pty_processes=self._pty_processes,
session_id=session_id,
)
if chars:
if not entry.tty:
raise RuntimeError("stdin is not available for this process")
await self._write_pty_stdin(entry.process, chars.encode("utf-8"))
await asyncio.sleep(0.1)
yield_time_ms = 250 if yield_time_s is None else int(yield_time_s * 1000)
output, original_token_count = await self._collect_pty_output(
entry=entry,
yield_time_ms=resolve_pty_write_yield_time_ms(
yield_time_ms=yield_time_ms, input_empty=chars == ""
),
max_output_tokens=max_output_tokens,
)
entry.last_used = time.monotonic()
return await self._finalize_pty_update(
process_id=session_id,
entry=entry,
output=output,
original_token_count=original_token_count,
)
async def pty_terminate_all(self) -> None:
async with self._pty_lock:
entries = list(self._pty_processes.values())
self._pty_processes.clear()
self._reserved_pty_process_ids.clear()
for entry in entries:
await self._terminate_pty_entry(entry)
async def _write_pty_stdin(self, process: ContainerProcess[bytes], payload: bytes) -> None:
stdin = process.stdin
write = getattr(stdin, "write", None)
if not callable(write):
raise RuntimeError("stdin is not writable for this process")
await self._call_modal(write, payload, call_timeout=5.0)
drain = getattr(stdin, "drain", None)
if callable(drain):
await self._call_modal(drain, call_timeout=5.0)
async def _collect_pty_output(
self,
*,
entry: _ModalPtyProcessEntry,
yield_time_ms: int,
max_output_tokens: int | None,
) -> tuple[bytes, int | None]:
deadline = time.monotonic() + (yield_time_ms / 1000)
chunks = bytearray()
while True:
stdout_chunk = await self._read_modal_stream(entry=entry, stream_name="stdout")
stderr_chunk = await self._read_modal_stream(entry=entry, stream_name="stderr")
if stdout_chunk:
chunks.extend(stdout_chunk)
if stderr_chunk:
chunks.extend(stderr_chunk)
if time.monotonic() >= deadline:
break
exit_code = await self._peek_exit_code(entry.process)
if exit_code is not None:
stdout_chunks = await self._drain_modal_stream(entry=entry, stream_name="stdout")
stderr_chunks = await self._drain_modal_stream(entry=entry, stream_name="stderr")
chunks.extend(stdout_chunks)
chunks.extend(stderr_chunks)
break
if not stdout_chunk and not stderr_chunk:
remaining_s = deadline - time.monotonic()
if remaining_s <= 0:
break
await asyncio.sleep(min(_PTY_POLL_INTERVAL_S, remaining_s))
text = chunks.decode("utf-8", errors="replace")
truncated_text, original_token_count = truncate_text_by_tokens(text, max_output_tokens)
return truncated_text.encode("utf-8", errors="replace"), original_token_count
async def _drain_modal_stream(
self,
*,
entry: _ModalPtyProcessEntry,
stream_name: Literal["stdout", "stderr"],
) -> bytes:
chunks = bytearray()
while True:
chunk = await self._read_modal_stream(
entry=entry,
stream_name=stream_name,
await_pending=True,
)
if not chunk:
break
chunks.extend(chunk)
return bytes(chunks)
async def _read_modal_stream(
self,
*,
entry: _ModalPtyProcessEntry,
stream_name: Literal["stdout", "stderr"],
await_pending: bool = False,
) -> bytes:
stream = entry.process.stdout if stream_name == "stdout" else entry.process.stderr
if stream is None:
return b""
iter_attr = "stdout_iter" if stream_name == "stdout" else "stderr_iter"
task_attr = "stdout_read_task" if stream_name == "stdout" else "stderr_read_task"
stream_iter = getattr(entry, iter_attr)
if stream_iter is None:
aiter_method = getattr(stream, "__aiter__", None)
if callable(aiter_method):
try:
stream_iter = aiter_method()
except Exception:
stream_iter = None
else:
setattr(entry, iter_attr, stream_iter)
task = getattr(entry, task_attr)
if task is None and stream_iter is not None:
task = asyncio.create_task(stream_iter.__anext__())
setattr(entry, task_attr, task)
if task is not None:
wait_timeout = 0.2 if await_pending else 0
done, _pending = await asyncio.wait({task}, timeout=wait_timeout)
if not done:
return b""
setattr(entry, task_attr, None)
try:
value = task.result()
except StopAsyncIteration:
setattr(entry, iter_attr, None)
return b""
except Exception:
setattr(entry, iter_attr, None)
return b""
return self._coerce_modal_stream_chunk(value)
read = getattr(stream, "read", None)
if not callable(read):
return b""
try:
value = await self._call_modal(read, 16_384, call_timeout=0.2)
except TypeError:
return b""
except Exception:
return b""
return self._coerce_modal_stream_chunk(value)
def _coerce_modal_stream_chunk(self, value: object) -> bytes:
if value is None:
return b""
if isinstance(value, bytes):
return value
if isinstance(value, bytearray):
return bytes(value)
if isinstance(value, str):
return value.encode("utf-8", errors="replace")
return str(value).encode("utf-8", errors="replace")
async def _finalize_pty_update(
self,
*,
process_id: int,
entry: _ModalPtyProcessEntry,
output: bytes,
original_token_count: int | None,
) -> PtyExecUpdate:
exit_code = await self._peek_exit_code(entry.process)
live_process_id: int | None = process_id
if exit_code is not None:
async with self._pty_lock:
removed = self._pty_processes.pop(process_id, None)
self._reserved_pty_process_ids.discard(process_id)
if removed is not None:
await self._terminate_pty_entry(removed)
live_process_id = None
return PtyExecUpdate(
process_id=live_process_id,
output=output,
exit_code=exit_code,
original_token_count=original_token_count,
)
async def _prune_pty_processes_if_needed(self) -> _ModalPtyProcessEntry | None:
if len(self._pty_processes) < PTY_PROCESSES_MAX:
return None
meta: list[tuple[int, float, bool]] = []
for process_id, entry in self._pty_processes.items():
exit_code = await self._peek_exit_code(entry.process)
meta.append((process_id, entry.last_used, exit_code is not None))
process_id_to_prune = process_id_to_prune_from_meta(meta)
if process_id_to_prune is None:
return None
self._reserved_pty_process_ids.discard(process_id_to_prune)
return self._pty_processes.pop(process_id_to_prune, None)
async def _peek_exit_code(self, process: ContainerProcess[bytes]) -> int | None:
try:
value = await self._call_modal(process.poll, call_timeout=0.2)
except Exception:
return None
if value is None:
return None
if isinstance(value, int):
return value
try:
return int(value)
except (TypeError, ValueError):
return None
async def _terminate_pty_entry(self, entry: _ModalPtyProcessEntry) -> None:
process = entry.process
for task in (entry.stdout_read_task, entry.stderr_read_task):
if task is not None and not task.done():
task.cancel()
try:
terminated = False
terminate = getattr(process, "terminate", None)
if callable(terminate):