Repository navigation
feat(sandbox): add Modal provider - #4237
reinainblood wants to merge 5 commits into
Conversation
|
@ananthsub thank you for inviting this upstream on the fork PR. This is the provider-only PR rebuilt on current |
|
/ok to test 317d454 |
| effective_user = user if user is not None else self._exec.user | ||
| if effective_user is None: | ||
| return [*self._exec.shell, command] | ||
| if not self._exec.allow_user_rewrite: |
There was a problem hiding this comment.
user="root" (and user=0) raises ValueError under the shipped defaults, which breaks the sandbox-backed agents already in the repo. anyswe_agent, anyterminal_agent, terminus_2_sandboxed_agent, the terminal_bench_4 verifier and the docker-compose adapter all pass user="root" on their exec and grading paths, so none of them can run on this provider without also setting exec.allow_user_rewrite: true. Even with that option on, root goes through su, which needs su to exist in the image.
Modal containers already run as root by default, so root can be a no-op, which is what the Daytona provider does (nemo_gym/sandbox/providers/daytona/provider.py#L940-L945). Could _shell_argv treat None, "root" and 0 as "no rewrite", and only require allow_user_rewrite for other users? The Fern page should also state the limitation for non-root users, since today only the README's security section hints at it.
| # A cancelled command must not mutate a subsequent evaluation step. | ||
| await asyncio.shield(self.close(handle)) | ||
| raise | ||
| except types["exec_timeout"] as exc: |
There was a problem hiding this comment.
Two contract differences from the other providers here. The facade documents that a command timeout is reported as a result with error_type="timeout" rather than raised (nemo_gym/sandbox/api.py#L256-L258), and the docker, apptainer, enroot, local, openshell, daytona and opensandbox providers all return SandboxExecResult(error_type="timeout", return_code=125). E2B is the only provider that raises. Callers branch on this: anyswe_agent/app.py#L418 and anyterminal_agent/app.py#L602 check error_type in ("timeout", "sandbox"), so on Modal an evaluation timeout lands in their generic except Exception and is recorded as a sandbox failure instead of a timeout.
Similarly, the sandbox_gone branch returns error_type="sandbox_terminated" with return code -1, a value no caller checks (siblings use "sandbox" with 125). The branch also looks unreachable with the real Modal client: SandboxTerminatedError and SandboxTimeoutError are only raised by Sandbox.wait() and Sandbox.tunnels(). In modal 1.6.1, ContainerProcess.wait() returns -1 on an exec deadline and otherwise raises InvalidError, and a task that shuts down mid-exec surfaces as NotFoundError (modal/_utils/task_command_router_client.py#L881-L886), while exec on an already-finished sandbox raises ConflictError. Could the timeout return the standard result, and could NotFoundError / ConflictError / ClientClosed from exec map to error_type="sandbox"? Returning the partial stdout and stderr that Modal already collected before the deadline would also help agents.
| if not task.done(): | ||
| task.cancel() | ||
| await asyncio.gather(*tasks, return_exceptions=True) | ||
| except asyncio.CancelledError: |
There was a problem hiding this comment.
Cancelling an exec closes the whole sandbox. The reasoning in the comment is sound, since Modal has no public call to kill one exec process, but it has a consequence for callers that wrap exec in their own deadline. The terminal_bench_4 verifier does asyncio.wait_for(...) and then calls download_dir on the same sandbox to keep diagnostics (resources_servers/terminal_bench_4/verifier.py#L99-L108). On Modal that download always fails with "has been closed", so the verifier logs are lost.
A less destructive option is to start the command in its own process group, recording the group id, and on cancellation kill that group through a second exec, closing the sandbox only if the kill fails. If you would rather keep the current behaviour, it would be worth stating on the Fern page that a client-side timeout destroys the sandbox, since the other providers leave it usable.
| except asyncio.CancelledError: | ||
| # Modal has no public kill method for an individual exec process. | ||
| # A cancelled command must not mutate a subsequent evaluation step. | ||
| await asyncio.shield(self.close(handle)) |
There was a problem hiding this comment.
If close() raises here (the 60 second close_timeout_s expiring, or a transport error after retries), that exception propagates in place of the CancelledError. A caller using asyncio.timeout() then sees the cleanup error instead of a TimeoutError, so for example the terminal_bench_4 verifier would not raise VerifierTimeoutError. The same pattern is in _file_operation at line 868, where the cleanup failure also hides the original TimeoutError. The create path already handles this correctly at lines 650-657 by logging the cleanup failure and re-raising the original exception. Could these two sites do the same?
| else: | ||
| entrypoint = [*self._create.keepalive_shell, self._create.keepalive_cmd] | ||
|
|
||
| create_task = asyncio.create_task(modal.Sandbox.create.aio(*entrypoint, **kwargs)) |
There was a problem hiding this comment.
Sandbox.create has no client-side deadline, and ready_timeout_s only covers the readiness probe that runs after it returns. With modal 1.6.1 the call blocks until the sandbox is scheduled (up to 21 minutes on the path GPU sandboxes take, modal/sandbox.py#L99 and #L604-L616), and the first create from a registry image also pulls it. base.py#L206-L213 says providers should raise SandboxCreateError if the sandbox cannot become ready before the configured timeout. On modal 1.5.5, which the pin allows, create returns before scheduling and the probe bounds it, so behaviour also differs across the supported range.
The cancellation path (sandbox = await create_task) is unbounded for the same reason. Could the whole create be bounded by ready_timeout_s, or alternatively could the docs (README.md#L81 and modal.mdx#L83, which say it bounds the whole readiness operation) be narrowed to say it covers only the probe?
| LOGGER.warning("modal sandbox %s cleanup after failed create raised: %s", handle.sandbox_id, exc) | ||
|
|
||
| async def _verify_created_handle(self, handle: SandboxHandle, *, ready_timeout_s: float | None) -> None: | ||
| deadline_s = ready_timeout_s if ready_timeout_s is not None else self._probe.deadline_s |
There was a problem hiding this comment.
The outer asyncio.timeout(deadline_s) uses the same deadline as the loop inside _run_readiness_probe, so it always fires first and the loop's own error, which includes the last return code and stderr (lines 724-728), is never produced. Line 725 is not covered by any test. The resulting message is only "did not pass readiness probe within Ns", with no hint why. Giving the outer timeout a small grace period, or keeping the last probe detail on the instance and including it in this message, would make failures like a missing /bin/sh diagnosable. The cancellation lands inside exec, which then runs the shielded close, so create() can also overrun ready_timeout_s by up to close_timeout_s.
| async def test_create_failure_is_wrapped_and_never_retried(self, fake_modal): | ||
| modal, created = fake_modal() | ||
| boom = modal.exception.ServiceError("region full") | ||
| modal, created = fake_modal(create_exc=boom) | ||
| provider = _provider(operations={"retries": 3}) | ||
| with pytest.raises(ModalCreateError, match="region full"): | ||
| await provider.create(_spec()) | ||
| assert created == [] |
There was a problem hiding this comment.
This test cannot fail for the behaviour its name describes: the fake raises before it appends to created, so created == [] is true no matter how many times Sandbox.create is called. A change wrapping Sandbox.create in _with_retries still passes (ServiceError is a retryable class), and that is exactly the billable-sandbox leak the comment at provider.py#L644-L645 guards against. This version counts calls, and was run locally against the PR head and kills that mutation:
| async def test_create_failure_is_wrapped_and_never_retried(self, fake_modal): | |
| modal, created = fake_modal() | |
| boom = modal.exception.ServiceError("region full") | |
| modal, created = fake_modal(create_exc=boom) | |
| provider = _provider(operations={"retries": 3}) | |
| with pytest.raises(ModalCreateError, match="region full"): | |
| await provider.create(_spec()) | |
| assert created == [] | |
| async def test_create_failure_is_wrapped_and_never_retried(self, fake_modal): | |
| modal, _ = fake_modal() | |
| calls = 0 | |
| async def failing_create(*entrypoint, **kwargs): | |
| nonlocal calls | |
| calls += 1 | |
| raise modal.exception.ServiceError("region full") | |
| modal.Sandbox.create = _Aio(failing_create) | |
| provider = _provider(operations={"retries": 3}) | |
| with pytest.raises(ModalCreateError, match="region full"): | |
| await provider.create(_spec()) | |
| assert calls == 1 | |
| with pytest.raises(TimeoutError): | ||
| await provider.exec(handle, "weird", timeout_s=30) | ||
|
|
||
| async def test_sandbox_terminated_mid_command_is_reported_without_exit_code(self, fake_modal): |
There was a problem hiding this comment.
This fake makes wait() raise SandboxTerminatedError, which the real Modal client never does from ContainerProcess.wait() (see the comment on the exec result handling in provider.py). The green test therefore proves a branch that cannot run in production. More generally, the fake exception classes are all flat Exception subclasses, whereas in the real library ConflictError is an InvalidError and the timeout errors subclass Modal's TimeoutError, so mistakes in the order of except clauses would not show up. Could the fake use the real exception classes (the surface test already imports the real module), and the test be rewritten around NotFoundError / ConflictError? The FakeStdin, mkdirs and cat pieces of the fake also look left over from an earlier implementation and are not used by the provider.
| ], | ||
| ) | ||
| async def test_endpoint_uses_real_sdk_tunnel_semantics(fake_modal, mode, expected): | ||
| from modal import Tunnel |
There was a problem hiding this comment.
test_endpoint_uses_real_sdk_tunnel_semantics imports modal directly, and test_closed_handle_status_works_with_real_sdk_without_authentication reaches it through _require_modal(). Simulating an environment without Modal (sys.modules["modal"] = None) makes these four parametrised cases fail instead of skip, while the rest of the file skips cleanly. CLAUDE.md asks for tests to skip when an external dependency is missing, and test_e2b_provider.py uses pytest.importorskip inside the test for this. CI is unaffected because the sandbox job installs the extra, but a local run without it would fail. Could both tests start with pytest.importorskip("modal")?
| | `image` | Required OCI image reference. Pin a digest for reproducible runs. | | ||
| | `entrypoint` | Overrides the image command; omitted values use a POSIX keepalive. | | ||
| | `ttl_s` | Hard lifetime, positive and no more than 24 hours. | | ||
| | `ready_timeout_s` | Overall provider readiness deadline. | |
There was a problem hiding this comment.
ready_timeout_s is described as the overall readiness deadline, but it only bounds the readiness probe that runs after Sandbox.create returns; image pull and scheduling are not covered (see the comment on provider.py#L642). Two other provider-behaviour notes that would help users here: registry images must be built for linux/amd64, and private Amazon ECR or Google Artifact Registry images need Modal's dedicated image constructors rather than the static REGISTRY_USERNAME / REGISTRY_PASSWORD secret. Also, the "creation is submitted once" statements in this page and the README are accurate for the provider itself, but the Modal client retries the create request internally on transient errors (using one idempotency key per request), so it may be worth saying "the provider does not add retries".
ananthsub
left a comment
There was a problem hiding this comment.
thanks for the great contribution @reinainblood !
ananthsub
left a comment
There was a problem hiding this comment.
Thanks @reinainblood for the quick and thorough turnaround. Every point from the first round is addressed in e5f19eab9 and debfb0d7f: root runs natively, timeouts and dead sandboxes come back as results, cancellation keeps the original error, create() has one deadline, configuration is validated up front, and the tests now use Modal's real exception classes. I re-checked the provider against the Modal 1.5.5 and 1.6.1 sources and the version pin holds.
This round found a smaller set of issues. Three block merge; the rest are suggestions, and the inline comments carry the detail.
Blocking
1. A borrower can destroy the owner's sandbox. Cancelling an exec closes the sandbox even when the handle came from connect(). The facade's contract is that only the creator stops a sandbox (nemo_gym/sandbox/api.py#L656-L661), and the other providers only end the exec, not the sandbox. With terminus_2_sandboxed_agent this turns a timed-out rollout into an infrastructure failure:
sequenceDiagram
participant Owner as Resources server
participant Sandbox as Modal sandbox
participant Agent as terminus_2 agent
Owner->>Sandbox: create sandbox
Owner-->>Agent: serialized handle
Agent->>Sandbox: connect as borrower
Agent->>Sandbox: exec command
Note over Agent: asyncio.timeout fires mid-command
Agent->>Sandbox: cancel cleanup terminates the sandbox
Agent->>Owner: verify
Owner->>Sandbox: grade final state
Sandbox-->>Owner: sandbox already gone
Recording that a handle was borrowed in connect() and skipping the terminate for borrowed handles would keep the current, documented behaviour for sandboxes the provider owns.
2. A command timeout is probably reported as an ordinary failure. The provider forwards the timeout to Modal, and the Modal worker kills the command at that deadline. The client's own deadline starts only after the exec has started, so the worker usually wins, and the exit comes back as a signal (return code 137) rather than the -1 sentinel the provider maps to error_type="timeout". Modal's own timeout tests use a mock that never kills the process, so they do not show this.
sequenceDiagram
participant Provider
participant Client as Modal client
participant Worker as Modal worker
Provider->>Client: exec with timeout T
Client->>Worker: start exec with deadline T
Worker-->>Client: exec started
Note over Client: client deadline starts only now
Worker->>Worker: kills the command at T
Worker-->>Client: exit by signal
Client-->>Provider: return code 137, not -1
Callers such as anyswe_agent, hermes_sandboxed_agent and cvdp branch on "timeout". Treating a run that lasted at least the timeout and ended by signal (or -1) as a timeout would cover both orders.
3. A live run on this head. The fix commits changed three runtime paths that have not yet run against real Modal: closing stdin on every exec (including the readiness probe), the combined create deadline, and cancellation cleanup. Could you run one gym eval run with an in-repo sandboxed agent? Terminal-Bench through anyterminal_agent is a good fit (prepare.py --limit 5 --no-build-sif, then gym env start and gym eval run). Please include a direct check of three behaviours, which settles item 2 and the stdin question below:
- a command that exceeds its timeout (for example
sleep 10withtimeout_s=2) and the result it returns - a command that reads standard input, such as
cat, returning promptly - the default
printf okreadiness probe passing on the first attempt
Suggested
- Unmapped transport errors. Python's built-in
ConnectionError(raised by Modal's command router), plusServiceErrorandInternalErrorafter Modal's own retries, still escapeexec()raw. Mapping them toerror_type="sandbox"would complete the contract. - Make the stdin close independent of the result. A failed
drain()currently replaces a return code that already arrived. Draining separately, and ignoringConflictErroronce the process has exited, mirrors Modal's own filesystem code. - Fail fast on a dead sandbox in the readiness probe instead of polling until the deadline, for example when the entrypoint exits immediately.
- Clear the image
ENTRYPOINT(Image.entrypoint([])) when the provider supplies its keep-alive command. The Docker provider overrides it for the same reason. - Small validation gaps.
operations.*fields acceptnulland later raiseTypeError, and boolean fields accept strings like"false". - Resource limits. The README says to configure CPU and memory limits outside the provider, but Modal accepts a request and a limit natively.
- Tests. Time-bound the stream-failure test, and add tests for
probe.stable_count, a probe with no deadline, and a transient probe error. I can share passing versions.
Structure as more Modal features land
We want broad Modal coverage, and these would make each addition cheaper:
- One typed model for
provider_options, with a single translation to Modal arguments. - Configuration grouped by capability (
network,storage), rather than more flat keys. probe.deadline_snow bounds the whole create. Acreate.start_timeout_s, as Docker has, would keepprobeabout the probe.SANDBOX_RUNTIME_RETURN_CODEinstead of the literal125, and the sharedproviders/utils.coerce_configinstead of a local copy.
Good next capabilities, each as its own follow-up with a real run:
| Capability | Modal feature | NeMo Gym fit |
|---|---|---|
| Shared storage | Volume.with_mount_options(read_only, sub_path) |
SupportsSandboxSharedStorage |
| Authenticated endpoints | create_connect_token |
headers on SandboxEndpoint |
| Hard resource caps | CPU and memory request and limit | SandboxResources |
| Service readiness | native TCP readiness_probe |
port-serving sandboxes |
| Network policy | inbound and outbound allowlists | provider_options |
Description corrections
status()polls once and is not retried.- Reads through Modal's filesystem API are limited to 5 GB.
| except asyncio.CancelledError: | ||
| # No public per-exec kill API. Cleanup must not replace cancellation, | ||
| # including when asyncio.timeout() relies on it to raise TimeoutError. | ||
| await asyncio.shield(self._cleanup_after_error(handle)) |
There was a problem hiding this comment.
This cleanup also runs for handles that came from connect(), so a borrower that cancels an exec terminates a sandbox it does not own. The facade's contract is that the component that created a sandbox stays responsible for stopping it (nemo_gym/sandbox/api.py#L656-L661), and the Docker, OpenSandbox and Daytona providers only end the exec on cancellation, never the sandbox.
This matters for terminus_2_sandboxed_agent. It connects to the sandbox the resources server created (responses_api_agents/terminus_2_sandboxed_agent/app.py#L468-L471), runs commands under asyncio.timeout(sandbox_timeout) (#L550), and then calls /verify, which grades in that same sandbox (#L654-L662). On Modal, a rollout whose time limit fires mid-command reaches /verify with its sandbox already terminated and is scored as an infrastructure failure; on Docker the final state is graded. Reproduced with the PR's fake SDK: a second provider instance connects, its exec is cancelled, and the original sandbox records one terminate.
Could connect() record that the handle is borrowed (for example a flag on _ModalSandbox), and this path skip the terminate for borrowed handles, logging it and relying on the exec timeout to end the process? The current behaviour for sandboxes this provider created can stay as documented.
| except types["exec_sandbox"] + types["sandbox_gone"] as exc: | ||
| return_code, error_type, error_detail = 125, "sandbox", str(exc) | ||
|
|
||
| if return_code == _MODAL_EXEC_SENTINEL_RC: |
There was a problem hiding this comment.
I think this sentinel is rarely what a real timeout produces. The provider forwards the timeout to Modal, which passes it to the worker as timeout_secs, documented as "the command will be killed" (modal_proto/task_command_router.proto#L178-L181 at the 1.6.1 release commit). The client-side deadline that produces -1 is only set after exec_start returns (modal/sandbox.py#L2391-L2402), so the worker's kill normally lands first. TaskExecWaitResponse carries only an exit code or a signal, with an upstream TODO about not being able to tell normal exit from termination by Modal (task_command_router.proto#L283-L292), and ContainerProcess.wait() maps a signal to 128 + n (modal/container_process.py#L175-L176). A timed-out command would then come back as return code 137 with error_type=None, which callers such as anyswe_agent, hermes_sandboxed_agent and cvdp do not treat as a timeout. Modal's own timeout tests use a mock router that never kills the process, so they do not cover this.
Could you check it live (for example sleep 10 with timeout_s=2) and, if it reproduces, classify a run that lasted at least the effective timeout and ended by signal or -1 as error_type="timeout"? Recording a monotonic start before exec.aio is enough to do that.
| collect(process.stdout, output[0]), | ||
| collect(process.stderr, output[1]), | ||
| process.wait.aio(), | ||
| process.stdin.drain.aio(), |
There was a problem hiding this comment.
Gathering drain() together with wait() means a failed drain replaces a return code that has already arrived. Modal's own filesystem code notes that the worker reports a stdin write to a process that has already exited as ConflictError, and checks process.poll() before deciding to re-raise (modal/sandbox_fs.py#L633-L640 at 1.6.1). If an end-of-file write behaves the same way, a fast command such as the printf ok readiness probe would be reported as error_type="sandbox", and a transient error would escape exec() raw. I have not seen this live, so this is mainly hardening: drain separately, and ignore ConflictError or NotFoundError from the drain once wait() or poll() reports an exit. The live smoke with a cat command would show whether it happens in practice.
| raise | ||
| except types["exec_timeout"] as exc: | ||
| return_code, error_type, error_detail = 125, "timeout", str(exc) | ||
| except types["exec_sandbox"] + types["sandbox_gone"] as exc: |
There was a problem hiding this comment.
Some failures still escape exec() as raw exceptions rather than becoming results. Modal's command router raises Python's built-in ConnectionError once its transient retries run out (modal/_utils/task_command_router_client.py#L193-L199 and #L1061-L1070; it does not import modal.exception.ConnectionError), and ServiceError and InternalError can also surface after Modal's own retries. None of these are in exec_sandbox, so a network failure mid-command bypasses the error_type in ("timeout", "sandbox") handling in the agents. Adding them here, with code 125 and error_type="sandbox", would complete the contract the README describes.
| else: | ||
| consecutive = 0 | ||
| if deadline_s is None: |
There was a problem hiding this comment.
When the sandbox has already exited (for example a SandboxSpec.entrypoint service that crashes at start, or an image whose ENTRYPOINT swallows the keep-alive), each probe attempt now returns error_type="sandbox" and the loop keeps polling until deadline_s, 180 seconds by default, before failing. Checking poll() after a "sandbox" result and failing immediately when the sandbox has stopped would turn that into a fast, clear error.
| if spec.entrypoint: | ||
| entrypoint = [str(p) for p in spec.entrypoint] | ||
| else: | ||
| entrypoint = [*self._create.keepalive_shell, self._create.keepalive_cmd] |
There was a problem hiding this comment.
Modal treats these arguments as the container command and keeps any ENTRYPOINT the image defines (Image.entrypoint() exists for overriding it, modal/_image.py#L1984). For an image with ENTRYPOINT ["python"], the keep-alive becomes python /bin/sh -c ..., the sandbox exits, and the probe then waits out its deadline. The Docker provider overrides the entrypoint for this reason (docker/provider.py#L343-L346). Clearing it with image.entrypoint([]) when the provider supplies its own keep-alive would match that behaviour. I have not verified the server side live, so a mention in the README is the minimum.
| _validate_optional_number("operations.retry_delay_s", self.retry_delay_s, positive=False) | ||
| _validate_optional_number("operations.retry_max_delay_s", self.retry_max_delay_s, positive=False) |
There was a problem hiding this comment.
retry_delay_s, retry_max_delay_s and tunnel_timeout_s are used as numbers but _validate_optional_number accepts None, so retry_delay_s: null passes construction and later fails with TypeError at the first retry (line 457), and tunnel_timeout_s: null fails in endpoint() at math.ceil(None). These fields should reject None. Relatedly, boolean fields such as create_app_if_missing, strict_resources and allow_user_rewrite are not type-checked, so a string "false" (which ${oc.env:...} produces) is truthy.
| image=descriptor.get("image"), | ||
| declared_ports=ports, | ||
| app_name=self._connection.app_name, | ||
| port_mode=descriptor.get("port_mode", self._create.port_mode), |
There was a problem hiding this comment.
Small one: port_mode from the descriptor is not checked against _PORT_MODES, so an unknown value silently behaves like encrypted, and a missing sandbox_id surfaces as a raw KeyError. Validating the descriptor here would give a clear error for hand-built or stale descriptors.
| CPU and memory values are Modal resource requests rather than hard usage caps. Configure limits | ||
| outside this provider if the workload needs a stricter ceiling. |
There was a problem hiding this comment.
Modal can set hard limits itself: cpu and memory accept a (request, limit) pair (modal/sandbox.py#L643-L644), while a scalar sets no limit at all (modal/_resources.py#L34-L36). There is no way to configure a limit "outside this provider", since the provider builds the create arguments. Either expose the limits (for example cpu_limit and memory_limit_mib) or reword this. Docker's memory_mib is a hard cap, so passing the same value as both request and limit would give parity by default.
| created[0].exec_script = {"work": process} | ||
| result = await provider.exec(handle, "work") | ||
| assert result.stdout == "caf\u00e9" and result.return_code == 125 | ||
| assert result.error_type == ("timeout" if error == "ExecTimeoutError" else "sandbox") |
There was a problem hiding this comment.
A mutation check against this head found a few behaviours no test pins: the probe treating a transient exec error as "not ready yet", probe.stable_count, a failing probe with no deadline (which would otherwise poll forever), and pending exec tasks being cancelled after a stream failure. The existing stream-failure test above has no time bound, so removing that cancellation still passes after waiting out the 30 second fake delay. These tests pass on this head and each fails against the corresponding mutation:
| assert result.error_type == ("timeout" if error == "ExecTimeoutError" else "sandbox") | |
| assert result.error_type == ("timeout" if error == "ExecTimeoutError" else "sandbox") | |
| async def test_probe_retries_after_a_transient_exec_error(fake_modal): | |
| modal = pytest.importorskip("modal") | |
| attempts = 0 | |
| def flaky(argv, kwargs): | |
| nonlocal attempts | |
| attempts += 1 | |
| if attempts == 1: | |
| raise modal.exception.ServiceError("container not attachable yet") | |
| return FakeProcess(stdout="ok") | |
| _, created = fake_modal(exec_script={"printf ok": flaky}) | |
| handle = await _provider().create(_spec()) | |
| assert attempts == 2 and handle.raw is not None and created[0].terminated == 0 | |
| async def test_probe_requires_consecutive_successes(fake_modal): | |
| outcomes = iter([0, 1, 0, 0]) | |
| def scripted(argv, kwargs): | |
| return FakeProcess(stdout="ok", returncode=next(outcomes)) | |
| _, created = fake_modal(exec_script={"printf ok": scripted}) | |
| await _provider(probe={"stable_count": 2}).create(_spec()) | |
| assert len(created[0].exec_calls) == 4 and created[0].terminated == 0 | |
| async def test_failed_probe_without_any_deadline_raises_instead_of_polling_forever(fake_modal): | |
| from nemo_gym.sandbox.providers.modal import ModalCreateVerificationError | |
| _, created = fake_modal(exec_script={"printf ok": FakeProcess(stderr="no shell", returncode=127)}) | |
| with pytest.raises(ModalCreateVerificationError, match="return_code=127.*no shell"): | |
| async with asyncio.timeout(0.5): | |
| await _provider(probe={"deadline_s": None}).create(_spec()) | |
| assert len(created[0].exec_calls) == 1 and created[0].terminated == 1 | |
| @pytest.mark.parametrize("error", ["ExecTimeoutError", "NotFoundError"]) | |
| async def test_stream_failure_does_not_wait_for_the_pending_process(fake_modal, error): | |
| modal, created = fake_modal() | |
| provider = _provider(probe={"command": None}) | |
| handle = await provider.create(_spec()) | |
| class FailingStream: | |
| async def __aiter__(self): | |
| yield b"partial" | |
| raise getattr(modal.exception, error)("stream ended") | |
| process = FakeProcess(wait_delay=30) | |
| process.stdout = FailingStream() | |
| created[0].exec_script = {"work": process} | |
| async with asyncio.timeout(1): | |
| result = await provider.exec(handle, "work") | |
| assert result.stdout == "partial" and result.return_code == 125 |
|
@ananthsub validation results for
Local reproduction: python -m pytest -q -o addopts='' \
tests/unit_tests/test_modal_provider.py \
tests/unit_tests/test_modal_provider_regressions.py \
tests/unit_tests/test_modal_sdk_surface.py \
tests/unit_tests/test_fern_docs_links.pyThe rollout used a temporary local fixture/model adapter, four agent turns, summarization disabled, concurrency one, and a 2,048-token generation cap. A test-only SDK wrapper enforced CPU/memory hard limits and selected a cached image. That image hook bypassed registry image construction and ENTRYPOINT clearing, so those paths have local-test coverage only. The observed SDK timeout was the -1 sentinel; this run did not exercise the signal-exit timing heuristic. These results are integration smoke evidence, not a benchmark score. DCO passes. Exact-head Code linting, Secrets detector, and Copyright workflows still require maintainer approval to run. Review threads remain open for re-review. |
ananthsub
left a comment
There was a problem hiding this comment.
Thanks @reinainblood, this round closes everything from the last review, and the live diagnostics you posted were exactly what was needed. Borrowed handles now leave the owner's sandbox alone, timeouts, transport failures and dead sandboxes all come back as results, the probe fails fast on a stopped sandbox, configuration and descriptors are validated, and the suggested tests landed in a stronger form.
A correction on my side. In the last round I wrote that the -1 sentinel is rarely what a real timeout produces. That was wrong. I checked Modal 1.5.5 and 1.6.1: both run exec through the command router, both start the client deadline only after the exec start returns, and both turn its expiry into -1 in ContainerProcess.wait(). So -1 is the usual timeout result, as your live run showed, and it applies to the locked 1.6.1 as well. The signal-range check is a reasonable fallback for the rarer race; the README can say that rather than "validation still pending".
Before merge
No code changes block merge from my side. One live check is still worth having, because the default create path has never run on Modal: the ENTRYPOINT clearing was added after the first smoke, and the latest rollout bypassed registry images through the test wrapper. Could you run one owned create through the unmodified provider (ideally Modal 1.6.1, since 1.5.5 is already covered) that:
- uses a public registry image whose
ENTRYPOINTis not a shell, such ascurlimages/curl, with noSandboxSpec.entrypoint - passes the default
printf okreadiness probe and runs oneexecthat returns 0 - confirms the sandbox stopped after
close() - reports the create time for the first (uncached) and a second (cached) create, so we can see the cost of clearing the entrypoint
Suggestions
- Always clear the image
ENTRYPOINT, and fold it into the base build. Docker and enroot treatSandboxSpec.entrypointas the full command, and in-repo configs such aspi_sandboxed_agent'sentrypoint: [sleep, infinity]assume that. Passingsetup_dockerfile_commands=["ENTRYPOINT []"]toImage.from_registryclears it in the same build instead of adding a layer per image. Details inline. - Let a completed exit code win over stdin errors, and map grpclib's
StreamTerminatedError, which Modal's router re-raises after its retries. Details inline. - Discard owned sandboxes on transport failures as well, for the same reason cancellation does: the remote command may still be running.
- Small validation and documentation items, plus three tests that pin behaviour no test covers yet. Details inline.
Follow-ups (not for this PR)
- CPU and memory hard limits via Modal's request and limit pair. Docker's
memory_mibis a hard cap, and your rollout needed a wrapper for it. - Detaching borrowed Modal objects when the facade disconnects. The facade has no provider hook for this today, so it belongs in the sandbox layer.
- The other Modal capabilities from the last round's table (shared storage, connect tokens, native readiness probe, network allowlists).
| if not spec.entrypoint: | ||
| kwargs["image"] = kwargs["image"].entrypoint([]) |
There was a problem hiding this comment.
Two suggestions here. First, clearing the entrypoint only when spec.entrypoint is empty means an explicit entrypoint behaves differently from Docker and enroot, which treat it as the full command (docker/provider.py#L340-L346). In-repo configs rely on that: pi_sandboxed_agent's benchmark config passes entrypoint: [sleep, infinity], which on an image with its own ENTRYPOINT would become arguments to it. Clearing it unconditionally would make the field mean the same thing on every provider.
Second, Image.entrypoint([]) goes through dockerfile_commands, so every distinct registry image gets an extra build on top of the pulled base, inside the create deadline. Image.from_registry(tag, setup_dockerfile_commands=["ENTRYPOINT []"]) puts it in the same Dockerfile as the base step (the parameter exists in both 1.5.5 and 1.6.1), which avoids the second build for large per-task image sets.
| async def drain_stdin() -> None: | ||
| try: | ||
| await process.stdin.drain.aio() | ||
| except types["stdin_closed"]: |
There was a problem hiding this comment.
Only ConflictError and NotFoundError are tolerated once the process has exited. If the end-of-input write fails for another reason after Modal's router has used up its retries (Python's built-in ConnectionError, ServiceError, or grpclib's StreamTerminatedError), gather raises it even though wait() already returned a real exit code, so a command that exited 0 is reported as error_type="sandbox". The bug-finder reproduced this with the PR's fake SDK. Since the exit code is authoritative once wait() has finished, ignoring any drain error at that point would be simpler and safer.
Related: call_with_retries_on_transient_errors in Modal's router client re-raises grpclib.exceptions.StreamTerminatedError unchanged after its retries (modal/_utils/task_command_router_client.py#L189-L192 at 1.6.1), so it can also escape exec() from exec_start or the output streams. Adding it to exec_sandbox (line 449) would close that.
| except types["exec_timeout"] as exc: | ||
| return_code, error_type, error_detail = SANDBOX_RUNTIME_RETURN_CODE, "timeout", str(exc) | ||
| except types["exec_sandbox"] + types["sandbox_gone"] as exc: | ||
| return_code, error_type, error_detail = SANDBOX_RUNTIME_RETURN_CODE, "sandbox", str(exc) |
There was a problem hiding this comment.
For an owned sandbox, a transport failure now returns error_type="sandbox" and leaves the sandbox running, while the command may still be executing remotely. The most likely trigger is the output stream exhausting its resumes while the process keeps going. That is the same situation the cancellation path guards against when it discards the sandbox, so discarding owned sandboxes here as well (borrowed handles unchanged) would keep the two paths consistent.
| def __post_init__(self) -> None: | ||
| if self.command is not None and (not isinstance(self.command, str) or not self.command.strip()): | ||
| raise ValueError("probe.command must be a non-empty string or null") | ||
| _validate_optional_number("probe.timeout_s", self.timeout_s, positive=True, allow_none=False) | ||
| _validate_optional_number("probe.deadline_s", self.deadline_s, positive=True) | ||
| _validate_positive_int("probe.stable_count", self.stable_count) | ||
| _validate_optional_number("probe.stable_delay_s", self.stable_delay_s, positive=False, allow_none=False) |
There was a problem hiding this comment.
probe.expected_stdout is not type-checked, so expected_stdout: 1 in YAML passes construction and then raises TypeError in the probe after a sandbox has been allocated, on every create. A string check here would catch it up front. Separately, the probe re-raises every ValueError as fatal (line 786), but Modal's stdio reader can raise ValueError("Received empty message streaming stdio...") (modal/io_streams.py#L325-L326 at 1.6.1). It is rare, so this is just worth knowing.
| return descriptor | ||
|
|
||
| async def connect(self, descriptor: Mapping[str, Any]) -> SandboxHandle: | ||
| """Rebuild a live handle from ``Sandbox.from_id``.""" |
There was a problem hiding this comment.
Could this docstring, and a comment on _ModalSandbox.owns_sandbox, state the ownership rules? A connected handle is borrowed, interruption never terminates it, close() still terminates regardless of ownership, and ownership is not part of the serialized descriptor. Today that lives only in the README and PR description.
| SDK timeout exceptions and the SDK's `-1` exit sentinel return | ||
| `SandboxExecResult(error_type="timeout", return_code=125)`. Worker-side deadlines can instead | ||
| surface as signal exits (for example, 137). The provider classifies signal-range exit codes | ||
| 129–192 as timeouts when dispatch-to-wait-completion time meets the timeout passed to Modal | ||
| (rounded up to whole seconds). This is a heuristic: a coincident explicit exit, OOM, unrelated | ||
| signal, or delayed dispatch can be indistinguishable from a deadline. Live validation of this | ||
| worker-timeout path is still pending. Early signals, signals without a deadline, and ordinary |
There was a problem hiding this comment.
Following the live result and the SDK check (both 1.5.5 and 1.6.1 return -1 when the client deadline expires), this can say that -1 is the observed common timeout result and the signal-range rule is a fallback for a worker kill that arrives first, rather than "validation still pending". Small nits in the same section: "Failed or cancelled creation attempts cleanup" (line 94) reads better as "are cleaned up", and file operations and reconnection are described twice (lines 130-135 and 137-151).
| await provider.create(_spec()) | ||
| else: | ||
| await provider.create(_spec()) | ||
| assert len(calls) == {"transient": 2, "unknown": 2, "consecutive": 4, "no_deadline": 1}[scenario] |
There was a problem hiding this comment.
A mutation check found a few behaviours still unpinned: the probe's expected_stdout comparison and stable_delay_s, the timeout clock starting before dispatch (moving it after exec.aio would miss a worker kill at exactly the deadline), and forwarding of idle_timeout, cloud and name. These pass on this head with Modal 1.5.5 and 1.6.1 and each fails against the corresponding mutation:
| assert len(calls) == {"transient": 2, "unknown": 2, "consecutive": 4, "no_deadline": 1}[scenario] | |
| assert len(calls) == {"transient": 2, "unknown": 2, "consecutive": 4, "no_deadline": 1}[scenario] | |
| async def test_probe_waits_for_expected_stdout_and_sleeps_between_attempts(fake_modal, monkeypatch): | |
| from nemo_gym.sandbox.providers.modal import provider as module | |
| outputs = iter(["starting", "ok"]) | |
| _, created = fake_modal(exec_script={"printf ok": lambda argv, kwargs: FakeProcess(stdout=next(outputs))}) | |
| sleeps = [] | |
| real_sleep = asyncio.sleep | |
| async def recording_sleep(delay): | |
| sleeps.append(delay) | |
| await real_sleep(0) | |
| monkeypatch.setattr(module.asyncio, "sleep", recording_sleep) | |
| await _provider(probe={"stable_delay_s": 0.25}).create(_spec()) | |
| assert len(created[0].exec_calls) == 2 and sleeps == [0.25] | |
| async def test_signal_timeout_clock_starts_before_exec_dispatch(fake_modal, monkeypatch): | |
| from nemo_gym.sandbox.providers.modal import provider as module | |
| _, created = fake_modal() | |
| provider = _provider(probe={"command": None}) | |
| handle = await provider.create(_spec()) | |
| now = [0.0] | |
| process = FakeProcess(returncode=137) | |
| async def dispatch(*argv, **kwargs): | |
| # The worker starts its own timeout once the process starts, before exec_start returns. | |
| now[0] = 0.5 | |
| return process | |
| async def wait(): | |
| now[0] = 2.2 | |
| return 137 | |
| process.wait = _Aio(wait) | |
| created[0].exec = _Aio(dispatch) | |
| monkeypatch.setattr(module, "monotonic", lambda: now[0]) | |
| result = await provider.exec(handle, "work", timeout_s=2) | |
| assert result.return_code == 125 and result.error_type == "timeout" | |
| async def test_lifecycle_options_reach_sandbox_create(fake_modal): | |
| _, created = fake_modal() | |
| await _provider(probe={"command": None}).create( | |
| _spec(provider_options={"idle_timeout_s": 1.2, "cloud": "oci", "name": "task-17"}) | |
| ) | |
| kwargs = created[0].create_kwargs | |
| assert (kwargs["idle_timeout"], kwargs["cloud"], kwargs["name"]) == (2, "oci", "task-17") |
|
@ananthsub the registry/ENTRYPOINT check passed on Image:
The first request produced two completed Modal builds: registry import and Reproduction uses the normal provider configuration below, then calls from nemo_gym.sandbox.providers.base import SandboxResources, SandboxSpec
from nemo_gym.sandbox.providers.modal.provider import ModalProvider
provider = ModalProvider(
connection={"app_name": APP, "environment_name": ENV, "create_app_if_missing": False},
create={"timeout_s": 300, "block_network": True},
operations={"close_timeout_s": 60},
)
spec = SandboxSpec(
image=IMAGE, ttl_s=300, ready_timeout_s=600,
resources=SandboxResources(cpu=1, memory_mib=1024),
)A local post-exec metadata read stalled on the first run and was interrupted; provider cleanup ran, and a separate control-plane read confirmed termination before the second create. Both sandboxes are terminated. The resource values are requests, not hard caps. No model rollout, benchmark, signal-timeout test, or code change was part of this check. |
ananthsub
left a comment
There was a problem hiding this comment.
thanks for the thorough contribution!
Signed-off-by: Kirsten Ruge <[email protected]>
Signed-off-by: Kirsten Ruge <[email protected]>
Signed-off-by: Kirsten Ruge <[email protected]>
Signed-off-by: Kirsten Ruge <[email protected]>
Signed-off-by: Kirsten Ruge <[email protected]>
9bea175 to
a86d085
Compare
|
/ok to test a86d085 |
|
@ananthsub thanks again for the thorough reviews. A quick status check on where this stands:
Could you re-trigger |
What does this PR do?
Modal sandboxes run OCI images on Modal's managed compute and expose command execution, file transfer, networking and lifecycle control through its Python SDK. This PR adds Modal as a built-in NeMo Gym
SandboxProvider, so an existing sandbox-backed agent or environment can select Modal through configuration without adding Modal-specific orchestration to the agent or resources server.Closes #1690.
Provider
modal:modalin the existing provider registry and uses the sameAsyncSandbox/SandboxSpecinterface as the other built-in providers.execcalls share the same sandbox state; Modal's remote timeout remains the hard lifetime.MODAL_TOKEN_ID/MODAL_TOKEN_SECRET. Provider credentials are not stored in Gym configuration or injected into evaluated workloads.Creation uses a configurable exec probe before returning the sandbox.
ready_timeout_snow covers App lookup, image preparation/pull, scheduling, and probing. Failure or cancellation attempts bounded cleanup before propagating the original error. If allocation cannot return an id within the cleanup budget, the provider logs the App and relies on the remote TTL as the final backstop.The provider adds no retries to create or exec requests: a new create request can allocate a second billable sandbox, and replaying exec can repeat a side effect. The Modal SDK may internally retry create using the same request idempotency key. Retries are limited to recognized transient failures on idempotent control-plane operations such as reconnection, tunnel resolution and cleanup.
status()polls once and returns unknown on transient failure.App resolution first performs a non-creating lookup and creates the configured App only after Modal reports it missing. This preserves
create_app_if_missingwithout turning every lookup into a deployment attempt, including in workspaces at their deployed-App limit.Root exec (
None,"root", or0) needs no user rewrite. Other named users require explicitexec.allow_user_rewriteandsu; the full shell argv, including login-shell flags, is preserved. SDK timeout exceptions and the-1sentinel map toerror_type="timeout", code 125. Worker-side timeouts may instead return a signal exit, so codes 129–192 are classified as timeouts when dispatch-to-wait-completion duration reaches the rounded timeout sent to Modal. This heuristic cannot distinguish a coincident explicit exit, OOM or unrelated signal; live validation is still pending. Early signals, signals without a deadline, and ordinary nonzero exits remain process results. Output-drain time does not affect classification.Missing/closed/invalid sandboxes and exhausted SDK or Python transport errors return
error_type="sandbox", code 125, without replaying exec. Captured output is preserved, stdin receives EOF, and expected drain errors after confirmed process exit do not replace the exit result. The 65,536-character argv limit is checked before dispatch. Dead sandboxes fail readiness promptly; transient failures on running or unknown sandboxes can retry. Config numbers, booleans and connection descriptors are validated before remote work.Modal does not expose a public operation to terminate only one exec process. Client cancellation or interrupted file transfer attempts termination for owned handles. Handles from
connect()are borrowed: interruption preserves the sandbox for owner verification and diagnostics, and logs that the owner retains cleanup responsibility. Borrowed commands can continue until their exec timeout and file writes may remain in flight. Use explicit command timeouts and owner-coordinated cleanup. Cleanup errors preserve the original exception, and failed cleanup retains the handle for retry.CPU and memory are scalar requests, not hard caps. Modal's request/limit pairs are not exposed yet. Typed provider options, capability-grouped configuration, a create-deadline naming migration, shared configuration coercion, and additional Modal capabilities remain follow-ups rather than expanding this provider introduction.
The shipped
modal.yamlcomposes into the normal top-levelsandboxblock.MODAL_ENVIRONMENTselects the Modal environment andNEMO_GYM_MODAL_APPselects the owning App; neither has to be embedded in an agent configuration. Thesandboxdependency extra addsmodal>=1.5.5,<2.0.0, with the installed 1.x SDK surface pinned by tests.Modal has no per-sandbox disk-size control. A requested
disk_gibwarns by default or fails before allocation whenstrict_resourcesis enabled. Outbound networking remains enabled by default for workloads that install dependencies;block_network: trueenables offline execution and is rejected when combined with exposed ports.Documentation is included both as the provider README and as a Fern sandbox-provider page covering setup, configuration, resource mapping, networking, cancellation, cleanup, file transfer and reconnection.
Validation
Current verified revision:
b976d2fac51a593ea1021a5b8d1ab0670ce0c1bb.sys.modules["modal"] = None): 28 passed, 171 skipped, no failures.test_enroot_provider.py::test_create_start_timeout_cleans_up, which requires Linux/proc; previously reproduced separately on original PR head317d454e.pre-commit run --all-files,uv lock --check, andgit diff --check: passed.make docs-check: 0 errors, 1 existing warning.The fake SDK uses the installed Modal exception hierarchy. Added regression coverage includes borrowed-handle diagnostics, signal deadlines, stdin-close races, no replay after transport failure, stopped and transient readiness, consecutive probe successes, and invalid connection descriptors. Existing coverage includes root/default-user compatibility, non-root shell flags, early config/spec validation and App lookup wrapping, allocation and probe deadlines, interrupted allocation reconciliation, preserved probe diagnostics and original errors, timeout/sandbox result contracts with streamed partial output, stdin EOF, argv limits, and create/exec retry boundaries.
Rollouts
Live smoke validation completed on
b976d2fac51a593ea1021a5b8d1ab0670ce0c1bb; results and validation details record the observations and reproduction scope. The in-repoterminus_2_sandboxed_agentran throughgym eval run --no-servewith GLM-5.3 Flash, Harbor 0.22.0, and Modal 1.5.5: one synthetic task, three model calls, five of five verifier cases passed, reward 1, and no agent error. Direct diagnostics confirmed stdin EOF, first-attempt default readiness, timeout classification with preserved partial output, borrowed cancellation preserving owner diagnostics, owned cancellation cleanup, and failed-readiness deadline/diagnostic preservation and cleanup. A test-only SDK wrapper enforced hard resource limits and selected a cached image, bypassing registry image construction and ENTRYPOINT clearing; those paths retain local-test coverage only. The observed live timeout used the SDK-1sentinel, so the signal-exit timing heuristic was not live-tested. This is integration smoke evidence, not a benchmark score. Exact-head Code linting, Secrets detector, and Copyright workflows have now passed; this does not establish upstream unit or benchmark CI coverage. The following older evidence predates the review fixes and is retained as integration history, not validation of the new runtime behavior.Previous head
317d454eonly: authenticated smoke on a live Modal workspace:python:3.13-slimsandbox with outbound networking blockedrunningAsyncSandbox.start()MODAL-PROVIDER-UPSTREAM-2026-10-08stoppedThe same provider was also exercised through a real NeMo Gym ExploitBench run before the current-upstream refresh. The observed run contained 99 valid rollout rows, 99 distinct Modal sandbox ids,
cleanup_completed=trueon all 99 valid rows, 39 calls to the benchmark grader, and four infrastructure or model failures retained in the failure sidecar rather than converted into benchmark scores.The runtime path was:
gym eval run→ agent → Resources Server →AsyncSandbox→ Modal sandbox → nested workload and grader → cleanupThe ExploitBench run is provider integration evidence, not a benchmark result reported by this PR.
Compatibility and benchmark impact
None for existing environments, agents, benchmark results or public sandbox call sites. Modal is a new optional provider and is inactive unless selected.
Outside
nemo_gym/sandbox/providers/modaland its tests:nemo_gym/sandbox/providers/registry.pyregisters the provider;pyproject.tomladds the bounded Modal SDK dependency to the existingsandboxextra;uv.lockrecords that dependency and its transitive packages;fern/versions/latest/pages/infrastructure/sandbox/index.mdxadds the Modal provider card; andfern/versions/latest/pages/infrastructure/sandbox/modal.mdxdocuments user-facing configuration and behavior.No benchmark dataset, prompt, verifier, agent policy or scoring implementation changes.
Proposed labels
featurearea:sandboxneeds-reviewcomplexity:highChecklist
pre-commit run --all-files) (so CI lint/format checks pass).git commit -s) (so the DCO check passes).Co-authored by Kirsten Ruge (@reinainblood) and Codex, working in Codex.
Snorkel AI · [email protected]