Skip to content

fix: read OpenCode's tool placeholder in token capture and enforce opencode_agent permissions - #5387

Merged
adil-a merged 25 commits into
mainfrom
adasif/harbor-rl-fixes
Nov 7, 2026
Merged

adil-a merged 25 commits into
mainfrom
adasif/harbor-rl-fixes

Conversation

@adil-a

@adil-a adil-a commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

What and why

Two fixes found while training Terminal-Bench 2.1 with OpenCode on NeMo RL. No issue was filed. NeMo RL's side of
running Environment Server tasksets (routing materialized rows and unwrapping episode replies) is
NVIDIA-NeMo/RL#4429. This PR covers the two problems only Gym can fix.

flowchart LR
  RL["NeMo RL<br/>(taskset routing and episode unwrap: RL #4429)"] -->|run_examples| ENV["Harbor<br/>Environment Server"]
  ENV --> AG["opencode_agent<br/>(OpenCode in sandbox)"]
  AG -->|"② permission profile<br/>now enforced"| AG
  AG <-->|model calls| MS["Gym model server<br/>+ token capture"]
  MS -->|"① reads OpenCode's invalid<br/>placeholder to find the parent call"| MS
  ENV -->|episode reply| RL
Loading
  1. Token capture reads OpenCode's unavailable-tool placeholder.

    • When the model calls a tool OpenCode doesn't offer, OpenCode echoes the call as invalid {tool, error} with the
      same call ID. The next request then has no parent, and NeMo RL masks the episode: 16% of OpenCode episodes when
      our TB2.1 captures are replayed through main.
    sequenceDiagram
      participant O as OpenCode
      participant G as Gym model server (token capture)
      participant M as Model
      O->>G: call N
      G->>M: generate
      M-->>G: tool call str_replace_editor (id call_7)
      G-->>O: reply (stored key: call_7 → str_replace_editor)
      Note over O: tool not offered, so OpenCode echoes it back<br/>as invalid {tool: str_replace_editor, error}
      O->>G: call N+1 (history has call_7 as invalid)
      Note over G: main: no parent matches → episode masked<br/>this PR: reads the placeholder as str_replace_editor → parent = call N
      G->>M: generate, starting from call N's exact tokens
    
    Loading
    • The fallback lookup now also reads that placeholder as the served tool, each placeholder-shaped call on its own,
      and picks a parent only if one candidate matches across all readings. Above 6 such calls in one turn it abstains.
      Stored keys and FINGERPRINT_VERSION are unchanged.
    • Terminal attribution's item-ID witness reads the same placeholder, so a transcript that ends with the placeholder
      and its error result still names its final call. It keeps the strict comparison when another item reuses the call
      ID or a reasoning item follows the placeholder. It reads only the last call, so it can attribute a turn with more
      than 6 placeholders that the turn-level fallback abstains on.
    • Like the existing ID-based fallback (feat(token-id-capture): resolve parent and terminal call by tool-call ids #4014), both readings assume tool-call IDs are unique per served call, as
      vLLM's tool parsers make them. Under a scheme that repeats IDs, for example a per-turn call_0 or the same IDs on
      a retry, two captured calls can share an ID, and the fallback can pick the wrong one or report ambiguity. Lookups
      also get slower: up to 65 fingerprint passes for a turn with 6 placeholders, and cubic growth in the turn count
      when IDs repeat across turns.
    • This is a targeted patch. It doesn't cover OpenCode's case-only renames (Read -> read) or the echo rewrites
      other harnesses make (for example stripped <think> blocks). Those need a wider look from the token-capture
      owners.
    • The unresolved-parent warning now logs the resolution reason and the number of request items.
  2. opencode_agent enforces its permission profile.

Compatibility

  • Benchmark impact. opencode_agent runs now get the bash deny-list, and 8 tools instead of 10. The deny-list
    also blocks Git history commands and git fetch, which some terminal tasks need; the README shows how to allow them
    per run. swe_together keeps its own tools map (pre-existing), and gdpval/opencode.yaml is unaffected.
  • Token capture. Stored keys and ledger rows are unchanged, so ledgers written before this PR replay identically.
    Only lookups change, and only for an echoed turn that contains a placeholder-shaped call.
  • NeMo RL. Bump the Gym submodule to a commit with this PR; nothing else is needed for this PR. Tested with
    feat(gym): support Environment Server tasksets RL#4429 at e0822095a on Gym main with this PR merged: #4429's 4,940 Gym-related unit tests give the
    same result for every test with and without this PR, and a GRPO smoke trained 2 steps (Rollout evidence). That smoke needed one RL-side change that is
    unrelated to this PR: #4429 adds max_output_tokens to Environment Server rows, and opencode_agent rejects it
    with a 422, on Gym main too.
  • Earlier revisions of this PR also added taskset routing, agent_ref stamping and an episode_records option to
    run_examples. They were removed: RL#4429 does all three on the RL side, and the agent_ref stamp would change how
    #4429 attributes taskset rows.

Validation

On 4ec6a35 (main e12458f merged), Python 3.13, CPUS unset as in CI:

  • pytest tests/unit_tests -m 'not sandbox' -n 24: 14,613 passed on e758836. On this head the 2,756 token-capture
    and attribution tests pass, and every other test gives the same result as on e758836.
  • Server tests on e758836 (later commits change only terminal.py and tests), run from each server directory as
    gym env test runs them:
    • opencode_agent: 620 passed, 22 skipped (no Node.js or OpenCode binary on this host);
    • vllm_model: 898 passed;
    • partner_if config tests and swe_together recipe tests: passed.
  • pre-commit run --files on the changed files: clean.
  • The new tests fail without their fixes:
    • placeholder lookup, including a turn that mixes a rewritten call with the model's own invalid call, and the
      abstention above 6 placeholders;
    • the item-ID witness on a transcript ending with the placeholder and its error, with an auxiliary root, and its
      strict fallbacks (reused ID, reasoning after the placeholder); one opencode_agent test builds that transcript
      through OpenCodeAgent._session_output;
    • ledger replay across the change;
    • the unresolved-parent log, including an unsized request history;
    • the permission profile's config tests.
  • Token capture against main. All 365,968 captured calls were replayed through main's code and this branch's:
    347,547 parent decisions, including both 50-step training runs.
    • Stored keys and ledger rows are identical.
    • 7,135 requests go from unresolved to resolved, each to the call the echoed tool-call IDs name.
    • No other decision changes.
    • Randomized tests over 500,000 turns and 80,000 rollouts find no difference for any turn without a
      placeholder-shaped call.
  • Terminal attribution on the 6,401 rollouts of both 50-step runs: exactly 5 change, all ending with the placeholder
    and its error result, from unattributed to their final call.
  • CI on fa3013a (the last commit only adds that opencode_agent test): unit tests, all 8 server-suite shards and
    session routing pass. The non-blocking kilocode harness
    conformance probe fails its model_error scenario (1 of 8), as on every earlier head of this PR; this PR does not
    touch kilocode_agent.

Rollout evidence

  • GRPO smoke with feat(gym): support Environment Server tasksets RL#4429, job 1526932. Nemotron-3-Nano-30B-A3B, 2 steps of 4 TB2.1 tasks × 8 on the
    Harbor path with opencode_agent. RL#4429 at e0822095a with the one RL-side change above; Gym main 4aff2e8 with
    this PR merged.
    • Both steps trained all 32 rows, none masked, and the rewards match the verifier for 64/64 episodes.
    • 18 episodes echoed a placeholder. Replaying their captures through Gym main leaves 46 calls unresolved, which
      NeMo RL would mask; this PR resolves all 46 to the preceding call and changes no other decision.
    • None of the 1,143 requests offered the web or skill tools.
  • Smoke, job 1508856. 6 TB2.1 tasks × 2 on the Harbor path, with Gym started in-process, as NeMo RL starts it.
    • None of the 261 requests offered the web or skill tools, and 12/12 rule-matching bash commands were blocked.
    • Replaying its captures through main leaves the 2 requests after a placeholder unresolved. This branch resolves
      them, and the other 246 are unchanged.
  • Permission smoke, job 1404281. 36/36 rule-matching bash commands blocked.
  • GRPO runs. Two 50-step runs carried a broader, ID-based lineage patch as a local patch.

🤖 Generated with Claude Code

adil-a and others added 7 commits October 30, 2026 11:13
run_examples now stamps each unstamped materialized row (task_id.taskset + task_input) with the
Environment Server its taskset routes to, as gym eval run does while preprocessing, and raises before
any POST when a taskset has no route. Without this, rows a trainer hands straight from the dataset fall
through to resolve_task_sources and fail. A row or caller that already names a server keeps it.
run_examples (only) also stamps those rows with the server's attributed agent_ref, so callers keyed on
agent_ref.name (NeMo RL) work; Gym's own stored records stay unattributed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
run_examples(..., episode_records=True) resolves a materialized row's result to the flat record
gym eval run stores (_episode_record plus the row's task_data provenance), on both the awaited and the
aclose_and_drain paths, so callers such as NeMo RL stop importing private helpers to unwrap a
BaseEpisodeResponse. A handled Environment Server failure comes back with reward 0.0 and mask_sample
True. gym eval run and run_examples now share one helper for that record; the default keeps raw replies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
…o its served call

OpenCode echoes a served call to a tool it does not offer as a call to its `invalid` tool with the
same ID and arguments exactly {tool, error}. The whole-turn fingerprint now hashes such a call under the
served name, so its next request resolves its parent instead of being poisoned as unresolved_parent.
Any other rename still does not match, and no fingerprint version or ledger column changes. The
unresolved-parent warning now also logs the resolution reason and the request item count.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
OpenCode places a `tools` map's entries before the permission map's "*": allow and applies the last
matching rule, so opencode_agent.yaml's tools map voided the default profile's command denies and its
webfetch/websearch/skill restrictions. Drop the whole opencode_config block from opencode_agent.yaml
(an empty block would null out the profile) and deny webfetch, websearch and skill right after "*" in
permissions/default.yaml. This changes behaviour and scores of every opencode_agent run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
With episode_records, aclose_and_drain converted each drained outcome inline, so one reply the record
conversion rejects raised out of the drain and lost every other outcome, which are transferred only once. That
outcome now raises when awaited, as it does on the awaited path. The run_examples docstring now says that the
taskset route, not a row's agent_ref, picks a materialized row's Environment Server, and when no agent is bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
Pin the exact-name, JSON-object and string-type guards of the placeholder mapping at the fingerprint, in the
Chat Completions shape OpenCode sends too, and cover terminal attribution's tool-ID reading, which now matches
a trailing placeholder to the served call it names. Document that the mapping moves the whole-turn key of a
served call that itself has the placeholder's shape (rare), without a fingerprint version change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
…l tasks

Now that the command filters apply, note that they also deny Git history commands and git fetch, which some
terminal tasks need, and how to allow them per run. State precisely how a tools map voids permission rules,
and update the partner_if comments that pointed at the tools map opencode_agent.yaml no longer sets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
@adil-a adil-a added bug Something isn't working area:training Training framework integrations and training-data interfaces labels Oct 30, 2026
@copy-pr-bot

copy-pr-bot Bot commented Oct 30, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

adil-a and others added 4 commits November 2, 2026 15:50
Drop the run-specific frequency from _served_tool_name's docstring; the
rare-collision caveat stays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
Resolve the conflict with #3302 (persist failures and resume unfinished
evaluations) in nemo_gym/rollout_collection.py:

- Keep main's gym eval run store loop. The branch's refactor of that loop
  onto _stored_episode_record no longer applies: main now validates replies
  at dispatch and stores failures as compatibility rows.
- episode_records translates a BaseEpisodeResponse through main's
  _native_episode_record, so the reply's episode and task identity is
  checked as gym eval run checks it.
- episode_records masks a handled Environment Server failure with
  matches_failure_class(record, {ENVIRONMENT_SERVER_FAILURE_CLASS}). Since
  #3302 a failure that names a failure_kind (for example
  harbor:task_deadline) carries that kind as its class and
  environment_server_failed as its legacy class; an exact class check would
  leave it unmasked.
- _RowResultIterator keeps the branch's per-outcome conversion with main's
  wider result type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
Since #3302 a handled Environment Server failure that names a failure_kind
carries the kind as its _ng_failure_class. Test that episode_records still
masks it (reward 0.0, mask_sample True) on the awaited and drained paths,
and that a reply for another attempt or task raises StaleRolloutResult or
InvalidRolloutResult from its own outcome.

Rename _stored_episode_record to _flat_episode_record: gym eval run no longer
stores this record, so the docstrings now describe it as a flat episode
record and say why episode_records exists next to run_outcomes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
The page told users to select OpenCode's tools with an opencode_config.tools
map. With opencode_agent, OpenCode places that map's keys before the
permission profile's "*": allow, which overrides them. Point to permission
rules instead, as the opencode_agent README does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
@adil-a

adil-a commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 68dc30d

@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

@adil-a
adil-a marked this pull request as ready for review November 3, 2026 03:20

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SHIP WITH CARE

Two RISK findings remain: episode_records=True can accept malformed Environment Server replies without validating their identity, and the changed fallback hash breaks replay of some existing custody-ledger rows.

I inspected all 15 changed files and their directly affected contracts, callers, and failure paths. I found no additional material issue in the OpenCode permission configuration. This was a static review; I couldn't execute tests or independently verify the reported smoke runs.


Inline comments (escaped v1):

  • nemo_gym/rollout_collection.py line 691: RISK — Validate every materialized HTTP reply before flattening it

    Failure: For a materialized row, return HTTP 200 with {"reward":1.0} or an episode envelope whose episode_id is missing/null. With episode_records=True, _is_episode_response is false, so this branch returns the malformed reply with provenance instead of raising InvalidRolloutResult. Non-object JSON also passes through the caller guard. The HTTP dispatch path doesn't validate these replies because run_examples enables neither typed_outcomes nor validate_results. A trainer can therefore receive an apparent reward without validated task/attempt identity.

    Correction: Could you distinguish HTTP replies from collector-built outcomes and apply _native_episode_record to every materialized HTTP reply when this option is enabled, without first requiring it to look valid? Keep budget-drained and routed transport-failure records outside that validation. The invariant is that only collector-built outcomes may bypass the episode envelope check. The exact origin-metadata plumbing needs verification; validating every dictionary here would incorrectly reject legitimate collector-built records.

    Preservation and acceptance — proposed tests, not executed: Using the new materialized-row fixture, return {"reward":1.0}, null, [], and envelopes with missing/null identity fields. Each awaited outcome should raise InvalidRolloutResult; draining should preserve each exception without losing another valid outcome. Retain valid success flattening and digest propagation, stale-attempt/task rejection, handled-failure masking with and without failure_kind, unmasked budget-drained records, routed transport-failure records, unchanged flat-row results, and unchanged raw replies when episode_records=False.

  • nemo_gym/models/token_capture/lineage.py line 1184: RISK — Preserve identical ledger replay across the fallback-hash change

    Failure: Persist a custody commit using base with served output [{"type":"function_call","call_id":"c","name":"invalid","arguments":"{\"tool\":\"Read\",\"error\":\"bad\"}"}], then reopen/import that ledger under head and replay the identical CaptureLedgerCommit. The base fingerprint hashes invalid; the new normalization hashes Read. Both retain fingerprint version 4. _record recomputes the persisted key and this equality check raises conflicting lineage record, violating the identical-replay no-op contract. An old row also loses its argument-tolerant match when only the echoed error changes: strict matching misses, and the custody reader compares the old stored key with the new incoming key. This affects existing ledgers containing model-emitted placeholder-shaped calls, not ordinary served tool calls.

    Correction: Could you preserve legacy fallback-key semantics in FileLineageStore._record and _resolve_row, either through explicit fallback-algorithm versioning or by retaining the stored hash algorithm and adding compatible request-side lookup? Identical replay must remain a no-op, genuine payload conflicts must still fail, and compatible fallback candidates must be pooled before deciding uniqueness. The strict fingerprint needn't change. The migration details need verification against checkpoint readers, so I don't have a sufficiently certain small patch to suggest.

    Preservation and acceptance — proposed tests, not executed: Add a base-format ledger fixture for the output above. Import it into head, replay the identical commit, and expect one row with no exception. Resolve a continuation changing only its echoed error and expect the original parent. Retain ordinary Read → exact invalid placeholder resolution, rejection of other names/malformed shapes, ambiguity for differing-token siblings, and checkpoint custody round-trips. Changing actual commit data must still raise a conflict.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

adil-a and others added 2 commits November 2, 2026 19:35
episode_records now treats every Environment Server reply for a
materialized row the same way:

- A reply that is not a BaseEpisodeResponse for the dispatched episode and
  task, or whose reward is present but not a finite number, raises
  InvalidRolloutResult (StaleRolloutResult for another attempt) from its own
  outcome. Before, a non-episode payload came back raw and a string or null
  reward came back as a score.
- A reply that carries any failure class is masked (reward 0.0, mask_sample
  True). That now includes a result marked judge_failed, whose reward is a
  placeholder; before, only Environment Server failures were masked.

Results Gym built itself (drained rows, routed /run failures) stay unmasked.
The reject-reply test now checks the exact error type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
The example rule was already in opencode_agent's profile, and a "*": deny
override does not cover edit and bash, which the profile allows after its
"*" rule. Use task: deny as the example and name the edit and bash maps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
@adil-a

adil-a commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test e6cfd10

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 3, 2026 03:36

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SHIP

No qualifying findings.

The prior public-API import failure is fixed in the OpenCode test imports. The session-export regression retains both outcomes: the matching placeholder selects the served call without masking, while a different tool name remains unattributed and masked.

I inspected all 15 changed files and their directly affected callers, contracts, tests and failure paths. Stored fingerprint semantics remain unchanged, placeholder lookup pools all readings within its bound, and terminal attribution handles following or interleaved tool results. The permission profile reaches both local and session configuration paths. I checked that topic directly because its delegated report wasn't available.

This was a static review; I didn't execute tests or independently verify the reported smoke and replay runs. OpenCode's native permission evaluator isn't included in the supplied tree, so I verified Gym's configuration plumbing rather than upstream rule precedence.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

@pthombre

pthombre commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Fix for OpenCode token capture LGTM

pthombre
pthombre previously approved these changes Nov 6, 2026
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 6, 2026 22:05
@kajalj22
kajalj22 removed the request for review from a team November 6, 2026 22:51
Conflicts:
- nemo_gym/models/token_capture/sink.py: main renamed rollout_id to
  capture_key in the unresolved-parent warning; kept the rename and this
  branch's reason and request-item count.
- responses_api_agents/opencode_agent/configs/opencode_agent.yaml: kept
  main's new owner-extension keys and this branch's removal of the
  opencode_config.tools map.

Follow-ups for main's API changes: tests build TokenEntry with capture_key,
and the opencode_agent test imports the token-capture names from
nemo_gym.models.token_capture, their public API since #5525.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
@adil-a

adil-a commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 46e3563

agentic_if (#4959), merged into main alongside this branch, adds the same
webfetch/websearch/skill denies after the default permission map and checks
that they are the map's last keys. With this profile declaring them right
after "*", the merged map kept them in that earlier position. Declaring them
last keeps both layouts the same; the denies apply either way, since they do
not overlap the edit and bash rules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
@adil-a

adil-a commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 22d207e

@adil-a
adil-a added this pull request to the merge queue Nov 7, 2026
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42339805160

This branch was previously deployed

1 inactive deployment
public — 22d207ee Deployed Nov 7, 2026 by copy-pr-bot[bot] via release / finalize / notify #10791
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:training Training framework integrations and training-data interfaces bug Something isn't working needs-review PR is ready for code review and waiting on a reviewer sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Pipeclean the current NeMo-RL v2 with TB2.1 in main native (non-harbor) path

5 participants