OpenEnv icon indicating copy to clipboard operation
OpenEnv copied to clipboard

Fix coding_env API compatibility and safety reward false positives

Open abhinavgautam01 opened this issue 7 months ago • 12 comments

Summary

This PR fixes multiple coding_env reliability issues with a focus on API compatibility and reward correctness.
It aligns PythonCodeActEnv with expected optional reset/step parameters, removes duplicate server entrypoint execution blocks, and replaces regex-based safety checks with AST-based detection to prevent reward false positives.
It also adds focused tests for the new behavior and safety-detection edge cases.

Type of Change

  • [x] Bug fix
  • [ ] New feature
  • [ ] Breaking change
  • [ ] Documentation
  • [ ] New environment
  • [x] Refactoring

Alignment Checklist

Before submitting, verify:

  • [x] I have read .claude/docs/PRINCIPLES.md and this PR aligns with our principles
  • [x] I have checked .claude/docs/INVARIANTS.md and no invariants are violated
  • [ ] I have run /pre-submit-pr (or bash .claude/hooks/lint.sh and tests) and addressed all issues

RFC Status

  • [x] Not required (bug fix, docs, minor refactoring)
  • [ ] RFC exists: #___
  • [ ] RFC needed (will create before merge)

Test Plan

Reviewers can verify with:

# Lint / syntax checks for touched files
uv run ruff check envs/coding_env/server/python_codeact_env.py \
 envs/coding_env/server/app.py \
 envs/coding_env/server/transforms.py \
 envs/coding_env/server/__init__.py \
 tests/envs/test_python_codeact_reset.py \
 tests/envs/test_coding_safety_transform.py

uv run python -m py_compile \
 envs/coding_env/server/python_codeact_env.py \
 envs/coding_env/server/app.py \
 envs/coding_env/server/transforms.py \
 envs/coding_env/server/__init__.py \
 tests/envs/test_python_codeact_reset.py \
 tests/envs/test_coding_safety_transform.py

# Focused behavior tests
PYTHONPATH=src:envs uv run pytest tests/envs/test_python_codeact_reset.py -q
PYTHONPATH=src:envs uv run pytest tests/envs/test_coding_safety_transform.py -q
PYTHONPATH=src:envs uv run pytest tests/envs/test_coding_env_integration.py -q

abhinavgautam01 avatar May 02 '26 04:05 abhinavgautam01

Greptile Summary

This PR fixes three coding_env reliability issues: AST-based safety detection replaces regex to eliminate false positives from string literals and same-named user functions, PythonCodeActEnv.reset() gains the seed/episode_id/**kwargs signature required by the Gymnasium API contract, and the __init__.py module adopts a lazy import to decouple transforms from the optional smolagents runtime dependency.

  • transforms.py: CodeSafetyTransform now uses ast.walk to detect only direct builtin calls and top-level os/subprocess imports; attribute-method calls like db.exec() are no longer penalised. CodeQualityTransform broadened its ast.parse guard to (SyntaxError, RecursionError, ValueError).
  • python_codeact_env.py: reset() accepts seed, episode_id, and **kwargs for API compatibility; step() is restored to the canonical step(action) -> Observation signature from INVARIANTS.md.
  • __init__.py / app.py: Module-level lazy loading via __getattr__ and an import reorder in app.py.

Confidence Score: 5/5

Safe to merge — all previously-identified bugs are resolved and the core transform/env logic is correct.

The two previous out-of-diff findings (CodeQualityTransform crash on deeply-nested code and the dead timeout_s parameter in step()) are both fixed in the current code. The remaining comments are style-level and do not affect runtime correctness.

No files require special attention for correctness; tests/envs/test_coding_safety_transform.py is worth a second look for CI portability.

Important Files Changed

Filename Overview
envs/coding_env/server/init.py Switched to lazy __getattr__-based import to avoid pulling in optional smolagents dependency; the resolved class is not cached on the module, so __getattr__ fires on every attribute access rather than only the first.
envs/coding_env/server/app.py Import reordering only — openenv.core.env_server moved before local coding_env imports; no functional change.
envs/coding_env/server/python_codeact_env.py Added seed, episode_id, and **kwargs to reset() for Gymnasium API compatibility; step() signature restored to the canonical step(action) -> Observation; both changes align with INVARIANTS.md.
envs/coding_env/server/transforms.py Replaced regex-based safety detection with AST-based _detect_violation; broadened CodeQualityTransform exception guard to include RecursionError and ValueError; both previous P1 findings are resolved.
tests/envs/test_coding_safety_transform.py New test file covering safety-transform false positives and recursion-error handling; missing the sys.path bootstrap used by the sibling test, so it silently breaks without PYTHONPATH=src:envs.
tests/envs/test_python_codeact_reset.py Added two new reset tests for episode_id override and empty-string preservation; both correctly exercise the new guard in python_codeact_env.py.

Sequence Diagram

sequenceDiagram
    participant Orch as Orchestrator
    participant Env as PythonCodeActEnv
    participant Exec as PyExecutor
    participant ST as CodeSafetyTransform
    participant QT as CodeQualityTransform

    Orch->>Env: "reset(seed?, episode_id?, **kwargs)"
    Env->>Exec: PyExecutor() (fresh instance)
    Env->>ST: create_safe_coding_transform()
    Env-->>Orch: "CodeObservation(reward=0.0)"

    Orch->>Env: "step(CodeAction(code=...))"
    Env->>Exec: run(code)
    Exec-->>Env: ExecutionResult(stdout, stderr, exit_code)
    Env->>ST: __call__(obs + last_code metadata)
    Note over ST: ast.parse to _detect_violation()
    ST-->>Env: "obs(reward=-1.0 or 0.0)"
    Env->>QT: __call__(obs)
    QT-->>Env: obs(reward adjusted)
    Env-->>Orch: CodeObservation
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
tests/envs/test_coding_safety_transform.py:9-10
**Test missing sys.path bootstrap — breaks without explicit PYTHONPATH**

The sibling test `test_python_codeact_reset.py` guards against missing path setup with `sys.path.insert(...)` for the repo root plus `src/`, then uses the fully-qualified prefix `envs.coding_env.*`. This file uses the short form `coding_env.*`, which works only when the runner sets `PYTHONPATH=src:envs`. Running bare (`pytest tests/`) or in a CI job that doesn't set that variable produces an `ImportError`, while the sibling test still passes. Following the same bootstrap pattern would make the suite self-contained.

### Issue 2 of 2
envs/coding_env/server/__init__.py:18-23
**Lazy loader doesn't cache the resolved class — `__getattr__` fires on every access**

The current implementation returns `PythonCodeActEnv` on each call to `__getattr__` but never writes it back onto the module. Any code that repeatedly accesses `coding_env.server.PythonCodeActEnv` as an attribute (rather than a one-time `from … import`) will re-execute the `__getattr__` body on each access. The standard fix is to set the resolved name on the module after the first load, turning subsequent lookups into a direct `__dict__` hit.

```suggestion
def __getattr__(name: str) -> Any:
    if name == "PythonCodeActEnv":
        from .python_codeact_env import PythonCodeActEnv
        import sys

        setattr(sys.modules[__name__], name, PythonCodeActEnv)
        return PythonCodeActEnv
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
```


Reviews (7): Last reviewed commit: "Harden coding env quality transform" | Re-trigger Greptile

greptile-apps avatar May 02 '26 04:05 greptile-apps

@greptile review

abhinavgautam01 avatar May 13 '26 19:05 abhinavgautam01

@greptile review

abhinavgautam01 avatar May 13 '26 19:05 abhinavgautam01

@greptile review

abhinavgautam01 avatar May 13 '26 20:05 abhinavgautam01

@greptile review

abhinavgautam01 avatar May 14 '26 02:05 abhinavgautam01

@greptile review

abhinavgautam01 avatar May 14 '26 02:05 abhinavgautam01

@greptile review

abhinavgautam01 avatar May 14 '26 02:05 abhinavgautam01

ping @Darktex

abhinavgautam01 avatar May 18 '26 06:05 abhinavgautam01

@greptile review

abhinavgautam01 avatar Jun 13 '26 16:06 abhinavgautam01

@Darktex thanks for checking. Confirmed there are no blocking issues left from this review. The episode_id point is an alignment note only: reset(seed, episode_id, **kwargs) mirrors the base Environment API and is intended for infrastructure/orchestration callers, not agent-facing MCP tools. The AST detector edge cases are acknowledged as non-regressions and the transform is documented as a reward heuristic rather than a security sandbox...

abhinavgautam01 avatar Jun 14 '26 08:06 abhinavgautam01

@Darktex i checked these against the PR head and i don’t think code changes are needed here...

test_coding_safety_transform.py does not require smolagents: coding_env.server.__init__ is lazy and importing coding_env.server.transforms does not import python_codeact_env or python_executor. I verified this in an environment where smolagents is absent and the transform test file collects and passes.

app.py also has a single if __name__ == "__main__": guard at the current PR head.

For the import style, the new transform test intentionally uses the standard PYTHONPATH=src:envs package import and avoids the local sys.path mutation pattern that earlier review feedback asked us to remove...

abhinavgautam01 avatar Jun 14 '26 16:06 abhinavgautam01

thanks @Darktex , i addressed the valid cleanup items: removed the _parse_code test seam, patched ast.parse directly in the test, made the .open( fallback explicit and documented empty episode_id behavior.

i also rechecked app.py on the PR head: it has exactly one if __name__ == "__main__" guard, and uv run usort check envs/coding_env/server/app.py passes with the current import order, so i did not change that file.

Could you also take one manual pass without the automated review loop? If there is still a real blocker, I’ll address it; otherwise, if this PR is no longer worth continuing, please let me know whether you’d prefer i close it...

abhinavgautam01 avatar Jun 15 '26 08:06 abhinavgautam01