Skip to content

feat(server): allow servers to opt out of Ray - #3622

Merged
ananthsub merged 1 commit into
NVIDIA-NeMo:mainfrom
ananthsub:ananthsub/ray-opt-out
Sep 28, 2026
Merged

ananthsub merged 1 commit into
NVIDIA-NeMo:mainfrom
ananthsub:ananthsub/ray-opt-out

Conversation

@ananthsub

@ananthsub ananthsub commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

What changed

Add a class-level ray_enabled: ClassVar[bool | None] contract for Gym server implementations. None preserves the historical Ray-enabled behavior and emits a migration warning; False skips the server process's Ray import and connection, while True connects as before.

Ray is imported lazily so non-Ray server processes do not pay the import cost. Existing server construction, dry-run preparation, Uvicorn manager behavior, readiness handling, and log prefixing remain unchanged.

Built-in declarations are intentionally split into dependent PR #3728 so this PR stays focused on the shared runtime contract.

Part of #3669.

Why

Gym historically connected every server process and Uvicorn worker to Ray, including stateless HTTP servers. Each connection imports the Ray runtime and creates process-local client state, so the overhead scales with num_workers. The compatibility default protects external components loaded from PyPI installations, forks, or --search-dir roots that may implicitly rely on automatic initialization.

Validation

  • PYTHONPATH=/tmp/Gym-ray-split /home/ansubramania/dev/Gym/.venv/bin/python -m pytest tests/unit_tests/test_ray_opt_out.py tests/unit_tests/test_server_utils.py -q — 80 passed.
  • Scoped pre-commit over the complete PR diff — passed.

Rollout evidence

N/A for model behavior. This changes only Ray import/connection selection; it does not alter prompts, model requests, server construction, trajectories, verification, or rewards.

Compatibility

  • Undeclared external servers remain Ray-enabled and receive a migration warning.
  • A future release can change None to disabled after downstream migration.
  • The orchestrator's shared Ray cluster is unchanged in this PR.

@copy-pr-bot

copy-pr-bot Bot commented Sep 22, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@ananthsub ananthsub added feature New capabilities, enhancements, or enablement work area:core Shared APIs, servers, telemetry, health, and registries labels Sep 22, 2026
@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

@ananthsub

Copy link
Copy Markdown
Contributor Author

/ok to test 8fdc1ad

@ananthsub
ananthsub force-pushed the ananthsub/ray-opt-out branch from 8fdc1ad to ee51686 Compare September 28, 2026 01:28
@ananthsub
ananthsub marked this pull request as ready for review September 28, 2026 01:29
@ananthsub ananthsub added the needs-review PR is ready for code review and waiting on a reviewer label Sep 28, 2026
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team September 28, 2026 01:29
@yaoyu-33 yaoyu-33 added the complexity:high Cross-component or shared-contract change with a large review surface label Sep 28, 2026
@ananthsub
ananthsub force-pushed the ananthsub/ray-opt-out branch from ee51686 to 9b99354 Compare September 28, 2026 16:51
@ananthsub ananthsub changed the title feat(server): declare Ray dependencies explicitly feat(server): allow servers to opt out of Ray Sep 28, 2026

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

Requesting changes for two reproduced lifecycle regressions: permanent multi-worker startup errors now leave the launcher waiting indefinitely, and dry run skips server-specific validation and constructor-based preparation. The logging finding and validation-description comment are nonblocking.

Reviewed commit 9b993542faa546f985a74bf28e92293175a25950 independently with Codex and Claude Opus 5.5, then verified the findings against the base behavior.

Validation performed on Python 3.13.14 with the locked dependencies (Ray 2.56.1, Uvicorn 0.37.0):

  • pytest tests/unit_tests/test_ray_opt_out.py tests/unit_tests/test_server_utils.py resources_servers/example_single_tool_call/tests/test_app.py -q: 83 passed.
  • Four real process/HTTP smoke cases using the production example weather server: Ray disabled with one and two workers, enabled with two workers, and the legacy None default with two workers. Disabled processes rejected Ray imports; enabled workers connected to the same temporary cluster.
  • Base/head comparisons reproduced the permanent startup-failure loop, skipped config validation, and skipped BigCodeBench constructor setup. The installation helper was mocked; no model inference was run.
  • Changed-file Ruff lint and formatting checks passed.

Please commit regression tests with both fixes: a permanent startup failure must produce a bounded launcher failure, and dry run must still reject invalid concrete server settings and execute the intended preparation hooks. The review harnesses supplied evidence but are not committed tests in this PR.

Nonblocking rollout note: coordinate landing with #3728 so built-in servers do not spend an extended period emitting implicit-Ray migration warnings.

Comment thread nemo_gym/server_utils.py Resolved
Comment thread nemo_gym/server_utils.py Resolved
Comment thread nemo_gym/server_utils.py Resolved

@yuhezhang-ai yuhezhang-ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-reviewed at 81a005e. All four earlier comments are addressed: startup failures remain visible to the launcher, dry runs preserve concrete validation and constructor preparation, server-name log prefixes are retained, and the earlier example/integration-test claim has been removed.

Validation: 81 focused tests passed, along with four real process/HTTP startup cases covering Ray opt-out, Ray-enabled and legacy multi-worker behavior. The opt-out cases blocked Ray imports, and a permanent startup-failure probe exited promptly and was detected by the launcher. Scoped lint/format checks passed. No full model rollout or full CI run was performed.

No remaining blocking findings. Thanks for addressing the feedback.

@ananthsub
ananthsub added this pull request to the merge queue Sep 28, 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/36490226057

Merged via the queue into NVIDIA-NeMo:main with commit 6a962dc Sep 28, 2026
43 checks passed
@ananthsub
ananthsub deleted the ananthsub/ray-opt-out branch September 28, 2026 22:18
khazic pushed a commit to khazic/Gym-lao that referenced this pull request Sep 29, 2026
## What changed

Declare `ray_enabled = True` or `False` on every built-in Gym server
implementation and add source audits that keep declarations synchronized
with direct and inherited production Ray dependencies. Ray-backed
subclasses such as `GenRMModel` and `LegalAgentBenchHarborBridge` remain
enabled even though their Ray calls live in parent implementations.

Generated environment scaffolds now emit explicit non-Ray declarations
for resources and custom agent servers. The inventory applies exclusions
relative to the checkout/component root so it remains valid in hidden
worktrees and cache directories.

This PR builds on merged PR NVIDIA-NeMo#3622, which introduced the class-level
contract, compatibility warning, and lazy import. It now targets `main`
directly and contains only the declaration layer.

## Why

Ray usage is an implementation property, not a deployment/configuration
choice. Keeping the declaration on each server class makes the
dependency visible to maintainers and avoids duplicating it across YAML
variants. The audits catch newly added servers, newly introduced direct
Ray imports, and known inherited Ray call paths.

No separate issue is required; this is part of NVIDIA-NeMo#3669.

## Validation

- `PYTHONPATH=/tmp/Gym-ray-split
/home/ansubramania/dev/Gym/.venv/bin/python -m pytest
tests/unit_tests/test_ray_opt_out.py
tests/unit_tests/test_environment_scaffold.py -q` — 53 passed.
- Scoped pre-commit over all feedback changes — passed.

## Rollout evidence

N/A. This PR declares existing server behavior and updates generated
templates; it does not change prompts, model requests, trajectories,
verification, or rewards.

## Compatibility

Ray-backed servers, including inherited consumers, explicitly retain
Ray. Non-Ray servers and newly scaffolded components opt out once NVIDIA-NeMo#3622
is present.

---------

Signed-off-by: Ananth Subramaniam <[email protected]>
ananthsub added a commit to jiwasawa/Gym that referenced this pull request Oct 8, 2026
…-NeMo#4245)

## What changed

`RunHelper.start()` now starts or joins Ray only when a configured
server may use it. Previously `RunHelper._start` called
`initialize_ray()` unconditionally. That started a local Ray cluster, or
connected to `ray_head_node_address`, even when every configured server
declared `ray_enabled = False`.

This applies to every path that launches servers through `RunHelper`:
- `gym env start`, including dry runs (`++dry_run=true`)
- `gym eval run` without `--no-serve`
- programs that import and call `RunHelper` themselves

How it works:

- **The check:** a new `entrypoint_may_use_ray()` in
`nemo_gym/server_utils.py` reads each server entrypoint's source without
importing it, because each server runs in its own venv. It finds the
classes the entrypoint calls `run_webserver()` on and reads their
`ray_enabled` declarations.
- **When it skips Ray:** only when every such class literally declares
`ray_enabled = False`.
- **When it still starts Ray:** when a declaration is missing,
inherited, computed, or on a class imported from another module, or when
the entrypoint can't be read. This matches the runtime default for
undeclared servers.
- **Logging:** when Ray starts, Gym prints which servers caused it. It
prints nothing when Ray is skipped.
- **Refactor:** the config walk moves into `_configured_servers()`, so
the Ray decision and the launch loop use the same server list.

## Why

A local Ray cluster costs host memory, an object store in `/dev/shm`,
background processes, and several seconds of startup. Starting one here
took about 9 seconds. Configs whose servers all opted out of Ray in
NVIDIA-NeMo#3622, NVIDIA-NeMo#3728 and NVIDIA-NeMo#4244 still paid that cost on every launch. That hurts
most in memory-limited containers and in image builds that use a dry run
to prebuild server venvs, which then had to stop the leftover cluster
with `ray stop`.

The check itself takes about 2 ms per server. Across all built-in
entrypoints the median is 1.8 ms and the slowest is 40 ms.

This is step 7 of NVIDIA-NeMo#3669.

## Guidance

**For server authors:** declare `ray_enabled` on the class your
entrypoint calls `run_webserver()` on, even when a parent class already
declares it. The check reads only that class's own source, so an
inherited `False` still starts Ray. To see why Ray started for a config,
look for the log line naming the servers that may use it.

**For programs that embed Gym:**
- **Gym starts Ray itself:** when your process hasn't initialized Ray
before calling `RunHelper.start()`, a config whose servers all declare
`ray_enabled = False` now runs without any Ray cluster.
- **Your process already runs Ray:** when Ray is initialized before
`RunHelper.start()`, for example inside a Ray actor, nothing changes.
`initialize_ray()` already returned immediately in that case, and Gym
never started a cluster of its own. Servers that use Ray still join the
cluster named by `ray_head_node_address`, and servers that declare
`ray_enabled = False` don't connect, as since NVIDIA-NeMo#3622.

**For image builds:** a dry run of a config whose servers all declare
`ray_enabled = False` no longer starts Ray, so a following `ray stop` is
unnecessary. It's harmless to keep as a guard for configs that include
servers that use Ray.

## Validation

- `pytest tests/unit_tests/test_cli.py
tests/unit_tests/test_server_utils.py
tests/unit_tests/test_ray_opt_out.py
tests/unit_tests/test_cli_endpoint_readiness.py
tests/unit_tests/h2_ping_sidecar`, rerun after rebasing onto the HTTP/2
ping sidecar change (NVIDIA-NeMo#4079).
- **New tests:**
- the source check, covering declared, undeclared, inherited, imported,
multiple-class, missing and unparseable entrypoints;
- a test that every built-in entrypoint's result matches the audited
declarations;
- a `RunHelper` test that Ray is skipped for `False` and started for
`True` or undeclared. The skip case fails on the previous code.
- `pre-commit run` scoped to the changed files.

## Rollout evidence

**Smoke run:**

```
gym env start "+config_paths=[resources_servers/example_single_tool_call/configs/example_single_tool_call.yaml,responses_api_models/openai_model/configs/openai_model.yaml]"
```

- Gym did not start or join a Ray cluster.
- `gym env status` reported all four servers healthy: the resources
server, the simple agent, the legacy agent environment server and the
OpenAI model server.
- No new `raylet` or `gcs_server` processes appeared.
- No server logged the undeclared-Ray warning.

No model requests were sent. This change only decides whether Ray
starts, so it can't affect prompts, trajectories, verification or
rewards.

## Compatibility

- **Configs with any Ray-backed or undeclared server:** unchanged. Ray
starts or connects exactly as before.
- **Configs whose servers all declare `ray_enabled = False`:** Gym
doesn't start a local Ray cluster. If `ray_head_node_address` is set,
the `gym` process no longer connects to it, since none of the servers
use Ray. A process that already initialized Ray before calling
`RunHelper` is unaffected.
- **A subclass that only inherits `ray_enabled = False` from another
module:** still starts Ray until it declares the value on its own class.

---------

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

This branch was previously deployed

1 inactive deployment
public — 81a005e6 Deployed Sep 28, 2026 by copy-pr-bot[bot] via release / finalize / notify #3770
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core Shared APIs, servers, telemetry, health, and registries complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants