Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: add Windows MXC Preview sandboxing (#11390)
Etherl095b0dee3c6f
diff --git a/pyproject.toml b/pyproject.tomlindex aef512b1261..3af32244b08 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1725,6 +1725,7 @@ markers = ["gpu: needs a real accelerator, and usually downloads a checkpoint to use it","slow: minutes rather than seconds, and covered again more cheaply elsewhere","reads_real_pip_config: opts out of the hermetic pip config stub, for the few tests that drive that read themselves",+ "native_mxc: needs native Windows, the pinned Microsoft WXC executable, and a working MXC ProcessContainer backend",]# Deselected by default, not deleted: CI runs them in their own leg with@@ -1732,4 +1733,4 @@ markers = [# A run that names one of these files directly will report "no tests ran"# until you pass `-m gpu` -- that is the cost of the default being fast.# Live Studio tests are opt-in: `pytest -m server`.-addopts = "-m 'not gpu and not slow and not server'"+addopts = "-m 'not gpu and not slow and not server and not native_mxc'"diff --git a/studio/backend/core/inference/mxc_adapter.py b/studio/backend/core/inference/mxc_adapter.pynew file mode 100644index 00000000000..5caeda556f8--- /dev/null+++ b/studio/backend/core/inference/mxc_adapter.py@@ -0,0 +1,203 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Direct adapter for Microsoft's pinned ``wxc-exec.exe`` release."""++from __future__ import annotations++import base64+import os+import subprocess++from . import mxc_policy, mxc_runtime++MAX_CONFIG_BASE64 = 24_000+++class MxcAdapterError(RuntimeError):+ def __init__(+ self,+ message: str,+ *,+ stage: str,+ may_have_started: bool = False,+ ) -> None:+ super().__init__(message)+ self.stage = stage+ self.may_have_started = may_have_started+++class MxcLaunchCancelled(MxcAdapterError):+ """The caller cancelled before WXC dispatch, so host replay is forbidden."""+++def _control_environment() -> dict[str, str]:+ allowed = {"SYSTEMROOT", "WINDIR", "PATH", "TEMP", "TMP", "PROGRAMDATA"}+ env = {key: value for key, value in os.environ.items() if key.upper() in allowed}+ # Always set, even with the fallback off: recovery at every start must read the same journal.+ env["MXC_DACL_STATE_DIR"] = str(mxc_runtime.dacl_state_dir())+ return env+++def spawn(+ request: dict,+ *,+ cancel_event = None,+ popen_kwargs: dict | None = None,+):+ """Verify the request and start the approved WXC executable directly."""+ if cancel_event is not None and cancel_event.is_set():+ raise MxcLaunchCancelled(+ "MXC launch cancelled before dispatch",+ stage = "startup",+ )++ config = request.get("config")+ if not isinstance(config, dict):+ raise MxcAdapterError("the MXC configuration is missing", stage = "policy")+ encoded_config = mxc_policy.canonical_config_bytes(config)+ if encoded_config != request.get("configBytes"):+ raise MxcAdapterError("the MXC configuration changed before dispatch", stage = "policy")+ if mxc_policy.compute_policy_hash(config) != request.get("policyHash"):+ raise MxcAdapterError("the MXC configuration hash is invalid", stage = "policy")+ fallback = config.get("fallback")+ if (+ not isinstance(fallback, dict)+ or set(fallback) != {"allowDaclMutation"}+ or type(fallback["allowDaclMutation"]) is not bool+ ):+ raise MxcAdapterError("the MXC DACL fallback policy is malformed", stage = "policy")+ if fallback["allowDaclMutation"] and not mxc_policy.dacl_fallback_enabled():+ raise MxcAdapterError("MXC DACL fallback is not enabled on this host", stage = "policy")+ if config.get("ui", {}).get("disable") is not False:+ raise MxcAdapterError("the Studio MXC UI policy is not enabled", stage = "policy")++ encoded = base64.b64encode(encoded_config).decode("ascii")+ if len(encoded) > MAX_CONFIG_BASE64:+ raise MxcAdapterError(+ "the MXC configuration exceeds the safe Windows command-line bound",+ stage = "policy",+ )++ runtime_lease = None+ proc = None+ try:+ runtime_lease = mxc_runtime.acquire_runtime()+ mxc_policy.verify_launch_identities(request)+ if cancel_event is not None and cancel_event.is_set():+ raise MxcLaunchCancelled(+ "MXC launch cancelled before dispatch",+ stage = "startup",+ )++ options = dict(popen_kwargs or {})+ options.pop("preexec_fn", None)+ options.pop("pass_fds", None)+ options.update(+ stdin = subprocess.DEVNULL,+ cwd = str(runtime_lease.info.path.parent),+ env = _control_environment(),+ close_fds = True,+ )+ try:+ proc = subprocess.Popen(+ [str(runtime_lease.info.path), "--config-base64", encoded],+ **options,+ )+ except OSError as exc:+ raise MxcAdapterError(+ f"could not start the approved wxc-exec.exe: {exc}",+ stage = "spawn",+ ) from exc++ # From this point WXC may have created the workload. No caller may replay+ # the original command on the host.+ proc._mxc_dispatched = True+ proc._mxc_backend_tier = "unknown"+ proc._mxc_policy_hash = request["policyHash"]+ proc._mxc_dacl = bool(fallback["allowDaclMutation"])+ proc._mxc_runtime_lease = runtime_lease+ runtime_lease = None+ return proc+ except MxcAdapterError:+ raise+ except mxc_policy.MxcPolicyError as exc:+ # The workdir or runtime changed since the policy was built: a refusal, never a host replay.+ raise MxcAdapterError(str(exc), stage = "policy", may_have_started = proc is not None) from exc+ except Exception as exc:+ raise MxcAdapterError(+ str(exc),+ stage = "dispatch" if proc is not None else "startup",+ may_have_started = proc is not None,+ ) from exc+ finally:+ if runtime_lease is not None:+ runtime_lease.release()+++def completion_result(proc) -> dict:+ if not getattr(proc, "_mxc_dispatched", False):+ raise MxcAdapterError(+ "the process has no WXC dispatch evidence",+ stage = "completion",+ may_have_started = True,+ )+ if proc.poll() is None:+ raise MxcAdapterError(+ "wxc-exec.exe has not completed",+ stage = "completion",+ may_have_started = True,+ )+ reason = getattr(proc, "_unsloth_completion_reason", None)+ if reason not in {"finished", "timed_out", "cancelled"}:+ raise MxcAdapterError(+ "wxc-exec.exe exited without a trusted Studio completion state",+ stage = "completion",+ may_have_started = True,+ )+ cleanup = "complete"+ if reason != "finished" and getattr(proc, "_mxc_dacl", False):+ # A forced kill skips wxc-exec's own ACE restore; replay the journal now, not at the next start.+ cleanup = (+ "complete" if mxc_runtime.recover_dacl_state(_control_environment()) else "uncertain"+ )+ return {+ "exitCode": int(proc.returncode),+ "timedOut": reason == "timed_out",+ "cancelled": reason == "cancelled",+ "cleanup": cleanup,+ "backendTier": "unknown",+ "policyHash": getattr(proc, "_mxc_policy_hash", ""),+ }+++def release_runtime(proc) -> None:+ runtime_lease = getattr(proc, "_mxc_runtime_lease", None)+ if runtime_lease is not None:+ proc._mxc_runtime_lease = None+ runtime_lease.release()+++def abort(proc, *, grace_seconds: float = 1) -> None:+ """Reclaim WXC and its descendants for capability-probe failures."""+ if proc.poll() is not None:+ return+ if os.name == "nt":+ try:+ subprocess.run(+ ["taskkill", "/PID", str(proc.pid), "/T", "/F"],+ stdin = subprocess.DEVNULL,+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,+ timeout = 5,+ creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),+ check = False,+ )+ except (OSError, subprocess.SubprocessError):+ pass+ if proc.poll() is None:+ proc.terminate()+ try:+ proc.wait(timeout = grace_seconds)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait(timeout = 5)diff --git a/studio/backend/core/inference/mxc_policy.py b/studio/backend/core/inference/mxc_policy.pynew file mode 100644index 00000000000..498aed2cab7--- /dev/null+++ b/studio/backend/core/inference/mxc_policy.py@@ -0,0 +1,405 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Trusted policy construction for the Windows MXC Studio profile."""++from __future__ import annotations++import hashlib+import json+import logging+import os+from pathlib import Path+import shutil+import site+import subprocess+import sys+import unicodedata+import uuid++from . import os_sandbox+from . import mxc_runtime+from .mxc_runtime import MXC_SCHEMA_VERSION++logger = logging.getLogger(__name__)++MAX_ENVIRONMENT_ENTRIES = 512+DACL_FALLBACK_ENV = "UNSLOTH_MXC_ALLOW_DACL_FALLBACK"+_WSL_TERMINAL_MARKERS = ("\\system32\\bash.exe", "\\windowsapps\\bash.exe")+++def _studio_ui_policy() -> dict:+ return {+ "ui": {+ "disable": False,+ "clipboard": "none",+ "injection": False,+ },+ "processContainer": {+ "ui": {+ "isolation": "container",+ "desktopSystemControl": False,+ "systemSettings": "none",+ "ime": False,+ }+ },+ }+++class MxcPolicyError(RuntimeError):+ pass+++def dacl_fallback_enabled() -> bool:+ """Host opt-in to MXC's AppContainer tier, which temporarily adds ACEs to the granted host paths."""+ return os.environ.get(DACL_FALLBACK_ENV, "").strip() == "1"+++def _reject_grants_over_dacl_journal(grants: list[str]) -> None:+ # A workload that can write the journal chooses which ACLs wxc-exec rewrites on recovery.+ journal = os.path.normcase(os.path.realpath(mxc_runtime.dacl_state_path()))+ for grant in grants:+ root = os.path.normcase(grant).rstrip("\\/")+ if journal == root or journal.startswith(root + os.sep):+ raise MxcPolicyError(f"an MXC grant would expose the DACL restore journal: {grant}")+++def _object_identity(path: str, *, directory: bool) -> dict[str, int]:+ """Read stable volume/file identity without following the final reparse point."""+ if os.name != "nt":+ metadata = os.stat(path, follow_symlinks = False)+ return {"volumeSerialNumber": metadata.st_dev, "fileId": metadata.st_ino}+ import ctypes+ from ctypes import wintypes++ class FileInformation(ctypes.Structure):+ _fields_ = [+ ("dwFileAttributes", wintypes.DWORD),+ ("ftCreationTime", wintypes.FILETIME),+ ("ftLastAccessTime", wintypes.FILETIME),+ ("ftLastWriteTime", wintypes.FILETIME),+ ("dwVolumeSerialNumber", wintypes.DWORD),+ ("nFileSizeHigh", wintypes.DWORD),+ ("nFileSizeLow", wintypes.DWORD),+ ("nNumberOfLinks", wintypes.DWORD),+ ("nFileIndexHigh", wintypes.DWORD),+ ("nFileIndexLow", wintypes.DWORD),+ ]++ create_file = ctypes.windll.kernel32.CreateFileW+ create_file.argtypes = [+ wintypes.LPCWSTR,+ wintypes.DWORD,+ wintypes.DWORD,+ wintypes.LPVOID,+ wintypes.DWORD,+ wintypes.DWORD,+ wintypes.HANDLE,+ ]+ create_file.restype = wintypes.HANDLE+ flags = 0x00200000 | (0x02000000 if directory else 0)+ handle = create_file(path, 0x80, 0x1 | 0x2, None, 3, flags, None)+ invalid = ctypes.c_void_p(-1).value+ if handle in (None, invalid):+ raise MxcPolicyError(f"could not open the MXC policy object identity: {path}")+ try:+ information = FileInformation()+ if not ctypes.windll.kernel32.GetFileInformationByHandle(handle, ctypes.byref(information)):+ raise MxcPolicyError(f"could not read the MXC policy object identity: {path}")+ if information.dwFileAttributes & 0x400:+ raise MxcPolicyError(f"MXC policy objects may not be reparse points: {path}")+ return {+ "volumeSerialNumber": int(information.dwVolumeSerialNumber),+ "fileId": (int(information.nFileIndexHigh) << 32) | int(information.nFileIndexLow),+ }+ finally:+ close_handle = ctypes.windll.kernel32.CloseHandle+ close_handle.argtypes = [wintypes.HANDLE]+ close_handle.restype = wintypes.BOOL+ close_handle(handle)+++def _long_path(path: str) -> str:+ """Expand 8.3 components (RUNNER~1); realpath already returns the long form."""+ if os.name != "nt":+ return path+ import ctypes+ from ctypes import wintypes++ get_long_path = ctypes.windll.kernel32.GetLongPathNameW+ get_long_path.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]+ get_long_path.restype = wintypes.DWORD+ size = get_long_path(path, None, 0)+ if not size:+ return path+ buffer = ctypes.create_unicode_buffer(size)+ if not get_long_path(path, buffer, size):+ return path+ return buffer.value+++def _is_reparse(path: str) -> bool:+ try:+ return bool(os.lstat(path).st_file_attributes & 0x400)+ except (AttributeError, OSError):+ return os.path.islink(path)+++def _safe_canonical_path(path: str, *, directory: bool) -> str:+ absolute = os.path.abspath(path)+ if absolute.startswith(("\\\\", "\\?\\", "\\.\\")):+ raise MxcPolicyError(+ f"UNC and device namespace paths are not supported by the MXC profile: {absolute}"+ )+ _, tail = os.path.splitdrive(absolute)+ if ":" in tail:+ raise MxcPolicyError(f"alternate data stream paths are not supported: {absolute}")+ if unicodedata.normalize("NFC", absolute) != absolute:+ raise MxcPolicyError(f"non-canonical Unicode paths are not supported: {absolute}")+ if directory and not os.path.isdir(absolute):+ raise MxcPolicyError(f"required MXC policy directory is unavailable: {absolute}")+ if not directory and not os.path.isfile(absolute):+ raise MxcPolicyError(f"required MXC runtime is unavailable: {absolute}")+ canonical = os.path.realpath(absolute)+ if os.path.normcase(canonical) != os.path.normcase(_long_path(absolute)):+ raise MxcPolicyError(f"MXC policy paths may not traverse a reparse point: {absolute}")+ current = Path(absolute)+ for candidate in (current, *current.parents):+ if _is_reparse(str(candidate)):+ raise MxcPolicyError(f"MXC policy paths may not contain a reparse point: {candidate}")+ return canonical+++def _scan_workdir(workdir: str, *, required: bool) -> tuple[str, ...]:+ """Reparse points and outside hard links refuse; an overrun budget degrades `auto` only."""+ try:+ limitations = os_sandbox.scan_workdir_for_host_channels(workdir)+ except os_sandbox.WorkdirUnsafeError as exc:+ raise MxcPolicyError(str(exc)) from exc+ if required and os_sandbox.WORKDIR_SCAN_INCOMPLETE in limitations:+ raise MxcPolicyError(+ "the session workdir is too large to check for host channels, and `required` "+ "cannot promise a boundary it did not verify. Start a new chat, or use `auto`."+ )+ return limitations+++def _trusted_terminal_path_dirs(plan) -> list[str]:+ """PATH entries under Program Files (admin-writable only): the Git userland tools.py adds for bash."""+ if plan.execution_kind != "terminal":+ return []+ from .tools import _is_trusted_windows_program_dir++ return [+ entry+ for entry in (plan.env.get("PATH") or "").split(os.pathsep)+ if entry and os.path.isabs(entry) and _is_trusted_windows_program_dir(entry)+ ]+++def _runtime_read_roots(executable: str, extra: list[str] = ()) -> list[str]:+ # Preserve the lexical executable for launch. Grants may use canonical roots,+ # but never broaden to the user profile or a drive root.+ roots = [os.path.dirname(os.path.abspath(executable)), sys.prefix, sys.base_prefix, *extra]+ roots.extend(site.getsitepackages())+ roots.append(str(Path(__file__).with_name("sandbox_site")))+ system_root = os.environ.get("SystemRoot") or os.environ.get("WINDIR")+ if system_root:+ roots.append(system_root)+ result: list[str] = []+ for root in roots:+ if not root:+ continue+ if not os.path.isdir(root):+ continue+ canonical = _safe_canonical_path(root, directory = True)+ drive, tail = os.path.splitdrive(canonical)+ if not tail.strip("\\/"):+ raise MxcPolicyError(f"volume-root MXC grant is forbidden: {canonical}")+ result.append(canonical)+ return _without_nested(result)+++def _without_nested(roots: list[str]) -> list[str]:+ """Drop grants inside another, first spelling wins: on the DACL tier each re-walks its tree."""+ return [+ root+ for index, root in enumerate(roots)+ if not any(+ _within(root, other) and (not _within(other, root) or other_index < index)+ for other_index, other in enumerate(roots)+ if other_index != index+ )+ ]+++def _within(path: str, root: str) -> bool:+ folded, base = os.path.normcase(path), os.path.normcase(root).rstrip("\\/")+ return folded == base or folded.startswith(base + os.sep)+++def _model_read_roots(workdir: str, granted: list[str]) -> list[str]:+ """Registered model folders and editable package sources, read-only as on Linux and macOS; one that cannot be granted is skipped."""+ covered = [workdir, *granted]+ result: list[str] = []+ candidates = [("model folder", root) for root in os_sandbox.model_library_roots()]+ # Directories only: a single-module editable install is a file, which the profile does not grant.+ candidates += [+ ("editable package", root)+ for root in os_sandbox.editable_source_roots()+ if os.path.isdir(root)+ ]+ for what, root in candidates:+ try:+ canonical = _safe_canonical_path(root, directory = True)+ except MxcPolicyError as exc:+ logger.info("Not granting a %s to the MXC profile: %s", what, exc)+ continue+ if any(_within(canonical, value) for value in covered):+ continue+ covered.append(canonical)+ result.append(canonical)+ return result+++def _selected_runtime(plan) -> str:+ executable = plan.argv[0]+ if os.path.isabs(executable):+ selected = executable+ elif plan.execution_kind == "terminal":+ selected = shutil.which(executable, path = plan.env.get("PATH"))+ if selected is None and executable.casefold() in {"cmd", "cmd.exe"}:+ selected = os.environ.get("COMSPEC")+ if selected is None:+ raise MxcPolicyError(+ f"the selected terminal executable could not be resolved: {executable}"+ )+ else:+ raise MxcPolicyError("the selected Python executable must be absolute")+ canonical = _safe_canonical_path(selected, directory = False)+ lowered = canonical.replace("/", "\\").casefold()+ if plan.execution_kind == "terminal" and any(+ marker in lowered for marker in _WSL_TERMINAL_MARKERS+ ):+ raise MxcPolicyError(+ "the selected bash.exe is WSL-backed and is not covered by the Windows MXC profile"+ )+ return selected+++def canonical_config_bytes(config: dict) -> bytes:+ """Serialize exactly the deterministic stable-v0.8 request sent to WXC."""+ return json.dumps(+ config,+ ensure_ascii = False,+ sort_keys = True,+ separators = (",", ":"),+ ).encode("utf-8")+++def compute_policy_hash(config: dict) -> str:+ return "sha256:" + hashlib.sha256(canonical_config_bytes(config)).hexdigest()+++def verify_launch_identities(request: dict) -> None:+ """Re-check the selected workload and workdir immediately before WXC dispatch."""+ if _object_identity(request["runtimePath"], directory = False) != request["runtimeIdentity"]:+ raise MxcPolicyError("the selected workload executable changed before WXC dispatch")+ if _object_identity(request["cwd"], directory = True) != request["workdirIdentity"]:+ raise MxcPolicyError("the MXC workdir changed before WXC dispatch")+ _safe_canonical_path(request["cwd"], directory = True)+ _scan_workdir(request["cwd"], required = request["requireCompleteScan"])+++def _with_session_packages(env: dict[str, str], workdir: str) -> dict[str, str]:+ """As on Linux and macOS: the interpreter is read-only in the container, so pip installs into the session."""+ packages = os.path.join(workdir, os_sandbox.SESSION_PACKAGES_RELPATH)++ def key(name: str) -> str:+ # Windows environment names are case-insensitive, and the inherited PATH is often spelled Path.+ return next((k for k in env if k.upper() == name), name)++ env[key("PIP_TARGET")] = packages+ env[key("PYTHONNOUSERSITE")] = "1"+ # Appended, so an installed package or script cannot shadow the sandbox shim or a trusted command.+ for name, value in (+ ("PYTHONPATH", packages),+ ("PATH", os.path.join(packages, "Scripts")),+ ("PATH", os.path.join(packages, "bin")),+ ):+ name = key(name)+ env[name] = os.pathsep.join(part for part in (env.get(name, ""), value) if part)+ return env+++def build_launch_request(plan, *, run_id: str | None = None) -> dict:+ if sys.platform != "win32":+ raise MxcPolicyError("MXC policy construction is Windows-only")+ if plan.execution_kind not in {"python", "terminal"}:+ raise MxcPolicyError("the MXC profile requires a trusted Python or Terminal launch plan")+ if not plan.argv:+ raise MxcPolicyError("the MXC launch argv is empty")+ if len(plan.env) > MAX_ENVIRONMENT_ENTRIES:+ raise MxcPolicyError("the sanitized environment exceeds the MXC policy bound")+ if any(not isinstance(k, str) or not k or "=" in k for k in plan.env):+ raise MxcPolicyError("the sanitized environment contains an invalid variable name")++ required = getattr(plan, "requested_mode", None) == "required"+ workdir = _safe_canonical_path(plan.workdir, directory = True)+ limitations = _scan_workdir(workdir, required = required)+ selected_runtime = _selected_runtime(plan)+ readonly = _runtime_read_roots(selected_runtime, _trusted_terminal_path_dirs(plan))+ readonly = _without_nested(readonly + _model_read_roots(workdir, readonly))+ _reject_grants_over_dacl_journal([workdir, *readonly])+ execution_argv = list(plan.argv)+ execution_argv[0] = selected_runtime+ run_id = run_id or uuid.uuid4().hex+ workload_env = _with_session_packages(dict(plan.env), workdir)+ # MXC's Windows ProcessContainer validator requires LOCALAPPDATA to be+ # present. Point it inside the session instead of exposing the real profile.+ workload_env.setdefault("LOCALAPPDATA", workdir)+ ui_policy = _studio_ui_policy()+ config = {+ "version": MXC_SCHEMA_VERSION,+ "containerId": f"unsloth-{run_id}",+ "containment": "processcontainer",+ "lifecycle": {"destroyOnExit": True, "preservePolicy": False},+ "process": {+ "commandLine": subprocess.list2cmdline(execution_argv),+ "cwd": workdir,+ "env": [f"{key}={value}" for key, value in sorted(workload_env.items())],+ "timeout": 0+ if plan.timeout_seconds is None+ else max(1, int(plan.timeout_seconds * 1000)),+ },+ "filesystem": {+ "readwritePaths": [workdir],+ "readonlyPaths": readonly,+ "deniedPaths": [],+ },+ "network": {+ "defaultPolicy": "allow",+ "allowLocalNetwork": True,+ "allowedHosts": [],+ "blockedHosts": [],+ "enforcementMode": "capabilities",+ },+ "processContainer": {+ "leastPrivilege": False,+ "capabilities": ["internetClient", "privateNetworkClientServer"],+ "ui": ui_policy["processContainer"]["ui"],+ },+ "ui": ui_policy["ui"],+ "fallback": {"allowDaclMutation": dacl_fallback_enabled()},+ }+ request = {+ "runtimePath": os.path.realpath(selected_runtime),+ "runtimeIdentity": _object_identity(selected_runtime, directory = False),+ "cwd": workdir,+ "workdirIdentity": _object_identity(workdir, directory = True),+ "config": config,+ "configBytes": canonical_config_bytes(config),+ "policyHash": compute_policy_hash(config),+ "requireCompleteScan": required,+ "launchLimitations": limitations,+ }+ return requestdiff --git a/studio/backend/core/inference/mxc_probe.py b/studio/backend/core/inference/mxc_probe.pynew file mode 100644index 00000000000..9c91000bfda--- /dev/null+++ b/studio/backend/core/inference/mxc_probe.py@@ -0,0 +1,315 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Bounded, single-flight live capability probe for the Windows MXC path."""++from __future__ import annotations++import json+import os+from pathlib import Path+import shlex+import subprocess+import sys+import tempfile+import threading+import time+from types import SimpleNamespace++from . import mxc_adapter, mxc_policy, mxc_runtime++_lock = threading.Lock()+_cache: dict[tuple, tuple[float, bool, str]] = {}+_inflight: dict[tuple, threading.Event] = {}+POSITIVE_TTL = 300.0+NEGATIVE_TTL = 30.0+++_host_prep_cache: dict[str, tuple[float, str | None]] = {}+++def invalidate_cache() -> None:+ with _lock:+ _cache.clear()+ _host_prep_cache.clear()+++def host_prep_remediation() -> str | None:+ """Name the elevated command when MXC reports Tier 3 host preparation missing."""+ try:+ identity = mxc_runtime.installation_identity()+ except Exception: # noqa: BLE001 - no runtime, nothing to prepare+ return None+ with _lock:+ cached = _host_prep_cache.get(identity)+ if cached is not None and time.monotonic() < cached[0]:+ return cached[1]+ steps = mxc_runtime.probe_host_prep_steps(env = mxc_adapter._control_environment())+ advice = None+ if steps:+ command = subprocess.list2cmdline(+ [+ sys.executable,+ str(Path(__file__).resolve().parents[3] / "install_mxc_prebuilt.py"),+ "--prepare-host",+ "--install-dir",+ str(mxc_runtime._installed_package_root()),+ ]+ )+ reboot = (+ " (prepare-null-device is undone by every reboot)"+ if ("prepare-null-device" in steps)+ else ""+ )+ advice = (+ f"MXC reports missing host preparation: {', '.join(steps)}{reboot}. "+ f"Run {command} and approve the administrator prompt."+ )+ with _lock:+ _host_prep_cache[identity] = (time.monotonic() + NEGATIVE_TTL, advice)+ return advice+++def _terminal_probe(selected_executable: str, workdir: Path, canary: Path, outside_write: Path):+ name = Path(selected_executable).name.casefold()+ read_capture = workdir / "outside-read.txt"+ if name in {"cmd", "cmd.exe"}:+ command = (+ "echo ok>inside.txt"+ f' & type "{canary}" >"{read_capture}" 2>nul'+ f' & (echo bad>"{outside_write}") 2>nul'+ " & echo UNSLOTH_MXC_TERMINAL_PROBE_OK"+ )+ return (selected_executable, "/d", "/s", "/c", command)+ if name in {"powershell", "powershell.exe", "pwsh", "pwsh.exe"}:+ ps_inside = str(workdir / "inside.txt").replace("'", "''")+ ps_canary = str(canary).replace("'", "''")+ ps_capture = str(read_capture).replace("'", "''")+ ps_outside = str(outside_write).replace("'", "''")+ command = (+ f"Set-Content -LiteralPath '{ps_inside}' -Value 'ok'; "+ f"try {{ Get-Content -LiteralPath '{ps_canary}' -ErrorAction Stop | "+ f"Set-Content -LiteralPath '{ps_capture}' }} catch {{}}; "+ f"try {{ Set-Content -LiteralPath '{ps_outside}' -Value 'bad' "+ "-ErrorAction Stop } catch {}; "+ "Write-Output 'UNSLOTH_MXC_TERMINAL_PROBE_OK'"+ )+ return (+ selected_executable,+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ command,+ )+ if name in {"bash", "bash.exe"}:+ command = (+ "printf ok > inside.txt; "+ f"cat {shlex.quote(str(canary))} > {shlex.quote(str(read_capture))} 2>/dev/null; "+ f"printf bad > {shlex.quote(str(outside_write))} 2>/dev/null; "+ # A missing cat would read as a denied read: the marker needs a cat that worked.+ "cat inside.txt >/dev/null && printf 'UNSLOTH_MXC_TERMINAL_PROBE_OK\\n'"+ )+ return (selected_executable, "-c", command)+ raise ValueError(f"the selected Windows Terminal shell is not qualified for MXC: {name}")+++def _probe(+ selected_executable: str,+ execution_kind: str,+ cancel_event = None,+) -> tuple[bool, str]:+ if sys.platform != "win32":+ return False, "MXC is enabled only for native Windows Studio"+ if sys.getwindowsversion().build < 26100:+ return False, "Windows 11 build 26100 or newer is required for the MXC Preview"+ try:+ mxc_runtime.wxc_path()+ except mxc_runtime.MxcRuntimeUnavailable as exc:+ return False, str(exc)+ if cancel_event is not None and cancel_event.is_set():+ return False, "MXC capability probe was cancelled"++ with tempfile.TemporaryDirectory(prefix = "unsloth-mxc-probe-") as root:+ root_path = Path(root)+ workdir = root_path / "workdir"+ other = root_path / "other-chat"+ workdir.mkdir()+ other.mkdir()+ canary = other / "secret.txt"+ canary.write_text("outside-secret", encoding = "utf-8")+ outside_write = other / "outside-write.txt"+ outside_write.write_text("host-positive", encoding = "utf-8")+ outside_write.unlink()+ if execution_kind == "python":+ script = workdir / "probe.py"+ script.write_text(+ "import json, os, subprocess, sys\n"+ f"canary={str(canary)!r}\n"+ f"outside={str(outside_write)!r}\n"+ "result={}\n"+ "open('inside.txt','w',encoding='utf-8').write('ok')\n"+ "result['workdir']=open('inside.txt',encoding='utf-8').read()=='ok'\n"+ "result['import']=json.loads('{\"ok\":true}')['ok']\n"+ "result['subprocess']=subprocess.run([sys.executable,'-c','print(7)'],capture_output=True,text=True).stdout.strip()=='7'\n"+ "try:\n open(canary,encoding='utf-8').read(); result['outside_read_denied']=False\n"+ "except OSError: result['outside_read_denied']=True\n"+ "try:\n open(outside,'w',encoding='utf-8').write('bad'); result['outside_write_denied']=False\n"+ "except OSError: result['outside_write_denied']=True\n"+ "print('UNSLOTH_MXC_PROBE='+json.dumps(result,sort_keys=True))\n",+ encoding = "utf-8",+ )+ probe_argv = (selected_executable, "-u", str(script))+ elif execution_kind == "terminal":+ try:+ probe_argv = _terminal_probe(selected_executable, workdir, canary, outside_write)+ except ValueError as exc:+ return False, str(exc)+ else:+ return False, f"unsupported MXC execution kind: {execution_kind}"+ env = {+ key: value+ for key, value in os.environ.items()+ if key.upper()+ in {"SYSTEMROOT", "WINDIR", "PATH", "TEMP", "TMP", "PATHEXT", "PYTHONIOENCODING"}+ }+ env["PYTHONIOENCODING"] = "utf-8"+ env["HOME"] = str(workdir)+ env["TEMP"] = str(workdir)+ env["TMP"] = str(workdir)+ # The DACL tier re-ACLs every granted tree per launch: 10-24s measured on a 24H2 runner.+ timeout = 60 if mxc_policy.dacl_fallback_enabled() else 20++ probe_plan = SimpleNamespace(+ argv = probe_argv,+ execution_kind = execution_kind,+ timeout_seconds = timeout,+ workdir = str(workdir),+ env = env,+ )++ try:+ request = mxc_policy.build_launch_request(probe_plan)+ proc = mxc_adapter.spawn(+ request,+ cancel_event = cancel_event,+ popen_kwargs = {+ "stdout": subprocess.PIPE,+ "stderr": subprocess.STDOUT,+ "text": True,+ "encoding": "utf-8",+ "errors": "replace",+ "creationflags": subprocess.CREATE_NO_WINDOW,+ },+ )+ deadline = time.monotonic() + timeout + 5+ while True:+ if cancel_event is not None and cancel_event.is_set():+ mxc_adapter.abort(proc)+ return False, "MXC capability probe was cancelled"+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ mxc_adapter.abort(proc)+ return False, "the live MXC probe exceeded its deadline"+ try:+ output, _ = proc.communicate(timeout = min(0.1, remaining))+ break+ except subprocess.TimeoutExpired:+ continue+ proc._unsloth_completion_reason = "finished"+ result = mxc_adapter.completion_result(proc)+ except Exception as exc: # capability result, never a workload fallback decision+ return False, f"the live MXC probe failed: {type(exc).__name__}: {exc}"+ finally:+ if "proc" in locals():+ # An unexpected error must not leave the probe workload running past its lease.+ if proc.poll() is None:+ mxc_adapter.abort(proc)+ mxc_adapter.release_runtime(proc)+ if (+ proc.returncode != 0+ or result.get("exitCode") != 0+ or result.get("cleanup") != "complete"+ ):+ return False, "the live MXC probe did not complete cleanly"+ if execution_kind == "terminal":+ captured = workdir / "outside-read.txt"+ outside_read = (+ captured.read_text(encoding = "utf-8", errors = "replace") if captured.exists() else ""+ )+ if (+ "UNSLOTH_MXC_TERMINAL_PROBE_OK" not in output+ or outside_write.exists()+ or "outside-secret" in outside_read+ or not (workdir / "inside.txt").is_file()+ ):+ return False, "the live MXC Terminal positive/negative controls failed"+ return True, "the selected Terminal passed the live MXC positive and negative controls"+ marker = next(+ (line for line in output.splitlines() if line.startswith("UNSLOTH_MXC_PROBE=")), None+ )+ if marker is None:+ return False, "the live MXC probe returned no result marker"+ try:+ result = json.loads(marker.split("=", 1)[1])+ except ValueError:+ return False, "the live MXC probe returned malformed results"+ expected = {+ "workdir",+ "import",+ "subprocess",+ "outside_read_denied",+ "outside_write_denied",+ }+ if set(result) != expected or not all(result.values()):+ return (+ False,+ f"the live MXC positive/negative controls failed: {sorted(k for k, v in result.items() if not v)}",+ )+ if outside_write.exists():+ return False, "the MXC outside-write negative control failed"+ return True, "the selected Python passed the live MXC positive and negative controls"+++def probe(+ selected_executable: str,+ *,+ execution_kind: str = "python",+ force: bool = False,+ cancel_event = None,+) -> tuple[bool, str]:+ try:+ identity = mxc_runtime.installation_identity()+ except Exception as exc:+ return False, str(exc)+ key = (+ identity,+ mxc_runtime.PROFILE_ID,+ execution_kind,+ os.path.abspath(selected_executable),+ mxc_policy.dacl_fallback_enabled(),+ )+ while True:+ with _lock:+ cached = _cache.get(key)+ if cached is not None and not force and time.monotonic() < cached[0]:+ return cached[1], cached[2]+ flight = _inflight.get(key)+ if flight is None:+ flight = threading.Event()+ _inflight[key] = flight+ break+ while not flight.wait(0.05):+ if cancel_event is not None and cancel_event.is_set():+ return False, "MXC capability probe was cancelled"++ try:+ result = _probe(selected_executable, execution_kind, cancel_event)+ with _lock:+ if cancel_event is None or not cancel_event.is_set():+ ttl = POSITIVE_TTL if result[0] else NEGATIVE_TTL+ _cache[key] = (time.monotonic() + ttl, *result)+ return result+ finally:+ with _lock:+ _inflight.pop(key, None)+ flight.set()diff --git a/studio/backend/core/inference/mxc_runtime.py b/studio/backend/core/inference/mxc_runtime.pynew file mode 100644index 00000000000..fd44ae9f84e--- /dev/null+++ b/studio/backend/core/inference/mxc_runtime.py@@ -0,0 +1,334 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Select and verify Studio's pinned Microsoft WXC executable."""++from __future__ import annotations++from dataclasses import dataclass+import hashlib+import json+import logging+import os+from pathlib import Path+import platform+import re+import subprocess+import sys+import tempfile+import threading++MXC_REVISION = "7dac1a952f0c9ad13f0a4cb089c4e0e8b3e0013a"+MXC_SCHEMA_VERSION = "0.8.0-alpha"+PROFILE_ID = "unsloth-mxc-windows-processcontainer-v2"+RELEASE_REPOSITORY = "microsoft/mxc"+RELEASE_TAG = "v0.8.0"+# Microsoft's @microsoft/mxc-sdk 0.8.0 npm package: every x64 binary is byte-identical to the+# v0.8.0 release zip (358 MB, which adds only .pdb/.dwp symbols), at 26 MB.+RELEASE_ASSET = "@microsoft/[email protected]"+RELEASE_URL = "https://registry.npmjs.org/@microsoft/mxc-sdk/-/mxc-sdk-0.8.0.tgz"+RELEASE_ARCHIVE_SIZE = 25_881_758+RELEASE_ARCHIVE_SHA256 = "06bb2399d7e98ab1907acf851e12a4e44748dd467b79d3e53c2f2fbf569da14e"+RELEASE_MEMBER = "package/bin/x64/wxc-exec.exe"+WXC_EXEC_SIZE = 9_478_968+WXC_EXEC_SHA256 = "6049c64723af1173c3739dc6cd6b2f33f6c021bb2832c4216233cba7f71aee9a"+# Tier 3 host preparation, elevated; never needed by the BaseContainer path.+RELEASE_HOST_PREP_MEMBER = "package/bin/x64/wxc-host-prep.exe"+WXC_HOST_PREP_SIZE = 913_728+WXC_HOST_PREP_SHA256 = "a9b8b14a11a1c5888641297c26abca547c2afa4435085c03ccfebd1deface310"+HOST_PREP_STEPS = ("prepare-system-drive", "prepare-null-device")+HOST_PREP_PROBE_SECONDS = 10.0+DACL_RECOVERY_SECONDS = 60.0++_WXC_EXEC_NAME = "wxc-exec.exe"+_WXC_HOST_PREP_NAME = "wxc-host-prep.exe"+logger = logging.getLogger(__name__)+_lock = threading.RLock()+++class MxcRuntimeUnavailable(RuntimeError):+ pass+++@dataclass(frozen = True)+class RuntimeInfo:+ path: Path+ sha256: str++ @property+ def identity(self) -> str:+ material = {+ "architecture": "x86_64",+ "mxcRevision": MXC_REVISION,+ "releaseTag": RELEASE_TAG,+ "sha256": self.sha256,+ "size": WXC_EXEC_SIZE,+ }+ encoded = json.dumps(material, sort_keys = True, separators = (",", ":")).encode()+ return hashlib.sha256(encoded).hexdigest()+++@dataclass+class RuntimeLease:+ info: RuntimeInfo+ _guard: object+ _released: bool = False++ def release(self) -> None:+ if self._released:+ return+ self._released = True+ close = getattr(self._guard, "close", None)+ if close is not None:+ close()+ self._guard = None++ def __enter__(self) -> RuntimeLease:+ return self++ def __exit__(self, *_args) -> None:+ self.release()+++def _studio_root() -> Path:+ override = (os.environ.get("UNSLOTH_STUDIO_HOME") or "").strip()+ if not override:+ override = (os.environ.get("STUDIO_HOME") or "").strip()+ return Path(override).expanduser() if override else Path.home() / ".unsloth" / "studio"+++def _installed_package_root() -> Path:+ return _studio_root() / "mxc-runtime" / "windows-x86_64"+++def dacl_state_path() -> Path:+ """WXC's DACL restore journal: one fixed place, so every start (probe included) reaps the same orphans."""+ # Absolute: wxc-exec runs with the runtime dir as its cwd, so a relative home would split the journal.+ return Path(os.path.abspath(_studio_root() / "mxc-runtime" / "dacl-restore"))+++def dacl_state_dir() -> Path:+ path = dacl_state_path()+ path.mkdir(parents = True, exist_ok = True)+ return path+++def _sha256_file(path: Path) -> str:+ digest = hashlib.sha256()+ try:+ with path.open("rb") as stream:+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(chunk)+ except OSError as exc:+ raise MxcRuntimeUnavailable("the managed wxc-exec.exe could not be read") from exc+ return digest.hexdigest()+++def _require_plain_directory(path: Path) -> Path:+ try:+ attributes = getattr(path.lstat(), "st_file_attributes", 0)+ except OSError as exc:+ raise MxcRuntimeUnavailable("the managed MXC runtime is not installed") from exc+ if not path.is_dir() or path.is_symlink() or attributes & 0x400:+ raise MxcRuntimeUnavailable(+ "the managed MXC runtime must be a non-reparse directory",+ )+ return path.resolve()+++def _expected_architecture() -> str:+ machine = platform.machine().casefold()+ if machine not in {"amd64", "x86_64"}:+ raise MxcRuntimeUnavailable(+ f"Microsoft MXC v0.8.0 is supported only on Windows x86-64, not {machine or 'unknown'}",+ )+ return "x86_64"+++def _validate_artifact(package_root: Path, name: str, size: int, sha256: str) -> RuntimeInfo:+ root = _require_plain_directory(package_root)+ executable = root / name+ if not executable.is_file() or executable.is_symlink():+ raise MxcRuntimeUnavailable(f"the managed {name} is missing or is not a regular file")+ try:+ metadata = executable.stat()+ except OSError as exc:+ raise MxcRuntimeUnavailable(f"the managed {name} is unreadable") from exc+ if getattr(metadata, "st_nlink", 1) != 1:+ raise MxcRuntimeUnavailable(+ f"the managed {name} has an unapproved hard link",+ )+ if metadata.st_size != size:+ raise MxcRuntimeUnavailable(f"the managed {name} size is not approved")+ digest = _sha256_file(executable)+ if digest != sha256:+ raise MxcRuntimeUnavailable(f"the managed {name} digest is not approved")+ return RuntimeInfo(path = executable.resolve(), sha256 = digest)+++def _validate_runtime(package_root: Path) -> RuntimeInfo:+ return _validate_artifact(package_root, _WXC_EXEC_NAME, WXC_EXEC_SIZE, WXC_EXEC_SHA256)+++def _validate_host_prep(package_root: Path) -> RuntimeInfo:+ return _validate_artifact(+ package_root, _WXC_HOST_PREP_NAME, WXC_HOST_PREP_SIZE, WXC_HOST_PREP_SHA256+ )+++def selected_runtime(*, package_root: Path | None = None) -> RuntimeInfo:+ if sys.platform != "win32":+ raise MxcRuntimeUnavailable("the MXC runtime is Windows-only")+ _expected_architecture()+ return _validate_runtime(package_root or _installed_package_root())+++def selected_host_prep(*, package_root: Path | None = None) -> RuntimeInfo:+ if sys.platform != "win32":+ raise MxcRuntimeUnavailable("MXC host preparation is Windows-only")+ _expected_architecture()+ return _validate_host_prep(package_root or _installed_package_root())+++def wxc_path() -> Path:+ return selected_runtime().path+++def installation_identity() -> str:+ return selected_runtime().identity+++class _WindowsHandleGuard:+ def __init__(self, handle: int) -> None:+ self.handle = handle++ def close(self) -> None:+ if self.handle:+ import ctypes+ from ctypes import wintypes++ close_handle = ctypes.windll.kernel32.CloseHandle+ close_handle.argtypes = [wintypes.HANDLE]+ close_handle.restype = wintypes.BOOL+ close_handle(self.handle)+ self.handle = 0+++def _open_artifact_guard(path: Path) -> object:+ if os.name != "nt":+ return path.open("rb")+ import ctypes+ from ctypes import wintypes++ create_file = ctypes.windll.kernel32.CreateFileW+ create_file.argtypes = [+ wintypes.LPCWSTR,+ wintypes.DWORD,+ wintypes.DWORD,+ wintypes.LPVOID,+ wintypes.DWORD,+ wintypes.DWORD,+ wintypes.HANDLE,+ ]+ create_file.restype = wintypes.HANDLE+ handle = create_file(str(path), 0x80000000, 0x1, None, 3, 0x80, None)+ invalid = ctypes.c_void_p(-1).value+ if handle in (None, invalid):+ raise MxcRuntimeUnavailable(f"the managed {path.name} could not be locked for launch")+ return _WindowsHandleGuard(int(handle))+++def _acquire(select, package_root: Path | None) -> RuntimeLease:+ with _lock:+ info = select(package_root = package_root)+ guard = _open_artifact_guard(info.path)+ try:+ if select(package_root = package_root) != info:+ raise MxcRuntimeUnavailable(+ f"the managed {info.path.name} changed during acquisition"+ )+ except Exception:+ guard.close()+ raise+ return RuntimeLease(info = info, _guard = guard)+++def acquire_runtime(*, package_root: Path | None = None) -> RuntimeLease:+ return _acquire(selected_runtime, package_root)+++def acquire_host_prep(*, package_root: Path | None = None) -> RuntimeLease:+ """Pinned wxc-host-prep held deny-write, so the elevated launch runs the verified bytes."""+ return _acquire(selected_host_prep, package_root)+++def _run_wxc_probe(+ package_root: Path | None,+ env: dict[str, str] | None,+ *,+ replay_journal: bool = True,+ timeout: float = HOST_PREP_PROBE_SECONDS,+):+ # --probe reaps orphaned ACEs first: point it at Studio's journal, not %LOCALAPPDATA%'s.+ env = dict(os.environ if env is None else env)+ with tempfile.TemporaryDirectory(prefix = "unsloth-mxc-empty-journal-") as empty:+ # An elevated probe must not replay a user-writable journal: it names the ACLs to rewrite.+ env["MXC_DACL_STATE_DIR"] = str(dacl_state_dir()) if replay_journal else empty+ with acquire_runtime(package_root = package_root) as lease:+ return subprocess.run(+ [str(lease.info.path), "--probe"],+ stdin = subprocess.DEVNULL,+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ cwd = str(lease.info.path.parent),+ env = env,+ timeout = timeout,+ creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),+ check = False,+ )+++def recover_dacl_state(env: dict[str, str] | None = None) -> bool:+ """Replay the DACL journal now; True only when wxc-exec reports no recovery error."""+ try:+ # Longer than the advice probe: it runs right after a kill, often beside other DACL launches.+ completed = _run_wxc_probe(None, env, timeout = DACL_RECOVERY_SECONDS)+ except Exception as exc: # noqa: BLE001 - an unknown outcome is not a clean one+ logger.warning("MXC DACL recovery did not run: %s", exc)+ return False+ stderr = completed.stderr or ""+ # main.rs prints "DACL recovery: ... N error(s)" only when there was work, or "DACL recovery failed".+ report = re.search(r"DACL recovery: .*?(\d+) error\(s\)", stderr)+ # Deleting a journal that is already gone is not a restore error: a concurrent run finished it.+ already_gone = len(re.findall(r"^\s*remove .*\(os error 2\)\s*$", stderr, re.MULTILINE))+ clean = (+ completed.returncode == 0+ and "DACL recovery failed" not in stderr+ and (report is None or int(report.group(1)) <= already_gone)+ )+ if not clean:+ logger.warning("MXC DACL recovery reported a problem: %s", stderr.strip()[-500:])+ return clean+++def probe_host_prep_steps(+ *,+ package_root: Path | None = None,+ env: dict[str, str] | None = None,+ replay_journal: bool = True,+) -> tuple[str, ...] | None:+ """Host preparation `wxc-exec --probe` reports missing; None when it cannot tell."""+ try:+ completed = _run_wxc_probe(package_root, env, replay_journal = replay_journal)+ warnings = json.loads(completed.stdout).get("warnings")+ except Exception: # noqa: BLE001 - advice only, never a capability verdict+ return None+ if completed.returncode != 0 or not isinstance(warnings, list):+ return None+ # MXC names the verb in each Tier 3 warning (fallback_detector.rs push_host_prep_warnings).+ return tuple(+ step+ for step in HOST_PREP_STEPS+ if any(isinstance(item, str) and f"wxc-host-prep {step}" in item for item in warnings)+ )diff --git a/studio/backend/core/inference/os_sandbox.py b/studio/backend/core/inference/os_sandbox.pyindex 79003997324..dfcd4c7109a 100644--- a/studio/backend/core/inference/os_sandbox.py+++ b/studio/backend/core/inference/os_sandbox.py@@ -1,7 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Studio tool launch contract and the OS-isolation backends (bwrap, Seatbelt)."""+"""Studio tool launch contract and platform OS-isolation backends."""from __future__ import annotationsimport errno@@ -17,6 +17,7 @@ import sysimport threadingimport timefrom dataclasses import dataclass, field+from dataclasses import replacefrom typing import Any, BinaryIO, Callable, Literalfrom loggers import get_logger@@ -24,6 +25,7 @@ logger = get_logger(__name__)ToolExecutionMode = Literal["auto", "required", "full"]TOOL_EXECUTION_MODES = ("auto", "required", "full")+PUBLIC_TOOL_EXECUTION_MODES = ("auto", "required")PROFILE_VERSION = "unsloth-sandbox-v1"@@ -117,6 +119,14 @@ class ToolExecutionRecord:retained_safeguards: tuple[str, ...]limitations: tuple[str, ...] = ()network_policy: str = "unrestricted"+ backend_tier: str = "unknown"+ runtime_revision: str = ""+ runtime_artifact_digest: str = ""+ schema_version: str = ""+ policy_hash: str = ""+ execution_status: str = "planned"+ completion_status: str = "pending"+ cleanup_status: str = "pending"def as_dict(self) -> dict[str, object]:return {@@ -130,6 +140,14 @@ class ToolExecutionRecord:"retained_safeguards": list(self.retained_safeguards),"limitations": list(self.limitations),"network_policy": self.network_policy,+ "backend_tier": self.backend_tier,+ "runtime_revision": self.runtime_revision,+ "runtime_artifact_digest": self.runtime_artifact_digest,+ "schema_version": self.schema_version,+ "policy_hash": self.policy_hash,+ "execution_status": self.execution_status,+ "completion_status": self.completion_status,+ "cleanup_status": self.cleanup_status,}@@ -145,6 +163,7 @@ class ToolLaunchPlan:terminate_descendants: bool = True# Set by the trusted tool owner, never inferred from model args.execution_kind: Literal["python", "terminal"] | None = None+ cancel_event: Any = None@dataclass@@ -163,6 +182,7 @@ class PreparedSandboxLaunch:terminate_descendants: bool = Truecleanup_callbacks: list[Callable[[], None]] = field(default_factory = list)cleanup_diagnostics: list[str] = field(default_factory = list)+ spawn_callback: Callable | None = Nonelaunch_limitations: tuple[str, ...] = ()def cleanup(self) -> None:@@ -191,7 +211,12 @@ class PreparedSandboxLaunch:def spawn_prepared_launch(prepared: PreparedSandboxLaunch, **popen_kwargs: Any) -> object:- return subprocess.Popen(prepared.argv, **popen_kwargs)+ if prepared.spawn_callback is not None:+ return prepared.spawn_callback(prepared, popen_kwargs)+ proc = subprocess.Popen(prepared.argv, **popen_kwargs)+ if prepared.execution_record is not None:+ prepared.execution_record = replace(prepared.execution_record, execution_status = "started")+ return proc# `auto` launches on this, `required` refuses; one name so both readers agree.@@ -256,6 +281,9 @@ def _host_channel_hazard(info = os.lstat(path)except OSError:return f"changed during its safety scan: {path}"+ # Windows only: MXC grants the workdir by path, so a junction or symlink inside it widens the grant.+ if getattr(info, "st_file_attributes", 0) & 0x400:+ return f"contains a reparse point: {path}"if stat.S_ISLNK(info.st_mode):continueif stat.S_ISDIR(info.st_mode):@@ -786,7 +814,21 @@ def _unavailable(reason: str, remediation: str, identity: str) -> SandboxCapabil)-def capability_snapshot(*, force: bool = False) -> SandboxCapability:+def capability_snapshot(+ *,+ force: bool = False,+ execution_kind = None,+ selected_executable = None,+ cancel_event = None,+) -> SandboxCapability:+ if sys.platform == "win32":+ from .sandbox_windows_mxc import capability_snapshot as windows_capability+ return windows_capability(+ force = force,+ execution_kind = execution_kind,+ selected_executable = selected_executable,+ cancel_event = cancel_event,+ )identity = _runtime_identity()if sys.platform == "linux":from . import sandbox_linux@@ -863,6 +905,8 @@ def _software_only_limitations() -> tuple[str, ...]:def prepare_tool_launch(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:"""Unavailable hosts fall back in auto; unsafe workdirs and build failures refuse."""+ if plan.cancel_event is not None and plan.cancel_event.is_set():+ raise SandboxBuildError("execution cancelled before sandbox preparation")if plan.requested_mode not in TOOL_EXECUTION_MODES:raise SandboxUnavailableError(f"unknown tool execution mode: {plan.requested_mode!r}")@@ -893,7 +937,14 @@ def prepare_tool_launch(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:),)- capability = capability_snapshot()+ capability = capability_snapshot(+ execution_kind = plan.execution_kind,+ selected_executable = plan.argv[0] if plan.argv else None,+ cancel_event = plan.cancel_event,+ )++ if plan.cancel_event is not None and plan.cancel_event.is_set():+ raise SandboxBuildError("execution cancelled before sandbox launch")if not capability.available:if plan.requested_mode == "required":@@ -922,6 +973,9 @@ def prepare_tool_launch(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:),)+ if sys.platform == "win32":+ from .sandbox_windows_mxc import prepare+ return prepare(plan, capability)if sys.platform == "linux":from . import sandbox_linux as backendelse:@@ -953,3 +1007,27 @@ def prepare_tool_launch(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:limitations = capability.limitations + prepared.launch_limitations,)return prepared+++def verify_prepared_completion(prepared: PreparedSandboxLaunch, proc) -> dict | None:+ if prepared.backend == "mxc-processcontainer":+ from .sandbox_windows_mxc import verify_success+ return verify_success(prepared, proc)+ reason = getattr(proc, "_unsloth_completion_reason", None)+ if prepared.execution_record is None or reason not in {"finished", "timed_out", "cancelled"}:+ return None+ prepared.execution_record = replace(+ prepared.execution_record,+ execution_status = "completed",+ completion_status = reason,+ )+ return {"timedOut": reason == "timed_out", "cancelled": reason == "cancelled"}+++def finalize_prepared_cleanup(prepared: PreparedSandboxLaunch) -> None:+ if prepared.backend == "mxc-processcontainer" or prepared.execution_record is None:+ return+ prepared.execution_record = replace(+ prepared.execution_record,+ cleanup_status = "uncertain" if prepared.cleanup_diagnostics else "complete",+ )diff --git a/studio/backend/core/inference/sandbox_windows_mxc.py b/studio/backend/core/inference/sandbox_windows_mxc.pynew file mode 100644index 00000000000..f0fda64aa03--- /dev/null+++ b/studio/backend/core/inference/sandbox_windows_mxc.py@@ -0,0 +1,264 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Windows-only MXC backend for the shared Studio tool launch contract."""++from __future__ import annotations++from dataclasses import replace+import hashlib+import logging+import os+import subprocess+import sys++from . import mxc_adapter, mxc_policy, mxc_probe, mxc_runtime+from .os_sandbox import (+ PreparedSandboxLaunch,+ SandboxBuildError,+ SandboxCapability,+ _OS_ISOLATION_SAFEGUARDS,+ _SOFTWARE_SAFEGUARDS,+ _record,+ with_session_packages,+)+++logger = logging.getLogger(__name__)+++def _capability_fingerprint(identity: str, execution_kind: str, selected_executable: str) -> str:+ return hashlib.sha256(+ repr(+ (+ identity,+ execution_kind,+ os.path.abspath(selected_executable),+ mxc_runtime.PROFILE_ID,+ mxc_policy.dacl_fallback_enabled(),+ )+ ).encode()+ ).hexdigest()+++def capability_snapshot(+ *,+ force = False,+ execution_kind = None,+ selected_executable = None,+ cancel_event = None,+):+ if sys.platform != "win32":+ raise SandboxBuildError("MXC is Windows-only")+ if execution_kind is None:+ execution_kind = "python"+ selected_executable = selected_executable or sys.executable+ if execution_kind not in {"python", "terminal"} or not selected_executable:+ return SandboxCapability(+ backend = "mxc-processcontainer",+ available = False,+ reason = "the MXC profile requires a selected Python or Terminal executable",+ environment = "win32",+ remediation = "Select a supported native Windows runtime.",+ limitations = ("unsupported_execution_kind",),+ )+ available, reason = mxc_probe.probe(+ selected_executable,+ execution_kind = execution_kind,+ force = force,+ cancel_event = cancel_event,+ )+ try:+ identity = mxc_runtime.installation_identity()+ except Exception:+ identity = "missing"+ fingerprint = _capability_fingerprint(identity, execution_kind, selected_executable)+ dacl = mxc_policy.dacl_fallback_enabled()+ limitations = (+ "mxc_preview_not_a_security_boundary",+ "wxc_exec_does_not_report_execution_tier",+ "workload_start_not_structured_by_wxc_exec",+ "network_posture_requested_not_attested",+ "nested_path_identity_may_change_during_mxc_grant_resolution",+ )+ if dacl:+ limitations += ("mxc_tier3_dacl_host_permission_changes",)+ remediation = (+ "Install the pinned Microsoft WXC runtime and prepare this host once as an "+ "administrator; the null device step repeats after every reboot."+ )+ else:+ remediation = (+ "Install the pinned Microsoft WXC runtime and enable BaseContainer/PSEC. On Windows "+ f"builds without it, set {mxc_policy.DACL_FALLBACK_ENV}=1 to use the AppContainer "+ "tier: it adds temporary permission entries to the granted host folders, removed "+ "on exit, and needs a one-time administrator host preparation plus one per reboot."+ )+ # Only in DACL mode: a bare --probe allows the fallback, so it warns on hosts Studio never uses it on.+ host_prep = mxc_probe.host_prep_remediation() if dacl and not available else None+ if host_prep:+ remediation = f"{remediation} {host_prep}"+ return SandboxCapability(+ backend = "mxc-processcontainer",+ available = available,+ reason = reason,+ environment = "win32",+ protection_state = "preview" if available else "unavailable",+ profile_id = mxc_runtime.PROFILE_ID,+ limitations = limitations,+ probe_generation = hashlib.sha256((fingerprint + str(available)).encode()).hexdigest(),+ environment_fingerprint = fingerprint,+ remediation = remediation,+ )+++def prepare(plan, capability):+ try:+ request = mxc_policy.build_launch_request(plan)+ except Exception as exc:+ raise SandboxBuildError(f"Windows MXC policy construction failed: {exc}") from exc+ launch_limitations = tuple(request.get("launchLimitations", ()))+ record = _record(+ plan,+ capability,+ effective_mode = "os_isolated",+ os_isolation = True,+ backend = "mxc-processcontainer",+ profile_id = capability.profile_id,+ safeguards = _OS_ISOLATION_SAFEGUARDS + ("ui_isolation",),+ limitations = capability.limitations + launch_limitations,+ )+ record = replace(+ record,+ network_policy = "mxc_compatibility_requested_unverified",+ backend_tier = "unknown",+ runtime_revision = mxc_runtime.MXC_REVISION,+ runtime_artifact_digest = f"sha256:{mxc_runtime.WXC_EXEC_SHA256}",+ schema_version = mxc_runtime.MXC_SCHEMA_VERSION,+ policy_hash = request["policyHash"],+ execution_status = "planned",+ cleanup_status = "pending",+ )+ prepared = PreparedSandboxLaunch(+ argv = plan.argv,+ workdir = plan.workdir,+ env = plan.env,+ preexec_fn = None,+ backend = "mxc-processcontainer",+ timeout_seconds = plan.timeout_seconds,+ execution_record = record,+ launch_limitations = launch_limitations,+ )++ def launch(_prepared, kwargs):+ try:+ current_identity = mxc_runtime.installation_identity()+ current_fingerprint = _capability_fingerprint(+ current_identity, plan.execution_kind, plan.argv[0]+ )+ if current_fingerprint != capability.environment_fingerprint:+ raise RuntimeError(+ "the selected MXC runtime changed after capability qualification"+ )+ proc = mxc_adapter.spawn(request, cancel_event = plan.cancel_event, popen_kwargs = kwargs)+ except Exception as exc:+ may_have_started = bool(getattr(exc, "may_have_started", False))+ cancelled = isinstance(exc, mxc_adapter.MxcLaunchCancelled)+ refused = getattr(exc, "stage", None) == "policy"+ if plan.requested_mode == "auto" and not (may_have_started or cancelled or refused):+ # The same environment as any other unisolated launch, session packages included.+ kwargs = {+ **kwargs,+ "env": with_session_packages(kwargs.get("env") or plan.env, plan.workdir),+ }+ try:+ proc = subprocess.Popen(plan.argv, **kwargs)+ except OSError as fallback_exc:+ raise SandboxBuildError(+ f"Windows MXC and software-safeguard launches both failed: {fallback_exc}"+ ) from fallback_exc+ prepared.backend = "software-safeguards"+ prepared.execution_record = _record(+ plan,+ capability,+ effective_mode = "software_safeguards",+ os_isolation = False,+ backend = "software-safeguards",+ profile_id = "software-safeguards-v1",+ safeguards = _SOFTWARE_SAFEGUARDS,+ limitations = (+ "no_os_isolation",+ "host_files_readable",+ "unrestricted_network",+ "mxc_launch_failed_before_dispatch",+ ),+ )+ prepared.execution_record = replace(+ prepared.execution_record,+ execution_status = "started",+ completion_status = "pending",+ cleanup_status = "pending",+ )+ mxc_probe.invalidate_cache()+ return proc+ prepared.execution_record = replace(+ prepared.execution_record,+ execution_status = "unknown_start" if may_have_started else "not_started",+ completion_status = (+ "uncertain"+ if may_have_started+ else ("cancelled" if cancelled else "not_started")+ ),+ cleanup_status = "uncertain" if may_have_started else "complete",+ )+ if not cancelled:+ mxc_probe.invalidate_cache()+ raise SandboxBuildError(+ f"Windows MXC launch failed without host replay: {exc}"+ ) from exc+ prepared.execution_record = replace(+ prepared.execution_record,+ execution_status = "dispatched",+ backend_tier = str(getattr(proc, "_mxc_backend_tier", "unknown")),+ )+ prepared.cleanup_callbacks.append(lambda: mxc_adapter.release_runtime(proc))+ return proc++ prepared.spawn_callback = launch+ return prepared+++def verify_success(prepared, proc) -> dict:+ try:+ result = mxc_adapter.completion_result(proc)+ except Exception as exc:+ if prepared.execution_record is not None:+ prepared.execution_record = replace(+ prepared.execution_record,+ completion_status = "uncertain",+ cleanup_status = "uncertain",+ )+ mxc_probe.invalidate_cache()+ raise SandboxBuildError(f"MXC completion state is uncertain: {exc}") from exc+ prepared.execution_record = replace(+ prepared.execution_record,+ execution_status = "completed",+ completion_status = (+ "timed_out"+ if result.get("timedOut")+ else ("cancelled" if result.get("cancelled") else "finished")+ ),+ cleanup_status = str(result.get("cleanup") or "unknown"),+ )+ if result.get("cleanup") != "complete":+ forced = bool(result.get("timedOut") or result.get("cancelled"))+ if not forced:+ raise SandboxBuildError(+ "MXC cleanup did not complete cleanly; execution state is uncertain"+ )+ # Studio killed the tree, so the workload is gone; only ACE restore is unconfirmed, and every+ # later wxc-exec start replays the journal. Report the timeout or cancel, not an error.+ logger.warning(+ "MXC could not confirm the DACL restore after a forced exit; it retries at the next start"+ )+ mxc_probe.invalidate_cache()+ return resultdiff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 9420cc11fea..8d280ea2e3d 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -9631,7 +9631,7 @@ def _reaches_host_paths(kind: str, text: str) -> bool:def _prepare_tool_launch(plan, *, host_access_approved: bool = False):- """Allow auto fallback for unavailable backends or unexpected planner errors; unsafe workdirs and build failures refuse."""+ """Fall back only when the backend is unavailable; unsafe workdirs, build failures and (outside `full`) planner errors refuse."""if host_access_approved and plan.requested_mode == "auto":return _software_safeguards_launch(plan, "user_approved_host_access")try:@@ -9661,16 +9661,12 @@ def _prepare_tool_launch(plan, *, host_access_approved: bool = False):exc_info = True,)return _software_safeguards_launch(plan, "sandbox_became_unavailable")- except Exception as exc: # noqa: BLE001 - auto falls back on unexpected planner errors- logger.warning("Sandbox planning failed, running with software safeguards", exc_info = True)- if plan.requested_mode == "required":- raise os_sandbox.SandboxUnavailableError(- f"OS_ISOLATION_UNAVAILABLE: the sandbox planner failed: {exc}",- remediation = os_sandbox.linux_unavailable_remediation()- if sys.platform == "linux"- else "This host cannot start an OS sandbox.",- ) from exc- return _software_safeguards_launch(plan, "sandbox_planner_error")+ except Exception as exc: # noqa: BLE001 - construction failures never buy a host replay+ if plan.requested_mode == "full":+ return _software_safeguards_launch(plan, "sandbox_planner_error")+ raise os_sandbox.SandboxBuildError(+ f"sandbox preparation failed without host fallback: {exc}"+ ) from exc# Launcher stderr prefixes for refusing to build the sandbox, not payload failures.@@ -18203,6 +18199,13 @@ def _cancel_watcher(short-circuit)."""while proc.poll() is None:if cancel_event is not None and cancel_event.is_set():+ request_cancel = getattr(proc, "_unsloth_cancel", None)+ if request_cancel is not None and request_cancel():+ try:+ proc.wait(timeout = 5)+ return+ except subprocess.TimeoutExpired:+ pass_killpg_captured(pgid)_kill_process_tree(proc)return@@ -19689,13 +19692,14 @@ def _python_exec(requested_mode = requested_mode,timeout_seconds = timeout,execution_kind = "python",+ cancel_event = cancel_event,),host_access_approved = host_access_approved and _reaches_host_paths("python", code),)- _note_tool_execution(prepared.execution_record)proc = os_sandbox.spawn_prepared_launch(prepared, **_apply_prepared_launch(prepared, popen_kwargs))+ _note_tool_execution(prepared.execution_record)else:popen_kwargs.update(cwd = workdir, env = safe_env)if sys.platform != "win32":@@ -19721,6 +19725,21 @@ def _python_exec(output, timed_out = _drain_process_output(proc, timeout, output_callback, cancel_event, pgid = pgid)+ if prepared is not None:+ proc._unsloth_completion_reason = (+ "timed_out"+ if timed_out+ else (+ "cancelled"+ if cancel_event is not None and cancel_event.is_set()+ else "finished"+ )+ )+ if prepared is not None:+ completion = os_sandbox.verify_prepared_completion(prepared, proc)+ if completion is not None and completion.get("timedOut"):+ timed_out = True+ _note_tool_execution(prepared.execution_record)# A run that wrote its file and then hung still produced that file, so report it: `printf data > report.csv;# sleep 999` is downloadable.if timed_out:@@ -19765,10 +19784,15 @@ def _python_exec(return resultexcept os_sandbox.SandboxUnavailableError as e:+ if cancel_event is not None and cancel_event.is_set():+ # A stop during the (on Windows DACL, multi-second) probe is a cancel, not a sandbox error.+ return "Execution cancelled."return _sandbox_refusal(e)except Exception as e:# An exception message carries whatever the failure put in it, so it is capped like the result would have# been.+ if prepared is not None and prepared.backend == "mxc-processcontainer":+ _note_tool_execution(prepared.execution_record)return _truncate(f"Execution error: {e}")finally:_call_finished(call_token)@@ -19778,6 +19802,8 @@ def _python_exec(# Private mounts and descriptors, released on every exit path.if prepared is not None:prepared.cleanup()+ os_sandbox.finalize_prepared_cleanup(prepared)+ _note_tool_execution(prepared.execution_record)_forget_tool_pid(locals().get("proc"))if tmp_path and os.path.exists(tmp_path):try:@@ -19885,14 +19911,15 @@ def _bash_exec(requested_mode = requested_mode,timeout_seconds = timeout,execution_kind = "terminal",+ cancel_event = cancel_event,),host_access_approved = host_access_approvedand _reaches_host_paths("terminal", command),)- _note_tool_execution(prepared.execution_record)proc = os_sandbox.spawn_prepared_launch(prepared, **_apply_prepared_launch(prepared, popen_kwargs))+ _note_tool_execution(prepared.execution_record)else:popen_kwargs.update(cwd = workdir, env = safe_env)if sys.platform != "win32":@@ -19917,6 +19944,21 @@ def _bash_exec(output, timed_out = _drain_process_output(proc, timeout, output_callback, cancel_event, pgid = pgid)+ if prepared is not None:+ proc._unsloth_completion_reason = (+ "timed_out"+ if timed_out+ else (+ "cancelled"+ if cancel_event is not None and cancel_event.is_set()+ else "finished"+ )+ )+ if prepared is not None:+ completion = os_sandbox.verify_prepared_completion(prepared, proc)+ if completion is not None and completion.get("timedOut"):+ timed_out = True+ _note_tool_execution(prepared.execution_record)# A run that wrote its file and then hung still produced that file, so report it: `printf data > report.csv;# sleep 999` is downloadable.if timed_out:@@ -19952,16 +19994,23 @@ def _bash_exec(return resultexcept os_sandbox.SandboxUnavailableError as e:+ if cancel_event is not None and cancel_event.is_set():+ # A stop during the (on Windows DACL, multi-second) probe is a cancel, not a sandbox error.+ return "Execution cancelled."return _sandbox_refusal(e)except Exception as e:# An exception message carries whatever the failure put in it, so it is capped like the result would have# been.+ if prepared is not None and prepared.backend == "mxc-processcontainer":+ _note_tool_execution(prepared.execution_record)return _truncate(f"Execution error: {e}")finally:_call_finished(call_token)# Private mounts and descriptors, released on every exit path.if prepared is not None:prepared.cleanup()+ os_sandbox.finalize_prepared_cleanup(prepared)+ _note_tool_execution(prepared.execution_record)_forget_tool_pid(locals().get("proc"))if _scratch_name:with _scratch_lock:diff --git a/studio/backend/tests/test_bypass_permissions.py b/studio/backend/tests/test_bypass_permissions.pyindex ff0ae15035c..f91b1cf33db 100644--- a/studio/backend/tests/test_bypass_permissions.py+++ b/studio/backend/tests/test_bypass_permissions.py@@ -134,6 +134,19 @@ def captured_popen(monkeypatch):return cap+def captured_prepared_launch(monkeypatch):+ cap = {}++ def fake_spawn(prepared, **kwargs):+ cap["prepared"] = prepared+ cap["kwargs"] = kwargs+ return _FakeProc()++ monkeypatch.setattr(tools.os_sandbox, "spawn_prepared_launch", fake_spawn)+ return cap++def _carries(preexec, expected) -> bool:"""A backend that isolates COMPOSES its pre-exec onto the plan's rather than replacing it, so on such a host the identity is one closure down."""if preexec is expected:@@ -142,11 +155,12 @@ def _carries(preexec, expected) -> bool:@_POSIX_ONLY-def test_python_sandboxed_uses_sandbox_preexec_and_safe_env(captured_popen, monkeypatch):+def test_python_sandboxed_uses_sandbox_preexec_and_safe_env(captured_prepared_launch, monkeypatch):monkeypatch.setenv("HF_TOKEN", "secret-abc")_python_exec("print(1)", None, 5, "t", disable_sandbox = False)- assert _carries(captured_popen["kwargs"]["preexec_fn"], tools._sandbox_preexec)- assert "HF_TOKEN" not in captured_popen["kwargs"]["env"]+ kwargs = captured_prepared_launch["kwargs"]+ assert _carries(kwargs["preexec_fn"], tools._sandbox_preexec)+ assert "HF_TOKEN" not in kwargs["env"]@_POSIX_ONLYdiff --git a/studio/backend/tests/test_install_mxc_prebuilt.py b/studio/backend/tests/test_install_mxc_prebuilt.pynew file mode 100644index 00000000000..fcaf1a91b64--- /dev/null+++ b/studio/backend/tests/test_install_mxc_prebuilt.py@@ -0,0 +1,376 @@+# SPDX-License-Identifier: AGPL-3.0-only++from __future__ import annotations++import hashlib+import importlib.util+import io+import os+from pathlib import Path+import stat+import tarfile++import pytest++_STUDIO = Path(__file__).resolve().parents[2]+_SPEC = importlib.util.spec_from_file_location(+ "install_mxc_prebuilt_under_test", _STUDIO / "install_mxc_prebuilt.py"+)+installer = importlib.util.module_from_spec(_SPEC)+assert _SPEC.loader is not None+_SPEC.loader.exec_module(installer)+++_HARDLINK = -1+++def _archive(entries: list[tuple[str, bytes, int | None]]) -> bytes:+ output = io.BytesIO()+ with tarfile.open(fileobj = output, mode = "w:gz") as bundle:+ for name, payload, mode in entries:+ info = tarfile.TarInfo(name)+ if mode == _HARDLINK or (mode is not None and stat.S_ISLNK(mode)):+ info.type = tarfile.LNKTYPE if mode == _HARDLINK else tarfile.SYMTYPE+ info.linkname = payload.decode()+ bundle.addfile(info)+ continue+ info.size = len(payload)+ info.mode = 0o644+ bundle.addfile(info, io.BytesIO(payload))+ return output.getvalue()+++_HOST_PREP = b"official-host-prep"+++def _pin_host_prep(monkeypatch, payload = _HOST_PREP):+ monkeypatch.setattr(installer.mxc_runtime, "WXC_HOST_PREP_SIZE", len(payload))+ monkeypatch.setattr(+ installer.mxc_runtime, "WXC_HOST_PREP_SHA256", hashlib.sha256(payload).hexdigest()+ )+++def _serve(monkeypatch, archive):+ monkeypatch.setattr(installer.mxc_runtime, "RELEASE_ARCHIVE_SIZE", len(archive))+ monkeypatch.setattr(+ installer.mxc_runtime,+ "RELEASE_ARCHIVE_SHA256",+ hashlib.sha256(archive).hexdigest(),+ )+ monkeypatch.setattr(+ installer, "_download", lambda destination: destination.write_bytes(archive)+ )+++def official_release(tmp_path, monkeypatch):+ payload = b"official-wxc"+ archive = _archive(+ [+ ("README.txt", b"Microsoft MXC release", None),+ (installer.mxc_runtime.RELEASE_MEMBER, payload, stat.S_IFREG | 0o644),+ (installer.mxc_runtime.RELEASE_HOST_PREP_MEMBER, _HOST_PREP, stat.S_IFREG | 0o644),+ ("package/bin/arm64/wxc-host-prep.exe", b"arm64", stat.S_IFREG | 0o644),+ ]+ )+ _pin_host_prep(monkeypatch)+ source = tmp_path / "official.tgz"+ source.write_bytes(archive)+ monkeypatch.setattr(installer.sys, "platform", "win32")+ monkeypatch.setattr(installer.mxc_runtime.sys, "platform", "win32")+ monkeypatch.setattr(installer.mxc_runtime, "_expected_architecture", lambda: "x86_64")+ monkeypatch.setattr(installer.mxc_runtime, "WXC_EXEC_SIZE", len(payload))+ monkeypatch.setattr(+ installer.mxc_runtime, "WXC_EXEC_SHA256", hashlib.sha256(payload).hexdigest()+ )+ monkeypatch.setattr(installer.mxc_runtime, "RELEASE_ARCHIVE_SIZE", len(archive))+ monkeypatch.setattr(+ installer.mxc_runtime,+ "RELEASE_ARCHIVE_SHA256",+ hashlib.sha256(archive).hexdigest(),+ )+ monkeypatch.setattr(+ installer, "_download", lambda destination: destination.write_bytes(archive)+ )+ return payload, archive+++def test_installs_only_the_official_wxc_member(tmp_path, official_release):+ payload, _archive_bytes = official_release+ install_dir = tmp_path / "installed" / "windows-x86_64"+ assert installer.install_mxc_release(install_dir) is True+ assert sorted(path.name for path in install_dir.iterdir()) == [+ "wxc-exec.exe",+ "wxc-host-prep.exe",+ ]+ assert (install_dir / "wxc-exec.exe").read_bytes() == payload+ assert (install_dir / "wxc-host-prep.exe").read_bytes() == _HOST_PREP+ assert installer.mxc_runtime.selected_host_prep(package_root = install_dir).path.name == (+ "wxc-host-prep.exe"+ )+ assert installer.mxc_runtime.selected_runtime(package_root = install_dir).path.name == (+ "wxc-exec.exe"+ )+++def test_matching_install_is_reused_without_download(tmp_path, monkeypatch, official_release):+ install_dir = tmp_path / "installed" / "windows-x86_64"+ assert installer.install_mxc_release(install_dir) is True+ monkeypatch.setattr(+ installer,+ "_download",+ lambda _destination: pytest.fail("verified installation was downloaded again"),+ )+ assert installer.install_mxc_release(install_dir) is False+++def test_corrupt_wxc_is_replaced_safely(tmp_path, official_release):+ install_dir = tmp_path / "installed" / "windows-x86_64"+ install_dir.mkdir(parents = True)+ (install_dir / "wxc-exec.exe").write_bytes(b"corrupt")+ assert installer.install_mxc_release(install_dir) is True+ installer.mxc_runtime.selected_runtime(package_root = install_dir)+++def test_install_without_host_prep_is_refreshed(tmp_path, official_release):+ # Installs from before host-prep was pinned must pick it up, not count as current.+ payload, _archive_bytes = official_release+ install_dir = tmp_path / "installed" / "windows-x86_64"+ install_dir.mkdir(parents = True)+ (install_dir / "wxc-exec.exe").write_bytes(payload)+ assert installer.install_mxc_release(install_dir) is True+ installer.mxc_runtime.selected_host_prep(package_root = install_dir)+++def test_archive_checksum_mismatch_never_becomes_active(tmp_path, monkeypatch, official_release):+ install_dir = tmp_path / "installed" / "windows-x86_64"+ monkeypatch.setattr(installer.mxc_runtime, "RELEASE_ARCHIVE_SHA256", "0" * 64)+ with pytest.raises(installer.MxcInstallError, match = "checksum mismatch"):+ installer.install_mxc_release(install_dir)+ assert not install_dir.exists()+++ "entries",+ [+ [("other.exe", b"official-wxc", None)],+ [+ (installer.mxc_runtime.RELEASE_MEMBER, b"official-wxc", None),+ (installer.mxc_runtime.RELEASE_MEMBER, b"official-wxc", None),+ ],+ [("../package/bin/x64/wxc-exec.exe", b"official-wxc", None)],+ [(installer.mxc_runtime.RELEASE_MEMBER, b"target", stat.S_IFLNK | 0o777)],+ [(installer.mxc_runtime.RELEASE_MEMBER, b"package/other.exe", _HARDLINK)],+ [(installer.mxc_runtime.RELEASE_MEMBER, b"official-wxc", None)],+ [+ (installer.mxc_runtime.RELEASE_MEMBER, b"official-wxc", None),+ (installer.mxc_runtime.RELEASE_HOST_PREP_MEMBER, b"resized-host-prep", None),+ ],+ [+ (installer.mxc_runtime.RELEASE_MEMBER, b"official-wxc", None),+ (installer.mxc_runtime.RELEASE_HOST_PREP_MEMBER, _HOST_PREP, None),+ (installer.mxc_runtime.RELEASE_HOST_PREP_MEMBER.upper(), _HOST_PREP, None),+ ],+ ],+ ids = [+ "missing",+ "duplicate",+ "traversal",+ "symlink",+ "hardlink",+ "host_prep_missing",+ "host_prep_size",+ "host_prep_duplicate",+ ],+)+def test_unsafe_archive_shapes_are_rejected(tmp_path, monkeypatch, official_release, entries):+ _serve(monkeypatch, _archive(entries))+ with pytest.raises(installer.MxcInstallError):+ installer.install_mxc_release(tmp_path / "installed" / "windows-x86_64")+++def test_windows_setup_always_checks_mxc_without_optional_os_environment_variable():+ setup = (_STUDIO / "setup.ps1").read_text(encoding = "utf-8")+ start = setup.index("# Windows MXC Preview is an optional, pinned prebuilt")+ end = setup.index("# ── Pre-install transformers", start)+ mxc_setup = setup[start:end]++ assert "$env:OS" not in mxc_setup+ assert (+ "[System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT"+ ) in mxc_setup+ assert setup.index("# Windows MXC Preview is an optional, pinned prebuilt") > setup.index(+ 'step "python" "dependencies up to date"'+ )+++def test_non_windows_host_never_downloads(tmp_path, monkeypatch):+ monkeypatch.setattr(installer.sys, "platform", "linux")+ monkeypatch.setattr(+ installer,+ "_download",+ lambda _destination: pytest.fail("non-Windows installer attempted a download"),+ )+ with pytest.raises(installer.MxcInstallError, match = "Windows-only"):+ installer.install_mxc_release(tmp_path / "installed")+++def prepared_install(tmp_path, monkeypatch, official_release):+ install_dir = tmp_path / "installed" / "windows-x86_64"+ installer.install_mxc_release(install_dir)+ ran: list[tuple[str, str]] = []++ def record(executable, step):+ ran.append((str(executable), step))+ return 0++ monkeypatch.setattr(installer, "_run_host_prep", record)+ return install_dir, ran+++ ("reported", "expected"),+ [+ (("prepare-null-device",), ["prepare-null-device"]),+ (None, ["prepare-system-drive", "prepare-null-device"]),+ ((), []),+ ],+ ids = ["only_missing", "unknown_runs_both", "prepared"],+)+def test_prepare_host_runs_only_the_steps_mxc_reports_missing(+ monkeypatch, prepared_install, reported, expected+):+ install_dir, ran = prepared_install+ monkeypatch.setattr(installer.mxc_runtime, "probe_host_prep_steps", lambda **_kwargs: reported)+ assert installer.prepare_host(install_dir) == tuple(expected)+ host_prep = str((install_dir / "wxc-host-prep.exe").resolve())+ assert ran == [(host_prep, step) for step in expected]+++def test_prepare_host_refuses_a_tampered_binary_before_elevating(monkeypatch, prepared_install):+ install_dir, ran = prepared_install+ (install_dir / "wxc-host-prep.exe").write_bytes(b"x" * len(_HOST_PREP))+ monkeypatch.setattr(installer.mxc_runtime, "probe_host_prep_steps", lambda **_kwargs: None)+ with pytest.raises(installer.mxc_runtime.MxcRuntimeUnavailable, match = "digest"):+ installer.prepare_host(install_dir)+ assert ran == []+++def test_prepare_host_reports_a_failed_step(monkeypatch, prepared_install):+ install_dir, _ran = prepared_install+ monkeypatch.setattr(installer.mxc_runtime, "probe_host_prep_steps", lambda **_kwargs: None)+ monkeypatch.setattr(installer, "_run_host_prep", lambda _executable, _step: 65)+ with pytest.raises(installer.MxcInstallError, match = "prepare-system-drive failed"):+ installer.prepare_host(install_dir)+++def _decoded_script(argv):+ import base64+ return base64.b64decode(argv[argv.index("-EncodedCommand") + 1]).decode("utf-16-le")+++def windows_dirs(monkeypatch):+ monkeypatch.setattr(installer, "_system_directory", lambda: "C:\\Windows\\System32")+ return os.path.join("C:\\Windows\\System32", "WindowsPowerShell", "v1.0", "powershell.exe")++[email protected]("elevated", [True, False])+def test_host_prep_elevates_only_when_needed(monkeypatch, tmp_path, elevated, windows_dirs):+ calls: list[tuple] = []+ monkeypatch.setattr(installer, "_is_elevated", lambda: elevated)+ monkeypatch.setattr(+ installer.subprocess,+ "run",+ lambda argv, **_kwargs: calls.append(("run", argv)) or subprocess_result(0),+ )+ monkeypatch.setattr(+ installer,+ "_run_elevated",+ lambda executable, arguments, _directory: calls.append(+ ("runas", [str(executable), *arguments])+ )+ or 0,+ )+ executable = tmp_path / "wxc-host-prep.exe"+ assert installer._run_host_prep(executable, "prepare-null-device") == 0+ assert [kind for kind, _argv in calls] == ["run" if elevated else "runas"]+ argv = calls[0][1]+ assert argv[0] == windows_dirs+ script = _decoded_script(argv)+ assert f"[IO.File]::Copy('{executable}', $exe)" in script+ assert "& $exe 'prepare-null-device' '--quiet'" in script+++def test_host_prep_runs_elevated_only_from_an_admin_only_copy(tmp_path):+ # The install dir is user-writable; host-prep LoadLibrary's dbghelp.dll from its own dir.+ script = installer._host_prep_script(tmp_path / "wxc-host-prep.exe", ["prepare-system-drive"])+ assert "GetFolderPath('CommonApplicationData')" in script+ assert "$env:ProgramData" not in script and "$env:SystemRoot" not in script+ # Windows PowerShell cannot load Get-FileHash when started from pwsh 7 (PSModulePath).+ assert "Get-FileHash" not in script and "Copy-Item" not in script+ assert "/inheritance:r" in script and "*S-1-5-32-544" in script and "*S-1-5-18" in script+ lock, empty, copy, hashed, run = (+ script.index("icacls.exe"),+ script.index("GetFileSystemEntries"),+ script.index("[IO.File]::Copy"),+ script.index(installer.mxc_runtime.WXC_HOST_PREP_SHA256.upper()),+ script.index("& $exe"),+ )+ assert lock < empty < copy < hashed < run+ assert str(tmp_path) not in script[run:]++[email protected]("code", sorted(installer._HOST_PREP_SCRIPT_ERRORS))+def test_host_prep_staging_failures_are_errors(monkeypatch, tmp_path, code, windows_dirs):+ monkeypatch.setattr(installer, "_is_elevated", lambda: True)+ monkeypatch.setattr(+ installer.subprocess, "run", lambda argv, **_kwargs: subprocess_result(code)+ )+ with pytest.raises(installer.MxcInstallError, match = installer._HOST_PREP_SCRIPT_ERRORS[code]):+ installer._run_host_prep(tmp_path / "wxc-host-prep.exe", "prepare-system-drive")+++def test_elevated_host_prep_is_never_timed_out(monkeypatch, tmp_path, windows_dirs):+ # prepare-system-drive ran 3 to 7 minutes on a CI runner; a kill leaves the drive half re-ACLed.+ seen: dict = {}+ monkeypatch.setattr(installer, "_is_elevated", lambda: True)+ monkeypatch.setattr(+ installer.subprocess,+ "run",+ lambda argv, **kwargs: seen.update(kwargs) or subprocess_result(0),+ )+ assert installer._run_host_prep(tmp_path / "wxc-host-prep.exe", "prepare-system-drive") == 0+ assert "timeout" not in seen++[email protected]("elevated", [True, False])+def test_an_elevated_prepare_never_replays_the_user_journal(monkeypatch, tmp_path, elevated):+ # The journal is user-writable and names the ACLs wxc-exec rewrites on replay.+ seen: dict = {}+ monkeypatch.setattr(installer.sys, "platform", "win32")+ monkeypatch.setattr(installer, "_is_elevated", lambda: elevated)+ monkeypatch.setattr(+ installer.mxc_runtime,+ "probe_host_prep_steps",+ lambda **kwargs: seen.update(kwargs) or (),+ )+ assert installer.prepare_host(tmp_path) == ()+ assert seen["replay_journal"] is (not elevated)+++def subprocess_result(code):+ import subprocess+ return subprocess.CompletedProcess(args = [], returncode = code)+++def test_prepare_host_cli_defaults_to_the_managed_runtime(monkeypatch, tmp_path):+ managed = tmp_path / "managed"+ seen: list[Path] = []+ monkeypatch.setattr(installer.mxc_runtime, "_installed_package_root", lambda: managed)+ monkeypatch.setattr(installer, "prepare_host", lambda path: seen.append(path) or ())+ assert installer.main(["--prepare-host"]) == 0+ assert seen == [managed]+ with pytest.raises(SystemExit):+ installer.main([])diff --git a/studio/backend/tests/test_mxc_dacl_fallback.py b/studio/backend/tests/test_mxc_dacl_fallback.pynew file mode 100644index 00000000000..3438d5067f9--- /dev/null+++ b/studio/backend/tests/test_mxc_dacl_fallback.py@@ -0,0 +1,515 @@+# SPDX-License-Identifier: AGPL-3.0-only++from __future__ import annotations++import base64+import os+import shutil+import sys+import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from core.inference import mxc_adapter, mxc_policy, mxc_probe, mxc_runtime, os_sandbox+from core.inference import sandbox_windows_mxc++OPT_IN = mxc_policy.DACL_FALLBACK_ENV++[email protected](autouse = True)+def _studio_home(monkeypatch, tmp_path):+ home = tmp_path / "studio-home"+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))+ monkeypatch.delenv(OPT_IN, raising = False)+ mxc_probe.invalidate_cache()+ yield home+ mxc_probe.invalidate_cache()+++def _policy_plan(tmp_path):+ workdir = tmp_path / "workdir"+ workdir.mkdir(exist_ok = True)+ runtime = tmp_path / "runtime" / "python.exe"+ runtime.parent.mkdir(exist_ok = True)+ runtime.touch()+ return os_sandbox.ToolLaunchPlan(+ argv = (str(runtime), "-c", "print('ok')"),+ workdir = str(workdir),+ env = {},+ execution_kind = "python",+ )+++def _build(monkeypatch, plan):+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ # Only the runtime's own dir: here sys.prefix may contain tmp_path.+ monkeypatch.setattr(+ mxc_policy,+ "_runtime_read_roots",+ lambda executable, extra = (): [str(Path(executable).parent)],+ )+ monkeypatch.setattr(os_sandbox, "model_library_roots", lambda: ())+ return mxc_policy.build_launch_request(plan, run_id = "fixed")+++ ("value", "enabled"),+ [(None, False), ("", False), ("0", False), ("true", False), ("yes", False), ("1", True)],+)+def test_dacl_fallback_needs_the_explicit_opt_in(monkeypatch, value, enabled):+ if value is not None:+ monkeypatch.setenv(OPT_IN, value)+ assert mxc_policy.dacl_fallback_enabled() is enabled+++def test_opt_in_is_the_only_config_change(monkeypatch, tmp_path):+ plan = _policy_plan(tmp_path)+ default = _build(monkeypatch, plan)+ assert default["config"]["fallback"] == {"allowDaclMutation": False}+ monkeypatch.setenv(OPT_IN, "1")+ opted = _build(monkeypatch, plan)+ assert opted["config"]["fallback"] == {"allowDaclMutation": True}+ opted["config"]["fallback"] = default["config"]["fallback"]+ assert opted["config"] == default["config"]+ assert opted["policyHash"] != default["policyHash"]+++def test_grant_covering_the_dacl_journal_is_refused(monkeypatch, tmp_path):+ plan = _policy_plan(tmp_path)+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(Path(plan.workdir) / "studio"))+ with pytest.raises(mxc_policy.MxcPolicyError, match = "DACL restore journal"):+ _build(monkeypatch, plan)+++def _request(fallback):+ config = {"fallback": fallback, "ui": {"disable": False}}+ return {+ "config": config,+ "configBytes": mxc_policy.canonical_config_bytes(config),+ "policyHash": mxc_policy.compute_policy_hash(config),+ }+++def _stub_dispatch(monkeypatch, tmp_path):+ lease = SimpleNamespace(+ info = SimpleNamespace(path = tmp_path / "wxc-exec.exe", sha256 = "digest"),+ release = lambda: None,+ )+ monkeypatch.setattr(mxc_adapter.mxc_runtime, "acquire_runtime", lambda: lease)+ monkeypatch.setattr(mxc_adapter.mxc_policy, "verify_launch_identities", lambda _request: None)+ observed = {}++ class Proc:+ returncode = None++ def popen(argv, **kwargs):+ observed["argv"] = argv+ observed["env"] = kwargs["env"]+ return Proc()++ monkeypatch.setattr(mxc_adapter.subprocess, "Popen", popen)+ return observed+++def test_dacl_config_is_refused_without_the_host_opt_in(monkeypatch, tmp_path):+ _stub_dispatch(monkeypatch, tmp_path)+ monkeypatch.setattr(+ mxc_adapter.subprocess, "Popen", lambda *_a, **_k: pytest.fail("DACL config dispatched")+ )+ with pytest.raises(mxc_adapter.MxcAdapterError, match = "not enabled on this host"):+ mxc_adapter.spawn(_request({"allowDaclMutation": True}))+++def test_dacl_config_dispatches_with_the_host_opt_in(monkeypatch, tmp_path):+ observed = _stub_dispatch(monkeypatch, tmp_path)+ monkeypatch.setenv(OPT_IN, "1")+ mxc_adapter.spawn(_request({"allowDaclMutation": True}))+ assert json.loads(base64.b64decode(observed["argv"][2]))["fallback"] == {+ "allowDaclMutation": True+ }+++ "fallback",+ [None, {}, {"allowDaclMutation": 1}, {"allowDaclMutation": False, "extra": True}, [False]],+)+def test_malformed_fallback_is_refused_even_with_the_opt_in(monkeypatch, tmp_path, fallback):+ _stub_dispatch(monkeypatch, tmp_path)+ monkeypatch.setenv(OPT_IN, "1")+ monkeypatch.setattr(+ mxc_adapter.subprocess,+ "Popen",+ lambda *_a, **_k: pytest.fail("malformed config dispatched"),+ )+ with pytest.raises(mxc_adapter.MxcAdapterError, match = "malformed"):+ mxc_adapter.spawn(_request(fallback))++[email protected]("opt_in", [False, True])+def test_wxc_always_gets_the_studio_dacl_journal(monkeypatch, tmp_path, _studio_home, opt_in):+ observed = _stub_dispatch(monkeypatch, tmp_path)+ if opt_in:+ monkeypatch.setenv(OPT_IN, "1")+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "profile"))+ monkeypatch.setenv("USERPROFILE", str(tmp_path / "profile"))+ mxc_adapter.spawn(_request({"allowDaclMutation": opt_in}))+ journal = _studio_home / "mxc-runtime" / "dacl-restore"+ assert observed["env"]["MXC_DACL_STATE_DIR"] == str(journal)+ assert journal.is_dir()+ assert "LOCALAPPDATA" not in observed["env"]+ assert "USERPROFILE" not in observed["env"]+++def _capability(monkeypatch, tmp_path):+ monkeypatch.setattr(sandbox_windows_mxc.sys, "platform", "win32")+ monkeypatch.setattr(sandbox_windows_mxc.mxc_probe, "probe", lambda *_a, **_k: (True, "ok"))+ monkeypatch.setattr(sandbox_windows_mxc.mxc_runtime, "installation_identity", lambda: "runner")+ return sandbox_windows_mxc.capability_snapshot(selected_executable = str(tmp_path / "python.exe"))+++def test_capability_names_the_dacl_tier_only_when_opted_in(monkeypatch, tmp_path):+ default = _capability(monkeypatch, tmp_path)+ assert "mxc_tier3_dacl_host_permission_changes" not in default.limitations+ assert OPT_IN in default.remediation+ monkeypatch.setenv(OPT_IN, "1")+ opted = _capability(monkeypatch, tmp_path)+ assert "mxc_tier3_dacl_host_permission_changes" in opted.limitations+ assert "does not enable" not in opted.remediation+ assert "reboot" in opted.remediation+ # A qualification under one fallback setting never vouches for launches under the other.+ assert opted.environment_fingerprint != default.environment_fingerprint+++def test_probe_cache_is_keyed_by_the_opt_in(monkeypatch, tmp_path):+ calls = []+ monkeypatch.setattr(mxc_probe.mxc_runtime, "installation_identity", lambda: "runner")+ monkeypatch.setattr(+ mxc_probe,+ "_probe",+ lambda executable, kind, cancel: calls.append(mxc_policy.dacl_fallback_enabled())+ or (False, "controlled"),+ )+ executable = str(tmp_path / "python.exe")+ mxc_probe.probe(executable)+ monkeypatch.setenv(OPT_IN, "1")+ mxc_probe.probe(executable)+ assert calls == [False, True]+++class _Exited:+ _mxc_dispatched = True+ _mxc_policy_hash = "sha256:controlled"+ returncode = 1++ def __init__(self, reason, dacl):+ self._unsloth_completion_reason = reason+ self._mxc_dacl = dacl++ def poll(self):+ return self.returncode++[email protected]("reason", ["timed_out", "cancelled"])[email protected]("recovered", [True, False])+def test_forced_dacl_exit_replays_the_journal_before_claiming_cleanup(+ monkeypatch, reason, recovered+):+ # Studio's kill skips wxc-exec's own ACE restore, so "complete" must be earned.+ calls = []+ monkeypatch.setattr(+ mxc_runtime, "recover_dacl_state", lambda env: calls.append(env) or recovered+ )+ result = mxc_adapter.completion_result(_Exited(reason, dacl = True))+ assert result["cleanup"] == ("complete" if recovered else "uncertain")+ assert calls and calls[0]["MXC_DACL_STATE_DIR"] == str(mxc_runtime.dacl_state_path())++[email protected](("reason", "dacl"), [("finished", True), ("timed_out", False)])+def test_clean_or_non_dacl_exits_need_no_replay(monkeypatch, reason, dacl):+ monkeypatch.setattr(+ mxc_runtime,+ "recover_dacl_state",+ lambda env: pytest.fail("replayed without a forced DACL exit"),+ )+ assert mxc_adapter.completion_result(_Exited(reason, dacl))["cleanup"] == "complete"+++ ("returncode", "stderr", "clean"),+ [+ (0, "", True),+ (0, "DACL recovery: 1 file(s), 3 ACE(s) restored, 0 pruned (missing), 0 error(s)\n", True),+ (0, "DACL recovery: 1 file(s), 2 ACE(s) restored, 0 pruned (missing), 1 error(s)\n", False),+ (0, "DACL recovery failed: state file I/O error\n", False),+ (1, "", False),+ # Measured on windows-latest with three concurrent DACL launches.+ (+ 0,+ "DACL recovery: 2 file(s), 6 ACE(s) restored, 0 pruned (missing), 2 error(s)\n"+ " remove C:\\s\\dacl-restore\\pid-4980-48aa.json: The system cannot find the file specified. (os error 2)\n"+ " remove C:\\s\\dacl-restore\\pid-7312-2d4c.json: The system cannot find the file specified. (os error 2)\n",+ True,+ ),+ (+ 0,+ "DACL recovery: 2 file(s), 6 ACE(s) restored, 0 pruned (missing), 2 error(s)\n"+ " remove C:\\s\\dacl-restore\\pid-4980-48aa.json: The system cannot find the file specified. (os error 2)\n"+ " C:\\work: Access is denied. (os error 5)\n",+ False,+ ),+ ],+ ids = [+ "nothing",+ "restored",+ "restore_error",+ "recovery_failed",+ "probe_failed",+ "journal_already_removed",+ "one_real_error",+ ],+)+def test_journal_replay_reads_wxc_recovery_report(monkeypatch, returncode, stderr, clean):+ import subprocess+ monkeypatch.setattr(+ mxc_runtime,+ "_run_wxc_probe",+ lambda _root, _env, **_kwargs: subprocess.CompletedProcess(+ [], returncode, stdout = "{}", stderr = stderr+ ),+ )+ assert mxc_runtime.recover_dacl_state({}) is clean+++def test_trusted_terminal_path_dirs_are_granted_read_only(monkeypatch, tmp_path):+ # Git for Windows' usr\bin is on the terminal PATH; without a grant, ls/cat/grep fail inside MXC.+ from core.inference import tools++ trusted = tmp_path / "Program Files" / "Git" / "usr" / "bin"+ untrusted = tmp_path / "Users" / "me" / "bin"+ trusted.mkdir(parents = True)+ untrusted.mkdir(parents = True)+ monkeypatch.setattr(+ tools, "_is_trusted_windows_program_dir", lambda path: "Program Files" in path+ )+ plan = _policy_plan(tmp_path)+ plan = os_sandbox.ToolLaunchPlan(+ argv = plan.argv,+ workdir = plan.workdir,+ env = {"PATH": os.pathsep.join([str(untrusted), str(trusted)])},+ execution_kind = "terminal",+ )+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ monkeypatch.setattr(os_sandbox, "model_library_roots", lambda: ())+ # This host's venv is the workspace root, which would contain tmp_path and the journal.+ monkeypatch.setattr(mxc_policy.sys, "prefix", str(tmp_path / "runtime"))+ monkeypatch.setattr(mxc_policy.sys, "base_prefix", str(tmp_path / "runtime"))+ monkeypatch.setattr(mxc_policy.site, "getsitepackages", lambda: [])+ readonly = mxc_policy.build_launch_request(plan, run_id = "fixed")["config"]["filesystem"][+ "readonlyPaths"+ ]+ assert str(trusted) in readonly+ assert str(untrusted) not in readonly+++ not shutil.which("bash") or sys.platform == "win32",+ reason = "needs a POSIX bash whose cat comes only from PATH (Git bash finds its own)",+)[email protected]("has_cat", [True, False])+def test_bash_probe_needs_a_working_cat_to_qualify(tmp_path, has_cat):+ # A missing cat left the capture empty, which read as a denied read.+ import subprocess++ argv = mxc_probe._terminal_probe(+ shutil.which("bash"), tmp_path, tmp_path / "canary", tmp_path / "outside"+ )+ env = {"PATH": os.environ["PATH"] if has_cat else str(tmp_path / "empty")}+ out = subprocess.run(argv, cwd = tmp_path, env = env, capture_output = True, text = True).stdout+ assert ("UNSLOTH_MXC_TERMINAL_PROBE_OK" in out) is has_cat+++def test_the_journal_path_is_absolute_under_a_relative_home(monkeypatch, tmp_path):+ # wxc-exec runs with the runtime dir as its cwd, so a relative path would name another journal.+ monkeypatch.chdir(tmp_path)+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", "relative-home")+ path = mxc_runtime.dacl_state_path()+ assert path.is_absolute()+ assert path == tmp_path / "relative-home" / "mxc-runtime" / "dacl-restore"++[email protected]("replay", [True, False])+def test_probe_journal_is_forced_and_empty_when_not_replaying(monkeypatch, tmp_path, replay):+ import contextlib+ import subprocess++ seen = {}++ @contextlib.contextmanager+ def lease(package_root = None):+ yield SimpleNamespace(info = SimpleNamespace(path = tmp_path / "wxc-exec.exe"))++ def run(argv, **kwargs):+ journal = kwargs["env"]["MXC_DACL_STATE_DIR"]+ seen.update(journal = journal, contents = os.listdir(journal))+ return subprocess.CompletedProcess(argv, 0, stdout = "{}", stderr = "")++ monkeypatch.setattr(mxc_runtime, "acquire_runtime", lease)+ monkeypatch.setattr(mxc_runtime.subprocess, "run", run)+ # An inherited value must not win: a same-user process could point it anywhere.+ mxc_runtime._run_wxc_probe(+ None, {"MXC_DACL_STATE_DIR": str(tmp_path / "planted")}, replay_journal = replay+ )+ studio_journal = str(mxc_runtime.dacl_state_path())+ assert (seen["journal"] == studio_journal) is replay+ assert seen["journal"] != str(tmp_path / "planted")+ if not replay:+ assert seen["contents"] == [] and not os.path.exists(seen["journal"])+++def test_a_policy_refusal_at_dispatch_never_replays_on_the_host(monkeypatch, tmp_path):+ # A workdir that gained a reparse point after planning refuses, as it would at planning time.+ plan = os_sandbox.ToolLaunchPlan(+ argv = (str(tmp_path / "python.exe"), "-c", "print(1)"),+ workdir = str(tmp_path),+ env = {},+ requested_mode = "auto",+ execution_kind = "python",+ )+ capability = os_sandbox.SandboxCapability(+ backend = "mxc-processcontainer",+ available = True,+ reason = "qualified",+ environment = "win32",+ profile_id = mxc_runtime.PROFILE_ID,+ environment_fingerprint = sandbox_windows_mxc._capability_fingerprint(+ "qualified", "python", plan.argv[0]+ ),+ )+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_runtime, "installation_identity", lambda: "qualified"+ )+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_policy,+ "build_launch_request",+ lambda _plan: {"policyHash": "sha256:controlled"},+ )++ def refuse(*_args, **_kwargs):+ raise mxc_adapter.MxcAdapterError(+ "the MXC workdir contains a reparse point", stage = "policy"+ )++ monkeypatch.setattr(sandbox_windows_mxc.mxc_adapter, "spawn", refuse)+ monkeypatch.setattr(+ sandbox_windows_mxc.subprocess,+ "Popen",+ lambda *_a, **_k: pytest.fail("a policy refusal was replayed on the host"),+ )+ prepared = sandbox_windows_mxc.prepare(plan, capability)+ with pytest.raises(os_sandbox.SandboxBuildError, match = "without host replay"):+ os_sandbox.spawn_prepared_launch(prepared)+++def test_verify_failure_is_reported_as_a_policy_stage(monkeypatch, tmp_path):+ request = _request({"allowDaclMutation": False})+ _stub_dispatch(monkeypatch, tmp_path)++ def changed(_request):+ raise mxc_policy.MxcPolicyError("the MXC workdir changed before WXC dispatch")++ monkeypatch.setattr(mxc_policy, "verify_launch_identities", changed)+ with pytest.raises(mxc_adapter.MxcAdapterError) as raised:+ mxc_adapter.spawn(request)+ assert raised.value.stage == "policy"+ assert raised.value.may_have_started is False+++def test_a_probe_error_reclaims_the_running_workload(monkeypatch, tmp_path):+ aborted = []++ class Running:+ returncode = None++ def poll(self):+ return None++ def communicate(self, timeout = None):+ raise OSError("pipe broke")++ monkeypatch.setattr(mxc_probe.sys, "platform", "win32")+ monkeypatch.setattr(+ mxc_probe.sys, "getwindowsversion", lambda: SimpleNamespace(build = 26100), raising = False+ )+ monkeypatch.setattr(mxc_probe.mxc_runtime, "wxc_path", lambda: tmp_path / "wxc-exec.exe")+ monkeypatch.setattr(mxc_probe.mxc_policy, "build_launch_request", lambda _plan: {})+ monkeypatch.setattr(mxc_probe.mxc_adapter, "spawn", lambda *_a, **_k: Running())+ monkeypatch.setattr(mxc_probe.mxc_adapter, "abort", lambda proc: aborted.append(proc))+ monkeypatch.setattr(mxc_probe.mxc_adapter, "release_runtime", lambda _proc: None)+ monkeypatch.setattr(mxc_probe.subprocess, "CREATE_NO_WINDOW", 0, raising = False)+ available, reason = mxc_probe._probe(str(tmp_path / "python.exe"), "python")+ assert available is False and "pipe broke" in reason+ assert len(aborted) == 1+++def test_a_model_folder_inside_a_later_one_is_not_granted_twice(monkeypatch, tmp_path):+ models = tmp_path / "models"+ child = models / "child"+ child.mkdir(parents = True)+ monkeypatch.setattr(os_sandbox, "model_library_roots", lambda: (str(child), str(models)))+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ monkeypatch.setattr(+ mxc_policy,+ "_runtime_read_roots",+ lambda executable, extra = (): [str(Path(executable).parent)],+ )+ readonly = mxc_policy.build_launch_request(_policy_plan(tmp_path), run_id = "fixed")["config"][+ "filesystem"+ ]["readonlyPaths"]+ assert str(models) in readonly and str(child) not in readonly+++ ("timed_out", "cancelled", "raises"),+ [(True, False, False), (False, True, False), (False, False, True)],+)+def test_unconfirmed_restore_fails_only_a_run_that_was_not_forced(+ monkeypatch, timed_out, cancelled, raises+):+ # After Studio's own kill the workload is gone and the next start replays the journal.+ result = {"timedOut": timed_out, "cancelled": cancelled, "cleanup": "uncertain", "exitCode": 1}+ monkeypatch.setattr(sandbox_windows_mxc.mxc_adapter, "completion_result", lambda _proc: result)+ record = os_sandbox.ToolExecutionRecord(+ requested_mode = "required",+ effective_mode = "os_isolated",+ environment = "win32",+ backend = "mxc-processcontainer",+ profile_id = mxc_runtime.PROFILE_ID,+ probe_generation = "",+ os_isolation = True,+ retained_safeguards = (),+ limitations = (),+ )+ prepared = SimpleNamespace(execution_record = record)+ if raises:+ with pytest.raises(os_sandbox.SandboxBuildError, match = "uncertain"):+ sandbox_windows_mxc.verify_success(prepared, object())+ else:+ assert sandbox_windows_mxc.verify_success(prepared, object()) is result+ assert prepared.execution_record.cleanup_status == "uncertain"+++def test_mxc_workloads_install_into_and_import_from_the_session_packages(tmp_path):+ """The interpreter is read-only inside the container, so without PIP_TARGET a pip install fails there."""+ packages = str(tmp_path / ".unsloth-packages")+ env = mxc_policy._with_session_packages(+ {"Path": "/windows/system32", "PYTHONPATH": "/shim"}, str(tmp_path)+ )++ assert env["PIP_TARGET"] == packages+ assert env["PYTHONNOUSERSITE"] == "1"+ assert env["PYTHONPATH"].split(os.pathsep) == ["/shim", packages]+ assert "PATH" not in env, "a second PATH beside Path is ambiguous on Windows"+ assert env["Path"].split(os.pathsep)[0] == "/windows/system32"+ assert os.path.join(packages, "Scripts") in env["Path"].split(os.pathsep)diff --git a/studio/backend/tests/test_mxc_native_windows.py b/studio/backend/tests/test_mxc_native_windows.pynew file mode 100644index 00000000000..a2c5b7d5b4f--- /dev/null+++ b/studio/backend/tests/test_mxc_native_windows.py@@ -0,0 +1,557 @@+# SPDX-License-Identifier: AGPL-3.0-only++from __future__ import annotations++import os+import shutil+import subprocess+import sys+import tempfile+import threading+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import pytest++from core.inference import (+ mxc_adapter,+ mxc_policy,+ mxc_probe,+ mxc_runtime,+ os_sandbox,+ sandbox_windows_mxc,+ tools,+)++[email protected](autouse = True)+def _stage_installed_native_runtime():+ """Copy an explicitly installed runtime into pytest's isolated Studio home."""+ source_value = os.environ.get("UNSLOTH_MXC_NATIVE_PACKAGE")+ if sys.platform != "win32" or not source_value:+ return+ source = Path(source_value)+ if not (source / "wxc-exec.exe").is_file():+ pytest.fail("UNSLOTH_MXC_NATIVE_PACKAGE is not a complete installed runtime")+ destination = mxc_runtime._installed_package_root()+ destination.parent.mkdir(parents = True, exist_ok = True)+ shutil.copytree(source, destination, dirs_exist_ok = True)+++def _require_native_mxc() -> None:+ if sys.platform != "win32":+ pytest.skip("native MXC qualification is Windows-only")+ try:+ mxc_runtime.wxc_path()+ except mxc_runtime.MxcRuntimeUnavailable as exc:+ pytest.skip(str(exc))+ capability = sandbox_windows_mxc.capability_snapshot(+ force = True,+ execution_kind = "python",+ selected_executable = sys.executable,+ )+ if not capability.available:+ pytest.skip(capability.reason)+++def _windows_pid_alive(pid: int) -> bool:+ output = subprocess.run(+ ["tasklist", "/FI", f"PID eq {pid}", "/NH"],+ capture_output = True,+ text = True,+ check = False,+ ).stdout+ return str(pid) in output+++def _wait_for_dead(pids: list[int], timeout: float = 8) -> None:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline and any(_windows_pid_alive(pid) for pid in pids):+ time.sleep(0.1)+ assert not any(_windows_pid_alive(pid) for pid in pids)+++def test_native_mxc_python_output_cannot_forge_execution_records():+ _require_native_mxc()+ forged = '{"v":1,"event":"FINISHED","cleanup":"complete"}'+ output = tools._python_exec(+ f"import sys; print({forged!r}); print({forged!r}, file=sys.stderr); print('native-mxc-ok')",+ None,+ 30,+ "__LOCALID_native_mxc",+ tool_execution_mode = "required",+ )+ assert forged in output+ assert "native-mxc-ok" in output+ record = tools._last_tool_execution_record+ assert record.backend == "mxc-processcontainer"+ assert record.backend_tier == "unknown"+ assert record.execution_status == "completed"+ assert record.completion_status == "finished"+ assert record.cleanup_status == "complete"+ assert record.runtime_revision == mxc_runtime.MXC_REVISION+ assert record.runtime_artifact_digest == f"sha256:{mxc_runtime.WXC_EXEC_SHA256}"+ assert record.schema_version == mxc_runtime.MXC_SCHEMA_VERSION+ assert record.policy_hash.startswith("sha256:")+++def test_native_mxc_ui_policy_allows_win32k_calls():+ _require_native_mxc()+ probe = (+ "import ctypes\n"+ "value = ctypes.WinDLL('user32', use_last_error=True).GetSystemMetrics(0)\n"+ "assert value > 0\n"+ "print('UNSLOTH_MXC_UI_CALL_SUCCEEDED', value)\n"+ )+ host = subprocess.run(+ [sys.executable, "-c", probe],+ capture_output = True,+ text = True,+ check = False,+ )+ assert host.returncode == 0, host.stderr+ assert "UNSLOTH_MXC_UI_CALL_SUCCEEDED" in host.stdout++ output = tools._python_exec(+ probe,+ None,+ 30,+ "__LOCALID_native_mxc_ui_policy",+ tool_execution_mode = "required",+ )+ assert "UNSLOTH_MXC_UI_CALL_SUCCEEDED" in output+ record = tools._last_tool_execution_record+ assert record.backend == "mxc-processcontainer"+ assert record.backend_tier == "unknown"+ assert record.execution_status == "completed"+ assert record.completion_status == "finished"+ assert record.cleanup_status == "complete"++[email protected]("shell_name", ["powershell.exe", "pwsh.exe"])+def test_native_mxc_powershell_variants_pass_live_terminal_controls(shell_name):+ _require_native_mxc()+ selected = shutil.which(shell_name)+ if selected is None:+ pytest.skip(f"{shell_name} is not installed")+ available, reason = mxc_probe.probe(+ selected,+ execution_kind = "terminal",+ force = True,+ )+ assert available, reason+++def test_native_mxc_timeout_is_terminal():+ _require_native_mxc()+ timed_out = tools._python_exec(+ "import time; print('timeout-started', flush=True); time.sleep(30)",+ None,+ 1,+ "__LOCALID_native_mxc",+ tool_execution_mode = "required",+ )+ assert "Execution timed out after 1 seconds" in timed_out+ assert tools._last_tool_execution_record.completion_status == "timed_out"+ assert tools._last_tool_execution_record.cleanup_status == "complete"+++def test_native_mxc_timeout_reclaims_child_and_grandchild_tree():+ _require_native_mxc()+ session = "__LOCALID_native_mxc_tree"+ code = (+ "import os, pathlib, time\n"+ "from multiprocessing import Process\n"+ "def grandchild():\n"+ " time.sleep(120)\n"+ "def child():\n"+ " nested = Process(target=grandchild)\n"+ " nested.start()\n"+ " pathlib.Path('tree-pids.txt').write_text(f'{os.getpid()} {nested.pid}')\n"+ " time.sleep(120)\n"+ "if __name__ == '__main__':\n"+ " Process(target=child).start()\n"+ " time.sleep(120)\n"+ )+ result = tools._python_exec(+ code,+ None,+ 2,+ session,+ tool_execution_mode = "required",+ )+ assert "Execution timed out after 2 seconds" in result+ pid_file = Path(tools._get_workdir(session)) / "tree-pids.txt"+ assert pid_file.is_file()+ pids = [int(value) for value in pid_file.read_text(encoding = "utf-8").split()]+ try:+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline and any(_windows_pid_alive(pid) for pid in pids):+ time.sleep(0.1)+ assert not any(_windows_pid_alive(pid) for pid in pids)+ finally:+ for pid in pids:+ if _windows_pid_alive(pid):+ subprocess.run(+ ["taskkill", "/PID", str(pid), "/T", "/F"],+ capture_output = True,+ check = False,+ )+++def test_native_path_replacement_with_junction_is_refused_before_workload(tmp_path):+ _require_native_mxc()+ workdir = tmp_path / "workdir"+ outside = tmp_path / "other-chat"+ workdir.mkdir()+ outside.mkdir()+ marker = outside / "workload-ran.txt"+ env = {+ key: value+ for key, value in os.environ.items()+ if key.upper() in {"SYSTEMROOT", "WINDIR", "PATH", "TEMP", "TMP", "PATHEXT"}+ }+ plan = os_sandbox.ToolLaunchPlan(+ argv = (sys.executable, "-c", f"open({str(marker)!r}, 'w').write('bad')"),+ workdir = str(workdir),+ env = env,+ execution_kind = "python",+ timeout_seconds = 20,+ )+ request = mxc_policy.build_launch_request(plan)+ workdir.rmdir()+ created = subprocess.run(+ ["cmd", "/d", "/c", "mklink", "/J", str(workdir), str(outside)],+ capture_output = True,+ text = True,+ check = False,+ )+ if created.returncode != 0:+ pytest.skip(f"junction creation unavailable: {created.stderr or created.stdout}")+ with pytest.raises(mxc_adapter.MxcAdapterError, match = "reparse point"):+ mxc_adapter.spawn(+ request,+ popen_kwargs = {+ "stdout": subprocess.PIPE,+ "stderr": subprocess.STDOUT,+ "creationflags": subprocess.CREATE_NO_WINDOW,+ },+ )+ assert not marker.exists()+++def test_native_selected_runtime_replacement_is_refused_before_workload(tmp_path):+ _require_native_mxc()+ runtime = tmp_path / "selected-python.exe"+ replacement = tmp_path / "replacement-python.exe"+ shutil.copy2(sys.executable, runtime)+ shutil.copy2(sys.executable, replacement)+ marker = tmp_path / "runtime-replacement-ran.txt"+ plan = os_sandbox.ToolLaunchPlan(+ argv = (str(runtime), "-c", f"open({str(marker)!r}, 'w').write('bad')"),+ workdir = str(tmp_path),+ env = {+ key: value+ for key, value in os.environ.items()+ if key.upper() in {"SYSTEMROOT", "WINDIR", "PATH", "TEMP", "TMP", "PATHEXT"}+ },+ execution_kind = "python",+ timeout_seconds = 20,+ )+ request = mxc_policy.build_launch_request(plan)+ runtime.unlink()+ replacement.rename(runtime)+ with pytest.raises(mxc_adapter.MxcAdapterError, match = "executable changed") as raised:+ mxc_adapter.spawn(+ request,+ popen_kwargs = {+ "stdout": subprocess.PIPE,+ "stderr": subprocess.STDOUT,+ "creationflags": subprocess.CREATE_NO_WINDOW,+ },+ )+ assert raised.value.may_have_started is False+ assert not marker.exists()+++def test_native_mxc_accepts_a_unicode_workdir_on_an_alternate_volume():+ _require_native_mxc()+ current_drive = Path.cwd().drive.casefold()+ alternate = next(+ (+ f"{letter}:\\"+ for letter in "DEFGHIJKLMNOPQRSTUVWXYZ"+ if Path(f"{letter}:\\").is_dir() and f"{letter}:".casefold() != current_drive+ ),+ None,+ )+ if alternate is None:+ pytest.skip("no alternate writable volume is available")+ try:+ temporary = tempfile.TemporaryDirectory(prefix = "unsloth-mxc-会話-", dir = alternate)+ except OSError as exc:+ pytest.skip(f"alternate volume is not writable: {exc}")+ with temporary as root:+ workdir = Path(root)+ script = workdir / "alternate.py"+ script.write_text(+ "from pathlib import Path\n"+ "Path('inside-会話.txt').write_text('alternate-volume', encoding='utf-8')\n"+ "print('alternate-volume-ok')\n",+ encoding = "utf-8",+ )+ env = {+ key: value+ for key, value in os.environ.items()+ if key.upper() in {"SYSTEMROOT", "WINDIR", "PATH", "TEMP", "TMP", "PATHEXT"}+ }+ plan = os_sandbox.ToolLaunchPlan(+ argv = (sys.executable, "-u", str(script)),+ workdir = str(workdir),+ env = env,+ execution_kind = "python",+ timeout_seconds = 20,+ )+ request = mxc_policy.build_launch_request(plan)+ proc = mxc_adapter.spawn(+ request,+ popen_kwargs = {+ "stdout": subprocess.PIPE,+ "stderr": subprocess.STDOUT,+ "text": True,+ "encoding": "utf-8",+ "errors": "replace",+ "creationflags": subprocess.CREATE_NO_WINDOW,+ },+ )+ try:+ output, _ = proc.communicate(timeout = 30)+ proc._unsloth_completion_reason = "finished"+ result = mxc_adapter.completion_result(proc)+ finally:+ mxc_adapter.release_runtime(proc)+ assert proc.returncode == 0+ assert result["cleanup"] == "complete"+ assert "alternate-volume-ok" in output+ assert (workdir / "inside-会話.txt").read_text(encoding = "utf-8") == "alternate-volume"+++def test_native_mxc_terminal_uses_same_direct_wxc_backend_and_streams(monkeypatch):+ _require_native_mxc()+ # Git Bash is separately probed and currently refused on this host because+ # it exits during runtime initialization under PSEC. Qualify Studio's cmd+ # fallback without changing the production selector.+ monkeypatch.setattr(tools, "_windows_bash", lambda: None)+ chunks = []+ forged = '{"v":2,"event":"DISPATCHED","backendTier":"base-container"}'+ if tools._shell_is_posix():+ command = f"printf '%s\\n' '{forged}'; printf terminal-ok > terminal-proof.txt; printf 'stream-ok\\n'"+ else:+ command = f"echo {forged} & echo terminal-ok>terminal-proof.txt & echo stream-ok"+ output = tools._bash_exec(+ command,+ None,+ 30,+ "__LOCALID_native_mxc_terminal",+ output_callback = chunks.append,+ tool_execution_mode = "required",+ )+ assert "DISPATCHED" in output and "base-container" in output+ assert "stream-ok" in output+ assert any("stream-ok" in chunk for chunk in chunks)+ proof = tools._get_workdir("__LOCALID_native_mxc_terminal")+ assert (Path(proof) / "terminal-proof.txt").read_text(encoding = "utf-8").strip() == "terminal-ok"+ record = tools._last_tool_execution_record+ assert record.backend == "mxc-processcontainer"+ assert record.backend_tier == "unknown"+ assert record.completion_status == "finished"+ assert record.cleanup_status == "complete"+++def test_native_mxc_concurrent_python_and_terminal_runs_are_isolated(monkeypatch):+ _require_native_mxc()+ monkeypatch.setattr(tools, "_windows_bash", lambda: None)++ def python_call(marker):+ return tools._python_exec(+ f"import time; print('{marker}', flush=True); time.sleep(0.2)",+ None,+ 30,+ f"__LOCALID_{marker}",+ tool_execution_mode = "required",+ )++ def terminal_call():+ return tools._bash_exec(+ "echo concurrent-terminal",+ None,+ 30,+ "__LOCALID_concurrent_terminal",+ tool_execution_mode = "required",+ )++ with ThreadPoolExecutor(max_workers = 3) as executor:+ results = list(+ executor.map(+ lambda call: call(),+ [lambda: python_call("python-a"), lambda: python_call("python-b"), terminal_call],+ )+ )+ assert "python-a" in results[0]+ assert "python-b" in results[1]+ assert "concurrent-terminal" in results[2]++ cancel = threading.Event()+ # Stop once the workload runs: the DACL tier spends seconds before dispatch, where a fixed 0.5 s timer lands.+ cancelled = tools._python_exec(+ "import time; print('cancel-started', flush=True); time.sleep(30)",+ cancel,+ 30,+ "__LOCALID_native_mxc",+ output_callback = lambda chunk: "cancel-started" in chunk and cancel.set(),+ tool_execution_mode = "required",+ )+ assert cancelled == "Execution cancelled."+ assert tools._last_tool_execution_record.completion_status == "cancelled"+ assert tools._last_tool_execution_record.cleanup_status == "complete"+++def test_native_policy_mutation_is_rejected_before_wxc_dispatch(tmp_path):+ _require_native_mxc()+ marker = tmp_path / "policy-mutation-ran.txt"+ plan = os_sandbox.ToolLaunchPlan(+ argv = (sys.executable, "-c", f"open({str(marker)!r}, 'w').write('bad')"),+ workdir = str(tmp_path),+ env = {+ key: value+ for key, value in os.environ.items()+ if key.upper() in {"SYSTEMROOT", "WINDIR", "PATH", "TEMP", "TMP", "PATHEXT"}+ },+ execution_kind = "python",+ timeout_seconds = 20,+ )+ request = mxc_policy.build_launch_request(plan)+ request["config"]["process"]["timeout"] += 1+ with pytest.raises(mxc_adapter.MxcAdapterError) as raised:+ mxc_adapter.spawn(+ request,+ popen_kwargs = {+ "stdout": subprocess.PIPE,+ "stderr": subprocess.STDOUT,+ "creationflags": subprocess.CREATE_NO_WINDOW,+ },+ )+ assert "changed before dispatch" in str(raised.value)+ assert raised.value.may_have_started is False+ assert not marker.exists()+++def test_native_wxc_process_loss_after_dispatch_is_uncertain(tmp_path):+ _require_native_mxc()+ marker = tmp_path / "direct-dispatch.txt"+ plan = os_sandbox.ToolLaunchPlan(+ argv = (+ sys.executable,+ "-c",+ f"import time; open({str(marker)!r}, 'w').write('ran'); time.sleep(120)",+ ),+ workdir = str(tmp_path),+ env = {+ key: value+ for key, value in os.environ.items()+ if key.upper() in {"SYSTEMROOT", "WINDIR", "PATH", "TEMP", "TMP", "PATHEXT"}+ },+ execution_kind = "python",+ timeout_seconds = 20,+ )+ proc = mxc_adapter.spawn(+ mxc_policy.build_launch_request(plan),+ popen_kwargs = {+ "stdout": subprocess.PIPE,+ "stderr": subprocess.STDOUT,+ "creationflags": subprocess.CREATE_NO_WINDOW,+ },+ )+ try:+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline and not marker.exists():+ time.sleep(0.05)+ assert marker.is_file()+ mxc_adapter.abort(proc)+ proc.wait(timeout = 10)+ with pytest.raises(mxc_adapter.MxcAdapterError, match = "completion state") as raised:+ mxc_adapter.completion_result(proc)+ assert raised.value.may_have_started+ finally:+ mxc_adapter.release_runtime(proc)+++def test_native_cmd_timeout_reclaims_terminal_child_and_grandchild(monkeypatch):+ _require_native_mxc()+ monkeypatch.setattr(tools, "_windows_bash", lambda: None)+ session = "__LOCALID_native_mxc_cmd_tree"+ workdir = Path(tools._get_workdir(session))+ script = workdir / "terminal-tree.py"+ script.write_text(+ "import os, pathlib, subprocess, sys, time\n"+ "grand = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)'])\n"+ "pathlib.Path('terminal-pids.txt').write_text(f'{os.getpid()} {grand.pid}')\n"+ "time.sleep(120)\n",+ encoding = "utf-8",+ )+ command = "python terminal-tree.py"+ result = tools._bash_exec(+ command,+ None,+ 2,+ session,+ tool_execution_mode = "required",+ )+ assert "Execution timed out after 2 seconds" in result+ pids = [int(value) for value in (workdir / "terminal-pids.txt").read_text().split()]+ _wait_for_dead(pids)+++def test_native_mxc_session_packages_import_inside_the_container():+ """Packages an earlier call installed into the session must stay importable once the call is isolated."""+ _require_native_mxc()+ session = "__LOCALID_native_mxc_packages"+ packages = Path(tools._get_workdir(session)) / os_sandbox.SESSION_PACKAGES_RELPATH+ subprocess.run(+ [+ sys.executable,+ "-m",+ "pip",+ "install",+ "-q",+ "--no-deps",+ "--target",+ str(packages),+ "six==1.16.0",+ ],+ check = True,+ )+ imported = tools._python_exec(+ "import six; print('SIX', six.__version__, six.__file__)",+ None,+ 60,+ session,+ tool_execution_mode = "required",+ )+ assert "SIX 1.16.0" in imported, imported+ assert os_sandbox.SESSION_PACKAGES_RELPATH in imported, importeddiff --git a/studio/backend/tests/test_mxc_policy_identity.py b/studio/backend/tests/test_mxc_policy_identity.pynew file mode 100644index 00000000000..262c73710b9--- /dev/null+++ b/studio/backend/tests/test_mxc_policy_identity.py@@ -0,0 +1,55 @@+# SPDX-License-Identifier: AGPL-3.0-only++from __future__ import annotations++import hashlib+import json++from core.inference import mxc_policy+++def _config() -> dict:+ return {+ "version": "0.8.0-alpha",+ "containerId": "unsloth-会話",+ "containment": "processcontainer",+ "filesystem": {+ "readwritePaths": [r"D:\会話 work"],+ "readonlyPaths": [r"C:\Python"],+ "deniedPaths": [],+ },+ "fallback": {"allowDaclMutation": False},+ "ui": {"disable": False, "clipboard": "none", "injection": False},+ }+++def test_policy_hash_is_the_exact_canonical_config_hash():+ config = _config()+ encoded = mxc_policy.canonical_config_bytes(config)+ assert encoded == json.dumps(+ config,+ ensure_ascii = False,+ sort_keys = True,+ separators = (",", ":"),+ ).encode("utf-8")+ assert mxc_policy.compute_policy_hash(config) == "sha256:" + hashlib.sha256(encoded).hexdigest()+++def test_canonical_hash_ignores_json_object_insertion_order():+ config = _config()+ reordered = dict(reversed(list(config.items())))+ assert mxc_policy.compute_policy_hash(reordered) == mxc_policy.compute_policy_hash(config)+++def test_one_byte_policy_mutation_changes_the_identity():+ config = _config()+ original = mxc_policy.compute_policy_hash(config)+ config["fallback"]["allowDaclMutation"] = True+ assert mxc_policy.compute_policy_hash(config) != original+++def test_ui_policy_mutation_changes_the_identity():+ config = _config()+ original = mxc_policy.compute_policy_hash(config)+ config["ui"]["disable"] = True+ assert mxc_policy.compute_policy_hash(config) != originaldiff --git a/studio/backend/tests/test_mxc_runtime_integrity.py b/studio/backend/tests/test_mxc_runtime_integrity.pynew file mode 100644index 00000000000..8dc7831dbd4--- /dev/null+++ b/studio/backend/tests/test_mxc_runtime_integrity.py@@ -0,0 +1,224 @@+# SPDX-License-Identifier: AGPL-3.0-only++from __future__ import annotations++import hashlib+import json+from pathlib import Path+import subprocess++import pytest++from core.inference import mxc_runtime++_WXC = b"official-wxc-test-payload"+++_REAL_ARCHITECTURE = mxc_runtime._expected_architecture+++def runtime(tmp_path, monkeypatch):+ # The runtime is x86-64 only; an arm64 test host (Apple Silicon CI) is not the host under test.+ monkeypatch.setattr(mxc_runtime, "_expected_architecture", lambda: "x86_64")+ root = tmp_path / "managed" / "windows-x86_64"+ root.mkdir(parents = True)+ (root / "wxc-exec.exe").write_bytes(_WXC)+ monkeypatch.setattr(mxc_runtime.sys, "platform", "win32")+ monkeypatch.setattr(mxc_runtime, "WXC_EXEC_SIZE", len(_WXC))+ monkeypatch.setattr(mxc_runtime, "WXC_EXEC_SHA256", hashlib.sha256(_WXC).hexdigest())+ return root+++def test_only_the_fixed_managed_wxc_is_selected(runtime, monkeypatch, tmp_path):+ path_runner = tmp_path / "bin" / "wxc-exec.exe"+ path_runner.parent.mkdir()+ path_runner.write_bytes(b"untrusted")+ monkeypatch.setenv("PATH", str(path_runner.parent))+ info = mxc_runtime.selected_runtime(package_root = runtime)+ assert info.path == (runtime / "wxc-exec.exe").resolve()+ assert info.sha256 == hashlib.sha256(_WXC).hexdigest()+++def test_cargo_target_wxc_is_ignored(runtime, monkeypatch, tmp_path):+ cargo_runner = tmp_path / "target" / "release" / "wxc-exec.exe"+ cargo_runner.parent.mkdir(parents = True)+ cargo_runner.write_bytes(_WXC)+ monkeypatch.chdir(cargo_runner.parents[2])+ assert (+ mxc_runtime.selected_runtime(package_root = runtime).path+ == (runtime / "wxc-exec.exe").resolve()+ )++[email protected]("mutation", [b"modified", b""])+def test_modified_or_truncated_wxc_is_rejected(runtime, mutation):+ (runtime / "wxc-exec.exe").write_bytes(mutation)+ with pytest.raises(mxc_runtime.MxcRuntimeUnavailable, match = "size|digest"):+ mxc_runtime.selected_runtime(package_root = runtime)+++def test_missing_wxc_is_rejected(runtime):+ (runtime / "wxc-exec.exe").unlink()+ with pytest.raises(mxc_runtime.MxcRuntimeUnavailable, match = "missing"):+ mxc_runtime.selected_runtime(package_root = runtime)+++def test_wrong_architecture_is_rejected(runtime, monkeypatch):+ monkeypatch.setattr(mxc_runtime, "_expected_architecture", _REAL_ARCHITECTURE)+ monkeypatch.setattr(mxc_runtime.platform, "machine", lambda: "ARM64")+ with pytest.raises(mxc_runtime.MxcRuntimeUnavailable, match = "x86-64"):+ mxc_runtime.selected_runtime(package_root = runtime)+++def test_runtime_lease_holds_and_revalidates_the_wxc_file(runtime, monkeypatch):+ opened = []++ class Guard:+ def close(self):+ opened.append("closed")++ monkeypatch.setattr(+ mxc_runtime,+ "_open_artifact_guard",+ lambda path: opened.append(Path(path).name) or Guard(),+ )+ lease = mxc_runtime.acquire_runtime(package_root = runtime)+ assert opened == ["wxc-exec.exe"]+ assert lease.info.path == (runtime / "wxc-exec.exe").resolve()+ lease.release()+ assert opened[-1] == "closed"+++def test_reparse_runtime_directory_is_rejected(runtime, tmp_path):+ link = tmp_path / "runtime-link"+ try:+ link.symlink_to(runtime, target_is_directory = True)+ except OSError as exc:+ pytest.skip(f"directory symlink creation unavailable: {exc}")+ with pytest.raises(mxc_runtime.MxcRuntimeUnavailable, match = "non-reparse"):+ mxc_runtime.selected_runtime(package_root = link)+++def test_release_identity_is_fixed_to_microsoft_v080():+ # The npm package ships the v0.8.0 release's x64 binaries byte for byte, without symbols.+ assert mxc_runtime.RELEASE_URL == (+ "https://registry.npmjs.org/@microsoft/mxc-sdk/-/mxc-sdk-0.8.0.tgz"+ )+ assert mxc_runtime.MXC_REVISION == "7dac1a952f0c9ad13f0a4cb089c4e0e8b3e0013a"+ assert mxc_runtime.RELEASE_ARCHIVE_SIZE == 25_881_758+ assert mxc_runtime.RELEASE_ARCHIVE_SHA256 == (+ "06bb2399d7e98ab1907acf851e12a4e44748dd467b79d3e53c2f2fbf569da14e"+ )+ assert mxc_runtime.RELEASE_MEMBER == "package/bin/x64/wxc-exec.exe"+ assert mxc_runtime.RELEASE_HOST_PREP_MEMBER == "package/bin/x64/wxc-host-prep.exe"+ assert mxc_runtime.WXC_EXEC_SIZE == 9_478_968+ assert mxc_runtime.WXC_EXEC_SHA256 == (+ "6049c64723af1173c3739dc6cd6b2f33f6c021bb2832c4216233cba7f71aee9a"+ )+++def test_corrupt_managed_wxc_is_never_executed(runtime, monkeypatch):+ from core.inference import mxc_adapter, mxc_policy++ (runtime / "wxc-exec.exe").write_bytes(b"corrupt")+ acquire_runtime = mxc_runtime.acquire_runtime+ monkeypatch.setattr(+ mxc_runtime,+ "acquire_runtime",+ lambda: acquire_runtime(package_root = runtime),+ )+ monkeypatch.setattr(+ mxc_adapter.subprocess,+ "Popen",+ lambda *_args, **_kwargs: pytest.fail("corrupt WXC was executed"),+ )+ config = {+ "fallback": {"allowDaclMutation": False},+ "ui": {"disable": False},+ }+ request = {+ "config": config,+ "configBytes": mxc_policy.canonical_config_bytes(config),+ "policyHash": mxc_policy.compute_policy_hash(config),+ }+ with pytest.raises(mxc_adapter.MxcAdapterError, match = "size|digest"):+ mxc_adapter.spawn(request)+++_HOST_PREP = b"official-host-prep-test-payload"+++def host_prep(runtime, monkeypatch):+ (runtime / "wxc-host-prep.exe").write_bytes(_HOST_PREP)+ monkeypatch.setattr(mxc_runtime, "WXC_HOST_PREP_SIZE", len(_HOST_PREP))+ monkeypatch.setattr(mxc_runtime, "WXC_HOST_PREP_SHA256", hashlib.sha256(_HOST_PREP).hexdigest())+ return runtime+++def test_host_prep_is_pinned_like_wxc(host_prep):+ with mxc_runtime.acquire_host_prep(package_root = host_prep) as lease:+ assert lease.info.path == (host_prep / "wxc-host-prep.exe").resolve()+ (host_prep / "wxc-host-prep.exe").write_bytes(b"y" * len(_HOST_PREP))+ with pytest.raises(mxc_runtime.MxcRuntimeUnavailable, match = "wxc-host-prep.exe digest"):+ mxc_runtime.acquire_host_prep(package_root = host_prep)+++def test_missing_host_prep_never_affects_the_wxc_runtime(runtime):+ mxc_runtime.selected_runtime(package_root = runtime)+ with pytest.raises(mxc_runtime.MxcRuntimeUnavailable, match = "missing"):+ mxc_runtime.selected_host_prep(package_root = runtime)+++_BOTH_WARNINGS = [+ "AppContainer + DACL tier selected: ... Run `wxc-host-prep prepare-system-drive` (elevated)",+ "AppContainer + DACL tier selected: ... Run `wxc-host-prep prepare-null-device` (elevated)",+]+++ ("stdout", "returncode", "expected"),+ [+ (+ json.dumps({"tier": "appcontainer-dacl", "warnings": _BOTH_WARNINGS}),+ 0,+ ("prepare-system-drive", "prepare-null-device"),+ ),+ (+ json.dumps({"tier": "appcontainer-dacl", "warnings": _BOTH_WARNINGS[1:]}),+ 0,+ ("prepare-null-device",),+ ),+ (json.dumps({"tier": "base-container", "warnings": []}), 0, ()),+ ("not json", 0, None),+ (json.dumps(["warnings"]), 0, None),+ (json.dumps({"warnings": _BOTH_WARNINGS}), 1, None),+ ],+ ids = ["both", "null_device", "prepared", "garbage", "not_object", "failed"],+)+def test_host_prep_probe_reads_wxc_probe_warnings(+ runtime, monkeypatch, stdout, returncode, expected+):+ seen: dict = {}++ def run(argv, **kwargs):+ seen.update(argv = argv, env = kwargs.get("env"), timeout = kwargs.get("timeout"))+ return subprocess.CompletedProcess(argv, returncode, stdout = stdout, stderr = "")++ monkeypatch.setattr(mxc_runtime.subprocess, "run", run)+ env = {"SYSTEMROOT": "C:\\Windows"}+ assert mxc_runtime.probe_host_prep_steps(package_root = runtime, env = env) == expected+ assert seen["argv"] == [str((runtime / "wxc-exec.exe").resolve()), "--probe"]+ assert seen["env"]["SYSTEMROOT"] == "C:\\Windows"+ # --probe reaps orphaned ACEs, so it must read the journal every launch writes.+ assert seen["env"]["MXC_DACL_STATE_DIR"] == str(mxc_runtime.dacl_state_path())+ assert seen["timeout"] == mxc_runtime.HOST_PREP_PROBE_SECONDS+++def test_host_prep_probe_timeout_is_not_a_verdict(runtime, monkeypatch):+ def run(argv, **_kwargs):+ raise subprocess.TimeoutExpired(argv, 1)++ monkeypatch.setattr(mxc_runtime.subprocess, "run", run)+ assert mxc_runtime.probe_host_prep_steps(package_root = runtime) is Nonediff --git a/studio/backend/tests/test_mxc_windows_backend.py b/studio/backend/tests/test_mxc_windows_backend.pynew file mode 100644index 00000000000..68b5145c1d5--- /dev/null+++ b/studio/backend/tests/test_mxc_windows_backend.py@@ -0,0 +1,881 @@+# SPDX-License-Identifier: AGPL-3.0-only++from __future__ import annotations++import importlib+import os+from pathlib import Path+import subprocess+import sys+import threading+import time+from concurrent.futures import ThreadPoolExecutor+from dataclasses import replace++import pytest++from core.inference import mxc_runtime, os_sandbox, tools++[email protected](autouse = True)+def _dacl_journal_outside_grants(monkeypatch, tmp_path):+ # A venv at a checkout root puts tmp_path under the sys.prefix grant, which the journal guard refuses.+ outside = Path(os.path.abspath(os.sep)) / "unsloth-test-dacl-journal-never-created"+ monkeypatch.setattr(mxc_runtime, "dacl_state_path", lambda: outside)+ monkeypatch.setattr(mxc_runtime, "dacl_state_dir", lambda: tmp_path)+++def _plan(tmp_path, mode = "auto"):+ return os_sandbox.ToolLaunchPlan(+ argv = (str(Path(__file__).resolve()), "arg"),+ workdir = str(tmp_path),+ env = {"PATH": "trusted"},+ requested_mode = mode,+ timeout_seconds = 10,+ execution_kind = "python",+ )+++def _unavailable():+ return os_sandbox.SandboxCapability(+ backend = "mxc-processcontainer",+ available = False,+ reason = "controlled unavailable",+ environment = "win32",+ remediation = "install the pinned runner",+ )+++def test_auto_unavailable_preserves_original_launch(monkeypatch, tmp_path):+ plan = _plan(tmp_path)+ monkeypatch.setattr(os_sandbox, "capability_snapshot", lambda **_kwargs: _unavailable())+ prepared = os_sandbox.prepare_tool_launch(plan)+ assert prepared.argv == plan.argv+ assert prepared.workdir == plan.workdir+ assert prepared.env is plan.env+ assert prepared.preexec_fn is plan.preexec_fn+ assert prepared.backend == "software-safeguards"+ assert prepared.execution_record.effective_mode == "software_safeguards"+++def test_required_unavailable_refuses_with_remediation(monkeypatch, tmp_path):+ plan = _plan(tmp_path, "required")+ monkeypatch.setattr(os_sandbox, "capability_snapshot", lambda **_kwargs: _unavailable())+ with pytest.raises(+ os_sandbox.SandboxUnavailableError, match = "controlled unavailable"+ ) as raised:+ os_sandbox.prepare_tool_launch(plan)+ assert "pinned runner" in raised.value.remediation+++def test_windows_terminal_uses_its_own_capability_identity(monkeypatch, tmp_path):+ from core.inference import sandbox_windows_mxc++ monkeypatch.setattr(sandbox_windows_mxc.sys, "platform", "win32")+ observed = []+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_probe,+ "probe",+ lambda executable, **kwargs: (+ observed.append((executable, kwargs["execution_kind"])) or (True, "ok")+ ),+ )+ monkeypatch.setattr(sandbox_windows_mxc.mxc_runtime, "installation_identity", lambda: "runner")+ capability = sandbox_windows_mxc.capability_snapshot(+ execution_kind = "terminal",+ selected_executable = str(tmp_path / "cmd.exe"),+ )+ assert capability.available+ assert observed == [(str(tmp_path / "cmd.exe"), "terminal")]+++ ("steps", "advised"),+ [(("prepare-system-drive", "prepare-null-device"), True), ((), False), (None, False)],+ ids = ["missing", "prepared", "unknown"],+)+def test_unavailable_capability_names_the_host_prep_command(monkeypatch, tmp_path, steps, advised):+ from core.inference import mxc_probe, sandbox_windows_mxc++ monkeypatch.setattr(sandbox_windows_mxc.sys, "platform", "win32")+ monkeypatch.setattr(mxc_probe, "_host_prep_cache", {})+ monkeypatch.setattr(sandbox_windows_mxc.mxc_probe, "probe", lambda *_a, **_k: (False, "no"))+ monkeypatch.setattr(sandbox_windows_mxc.mxc_runtime, "installation_identity", lambda: "runner")+ monkeypatch.setattr(mxc_probe.mxc_runtime, "probe_host_prep_steps", lambda **_kwargs: steps)+ monkeypatch.setenv("UNSLOTH_MXC_ALLOW_DACL_FALLBACK", "1")+ capability = sandbox_windows_mxc.capability_snapshot(+ execution_kind = "python", selected_executable = str(tmp_path / "python.exe")+ )+ assert ("--prepare-host" in capability.remediation) is advised+ assert ("undone by every reboot" in capability.remediation) is advised+ assert "install_mxc_prebuilt.py" in capability.remediation or not advised+++def test_host_prep_is_not_advised_without_the_dacl_opt_in(monkeypatch, tmp_path):+ # A bare --probe allows the fallback, so it reports host-prep steps Studio never needs.+ from core.inference import mxc_probe, sandbox_windows_mxc++ monkeypatch.setattr(sandbox_windows_mxc.sys, "platform", "win32")+ monkeypatch.setattr(mxc_probe, "_host_prep_cache", {})+ monkeypatch.delenv("UNSLOTH_MXC_ALLOW_DACL_FALLBACK", raising = False)+ monkeypatch.setattr(sandbox_windows_mxc.mxc_probe, "probe", lambda *_a, **_k: (False, "no"))+ monkeypatch.setattr(sandbox_windows_mxc.mxc_runtime, "installation_identity", lambda: "runner")+ monkeypatch.setattr(+ mxc_probe.mxc_runtime,+ "probe_host_prep_steps",+ lambda **_kwargs: pytest.fail("host preparation was probed with the DACL tier off"),+ )+ capability = sandbox_windows_mxc.capability_snapshot(+ execution_kind = "python", selected_executable = str(tmp_path / "python.exe")+ )+ assert "--prepare-host" not in capability.remediation+ assert "UNSLOTH_MXC_ALLOW_DACL_FALLBACK=1" in capability.remediation+++def test_available_capability_never_runs_the_host_prep_probe(monkeypatch, tmp_path):+ from core.inference import mxc_probe, sandbox_windows_mxc++ monkeypatch.setattr(sandbox_windows_mxc.sys, "platform", "win32")+ monkeypatch.setattr(sandbox_windows_mxc.mxc_probe, "probe", lambda *_a, **_k: (True, "ok"))+ monkeypatch.setattr(sandbox_windows_mxc.mxc_runtime, "installation_identity", lambda: "runner")+ monkeypatch.setattr(+ mxc_probe.mxc_runtime,+ "probe_host_prep_steps",+ lambda **_kwargs: pytest.fail("a qualified host was probed for host preparation"),+ )+ capability = sandbox_windows_mxc.capability_snapshot(+ execution_kind = "python", selected_executable = str(tmp_path / "python.exe")+ )+ assert "--prepare-host" not in capability.remediation++[email protected]("name", ["powershell.exe", "pwsh.exe"])+def test_terminal_probe_supports_powershell_argv(name, tmp_path):+ from core.inference import mxc_probe++ argv = mxc_probe._terminal_probe(+ str(tmp_path / name),+ tmp_path,+ tmp_path / "other's secret.txt",+ tmp_path / "outside write.txt",+ )+ assert argv[:5] == (+ str(tmp_path / name),+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ )+ assert "UNSLOTH_MXC_TERMINAL_PROBE_OK" in argv[-1]+ assert "other''s secret.txt" in argv[-1]+++def test_terminal_probe_supports_native_bash_argv(tmp_path):+ from core.inference import mxc_probe++ argv = mxc_probe._terminal_probe(+ str(tmp_path / "bash.exe"),+ tmp_path,+ tmp_path / "secret.txt",+ tmp_path / "outside.txt",+ )+ assert argv[:2] == (str(tmp_path / "bash.exe"), "-c")+ assert "UNSLOTH_MXC_TERMINAL_PROBE_OK" in argv[-1]+++def test_unexpected_planner_failure_never_becomes_auto_host_fallback(monkeypatch, tmp_path):+ monkeypatch.setattr(+ os_sandbox, "prepare_tool_launch", lambda _plan: (_ for _ in ()).throw(RuntimeError("boom"))+ )+ with pytest.raises(os_sandbox.SandboxBuildError, match = "without host fallback"):+ tools._prepare_tool_launch(_plan(tmp_path))+++def test_selected_python_spelling_is_preserved_in_trusted_policy(monkeypatch, tmp_path):+ from core.inference import mxc_policy++ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ selected = str(tmp_path / "venv" / "Scripts" / "python.exe")+ Path(selected).parent.mkdir(parents = True)+ Path(selected).touch()+ plan = os_sandbox.ToolLaunchPlan(+ argv = (selected, "-u", str(tmp_path / "tool.py")),+ workdir = str(tmp_path),+ env = {"PATH": str(Path(selected).parent)},+ execution_kind = "python",+ )+ request = mxc_policy.build_launch_request(plan)+ assert request["config"]["containerId"].startswith("unsloth-")+ assert request["policyHash"].startswith("sha256:")+ assert request["config"]["filesystem"]["readwritePaths"] == [str(tmp_path)]+ assert request["config"]["fallback"] == {"allowDaclMutation": False}+ assert request["config"]["ui"] == {"disable": False, "clipboard": "none", "injection": False}+ assert request["config"]["processContainer"]["ui"]["isolation"] == "container"++[email protected](sys.platform != "win32", reason = "requires Windows MXC launch routing")+def test_dacl_refusal_after_successful_probe_is_never_replayed(monkeypatch, tmp_path):+ from core.inference import sandbox_windows_mxc++ plan = _plan(tmp_path, "required")+ identity = "qualified-runner"+ capability = os_sandbox.SandboxCapability(+ backend = "mxc-processcontainer",+ available = True,+ reason = "probe passed before the host changed",+ environment = "win32",+ profile_id = mxc_runtime.PROFILE_ID,+ environment_fingerprint = sandbox_windows_mxc._capability_fingerprint(+ identity, "python", plan.argv[0]+ ),+ )+ monkeypatch.setattr(os_sandbox, "capability_snapshot", lambda **_kwargs: capability)+ monkeypatch.setattr(sandbox_windows_mxc.mxc_runtime, "installation_identity", lambda: identity)+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_adapter,+ "spawn",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ RuntimeError("fallback.allowDaclMutation=false refused Tier 3")+ ),+ )+ host_calls = []+ monkeypatch.setattr(subprocess, "Popen", lambda *_args, **_kwargs: host_calls.append(True))++ prepared = os_sandbox.prepare_tool_launch(plan)+ assert "ui_isolation" in prepared.execution_record.retained_safeguards+ with pytest.raises(os_sandbox.SandboxBuildError, match = "without host replay"):+ os_sandbox.spawn_prepared_launch(prepared)+ assert host_calls == []+++def test_capability_probe_is_single_flight_and_keyed_by_runtime(monkeypatch, tmp_path):+ from core.inference import mxc_probe++ mxc_probe.invalidate_cache()+ identity = ["generation-a"]+ calls = []+ monkeypatch.setattr(mxc_probe.mxc_runtime, "installation_identity", lambda: identity[0])++ def live_probe(+ executable,+ execution_kind,+ cancel_event = None,+ ):+ calls.append((identity[0], executable, execution_kind))+ time.sleep(0.05)+ return True, "qualified"++ monkeypatch.setattr(mxc_probe, "_probe", live_probe)+ executable = str(tmp_path / "python.exe")+ with ThreadPoolExecutor(max_workers = 4) as executor:+ results = list(+ executor.map(+ lambda _index: mxc_probe.probe(executable, execution_kind = "python"), range(4)+ )+ )+ assert results == [(True, "qualified")] * 4+ assert len(calls) == 1++ identity[0] = "generation-b"+ assert mxc_probe.probe(executable, execution_kind = "python") == (True, "qualified")+ assert len(calls) == 2+++def test_cancelled_probe_waiter_does_not_block_behind_the_live_probe(monkeypatch, tmp_path):+ from core.inference import mxc_probe++ mxc_probe.invalidate_cache()+ started = threading.Event()+ release = threading.Event()+ calls = []+ monkeypatch.setattr(mxc_probe.mxc_runtime, "installation_identity", lambda: "generation")++ def live_probe(*_args, **_kwargs):+ calls.append(True)+ started.set()+ assert release.wait(5)+ return True, "qualified"++ monkeypatch.setattr(mxc_probe, "_probe", live_probe)+ executable = str(tmp_path / "python.exe")+ cancel = threading.Event()+ with ThreadPoolExecutor(max_workers = 2) as executor:+ leader = executor.submit(mxc_probe.probe, executable)+ assert started.wait(2)+ waiter = executor.submit(mxc_probe.probe, executable, cancel_event = cancel)+ cancel.set()+ assert waiter.result(timeout = 1) == (False, "MXC capability probe was cancelled")+ assert not release.is_set()+ mxc_probe.invalidate_cache()+ release.set()+ assert leader.result(timeout = 2) == (True, "qualified")+ assert calls == [True]++[email protected](sys.platform != "win32", reason = "requires Windows MXC launch routing")+def test_runner_replacement_after_probe_is_refused_before_spawn(monkeypatch, tmp_path):+ from core.inference import sandbox_windows_mxc++ plan = _plan(tmp_path, "required")+ qualified_identity = "qualified-runner"+ fingerprint = sandbox_windows_mxc._capability_fingerprint(+ qualified_identity, "python", plan.argv[0]+ )+ capability = os_sandbox.SandboxCapability(+ backend = "mxc-processcontainer",+ available = True,+ reason = "qualified",+ environment = "win32",+ profile_id = mxc_runtime.PROFILE_ID,+ environment_fingerprint = fingerprint,+ )+ monkeypatch.setattr(os_sandbox, "capability_snapshot", lambda **_kwargs: capability)+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_runtime,+ "installation_identity",+ lambda: "replacement-runner",+ )+ spawned = []+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_adapter,+ "spawn",+ lambda *_args, **_kwargs: spawned.append(True),+ )+ prepared = os_sandbox.prepare_tool_launch(plan)+ with pytest.raises(os_sandbox.SandboxBuildError, match = "changed after capability"):+ os_sandbox.spawn_prepared_launch(prepared)+ assert spawned == []+++def test_terminal_policy_preserves_constructed_shell_argv(monkeypatch, tmp_path):+ from core.inference import mxc_policy++ shell = tmp_path / "Program Files" / "PowerShell" / "7" / "pwsh.exe"+ shell.parent.mkdir(parents = True)+ shell.touch()+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ plan = os_sandbox.ToolLaunchPlan(+ argv = (str(shell), "-NoProfile", "-Command", '"quoted"; $env:VALUE | Out-File "x y.txt"'),+ workdir = str(tmp_path),+ env = {"PATH": str(shell.parent)},+ execution_kind = "terminal",+ )+ request = mxc_policy.build_launch_request(plan)+ assert request["config"]["process"]["commandLine"] == subprocess.list2cmdline(list(plan.argv))+ assert request["config"]["fallback"]["allowDaclMutation"] is False+++def test_wsl_bash_is_refused_before_execution(monkeypatch, tmp_path):+ from core.inference import mxc_policy++ shell = tmp_path / "Windows" / "System32" / "bash.exe"+ shell.parent.mkdir(parents = True)+ shell.touch()+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ plan = os_sandbox.ToolLaunchPlan(+ argv = (str(shell), "-c", "echo hi"),+ workdir = str(tmp_path),+ env = {},+ execution_kind = "terminal",+ )+ with pytest.raises(mxc_policy.MxcPolicyError, match = "WSL-backed"):+ mxc_policy.build_launch_request(plan)++[email protected](sys.platform != "win32", reason = "requires Windows junction semantics")+def test_workdir_junction_escape_is_refused(monkeypatch, tmp_path):+ from core.inference import mxc_policy++ if not hasattr(os.path, "isjunction"):+ pytest.skip("junction detection requires Python 3.12 on Windows")+ workdir = tmp_path / "会話"+ outside = tmp_path / "other-chat"+ workdir.mkdir()+ outside.mkdir()+ (outside / "secret.txt").write_text("secret", encoding = "utf-8")+ junction = workdir / "junction_to_secret"+ created = subprocess.run(+ ["cmd", "/d", "/c", "mklink", "/J", str(junction), str(outside)],+ capture_output = True,+ text = True,+ check = False,+ )+ if created.returncode != 0:+ pytest.skip(f"junction creation unavailable: {created.stderr or created.stdout}")+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ plan = os_sandbox.ToolLaunchPlan(+ argv = (sys.executable, "-c", "print('never')"),+ workdir = str(workdir),+ env = {},+ execution_kind = "python",+ )+ with pytest.raises(mxc_policy.MxcPolicyError, match = "reparse point"):+ mxc_policy.build_launch_request(plan)+++def test_workdir_hard_link_to_outside_object_is_refused(monkeypatch, tmp_path):+ from core.inference import mxc_policy++ workdir = tmp_path / "workdir"+ outside = tmp_path / "other-chat"+ workdir.mkdir()+ outside.mkdir()+ secret = outside / "secret.txt"+ secret.write_text("secret", encoding = "utf-8")+ try:+ os.link(secret, workdir / "linked-secret.txt")+ except OSError as exc:+ pytest.skip(f"hard-link creation unavailable: {exc}")+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ plan = os_sandbox.ToolLaunchPlan(+ argv = (sys.executable, "-c", "print('never')"),+ workdir = str(workdir),+ env = {},+ execution_kind = "python",+ )+ with pytest.raises(mxc_policy.MxcPolicyError, match = "hard-linked"):+ mxc_policy.build_launch_request(plan)+++def _policy_plan(workdir, mode = "auto"):+ # A plain file: a venv's python is a symlink on POSIX, which the policy refuses.+ runtime = Path(workdir).parent / "runtime" / "python.exe"+ runtime.parent.mkdir(exist_ok = True)+ runtime.touch()+ return os_sandbox.ToolLaunchPlan(+ argv = (str(runtime), "-c", "print('ok')"),+ workdir = str(workdir),+ env = {},+ requested_mode = mode,+ execution_kind = "python",+ )+++def test_workdir_hard_links_within_it_are_allowed(monkeypatch, tmp_path):+ # uv and pip hard-link from their caches; refusing every nlink > 1 bricked the chat.+ from core.inference import mxc_policy++ workdir = tmp_path / "workdir"+ workdir.mkdir()+ (workdir / "a.txt").write_text("same", encoding = "utf-8")+ try:+ os.link(workdir / "a.txt", workdir / "b.txt")+ except OSError as exc:+ pytest.skip(f"hard-link creation unavailable: {exc}")+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ request = mxc_policy.build_launch_request(_policy_plan(workdir))+ assert request["launchLimitations"] == ()++[email protected]("mode", ["auto", "required"])+def test_oversized_workdir_degrades_auto_and_refuses_required(monkeypatch, tmp_path, mode):+ from core.inference import mxc_policy++ for index in range(8):+ (tmp_path / f"f{index}.txt").write_text("x", encoding = "utf-8")+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_ENTRIES", 3)+ if mode == "required":+ with pytest.raises(mxc_policy.MxcPolicyError, match = "too large"):+ mxc_policy.build_launch_request(_policy_plan(tmp_path, mode))+ return+ request = mxc_policy.build_launch_request(_policy_plan(tmp_path, mode))+ assert request["launchLimitations"] == (os_sandbox.WORKDIR_SCAN_INCOMPLETE,)+ mxc_policy.verify_launch_identities(request)+++def test_incomplete_workdir_scan_is_named_on_the_execution_record(monkeypatch, tmp_path):+ from core.inference import sandbox_windows_mxc++ plan = _plan(tmp_path, "auto")+ capability = os_sandbox.SandboxCapability(+ backend = "mxc-processcontainer",+ available = True,+ reason = "qualified",+ environment = "win32",+ profile_id = mxc_runtime.PROFILE_ID,+ limitations = ("mxc_preview_not_a_security_boundary",),+ )+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_policy,+ "build_launch_request",+ lambda _plan: {+ "policyHash": "sha256:controlled",+ "launchLimitations": (os_sandbox.WORKDIR_SCAN_INCOMPLETE,),+ },+ )+ prepared = sandbox_windows_mxc.prepare(plan, capability)+ assert prepared.launch_limitations == (os_sandbox.WORKDIR_SCAN_INCOMPLETE,)+ assert os_sandbox.WORKDIR_SCAN_INCOMPLETE in prepared.execution_record.limitations+++def test_registered_model_folders_are_granted_read_only(monkeypatch, tmp_path):+ from core.inference import mxc_policy++ workdir = tmp_path / "workdir"+ models = tmp_path / "models"+ inside = workdir / "local-models"+ for path in (workdir, models, inside):+ path.mkdir()+ missing = tmp_path / "gone"+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ monkeypatch.setattr(+ os_sandbox, "model_library_roots", lambda: (str(models), str(missing), str(inside))+ )+ # Only the runtime's own dir: here sys.prefix may contain tmp_path and swallow the grant.+ monkeypatch.setattr(+ mxc_policy,+ "_runtime_read_roots",+ lambda executable, extra = (): [os.path.dirname(executable)],+ )+ request = mxc_policy.build_launch_request(_policy_plan(workdir))+ filesystem = request["config"]["filesystem"]+ assert str(models) in filesystem["readonlyPaths"]+ assert str(missing) not in filesystem["readonlyPaths"]+ assert str(inside) not in filesystem["readonlyPaths"]+ assert filesystem["readwritePaths"] == [str(workdir)]++[email protected](sys.platform != "win32", reason = "requires Windows 8.3 short names")+def test_short_name_workdir_is_not_mistaken_for_a_reparse_point(monkeypatch, tmp_path):+ import ctypes+ from core.inference import mxc_policy++ workdir = tmp_path / "long directory name for 8dot3"+ workdir.mkdir()+ buffer = ctypes.create_unicode_buffer(1024)+ if not ctypes.windll.kernel32.GetShortPathNameW(str(workdir), buffer, 1024):+ pytest.skip("GetShortPathNameW failed")+ short = buffer.value+ if os.path.normcase(short) == os.path.normcase(str(workdir)):+ pytest.skip("8.3 name generation is disabled on this volume")+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ canonical = mxc_policy._safe_canonical_path(short, directory = True)+ assert os.path.normcase(canonical) == os.path.normcase(os.path.realpath(workdir))+++ "path",+ [+ r"\\server\share\workdir",+ r"\\?\C:\workdir",+ r"\\.\C:\workdir",+ r"C:\workdir\file.txt:secret",+ "C:\\workdir\\e\u0301",+ ],+)[email protected](sys.platform != "win32", reason = "requires Windows path semantics")+def test_unsupported_windows_path_namespaces_are_refused(monkeypatch, path):+ from core.inference import mxc_policy+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ with pytest.raises(mxc_policy.MxcPolicyError, match = "not supported"):+ mxc_policy._safe_canonical_path(path, directory = True)+++def test_direct_adapter_sends_the_exact_canonical_config(monkeypatch, tmp_path):+ import base64+ import json+ from types import SimpleNamespace++ from core.inference import mxc_adapter, mxc_policy++ config = {+ "version": mxc_runtime.MXC_SCHEMA_VERSION,+ "fallback": {"allowDaclMutation": False},+ "ui": {"disable": False},+ }+ request = {+ "config": config,+ "configBytes": mxc_policy.canonical_config_bytes(config),+ "policyHash": mxc_policy.compute_policy_hash(config),+ }+ lease = SimpleNamespace(+ info = SimpleNamespace(path = tmp_path / "wxc-exec.exe", sha256 = "digest"),+ release = lambda: None,+ )+ monkeypatch.setattr(mxc_adapter.mxc_runtime, "acquire_runtime", lambda: lease)+ monkeypatch.setattr(mxc_adapter.mxc_policy, "verify_launch_identities", lambda _request: None)+ observed = {}++ class Proc:+ returncode = None++ def popen(argv, **kwargs):+ observed["argv"] = argv+ observed["kwargs"] = kwargs+ return Proc()++ monkeypatch.setattr(mxc_adapter.subprocess, "Popen", popen)+ proc = mxc_adapter.spawn(request)+ sent = base64.b64decode(observed["argv"][2])+ assert observed["argv"][:2] == [str(lease.info.path), "--config-base64"]+ assert sent == request["configBytes"]+ assert json.loads(sent)["fallback"]["allowDaclMutation"] is False+ assert json.loads(sent)["ui"]["disable"] is False+ assert proc._mxc_backend_tier == "unknown"+++def test_policy_mutation_is_refused_before_wxc_dispatch(monkeypatch):+ from core.inference import mxc_adapter, mxc_policy++ config = {+ "fallback": {"allowDaclMutation": False},+ "ui": {"disable": False},+ }+ request = {+ "config": config,+ "configBytes": mxc_policy.canonical_config_bytes(config),+ "policyHash": mxc_policy.compute_policy_hash(config),+ }+ request["config"]["fallback"]["allowDaclMutation"] = True+ monkeypatch.setattr(+ mxc_adapter.subprocess,+ "Popen",+ lambda *_args, **_kwargs: pytest.fail("mutated configuration was executed"),+ )+ with pytest.raises(mxc_adapter.MxcAdapterError, match = "changed before dispatch"):+ mxc_adapter.spawn(request)+++def test_launch_failure_is_not_replayed(monkeypatch, tmp_path):+ calls = []+ prepared = os_sandbox.PreparedSandboxLaunch(+ argv = ("model-authored.exe", "argument"),+ workdir = str(tmp_path),+ env = {},+ preexec_fn = None,+ backend = "mxc-processcontainer",+ )++ def fail(_prepared, _kwargs):+ calls.append("mxc")+ raise os_sandbox.SandboxBuildError("controlled launch failure")++ prepared.spawn_callback = fail+ monkeypatch.setattr(subprocess, "Popen", lambda *_a, **_k: calls.append("host"))+ with pytest.raises(os_sandbox.SandboxBuildError, match = "controlled"):+ os_sandbox.spawn_prepared_launch(prepared)+ assert calls == ["mxc"]++[email protected](sys.platform != "win32", reason = "requires Windows MXC launch routing")+def test_auto_spawn_failure_before_dispatch_uses_software_safeguards(monkeypatch, tmp_path):+ from core.inference import mxc_adapter, sandbox_windows_mxc++ plan = _plan(tmp_path, "auto")+ identity = "qualified-wxc"+ capability = os_sandbox.SandboxCapability(+ backend = "mxc-processcontainer",+ available = True,+ reason = "qualified",+ environment = "win32",+ profile_id = mxc_runtime.PROFILE_ID,+ environment_fingerprint = sandbox_windows_mxc._capability_fingerprint(+ identity, "python", plan.argv[0]+ ),+ )+ monkeypatch.setattr(os_sandbox, "capability_snapshot", lambda **_kwargs: capability)+ monkeypatch.setattr(sandbox_windows_mxc.mxc_runtime, "installation_identity", lambda: identity)+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_adapter,+ "spawn",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ mxc_adapter.MxcAdapterError("CreateProcess failed", stage = "spawn")+ ),+ )+ calls = []+ envs = []+ packages = Path(plan.workdir) / os_sandbox.SESSION_PACKAGES_RELPATH+ packages.mkdir(parents = True, exist_ok = True)++ class Proc:+ pass++ monkeypatch.setattr(+ sandbox_windows_mxc.subprocess,+ "Popen",+ lambda argv, **kwargs: calls.append(tuple(argv))+ or envs.append(kwargs.get("env"))+ or Proc(),+ )+ prepared = os_sandbox.prepare_tool_launch(plan)+ os_sandbox.spawn_prepared_launch(prepared)+ assert calls == [plan.argv]+ # Packages an earlier isolated call installed must not vanish on this fallback.+ assert str(packages) in envs[0]["PYTHONPATH"].split(os.pathsep)+ assert prepared.backend == "software-safeguards"+ assert prepared.execution_record.effective_mode == "software_safeguards"+++def test_auto_cancellation_before_dispatch_never_replays_on_host(monkeypatch, tmp_path):+ from core.inference import sandbox_windows_mxc++ cancel = threading.Event()+ plan = replace(_plan(tmp_path, "auto"), cancel_event = cancel)+ identity = "qualified-wxc"+ capability = os_sandbox.SandboxCapability(+ backend = "mxc-processcontainer",+ available = True,+ reason = "qualified",+ environment = "win32",+ profile_id = mxc_runtime.PROFILE_ID,+ environment_fingerprint = sandbox_windows_mxc._capability_fingerprint(+ identity, "python", plan.argv[0]+ ),+ )+ monkeypatch.setattr(sandbox_windows_mxc.mxc_runtime, "installation_identity", lambda: identity)+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_policy,+ "build_launch_request",+ lambda _plan: {"policyHash": "sha256:controlled"},+ )+ monkeypatch.setattr(+ sandbox_windows_mxc.subprocess,+ "Popen",+ lambda *_args, **_kwargs: pytest.fail("cancelled command was replayed on the host"),+ )++ prepared = sandbox_windows_mxc.prepare(plan, capability)+ cancel.set()+ with pytest.raises(os_sandbox.SandboxBuildError, match = "without host replay"):+ os_sandbox.spawn_prepared_launch(prepared)+ assert prepared.execution_record.execution_status == "not_started"+ assert prepared.execution_record.completion_status == "cancelled"+ assert prepared.execution_record.cleanup_status == "complete"++[email protected](sys.platform != "win32", reason = "requires Windows MXC launch routing")+def test_auto_failure_after_possible_dispatch_never_replays_on_host(monkeypatch, tmp_path):+ from core.inference import mxc_adapter, sandbox_windows_mxc++ plan = _plan(tmp_path, "auto")+ identity = "qualified-wxc"+ capability = os_sandbox.SandboxCapability(+ backend = "mxc-processcontainer",+ available = True,+ reason = "qualified",+ environment = "win32",+ profile_id = mxc_runtime.PROFILE_ID,+ environment_fingerprint = sandbox_windows_mxc._capability_fingerprint(+ identity, "python", plan.argv[0]+ ),+ )+ monkeypatch.setattr(os_sandbox, "capability_snapshot", lambda **_kwargs: capability)+ monkeypatch.setattr(sandbox_windows_mxc.mxc_runtime, "installation_identity", lambda: identity)+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_adapter,+ "spawn",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ mxc_adapter.MxcAdapterError(+ "WXC process state was lost",+ stage = "dispatch",+ may_have_started = True,+ )+ ),+ )+ monkeypatch.setattr(+ sandbox_windows_mxc.subprocess,+ "Popen",+ lambda *_args, **_kwargs: pytest.fail("original command was replayed"),+ )+ prepared = os_sandbox.prepare_tool_launch(plan)+ with pytest.raises(os_sandbox.SandboxBuildError, match = "without host replay"):+ os_sandbox.spawn_prepared_launch(prepared)+ assert prepared.execution_record.execution_status == "unknown_start"+++def test_uncertain_completion_is_terminal_and_invalidates_probe(monkeypatch, tmp_path):+ from core.inference import sandbox_windows_mxc++ prepared = os_sandbox.PreparedSandboxLaunch(+ argv = ("python.exe",),+ workdir = str(tmp_path),+ env = {},+ preexec_fn = None,+ backend = "mxc-processcontainer",+ )+ invalidated = []+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_adapter,+ "completion_result",+ lambda _proc: (_ for _ in ()).throw(RuntimeError("missing completion state")),+ )+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_probe, "invalidate_cache", lambda: invalidated.append(True)+ )+ with pytest.raises(os_sandbox.SandboxBuildError, match = "state is uncertain"):+ sandbox_windows_mxc.verify_success(prepared, object())+ assert invalidated == [True]+++def test_public_full_remains_separate_from_tool_execution_mode():+ with pytest.raises(os_sandbox.SandboxUnavailableError, match = "not requestable"):+ tools._requested_execution_mode("full", False)+ assert tools._requested_execution_mode("auto", True) == "full"+ assert os_sandbox.PUBLIC_TOOL_EXECUTION_MODES == ("auto", "required")+++def test_native_backends_do_not_import_or_reference_mxc():+ inference = Path(os_sandbox.__file__).parent+ for name in ("sandbox_linux.py", "sandbox_macos.py"):+ source = (inference / name).read_text(encoding = "utf-8").lower()+ assert "mxc" not in source+++def test_non_windows_capability_does_not_import_windows_backend(monkeypatch):+ import sys++ sys.modules.pop("core.inference.sandbox_windows_mxc", None)+ monkeypatch.setattr(os_sandbox.sys, "platform", "unsupported-test-platform")+ capability = os_sandbox.capability_snapshot()+ assert not capability.available+ assert "core.inference.sandbox_windows_mxc" not in sys.modules+++def test_nested_runtime_grants_collapse_to_their_outermost_root(monkeypatch, tmp_path):+ # Each DACL-tier grant re-walks its tree: a nested site-packages grant cost about 9s per call.+ from core.inference import mxc_policy++ prefix = tmp_path / "venv"+ scripts = prefix / "Scripts"+ site_packages = prefix / "Lib" / "site-packages"+ base = tmp_path / "base-python"+ for path in (scripts, site_packages, base):+ path.mkdir(parents = True)+ executable = scripts / "python.exe"+ executable.touch()+ monkeypatch.setattr(mxc_policy.sys, "prefix", str(prefix))+ monkeypatch.setattr(mxc_policy.sys, "base_prefix", str(base))+ monkeypatch.setattr(mxc_policy.site, "getsitepackages", lambda: [str(site_packages)])+ monkeypatch.delenv("SystemRoot", raising = False)+ monkeypatch.delenv("WINDIR", raising = False)+ roots = mxc_policy._runtime_read_roots(str(executable))+ assert str(prefix) in roots and str(base) in roots+ assert str(scripts) not in roots and str(site_packages) not in roots+ assert len(roots) == len(set(roots))+++def test_editable_package_sources_are_granted_read_only(monkeypatch, tmp_path):+ """The .pth or PEP 660 finder stays visible in site-packages; without its source the import fails only under MXC."""+ from core.inference import mxc_policy++ workdir = tmp_path / "workdir"+ package = tmp_path / "checkout" / "mypkg"+ for path in (workdir, package):+ path.mkdir(parents = True)+ module = tmp_path / "checkout" / "single_module.py"+ module.write_text("", encoding = "utf-8")+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")+ monkeypatch.setattr(os_sandbox, "model_library_roots", lambda: ())+ monkeypatch.setattr(os_sandbox, "editable_source_roots", lambda: (str(package), str(module)))+ monkeypatch.setattr(+ mxc_policy,+ "_runtime_read_roots",+ lambda executable, extra = (): [os.path.dirname(executable)],+ )+ readonly = mxc_policy.build_launch_request(_policy_plan(workdir))["config"]["filesystem"][+ "readonlyPaths"+ ]+ assert str(package) in readonly+ assert str(module) not in readonly+ assert str(tmp_path / "checkout") not in readonlydiff --git a/studio/backend/tests/test_tool_sandbox_wiring.py b/studio/backend/tests/test_tool_sandbox_wiring.pyindex 0f9c2eab4ae..4a0d592714a 100644--- a/studio/backend/tests/test_tool_sandbox_wiring.py+++ b/studio/backend/tests/test_tool_sandbox_wiring.py@@ -29,6 +29,17 @@ from core.inference.os_sandbox import (_SESSION = "__LOCALID_sandbox_wiring"+class _PassthroughAccountConfinement:+ preexec = None+ # Stands in for a real account boundary. tools.py only takes the managed+ # path when `confines` is true, so an owner placeholder cannot pass as one.+ confines = True++ @staticmethod+ def wrap(argv):+ return argv++def test_execute_tool_keeps_every_parameter_it_had_in_the_same_order():parameters = inspect.signature(tools.execute_tool).parameterspositional = [@@ -77,6 +88,24 @@ def test_the_executors_take_the_mode_keyword_only_and_default_it(function):]+ "function,payload",+ [+ (tools._python_exec, "print('MANAGED_OK')"),+ (tools._bash_exec, "echo MANAGED_OK"),+ ],+ ids = ["python", "terminal"],+)+def test_managed_account_launch_does_not_require_a_generic_sandbox_record(+ monkeypatch, function, payload+):+ monkeypatch.setattr(tools, "_account_confinement", lambda: _PassthroughAccountConfinement())+ tools._last_tool_execution_record = None++ assert "MANAGED_OK" in function(payload, None, 60, _SESSION)+ assert tools._last_tool_execution_record is None++def test_a_caller_that_passes_nothing_new_behaves_as_auto():tools._last_tool_execution_record = Noneassert "2" in tools._python_exec("print(1 + 1)", None, 60, _SESSION)@@ -90,6 +119,9 @@ def test_disable_sandbox_still_means_full_access():assert record.requested_mode == "full"assert record.effective_mode == "full"assert record.limitations == ("security_restrictions_disabled",)+ assert record.execution_status == "completed"+ assert record.completion_status == "finished"+ assert record.cleanup_status == "complete"def test_full_access_is_not_turned_into_a_refusal_by_a_stale_required():@@ -391,16 +423,14 @@ def test_pass_fds_and_owned_files_reach_the_spawn(monkeypatch):assert holder.closed-def test_auto_still_runs_when_the_planner_itself_breaks(monkeypatch):+def test_auto_refuses_when_the_planner_itself_breaks(monkeypatch):def explode(plan):raise ImportError("no module named sandbox_linux")monkeypatch.setattr(os_sandbox, "prepare_tool_launch", explode)- tools._last_tool_execution_record = None- assert "5" in tools._python_exec("print(5)", None, 60, _SESSION)- record = tools._last_tool_execution_record- assert record.effective_mode == "software_safeguards"- assert "sandbox_planner_error" in record.limitations+ out = tools._python_exec("print('SHOULD_NOT_RUN')", None, 60, _SESSION)+ assert "SHOULD_NOT_RUN" not in out+ assert "without host fallback" in outdef test_full_access_keeps_its_own_label_even_when_the_planner_breaks(monkeypatch):@@ -445,10 +475,10 @@ def test_required_still_refuses_when_the_planner_itself_breaks(monkeypatch):"print('SHOULD_NOT_RUN')", None, 60, _SESSION, tool_execution_mode = "required")assert "SHOULD_NOT_RUN" not in out- assert "OS_ISOLATION_UNAVAILABLE" in out+ assert "without host fallback" in out[email protected]("platform", ["win32", "cygwin", "aix"])[email protected]("platform", ["cygwin", "aix"])def test_a_platform_with_no_backend_gets_exactly_the_plan_it_handed_in(monkeypatch, platform):monkeypatch.setattr(sys, "platform", platform)@@ -476,7 +506,7 @@ def test_a_platform_with_no_backend_gets_exactly_the_plan_it_handed_in(monkeypatdef test_a_platform_with_no_backend_still_refuses_in_required(monkeypatch):- monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setattr(sys, "platform", "aix")with pytest.raises(SandboxUnavailableError):os_sandbox.prepare_tool_launch(ToolLaunchPlan(argv = ("prog",), workdir = "/work", env = {}, requested_mode = "required")@@ -640,12 +670,16 @@ def test_a_backend_that_fails_at_launch_drops_the_cached_verdict(monkeypatch):def test_a_planner_os_error_refuses_rather_than_running_unisolated(monkeypatch):backend = importlib.import_module(- "core.inference.sandbox_linux"- if sys.platform == "linux"- else "core.inference.sandbox_macos"+ "core.inference.sandbox_windows_mxc"+ if sys.platform == "win32"+ else (+ "core.inference.sandbox_linux"+ if sys.platform == "linux"+ else "core.inference.sandbox_macos"+ ))- def full_disk(plan):+ def full_disk(plan, *_args):raise OSError(errno.ENOSPC, "No space left on device")monkeypatch.setattr(@@ -815,6 +849,27 @@ def test_an_approval_does_not_lift_the_jail_for_a_call_that_needs_no_host_path(massert len(planned) == 1[email protected]("executor", ["python", "terminal"])+def test_a_stop_during_the_sandbox_probe_reads_as_a_cancel(monkeypatch, executor):+ # The Windows DACL probe takes seconds; a stop that lands in it is not a sandbox error.+ import threading++ cancel = threading.Event()++ def probe_then_stop(**_kwargs):+ cancel.set()+ return os_sandbox.SandboxCapability(+ backend = "test", available = True, reason = "ok", environment = sys.platform+ )++ monkeypatch.setattr(os_sandbox, "capability_snapshot", probe_then_stop)+ if executor == "python":+ out = tools._python_exec("print('never')", cancel, 60, _SESSION)+ else:+ out = tools._bash_exec("echo never", cancel, 60, _SESSION)+ assert out == "Execution cancelled."++@pytest.mark.parametrize("command",[diff --git a/studio/install_mxc_prebuilt.py b/studio/install_mxc_prebuilt.pynew file mode 100644index 00000000000..b587c25c546--- /dev/null+++ b/studio/install_mxc_prebuilt.py@@ -0,0 +1,367 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Install Microsoft's pinned WXC v0.8.0 executables for Studio on Windows."""++from __future__ import annotations++import argparse+import os+from pathlib import Path, PurePosixPath+import shutil+import subprocess+import sys+import tarfile+import tempfile+import urllib.error+import urllib.request++_STUDIO_DIR = Path(__file__).resolve().parent+if str(_STUDIO_DIR) not in sys.path:+ sys.path.insert(0, str(_STUDIO_DIR))++from backend.core.inference import mxc_runtime # noqa: E402+from prebuilt_core import BusyInstallConflict, install_lock, install_lock_path, swap_into_place # noqa: E402+++class MxcInstallError(RuntimeError):+ pass+++def _download(destination: Path) -> None:+ request = urllib.request.Request(+ mxc_runtime.RELEASE_URL,+ headers = {"User-Agent": "unsloth-studio-mxc-prebuilt"},+ )+ try:+ with urllib.request.urlopen(request, timeout = 60) as response, destination.open("wb") as out:+ shutil.copyfileobj(response, out, length = 1024 * 1024)+ out.flush()+ os.fsync(out.fileno())+ except (OSError, urllib.error.URLError) as exc:+ destination.unlink(missing_ok = True)+ raise MxcInstallError(+ f"could not download the pinned Microsoft MXC package: {exc}"+ ) from exc+++def _approved_members() -> dict[str, tuple[str, int]]:+ return {+ mxc_runtime.RELEASE_MEMBER: ("wxc-exec.exe", mxc_runtime.WXC_EXEC_SIZE),+ mxc_runtime.RELEASE_HOST_PREP_MEMBER: (+ "wxc-host-prep.exe",+ mxc_runtime.WXC_HOST_PREP_SIZE,+ ),+ }+++def _already_installed(install_dir: Path) -> bool:+ try:+ mxc_runtime._validate_runtime(install_dir)+ mxc_runtime._validate_host_prep(install_dir)+ except mxc_runtime.MxcRuntimeUnavailable:+ return False+ return True+++def _validate_archive_entries(bundle: tarfile.TarFile) -> dict[str, tarfile.TarInfo]:+ members = _approved_members()+ seen: set[str] = set()+ approved: dict[str, list[tarfile.TarInfo]] = {name: [] for name in members}+ for entry in bundle.getmembers():+ name = entry.name+ path = PurePosixPath(name)+ if (+ not name+ or "\\" in name+ or path.is_absolute()+ or any(part in {"", ".", ".."} for part in path.parts)+ ):+ raise MxcInstallError("the Microsoft MXC archive contains an unsafe member path")+ folded = name.rstrip("/").casefold()+ if folded in seen:+ raise MxcInstallError("the Microsoft MXC archive contains a duplicate member")+ seen.add(folded)+ if not (entry.isfile() or entry.isdir()):+ raise MxcInstallError("the Microsoft MXC archive contains a link or special file")+ if name in approved:+ approved[name].append(entry)+ result: dict[str, tarfile.TarInfo] = {}+ for name, (target, size) in members.items():+ if len(approved[name]) != 1:+ raise MxcInstallError(+ f"the Microsoft MXC archive does not contain one approved {target}"+ )+ entry = approved[name][0]+ if not entry.isfile() or entry.size != size:+ raise MxcInstallError(+ f"the approved {target} archive member has an unexpected shape or size"+ )+ result[target] = entry+ return result+++def install_mxc_release(install_dir: Path) -> bool:+ """Install the approved WXC binary; return ``True`` only when files changed."""+ if sys.platform != "win32":+ raise MxcInstallError("the MXC runtime installer is Windows-only")+ if mxc_runtime._expected_architecture() != "x86_64":+ raise MxcInstallError("the Microsoft MXC release supports Windows x86-64 only")++ install_dir = install_dir.expanduser().resolve()+ install_dir.parent.mkdir(parents = True, exist_ok = True)+ with install_lock(install_lock_path(install_dir)):+ if _already_installed(install_dir):+ return False++ stage = Path(tempfile.mkdtemp(prefix = f".{install_dir.name}-", dir = install_dir.parent))+ try:+ archive = stage / ".mxc-sdk.tgz"+ _download(archive)+ actual_size = archive.stat().st_size+ if actual_size != mxc_runtime.RELEASE_ARCHIVE_SIZE:+ raise MxcInstallError(+ "MXC release size mismatch: "+ f"expected {mxc_runtime.RELEASE_ARCHIVE_SIZE}, got {actual_size}"+ )+ actual_digest = mxc_runtime._sha256_file(archive)+ if actual_digest != mxc_runtime.RELEASE_ARCHIVE_SHA256:+ raise MxcInstallError(+ "MXC release checksum mismatch: "+ f"expected {mxc_runtime.RELEASE_ARCHIVE_SHA256}, got {actual_digest}"+ )+ try:+ with tarfile.open(archive, "r:gz") as bundle:+ for target, entry in _validate_archive_entries(bundle).items():+ # Streamed by name, never tar.extract: the member path is not trusted.+ source = bundle.extractfile(entry)+ if source is None:+ raise MxcInstallError(f"the approved {target} member is unreadable")+ with source, (stage / target).open("wb") as output:+ shutil.copyfileobj(source, output, length = 1024 * 1024)+ output.flush()+ os.fsync(output.fileno())+ except (OSError, tarfile.TarError) as exc:+ raise MxcInstallError("the pinned Microsoft MXC archive is invalid") from exc+ archive.unlink()+ mxc_runtime._validate_runtime(stage)+ mxc_runtime._validate_host_prep(stage)+ swap_into_place(stage, install_dir)+ finally:+ shutil.rmtree(stage, ignore_errors = True)+ return True+++def _is_elevated() -> bool:+ import ctypes+ try:+ return bool(ctypes.windll.shell32.IsUserAnAdmin())+ except (AttributeError, OSError):+ return False+++def _run_elevated(executable: Path, arguments: list[str], directory: str) -> int:+ """UAC prompt via ShellExecuteExW("runas"): CreateProcess cannot start this exe unelevated."""+ import ctypes+ from ctypes import wintypes++ class ShellExecuteInfo(ctypes.Structure):+ _fields_ = [+ ("cbSize", wintypes.DWORD),+ ("fMask", wintypes.ULONG),+ ("hwnd", wintypes.HWND),+ ("lpVerb", wintypes.LPCWSTR),+ ("lpFile", wintypes.LPCWSTR),+ ("lpParameters", wintypes.LPCWSTR),+ ("lpDirectory", wintypes.LPCWSTR),+ ("nShow", ctypes.c_int),+ ("hInstApp", wintypes.HINSTANCE),+ ("lpIDList", wintypes.LPVOID),+ ("lpClass", wintypes.LPCWSTR),+ ("hkeyClass", wintypes.HKEY),+ ("dwHotKey", wintypes.DWORD),+ ("hIconOrMonitor", wintypes.HANDLE),+ ("hProcess", wintypes.HANDLE),+ ]++ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)+ shell32 = ctypes.WinDLL("shell32", use_last_error = True)+ shell32.ShellExecuteExW.argtypes = [ctypes.POINTER(ShellExecuteInfo)]+ shell32.ShellExecuteExW.restype = wintypes.BOOL+ kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]+ kernel32.WaitForSingleObject.restype = wintypes.DWORD+ kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]+ kernel32.GetExitCodeProcess.restype = wintypes.BOOL+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ kernel32.CloseHandle.restype = wintypes.BOOL++ info = ShellExecuteInfo()+ info.cbSize = ctypes.sizeof(ShellExecuteInfo)+ info.fMask = 0x40 | 0x100 | 0x400 # NOCLOSEPROCESS | NOASYNC | FLAG_NO_UI+ info.lpVerb = "runas"+ info.lpFile = str(executable)+ info.lpParameters = subprocess.list2cmdline(arguments)+ info.lpDirectory = directory+ info.nShow = 1 # its console shows the progress of a multi-minute run+ if not shell32.ShellExecuteExW(ctypes.byref(info)):+ error = ctypes.get_last_error()+ if error == 1223:+ raise MxcInstallError("the Windows administrator prompt was declined")+ raise MxcInstallError(+ f"could not start the elevated host preparation (Windows error {error})"+ )+ if not info.hProcess:+ raise MxcInstallError("wxc-host-prep started without a process handle")+ try:+ # INFINITE: killing prepare-system-drive mid-propagation leaves C:\ half re-ACLed.+ if kernel32.WaitForSingleObject(info.hProcess, 0xFFFFFFFF) != 0:+ raise MxcInstallError("could not wait for wxc-host-prep")+ code = wintypes.DWORD()+ if not kernel32.GetExitCodeProcess(info.hProcess, ctypes.byref(code)):+ raise MxcInstallError("could not read the wxc-host-prep exit code")+ return int(code.value)+ finally:+ kernel32.CloseHandle(info.hProcess)+++def _system_directory() -> str:+ """System32 from the API: SystemRoot is a user-settable variable, and this path runs elevated."""+ import ctypes++ buffer = ctypes.create_unicode_buffer(260)+ if not ctypes.windll.kernel32.GetSystemDirectoryW(buffer, 260):+ raise MxcInstallError("could not locate the Windows system directory")+ return buffer.value+++def _host_prep_script(executable: Path, arguments: list[str]) -> str:+ """Elevated: copy the pinned exe into a fresh admin-only dir, re-hash it, run it from there.++ The install dir is user-writable, so running host-prep in place would let a planted DLL+ (it LoadLibrary's dbghelp.dll) execute as administrator.+ """++ def quote(value: str) -> str:+ return "'" + value.replace("'", "''") + "'"++ return "\n".join(+ (+ "$ErrorActionPreference = 'Stop'",+ # .NET only: cmdlets such as Get-FileHash fail to load when PSModulePath is pwsh 7's.+ # Known folder, not $env:ProgramData: user variables can shadow it.+ "$root = [Environment]::GetFolderPath('CommonApplicationData')",+ "$dir = [IO.Path]::Combine($root, 'unsloth-mxc-host-prep-' + [guid]::NewGuid().ToString('N'))",+ "if ([IO.Directory]::Exists($dir)) { exit 92 }",+ "$null = [IO.Directory]::CreateDirectory($dir)",+ "try {",+ " $icacls = [IO.Path]::Combine([Environment]::SystemDirectory, 'icacls.exe')",+ " $null = & $icacls $dir /inheritance:r /grant:r '*S-1-5-32-544:(OI)(CI)F' "+ "'*S-1-5-18:(OI)(CI)F'",+ " if ($LASTEXITCODE -ne 0) { exit 90 }",+ # Anything planted before the ACL change stays: the dir must still be empty.+ " if ([IO.Directory]::GetFileSystemEntries($dir).Length -ne 0) { exit 92 }",+ " $exe = [IO.Path]::Combine($dir, 'wxc-host-prep.exe')",+ f" [IO.File]::Copy({quote(str(executable))}, $exe)",+ " $stream = [IO.File]::OpenRead($exe)",+ " try { $digest = [Security.Cryptography.SHA256]::Create().ComputeHash($stream) }",+ " finally { $stream.Dispose() }",+ " $hash = [BitConverter]::ToString($digest).Replace('-', '')",+ f" if ($hash -ne '{mxc_runtime.WXC_HOST_PREP_SHA256.upper()}') {{ exit 91 }}",+ f" & $exe {' '.join(quote(value) for value in arguments)}",+ " exit $LASTEXITCODE",+ "} finally {",+ " try { [IO.Directory]::Delete($dir, $true) } catch { }",+ "}",+ )+ )+++_HOST_PREP_SCRIPT_ERRORS = {+ 90: "could not restrict the host-prep staging directory to administrators",+ 91: "the staged wxc-host-prep.exe does not match its pinned digest",+ 92: "the host-prep staging directory was not empty after it was locked down",+}+++def _run_host_prep(executable: Path, step: str) -> int:+ import base64++ arguments = [step, "--quiet"] if step == "prepare-null-device" else [step]+ system = _system_directory()+ powershell = os.path.join(system, "WindowsPowerShell", "v1.0", "powershell.exe")+ encoded = base64.b64encode(_host_prep_script(executable, arguments).encode("utf-16-le"))+ launcher = ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded.decode()]+ # Measured 3 to 7 minutes on a CI runner: it propagates an ACE across the whole system drive.+ print(f"[mxc-prebuilt] running wxc-host-prep {step}; this can take several minutes")+ if _is_elevated():+ code = subprocess.run(+ [powershell, *launcher],+ cwd = system,+ stdin = subprocess.DEVNULL,+ check = False,+ ).returncode+ else:+ code = _run_elevated(Path(powershell), launcher, system)+ if code in _HOST_PREP_SCRIPT_ERRORS:+ raise MxcInstallError(_HOST_PREP_SCRIPT_ERRORS[code])+ return code+++def prepare_host(install_dir: Path) -> tuple[str, ...]:+ """Run the host preparation MXC's Tier 3 reports missing; both steps when it cannot tell."""+ if sys.platform != "win32":+ raise MxcInstallError("MXC host preparation is Windows-only")+ install_dir = install_dir.expanduser().resolve()+ steps = mxc_runtime.probe_host_prep_steps(+ package_root = install_dir, replay_journal = not _is_elevated()+ )+ if steps is None:+ steps = mxc_runtime.HOST_PREP_STEPS+ if not steps:+ return ()+ with mxc_runtime.acquire_host_prep(package_root = install_dir) as lease:+ for step in steps:+ code = _run_host_prep(lease.info.path, step)+ if code != 0:+ raise MxcInstallError(f"wxc-host-prep {step} failed with exit code {code}")+ return tuple(steps)+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description = __doc__)+ parser.add_argument("--install-dir", type = Path)+ parser.add_argument(+ "--prepare-host",+ action = "store_true",+ help = "Run the elevated wxc-host-prep steps the opt-in DACL mode needs "+ "(prepare-null-device again after every reboot).",+ )+ args = parser.parse_args(argv)+ if args.prepare_host:+ try:+ steps = prepare_host(args.install_dir or mxc_runtime._installed_package_root())+ except (MxcInstallError, mxc_runtime.MxcRuntimeUnavailable, OSError) as exc:+ print(f"[mxc-prebuilt] {exc}", file = sys.stderr)+ return 1+ print(+ f"[mxc-prebuilt] host prepared: {', '.join(steps)}"+ if steps+ else "[mxc-prebuilt] host already prepared"+ )+ return 0+ if args.install_dir is None:+ parser.error("--install-dir is required")+ try:+ changed = install_mxc_release(args.install_dir)+ except BusyInstallConflict as exc:+ print(f"[mxc-prebuilt] install blocked by an active MXC process: {exc}", file = sys.stderr)+ return 3+ except (MxcInstallError, mxc_runtime.MxcRuntimeUnavailable) as exc:+ print(f"[mxc-prebuilt] {exc}", file = sys.stderr)+ return 1+ print("[mxc-prebuilt] installed and validated" if changed else "[mxc-prebuilt] already matches")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/studio/setup.ps1 b/studio/setup.ps1index 315143ba843..d47b63c5e56 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -8352,6 +8352,48 @@ if ($stackExit -ne 0) {$ErrorActionPreference = $prevEAP}+# Windows MXC Preview is an optional, pinned prebuilt like the other native+# runtimes. Keep this outside the Python dependency fast path: a missing or+# corrupt runtime must be installed or repaired even when the venv is current.+if ([System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT) {+ $_mxcInstaller = Join-Path $PSScriptRoot "install_mxc_prebuilt.py"+ $_mxcInstallDir = Join-Path $StudioHome "mxc-runtime\windows-x86_64"+ if (Test-Path -LiteralPath $_mxcInstaller -PathType Leaf) {+ substep "installing Windows MXC Preview runtime..."+ # Optional, so a nonzero exit or stderr line must reach the fallback below, not stop setup.+ $_mxcPrevEAP = $ErrorActionPreference+ $ErrorActionPreference = "Continue"+ $_mxcRestoreNative = $PSVersionTable.PSVersion.Major -ge 7+ if ($_mxcRestoreNative) {+ $_mxcPrevNative = $PSNativeCommandUseErrorActionPreference+ $PSNativeCommandUseErrorActionPreference = $false+ }+ try {+ $_mxcOutput = & python $_mxcInstaller --install-dir $_mxcInstallDir 2>&1 | Out-String+ $_mxcExit = $LASTEXITCODE+ } finally {+ $ErrorActionPreference = $_mxcPrevEAP+ if ($_mxcRestoreNative) {+ $PSNativeCommandUseErrorActionPreference = $_mxcPrevNative+ }+ }+ if ($_mxcExit -eq 0) {+ if ($_mxcOutput -match "already matches") {+ step "MXC Preview" "prebuilt up to date and validated"+ } else {+ step "MXC Preview" "prebuilt installed and validated"+ }+ } elseif ($_mxcExit -eq 3) {+ step "MXC Preview" "install blocked by an active MXC process; existing runtime kept" "Yellow"+ } else {+ step "MXC Preview" "prebuilt unavailable; Studio will use software safeguards" "Yellow"+ }+ if ($script:UnslothVerbose -and $_mxcOutput) {+ Write-StudioLine $_mxcOutput.Trim() -ForegroundColor $(if ($_mxcExit -eq 0) { "DarkGray" } else { "Yellow" })+ }+ }+}+# ── Pre-install transformers 5.x into .venv_t5_530/, .venv_t5_550/, and .venv_t5_510/ ──# Runs outside the deps fast-path gate so that upgrades from the legacy# single .venv_t5 are always migrated to the tiered layout.@@ -9107,7 +9149,7 @@ if ($env:WHISPER_SERVER_PATH -or $env:UNSLOTH_WHISPER_CPP_PATH) {# caught here; an unowned tree still stops.step "whisper.cpp" "install directory cannot be read: access is denied; curated whisper.cpp dictation is unavailable; restore access to $WhisperCppDir or move it aside, then re-run setup; browser and Transformers dictation remain available" "Yellow"} elseif (Test-Path -LiteralPath $WhisperInstaller) {- # The installer's atomic activation replaces the whole directory, so the+ # The installer replaces the whole directory during activation, so the# custom-home ownership guard must run first (mirrors the llama block).if ($RuntimeRootIsCustom) {Assert-StudioOwnedOrAbsent -Path $WhisperCppDir -Label "whisper.cpp install" -IsCustom $RuntimeRootIsCustomdiff --git a/tests/test_installer_interactive_prompts.py b/tests/test_installer_interactive_prompts.pyindex a991f3934a5..8ff0cf023cd 100644--- a/tests/test_installer_interactive_prompts.py+++ b/tests/test_installer_interactive_prompts.py@@ -47,6 +47,7 @@ SCANNED_SCRIPTS = ENTRY_POINTS + ("studio/install_lemonade_prebuilt.py","studio/install_llama_prebuilt.py","studio/install_manifest.py",+ "studio/install_mxc_prebuilt.py","studio/install_node_prebuilt.py","studio/install_python_stack.py","studio/install_sd_cpp_prebuilt.py",