Skip to content

Studio: cut the per-call overhead of sandboxed Python and Terminal calls - #19408

Merged
danielhanchen merged 5 commits into
mainfrom
studio-tool-call-overhead
Nov 25, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-tool-call-overhead

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

A sandboxed tool call cost far more than the sandbox it runs in. On GitHub runners bwrap true takes 3 to 5 ms and Seatbelt about 13 ms, yet a Studio Terminal call took 50 to 130 ms and a curl call about 300 ms. Profiling the real execute_tool path showed most of that time was Studio repeating work on every call. This PR removes the repeats and keeps every check.

What changes

  • One read connection for app settings and scan folders (storage/studio_db.py).
    • A sandboxed launch reads about ten settings. Each get_app_setting used to open a fresh SQLite connection (connect, three PRAGMAs, close, all behind the process-wide sqlite_gate). That cost 1 to 3 ms per read. A cached read now takes about 56 us, against about 484 us for a one-shot connection.
    • Reads share one long-lived connection per database. Each autocommit SELECT starts a new read transaction, so a write from any connection or process is visible to the next read.
    • Every read still runs the account-retirement check that get_connection runs, so a deleted account is refused on a warm reader too.
    • The map lock only guards the lookup. Each connection has its own busy lock, and a read that finds it busy uses a one-shot connection. A database waiting on a lock never stalls another account's reads.
    • A reader is published only if the file did not move while it opened and no close ran meanwhile. It reopens when the file identity changes, is dropped after any SQLite error, and is reset in a forked child. It closes with the WAL keeper (on_wal_keeper_closed), on reset_schema_state_for_tests, and after every backend and Hub test.
    • Only the real get_connection is cached. A substituted factory (test doubles) is read through.
  • One scan memo scope per launch (os_sandbox.prepare_tool_launch). The grant-root checks re-read the HF cache homes and scan folders several times while building one policy. Nothing is kept across launches, so a credential file added between calls is still seen by the next call.
  • The egress proxy no longer sleeps on close (sandbox_egress.EgressProxy.close). Closing the listener does not interrupt a blocked accept(), so every proxied curl or wget call waited out the 0.25 s accept timeout. Close now wakes the accept loop once, with a connection that _track refuses. A second close is a no-op. Close takes about 0.5 ms instead of up to 250 ms.
  • Sandbox shim bytecode (tools._ensure_sandbox_site_bytecode).
    • The OS sandboxes mount sandbox_site read-only, so a sandboxed Python could never cache sitecustomize.py. It recompiled about 1,800 lines on every start.
    • Studio now writes the bytecode itself, once per shim version, before the first launch. It is written to the path a default child reads, ignoring the host's PYTHONPYCACHEPREFIX and -O tag.
    • The pyc is checked-hash (PEP 552), so a child validates it against the source bytes. An edit, even a same-size edit within one second, never runs stale bytecode. A child with the checked-hash pyc starts in 21 ms, against 22 ms with a timestamp pyc and 34 ms with none.
    • A read-only install, or an interpreter with another cache tag, behaves exactly as before.
  • Cheaper workdir snapshot (tools._snapshot_workdir_views, _servable_segment). The per-character lone-surrogate scan is replaced by isascii() plus a regex, and the per-file os.path.join is replaced by one join per directory. Output is unchanged.
  • Linux: duplicate interpreter paths dropped before resolution (sandbox_linux._runtime_read_paths). The bind list is identical.

Timing

tool_loop_bench.py on staging CI. It times the real execute_tool in required mode and the real tool loops driven by a scripted model. Base is main and head is this branch together with #19409 and #19410, on the same runner, alternating rounds. On Linux and macOS this PR is the only one of the three that changes these paths. Warm medians are in ms.

Runner Sandbox Python Terminal Terminal, chat session grep over 2,000 files curl
ubuntu-24.04 bubblewrap 80 -> 52 56 -> 29 80 -> 47 58 -> 29 287 -> 50
ubuntu-22.04 bubblewrap 115 -> 71 88 -> 44 127 -> 76 89 -> 46 306 -> 70
ubuntu-26.04 bubblewrap 81 -> 52 56 -> 28 80 -> 44 57 -> 32 286 -> 50
ubuntu-latest bubblewrap 73 -> 48 52 -> 27 71 -> 42 54 -> 29 285 -> 45
ubuntu-slim bubblewrap 152 -> 88 106 -> 55 156 -> 88 111 -> 55 312 -> 84
ubuntu-22.04-arm bubblewrap 89 -> 57 64 -> 31 94 -> 55 65 -> 32 294 -> 55
ubuntu-24.04-arm bubblewrap 104 -> 71 77 -> 43 108 -> 68 78 -> 44 296 -> 69
ubuntu-26.04-arm bubblewrap 104 -> 67 75 -> 40 105 -> 65 78 -> 43 296 -> 65
macos-latest Seatbelt 116 -> 75 69 -> 41 100 -> 79 72 -> 43 261 -> 53
macos-15 Seatbelt 127 -> 90 94 -> 50 119 -> 88 79 -> 57 258 -> 72
macos-26 Seatbelt 117 -> 83 78 -> 47 114 -> 76 84 -> 56 258 -> 61
xcode-27 Seatbelt 130 -> 73 69 -> 35 111 -> 61 104 -> 44 259 -> 52

Windows shares the settings, scan memo, shim and snapshot paths. The same pass on Windows, with #19409's MXC changes included:

Runner Sandbox Python Terminal
windows-11-arm MXC, native tier 369 -> 244 376 -> 190
windows-11-vs2026-arm MXC, native tier 350 -> 231 346 -> 177
windows-2025 MXC, AppContainer + DACL tier 237 -> 148 252 -> 121
windows-2025-vs2026 MXC, AppContainer + DACL tier 270 -> 184 278 -> 148
windows-latest MXC, AppContainer + DACL tier 257 -> 174 293 -> 138
windows-2022 none (Studio needs build 26100), software safeguards 41 -> 7 107 -> 10
  • The Linux, macOS and native-tier Windows rows ran every case on the real OS sandbox (bubblewrap, macos-seatbelt or mxc-processcontainer).
  • The DACL-tier runners hit the job time limit after two or three rounds, so those rows are the median over the finished rounds.
  • The tool loop itself is cheap. On Windows its overhead for three tool rounds went from 14 to 31 ms to 9 to 18 ms, and streaming costs about 17 us per chunk on both sides.

Behaviour checks

  • Settings changed mid-turn. One GGUF tool-loop turn ran four tool rounds, with changes made between rounds. Base and head produced identical rows on every Linux and macOS runner and on both Windows ARM64 runners:
    • A model folder outside the scan list is refused at first.
    • A scan folder added mid-turn is readable on the next call and is still read-only.
    • A lowered tool output limit applies to the next call.
    • The approval card's full-access upgrade keeps the OS sandbox.
  • Sandbox toggle across turns. Switching Sandbox High, then Low, then High again gives os_isolated, then software_safeguards, then os_isolated.
  • Tests:
    • New: test_studio_db_settings_reader.py and test_tool_launch_overhead.py, plus egress close tests.
    • With only the functional lines reverted (helpers kept), the shim, reader, scan memo, egress and path dedupe tests fail. The snapshot rule tests pass both ways, as they should.
    • The sandbox, tool, settings, account, tool-loop and Hub suites show the same failing test IDs on base and head.

Compared with the bare sandbox

Same runners as the timing table, warm medians in ms.

  • Host runs true and python -c pass with no sandbox.
  • Bare sandbox runs the same two commands under a minimal profile:
    • Linux: bwrap --ro-bind / / --dev /dev --proc /proc --unshare-all --die-with-parent
    • macOS: sandbox-exec -p '(version 1)(allow default)'
  • Studio is a full tool call through execute_tool in required mode, with no chat session.
Runner Host shell / Python Bare sandbox shell / Python Studio Terminal, base -> head Studio Python, base -> head
ubuntu-24.04 0.4 / 17 2.7 / 20 56 -> 29 80 -> 52
ubuntu-22.04 0.8 / 27 5.3 / 32 88 -> 44 115 -> 71
ubuntu-26.04 0.5 / 25 3.9 / 30 56 -> 28 81 -> 52
ubuntu-latest 0.8 / 27 5.6 / 33 52 -> 27 73 -> 48
ubuntu-22.04-arm 0.6 / 22 3.6 / 25 64 -> 31 89 -> 57
ubuntu-24.04-arm 0.6 / 21 3.7 / 25 77 -> 43 104 -> 71
ubuntu-26.04-arm 0.7 / 22 4.4 / 26 75 -> 40 104 -> 67
macos-latest 3.1 / 34 15 / 42 69 -> 41 116 -> 75
macos-15 4.1 / 34 13 / 42 94 -> 50 127 -> 90
macos-26 4.7 / 40 13 / 56 78 -> 47 117 -> 83
xcode-27 3.6 / 33 13 / 41 69 -> 35 130 -> 73

How to read the table:

  • The bare sandbox adds 2 to 6 ms with bubblewrap and about 10 ms with Seatbelt. Studio added about 50 to 85 ms on top of that before this PR. After it, the gap above the bare sandbox is about 20 to 50 ms.
  • That gap is not all removable. Studio's real profile does more than the bare one:
    • Linux adds seccomp, Landlock, a fresh /tmp, runtime, model and identity binds, and per-launch identity files.
    • macOS adds a generated SBPL profile with literal-only rules.
    • Both sides also run the safety checks, the workdir snapshot that drives the file cards, PID tracking for cleanup, and output budgeting.
    • Python additionally loads the sandbox sitecustomize shim.
  • The host and bare-sandbox columns come from an earlier pass on the same runner images.
  • ubuntu-slim is left out because its bare-sandbox Python number matched true, so that probe did not run Python.

Reuse one read connection for app settings and scan folders instead of opening a new SQLite connection per read, memoize repeated grant-root lookups within one launch, wake the egress proxy listener on close instead of waiting out its 0.25 s accept timeout, write the sandbox sitecustomize bytecode from Studio since the sandboxes mount it read-only, and trim the per-file cost of the workdir snapshot.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T06:07:24.645349Z 2754a09 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 7263534fd6

ℹ️ 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".

…d settings connection, validate shim bytecode by source hash
… reset them on fork and schema reset, pin the shim pyc next to the shim
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 2754a09dce

ℹ️ 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 22b0960 into main Nov 25, 2026
@danielhanchen
danielhanchen deleted the studio-tool-call-overhead branch November 25, 2026 07:06
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 25, 2026
…y once per stage (unslothai#19409)

On Windows a sandboxed tool call took about 210 ms on Server 2025 (DACL
tier) and about 370 ms on Windows 11 ARM64 (native tier). On the same
runners `wxc-exec` alone ran Studio's own policy in 45 ms and 102 to 124
ms. The profile shows the 9.5 MB `wxc-exec.exe` was SHA-256 hashed five
times per call. On ARM64 two of those hashes alone took 34 ms. The
policy was also serialized four times per call.

## What changes

- **One digest per launch, taken under the guard**
(`mxc_runtime._acquire`).
- The runtime used to be validated before and after the deny-write
handle was opened. The handle denies write, rename and delete for the
whole lease, so a single digest taken after it opens covers the bytes
`wxc-exec` will run.
- The host and architecture gates run before any artifact is opened, as
the selectors did, and a reparse-point executable is refused before the
open.
- The verified path must equal the path resolved before the guard
opened, so a path redirected while the guard opens is refused.
- **Installation identity cached by file identity, for the per-call
fingerprints only** (`mxc_runtime.installation_identity`).
- Capability fingerprints read this three times per call. The cache key
is the path, architecture and approved size and digest. A hit also needs
the same device, inode, size, mtime, creation time (birth time, or
`st_ctime` on older Windows Pythons) and link count. Any change, or a
new pin, forces a full rehash, and a failed rehash drops the old
verdict.
- This identity never authorizes a launch: `acquire_runtime` still
verifies the bytes.
- Status, setup planning, repair and host preparation call the new
`verified_installation_identity`, which always rehashes. A failed full
verification also drops the cached identity.
- `install_mxc_prebuilt` drops the cache after a swap, and so does the
backend refresh that runs after setup and on Settings refresh.
- **Policy serialized once per stage**
(`mxc_policy.policy_hash_of_bytes`, `mxc_adapter.spawn`). Building the
request serialized the config for its bytes and again for its hash, and
dispatch did both again. Each stage now hashes the bytes it just
produced. Dispatch still compares both the bytes and the digest, and
sends exactly the verified bytes.
- **No read-grant lease when the DACL fallback is off**
(`mxc_read_grants.hold_before_build`, `hold_for_request`). Each launch
and probe took the record lock, created and deleted a lease file, and
ran a deferred-revoke check, even on the native tier.
- With the fallback off the request carries `allowDaclMutation: false`,
so `wxc-exec` cannot pick the AppContainer + DACL tier.
- That tier is the only one that skips its own grant where a recorded
ACE already covers a path. It was the reason unslothai#12215 leased every launch.
- A request built with DACL allowed is still leased before spawn, with
fresh switches, even if the switch turned on after the first check.
- The lease is tried once: a best-effort lease that already failed is
not retried, so a contended record lock is never waited on twice.
- The rules for when a failed lease refuses the launch are unchanged
from `main`.
  - **Please look at this one closely.** It narrows a rule from unslothai#12215.
- **Each exact runtime read root checked once**
(`mxc_policy._runtime_read_roots`). On Windows
`site.getsitepackages()[0]` equals `sys.prefix`, so that root was
canonicalized twice. Only an exact repeat is skipped; any other
spelling, including a case variant, still gets its own checks.

Unchanged:
- The workload, workdir and alias identity checks.
- Both workdir scans.
- The fresh DACL consent check.
- The rule against an uncertain host replay.

## Measurements

| What | Base | Head |
|---|---|---|
| `acquire_runtime` on a GitHub x64 runner | 17 ms (two digests) | one
digest |
| Build plus spawn per launch, real path with Windows faked on Linux |
11.4 ms | about 5.5 ms |
| Digests per warm launch | 5 | 1 |

End to end on staging CI, `tool_loop_bench.py` times the real
`execute_tool` in `required` mode. Base is `main`. Head is this branch
together with unslothai#19408 (settings, scan memo, shim bytecode) and unslothai#19410
(macOS only). Warm medians are in ms, with no chat session.

| Runner | Tier | Python | Terminal | `grep` over 2,000 files |
|---|---|---|---|---|
| windows-11-arm (Win11 ARM64) | native BaseContainer | 369 -> 244 | 376
-> 190 | 393 -> 211 |
| windows-11-vs2026-arm (Win11 ARM64) | native BaseContainer | 350 ->
231 | 346 -> 177 | 357 -> 192 |
| windows-2025 (Server 2025) | AppContainer + DACL | 237 -> 148 | 252 ->
121 | 264 -> 130 |
| windows-2025-vs2026 (Server 2025) | AppContainer + DACL | 270 -> 184 |
278 -> 148 | 286 -> 157 |
| windows-latest (Server 2025) | AppContainer + DACL | 257 -> 174 | 293
-> 138 | 300 -> 149 |

- Every row ran on `mxc-processcontainer`.
- The DACL-tier runners hit the job time limit after two or three
rounds, so those rows are the median over the finished rounds.
- The bare `wxc-exec` floor is about 102 to 136 ms on the native tier
and 38 to 56 ms on the DACL tier (see below), so Studio's own share of a
native-tier Python call went from about 240 ms to about 120 ms.
- A chat session still adds a lot on Windows: about 100 to 120 ms on the
native tier and about 430 to 700 ms on the DACL tier. That cost is
outside these changes and is the next thing to profile.
- The mid-turn settings checks (scan folder added, output limit lowered,
full-access upgrade, Sandbox High, Low, High) gave identical rows on
base and head on both ARM64 runners.

## Tests

- **`test_mxc_launch_repeats.py`:** serialization counts, the lease when
DACL is off and on, a switch turned on mid-launch, a failed lease tried
once, exact-repeat root dedupe, and a wrong hash still refused.
- **`test_mxc_runtime_integrity.py` additions:**
  - one digest, taken after the guard opens;
- the identity cache rehashes on file change and on a new pin, and drops
a verdict that fails to verify;
  - status and repair verify the bytes even with a cached identity;
  - an unsupported host is refused before any artifact is opened;
  - a path redirected while the guard opens is refused;
  - a corrupt runtime still fails the lease after a cached identity.
- **Removed case:**
`test_a_launch_holds_the_read_grants_until_its_last_cleanup` asserted
the old always-lease behaviour with DACL off. That one case is dropped.
- **Suite comparison:** the MXC, sandbox settings, setup and install
suites show the same failing test IDs on base and head.


## MXC versions

All numbers are bare `wxc-exec` (no Studio) running the same
ProcessContainer profile Studio builds, as warm medians in ms on GitHub
runners.
- `cmd` runs `cmd /d /c echo 1`.
- `python` runs `python -S -c "print(1)"` with the Python install
granted read-only.
- 0.8.0 and 0.9.0 ran today's `0.8.0-alpha` config. 1.0.1 and 1.1.0
refuse that config and ran the schema `1.0.0` form. That form only
changes the network fields: `network.egress.default = "allow"` and
`network.ingress = {"default": "allow", "hostLoopback": "deny"}`. With
those values it still blocks host loopback and allows internet egress,
like 0.8.0 does today.

| Runner | Tier | Workload | 0.8.0 (pinned) | 0.9.0 | 1.0.1 | 1.1.0 |
|---|---|---|---|---|---|---|
| windows-11-arm (Win11 26200, ARM64) | native BaseContainer | cmd | 127
| 103 | 102 | 103 |
| windows-11-arm | native BaseContainer | python | 135 | 111 | 110 | 110
|
| windows-11-vs2026-arm (Win11 26200, ARM64) | native BaseContainer |
cmd | 136 | 111 | 110 | 108 |
| windows-11-vs2026-arm | native BaseContainer | python | 143 | 121 |
118 | 118 |
| windows-2025-vs2026 (Server 2025, x64) | AppContainer + DACL | cmd |
44 | 40 | 38 | refused |
| windows-2025 (Server 2025, x64) | AppContainer + DACL | cmd | 56 | 52
| 50 | refused |
| windows-2022 (Server 2022, x64) | AppContainer + DACL | cmd | 39 | 43
| 38 | refused |
| Server 2025 / 2022 | AppContainer + DACL | python | 14 to 27 s | 14 to
27 s | 14 to 27 s | refused |

| `wxc-exec --probe` | 0.8.0 | 0.9.0 | 1.0.1 | 1.1.0 |
|---|---|---|---|---|
| Win11 ARM64 | 65 to 69 ms, base-container | 42 to 45 ms,
base-container | 40 to 43 ms, base-container | 43 ms, base-container |
| Server 2025 | 18 to 19 ms, appcontainer-dacl | 18 to 20 ms,
appcontainer-dacl | 18 to 20 ms, appcontainer-dacl | 18 to 20 ms, no
tier |

What this means:
- On the native tier, 0.9.0 and later are about 20 ms faster per call
than the pinned 0.8.0. 1.0.1 and 1.1.0 match 0.9.0.
- 1.1.0 removed the AppContainer + DACL tier (microsoft/mxc#1558). It
refuses every config on Server 2025 and Server 2022 with exit -1,
`backend_unavailable`. Its probe still exits 0 but reports no tier.
- 1.0.1 is the newest release that still runs the DACL tier, and it does
so with the schema `1.0.0` config.
- The multi-second DACL `python` rows show why unslothai#12121's persistent read
grants exist. Without them the DACL tier re-ACLs the whole granted
Python tree on every launch. Studio's own DACL calls below grant once
and stay around 200 ms.
- Upgrading the pin is a separate change from this PR.

## Bare sandbox vs MXC vs Studio

Warm medians in ms.
- **Host** runs the shell and Python with no sandbox.
- **Bare sandbox** runs the same two commands under:
  - Linux: `bwrap --ro-bind / / --dev /dev --proc /proc --unshare-all`
  - macOS: `sandbox-exec -p '(version 1)(allow default)'`
  - Windows: `wxc-exec` 0.8.0 with Studio's profile
- **Studio** is a full `execute_tool` call in `required` mode on `main`,
with no chat session on Linux and macOS.

| Runner | Sandbox | Host shell / Python | Bare sandbox shell / Python |
Studio Terminal / Python (`main`) |
|---|---|---|---|---|
| ubuntu-24.04 | bubblewrap | 0.4 / 17 | 2.7 / 20 | 55 / 92 |
| ubuntu-24.04-arm | bubblewrap | 0.6 / 21 | 3.7 / 25 | 78 / 120 |
| macos-latest | Seatbelt | 3.1 / 34 | 15 / 42 | 69 / 108 |
| macos-15 | Seatbelt | 4.1 / 34 | 13 / 42 | 85 / 123 |
| windows-2025-vs2026 (Server 2025) | MXC 0.8.0, DACL tier | 7.4 / 31 |
44 / see above | 213 / 194 |
| windows-2025 (Server 2025) | MXC 0.8.0, DACL tier | 10 / 42 | 56 / see
above | 252 / 255 |
| windows-11-arm (Win11 ARM64) | MXC 0.8.0, native | 16 / 26 | 127 / 135
| 365 / 375 |
| windows-11-vs2026-arm (Win11 ARM64) | MXC 0.8.0, native | 18 / 29 |
136 / 143 | 401 / 374 |

What this means:
- The bare sandbox costs 2 to 6 ms with bubblewrap and about 10 ms with
Seatbelt.
- MXC costs 30 to 50 ms on the DACL tier and about 110 ms on the native
tier. That cost is container creation inside Windows, so Studio cannot
remove it.
- On top of the bare sandbox, Studio adds about 150 to 260 ms on
Windows, against 50 to 85 ms on Linux and macOS.
- This PR targets the Windows-only part of that gap: the five digests of
the 9.5 MB `wxc-exec.exe` (about 34 ms on ARM64 for two of them) and the
repeated policy work.
- unslothai#19408 removes the shared part: settings connections, grant-root
lookups and the shim bytecode.
- The head numbers for both Windows tiers are in the Measurements
section above.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 25, 2026
…tbelt paths once per render (unslothai#19410)

On macOS every tool call spawns `ps` to record the start time of the
tracked child (`adopt_pid`), and again when forgetting it. The Seatbelt
profile render also resolves the same path spellings many times. This PR
replaces the successful `ps` lookup with a libproc query and memoizes
path resolution within one render.

## What changes

- **libproc process identity** (`utils/process_lifetime.py`).
- On darwin, `_pid_identity` and `_pid_is_zombie` ask
`proc_pidinfo(PROC_PIDTBSDINFO)` in `/usr/lib/libproc.dylib`.
- The start time comes from the same kernel field `ps -o lstart` prints
(adv_cmds `ps/print.c`, xnu `proc_info.c`). The struct layout matches
xnu `proc_info.h`: 136 bytes, start time at offset 120.
- The text is built with `time.asctime`, the C-locale `%c`, so it never
depends on the locale Python itself runs in. `ps` only sees the
inherited environment.
  - Zombies are answered too, via the zombie flag in `proc_info.c`.
- libproc is used only when the inherited locale is one whose `ps` text
is known (`C`, `POSIX`, `C.UTF-8` and the `en_US` spellings) and
`PATH_LOCALE` is unset. Every other locale falls back to `ps` as before.
- Any libproc failure (missing library, a ctypes error, a short read,
another pid's record, an errno other than `ESRCH`, an out-of-range start
time) falls back to `ps`. errno is cleared before the call, so a stale
`ESRCH` is never read as "gone".
- Only pids inside `pid_t` reach libproc. A bool or an int that would
truncate into another pid goes to `ps`.
  - The library is loaded once under a lock.
- **Seatbelt render memo** (`sandbox_macos.build_profile`,
`runtime_read_paths`, `runtime_paths_under`).
- Within one render, each path spelling is resolved once and
`_sbpl_string` quoting is cached.
- The memo is cleared after every render, so the next launch resolves
everything fresh, and a rejected path still refuses.
- Both runtime scans skip repeated candidates before any filesystem
call. `sys.executable` stays first, so its identity check still applies.

## Compatibility

- The start-time part of a libproc identity is the same text `ps`
printed.
- The trailing command name can differ (libproc's short name versus the
`ps` argv name). macOS identities are compared on the first five
start-time tokens only, so old records still match new ones both ways.
Exact identity comparisons happen only on Windows.
- The rendered Seatbelt profile is byte-identical to the previous
renderer on four inputs:
  - a symlinked workdir with a runtime alias;
  - a non-ASCII path;
  - `/tmp` aliasing with an egress port;
  - the real runtime paths.

## Tests

- `test_process_lifetime_darwin_libproc.py`:
- struct offsets, zombies, a gone pid returning `None` without running
`ps`, and identity equality with `ps` records;
  - Python's own `LC_TIME` not changing the identity;
- the locale gate admitting only known spellings, and `PATH_LOCALE`
keeping `ps`;
- the ctypes result mapping (full record, another pid, short read,
`ESRCH`, `EPERM`), a failed call that leaves errno alone, pids outside
`pid_t`, and a native failure falling back to `ps`;
- on macOS only, the libproc identity of a real child matched against
the system `ps`.
- `test_sandbox_macos_render_memo.py`: byte-identical profiles, a fresh
memo per render, and each runtime scan resolving a repeated prefix once.
It skips on Windows like the existing Seatbelt suite.
- With only the functional lines reverted (helpers kept), the libproc,
locale and memo-count tests fail. The byte-identity tests pass both
ways, as they should.
- The macOS sandbox and process-lifetime suites show no failures on base
or head.

## Timing

`tool_loop_bench.py` on staging CI times the real `execute_tool` in
`required` mode under `macos-seatbelt`. Base is `main`. Head is this
branch together with unslothai#19408, which carries most of the macOS gain
(settings, scan memo, shim bytecode, egress close). Warm medians in ms,
no chat session.

| Runner | Python | Terminal | `curl` |
|---|---|---|---|
| macos-latest | 116 -> 75 | 69 -> 41 | 261 -> 53 |
| macos-15 | 127 -> 90 | 94 -> 50 | 258 -> 72 |
| macos-26 | 117 -> 83 | 78 -> 47 | 258 -> 61 |
| xcode-27 | 130 -> 73 | 69 -> 35 | 259 -> 52 |

On its own, this PR saves the two `ps` spawns per call (one on adopt,
one on forget) and part of the render: on Linux with darwin faked, a
render went from 4.8 ms to 3.9 ms.
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.

1 participant