Repository navigation
feat: binary sandbox files and shared media helpers - #4917
Conversation
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]>
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]>
4c78c92 to
b8fa950
Compare
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
left a comment
There was a problem hiding this comment.
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.
0o644on partial uploads.-Tagainst a directory at the target.- Cleanup on every failure path, bounded to 30 s.
- The
SandboxUnavailableError/SandboxTransferErrorsplit, 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.
| 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()) |
There was a problem hiding this comment.
-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.
There was a problem hiding this comment.
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.
| 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()) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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]>
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]>
Where this sits
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 --> rejectThis 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.filesholds files to upload at startup, before the first command runs.AsyncSandbox.start()wrote every value withwrite_text, so only text could be uploaded this way, and abytesvalue failed with aTypeErrorbefore the upload. Abytesvalue is now written unchanged, and astrvalue is still written as UTF-8 text. Every provider uploads startup files through the same loop innemo_gym/sandbox/api.py, so the change applies to all of them. The loop callsupload(), so these uploads also get feat(sandbox): instrument file transfers #4934's transfer telemetry. The ECS Fargate engine's ownfilesfield is widened to match; the engine never reads it.nemo_gym.sandbox.utilsgainsupload_bytesanddownload_bytes, which move bytes into and out of a running sandbox throughupload()anddownload()without a shell.upload_textandread_textnow delegate to them.nemo_gym/core/media.pydecodes media in Responses messages.split_text_and_mediasplits a message into its text and its media files, andMediaFileconverts to and from data URIs.image/jpgforimage/jpeg, and parameters before;base64. It is stricter in one way:base64must be the last parameter, as RFC 2397 specifies.MediaFilealways 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 labeledimage/png, the content's type wins, so the file is written with the extension it needs; Gym's own data labels raw images asimage/pngwhatever their format.UnsupportedContentError, so callers reject the request instead of dropping the content.nemo_gym.sandbox.utilsalso gainsstage_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.mv, after checking that no directory sits there. The command uses only options that GNU, BusyBox and BSDmvall 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.SandboxUnavailableErrorand a failed commandSandboxTransferError, as the transfer helpers do./tmpdrops 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.upload_bytesrather than inagents, so a resources server or environment server that puts task media into a sandbox can use it too.nemo_gym.sandboxexports it,media_path,MEDIA_DIRECTORYand the byte helpers.upload()anddownload()directly for binary files.Why
Multimodal tasks carry media in the prompt as Responses content parts, such as an
input_imagepart 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 withstage_media; a caller that creates its own sandbox can pass the file inSandboxSpec.filesinstead.The two parts sit where the package layering allows. Decoding lives in
core, next to the Responses API types and belowmodels,agents,rolloutsanddata, 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 needsandbox, which sits abovecore, so they live innemo_gym.sandbox.utils. Images are supported today; the media-type, signature and part-type tables incore/media.pyare 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
strstartup files,upload_textandread_textbehave as before:read_textstill replaces invalid UTF-8 and turns\r\nand\rinto\n. No provider code changes: providers receive a local file path inupload_fileeither 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 thedevandsandboxextras, passed, and the import-linter layer contract passes in pre-commit.The sandbox tests check that a
bytesstartup file reaches the provider unchanged and a non-ASCIIstrstartup file arrives as UTF-8, failing with aTypeErrorwithout the change toapi.py. They also check that non-UTF-8 bytes round-trip throughupload_bytesanddownload_byteswithout any shell command, thatupload_textwrites UTF-8, and thatread_textreads\r\nand\ras\n.The media tests check:
image/jpg, a parameter before;base64), which fail without the decoder change;data:and end its header withbase64;MediaFilewhose data does not match its type are rejected, each failing without the content check;The staging tests run against a local directory and real
mvand check:stage_medianames each file by its content, returns the paths in input order and uploads a repeated file once;mvthat rejects-T, as on macOS, and that a cleanup that does not finish is abandoned after its timeout;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.