Repository navigation
feat(opencode): multi-turn visual coding environment and BabyVision benchmarks - #5712
DanialTaheri wants to merge 23 commits into
Conversation
| text on every call. RL needs both the sampled tokens and a token sequence where each model | ||
| call's prompt extends the previous call's prompt + generation. | ||
|
|
||
| With ``track_token_ids`` the agent points OpenCode at its own chat-completions route and |
There was a problem hiding this comment.
responses_api_agents/opencode_agent/token_tracking.py:22
Could you say why track_token_ids adds its own tracker instead of using the training token capture already on main (token_id_capture, nemo_gym/models/token_capture/)? OpenCode's local /run already sends its model calls through it via _resolve_model_base_url(rollout_id).
From the code, the gaps this fills seem to be: images that tool calls add between model calls (main's project_chain_to_output_items carries them only as prompt tokens, so a VLM trainer gets no pixels), per-token top-k log-probabilities, and token IDs inline in the /run output rather than finalized from the capture store. If that is right, would adding images and top-k to TokenEntry and project_chain_to_output_items work for you instead?
Keeping two paths has costs:
- The tracked route posts to
/v1/chat/completionswithout the/ng-rollout/<id>/prefix, so model-call observability andtoken_id_capturenever see these calls. - The per-run state lives in memory, so it needs
num_workers <= 1. - A call that comes back without tokens splits the chain, and
main_chainkeeps only the deeper part. Main's builder masks such a sample instead of training on part of it.
There was a problem hiding this comment.
Thanks, your reading is right, and I agree two paths is one too many. I've removed track_token_ids from this PR in 4a67a36: the /ng-tok//v1/chat/completions proxy, token_tracking.py and its tests, and the per-token top-k fields it carried through responses_api_types and vllm_model. OpenCode's model calls now go only through _resolve_model_base_url(rollout_id), so RL on this environment uses token_id_capture like the other external harnesses. That also removes the num_workers <= 1 limit and the unchecked parent links.
The gaps you listed are the ones the tracker filled for us:
Tool-call images. The model crops and plots in the shell, and later calls see those images. A VLM trainer needs their pixels on the turn that first saw them; project_chain_to_output_items carries them only as prompt tokens.
Per-token top-k log-probabilities, which we use for score centering.
I'll follow up with a separate PR against main's capture: top-k through the vLLM adapter's extract_extras and the projection (alongside routed_experts), and tool-call images in TokenEntry and project_chain_to_output_items. Before adding images, I'll check whether NeMo RL's external staging path already sends them as attachments
292224a to
b7e0322
Compare
|
/ok to test b7e0322 |
|
/review |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
HOLD — 5 BLOCKER findings, 8 RISK findings, and 1 NOTE.
The blockers concern sandbox-to-host file writes, infrastructure failures becoming scored samples, and tracked outputs that can change the scored answer or publish an unsafe training sequence. The inline comments include repair boundaries and proposed acceptance checks.
I reviewed all 41 changed files and traced the affected scoring, runtime, model, capture, and validation paths. This was a static review; I didn't execute tests. The PR's reported smoke rollouts provide useful evidence, but they don't cover the failure cases below.
NOTE — Add discoverable user documentation for the new environment. The component and benchmark READMEs explain the feature, but the PR adds no user guide under the documentation site's pages. The pinned review rubric requires site documentation for a notable user-facing feature or benchmark. Could you add a short visual-coding guide, linked from the existing benchmark or agent documentation, covering both BabyVision variants, TSV staging, image-capable serving, judge credentials, host execution permissions, and the user-namespace requirement? Keep the component READMEs as the detailed references. Acceptance is a reachable documentation page whose prepare/run example matches the shipped configuration and clearly distinguishes local execution from session_sandbox; this is a proposed documentation check, not an executed preview.
Inline comments (escaped v1):
-
responses_api_agents/opencode_agent/app.pyline 1179: BLOCKER — Don't use sandbox output as a host download destination._run_sandbox_session()accepts every@@ng-opencode@@db=line from the combined output, including the tail of the model-writable.opencode-stderr. A sandboxed task can create a file at an absolute path matching a writable host file and append a marker naming it. This loop then overwrites that host file: the OpenSandbox downloader opens the destination withwb. Choosing the host's writable OpenCode launcher as the destination turns the next local invocation into execution of sandbox-supplied code. The model should control only files inside its sandbox, not writes on the agent host.Could you validate source markers and derive destinations from the trusted workspace? Replace this download loop with a constrained mapping, for example:
remote_db_dir = PurePosixPath(data_home) / "opencode" local_db_dir = work_dir / ".opencode-data" / "opencode" for database in databases: source = PurePosixPath(database) if source.parent != remote_db_dir or not source.name.startswith("opencode.db"): raise RuntimeError("Unexpected OpenCode database path") await provider.download_file(handle, str(source), local_db_dir / source.name)
This retains database and SQLite sidecar downloads without allowing a sandbox path to select an arbitrary host destination. Please verify the suggestion before adopting it.
Acceptance — proposed, not executed: return a forged marker naming a pre-existing host executable or sentinel file; it must remain unchanged and the run must report a protocol/infrastructure failure. Ordinary
opencode.db,opencode.db-wal, andopencode.db-shmmarkers must still download into the current run's database directory and parse successfully. -
responses_api_agents/opencode_agent/app.pyline 1184: BLOCKER — Preserve sandbox infrastructure failures instead of grading them as model failures. Whenprovider.create(), execution, or download raises, this branch returns(None, ..., False)._run_opencode()then parses a missing database as empty output, and_create_episode()returns an ordinary response. Local/runsends it to verification, where empty output scores zero. A provider outage therefore becomes a valid zero-reward evaluation/training sample. A diagnostic observation doesn't prevent that scoring.Could you propagate the provider failure through the existing typed failure path rather than returning a successful tuple? Also reject an inconclusive run exec result: inspect
result.error_type,result.return_code, and the runner completion marker before accepting output. The invariant is that an unavailable or unconfirmed execution cannot reach ordinary grading. UpdateTestSessionSandbox.test_infrastructure_failure_is_a_failed_run_not_an_exception, which currently locks in the lossy tuple behavior. The exact mapping should follow the existing failure contract, so I haven't invented a replacement exception here.Preserve: successful runs remain gradable; confirmed inner task timeouts (
124/137) retain the benchmark's task-timeout policy, rather than being blanket-classified as provider outages.Acceptance — proposed, not executed: exercise
/runwith create, run, and download failures, plus an exec result witherror_type="timeout"and no runner marker. Each must remain an infrastructure failure and bypass ordinary grading. Retain successful execution and confirmed inner-timeout cases with their existing outcomes. -
responses_api_agents/opencode_agent/token_tracking.pyline 151: BLOCKER — Verify token-prefix continuity before publishing a parent link.record_call()trusts its proposed parent without checking the returned prompt. A first call with prompt[1], generation[2], followed by a child with prompt[99], generation[3], is emitted as one trainable chain. That violates the module's stated contract. This is reachable through the shipped model adapter: vllm_model supplies required prefixes from an active capture context, not merely from the assistant token fields this proxy attaches. The tracked route currently loses that context. Finalization trusts responses already carrying token IDs, so it won't repair this sequence.Could you make prefix supply and generation-time verification part of the tracked contract? Before accepting a child, require its prompt to extend the parent's exact prompt plus generation, and require one log probability per generated token. A mismatch or missing bundle on the retained trajectory must invalidate/mask that training sample; silently skipping the call or publishing a later fragment isn't sufficient. The complete implementation depends on the selected prefix transport, so a local assertion alone isn't a complete patch.
Acceptance — proposed, not executed:
[1]/[2] → [99]/[3]must not produce an unmasked training sequence;[1]/[2] → [1,2,4]/[3]must retain both generations unchanged. A missing intermediate bundle must not produce an unmasked partial rollout. Preserve the existing two-turn crop/image ordering, echoed-reasoning handling, and top-k output assertions. -
responses_api_agents/opencode_agent/token_tracking.pyline 160: BLOCKER — Select the terminal OpenCode retained, not the deepest branch.main_chain()chooses solely by depth and latest index. Record a three-call tool chain, then a later root containing the final answer after history compaction: this chooses the old tool chain and drops the actual answer. A deepertaskchild session can likewise replace the root session's final answer. The existing artifact parser represents both compaction and child sessions, so these paths aren't equivalent to disposable title calls. The replacement output also goes to verification, silently changing the reward as well as the training trajectory.Could you use the persisted root-session terminal and model-call/session attribution to select its ancestry? If that ancestry crosses an uncaptured or compacted boundary the tracker can't represent, retain the real response for grading and mark its training representation unusable. Don't substitute a different branch. This requires identity plumbing rather than a safe one-line change.
Acceptance — proposed, not executed: a depth-two abandoned chain followed by a compacted root containing
\\boxed{7}must grade that root answer, then either train supported ancestry or mask it. A deeper child-session chain must never replace a shorter root-session final answer. Preserve the existing unrelated-title exclusion case, tool-produced images, and top-k values on the selected ancestry. -
responses_api_agents/opencode_agent/app.pyline 954: BLOCKER — Keep timeout grading separate from retained training tokens. A timed-out run first receives empty output at lines 946–949, but tracking immediately replaces it with captured calls. If a captured call contains a correct boxed answer and OpenCode subsequently times out, local/runsends that text to verification. The visual-coding verifier grades nonempty assistant text, and the timeout exists only in observations—not the grading response. The task can therefore score 1 despite the documented zero-reward timeout policy.Could you carry the timeout result separately through
_run_opencode()and_create_episode()intorun(), send an empty grading response for that timeout, and retain the original token-bearing response in the returned rollout? Don't discard the sampled tokens merely to obtain zero reward, or blanket-zero every incomplete/failed response. The correction is specifically the existing timeout policy. The shared verification helper illustrates separating grading and retained responses, but its execution-failure label shouldn't be copied blindly for timeouts.Acceptance — proposed, not executed: simulate a tracked correct
\\boxed{7}call followed by timeout. The verifier must see empty grading output, reward must be 0, and the returned response must retain that call's token IDs/logprobs. Normal completion with the same answer must remain gradable for reward 1. Preserve untracked timeout scoring and per-request budget behavior. -
responses_api_agents/opencode_agent/app.pyline 777: RISK — Preserve rollout and model-call attribution through the tracked proxy. Enablingtrack_token_idsreplaces the resolved model URL with/ng-tok/<key>/v1, then forwards here to plain/v1/chat/completions. This separate inbound request doesn't inherit/run's rollout context, and no run-key mapping restores it. ServerClient adds attribution only with a current rollout; capture derives its identity and training selection from the URL prefix. The new route consequently bypasses configured model-call observability and training capture. It also forwards cookies but drops OpenCode's session/assistant correlation headers.Could you retain each run key's rollout identity and resolved model endpoint, forward through the appropriate evaluation/training prefix, and preserve the supported correlation headers? Keep
X-Session-Idand the configured assistant-message header. If inline tracking can't coexist with external staging, reject that combination explicitly rather than silently bypassing it. Preserve untracked routing, cookies, and isolation between run keys.Acceptance — proposed, not executed: send two tracked runs through the agent/model ASGI apps with capture enabled. Each exchange must appear under its own rollout and session/assistant IDs; selected training capture must receive those calls. Retain the untracked routing case and test the chosen external-staging coexistence or explicit-rejection behavior.
-
nemo_gym/models/token_capture/external_capture.pyline 100: RISK — Strip the newly recognized top-k fields on external capture. This PR addsgeneration_topk_token_idsandgeneration_topk_log_probsto the atomic metadata contract, but this unchanged scrubber removes only the old token fields and sampler aliases. For a staged worker response containing the new pair and its normal token bundle, it removes the three required fields but leaves the pair. SubsequentNeMoGymChatCompletionvalidation now rejects the response as partial token metadata. Before this PR, those names didn't trigger the atomic validator.Could you add these entries to this scrubber's tuple?
"generation_topk_token_ids", "generation_topk_log_probs",
Keep
prepare_response()'s no-context early return unchanged. External staging must remove transport arrays before the agent hop; ordinary non-staged responses must retain the new fields as intended. Preserve legacy sampler aliases, routed-expert stripping, andcompact_prompt_token_ids. Please verify the suggested addition before adopting it.Acceptance — proposed, not executed: extend the existing handler payload with both new fields; correlated staged prepare/finalize must strip them, commit normally, and leave a payload accepted by
NeMoGymChatCompletion. Extendtest_handlers_leave_uncorrelated_traffic_untouchedto assert that both new fields survive there. Retain the tracked-output top-k assertions. -
responses_api_agents/opencode_agent/token_tracking.pyline 82: RISK — Preserve literal think tags in answer text._THINK_RE.sub()removes every `` span, not just Gym's leading reasoning wrapper. A completionThe literal isbecomes `The literal is`, changing both the answer sent to verification and parent matching. The existing OpenCode regression cases explicitly retain interior tags and split only a block beginning the reply.Could you import the neighboring
observability.split_gym_reasoninghelper and replace_visible_text()'s body with:return split_gym_reasoning(_text(content))[1].strip()
Remove
_THINK_REandreif unused. The inspected helper doesn't introduce an import cycle. This gives output projection and parent matching the same established semantics. Please verify the replacement before adopting it.Acceptance — proposed, not executed: retain
The literal is; emitanswerforanswer; emit an empty assistant answer for ``; retain<think>unclosedliterally. Keep the existing token-prefix, top-k, and echoed-reasoning assertions. -
responses_api_agents/opencode_agent/app.pyline 1161: RISK — Preserve fractional task budgets in the sandbox watchdog. The timeout resolver accepts positive fractional budgets, and existing local coverage retains12.5. Here,int(timeout)truncates them. Valid metadataagent_timeout_sec="0.5"generatestimeout -k 10 0 ..., disabling the inner watchdog and allowing execution until the much larger provider limit (timeout + 120).Could you replace
{int(timeout)}in this command with{timeout:g}? This preserves the numeric duration instead of turning a positive budget into zero. Integer budgets keep their existing command form. Please verify the suggestion before adopting it.Acceptance — proposed, not executed: a
0.5budget must generatetimeout -k 10 0.5, and a longer-running command must stop as a task timeout rather than consume the provider backstop. Retain12.5, the default 1800-second duration, invalid-metadata fallback, above-ceiling capping, and the existing124/137handling. -
responses_api_agents/opencode_agent/app.pyline 1142: RISK — Transport generated project inputs whenrepo_dirdiffers from the workspace._run_opencode()writesopencode.jsonand attachedimage_<i>.*files intoproject_dir, which becomes the persistent repository whenrepo_diris configured. This uploader collects onlywork_dir, then merely creates the project directory in the sandbox. With an externalrepo_dir, a model-server binding, and an image, the sandbox receives neither the generated model/provider config nor the file referenced by-f. The remote-node collector has the same boundary, so a node-local repository also misses the newly generated files.Could you explicitly stage the required project/config/attachment inputs, or reject unsupported remote/sandbox
repo_dircombinations before launch? The right implementation depends on the intended persistent-repository contract; the invariant is that every referenced input and generated configuration reaches the execution host.Acceptance — proposed, not executed: use distinct workspace/repository directories with a generated provider config and one image. A supported sandbox/remote run must see both at the referenced paths; otherwise configuration must fail explicitly before execution. Preserve
TestRepoDir's local repository survival and request-specific replacement-prompt assertions, plus ordinary transport whenproject_dir == work_dir. -
responses_api_agents/opencode_agent/app.pyline 881: RISK — Don't install an unused host runtime for sandbox-only execution. Every call awaits_ensure_local_runtime()before reaching the newsession_sandboxbranch, although that branch executessandbox_config.commandinside the sandbox. A valid preinstalled sandbox image therefore fails before creation when the agent host lacks OpenCode and can't install it. The host copy is never used by this branch.Could you restrict this call to host execution paths?
if self.config.session_sandbox is None: await self._ensure_local_runtime()
The sandbox image or its setup command then owns its runtime. Ordinary local calls and the current remote-node path still receive host setup. Please verify the suggestion before adopting it.
Acceptance — proposed, not executed: configure a preinstalled sandbox command, make
_ensure_local_runtime()fail if called, and verify that sandbox execution proceeds. Preserve local first-call installation, shared concurrent installation, failed-install retry, and the existing remote-node setup behavior. -
resources_servers/visual_coding_opencode/app.pyline 97: RISK — Add the resources server's task-data schema and share it with runtime parsing. The new resources server has notask_data.py. The existing schema-presence gate will listvisual_coding_opencodeas missing, and data preparation skips validation when the schema is absent. Thus malformed rows can pass preparation and fail only at runtime; the committed-row drift gate also has no loadable schema for the example dataset.Could you add a dependency-light
resources_servers/visual_coding_opencode/task_data.pyexportingTaskData, then inherit it here instead of duplicating its runtime fields? The inspected row contract can be represented as:class TaskData(BaseModel): model_config = ConfigDict(extra="allow") expected_answer: str question: str = "" source_id: str | None = None category: str | None = None l2_category: str | None = None ans_type: str | None = None
Import
BaseModel/ConfigDictfrom Pydantic in that module, add the required SPDX header, and replace this request declaration withclass VisualCodingOpenCodeVerifyRequest(BaseVerifyRequest, TaskData): pass. Please verify the suggested shared-model arrangement before adopting it.Acceptance — proposed, not executed: the schema-presence and committed-row gates must accept this server and all three example rows. Validate rows from both prepare variants; a missing
expected_answermust fail before dispatch, omittedquestionmust retain its empty default, provenance fields must survive, and the existing permissive unknown-field policy must remain consistent between schema and request. Add drift coverage proving these shared requirements can't diverge. -
responses_api_agents/opencode_agent/app.pyline 89: RISK — Use the model package's public exports so the import gate passes. This new import takessynthesize_chat_completion_ssefrom its implementation module even though the package exports it. The existing outside-library import gate scans server imports and reports this exact dependency. This is a source-identified CI failure, not a formatting preference.Could you add
sanitize_streaming_chat_bodyto theTYPE_CHECKINGimports and_PUBLIC_APIinnemo_gym.models, then replace this line with:from nemo_gym.models import sanitize_streaming_chat_body, synthesize_chat_completion_sse
Preserve lazy loading and both function identities; their implementations needn't move. Please verify the import and dependent facade changes before adopting them.
Acceptance — static checks, not executed: the outside-library import gate must stop reporting this file, the facade declaration-consistency test must include the sanitizer export, and importing either function through
nemo_gym.modelsmust return itschat_streamingimplementation object. Retain the sanitizer's no-mutation and assistant-reasoning regression assertions.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
…ts-detector false positive The secrets detector flags the two BabyVision.tsv md5 checksums in prepare.py as hex high-entropy strings. They are public file checksums; mark the line with the repo's inline allowlist pragma. Signed-off-by: Danial MohseniTaheri <[email protected]>
Add resources_servers/visual_coding_opencode/task_data.py exporting TaskData (expected_answer required, question default "", provenance fields source_id, category, l2_category, ans_type; extra=allow) and make VisualCodingOpenCodeVerifyRequest inherit it, so data preparation validates rows against the same contract the server reads and the schema-presence and committed-row checks cover this server. Signed-off-by: Danial MohseniTaheri <[email protected]>
…r scoring outages Two review blockers on session_sandbox: - The run's database list came from any "@@ng-opencode@@db=<path>" line in the combined output, including the model-writable stderr tail, and each path was downloaded to the same path on the agent host. A sandboxed task could name a writable host file and have it overwritten. Marker lines now carry a per-run nonce and are printed before the stderr tail, and a database path must be OpenCode's own database file (opencode.db or a SQLite sidecar) in the run's data directory; it is written to the matching local path. Anything else is a provider protocol failure. - A failed create, setup, upload, run or download returned an empty run, which was graded as a zero-reward answer. These now raise a typed sandbox failure (provider_request_failed, provider_setup_failed, provider_protocol_error, or provider_command_outcome_unknown when the exec reports an error type, a nonzero exec status or no exit-code marker), so the episode fails instead of scoring. A confirmed task timeout (124/137) keeps the timeout policy. Also pass fractional task budgets to timeout(1) as given ({timeout:g}); int() turned 0.5 s into 0, which disabled the inner watchdog. Signed-off-by: Danial MohseniTaheri <[email protected]>
… sandboxes; add visual-coding guide Remaining review items on NVIDIA-NeMo#5712: - repo_dir with session_sandbox or session_nodes > 1: _run_opencode writes the generated opencode.json and attached images into repo_dir, but sandbox and remote sessions copy only the run directory, so OpenCode started without them. The agent now rejects the combination at startup. - session_sandbox runs no longer install OpenCode on the agent host before dispatching; the sandbox image or setup_command provides it. Local and remote-node sessions still install it. - Add an evaluation tutorial, "Evaluate Visual Coding with OpenCode", covering both BabyVision variants, TSV staging, image-capable serving, judge credentials, host execution permissions, the user-namespace requirement, and local versus session_sandbox runs. Link it from the evaluation tutorials index (the docs link test's pinned count goes from 15 to 16). Signed-off-by: Danial MohseniTaheri <[email protected]>
|
Thanks for the review. Status of the findings on head 3d7e6ff: Blockers Sandbox output as a host download destination: fixed in deb6267. Marker lines carry a per-run nonce and come before the model-writable stderr tail. A database path must be OpenCode's own database file (opencode.db or a SQLite sidecar) in the run's data directory, and it is written to the matching local path. Anything else is a provider_protocol_error. Tests cover a forged marker in stderr and nonce-carrying paths outside the directory; the host sentinel stays unchanged. Proxy attribution, literal tags, top-k scrubbing on external capture: removed with track_token_ids and its top-k fields. Documentation page: added in 3d7e6ff, "Evaluate Visual Coding with OpenCode" under evaluation tutorials, linked from the tutorials index. It covers both BabyVision variants, TSV staging, image-capable serving, judge credentials, host execution permissions, the user-namespace requirement, and local versus session_sandbox runs. |
…n benchmarks on OpenCode sandbox sessions
A multi-turn visual-coding environment: OpenCode answers a question about an image in a sandbox whose shell has
Python with pillow, numpy, scipy and opencv, and a GPT judge grades the final \boxed{} answer against the gold
answer. BabyVision (388 visual-reasoning puzzles) and its question-only variant run on it.
- `resources_servers/visual_coding_opencode`: the judge (`equivalent` scores 1; a failed call or a reply without a
valid verdict is masked as `judge_failed`, not scored 0), the task-data schema, and a typed seed and close that
lend each episode a sandbox through `LentSandboxes` with `sandbox_network_access: model_only`, so the sandbox
reaches only the policy model. A sandbox image (`sandbox_image/Dockerfile`) carries the toolkit and OpenCode
1.17.11, pinned by its SHA-256.
- The environment config runs each task with `opencode_agent` in a sandbox session behind the
`single_agent_turn_legacy` Environment Server. The prompt image is attached with `opencode run --file`.
Compaction is off and there is no step limit, so Gym's token capture joins every model call and the same config
serves evaluation and RL.
- `benchmarks/babyvision_opencode` and `benchmarks/babyvision_opencode_question_only`: prepare scripts for
VLMEvalKit's BabyVision TSV (checked by md5), configs and manifests.
- The "Evaluate Visual Coding with OpenCode" tutorial and its index entry.
- Tests: the judge, the lent sandbox and the session contract, the BabyVision configs, the prepare scripts, and the
example rows run through a seeded `opencode_agent` session.
Based on #5712 by Danial MohseniTaheri, moved from a host-CLI agent path onto sandbox sessions.
Co-authored-by: Danial MohseniTaheri <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
|
/ok to test 3d7e6ff |
|
/review |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP — no unresolved findings remain from the previous bot review.
I verified the fixes against the current source and inspected the relevant regression assertions:
- Sandbox execution constrains database downloads, rejects unconfirmed execution, propagates provider failures instead of grading empty responses, and preserves fractional task budgets and confirmed task-timeout handling.
- The agent-side tracker and its output replacement are gone, closing the reported prefix, branch-selection, timeout-grading, attribution and literal-tag failures. Model calls use the shared URL resolver. The added top-k metadata and offending streaming-helper import were also removed.
- The startup guard rejects unsupported off-host
repo_dircombinations. The runtime guard skips host installation for session sandboxes while retaining it for local and remote-node execution. - The resources server now exports TaskData, and the runtime verify request inherits it.
- The new tutorial covers the requested setup and execution distinctions and is linked from the tutorial index.
This completes the scoped follow-up to review 5810329934, not a fresh whole-PR review. The previously reviewed tree wasn't available, so I couldn't independently compare the full inter-review delta. This was static inspection; I didn't execute tests or render the documentation.
Review generated by codex. This was a findings-only review. Request a full review with /review reset=true.
|
/review reset=true |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
HOLD — 1 BLOCKER, 10 RISK findings, and 1 NOTE.
The blocker is an unbounded wait after a remote session times out. The risks concern image isolation, Ray and worker startup, sandbox configuration and cleanup, benchmark task identity, and malformed judge replies. Each inline finding includes a repair boundary and proposed acceptance checks.
I completed a fresh review of all 41 changed files and traced their affected runtime, scoring, data, capture, and startup contracts. The previously reported sandbox download, swallowed provider-failure, fractional-timeout, off-host repo_dir, and host-installation counterexamples are fixed in the current source; the removed token tracker isn't an unresolved finding.
This was static inspection. I didn't execute tests, install dependencies, or render the documentation. I inspected both added lockfiles' manifests and relevant dependency/source records, not every distribution hash. The PR's reported smoke rollouts provide useful evidence, but they don't cover the failure cases below.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| except subprocess.TimeoutExpired: | ||
| timed_out = True | ||
| os.killpg(proc.pid, signal.SIGKILL) | ||
| _, stderr = proc.communicate() |
There was a problem hiding this comment.
BLOCKER — Bound cleanup after a remote session times out. On a Linux host with setsid, a minimal session command is sh -c 'setsid sleep 1000 & wait'. The sleep moves to another process group and inherits the piped stderr. At the task deadline, run_session() kills only the launcher's group, then calls proc.communicate() without another deadline. That call waits for the surviving child's pipe to close, so the Ray task and its awaiting agent request can remain blocked far beyond the configured budget. The existing supervisor explicitly handles live descendants in other groups; this new path doesn't.
Could you change run_session() to terminate the reached session descendants before draining stderr and bound that drain? Track process identities before killing the launcher, or integrate the existing supervision mechanism, so cleanup cannot signal unrelated or reused PIDs. If termination remains unconfirmed after the cleanup bound, fail the execution instead of waiting indefinitely or returning a gradable result. I haven't established a drop-in supervisor integration, so I haven't supplied replacement code.
Preserve: successful sessions must still return the database and SQLite sidecars before removing their workspace. Confirmed task timeouts must retain timed_out=True and the benchmark's timeout policy.
Acceptance — proposed, not executed: run the command above with a short timeout; the worker must finish within the task-plus-cleanup bound, with both processes stopped. Retain the existing remote-session tests' database-content, workspace-removal, and timeout assertions. Add a cleanup case with a live child in a separate process group.
| cmd = [*self.config.command_parts, "run", "-m", self._effective_model(), "--dir", str(project_dir)] | ||
| files = [] | ||
| for index, (suffix, data) in enumerate(images or []): | ||
| path = project_dir / f"image_{index}{suffix}" |
There was a problem hiding this comment.
RISK — Isolate attached images when local requests share repo_dir. With attach_images=True and a configured repository, every invocation writes image_0.png to the same directory. Two overlapping requests with different PNGs can overwrite each other's attachment before OpenCode reads it, causing one task to answer another task's image. A sequential request also overwrites a pre-existing repository file with that name. Per-run XDG state doesn't isolate these new inputs.
Could you create an invocation-specific image directory inside the persistent repository? At this loop, the staging change can be:
image_dir = project_dir
if images and self.config.repo_dir:
image_dir = Path(tempfile.mkdtemp(prefix=".ng-images-", dir=project_dir))
for index, (suffix, data) in enumerate(images or []):
path = image_dir / f"image_{index}{suffix}"
path.write_bytes(data)
files.append(str(path.resolve()))Move image staging inside the existing cleanup try/finally, and add shutil.rmtree(image_dir, ignore_errors=True) to that finally only when image_dir != project_dir. Keep the directory inside the repository so reads don't become external-directory accesses. Please verify the suggestion before adopting it.
Preserve: fresh-workspace runs retain ordered image_<i> attachments; attach_images=False creates no image directory; the repository and its existing files remain intact. Keep the off-host repo_dir rejection.
Acceptance — proposed, not executed: launch two requests against one repository with distinct image bytes, delaying file reads until both launch. Each attachment must have a distinct path and retain its own bytes. A pre-existing image_0.png sentinel must remain unchanged. Retain the default-workspace test's image-content and prompt-before--f assertions.
| """Run one OpenCode session on a session node; copy its session database back here.""" | ||
| from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy | ||
|
|
||
| nodes = self._session_node_ids() |
There was a problem hiding this comment.
RISK — Join Ray before using the new session_nodes path. Setting session_nodes > 1 through the normal Gym launcher doesn't initialize Ray in this agent. OpenCodeAgent inherits ray_enabled=False, so server startup skips its connection. The supervisor also sets RAY_ENABLE_AUTO_CONNECT=0 for this undeclared server. _session_node_ids() then accesses the Ray runtime without any explicit initialization. Installing the optional Ray package alone doesn't make the advertised multi-node path work.
Could you explicitly join the configured Ray cluster before this opt-in path calls _session_node_ids(), using the shared initialization contract, or provide an opt-in Ray entrypoint recognized by startup discovery? Keep the dependency and initialization conditional: simply setting ray_enabled=True on the ordinary agent would make default local and session-sandbox runs require Ray despite these options defaulting off. The startup-wiring choice needs verification, so I haven't supplied an unconditional flag patch.
Preserve: local and session-sandbox runs must remain usable without Ray. Multi-node runs must use the configured cluster and preserve node exclusion and round-robin placement.
Acceptance — proposed, not executed: launch through RunHelper with Ray installed, a configured two-node cluster, and session_nodes=2; execute sessions on the selected nodes without an uninitialized-runtime failure or a private replacement cluster. Retain the node-order and exclusion assertions. Check that default local and sandbox configurations still start in a dependency environment without Ray.
| if len(provider_config) != 1: | ||
| raise ValueError("session_sandbox.provider must contain exactly one provider name") | ||
| provider_kwargs = next(iter(provider_config.values())) | ||
| connection = provider_kwargs.setdefault("connection", {}) |
There was a problem hiding this comment.
RISK — Don't add an OpenSandbox constructor argument to every provider. For session_sandbox.provider: {docker: {}}, this function changes the mapping to {"docker": {"connection": {}}} even when no secret injection is requested. The registry forwards those keys to the constructor, but DockerProvider accepts no connection argument. The same is true of LocalProvider. These sessions fail before creation.
Could you replace the unconditional connection setup and secret loop with:
provider_name, provider_kwargs = next(iter(provider_config.items()))
if provider_kwargs is None:
provider_kwargs = provider_config[provider_name] = {}
if sandbox_config.provider_secret_env:
connection = provider_kwargs.setdefault("connection", {})
for field_name, env_name in sandbox_config.provider_secret_env.items():
value = os.environ.get(env_name)
if not value:
raise RuntimeError(f"session_sandbox: environment variable {env_name} is not set")
connection[field_name] = valueThis preserves provider-specific constructor mappings when injection is unused and normalizes null consistently with the registry. Please verify it before adoption.
Preserve: retain copied-config behavior, OpenSandbox secret injection, and the missing-secret error.
Acceptance — proposed, not executed: register a fake provider with a no-argument constructor and construct it from both {fake: {}} and {fake: null}; neither may receive connection. Retain the existing secret tests, including the assertion that injection doesn't mutate the original config.
| sandbox_config = self.config.session_sandbox | ||
| provider = self._session_sandbox_provider() | ||
| spec = SandboxSpec(**{"ttl_s": int(timeout) + sandbox_config.setup_timeout + 600, **sandbox_config.spec}) | ||
| sandbox_env = {**_SANDBOX_DEFAULT_ENV, **{key: env[key] for key in _SANDBOX_SESSION_ENV_KEYS if env.get(key)}} |
There was a problem hiding this comment.
RISK — Reject model URLs that a session sandbox cannot reach. An ordinary benchmark run with session_sandbox and no address override generates a policy URL on 127.0.0.1, because global configuration defaults to loopback. This path uploads that URL in opencode.json and forwards it in the environment. Inside a remote OpenSandbox container, loopback names the container, not Gym's policy server. There is no configuration rejection before launch; a confirmed CLI exit without an answer can subsequently reach ordinary empty-answer grading.
Could you apply the existing model-URL reachability guard before creating the sandbox, and add the reachable-address requirement to the sandbox tutorial? Validate the actual generated provider URL when model_server is set; an environment override mustn't hide an unreachable URL still embedded in the config. Document a scoped reachable model-server address rather than exposing unrelated services unnecessarily.
Preserve: keep non-loopback endpoints unchanged, accept the host-network local case, and retain the shared guard's warning-only Docker behavior. Don't change ordinary local execution.
Acceptance — proposed, not executed: an OpenSandbox session with a generated loopback policy URL must fail before provider.create and verification. A reachable non-loopback URL must run unchanged. Retain the helper's accepted local-provider and warning-only Docker cases.
| f'do [ -f "$f" ] && echo "{mark}db=$f"; done; ' | ||
| f"echo {mark}end; tail -c 4000 {shlex.quote(stderr_path)}; exit 0" | ||
| ) | ||
| result = await provider.exec(handle, script, env=sandbox_env, timeout_s=timeout + 120) |
There was a problem hiding this comment.
RISK — Honor the execution user declared in SandboxSpec. The new spec accepts user, but both direct provider.exec() calls omit it. This is observable with Docker: creation deliberately doesn't apply spec.user, because the sandbox facade applies it per exec. The OpenSandbox creation path likewise doesn't apply this field. Bypassing the facade runs commands under the provider/image default instead of the configured identity. For a root-default image, an operator's non-root setting is silently ignored.
Could you use the facade or pass user=spec.user on both preparation and run execs?
prepared = await provider.exec(
handle, prepare, timeout_s=sandbox_config.setup_timeout, user=spec.user
)
# At the run exec:
result = await provider.exec(
handle, script, env=sandbox_env, timeout_s=timeout + 120, user=spec.user
)Please verify the suggestion before adoption. A requested identity that cannot execute must fail explicitly, not fall back to root.
Preserve: user=None must retain the image/provider default, and setup failures must still propagate before grading. This is separate from the provider-constructor failure above: fixing construction alone would leave the identity ignored.
Acceptance — proposed, not executed: use a root-default Docker image, configure UID 1000, and provide a workspace writable by that UID. Both setup and harness id -u must return 1000, and writing a root-only sentinel must fail. With no user configured, retain the image's default identity. Assert that both exec calls receive the requested user.
| }, | ||
| "expected_answer": row["answer"], | ||
| "question": question, | ||
| "source_id": row["index"], |
There was a problem hiding this comment.
RISK — Export the BabyVision index as a recognized task ID. Both preparers emit only source_id. With a valid staged TSV, gym eval plan --benchmark babyvision_opencode --out plan.json prepares the data and then rejects all 388 rows: the planner recognizes only task_id, problem_id, or instance_id. The question-only benchmark calls the same converter. The public Python planning API and stable-ID selection therefore cannot use either new benchmark, despite the TSV supplying stable IDs.
Could you add "task_id": str(row["index"]) beside source_id in convert() and declare an optional string task_id provenance field in the owning TaskData schema? The schema change is required because strict collation reports undeclared fields. Retain source_id, and keep task_id optional so existing example/training rows remain valid. Please verify this correction before adoption.
Acceptance — proposed, not executed: extend the two-row preparation fixture to assert task_id == source_id == "0"/"1" for both variants. Pass those rows to build_eval_plan() and assert stable IDs after reversing row order and selection of only "1". TaskDataValidator must report the rows clean. Preserve image ordering, PNG/JPEG handling, gold-answer separation, prompt differences, and validity of committed examples without task_id.
| json=params, | ||
| response_model=NeMoGymChatCompletion, | ||
| ) | ||
| return parse_verdict(completion.choices[0].message.content or "") |
There was a problem hiding this comment.
RISK — Handle a judge completion with no choices. A reply such as {"id":"c","created":0,"model":"gpt","object":"chat.completion","choices":[]} passes the completion schema. call_judge() returns it, but this indexing raises IndexError outside the judge-call failure boundary. Any nonempty policy answer then gets a /verify 500 rather than the documented unsure fallback for a received reply with no valid verdict. This is a reproducible response-shape edge case, not evidence of an upstream incident.
The smallest correction here is:
content = completion.choices[0].message.content if completion.choices else ""
return parse_verdict(content or "")Please verify it before adoption. The invariant is that a received completion without a verdict reaches parse_verdict()'s fallback; transport failures must retain the shared retry/failure policy.
Acceptance — proposed, not executed: return the minimal empty-choices completion from the judge mock, call verify() with \\boxed{(4,7)}, and assert reward == 0.0, judge_verdict == "unsure", and no exception. Preserve the existing tests for ordinary verdicts, unboxed answers, and an empty policy response that makes no judge call. Don't replace this guard with a blanket exception-to-zero handler.
| from responses_api_agents.opencode_agent.app import OpenCodeAgent | ||
|
|
||
|
|
||
| if __name__ == "__main__": |
There was a problem hiding this comment.
RISK — Export the app when Uvicorn imports either new entrypoint. With num_workers=2, run_webserver() starts workers by importing the configured component's app attribute. This new wrapper calls run_webserver() only under __main__, so worker imports never create that attribute. The new resources-server entrypoint has the same omission. Either component fails to serve when configured with multiple workers.
Could you add the existing worker-entrypoint guard to both files? For this wrapper:
from nemo_gym.utils import is_nemo_gym_fastapi_entrypoint
if __name__ == "__main__":
OpenCodeAgent.run_webserver()
elif is_nemo_gym_fastapi_entrypoint(__file__):
app = OpenCodeAgent.run_webserver()Apply the same pattern using VisualCodingOpenCodeServer in its entrypoint. This matches the underlying agent's current contract. Please verify the code before adoption.
Preserve: ordinary imports must not start a server, and single-worker script execution must still start once.
Acceptance — proposed, not executed: start each new component with num_workers=2 and confirm its workers expose /readyz and the intended API routes. Add an entrypoint test using the worker markers to assert a module-level FastAPI app; without those markers, importing the module must remain side-effect-free.
| `visual_coding_opencode_judge_model_name`, with the key in `OPENAI_API_KEY`). The judge sees the question text, the gold answer, string_match's extraction | ||
| (the last "answer:", else the last `\boxed{}`), and the last 4000 characters of the model's | ||
| text. It cannot see the image. Only `"equivalent"` scores 1; `"different"`, `"unsure"`, a judge | ||
| error and an empty response score 0. `string_match_reward` is kept as a diagnostic. |
There was a problem hiding this comment.
NOTE — Distinguish judge outages from scored zeroes. The statement that a judge error scores zero doesn't match the current HTTP path. A judge HTTP 401 or exhausted 503 retries makes call_judge() raise NgFailureEvent, not JudgeError. The verifier doesn't catch that event; the inherited route wrapper sends it through judge_failsafe(), producing a masked judge_failed row excluded from accuracy. That distinction changes how users interpret the denominator.
Could you replace the zero-on-error statement with: “Received invalid or unsure verdicts and empty policy answers score zero. Failed judge calls use the shared retry policy, then enter the failures sidecar and are excluded from accuracy until recovered.” Update the application docstring to agree. Keep the shared failure behavior rather than broadening the catch to turn outages into scored samples. The current test_judge_error_scores_zero mocks an exception the normal call path doesn't emit; supplement or replace it with a typed-failure test through the HTTP route.
Acceptance — proposed, not executed: persistent 503 replies must exhaust the shared three attempts and return mask_sample=true, failure_kind="judge_failed", and _ng_failure_class="judge_failed", preserving the policy response. Successful different and unsure verdicts must remain ordinary unmasked zeroes. Inspect the README and docstring for that distinction.
…xes; fix review findings Second full review of NVIDIA-NeMo#5712 (1 blocker, 10 risks, 1 note): - session_nodes: each node runs OpenCode under Gym's process supervisor with stderr in a file, so a child that leaves OpenCode's process group cannot hold the Ray task open. The wait is bounded, and a missing or negative cleanup receipt raises harness_termination_unconfirmed instead of grading. - session_nodes: join the run's configured Ray cluster (ray_head_node_address) before the first remote session; fail clearly without one instead of starting a private cluster. opencode_agent is listed in the Ray inventory as using Ray only on this opt-in path, so local and sandbox runs need no Ray. - session_sandbox: pass provider configs unchanged unless provider_secret_env is set (docker and local take no `connection`); reject a loopback model URL on a remote provider before creating a sandbox; run setup and OpenCode as spec.user; stage the correlation plugin in the run directory when observability is on; close each sandbox in an agent-owned task that a cancelled request cannot abandon, keep failed closes for a shutdown retry, and close a sandbox whose create finishes after cancellation. - attach_images with repo_dir: each run stages its images in its own directory inside the repository and removes it afterwards. - BabyVision rows carry task_id (the TSV index), declared in TaskData, so `gym eval plan` and task selection accept them. - visual_coding_opencode: a judge reply without choices is "unsure"; failed judge calls go through the shared judge failsafe (masked, out of accuracy) instead of a dead JudgeError branch; README and docstring say so. - opencode_vision_agent and visual_coding_opencode export `app` for Uvicorn workers (num_workers > 1). - Docs: the sandbox tutorial requires a model address the sandbox can reach (++use_absolute_ip=true) and shows spec.user. Signed-off-by: Danial MohseniTaheri <[email protected]>
|
/ok to test b1c92cc |
|
Thanks for the full review. Status of its findings on head b1c92cc: Blocker Bound cleanup after a remote session times out: fixed. Each session node now runs OpenCode under Gym's process supervisor (process_supervisor.sh, passed to the Ray task by value) with stderr written to a file instead of a pipe, so an escaped child cannot hold the task open. The supervisor stops OpenCode with every process it reached at the deadline, including ones in other process groups or sessions; the Python wait on the supervisor is bounded by exec_timeout. A missing, malformed or negative cleanup receipt raises harness_termination_unconfirmed instead of returning a gradable result. Successful runs still return the database and sidecars before the workspace is removed; confirmed timeouts keep timed_out=True. New test: sh -c 'setsid sleep 1000 & wait' with a 1 s budget finishes within the task-plus-cleanup bound, and the child is gone. Images with a shared repo_dir: fixed as suggested: per-run .ng-images-* directory inside the repository, staged inside the cleanup try/finally and removed afterwards. Test: two overlapping runs with different PNGs each read their own bytes, and a pre-existing image_0.png is untouched. Judge outages: README, docstring and tutorial now say failed judge calls go to the failures sidecar. The dead JudgeError branch is gone, and test_judge_error_scores_zero is replaced by a /verify route test: three 503s give a masked judge_failed row with the response preserved. |
…n benchmarks on OpenCode sandbox sessions
A multi-turn visual-coding environment: OpenCode answers a question about an image in a sandbox whose shell has
Python with pillow, numpy, scipy and opencv, and a GPT judge grades the final \boxed{} answer against the gold
answer. BabyVision (388 visual-reasoning puzzles) and its question-only variant run on it.
- `resources_servers/visual_coding_opencode`: the judge (`equivalent` scores 1; a failed call or a reply without a
valid verdict is masked as `judge_failed`, not scored 0), the task-data schema, and a typed seed and close that
lend each episode a sandbox through `LentSandboxes` with `sandbox_network_access: model_only`, so the sandbox
reaches only the policy model. A sandbox image (`sandbox_image/Dockerfile`) carries the toolkit and OpenCode
1.17.11, pinned by its SHA-256.
- The environment config runs each task with `opencode_agent` in a sandbox session behind the
`single_agent_turn_legacy` Environment Server. The prompt image is attached with `opencode run --file`.
Compaction is off and there is no step limit, so Gym's token capture joins every model call and the same config
serves evaluation and RL.
- `benchmarks/babyvision_opencode` and `benchmarks/babyvision_opencode_question_only`: prepare scripts for
VLMEvalKit's BabyVision TSV (checked by md5), configs and manifests.
- The "Evaluate Visual Coding with OpenCode" tutorial and its index entry.
- Tests: the judge, the lent sandbox and the session contract, the BabyVision configs, the prepare scripts, and the
example rows run through a seeded `opencode_agent` session.
Based on #5712 by Danial MohseniTaheri, moved from a host-CLI agent path onto sandbox sessions.
Co-authored-by: Danial MohseniTaheri <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
…n benchmarks on OpenCode sandbox sessions
A multi-turn visual-coding environment: OpenCode answers a question about an image in a sandbox whose shell has
Python with pillow, numpy, scipy and opencv, and a GPT judge grades the final \boxed{} answer against the gold
answer. BabyVision (388 visual-reasoning puzzles) and its question-only variant run on it.
- `resources_servers/visual_coding_opencode`: the judge (`equivalent` scores 1; a failed call or a reply without a
valid verdict is masked as `judge_failed`, not scored 0), the task-data schema, and a typed seed and close that
lend each episode a sandbox through `LentSandboxes` with `sandbox_network_access: model_only`, so the sandbox
reaches only the policy model. A sandbox image (`sandbox_image/Dockerfile`) carries the toolkit and OpenCode
1.17.11, pinned by its SHA-256.
- The environment config runs each task with `opencode_agent` in a sandbox session behind the
`single_agent_turn_legacy` Environment Server. The prompt image is attached with `opencode run --file`.
Compaction is off and there is no step limit, so Gym's token capture joins every model call and the same config
serves evaluation and RL.
- `benchmarks/babyvision_opencode` and `benchmarks/babyvision_opencode_question_only`: prepare scripts for
VLMEvalKit's BabyVision TSV (checked by md5), configs and manifests.
- The "Evaluate Visual Coding with OpenCode" tutorial and its index entry.
- Tests: the judge, the lent sandbox and the session contract, the BabyVision configs, the prepare scripts, and the
example rows run through a seeded `opencode_agent` session.
Based on #5712 by Danial MohseniTaheri, moved from a host-CLI agent path onto sandbox sessions.
Co-authored-by: Danial MohseniTaheri <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
…n benchmarks on OpenCode sandbox sessions
A multi-turn visual-coding environment: OpenCode answers a question about an image in a sandbox whose shell has
Python with pillow, numpy, scipy and opencv, and a GPT judge grades the final \boxed{} answer against the gold
answer. BabyVision (388 visual-reasoning puzzles) and its question-only variant run on it.
- `resources_servers/visual_coding_opencode`: the judge (`equivalent` scores 1; a failed call or a reply without a
valid verdict is masked as `judge_failed`, not scored 0), the task-data schema, and a typed seed and close that
lend each episode a sandbox through `LentSandboxes` with `sandbox_network_access: model_only`, so the sandbox
reaches only the policy model. A sandbox image (`sandbox_image/Dockerfile`) carries the toolkit and OpenCode
1.17.11, pinned by its SHA-256.
- The environment config runs each task with `opencode_agent` in a sandbox session behind the
`single_agent_turn_legacy` Environment Server. The prompt image is attached with `opencode run --file`.
Compaction is off and there is no step limit, so Gym's token capture joins every model call and the same config
serves evaluation and RL.
- `benchmarks/babyvision_opencode` and `benchmarks/babyvision_opencode_question_only`: prepare scripts for
VLMEvalKit's BabyVision TSV (checked by md5), configs and manifests.
- The "Evaluate Visual Coding with OpenCode" tutorial and its index entry.
- Tests: the judge, the lent sandbox and the session contract, the BabyVision configs, the prepare scripts, and the
example rows run through a seeded `opencode_agent` session.
Based on #5712 by Danial MohseniTaheri, moved from a host-CLI agent path onto sandbox sessions.
Co-authored-by: Danial MohseniTaheri <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
…n on OpenCode sandbox sessions (NVIDIA-NeMo#5839) * feat(visual_coding_opencode): visual-coding environment and BabyVision benchmarks on OpenCode sandbox sessions A multi-turn visual-coding environment: OpenCode answers a question about an image in a sandbox whose shell has Python with pillow, numpy, scipy and opencv, and a GPT judge grades the final \boxed{} answer against the gold answer. BabyVision (388 visual-reasoning puzzles) and its question-only variant run on it. - `resources_servers/visual_coding_opencode`: the judge (`equivalent` scores 1; a failed call or a reply without a valid verdict is masked as `judge_failed`, not scored 0), the task-data schema, and a typed seed and close that lend each episode a sandbox through `LentSandboxes` with `sandbox_network_access: model_only`, so the sandbox reaches only the policy model. A sandbox image (`sandbox_image/Dockerfile`) carries the toolkit and OpenCode 1.17.11, pinned by its SHA-256. - The environment config runs each task with `opencode_agent` in a sandbox session behind the `single_agent_turn_legacy` Environment Server. The prompt image is attached with `opencode run --file`. Compaction is off and there is no step limit, so Gym's token capture joins every model call and the same config serves evaluation and RL. - `benchmarks/babyvision_opencode` and `benchmarks/babyvision_opencode_question_only`: prepare scripts for VLMEvalKit's BabyVision TSV (checked by md5), configs and manifests. - The "Evaluate Visual Coding with OpenCode" tutorial and its index entry. - Tests: the judge, the lent sandbox and the session contract, the BabyVision configs, the prepare scripts, and the example rows run through a seeded `opencode_agent` session. Based on NVIDIA-NeMo#5712 by Danial MohseniTaheri, moved from a host-CLI agent path onto sandbox sessions. Co-authored-by: Danial MohseniTaheri <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * feat(visual_coding_opencode): five example rows with metrics and rollouts The server test's data check expects 5 example rows, their metrics and 5 example rollouts. - example.jsonl: three small synthetic puzzles, and BabyVision tasks 4624 (Spatial Perception, Count 3D blocks) and 487 (Visual Pattern Recognition, Logic Patterns) from the UnipatAI/BabyVision dataset on Hugging Face (MIT license), revision 849cbeea2b1d00ad334e9e1e2b49a1960c9ff3f3, in prepare.py's format. The README names the source. - example_metrics.json comes from `gym dataset collate ... +mode=example_validation`. - example_rollouts.jsonl is one rollout of each row: OpenCode in a lent, model-only sandbox, a hosted vision-language policy and a gpt-4o-mini judge. Four rows score 1.0; task 4624 ends incomplete and scores 0. Co-authored-by: Danial MohseniTaheri <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * feat(visual_coding_opencode): declare image input in the OpenCode config The model looks at its crops and plots through OpenCode's read tool, and OpenCode passes those images to the model only when the model declares image input. Since NVIDIA-NeMo#4922, opencode_agent declares it when the prompt has images or image_input is true. The prompt image already declared it; image_input: true keeps it declared for any row, as NVIDIA-NeMo#4922 asks of configs whose tools return images. The session tests now run with the setting. Tests: visual_coding_opencode, BabyVision, docs link and session contract tests: 73 passed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * fix(babyvision_opencode): give rows a task_id, license the manifests MIT, and run the prepare tests in CI - prepare.py writes the TSV index as task_id, which `gym eval plan` needs (it raised ConfigError for every row); TaskData declares it, optional, so the example rows stay valid. - Both manifests say `licensing: MIT`, the license of UnipatAI/BabyVision, so `gym env publish` accepts them. - The prepare tests move to tests/unit_tests/benchmarks/, where the core test suite runs them; no CI job collected benchmarks/babyvision_opencode/tests. A new check covers task_id. - The README says that mean/reward leaves judge failures out, and that scores are not comparable to the BabyVision leaderboard, whose scorer judges only the last \boxed{} with another judge. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * fix(visual_coding_opencode): keep the sandbox off every server but the policy model, and grade only a finished final answer Network and seeds: - The lent sandbox's egress rule opens every port of the policy model's host, and NeMo RL gives every server without its own host that address. The judge, the agent, the resources server and the Environment Server now set host 127.0.0.1, so sandbox code cannot spend the judge's key, run OpenCode on the host, or start sandboxes and episodes. All their callers run on the same host. A config test checks that only the policy model takes NeMo RL's default_host. - While the server lends sandboxes, it refuses a cookie seed (an agent's own /run, which would run OpenCode on its host without the image) and a malformed typed seed with 422; the stateless server refuses only the latter. Grading: - A run whose status is incomplete (a timeout, an output cap or a context limit) scores 0 without a judge call, as the docs promised; an early \boxed{} guess no longer reaches the judge. - `extracted` is the last \boxed{}, the answer the prompt asks for, not string_match's last "answer:". - The verdict comes from every JSON object in the reply that has one: a brace ahead of it no longer masks the row, and objects that disagree stay a judge failure. A reply with no choices is a judge failure too. - Judge calls run inside observe_llm_judge_grading, so judged rows carry a grading record. - judge_model is removed: the judge's model server picks the model. Config and docs: - The Environment Server admits 64 episodes at a time (the agent's concurrency), and an episode has 5400 s, below the sandbox's 7200 s TTL; before, all rows started sandboxes at once with a 21600 s deadline. - The docs say that model_only keeps the model off the internet only on an OpenSandbox server that enforces egress at the IP layer (dns+nft), what `thinking` does, and how NeMo RL's masked_reward_policy treats a judge failure. Tests: verdict parsing, empty choices, incomplete runs, the last \boxed{}, the gold answer in the judge prompt, the exported verifier fixture, seed refusals, hosts and admission. Ten new cases fail on the old code. 86 passed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * feat(visual_coding_opencode): bake OpenCode's plugin dependencies into the sandbox image opencode_agent always configures a plugin, so OpenCode 1.17.11 installs @opencode-ai/plugin from npm at each start unless the dependencies are present. The lent sandbox reaches only the model server, so each start waited about 70 s for that install to fail before the first model call. The image now builds the dependency archive in two stages, from a copy of benchmarks/agentic_if/opencode's lockfile with the recipe in benchmarks/agentic_if/README.md: npm ci with Node 24.15.0 (npm 11.12.1), then GNU tar 1.34 and GNU gzip 1.10 (Debian 11). The build checks the archive against the pinned SHA-256 (77b03eba..., the same bytes agentic_if pins), and the config sets sandbox_plugin_dependencies_path and _sha256 to it. The docker build context is sandbox_image/, so the two lockfile files are copied there; a test keeps them equal to agentic_if's. Checked: the image builds and holds the archive with the pinned digest. Offline (docker --network none), with one plugin configured and the adapter's OpenCode environment, the first model request came 1.0 s after start with the archive unpacked into XDG_CONFIG_HOME/opencode, and 71.1 s without it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * fix(agentic_if_realworld): skip hidden directories in the runtime source fingerprint Other test runs in the same checkout install tools into hidden directories (pi_agent's .pi_node holds node-gyp .py files) and delete them. Hashing them made the resume fingerprint change mid-test, which failed test_observed_driver and test_driver in the sharded server suite. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * test(agentic_if_realworld): pin the driver's source fingerprint in tests The driver tests run and then resume within one test. In CI, other servers' tests share the checkout and add or delete .py files, so the source hash could change between the run and the resume. The runtime_identity tests still cover the hash itself. A conftest fixture pins it for every test in the folder, so the pin that NVIDIA-NeMo#5088 added inside test_adaptive_capture_selected_parameters_and_resume is no longer needed. The fixture also covers test_observed_driver.py::test_http_resume_and_connection_recovery, which failed the same way. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * feat(babyvision_opencode): prepare BabyVision from the public Hugging Face release prepare.py read BabyVision from one of two VLMEvalKit-style TSVs that have no public download. It now downloads UnipatAI/BabyVision (MIT license) at revision 849cbeea2b1d, checks the parquet file's SHA-256 and builds each row from the release record: the options listed as (A), (B), ... after "Choices:", the option's letter as the answer, type, subtype and ansType as category, l2_category and ans_type, and every image as an RGB PNG. BABYVISION_PARQUET reads a local copy of the file on a host without internet access. Both prepared files (babyvision_opencode and the question-only variant) are byte-identical to the ones the TSV with md5 4216333e produced, so scores on that copy stay comparable. Both benchmarks declare prepare_dependencies: [pillow], as agentic_mme does, since a dev install of Gym has no Pillow. Signed-off-by: Danial MohseniTaheri <[email protected]> * fix(visual_coding_opencode): grade only completed runs, count only the judge's own verdict, refuse several workers - A response whose status is not completed (incomplete, or failed but still sent to verify by the outcome policy) scores 0 without a judge call, so an early \boxed{} guess in a failed run cannot score. - parse_verdict takes the judge's last verdict object, and the judge prompt marks the model's text as data. A verdict object quoted from the model's text no longer masks the row, so a wrong answer cannot leave the loss by writing one. - multiple_workers_unsupported_reason refuses num_workers > 1 before launch: lent sandboxes live in one worker's memory. - Local copies of the response-text and last-\boxed{} helpers replace string_match's private ones. The string_match_reward diagnostic is dropped with them. - Tests: the judge grading record (completed, failed, none), the close order after a failed stop, a failed run, the worker refusal. The session test moves from opencode_agent's suite into this environment's tests, without the two tests that restated YAML values, and with a text-only row for image_input. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * build(visual_coding_opencode): check the OpenCode binary against its pin when the sandbox image builds The Dockerfile downloads OpenCode 1.17.11 without a build argument and checks the binary against the SHA-256 that the config pins (sandbox_executable_sha256), so a mismatched image fails at build time instead of at the first episode. The config test requires both pins in the Dockerfile. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * docs(visual_coding_opencode): head server reach under NeMo RL, tool images in training, OpenCode-only pairing - Under NeMo RL the lent sandbox can reach Gym's head server, whose /global_config_dict_yaml returns the merged config. The README, tutorial and config comment state this limit. - The images that read returns are staged by NeMo RL's single controller and recorded by local capture only with NVIDIA-NeMo#5837. Saved rollouts keep only the tool's text. - The step-limit reason is gone (Gym NVIDIA-NeMo#5833 joins OpenCode's step-limit note under capture). Only the compaction reason stays. - Only the policy model server advertises the host address. The question-only variant still sends the image. The pairing is OpenCode-only. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * test(agentic_if_realworld): drop the driver-test fingerprint pin Main's NVIDIA-NeMo#5909 fixed the cause: the runtime fingerprint skips hidden folders and ignores the checkout's dirty flag. This PR no longer changes agentic_if_realworld. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * data(visual_coding_opencode): regenerate the example rollouts at the head One OpenCode rollout of each of the 5 example rows, collected at 8a39cda. All 5 runs complete; 4 are correct, and the 3D cube-counting row answers 20 where 19 is right (judge: different, reward 0). The prompt image is attached to the first message, so no row reads the old input-media/None path. The rows carry task_id and no longer carry string_match_reward. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> * build(visual_coding_opencode): relock for openai 2.45.0 Main's NVIDIA-NeMo#5464 moved the shared openai pin to 2.45.0 and relocked every component on main. This component was not on main yet, so its lock still had 2.44.0, and both the component-lock check and the server suite's `uv sync --locked` failed in the merge queue. Regenerated with scripts/component_locks.py (check_project, update=True); the only change is openai 2.44.0 -> 2.45.0. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> --------- Signed-off-by: Yi-Fu Wu <[email protected]> Signed-off-by: Yi-Fu Wu <[email protected]> Signed-off-by: Danial MohseniTaheri <[email protected]> Co-authored-by: Danial MohseniTaheri <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
|
#5839 replaced this PR |
What does this PR do?
Adds a multi-turn visual coding environment: the OpenCode CLI, with a Python shell that can crop, measure and plot images, answers a question about an image over as many tool turns as it needs, and a GPT judge grades the final
\boxed{}answer. It also extendsopencode_agentso the environment can run at RL-training scale. Training tokens come frommain'stoken_id_capture; this PR adds no token tracking of its own.New components:
resources_servers/visual_coding_opencode: a dataset-agnostic verifier. A GPT judge (defaultgpt-4o-minion the OpenAI API; any OpenAI-compatible endpoint throughvisual_coding_opencode_judge_base_url/visual_coding_opencode_judge_model_name) decides whether the final answer matches the gold answer. string_match's grade is kept as a diagnostic. It exports aVERIFIER_FIXTURE.responses_api_agents/opencode_vision_agent:opencode_agentin a venv with pillow, numpy, scipy and opencv for the model's shell.scripts/component-lock-policy.jsonre-enablesopencv-python-headlessfor this agent only.benchmarks/babyvision_opencodeandbenchmarks/babyvision_opencode_question_only: BabyVision (388 puzzles) with and without a visual-reasoning instruction. Each has a manifest, a README andprepare.pytests.opencode_agent(local CLI path; every option defaults to off):attach_images,vision: write the user message's images into the run directory, attach them with-f, and declare the model entry image-capable.private_tmp: a per-run/tmpin a user and mount namespace.session_nodes,session_exclude_actor_classes: spread sessions over Ray nodes.session_sandbox: onenemo_gym.sandboxsandbox per session.provider_id: the OpenCode provider id of the generated model entry.--title.Core:
nemo_gym/models/chat_streaming.py: drop thereasoningfield that OpenCode echoes on assistant history messages. The strict assistant-message model rejected every request after the first tool call with 422, which ended OpenCode sessions undertoken_id_capture.How to run
Requirements: a vision-capable policy behind an OpenAI-compatible endpoint (vLLM through
vllm_model), the OpenCode CLI 1.17.11 installable on the agent host, unprivileged user namespaces forprivate_tmp, and an OpenAI key for the judge.Prepare the data.
prepare.pyreads BabyVision in VLMEvalKit's TSV format and checks its md5:Run the benchmark (
babyvision_opencode_question_onlyis the same without the visual-reasoning instruction):The metric is
mean/reward: GPT-judged accuracy over the 388 puzzles. To use another judge endpoint, add++visual_coding_opencode_judge_base_url=<>and++visual_coding_opencode_judge_model_name=<>.For RL training, enable
main's training-token capture: run-leveltoken_id_capture.enabled: trueplustoken_id_capture: trueonopencode_vision_agent(seetraining-tutorials/external-agent-harnesses). OpenCode's model calls then go through/ng-rollout/<id>/training-token-capture, and capture records their token IDs and log-probabilities. Addsession_nodesto spread sessions over Ray nodes.Check the environment without a model:
Serving note for Nemotron 3.5 Super: vLLM auto-detects the
openaicontent format for its chat template, and that template then prints list-shapedcontentas a Python repr in assistant and tool turns. Serve it with a template that renders list content (see Rollouts) until the checkpoint's template is fixed.The README of each new component has the details:
resources_servers/visual_coding_opencode/README.md,responses_api_agents/opencode_vision_agent/README.md,benchmarks/babyvision_opencode/README.md, and the new options table inresponses_api_agents/opencode_agent/README.md.Validation
After review,
track_token_idswas removed (see the review thread),visual_coding_opencodegained atask_data.pyschema, and the BabyVision md5 line is marked for the secrets detector: head0c4c1c020, rebased ontomain(72275b85d), Python 3.13.14:pytest tests/unit_tests/data/test_task_data.py: 437 passed (schema presence and committed-row checks include this server).pytest responses_api_agents/opencode_agent/tests(with therayextra): 856 passed.pytest resources_servers/visual_coding_opencode/tests: 12 passed.pytest benchmarks/babyvision_opencode/tests: 8 passed.pytest tests/unit_tests/models/test_chat_completions_streaming.py tests/unit_tests/models/test_external_capture_handlers.py: 103 passed.responses_api_models/vllm_model/tests: 996 passed.tests/unit_tests/test_public_api_facades.py: 845 passed.pytest responses_api_agents/opencode_vision_agent: 1 passed, 1 failed (import cv2: the shared test venv has no opencv; it passed in the agent's locked venv).checkandformat --checkon the changed Python files: clean (ruff 0.17.3; the pinned 0.9.9 crashes on the aarch64 dev node).Before the rebase, on
292224aa7:gym env validate --sync babyvision_opencodeandgym env validate --sync babyvision_opencode_question_only: manifests and components agree, 388 prepared rows each.gym env test babyvision_opencode: verifier fixture, 5 cases passed.gym env test +entrypoint=resources_servers/visual_coding_opencode: 12 passed.gym env test +entrypoint=responses_api_agents/opencode_vision_agent: 2 passed (cv2 importable in the locked venv).gym env test +entrypoint=responses_api_agents/opencode_agent: 666 passed, 7 skipped (Ray), 2 failed. The two failures,test_exec_transport.py::test_exec_only_supervision_leaves_task_children_for_sandbox_owner[close]and::test_confirmed_cleanup_cancels_stuck_transport, are unchanged by this PR and passed 3 of 3 times when rerun alone; they look load-sensitive.pytest responses_api_agents/opencode_agent/tests/test_app.py -k "TestRemoteSessionTask or TestSessionNodes"with therayextra: 7 passed. These are skipped without Ray.pytest benchmarks/babyvision_opencode/tests: 8 passed.pytest tests/unit_tests/models/test_chat_completions_streaming.py: 51 passed.tests/unit_tests/models/test_external_capture_handlers.py: 48 passed.responses_api_models/vllm_model/tests: 984 passed.python scripts/component_locks.py: the two new projects lock and check clean.resources_servers/opencode_search, already onmain, still reportsMissing pyproject.toml.check --fix,--select I,format),lint-imports(1 contract kept),scripts/add_verified_flag.py,scripts/update_env_list.py.Scaffold/CI mismatch:
resources_servers/visual_coding_opencode/data/example.jsonlhas 3 rows. These workloads use the manifest path, so no legacy five-row artifacts were added.Rollouts
Before the merge with
main, this code ran end to end at scale:session_nodesand an agent-side token tracker (since removed in favor oftoken_id_capture, see below) drove RL training on the visual coding environment, andbabyvision_opencodeevaluated the training checkpoints (step 35 checkpoint: 76.8 on the 388 puzzles, with the agent and judge working as described above).Smoke rollout on
292224aa7(the same changes before the rebase ontomain):babyvision_opencode, 5 rows, Nemotron 3.5 Super (vLLM 0.32,nemotron_v3reasoning parser) as the policy throughvllm_model,gpt-4o-minias the judge. 5 of 5 rollouts completed with no failures and ahealthyverdict each:bashbashbashbashEach rollout got the puzzle image attached. The agent cropped and measured it with PIL/numpy in the shell, the judge returned a verdict with a reason, and the reward followed the verdict. In 525 the model answered without
\boxed{}, and the judge still graded the final answer. In 534 the model ended a turn in prose with no tool call after 75 turns, so OpenCode finished with no answer. These five are hard "find the different" puzzles; five rows say nothing about accuracy.The run served Super 3.5 with a copy of its chat template patched to flatten list-shaped
contentfor assistant and tool messages. vLLM auto-detects theopenaicontent format for this template, so every message'scontentreaches it as a parts list, and the stock template prints the list's Python repr ([{'type': 'text', 'text': ...}]) into assistant and tool turns. An earlier run with the stock template completed the same way but scored 0/5, with the model copying the repr into its own answers. This is a serving issue, not a Gym change.Compatibility and benchmark impact
opencode_agentoption defaults to off, so existing configs and benchmarks behave as before. The local run passes--title "NeMo Gym", so OpenCode no longer makes a session-title model call.reasoningfrom assistant history messages. Requests that carried it previously failed with 422.experimental: true. The resources server config isverified: false.Checklist
pre-commit run --all-files) (so CI lint/format checks pass). The same hooks were run directly on the changed files. pre-commit could not build its hook environments on the dev cluster. The guardwords hook was not run locally.git commit -s) (so the DCO check passes).