Skip to content

Studio: minimal OS sandbox for Python and Terminal tools on Linux and macOS - #11209

Merged
danielhanchen merged 51 commits into
unslothai:mainfrom
oobabooga:studio-minimal-sandbox-reopen
Sep 25, 2026
Merged

danielhanchen merged 51 commits into
unslothai:mainfrom
oobabooga:studio-minimal-sandbox-reopen

Conversation

@oobabooga

@oobabooga oobabooga commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

Reopened from #10526, which was merged and then reverted in be34438.

Summary

Runs Studio's Python and Terminal tools inside a real OS sandbox on Linux and macOS: bubblewrap on Linux, Seatbelt on macOS. No Node, no vendored dependency, no npm, no network proxy.

Today those tools run on the host behind software safeguards only, and tools.py says so at line 7127: "Network policy is enforced by the AST host check and the bash blocklist". A model-authored script can read ~/.aws/credentials right now.

This is deliberately not a fourth attempt at everything. It is Linux and macOS only. Windows keeps today's behaviour untouched.

What the boundary covers

Blocked:

  • writes anywhere outside the session workdir, /tmp and /dev/shm
  • reads of the user's home beyond the runtime paths the interpreter itself needs, so ~/.ssh, ~/.aws, ~/.config/gcloud, browser cookies and unrelated documents are gone
  • host process visibility, via a fresh PID namespace
  • AF_VSOCK, io_uring, and nested user namespaces

Not blocked, and the execution record states it rather than staying quiet:

  • network egress. pip install, model downloads and API calls inside a tool call keep working. A script that can still reach a secret can still send it. The record carries network_policy = "unrestricted" so the badge cannot read as more than this is. The static analysis in tools.py remains the only thing between a tool call and an outbound secret, which is why Studio: harden software sandbox against credential exfil and dynamic-path bypasses #5603 matters more after this lands, not less.
  • reads of system directories such as /usr/lib.

Strictly stronger than today on every host where it engages, and identical to today where it does not.

Nothing that runs today stops running

Three modes replace the current disable_sandbox boolean:

mode behaviour
auto (default) isolate if the host can, otherwise run exactly as today with the result labelled "no OS isolation"
required (opt in) refuse rather than run unisolated, with an actionable reason
full the existing bypass, unchanged

auto is the default and is the one mode that can never refuse. This matters because Ubuntu 23.10 and newer ship kernel.apparmor_restrict_unprivileged_userns=1, which denies the user namespace bubblewrap needs even when bubblewrap is installed. That is a large share of current Linux desktops. Fail-closed by default would take working tools away from all of them.

Measured, not asserted: in auto on a host without a sandbox, the planner hands back the argv, cwd, env and pre-exec it was given, unchanged. win32, freebsd and an unavailable Linux all come back byte identical, with no preexec_fn or pass_fds added on Windows and creationflags preserved.

Availability is probed, never inferred

An installed bubblewrap on a host that denies user namespaces looks identical to a working one until you try it. So the probe launches a real sandbox through the same prepare() the product uses, and checks that its negative controls fail. Every negative control has a matching positive control proven on the host first, because a read that fails for an unrelated reason proves nothing.

When it does fail, the message names the cause. Previously a user in this position had nothing to act on:

reason:      the bubblewrap live probe failed (exit 1): bwrap: setting up uid map: Permission denied
remediation: This host denies unprivileged user namespaces
             (kernel.apparmor_restrict_unprivileged_userns=1, the default on Ubuntu 23.10
             and newer), so bubblewrap cannot build a sandbox even though it is installed.
             Grant bwrap the userns permission with an AppArmor profile
             (/etc/apparmor.d/bwrap-userns-restrict from the apparmor-profiles package).
             Python and Terminal still run, with software safeguards only and no OS isolation.

Getting bubblewrap onto the host

install.sh now checks the tool sandbox on Linux and WSL after the build tools. It is advisory only and never fails the install or asks for elevation on its own:

  • bubblewrap missing, installer already running as root with apt: installed, like the other optional packages.
  • bubblewrap missing otherwise: prints the one command for the detected package manager (apt, dnf, pacman, zypper, apk). On Ubuntu 23.10 and newer, where installing bubblewrap alone still leaves it blocked, that command also loads Ubuntu's own bwrap-userns-restrict AppArmor profile.
  • bubblewrap installed: runs bwrap --unshare-all --ro-bind / / true and reports whether it works, whether AppArmor blocks it (with the same fix), or whether user namespaces are unavailable, as in most containers.

The runtime remediation text in os_sandbox.py names the same commands, so the installer and the capability report never disagree. macOS needs nothing: sandbox-exec ships with the OS.

A Studio home that does not exist yet (first launch, or a custom UNSLOTH_STUDIO_HOME) used to make the macOS probe fail ("no paths survived" for the Studio state deny), so tools fell back to software safeguards. It is now denied as a directory by its spellings, so the rule is never empty and a home created later is still covered. Measured on macos-15, macos-26 and macos-15-intel runners.

Review fixes since the last description

  • macOS: the workdir under the Studio home was unreadable (deny file-read-data beats allow file-read* in Seatbelt regardless of order), so every tool call on a default install failed with Operation not permitted while the probe, which runs from /tmp, passed. Fixed and measured on macos-15.
  • Linux: bwrap must resolve to a root-owned binary in root-owned, non-writable directories before it is run or probed.
  • A registered model folder that is a credential directory (~/.ssh, /etc/ssh, ~/.aws, ...) is no longer granted.
  • Studio state inside a runtime or editable path is carved out the same way as for system roots.
  • Cache revalidation and the workdir scan are bounded and shared: a stalled NFS/FUSE cache costs one bounded wait, and concurrent launches on one workdir reuse the scan in flight instead of reporting it incomplete.
  • An approved Terminal call written with ANSI-C quoting (cat $'/home/u/x') now leaves the jail as approved.
  • The installer probes bwrap with the namespaces tool calls use, and CI copies the AppArmor profile into place before loading it.

How this was tested

This workspace host denies unprivileged user namespaces, so confinement measured here would be vacuous. The confinement tests run in a privileged container where bubblewrap works, driving the real prepare_tool_launch.

check where result
Real confinement through prepare_tool_launch container 21 of 21 pass
auto runs, argv unchanged AppArmor-restricted host pass
required refuses, names the fix AppArmor-restricted host pass
full unchanged AppArmor-restricted host pass
Windows, freebsd, unavailable Linux passthrough simulated byte identical
Full regression plus 4 new suites AppArmor-restricted host 1305 passed, 13 skipped, 0 failed
Python call in the default ~/.unsloth/studio/sandbox workdir macos-15 9, was Operation not permitted before 3c8875d
Sandbox, tool loop and streaming suites macos-15 3119 passed, 13 failed (all 13 also failed on the 2026-09-20 run), 24 fixed vs the parent commit

Inside the jail: all four credential canaries unreadable, writes to /etc, /usr and / refused, workdir and private tmp writable, network reachable, host processes hidden, and numpy, Pillow and a multiprocessing spawn pool all working. Every one of the 13 skips is platform-gated and recorded as a skip rather than a pass.

What is not proven

  • macOS: the profile now runs on Darwin, and the enforcement claim is narrower than the Linux one. On a macos-15 runner the profile compiles under sandbox-exec and $HOME is unreadable from inside, checked against a host-side positive control that reads the same canary. That is two rules, not the whole profile: the rest is still asserted about the generated SBPL text rather than about kernel behaviour.
  • The unprivileged user namespace path is unproven. The container runs as root, because no combination of container flags lets an unprivileged process create a user namespace on a host with the AppArmor restriction (I tested seccomp, apparmor and cap-add variants; all fail at uid_map). That covers the mount layout, read and write confinement, network and PID isolation, but not the namespace path a real user's launch takes. CI on a runner without the restriction is what closes this.
  • The live probe runs from /tmp, not from a workdir under the Studio home, so it did not catch the file-read-data precedence bug fixed in 3c8875d; the regression test for that is on the profile text, and the kernel behaviour was measured on macos-15.
  • Nine tests in test_sandbox_files_and_storage_roots.py fail on macOS. They fail identically at this PR's merge base (56b8a6e4a) on the same runner image, so they predate it, but this PR does not fix them either.
  • Relative to the other attempts, this claims less: it is Preview on both platforms, qualified is never set, and the network is out of scope entirely.

Relationship to the other sandbox work

This PR is 2,625 lines of product code and 2,084 lines of tests. It does not supersede #10441 on Windows, which is genuinely hard and where SRT is the better answer if its Windows support firms up.

Scope of this PR

Backend only. Deliberately out of scope here, and small follow-ups:

  • routes and request-model wiring, so tool_execution_mode can be set per request
  • the UI: the per-call badge, the capability pill and the required toggle
  • sandbox_startup.py has no caller yet, so the startup notice does not print

Every existing caller gets auto, which is why the change is inert until those land.

How to test

On a host with working user namespaces, for example Ubuntu 22.04 or a container:

  1. Load a model, enable Code, and run a Python tool call. It should work as before.
  2. Ask it to read ~/.ssh/id_rsa. It should fail with a file-not-found rather than printing a key.
  3. Ask it to pip install something. It should succeed, because the network is intentionally not confined.

On Ubuntu 24.04 or newer with the stock AppArmor setting:

  1. The same tool calls should still work, unchanged.
  2. Sandbox details should report OS isolation unavailable and name the AppArmor restriction.

@oobabooga

Copy link
Copy Markdown
Member Author

Performance and compatibility measurements for auto on Linux and macOS

I compared main (e43b2baea5) with this PR (cfb68c57bb) through the real tools._python_exec and tools._bash_exec entry points. The core workloads used 15 repetitions per arm in alternating rounds. PR calls reported effective_mode: os_isolated with bubblewrap on Linux and macos-seatbelt on macOS.

The main findings are:

  • Linux pays an avoidable 0.4 to 0.6 second launch cost on every call because the full Hugging Face cache is scanned each time.
  • On both platforms, ordinary tool activity can make the chat folder fail validation permanently, leaving the model with no working tool.
  • The macOS profile denies /tmp, and both backends remove GPU access that is available on main.
  • macOS launch overhead is much smaller than Linux, but filesystem calls and child-process creation are measurably slower inside the sandbox.

I would address the cache scan, unrecoverable workdir validation, and macOS /tmp behavior before this ships, since auto is the default and every existing caller already passes it. The remaining compatibility changes should at least be documented.

Linux launch overhead

Test host: Linux 7.0, 32 threads, 94 GB RAM, NVMe, bubblewrap 0.9.0, unprivileged user namespaces enabled, and a 14,696-entry Hugging Face cache.

workload main PR delta
print("ok") 0.029 s 0.466 s +0.44 s
echo ok 0.013 s 0.429 s +0.42 s
matplotlib savefig 0.330 s 0.770 s +0.44 s
300k-row CSV groupby 0.380 s 0.758 s +0.38 s
first streamed chunk 0.036 s 0.860 s +0.82 s

Bulk disk I/O, network, CPU throughput, multiprocessing, cancellation, and parallel execution were unaffected once the child started. There is a smaller version of the macOS in-sandbox cost here as well, stat at +15% and process spawn at +26%, but the regression is almost entirely launch overhead.

The main cause is _model_cache_binds, which walks hub, datasets, xet, and assets with an lstat per entry on every launch. On this host it costs 294 to 506 ms and accounts for 85 to 95% of the overhead, even though the cache does not change between calls. With HF_HOME pointed at an empty cache, total PR overhead falls to 6 ms for Python and 11 ms for bash. At 180,027 synthetic entries, the scan costs 264 ms but shares nothing because every component exceeds the 50,000-entry cap.

The cold capability probe adds 353 ms and expires after 60 seconds. After 70 seconds idle, a call took 1.24 to 1.32 seconds on the PR against 0.040 seconds on main. Launch failures already invalidate the cached capability, so the normal TTL could be much longer.

macOS overhead and breakage

Test host: macOS 14.5 on an M1 Mac mini with 8 cores, 8 GB RAM, SIP enabled, and a 567-entry Hugging Face cache. Both hosts used the Studio Python 3.13 environment with the same libraries.

workload main PR delta
print("ok") 0.040 s 0.076 s +0.035 s
300k-row CSV groupby 0.348 s 0.422 s +0.075 s
200 process spawns, each 1.087 ms 4.069 ms 3.7x
call after 70 s idle 0.081 s 0.211 s +0.130 s

The Hugging Face cache is not scanned on macOS. A minimal call carries a 30 to 35 ms launch tax, of which about 4 ms is preparation and 14 ms is sandbox-exec itself (14.86 ms against 1.29 ms for a plain spawn); I did not attribute the remainder. There is also cost inside the sandbox: stat latency rises from 1.115 to 2.064 us, and process creation is 3.7 times slower. CPU throughput, bulk I/O, network, and multiprocessing were unchanged.

More importantly, /tmp is not writable. Python and shell writes both fail with Operation not permitted. This differs from Linux, where /tmp is writable but recreated for every call. TMPDIR, which points inside the chat folder, works and persists on both platforms, but model-written code commonly targets /tmp directly.

Apple GPU access is also gone. Main reports MPS available and runs a 2000x2000 MPS matmul in 10.7 ms. The PR reports MPS unavailable and fails to load the accelerator bundle.

Chats can become permanently unusable on both platforms

The shared workdir validator refuses every call after the chat folder passes 50,000 entries. Five ordinary pip install batches reached 51,236 entries on Linux because the PR directs packages into .unsloth-packages; the same installs on main left 1,206 entries. Once the cap was crossed, every subsequent Python and Terminal call was refused.

The same mechanism reproduces on macOS. One seaborn plotly statsmodels installation added 17,514 entries on the PR against 161 on main, while increasing later minimal-call time from 0.031 to 0.160 seconds.

Special files have the same recovery problem. A Unix socket created with socket.bind(), a FIFO created with mkfifo, or a file hard-linked from outside the workdir makes every later call fail validation. Because no tool can start, the model cannot remove the offending entry. All three cases reproduce on Linux and macOS.

Other compatibility changes

behavior Linux macOS
GPU CUDA unavailable MPS unavailable
/tmp writable, but lost between calls denied
$$ always 2, causing name collisions remains unique
background jobs die when the call ends survive
/dev listing works denied

These differences affect common generated scripts and should be documented if intentional.

Benefits and requested changes

The isolation itself behaved as described on both platforms: host dotfiles became unreadable, writes to the real home directory were refused, and host processes were hidden. Hosts where the Linux sandbox cannot engage fall back to software safeguards with no measurable overhead. Sharing the host Hugging Face cache on Linux also improved a cached 88 MB download from 4.691 to 0.918 seconds.

Before this ships, I would make these changes:

  1. Memoize _model_cache_binds per component using the path and a cheap staleness signal, or move it into the capability probe. This should reduce the measured Linux launch penalty from about 0.44 seconds to roughly 10 ms.
  2. Ensure workdir validation cannot permanently disable a chat because tool-managed packages, caches, sockets, or FIFOs crossed a limit. Possible designs include excluding tool-managed directories, cleaning up tool-created IPC nodes, or choosing an explicit recovery mode consistent with the security model.
  3. Make /tmp writable in the macOS profile, or provide a compatible redirection for programs that use it directly.
  4. Increase the capability-probe TTL and rely on the existing launch-failure invalidation path.
  5. Document the remaining PID, temporary-file, background-process, GPU, and device-access differences by platform.

@danielhanchen danielhanchen added >3000# important# new-feature# refactor# regresses# security# Moves a security boundary: sandbox, allowlist, permission or network guard labels Sep 18, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the gap this closes, that tool calls today can read files like ~/.aws/credentials with only the AST and blocklist in the way, and auto being the default is the right call for AppArmor-restricted hosts. Before I review, could you bind the GPU device nodes so CUDA tool calls keep working inside the jail, cache the model-cache bind resolution instead of walking the HF cache on every launch, and sort the workdir validation that can wedge permanently and the macOS /tmp denial you measured?

Three fixes to the Linux and macOS backends, all found by measuring the
reviewed head rather than reading it.

The workdir scan conflated two different things: a finding about the tree
(a socket, a FIFO, a device node, a nested mount, a hard link from outside)
and the scan simply running out of budget. Both refused the call. The second
should not: the workdir only ever grows, one pip install batch reaches the
50,000-entry cap because packages are directed into .unsloth-packages, and
the scan is also the thing that must run before a tool could delete anything,
so a chat that crossed the cap could never run Python or Terminal again and
could not clean itself up. Recovery meant deleting the chat. An overrun now
builds the sandbox anyway and records workdir_scan_incomplete, which reaches
the execution record. Findings stay fatal, verified by test: a planted socket,
a FIFO and an external hard link all still refuse.

The model cache walk was re-paid on every launch though the cache rarely
changes between two of them: measured here, 2.1ms empty against 44.2ms at
15,000 entries, and it scales with the cache. It is now memoized per component
on the root's identity and mtime, with a 5 minute ceiling, dropped when a
launch fails for the same reason the capability probe is dropped there. The
comment at the memo states what the key does not cover and why the residual
window is narrow.

The capability probe's 60s TTL made an idle chat pay the 353ms cold probe
again on its next message. Correctness never rested on the TTL: the key
carries the runtime identity, so a changed interpreter re-probes at once, and
a failed launch invalidates the entry outright, which is what actually covers
installing the AppArmor profile without a restart.

Measured on this branch: 406 passed, 4 skipped in the six sandbox suites.
Real confinement re-checked through prepare_tool_launch in a container where
bubblewrap works, 13 of 13, every negative control paired with a host-side
positive control proven first.
@danielhanchen

Copy link
Copy Markdown
Member

Reviewed this end to end and pushed three fixes to the branch in f2d90ebcf. The boundary itself holds up; what I changed is the part that made it unusable in ordinary use.

The boundary is real

Driven through the real prepare_tool_launch in a container where bubblewrap works, with every negative control paired against a host side positive control proven first: 13 of 13. All four credential canaries unreadable, writes to /etc, /usr and / refused, a host file outside the workdir unmodified, workdir and private tmp writable, child processes spawn, 2 host PIDs visible instead of 6.

Fallback is correct too. On a host with bubblewrap 0.9.0 installed and the AppArmor restriction active, auto runs with argv, env and cwd byte identical to base, required refuses before any payload marker exists and names the AppArmor cause, and disable_sandbox is unchanged. I also confirmed your claim that no combination of container flags gets an unprivileged process a user namespace on a restricted host. That is accurate.

The CI step does not do what its name says

This is the one I would fix before merging, because it makes the rest of the evidence look stronger than it is.

The new step is named "Install bubblewrap, so the sandbox tests run instead of skipping". On the ubuntu-24.04 runner it logs:

File /etc/apparmor.d/bwrap-userns-restrict not found, skipping...
bwrap: setting up uid map: Permission denied
::warning::bubblewrap cannot build a sandbox here; confinement tests will skip

apparmor-profiles on 24.04 does not ship that profile at that path, so apparmor_parser -r finds nothing, the || true swallows it, and bwrap still fails at uid_map. The run finishes green at 13,165 passed with every confinement test skipped. So "CI on a runner without the restriction is what closes this" is not yet closed.

Two changes fix it: run the confinement job on ubuntu-22.04, which predates kernel.apparmor_restrict_unprivileged_userns, and make the job fail rather than skip when the sandbox cannot be built. I have a workflow doing exactly that in #11357 if you want to take it from there.

Unrelated, the diff to studio-backend-ci.yml also removes the test_pr5624_regressions.py ignores. That looks like rebase noise rather than something this PR intends.

Fixes pushed in f2d90eb

The workdir scan could end a chat permanently. This was the merge blocker. scan_workdir_for_host_channels treated two different things the same way: a finding about the tree (a socket, a FIFO, a device node, a nested mount, an external hard link) and the scan simply running out of budget. Both refused the call, and tools.py deliberately excludes WorkdirUnsafeError from the auto fallback, so the refusal was final.

The workdir only ever grows, one pip install batch crosses 50,000 entries because packages are directed into .unsloth-packages, and the scan is also what must run before a tool could delete anything. So a chat that crossed the cap could never run Python or Terminal again and could not clean itself up. Recovery meant deleting the chat.

Reproduced at 52,000 entries: permanent refusal, retry never recovers. An overrun now builds the sandbox anyway and records a workdir_scan_incomplete limitation that reaches the execution record. The call it was refusing was a confined one, so refusing left the user with no working tool rather than with a weaker boundary. Findings stay fatal, and I added tests proving a planted socket, a FIFO and an external hard link all still refuse.

The model cache was walked on every launch. _model_cache_binds re-paid an O(entries) walk even though the cache rarely changes between two launches. Measured here at 2.1ms against an empty cache and 44.2ms at 15,000 entries, scaling with size, which matches your 294 to 506ms on a real one. Now memoized per component on the root's identity and mtime with a five minute ceiling, dropped when a launch fails for the same reason the capability probe is dropped there. The comment at the memo states what the key does not cover and why the residual window is narrow. Back to 0.1ms.

Probe TTL. 60s meant an idle chat paid the 353ms cold probe again on its next message. Raised to 900s. Correctness never rested on the TTL: the key carries the runtime identity, so a changed interpreter re-probes at once, and a failed launch invalidates the entry outright, which is what actually covers installing the AppArmor profile without a restart.

Results

406 passed, 4 skipped, 0 failed across the six sandbox suites, and confinement re-verified at 13 of 13 after the changes. The 3 failures in test_account_tool_confinement.py are identical at your unmodified head cfb68c57b, so they predate this.

Still open

The macOS /tmp difference is real and I have not fixed it. Linux allows /tmp writes while the Seatbelt profile grants only the per launch private_tmp, so a script targeting /tmp directly fails on one platform and not the other. Worth making the two agree rather than leaving it silently different.

The remaining compatibility items you listed, GPU hidden, $$ always 2, background jobs dying with the call, are already in LIMITATIONS, which I think is the right place for them.

I have not measured macOS Seatbelt enforcement on real hardware yet. That and the ordinary user Linux run are both in the enforcement workflow in #11357.

danielhanchen added a commit that referenced this pull request Sep 20, 2026
…e CI job

Two fixes found by running the enforcement workflow on real runners rather
than reasoning about it.

The probe's positive controls were POSIX shaped. They open an AF_UNIX
socketpair and pass a descriptor with multiprocessing.reduction.DupFd, which
is the right control on Linux and macOS because that is what a Pool or a
ProcessPoolExecutor rides. On Windows multiprocessing rides a named pipe and
duplicates HANDLEs instead, so the socketpair tests winsock rather than the
sandbox. On GitHub's windows-2025 and windows-11-arm runners it raises
WinError 10106, the requested service provider could not be loaded, on the
HOST, before any sandbox exists. The probe correctly refused to conclude and
returned VOID, which is the designed behaviour and also useless here. The
control is now the platform's own primitive: a duplex multiprocessing.Pipe on
Windows, the socketpair and DupFd everywhere else.

The Linux job installed structlog and pydantic but not pytest, so the unit
suite step failed after the measurement step had already passed.

The Linux measurement from that run is the one #11209 was missing. On an
ordinary unprivileged ubuntu-22.04 runner, not a privileged container and not
root: verdict PASS, effective_mode os_isolated, backend bubblewrap, all four
credential canaries unreadable and the workdir positive controls satisfied.
The system write targets came back as an empty set and were dropped from the
verdict rather than counted as confinement, because the runner user cannot
write /etc, /usr or / in the first place, which is exactly what pairing every
negative control with a host side positive control is for.
danielhanchen added a commit that referenced this pull request Sep 20, 2026
Both found by the Windows CI job failing, which is what it is for.

MXC grants nothing implicitly. Its policy doc is explicit: "Omitted = no
filesystem access beyond the default sandbox root". The backend granted the
interpreter tree and the workdir and nothing else, so python.exe could not
resolve ntdll, kernel32 or the CRT and the launch failed before the payload
ran. %SystemRoot% and %SystemRoot%\System32 are now granted read only, which
is the same grant the Linux backend makes by binding /usr and /lib read only,
and is already described by the system_paths_readable limitation. It widens
what a tool call can read, not what it can write.

Tier 3 also needs a one time elevated host preparation that the first version
of this did not do. wxc-host-prep.exe applies minimum rights ACEs to the
system drive root and MXC's managed descriptor to \Device\Null, and
AppContainer plus DACL is the tier every shipping Windows build lands on, so
this is not optional there. It is exposed as install_mxc_runtime.py
--prepare-host and kept separate from the download on purpose: fetching a
binary needs no privilege, and Studio should ask before changing host security
state rather than doing it silently. The binary has requireAdministrator in
its manifest and exits 65 when elevation is refused.

Also adds huggingface_hub to the CI dependency list, since the repo's session
scoped conftest imports it, and a failure only diagnostic step that re runs a
minimal policy with --debug so the next failure reports why rather than that.

Measured on real runners in the meantime, both of which are evidence #11209
did not have:

Linux, ordinary unprivileged user on ubuntu-22.04, not root and not a
privileged container: verdict PASS, effective_mode os_isolated, backend
bubblewrap, four credential canaries unreadable.

macOS, Apple Silicon macos-15: verdict PASS, backend macos-seatbelt,
os_isolation true, four credential canaries unreadable, host file outside the
workdir unmodified, every positive control satisfied. #11209 says of macOS
that "the rest is still asserted about the generated SBPL text rather than
about kernel behaviour". This measures the kernel behaviour.

The Windows argv splice step passed on both windows-2025 and windows-11-arm,
which confirms the design choice to emit no process.commandLine and let MXC
render the argv.
danielhanchen and others added 2 commits September 20, 2026 07:18
Found by reverting each functional hunk and re-running the suite. Both changes
could be removed with all 133 tests still green, which is the same as not
having made them: a later refactor reintroduces the per-launch cache walk or
drops the TTL back to 60s and CI stays green either way.

The memo test asserts the second launch does not re-walk the component, which
is the whole behaviour: measured 2.1ms against an empty cache and 44.2ms at
15,000 entries, re-paid on every call before this.

Two companion tests pin the invalidation direction, because a memo that never
expires is a stale security verdict rather than an optimisation. One asserts a
component changed through its root is re-inspected; the other asserts
reset_cache_verdicts, which tools.py calls when a launch fails, actually drops
the entry.

The TTL test asserts the constant stays at or above ten minutes and that a
seeded entry survives the 70s that used to expire it. Correctness never rested
on the TTL, since the key carries the runtime identity and a failed launch
invalidates outright, but the cost did: a call 70s after the last one measured
1.24s against 0.040s unsandboxed.

Verified falsifiable: reverting the memo fails the memo test, reverting the
TTL to 60 fails the TTL test. 137 passed with both in place.
@danielhanchen

Copy link
Copy Markdown
Member

#11209 | issue: REAL | PR as submitted: DEFECTIVE, 3 fixed by me | merge: YES AFTER the CI job measures something

ELI18

Studio's Python and Terminal tools ran model-written code directly on your
machine, so a script could read your cloud credentials and SSH keys. This makes
those tools run inside a real operating system jail on Linux and macOS, and
falls back to today's behaviour where the host cannot build one. Anyone using
Code or Terminal notices that a tool call can no longer read files outside the
chat folder, and nobody else notices anything.

Before / after

# what a user gets today what they get after the PR reproduced on main proven on branch verdict
1 a tool call reads ~/.aws/credentials and prints it the read fails: FileNotFoundError: [Errno 2] No such file or directory: '/home/.../.aws/credentials' host positive control proves the file is readable outside the jail 4 of 4 credential canaries unreadable, container and ubuntu-22.04 REAL
2 a tool call writes /etc/unsloth-escape OSError: [Errno 30] Read-only file system: '/etc/unsloth-escape' host can write the same target writes to /etc, /usr, / all refused REAL
3 a tool call sees every process on the box 2 PIDs visible instead of 6 ls /proc outside shows the host's processes fresh PID namespace confirmed REAL
4 on a host that cannot isolate, tools work identical, argv/env/cwd byte-identical, record says software_safeguards n/a, this is the no-change arm byte-identical on this AppArmor-restricted host REAL
5 (submitted PR) one pip install ends the chat: every later tool call returns Execution error: the session workdir too large to check for host channels the call runs, record carries workdir_scan_incomplete 52,000 entries, permanent refusal, retry never recovers launches; 6 of 144 routing cells move, 0 unintended REAL, fixed by me
6 (submitted PR) every launch re-walks the whole model cache memoized per component 2.1 ms empty vs 44.2 ms at 15,000 entries 0.1 ms, second call proven not to re-walk REAL, fixed by me
7 (submitted PR) an idle chat re-pays the 353 ms cold probe after 60 s TTL 900 s probe TTL was 60 s seeded entry survives 70 s REAL, fixed by me
8 a tool call can use the GPU CUDA unavailable inside the jail n/a carried as the gpu_devices_hidden limitation REAL, intended, disclosed
9 a backgrounded job outlives the tool call it dies with the call n/a detached_processes_die_with_the_call REAL, intended, disclosed

Gate A

  1. Executes on the reported path. Line-traced through the product entry
    point, not read: scan_workdir_for_host_channels and _host_channel_hazard
    EXECUTED; _cache_hazard_within_deadline and _cache_component_signature
    EXECUTED. The memo is proven behaviourally: first call walks
    (_cache_hazard_uncached true), second does not (false), and after
    reset_cache_verdicts() it walks again (true).
  2. Revert the functional hunk, keep the tests. Reverting the degradation
    fails test_a_workdir_too_large_to_check_still_launches_and_says_it_was_not_checked
    and test_an_incomplete_scan_reaches_the_execution_record.
    Finding: the cache memo and the probe TTL were unfalsifiable. 133 tests
    passed with the memo reverted and 27 with the TTL reverted. Fixed: four new
    guards added and each re-verified to fail on revert. 410 passed with them in.
  3. Prior fix. None merged. Four overlapping OPEN PRs: Studio: minimal OS sandbox for Python and Terminal tools on Linux and macOS #10526 (this PR's
    merged-then-reverted ancestor), Studio: add capability-aware OS isolation for local tools #10285, Add SRT-backed isolation for Studio Python and Terminal tools #10441, Studio: add Windows SRT isolation and shared sandbox controls #10615. Merge order matters;
    none supersedes this.
  4. Diff vs cells. 6,771 insertions for a new subsystem, not a fix, so the
    ratio is not the bloat signal it would be on a one-line change. My fix
    commit moves 6 of 144 routing cells with 0 unintended moves.

Gate B

  1. Inference: N/A, proven structurally and measured. Every tools.py hunk is
    inside execute_tool, _python_exec or _bash_exec, which run once per
    tool call. grep finds no reference to prepare_tool_launch or os_sandbox
    in llama_cpp.py or safetensors_agentic.py, so nothing new is in the
    per-token or per-layer path. Import cost measured anyway, 10 runs a side:
    base median 150.1 ms (spread 22.1), head 158.3 ms (spread 32.0). The +8.2 ms
    delta is inside the noise band.
  2. GPU detection: N/A, proven. Neither PR touches any GPU, device, CUDA or
    accelerator file, and no detection module imports the sandbox package. The
    device set Studio itself detects is untouched. Separately, the sandbox hides
    GPUs from the sandboxed tool subprocess: that is a deliberate narrowing for
    tool calls only, disclosed as gpu_devices_hidden, and is row 8 above rather
    than a Gate B2 violation.
  3. System prompt: PASS, byte-diffed. All 13 rendered tool specs hash
    identically across base, 11209 and 11357
    (PYTHON_TOOL a2147a82966da3ef, TERMINAL_TOOL c05409a4c8027f12, and the
    other 11). The prompt does not move, so no KV-cache shift and no
    exact-match run is required.

Enumeration

144 cells over mode x platform x capability x preview x workdir state.
Submitted PR to my fix: 138 identical, 6 changed, 0 violations. All 6 are
linux|avail=True|over_budget under auto and required, moving from
refuse_workdir to launch os_isolated, which is exactly the intended fix.
Every non-Linux and every clean-workdir cell is untouched.

Blast radius

_validate_workdir was retyped to return a tuple. One production reader
(sandbox_linux.py:552), which unpacks it, plus tests, all updated.
scan_workdir_for_host_channels was retyped to return a tuple: three
production readers (linux, macOS, Windows), all capture it. Every new symbol
(launch_limitations, reset_cache_verdicts, _ScanBudgetExceeded) has 0
readers outside studio/backend
.

Cross-platform

leg runner result
Linux bubblewrap ubuntu-22.04, ordinary unprivileged user PASS, effective_mode: os_isolated
macOS Seatbelt macos-15, Apple Silicon PASS, os_isolation: true
Linux confinement privileged container PASS, 13 of 13
Windows not touched by this PR unchanged

The ubuntu-22.04 leg is the unprivileged user namespace path the PR itself
calls unproven. The macos-15 leg measures kernel behaviour, which the PR says
is "asserted about the generated SBPL text rather than about kernel behaviour".

Defects found and NOT fixed, for the author

  1. The new CI step does not do what its name says. "Install bubblewrap, so
    the sandbox tests run instead of skipping" logs, on ubuntu-24.04:
    File /etc/apparmor.d/bwrap-userns-restrict not found, skipping... then
    bwrap: setting up uid map: Permission denied then
    bubblewrap cannot build a sandbox here; confinement tests will skip.
    apparmor-profiles on 24.04 does not ship that profile at that path, so
    apparmor_parser finds nothing and || true swallows it. The run is green
    at 13,165 passed with every confinement test skipped. This is why merge is
    YES AFTER: the PR's central claim that "CI on a runner without the
    restriction is what closes this" is not yet closed by its own CI.
  2. Unrelated churn in the diff. studio/backend/main.py carries three
    pure reformatting hunks (2 insertions, 8 deletions, line joining only), and
    the studio-backend-ci.yml diff removes the test_pr5624_regressions.py
    ignores. Neither relates to sandboxing.
  3. macOS /tmp differs from Linux and is not documented. Linux allows
    /tmp writes; the Seatbelt profile grants only the per-launch private_tmp,
    so a script targeting /tmp directly fails on one platform and not the
    other.

What I could NOT prove

  • Real bubblewrap confinement on this workspace host. It has bwrap 0.9.0 and
    kernel.apparmor_restrict_unprivileged_userns=1; I independently confirmed
    the author's claim that no container flag combination gets an unprivileged
    userns here. Confinement was measured in a privileged container and on
    ubuntu-22.04, not on this box.
  • test_a_tool_call_cannot_read_the_servers_stdin[terminal] is VOID, not a
    pass or a regression. It failed at both the PR head and the pre-fix head
    across 3 alternating rounds with bash: fork: Resource temporarily unavailable; the box was carrying 465 user processes from other sessions.
    Its security assertion passed in every arm; only the liveness assertion
    failed. My first single back-to-back comparison suggested my commit caused
    it, and repeating the measurement disproved that.
  • The nine pre-existing test_sandbox_files_and_storage_roots.py macOS
    failures the author reports. I did not run that file on macOS hardware.
  • Windows behaviour under this PR beyond "unchanged", since it adds no Windows
    code.

…inutes

Raising the probe TTL to 900s was about the hot path, where the verdict is
available and the host is not changing underneath it. Applied to the negative
verdict it works against the user: the cache key carries only the backend name
and the runtime identity, and neither moves when bubblewrap is installed or the
AppArmor profile is loaded, which is exactly what the remediation text tells
the user to do. So `auto` kept running without OS isolation and `required` kept
refusing calls for up to 15 minutes after the prerequisite was in place.

An unavailable verdict now keeps the original 60s TTL and an available one
keeps 900s, so the cost saving is unchanged and the remediation takes effect
about as quickly as it did before. Verified to fail with the split reverted.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 20, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 20, 2026
pre-commit-ci Bot and others added 2 commits September 20, 2026 07:49
/opt is in the Linux read allowlist and the shipped Docker layout puts Studio's
state inside it: docker/run.sh mounts the Studio volume at /opt/unsloth-studio
and studio_launch.sh exports UNSLOTH_STUDIO_HOME to match. Binding /opt whole
therefore hands auth/auth.db to model-authored Python and Terminal code
read-only. That database holds the HS256 jwt_secret, and tools.py's guard is on
the literal path, so building the path dynamically walks past it and the
disclosure survives required mode, which is the mode that exists to prevent
exactly this.

Dropping /opt outright would take away toolchains that legitimately install
there, so a system root that contains Studio's state is replaced by its
children with the state directory left out, recursively and bounded. Everything
else under the root stays readable and the state directory is never a bind
source. Roots that do not contain Studio state are untouched, so no launch pays
a listdir of /usr.

Two tests, both verified to fail with the exclusion reverted.
883 passed, 4 skipped across the sandbox suites.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Sep 25, 2026
…ded worker too

A memo hit re-stats the component and every directory the walk visited,
and did so on the request thread, partly under the scan lock. On an
NFS/FUSE cache that stalls after a clean scan, that blocks the call
before the subprocess and its timeout exist, and holds up every other
launch. The hit and the walk now both run on the bounded worker, and the
witness is checked outside the lock.
… file-read-data too

Since 98ab964 denied Studio state with (deny file-read-data ...) and
restored the workdir with (allow file-read* ...), every Python and
Terminal call in a workdir under the Studio home, which is the default
layout, failed with Operation not permitted: Seatbelt lets a rule on
the exact operation win over a rule on its wildcard, whatever the order.
The live probe runs from /tmp, so it passed and the backend stayed
selected.

Measured on macos-15 (Apple Silicon), same runner and test set, this
commit vs its parent: 37 failed -> 13 failed, 24 fixed, none new; the 13
left (4 bypass-permission, 9 storage-root) failed the same way on this
branch's 2026-09-20 macOS run, the storage-root ones also at the merge
base. Default ~/.unsloth/studio home: print(4 + 5)
returned 'Exit code 2 ... Operation not permitted' before, '9' after.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Sep 25, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 25, 2026
…loading it

apparmor-profiles ships bwrap-userns-restrict disabled under
/usr/share/apparmor/extra-profiles, so apparmor_parser on the /etc path
failed quietly and the confinement tests skipped on ubuntu-24.04. Same
command the installer prints.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Sep 25, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Sep 25, 2026
danielhanchen and others added 4 commits September 25, 2026 17:28
bwrap is executed on the host, unconfined, while a launch is prepared, so
a bwrap planted in a user-writable directory earlier on PATH would have
run with Studio's own access and could answer the probe. The resolved
binary and its directory must now be root-owned and writable only by
root, the rule macOS already applies to sandbox-exec.
pip --target writes console scripts to Scripts on Windows, and the
unisolated launch only appended bin, so a command installed into the
session was lost on the next Terminal call. The helper moves to
os_sandbox so a backend's own fallback can apply the same environment.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Sep 25, 2026
A second launch on the same workdir saw the first one's walk still
running, took it for a walk a previous launch had given up on, and
reported the workdir unchecked, which required mode refuses. It now
waits out that walk's own deadline and reuses its verdict; a walk
already past its deadline still reports incomplete at once.
--unshare-all adds the network namespace, which the sandbox never
creates, so a host that only denies that one was told bubblewrap cannot
build a sandbox.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Sep 25, 2026
… holds it

System roots already bind their children instead when the Studio home is
inside them, but a runtime or editable root containing it was bound
whole, auth.db included. Those are now carved the same way; a runtime
inside the Studio home, the managed venv, is unchanged.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Sep 25, 2026
…st path

The approval classifier decodes $'...' and prompts for cat $'/home/u/x',
but the check that lets an approved call leave the jail lexed the raw
word as $/home/u/x, so the approved read still failed inside it.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Sep 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member

pre-commit.ci run

@danielhanchen
danielhanchen merged commit 588c7df into unslothai:main Sep 25, 2026
69 of 72 checks passed
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Sep 25, 2026
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
… macOS (unslothai#11209)

Runs Studio's Python and Terminal tools in an OS sandbox on Linux (bubblewrap) and macOS (Seatbelt), with auto falling back to software safeguards where the host cannot isolate, required refusing, and full unchanged. Availability comes from a live probe with paired positive and negative controls. install.sh installs or names bubblewrap and the Ubuntu 23.10+ AppArmor profile.

Co-authored-by: oobabooga <[email protected]>
Co-authored-by: Etherll <[email protected]>
danielhanchen added a commit that referenced this pull request Oct 26, 2026
… forever (#15345)

## 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](https://github.com/shimmyshimmer/unsloth-staging-4/actions/runs/40294702755)),
including the live Seatbelt spawn test
- Ubuntu: 89 passed, 6 skipped
([run](https://github.com/shimmyshimmer/unsloth-staging-4/actions/runs/40294702709)),
including the process-group teardown test
- Windows: both modules skip as POSIX only, as expected, since Windows
never runs this probe
([run](https://github.com/shimmyshimmer/unsloth-staging-4/actions/runs/40294702719))
- Studio install, launch and Playwright smoke: OK
([run](https://github.com/shimmyshimmer/unsloth-staging-4/actions/runs/40294702799))

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.

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

important# new-feature# regresses# security# Moves a security boundary: sandbox, allowlist, permission or network guard >3000#

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants