Skip to content

Studio: stop the macOS sandbox probe from leaking processes that spin forever - #15345

Merged
danielhanchen merged 12 commits into
mainfrom
studio-sandbox-probe-fd-spin
Oct 26, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
studio-sandbox-probe-fd-spin

Conversation

@shimmyshimmer

@shimmyshimmer shimmyshimmer commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

What this fixes

On macOS, Unsloth Studio could leave behind python3.13 processes that each burn a full CPU core forever. One Studio left running overnight had 20 of them, pinning a 16-core M3 Max at a load average over 120 with the fans at full speed. Each sandbox check (re-run every 60 seconds once it fails) added another one, and the sandbox was reported as unavailable the whole time.

Root cause

The live sandbox probe runs a payload inside the Seatbelt profile, and the payload starts a child python to prove tool code can shell out. Before exec, CPython's subprocess closes inherited file descriptors. It does that by listing /dev/fd, and when it cannot, it calls close() on every fd number up to RLIMIT_NOFILE.

The profile allowed /dev/fd/<n> but not the /dev/fd directory itself, so the listing failed and CPython fell back to the brute-force loop. With an unlimited soft limit (9.2e18) that loop never finishes:

soft RLIMIT_NOFILE child spawn inside the profile
256 0.002 s
1,048,576 0.10 s
16,777,216 1.9 s
unlimited never returns (spins at 100% CPU)

Then the cleanup failed too. subprocess.run(timeout=30) killed only the payload, so the stuck child was reparented to launchd and kept spinning. Nothing capped its CPU time, and the UNAVAILABLE verdict expired after 60 seconds, so the next check started another one.

Changes

  • sandbox_macos.py: allow file-read* on the /dev/fd directory. It lists only the calling process's own descriptors, and the managed-account profile in tool_confinement.py already allows (subpath "/dev/fd"). This also stops every sandboxed tool spawn from brute-force closing 16384 fds.
  • sandbox_probe.py: run the payload in its own session and SIGKILL the whole process group on every exit path, not just the payload.
  • sandbox_probe.py: give the payload the same fd cap as a tool launch (16384, tools._sandbox_preexec) plus a 60 s RLIMIT_CPU, so the kernel ends a stuck process even if nothing is left to kill it.

Tool calls themselves were not affected. _sandbox_preexec already caps fds at 16384 and CPU at 600 s, and tool teardown is already killpg based. The probe was the only sandboxed launch with none of these guards.

Where it came from

git bisect with a behavioural check (run the real sandbox_macos probe under an unlimited soft limit; bad = timeout or a leftover process) over every commit touching the sandbox modules points at #11209 (588c7df949), which added the OS sandbox. The same code was first added in #10526 (5a55b9b43f) and reverted the next day; that commit hangs the same way. git blame puts the /dev/fd rule, the child-python step of the payload, the single-pid timeout and the 60 s UNAVAILABLE TTL all in #11209. No later commit changed this behaviour.

Verification (macOS 26, Apple Silicon)

  • Real probe, real sandbox_macos backend, soft RLIMIT_NOFILE = unlimited:

    • before: timed out after 30s, one orphan (PPID 1) left at 100% CPU
    • after: live isolation probe passed in 0.3 s, no leftover processes
  • New tests fail on main and pass with the fix:

    • test_the_fd_directory_is_listable_so_spawning_never_brute_forces_closes
    • test_a_child_spawns_promptly_under_an_unlimited_fd_limit (live Seatbelt, darwin only)
    • test_a_timed_out_probe_also_ends_what_the_payload_spawned
    • test_the_payload_runs_under_the_tool_launch_fd_and_cpu_caps
  • pytest over the sandbox suites (test_sandbox_{probe,macos,linux,level,settings_route,setup_job}, test_tool_sandbox_*, test_permission_mode_degrade, test_mxc_git_bash_namespace, test_account_tool_confinement): 728 passed, 42 skipped. test_no_read_root_reaches_the_users_home fails on this host before and after the change, because ~/.lmstudio exists here and is a model library root.

  • Staging CI (scoped to test_sandbox_macos.py and test_sandbox_probe.py), all green:

    • macOS 15: 91 passed, 4 skipped (run), including the live Seatbelt spawn test
    • Ubuntu: 89 passed, 6 skipped (run), including the process-group teardown test
    • Windows: both modules skip as POSIX only, as expected, since Windows never runs this probe (run)
    • Studio install, launch and Playwright smoke: OK (run)

Platform scope: only macOS could hit the spin. On Linux, CPython closes fds with one close_range call (Modules/_posixsubprocess.c), the soft limit cannot be unlimited, and bubblewrap runs with --die-with-parent --unshare-pid, so killing it takes the whole sandbox down. On Windows the MXC probe is separate and already tree-kills with taskkill /T /F.

Not exercised here: the Linux bubblewrap path on a real Linux host, since the change there is only the process-group teardown and the limits (Linux CPython uses close_range, so it never had the spin).

Probe once, re-check only on events

The leak multiplied because the probe re-ran on timers: a failed verdict expired after 60 s, a pass after 15 min (served stale while a background re-probe ran), and every poll of the tool-isolation answer older than 60 s started another check. On Windows the MXC probe expired after 5 min (pass), 30 s (fail) and 6 h (incompatible shell). None of these timers is needed for correctness, so they are gone:

  • sandbox_probe.py: no pass/fail TTL, no stale grace, no background re-probe thread. A verdict holds until the cache key changes (interpreter, venv or bwrap binary, re-read on every real tool launch), reset_probe_cache() runs (a launch failing in the backend, the setup job), or Settings > Refresh forces a probe. A resource-exhaustion verdict is still never cached.
  • os_sandbox.py: cached_tool_capability starts a background check only while a tool has no answer yet; polling an answered tool never probes.
  • mxc_probe.py: verdicts and the host-prep advice are kept until invalidate_cache() (setup, host preparation, Refresh, a failed MXC launch already call it).
  • The host-side positive control (an unsandboxed python that also starts a child) now goes through the same helper as the sandboxed payload: own session, the probe's fd and CPU caps, killpg on every exit path. Its subprocess.run timeout used to kill only that python.

Trade-off: a host fix that changes none of the above (for example relaxing the AppArmor user-namespace sysctl) is picked up by Settings > Refresh or the setup job instead of within a minute. Installing bubblewrap changes the key, so the next tool call re-probes.

Tests: the TTL tests are replaced by ones that advance a fake clock by a day per read, so any timer left in either cache fails them (test_a_verdict_is_held_until_an_event_not_a_timer, test_polling_an_answered_tool_never_probes_again, test_a_verdict_is_never_re_probed_on_its_own, test_a_failure_is_held_until_invalidated_not_until_a_timer), plus test_a_timed_out_host_control_also_ends_what_it_spawned. test_differential.py against the merge base: 10 tests fail on base and pass here, 0 head failures.

… forever

Under the macOS Seatbelt profile, /dev/fd/<n> was readable but /dev/fd itself was not, so
CPython's subprocess could not list open fds before exec and close()d every fd number up
to RLIMIT_NOFILE instead. With an unlimited soft limit that loop never ends. The probe's
payload spawns a child python, so the child spun at 100% CPU; the probe's 30s timeout then
killed only the payload, orphaning the child, and the UNAVAILABLE verdict re-probed every
60s, adding one more spinner each time.

- Allow reading the /dev/fd directory (it lists only the caller's own fds; the managed
  account profile already allows it).
- Run the probe payload in its own session and SIGKILL the whole group on every exit path.
- Give the payload the tool launch's fd cap (16384) and a 60s RLIMIT_CPU, so a stuck
  process ends even if nothing is left to kill it.

Introduced with the OS sandbox in #10526 (reverted) and #11209.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T11:00:19.610214Z 9904bc3 Manual request
🔒 Security Review ✅ Completed 2026-10-26T08:55:09.744493Z 46d390f Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 46d390fa98

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +266 to +268
os.kill(pid, 0)
except ProcessLookupError:
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat terminated zombies as stopped in the cleanup test

On Linux containers whose PID 1 does not reap orphaned children, killing the probe's process group leaves the grandchild as a zombie. os.kill(pid, 0) still succeeds for that terminated process, so _gone() returns false and the new regression test fails even though cleanup successfully stopped the child. I reproduced this with the helper: after SIGKILL the process state was Z, but _gone() returned false. Recognize the zombie state as terminated or arrange for the test to adopt and reap the grandchild instead of requiring its PID to disappear.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 0303924: _gone() now also treats a zombie (state Z in /proc//stat) as stopped.

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 46d390fa98

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@danielhanchen danielhanchen self-assigned this Oct 26, 2026
Drop the pass/fail TTLs, the stale-pass background re-probe and the 60 s tool
isolation re-check (sandbox_probe, os_sandbox) and the MXC probe TTLs on Windows.
A verdict now holds until the runtime identity changes, a launch fails, the
setup job runs or the user clicks Refresh, so polling never starts a probe.
# Conflicts:
#	studio/backend/core/inference/sandbox_probe.py
The host-side positive control also starts a python that starts a child, and
its subprocess.run timeout killed only that python. Both launches now share
one helper: own session, the probe's fd and CPU caps, killpg on every exit.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: dad6e275a0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

With no TTL left, a probe in flight when setup, host preparation or Refresh
cleared the cache would have published its stale verdict for good.

[skip ci]
…hanges

The gate's answer had no key, so with the TTL gone installing bubblewrap was
only noticed at the next tool launch. A stat-only key (interpreter, trusted
bwrap file) now starts one background check when it moves, which also keeps
the 'picks it up within a minute' remediation true.
Signal the probe's process group only while its leader is unreaped: after
communicate() reaps it and the group empties, the id can be reused. And give
each probe a ticket, so a slow probe that started first cannot replace the
verdict of a newer forced one, which would now stick with no TTL.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 26, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 22f0bace47

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

tool in ISOLATED_TOOLS
and not _background_probes_disabled()
and (entry is None or now - entry[0] >= _TOOL_ISOLATION_TTL_SECONDS)
and (entry is None or entry[3] != key)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep undecided resource failures eligible for another check

If a warmup or background check encounters transient resource exhaustion, capability_snapshot() returns an undecided capability, but refresh_tool_isolation() still stores it as an ordinary negative tool answer. This new condition then prevents subsequent capability reads from retrying after resources recover, despite sandbox_probe.probe() deliberately not caching that verdict. Consequently, Settings continues reporting isolation as unavailable and off_mode_still_gates() keeps requiring approval until an explicit Refresh or approved tool launch updates the answer. Preserve the undecided state in this cache and allow it to be retried rather than holding it indefinitely.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intended: no probe on a timer or a poll, including after resource exhaustion (retrying it on every read re-launches a probe while the host is still out of disk or fds). The undecided answer fails closed (off mode asks), and the first approved Python/Terminal call goes through prepare_tool_launch, which re-probes because the undecided verdict is never cached below and notes the fresh answer; Settings > Refresh does the same.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reconsidered and fixed in 9904bc3: an undecided (resource exhaustion) answer is now noted with an empty key, so the next read starts one background check instead of holding it until a Refresh; ordinary verdicts still never re-probe on a read.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 22f0bace47

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…read

A resource-exhaustion verdict is not cached by the probe, but the tool answer
kept it until a Refresh; it now carries an empty key, so the next read checks
again. Likewise an inconclusive MXC host-prep check is no longer cached as
'nothing missing'. Also update the Linux no_new_privs test for the probe's
composed preexec hook.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 9904bc3cc7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 6285c11 into main Oct 26, 2026
26 of 35 checks passed
@danielhanchen
danielhanchen deleted the studio-sandbox-probe-fd-spin branch October 26, 2026 11:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants