Skip to content

feat(sandbox): add Modal provider - #4237

Open
reinainblood wants to merge 5 commits into
NVIDIA-NeMo:mainfrom
reinainblood:codex/modal-provider-upstream-submit-20261008
Open

reinainblood wants to merge 5 commits into
NVIDIA-NeMo:mainfrom
reinainblood:codex/modal-provider-upstream-submit-20261008

Conversation

@reinainblood

@reinainblood reinainblood commented Oct 8, 2026 •

Copy link
Copy Markdown

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:

  • implements create, exec, upload, download, status, endpoint, close, serialize and reconnect through the public Modal SDK; it registers under modal in the existing provider registry and uses the same AsyncSandbox / SandboxSpec interface as the other built-in providers.
  • creates sandboxes from OCI registry references. With no explicit entrypoint it clears the image ENTRYPOINT and injects a POSIX keep-alive process, so repeated exec calls share the same sandbox state; Modal's remote timeout remains the hard lifetime.
  • maps neutral CPU, memory and GPU requests onto Modal resources. Per-sandbox provider options add Modal placement, Secrets, Volumes, blocked networking, idle timeout, registry credentials, names and tags.
  • exposes declared ports through Modal tunnels. Encrypted and HTTP/2 modes use Modal's TLS termination; unencrypted mode returns the public raw TCP endpoint.
  • uploads and downloads through Modal's streaming filesystem API. Uploads create missing parent directories; downloads use the SDK's atomic local replacement behavior. Reads are limited to 5 GB by the SDK.
  • supports cross-process handoff: serialized handles retain the Modal sandbox id, image, ports, working directory and port mode, and another configured provider can reconnect without reprovisioning the sandbox.
  • authenticates through Modal's profile or 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_s now 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_missing without turning every lookup into a deployment attempt, including in workspaces at their deployed-App limit.

Root exec (None, "root", or 0) needs no user rewrite. Other named users require explicit exec.allow_user_rewrite and su; the full shell argv, including login-shell flags, is preserved. SDK timeout exceptions and the -1 sentinel map to error_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.yaml composes into the normal top-level sandbox block. MODAL_ENVIRONMENT selects the Modal environment and NEMO_GYM_MODAL_APP selects the owning App; neither has to be embedded in an agent configuration. The sandbox dependency extra adds modal>=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_gib warns by default or fails before allocation when strict_resources is enabled. Outbound networking remains enabled by default for workloads that install dependencies; block_network: true enables 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.

  • Modal provider, regression and installed-SDK surface suite: 211 passed on both Modal 1.5.5 and 1.6.1, without remote workloads. SDK 1.6.1 provider-package coverage: 98.15%.
  • Provider suite plus Fern link tests: 229 passed, 17 subtests passed.
  • Missing Modal simulation (sys.modules["modal"] = None): 28 passed, 171 skipped, no failures.
  • Regression validation against the previous provider: 45 selected cases fail there and pass with these fixes; ten selected control cases pass on both. Removing local-task cancellation fails both bounded stream-error tests. Adding provider exec retries fails the submission-count test.
  • Broader sandbox unit suite: 1,042 passed, 7 skipped, 1 failed on macOS. The sole failure is unchanged test_enroot_provider.py::test_create_start_timeout_cleans_up, which requires Linux /proc; previously reproduced separately on original PR head 317d454e.
  • pre-commit run --all-files, uv lock --check, and git diff --check: passed.
  • make docs-check: 0 errors, 1 existing warning.
  • DCO sign-off included. Exact-head CI is checked after pushing; earlier-head trusted CI does not validate this revision.
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.py
python -m pytest tests/unit_tests -m sandbox -q -o addopts=''
pre-commit run --all-files
uv lock --check
make docs-check
git diff --check

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-repo terminus_2_sandboxed_agent ran through gym eval run --no-serve with 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 -1 sentinel, 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 317d454e only: authenticated smoke on a live Modal workspace:

  • resolved the existing configured App without attempting a deployment
  • created a python:3.13-slim sandbox with outbound networking blocked
  • observed the sandbox in running
  • uploaded an input file during AsyncSandbox.start()
  • executed a Python command with return code 0
  • downloaded the generated file and verified MODAL-PROVIDER-UPSTREAM-2026-10-08
  • stopped the sandbox and observed stopped
  • queried the container inventory after cleanup and found zero matching live containers

The 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=true on 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 → cleanup

