feat(mini_swe_env): add SWE-Gym async GRPO environment with Pi interception and HF Space deployment
Summary
This PR adds a new mini_swe_env and a complete async RL training path for SWE tasks: Pi agent in sandbox, host-side interception, vLLM generation, and Async GRPO updates. It is self-contained for review against feat/multi-harness and supports both direct black-box rollouts and interception-driven async training. The goal is to make SWE-Gym-style training runnable end-to-end on local Docker and HF Space + HF Sandbox.
Type of Change
- [ ] Bug fix
- [x] New feature
- [ ] Breaking change
- [x] Documentation
- [x] New environment
- [x] Refactoring
Alignment Checklist
Before submitting, verify:
- [x] I have read
.claude/docs/PRINCIPLES.mdand this PR aligns with our principles - [x] I have checked
.claude/docs/INVARIANTS.mdand no invariants are violated - [x] I have run
/pre-submit-pr(orbash .claude/hooks/lint.shand tests) and addressed all issues
What this PR does (self-contained)
1) Adds a new SWE environment package
New package: envs/mini_swe_env/
- SWE task models + SWE-Gym loader (
models.py,task_loader_swegym.py) - host-side grading (
grading.py) with binary resolved/not-resolved semantics - harness integration (
harness.py) for Pi/OpenCode sessions - server + MCP environment (
server/swe_environment.py,server/app.py) - client (
client.py) and env package metadata (pyproject.toml,uv.lock)
2) Supports both rollout modes needed by SWE workflows
black_boxmode: agent calls upstream LLM directlyinterception_gatemode: trainer owns generation + logprob capture
3) Adds async GRPO control plane + rollout worker
New modules in envs/mini_swe_env/async_grpo/:
control_plane.py— starts/owns interception server lifecyclerollout_worker.py— custom worker implementing TRL rollout protocol- consumes intercepted chat requests
- tokenizes with
apply_chat_template - calls vLLM
/v1/completionswithreturn_token_ids=True,logprobs=0 - delivers chat responses back to Pi
- assembles
input_ids,completion_mask,old_log_probsfor trainer
4) Adds runnable training/examples and HF Space deploy path
examples/mini_swe_env/train_swe_async_grpo.pyexamples/mini_swe_env/run_swe_sample.py- HF Space app assets:
envs/mini_swe_env/async_grpo/space_app/Dockerfileenvs/mini_swe_env/async_grpo/space_app/start.shenvs/mini_swe_env/async_grpo/space_app/deploy_hf_space.shenvs/mini_swe_env/async_grpo/space_app/README.md
5) Core harness compatibility updates used by this env
src/openenv/core/harness/agents/cli_driver.pyupdated for interception + queue handling needed by async rollouts.
Execution modes
| Area | black_box mode |
interception_gate mode |
|---|---|---|
| Agent LLM calls | Direct to upstream provider | Routed through host InterceptionServer |
| Training signal | No token/logprob capture | Exact token IDs + logprobs captured via vLLM |
| Main use | Eval / smoke / demos | Async GRPO training |
| Host tools | Optional | Required (answer host-side) |
| Endpoints | provider-specific | /rollout/{id}/v1/chat/completions, /rollout/{id}/v1/tools/answer, internal vLLM /v1/completions |
Network diagram (async training path)
flowchart LR
subgraph SPACE[HF Space / Trainer Host]
IS["InterceptionServer<br/>0.0.0.0:7860<br/>/rollout/:rollout_id/v1/chat/completions<br/>/rollout/:rollout_id/v1/tools/answer"]
RW["SWERolloutWorker<br/>threads + queues"]
TR["AsyncGRPOTrainer"]
VLLM["vLLM<br/>127.0.0.1:8000<br/>/v1/completions"]
IS <--> RW
RW --> TR
RW <--> VLLM
TR -. weight sync .-> VLLM
end
SB["Sandbox (HF or Docker)<br/>Pi agent + /testbed"] -->|chat completion request| IS
SB -->|answer tool call| IS
RW -->|create/exec/kill sandboxes| HFAPI["HF Sandbox API"]
black_box mode at a glance
Pi agent (sandbox) -> upstream LLM directly
verify() runs at end; no host-side token/logprob interception loop
Reward and grading integrity
- Reward source is host-side grading path.
answer()is routed to host tool handler (not sandbox-owned grader).- Grading uses SWE-Gym-style case outcomes (
FAIL_TO_PASS,PASS_TO_PASS) with binary reward1.0/0.0. - This keeps reward authority on host and aligns with OpenEnv invariants.
[!NOTE] This PR depends and should be merged after #694
CC: @burtenshaw
Greptile Summary
This PR introduces a new mini_swe_env package for SWE-Gym-style RL training, along with an async GRPO control plane, an InterceptionServer that gates agent LLM calls for trainer-owned generation, and HF Space deployment tooling. It also promotes opencode_env to coding_agent_env and migrates shared agent/sandbox infrastructure into src/openenv/core/.
- New
mini_swe_env:SWEEnvironment(MCP),SWERolloutWorker(TRLRolloutWorkerProtocol), host-sideanswer()grading, SWE-Gym task loader, and a Docker/HF Space deploy path. - New core infrastructure:
InterceptionServer,CLIAgentDriver,HFSandboxBackend,DockerSandboxBackend, and a newagents/subpackage added tosrc/openenv/core/without a covering RFC. - Three mechanical issues require fixes before merge: shell injection in the deploy script, bare
assertremoval under-O, and a TOCTOU race in the weight-sync path.
Confidence Score: 3/5
The deploy script has an exploitable shell injection path, and the rollout worker has two defects in the weight-sync path that can silently pass None into the NCCL engine; three alignment questions also need human sign-off.
Shell injection in deploy_hf_space.sh is a present, exploitable code path via CLI argument interpolation with no escaping. The TOCTOU race in send_weights and bare assert removal under -O are both present defects in the critical weight-sync path. Three alignment questions (host-side grading, missing generics, core changes without RFC) each require explicit human decisions before these patterns become load-bearing in downstream training code.
deploy_hf_space.sh (shell injection), rollout_worker.py (weight-sync race and assert removal), swe_environment.py and client.py (missing generics), harness.py (host-side grading alignment)
Security Review
- Shell injection (
deploy_hf_space.shlines 83\u2013100, 181\u2013187): space ID and hardware tier from CLI arguments are interpolated intopython3 -cstrings; a crafted value executes arbitrary Python on the deploy host. - Token in Python string literal (same file, lines 84, 95): auth token is shell-expanded inside single-quoted Python string; corrected pattern using
os.environis already present in the heredoc section. - No credential exposure found in Python source; secrets are read from environment variables and never logged.
Important Files Changed
| Filename | Overview |
|---|---|
| envs/mini_swe_env/async_grpo/rollout_worker.py | New 736-line rollout worker; TOCTOU race on _model_update_group and bare asserts stripped by -O in the weight-sync path |
| envs/mini_swe_env/async_grpo/space_app/deploy_hf_space.sh | Deploy script with shell injection via $SPACE_ID and $HARDWARE interpolated into python3 -c strings |
| envs/mini_swe_env/server/swe_environment.py | SWEEnvironment extends MCPEnvironment without generic type parameters, violating the Environment[ActT, ObsT, StateT] invariant |
| envs/mini_swe_env/harness.py | Host-side grading via answer() conflicts with the Rewards-in-environment invariant; references missing CORE_CHANGES.md |
| src/openenv/core/harness/agents/interception_server.py | New aiohttp interception server; hmac auth correct; significant core addition without RFC |
| src/openenv/core/harness/agents/cli_driver.py | New CLI agent driver for black_box/interception_gate modes; well-structured; core addition without RFC |
| envs/mini_swe_env/grading.py | Clean binary grading module; correctly implements FAIL_TO_PASS/PASS_TO_PASS semantics |
| envs/mini_swe_env/models.py | Well-designed frozen dataclasses and Pydantic wire types; SWEState correctly extends State |
| envs/mini_swe_env/async_grpo/control_plane.py | Clean control plane with rollout registration and context-manager support; no issues found |
| envs/mini_swe_env/client.py | Typed MCP client; no server imports; missing EnvClient generic parameterization |
Sequence Diagram
sequenceDiagram
participant SB as Pi Agent Sandbox
participant IS as InterceptionServer host:7860
participant RW as SWERolloutWorker
participant vLLM as vLLM /v1/completions
participant TR as AsyncGRPOTrainer
SB->>IS: POST /rollout/id/v1/chat/completions
IS-->>RW: enqueue request_id
RW->>IS: get_intercept(request_id)
RW->>RW: apply_chat_template to prompt_ids
RW->>vLLM: POST /v1/completions token IDs
vLLM-->>RW: completion_ids and logprobs
RW->>IS: deliver_response intercept chat_resp
IS-->>SB: streaming SSE response
SB->>IS: POST /rollout/id/v1/tools/answer
IS->>RW: answer_handler grade_from_case_results
RW-->>IS: reward result
IS-->>SB: tool result
RW->>RW: assemble RolloutSample
RW->>TR: rollout_buffer.put sample
TR->>RW: send_weights via NCCL
RW->>vLLM: POST /update_weights
Prompt To Fix All With AI
Fix the following 7 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 7
envs/mini_swe_env/async_grpo/space_app/deploy_hf_space.sh:83-90
**Shell injection via CLI argument interpolation**
`$SPACE_ID` and `$HARDWARE` originate from `--space-id` / `--hardware` command-line arguments (attacker-controlled), and they are interpolated directly into a Python string passed to `python3 -c`. A crafted `--space-id` value can execute arbitrary Python. The heredoc section at line 125 correctly uses `os.environ` — the inline `-c` blocks (lines 83–90, 94–100, 181–187) should follow the same safe pattern.
### Issue 2 of 7
envs/mini_swe_env/async_grpo/rollout_worker.py:239-243
**Bare `assert` stripped by `-O` flag**
`assert NCCLWeightTransferEngine is not None` and `assert NCCLTrainerSendWeightsArgs is not None` are silently removed when Python is run with the `-O` flag. The code then calls `None.trainer_send_weights(...)`, raising a confusing `AttributeError`. Replace with explicit `if ... raise RuntimeError(...)` guards.
### Issue 3 of 7
envs/mini_swe_env/async_grpo/rollout_worker.py:202-225
**TOCTOU race between `send_weights` and `stop`**
The null-check on `_model_update_group` happens outside `_weight_sync_lock`, while `_destroy_model_update_group()` clears the field without acquiring that lock. A concurrent `stop()` can race to pass `None` into the NCCL engine. Move the null-check inside `_weight_sync_lock`, or have `_destroy_model_update_group` acquire it before clearing the field.
### Issue 4 of 7
envs/mini_swe_env/harness.py:41-44
**ALIGNMENT FLAG: Reward computation outside environment boundary**
- **Principle at stake**: "Rewards in environment" (INVARIANTS.md §Architectural Invariants 3)
- **The concern**: In `interception_gate` mode, `answer()` runs `grade_from_case_results` on the trainer host, not inside the containerized `SWEEnvironment`. The PR notes this is intentional, but it directly conflicts with the invariant.
- **Suggested reviewer**: `@darktex`
### Issue 5 of 7
envs/mini_swe_env/server/swe_environment.py:97
**ALIGNMENT FLAG: Missing `Environment[ActT, ObsT, StateT]` generics**
- **Principle at stake**: INVARIANTS.md §API Invariants 2
- **The concern**: `SWEEnvironment(MCPEnvironment)` carries no generic parameters; `MiniSWEEnv(MCPToolClient)` in `client.py` similarly omits `EnvClient[ActT, ObsT, StateT]`. This violates the type-safety invariant.
- **Suggested reviewer**: `@darktex`
### Issue 6 of 7
src/openenv/core/harness/agents/interception_server.py:73-75
**ALIGNMENT FLAG: Core changes without RFC**
- **Principle at stake**: INVARIANTS.md §Architectural Invariants
- **The concern**: `InterceptionServer`, `CLIAgentDriver`, two new sandbox backends, and a new `agents/` subpackage are added to `src/openenv/core/` without a covering RFC. The interception-gate pattern is a new architectural layer not discussed in RFC 001 or RFC 002.
- **Suggested reviewer**: `@darktex`
### Issue 7 of 7
envs/mini_swe_env/harness.py:31-44
**Missing `CORE_CHANGES.md` referenced in docstring**
The module docstring says "Requires core changes — see `CORE_CHANGES.md`" but this file is not included in the PR. Update the docstring to point to actual documentation.
Reviews (1): Last reviewed commit: "feat: deploy script for SWE Async GRPO t..." | Re-trigger Greptile
Thanks @AmineDiro for the detailed review. It helped me catch a few core issues. Addressing each point:
1. The weight-transfer
All
send_weights/pause/resume/_init_weight_transferNCCL setups are basically unreachable. Injecting a worker setsself.weight_transfer = Noneand skips every sync path so vLLM never receives updated weights.
I verified this, weight sync does happen. No code change needed, but I added a clarifying comment. The trainer's _sync_weight() calls self.rollout_worker.send_weights() regardless of injection, so my SWERolloutWorker.send_weights() is always reached. The hardcoded language_model. prefix remap is necessary due to a VLM param-name mismatch that TRL's default sync doesn't handle. I'll propose this fix upstream.
2. The loss is REINFORCE, not GRPO
advantage = reward = 0/1and you have no baseline, and no group-relative normalization.
Thank you for catching this, I already had this fixed but havent pushed yet. I implemented proper group-relative normalization: accumulate N rollouts per task, compute advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-8), exclude overflow/timeout samples. Bumped gradient_accumulation_steps to 4 and weight_decay to 0.1 to match Polar's hyperparameters.
3. Import helpers from TRL
Subtle logic in tool-suffix tokenization / multiturn handling / token length clamping is tricky. I would advise reusing the logic.
Fixed for suffix/template. I now import TRL's get_training_chat_template and is_chat_template_prefix_preserving, which resolved a silent bug where Qwen3.5's <think> tokens misaligned. For length clamping, I use progressive truncation before tokenization rather than post-hoc clamping.
Staleness: staleness handling matches Polar's approach for now but this results in wasted sandbox compute. I will visit this at a later revision.
Duplicated RolloutSample: TRL's version includes fields my pipeline doesn't use; my local version covers what RolloutQueueDataset actually reads, but I can update it as well if needed
Defensive scaffolding: Fair point. The getattr and try/except is higher than it should be — a lot of it accrued while debugging Qwen3.5-specific crashes. I will do a pass to tighten these up.
Reinvent turn-termination heuristics: The post_response_grace_s idle-stop is needed for remote sandboxes where process exit isn't synchronously observable. Documented inline.