Skip to content

feat(opencode): per-row sandbox inputs, model id, streamed uploads - #5904

Merged
athitten merged 5 commits into
mainfrom
opencode-sandbox-per-row-inputs
Nov 19, 2026
Merged

athitten merged 5 commits into
mainfrom
opencode-sandbox-per-row-inputs

Conversation

@jubick1337

@jubick1337 jubick1337 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Per-row sandbox inputs for opencode_sandboxed_agent: sandbox_provider_options (merged over config) and sandbox_uploads (restricted to sandbox_upload_roots). Configurable opencode_provider_id/opencode_model_id (defaults unchanged). With a deny-by-default network_policy, the model server is appended to allowed hosts instead of replacing them. OpenSandboxProvider.upload_file streams from disk. Needed for BMB-style trace generation (per-task S3 data mounts) in sdg-pipelines.

Validation

  • pytest tests/unit_tests/sandbox/test_opensandbox_provider.py responses_api_agents/opencode_sandboxed_agent/tests/test_app.py — 460 passed, 2 skipped
  • ruff check / ruff format --check (0.9.9) on touched files — clean

Rollouts

4 tasks × 1 sample on OpenSandbox (BMB-style tasks, per-task S3 mount, ECR image) via sdg-pipelines bmb-traces, on the same change applied to an earlier Gym commit: all rollouts written, sandboxes cleaned up.

Compatibility and benchmark impact

  • With network_access: model_only or model_and_tools, a configured network_policy now keeps its egress and gets the model/tool hosts appended instead of being replaced, so egress is wider.
  • A configured network_policy with defaultAction: allow and a restricted network_access now fails every row.
  • opencode_config.provider entries that name a provider or model other than opencode_provider_id/opencode_model_id now fail every row.
  • No checked-in config is affected.

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

@copy-pr-bot

copy-pr-bot Bot commented Nov 10, 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.

@svcnvidia-nemo-ci svcnvidia-nemo-ci 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.

SHIP WITH CARE — three RISK findings and one documentation NOTE.

The risks concern custom provider IDs losing existing behavior and per-row create options being silently ignored for resource-owned sandboxes.

NOTE — Document the new row and configuration contracts. The new configuration and request fields add user-facing input staging and model selection, but the harness README still describes only the previous behavior. Could you add a minimal YAML configuration and matching JSONL row, linked from the agent guide? Explain remote-destination → host-source mapping, resolved-path allowlisting on each agent-server host, the empty allowlist default, top-level row-option precedence, create-only option limitations, and provider/model defaults. Also explain that configured deny-default egress is retained alongside model/tool hosts; the current statement that other destinations are denied is no longer sufficient. Preserve the distinction that sandbox_config.files contains file contents, not local filenames, and retain the legacy-harness deprecation warning. Proposed acceptance: parse the documented row with the request model, check that an existing allowed source stages while an outside-root source is rejected, and inspect that the example's provider/model override keys match its selected IDs. This is a documentation gap, not another demonstrated runtime failure.

I inspected all four changed files and their directly affected provider, request, plugin, and subclass paths. This was a static review: I couldn't execute tests or independently verify the reported rollouts. The external OpenSandbox SDK source isn't mounted, so its stream-consumption behavior wasn't independently verified.


Inline comments (escaped v1):

  • responses_api_agents/opencode_sandboxed_agent/remaining-context.js line 6: RISK — Keep remaining_context effective with a custom provider ID. With opencode_provider_id: custom and output_token_policy: remaining_context, config generation selects custom/..., and plugin registration still installs this hook. This condition only removes maxOutputTokens for nemo_gym, however. The custom provider silently keeps the output cap instead of allowing the model server to choose its budget.

    Could you pass the configured ID to the hook rather than removing the provider guard altogether? At the launch-environment construction, replace the single assignment with:

    extra_env = self._resolve_opencode_env(query)
    extra_env["NEMO_GYM_OPENCODE_PROVIDER_ID"] = self.config.opencode_provider_id
    extra_env_str = " ".join(f"{k}={quote(v)}" for k, v in sorted(extra_env.items()))

    Then replace this condition with:

        if (input.model.providerID === (process.env.NEMO_GYM_OPENCODE_PROVIDER_ID || "nemo_gym")) {
    

    The invariant is that the policy applies to the configured Gym provider, while unrelated providers retain their limits. This preserves existing environment resolution and prevents an ordinary opencode_env value from overriding the generated ID. Please verify the suggestion before adopting it.

    Proposed acceptance, not executed: Invoke the hook with maxOutputTokens: 17. The default nemo_gym case and a configured custom case must remove the property; an unrelated provider must retain 17. Check that the launch environment contains the configured ID, and retain the existing behavior that output_token_policy: fixed doesn't register this plugin.

  • responses_api_agents/vibench_agent/app.py line 178: RISK — Apply ViBench's model URL rewrite to the configured provider. VibenchAgentConfig inherits the new opencode_provider_id, but this consumer still reads only provider.nemo_gym. With opencode_provider_id: custom, the parent now generates provider.custom. This lookup consequently returns no options and exits before either URL-rewrite branch. A host model URL of http://127.0.0.1:9000 stays loopback inside a bridged Docker sandbox, so the harness can't reach it. An explicit sandbox_model_base_url is likewise ignored.

    Could you select the provider the parent generated?

            options = ((config.get("provider") or {}).get(self.config.opencode_provider_id) or {}).get("options")
    

    This retains the missing-options guard and existing rewrite branches. The invariant is that changing the provider ID must not disable model routing. Please verify the suggestion before adopting it.

    Preservation and acceptance — proposed, not executed: Parameterize the existing TestSandboxModelUrl cases over nemo_gym and custom, asserting the corresponding provider entry. Docker loopback must become http://host.docker.internal:9000/v1; the capture-path case must retain /ng-rollout/abc123/v1; the explicit override must yield http://sandbox-gw:7000/ng-rollout/xyz/v1; and a routable non-Docker URL must remain http://10.0.0.5:9000/v1.

  • responses_api_agents/opencode_sandboxed_agent/app.py line 775: RISK — Reject per-row create options for an existing sandbox instead of ignoring them. A SWE-bench /run row can now supply sandbox_provider_options, but the resources server creates its sandbox from its own configuration and returns its handle. _run forwards the new options, yet this branch connects and returns without reading them. For example, with network_access: inherit, a row requesting a deny-default network_policy still runs under the resource-side policy, not the requested one. Per-row volumes are discarded too.

    Could you reject nonempty row options when a seed supplies a handle? Don't merely raise before connecting: seeding has already created the resource, and _run hasn't entered its cleanup block yet. A small correction is to add this guard inside the existing _run try, before _upload_inputs at the staging call:

    if seed_session_result.get("sandbox_handle") and body.sandbox_provider_options:
        raise ValueError("sandbox_provider_options cannot be applied to an externally supplied sandbox")

    That lets the existing shielded finally stop the connected sandbox. The invariant is that explicit row options are applied during creation or rejected, never silently ignored. Please verify the suggested guard before adopting it.

    Preservation and acceptance — proposed, not executed: Exercise /run with a seeded handle and nonempty row options: expect the specific error, no input staging/generation/verification, and confirmed sandbox cleanup. Empty options must still connect with the seeded workdir; retain the sb-1 /workspace/repo and sb-2 None descriptor assertions in the connection test. Newly created sandboxes must still preserve unrelated config options, apply row volumes, retain both egress entries, and reject defaultAction: allow, as asserted by the new merge test.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

@jubick1337

Copy link
Copy Markdown
Contributor Author

SHIP WITH CARE — three RISK findings and one documentation NOTE.

The risks concern custom provider IDs losing existing behavior and per-row create options being silently ignored for resource-owned sandboxes.

NOTE — Document the new row and configuration contracts. The new configuration and request fields add user-facing input staging and model selection, but the harness README still describes only the previous behavior. Could you add a minimal YAML configuration and matching JSONL row, linked from the agent guide? Explain remote-destination → host-source mapping, resolved-path allowlisting on each agent-server host, the empty allowlist default, top-level row-option precedence, create-only option limitations, and provider/model defaults. Also explain that configured deny-default egress is retained alongside model/tool hosts; the current statement that other destinations are denied is no longer sufficient. Preserve the distinction that sandbox_config.files contains file contents, not local filenames, and retain the legacy-harness deprecation warning. Proposed acceptance: parse the documented row with the request model, check that an existing allowed source stages while an outside-root source is rejected, and inspect that the example's provider/model override keys match its selected IDs. This is a documentation gap, not another demonstrated runtime failure.

I inspected all four changed files and their directly affected provider, request, plugin, and subclass paths. This was a static review: I couldn't execute tests or independently verify the reported rollouts. The external OpenSandbox SDK source isn't mounted, so its stream-consumption behavior wasn't independently verified.

Inline comments (escaped v1):

  • responses_api_agents/opencode_sandboxed_agent/remaining-context.js line 6: RISK — Keep remaining_context effective with a custom provider ID. With opencode_provider_id: custom and output_token_policy: remaining_context, config generation selects custom/..., and plugin registration still installs this hook. This condition only removes maxOutputTokens for nemo_gym, however. The custom provider silently keeps the output cap instead of allowing the model server to choose its budget.
    Could you pass the configured ID to the hook rather than removing the provider guard altogether? At the launch-environment construction, replace the single assignment with:
    extra_env = self._resolve_opencode_env(query)
    extra_env["NEMO_GYM_OPENCODE_PROVIDER_ID"] = self.config.opencode_provider_id
    extra_env_str = " ".join(f"{k}={quote(v)}" for k, v in sorted(extra_env.items()))

    Then replace this condition with:

        if (input.model.providerID === (process.env.NEMO_GYM_OPENCODE_PROVIDER_ID || "nemo_gym")) {
    

    The invariant is that the policy applies to the configured Gym provider, while unrelated providers retain their limits. This preserves existing environment resolution and prevents an ordinary opencode_env value from overriding the generated ID. Please verify the suggestion before adopting it.
    Proposed acceptance, not executed: Invoke the hook with maxOutputTokens: 17. The default nemo_gym case and a configured custom case must remove the property; an unrelated provider must retain 17. Check that the launch environment contains the configured ID, and retain the existing behavior that output_token_policy: fixed doesn't register this plugin.

  • responses_api_agents/vibench_agent/app.py line 178: RISK — Apply ViBench's model URL rewrite to the configured provider. VibenchAgentConfig inherits the new opencode_provider_id, but this consumer still reads only provider.nemo_gym. With opencode_provider_id: custom, the parent now generates provider.custom. This lookup consequently returns no options and exits before either URL-rewrite branch. A host model URL of http://127.0.0.1:9000 stays loopback inside a bridged Docker sandbox, so the harness can't reach it. An explicit sandbox_model_base_url is likewise ignored.
    Could you select the provider the parent generated?

            options = ((config.get("provider") or {}).get(self.config.opencode_provider_id) or {}).get("options")
    

    This retains the missing-options guard and existing rewrite branches. The invariant is that changing the provider ID must not disable model routing. Please verify the suggestion before adopting it.
    Preservation and acceptance — proposed, not executed: Parameterize the existing TestSandboxModelUrl cases over nemo_gym and custom, asserting the corresponding provider entry. Docker loopback must become http://host.docker.internal:9000/v1; the capture-path case must retain /ng-rollout/abc123/v1; the explicit override must yield http://sandbox-gw:7000/ng-rollout/xyz/v1; and a routable non-Docker URL must remain http://10.0.0.5:9000/v1.

  • responses_api_agents/opencode_sandboxed_agent/app.py line 775: RISK — Reject per-row create options for an existing sandbox instead of ignoring them. A SWE-bench /run row can now supply sandbox_provider_options, but the resources server creates its sandbox from its own configuration and returns its handle. _run forwards the new options, yet this branch connects and returns without reading them. For example, with network_access: inherit, a row requesting a deny-default network_policy still runs under the resource-side policy, not the requested one. Per-row volumes are discarded too.
    Could you reject nonempty row options when a seed supplies a handle? Don't merely raise before connecting: seeding has already created the resource, and _run hasn't entered its cleanup block yet. A small correction is to add this guard inside the existing _run try, before _upload_inputs at the staging call:
    if seed_session_result.get("sandbox_handle") and body.sandbox_provider_options:
    raise ValueError("sandbox_provider_options cannot be applied to an externally supplied sandbox")

    That lets the existing shielded finally stop the connected sandbox. The invariant is that explicit row options are applied during creation or rejected, never silently ignored. Please verify the suggested guard before adopting it.
    Preservation and acceptance — proposed, not executed: Exercise /run with a seeded handle and nonempty row options: expect the specific error, no input staging/generation/verification, and confirmed sandbox cleanup. Empty options must still connect with the seeded workdir; retain the sb-1 /workspace/repo and sb-2 None descriptor assertions in the connection test. Newly created sandboxes must still preserve unrelated config options, apply row volumes, retain both egress entries, and reject defaultAction: allow, as asserted by the new merge test.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

Addressed all three risks and the docs note in the latest commit. /review

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

🟡 Changes recommended

Unrestricted row overrides let task data expose the host filesystem, request privileged containers, and weaken restricted egress policies.

5 open issues
What changed in this PR

This PR extends NeMo Gym’s sandboxed OpenCode adapter for task-specific data mounts and trace generation, while preserving the default provider and model IDs.

Changes:

  • Add per-row sandbox provider options and root-restricted local-file uploads.
  • Support configurable OpenCode provider/model IDs across configuration, plugins, and Vibench.
  • Preserve configured egress rules in restricted network modes and stream OpenSandbox uploads from disk.
File Description
tests/​unit_tests/​sandbox/​test_opensandbox_provider.py Adapt the upload fake to accept file streams.
responses_api_agents/​vibench_agent/​tests/​test_app.py Cover URL rewriting with custom provider IDs.
responses_api_agents/​vibench_agent/​app.py Use the configured provider ID for URL rewriting.
responses_api_agents/​opencode_sandboxed_agent/​tests/​test_app.py Test upload roots, option merging, provider-ID export, and cleanup.
responses_api_agents/​opencode_sandboxed_agent/​remaining-context.js Apply output-budget handling to the configured provider.
responses_api_agents/​opencode_sandboxed_agent/​README.md Document per-row inputs, configurable IDs, and egress behavior.
responses_api_agents/​opencode_sandboxed_agent/​app.py Implement row-specific inputs, configurable IDs, and network-policy merging.
nemo_gym/​sandbox/​providers/​opensandbox/​provider.py Stream uploads while retaining timeout and failure handling.

Review effort: Max

@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Nov 11, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added feature New capabilities, enhancements, or enablement work area:agent Agent harnesses and Responses API agent behavior needs-review PR is ready for code review and waiting on a reviewer labels Nov 16, 2026
@cg1177

cg1177 commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

We need this for video benchmarks: MM-Lifelong agentic has source videos of several GB that go into the sandbox, and Yu Yao and I agreed to use this PR's streamed upload instead of #5365. I tested it at 3e1ce2f: a 3 GiB video uploaded with upload_file in one stream in 177.6 s (18.1 MB/s); on current main, a raw upload of 2 GB or more fails. @cmunley1 could you run /ok to test 3e1ce2f? @yaoyu-33 could you review? Thanks!

yaoyu-33 added a commit that referenced this pull request Nov 17, 2026
Merge current main and apply the shared provider streaming improvement from #5904. Reopen the file for each retry and close it on every completion path. Keep archive splitting explicit via upload_part_bytes, preserve archive metadata and cleanup, and retain optional size-based deadlines.

Validation: 429 focused tests, all-files pre-commit, and live raw/default-archive/multipart checksum smoke passed on the final diff.
Signed-off-by: yaoyu-33 <[email protected]>
yaoyu-33 added a commit that referenced this pull request Nov 18, 2026
@yfw

yfw commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

/ok to test 3e1ce2f

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 18, 2026 07:06
khazic pushed a commit to khazic/Gym-lao that referenced this pull request Nov 18, 2026
…VIDIA-NeMo#5365)

* feat(sandbox): chunk large archive uploads and scale transfer deadlines

Bound per-request upload size and allow callers to size archive deadlines from payload size. Preserve existing default deadlines and clean up attempted upload parts when a transfer fails or is cancelled.

Includes synthetic file-transfer and interruption regression tests.

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): size linked directories and report cleanup failures

Follow only the root directory symlink when sizing archive deadlines. Warn on unsuccessful multipart cleanup while preserving the original upload exception or cancellation. Add regressions for symlink semantics and command, provider, and timeout cleanup failures.

Validation: reproduced both review findings before the fix; 438 focused tests and all-files pre-commit passed after the fix.
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): preserve default deadlines and defer streaming to NVIDIA-NeMo#5904

Signed-off-by: yaoyu-33 <[email protected]>

---------

Signed-off-by: yaoyu-33 <[email protected]>
Co-authored-by: FrontierJam Agent <[email protected]>
@athitten

athitten commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

@jubick1337 @cg1177 thanks, reviewing this now

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

Reviewed at 3e1ce2f. I ran the provider, OpenCode and ViBench tests at the head and merged with current main. I also checked the streamed upload against the pinned OpenSandbox SDK (0.1.15) with a local fake server: a 1 GiB upload adds no memory (it added 1 GiB before), and a retry resends the file from byte 0. All comments are non-blocking. The README example and the upload_file error type are the two I'd fix before merge.

non-blocking (question) Scope. The README and the agent guide say not to build new configs on opencode_sandboxed_agent. The session harnesses also treat the same config differently: restrict_sandbox_network rejects network_policy together with a restricted network_access, while this PR merges them, and opencode_agent already calls the model setting sandbox_model_id. Is adding per-row inputs to this relay agreed with maintainers? If that needs more discussion, the streamed upload_file and its two tests stand alone and could land first for the video work (#6315).

optional The compatibility section is empty. Worth listing:

  • With model_only/model_and_tools, a configured network_policy's egress is now kept instead of replaced, so egress is wider.
  • A configured defaultAction: allow with a restricted network_access now fails every row.
  • opencode_config.provider entries that name another provider or model now fail every row.

No checked-in config is affected.

Comment on lines +66 to +76
```yaml
sandbox_upload_roots: [/data/inputs]
sandbox_config:
provider_options: {network_policy: {defaultAction: deny, egress: []}}
```

```json
{"responses_create_params": {"input": "..."}, "sandbox_provider_options": {"image": "x"}, "sandbox_uploads": {"/work/in.csv": "/data/inputs/a.csv"}}
```

`sandbox_uploads` maps a sandbox path to a local file, which must resolve under `sandbox_upload_roots` (empty roots refuse all). Row `sandbox_provider_options` override `sandbox_config.provider_options` at creation only, only for top-level keys the operator lists in `sandbox_row_option_keys` (default empty: any row option is rejected; `network_policy` is also rejected when `network_access` is restricted), and are rejected for a sandbox supplied by the resources server. A configured deny-default `network_policy` keeps its egress and gets the model/tool hosts appended. `opencode_provider_id` and `opencode_model_id` default to `nemo_gym` and `dummy_model`; `opencode_config` overrides must use `provider.<opencode_provider_id>.models.<opencode_model_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.

non-blocking The example fails as written. The row is rejected (sandbox_provider_options ['image'] are not listed in sandbox_row_option_keys), and listing image wouldn't help, because no provider takes it: OpenSandbox raises Unknown OpenSandbox provider option(s): image, and Docker ignores it. Under the default network_access: inherit, the deny-all policy is also sent as written, so the sandbox can't reach the model. I checked the version below: the row parses, OpenSandbox accepts the volume, an in-root upload stages, and /etc/hostname is rejected. Its sentence on what a listed key grants also answers the open row-overrides thread.

Suggested change
```yaml
sandbox_upload_roots: [/data/inputs]
sandbox_config:
provider_options: {network_policy: {defaultAction: deny, egress: []}}
```
```json
{"responses_create_params": {"input": "..."}, "sandbox_provider_options": {"image": "x"}, "sandbox_uploads": {"/work/in.csv": "/data/inputs/a.csv"}}
```
`sandbox_uploads` maps a sandbox path to a local file, which must resolve under `sandbox_upload_roots` (empty roots refuse all). Row `sandbox_provider_options` override `sandbox_config.provider_options` at creation only, only for top-level keys the operator lists in `sandbox_row_option_keys` (default empty: any row option is rejected; `network_policy` is also rejected when `network_access` is restricted), and are rejected for a sandbox supplied by the resources server. A configured deny-default `network_policy` keeps its egress and gets the model/tool hosts appended. `opencode_provider_id` and `opencode_model_id` default to `nemo_gym` and `dummy_model`; `opencode_config` overrides must use `provider.<opencode_provider_id>.models.<opencode_model_id>`.
```yaml
sandbox_upload_roots: [/data/inputs]
sandbox_row_option_keys: [volumes]
```
```json
{"responses_create_params": {"input": "..."}, "sandbox_provider_options": {"volumes": [{"name": "task", "pvc": {"claimName": "task-a"}, "mountPath": "/mnt/task", "readOnly": true}]}, "sandbox_uploads": {"/work/in.csv": "/data/inputs/a.csv"}}
```
`sandbox_uploads` maps a sandbox path to a file on the agent server host, which must resolve under `sandbox_upload_roots` (empty roots refuse all; relative paths resolve from the agent server's directory). Row `sandbox_provider_options` override `sandbox_config.provider_options` at creation only, only for top-level keys the operator lists in `sandbox_row_option_keys` (default empty: any row option is rejected; `network_policy` is also rejected when `network_access` is restricted), and are rejected for a sandbox supplied by the resources server. A listed key gives every row that provider option as is, for example host mounts through Docker `volumes` or `run_args`. With `network_access: model_only` or `model_and_tools`, a configured deny-default `network_policy` keeps its egress and gets the model/tool hosts appended; with the default `inherit` it is applied as written, so it must allow the model host itself. `opencode_provider_id` and `opencode_model_id` default to `nemo_gym` and `dummy_model`; `opencode_config` overrides must use `provider.<opencode_provider_id>.models.<opencode_model_id>`.

Comment on lines +3097 to +3114
async def upload_file(self, handle: SandboxHandle, source_path: Path, target_path: str) -> None:
"""Upload one local file into an OpenSandbox sandbox."""
await self._write_file(handle, target_path, source_path.read_bytes())

async def write() -> None:
with source_path.open("rb") as stream:
await handle.raw.files.write_file(target_path, stream)

try:
await self._await_sdk_operation(
write,
operation="write_file",
sandbox_id=handle.sandbox_id,
timeout_s=float(self._connection.request_timeout_s)
if self._connection.request_timeout_s is not None
else None,
)
except TimeoutError as error:
raise opensandbox_failure(operation="provider I/O", sandbox_id=handle.sandbox_id, cause=error) from error

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.

non-blocking Opening the file inside the _await_sdk_operation factory turns local file errors into sandbox failures. A missing or unreadable source now raises NgFailureEvent(boundary=sandbox, kind=provider_request_failed) ("remote outcome is unknown") without any SDK call; main raised FileNotFoundError/PermissionError. The /run 500 and the saved row then show that error for every OpenSandbox upload. Row inputs hit it for an unreadable file under the roots, since is_file() passes a mode-000 file. Opening the file once outside the wrapper and rewinding per attempt keeps the original error. With it, a 502 or a dropped connection still resends the whole file from byte 0 through the real SDK, and the tests pass.

Suggested change
async def upload_file(self, handle: SandboxHandle, source_path: Path, target_path: str) -> None:
"""Upload one local file into an OpenSandbox sandbox."""
await self._write_file(handle, target_path, source_path.read_bytes())
async def write() -> None:
with source_path.open("rb") as stream:
await handle.raw.files.write_file(target_path, stream)
try:
await self._await_sdk_operation(
write,
operation="write_file",
sandbox_id=handle.sandbox_id,
timeout_s=float(self._connection.request_timeout_s)
if self._connection.request_timeout_s is not None
else None,
)
except TimeoutError as error:
raise opensandbox_failure(operation="provider I/O", sandbox_id=handle.sandbox_id, cause=error) from error
async def upload_file(self, handle: SandboxHandle, source_path: Path, target_path: str) -> None:
"""Upload one local file into an OpenSandbox sandbox, streamed from disk."""
# Opened outside the SDK wrapper, so a missing or unreadable local file is not a sandbox failure.
with source_path.open("rb") as stream:
async def write() -> None:
stream.seek(0) # a retry sends the whole file again
await handle.raw.files.write_file(target_path, stream)
try:
await self._await_sdk_operation(
write,
operation="write_file",
sandbox_id=handle.sandbox_id,
timeout_s=float(self._connection.request_timeout_s)
if self._connection.request_timeout_s is not None
else None,
)
except TimeoutError as error:
raise opensandbox_failure(
operation="provider I/O", sandbox_id=handle.sandbox_id, cause=error
) from error

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not formally. I added it for the sdg-pipelines bmb-traces recipe, which has no session path yet (its resources server is the LLM judge and returns no sandbox_access), so it stays on this agent like the setups the README lists. The per-row inputs are opt-in and off by default, and no checked-in config is affected. The recipe needs both parts, so I'd prefer to keep them in one PR.

Comment on lines +3109 to +3111
timeout_s=float(self._connection.request_timeout_s)
if self._connection.request_timeout_s is not None
else 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.

non-blocking (follow-up) One per-attempt deadline still bounds the whole stream, and an upload timeout isn't retried. With the shipped request_timeout_s: 300 and the 18.1 MB/s measured above, uploads over about 5.4 GB fail on the first attempt, and the limit is lower when uploads share the link. timeout_s=None, as in download_file, isn't safe here: aiohttp starts its read timeout only after the body is sent, so a stalled upload would hang. A size-scaled deadline, or a README note to raise request_timeout_s for large sandbox_uploads, would cover the video case. Also, #4702 adds its timeout retry to _write_file, which has no callers after this PR.

resources=resources,
entrypoint=self.config.sandbox_config.get("entrypoint"),
provider_options=deepcopy(self.config.sandbox_config.get("provider_options", {})),
provider_options=deepcopy(self.config.sandbox_config.get("provider_options", {})) | deepcopy(row_options),

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.

non-blocking (question) A row value replaces the operator's value for the same key. With provider_options.volumes: [shared], sandbox_row_option_keys: [volumes] and a row volume task0, the sandbox gets only [task0], so the shared mount is gone for that row. Is that intended for list keys? The compose adapter appends lists (_merge_provider_options). Either way, a test that sets the same key in both config and row would pin it. Today they never overlap, so flipping the merge order also passes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, intended: a listed key belongs to the row, so the row value replaces the configured one, lists included. A row that also needs the shared mount can repeat it. Pinned it in the test (config volumes: [shared] + row [v] gives [v]), and the README now says lists are not merged.

forwards attached images instead of replacing them with "this model does not support image input"
(``unsupportedParts`` in OpenCode's provider/transform.ts reads ``capabilities.input.image``, which
provider.ts derives from the model's ``modalities.input``)."""
for provider_id, provider in self.config.opencode_config.get("provider", {}).items():

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.

nit opencode_config: {provider: null} (or "") now fails every rollout with AttributeError: 'NoneType' object has no attribute 'items'. It works on main, and _merge below treats both values as unset.

Suggested change
for provider_id, provider in self.config.opencode_config.get("provider", {}).items():
for provider_id, provider in (self.config.opencode_config.get("provider") or {}).items():

Comment on lines +1817 to +1818
with raises(ValueError, match="sandbox_row_option_keys"):
await server._start_sandbox(provider_options={"privileged": True})

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.

optional No test sends row options with the default empty sandbox_row_option_keys, so treating empty as "allow all" keeps the suite green (I checked). This pins the deny-by-default.

Suggested change
with raises(ValueError, match="sandbox_row_option_keys"):
await server._start_sandbox(provider_options={"privileged": True})
with raises(ValueError, match="sandbox_row_option_keys"):
await server._start_sandbox(provider_options={"privileged": True})
config.sandbox_row_option_keys = [] # the default refuses every row option
with raises(ValueError, match="sandbox_row_option_keys"):
await server._start_sandbox(provider_options={"volumes": ["v"]})

Comment on lines +1884 to +1886
with raises(ValueError, match="sandbox_upload_roots"):
await server._upload_inputs(sandbox, {"/data/b.txt": str(outside)})
assert sandbox.upload.await_count == 1

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.

optional Only a plain outside path is tested. Each of these changes keeps this file green, and each would let a row copy other host files into the sandbox (I checked all three):

  • replacing is_relative_to with a string prefix check;
  • dropping resolve();
  • letting empty roots allow everything.

These lines catch all three and pass on the head.

Suggested change
with raises(ValueError, match="sandbox_upload_roots"):
await server._upload_inputs(sandbox, {"/data/b.txt": str(outside)})
assert sandbox.upload.await_count == 1
(tmp_path / "root" / "link").symlink_to(outside)
(tmp_path / "root2").mkdir()
(tmp_path / "root2" / "c.txt").write_text("c")
# Outside, through `..`, through a symlink, or in a sibling whose name starts with the root's.
escapes = [
outside,
tmp_path / "root" / ".." / "b.txt",
tmp_path / "root" / "link",
tmp_path / "root2" / "c.txt",
]
for escape in escapes:
with raises(ValueError, match="sandbox_upload_roots"):
await server._upload_inputs(sandbox, {"/data/x": str(escape)})
config.sandbox_upload_roots = [] # no roots refuse every file
with raises(ValueError, match="sandbox_upload_roots"):
await server._upload_inputs(sandbox, {"/data/a.txt": str(allowed)})
assert sandbox.upload.await_count == 1

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.

optional VibenchAgent.run takes the same request model but builds its own sandbox, so sandbox_provider_options and sandbox_uploads are silently dropped there. Rejecting them, as the seeded-sandbox path does, keeps "applied or rejected" true. For example, before cookies = request.cookies:

        if body.sandbox_provider_options or body.sandbox_uploads:
            raise ValueError("vibench_agent does not apply sandbox_provider_options or sandbox_uploads")

@jubick1337

Copy link
Copy Markdown
Contributor Author

@athitten
Thanks for the review! Everything is addressed in e528881:

  • ViBench now rejects row sandbox_provider_options/sandbox_uploads, with a test.
  • Added your upload escape cases and the deny-by-default check.
  • opencode_config: {provider: null} works again.
  • README example replaced with your verified version.
  • upload_file opens the file outside the SDK wrapper, so local file errors raise as before.
  • README now says to raise request_timeout_s for large uploads; a size-scaled deadline can be a follow-up. _write_file had no callers left, so I removed it, and fix(sandbox): retry OpenSandbox file transfers that time out #4702's retry can go into upload_file.
  • Added your compatibility list to the PR description.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the risk:high Autobot PR risk: high label Nov 19, 2026

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

Thank you @jubick1337 for addressing the comments!

@athitten

Copy link
Copy Markdown
Contributor

/ok to test 2320421

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 19, 2026 20:12
@athitten
athitten added this pull request to the merge queue Nov 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44609774926

Merged via the queue into main with commit c4b59fc Nov 19, 2026
80 of 85 checks passed
@athitten
athitten deleted the opencode-sandbox-per-row-inputs branch November 19, 2026 20:46
zhiqi-li pushed a commit to zhiqi-li/Gym that referenced this pull request Nov 23, 2026
…ng (NVIDIA-NeMo#6628)

configs/video_mcqa_agentic.yaml wires the benchmarks' agentic setup on
the shared video_mcqa server for a question-set cohort: the stock
opencode_agent (OpenCode 1.17.11, video tools, compaction off, 262,144
tokens of context and 32,768 output tokens per call) through a
single_agent_turn_legacy Environment Server, with the resources server
lending each episode an OpenSandbox sandbox that holds the row's video.
The cohort's answer policy grades the final answer (boxed_only_v1 by
default); the config names no judge model. Rows name the agent
video_mcqa_agentic_opencode.

The README gains "Training with OpenCode": the NeMo RL settings, the
sandbox image, the limits the config sets for the trainer and the DSS
datasets of our training rows. The "Seeding" section now says that
uploads stream from disk (NVIDIA-NeMo#5904) and that the provider's
request_timeout_s bounds each upload, with the timings of 16 concurrent
3.5 GiB uploads.

The composed-config test covers the new config, and a new test starts
the server from it on an agentic question set and grades a row by its
boxed letter without a judge.

Signed-off-by: Guo Chen <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent harnesses and Responses API agent behavior feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer risk:high Autobot PR risk: high sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants