Skip to content

feat(sandbox): bwrap sandbox provider - #6279

Merged
yaoyu-33 merged 3 commits into
mainfrom
stepheng/bwrap-provider
Nov 20, 2026
Merged

yaoyu-33 merged 3 commits into
mainfrom
stepheng/bwrap-provider

Conversation

@stephencge

@stephencge stephencge commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds a bwrap (bubblewrap) provider to Gym's sandbox API. Each sandbox is a host directory
(<base_dir>/<id>/{workspace,tmp,home}) run under its own unprivileged user, mount and pid namespace. There is no
daemon, no image and no long-lived container process:

  • the environment is allow-listed;
  • GPUs are hidden by default;
  • file transfer is contained, and symlinks, .. and FIFOs are refused;
  • exec concurrency is bounded;
  • stop kills tracked processes and removes the sandbox directory.

It is meant for hosts where container runtimes aren't available inside a job, for example a Slurm + pyxis step.

It also adds an optional SupportsSandboxExecScopedProcesses protocol and AsyncSandbox.exec_processes_terminated().
A caller (the harness supervisor, in #6280) can use them to confirm from the provider side that no exec
process can still run.

No issue: the provider is new and self-contained.

Validation

At 44b774f (round 2; c226865 had 1708 passed with the same 78):

  • Linux (Debian 12 container, kernel 7.0, bwrap 0.8.0, tests run as a non-root user with
    NEMO_GYM_REQUIRE_BWRAP=1):
    • pytest -m "sandbox or not sandbox" tests/unit_tests/sandbox tests/unit_tests/agents/test_sandbox_session.py:
      1713 passed.
    • The 78 failures are identical on main at 5d6429f. They are OpenSandbox tests run without the sandbox
      extra.
    • Every real-bwrap test passes:
      • isolation;
      • the process proof from creator and borrower;
      • the --info-fd child being the namespace's pid 1;
      • a timeout killing setsid children;
      • a borrower's stop killing an in-flight exec;
      • planted symlinks refused.
  • macOS: the same suites with no new failures. The real-bwrap tests skip there.
  • CI: CI now installs bubblewrap and sets NEMO_GYM_REQUIRE_BWRAP=1, so a skip becomes a failure. It also
    lifts Ubuntu 24.04's AppArmor restriction on unprivileged user namespaces, which otherwise makes bwrap fail with
    "setting up uid map". Whether the runner allows that is unverified until CI runs.
  • pre-commit run passes on the changed files.

Rollouts

The provider ran every episode of about 15 full agentic evaluations (466 Codex episodes each) of an internal CUDA
kernel benchmark on a GB300 Slurm + pyxis cluster.

Compatibility and benchmark impact

None. The provider is opt-in, and the protocol and method are additive.

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 (macOS, and Linux with real bwrap; see Validation).
  • Documentation added or updated, or N/A with justification.
  • Pre-commit checks pass locally on the changed files.
  • New source files include the required Apache-2.0 SPDX header.
  • All commits have DCO sign-off (git commit -s).

🤖 Generated with Claude Code

A bubblewrap provider for Gym's sandbox API: one unprivileged user+mount+pid namespace per sandbox on the
host (no daemon, no image), an allow-listed environment with GPUs hidden, contained file transfer, bounded
exec concurrency, and a stop that kills tracked processes and removes the sandbox directory.

Adds the optional SupportsSandboxExecScopedProcesses protocol and AsyncSandbox.exec_processes_terminated, so a
caller can confirm from the provider side that no exec process can still run. Tests live in
tests/unit_tests/sandbox/ (unit tests with a fake bwrap; integration tests with the real binary when present).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Stephen Ge <[email protected]>
@copy-pr-bot

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

yaoyu-33
yaoyu-33 previously approved these changes Nov 17, 2026

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

Thanks for this. A daemon-free, image-free provider for container-less Slurm steps fills a real gap. The openat/O_NOFOLLOW transfer walk, FIFO handling, --die-with-parent teardown and GPU hiding all held up when we tested them against real bwrap.

Approving: we found no blockers. Four inline comments are risks we'd like fixed before this is marked ready:

  • the host-side mount-point creation through /tmp;
  • an exec queued on exec_concurrency that outlives stop();
  • the provider failure contract;
  • CI never running the real-bwrap tests.

The rest are notes.

How we checked: we ran the PR's bwrap tests on a Linux workstation against real bwrap 0.4.0 with working user namespaces (28 passed), and we added real-bwrap probes for stop, timeout, borrower and path cases. The rest of tests/unit_tests/sandbox showed no regressions, and import-linter passes. We ran no model rollouts.

PR body: "Linux-only tests are left to CI" isn't accurate today, because CI doesn't install bubblewrap (see the inline comment). Could you update it with a Linux run at this head?

Stacked #6280: the comments on exec_processes_terminated, uploads_independent_of_execs, the /tmp mounts and the failure contract also apply to the Codex-on-bwrap path there.

DEFAULT_ENV_PASSTHROUGH: tuple[str, ...] = ("PATH", "LANG", "LD_LIBRARY_PATH", "CUDA_HOME")


class BwrapCreateError(SandboxCreateError):

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.

nemo_gym/sandbox/providers/bwrap/provider.py:111-116

Risk: this provider uses the compatibility error contract that the provider guide says new providers must not use.

adding-a-provider.mdx:64 says "New provider implementations must follow this lifecycle and failure contract": allocation, readiness and runtime failures raise NgFailureEvent through nemo_gym.sandbox.failures.sandbox_failure with a registered kind. index.mdx:423-426 adds that SandboxCreateError/SandboxCreateVerificationError "are not an alternative contract for new providers".

This provider subclasses those classes. It also returns spawn and setup failures as error-valued results (error_type="sandbox", rc 125), and raises a bare RuntimeError for stop failures (:659, :872).

Callers handle all of this today, so it isn't a correctness break. Could you either:

  • move to the failure-event contract (for example provider_setup_failed for create and probe, provider_command_timeout for timeouts); or
  • with a maintainer's OK, add bwrap to the "Required provider migrations" table with a tracking issue?

Whichever lands, #6280's Codex-on-bwrap path inherits it.

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.

Took the second option in c226865. bwrap is in the "Required provider migrations" table, and bwrap.mdx says it still uses the compatibility classes.

All the other built-in providers except OpenSandbox are already in that table, Local, Docker, Apptainer and Enroot included. Migrating bwrap alone would also mean changing its callers (codex_agent's error handling) in this PR.

Do you want a tracking issue for it, or is the table entry enough?

Comment thread nemo_gym/sandbox/providers/base.py Resolved
@svcnvidia-nemo-ci svcnvidia-nemo-ci added feature New capabilities, enhancements, or enablement work area:sandbox Sandbox providers, isolation, and sandbox runtime contracts labels Nov 17, 2026
…s, setup-failure channel, CI)

- Mount targets at, above or inside the sandbox's own /tmp, home or workdir are refused (bwrap would create the
  mount point in sandbox-writable space, following symlinks, or shadow that directory), and the workspace is
  bound at its host path only when that path lies outside them (the default base_dir is under /tmp).
- An exec queued on exec_concurrency re-checks the closing marker after taking its slot; close() waits (bounded)
  for this instance's execs that are about to spawn; exec_processes_terminated() is False while any is queued or
  starting.
- bwrap's own setup failure is detected from --info-fd (no child-pid reported), a channel the command cannot
  write; a command printing "bwrap: ..." now fails as itself.
- uploads_independent_of_execs() is True (uploads never take the exec semaphore); the info pipe is closed on any
  spawn exception; SupportsSandboxExecScopedProcesses is exported with the other protocols and documented
  generically.
- bwrap is listed under "Required provider migrations"; docs fixed (cancel re-raises, probe only with
  probe_on_create, exec_processes_terminated); the Codex runtime-mount section is dropped (mounts under /tmp are
  refused now).
- CI installs bubblewrap and sets NEMO_GYM_REQUIRE_BWRAP=1 so the real-bwrap tests fail instead of skipping; new
  real-bwrap tests cover the process proof (creator and borrower), the info-fd child being pid 1, timeouts
  killing setsid children, a borrower's stop, and planted symlinks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Stephen Ge <[email protected]>
stephencge added a commit that referenced this pull request Nov 17, 2026
@stephencge
stephencge requested a review from yaoyu-33 November 17, 2026 22:12
@yaoyu-33
yaoyu-33 marked this pull request as ready for review November 17, 2026 23:06
@yaoyu-33
yaoyu-33 requested a review from a team as a code owner November 17, 2026 23:06
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the needs-review PR is ready for code review and waiting on a reviewer label Nov 17, 2026

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

Rechecked the updated implementation; one mount-overlap case remains.

for mount in mounts:
if not os.path.exists(mount.src):
raise BwrapCreateError(f"bwrap mount source {mount.src!r} does not exist")
if workdir == self._config.home_path:

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 we also reject overlapping built-in mount paths, not just equality? With workdir=/home and the default home_path=/home/sandbox, upload to /home/sandbox/marker.txt succeeds but cat inside the sandbox reports no such file (reproduced with real bwrap). The workspace mount hides the home directory while transfers still target it. Please validate the effective workdir, including SandboxSpec.workdir overrides.

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 44b774f. /tmp, home_path and the workdir must now be pairwise disjoint, checked against the config and against each sandbox's effective workdir (SandboxSpec.workdir overrides included).

workdir=/home with the default home, /home/sandbox, /home/sandbox/w, /tmp/w, and workdir=/task with home_path=/task/home are all refused before allocation; disjoint /task still works (test_own_directories_must_be_disjoint).

Linux (bwrap 0.8.0, non-root, NEMO_GYM_REQUIRE_BWRAP=1): tests/unit_tests/sandbox + test_sandbox_session.py 1713 passed; the 78 failures are the OpenSandbox SDK tests, identical on main.

@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

I found five RISK-level issues in cross-provider process tracking, transfer resolution and reconnect behavior. They affect the opt-in bwrap provider; I found no blockers.

The current source includes the earlier /tmp mount restrictions, queued-exec recheck, capability exports and real-bwrap CI requirement. I inspected all 16 changed files and their directly affected contracts and callers. This was a static review: I did not execute tests or verify the runner's namespace support. The regression checks below are proposed, and suggested code needs verification before adoption.

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

an unreadable record or an init this instance failed to record, is False.
"""
inst: _BwrapSandbox = handle.raw
if inst.sandbox_id in self._untracked_inits or self._pending_execs.get(inst.sandbox_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.

RISK: pending execs are invisible to other provider instances.

With two providers sharing a sandbox, provider A can have an exec queued while provider B returns True here. For example, set A's exec_concurrency=1, occupy its slot with another sandbox, then queue an exec for the shared sandbox. A records that request only in its own _pending_execs; B sees neither that entry nor a process record, so it reports termination even though the queued command can still run. This violates the new protocol's explicit no-queued-or-starting guarantee.

The same visibility gap affects stop: process registration happens after the spawn await, while close waits only for its own pending execs. Another instance's spawned-but-unregistered command can therefore escape both kill passes.

Could you make queued/starting ownership visible across provider instances and synchronize the final closing check, spawn-to-registration transition and close? The invariant is that a termination proof cannot succeed while another instance has an admitted exec, and close cannot report success or remove the registry while such an exec can still start or run. Keep the operation bounded; if ownership cannot be drained or proved, report failure rather than deleting its evidence. I have not supplied a patch because the cross-process synchronization choice affects all three operations.

Proposed acceptance checks: use two actual provider instances. While A's target-sandbox exec is queued behind an unrelated sandbox, B's proof must be False; after both commands finish it must become True. Add a controlled pause after spawning but before registration, then stop through B: stop must either wait and kill that command or fail retryably without deleting its tracking state. Retain the existing assertion that a queued command never runs after stop, registered borrower-stop coverage, PID-reuse protection and idempotent close.

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

  • Shared records: a pending exec (queued on exec_concurrency or about to spawn) writes a record to the sandbox's run/ (pending-*, with the owner's pid and start time) and removes it only after its bwrap process is registered, so every provider instance sees it.
  • Proof: exec_processes_terminated() is False while a live owner holds one; an unreadable record counts as live.
  • Stop: close() waits, bounded by kill_timeout_s, for any instance's records before its final kill pass. Since registration precedes removal, that pass sees the spawned process.
  • Stale records: a dead owner's record is removed.
  • Tests: test_a_pending_exec_of_another_instance_blocks_the_proof_and_the_stop (provider A queues for a shared sandbox; borrower B can neither prove it empty nor stop past it, and the queued command never runs) and test_a_dead_owners_pending_record_does_not_block_the_proof.

for mount in mounts:
if not os.path.exists(mount.src):
raise BwrapCreateError(f"bwrap mount source {mount.src!r} does not exist")
if workdir == self._config.home_path:

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.

RISK: a workspace mounted above home hides the home directory from commands but not transfers.

SandboxSpec(workdir="/home") passes this equality-only check with the default home /home/sandbox. The argv builder mounts home first, then workspace over /home, hiding that home mount. However, the transfer table still maps /home/sandbox/x to inst.home/x. An upload succeeds but the next command cannot see the uploaded bytes.

Could you reject a workdir that contains the home destination before allocating the sandbox? The smallest correction for this shadowing case is to replace the equality check with:

home = posixpath.normpath(self._config.home_path)
if workdir == home or home.startswith(workdir.rstrip("/") + "/"):
    raise BwrapCreateError("bwrap workdir cannot equal or contain home_path")

This keeps the home transfer mapping attached to a visible mount. It does not blanket-reject every nested destination or change extra-mount permissions.

Proposed acceptance checks: creating with workdir /home and default home must fail before allocation; so must workdir /task with home /task/home. Retain equality rejection, default /workspace, disjoint custom workdir /task and home /users/agent, and the working /tmp workdir case where /tmp/x transfers resolve to the workspace mounted there. Keep /tmpdata distinct from /tmp and retain the existing extra-mount overlap rejection tests.

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 44b774f. The check is broader than the suggestion: /tmp, home_path and the workdir must be pairwise disjoint, so a workdir inside /tmp (its mount point would be in sandbox-writable space) is refused too. The acceptance cases are in test_own_directories_must_be_disjoint.

if self._binds_workspace_host_path(inst):
table.append((str(inst.workspace), inst.workspace, True))
table += [(posixpath.normpath(m.dst), Path(m.src), not m.ro) for m in [*self._config.mounts, *inst.mounts]]
return sorted(table, key=lambda entry: len(entry[0]), reverse=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.

RISK: transfer resolution ignores which overlapping extra mount is visible.

A config mount {src: A, dst: /tools, ro: false} followed by a per-sandbox mount {src: B, dst: /tools, ro: true} is accepted. The argv builder applies B last, but this stable length sort keeps A first. Upload then modifies A despite the visible mount being read-only B, and download returns A's bytes instead of B's. A later parent mount similarly hides an earlier child mount, which longest-prefix matching alone cannot represent.

Could you construct the effective table in bind order and remove earlier mappings hidden by each later mount? First put the owned entries in argv order: /tmp, home, workspace, then the optional workspace alias. After appending extra mounts, replace the final sort with:

effective = []
for entry in table:
    prefix = entry[0]
    effective = [
        previous for previous in effective
        if not (
            previous[0] == prefix
            or previous[0].startswith(prefix.rstrip("/") + "/")
        )
    ]
    effective.append(entry)
return sorted(effective, key=lambda entry: len(entry[0]), reverse=True)

The invariant is that transfer source and writability match the bind visible to the command. A later child must remain more specific than its earlier parent.

Proposed acceptance checks: for the duplicate destinations above, download must return B's bytes and upload must raise BwrapPathError, leaving A unchanged. With earlier /tools/sub and later /tools, resolve /tools/sub/x through the later parent. In the opposite order, retain the later child mapping. Pre-create child mount points for real-bwrap tests. Preserve disjoint mounts, /tools versus /tools2, workspace-at-/tmp resolution, and symlink/FIFO rejection.

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 44b774f. _mount_table is now built in bind order (/tmp, home, workspace, the optional alias, then the extra mounts), with your filter: a later mount at or above an earlier one's destination drops it.

test_transfers_resolve_to_the_bind_a_command_sees covers both cases:

  • a config read-write mount hidden by a per-sandbox read-only one at /tools: download returns the visible bytes, and upload is refused as read-only;
  • a later parent mount hiding an earlier child.

raise ValueError(f"bwrap sandbox {sandbox_id} has no readable state file") from error
if state.get("sandbox_id") != sandbox_id:
raise ValueError(f"bwrap sandbox {sandbox_id} state file does not match its directory")
for key in ("workdir", "network"):

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.

RISK: reconnect rejects a working directory changed through the public facade.

Start at /workspace, create /workspace/project, call set_default_workdir("/workspace/project"), then serialize and connect. The facade serializes the current default cwd, while the state file correctly keeps /workspace as the workspace bind destination. This comparison treats those different values as one contract and rejects the descriptor. An initial spec workdir /workspace/ also fails round-trip because creation normalizes the state value but the facade carries the original spelling.

Could you stop comparing the descriptor's generic workdir with the immutable bind destination? Replace this loop header with:

Suggested change
for key in ("workdir", "network"):
for key in ("network",):

Keep loading inst.workdir from the host-only state file. The facade already restores the descriptor's default cwd into its own SandboxSpec, so accepting that cwd does not move the workspace mount. Update the README's descriptor-validation wording to distinguish these fields.

Proposed acceptance checks: add a bwrap case matching the existing facade regression test. After changing the default cwd to a created subdirectory, a connected sandbox's pwd must return that directory, while /workspace/file uploads still reach the original workspace. Also round-trip /workspace/. Update the bwrap refusal test that currently rejects any changed descriptor workdir; retain network mismatch, host/uid/base-dir/id checks and ordinary round-trips.

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 44b774f. connect compares only network with the state file. The descriptor's workdir is the facade's default cwd, which set_default_workdir moves, and the workspace bind still comes from the state file. test_connect_refusals now connects with workdir=/workspace/project, and the README's descriptor section says which fields come from where.


def _download(self, inst: _BwrapSandbox, source_path: str, target_path: Path) -> None:
root, parts = self.host_path(inst, source_path, write=False)
if not parts:

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.

RISK: regular-file mounts cannot use the advertised transfer API.

Mount a host regular file at /tool, for example {src: "/host/tool", dst: "/tool", ro: true}. Source validation accepts files and the argv builder binds them, but download("/tool", local) produces empty parts and unconditionally raises IsADirectoryError. Read-write file mounts have the same problem in _write_bytes. _exists also reports their roots absent because it calls root.is_dir().

Could you distinguish regular-file mounts from directory mounts in transfer resolution and support their exact destination? A directory mount root must still raise IsADirectoryError; a regular-file mount root must address that file, with read-only enforcement before upload and the existing nonblocking/regular-file safeguards. Reject suffixes such as /tool/child. I have not supplied a patch because the representation needs to stay consistent across upload, download and exists, including the handling of configured source symlinks.

Proposed acceptance checks: mount a temporary regular file read-only at /tool; a command read and download must return its bytes, exists("/tool") must be true, and upload must raise BwrapPathError. With a read-write regular-file mount, upload must replace the bytes and a command must observe them. Preserve directory-root rejection, nested directory transfers, read-only directory enforcement, and rejection of planted symlinks, FIFOs and ...

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

  • Resolution: a regular-file mount resolves to the realpath of its source, so a configured source symlink is followed at config time, while transfers still refuse symlinks below that.
  • Addressing: only its exact destination addresses it (parent, (name,)). A /tool/child path is refused as below a file mount.
  • Read-only: enforced before upload.
  • Coverage: download, exists and upload all use the same mapping, with the existing non-blocking and regular-file checks (test_a_regular_file_mount_is_transferable_at_its_destination).
  • Directory roots: a directory mount root still raises IsADirectoryError.

… pending execs, visible-bind transfers)

- /tmp, home_path and the workdir (SandboxSpec.workdir overrides included) must be pairwise disjoint: a
  workdir of /home with home /home/sandbox hid home from commands while uploads still landed there.
- A pending exec (queued on exec_concurrency or about to spawn) is recorded in run/ (pending-*, owner pid and
  start time), so every provider instance sees it: exec_processes_terminated() is False while a live owner has
  one, and close() waits for them (bounded) before its final kill pass. A dead owner's record is removed.
- The transfer table follows bind order: a later mount at or above an earlier one's destination hides it, so
  transfers resolve to the mount a command sees (and its writability). Regular-file mounts are addressable at
  their exact destination (download, exists; upload when read-write).
- connect no longer compares the descriptor's workdir (the facade's default cwd, which set_default_workdir
  moves) with the workspace bind from the state file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Stephen Ge <[email protected]>
stephencge added a commit that referenced this pull request Nov 18, 2026
@stephencge

Copy link
Copy Markdown
Contributor Author

/ok to test 44b774f

@stephencge
stephencge requested a review from yaoyu-33 November 18, 2026 15:00
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 18, 2026 15:01
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the risk:high Autobot PR risk: high label Nov 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Nov 19, 2026
@stephencge

Copy link
Copy Markdown
Contributor Author

@yaoyu-33 this is ready for another look: round 2 (44b774f) addresses your workdir note and the CI review's five risks, every thread has a reply, and the full CI run is green, including the real-bwrap tests.

@yaoyu-33 yaoyu-33 added the ready-to-merge PR is approved, current, and waiting for final CI or merge label Nov 20, 2026
@yaoyu-33
yaoyu-33 added this pull request to the merge queue Nov 20, 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/44646094628

@yaoyu-33
yaoyu-33 removed this pull request from the merge queue due to a manual request Nov 20, 2026

@hemildesai hemildesai 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

Thanks, this is a careful provider. Earlier rounds covered the mount, transfer and lifecycle issues, so I focused on one question: does running commands under bwrap stop an agent's pkill -f … / kill -9 -1 from killing the harness or Gym server?

Short answer: yes for the Gym servers on the host, with caveats. From bwrap_argv:

  • PID namespace. Every exec gets --unshare-pid plus a fresh --proc /proc, so sandboxed code can't see or name a host pid. pkill, kill -9 -1, ptrace and /proc/<pid> can't reach the agent or resources server.
  • Sessions and process groups. start_new_session=True and --new-session keep process-group kills on their own side.
  • Capabilities, IPC and network. --cap-drop ALL and --unshare-ipc apply everywhere. With network: none, --unshare-net also makes localhost ports unreachable.
  • Filesystem and teardown. The read-only system binds plus a per-sandbox /tmp and home hide host sockets, caches and the repo, and --die-with-parent means nothing outlives its exec.

Caveats (inline, none blocking):

  • A harness inside the sandbox isn't protected from its own tools. When the harness runs inside one long exec, it shares that pid namespace with the commands it spawns.
  • network: host is not an isolation boundary. The sandbox shares loopback with host services such as Ray.
  • No resource limits. A fork bomb or memory blow-up can still take the server down via shared pid/memory limits.
  • Two smaller follow-ups: a real-bwrap regression test of the kill property itself, and scoping the CI sysctl change to the sandbox job.

- `bwrap … true` takes 52 ms per exec.
- 20 concurrent nvcc compiles took 0.89 s wall.
- The GPU is hidden even in a GPU-holding step.
- PID isolation holds: `pkill` and `kill -9 -1` inside the sandbox don't reach

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.

NOTE This holds for processes outside the exec. When the harness runs inside the sandbox as one long exec (the Codex-episode case), its tool commands share that exec's pid namespace. So a tool's kill -9 -1 or pkill -f codex still kills the harness; only pid 1 and the caller are spared. Could you say that here and point to the nested tool pid namespace / supervisor approach (#6280) as the way to protect an in-sandbox harness from its tools? Otherwise readers may take bwrap alone to mean "agents can't kill the harness".

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.

Added in #6544: a "One exec is one pid namespace" limit in the README and the docs page. It says a harness running as one long exec shares that namespace with its own tool commands (only the exec's init and the calling shell are spared), and points to the supervisor's stop policy and codex_agent's tool_pid_namespace from #6280.

- **No background services** survive an exec (`SupportsSandboxBackgroundServices` is
not implemented), and there are no endpoints or PTYs.
- **Isolation.** All sandboxes share the Gym process's uid and host. Isolation relies
on the namespaces, the read-only binds and `--cap-drop ALL`. With `network: host`,

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.

NOTE "can reach every service" understates network: host, which the example config and the Codex→model path use. The sandbox shares loopback with host-local control planes, e.g. the Ray head Gym starts. If something like Ray's dashboard Jobs API or GCS listens on localhost (please confirm), sandboxed code could submit work that runs on the host as the Gym uid, outside every namespace, and that work could kill the servers. Suggest stating plainly that network: host is not an isolation boundary against the agent, and preferring network: none plus a bound socket or proxy to the model endpoint.

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.

Confirmed, and documented in #6544. With ray.init() as initialize_ray calls it, the dashboard and Jobs API listen on 127.0.0.1:8265 with no auth. A bwrap sandbox with network: host posted a job with entrypoint touch /tmp/<random>, and the file appeared in the host's /tmp: the job ran as the Gym uid outside every namespace. With network: none the connection was refused. The README now says network: host is not an isolation boundary, names the Ray head, and recommends network: none where no network is needed.

before the harness finishes) still stops the harness and confirms its cleanup.
- **No background services** survive an exec (`SupportsSandboxBackgroundServices` is
not implemented), and there are no endpoints or PTYs.
- **Isolation.** All sandboxes share the Gym process's uid and host. Isolation relies

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.

NOTE Worth one more Limits bullet: there are no cgroup or rlimit bounds. A fork bomb or memory blow-up inside an exec counts against the same uid and job cgroup as the Gym server. It can stop the server from creating threads or get it OOM-killed before the exec timeout fires. So the pid namespace alone doesn't keep the harness alive; prlimit in the wrapper or a per-exec cgroup are the usual mitigations.

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.

Added in #6544 as a "No resource limits" bullet: no cgroup or rlimit bounds, so a fork bomb or memory blow-up counts against the Gym server's uid and job cgroup, with prlimit/ulimit in the task's commands as the stopgap. Per-exec cgroups would be a provider change; I left that out of this PR.

return BwrapProvider(bwrap_path=BWRAP, base_dir=str(tmp_path / "base"), probe_on_create=True)


async def test_real_bwrap_isolation(provider: BwrapProvider, tmp_path: Path) -> 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.

NOTE (suggestion) The property motivating this provider has no real-bwrap test yet. It's cheap to add one: start a host subprocess.Popen(["sleep", "61.7777"]), run pkill -f 61.7777; kill -9 -1; true in the sandbox, then assert the host sleep and the test process are still alive. That would catch a future argv change that drops --unshare-pid or --proc /proc.

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.

Added in #6544: test_kill_commands_cannot_reach_processes_outside_the_exec. A host sleep 61.7777 survives while, in the sandbox, pkill -f kills the exec's own sleep 61.7777 (exit 143) and kill -9 -1 runs. The pattern is built inside the shell (61.$((7776 + 1))), because the exec's own sh -c argv would otherwise match pkill -f 61.7777 and kill the shell itself.

# The bwrap sandbox tests need unprivileged user namespaces, which Ubuntu 24.04's AppArmor default refuses
# ("setting up uid map: Permission denied"). Lift that for the job; NEMO_GYM_REQUIRE_BWRAP makes a runner where
# it cannot be lifted fail those tests instead of skipping them.
if [[ -e /proc/sys/kernel/apparmor_restrict_unprivileged_userns ]]; then

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.

NOTE This script runs in several jobs (core, servers, sandbox, full suite), and every one of them now relaxes apparmor_restrict_unprivileged_userns, though only the sandbox job needs it. If runners are ever reused between jobs, the relaxed setting persists. Consider gating it on NEMO_GYM_REQUIRE_BWRAP, which is already set only for the sandbox job.

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.

Done in #6544: the script lifts the sysctl only when NEMO_GYM_REQUIRE_BWRAP=1, and the sandbox job now sets that for the whole job, not just the test step. The server jobs that also run real-bwrap tests (agentvista's) run as root, which the AppArmor restriction doesn't cover, so they keep passing.

@yaoyu-33
yaoyu-33 added this pull request to the merge queue Nov 20, 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/44665752622

@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/44666801452

Merged via the queue into main with commit 240fedc Nov 20, 2026
81 checks passed
@yaoyu-33
yaoyu-33 deleted the stepheng/bwrap-provider branch November 20, 2026 03:33
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 ready-to-merge PR is approved, current, and waiting for final CI or merge 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.

5 participants