codex icon indicating copy to clipboard operation
codex copied to clipboard

Metal devices are invisible inside sandbox on Apple Silicon, which causes false MLX failures

Open weypro opened this issue 7 months ago • 3 comments

What version of Codex CLI is running?

latest

What subscription do you have?

plus

Which model were you using?

No response

What platform is your computer?

No response

What terminal emulator and version are you using (if applicable)?

No response

What issue are you seeing?

Inside the sandbox, Metal is not visible to the process. This makes MLX-based checks fail inside the sandbox even though they work in a normal terminal on the same machine.

What steps can reproduce the bug?

Repro in sandbox(codex):

mkdir -p .cache/swift-module .cache/xcode-home
CLANG_MODULE_CACHE_PATH="$PWD/.cache/swift-module" \
HOME="$PWD/.cache/xcode-home" \
swift -e 'import Metal
let all = MTLCopyAllDevices()
let defaultName = MTLCreateSystemDefaultDevice()?.name ?? "<nil>"
print("all_devices_count=\(all.count)")
print("default=\(defaultName)")'

Observed in sandbox:

all_devices_count=0
default=<nil>

Then:

python -c 'import mlx.core as mx; print("ok", mx.float32)'

Observed in sandbox:

  • MLX may abort during Metal init instead of failing gracefully.

Control result in a normal terminal on the same machine:

all_devices_count=1
default=Apple M5
ok mlx.core.float32

Expected:

  • Either expose Metal consistently, or clearly document that Metal is intentionally unavailable in sandboxed sessions.

What is the expected behavior?

No response

Additional information

https://github.com/ml-explore/mlx/issues/3148

weypro avatar Apr 06 '26 18:04 weypro

Additional reproduction affecting Blender EEVEE on Apple Silicon, observed 2026-09-08.

Environment:

  • Apple M5 Pro; macOS 26.6.2.
  • ChatGPT desktop with Codex tasks: 26.901.51231 (build 8109).
  • Blender 5.2.1 ARM64, build 9e2066aef7ef.
  • The task uses restricted workspace-write execution with networking disabled. All Metal probes and the reported Blender launches used this restricted executor, without escalation.

A minimal check reproduces the unavailable device without launching Blender:

import ctypes

metal = ctypes.CDLL('/System/Library/Frameworks/Metal.framework/Metal')
metal.MTLCreateSystemDefaultDevice.argtypes = []
metal.MTLCreateSystemDefaultDevice.restype = ctypes.c_void_p
device = metal.MTLCreateSystemDefaultDevice()
print('default_device_available=', bool(device))
if device:
    cf = ctypes.CDLL('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation')
    cf.CFRelease.argtypes = [ctypes.c_void_p]
    cf.CFRelease.restype = None
    cf.CFRelease(device)

Observed repeatedly: default_device_available= False. A separate MTLCopyAllDevices() check returned an array count of 0. The system IORegistry nevertheless reports an active Apple M5 Pro GPU. No new unsandboxed control was run during this diagnosis.

Downstream symptom: two Blender background launches with factory startup and embedded-script autoexecution disabled exited with SIGSEGV during startup, before the task Python script ran. The preserved Blender crash stacks both contain:

_platform_strstr
blender::gpu::supports_barycentric_whitelist(id<MTLDevice>)
blender::gpu::MTLBackend::metal_is_supported()
blender::GPU_backend_type_selection_detect()
wm_homefile_read_ex
WM_init

The first macOS report also shows EXC_BAD_ACCESS / KERN_INVALID_ADDRESS at address 0. This is a downstream Blender null-handling bug: the 5.2.1 Metal source uses the device without a nil guard, while upstream main adds a nil check and explicitly mentions sandboxed/non-GUI contexts (#163272). That guard can prevent the startup crash, but does not restore GPU access for EEVEE.

Local mitigation now checks Metal before launching Blender and safely stops when no device is available. This prevents repeatedly triggering the crash; rendering remains unavailable. The precise OS denial responsible for Metal returning nil has not been established, so we are not claiming a confirmed specific IOKit rule is at fault.

Could maintainers confirm whether Metal unavailability is intentional in this restricted macOS execution context, and whether there is a supported way or planned fix to allow Metal while retaining filesystem and network restrictions? We need GPU rendering inside the restricted executor; disabling the sandbox is not an acceptable workaround for this workflow.

This report contains no project files, user-directory paths, account identifiers, or full session logs.

eaton-wu993 avatar Sep 08 '26 07:09 eaton-wu993

A candidate root cause for the missing Metal devices (macOS 26.7.2, Apple M3 Pro, codex-cli 0.167.0-alpha.4.1).

The seatbelt base policy (codex-rs/sandboxing/src/seatbelt_base_policy.sbpl) allows iokit-open only for RootDomainUserClient. Metal device enumeration has to open the GPU user client.

I reproduced the symptom outside Codex with plain sandbox-exec and a (deny default) profile, using a small Swift probe (MTLCopyAllDevices plus a 1024-element compute kernel compiled from source):

Added to the profile MTLCopyAllDevices Compute
nothing 0 devices not reached
(allow iokit-open (iokit-user-client-class "AGXDeviceUserClient")) and (allow mach-lookup (global-name "com.apple.MTLCompilerService")) Apple M3 Pro correct
the same without AGXDeviceUserClient 0 devices not reached
the same without MTLCompilerService Apple M3 Pro makeLibrary(source:) fails with "Unable to reach MTLCompilerService"

The same probe returns 0 devices under codex sandbox -P <profile>, and --log-denials reports "None found", so the denial does not show up in the log.

Two details from further testing:

  • IOSurfaceRootUserClient is not needed for this probe, but MLX needs it. Without it, mx.eval fails with "[Event::Event] Failed to create Metal shared event".
  • iokit-get-properties is not denied by (deny default) in a (version 1) profile, so nothing has to be added for it. If a profile denies it explicitly, the device disappears again unless the properties MetalPluginName and MetalPluginClassName are allowed.

With AGXDeviceUserClient, IOSurfaceRootUserClient and MTLCompilerService allowed, and with network access still denied and file access restricted, MLX reports mx.metal.is_available() == True and an MLX text-to-speech model runs on the GPU.

An opt-in switch in a permissions profile for GPU access would cover this use case without disabling the sandbox.

akiyama709 avatar Nov 13 '26 07:11 akiyama709

I can reproduce this in the Codex Desktop local executor on Apple Silicon. It blocks a local MLX text-to-speech workflow.

Environment (retested November 23, 2026)

  • Codex Desktop 26.1117.41037, local session with managed workspace-write permissions.
  • macOS 15.3 (24D2059), arm64.
  • Python 3.13.15 (arm64), MLX 0.32.4, using the Python environment that runs the voice-generation scripts.
  • codex --version on PATH reports codex-cli 0.137.0. That is the standalone binary reported by the shell. The repro below ran in the Desktop executor.

Minimal reproduction inside the Desktop session

probe_dir=$(mktemp -d /tmp/codex-metal.XXXXXX)
CLANG_MODULE_CACHE_PATH="$probe_dir" swift -module-cache-path "$probe_dir" -e '
import Metal
print("all_devices_count=\(MTLCopyAllDevices().count)")
print("default=\(MTLCreateSystemDefaultDevice()?.name ?? "<nil>")")
'
# Use the Python interpreter from the MLX environment.
python -c 'import mlx.core as mx; print("import ok", mx.float32)'
all_devices_count=0
default=<nil>
ImportError: [metal::load_device] No Metal device available.

A separate ctypes call into Metal.framework in the same session also reported zero devices and a null default device. An earlier test in a regular terminal on the same Mac reported Metal available. The regular-terminal check was not repeated in this run. The error occurs during import mlx.core, before model loading or synthesis.

Could you confirm whether Metal is expected to be unavailable in managed local sessions? An opt-in Metal permission that preserves filesystem and network restrictions would let this workflow run inside Codex.

laidiandian avatar Nov 23 '26 01:11 laidiandian