Repository navigation
[core][sandbox] Kill a timed-out command's processes and decode exec output leniently - #66986
Conversation
There was a problem hiding this comment.
Code Review
This pull request improves the handling of timed-out commands in the gVisor sandbox backend by ensuring that the command and all processes it started are properly terminated, and decodes non-UTF-8 output bytes using replacement characters. Feedback on these changes suggests robustly parsing the runsc ps output header to handle potential leading warnings or empty lines, and sorting the process tree PIDs in descending order to ensure child processes are killed before their parents.
| lines = ps_table.splitlines() | ||
| header = lines[0].split() if lines else [] | ||
| if "PID" not in header or "PPID" not in header: | ||
| return {root_pid} | ||
| pid_col, ppid_col = header.index("PID"), header.index("PPID") | ||
| pgid_col = header.index("PGID") if "PGID" in header else None | ||
| rows = [] | ||
| for line in lines[1:]: |
There was a problem hiding this comment.
Assuming that the first line (lines[0]) is always the header line is fragile. If runsc ps prints any leading empty lines, warnings (e.g., WARNING: host page size mismatch), or other diagnostic output before the table, the header parsing will fail and fall back to returning only {root_pid}.
We should dynamically search for the line containing both "PID" and "PPID" to locate the header robustly.
| lines = ps_table.splitlines() | |
| header = lines[0].split() if lines else [] | |
| if "PID" not in header or "PPID" not in header: | |
| return {root_pid} | |
| pid_col, ppid_col = header.index("PID"), header.index("PPID") | |
| pgid_col = header.index("PGID") if "PGID" in header else None | |
| rows = [] | |
| for line in lines[1:]: | |
| lines = ps_table.splitlines() | |
| header = [] | |
| header_idx = -1 | |
| for i, line in enumerate(lines): | |
| fields = line.split() | |
| if "PID" in fields and "PPID" in fields: | |
| header = fields | |
| header_idx = i | |
| break | |
| if header_idx == -1: | |
| return {root_pid} | |
| pid_col, ppid_col = header.index("PID"), header.index("PPID") | |
| pgid_col = header.index("PGID") if "PGID" in header else None | |
| rows = [] | |
| for line in lines[header_idx + 1:]: |
There was a problem hiding this comment.
No longer applies after ed559ce: the kill path doesn't read the runsc ps table anymore. It reads runsc trace procfs, and _exec_processes parses each line as JSON and skips any line that isn't a process object, so a header, blank lines or a stray warning can't shift anything. test_exec_processes_follows_the_session_and_children feeds it the real output shape (a PROCFS DUMP header and blank lines) and non-JSON input.
| tree = _exec_process_tree(ps.stdout, root_pid) | ||
| except (OSError, subprocess.TimeoutExpired): | ||
| tree = {root_pid} | ||
| for pid in tree: |
There was a problem hiding this comment.
Iterating over tree (which is a set) kills processes in an arbitrary order. If a parent process is killed before its children, the children might get reparented to PID 1 (or another subreaper) and potentially perform unexpected cleanup, spawn more processes, or become harder to track.
Sorting the PIDs in descending order is a simple and effective heuristic to ensure children (which typically have higher PIDs) are killed before their parents.
| for pid in tree: | |
| for pid in sorted(tree, reverse=True): |
There was a problem hiding this comment.
Not changing this: the signal is SIGKILL, so no child can react to its parent dying first, and every PID in the list gets its own kill whether or not it was reparented. Killing children first would leave the parents running longest, free to start processes the listing missed. Since d0844d4 the command itself is killed first, the rest go in ascending PID order (parents first), and the listing repeats until it comes back empty; test_exec_timeout_kills_processes_started_during_the_kill covers a child forking in a loop, where a single pass left 57 of about 520 sleeps running.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit d5e3b66. Configure here.
pcmoritz
left a comment
There was a problem hiding this comment.
I think this is good to merge but worth finding a better upstream solution going forward since runsc trace procfs might get expensive (e.g. if a process has many open file descriptors)
…output leniently When an exec ran past its timeout, Ray killed only the `runsc exec` client. The command kept running inside the sandbox, and its output pipes stayed open until it exited, so `exec(timeout=2)` on `sleep 100` returned after 100 seconds. Now a timed-out exec kills the command and every process it started inside the sandbox, found with `runsc ps`, and returns at its timeout. `runsc kill --pgid` signals only a process group's leader, so each process is killed by PID. Commands that printed bytes that aren't valid UTF-8 failed the whole exec with a decode error. Output is now decoded with replacement characters. Signed-off-by: xyuzh <[email protected]>
runsc ps has printed a PGID column only since April 2026, so with an older runsc a background job that outlived its shell survived the timeout. With any runsc, a job that moved to a process group of its own survived too (GNU timeout calls setpgid). Either way the job kept the output pipes open until the 5 s grace ran out. runsc exec makes the command a session leader, and the processes it starts stay in that session unless they call setsid(). List processes with runsc trace procfs, which reports sessions on every runsc since 2022 and leaves out zombies, and kill the command's session and its descendants. Signed-off-by: xyuzh <[email protected]>
…is left A process can start another between the listing and its own kill. With a child shell forking in a loop, one pass killed about 460 processes and left 57 running, and the exec then waited out the 5 s grace. Kill the command first, then list and kill until a listing comes back empty, at most 5 times. Signed-off-by: xyuzh <[email protected]>
Decoding the output bytes in exec_command drops Popen's universal newlines, so \r and \r\n now come back as the command printed them, as they do from docker exec or Modal. Pin that in the test. Signed-off-by: xyuzh <[email protected]>
_kill_exec killed the command first and listed its processes afterwards. A child that left the command's session with setsid() is found only through its parent, so once the command died, that child was reparented out of reach and survived the timeout, e.g. `setsid sleep 1000 &` from the exec'd shell. The first listing now comes before any kill. Later rounds still catch processes started during the kill. If runsc can't list the processes, the command itself is still killed. Signed-off-by: xyuzh <[email protected]>
df8320c to
a1016bf
Compare
…output leniently (ray-project#66986) ## Description On timeout, `exec_command` killed only the `runsc exec` client, then waited without a timeout for the output pipes, which the command kept open in the sandbox: `exec("sleep 30; echo done", timeout=1)` returned after 30 s. Separately, one byte of output that isn't UTF-8 failed the whole exec (`'utf-8' codec can't decode byte 0xff`), losing the exit code and output. This PR changes `backend/gvisor.py`: - On timeout, `_kill_exec` lists the sandbox's processes with `runsc trace procfs` and kills by PID everything in the command's session plus its descendants (the command's PID comes from `runsc exec -internal-pid-file`). It lists before killing anything, so a `setsid` child is still found through its parent, and lists again until nothing is left, at most 5 times, because a process can fork between a listing and its kill. - Output is read as bytes and decoded with U+FFFD for invalid UTF-8. Why sessions: `runsc exec` makes the command a session leader, and its processes stay in the session unless they call `setsid()`, even after their parent exits or they change process group (GNU `timeout` does). Only `runsc trace procfs` reports sessions; the PGID column of `runsc ps` and `runsc kill --pgid` are new (April 2026) and cover one group. Behavior changes: - A timed-out exec returns at its timeout and leaves nothing running, except a daemon that called `setsid` and whose parent exited. The docs say so next to the exec example. - Line endings come back as printed. `text=True` used to turn `\r` and `\r\n` into `\n`. ## Related issues None filed. Found running SkyRL's Harbor environment on Ray Sandbox (skyrl-project/SkyRL#2467), where a stuck command held its trial for the agent's full 5,400 s timeout. ## Additional information - Not a duplicate: open PRs that touch the gVisor backend (ray-project#66932, ray-project#67022, ray-project#66821, ray-project#66471, ray-project#66470, ray-project#65898) don't change exec timeouts or output decoding. ray-project#66932 wraps `runsc exec` in its cgroup launcher, so whichever lands second needs a small merge in `exec_command`. - Tests: a parser unit test and five gVisor tests. The plain timeout and UTF-8 tests fail on master; the background-job and fork-loop tests fail on this PR's first commit (d4fafd8), and the `setsid`-child test fails if the command is killed before the listing. - Tested on a CoreWeave pod (runsc release-20261012.0), rebased on master afd4ccf: `TEST_SANDBOX=1 pytest tests/test_gvisor_backend.py tests/test_image_manager.py tests/test_image_utils.py tests/test_sandbox_config.py tests/test_sandbox_runtime.py -k "not netns"`: 117 passed, 1 skipped (`test_create_sandbox_helper` ran on its own and passed); `-k netns`: 13 passed. pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4

Description
On timeout,
exec_commandkilled only therunsc execclient, then waited without a timeout for the output pipes, which the command kept open in the sandbox:exec("sleep 30; echo done", timeout=1)returned after 30 s. Separately, one byte of output that isn't UTF-8 failed the whole exec ('utf-8' codec can't decode byte 0xff), losing the exit code and output.This PR changes
backend/gvisor.py:_kill_execlists the sandbox's processes withrunsc trace procfsand kills by PID everything in the command's session plus its descendants (the command's PID comes fromrunsc exec -internal-pid-file). It lists before killing anything, so asetsidchild is still found through its parent, and lists again until nothing is left, at most 5 times, because a process can fork between a listing and its kill.Why sessions:
runsc execmakes the command a session leader, and its processes stay in the session unless they callsetsid(), even after their parent exits or they change process group (GNUtimeoutdoes). Onlyrunsc trace procfsreports sessions; the PGID column ofrunsc psandrunsc kill --pgidare new (April 2026) and cover one group.Behavior changes:
setsidand whose parent exited. The docs say so next to the exec example.text=Trueused to turn\rand\r\ninto\n.Related issues
None filed. Found running SkyRL's Harbor environment on Ray Sandbox (skyrl-project/SkyRL#2467), where a stuck command held its trial for the agent's full 5,400 s timeout.
Additional information
runsc execin its cgroup launcher, so whichever lands second needs a small merge inexec_command.setsid-child test fails if the command is killed before the listing.TEST_SANDBOX=1 pytest tests/test_gvisor_backend.py tests/test_image_manager.py tests/test_image_utils.py tests/test_sandbox_config.py tests/test_sandbox_runtime.py -k "not netns": 117 passed, 1 skipped (test_create_sandbox_helperran on its own and passed);-k netns: 13 passed. pre-commit passes.