Skip to content

feat: binary sandbox files and shared media helpers - #4917

Merged
ananthsub merged 7 commits into
mainfrom
ananthsub/sandbox-spec-file-bytes
Nov 10, 2026
Merged

ananthsub merged 7 commits into
mainfrom
ananthsub/sandbox-spec-file-bytes

Conversation

@ananthsub

@ananthsub ananthsub commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Where this sits

flowchart BT
  main["main, which has 4934 telemetry<br/>and 5862 close-fence staging"]
  p4917["4917: sandbox bytes, media decoding,<br/>content-hash media staging"]
  p4922["4922: OpenCode session images"]
  p4923["4923: Pi session images"]
  p5719["5719: images in tool replies,<br/>lent sandboxes, OpenCode settings"]
  p4917 --> main
  p4922 --> p4917
  p4923 --> p4917
  p5719 --> p4922
  classDef current stroke:#d97706,stroke-width:3px
  class p4917 current
Loading

Each arrow points from a PR to its base. This branch is rebased onto main, which now has the sandbox transfer telemetry (#4934) and close-fence staging of activation files (#5862). The merge order is #4917, then #4922 and #4923 in either order; yfw's #5719 is stacked on #4922.

What changed

flowchart TD
  env["Environment server<br/>task prompt with input_image parts<br/>holding base64 data URIs"]
  seed["Agent session seed<br/>sandbox owned by the session or borrowed"]
  act["Activation request<br/>carries the task prompt"]
  subgraph shared["4917: shared, harness-neutral"]
    split["nemo_gym.core.split_text_and_media<br/>prompt text plus a list of MediaFile"]
    check["MediaFile<br/>leading bytes must be a supported image type,<br/>a PNG must start with IHDR"]
    path["nemo_gym.sandbox.media_path<br/>content-hash path per image<br/>/tmp/nemo-gym-media/sha256.ext"]
    stage["nemo_gym.sandbox.stage_media<br/>default user creates the directory,<br/>upload a .partial file per image,<br/>then mv into place in one exec"]
  end
  subgraph harness["4922 and 4923: one per harness"]
    decl["Harness model config declares image input"]
    cli["Harness command gets each path<br/>OpenCode: --file, Pi: @path"]
  end
  read["Harness reads the file<br/>and sends an image part"]
  proxy["Gym model server, a proxy"]
  deploy["Model deployment<br/>assumed to accept images"]
  reject["422 for media outside the user prompt<br/>or content that cannot be passed on"]
  env --> seed --> act --> split --> check --> path --> stage --> cli
  decl --> read
  cli --> read --> proxy --> deploy
  split --> reject
  check --> reject
Loading

This adds the shared pieces harness agents need to pass media such as images into a sandbox: byte support in the sandbox API, and one utility for media in Responses messages.

  • SandboxSpec.files holds files to upload at startup, before the first command runs. AsyncSandbox.start() wrote every value with write_text, so only text could be uploaded this way, and a bytes value failed with a TypeError before the upload. A bytes value is now written unchanged, and a str value is still written as UTF-8 text. Every provider uploads startup files through the same loop in nemo_gym/sandbox/api.py, so the change applies to all of them. The loop calls upload(), so these uploads also get feat(sandbox): instrument file transfers #4934's transfer telemetry. The ECS Fargate engine's own files field is widened to match; the engine never reads it.
  • nemo_gym.sandbox.utils gains upload_bytes and download_bytes, which move bytes into and out of a running sandbox through upload() and download() without a shell. upload_text and read_text now delegate to them.
  • nemo_gym/core/media.py decodes media in Responses messages. split_text_and_media splits a message into its text and its media files, and MediaFile converts to and from data URIs.
    • It accepts the media-type spellings Gym's Anthropic converter accepts: any case, image/jpg for image/jpeg, and parameters before ;base64. It is stricter in one way: base64 must be the last parameter, as RFC 2397 specifies.
    • A MediaFile always holds data that starts with the bytes of its media type, and a PNG must start with the IHDR chunk the PNG standard puts first. Harnesses such as Pi tell an image's type from those bytes: they skip an empty file and read a file they do not recognize as text. So an empty payload, or one that holds no supported media type, is rejected. When the label and the content disagree, as for a JPEG labeled image/png, the content's type wins, so the file is written with the extension it needs; Gym's own data labels raw images as image/png whatever their format.
    • Content it cannot pass on raises UnsupportedContentError, so callers reject the request instead of dropping the content.
  • nemo_gym.sandbox.utils also gains stage_media(sandbox, files), which writes each media file to /tmp/nemo-gym-media/<sha256>.<extension> and returns the paths in order; media_path(file) gives that path before staging.
    • The path depends only on the content, so every rollout of a task gets the same prompt.
    • The sandbox's default user creates the media directory first, so the rename works when uploads run as another user, such as root on Docker.
    • Each file is uploaded under a unique partial name, readable by every user, and one command then renames every file onto its path with mv, after checking that no directory sits there. The command uses only options that GNU, BusyBox and BSD mv all accept, so it also works with the local provider on macOS. A rename is atomic, so sessions sharing a borrowed sandbox only ever replace a file with identical bytes and never read a partly written one.
    • When an upload or the rename fails, times out or is cancelled, the partial files are removed, with the cleanup bounded to 30 seconds. The cleanup is shielded from cancellation, because an anyio cancel scope, such as the one that cancels a request when its client disconnects, stays cancelled and would otherwise cancel the cleanup too. A provider error raises SandboxUnavailableError and a failed command SandboxTransferError, as the transfer helpers do.
    • Sessions never delete staged files, because another session may be reading them. A sandbox with its own /tmp drops them when it is destroyed; the local provider, and Apptainer without --contain, use the host's /tmp, where they stay until the host clears it.
    • It sits beside upload_bytes rather than in agents, so a resources server or environment server that puts task media into a sandbox can use it too. nemo_gym.sandbox exports it, media_path, MEDIA_DIRECTORY and the byte helpers.
  • The sandbox overview page describes both kinds of startup file and shows the byte and media helpers. The harness guide lists them, in place of its advice to call upload() and download() directly for binary files.

Why

Multimodal tasks carry media in the prompt as Responses content parts, such as an input_image part holding a base64 data URI. Harness CLIs read media from files on disk (opencode run --file, pi @file), so an agent has to decode the part and write the file into the sandbox first. A harness agent session usually receives a sandbox that is already running, often borrowed from the environment server, so it writes with stage_media; a caller that creates its own sandbox can pass the file in SandboxSpec.files instead.

The two parts sit where the package layering allows. Decoding lives in core, next to the Responses API types and below models, agents, rollouts and data, so each of them can share it. Today the Anthropic converter, the harness conformance checker, the OpenCode sandboxed agent and the Stirrup agent each parse data URIs on their own. The sandbox transfers need sandbox, which sits above core, so they live in nemo_gym.sandbox.utils. Images are supported today; the media-type, signature and part-type tables in core/media.py are the extension point for audio and video, so agents keep calling the same functions when those are added.

#4922 (OpenCode) and #4923 (Pi) are stacked on this branch and use these helpers to pass prompt images into agent sessions.

No issue: this is a small, self-contained API extension.

Compatibility

Existing str startup files, upload_text and read_text behave as before: read_text still replaces invalid UTF-8 and turns \r\n and \r into \n. No provider code changes: providers receive a local file path in upload_file either way.

Validation

  • pytest tests/unit_tests/sandbox/test_sandbox.py tests/unit_tests/agents/test_sandbox_supervisor_client.py tests/unit_tests/core/test_media.py tests/unit_tests/sandbox/test_sandbox_media.py tests/unit_tests/test_public_api_facades.py tests/unit_tests/test_public_api.py tests/unit_tests/test_import_linter_coverage.py, with the dev and sandbox extras, passed, and the import-linter layer contract passes in pre-commit.

  • The sandbox tests check that a bytes startup file reaches the provider unchanged and a non-ASCII str startup file arrives as UTF-8, failing with a TypeError without the change to api.py. They also check that non-UTF-8 bytes round-trip through upload_bytes and download_bytes without any shell command, that upload_text writes UTF-8, and that read_text reads \r\n and \r as \n.

  • The media tests check:

    • data URI round trips;
    • the other spellings of a supported type (uppercase, image/jpg, a parameter before ;base64), which fail without the decoder change;
    • that a URI must start with data: and end its header with base64;
    • that each signature variant (GIF87a, a WEBP size holding a newline byte) is accepted and a near miss or an offset signature is rejected;
    • that the content decides the type of a mislabeled file, and that an empty payload, a payload of no supported type, a PNG without its IHDR chunk and a MediaFile whose data does not match its type are rejected, each failing without the content check;
    • that the repr leaves out the data;
    • decoding text and media in order, including both text part types and a text part without text;
    • rejection of URLs, file IDs, unsupported media types, invalid base64 and non-media parts.
  • The staging tests run against a local directory and real mv and check:

    • that stage_media names each file by its content, returns the paths in input order and uploads a repeated file once;
    • that the default user creates the media directory before any upload, and that staged files are readable by every user under a private umask;
    • that two concurrent stagings of the same image, with uploads written in two halves, never expose a partial file at the shared path;
    • that a failed, partial or raising upload, a rename failing anywhere in the chain, a rename that raises, times out, or is cancelled by an asyncio task or an anyio cancel scope, and a directory at the target path each leave no partial file behind;
    • that staging works with an mv that rejects -T, as on macOS, and that a cleanup that does not finish is abandoned after its timeout;
    • which error each failure raises, and that a failing cleanup keeps the original error and logs.

    Each fix's test fails when that fix is reverted.

  • pre-commit run --files <changed files> passed.

Rollout evidence

N/A: this adds library functions and changes how files are written into sandboxes, with no environment or agent behavior. The OpenCode and Pi PRs stacked on it carry rollout evidence.

@ananthsub ananthsub added feature New capabilities, enhancements, or enablement work area:sandbox Sandbox providers, isolation, and sandbox runtime contracts labels Oct 22, 2026
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 22, 2026 14:00
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the needs-review PR is ready for code review and waiting on a reviewer label Oct 22, 2026
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

@ananthsub
ananthsub requested a review from hemildesai October 22, 2026 14:03
@ananthsub ananthsub changed the title feat(sandbox): accept bytes in SandboxSpec.files feat(sandbox): write binary files into sandboxes Oct 22, 2026
@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team October 22, 2026 14:32
@ananthsub ananthsub changed the title feat(sandbox): write binary files into sandboxes feat(sandbox): binary sandbox files and a shared media utility Oct 22, 2026
@ananthsub ananthsub changed the title feat(sandbox): binary sandbox files and a shared media utility feat: binary sandbox files and a shared media utility Oct 22, 2026
@ananthsub
ananthsub requested a review from yfw October 22, 2026 17:32
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Oct 23, 2026
yaoyu-33 added a commit that referenced this pull request Nov 9, 2026
Fold in what #4917 (shared media decoding and staging) and #4922 (OpenCode
session images) settle: how MediaFile decides a file's type, why
stage_media names files by content, why staged files survive close in a
borrowed sandbox, decoding once per activation request, staging inside
the activation's execution so close can cancel it, SandboxSpec.files bytes
for startup files, and OpenCode's _session_input and stage_activation as
the reference adapter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
ananthsub added a commit that referenced this pull request Nov 9, 2026
Follow #4917's staging changes: the fake sandbox now renames files with
the separate mv -fT command. A new test checks that a provider timeout or a
refused rename while staging images fails the activation as a server error
rather than ending it incomplete. The README now limits the claim that a
timeout before launch leaves the session usable to the activation's own
budget.

Signed-off-by: Ananth Subramaniam <[email protected]>
SandboxSpec.files uploads seed files before the first command runs.
Every value was written with write_text, so only text could be seeded.
A harness that needs a binary file in the sandbox, such as a prompt image,
had to encode it and decode it inside the sandbox.

A bytes value is now written unchanged, and a str value is still written as UTF-8 text.
The type annotations on SandboxSpec, SandboxConfig.spec and the ECS Fargate engine spec
say so, and the sandbox docs describe both forms.

Signed-off-by: Ananth Subramaniam <[email protected]>
Seed files cover content written when a sandbox is created.
A harness agent session usually receives a sandbox that is already running,
often borrowed from the environment server, so it needs to write content afterwards.
upload_text already does that for UTF-8 text by writing a temporary file and calling upload().

upload_bytes writes bytes unchanged the same way, and upload_text now delegates to it.
The sandbox docs show both helpers.

Signed-off-by: Ananth Subramaniam <[email protected]>
Harness agents receive media as Responses content parts, such as an input_image part
holding a base64 data URI, while harness CLIs read media from files.

nemo_gym.core.media decodes a message into its text and media files (split_text_and_media),
converts MediaFile to and from data URIs, and names the media type a file extension implies.
It accepts the spellings Gym's Anthropic converter accepts: any case, image/jpg for image/jpeg,
and parameters before ;base64.
Content it cannot pass on raises UnsupportedContentError, so a caller rejects the request
instead of dropping the content.
It sits in core, below models, agents, rollouts and data, so each of them can share it.

upload_media writes media files into a sandbox and download_media reads one back. They sit
in nemo_gym/sandbox/utils.py next to upload_bytes and download_bytes, which they call, so
agents, resources servers and environment servers can all use them.
Images are supported today; audio and video need entries in core.media's type tables.

download_bytes joins upload_bytes in nemo_gym/sandbox/utils.py, and read_text delegates to it.
nemo_gym.sandbox exports all four byte and media helpers.

Signed-off-by: Ananth Subramaniam <[email protected]>
Harnesses such as Pi tell an image's type from its leading bytes. They skip
an empty file and read one they do not recognize as text, so such media
never reaches the model as an image. MediaFile now requires its data to
start with the bytes of its media type. from_data_uri rejects a payload
that is empty or holds no supported media type, and takes the type from the
content when the label differs, because Gym's own data labels raw images
as image/png whatever their format.

read_text decoded the downloaded bytes directly, which stopped turning
\r\n and \r into \n as Path.read_text did. It translates them again, so
harness logs read the same as before.

download_media and media_type_for_path had no caller, so they are removed
until one needs them. MediaFile leaves its data out of its repr. The
harness guide and the sandbox page describe the byte and media helpers.

Signed-off-by: Ananth Subramaniam <[email protected]>
Replace upload_media with stage_media, which writes each media file to
/tmp/nemo-gym-media/<sha256>.<extension> and returns the paths in order.
Rollouts of one task then get the same paths, and so the same prompt.
Each file is uploaded under a unique partial name and renamed onto its
path in one command, so sessions sharing a borrowed sandbox only ever
replace a file with identical bytes and never read a partial one.
Partial uploads are removed when an upload or rename fails; staged files
are never deleted, since another session may be reading them.
media_path gives a file's path before it is staged.

The PNG check now also requires the IHDR chunk that the PNG standard
puts first: Pi reads a PNG without it as text.

Signed-off-by: Ananth Subramaniam <[email protected]>
Review fixes for stage_media:
- The sandbox's default user creates the media directory before any
  upload, so the rename works when uploads run as another user, such as
  root on Docker with a non-root task user.
- Partial uploads are made readable by every user, since copying
  providers keep the host file's mode, which a private umask restricts.
- mv -T fails on a directory at the target path instead of moving the
  file into it.
- Partial files are removed when the rename raises, times out or is
  cancelled, not only when an upload fails. The cleanup is bounded to
  30 seconds and logs a failed rm.
- A provider error raises SandboxUnavailableError and a failed command
  SandboxTransferError, as the transfer helpers do, so callers can tell
  an outage from a failure inside the sandbox.
- The docs no longer claim staged files always end with the sandbox:
  the local provider and Apptainer without --contain use the host's /tmp.

Tests cover each of these, the order of returned paths, a rename that
fails partway through the chain, and stricter media signatures.

Signed-off-by: Ananth Subramaniam <[email protected]>
@ananthsub
ananthsub force-pushed the ananthsub/sandbox-spec-file-bytes branch from 4c78c92 to b8fa950 Compare November 9, 2026 20:50
ananthsub added a commit that referenced this pull request Nov 9, 2026
Follow #4917's staging changes: the fake sandbox now renames files with
the separate mv -fT command. A new test checks that a provider timeout or a
refused rename while staging images fails the activation as a server error
rather than ending it incomplete. The README now limits the claim that a
timeout before launch leaves the session usable to the activation's own
budget.

Signed-off-by: Ananth Subramaniam <[email protected]>

@yaoyu-33 yaoyu-33 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.

Re-reviewed stage_media at b8fa950 (since 1026f97). The fixes hold up:

  • The default user creates the directory, so the rename works when uploads run as another user.
  • 0o644 on partial uploads.
  • -T against a directory at the target.
  • Cleanup on every failure path, bounded to 30 s.
  • The SandboxUnavailableError / SandboxTransferError split, so the episode retries only outages.

The harness guide PR #5868 now describes these.

Two inline notes. Neither blocks: the first only hits non-GNU mv, and the second only an anyio-style cancellation.

Comment thread nemo_gym/sandbox/utils.py Outdated
partials[path] = f"{MEDIA_DIRECTORY}/.{uuid.uuid4().hex}.partial"
await _upload(sandbox, path=partials[path], data=file.data, readable_by_all=True)
# -T fails on a directory at the target path, which mv would otherwise move the file into.
renames = " && ".join(f"mv -fT -- {quote(partial)} {quote(path)}" for path, partial in partials.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.

-T is GNU-only. BSD mv rejects it. On macOS (Darwin 25) I get mv: illegal option -- T (exit 64), so stage_media() raises SandboxTransferError for every image on the local provider on a Mac. Harness sessions need Linux for the supervisor anyway, but stage_media() is documented as a general helper in the sandbox page.

Please also check that BusyBox mv accepts -T, since some task images are Alpine-based; I did not verify that.

A portable form keeps the directory guard: [ ! -d {path} ] && mv -f -- {partial} {path}. The race between the test and the mv only matters when something creates a directory at a content-hash path, the same case -T guards against.

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.

Fixed in 02c3db6. The rename now checks for a directory first and then runs mv -f, failing with "<path> is a directory" when one is in the way. BusyBox 1.36 (Alpine 3.20) does accept -T, but the portable form doesn't depend on that. A new test stages with an mv that rejects -T.

Comment thread nemo_gym/sandbox/utils.py Outdated
renames = " && ".join(f"mv -fT -- {quote(partial)} {quote(path)}" for path, partial in partials.items())
await _run_media_command(sandbox, renames, action="rename the staged media files")
except BaseException:
await _remove_partial_media(sandbox, partials.values())

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: this cleanup runs in an except that a cancellation also enters. Under asyncio's one-shot task.cancel(), the next await runs, so the close-during-staging test passes. Under an anyio cancel scope, which stays cancelled, sandbox.exec here is cancelled at once and the partial files stay.

LentSandboxes._stop in #5719 shields its stop for the same reason. Wrapping this call in anyio.CancelScope(shield=True) would keep the cleanup independent of how the caller cancels; it is already bounded by _CLEANUP_TIMEOUT_S.

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.

Fixed in 02c3db6. This was reachable in Gym itself: the client-disconnect middleware cancels handlers through an anyio task group. The cleanup now runs in anyio.move_on_after(30, shield=True), so it runs under either kind of cancellation and still gives up after 30 s, logging a warning. New tests cancel a staging through an anyio task group and check that the partial files are removed, and check that a cleanup that never finishes is abandoned after the timeout.

yaoyu-33 added a commit that referenced this pull request Nov 9, 2026
Pi (#4923) now takes prompt images as @path arguments, so it joins
OpenCode as a reference adapter and gets its own row in the adapter
table, with where Pi puts the images and its default resizing (which
images.autoResize turns off). From the updated #4917: who creates the
media directory, cleanup of partial files on failure, where staged files
live on providers that share the host's /tmp, and the
SandboxUnavailableError / SandboxTransferError split. Staging now has to
run under the activation's deadline, as Pi does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
GNU mv -T refused a directory at the target path, but BSD mv, as on
macOS, has no -T, so staging failed for every file on the local
provider there. The rename now tests for a directory first and uses
only options GNU, BusyBox and BSD mv all accept.

The cleanup of partial uploads ran in an except block that a
cancellation also enters. An anyio cancel scope, such as the one that
cancels a request when its client disconnects, stays cancelled, so the
cleanup was cancelled at once and the partial files stayed. The cleanup
now runs in a shielded scope with the same 30 second deadline, and logs
when it gives up.

Signed-off-by: Ananth Subramaniam <[email protected]>
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 9, 2026 23:10
@ananthsub
ananthsub requested a review from yaoyu-33 November 9, 2026 23:11
ananthsub added a commit that referenced this pull request Nov 9, 2026
Follow #4917's staging changes: the fake sandbox now renames files with
the separate mv -fT command. A new test checks that a provider timeout or a
refused rename while staging images fails the activation as a server error
rather than ending it incomplete. The README now limits the claim that a
timeout before launch leaves the session usable to the activation's own
budget.

Signed-off-by: Ananth Subramaniam <[email protected]>

This branch was previously deployed

1 inactive deployment
public — 02c3db61 Deployed Nov 9, 2026 by copy-pr-bot[bot] via release / finalize / notify #11212
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 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants