Skip to content

fix(opencode): repair snapshot collection and Java setup - #4172

Merged
zyzhou5 merged 1 commit into
mainfrom
glovisotto/opencode-snapshot-setup
Oct 9, 2026
Merged

zyzhou5 merged 1 commit into
mainfrom
glovisotto/opencode-snapshot-setup

Conversation

@giuliolovisotto

Copy link
Copy Markdown
Contributor

OpenCode observation collection currently runs Python's SQLite backup API inside each task image. Images without Python, or with Python older than 3.7, cannot produce the snapshot: native evidence becomes unobserved and child-session usage absent from the parent export is lost.

Use OpenCode's bundled SQLite through opencode db "VACUUM INTO ..." to create a consistent standalone snapshot, including committed WAL rows. Preserve session-selection environment, timeout and failure reporting; escape the destination as a SQL literal and shell argument. Update snapshot tests to exercise the real SQL query against a live WAL database and preserve failure coverage.

Also upload the SWE-bench Java Gradle mirror configuration to /root/.gradle/init.d/maven_central_mirror.gradle. The Docker upload path is not expanded by a shell, so ~/.gradle/... failed during Druid/Lucene setup. This path fix is validated on Docker only; no Slurm validation is claimed.

Split from #4106 so the cached-token sums can be reviewed independently. This PR targets main, does not depend on #4106, and does not change token conversion formulas. No separate issue is needed for these reproduced failures from the #3764 follow-up evaluation.

Validation

At 1e28f88d8, using gym env test with +should_validate_data=true ++skip_venv_if_present=true:

  • Sandboxed OpenCode agent: 50 passed, including snapshots with committed WAL rows, database-name variants, child/grandchild ownership, and failed snapshot commands with observations enabled/disabled.
  • SWE-bench resources: 28 passed; example-data validation passed.
  • pre-commit run --all-files and git diff --check: passed.

Previously, the same runtime snapshot and Gradle changes were tested together with the cached-token fix at 266ec1154056cf31a54950f6def5e193cebfebdc:

  • Stock OpenCode 1.17.11 snapshot fixtures passed with Python absent and Python 3.5.6, including committed WAL data, integrity checks and quoted/metacharacter destination paths. These fixtures made no model calls.
  • Seven targeted SWE-bench reruns completed: 6 healthy / 1 unhealthy / 0 unobserved, compared with six unobserved in the initial batch. All 322 calls reconciled in the combined implementation. The remaining unhealthy result was Caddy hitting a generation length limit, not missing evidence.
  • Druid and Lucene completed setup with the committed absolute upload destination.

The live reruns used stock OpenCode 1.17.11 and azure/openai/gpt-4.1, capture/observability enabled, Docker on macOS arm64, and the supported file-watcher-disable setting for a separate shutdown hang. Selected CPU and step-budget settings changed between original and follow-up runs, so this is not a controlled score comparison. These are retained combined-change rollout results, not new standalone-branch rollouts; accurate cached-token totals additionally require #4106.

Compatibility and benchmark impact

No configuration migration. Task images no longer need Python for this snapshot operation. Successful collection restores native observations and descendant usage where collection previously failed; Java Docker tasks can complete Gradle configuration upload. Model sampling and verifier logic are unchanged. The native SQLite command was validated with OpenCode 1.17.11. Slurm confirmation of the Java setup fix remains outstanding.

Use bundled SQLite to preserve committed WAL evidence without requiring Python in task images. Use an absolute destination for the Gradle mirror upload in SWE-bench Java setup.

Signed-off-by: Giulio Lovisotto <[email protected]>
@giuliolovisotto giuliolovisotto added bug Something isn't working area:agent Agent harnesses and Responses API agent behavior needs-review PR is ready for code review and waiting on a reviewer labels Oct 7, 2026
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 7, 2026 10:39
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

@yaoyu-33 yaoyu-33 added the complexity:low Localized change in one scope with a small, straightforward review surface label Oct 7, 2026
shy982 pushed a commit to shy982/Gym that referenced this pull request Oct 7, 2026
OpenCode reports uncached input, cache reads, and cache writes
separately. The sandboxed adapter omitted both cache categories from
`input_tokens`; the local adapter omitted cache writes. For example, 122
uncached input tokens plus 5,760 cached reads must report 5,882 input
tokens, not 122.

Both adapters now sum uncached input + cache reads + cache writes
exactly once. Cached-read details and output/reasoning accounting from
NVIDIA-NeMo#3764 retain their existing semantics. Regressions cover cache reads,
writes, and absent/null cache counters. This is a direct follow-up to
NVIDIA-NeMo#3764; a separate issue is unnecessary for this bounded correction.

OpenCode 1.17.11 explicitly subtracts both cache reads and cache writes
from its stored `input` count ([upstream
implementation](https://github.com/anomalyco/opencode/blob/v1.17.11/packages/opencode/src/session/session.ts#L328-L360)).
Cache writes are prompt tokens used to populate the cache; adding them
back reconstructs prompt size, rather than counting an extra copy or
applying a billing multiplier. Gym capture already normalizes to full
prompt size, and the health check compares that total with the adapter
total.

This PR contains only token conversion and its tests. Snapshot
collection and the Gradle upload correction are tracked separately in
NVIDIA-NeMo#4172.

## Validation

At `ba60d5f48`, using `gym env test` with `+should_validate_data=true
++skip_venv_if_present=true`:
- Local OpenCode agent: **129 passed**.
- Sandboxed OpenCode agent: **57 passed**.
- `pre-commit run --all-files` and `git diff --check`: passed.

The complete tracked tree is identical to the original cached-token
commit `afe8826306eae36844045cebac6ce9fa114f65f6`, which was tested on
10 SWE-bench Verified, 10 Multilingual, and 10 Pro tasks (one repeat
each). Across 1,297 captured calls, independent comparison found zero
input/output/cache mismatches in 1,077 completed calls with canonical
ownership, including 62 child calls; the previous conversion
undercounted 1,059 of those calls. Cache writes were zero in live runs
and are covered by regression tests.

That original batch produced **23 healthy / 1 unhealthy / 6 unobserved**
rollouts. The six unobserved outcomes were snapshot collection failures
addressed by the separate PR. The unhealthy run had a native timeout and
missing final-stream usage. The later combined-fix reruns are not
evidence that this cache-only PR resolves those failures.

Runs used stock OpenCode 1.17.11, `azure/openai/gpt-4.1`, model-call
capture and observability, amd64 Docker on macOS arm64, a 1,800-second
native timeout, and the supported file-watcher-disable setting for a
separate shutdown hang. Initial Java tasks used an isolated Gradle-path
overlay. This batch therefore validates token reconciliation, not the
Java setup correction in this PR.

## Compatibility

No configuration migration. Reported input totals increase by previously
omitted cached tokens. No change to model sampling or verification.

---------

Signed-off-by: Giulio Lovisotto <[email protected]>
@github-actions github-actions Bot added the sla:triage-overdue Review assignment is over the one-business-day SLA label Oct 8, 2026

@zyzhou5 zyzhou5 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.

LGTM

@zyzhou5
zyzhou5 added this pull request to the merge queue Oct 9, 2026
@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

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

@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

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

@github-actions github-actions Bot removed the sla:triage-overdue Review assignment is over the one-business-day SLA label Oct 9, 2026
Merged via the queue into main with commit 949e07c Oct 9, 2026
52 checks passed
@zyzhou5
zyzhou5 deleted the glovisotto/opencode-snapshot-setup branch October 9, 2026 20:43
Ashish-Soni08 pushed a commit to Ashish-Soni08/Gym that referenced this pull request Oct 10, 2026
## What / expected

Add sandbox sessions to `opencode_agent` using the shared execute/close
lifecycle. An agent session runs OpenCode in a borrowed or agent-owned
sandbox; no session uses the local CLI. Close confirms cleanup before
Resources verifies. Invalid/closed sessions never fall back to the host.

- Include NVIDIA-NeMo#4288's shared runtime pin and model-call attribution plugin
in both paths.
- Keep failure artifacts and cleanup observations; cap combined
diagnostics at 16k characters. Local installation is off-loop and
retryable even after all waiters cancel; sandbox ripgrep provisioning is
best-effort.
- Remove the unshipped execution selector, old-adapter bridge and
obsolete cookie. Session requests use an explicit supported-field
contract.

Existing `opencode_sandboxed_agent` benchmarks, recipes and allowlists
stay unchanged; only four required PATH-quoting fixes remain in that
adapter. Shared-helper/fixture cleanup is tracked in NVIDIA-NeMo#4306.

## Compatibility / concerns

The shipped YAML now selects `${policy_model_name}` through Gym,
removing the fixed `nvinf` provider/model example. Removed local example
keys (`openai_api_key`, `openai_base_url`, `env`, `workspace_root`,
`system_prompt`, `extra_args`, `concurrency`) remain configurable class
fields. `thinking` now defaults to **true**, timeout changes **900 →
10800s**, and `resources_server: null` means local `/run` needs an
explicit binding. Install/close budgets are **600/60s**; owned sandboxes
need an explicit provider.

Local prompt compatibility is preserved; sandbox instructions use a
separate file. Sandbox `env`, custom `command` and `extra_args` are
rejected. Default permissions apply locally too; subagents are enabled
here but remain disabled in the old benchmark profile. These differences
can affect scores. One worker; eval-only, with training token capture
off by default. No new benchmark baseline is claimed.

Missing system `rg` warns and falls back to OpenCode's on-demand
download; required runtime prerequisites still fail explicitly. Offline
images should preinstall ripgrep. A separately identified input-upload
permission issue for non-root Docker with controller umask 077 remains
outside this fix; the model smokes below use a root image.

## Validation

Current head: `5cfdbae0d6167fb055342a5ad2faf89e261975f8`; merged main
`f128d43d3`. The conflict with NVIDIA-NeMo#4172 retains its `opencode db VACUUM
INTO` snapshot and our quoted PATH.

Pytest selection: both OpenCode agent suites,
`responses_api_models/vllm_model/tests`, and core
`test_sandbox_session`, `test_sandbox_supervisor_client`,
`test_agent_sessions`, `test_agent_session_retries`,
`test_add_legacy_agent_environment_servers`, `test_global_config`, plus
`test_ray_opt_out`, `test_server_utils` and `telemetry/test_config`
after merging main. Run with `--import-mode=importlib -q -o addopts=''
-o log_cli=false`; Linux exclusions are named below.

- macOS/Python 3.13.14 after merge: **1,382 passed / 43 skips** (39
platform/runtime; four optional `nemo.lens` integration tests). Final
all-file pre-commit and whitespace checks pass. The initial restricted
pre-merge run could not bind a test port; permitted reruns pass without
exclusions.
- Linux/Python 3.13.14 after merge: **1,419 passed / 4 skipped / 2
deselected**, including real Linux process-supervision, installer and
Node plugin tests. Skipped: optional `nemo.lens` integration. Excluded:
the previously reproduced vLLM endpoint-mtime failures
(`test_publish_rebinds_clients_and_clears_sessions`,
`test_unpublished_endpoint_grace_lifecycle`); those unchanged model
files match main. Canonical isolated `gym env test` and core-wide
coverage were not rerun.
- New regressions reproduce 11 pre-fix Linux installer failures
(uncached/cached, non-root, no package manager, apt/apk failures), the
cancelled-waiter retry failure and oversized combined diagnostics. The
fixed focused Linux suite passes **55 tests**; 502 and capture errors
share the same bound without duplicating stderr.
- Regression checks against the merge-only pre-fix snapshot reproduce
plugin/input, diagnostics, cleanup-observation and synchronous-parser
defects; the future-field check also fails before the allow-list fix.
- Smoke: real OpenCode **1.17.11**, `nvidia/nemotron-3-super-120b-a12b`,
Docker sandbox and stock math verifier. On runtime candidate
`68fd15170`, owned and borrowed episodes both score **1**, retain
tools/nonzero usage, carry message-ID headers on all three model calls,
and confirm cleanup before verification. The owned driver required
fixture/capture-path corrections; evidence was retained and the
successful episode was audited without a score-driven rerun.
- Post-merge borrowed smoke also passes: **reward 1**, **3/3 correlated
model calls**, **24,214 tokens**, tool-written answer, paired tool
output, retained observations and confirmed cleanup before verification.
Resources destroys the borrowed sandbox; task-scoped inventory is empty
after the run. The earlier pre-merge smoke also passed (24,262 tokens);
neither was rerun for score selection.
- These are bounded functional checks, not SWE-Pro accuracy validation.
Full current-head CI and maintainer approval remain separate gates; no
CI trust-gate authorization is implied.

<details>
<summary>Earlier benchmark evidence (not rerun on this head)</summary>

At `da85bf9ef` (documentation-only follow-up `52d8e12df`), the HSG
SWE-Pro smoke completed official grading with **reward 0**, **161/178
tests passed**. The model hit its output limit without producing a
patch. Existing direct/local and borrowed-sandbox smoke evidence remains
revision-pinned in the PR history; it is not a score baseline for this
revision.

</details>

---------

Signed-off-by: yaoyu-33 <[email protected]>

This branch was previously deployed

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

Labels

area:agent Agent harnesses and Responses API agent behavior bug Something isn't working complexity:low Localized change in one scope with a small, straightforward review surface needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants