Repository navigation
feat(server): run every server that can with several workers - #4790
Conversation
43c289e to
8b6e4a6
Compare
8b6e4a6 to
bbe9e7a
Compare
19ca169 to
7a970aa
Compare
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
bbe9e7a to
939644b
Compare
939644b to
c46fd97
Compare
7a970aa to
0fff412
Compare
0fff412 to
e54313a
Compare
676aded to
19153c6
Compare
19153c6 to
8b1d47e
Compare
yaoyu-33
left a comment
There was a problem hiding this comment.
Reviewed at 8b1d47e, looking at three things: reuse of the existing multi-worker support, retries, and cleanup.
Summary: the design is sound. The PR reuses the session routing from #3905, the same routing simple_agent relies on, and adds no new routing code. Retries and normal shutdown hold up. One regression is worth fixing before merge, and the crash path has gaps worth stating.
1. Reuse of simple_agent's multi-worker support: yes
- Most of the diff is the module-level
appadapter, whichsimple_agentalready has. Requests are still routed bySessionRoutingMiddleware(private Unix sockets plus owner files), and nothing undernemo_gym/server_runtimechanges. tool_simulation_agent'sx-ng-session-ownerheader on its own/v1/responsescall matches whatsimple_agent/app.pyalready does. 👍
2. Retries
Working as intended:
- A retried seed or close is forwarded to the worker that owns the session. The owner remembers the close for the close retry window, so every worker answers a late seed the same way. The two-worker
interactive_browsere2e test covers this. - A retried
/runonsimple_agentortool_simulation_agentwith checkpointing claims the episode from the coordinator, so any worker can take it. Keeping the refusal forminiswe_sandboxed_agentwith aresources_server, which replays from process memory, is right. - A failed install releases the lock, and the next call deletes the partial tree before installing again. The version in the install record makes a pin change reinstall.
Should fix: install_lock has no fallback for filesystems without file locks. install_lock.py:42 and :57 call fcntl.flock bare, so on Lustre mounted with noflock, or NFS without lockd, they raise OSError.
- The PR already handles this case for the log appends in
competitive_coding_challengesandproof_genselect(except OSError: pass), but not here. - This PR wraps every first local install in the lock even with
num_workers=1: the Claude Code, Codex, Kilo Code and OpenClaw installers, and CVDP's deps build. The lock files sit beside the install, inside the repository checkout (e.g.setup_claude_code.py:36), which on a cluster is often on Lustre. - So a single-worker first install that works on main can fail after this PR.
- Suggestion: catch
OSErrorother thanBlockingIOErrorin both functions, log a warning and continue without the lock, as the log appends do. Add a test that patchesflockto raiseOSError(ENOLCK).
Nit: waiting for the lock has no time limit. If one worker's npm install hangs, every other worker blocks on its first local call indefinitely. The event loops stay responsive (to_thread / polling), so this isn't a blocker. A time limit with a clear error, or a comment on the trade-off, would help.
3. Cleanup
Working as intended:
- On normal shutdown each worker runs its own lifespan.
swebench_proandterminal_bench_2_1stop their sandboxes, each worker closes its private socket and forwarding clients, the background sweep releases owner files of ended sessions, and the runtime dir is removed at exit. - Install leftovers are deleted before a reinstall.
Gaps worth stating in the PR's Compatibility section:
- A crashed worker (OOM, kill) leaks its sandboxes until the provider TTL. In
swebench_pro,ttl_scomes fromsandbox_configand is optional (app.py:447), so without it they never expire. More workers means more processes that can die:competitive_coding_challengesalone is about 27 GB per worker. Consider givingttl_sa default whennum_workers > 1, or at least documenting it. The dead worker's sessions answer 410, which is the right signal. interactive_browserhas no shutdown hook. Remote CDP browsers (thelexmountprovider) outlive a worker that exits. This predates the PR, but several workers make it more likely.- Minor: the per-worker
tavily_searchmetrics files (session_id_metrics.<ppid>.<pid>.json) build up across runs with nothing removing them. They're gitignored, so this is low priority.
Removing num_workers: 1 from configs
This is fine: the default is None, which still runs one worker. A short line in the langgraph README on how to raise it would help users who relied on the pin as a signal, e.g. ++<instance>.<server type>.<implementation>.num_workers=N.
8b1d47e to
476bc54
Compare
|
Thanks for the review. Changes, now in
Not changed in this PR:
|
yaoyu-33
left a comment
There was a problem hiding this comment.
Re-reviewed at bc2440ef33. Thanks for the quick turnaround on the last round.
Merge conflict first: GitHub now reports the branch as conflicting with main, on responses_api_agents/mini_swe_agent/app.py (8 commits landed since dff64b2041). Could you merge or rebase onto main? Please also check that any servers added there get the adapter or a refusal. With the conflict resolved, I'm happy to approve: nothing below blocks merge.
Previous round, verified at this head:
install_lockandasync_install_lockfall back on anOSErrorfromflockand warn. The async loop still handlesBlockingIOErrorfirst, and the ENOLCK test covers both functions (nemo_gym/utils/install_lock.py:52-80,tests/unit_tests/utils/test_install_lock.py:111).- The module docstring explains why the wait has no timeout. The crashed-worker note is in Compatibility, and
swebench_pro.yamldoes shipttl_s: 18000. - The langgraph README override path matches the
reasoning_gym_langgraph_agentinstance. - The bot's three threads hold at this head:
finance_sec_searchgives each workerrequests_per_second // num_workersand refuses more workers thanrequests_per_second.nemo_user_simkeeps a closed session's owner for the longer of the two windows.miniswe_sandboxed_agentwith aresources_serverstill refuses several workers.
- Agreed on deferring the
interactive_browsershutdown hook. A linked follow-up issue would be nice.
Also checked, no change needed:
- All 196 added adapters run the same class as their
__main__branch, and each imports the helper. - Every installer's sync lock runs in
asyncio.to_thread. - The main-process-only steps in
legal_agent_benchandihevalrun beforerun_webservermarks the process as a worker. - Playwright 1.62.0 writes
INSTALLATION_COMPLETEafter unpacking. - Unit tests for the touched agents, installers,
swebench_pro,terminal_bench_2_1,interactive_browser,legal_agent_benchand the proof servers pass locally. CI is green.
Inline comments: all NOTEs. They cover:
- one stray server build in
math_with_code's forkserver; - the install lock on a read-only package directory;
vibenchgetting the adapter while it still refuses several workers;code_gen/sandbox_app.py;- leftover "one worker" docs;
- an e2e filter that never matches;
- public-API imports;
- one untested lock path.
PR description:
- "A pin bump installs the new version instead of running the old one" holds only when the CLI is not already on
PATH. Claude Code, Codex, Kilo Code and Pi return onshutil.whichbefore reading the record (responses_api_agents/claude_code_agent/setup_claude_code.py:72), the same as onmain. Could you narrow that sentence? - The adapter-or-refusal contract test lives in #4885, and this PR already drifted from it once (
chartography,copilot_agent). Landing #4885 right after this one would keep new servers honest.
yaoyu-33
left a comment
There was a problem hiding this comment.
Approving at b0d000696a. The rebase onto main resolves the mini_swe_agent conflict, and the range-diff from bc2440ef33 is only that resolution plus the adapter on mini_swe_agent/sessions_app.py, whose state lives in agent sessions that routing follows. The NOTEs from the previous review are non-blocking and fine as follow-ups. Please land #4885 soon after, so its contract test covers new servers.
With num_workers > 1, each uvicorn worker imports the server's entrypoint and serves its module-level app. Most resources, agent and environment servers had no such app, so every worker exited at startup and uvicorn stopped the server. Every server that is safe with several workers now ends its entrypoint with it. For langgraph_agent that is its four entrypoint modules, and for langchain_deepagents_agent it is reasoning_search_agent.py. The langgraph configs and environment pairings no longer pin one worker. interactive_browser, swebench_pro and terminal_bench_2_1 no longer refuse several workers. Their per-session state is keyed by the session cookie or by resources_session_id, and session routing sends an environment server's cookieless seed and close by resources_session_id to the worker that holds the session. An opt-in end-to-end test runs interactive_browser with two workers and real browsers. It seeds through each worker's private socket in turn, so both workers hold browsers whichever worker the TCP listener picks, and checks that a cookieless retried seed, a conflicting seed, a close and a late seed each act on the worker that holds the browser. miniswe_sandboxed_agent drops its num_workers: Literal[1] for episode sessions, which are routed by agent_session_id, and refuses several workers when a resources_server enables its own /run path, which replays a retried run from process memory keyed by the cookie's session_id and the rollout ID; and harbor_oracle_agent drops its own num_workers check, because its sessions are agent sessions, which routing follows. browsecomp_agent drops the num_workers: Literal[1] main gave it with its sandboxed session harness, for the same reason. The CI job for the routing tests now builds interactive_browser's environment and Chromium, so its two-worker test runs there instead of skipping. tool_simulation_agent's own /run path calls its /v1/responses, which activates the episode this worker holds. The call now names this worker in x-ng-session-owner, as simple_agent's does, so with several workers it returns here instead of restarting the rollout on another worker. nemo_user_sim keeps a closed session's tombstone for session_ttl_seconds, 1980 seconds by default, while a closed session keeps its owner only session_close_retry_window_seconds after the close. It now keeps its owner for the longer of the two, so with several workers a delayed seed still reaches the worker that holds the tombstone and is refused there. interactive_browser, swebench_pro and example_single_tool_call already keep closed sessions in ResourcesSessionFences, which forgets a close when the session's owner expires. The Claude Code, Codex, CVDP, Kilo Code, OpenClaw, OpenCode and Pi agents install their command line tools on first local use, into one shared directory per agent, so the first calls in several workers raced. Each install now runs under nemo_gym.utils.install_lock beside the install directory, and checks inside the lock for an install another worker finished. The record names the version it installed and is reused only for that version, so a changed pin reinstalls instead of running the old tool. The Node.js toolchain and the CVDP runtime are reused only when a marker written last says the install finished, so an interrupted install is redone from an empty directory. Cline and AnyTerminal install before uvicorn starts the workers, and a comment at each install states that ordering. interactive_browser counts Chromium as installed only once Playwright marks the install complete, and iheval fetches its IFEval corpus in the main process before the workers start. Other servers that are safe with several workers needed a change: - finance_sec_search divides requests_per_second among the workers, so the server as a whole stays within SEC.gov's rate limit, and refuses more workers than requests_per_second, where a worker's share would round to zero; - legal_agent_bench rebuilds its runtime task tree only in the main process, which runs setup_webserver before uvicorn starts the workers; - the proof_genselect, proof_verification and competitive_coding_challenges debug logs take a file lock around each append, and still write the record on a filesystem without file locks; - tavily_search and browsecomp_advanced_harness write one session metrics file per worker at exit, named by the main process and the worker, and the plot script reads one run's files; - finance_agent_v2 and finance_sec_search configure their logging in the workers too; - opencode_search, indian_banking, competitive_coding_challenges, agentic_mme and agentic_mme_agent say which caches, counters, concurrency limits and memory are per worker. Signed-off-by: Ananth Subramaniam <[email protected]>
|
Thanks for the second pass. Rebased onto
|
What changed and why
This is the second of three changes that let every resources, agent and environment server either run with
num_workers > 1or refuse it at startup with a reason. #4884, now merged, added the refusal method and the shared install lock, and #4885 adds the refusals.With
num_workers > 1, each uvicorn worker imports the server's entrypoint and serves its module-levelapp. Most servers had no suchapp, so every worker exited at startup and uvicorn stopped the server. Every server that is safe with several workers now ends its entrypoint with it:flowchart TD A["A config sets num_workers > 1"] --> B{"Where does the server keep state between requests?"} B -->|"in a session that routing follows, an external store, read-only data, or nowhere"| C["Entrypoint ends with the module-level app (this change)"] B -->|"anywhere else"| D["run_webserver refuses with the reason (#4885)"] C --> E["uvicorn starts the workers, and each serves app"] D --> F["The server fails at startup, before uvicorn starts"]For
langgraph_agentthe adapter goes in its four entrypoint modules, and forlangchain_deepagents_agentinreasoning_search_agent.py. The langgraph configs and environment pairings no longer pinnum_workers: 1. #5681, now merged, keeps uvicorn's__mp_main__copy of the entrypoint from building a second server in each worker.Servers that no longer refuse several workers
These servers refused several workers, or main gave them a one-worker pin, although session routing (#3905) reaches all of their state:
interactive_browser,swebench_pro,terminal_bench_2_1resources_session_idresources_session_idharbor_oracle_agent,browsecomp_agentagent_session_idminiswe_sandboxed_agentwithout aresources_serveragent_session_id. With aresources_server, its own/runreplays a retried run from process memory, so it still refusestool_simulation_agentwith checkpointing/runholds/v1/responsesnow names this worker inx-ng-session-owner, assimple_agent's doesA seed or close from an environment server carries no cookie, so the worker that accepts it looks up the session's owner and forwards the request there:
sequenceDiagram participant E as Environment server participant A as Worker A participant B as Worker B, holds the browser E->>A: seed or close for resources_session_id s, no cookie A->>A: the owner file for s names worker B A->>B: forward over B's private socket B->>B: act on the browser for s B-->>A: reply A-->>E: reply, unchangedtool_simulation_agent's own/runpath calls the server's/v1/responsesto activate the episode. Without the header, that call could reach another worker and restart the rollout there:sequenceDiagram participant C as Caller participant A as Worker A, runs the episode participant B as Worker B C->>A: POST /run A->>B: POST /v1/responses, x-ng-session-owner names A Note over B: the shared listener handed the call to B B->>A: forward to the worker the header names A-->>C: the rollout continues on Aagentic_mme,agentic_mme_agentandbig_finance, which main added since the last revision, get the adapter too.big_financekeeps each session's as-of date by the session cookie and writes its SEC cache files atomically. The two Agentic MME servers' concurrency limits are per worker, andagentic_mme_agent's retrieval cache is files written atomically under one root, which several processes can already share.chartography,copilot_agentandmini_swe_agent's newsessions_app.py, which main added since then, get the adapter as well.chartography's verify reads only its request, and its judge limit is per worker.copilot_agentkeeps its state in agent sessions, installs the CLI inside the task sandbox rather than on the host, and limits Copilot invocations per worker.sessions_app.pyservesmini_swe_agent's agent sessions without Ray. Those sessions keep their state in agent sessions and install mini-SWE inside the task sandbox, somini_swe_agent/app.pykeeps its adapter after main moved it onto agent sessions.An opt-in end-to-end test (
NEMO_GYM_MULTIWORKER_E2E=1) runsinteractive_browserwith two workers and real headless browsers, and CI now builds that server's environment and Chromium so the test runs there:resources_session_id, an earlier revision of fix(server): route a session's requests to the worker that holds it #3905 failed this test: closes left browsers open, and later seeds opened new ones.swebench_proandterminal_bench_2_1need real sandboxes for the same check, so their coverage is the unit tests plus the shared routing.Closed sessions and their owner
A worker owns a
resources_session_iduntilsession_close_retry_window_secondsafter its close. Within that window, a delayed seed or retried close reaches the worker that remembers the close.nemo_user_simkeeps a closed session's tombstone forsession_ttl_seconds, 1980 seconds by default. A closed session now keeps its owner for the longer of the two settings, so a delayed seed reaches the worker that holds the tombstone and is refused there. The override uses main's new name,owned_session_routing.interactive_browser,swebench_proandexample_single_tool_callkeep closes inResourcesSessionFencesfor the same window, andterminal_bench_2_1forgets a close after it. Each gives a late seed the same answer on every worker.Local installs shared by several workers
The Claude Code, Codex, CVDP, Kilo Code, OpenClaw, OpenCode and Pi agents install their command line tools on first local use, into one shared directory per agent. With several workers, the first calls raced and a partial tree could be reused later. Each install now runs under
nemo_gym.utils.install_lock:flowchart TD A["A worker's first local call"] --> L["Take the install lock beside the install directory"] L --> R{"Does the record name this version, and does its binary exist?"} R -->|"yes"| U["Reuse the install another worker finished"] R -->|"no"| I["Install into an empty directory"] I --> M["Mark the tree complete once every file is in place"] M --> W["Write the record, naming the version"] U --> X["Release the lock"] W --> XPATH, a pin bump installs the new version instead of reusing the old install. Claude Code, Codex, Kilo Code and Pi still run a tool found onPATHfirst, as on main.noflock, or in a read-only package directory, the install logs a warning and runs unlocked, as it did before. A record that cannot be written logs a warning too, and a later process installs again.interactive_browsercounts Chromium as installed only once Playwright writesINSTALLATION_COMPLETE.ihevalfetches its IFEval corpus in the main process, before the workers start.Other changes for servers that run with several workers
finance_sec_searchrequests_per_second // num_workersrequests a second, so the server stays within SEC.gov's rate limit. It refuses more workers thanrequests_per_second.legal_agent_benchproof_genselect,proof_verification,competitive_coding_challengesnoflock.tavily_search,browsecomp_advanced_harnesssession_id_metrics.<main pid>.<worker pid>.jsonat exit, andplot_session_id_metrics.pyreads one run's files together.finance_agent_v2,finance_sec_searchopencode_search,indian_banking,competitive_coding_challenges,agentic_mme,agentic_mme_agentcompetitive_coding_challengesloads about 27 GB per worker for the full test set.swe_pivotnemo_gymstub now includesnemo_gym.utils, which the adapter imports.math_with_codecode_gensandbox_app.py, the entrypoint without Ray, gets its own adapter.browsecomp_agentand Terminal-Bench 2.1 READMEs, the harness guide and the add-harness skill no longer say agent sessions need one worker.Issue
No separate issue: this follows #3905.
Validation
Run on this revision, rebased onto main at 65dd99e:
pytest -n 16 tests/unit_testsin a virtual environment synced with the extras the unit-test workflow installs (uv sync --extra dev --extra ray --extra sandbox --extra openshell --extra mlflow --extra wandb). The files with failures fail the same way on main at the same commit.test_multiple_workers_contract.pyfailed after the rebases onchartography,copilot_agentandmini_swe_agent/sessions_app.py, and passes with their adapters and feat(server): refuse several workers in servers that cannot share state #4885 on top.chartography,copilot_agent, the install lock and the langgraph pairings, whosenum_workersassertion moved to a new file on main.PermissionError, and two CVDP agents building the sandbox runtime archive at once, which builds twice with a lock that does nothing.math_with_code's tests, and a check that its forkserver preloads only the main script and the session worker's module.pre-commit run --files <changed files>. CI's per-server run covers the server tests.Run on the previous revision, rebased onto main at f49b582:
pytest -n 16 tests/unit_testsin a virtual environment synced with the extras the unit-test workflow installs (uv sync --extra dev --extra ray --extra sandbox --extra openshell --extra mlflow --extra wandb). Rerunning the files with failures on this branch and on main at the same commit gives the same failures on both; two tests that failed only under the parallel run pass on rerun.test_multiple_workers_contract.py, which reads every server entrypoint, passes with feat(server): refuse several workers in servers that cannot share state #4885 on top.agentic_mme,agentic_mme_agent(with its image packages added),agentic_turn_simulation,bbq,gdp_pdf,terminal_bench_2_1,harbor_oracle_agent,tool_simulation_agent,swe_pivotandnemo_user_sim;nemo_user_sim's failures fail the same way on main.gym env testforbig_financeandfinance_sec_search; the test offinance_sec_search's refusal fails on the previous message, which did not name the limit.swebenchandlanggraph_agentneed packages that environment lacks, so CI's per-server run covers them.NEMO_GYM_MULTIWORKER_E2E=1 pytest tests/e2e/session_routing/test_typed_sessions_e2e.py, the two-workerinteractive_browsercase.flockfails withENOLCK: both locks must still run the install and warn. It fails on the previous revision.pre-commit run --files <changed files>.Run on earlier revisions, rebased onto main at 390c954:
tool_simulation_agent's owner header, a half-unpacked Chromium build, and refusals no longer raised byswebench_pro,harbor_oracle_agentandbrowsecomp_agent.gym env testfor the resources servers this change touches beyond the adapter, each in its own environment:interactive_browser,tavily_search,browsecomp_advanced_harness,iheval,code_gen,xstest,competitive_coding_challenges,proof_genselect,proof_verification,swebench_pro,opencode_search,indian_bankingandreasoning_gym. The touched agents' tests ran in the repository's virtual environment:tool_simulation_agent,harbor_oracle_agentand the Claude Code, Codex, Kilo Code, OpenCode and OpenClaw installers pass; Pi's pinned-runtime tests fail the same way on main, because they run the host's Pi.langgraph_agentneeds packages that environment lacks, so CI's per-server run covers it.NEMO_GYM_MULTIWORKER_E2E=1 pytest tests/e2e/session_routing, which runs fix(server): route a session's requests to the worker that holds it #3905's routing cases and the two-workerinteractive_browsercase, and the same withNEMO_GYM_MULTIWORKER_STRESS=1for the stress cases.Rollout evidence
N/A for model rollouts: no verifier or agent logic changes, and the behavior changes are startup, install and file handling, which the tests above cover. On this revision, the end-to-end tests start real servers with two workers and drive sessions through them. On an earlier revision, as evidence that the adapter serves,
gym env startran these servers withnum_workers=2: resources serversarc_agi,mcqa,wordle,xlam_fc,grl_sokoban,structured_outputsandnemo_user_sim; agentsgymnasium_agent,non_executing_simple_agent,tool_simulation_agentandlanggraph_agent(ReWOO); and thenemo_user_simenvironment server. Each started two uvicorn worker processes under its parent, answeredGET /healthwith 200 on repeated requests, and the resources servers answeredPOST /seed_sessionwith 200.Compatibility
num_workers > 1, includinginteractive_browser,swebench_pro,terminal_bench_2_1,harbor_oracle_agent,browsecomp_agent, andminiswe_sandboxed_agentwithout aresources_server, which refused it before.finance_sec_searchrefuses more workers thanrequests_per_second, and its refusal names that limit.nemo_user_simsession keeps its owner as long as its tombstone,session_ttl_seconds, when that is longer thansession_close_retry_window_seconds.num_workerstimes the configured limit.tool_simulation_agentwith checkpointing accepts several workers.num_workers: 1.session_id_metrics.<main pid>.<worker pid>.json.ihevallooks up NLTK'spunktdata at startup, and downloads it if it is missing, even with one worker. Before, its first verify call did that. On a host without the data or network access, startup waits for the failed download, which does not stop it.swebench_prosandboxes stay open until the provider's TTL, as a crashed single-worker server's do. The shipped config setsttl_s: 18000, so keepttl_sset when overriding it.