Skip to content

Add Ray Sandbox HTTP API environment (-e ray-sandbox) - #2811

Open
xyuzh wants to merge 11 commits into
harbor-framework:mainfrom
xyuzh:ray-sandbox-http-env
Open

xyuzh wants to merge 11 commits into
harbor-framework:mainfrom
xyuzh:ray-sandbox-http-env

Conversation

@xyuzh

@xyuzh xyuzh commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Adds -e ray-sandbox: runs trials on a deployed Ray Sandbox HTTP API service (ray-project/ray#65633, merged into Ray master; not yet in a Ray release) — gVisor sandboxes on your own Ray cluster, driven over plain HTTPS with a bearer token.

export RAY_SANDBOX_API_URL=https://<service-url>   # Anyscale service or any `serve run`
export RAY_SANDBOX_API_KEY=<service bearer token>
harbor run -t <org>/<task> -e ray-sandbox

Zero new dependencies: httpx/tenacity are core deps, so this registers with pip_extra=None and works from a bare pip install harbor — no ray, no cluster connectivity. Testable and mergeable independently of the Ray PR (the unit suite fakes the API); a live deployment is only needed for the env-var-gated integration test.

Update (October 12): resource enforcement

The Ray configuration used in the earlier evaluation wrote CPU and memory limits into the OCI spec without enforcing them in either public or none mode. This update gates both limit capabilities behind RAY_SANDBOX_LIMITS_VERIFIED=1, which operators must set only after verifying enforcement on every eligible worker. Without it, auto makes scheduling requests and explicit limit or guarantee policies fail before trials start. The capability tables now document this requirement.

ray-project/ray#66932 (draft) adds host cgroup v2 CPU and memory budgets, exclusive whole-core allocation, and crash cleanup. With that change, the bundled reference solution for schemelike-metacircular-eval passed all 63 task checks in each network mode, alongside four neighbouring sandboxes running 16 busy processes:

Network mode Checks Whole verifier Longest reported subprocess
public 63/63 62.84 s 11.83 s
none 63/63 62.59 s 10.82 s

The task sandbox used 1 CPU, 2 GiB memory, and exclusive CPU isolation; nproc reported 1. Validation used real gVisor release-20261005.0 on a 14-vCPU aarch64 Docker LinuxKit VM, the task's unchanged Dockerfile and verifier, and its original 60 s subprocess timeout. The verifier SHA-256 was fbb84e3c0c2f72ed7de90f54380f860052c16155e7d0c9076cd57c966e9be7ed. This focused rerun used a local copy of that change before it was opened as a PR; the October 11 83/89 Anyscale full-suite result below remains the recorded result for that run.

Validation for this Harbor update, in its virtual environment:

uv run --no-sync pytest tests/unit/environments/test_ray_sandbox.py -q                 # 48 passed
uv run --no-sync ruff check --fix .                       # passed
uv run --no-sync ruff format .                           # passed
uv run --no-sync ty check src/harbor/environments/ray_sandbox/environment.py tests/unit/environments/test_ray_sandbox.py  # passed
uv run --no-sync ty check                                # 10 missing optional SDK imports in unrelated files

Before it was opened as ray-project/ray#66932, the Ray change passed 38 allocator/config/runtime/kernel tests (including 8 real-cgroup tests covering CPU caps, memory OOM, affinity, concurrent allocation, and crash cleanup), 161 HTTP/gRPC tests, and the applicable pre-commit hooks. The task driver ran /validation/venv/bin/python -u /validation/benchmark.py public and the same command with none against the provisioned cgroup pools. The Ray PR lists the tests run at its head, including all 8 real-cgroup tests with gVisor on Linux.

Update (October 11)

  • Merged main. The docs moved to docs-mintlify/, so the ray-sandbox entries now go in the new provider list, capability tables, network-policy table, resource table, and environment.type reference. The provider entry names the two variables this environment needs.
  • The client matches the HTTP API as merged into Ray master: routes, request and response fields, status values, long-poll parameter, and error shape are unchanged.
  • One fix, which the Terminal-Bench rerun found: the merged API holds a call to a sandbox whose actor the cluster hasn't placed yet for up to its scheduling grace (60 s by default) past the call's long-poll, then reports the sandbox pending. The client stopped listening after 60 s, so a trial whose sandbox waited for a free node timed out. Requests now default to 90 s, long-polls to their wait plus the grace, and a start poll that still gets no answer (say, a proxy ended it) counts as pending until the start deadline.
  • Reran Terminal-Bench 2.1 on this branch against Ray master: see Terminal-Bench 2.1 below.

Design

  • client.py — submit-and-poll (creation and execs return immediately; long-poll ≤ 30 s per request), so every HTTP request stays short under load-balancer limits. Narrow retries, Modal-style: connection errors, read timeouts, and 502/503/504 on idempotent calls only; creation retries connection errors only and is idempotent via client_token; exec submission is never auto-retried.
  • environment.py — the task's network policy is authoritative: no-network → the service's none mode, and a wider --ek network= is rejected at construction; mode values are validated by the service (new modes need no Harbor change); default is public (egress + generated resolv.conf). Resource requests become cluster reservations. Limits require RAY_SANDBOX_LIMITS_VERIFIED=1 after the operator verifies CPU and memory enforcement on every eligible worker. By default, auto uses requests and explicit limit or guarantee policies are rejected before trials run. Directory transfers stage tar archives; cleanup is best-effort so it can't mask a real failure.

What runs today

The service pulls prebuilt public images (no build step inside gVisor), so any task with [environment].docker_image works out of the box (e.g. MedAgentBench). Terminal-Bench 2.1 publishes a prebuilt image for every one of its 89 tasks. Dockerfile-only tasks, plus compose, GPU, and allowlist tasks, are rejected up front with actionable errors.

Results

Oracle agent, ubuntu:24.04 images, service running the ray#65633 code with runsc:

Probe Result
Full trial: env upload, tar transfers, WORKDIR, verifier apt-get + PyPI in-sandbox (default public egress) reward 1.0, 29 s
8 attempts, -n 4 8/8 reward 1.0, 3 m 02 s (per-trial p50 45 s)
no-network task (in-sandbox probe confirms no egress) reward 1.0
no-network + --ek network=host rejected at construction (ValueError)

vs. local docker — the short answer: a single trial is end-to-end faster (29.2 s vs 34.6 s), even though each phase inside the sandbox is a little slower. Boot costs +1.4 s and syscall-heavy in-sandbox work ~+30% (that's the gVisor isolation), but Docker gives it all back in teardown: its keepalive PID 1 (tail -f /dev/null) ignores SIGTERM, so every trial's compose down waits out the full 10 s stop grace before SIGKILL (~11.6 s total vs ~0.3 s for a sandbox delete, which is an immediate kill by design). That part is fixable on the Docker side (stop_grace_period: 0), so read the phase rows — not the total — as the isolation cost. Same dev VM, warm caches, indicative not a benchmark:

Phase docker ray-sandbox Δ
create + boot + env upload 7.5 s 8.9 s +1.4 s slower
verifier (apt-get + PyPI, in-sandbox) 15.3 s 19.9 s +4.6 s slower (~+30%, gVisor syscall cost)
teardown + everything else 11.6 s (10 s SIGTERM grace: keepalive PID 1 ignores SIGTERM) 0.3 s (immediate kill) −11.3 s faster
single-trial total 34.6 s 29.2 s −5.4 s faster
8 attempts -n 4 (wall / p50) 1 m 08 s / 35 s 3 m 02 s / 45 s 2.7× slower — see below

The concurrency row is a node-sizing artifact, not steady-state cost: here the four sandboxes, the Ray runtime, and the Serve app all share one 7.6 GiB container while Docker gets the VM to itself (an ubuntu sandbox running apt wants ~1 GiB; on a real cluster, per-sandbox reservations make Ray spread and autoscale this). Pushing to -n 8 oversubscribed memory and usefully surfaced two robustness fixes: creation no longer blocks on actor scheduling (ray PR), and the client retries read timeouts on idempotent polls (this PR). Cloud providers aren't in the table — no credentials in this setup, and their create paths include fleet scheduling + WAN latency; reproduce with harbor run -p ./task -e <env> -a oracle [-k 8 -n 4] to add a column.

The same evals also passed against an Anyscale-hosted deployment of the service (URL + token only).

Terminal-Bench 2.1 oracle results

Rerun on October 11 with this branch and Ray master at 75e638e4645: the oracle agent on all 89 tasks with -n 8, as an Anyscale job on EKS with a head node and four 8-CPU, 32 GB workers. The HTTP API ran in the same cluster under Ray Serve, with Harbor on the head node calling http://127.0.0.1:8000, so these numbers include no ingress or load balancer. Task images came through RAY_SANDBOX_REGISTRY_MIRROR=mirror.gcr.io (ray-project/ray#65745), because pulling all 89 anonymously from Docker Hub hit its rate limit.

83/89 tasks pass, and no trial errors, in 47 minutes (median trial 79 s). The Python API environment (#2785) failed the same six tasks in the same setup.

Task Why it fails
qemu-startup, qemu-alpine-ssh The verifier can't install curl: Debian 11's security archive lists curl 7.74.0-1.3+deb11u16 but returns 404 for it, so no test runs.
mcmc-sampling-stan The solution installs rstan, whose RcppParallel 6.2.1 now needs cmake, so the Stan model is never written.
protein-assembly The solution asks RCSB for a feature type it has since renamed (modified_monomer is now non_standard_monomer), so it writes no gblock.txt.
build-cython-ext One of the repository's own tests fails against planarity 1.0, which renamed a node attribute (pos to vertex_position).
schemelike-metacircular-eval Load-sensitive. Alone it passes all 63 tests, but its slowest takes 44 s of a 60 s limit, and a CPU-heavy trial on the same node pushes it over: public sandboxes run with --ignore-cgroups, so their CPU limit isn't enforced.

The first five fail for reasons outside the sandbox: the archives and APIs they use changed after the task images were published, and they failed the same way through Ray's gRPC facade on September 27.

Since August's 82/89, mailman, install-windows-3.11 and build-pov-ray pass. Ray now gives each public sandbox its own network namespace (ray-project/ray#65820, #66004) and caches images as EROFS root filesystems that keep the image's file ownership (#65992), which mailman needed. The qemu tasks now fail on the Debian archive before their tests run.

On two workers (16 schedulable CPUs, since the head node offers none), the same suite had three errors: a 4-CPU task waited past Harbor's 600 s start limit for a free node, and compile-compcert and torch-pipeline-parallelism ran past their time limits under CPU contention. Size the cluster so the -n trials fit at once. The first rerun also found the client timeout fixed in this update.

The August campaign behind the earlier 82/89 surfaced and fixed ten real bugs upstream: ray-project/ray#65737 (extraction discarded mtimes — broke apt in ~30% of tasks), #65744 (no /etc/hosts — localhost didn't resolve; tmpfs /tmp EXDEV; extraction discarded directory modes), #65745 (registry pull-through mirror), #65748 (unbounded image cache), and four hardening commits on #65633 (LB capacity, non-blocking creation, unschedulable→409, append uploads) — plus this PR's read-timeout retries, ingress-sized chunked uploads (the Anyscale LB caps bodies at 1 MiB, measured), and the pull+start wait-budget fix.

Notes

  • Coexists with feat(environments/ray) Add Ray Sandbox environment (Ray Python API) #2785 (the Python-API -e ray); the two touch the same two registry lines, so whichever lands second rebases trivially.
  • allowlist network policy is rejected up front by the capabilities validator (same as several other providers); Ray-side CIDR allowlists are in review in [core][sandbox] Default network="public" egress to the public internet and enforce allowlists ray-project/ray#66359.
  • Docs updated append-only: the provider list, the capability, network-policy and resource tables, the environment.type reference, and the AGENTS.md lists.
  • Tests: 48 unit tests against an in-memory fake of the API, plus the existing preflight tests and env-var-gated live suite.
  • AI assistance: Claude Code helped write this change and its tests, ran the Terminal-Bench evaluation, and drafted this description. Codex implemented the resource-capability gate and documentation corrections, ran the focused validation above, and updated this description.

Open in Devin Review

@github-actions

Copy link
Copy Markdown
Contributor

Enjoy a better diff viewing experience by clicking one of these URLs:

devin-ai-integration[bot]

This comment was marked as resolved.

@alexgshaw
alexgshaw enabled auto-merge (squash) August 26, 2026 04:35
auto-merge was automatically disabled August 27, 2026 16:49

Head branch was pushed to by a user without write access

@devin-ai-integration devin-ai-integration Bot 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.

Note

This report is out of date. Scroll down for Devin Review's latest report on this PR.

Devin Review found 1 new potential issue.

1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

Comment on lines +442 to +444
# A numeric uid, "uid:gid", or a name from the image's
# /etc/passwd; the service resolves names.
user=str(user) if user is not None else None,

@devin-ai-integration devin-ai-integration Bot Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Non-root users break directory transfers

With a non-root default, exec also runs internal archive operations as that user. Uploads to root-owned directories fail, breaking agent setup.

Learn more

RaySandboxEnvironment.exec now honors default_user, so internal calls from upload_dir and download_dir inherit the active agent or verifier user. These transfer operations stage files through the service and commonly extract into root-owned paths such as /installed-agent, /tests, and /logs. Make the provider's internal archive extraction, packing, and cleanup execs run explicitly as root, matching BaseEnvironment transfer helpers and other providers. Add unit coverage with env.default_user set to a non-root user that verifies transfer plumbing still submits root while normal bare exec calls submit the configured user.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

xyuzh added 8 commits August 31, 2026 16:03
A new -e ray-sandbox environment that talks to a deployed
ray.experimental.sandbox.http service (ray-project/ray#65633) over plain
HTTPS with a bearer token — no ray dependency, no cluster connectivity,
zero new Harbor dependencies (httpx and tenacity are core deps):

    export RAY_SANDBOX_API_URL=https://<service-url>
    export RAY_SANDBOX_API_KEY=<service bearer token>
    harbor run -t <task> -e ray-sandbox

Sandboxes run the task's prebuilt image under gVisor on the service's
Ray cluster. Creation and execution are submit-and-poll so every HTTP
request stays short regardless of image pull or command duration; the
client retries narrowly (connection errors and 502/503/504 on idempotent
calls only, Modal-style) and creation is idempotent via client_token.
The task's network policy is authoritative: no-network maps to the
service's none mode and a wider --ek network= override is rejected at
construction; mode values themselves are validated by the service.
NTFS has no executable bits to preserve; the rest of the upload_dir
test still runs there.
A loaded service can take longer than the client read timeout to answer
a poll; everything routed through the shared retry predicate is
idempotent, so retry ReadTimeout there too. Creation keeps its
connection-error-only predicate. Surfaced by an 8-way concurrency run
against a memory-oversubscribed single node.
Proxies in front of a deployed service cap request bodies (an Anyscale
ingress 413s a ~5MB PUT and kills an 11MB one mid-body), which failed
every Terminal-Bench task whose tests directory tars above the cap.
Uploads above 3MB now go up as a truncating first chunk plus append
chunks (the service's new append flag). Retry semantics stay safe: the
first chunk retries broadly (same-bytes rewrite is idempotent), append
chunks retry only on connection errors since a repeated append would
duplicate bytes. Requires a service with append support for files
above the chunk size.
…ss default

Measured empirically: the Anyscale ingress accepts 0.9MiB and 413s
1.5MiB — nginx's default client_max_body_size of 1MiB. The previous
3MiB chunks sailed over it; 768KiB leaves headroom.
…rdown

The service gets two sequential budgets (image pull, then container
start), but the client only waited out the pull budget, so a sandbox
that pulled slowly but successfully could be deleted moments before
becoming ready. Wait for the sum. Review finding on the PR.
The service now supports per-exec users (numeric uid, uid:gid, or an
image /etc/passwd name, resolved service-side); stop dropping the
environment contract's user= parameter.
The Ray Sandbox service now gives each network="public" sandbox its own
network namespace (bridged by pasta): ports and loopback are per-sandbox,
so tasks that bind fixed ports (e.g. QEMU tasks forwarding SSH on
localhost:2222) run safely under concurrency. network="host" remains the
shared-namespace escape hatch.
@xyuzh
xyuzh force-pushed the ray-sandbox-http-env branch from da0fd9a to bcd5e02 Compare August 31, 2026 23:05

@devin-ai-integration devin-ai-integration Bot 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.

Devin Review found 4 new potential issues.

3 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment on lines +393 to +399
self._sandbox_id = None
if client is None or sandbox_id is None:
return
try:
await client.delete_sandbox(sandbox_id)
except Exception as exc:
self.logger.warning(f"Failed to delete Ray Sandbox {sandbox_id}: {exc}")

@devin-ai-integration devin-ai-integration Bot Aug 31, 2026 •

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.

🔴 Failed deletion reports cleanup success

When all deletion retries fail, _safe_delete clears the only sandbox identifier and suppresses the error. The trial reports cleanup success while the sandbox remains billed for up to 24 hours.

Learn more

Separate best-effort startup cleanup from normal stop cleanup in src/harbor/environments/ray_sandbox/environment.py. _safe_delete currently clears _sandbox_id before deletion and suppresses every failure. Startup error handling may preserve the original exception, but stop(delete=True) must retain enough state for a retry and propagate a final deletion failure so the trial does not report successful cleanup while a remote sandbox remains active. Keep client closure reliable in both paths.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +210 to +216
missing = [
var for var in (API_URL_ENV_VAR, API_KEY_ENV_VAR) if not os.environ.get(var)
]
if missing:
raise SystemExit(
f"Missing {', '.join(missing)}.\n{_MISSING_CREDENTIALS_HINT}"
)

@devin-ai-integration devin-ai-integration Bot Aug 31, 2026 •

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.

🟡 Constructor credentials cannot start jobs

When credentials come through documented environment kwargs, preflight checks only process variables and exits before construction. CLI jobs cannot use the supported api_url and api_key parameters.

Learn more

Reconcile Ray Sandbox credential preflight with constructor kwargs in src/harbor/environments/ray_sandbox/environment.py. CLI preflight runs before construction and receives no environment kwargs, so it rejects jobs that supply the documented api_url and api_key through --ek or job configuration. Either pass kwargs into provider preflight or avoid a hard failure when credentials can be provided at construction, while preserving a clear missing-credentials error when neither source is configured.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +91 to +95
self._client = httpx.AsyncClient(
base_url=api_url.rstrip("/") + _API_PREFIX,
headers={"Authorization": f"Bearer {api_key}"},
timeout=httpx.Timeout(request_timeout_sec, connect=10.0),
transport=transport,

@devin-ai-integration devin-ai-integration Bot Aug 31, 2026 •

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.

🟨 Plain HTTP exposes sandbox credentials

When api_url uses HTTP, RaySandboxClient sends the bearer token without encryption. Network observers can recover it and control the deployment's sandboxes.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +323 to +325
f"/sandboxes/{sandbox_id}/files",
params={"path": path, "append": "true"} if append else {"path": path},
content=chunk,

@devin-ai-integration devin-ai-integration Bot Aug 31, 2026 •

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.

🟨 Remote file paths lack validation

Unvalidated path values reach the file API directly. Configurable artifact paths can access unintended sandbox files if the service does not enforce containment.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

xyuzh and others added 3 commits October 11, 2026 12:18
Conflicts:
- docs/content/docs moved to docs-mintlify on main. The ray-sandbox
  entries now go in the new pages: the provider list and capability tables
  in sandboxes/pre-integrated-sandboxes.mdx, the no-network row in
  tasks/network-policies.mdx, the resource table in tasks/resources.mdx,
  and the environment.type list in jobs/configs.mdx. The new pages have no
  per-provider setup sections, so the provider entry names the two
  variables the environment needs and links to the HTTP API service docs.
- AGENTS.md, factory.py, environment_type.py and
  test_environment_preflight.py: main's additions and the ray-sandbox
  entries side by side.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Ray Sandbox API, as merged into Ray, holds a call to a sandbox whose
actor the cluster hasn't placed yet for up to its scheduling grace (60 s by
default) past the call's own long-poll, then reports the sandbox pending.
The client stopped listening after 60 s per request, so a 20 s status poll
on a sandbox that was still being scheduled timed out three times and failed
the trial (Terminal-Bench 2.1's mcmc-sampling-stan, on a full cluster).

Requests now default to a 90 s timeout and long-polls to their wait plus the
grace plus 10 s. While a sandbox starts, a status poll that still gets no
answer, because a proxy ended the long request, counts as pending until the
start deadline. A failed cleanup delete now names its exception type
instead of logging an empty message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant