Repository navigation
Studio: minimal OS sandbox for Python and Terminal tools on Linux and macOS - #11209
Conversation
Performance and compatibility measurements for
|
| 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:
- Memoize
_model_cache_bindsper 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. - 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.
- Make
/tmpwritable in the macOS profile, or provide a compatible redirection for programs that use it directly. - Increase the capability-probe TTL and rely on the existing launch-failure invalidation path.
- Document the remaining PID, temporary-file, background-process, GPU, and device-access differences by platform.
|
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.
|
Reviewed this end to end and pushed three fixes to the branch in The boundary is realDriven through the real Fallback is correct too. On a host with bubblewrap 0.9.0 installed and the AppArmor restriction active, The CI step does not do what its name saysThis 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
Two changes fix it: run the confinement job on Unrelated, the diff to Fixes pushed in f2d90ebThe workdir scan could end a chat permanently. This was the merge blocker. The workdir only ever grows, one Reproduced at 52,000 entries: permanent refusal, retry never recovers. An overrun now builds the sandbox anyway and records a The model cache was walked on every launch. 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. Results406 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 Still openThe macOS The remaining compatibility items you listed, GPU hidden, 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. |
…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.
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.
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.
|
#11209 | issue: REAL | PR as submitted: DEFECTIVE, 3 fixed by me | merge: YES AFTER the CI job measures something ELI18Studio's Python and Terminal tools ran model-written code directly on your Before / after
Gate A
Gate B
Enumeration144 cells over mode x platform x capability x preview x workdir state. Blast radius
Cross-platform
The Defects found and NOT fixed, for the author
What I could NOT prove
|
…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.
/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.
…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.
…xes into the Windows MXC branch
…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.
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.
…indows MXC branch
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.
… into the Windows MXC branch
… 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.
…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.
|
pre-commit.ci run |
… 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]>
… 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]>
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.pysays so at line 7127: "Network policy is enforced by the AST host check and the bash blocklist". A model-authored script can read~/.aws/credentialsright 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:
/tmpand/dev/shm~/.ssh,~/.aws,~/.config/gcloud, browser cookies and unrelated documents are goneNot blocked, and the execution record states it rather than staying quiet:
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 carriesnetwork_policy = "unrestricted"so the badge cannot read as more than this is. The static analysis intools.pyremains 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./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_sandboxboolean:auto(default)required(opt in)fullautois the default and is the one mode that can never refuse. This matters because Ubuntu 23.10 and newer shipkernel.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
autoon a host without a sandbox, the planner hands back the argv, cwd, env and pre-exec it was given, unchanged.win32,freebsdand an unavailable Linux all come back byte identical, with nopreexec_fnorpass_fdsadded on Windows andcreationflagspreserved.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:
Getting bubblewrap onto the host
install.shnow 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:bwrap-userns-restrictAppArmor profile.bwrap --unshare-all --ro-bind / / trueand 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.pynames the same commands, so the installer and the capability report never disagree. macOS needs nothing:sandbox-execships 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
deny file-read-databeatsallow file-read*in Seatbelt regardless of order), so every tool call on a default install failed withOperation not permittedwhile the probe, which runs from/tmp, passed. Fixed and measured onmacos-15.bwrapmust resolve to a root-owned binary in root-owned, non-writable directories before it is run or probed.~/.ssh,/etc/ssh,~/.aws, ...) is no longer granted.cat $'/home/u/x') now leaves the jail as approved.bwrapwith 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.prepare_tool_launchautoruns, argv unchangedrequiredrefuses, names the fixfullunchanged~/.unsloth/studio/sandboxworkdirmacos-159, wasOperation not permittedbefore 3c8875dmacos-15Inside the jail: all four credential canaries unreadable, writes to
/etc,/usrand/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-15runner the profile compiles undersandbox-execand$HOMEis 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.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./tmp, not from a workdir under the Studio home, so it did not catch thefile-read-dataprecedence bug fixed in 3c8875d; the regression test for that is on the profile text, and the kernel behaviour was measured onmacos-15.test_sandbox_files_and_storage_roots.pyfail 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.qualifiedis never set, and the network is out of scope entirely.Relationship to the other sandbox work
@anthropic-ai/sandbox-runtimenpm helper: 18,464 lines, a Node runtime dependency, and fail-closed by default.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:
tool_execution_modecan be set per requestrequiredtogglesandbox_startup.pyhas no caller yet, so the startup notice does not printEvery 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:
~/.ssh/id_rsa. It should fail with a file-not-found rather than printing a key.pip installsomething. It should succeed, because the network is intentionally not confined.On Ubuntu 24.04 or newer with the stock AppArmor setting: