Conversation
smolagents' LocalPythonExecutor is an AST interpreter inside the server process, so imported classes and module state are shared by every executor in that process. Changes made by one episode's code survived reset() and were visible to other sessions. Each PythonCodeActEnv now runs its PyExecutor in a dedicated worker process (IsolatedPyExecutor). reset() replaces the worker and close() stops it. The worker gets a minimal environment without the server's variables, runs as nobody when the server is root, is non-dumpable on Linux, and talks to the server with bounded JSON only. A step that runs past CODING_ENV_EXEC_TIMEOUT_S (default 30) kills only that session's worker. With no shared interpreter state left, the env declares SUPPORTS_CONCURRENT_SESSIONS and the app reads MAX_CONCURRENT_ENVS (default 8).
There was a problem hiding this comment.
Stale comment
Alignment Review Report
Automated Checks
- Lint: PASS —
usort check,ruff format --check, andruff checkall pass onsrc/andtests/(ranbash .claude/hooks/lint.shafteruv sync --all-extras).- Debug code: CLEAN —
bash .claude/hooks/check-debug.shonly flags pre-existingprint()/TODOlines in files this PR does not touch (src/openenv/core/containers/test_local_docker_provider.py,providers.py,harness/*,env_client.py,mcp_client.py). Nothing inenvs/coding_env/**or the new test file.Open RFCs Context
- RFC 002 (
env-spec, In Review) defines Security Invariants S1–S6 for Cloud Sandbox Providers executing untrusted code, including S5 "No command injection" and S6 "Bounded blast radius" (CPU/memory/disk limits). This PR runs untrusted model code too, just via a local worker process rather than aContainerProvider, so these invariants are a relevant lens even though not formally binding oncoding_env.- RFC 005 (Agentic Harness Integration, In Review) covers a related isolation-boundary problem (harness tool bridges reaching the local network namespace) but scopes to harnesses, not plain code-exec environments — no direct conflict.
- No Draft/In Review RFC proposes an alternative session/process isolation model for
coding_env, so this doesn't preempt an open design discussion.Tier 1: Fixes Required
None. Specifically verified:
- No lint failures or debug/print/breakpoint code introduced.
- No missing imports/syntax errors —
envs/coding_envinstalls and imports cleanly (smolagentsbumped to>=1.24.0, consistent with the newtimeout_secondspassthrough it requires).- No credential exposure:
WORKER_ENV_ALLOWLISTexplicitly restricts what the worker inherits from the server, exercised bytest_server_secrets_are_not_visible_to_model_code.- No command/code injection: code and replies cross the worker boundary as bounded JSON over a socket pair, never interpolated into a shell command or
argv.Test results:
tests/envs/test_coding_env_isolation.py— 9/9 passed.tests/envs/test_coding_env_integration.py— 13 skipped (Docker unavailable here, expected).- Full suite (
PYTHONPATH=src:envs uv run pytest tests/) — 6023 passed, 233 skipped, 2 failed. The 2 failures are intests/envs/test_websockets.py(echo_env-based step-count timing assertions) — a file this PR does not touch or exercise. Confirmed viagit diffthat this PR has zero changes to that file; these failures are pre-existing/flaky and unrelated to this change.Tier 2: Alignment Discussion
Principle Conflicts
None identified.
- Gym-like
reset()/step()/state()signatures and the MCP/WebSocket agent boundary are untouched — agents still cannot reach reset/simulation control.CodeAction/CodeObservation/CodeStateand the reward/transform logic (create_safe_coding_transform) are unchanged — rewards remain computed inside the environment.- Change is fully contained to
envs/coding_env/; no other environment's files are touched, consistent with "self-contained environments."- Reuses the existing
SUPPORTS_CONCURRENT_SESSIONS/max_concurrent_envsmechanism fromopenenv.core.env_serverrather than inventing a new concurrency concept.RFC Conflicts
No blocking conflicts. One discussion point worth surfacing, since it's directly on-topic for a currently-open RFC even though not formally required by it:
ALIGNMENT FLAG: No per-worker memory/CPU bound for untrusted code execution
- Principle/RFC at stake: RFC 002, Security Invariants, S6 "Bounded blast radius" (providers set CPU/memory/disk limits so a runaway or malicious workload cannot exhaust resources).
- The concern:
IsolatedPyExecutorisolates state well (process-per-session, env allowlist, non-dumpable, unprivileged uid) and bounds time (CODING_ENV_EXEC_TIMEOUT_S), but sets no memory/CPU ulimit on the worker itself.MAX_CONCURRENT_ENVSbounds how many workers can exist, not what one worker can consume. The PR description already discloses this ("No memory limit per worker, so one session can still use up the container's memory") and it's documented in the README/docs page, so it isn't hidden — but S6 exists for exactly this failure mode (OOM/runaway allocation from untrusted code), so it seems worth a maintainer decision on whether aresource.setrlimit(RLIMIT_AS, ...)(or similar) in_worker_mainis in scope here or left to the surrounding container's own memory limit.- Suggested reviewer: @thegovind (authored the S5/S6 security-invariants section of RFC 002); @Darktex (authored the "Container isolation"/"Agent isolation" sections of INVARIANTS.md).
Summary
- 0 mechanical issues to fix
- 1 alignment point for human review (non-blocking, already partially disclosed by the author in the PR description)
- 0 RFC conflicts requiring a design change
Sent by Cursor Automation: Pre-review
Each reset spawned a fresh Python that imported smolagents and openenv, which cost seconds of CPU and a full interpreter of memory per session. Workers are now forked from a zygote that the server starts once, with a minimal environment, non-dumpable before its imports, and smolagents already loaded. Workers start in milliseconds, share its pages and are non-dumpable from the start. The zygote kills and reaps them, and is restarted if it dies. - When the server is root, workers run as nobody only if that user can start the interpreter with the server's PYTHONPATH, otherwise they keep the server's uid and a warning is logged. CODING_ENV_WORKER_USER=nobody|same forces either. - A worker that can't start comes back as an exit_code=1 observation, from reset() and from step(), not as a server error. - TMPDIR, TMP and TEMP point to the session's own directory. - Start failures and garbage-collected executors release the worker, its socket and its directory. - Optional CODING_ENV_WORKER_MEMORY_MB sets RLIMIT_AS per worker. - Older coding_env tests close their envs.
- Report the fallback to the server's uid with warnings.warn. The module logger has a NullHandler and a plain uvicorn server configures no logging, so a log record was never shown. - Exit the zygote quietly when the server connection resets. - CODING_ENV_WORKER_MEMORY_MB is now on top of the worker's starting address space. The zygote's imports already map about 2.3 GB of virtual memory, so an absolute limit failed small allocations.
A worker's garbage collections otherwise write to the headers of every object it inherited from the zygote and copy those pages. With 32 workers after an allocation-heavy step, private memory per worker was about 75 MB without gc.freeze() and about 10 MB with it.
Describe how workers are started, their cost, the worker user check, CODING_ENV_WORKER_USER and CODING_ENV_WORKER_MEMORY_MB, in the README and the synced docs page.
The zygote now keeps the server's uid, so it can import the server's packages from anywhere, including a virtual environment under /root. It also imports each session's authorized modules before forking. When the server is root, each forked worker clears its groups and switches to nobody before running model code, then turns non-dumpable again (the uid change resets that flag) and sets its parent-death signal. Workers can no longer signal the zygote or the server. The uid fallback, CODING_ENV_WORKER_USER and CODING_ENV_WORKER_MEMORY_MB are removed: with the drop in the worker there is nothing to fall back from, and the container's memory limit is the guard.
Describe the drop to nobody after the fork, and list the limits: same user for all workers, shared /tmp when file access is authorized, and no memory limit per worker.
The worker switches to nobody right after the fork, so its uid can still be root when reset() returns. The dumpable check reads as the user the worker runs as, which is denied before and after the switch.
|
On the alignment review's RFC 002 S6 flag (no per-worker memory limit): There is no per-worker limit, on purpose. The container's memory limit is the guard, and since each session runs in its own worker, the process the kernel kills when memory runs out is most likely the one that used it, so only that session restarts (its next step gets a |
There was a problem hiding this comment.
Alignment Review Report
Automated Checks
- Lint: PASS —
bash .claude/hooks/lint.sh(usort/ruff format/ruff check onsrc/,tests/) passes cleanly. That hook's scope doesn't includeenvs/; runningruff check/usort checkdirectly on the touchedenvs/coding_env/files finds no issues introduced by this PR (the one usort hit inserver/app.pyand the one unused-variable lint hit inserver/python_executor.pyboth predate this change and sit outside files/lines this PR edits). - Debug code: CLEAN —
bash .claude/hooks/check-debug.shonly flags pre-existingprint()/TODOlines in unrelated files. A direct diff scan ofenvs/coding_env/**finds noprint,pdb,breakpoint, or newTODO/FIXMEin the added/changed lines.
Open RFCs Context
- RFC 002 (
env-spec, In Review) defines Security Invariants S1–S6 for Cloud Sandbox Providers running untrusted code, including S6 "Bounded blast radius" (CPU/memory/disk limits).coding_env's local worker isolation isn't formally in that provider's scope, but it's the same threat model (untrusted model code), so it's a useful lens — see the flag below. - RFC 005 (Agentic Harness Integration, In Review) independently describes the same pattern this PR implements for
coding_env: "Process isolation: the harness runs as a subprocess" + "State isolation: reset() kills the process and starts a fresh one." This PR's design (process-per-session, killed and replaced onreset()/timeout) is consistent with that precedent rather than conflicting with it. - No Draft/In Review RFC proposes an alternative session/process isolation model for
coding_env, so this PR doesn't preempt an open design discussion.
Tier 1: Fixes Required
None. Verified directly:
envs/coding_envinstalls and imports cleanly;smolagentsbump to>=1.24.0matches thesend_tools/timeout_secondsusage.PYTHONPATH=src:envs uv run pytest tests/envs/test_coding_env_isolation.py tests/envs/test_coding_codeact_env.py tests/envs/test_python_codeact_reset.py tests/envs/test_python_codeact_rewards.py -v→ 55 passed, 3 skipped (the 3 skips are theroot_onlyprivilege-drop tests, expected without root in this sandbox).scripts/sync_env_docs.py --checkpasses — the new "Sessions and isolation" section is mirrored correctly betweenenvs/coding_env/README.mdanddocs/source/environments/coding.md.- No credential exposure:
WORKER_ENV_ALLOWLISTexplicitly restricts what a worker inherits from the server, exercised bytest_server_secrets_are_not_visible_to_model_code. - No command/code injection: worker code and replies cross the socket boundary as bounded, typed JSON only (
MAX_REPLY_BYTES), never pickled or shelled out. - Privilege-drop ordering in
_worker_mainis correct:PR_SET_PDEATHSIGis (re)applied afteros.setuid, since changing uid resets both the dumpable flag and the death signal — and the commit history (9a21ff2d,81cbbe68) shows this was caught and fixed by the author during the PR's own iteration, which is a good sign.
Tier 2: Alignment Discussion
Principle Conflicts
None identified.
- Gym-like
reset()/step()/state()signatures and the MCP/WebSocket agent boundary are untouched; agents still cannot reach reset or simulation control through this change. CodeAction/CodeObservation/CodeStateand the reward/transform logic (create_safe_coding_transform) are unchanged — rewards remain computed inside the environment, not externally.- Change is fully contained to
envs/coding_env/(plus its doc stub and tests) — consistent with "self-contained environments." - Reuses the existing
SUPPORTS_CONCURRENT_SESSIONS/max_concurrent_envsmechanism rather than inventing a new concurrency concept, and the newPythonCodeActEnv.SUPPORTS_CONCURRENT_SESSIONS = Trueis exercised end-to-end bytest_server_runs_isolated_concurrent_websocket_sessions.
RFC Conflicts
No blocking conflicts. One non-blocking discussion point carried over from the first review of this PR (at commit bc721d7f), which is still accurate against the current head — the limitation is already disclosed by the author in the README/docs ("There is no memory limit per worker...") rather than hidden, so this is a maintainer judgment call, not a defect:
ALIGNMENT FLAG: No per-worker CPU/memory bound for untrusted code execution
- Principle/RFC at stake: RFC 002, Security Invariants, S6 "Bounded blast radius" (providers set CPU/memory/disk limits so a runaway or malicious workload cannot exhaust resources).
- The concern:
IsolatedPyExecutor/_worker_mainisolates state well (process-per-session, env allowlist, non-dumpable, unprivileged uid when root) and bounds time (CODING_ENV_EXEC_TIMEOUT_S), but sets no memory/CPU ulimit on the worker itself — onlyresource.setrlimit(RLIMIT_CORE, (0, 0))to suppress core dumps.MAX_CONCURRENT_ENVSbounds how many workers can exist, not what one worker can consume, so one session's code (e.g. an unbounded list comprehension) can still exhaust the container's memory and affect sibling sessions sharing it. S6 is scoped to cloud sandbox providers in RFC 002, not formally binding on a local-process executor like this one, but the failure mode is the same one S6 exists for. - Suggested reviewer: @thegovind (authored the S5/S6 security-invariants section of RFC 002); @Darktex (authored the "Container isolation" / "Agent isolation" sections of INVARIANTS.md).
Summary
- 0 mechanical issues to fix
- 1 alignment point for human review (non-blocking, already disclosed in the PR's own docs)
- 0 RFC conflicts requiring a design change
Sent by Cursor Automation: Pre-review
Co-authored-by: burtenshaw <burtenshaw@users.noreply.github.com>
Co-authored-by: burtenshaw <burtenshaw@users.noreply.github.com>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 74e74f3. Configure here.
| def close(self) -> None: | ||
| """Kill the worker and remove its home. Safe to call more than once.""" | ||
| if self._pid is not None: | ||
| self._zygote.kill(self._pid) |
There was a problem hiding this comment.
Timeout waits on zygote lock
Medium Severity
A timed-out step SIGKILLs its worker immediately, then close() still calls kill(wait=True), which blocks up to ZYGOTE_REPLY_TIMEOUT_S (10s) for the zygote lock. If another session is preloading a module, the client waits those extra seconds after the step timeout has already fired. The isolation test only stays fast because it monkeypatches that constant down to 0.5s.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 74e74f3. Configure here.
| if config["uid"] is not None: | ||
| os.setgroups([]) | ||
| os.setgid(config["uid"]) | ||
| os.setuid(config["uid"]) |
There was a problem hiding this comment.
Nobody workers miss lazy submodules
Medium Severity
_preload only imports each authorized top-level name in the root zygote, then the worker drops to nobody. Lazy submodules (for example matplotlib.pyplot or numpy.linalg) are opened from disk later in that worker. When the venv lives in a root-only tree such as /root, those opens fail with ImportError, even though the package was listed in additional_imports.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 74e74f3. Configure here.




Summary
coding_envran every session's code through smolagents'LocalPythonExecutorinside the server process. That interpreter keeps per-session variables apart, but module and class state is shared by the whole process, so code from one episode could affect later episodes and other sessions. This PR gives each session its own worker process, replaced on everyreset(), so each episode starts from a clean interpreter. Workers are forked from a pre-imported template process (a zygote), so a new one is ready in milliseconds and costs about 10 MB. With no shared state left, the env now declaresSUPPORTS_CONCURRENT_SESSIONS = True.Type of Change
What changed
server/python_executor.py: newIsolatedPyExecutor, with the samerun(code) -> CodeExecResultcontract. Each session gets one worker process that owns aPyExecutor. Server and worker exchange bounded JSON with typed fields only, never pickle.reset()) fromsys.executable, with the server's uid, a socket pair and a minimal environment. It becomes non-dumpable before importing anything, imports smolagents, this module and the sessions' authorized modules, callsgc.freeze()so the workers' garbage collections don't copy the pages they share with it, and forks one worker per session on request. The threaded server is never forked. The zygote also kills and reaps workers, so a worker's pid can't be reused while the server still refers to it. If it dies, its workers die with it (PR_SET_PDEATHSIG), those sessions get the usual crash message, and the next call starts a new zygote.PATH,LANG,LC_ALL,LC_CTYPE,TZfrom the server environment (plusPYTHONPATH), so tokens and keys set on the server are not visible to model code,HOME,TMPDIR,TMP,TEMPand working directory, removed when the session ends,nobody(65534) right after the fork, before any model code, so it can't signal the server or the zygote. Because the zygote imports everything with the server's uid first, this also works when the packages live wherenobodycan't read them (for example a virtual environment under/root),/proc/<pid>/{environ,mem}.app.pymakes the server non-dumpable at startup for the same reason,close(), by a failed start and by aweakref.finalizewhen the executor is garbage collected.PyExecutoris unchanged apart from atimeout_secondspassthrough to smolagents. The env's smolagents pin moves from>=1.22.0to>=1.24.0, the first version with that argument (the lock already resolves 1.26.0).server/python_codeact_env.py:reset()stops the old worker and forks a new one,close()stops it, new optionaltimeout_sargument (defaultCODING_ENV_EXEC_TIMEOUT_Sor 30 s, the smolagents default). If a worker can't start,reset()andstep()returnexit_code=1with aRuntimeError: ...message instead of raising. Instances the server builds only for introspection never start a worker.SUPPORTS_CONCURRENT_SESSIONS = True.server/app.py:max_concurrent_envs=int(os.getenv("MAX_CONCURRENT_ENVS", "8")), and the server is made non-dumpable at startup.Why not smolagents' remote executors (E2B, Docker, Modal): they need an external service or a Docker daemon inside the env container. A local worker process keeps the server self-contained.
Why a zygote: a fresh interpreter per
reset()imports smolagents and openenv every time, about 4 s of CPU and 140 MB per worker. Forking from one pre-imported process brings that down to a few milliseconds and about 10 MB.Public API is unchanged:
CodeAction,CodeObservation,CodeState, and thestdout/stderr/exit_codesemantics are the same, because the samePyExecutorcode produces them, only in another process. Behavior changes that callers can see:exit_code=1with aTimeoutError: ...message and the session restarts on the next step, so earlier variables are gone (before, smolagents returned an error after 30 s and left the loop running in a thread of the server).exit_code=1with aRuntimeError: ...message and the next step starts a fresh worker. Other sessions and the server keep running.Why concurrency is now safe
Each
PythonCodeActEnvowns its worker process, its transform and its state. The only module-level state left in the server is the zygote handle (behind a lock), constants and the logger. Workers share no writable memory (fork is copy-on-write, andrandomis reseeded in each child) and receive no file descriptors from other sessions. The tests run two sessions on separate threads, as the server does for WebSocket sessions, and through the real app over two WebSocket connections.Cost
On Linux: the zygote starts once in 3 to 5 s (170 MB),
reset()plus a first step then takes about 15 to 25 ms, and each worker costs about 10 to 15 MB (PSS, 32 workers). In a training run with 32 concurrent sessions this is about +2 s per training step over v0.13.0 (49 s against 47 s median, 5 steps on one A100).Limits
osby default, is what keeps one session's code from signaling other sessions' workers (or, without root, the server)./tmpitself is still shared ifosoropenare authorized.osis authorized, model code can write lines into the server log.Alignment Checklist
.claude/docs/PRINCIPLES.mdand this PR aligns with our principles.claude/docs/INVARIANTS.mdand no invariants are violated/pre-submit-pr(orbash .claude/hooks/lint.shand tests) and addressed all issuesNotes: no change to the Gym-like API or to the agent/infrastructure boundary. It strengthens "No credential exposure" (server environment variables don't reach model code) and fits "Performance for isolation".
RFC Status
No files in
src/openenv/core/change, no public signature changes (one new optional keyword argument), and the worker processes are an implementation detail of one environment.Test Plan
tests/envs/test_coding_env_isolation.pycovers: state patched by an episode is gone afterreset(), concurrent sessions (threads and two WebSocket connections) don't share interpreter state, server secrets don't reach model code, timeouts kill only their own worker,close(), garbage collection and failed starts release everything, a dead zygote is replaced, temporary paths point to the session directory, and on Linux workers are non-dumpable. As root on Linux, it also checks that workers run asnobodywhile the zygote keeps root, that a worker withosauthorized can't kill the zygote or the server, and that an authorized module in a directory only root can read still loads.Results: 54 passed, 17 skipped on macOS (Docker, Linux-only and root-only tests skipped). On Linux (
python:3.12), 58 passed as root and 55 passed as an unprivileged user, with the 13 Docker tests skipped. Also checked on Linux: theDockerfilesteps replayed inpython:3.11-slim(workers asnobody, capacity error on the 9th session, 8 concurrent sessions isolated), and a server started withuv runas root with its virtual environment under/root(workers asnobody, packages from that environment importable).Claude Code Review
Alignment review: no principle or RFC conflicts, no mechanical issues. Full
lint.shpasses.Note
Medium Risk
Touches untrusted code execution, process forking, privilege dropping, and credential isolation; behavior changes on timeouts/crashes (session restart) but the public action/observation API stays the same.
Overview
coding_envnow runs each session in a dedicated worker process forked from a shared zygote, instead of executing all model code in the server process via smolagents’ in-process interpreter.reset()tears down and spawns a new worker, so episodes and concurrent sessions no longer share interpreter or patched-module state; the env setsSUPPORTS_CONCURRENT_SESSIONS = True.The new
IsolatedPyExecutor/ zygote stack enforces per-step timeouts by killing only that session’s worker, strips server secrets from worker environments, uses bounded JSON IPC, and on Linux adds non-dumpable processes andnobodyworkers when the server runs as root.app.pywiresMAX_CONCURRENT_ENVS(default 8) and hardens the server process the same way.Docs gain a “Sessions and isolation” section; smolagents is bumped to ≥1.24.0. A large
test_coding_env_isolation.pysuite plus fixture cleanup in existing tests cover concurrency, secrets, timeouts, and failure recovery.Reviewed by Cursor Bugbot for commit 74e74f3. Bugbot is set up for automated code reviews on this repo. Configure here.