Repository navigation
feat(sidecar): optionally run an HTTP/2 PING proxy from gym env start for endpoints with idle timeouts - #4079
Conversation
Signed-off-by: Onur Yilmaz <[email protected]>
|
/review |
|
/ok to test 744d961 |
There was a problem hiding this comment.
Note: this was submitted as an approval by mistake and GitHub does not let the author change that. Please read it as a comment-only review from the NVCF side; merge judgement stays with the Gym maintainers.
Reviewed from the NVCF side. This matches the sidecar we validated against the production path (Global Accelerator 340 s and the ALB's hourly GOAWAY), and the wiring is careful. Approving, with two follow-ups and one doc nit as inline comments.
What I checked locally on 744d961:
| Check | Result |
|---|---|
| go vet, go test (Go 1.27) | pass |
| tests/unit_tests/h2_ping_sidecar and test_cli.py | 186 passed |
| ruff check / format | clean |
| Go sources in the wheel | yes: nemo_gym/tools/sidecar/*.go and go.mod ship, so build-on-first-use works from a pip install |
| PING frames while a request waits | yes. Against a local HTTP/2 origin with a 6 s first-byte delay and -ping-interval 1s (GODEBUG=http2debug=2), the sidecar wrote 6 PINGs and received 6 ACKs during the wait |
The last row covers the mechanism behind the "keepalive not demonstrated end to end" note: the read-idle timer fires and the frames go out while the stream is waiting. It is the same timer we validated on the real endpoint with the original sidecar.
Things done well: ready file only after bind plus the stale-file guard, own session so Ctrl-C drains servers before the proxy, URL rewriting that leaves interpolations alone and matches hosts exactly, sidecar in the reserved keys, dry run starts nothing, startup failure aborts before any server, all tested.
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
HOLD — automatic URL routing and startup cleanup need corrections, and readiness markers must be isolated between concurrent runs.
Reviewed all 17 changed files and traced config serialization, model URL consumption, process ownership, Ray supervision, and the existing regression tests. Findings: three RISKs and one documentation NOTE.
Validation was source-only: tests were not executed. The existing Go tests also do not establish end-to-end survival of a request silent for more than 340 seconds. Suggested code below requires author verification.
Review generated by codex
… and ready markers
- Route resolver-backed URLs (for example ${oc.env:POLICY_URL}) through the sidecar by
matching the resolved value; aliases stay aliases and a list that aliases another list is
rewritten as a copy.
- Make startup transactional: validate the rewrite on a copy before any process starts, and
stop the proxy if anything fails or is interrupted after it started.
- Give every NodeSidecars owner its own ready-marker name so concurrent runs cannot delete or
accept each other's marker.
- Add -max-conn-age (config: max_conn_age, default 50m, jittered) so the upstream connection is
retired before the load balancer's hourly GOAWAY; in-flight requests finish on the old one.
- Warn when an instance listens on a non-loopback address.
- Docs: version-prefixed internal links, 'at the time of writing' for the integrate hostname
timeout, and the new settings and limits.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Onur Yilmaz <[email protected]>
…decar The proxy listens on loopback, so each node that runs a Gym process needs its own. 'all' is now the default; 'local' (plain child process, no Ray) and an explicit list of node IPs remain available. Tests that need a local run pin nodes explicitly, and a new test covers the default. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: Onur Yilmaz <[email protected]>
| // | ||
| // NVCF's endpoints sit behind AWS Global Accelerator, which drops any TCP | ||
| // connection carrying no application-layer data for 340s. That limit is fixed | ||
| // by AWS. TCP keepalive does not reset it because only bytes above the TCP |
There was a problem hiding this comment.
alternatives worth ruling out: this PR targets requests whose first response byte takes more than 340 seconds.
- Streaming: with
stream: true, the first byte arrives with the first generated token, reasoning tokens included. Only time spent queued inside NVCF would stay silent. - NVCF polling: NVCF documents an
NVCF-POLL-SECONDSheader and a/v2/nvcf/pexec/status/{requestId}endpoint for long invocations (docs).
Have you measured whether NVCF queueing alone goes past 340 seconds? And does the OpenAI-compatible invocation URL support polling? @balajinvda may know the second.
There was a problem hiding this comment.
I don't have data about NVCF queuing, but these seem like reasonable things to try. Not sure if we looked at these before the sidecar solution. CC @saumishr
There was a problem hiding this comment.
correction on streaming: Gym doesn't stream from the upstream today. The request models only accept stream: false (openai_utils.py#L880, #L1284). When a client sends stream: true, the model server still makes a non-streaming upstream call and replays the finished response as SSE (base_responses_api_model.py#L376-L378).
So streaming isn't a config switch here. The model server would have to read the upstream as SSE and rebuild one response from the text, reasoning, tool-call and usage chunks. That keeps the fix in Python, but it's real work, and time spent queued inside NVCF would still be silent. The polling question still stands.
|
|
||
| def build_sidecar(output_path: Path) -> None: | ||
| """Compile the bundled Go source into ``output_path``.""" | ||
| go = shutil.which("go") |
There was a problem hiding this comment.
build the binary into the container image: Gym's container image (docker/Dockerfile) doesn't install Go. So build-on-first-use fails in the main deployment path, including NeMo-RL containers, and every user needs Go or a hand-built binary.
Please build the sidecar in a Go stage of the Dockerfile and copy it to a fixed path in the image, and have default_binary_path check that path first. The image then needs no Go at run time.
Please don't add prebuilt binaries to the nemo-gym wheel, because that turns it into a per-platform wheel for one optional feature. If pip users need a prebuilt binary, ship a separate per-platform package behind an extra such as nemo-gym[sidecar], the way ruff and uv ship theirs.
There was a problem hiding this comment.
I'll leave this to a follow up PR, I think @kajalj22 can do this better than me.
| } else { | ||
| r.Body = io.NopCloser(bytes.NewReader(buf)) | ||
| r.ContentLength = int64(len(buf)) | ||
| r.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(buf)), nil } |
There was a problem hiding this comment.
the buffer lives for the whole wait: GetBody keeps buf alive until the transport is done with the request. For this feature, that is the whole multi-minute wait for the first byte. The docs (L88) say peak memory is the limit times the number of concurrent requests. That peak lasts for minutes, and the garbage collector can't free any of it. For example, 2,000 judge calls with 0.5 MB bodies hold about 1 GB.
gomemlimit makes this worse. The docs suggest a value like 1GiB, but the limit is soft. When live memory is above it, Go keeps collecting instead of failing, and can spend up to half the sidecar's CPU doing so.
Please document how to size retry_body_limit and gomemlimit for the expected concurrency. Please also warn that a gomemlimit below that size slows the sidecar down instead of capping its memory.
There was a problem hiding this comment.
Done. The docs now have a "Sizing memory" section, and the config docstrings and the README match it. Buffered bodies stay in memory for the whole wait for the first byte, so the memory held is the sum of the bodies in flight, at most retry_body_limit × concurrent requests. Your example (2,000 calls × 0.5 MB ≈ 1 GB) is in there, along with the 16 MiB worst case. I recommend sizing retry_body_limit for the largest body you expect to retry. gomemlimit is documented as a soft limit that should be set above that working set. A value below it slows the sidecar down instead of capping memory, so bound memory with retry_body_limit or the concurrency instead. I haven't measured the Go runtime's own overhead on top, and the docs say to measure with your workload.
| Protocols: protocols, | ||
| HTTP2: &http.HTTP2Config{ | ||
| SendPingTimeout: *pingInterval, | ||
| PingTimeout: *pingTimeout, |
There was a problem hiding this comment.
one late PING reply fails every request on the connection: aiohttp spreads Gym's requests over up to 1,024 connections per host. The sidecar folds them into a few HTTP/2 connections, and AWS load balancers allow up to 128 concurrent requests per connection.
When one PING reply arrives later than PingTimeout (15 seconds by default), Go closes the connection. Every request on it then fails at once, each possibly minutes into its wait. Under heavy load, the PING reply can queue behind response data on the same connection. Any retries then resend the whole batch together, so the judge compute is spent twice.
Could you share results from the training scale tests along with sidecar memory, 502 responses, and connections closed by PING timeouts?
There was a problem hiding this comment.
-
The concern is accepted and documented. The docs page's Limits section, lines 191–197 ("One late PING reply fails every request on that connection"), describes the failure mode. A late PING reply makes Go close the shared connection, every request on it fails at once, and a retry resends the whole batch.
-
There is one knob. ping_timeout is the setting, default 15s, and the docs say to raise it if you see this.
-
It says what is unknown. It states plainly: "This has not been measured at training scale yet."
I don't have the scale results. @yfw or @balajinvda have tested this and they might have it.
There was a problem hiding this comment.
In the POC implementation, we previously ran a Nano 3.5 training test (https://wandb.ai/nvidia/nemotron-3.5-nano/runs/0xaofqr8) with 8,192 sequences/update for 10 updates, using 60s read-idle PINGs and a 15s PING timeout.
The run completed with zero logged GenRM 502s or sidecar upstream errors. We observed nine proactive connection retirements, including connections with 128 in-flight requests, without accompanying errors.
We didn’t collect sidecar-specific RSS or dedicated PING-timeout counters, so this doesn’t rule out the correlated-failure scenario you describe. For future validation, we should collect sidecar RSS and PING-timeout/affected-request counts, and deliberately delay PING acknowledgements while requests are active.
Co-authored-by: Yi-Fu Wu <[email protected]> Signed-off-by: Onur Yilmaz <[email protected]>
|
/ok to test 91c8b65 |
|
/ok to test 91c8b65 |
@oyilmaz-nvidia, there was an error processing your request: See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/ |
|
/ok to test 45d330f |
|
/review |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP — the prior findings are fixed; no escalation-eligible regression found in this follow-up.
Verified against current source and regression assertions:
- Resolved scalar and list URLs are routed, while referenced non-model lists remain unchanged.
- Malformed URLs fail before spawning, and post-start failures stop the proxy.
- Readiness markers and logs are isolated per owner.
- All four previously reported documentation links now use
/main/targets.
Compared relevant subsequent changes with reviewed head 744d961, including binary caching, local process ownership, configuration changes, and connection rotation; traced their launch, serialization, and cleanup paths. This is a follow-up under the existing moderate-impact ceiling, not a fresh whole-PR review.
Validation was source-only: tests, builds, documentation previews, and live NVCF requests were not executed.
Review generated by codex
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/37820634890 |
…-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]>
Summary
Some model endpoints sit behind a load balancer or accelerator with a fixed idle timeout (for example 340s) that only counts application-level data. TCP keepalive doesn't reset it, so a request that takes longer than the timeout to return its first byte fails with
ServerDisconnectedError. HTTP/2 PING frames do reset the timer, but Gym's aiohttp client speaks only HTTP/1.1.This PR adds an optional local proxy (the "sidecar") that accepts HTTP/1.1 from Gym, forwards over HTTP/2, and sends PINGs while a request waits.
gym env startandgym eval runcan now start, supervise and stop it from config, and point model URLs at it. Gym itself stays on aiohttp, with no client changes.It is off by default. With no
sidecar:block, behavior is unchanged.Changes
nemo_gym/tools/sidecar/): a small Go proxy (stdlib only), a README and a Go test.-ready-file, written only after the port is bound.-retry-body-limit, default 16 MiB), so a request refused with a graceful GOAWAY is re-sent on a fresh connection instead of failing with a 502.nemo_gym/h2_ping_sidecar/)sidecar:(config.py, pydantic withextra="forbid").launcher.pystarts the processes, waits for the ready file, checks them on each poll, stops them with their own grace period, and builds the binary on first use if it is missing (needs Go).nodes: local | all | [ips].allruns one small Ray actor per node, pinned withNodeAffinitySchedulingStrategy.policy_base_urland any*base_urlunderresponses_api_models) are rewritten in memory tohttp://127.0.0.1:<port>. Config files on disk are not modified, and OmegaConf interpolations are left alone.nemo_gym/cli/env.py,global_config.py)RunHelperstarts the sidecar afterinitialize_ray()and before the servers are launched, because the config is serialized for them at that point. It checks the sidecar inpoll()and stops it after the servers.sidecaris added to the reserved top-level keys, so it isn't treated as a server.infrastructure/nvcf-h2-ping-sidecar.mdx(try-it commands, settings table, limits), plus entries in the infrastructure index, the configuration reference and the OpenAI model page.Configuration
Or as overrides:
Testing
go vetandgo test. A regression test makes the origin send GOAWAY after each response. Without body buffering, 2–9 of 40 requests failed in each of 8 runs. With it, none did.RunHelperstart and stop ordering and the dry-run skip. The related test files pass and ruff is clean.gym env startagainst a local fake HTTPS/HTTP/2 origin: the readiness probe and requests arrived over HTTP/2, theAuthorizationheader passed through, the Go memory and CPU limits applied, and Ctrl-C drained the sidecar and removed its ready file.nodes: allon a single-node cluster.genrm_compareevaluation against a hosted GenRM endpoint through the sidecar completed with all 16 rewards and no failures.Not covered / limitations
retry_body_limit.nodes: all, the binary path must be readable on every node. Prebuilt per-architecture binaries (for example in the container image) are not part of this PR.RunHelper(for example onesrunstep per server) don't get a sidecar.SidecarError, not a clean config error.nodes: all, the multi-node path was tested with mocks and a single-node Ray cluster only. Detecting a dead actor depends on the 60s poll loop.