Repository navigation
Conversation
65e0f16 to
a3badb2
Compare
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE
I found four correctness/operability risks and one documentation NOTE. The inline comments include repair boundaries and proposed regression checks.
RISK — Please provide representative real smoke-rollout evidence for the final head. The PR leaves post-rebase rollout validation pending. Its pre-rebase timing tables don't establish that the final transport and routing changes preserve native tool execution, agent output, capture, and verification. AGENTS.md requires real model rollouts and inspection of agent/verifier behavior for behavior-changing agent work.
Please record representative delta-enabled multi-turn/tool runs for Codex, Hermes, OpenCode, and Pi against this head, including configuration, model/task identity, artifact locations, agent/tool behavior, and verifier outcome. Include a disabled control and check that Gym captures complete reconstructed requests with the expected model-call correlation. Preserve the existing native harness and default-disabled behavior; this transport-only change doesn't require a benchmark reward profile. Acceptance is recorded final-head evidence that each affected path reaches verification with intact conversation/capture evidence, rather than latency tables or mocked results alone.
I completed the source review across all 22 changed files and their directly affected paths. I couldn't execute tests or rollouts in this read-only review.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| # Reuse the same Gym connection even when the CLI opens a new local | ||
| # connection. Requests within this rollout must remain sequential. | ||
| # http.client preserves compressed/SSE data while handling framing. | ||
| connection = self._connection |
There was a problem hiding this comment.
RISK — Give each active HTTP exchange exclusive connection ownership. The helper uses a threaded listener, but every handler uses the same upstream connection without synchronization through response consumption. Hold the first upstream response open and POST from a second local connection: the handlers compete for one active HTTP/1.1 exchange, and the exception path closes that shared socket, so one request can receive a helper-generated 502 while the other's response is interrupted. Both should receive their own complete response. This isn't merely hypothetical unsupported traffic: the shipped OpenCode configuration enables subagent tasks, and the adapter doesn't enforce a single-outstanding-request contract.
Please change HistoryTransport.handle() and connection ownership so a connection belongs to one handler until its response is consumed or closed, and synchronize the corresponding history-state transition. A pool can retain parallel calls; serializing complete exchanges is narrower only if that restriction is acceptable for the supported harness behavior. The concurrency choice needs an explicit contract, so I haven't supplied an exact patch. Preserve sequential keepalive reuse, full/append/edit reconstruction, and the single full resend after explicit resync; don't retry uncertain model executions or interrupted streams.
Proposed acceptance: block the first upstream response, submit a second request through another local connection, then release both. Assert complete, unmixed responses without 502/socket reset, including streamed replies and distinct session headers. Retain the existing sequential test's exact reconstructed requests, suffix-only append, and one-upstream-connection assertions. These checks weren't executed.
There was a problem hiding this comment.
Fixed at the head: HistoryTransport._upstream_connection() now leases one pooled connection per exchange and holds it until the response body has been relayed, and a failed exchange closes only its own connection.
The new tests in tests/unit_tests/test_model_history_transport.py hold one response open while a second request with a different session header completes, check that a failed exchange does not interrupt another response, and check that sequential calls still reuse one upstream connection.
| if harness == "opencode": | ||
| config = json.loads(params["env"]["OPENCODE_CONFIG_CONTENT"]) | ||
| config["provider"]["nemo_gym"]["options"]["baseURL"] = local_url | ||
| params["env"]["OPENCODE_CONFIG_CONTENT"] = json.dumps(config) |
There was a problem hiding this comment.
RISK — Preserve OpenCode's literal replacement-prompt serialization. When deltas are enabled, parsing and reserializing OPENCODE_CONFIG_CONTENT turns the deliberately escaped \u007b back into {. A replacement system prompt such as {env:G10_TEMPLATE_VALUE} or {file:missing-prompt.txt} is protected by _serialize_replacement_config() in the sandbox caller. This rewrite removes that protection before the CLI loads it, allowing substitution or a missing-file failure instead of literal instructions. The existing pinned-CLI regression defines this contract.
One bounded correction is to move the existing stdlib-only _serialize_replacement_config() and _dump_with_serialized_member() into the shared helper, keeping the agent's existing serializer name available through an import. Add literal_replacement_prompt: bool(system) and self.config.system_prompt_mode == "replace" to the staged payload, then replace this assignment with:
params["env"]["OPENCODE_CONFIG_CONTENT"] = (
_serialize_replacement_config(config)
if params.get("literal_replacement_prompt", False)
else json.dumps(config)
)The uploaded helper must contain the serializer; it can't import the full agent application. The invariant is selective protection of the generated agent.build.prompt only. Don't escape every brace: other fields, append-mode prompts, and configured prompts without a generated replacement must retain native expansion.
Proposed acceptance: extend the pinned-CLI test through delta-enabled staging and configure_transport(). Assert that build.prompt remains exactly equal to the input, including missing-file markers, Unicode, quotes, backslashes, and literal \u007b; retain ordinary-field expansion. Also retain the provider configuration test's unchanged model/API key and loopback URL assertions. This suggested correction needs verification; I couldn't run these checks.
|
|
||
| def __init__(self, socket_dir: str) -> None: | ||
| super().__init__(socket_dir) | ||
| self.claims = SessionClaims(socket_dir, uuid4().hex, holds=lambda _: True) |
There was a problem hiding this comment.
RISK — Bound the lifetime of model-rollout ownership records. With the global history flag enabled and multiple model workers, every distinct prefixed generation request creates a claim, including ordinary full-history requests. SessionClaims.claim() retains each ID in _mine and writes a claim file. Here, holds=lambda _: True prevents release, and install_rollout_routing() installs no cleanup. N completed one-call rollouts therefore leave N memory entries and N files for the server's entire lifetime, even after the bounded history buffer has evicted their histories. Long-running evaluation/training servers accumulate unbounded routing state.
Please give RolloutRouter/install_rollout_routing() a bounded ownership lifecycle coordinated with active requests and retained worker-local history. Reclaim inactive claims once the worker no longer needs that rollout's local state; don't cap _mine independently of the on-disk claims. Preserve ownership during inference and while usable histories remain. After ownership expires, an append reaching an empty worker must still get the explicit pre-inference resync response, not execute with partial history. The cleanup hook needs coordination with the history owner, so an exact eviction patch isn't clear from the current interfaces.
Proposed acceptance: submit more distinct one-call rollouts than the history retention limit, expire/evict their histories, and assert inactive claim files and in-memory IDs are reclaimed. Keep a blocked in-flight request and an actively appended conversation during cleanup; both must retain their owner. Retain the reconnect/delta tests' complete-history and no-double-append assertions. Source reasoning only; checks weren't executed.
| # A forwarded request must never bounce between workers. | ||
| await _conflict("The rollout's worker ownership changed while routing the request.", scope, receive, send) | ||
| else: | ||
| await self.forward(owner, scope, receive, send) |
There was a problem hiding this comment.
RISK — Recover model ownership after an owner worker exits. Establish rollout R on worker A, stop A while worker B remains alive, then send R's next request to B. The claim still names A, so this branch forwards to its dead socket and receives HTTP 410. Nothing transfers the claim, so even a complete-history resend keeps failing until the whole server restarts. The client's full-history fallback only handles 409 gym_history_resync. This newly strands otherwise recoverable model calls, including ordinary full-history requests; unlike resources-session state, model input history is available from the caller.
Please add model-specific dead-owner recovery in RolloutRouter, leaving stateful-session forwarding's 410 behavior unchanged. After a confirmed missing/refused owner socket before dispatch, atomically transfer the stale claim to a live worker. Its normal reconstruction can then reject an append with gym_history_resync or accept a full request. Preserve single ownership, the forwarding-loop guard, and checkpoint admission/fencing. Don't retry a request after uncertain execution, timeout, or an interrupted response. The claim-replacement fencing needs design verification; blindly unlinking the file would race competing recoveries.
Proposed acceptance: accept a full request on A, shut A down, and send the next append through B. Expect one explicit resync followed by successful full-history dispatch on the new owner. A direct full-history request should recover too, and simultaneous recovery attempts must select one owner. Retain the existing stateful-session worker-loss tests' 410 assertions. These checks weren't executed.
| For sandboxed OpenCode, Pi, Codex, and Hermes, set the agent's | ||
| `history_delta_enabled: true` and the Gym global flag | ||
| `history_delta_enabled: true`. Both default to `false`. Delta transport currently | ||
| requires exactly one model-proxy worker because histories are stored in process |
There was a problem hiding this comment.
NOTE — Suggestion: document the implemented multiworker behavior. The guide says exactly one model-proxy worker is required, but run_webserver() explicitly installs rollout-owner routing for multiple workers, with forwarded-delta coverage. The stale limit unnecessarily directs users to single-worker deployment.
Suggested replacement for the paragraph at lines 425–429:
For sandboxed OpenCode, Pi, Codex, and Hermes, set the agent's
`history_delta_enabled: true` and the Gym global flag
`history_delta_enabled: true`. Both default to `false`. With multiple model-proxy
workers, Gym routes each rollout to the worker holding its in-memory history.
OpenCode, Pi, and Codex also require Python 3 in the task sandbox.Preserve both opt-in flags and the sandbox Python requirement. Static acceptance: the documented worker behavior should match the enabled multiworker branch and forwarded-delta test. This wording doesn't claim recovery from worker loss. I haven't previewed the docs.
a3badb2 to
18bd7b4
Compare
18bd7b4 to
3460c81
Compare
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
Signed-off-by: Stefan Niebler <[email protected]>
3460c81 to
07cf94f
Compare
There was a problem hiding this comment.
Requesting changes because this adds a second mechanism, with its own server state, for something the model server already works out.
Capture lineage already identifies which earlier call a request extends, by fingerprinting the model-authored turns (assistant_fingerprint).
This PR answers the same question a second way: the client declares a version, a separate canonical JSON encoding gets its own sha256, and each model server worker keeps its own copy of every conversation.
That copy is what requires the per-worker history buffer, the rollout owner files and routing between workers, and the 409 resync protocol.
It also brings Python back into the sandbox, which #5153 and #5327 removed.
The inline comments show where this extra state breaks today: above 64 conversations per worker most calls become an append, a 409 and a full resend, which is slower than sending the full history, and checkpoint retire leaves the state behind until eviction.
The measured gain is the body read on the sandbox-to-Gym hop, roughly 90 to 170 ms per call.
Please measure stateless request compression first: the existing JavaScript proxies compress the body with gzip or zstd and the model server decompresses it, with no buffer, no ownership, no resync and no interaction with checkpointing.
If that is not enough, a delta design should build on the model call identity that capture already resolves rather than a parallel one.
| class HistoryBuffer: | ||
| """Bounded, expiring histories owned by one Gym worker, isolated by rollout/conversation.""" | ||
|
|
||
| def __init__(self, *, max_bytes: int = 256 * 1024 * 1024, max_entries: int = 64, ttl: float = 1800) -> None: |
There was a problem hiding this comment.
The history buffer keeps at most 64 conversations per uvicorn worker, and the model server always builds it with these defaults (install_model_call_capture).
Each key is a rollout attempt plus a conversation, so subagents and resumed activations each take their own entry.
Training and evaluation commonly run hundreds of concurrent rollouts per model server worker, and above 64 live conversations most appends find their base already evicted.
Each miss then costs a delta request, a 409 gym_history_resync, and a full resend, which is one more round trip and more server work than sending the full history directly.
For example, when 65 conversations take turns round-robin against one buffer, every one of 195 appends is answered with a 409.
Could the capacity come from configuration, sized from the expected concurrent conversations per worker, with hit, miss and eviction counters so the hit rate is visible in rollouts?
| if buffer is None: | ||
| raise ValueError("Model rollout routing requires an installed history buffer") | ||
| router = install_rollout_routing(app, socket_dir=socket_dir, holds=buffer.retains_rollout, backlog=backlog) | ||
| buffer.on_rollout_evicted = router.claims.release |
There was a problem hiding this comment.
A rollout attempt's buffered history and its owner file are released only when the buffer evicts them, either through the 64-entry limit or the 30-minute timeout.
Checkpoint retire does not touch them: PolicyGate.retire, the participant retire and retire_local only refuse and cancel calls.
After NeMo RL retires an attempt, its entries were touched more recently than a live rollout that is in a long tool step, so eviction removes the live rollout first and that rollout pays a resync on its next call.
Checkpointing requires that an attempt's state is released when retire returns, rather than at the end of a time window.
Could retire (single worker and retire_local) drop the buffer entries whose capture key belongs to the retired attempt?
That would also release the owner files through on_rollout_evicted, and the timeout could then go away.
| if self._closed: | ||
| raise OSError("History transport is closing") | ||
| if self._idle_connections: | ||
| connection = self._idle_connections.pop() |
There was a problem hiding this comment.
The pool hands out idle connections without checking how long they have been idle, but Gym's uvicorn closes a keep-alive connection after 30 seconds (timeout_keep_alive=30).
When a tool step such as a build or a test run takes longer than that, the next model call is sent on a closed socket, getresponse() raises RemoteDisconnected, and the helper answers the CLI with a 502 without retrying.
By then state.submitted() has already recorded a base that Gym never stored, so the CLI's own retry costs another 409 and a full resend.
Could the helper retry once on a new connection when a reused idle connection fails before any response bytes arrive, and call submitted() only after getresponse() returns?
|
|
||
|
|
||
| def _encoded(value: Any) -> bytes: | ||
| return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() |
There was a problem hiding this comment.
json.dumps(..., ensure_ascii=False).encode() raises UnicodeEncodeError when a string contains a lone UTF-16 surrogate.
That happens when a JavaScript CLI truncates tool output in the middle of an emoji: JSON.stringify writes a lone \ud83d escape, and Python parses it into an unpaired surrogate.
The helper then answers 400 to that call and to every later call, because the item stays in the history, so the rollout cannot continue.
The same bytes pass on the path without deltas, and Gym's client already handles lone surrogates for the same reason (http_client.py).
Could all three encoders (this one, _encoded in model_history_transport.py, and the Hermes copy) use ensure_ascii=True, together with full_bytes below?
They need to change together so the digests still agree.
| { | ||
| "type": "http.response.start", | ||
| "status": status, | ||
| "headers": [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())], |
There was a problem hiding this comment.
The OpenAI Python SDK retries every 409 unless the response carries x-should-retry: false (_should_retry), and Hermes builds its client with the default of two retries.
So each gym_history_resync makes Hermes send the same stale append three times, with backoff, before HistoryDeltaClient falls back to the full history.
Even against a server that answers immediately, one resync takes about 1.4 seconds, and resyncs are frequent once the buffer is full.
| "headers": [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())], | |
| "headers": [ | |
| (b"content-type", b"application/json"), | |
| (b"content-length", str(len(body)).encode()), | |
| (b"x-should-retry", b"false"), | |
| ], |
The current tests raise ConflictError from a mock, so they cannot catch this.
A Hermes test that uses a real openai.OpenAI client against the test app would.
| ) | ||
| if harness == "opencode": | ||
| config = json.loads(params["env"]["OPENCODE_CONFIG_CONTENT"]) | ||
| config["provider"]["nemo_gym"]["options"]["baseURL"] = local_url |
There was a problem hiding this comment.
This replaces OpenCode's baseURL with the helper's address and gives the helper a fixed upstream from history_transport.base_url.
Open #5413 resumes OpenCode in place from a snapshot that keeps processes, and it relies on its own relay being OpenCode's baseURL so it can re-point calls at the replacement attempt's model URL.
If both land, the helper sits in front of the relay and keeps sending to the dead attempt's model server after a restore, so resumed calls fail with 502.
Could the helper take its upstream from the URL the CLI was already configured with, so the chain becomes CLI, helper, relay, Gym?
Whichever of the two PRs merges second should cover this combination with a test.
| """Default shim protocol; integrations may override detection and reconstruction.""" | ||
|
|
||
| def matches_request(self, scope: dict[str, Any]) -> bool: | ||
| return any(name.lower() == b"x-gym-history-transport" for name, _ in scope.get("headers", [])) |
There was a problem hiding this comment.
Gym's own headers use the x-ng- prefix, for example x-ng-session-owner, while this PR adds x-gym-history-transport and x-gym-client-request-id.
Nothing in Gym reads x-gym-client-request-id, because only the helper sets and forwards it.
Error replies on this path also come in two shapes.
History errors use an OpenAI-style {"error": {"code": ...}} body, while routing errors for the same request use {"detail": ...} (_conflict), and the 410 tells a model call to "Start a new session".
Once agents depend on these names and bodies, changing them breaks the wire format.
Could the transport header become x-ng-history-transport, the request ID header be dropped until the model call identity work in #5903 defines one, and the routing errors on model calls use the same typed error body as the history errors?
| @@ -0,0 +1,530 @@ | |||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | |||
| # SPDX-License-Identifier: Apache-2.0 | |||
| """Sandbox-local, stdlib-only history transport for unmodified native CLI clients. | |||
There was a problem hiding this comment.
This docstring calls the CLI "native", a word Gym does not use for CLIs or protocols.
The same word appears at lines 428, 439 and 471, in the fern page, and in the NativeProtocol test class.
Could these say "unmodified CLI", "the CLI's own retry policy" or "a harness-specific protocol", depending on the meaning at each place?
The flag name history_delta_enabled also sits next to the unrelated delta_records in the same _CaptureMiddleware constructor (model_call_capture.py).
A name such as model_history_transport_enabled would keep the two apart.
| For sandboxed OpenCode, Pi, Codex, and Hermes, set the agent's | ||
| `history_delta_enabled: true` and the Gym global flag | ||
| `history_delta_enabled: true`. Both default to `false`. Delta transport currently | ||
| requires exactly one model-proxy worker because histories are stored in process |
There was a problem hiding this comment.
This section still says the transport requires exactly one model server worker, but run_webserver now installs rollout routing for several workers.
A reader following the page would limit the model server to one worker when that is no longer needed.
Could the section describe the multi-worker routing and also write down the wire contract?
That contract covers the _gym_history envelope fields, the error codes (409 gym_history_resync, 400 gym_history_invalid and gym_history_disabled, 413), the 32 MiB limit, the buffer capacity and what happens when it is exceeded, and how the transport behaves across a checkpoint restore, where the first call of each conversation resends the full history.
The same section says "model-proxy worker" where it means "model server worker".
The module docstrings are out of date in the same way: history_delta.py says "single-process", and the session_routing.py module docstring still says a request for a gone owner always gets a 410.
| assert recovered.json()["input"] == [] | ||
|
|
||
|
|
||
| def test_forwarded_request_enters_only_the_owners_admission_gate(make_client, envelope): |
There was a problem hiding this comment.
The routing and admission tests here are thorough, but these cases are still uncovered:
- more live conversations than the buffer capacity, checking the resync rate and that owner files stay bounded
- retire releasing the attempt's buffer entries and owner files, and a retired attempt that lets a live one stay in the buffer
- a restored generation cut whose first call is an append that gets a 409, checking that the cut is given back and the full resend continues it
- the conversation headers each pinned CLI actually sends when subagents run (Codex
thread-id, OpenCodex-opencode-session), since a shared key turns every other call into a full resend
The smoke rollouts the earlier review asked for could also report the append-versus-full ratio per harness.
| await self.session.sandbox.upload( | ||
| Path(__file__).with_name("history_delta.py"), f"{_SANDBOX_RUNTIME_DIR}/history_delta.py" | ||
| ) |
There was a problem hiding this comment.
This uploads history_delta.py on every Hermes runtime install, including when history_delta_enabled is off, and the runner imports it on every run (sandbox_runner.py).
Three existing Hermes agent tests assert the exact set of uploaded files, so they now fail: both cases of test_sandbox_access_selects_runtime_provider (test_app.py) and test_seed_installs_hermes_when_it_does_not_import (test_app.py).
CI has not run the changed-server job on this PR yet, which is why nothing has flagged it.
Could the upload and the import happen only when history_delta_enabled is set?
That keeps the three tests passing as they are, and Hermes then behaves exactly as before when the flag is off.
What does this PR do?
Reduce sandbox-to-Gym HTTP traffic for long rollouts by sending newly appended conversation messages instead of resending the full history on every model call.
Adds optional history-delta transport for Codex, Hermes, OpenCode, and Pi. Gym reconstructs the complete request before validation, training capture, and inference.
The first request sends full history. History edits or compaction also trigger a full send. Missing or stale history triggers one full-history resynchronization before inference. Repeated delivery does not append the same delta twice.
Validation
Adds coverage for full and incremental requests, history edits, missing or stale bases, malformed deltas, repeated delivery, and dropped responses.
Focused test suite: 270 passed 3 skipped:
tests/unit_tests/test_model_history_transport.py
tests/unit_tests/test_history_delta.py
tests/unit_tests/models/test_base_responses_api_model.py
tests/unit_tests/server_runtime/test_session_routing.py
responses_api_agents/opencode_agent/tests/test_prompt_serialization.py
tests/e2e/session_routing/test_session_routing_e2e.py
I tested with this PRs changes on and off agains run_harness_conformance.py with real Pi, Codex, OpenCode, and Hermes harnesses against scripted model responses. We compared reconstructed model requests, tool-call sequences and results, final outputs, usage, and verification outcomes. These matched after normalizing generated IDs and paths, with only Hermes’s generated conversation-start timestamp differing
Rollouts
Measured on Commit 3460c81
Baseline = This branch with delta disabled
Delta = This branch with delta enabled
Tables show: Baseline -> Delta
Unit: ms
Gym side:
Harness side :
Components can overlap; do not sum the rows. Zero means no separately attributed duration; Hermes has no separate helper measurement.
¹ OpenCode’s tool timing was unreliable in these runs, so this row can include tool execution time and is not validated harness overhead.
Compatibility and benchmark impact
Disabled by default. Enable
history_delta_enabled: truein both the agent configuration and Gym’s global configuration.Ordinary requests retain their existing behavior. Model processing and training capture receive reconstructed full histories. The transport does not add retries for model errors, timeouts, or interrupted streams.
No benchmark-result change is intended; the change reduces request payload size.
Checklist