-
Notifications
You must be signed in to change notification settings - Fork 0
#minor: Implement Modal sandbox provider #66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tthuwng
wants to merge
3
commits into
main
Choose a base branch
from
ht/modal-adapter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,46 +1,246 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import AsyncGenerator, Mapping | ||
| from typing import Literal | ||
| import asyncio | ||
| import shlex | ||
| from collections.abc import AsyncGenerator | ||
| from typing import Any, Literal | ||
|
|
||
| from modal import App, Client, Image | ||
| from modal import Sandbox as ModalSdkSandbox | ||
| from modal.exception import ConnectionError as ModalConnectionError | ||
| from modal.exception import Error as ModalError | ||
| from modal.exception import NotFoundError as ModalNotFoundError | ||
| from pydantic import BaseModel | ||
| from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed | ||
|
|
||
| from benchmark_service.sandbox.types import ( | ||
| ExecResult, | ||
| ImageSource, | ||
| Sandbox, | ||
| SandboxCommandError, | ||
| SandboxConnectionError, | ||
| SandboxCreateRequest, | ||
| SandboxError, | ||
| SandboxNotFoundError, | ||
| SandboxProvider, | ||
| SandboxQuery, | ||
| ) | ||
|
|
||
| _APP_NAME = "benchmark-service" | ||
| # Modal terminates a sandbox when its entrypoint exits, so keep a long-lived | ||
| # entrypoint and run task commands through exec. | ||
| _KEEPALIVE = ("/bin/sh", "-lc", "while true; do sleep 3600; done") | ||
| # Adapter-owned max sandbox lifetime; Modal defaults to 5 minutes otherwise. | ||
| _MAX_LIFETIME_SECONDS = 24 * 60 * 60 | ||
|
|
||
|
|
||
| _PROVIDER_RETRY = retry( | ||
| retry=retry_if_exception_type(SandboxConnectionError), | ||
| stop=stop_after_attempt(3), | ||
| wait=wait_fixed(2), | ||
| reraise=True, | ||
| ) | ||
|
|
||
|
|
||
| class ModalProviderConfig(BaseModel): | ||
| type: Literal["modal"] = "modal" | ||
|
|
||
| @classmethod | ||
| def from_headers(cls, headers: Mapping[str, str]) -> "ModalProviderConfig": | ||
| return cls() | ||
| MODAL_TOKEN_ID: str | ||
| MODAL_TOKEN_SECRET: str | ||
| MODAL_ENVIRONMENT: str | None = None | ||
|
|
||
| def create_provider(self) -> SandboxProvider: | ||
| return ModalSandboxProvider(self) | ||
|
|
||
|
|
||
| def _sandbox_error(exc: ModalError) -> SandboxError: | ||
| if isinstance(exc, ModalNotFoundError): | ||
| return SandboxNotFoundError(str(exc)) | ||
| if isinstance(exc, ModalConnectionError): | ||
| return SandboxConnectionError(str(exc)) | ||
| return SandboxError(str(exc)) | ||
|
|
||
|
|
||
| def _command(command: str, cwd: str | None, timeout: float | None) -> str: | ||
| # Mirrors the Daytona adapter: a timed-out command exits with code 124 | ||
| # instead of raising, and cwd wraps the timeout prefix. stderr is merged | ||
| # into stdout to match the combined PTY output of the Daytona adapter. | ||
| if timeout is not None: | ||
| command = f"timeout {timeout:g} {command}" | ||
| if cwd: | ||
| command = f"cd {shlex.quote(cwd)} && {command}" | ||
| return f"{{ {command} ; }} 2>&1" | ||
|
|
||
|
|
||
| class ModalSandbox(Sandbox): | ||
| def __init__(self, sandbox: ModalSdkSandbox, name: str | None = None) -> None: | ||
| self._sandbox = sandbox | ||
| self._name = name | ||
|
|
||
| @property | ||
| def id(self) -> str: | ||
| return self._sandbox.object_id | ||
|
|
||
| @property | ||
| def name(self) -> str: | ||
| return self._name or self._sandbox.object_id | ||
|
|
||
| @property | ||
| def state(self) -> str: | ||
| # Modal does not expose a cached lifecycle state on the sandbox handle. | ||
| return "unknown" | ||
|
|
||
| async def exec( | ||
| self, | ||
| command: str, | ||
| *, | ||
| cwd: str | None = None, | ||
| timeout: float | None = None, | ||
| ) -> ExecResult: | ||
| process = await self._start_process(command, cwd=cwd, timeout=timeout) | ||
| try: | ||
| output = "".join([str(chunk) async for chunk in process.stdout]) | ||
| exit_code = await process.wait.aio() | ||
| except ModalError as exc: | ||
| raise _sandbox_error(exc) from exc | ||
| return ExecResult(exit_code=exit_code, output=output) | ||
|
|
||
| @_PROVIDER_RETRY | ||
| async def _start_process(self, command: str, *, cwd: str | None, timeout: float | None) -> Any: | ||
| try: | ||
| return await self._sandbox.exec.aio("/bin/sh", "-lc", _command(command, cwd, timeout), text=True) | ||
| except ModalError as exc: | ||
| raise _sandbox_error(exc) from exc | ||
|
|
||
| async def command( | ||
| self, | ||
| command: str, | ||
| *, | ||
| cwd: str | None = None, | ||
| timeout: float | None = None, | ||
| ) -> AsyncGenerator[str, None]: | ||
| process = await self._start_process(command, cwd=cwd, timeout=timeout) | ||
|
|
||
| try: | ||
| async for chunk in process.stdout: | ||
| yield str(chunk) | ||
| exit_code = await process.wait.aio() | ||
| except ModalError as exc: | ||
| raise _sandbox_error(exc) from exc | ||
|
|
||
| if exit_code != 0: | ||
| raise SandboxCommandError(exit_code) | ||
|
|
||
| @_PROVIDER_RETRY | ||
| async def upload_file(self, remote_path: str, content: bytes) -> None: | ||
| try: | ||
| await asyncio.to_thread(self._sandbox.filesystem.write_bytes, content, remote_path) | ||
| except ModalError as exc: | ||
| raise _sandbox_error(exc) from exc | ||
|
|
||
| @_PROVIDER_RETRY | ||
| async def download_file(self, remote_path: str) -> bytes: | ||
| try: | ||
| content = await asyncio.to_thread(self._sandbox.filesystem.read_bytes, remote_path) | ||
| except ModalError as exc: | ||
| raise _sandbox_error(exc) from exc | ||
| return bytes(content) | ||
|
|
||
|
|
||
| class ModalSandboxProvider(SandboxProvider): | ||
| def __init__(self, config: ModalProviderConfig) -> None: | ||
| self._config = config | ||
| self._client: Client | None = None | ||
| self._app: App | None = None | ||
|
|
||
| async def _connect(self) -> tuple[Client, App]: | ||
| if self._client is None or self._app is None: | ||
| try: | ||
| client = await Client.from_credentials.aio(self._config.MODAL_TOKEN_ID, self._config.MODAL_TOKEN_SECRET) | ||
| self._app = await App.lookup.aio( | ||
| _APP_NAME, | ||
| client=client, | ||
| environment_name=self._config.MODAL_ENVIRONMENT, | ||
| create_if_missing=True, | ||
| ) | ||
| self._client = client | ||
| except ModalError as exc: | ||
| raise _sandbox_error(exc) from exc | ||
| return self._client, self._app | ||
|
|
||
| @_PROVIDER_RETRY | ||
| async def create_sandbox(self, request: SandboxCreateRequest) -> Sandbox: | ||
| raise SandboxError("Modal sandbox provider is not implemented") | ||
| if not isinstance(request.source, ImageSource): | ||
| raise SandboxError(f"Modal sandbox provider does not support source type {request.source.type!r}") | ||
| client, app = await self._connect() | ||
| image = Image.from_registry(request.source.image) # pyright: ignore[reportUnknownMemberType] | ||
| create_kwargs: dict[str, Any] = { | ||
| "app": app, | ||
| "name": request.name, | ||
| "image": image, | ||
| "env": dict(request.env_vars), | ||
| "tags": request.labels, | ||
| "cpu": float(request.resources.vcpu), | ||
| "memory": request.resources.memory * 1024, | ||
| "idle_timeout": request.auto_stop_interval * 60 if request.auto_stop_interval else None, | ||
| "timeout": _MAX_LIFETIME_SECONDS, | ||
| "client": client, | ||
| } | ||
| if request.resources.enable_docker: | ||
| create_kwargs["experimental_options"] = {"enable_docker": True} | ||
|
|
||
| try: | ||
| # Modal sandboxes have no disk parameter; request.resources.disk is | ||
| # accepted but not enforced. memory is MiB, cpu is fractional cores. | ||
| inner = await asyncio.wait_for( | ||
| ModalSdkSandbox.create.aio( # pyright: ignore[reportUnknownMemberType] | ||
| *_KEEPALIVE, | ||
| **create_kwargs, | ||
| ), | ||
| timeout=request.create_timeout, | ||
| ) | ||
| except TimeoutError as exc: | ||
| raise SandboxError(f"Failed to create Modal sandbox within {request.create_timeout}s") from exc | ||
| except ModalError as exc: | ||
| raise _sandbox_error(exc) from exc | ||
| return ModalSandbox(inner, name=request.name) | ||
|
|
||
| @_PROVIDER_RETRY | ||
| async def get_sandbox(self, instance_id: str) -> Sandbox: | ||
| raise SandboxError("Modal sandbox provider is not implemented") | ||
| client, _ = await self._connect() | ||
| try: | ||
| inner = await ModalSdkSandbox.from_id.aio(instance_id, client=client) | ||
| except ModalError as exc: | ||
| raise _sandbox_error(exc) from exc | ||
| return ModalSandbox(inner) | ||
|
|
||
| @_PROVIDER_RETRY | ||
| async def delete_sandbox(self, instance_id: str) -> None: | ||
| raise SandboxError("Modal sandbox provider is not implemented") | ||
| client, _ = await self._connect() | ||
| try: | ||
| inner = await ModalSdkSandbox.from_id.aio(instance_id, client=client) | ||
| await inner.terminate.aio() | ||
| except ModalNotFoundError: | ||
| return | ||
| except ModalError as exc: | ||
| raise _sandbox_error(exc) from exc | ||
|
|
||
| async def list_sandboxes(self, query: SandboxQuery) -> AsyncGenerator[Sandbox, None]: | ||
| raise SandboxError("Modal sandbox provider is not implemented") | ||
| yield | ||
| for inner in await self._list_sandboxes(query): | ||
| yield ModalSandbox(inner) | ||
|
|
||
| @_PROVIDER_RETRY | ||
| async def _list_sandboxes(self, query: SandboxQuery) -> list[ModalSdkSandbox]: | ||
| client, app = await self._connect() | ||
| try: | ||
| return [ | ||
| inner | ||
| async for inner in ModalSdkSandbox.list.aio(app_id=app.app_id, tags=query.labels or None, client=client) | ||
| ] | ||
| except ModalError as exc: | ||
| raise _sandbox_error(exc) from exc | ||
|
|
||
| async def close(self) -> None: | ||
| pass | ||
| if self._client is not None: | ||
| await self._client._close.aio() # pyright: ignore[reportPrivateUsage, reportUnknownMemberType] | ||
| self._client = None | ||
| self._app = None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How does modal use this? do they not have support for docker?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Modal sandboxes don't run a Docker daemon by default.
enable_docker=Truemaps to Modal'sexperimental_options={"enable_docker": True}(see modal.py:196), which provisions a sandbox that permits nested Docker (Docker-in-Docker). CBS only requests the capability — it does not startdockerdor run containers; that's the benchmark service's job (e.g. VCB startsdockerd+docker composeinside the sandbox). The field is provider-generic: providers without nested-Docker support just ignore it. Expanded the field description in 49ed755.