Skip to content

fix(sandbox): support LAB harness sessions across sandbox providers - #5792

Closed
rystewart-nvidia wants to merge 16 commits into
NVIDIA-NeMo:mainfrom
rystewart-nvidia:lab-refresh/sandbox
Closed

rystewart-nvidia wants to merge 16 commits into
NVIDIA-NeMo:mainfrom
rystewart-nvidia:lab-refresh/sandbox

Conversation

@rystewart-nvidia

@rystewart-nvidia rystewart-nvidia commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Let agents use Enroot, ECS Fargate, and OpenShell sandboxes created by the Harbor Environment Server. When an agent disconnects, the sandbox stays running until the environment server finishes the task and deletes it.

  • Connect to the correct sandbox. Check its identity and connection settings, and preserve OpenShell’s workspace. Exclude environment variables from Enroot and OpenShell connection details so task secrets aren’t exposed.
  • Disconnect Fargate clients safely. Release each agent’s connection and temporary S3 files without stopping the sandbox or affecting other agents. Keep the same local port when reconnecting the SSH tunnel.
  • Handle Fargate disk requests correctly. Round fractional requests up. Use the default storage for requests up to 20 GiB unless the provider already specifies an allocation. Reject negative sizes.
  • Fix an existing Enroot startup bug. Replace --rc /dev/null with a script that runs Gym’s command when bypassing the image’s entrypoint.
  • Remove leftover Enroot and Apptainer files safely. Handle read-only directories without following symlinks or trying to change permissions on directories owned by another user.

Builds on #5790 and will be rebased after 5790 merges. LAB's Environment Server integration is separate in #5788.

Validation

Run filesystem cleanup tests as a non-root user so root permissions do not hide failures.

All selected provider and connection tests passed, including ownership, descriptor validation, cleanup, and SSH reconnect checks. SWE-bench Pro, DeepSWE, JobBench, and Terminal Bench 4 regression suites also passed. All-files pre-commit and import checks passed.

uv sync --locked --project environment_servers/harbor
source environment_servers/harbor/.venv/bin/activate
uv pip install openshell==0.1.6
PYTHONPATH=. LITELLM_LOCAL_MODEL_COST_MAP=True uv run --active --no-sync python -m pytest \
  tests/unit_tests/test_sandbox_provider_utils.py \
  tests/unit_tests/sandbox/test_apptainer_provider.py \
  tests/unit_tests/sandbox/test_ecs_fargate_engine.py \
  tests/unit_tests/sandbox/test_ecs_fargate_provider.py \
  tests/unit_tests/sandbox/test_enroot_provider.py \
  tests/unit_tests/sandbox/test_openshell_provider.py \
  tests/unit_tests/sandbox/test_sandbox_connect.py --import-mode=importlib -q

LITELLM_LOCAL_MODEL_COST_MAP=True avoids downloading model prices during imports; --active --no-sync uses the activated environment.

pre-commit run --all-files
git diff --check

Rollouts

LocalEmu checks passed for ECS resource settings, S3 transfer and cleanup, separate borrowers sharing a provider, owner survival after disconnect, and teardown. Real AWS provisioning and SSH networking remain unverified; LocalEmu checks used a local exec server. Enroot and OpenShell also passed live checks for borrowed execution, environment inheritance, owner survival after disconnect, isolated output transfer, and teardown.

Reproduce the ownership check

Run from the repository root with the Gym uv environment activated. The default example uses Docker; other backends need their own runtime or service. No model endpoint is needed. The script reads a file through a second connection, disconnects it, and checks that the owner can still read the file before cleanup.

mkdir -p results/sandbox-repro
cat > results/sandbox-repro/lifecycle.py <<'PY'
import asyncio
import json
import os

from omegaconf import OmegaConf
from nemo_gym.sandbox import AsyncSandbox, SandboxResources, SandboxSpec, create_provider

async def main():
    config_path = os.environ.get(
        "LAB_SANDBOX_CONFIG", "nemo_gym/sandbox/providers/docker/configs/docker.yaml"
    )
    config = OmegaConf.to_container(OmegaConf.load(config_path), resolve=True)["sandbox"]
    metadata = config.pop("default_metadata", {})
    workdir = os.environ.get("LAB_SANDBOX_WORKDIR", "/workspace")
    owner = AsyncSandbox(config, SandboxSpec(
        image=os.environ.get("LAB_SANDBOX_IMAGE", "python:3.13.14-slim-bookworm"),
        workdir=workdir,
        metadata=metadata,
        files={f"{workdir.rstrip('/')}/marker.txt": "READY\n"},
        resources=SandboxResources(cpu=1, memory_mib=1024),
    ))
    borrower = None
    try:
        await owner.start()
        descriptor = json.loads(json.dumps(await owner.serialize()))
        borrower = await AsyncSandbox.connect(descriptor, provider=create_provider(config))
        result = await borrower.exec("cat marker.txt")
        assert result.return_code == 0 and result.stdout.strip() == "READY", result
        await borrower.disconnect()
        borrower = None
        result = await owner.exec("cat marker.txt")
        assert result.return_code == 0 and result.stdout.strip() == "READY", result
        print("PASS: borrower read the staged file; owner survived borrower disconnect")
    finally:
        try:
            if borrower is not None:
                await borrower.disconnect()
        finally:
            await owner.stop()
    print("PASS: owner cleanup completed")

asyncio.run(main())
PY
PYTHONPATH=. uv run --active --no-sync python results/sandbox-repro/lifecycle.py

For Enroot, use the tested image-preparation and /sandbox example below.

For other providers, set LAB_SANDBOX_CONFIG to their configured sandbox YAML, LAB_SANDBOX_IMAGE to a compatible image, and LAB_SANDBOX_WORKDIR to a writable directory.

Reproduce the Enroot startup fix

Use a Linux host with working rootless Enroot and the activated Gym environment. Docker is needed only to build the test image and import it from the local Docker daemon. Once the .sqsh file exists, running the Enroot sandbox does not require Docker; you can also prepare that file on another host. Create lifecycle.py above first, then set SANDBOX_REPRO_DIR to a writable scratch directory. No GPU or model endpoint is needed.

: "${SANDBOX_REPRO_DIR:?Set SANDBOX_REPRO_DIR to a writable scratch directory}"
mkdir -p "$SANDBOX_REPRO_DIR/build"
cat > "$SANDBOX_REPRO_DIR/build/Dockerfile" <<'DOCKERFILE'
FROM python:3.13.14-slim-bookworm
ENTRYPOINT ["/bin/sh", "-c", "echo IMAGE_ENTRYPOINT_MUST_BE_BYPASSED >&2; exit 73"]
DOCKERFILE
docker build -t gym-enroot-entrypoint-repro:latest "$SANDBOX_REPRO_DIR/build"
enroot import -o "$SANDBOX_REPRO_DIR/entrypoint.sqsh" dockerd://gym-enroot-entrypoint-repro:latest
NEMO_GYM_ENROOT_BASE="$SANDBOX_REPRO_DIR/runtime" \
LAB_SANDBOX_CONFIG=nemo_gym/sandbox/providers/enroot/configs/enroot.yaml \
LAB_SANDBOX_IMAGE="$SANDBOX_REPRO_DIR/entrypoint.sqsh" \
LAB_SANDBOX_WORKDIR=/sandbox \
PYTHONPATH=. uv run --active --no-sync python results/sandbox-repro/lifecycle.py

Both PASS checks succeeded with this Python image as a non-root user. Without bypass, the same image exited with code 73 as intended. Docker was shut down before the Enroot run, and sandbox cleanup completed.

Compatibility and benchmark impact

Existing provider APIs remain available. A borrower no longer needs to own the sandbox or close a provider shared by other connections. The cleanup helper is used only by Enroot and Apptainer; the other providers keep their cleanup paths.

Backend prerequisites still apply: local providers need the same host and user; Fargate borrowing requires exec-server mode and an active owner SSH forward.

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

Copy link
Copy Markdown

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

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@nemo-automation-bot nemo-automation-bot Bot added the community-request Issue reported or requested by someone from the community label Nov 7, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added feature New capabilities, enhancements, or enablement work area:sandbox Sandbox providers, isolation, and sandbox runtime contracts needs-review PR is ready for code review and waiting on a reviewer labels Nov 7, 2026
@github-actions github-actions Bot added the sla:triage-overdue Review assignment is over the one-business-day SLA label Nov 9, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Nov 9, 2026
@cmunley1

Copy link
Copy Markdown
Contributor

Some points on the provider changes, since these are shared by other benchmarks:

  1. Making Enroot, ECS Fargate and OpenShell connectable turns on new paths elsewhere: resources_servers/swebench_pro/app.py now calls serialize() for these providers, and deepswe, job_bench and terminal_bench_4 always serialize. Worth a quick check of those pairings, or a note in the PR body.
  2. nemo_gym/sandbox/providers/enroot/provider.py L707 and openshell/provider.py L960 put the sandbox env into the serialized descriptor, so task secrets travel in plain text through seed responses. The Docker descriptor leaves env out. Could these do the same?
  3. nemo_gym/sandbox/providers/ecs_fargate/provider.py L216-220: borrowed exec clients are released only in aclose(). A long-lived shared provider (for example harness_agent's) keeps one per rollout. Releasing the borrowed client in close() would fix that.
  4. ecs_fargate/provider.py L140-148: the descriptor pins the owner's local exec_port. If the owner's SSH tunnel reconnects on a new port, a connected peer keeps using the stale one.
  5. ecs_fargate/provider.py L214-215: close() calls stop() on handle.raw for borrowed handles too. Could a borrower's close stop the owner's task? If borrowed handles are meant to detach only, a guard here would make that explicit.
  6. ecs_fargate/provider.py L104-105: disk_gib of 20.5 passes the > 20 check, is truncated to 20 and sent explicitly, which Fargate rejects (it accepts 21-200 explicitly). math.ceil would avoid it.
  7. nemo_gym/sandbox/providers/utils.py L72-74: remove_writable_tree calls fchmod on every directory, so a directory owned by another uid (Apptainer --fakeroot subuids) raises EPERM and cleanup stops before deleting anything. Previously rmtree removed what it could. Skipping the chmod when the directory is already writable would keep that behavior.

@svcnvidia-nemo-ci svcnvidia-nemo-ci removed the waiting-on-maintainers Waiting on maintainers to respond label Nov 12, 2026
@rystewart-nvidia

Copy link
Copy Markdown
Contributor Author

@cmunley1 Thanks, I’ve addressed each of these and added tests. Also ran the SWE-bench Pro, DeepSWE, JobBench, and Terminal Bench 4 tests to check for effects on other users and confirmed they all pass

@ananthsub
ananthsub requested a review from adil-a November 12, 2026 21:21
@github-actions github-actions Bot removed the sla:triage-overdue Review assignment is over the one-business-day SLA label Nov 12, 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 WITH CARE (sandbox provider changes)

Thanks. The provider work is careful, and all of cmunley1's points are fixed in the code: descriptors no longer carry env, a borrowed ECS close()/disconnect_handle only detaches, the tunnel reconnects on the same port, math.ceil is applied to disk_gib, and fchmod only runs on directories this user owns. On every path I traced the owner keeps control of the lifecycle. A borrower's disconnect() never reaches stop_task, enroot remove or an OpenShell delete, and the OpenShell orphan reap is keyed per process, so a borrower's aclose() can't reap the owner's sandboxes.

  • Scope: this head also carries #5787 (legal-agent-bench layout) and #5790 (deferred dataset paths). As asked, I reviewed only the nemo_gym/sandbox/* changes and their tests.
  • RISK — ECS borrowing on real AWS. The PR body says real AWS provisioning and SSH networking are unverified, and recovery from a dropped tunnel only works if the owner itself execs (inline). Could you run one real Fargate smoke (owner seed, then a borrowed harness exec, disconnect, owner verify), or mark ECS borrowing experimental until then?
  • NOTE: make_writable recursion can break cleanup on a deep agent-written tree (inline, reproduced locally).
  • NOTE/question: ECS connect() doesn't check which task answers on the port, unlike Enroot and OpenShell (inline).

The main CI hasn't run yet; copy-pr-bot is waiting on /ok to test.

Comment thread nemo_gym/sandbox/providers/utils.py Resolved
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 13, 2026 15:15
@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

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

Thanks for the quick turnaround. All three of my points are addressed in 3629a50 / 22f9a49 / d0cc617, and I've resolved those threads. Locally the changed sandbox tests pass (296 passed, 1 skipped).

Before I approve, the required Unit tests / Sandbox tests job is red on d0cc617 with one failure introduced by the rmtree-first change:

FAILED tests/unit_tests/test_sandbox_provider_utils.py::test_cleanup_root_replacement_after_open_cannot_redirect_chmod - Failed: DID NOT RAISE <class 'OSError'>

CI appears to run with privileges that let shutil.rmtree delete the 0o555 tree on the first try. So the chmod pass (and the racing fchmod) never runs. The other race tests already opt into require_permission_repair; this one just needs the same fixture (inline).

FYI: secrets-detector failed with a detect-secrets-hook usage error rather than an actual finding, so a re-run may be enough there.

Once Sandbox tests are green I'm happy to approve the sandbox-provider part. As before, I've only reviewed the nemo_gym/sandbox/* changes here, not the #5787/#5790 content carried on this branch.

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 13, 2026 15:56
hemildesai
hemildesai previously approved these changes Nov 13, 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.

LGTM on the sandbox provider changes. Thanks for the fast turnaround.

  • 21af99c adds require_permission_repair to the root-replacement race test, and CI is now fully green, including Sandbox tests.
  • The rebase onto main left the sandbox commits unchanged (checked with range-diff).
  • All my earlier threads are resolved: deep-tree cleanup, the per-sandbox ECS identity check, and Fargate borrowing documented as experimental.

Scope note: I reviewed the nemo_gym/sandbox/* changes and their tests, as asked. The dataset-path commit (9abfeed, #5790) is outside what I looked at.

Signed-off-by: Ryan Stewart <[email protected]>
Signed-off-by: Ryan Stewart <[email protected]>
Signed-off-by: Ryan Stewart <[email protected]>
Signed-off-by: Ryan Stewart <[email protected]>
Signed-off-by: Ryan Stewart <[email protected]>
Signed-off-by: Ryan Stewart <[email protected]>
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 13, 2026 20:20
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Nov 13, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Nov 15, 2026
@hemildesai

Copy link
Copy Markdown
Contributor

/ok to test 6d8a7e7

@nemo-automation-bot nemo-automation-bot Bot removed the community-request Issue reported or requested by someone from the community label Nov 17, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci removed the waiting-on-maintainers Waiting on maintainers to respond label Nov 17, 2026
Signed-off-by: Ryan Stewart <[email protected]>
Signed-off-by: Ryan Stewart <[email protected]>
Signed-off-by: Ryan Stewart <[email protected]>
@hemildesai

Copy link
Copy Markdown
Contributor

/ok to test ce3cfa0

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

Re-approving at ce3cfa0 after the merges from main dismissed my approval. The conflict resolution drops this PR's Enroot serialize/connect in favour of #6105's version now on main, and the remaining sandbox changes are the ones I reviewed. Required CI is green (a re-run cleared an unrelated flaky openclaw_agent test). As before, my review covers the nemo_gym/sandbox/* changes.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Nov 21, 2026
@rystewart-nvidia

Copy link
Copy Markdown
Contributor Author

superseded by changes merged in #5791, closing

@svcnvidia-nemo-ci svcnvidia-nemo-ci removed the waiting-on-maintainers Waiting on maintainers to respond label Nov 27, 2026
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 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.

4 participants