The 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/modal and its tests: nemo_gym/sandbox/providers/registry.py registers the provider; pyproject.toml adds the bounded Modal SDK dependency to the existing sandbox extra; uv.lock records that dependency and its transitive packages; fern/versions/latest/pages/infrastructure/sandbox/index.mdx adds the Modal provider card; and fern/versions/latest/pages/infrastructure/sandbox/modal.mdx documents user-facing configuration and behavior.

No benchmark dataset, prompt, verifier, agent policy or scoring implementation changes.

Proposed labels

  • feature
  • area:sandbox
  • needs-review
  • complexity:high

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Documentation added or updated, or N/A with justification.
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format checks pass).
  • New source files include the required Apache-2.0 SPDX header.
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

Co-authored by Kirsten Ruge (@reinainblood) and Codex, working in Codex.

Snorkel AI · [email protected]

@reinainblood
reinainblood requested a review from a team as a code owner October 8, 2026 14:56
@copy-pr-bot

copy-pr-bot Bot commented Oct 8, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@nemo-automation-bot nemo-automation-bot Bot added the community-request Issue reported or requested by someone from the community label Oct 8, 2026
@reinainblood

Copy link
Copy Markdown
Author

@ananthsub thank you for inviting this upstream on the fork PR. This is the provider-only PR rebuilt on current main; the final head is 317d454e821d5e548134b1378adaa688d418e547. Focused tests, current Modal SDK surface checks, Fern validation, pristine-main failure comparison, and a fresh authenticated live-runtime smoke are recorded in the description. It is ready for review; would you or another qualified vetter be able to approve trusted CI for this head?

@yaoyu-33 yaoyu-33 added area:sandbox Sandbox providers, isolation, and sandbox runtime contracts complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Oct 8, 2026
@ananthsub
ananthsub requested a review from hemildesai October 8, 2026 17:16
@ananthsub

Copy link
Copy Markdown
Contributor

/ok to test 317d454

@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread tests/unit_tests/test_modal_provider.py Outdated
Comment on lines +508 to +515
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 == []

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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

Comment thread tests/unit_tests/test_modal_provider.py Outdated
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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ananthsub left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for the great contribution @reinainblood !

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-customer Waiting on the original author to respond label Oct 9, 2026

@ananthsub ananthsub left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Loading

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
Loading

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 10 with timeout_s=2) and the result it returns
  • a command that reads standard input, such as cat, returning promptly
  • the default printf ok readiness probe passing on the first attempt

Suggested

  • Unmapped transport errors. Python's built-in ConnectionError (raised by Modal's command router), plus ServiceError and InternalError after Modal's own retries, still escape exec() raw. Mapping them to error_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 ignoring ConflictError once 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 accept null and later raise TypeError, 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_s now bounds the whole create. A create.start_timeout_s, as Docker has, would keep probe about the probe.
  • SANDBOX_RUNTIME_RETURN_CODE instead of the literal 125, and the shared providers/utils.coerce_config instead 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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +764 to +766
else:
consecutive = 0
if deadline_s is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +332 to +333
_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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +53 to +54
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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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

@yaoyu-33 yaoyu-33 removed the needs-review PR is ready for code review and waiting on a reviewer label Oct 9, 2026
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Oct 9, 2026
@reinainblood

Copy link
Copy Markdown
Author

@ananthsub validation results for b976d2fac51a593ea1021a5b8d1ab0670ce0c1bb:

  • Local provider/regression/SDK tests: 211 passed on each of Modal 1.5.5 and 1.6.1. Adding Fern link tests: 229 passed, 17 subtests passed. Full pre-commit, lock consistency, and diff checks passed. The broader sandbox suite had 1,042 passed, 7 skipped, and one unchanged Enroot /proc failure on macOS, also reproduced on the original head.
  • Live diagnostics on Modal 1.5.5: cat received EOF and exited 0 with empty output in 0.047 s. Default printf ok readiness succeeded on the first attempt on both normal diagnostic creates. For printf before-timeout; sleep 10 with timeout_s=2, raw SDK wait returned -1 at 2.028 s; the provider returned 125, error_type=timeout, and preserved before-timeout at 2.029 s.
  • Cancelling an exec through a borrowed handle preserved the owner's sandbox and diagnostic file. Owned cancellation terminated the sandbox. Failed readiness retained probe output not-ready and exit 1, reached the ten-second deadline, and terminated the allocation. Cleanup was independently confirmed through fresh control-plane reads.
  • One successful GLM-5.3 Flash rollout used the in-repo terminus_2_sandboxed_agent through gym eval run --no-serve, with Harbor 0.22.0 and Modal 1.5.5: 3 model calls, 5/5 verifier cases, reward 1, completed with no agent error. This was a single synthetic smoke task: write a Python program that reads integers from stdin and sums the even values. Cases covered empty input, positives, negatives/zero, mixed whitespace, and no even values.

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.py

The 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
ananthsub previously approved these changes Oct 9, 2026

@ananthsub ananthsub left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ENTRYPOINT is not a shell, such as curlimages/curl, with no SandboxSpec.entrypoint
  • passes the default printf ok readiness probe and runs one exec that 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 treat SandboxSpec.entrypoint as the full command, and in-repo configs such as pi_sandboxed_agent's entrypoint: [sleep, infinity] assume that. Passing setup_dockerfile_commands=["ENTRYPOINT []"] to Image.from_registry clears 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_mib is 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).

Comment on lines +694 to +695
if not spec.entrypoint:
kwargs["image"] = kwargs["image"].entrypoint([])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +288 to +294
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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``."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +101 to +107
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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")

@reinainblood

Copy link
Copy Markdown
Author

@ananthsub the registry/ENTRYPOINT check passed on b976d2fac51a593ea1021a5b8d1ab0670ce0c1bb with Modal 1.6.1, through the unmodified provider's owned-create path. No cached-image hook, provider/SDK wrapper, or SandboxSpec.entrypoint override was used.

Image: curlimages/curl:8.12.1, pinned to the Linux/amd64 manifest below. Registry config declares ENTRYPOINT ["/entrypoint.sh"] and CMD ["curl"].

curlimages/curl@sha256:88a9abad9d958340e48564f9bdcdaa29916a2984be59314da709f8bbc0eef6f7
Observation First create Second create
End-to-end provider.create() including default readiness 6.048 s 0.933 s
Default printf ok probe Passed Passed
printf registry-entrypoint-cleared; curl --version Exit 0, curl 8.12.1, empty stderr Exit 0, curl 8.12.1, empty stderr
After close() Independently confirmed terminated Provider stopped, fresh SDK poll stopped, independently confirmed terminated

The first request produced two completed Modal builds: registry import and ENTRYPOINT []. Build-chain timestamps place both builds within that request; build output reports 1.46 s and 1.36 s, respectively. The second reused the identical resulting image with no build wait. This establishes first-build versus cached-image behavior for these Modal image definitions; it does not establish a globally cold registry/blob cache or isolate ENTRYPOINT overhead from the rest of create.

Reproduction uses the normal provider configuration below, then calls create(spec), exec(handle, "printf registry-entrypoint-cleared; curl --version", timeout_s=15), and close(handle) in finally, twice sequentially with a fresh provider each time. APP/ENV identify an existing authorized Modal App/environment; IMAGE is the digest above.

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.

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team October 19, 2026 13:54
ananthsub
ananthsub previously approved these changes Oct 19, 2026

@ananthsub ananthsub left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for the thorough contribution!

@ananthsub
ananthsub force-pushed the codex/modal-provider-upstream-submit-20261008 branch from 9bea175 to a86d085 Compare October 22, 2026 19:58
@ananthsub

Copy link
Copy Markdown
Contributor

/ok to test a86d085

@reinainblood

Copy link
Copy Markdown
Author

@ananthsub thanks again for the thorough reviews. A quick status check on where this stands:

  • The live registry/ENTRYPOINT check you asked for is in the 2026-10-09 comment above: Modal 1.6.1, curlimages/curl, the unmodified owned-create path, with first-build vs. cached create times.
  • The last CI run on a86d085c had three failures, all in tests this PR doesn't touch: test_checkpoint_agent.py::test_an_episode_the_environment_reports_as_a_restart_..., test_eval_resubmit.py::test_two_concurrent_resubmits_queue_one_job, and test_terminal.py::test_exited_shell_recovery_discards_pending_input_and_reports_lost_state[interrupt]. They look timing-sensitive, and main's own unit-test jobs pass.

Could you re-trigger /ok to test and, if you're happy with it, approve? #3650 (ExploitBench) depends on this provider for its sandboxes. Its config resolves cleanly against this branch's modal.yaml.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added needs-review PR is ready for code review and waiting on a reviewer waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-customer Waiting on the original author to respond labels Oct 28, 2026

This branch was previously deployed

1 inactive deployment
public — a86d085c Deployed Oct 23, 2026 by copy-pr-bot[bot] via release / finalize / notify #6817
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:sandbox Sandbox providers, isolation, and sandbox runtime contracts community-request Issue reported or requested by someone from the community complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer sla:review-overdue Review response is over the one-business-day SLA waiting-on-maintainers Waiting on maintainers to respond

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(sandbox): Modal sandbox provider

4 participants