Skip to content

feat(core): add temporary dir helpers, save_dir and temp_dir for runtime files - #6235

Open
ananthsub wants to merge 32 commits into
mainfrom
ananthsub/runtime-write-paths
Open

ananthsub wants to merge 32 commits into
mainfrom
ananthsub/runtime-write-paths

Conversation

@ananthsub

@ananthsub ananthsub commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

Gym's runtime file writes are a cluster reliability problem. A Lustre filesystem has a small set of metadata servers shared by every job on the cluster, and every small file a Gym server creates, renames or deletes there is a metadata operation, repeated for thousands of rollouts across hundreds of nodes. The cluster team recently traced heavy metadata load on a Lustre filesystem that had failed to Gym SWE training and evaluation jobs.

Much of that load comes from where servers put their files. The server supervisor starts each server with its own source folder as the working directory, so a relative default such as results/... or cache/..., or a path built from Path.cwd(), writes into the Gym checkout, which training jobs mount from shared storage. Each server also picks its own location, cleanup and setting name.

This PR adds the helpers every server can use instead, exported from nemo_gym.core, a temp_dir setting, a per-node storage warning, and the rule in AGENTS.md and the configuration reference. It migrates no server; follow-up PRs move the existing writers. The design is in the shared doc "Gym runtime file layout: pain points and proposal".

Where files go

Kind of file Where it goes Who removes it
Needed only while a request, a session or the run is going A temporary folder under temp_dir (new), by default <system temp>/nemo_gym-<user id>/ The process that made it, when that work ends
Kept after the job: logs and screenshots someone may read later Written in a temporary folder, then copied once under <results_dir>/<server name>/ with save_dir Whoever owns the run
State a later run reads back, or generated media handed to another process The server's output_dir, by default <results_dir>/<server name>/, written once as whole files Whoever owns the run
Reused across runs cache_dir Unchanged

Each server decides what to keep with its own setting, such as keep_verification_logs; Gym core has no global switch for kept files. Core decides where files go and removes temporary ones.

Helpers in nemo_gym/core/runtime_files.py

Helper Lifetime What it does
request_temp_dir(name, *, temp_dir=None) / async_request_temp_dir(...) One request A context manager; the folder is always removed when the block exits, also on errors and cancellation. The async version creates and removes the folder on eight threads of its own, so slow removals never hold the event loop's default executor, which sandbox calls and DNS lookups need; it shields its removal and removes a folder created after the task was cancelled
session_temp_dir(name, *, temp_dir=None) and remove_temp_dir(path), or await async_session_temp_dir(...) and await async_remove_temp_dir(path) One session Returns a folder the server keeps on its session; remove_temp_dir returns whether it is gone, can be called again after a failure, and refuses any path that is not a session folder of this process, such as a request folder or a folder a tool made beside it. The async versions create and remove it on the temporary folder threads, off the event loop, and remove a folder created after the caller was cancelled
process_temp_dir(name, *, temp_dir=None) The server process The same folder for every call with the same name and temp_dir; removed when the process exits; a forked child gets its own
await save_dir(src, *, server_name, name, label=None, output_dir=None) Kept Copies a finished folder once into <results_dir>/<server name>/<name>/<rollout>/<UTC time>-[<label>-]<random>/, or under the server's output_dir, and returns that folder or None
  • save_dir never fails the request. It copies folders, regular files by content, and symlinks as symlinks, and skips sockets and other special files. It copies no permissions or times, which would cost a chmod and a utime per file on shared storage, so kept files get the user's usual permissions rather than the temporary folder's private ones or a file's execute bits. Copies run on a pool of four threads of their own, so a burst of them never holds the event loop's default executor, which DNS lookups and other file work need. A copy has no time limit, since a thread blocked on stalled shared storage cannot be stopped. A file or folder it cannot read is skipped and logged, and the rest is kept. A failure to write is logged by the copy itself, so it is reported even after the request was cancelled, removes the partial folder and returns None. A copy already running when its task is cancelled stops before its next entry and removes what it copied, since the request may remove the source next. A copy is written to <folder>.partial and renamed once complete, so a folder without that suffix always holds a whole copy, also after a process is killed mid-copy. An invalid name or server_name is a bug in the server and raises ValueError. Each kept file is one exclusive create on the destination, with no stat of it. It skips the copy, returning None, when the calling task is being cancelled, when the server's output_dir is relative, and when no results_dir is set. Call it in a finally, so a failed request's files are kept too, and outside any asyncio.timeout block: inside one that has expired, the task counts as being cancelled and nothing is kept.
  • The default temp_dir is private to each user. It is <system temp>/nemo_gym-<user id>/, created with mode 700. One that is a symlink, not a folder, or another user's is refused with an error that says to set temp_dir. An existing one that others can open, such as a folder a launcher made with mode 777, is made private again with a warning. A temp_dir argument expands ~ and must be absolute.
  • One folder per process. A process keeps every temporary folder in <temp_dir>/nemo-gym-<boot id>-<pid namespace>-<pid>-<random>/, private to the user like the folders in it, and removes it at exit. The random part, drawn once per process, keeps a new process that reuses a dead process's pid from losing its folder to the cleanup below. A killed process cannot, so the first temporary folder a process creates under a parent also removes this user's process folders from the same boot of the same host and the same namespace whose process is no longer running. Folders of another boot, host or namespace stay; the launcher's per-job temp_dir and the system's temporary-file cleaner bound those. The boot id matters because every host's initial PID namespace has the same number, so a namespace check alone would let one host delete another host's live folder on a shared directory. Any doubt about a process keeps its folder, and a failure while removing leftovers is logged and never fails the request. Leftovers are removed outside the process's lock, so a large one never holds up session removals or another temp_dir's first use. Removal makes read-only folders, such as a module cache a tool left behind, writable first; an entry it still cannot remove, such as a file a container wrote as root, is skipped so the rest is removed, and what is left is logged once. A temp_dir or process folder that something outside removed is checked and created again, and a thread that recovers late keeps what another thread already made again, and a forked child resets all per-process state, its lock and its threads.
  • A folder that cannot be created raises an error naming the setting that chose it: the temp_dir argument, the temp_dir setting, or the default.
  • Rollout folders. Kept files are grouped by current_rollout_id(), no-rollout outside a rollout, and every part of the path is percent-encoded, with a rollout id of . or .. encoded too so it never names the folder above, and a long one cut so the encoded name stays under the filesystem's limit. Today a request carries its rollout id only when model-call capture is on; giving kept files a rollout identity of their own is a follow-up in the base agent.
  • Capture cleanup is not in this PR. A capture folder is deleted only by a consumer that has already taken what it needs from it: NeMo RL, which reads the capture rows into training during the run, deletes the folders it chose at shutdown. An evaluation run keeps capture as run output.

nemo_gym/utils/processes.py holds the one rule for whether a process that left files behind may still be running, and server_runtime/runtime_dir.py's cleanup of socket folders now uses it too. For real process ids the behavior is unchanged; a number no process can have now keeps its folder instead of raising.

Helpers in nemo_gym/utils

The parts that need no Gym code live in nemo_gym/utils, so nemo_gym/core/runtime_files.py holds only where runtime files go and how long they last. utils/file_trees.py has remove_tree, which makes read-only folders writable, skips what it still cannot remove and never raises, and copy_tree, the copy behind save_dir, which another thread can stop through an event.

Storage warning on the writing node

nemo_gym/utils/filesystems.py finds the filesystem a folder is on from /proc/self/mountinfo. Each process checks temp_dir on its own node on first use, and each model server checks its capture folder when it starts writing. It logs a warning when the folder is on a filesystem shared by many hosts (Lustre, NFS, GPFS, BeeGFS, Ceph, CIFS, WekaFS, GlusterFS, PanFS, DVS), or in memory (tmpfs, ramfs), as /tmp can be inside a container. For capture, the warning adds that a shared folder is expected when capture is kept as run output, and that a run deleting capture at shutdown should place it on local disk. The setting still applies.

Documentation

AGENTS.md gets the rule under "Environment Design Recommendations". reference/configuration.mdx gets a "Files Written at Runtime" section with where each file goes, the setting, the helpers with a worked example, and cleanup; the stateful environment tutorial points to it.

Related work

Follow-ups

  • A rollout identity for kept files that does not depend on model-call capture.
  • The storage warning for the token-capture and lineage stores.
  • A check that stops new relative writes, once the existing writers have moved. A check with a list of existing sites does not fit branches that carry different servers.
  • A CODEOWNERS entry for nemo_gym/core/runtime_files.py and nemo_gym/utils/file_trees.py.
  • A review-rubric check that new servers write through these helpers.

Compatibility

No existing behavior changes: no server uses the helpers yet, an unset temp_dir only matters to code that calls them, and the new warning only logs. The new top-level key joins the reserved names, so Gym never treats it as a server instance; no config in the repository uses it.

Validation

  • New unit tests cover:
    • the default temp_dir: a private folder per user, made private again when others can open an existing one, refused when it is a symlink, a file or another user's, an error naming the setting when it or a configured temp_dir cannot be created, a temp_dir argument that expands ~ and refuses a relative path, and a folder removed from outside that is checked and created again
    • temporary folders go under temp_dir and are removed on normal exit, on an exception, when the task is cancelled, when it is cancelled while the folder is being created, under an anyio cancel scope, and on repeated cancellation while removal waits behind a busy worker thread, and while every thread of the default executor is busy
    • session folders last until removed, removal twice is fine, a failed removal is reported and retried, a coroutine creates and removes one on the temporary folder threads, a session folder created after its caller was cancelled is removed, a coroutine's removal still happens when it is cancelled while waiting behind a busy thread, and remove_temp_dir refuses any other path, including another process's folders, its own process folder, a request folder, a folder a tool made beside the session folders, and a path ending in .. that would name temp_dir itself, warning once for all of them
    • read-only folders inside a temporary folder are removed, folders with no permissions too, an entry that cannot be removed leaves its siblings removed and is logged, and an unexpected error while removing never replaces the request's own error
    • process folders are the same for every call with one name, differ by name, agree under concurrent first calls, and come back after removal from outside, and a late recovery by a second thread keeps the folders the first made again
    • in a real subprocess, exit removes every folder, and a forked child gets its own lock, threads, folder names and folders and leaves its parent's alone
    • save_dir copies into the server's results by name and rollout, gives kept files and folders the user's usual permissions, keeps symlinks and skips special files, gives each copy its own folder, honors the server's output_dir, keeps nothing for a relative output_dir or without a results_dir, each with one warning, returns None, logs once and leaves no partial folder when a copy fails, logs a copy that fails after its request was cancelled, stops a running copy whose request was cancelled and keeps nothing of it, skips and logs an unreadable file or folder and keeps the rest, keeps a failed request's files from a finally, copies nothing while the task is being cancelled or an anyio cancel scope fires, keeps files when called after an expired asyncio.timeout block, runs at most four copies at once while other thread work still runs, keeps a long label under the name limit, keeps names and labels one folder under the root, gives a . or .. rollout id a folder of its own, keeps files for a rollout id that is long once encoded, shows a copy under its name only once complete, and refuses an unsafe name or server name
    • leftover folders of dead processes on the same host, boot and namespace are removed, while those of live processes, a new process that reused a dead pid, other namespaces, other hosts or boots, other users, and unrelated files and symlinks stay, and an unknown host removes nothing
    • one folder per process, private to the user under a configured temp_dir, a process folder removed from outside made again, removing leftovers holding up no session removal or other first use, the exit handler skipped in a forked child, and concurrent first use losing no request
    • the shared liveness rule, the filesystem lookup and warning, and temp_dir parsing: null by default, made absolute without following the driver's symlinks, an empty value refused
  • The new tests fail on upstream/main, where the helpers and the setting do not exist. Undoing each review fix in turn (the copy pool, the temporary folder pool, the removal check, the read-only removal, the re-check after removal, the late-recovery check, removal past an entry it cannot remove, kept-file permissions, partial-copy cleanup, skipping unreadable entries, the absolute-path check, the after-fork reset, the owner check, the one-time warnings, making an open default private, the session-only removal, the per-process random name part, stopping a cancelled copy, the dot rollout encoding, the off-loop session creation and removal, the private process folders, the .partial rename, removing leftovers outside the lock and the rollout length cap) fails at least one test.
  • Rebased on the latest main. pytest -n 16 tests/unit_tests passed apart from tests that fail the same way on main in this environment (tool telemetry, which needs the telemetry extra) or only under parallel load (two Docker terminal tests, which pass alone), and pre-commit run on the changed files passed.
  • fern check was not run locally; the docs CI runs it.

Rollout evidence

N/A. No server changes behavior: the PR adds helpers, one configuration key with a default that changes nothing for existing servers, a warning that only logs, and documentation.

@copy-pr-bot

copy-pr-bot Bot commented Nov 16, 2026

Copy link
Copy Markdown

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.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added feature New capabilities, enhancements, or enablement work area:core Shared APIs, servers, telemetry, health, and registries labels Nov 16, 2026
@ananthsub
ananthsub marked this pull request as ready for review November 16, 2026 21:59
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 16, 2026 21:59
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

ananthsub added a commit that referenced this pull request Nov 16, 2026
#6235 replaced the debug_dir setting with a debug_files switch: every
server config has debug_files, which defaults to the global switch,
and debug folders sit under the server's results folder.

The SWE servers no longer declare their own debug_dir, and their YAML
configs drop the line. They pass debug_files=self.config.debug_files
to debug_folder, so verification logs go to
<results_dir>/<server name>/debug/verification/... when debug files
are on, and nowhere when they are off.

swebench's warning for clear_swebench_debug_logs=false now points at
debug_files, and analyze_golden_patch_logs.py says which folder to pass.

Signed-off-by: Ananth Subramaniam <[email protected]>
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the needs-review PR is ready for code review and waiting on a reviewer label Nov 16, 2026
@ananthsub ananthsub changed the title feat(core): keep server runtime writes out of the source checkout feat(core): add temporary folder helpers, save_folder and temp_dir for runtime files Nov 16, 2026
@ananthsub ananthsub changed the title feat(core): add temporary folder helpers, save_folder and temp_dir for runtime files feat(core): add temporary dir helpers, save_dir and temp_dir for runtime files Nov 16, 2026
ananthsub added a commit that referenced this pull request Nov 16, 2026
…_folder

#6235 replaced the debug_files switch with temporary folders and an
explicit save_folder call, and leaves keeping files to each server.

Each SWE server now has keep_verification_logs, off by default. Every
verification attempt writes its logs into a temporary folder on the
node, which is removed when the attempt ends. With the setting on, the
folder is copied once into
<results_dir>/<server name>/verification/<rollout>/<time>-<instance id>-attempt<n>-<random>/
after the attempt, even when it fails. So a verify never writes into the
checkout or onto shared storage while it runs.

run_keeping_logs in resources_servers/swebench/verification_logs.py does
this for all thirteen servers. The servers that report a log folder in
their verify response report the kept copy, or nothing when logs are
not kept.

Signed-off-by: Ananth Subramaniam <[email protected]>
ananthsub added a commit that referenced this pull request Nov 16, 2026
…_dir

#6235 replaced the debug_files switch with temporary folders and an
explicit save_dir call, and leaves keeping files to each server.

Each SWE server now has keep_verification_logs, off by default. Every
verification attempt writes its logs into a temporary folder on the
node, which is removed when the attempt ends. With the setting on, the
folder is copied once into
<results_dir>/<server name>/verification/<rollout>/<time>-<instance id>-attempt<n>-<random>/
after the attempt, even when it fails. So a verify never writes into the
checkout or onto shared storage while it runs.

run_keeping_logs in resources_servers/swebench/verification_logs.py does
this for all thirteen servers. The servers that report a log folder in
their verify response report the kept copy, or nothing when logs are
not kept.

Signed-off-by: Ananth Subramaniam <[email protected]>
ananthsub added a commit that referenced this pull request Nov 17, 2026
…_dir

#6235 replaced the debug_files switch with temporary folders and an
explicit save_dir call, and leaves keeping files to each server.

Each SWE server now has keep_verification_logs, off by default. Every
verification attempt writes its logs into a temporary folder on the
node, which is removed when the attempt ends. With the setting on, the
folder is copied once into
<results_dir>/<server name>/verification/<rollout>/<time>-<instance id>-attempt<n>-<random>/
after the attempt, even when it fails. So a verify never writes into the
checkout or onto shared storage while it runs.

run_keeping_logs in resources_servers/swebench/verification_logs.py does
this for all thirteen servers. The servers that report a log folder in
their verify response report the kept copy, or nothing when logs are
not kept.

Signed-off-by: Ananth Subramaniam <[email protected]>
ananthsub added a commit that referenced this pull request Nov 17, 2026
…_dir

#6235 replaced the debug_files switch with temporary folders and an
explicit save_dir call, and leaves keeping files to each server.

Each SWE server now has keep_verification_logs, off by default. Every
verification attempt writes its logs into a temporary folder on the
node, which is removed when the attempt ends. With the setting on, the
folder is copied once into
<results_dir>/<server name>/verification/<rollout>/<time>-<instance id>-attempt<n>-<random>/
after the attempt, even when it fails. So a verify never writes into the
checkout or onto shared storage while it runs.

run_keeping_logs in resources_servers/swebench/verification_logs.py does
this for all thirteen servers. The servers that report a log folder in
their verify response report the kept copy, or nothing when logs are
not kept.

Signed-off-by: Ananth Subramaniam <[email protected]>
ananthsub added a commit that referenced this pull request Nov 17, 2026
…_dir

#6235 replaced the debug_files switch with temporary folders and an
explicit save_dir call, and leaves keeping files to each server.

Each SWE server now has keep_verification_logs, off by default. Every
verification attempt writes its logs into a temporary folder on the
node, which is removed when the attempt ends. With the setting on, the
folder is copied once into
<results_dir>/<server name>/verification/<rollout>/<time>-<instance id>-attempt<n>-<random>/
after the attempt, even when it fails. So a verify never writes into the
checkout or onto shared storage while it runs.

run_keeping_logs in resources_servers/swebench/verification_logs.py does
this for all thirteen servers. The servers that report a log folder in
their verify response report the kept copy, or nothing when logs are
not kept.

Signed-off-by: Ananth Subramaniam <[email protected]>
ananthsub added a commit that referenced this pull request Nov 17, 2026
…_dir

#6235 replaced the debug_files switch with temporary folders and an
explicit save_dir call, and leaves keeping files to each server.

Each SWE server now has keep_verification_logs, off by default. Every
verification attempt writes its logs into a temporary folder on the
node, which is removed when the attempt ends. With the setting on, the
folder is copied once into
<results_dir>/<server name>/verification/<rollout>/<time>-<instance id>-attempt<n>-<random>/
after the attempt, even when it fails. So a verify never writes into the
checkout or onto shared storage while it runs.

run_keeping_logs in resources_servers/swebench/verification_logs.py does
this for all thirteen servers. The servers that report a log folder in
their verify response report the kept copy, or nothing when logs are
not kept.

Signed-off-by: Ananth Subramaniam <[email protected]>
create_owned_folder refused an existing empty folder, which a job
script's mkdir -p or a start cut short between mkdir and marker leaves.
An empty folder holds nobody's files, so mark it. Also state the
capture rule by consumer: NeMo RL deletes its capture folders at
shutdown with checkpointing on or off, and an evaluation run keeps
capture as run output.

Signed-off-by: Ananth Subramaniam <[email protected]>
- Take create_owned_folder and delete_owned_folder out: they did not
  create exclusively, their deadline did not bound a flat folder, and
  NeMo RL, their stated caller, keeps its own guarded cleanup. They land
  with a first caller.
- Check the capture folder from the writer (make_capture_store) only,
  so rollout collection reading it stays quiet, and word the warning
  for capture kept as run output.
- Never let removing leftover temporary folders fail a request: an
  impossible pid counts as running, and any error is logged.
- Remove leftovers under a shared temp_dir too; the boot id already
  keeps other hosts' folders safe.
- Reject server names that leave the debug root, accept a string
  override, create the temp parent only on first check, drop 9p and
  virtiofs from the shared list and add panfs and dvs, prune hidden
  folders in the check script, and align the docs on what is supported
  today and on the rule for a new top-level setting.

Signed-off-by: Ananth Subramaniam <[email protected]>
Add tests that fail when the cleanup shield, the leftover-removal guards
(uid, folder type, unsignalable processes), the deepest-mount rule, the
empty-setting check or the check script's skips and parsing are removed.
Keep the default-temp-directory test off the host's own /tmp, and say
in the async docstring that removal can finish after the block exits
under an anyio cancel scope.

Signed-off-by: Ananth Subramaniam <[email protected]>
…sted

The test could pass before the worker thread created the folder, so
removing the cleanup callback went unnoticed. Wait until the folder is
created after the cancel, then check it is removed. Also skip hidden
files, not only hidden folders, in the check script.

Signed-off-by: Ananth Subramaniam <[email protected]>
Three config folders added on main since this branch began only read
bundled data (mm_coding_training reference_root, agentic_mme
image_root), so mark them as reads. The agentvista output_root settings
write, so list them in the allowlist for their migration.

Signed-off-by: Ananth Subramaniam <[email protected]>
Each process now creates one folder per parent,
nemo-gym-<boot id>-<pid namespace>-<pid>, and makes its request folders
as plain mkdtemp folders inside it. The process removes that folder at
exit; the cleanup of killed processes reads only that one name format at
the top level and removes a dead process's folder with everything in
it. Request folder names no longer carry process data.

Move the "may this process still be running" rule into
nemo_gym/core/processes.py and use it from runtime_dir.py too, keeping
runtime_dir's old private name for the moved-path import surface.

Signed-off-by: Ananth Subramaniam <[email protected]>
A server's own debug_dir was only checked inside debug_folder, so a
relative value loaded fine and then failed every request that writes
debug files. Servers can type the setting DebugDir to fail at config
load instead; debug_folder uses the same check.

Signed-off-by: Ananth Subramaniam <[email protected]>
Concurrent first requests in worker threads each cleared and created
this process's folder, so one could delete another's request folder and
others failed with FileExistsError. Guard the first-use check, cleanup
and creation with one lock, and make the folder again if something
outside the process removes it. Check the server name in debug_folder
only where the name is used, so a request with debug files off never
fails over it.

Signed-off-by: Ananth Subramaniam <[email protected]>
Keep the per-server debug_dir override as a plain path. A relative
value would land in the server's source folder, so debug_folder turns
that server's debug files off with one warning instead of failing every
request; debug files never fail a request.

Signed-off-by: Ananth Subramaniam <[email protected]>
Dropping the DebugDir tests also removed the three tests after them,
which guard the first-use lock, recreating a removed process folder and
the scoped server-name check. Restore them. Also give a forked child a
fresh first-use lock, since a parent thread may have held it at the
fork.

Signed-off-by: Ananth Subramaniam <[email protected]>
The check needs an allowlist of existing sites, and one list cannot fit
both upstream main and a downstream branch that carries other servers:
there it fails on that branch's own sites and on entries that match
nothing. The rule stays in AGENTS.md and the configuration reference,
and code review enforces it until the existing writers have moved.

Signed-off-by: Ananth Subramaniam <[email protected]>
Debug files live as long as the run's output, are read by the same
people and need the same storage, so they do not earn a location of
their own. Replace the debug_dir setting with a debug_files switch,
global and per server, and write debug folders under the server's
output: <results_dir>/<server name>/debug/, or the server's own
output_dir. Runtime files now go to one of three places: temp_dir,
results_dir and cache_dir.

Every server config accepts debug_files beside uvicorn_reuse_port.
Debug folders drop the agent instance segment, which a resources server
cannot know, and no longer warn about shared storage, where kept files
belong.

Signed-off-by: Ananth Subramaniam <[email protected]>
…me and save_folder

Each server decides what to keep with its own setting, so Gym core no
longer has a debug switch, debug_folder or keep_as. Core places files
and cleans them up:

- temp_folder / async_temp_folder for one request, open_temp_folder and
  remove_temp_folder for one session, run_temp_folder for the process,
  all under temp_dir, by default <system temp>/nemo_gym/<user id>/;
- save_folder copies a finished folder once under
  <results_dir>/<server name>/<name>/<rollout>/, contents only, a few
  copies at a time per process, and returns the folder or None without
  ever failing the request or copying while the task is cancelled.

<system temp>/nemo_gym/ is shared like /tmp (mode 1777) with a private
folder per user; an unsafe shared folder falls back to
nemo_gym-<user id>/. Cleanup after a kill also removes folders from an
earlier boot when temp_dir is private to the host. A folder that cannot
be created raises an error naming the setting that chose it.

Signed-off-by: Ananth Subramaniam <[email protected]>
Gym's settings and arguments say _dir, so the helpers do too, named by
the lifetime of what they return: request_temp_dir and
async_request_temp_dir, session_temp_dir and remove_temp_dir,
process_temp_dir, and save_dir.

Signed-off-by: Ananth Subramaniam <[email protected]>
- The default temp_dir is <system temp>/nemo_gym-<user id>/, created with
  mode 700 and refused when it is a symlink, not a folder, or another
  user's. The shared mode-1777 parent and its fallback are gone.
- Leftover cleanup removes only folders of dead processes on this boot of
  this host, in this PID namespace; the earlier-boot removal is gone.
- save_dir copies on a dedicated pool of four threads, so queued copies
  never hold the default executor. It copies folders, regular files and
  symlinks, gives kept folders the user's usual permissions, skips special
  files and removes a partial copy. The docs say to call it outside any
  asyncio.timeout block.
- remove_temp_dir refuses, with a warning, any path that is not a
  temporary folder this process created.
- One removal routine makes read-only folders writable before removing
  them, and is used everywhere a folder is removed.
- A temp_dir or process folder removed from outside is checked and created
  again. process_temp_dir is a fixed process.<name> folder.
- One after-fork hook resets all per-process state, the lock and the copy
  threads.
- The temp_dir argument expands ~ and must be absolute. The missing
  results_dir warning is logged once.
- The helpers are exported from nemo_gym.core, and the filesystem helpers
  other modules do not use are private.

Signed-off-by: Ananth Subramaniam <[email protected]>
pathlib keeps "..", so <process folder>/.. passed the parent check and
removed temp_dir with every process's folders in it. The path is now
normalized before the check.

Signed-off-by: Ananth Subramaniam <[email protected]>
- A late recovery from an outside removal drops only what is really
  gone, so it no longer removes a process folder another thread has
  already made again.
- Removal skips an entry it cannot remove and goes on with the rest,
  logs what is left once, and never raises, even on a RecursionError.
- remove_temp_dir warns once for all refused paths, so the record of
  warnings stays bounded.
- save_dir skips and logs entries it cannot read instead of losing the
  whole folder, logs a failed copy from the copy itself, so a cancelled
  request's failure is still reported, and opens each kept file with
  one exclusive create.
- The default temp_dir skips the lock once it is checked.

Signed-off-by: Ananth Subramaniam <[email protected]>
A failed save_dir copy removed its destination even when dest.mkdir()
had failed because the folder was already there. It now removes the
destination only after creating it.

Signed-off-by: Ananth Subramaniam <[email protected]>
A copy blocked on stalled shared storage cannot be stopped from Python;
a caller with a time budget wraps save_dir in asyncio.wait_for, which
returns on time while the copy finishes on its thread. A test checks
both.

Signed-off-by: Ananth Subramaniam <[email protected]>
The liveness rule, the filesystem lookup, and tree removal and copying
import nothing from nemo_gym, so they belong in nemo_gym/utils:
processes.py and filesystems.py move there, and remove_tree and
copy_tree move out of runtime_files.py into utils/file_trees.py. Core
keeps where runtime files go and how long they last.

Each new module now lists its public functions before its private
helpers.

Signed-off-by: Ananth Subramaniam <[email protected]>
Bounding save_dir with asyncio.wait_for exits the temporary folder's
block while the copy still reads it, so most files are lost. Keep only
that a copy has no time limit, and rewrap copy_tree's docstring.

Signed-off-by: Ananth Subramaniam <[email protected]>
async_request_temp_dir created and removed its folder with asyncio.to_thread, on the
event loop's default executor. Sandbox calls and DNS lookups share that executor, so a
burst of slow removals held their threads. The folder work now runs on a small pool of
its own, reset after fork like the copy pool, and a folder created after a cancel is
removed on that pool instead of on the event loop.

Signed-off-by: Ananth Subramaniam <[email protected]>
- The default temp_dir: an existing folder that others can open is made
  private again, with a warning, so a launcher's 0777 folder cannot let
  another user rename or replace this user's folders.
- Session folders now start with "session.", and remove_temp_dir removes
  only those, so a request folder or a folder a tool made beside them is
  refused.
- async_remove_temp_dir removes a session folder on the temporary folder
  threads, off the event loop.
- Process folder names end with a random part drawn once per process, so
  removing a dead process's folder never removes the folder of a new
  process that reused its pid. The same-name clearing before use goes.
- save_dir: a copy already running when its task is cancelled stops and
  removes what it copied, since the request may remove the source next.
  copy_tree takes a stop event and raises CopyStopped.
- A rollout id of "." or ".." gets a folder of its own instead of naming
  the folder above it.
- The save_dir docstring and the reference say that an invalid name or
  server_name raises ValueError.

Signed-off-by: Ananth Subramaniam <[email protected]>
…ed removal

remove_temp_dir now runs on worker threads through async_remove_temp_dir,
so it reads the process folders under the lock: another thread adding or
dropping one mid-iteration would otherwise raise instead of logging.

A new test cancels async_remove_temp_dir while its removal waits behind a
busy thread and checks that the folder is still removed.

Signed-off-by: Ananth Subramaniam <[email protected]>
- Process folders and process-wide folders are created with mode 700,
  like the request and session folders in them, so a configured temp_dir
  that others can open does not expose process-wide state.
- copy_tree writes into <dest>.partial and renames it to dest once
  complete, so a process killed mid-copy never leaves a kept folder that
  looks whole.
- Leftovers of dead processes are removed outside the first-use lock, so
  a large one never holds up session removals or another temp_dir's first
  use. It removes only folders of processes that are gone, so it races
  with nothing this process makes.
- async_session_temp_dir creates a session folder on the temporary folder
  threads and removes one created after its caller was cancelled; it
  shares that code with async_request_temp_dir.
- The rollout part of a kept folder's path is cut to 200 characters after
  percent-encoding, which can triple a rollout id's length past the
  filesystem's name limit.

Signed-off-by: Ananth Subramaniam <[email protected]>
A rename onto an empty folder replaces it, so copy_tree's check for an
existing destination is what keeps a copy from taking over a folder it
did not create. The existing test used a folder that was not empty, which
the rename alone refuses.

Signed-off-by: Ananth Subramaniam <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core Shared APIs, servers, telemetry, health, and registries feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer risk:high Autobot PR risk: high sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants