Skip to content

feat(deepswe_external1): serve episode sessions and run OpenCode through single_agent_turn - #5815

Merged
yaoyu-33 merged 8 commits into
mainfrom
yuya/deepswe-external1-sessions
Nov 12, 2026
Merged

yaoyu-33 merged 8 commits into
mainfrom
yuya/deepswe-external1-sessions

Conversation

@yaoyu-33

@yaoyu-33 yaoyu-33 commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

deepswe_external1 (self-contained DeepSWE rows) only served the agent-run seed: its sandbox lived in a cookie-keyed map that only verify, a re-seed or shutdown released, so it could not run under an Environment Server, and an episode that never reached verify held its sandbox until shutdown. This PR moves it onto the shared SandboxSessionResourcesServer base (resources_servers/swebench/sandbox_sessions.py, the one swe_gym and r2e_gym use) and switches its OpenCode config to opencode_agent sessions under single_agent_turn.

Server (resources_servers/deepswe_external1/app.py)

  • An episode seed (ResourcesSeedSessionRequest) validates task_data as the row's TaskData (422 when invalid), starts the agent sandbox and lends it as sandbox_access with an operate-scoped descriptor and the row's workdir (/app or /workspace/repo). Repeating the seed for the same episode and task returns the same sandbox.
  • verify runs inside the base's verify wrapper: it collects the committed patch, stops the agent sandbox, and grades in a fresh verifier sandbox as before. An identical retry replays the verdict; a verify of another task is refused with 409; a verify after close is masked as session_lost.
  • /close_session is the base's: it stops the agent sandbox if verify did not (a failed stop raises and keeps the sandbox for a retried close) and fences later seeds. Episode sessions that are never closed expire with the sandbox's ttl_s.
  • The agent-run seed still returns sandbox_handle / sandbox_descriptor for the relay. Both kinds of seed now register the sandbox with the base, so verify, close and shutdown stop it; the server's own shutdown hook is gone. Only an episode session also expires: an agent-run seed that never reaches verify keeps its sandbox until a re-seed or shutdown, and the provider reclaims it after ttl_s. An agent-run seed cannot replace an episode session (409), and a flat row that names a resources_session_id must validate as an episode seed (422).
  • A verifier sandbox started for a session is registered with it until released, so close or shutdown stops one a request could not. Verify tries that stop twice before it builds the verdict, so cleanup_errors names the verifier only when it is still running.
  • The episode capture keeps the agent sandbox's ID with the patch, so a verify retried after a cancellation reports the same agent_sandbox_id and still refuses a verifier that reuses the agent sandbox.
  • Golden- and null-patch validation stop their sandboxes with a shielded, bounded stop, so a cancelled request no longer leaves them to the provider's ttl_s.
  • Golden- and null-patch validation grade as before; they refuse episode seeds with 422 (was a 500 RuntimeError).
  • The class is DeepsweExternal1ResourcesServer(DeepSWEResourcesServer, SandboxSessionResourcesServer): DeepSWE supplies collection and grading, the base the session lifecycle. close_resources_session is pinned to the base, so a session lifecycle added to DeepSWEResourcesServer later cannot take over these sessions.

Configs

  • configs/deepswe_external1_opencode.yaml now runs opencode_agent through single_agent_turn (rows reach it through the deepswe_external1 taskset), following the naming of feat(swe): run the SWE OpenCode configs through single_agent_turn and keep the relay configs as *_legacy_agent #5762.
  • The relay config is kept as configs/deepswe_external1_opencode_legacy_agent.yaml with a deprecation note. Nothing else in the repository cited the old file.
  • single_agent_turn admits 8 episodes at a time (max_concurrent_episodes, matching opencode_agent's default concurrency), queues the rest for up to a week, and gives each episode 18,000 s (default_episode_timeout_seconds), the sandbox's ttl_s. Without this, every dispatched row seeded its sandbox at once and held it while waiting for an OpenCode slot, and the 6 h episode default outlived the sandbox's ttl_s.
  • The README documents both configs, and that on providers that enforce the network policy the agent sandbox denies network except the model host, so opencode_agent needs its whole offline bundle pinned (sandbox_executable_*, sandbox_ripgrep_*, sandbox_plugin_dependencies_*) or images with the runtime cached at /tmp/nemo-gym-opencode-runtime-<opencode_version>.

Relation to #4560. #4560 (draft) moves deepswe itself to agent sessions with its own session code. This PR does not depend on it and does not touch resources_servers/deepswe. I did not stack on it: #4560's branch is about 600 commits behind main and conflicts in nine files, mostly in opencode_agent, where main has since added sandbox_executable_path and the task-HOME hook for tool shells. If #4560 later moves deepswe onto the same base, this subclass needs no change.

Issue

No public issue. This is the deepswe_external1 part of the resources-session migration of the SWE servers (the deepswe part is #4560).

Compatibility

  • deepswe_external1_opencode.yaml now starts opencode_agent + single_agent_turn instead of opencode_sandboxed_agent + legacy_agent. Runs that need the relay use deepswe_external1_opencode_legacy_agent.yaml; overrides of deepswe_external1_opencode_sandboxed_agent.* belong with that file.
  • Rows collated with the new config are materialized tasks with the deepswe_external1 taskset, routed through environment_server_routes.
  • Resources-server overrides for the new config target deepswe_external1_resources_server; the relay config keeps deepswe_external1_opencode_resources_server.
  • The new config does not set token_id_capture: true (the relay preset did), like the other opencode_agent session presets on main. Training runs set token_id_capture.all_agents=true or override the agent.
  • The new config runs at most 8 episodes at a time; raise max_concurrent_episodes together with opencode_agent.concurrency to run faster.
  • Grading, the reward and the failure kinds are unchanged; the two harnesses are configured differently, so do not compare their scores as one measurement. These differences live in the shared opencode_agent, not in this server or config, so this PR leaves them: no 1 h cap per model call (opencode_agent sends "timeout": false and accepts only permission and tools in opencode_config), no remaining_context, no host artifacts_dir, and the compaction / agent / title keys refused. execution_failure_reward_zero is not a difference: the relay preset leaves it false.

Validation

  • pytest resources_servers/deepswe_external1/tests resources_servers/deepswe/tests tests/unit_tests/test_session_contract_repo.py: 247 passed (primary venv with this worktree on the path). The verifier-ownership, cancellation, retry and validation-cancellation tests each fail with their fix reverted. New tests/test_sessions.py covers, through the HTTP routes with fake sandboxes: episode seed → sandbox_access → verify → replay → close → fenced seed → masked late verify; close without verify, with a failed stop retried; a verify of another task refused; failed agent cleanup masked with no verifier started; validation modes refusing episode seeds; the agent-run seed path; and check_resources_session_contract with verify_body. Existing tests now seed through the base's registry.
  • gym env validate on deepswe_external1.yaml, deepswe_external1_opencode.yaml and deepswe_external1_opencode_legacy_agent.yaml: valid (the policy_model reference warning is expected without a model config).
  • pre-commit run on the changed files: passed.

Rollouts

Real-model pairing runs of configs/deepswe_external1_opencode.yaml at 0dc538e on a workstation's Docker, on the public example actionlint-action-pinning-lint (Go, 55 FAIL_TO_PASS / 145 PASS_TO_PASS tests). They predate the admission settings and the verify/cleanup fixes above, which only unit tests cover so far.

  • Model and harness. nvidia/nemotron-3.5-super-vl-120b-a12b through a hosted endpoint and Gym's vllm_model server, thinking off, max_output_tokens 16,384 and a 1,200 s agent timeout. Collection used gym env start + gym eval run --no-serve --limit 1, with servers on the docker0 address.
  • The config ran as committed, with the stock Docker provider config and the task's own image. The Docker provider does not enforce the agent sandbox's network policy, so opencode_agent downloaded OpenCode 1.17.11 at seed. On a provider that enforces it, set sandbox_executable_path as the README says.
Run Request order seen by the servers Result Sandboxes
Full episode /seed_session → /v1/agent_sessions (borrowing the task sandbox) → (agent turn, 91 model calls) → /v1/agent_sessions/close → /verify → /close_session 0.0, evaluation_completed: true, mask_sample: false; FAIL_TO_PASS 0/55, PASS_TO_PASS 145/145, verifier exit 0, cleanup_errors: [] agent sandbox stopped by verify after collection, then a fresh verifier sandbox; none left after shutdown
Sandbox killed after the first model call /seed_session → /v1/agent_sessions → /v1/responses 500 (OpenCode launch outcome is unknown) → /v1/agent_sessions/close 500 → /close_session non-terminal environment_server_failed, no /verify, no reward none left
Sandbox killed 25 s in, during OpenCode's install /seed_session → /v1/agent_sessions 500 → /v1/agent_sessions/close 500 → /close_session non-terminal environment_server_failed, no /verify, no reward none left

Why the full episode scored 0. This is the task's own result, not a lifecycle failure. The agent branched, wrote the rule, its tests and config parsing, and ran go test. Its last model call then hit the 16,384-token output cap (finish_reason: length), so OpenCode ended the turn (incomplete) before the agent committed. The task prompt says to commit everything, and collection takes only committed changes (README, "Verification contract"). The captured patch is therefore empty (0 bytes), and the base tree fails FAIL_TO_PASS.

In the interrupted runs the sandbox is the task's, lent to the agent. Once it was gone, opencode_agent could not remove its session files from it, so its close returned 500 and it kept the session. single_agent_turn logged "Episode cleanup failed: agent session" and still sent /close_session, which released the task sandbox. That close behavior belongs to the shared agent-session code, not to this PR.

🤖 Generated with Claude Code

…ode through single_agent_turn

deepswe_external1 now serves the resources session contract on the shared
SandboxSessionResourcesServer base: a typed seed starts the agent sandbox and lends it
as sandbox_access, verify grades it once and replays the verdict on an identical retry,
close stops the sandbox if verify did not and fences later seeds, and abandoned sessions
expire with the sandbox's ttl_s. The agent-run seed keeps returning the sandbox handle for
the legacy_agent relay; both kinds of seed register their sandbox with the base, so
close, expiry and shutdown stop it. Golden/null validation is unchanged and refuses
episode seeds with 422.

deepswe_external1_opencode.yaml now runs opencode_agent through single_agent_turn; the
relay config is kept as deepswe_external1_opencode_legacy_agent.yaml with a deprecation
note.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 8, 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.

@yaoyu-33

yaoyu-33 commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 0dc538e

@svcnvidia-nemo-ci svcnvidia-nemo-ci added feature New capabilities, enhancements, or enablement work area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers labels Nov 8, 2026
…eview fixes

- Admit OpenCode episodes at the agent's rate (max_concurrent_episodes 8, a queue timeout) and keep the
  episode deadline within the sandbox ttl_s, so queued rows no longer each hold a seeded sandbox while
  waiting for an OpenCode slot.
- Refuse a seed body that names a resources_session_id but is not a valid episode seed (422) instead of
  starting an agent-run sandbox, with reject_partial_typed_seed on the agent-run arm.
- Drop the unused _stop_sandbox override.
- Say that only episode sessions expire, and that a failed agent-sandbox stop is masked and replayed.
- List the whole opencode_agent offline bundle (binary, ripgrep, plugin dependencies) in the README.
- Test verifier ownership: a failed verifier stop retried by the verify wrapper and by close, and a
  cancelled verify that stops both sandboxes and regrades the saved patch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

yaoyu-33 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test ac349ed

yaoyu-33 and others added 2 commits November 8, 2026 21:59
…d cancellation

- Save the agent sandbox's ID with an episode's captured patch, so a verify retried
  after a cancellation reports it and still refuses a verifier that reuses it.
- Try a session verifier's stop twice before building the verdict, so cleanup_errors
  names the verifier only when it is still running.
- Shield and bound the stop of golden- and null-validation sandboxes, so a cancelled
  request does not leave them to the provider's ttl_s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

yaoyu-33 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 5323648

@yaoyu-33 yaoyu-33 changed the title feat(deepswe_external1): serve typed resources sessions and run OpenCode through single_agent_turn feat(deepswe_external1): serve episode sessions and run OpenCode through single_agent_turn Nov 9, 2026
@yaoyu-33
yaoyu-33 marked this pull request as ready for review November 9, 2026 20:30

@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

I found two RISK issues: session ownership becomes visible too late during sandbox setup, and the documented cached-runtime alternative is incomplete for offline execution. One NOTE covers stale cleanup diagnostics.

I inspected all seven changed files and traced the affected session, sandbox, environment and agent contracts. This was a read-only source review; I didn't execute tests or rollouts.

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

"""Start and set up the agent sandbox for a task row, and return the repository the agent works in."""
data = TaskData.model_validate(task)
self._forget_task_sandbox_state(session_id)
sandbox = await self._create_sandbox(InlineTask(data), phase="agent")

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.

RISK — Register session-owned sandboxes before startup/setup awaits.

If an episode seed disconnects during image setup, _create_sandbox() hasn't returned, so the assignment below this line never runs. After provider creation, start_with_setup attempts an unshielded stop when setup is cancelled; that stop can itself be cancelled. The outer failed-seed cleanup then finds no registered sandbox and drops the record. Close and shutdown cannot recover it. A setup exception followed by a failed stop has the same result. The new session-verifier registration has the same ordering problem during verifier setup. The helper weakness predates this PR, but the newly added session-owned paths don't satisfy their cleanup contract.

Could you make ownership visible before start_with_setup? A focused correction, following SWE Gym's allocation pattern, is to add keyword-only session_id: str | None = None and verifier_session_id: str | None = None parameters to _create_sandbox, then insert immediately after constructing AsyncSandbox:

if session_id is not None:
    self._session_id_to_sandbox[session_id] = sandbox
if verifier_session_id is not None:
    self._verifier_sandboxes[verifier_session_id] = sandbox

Pass session_id=session_id from _start_task_sandbox. Pass verifier_session_id=session_id if mode == "agent" else None from _verify_task's verifier allocation. Remove the redundant post-return registrations and update the allocation fakes to accept and honor these keywords. Keep failed stops registered for the existing shielded cleanup and later close. Please verify this suggested change before adopting it.

Acceptance — proposed, not executed: use a real AsyncSandbox with a fake provider whose create succeeds, suspend agent setup, then cancel the request's AnyIO scope. Cleanup must stop the sandbox. Repeat during verifier setup. For setup errors whose cleanup keeps failing, assert that the appropriate registry retains the handle and a later close stops it. Preserve successful seed replay without another allocation, the operate-scoped handoff, flat-seed descriptor preservation, failed-close retry, and golden/null grading without session registration.

(`sandbox_ripgrep_path`, `sandbox_ripgrep_sha256`) and the plugin dependencies
(`sandbox_plugin_dependencies_path`, `sandbox_plugin_dependencies_sha256`), each a
file already inside the sandbox, for example on a mounted cache. Alternatively, use
task images that hold the runtime at `/tmp/nemo-gym-opencode-runtime-<opencode_version>`

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.

RISK — Cached OpenCode and rg don't replace the plugin-dependency bundle.

On a provider enforcing the model-only network policy, the advertised alternative—cache OpenCode under /tmp/nemo-gym-opencode-runtime-<opencode_version> and put rg on PATH—still cannot run offline without sandbox_plugin_dependencies_*. The agent creates a fresh private config directory, stages dependencies only when those fields are set, and always configures the task-environment plugin. The agent's documented contract states that each fresh config downloads plugin dependencies without the bundle; offline, installation fails.

Could you replace the alternative with: “Alternatively, cache the OpenCode binary at /tmp/nemo-gym-opencode-runtime-<opencode_version> and put rg on PATH; still set sandbox_plugin_dependencies_path and sandbox_plugin_dependencies_sha256 to populate each session's private config directory.” Apply the same correction to the config comments. This preserves both binary-install choices while keeping plugin dependencies mandatory offline; no shared-agent change is needed.

Acceptance — proposed, not executed: on a network-enforcing provider, use the matching cached binary and rg plus the pinned plugin-dependency archive. A minimal model turn should initialize the task-environment plugin without GitHub/npm downloads and reach verification. Preserve the fully pinned bundle option. Statically check that neither document describes cached binary plus rg alone as sufficient.

if verifier_sandbox is not None:
if not await self._release_sandbox(verifier_sandbox, task_id=task_id, phase="verifier"):
if mode == "agent":
if not await self._stop_session_verifier(session_id, task_id=task_id):

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.

NOTE — Suggestion: reconcile diagnostics after the wrapper's final cleanup.

With verifier stop outcomes [RuntimeError("down"), RuntimeError("down"), None], _stop_session_verifier() exhausts its two attempts and records "verifier" in cleanup_errors. The shared verify wrapper then attempts another stop, which succeeds before the HTTP response returns. Nevertheless, the response, saved replay and result.json still report cleanup_errors: ["verifier"]. This conflicts with the helper's stated meaning that the entry identifies a verifier still running after cleanup. The impact is misleading diagnostics, not an incorrect reward.

Could you reconcile the returned and persisted diagnostics after the wrapper's final stop, or arrange for cleanup to finish before building the verdict? The exact implementation needs to account for both the shared wrapper and the result-file write; increasing the helper's retry count alone leaves the same ordering problem. Preserve completed grades regardless of cleanup failures, ownership when every stop fails, and identical verdict replay.

Acceptance — proposed, not executed: add the two-failures-then-success case to the verifier-stop tests. Expect reward 1.0, mask_sample: false, no owned verifier, and cleanup_errors: [] in the response, identical retry and persisted result. Retain the first-failure-then-success case and the three-failures case, which must retain cleanup_errors: ["verifier"] and ownership until close succeeds.

@yaoyu-33

yaoyu-33 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 94c1c0e

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 9, 2026 20:58
Clean session-owned verifiers even when setup fails before allocation returns. Preserve cleanup diagnostics in the masked response, replay, and saved result while retaining ownership for a later close.

Validation on ws: 252 focused DeepSWE and session-contract tests passed; pre-commit run --all-files passed. The setup-failure regression fails against the parent revision. No new model rollout: this follow-up covers failed setup and teardown diagnostics, with grading and model interaction unchanged.

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

Copy link
Copy Markdown
Contributor Author

/ok to test 0af9f82

@yaoyu-33

Copy link
Copy Markdown
Contributor Author

/review

@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

The two prior RISK findings and the NOTE are fixed in the current source:

I compared the follow-up changes with the previously reviewed head and traced the affected sandbox, session, replay and OpenCode contracts, including the relevant regression tests. No unresolved prior findings or eligible introduced regressions remain. This was a scoped, read-only follow-up, not a fresh whole-PR review; I didn't execute tests or rollouts.

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

@init-nikhil init-nikhil left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this mostly looks good to me. One small change you can have your agent make:

If shutting down the agent sandbox fails, we can retry the shutdown and then proceed with verification, like some of the other SWE resource servers do.

@init-nikhil init-nikhil left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, the shutdown retry addresses my request. Looks good to me.

@yaoyu-33
yaoyu-33 enabled auto-merge November 12, 2026 06:51
@yaoyu-33

Copy link
Copy Markdown
Contributor Author

/ok to test 81a97ac

@github-actions

Copy link
Copy Markdown
Contributor

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

Merged via the queue into main with commit c26b83c Nov 12, 2026
62 of 64 checks passed
@yaoyu-33
yaoyu-33 deleted the yuya/deepswe-external1-sessions branch November 12, 2026 07:16

This branch had an error being deployed

1 failed deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers feature New capabilities, enhancements, or enablement work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants