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
CI: fix llama.cpp seed caching, Diffusers wheel installs, and isolated test coverage (#9979)
oobabooga1400031e2fe0
diff --git a/.github/scripts/assert-nobuild.ps1 b/.github/scripts/assert-nobuild.ps1index 9cb39ed52ed..38faf09d625 100644--- a/.github/scripts/assert-nobuild.ps1+++ b/.github/scripts/assert-nobuild.ps1@@ -18,8 +18,8 @@ if (-not (Test-Path -LiteralPath $LogPath)) {# "Built an sdist" is NOT "needed a compiler": each name was verified against its own# sdist (setuptools.build_meta, no ext_modules, no .c/.cpp/.pyx/.rs), so its PEP 517# build is a pure-Python copy step. clean-machine-assert.sh carries the per-name detail.-# diffusers is pinned to a source archive because MiniMax-H3 support is not in any release-# yet; remove it here once a release carries H3. clean-machine-assert.sh carries the detail.+# diffusers is here only for the `overlay: false` legs, which install the released wheel+# and its pre-0.40.0 GitHub-archive pin; remove it once a release carries the wheel pin.$allow = @('openai-whisper', 'argbind', 'randomname', 'antlr4-python3-runtime', 'triton-kernels', 'diffusers')if ($env:UNSLOTH_ALLOW_SDIST) {$allow += ($env:UNSLOTH_ALLOW_SDIST -split '\s+' | Where-Object { $_ })diff --git a/.github/scripts/assert-prompt-cache.sh b/.github/scripts/assert-prompt-cache.shindex 8c28569f77b..56cecdb59e5 100755--- a/.github/scripts/assert-prompt-cache.sh+++ b/.github/scripts/assert-prompt-cache.sh@@ -100,6 +100,8 @@ case "$MODE" in# A deliberately long, fixed system prompt makes the shared prefix big so a# KV-cache hit is unambiguous (cached_tokens grows with the reused prefix).+ # Do not set a request seed: fixed seeds disable prompt caching for reproducibility.+ # This probe measures cache reuse; the server already uses --seed/--temp 0.SYS='You are a meticulous assistant. Always answer concisely and correctly. This is a fixed system preamble that exists only to create a large, identical prompt prefix across both turns so the KV cache has something substantial to reuse on the second request. Do not mention this preamble.'turn1_body() {@@ -109,7 +111,7 @@ case "$MODE" in{role:"system", content:$sys},{role:"user", content:"What is the capital of France?"}],- temperature: 0.0, seed: 3407, max_tokens: 40, stream: false,+ temperature: 0.0, max_tokens: 40, stream: false,enable_thinking: false}'}@@ -132,7 +134,7 @@ case "$MODE" in{role:"assistant", content:$a1},{role:"user", content:"And the capital of Germany?"}],- temperature: 0.0, seed: 3407, max_tokens: 40, stream: false,+ temperature: 0.0, max_tokens: 40, stream: false,enable_thinking: false}'}diff --git a/.github/scripts/clean-machine-assert.sh b/.github/scripts/clean-machine-assert.shindex fe88798ac7c..3dbee2cc150 100755--- a/.github/scripts/clean-machine-assert.sh+++ b/.github/scripts/clean-machine-assert.sh@@ -207,11 +207,8 @@ for check in "$@"; do# triton-kernels -- a git URL under the triton repo's python/triton_kernels# subdir: 75 Python files, no setup.py, kernels compiled at runtime. Named by# the installer, not chosen by resolution, and only the Linux legs reach it.- # diffusers -- pinned to a source archive because MiniMax-H3 support is not in- # any release yet. Plain setuptools, no ext_modules, and the tree has zero- # .c/.cpp/.pyx/.rs/.cu files, so the PEP 517 build is a pure-Python copy.- # REMOVE this entry once a diffusers release carries H3 and the requirement- # goes back to a version specifier.+ # diffusers -- overlay:false releases still pin a pure-Python source archive.+ # Remove this once a published Unsloth release carries the wheel pin.# UNSLOTH_ALLOW_SDIST extends it. Lowercased and underscore-folded on both sides:# the distribution name and the name uv prints can differ on the separator._allow="$(printf '%s' "openai-whisper argbind randomname antlr4-python3-runtime triton-kernels diffusers ${UNSLOTH_ALLOW_SDIST:-}" | tr 'A-Z_' 'a-z-')"diff --git a/.github/workflows/consolidated-tests-ci.yml b/.github/workflows/consolidated-tests-ci.ymlindex 301efb4bb1e..13c3b7db7ea 100644--- a/.github/workflows/consolidated-tests-ci.yml+++ b/.github/workflows/consolidated-tests-ci.yml@@ -466,62 +466,51 @@ jobs:# here unblocks unsloth CI until the loader fixture is fixed.working-directory: ${{ runner.temp }}/unsloth-zoorun: |- # Two passes: everything in parallel, then the two files that cannot share a- # process with the rest of the suite.- #- # Measured on a staging runner across all three matrix cells, whole suite:- #- # cell serial -n 4 --dist loadfile- # HF=latest + TRL=latest 580s 253s- # HF=4.57.6 + TRL<1 517s 229s- # HF=default + TRL=default 568s 246s- #- # Across two runs of all three cells, four agreed exactly -- failure sets and- # skip sets both -- and two produced 14 failures serial does not: 8 in- # test_mlx_generate.py and 6 in test_moe_bnb4bit_per_expert_conversions.py.- #- # The same 14 every time, and NOT the same cell: the second run moved them from- # HF=default to HF=latest. So this is not a dependency combination, it is worker- # scheduling, and roughly one cell per run draws the losing order.- #- # Both files pass on their own, and pass under xdist on their own, so they are- # self-contained. What breaks them is another file running first in the same- # worker -- an ordering serial never produces, because serial is alphabetical.- # So the parallel speedup is real and the divergence is real, and the two are- # separable: run those two files in their own process, where they are reliable.- #- # This is a mitigation, not a cure. The suite has cross-file pollution that- # alphabetical ordering happens to hide, and the right fix is in unsloth_zoo,- # on whichever file leaks. Pinning here keeps CI honest meanwhile: what these- # two files prove is unchanged, because a fresh process is what they get today.- #- # test_hf_xet_fallback.py is here for a different reason, found the same way.- # It drives a stall detector against the real clock -- 27 sub-second sleeps,- # one of them commented "within the unmeasurable window" -- and under four- # workers on four cores it reported "Download appears stalled (xet transport)- # -- no progress for 0s". Nothing was stalled; the test was descheduled. No- # ordering fix helps a wall-clock margin, so it gets the quiet process too.- #- # It is the only file in the suite with that shape: two use sub-second sleeps- # and the other one (test_mlx_save_export_edge_cases.py) sleeps 0.01s to widen- # a race window without asserting on elapsed time.- #- # loadfile rather than the default `load`: 34 of the 236 files touch sys.modules- # or importlib.reload, so tests within a file must stay on one worker, in order.+ # Keep tests within each file on one worker. MLX shims contaminate sys.modules,+ # so exclude that family from xdist and run it separately below. The other+ # ignores either leak process state or use timing assertions that need a quiet+ # process.python -m pytest -q --tb=short -n 4 --dist loadfile tests/ \- --ignore=tests/test_mlx_generate.py \+ --ignore-glob='tests/test_mlx_*.py' \--ignore=tests/test_moe_bnb4bit_per_expert_conversions.py \--ignore=tests/test_hf_xet_fallback.py \+ --ignore=tests/test_gemma3_forced_float32_boundary_dtype.py \--deselect tests/test_unsloth_zoo_lora_merge.py::test_active_merge_device_returns_string_on_cuda_host \- --deselect tests/test_unsloth_zoo_lora_merge.py::test_merge_lora_moves_cpu_inputs_to_active_device \- --deselect tests/test_mlx_finetune_last_n_layers.py::test_get_peft_model_passes_finetune_last_n_layers_through-- # The pair, serially, in a process of their own. Not optional: without this the- # ignores above delete 51 tests from CI and the job still goes green.- python -m pytest -q --tb=short \- tests/test_mlx_generate.py \- tests/test_moe_bnb4bit_per_expert_conversions.py \- tests/test_hf_xet_fallback.py+ --deselect tests/test_unsloth_zoo_lora_merge.py::test_merge_lora_moves_cpu_inputs_to_active_device++ # Run contamination-sensitive files in separate processes. Keep collecting+ # results after failures, and treat pytest exit 5 as a module-level skip.+ rc=0+ _keep() {+ if [ "$1" = 5 ]; then+ # Named: an expected module-level skip and a file that stopped collecting+ # for a new reason both exit 5.+ echo "note: ${2:-that run} collected nothing (module-level skip), not a failure"+ else+ rc=1+ fi+ }+ python -m pytest -q --tb=short tests/test_mlx_generate.py || _keep "$?" tests/test_mlx_generate.py+ python -m pytest -q --tb=short tests/test_moe_bnb4bit_per_expert_conversions.py || _keep "$?" tests/test_moe_bnb4bit_per_expert_conversions.py+ python -m pytest -q --tb=short tests/test_hf_xet_fallback.py || _keep "$?" tests/test_hf_xet_fallback.py+ python -m pytest -q --tb=short tests/test_mlx_neftune_quant_map.py || _keep "$?" tests/test_mlx_neftune_quant_map.py+ python -m pytest -q --tb=short tests/test_mlx_gated_delta_vjp.py || _keep "$?" tests/test_mlx_gated_delta_vjp.py+ python -m pytest -q --tb=short tests/test_gemma3_forced_float32_boundary_dtype.py || _keep "$?" tests/test_gemma3_forced_float32_boundary_dtype.py++ # Run the remaining MLX files serially in alphabetical order. The three isolated+ # above also contaminate this group, so exclude them from its file list.+ mlx_group=$(ls tests/test_mlx_*.py |+ grep -vE 'tests/test_mlx_(generate|neftune_quant_map|gated_delta_vjp)\.py$')+ # Passed unquoted below to word-split into file arguments, so an empty list+ # would pass none and pytest would collect the whole rootdir instead.+ if [ -z "$mlx_group" ]; then+ echo "::error::the mlx group glob matched no files"+ exit 1+ fi+ python -m pytest -q --tb=short $mlx_group \+ --deselect tests/test_mlx_finetune_last_n_layers.py::test_get_peft_model_passes_finetune_last_n_layers_through \+ || _keep "$?" "the mlx group"+ exit "$rc"- name: unsloth_zoo — test_apply_fused_lm_head (lives in compiler.py)# `test_apply_fused_lm_head` lives at unsloth_zoo/compiler.py:1983,@@ -2578,4 +2567,3 @@ jobs:dir: ${{ steps.pip-cache.outputs.dir }}key: ${{ steps.pip-cache.outputs.key }}cache-hit: ${{ steps.pip-cache.outputs.cache-hit }}-diff --git a/.github/workflows/studio-backend-ci.yml b/.github/workflows/studio-backend-ci.ymlindex 07911417ed5..f7ccf9267c7 100644--- a/.github/workflows/studio-backend-ci.yml+++ b/.github/workflows/studio-backend-ci.yml@@ -185,7 +185,8 @@ jobs:# Torch CPU + transformers are required by a chunk of the backend test# suite (gpu_selection, kv_cache_estimation, utils). CPU-only torch# keeps the install ~250 MB / ~1 min on a clean runner.- pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple 'torch>=2.4,<2.11'+ pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \+ 'torch>=2.4,<2.11' 'torchaudio<2.11'pip install 'transformers>=4.51,<5.5'# peft: core/inference/inference.py imports it at module scope, and it is listed# only in extras-no-deps.txt and no-torch-runtime.txt, neither of which this job@@ -252,6 +253,8 @@ jobs:# isolation guard scans for the tight ones, so a new test below the threshold# fails that guard instead of flaking here.#+ # test_media_auto_switch has a 0.4s budget that xdist scheduling can exceed.+ ## --timeout: a per-test wall-clock cap, so a test that never returns fails with its# own name in the summary instead of taking the job's 45 minutes down with it and# reporting "cancelled". 330s comes off the measured distribution rather than taste:@@ -287,6 +290,7 @@ jobs:--ignore=tests/test_scan_loras_off_event_loop.py \--ignore=tests/test_anthropic_messages.py \--ignore=tests/test_profile_stats.py \+ --ignore=tests/test_media_auto_switch.py \-k 'not llama_cpp_load_progress_live and not TestGpuAutoSelection and not TestPreSpawnGpuResolution and not TestPerGpuFitGuardAllCounts and not TestTransformersIntrospection and not test_returns_cuda_when_cuda_available and not test_calls_cuda_cache_when_cuda'- name: Backend tests that cannot share a worker@@ -306,7 +310,8 @@ jobs:tests/test_tunnel_safe_long_post.py \tests/test_scan_loras_off_event_loop.py \tests/test_anthropic_messages.py \- tests/test_profile_stats.py+ tests/test_profile_stats.py \+ tests/test_media_auto_switch.py- name: Pre-3.12 branches, on the newest interpreter that takes themif: matrix.scope == 'floor-spot-check'@@ -388,7 +393,7 @@ jobs:'numpy<3' pytest pytest-asyncio pytest-xdist httpx# torchvision: unsloth_zoo.vision_utils imports it at module scope.pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \- 'torch>=2.4,<2.11' 'torchvision<0.26'+ 'torch>=2.4,<2.11' 'torchvision<0.26' 'torchaudio<2.11'pip install 'transformers>=4.51,<5.5'# bitsandbytes: hard import in unsloth/models/_utils.py. Recent# versions ship a CPU build that imports cleanly on Linux.@@ -537,4 +542,3 @@ jobs:dir: ${{ steps.pip-cache.outputs.dir }}key: ${{ steps.pip-cache.outputs.key }}cache-hit: ${{ steps.pip-cache.outputs.cache-hit }}-diff --git a/install.ps1 b/install.ps1index 64f6d189c40..e9bf1deefaa 100644--- a/install.ps1+++ b/install.ps1@@ -1596,10 +1596,12 @@ public static class UnslothStudioFinalPathV2(Get-CanonicalDir -Path (Join-Path $env:USERPROFILE ".unsloth\studio")))}- # Shared default cache, or the custom Unsloth home's llama.cpp tree.+ # Explicit staging root, shared default cache, or the custom Unsloth home's tree.function Get-ManagedLlamaCppDir {- if ($StageRoot) {- return (Join-Path $StageRoot "llama.cpp")+ param([AllowNull()][string]$StagingRoot = $null)++ if ($StagingRoot) {+ return (Join-Path $StagingRoot "llama.cpp")}if (-not (Test-StudioHomeIsCustom)) {return (Join-Path $env:USERPROFILE ".unsloth\llama.cpp")@@ -1609,9 +1611,11 @@ public static class UnslothStudioFinalPathV2# Failure reason when the managed tree is denied; never touches its ACLs.function Invoke-ManagedLlamaCppPreflight {+ param([AllowNull()][string]$StagingRoot = $null)+# Let the existing profile validation handle a missing USERPROFILE later.if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { return $null }- $dir = Get-ManagedLlamaCppDir+ $dir = Get-ManagedLlamaCppDir -StagingRoot $StagingRootif ((Get-LlamaCppInstallReadState -Path $dir) -ne "Denied") { return $null }Write-StudioLine ""# A denied custom home cannot be claimed as an Unsloth-managed cache.diff --git a/scripts/scan_packages_baseline.json b/scripts/scan_packages_baseline.jsonindex e6b1435d2dc..d320a2ff3d7 100644--- a/scripts/scan_packages_baseline.json+++ b/scripts/scan_packages_baseline.json@@ -1741,7 +1741,8 @@"check": "Harvests environment variables/secrets AND makes network calls","severity": "CRITICAL","evidence": "Env: L150: return os.environ.get(UNSLOTH_ALLOW_PRIVATE_URL_FETCH_VAR, \"0\") == \"1\"\nNetwork: L108: from urllib.request import url2pathname | L287: with requests.Session() as session:",- "evidence_hash": "13af1f1a0b133cbd4bc1e38e29a95a7e507078f1b43aca218b54654085cd2b99"+ "evidence_hash": "13af1f1a0b133cbd4bc1e38e29a95a7e507078f1b43aca218b54654085cd2b99",+ "file_sha256": "7c6266737b14cb08e136c0fcc5d63dc5047f416daa1fad4f16298a6269b73ce4"},{"package": "unsloth-zoo",@@ -1749,7 +1750,8 @@"check": "Accesses cloud metadata/IMDS AND makes network calls","severity": "CRITICAL","evidence": "IMDS: L143: \"metadata.google.internal\", \"metadata.goog\", \"metadata\",\nNetwork: L108: from urllib.request import url2pathname | L287: with requests.Session() as session:",- "evidence_hash": "285f7daff8b222ab03cc239132a58f2273213b83a38095d675041e086d547f31"+ "evidence_hash": "285f7daff8b222ab03cc239132a58f2273213b83a38095d675041e086d547f31",+ "file_sha256": "7c6266737b14cb08e136c0fcc5d63dc5047f416daa1fad4f16298a6269b73ce4"},{"package": "unsloth-zoo",@@ -1757,7 +1759,16 @@"check": "Advanced obfuscation (marshal/compile/zlib) + exec/eval","severity": "HIGH","evidence": "Obfusc: L1240: _mod = __import__(model_location, fromlist=items) | L5329: f\" {chr(92)}{chr(92)} /| Num examples = {num_examples:,} | Num Epochs = {num_train_epochs:,} | Total steps = {max_steps:,}\\\\n\"\\\\\nL5330: f\"O^O/ {chr(92)}_/ {chr(92)} Batch size per device = {self._train_batch_size:,} | Gradient accumulation steps = {args.gradient_accumulation_steps}\\\\n\"\\\\\nL5331: f\"{chr(92)} / Data Parallel GPUs = {args.world_size} | Total batch size ({self._train_batch_size} x {args.gradient_accumulation_steps} x {args.world_size}) = {total_train_batch_size: sha256:b7ea9cdbe360ad323911014caf12a9d4ec87cb36195a511080e4e484c2fb80d2\nL5332: f' \"-____-\" Trainable parameters = {get_model_param_count(model, trainable_only=True):,} of {get_model_param_count(model):,} ({get_model_param_count(model, trainable_only=True)/get_model_p sha256:9e832c1e7b2815aa44dc42638d821cb9df22550db88d85bd4bfb29c13f984b53 | L5330: f\"O^O/ {chr(92)}_/ {chr(92)} Batch size per device = {self._train_batch_size:,} | Gradient accumulation steps = {args.gradient_accumulation_steps}\\\\n\"\\\\\nL5331: f\"{chr(92)} / Data Parallel GPUs = {args.world_size} | Total batch size ({self._train_batch_size} x {args.gradient_accumulation_steps} x {args.world_size}) = {total_train_batch_size: sha256:b7ea9cdbe360ad323911014caf12a9d4ec87cb36195a511080e4e484c2fb80d2\nL5332: f' \"-____-\" Trainable parameters = {get_model_param_count(model, trainable_only=True):,} of {get_model_param_count(model):,} ({get_model_param_count(model, trainable_only=True)/get_model_p sha256:9e832c1e7b2815aa44dc42638d821cb9df22550db88d85bd4bfb29c13f984b53 | L5329: f\" {chr(92)}{chr(92)} /| Num examples = {num_examples:,} | Num Epochs = {num_train_epochs:,} | Total steps = {max_steps:,}\\\\n\"\\\\\nL5330: f\"O^O/ {chr(92)}_/ {chr(92)} Batch size per device = {self._train_batch_size:,} | Gradient accumulation steps = {args.gradient_accumulation_steps}\\\\n\"\\\\\nL5331: f\"{chr(92)} / Data Parallel GPUs = {args.world_size} | Total batch size ({self._train_batch_size} x {args.gradient_accumulation_steps} x {args.world_size}) = {total_train_batch_size: sha256:b7ea9cdbe360ad323911014caf12a9d4ec87cb36195a511080e4e484c2fb80d2\nExec: L1169: _modeling_file = eval(model_location) | L1658: f = eval(f\"{model_location}.{module}\") | L1988: exec(f\"def raise_{j}(*args, **kwargs): print('{function}')\", globals(), locals()) | L1989: try: exec(f\"EMPTY_LOGITS.{function} = raise_{j}\", globals(), locals()) | L3414: exec(f\"import {parent}\", locals(), globals()) | L3545: dir(eval(parent)), | L3549: exec(f\"{parent}.{child}.forward = forward\", globals(), locals()) | L3623: module = eval(f\"modeling_file.{module}\") | L3650: inner_class = eval(f\"modeling_file.{inner_class}\") | L3780: exec(f\"from timm.layers.norm_act import {norm}\") | L3788: forward = eval(norm).forward | L3794: exec(f\"timm.layers.norm_act.{norm}.forward = forward\") | L3811: exec(f\"from timm.models._efficientnet_blocks import {block}\") | L3819: forward = eval(block).forward | L3825: exec(f\"timm.models._efficientnet_blocks.{block}.forward = forward\") | L4059: exec(\nL4060: f\"{model_location}.torch.nn.{module}.forward = forward\",\nL4061: globals(),\nL4062: locals(),\nL4063: ) | L4065: exec(f\"{model_location}.nn.{module}.forward = forward\", globals(), locals()) | L4069: exec(\nL4070: f\"combined_module.torch.nn.{module}.forward = forward\",\nL4071: globals(),\nL4072: locals(),\nL4073: ) | L4075: exec(f\"combined_module.nn.{module}.forward = forward\", globals(), locals()) | L4152: source = eval(f\"{model_location}.torch\") | L4159: function = eval(f\"source.nn.{module}\") | L4336: exec(\"import transformers\", globals()) | L4349: exec(\nL4350: \"model_logger.addFilter(HideLoggingMessage('`use_cache`'))\", globals(), locals()\nL4351: ) | L4353: exec(\nL4354: \"model_logger.addFilter(HideLoggingMessage('compile_config'))\",\nL4355: globals(),\nL4356: locals(),\nL4357: ) | L4589: source = eval(f\"modeling_file.{module}\") | L4603: source = eval(f\"modeling_file.{module}\") | L4704: source = eval(f\"modeling_file.{module}\") | L4742: source = eval(f\"{model_location}.{module}\") | L4822: source = eval(f\"{model_location}.{module}\") | L4870: source = eval(f\"{model_location}.{module}\") | L5092: source = eval(f\"{model_location}.{module}\") | L5103: exec(\nL5104: f\"{model_location}.{module}._update_causal_mask = no_update_causal_mask\",\nL5105: globals(),\nL5106: ) | L5169: source = eval(f\"{model_location}.{module}\") | L5210: module_cls = eval(f\"{model_location}.{module}\") | L5247: module_cls = eval(f\"{model_location}.{module}\") | L5314: exec(\nL5315: \"from transformers.trainer import (\" + \", \".join(x for x in good_items) + \")\",\nL5316: globals(),\nL5317: ) | L5379: exec(inner_training_loop, globals()) | L5387: function = eval(f\"{model_location}.{module}\") | L5465: function = eval(f\"{model_location}.{module}\") | L5603: exec(\nL5604: f\"{model_location}.{module} = combined_module.{module}\",\nL5605: globals(),\nL5606: locals(),\nL5607: ) | L5617: check_dicts = dir(eval(f\"{model_location}\")) | L5619: item = eval(f\"{model_location}.{check}\") | L5629: exec(\nL5630: f\"{model_location}.{check}['{key}'] = combined_module.{replaced_class}\",\nL5631: globals(),\nL5632: locals(),\nL5633: )",- "evidence_hash": "bdfae4c24572c2a86fa6a2dede720ebb0723746963e43c2cd42701de5fc48fdb"+ "evidence_hash": "bdfae4c24572c2a86fa6a2dede720ebb0723746963e43c2cd42701de5fc48fdb",+ "file_sha256": "58f43e3b6ddeefff69cb345baec7642eb10e3f081b0753f236be6571550d54e3"+ },+ {+ "package": "triton",+ "file": "triton/_internal_testing.py",+ "check": "Reverse shell / bind shell pattern",+ "severity": "CRITICAL",+ "evidence": "L259: os.dup2(tmp_stderr.fileno(), 2) | L270: os.dup2(saved_stderr_fd, 2)",+ "evidence_hash": "c6336d0259890fa8501965b7a7c32cb9ceb47e7c0843d6bc6864d91bb2ed1f94"}]}diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 0d1cbbe7fca..e29740dc84f 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -620,6 +620,23 @@ _SPEC_KIND_CAPABILITY: dict[str, str] = {"mtp": "supports_mtp",}++# llama.h: #define LLAMA_DEFAULT_SEED 0xFFFFFFFF+_LLAMA_RANDOM_SEED = 0xFFFFFFFF+++def _apply_seeded_llama_request(payload: dict, seed: Optional[int]) -> None:+ """Disable prompt caching for fixed seeds so repeated requests stay reproducible."""+ if seed is None:+ return+ payload["seed"] = seed+ # llama.cpp reads the seed as uint32 and LLAMA_DEFAULT_SEED is 0xFFFFFFFF, so -1 and+ # 4294967295 are the same "pick one at random" and both keep cache reuse. Compared in+ # that domain rather than against the -1 literal, which the schemas also accept above.+ if (seed & 0xFFFFFFFF) != _LLAMA_RANDOM_SEED:+ payload["cache_prompt"] = False++_PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR = ("This Mac's Metal device is virtualised, where offloaded layers can return ""corrupt output, and the installed unsloth_zoo diffusion shim has no --ngl, "@@ -27374,8 +27391,7 @@ class LlamaCppBackend:logger.warning("Could not preflight the rolling context window: %s", exc)if stop:payload["stop"] = stop- if seed is not None:- payload["seed"] = seed+ _apply_seeded_llama_request(payload, seed)payload["stream_options"] = {"include_usage": True}url = f"{self.base_url}/v1/chat/completions"@@ -28352,8 +28368,7 @@ class LlamaCppBackend:_continuation_max_tokens = Noneif stop:payload["stop"] = stop- if seed is not None:- payload["seed"] = seed+ _apply_seeded_llama_request(payload, seed)_respawn_truncations: list[dict] = []@@ -30790,8 +30805,7 @@ class LlamaCppBackend:stream_payload["max_tokens"] = _final_max_tokensif stop:stream_payload["stop"] = stop- if seed is not None:- stream_payload["seed"] = seed+ _apply_seeded_llama_request(stream_payload, seed)stream_payload["stream_options"] = {"include_usage": True}if perf_callback is not None:diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex c9551572d40..537c249a400 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2929,6 +2929,12 @@ class ResponsesRequest(BaseModel):instructions: Optional[str] = Field(None, description = "System / developer instructions")temperature: Optional[float] = Field(None, ge = 0.0, le = 2.0)top_p: Optional[float] = Field(None, ge = 0.0, le = 1.0)+ seed: Optional[int] = Field(+ None,+ ge = -(2**63),+ le = 2**64 - 1,+ description = "[x-unsloth] Best-effort deterministic sampling seed.",+ )max_output_tokens: Optional[int] = Field(None, ge = 1)stream: bool = Field(False, description = "Whether to stream the response via SSE")@@ -3279,6 +3285,12 @@ class AnthropicMessagesRequest(BaseModel):temperature: Optional[float] = Nonetop_p: Optional[float] = Nonetop_k: Optional[int] = None+ seed: Optional[int] = Field(+ None,+ ge = -(2**63),+ le = 2**64 - 1,+ description = "[x-unsloth] Best-effort deterministic sampling seed.",+ )stop_sequences: Optional[list[str]] = Nonemetadata: Optional[dict] = None# [x-unsloth] extensions mirroring the OpenAI endpoint convenience fieldsdiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex b56742c11b7..43604672c13 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -627,20 +627,21 @@ def _choice_seed("""A seed of its own per choice, so a seeded request samples n times ratherthan repeating one run. Shared by both drains so they cannot disagree.- llama-server holds the seed as a uint32 and draws at random for exactly one- value, LLAMA_DEFAULT_SEED (0xFFFFFFFF); ``-1`` is the only request seed that- converts to it, and offsetting that would make every choice after the first- deterministic. Every other negative is an ordinary fixed seed there, so it- must be offset like any other or all n choices repeat one run. The offset is- taken in that same uint32 domain, so a shifted seed cannot land on the- sentinel and turn one choice random. MLX maps every seed onto its key domain- instead, so nothing is exempt on that side.+ llama-server reads the seed as a uint32 and draws at random for exactly one+ value, LLAMA_DEFAULT_SEED (0xFFFFFFFF). Every seed congruent to it is that+ sentinel, not just ``-1``: the schemas above also accept ``4294967295`` and+ ``2**64-1``. Tested in that domain to match ``_apply_seeded_llama_request``,+ since a literal ``-1`` left choice 0 random and cached while choice 1 was+ offset into a fixed, uncached seed. Every other negative is an ordinary fixed+ seed and must be offset, or all n choices repeat one run; offsetting in the+ same domain cannot land on the sentinel. MLX maps every seed onto its key+ domain, so nothing is exempt there."""if seed is None or not choice_index:return seedif not negative_is_random:return seed + choice_index- if seed == -1:+ if (seed & 0xFFFFFFFF) == 0xFFFFFFFF:return seedreturn ((seed & 0xFFFFFFFF) + choice_index) % 0xFFFFFFFF@@ -1462,6 +1463,7 @@ try:_DEFAULT_FIRST_TOKEN_TIMEOUT_S,_DEFAULT_MAX_TOKENS_FLOOR,_DEFAULT_STREAM_STALL_TIMEOUT_S,+ _apply_seeded_llama_request,_emitted_n_batch,_extra_args_draft_device_pin,_extra_args_n_ubatch,@@ -1519,6 +1521,7 @@ except ImportError:_DEFAULT_FIRST_TOKEN_TIMEOUT_S,_DEFAULT_MAX_TOKENS_FLOOR,_DEFAULT_STREAM_STALL_TIMEOUT_S,+ _apply_seeded_llama_request,_emitted_n_batch,_extra_args_draft_device_pin,_extra_args_n_ubatch,@@ -25435,6 +25438,8 @@ def _build_chat_request(chat_kwargs["temperature"] = payload.temperatureif payload.top_p is not None:chat_kwargs["top_p"] = payload.top_p+ if payload.seed is not None:+ chat_kwargs["seed"] = payload.seedif payload.max_output_tokens is not None:chat_kwargs["max_tokens"] = payload.max_output_tokens@@ -28030,6 +28035,7 @@ async def anthropic_messages(min_p = min_p,repetition_penalty = repetition_penalty,presence_penalty = presence_penalty,+ seed = payload.seed,tool_choice = openai_tool_choice,session_id = payload.session_id,cancel_id = payload.cancel_id,@@ -28054,6 +28060,7 @@ async def anthropic_messages(min_p = min_p,repetition_penalty = repetition_penalty,presence_penalty = presence_penalty,+ seed = payload.seed,tool_choice = openai_tool_choice,disable_parallel_tool_use = _disable_parallel,auto_heal_tool_calls = payload.auto_heal_tool_calls,@@ -28171,6 +28178,7 @@ async def anthropic_messages(presence_penalty = presence_penalty,max_tokens = payload.max_tokens,stop = stop,+ seed = payload.seed,cancel_event = cancel_event,max_tool_iterations = 25,on_conversation_grew = _anthropic_recost,@@ -28239,6 +28247,7 @@ async def anthropic_messages(presence_penalty = presence_penalty,max_tokens = payload.max_tokens,stop = stop,+ seed = payload.seed,cancel_event = cancel_event,promote_reasoning_only = False,perf_callback = _monitor_perf_callback(@@ -29130,8 +29139,7 @@ def _build_passthrough_payload(tool_choice = reconciled_tool_choice(tool_choice, openai_tools, safe_tools)if tool_choice is not None:body["tool_choice"] = tool_choice- if seed is not None:- body["seed"] = seed+ _apply_seeded_llama_request(body, seed)if stream and stream_options is not None:body["stream_options"] = stream_optionsbody["max_tokens"] = (@@ -29253,6 +29261,7 @@ async def _anthropic_passthrough_stream(min_p = None,repetition_penalty = None,presence_penalty = None,+ seed = None,tool_choice = "auto",session_id = None,cancel_id = None,@@ -29278,6 +29287,7 @@ async def _anthropic_passthrough_stream(min_p = min_p,repetition_penalty = repetition_penalty,presence_penalty = presence_penalty,+ seed = seed,tool_choice = tool_choice,chat_template_kwargs = _reasoning_template_kwargs(llama_backend, enable_thinking, reasoning_effort, preserve_thinking@@ -29553,6 +29563,7 @@ async def _anthropic_passthrough_non_streaming(min_p = None,repetition_penalty = None,presence_penalty = None,+ seed = None,tool_choice = "auto",disable_parallel_tool_use = False,auto_heal_tool_calls = None,@@ -29584,6 +29595,7 @@ async def _anthropic_passthrough_non_streaming(min_p = min_p,repetition_penalty = repetition_penalty,presence_penalty = presence_penalty,+ seed = seed,tool_choice = tool_choice,chat_template_kwargs = _reasoning_template_kwargs(llama_backend, enable_thinking, reasoning_effort, preserve_thinkingdiff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.pyindex 245e2d04530..32ef0e0a16a 100644--- a/studio/backend/tests/test_anthropic_messages.py+++ b/studio/backend/tests/test_anthropic_messages.py@@ -1776,12 +1776,15 @@ class TestAnthropicPassthroughStreamAdapter:16,"msg_1","test-model",+ seed = 3407,)return await self._collect(response)lines = asyncio.run(run())assert captured["body"]["stream_options"] == {"include_usage": True}+ assert captured["body"]["seed"] == 3407+ assert captured["body"]["cache_prompt"] is Falsemessage_delta = self._payloads(lines, "message_delta")[0]assert message_delta["usage"]["input_tokens"] == 2assert message_delta["usage"]["output_tokens"] == 4@@ -2306,6 +2309,61 @@ class TestAnthropicMessagesToolRouting:"content": "The current date is 2026-08-15.",}+ @pytest.mark.parametrize(+ ("extra", "expected_path"),+ [+ ({}, "plain"),+ ({"enable_tools": True, "permission_mode": "off"}, "tools"),+ ],+ ids = ["plain", "server-tools"],+ )+ def test_seed_reaches_internal_anthropic_generation(self, monkeypatch, extra, expected_path):+ backend = _mock_backend(monkeypatch)++ _drive(+ anthropic_messages(+ _basic_payload(seed = 3407, **extra),+ request = self._Request(),+ current_subject = "t",+ )+ )++ [(path, kwargs)] = backend.calls+ assert path == expected_path+ assert kwargs["seed"] == 3407++ @pytest.mark.parametrize("stream", [False, True])+ def test_seed_reaches_anthropic_client_tool_passthrough(self, monkeypatch, stream):+ import routes.inference as inf_mod+ from fastapi.responses import JSONResponse++ _mock_backend(monkeypatch)+ captured = {}++ async def _passthrough(*args, **kwargs):+ captured.update(kwargs)+ return JSONResponse({"type": "message", "content": []})++ helper = (+ "_anthropic_passthrough_stream" if stream else "_anthropic_passthrough_non_streaming"+ )+ monkeypatch.setattr(inf_mod, helper, _passthrough)+ payload = _basic_payload(+ seed = 3407,+ stream = stream,+ tools = [+ {+ "name": "lookup",+ "description": "Look something up",+ "input_schema": {"type": "object"},+ }+ ],+ )++ _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))++ assert captured["seed"] == 3407+def test_plain_non_streaming_records_api_monitor_entry(self, monkeypatch):import routes.inference as inf_moddiff --git a/studio/backend/tests/test_install_resolve_prebuilt.py b/studio/backend/tests/test_install_resolve_prebuilt.pyindex 619d6c56597..5989188b847 100644--- a/studio/backend/tests/test_install_resolve_prebuilt.py+++ b/studio/backend/tests/test_install_resolve_prebuilt.py@@ -484,7 +484,9 @@ def test_fork_linux_intel_prefers_published_vulkan_bundle():)assert [attempt.install_kind for attempt in attempts] == ["linux-vulkan", "linux-cpu"]assert attempts[0].source_label == "published"- assert ["llama-diffusion-gemma-visual-server"] in ilp.runtime_payload_health_groups(attempts[0])+ assert ["llama-diffusion-gemma-visual-server"] in ilp.runtime_payload_health_groups(+ attempts[0].install_kind, source_label = attempts[0].source_label+ )def test_fork_linux_arm64_does_not_select_x64_vulkan_bundle():@@ -532,7 +534,7 @@ def test_fork_windows_intel_prefers_published_vulkan_bundle():assert [attempt.install_kind for attempt in attempts] == ["windows-vulkan", "windows-cpu"]assert attempts[0].source_label == "published"assert ["llama-diffusion-gemma-visual-server.exe"] in ilp.runtime_payload_health_groups(- attempts[0]+ attempts[0].install_kind, source_label = attempts[0].source_label)@@ -547,7 +549,7 @@ def test_linux_vulkan_health_glob_matches_bare_cpu_lib():source_label = "upstream",install_kind = "linux-vulkan",)- groups = ilp.runtime_payload_health_groups(choice)+ groups = ilp.runtime_payload_health_groups(choice.install_kind)assert ["libggml-cpu*.so*"] in groupsassert ["libggml-cpu-*.so*"] not in groupsdiff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.pyindex 2a7e88afeb9..6a3779b7fc5 100644--- a/studio/backend/tests/test_llama_cpp_tool_loop.py+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py@@ -177,6 +177,65 @@ def test_plain_stream_reports_request_scoped_live_prompt_and_generation_timings(assert samples[-1]["predicted_per_second"] == 200+def test_plain_fixed_seed_disables_slot_prompt_cache_reuse(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_sse({"content": "seeded"}), _done()]],+ payloads,+ )++ list(+ backend.generate_chat_completion(+ messages = [{"role": "user", "content": "repeat this"}],+ seed = 3407,+ )+ )++ assert payloads[0]["seed"] == 3407+ assert payloads[0]["cache_prompt"] is False+++def test_the_uint32_random_seed_sentinel_also_keeps_cache_reuse(monkeypatch):+ """llama.h defines LLAMA_DEFAULT_SEED as 0xFFFFFFFF and the seed is read as uint32, so+ 4294967295 is the same "pick one at random" as -1 and must keep prompt-cache reuse."""+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_sse({"content": "random"}), _done()]],+ payloads,+ )++ list(+ backend.generate_chat_completion(+ messages = [{"role": "user", "content": "vary this"}],+ seed = 0xFFFFFFFF,+ )+ )++ assert payloads[0]["seed"] == 0xFFFFFFFF+ assert "cache_prompt" not in payloads[0]+++def test_plain_random_seed_sentinel_keeps_slot_prompt_cache_reuse(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_sse({"content": "random"}), _done()]],+ payloads,+ )++ list(+ backend.generate_chat_completion(+ messages = [{"role": "user", "content": "vary this"}],+ seed = -1,+ )+ )++ assert payloads[0]["seed"] == -1+ assert "cache_prompt" not in payloads[0]++def test_tool_stream_reports_progress_without_leaking_a_content_event(monkeypatch):stream = [_progress(processed = 512, cached = 0, time_ms = 64),diff --git a/studio/backend/tests/test_llama_cpp_update.py b/studio/backend/tests/test_llama_cpp_update.pyindex 662ce431fd9..50b99d32594 100644--- a/studio/backend/tests/test_llama_cpp_update.py+++ b/studio/backend/tests/test_llama_cpp_update.py@@ -593,6 +593,43 @@ def test_start_update_reports_full_release_tag(monkeypatch, tmp_path):assert "Updated llama.cpp to b9596-mix-e6f2453." in job["message"]+def test_an_update_that_kept_the_existing_install_does_not_claim_a_new_release(+ monkeypatch, tmp_path+):+ """Exit 0 no longer implies the release changed.++ The installer answers a transient failure by keeping the tree on disk and+ exiting 0, so "Updated llama.cpp to <tag>" would name the release the user+ already had. The phase only starts when a newer release was offered, so+ reporting the kept release as current would be just as wrong: the update is+ still pending and the user has to retry.+ """+ install_dir = tmp_path / "llama.cpp"+ binary = _write_install(install_dir, "b9595", release_tag = "b9595-mix-aaaaaaa")+ monkeypatch.setattr(upd, "_find_binary", lambda: binary)+ monkeypatch.setattr(upd, "_installer_script", lambda: tmp_path / "install_llama_prebuilt.py")+ monkeypatch.setattr(+ freshness,+ "_fetch_latest_release_tag",+ lambda repo, timeout = 5.0: "b9596-mix-e6f2453",+ )++ # macOS is the reachable case: start_update passes no pin there, so the pinned-tag+ # mismatch guard that catches this elsewhere does not run.+ monkeypatch.setattr(upd.sys, "platform", "darwin")++ # Exit 0 having changed nothing, which is what the keep path does.+ _patch_installer_popen(monkeypatch, on_start = lambda cmd: None)++ job = _run_start_update_to_completion()+ assert job["state"] == "success", job+ assert job["to_tag"] == "b9595-mix-aaaaaaa"+ assert "Updated llama.cpp to" not in job["message"], job["message"]+ assert "up to date" not in job["message"], job["message"]+ assert "could not be updated" in job["message"], job["message"]+ assert "Try again later" in job["message"], job["message"]++def _run_start_update_to_completion():res = upd.start_update()assert res["started"] is Truediff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.pyindex 68a0a48894a..eca55599070 100644--- a/studio/backend/tests/test_openai_tool_passthrough.py+++ b/studio/backend/tests/test_openai_tool_passthrough.py@@ -2447,6 +2447,17 @@ class TestBuildPassthroughPayloadToolChoice:)assert body.get("stream_options") == {"include_usage": False}+ def test_an_explicit_seed_disables_slot_prompt_cache_reuse(self):+ seeded = _build_passthrough_payload(**self._args(), seed = 3407)+ randomized = _build_passthrough_payload(**self._args(), seed = -1)+ ordinary = _build_passthrough_payload(**self._args())++ assert seeded["seed"] == 3407+ assert seeded["cache_prompt"] is False+ assert randomized["seed"] == -1+ assert "cache_prompt" not in randomized+ assert "cache_prompt" not in ordinary+def test_response_format_without_tools_omits_tool_fields(self):args = self._args()args["openai_tools"] = None@@ -5823,10 +5834,10 @@ class TestApiMonitorProviderAndCompletionStreams:"chatcmpl-test",monitor_id = monitor_id,),- timeout = 0.2,+ timeout = 5.0,)- first = await asyncio.wait_for(response.body_iterator.__anext__(), timeout = 0.2)+ first = await asyncio.wait_for(response.body_iterator.__anext__(), timeout = 5.0)assert first == ": keep-alive\n\n"gate.set()@@ -6219,7 +6230,7 @@ class TestApiMonitorProviderAndCompletionStreams:"chatcmpl-test",monitor_id = monitor_id,),- timeout = 0.2,+ timeout = 5.0,)assert isinstance(response, _SameTaskStreamingResponse)@@ -8782,12 +8793,12 @@ class TestApiMonitorProviderAndCompletionStreams:current_subject = "test",))- await asyncio.wait_for(client.started.wait(), 0.2)+ await asyncio.wait_for(client.started.wait(), 5.0)assert cancel_id in inf_mod._CANCEL_REGISTRYassert inf_mod._cancel_by_cancel_id_or_stash(cancel_id) == 1with pytest.raises(asyncio.CancelledError):- await asyncio.wait_for(task, 0.5)+ await asyncio.wait_for(task, 5.0)assert client.closed.is_set()assert cancel_id not in inf_mod._CANCEL_REGISTRY@@ -10285,3 +10296,36 @@ def test_every_gguf_choice_gets_a_seed_of_its_own():# Choice 0 is always the caller's own seed, on both drains.assert _choice_seed(-2, 0, negative_is_random = True) == -2assert _choice_seed(None, 2, negative_is_random = True) is None+++def test_the_two_seed_helpers_agree_on_which_seeds_are_random():+ """``-1`` is not the only request seed that reaches LLAMA_DEFAULT_SEED.++ The seed is a uint32 there, so ``-1``, ``4294967295`` and ``2**64-1`` are all+ the sentinel and all draw at random; the schemas accept all three. Both+ helpers must agree, or one request disagrees with itself: choice 0 keeps the+ caller's random seed while choice 1 is offset into a fixed one, so half the+ choices are reproducible and only half disable prompt caching.+ """+ from core.inference.llama_cpp import _LLAMA_RANDOM_SEED, _apply_seeded_llama_request+ from routes.inference import _choice_seed++ for seed in (-1, 0xFFFFFFFF, 2**64 - 1):+ served = [_choice_seed(seed, i, negative_is_random = True) for i in range(3)]+ assert all((v & 0xFFFFFFFF) == _LLAMA_RANDOM_SEED for v in served), (seed, served)++ # And the cache policy must reach the same verdict for every choice.+ for value in served:+ payload: dict = {}+ _apply_seeded_llama_request(payload, value)+ assert "cache_prompt" not in payload, (seed, value, payload)++ # The converse: a fixed seed stays fixed for every choice, and every choice+ # turns the cache off.+ for seed in (0, 5, 4294967294):+ served = [_choice_seed(seed, i, negative_is_random = True) for i in range(3)]+ assert all((v & 0xFFFFFFFF) != _LLAMA_RANDOM_SEED for v in served), (seed, served)+ for value in served:+ payload = {}+ _apply_seeded_llama_request(payload, value)+ assert payload["cache_prompt"] is False, (seed, value)diff --git a/studio/backend/tests/test_responses_tool_passthrough.py b/studio/backend/tests/test_responses_tool_passthrough.pyindex 68aa0c356a4..05b517b3ff3 100644--- a/studio/backend/tests/test_responses_tool_passthrough.py+++ b/studio/backend/tests/test_responses_tool_passthrough.py@@ -65,6 +65,7 @@ from routes.inference import (_ResponsesReasoningExtractor,_SameTaskStreamingResponse,_build_chat_request,+ _build_openai_passthrough_body,_chat_tool_calls_to_responses_output,_extract_response_format,_extract_responses_reasoning,@@ -384,6 +385,17 @@ class TestToolChoiceTranslation:class TestBuildChatRequest:+ def test_seed_reaches_the_llama_passthrough_policy(self):+ payload = ResponsesRequest(input = "hi", seed = 3407)+ messages = [ChatMessage(role = "user", content = "hi")]++ chat_req = _build_chat_request(payload, messages, stream = True)+ body = _build_openai_passthrough_body(chat_req, backend_ctx = 4096)++ assert chat_req.seed == 3407+ assert body["seed"] == 3407+ assert body["cache_prompt"] is False+def test_parallel_tool_calls_false_is_preserved_for_passthrough_caps(self):payload = ResponsesRequest(input = "hi",diff --git a/studio/backend/utils/llama_cpp_update.py b/studio/backend/utils/llama_cpp_update.pyindex 55bd46f0d96..156294fb49d 100644--- a/studio/backend/utils/llama_cpp_update.py+++ b/studio/backend/utils/llama_cpp_update.py@@ -613,6 +613,12 @@ def _run_llama_phase(backend = Nonemodel_was_active = Falsemtmd_guard = ExitStack()+ # The installer now exits 0 for a transient failure it answered by keeping the+ # existing tree, so success no longer implies the release changed. Read the same way+ # as the post-install check so the two tags compare. Mainly a macOS case: the update+ # path passes no pin there, so it does not disqualify itself from the keep branch.+ prior_marker = read_install_marker(_find_binary())+ prior_tag = (prior_marker or {}).get("release_tag") or (prior_marker or {}).get("tag")try:# Block loads and free the binary while the installer swaps it.try:@@ -716,17 +722,33 @@ def _run_llama_phase(f"{new_backend or 'an unknown backend'}")- logger.info("llama update: success", to_tag = new_tag, backend = new_backend)+ kept_existing = backend_request is None and new_tag is not None and new_tag == prior_tag+ logger.info(+ "llama update: success",+ to_tag = new_tag,+ backend = new_backend,+ kept_existing = kept_existing,+ )reload_hint = " Reload your model to use it." if model_was_active else ""+ if backend_request is not None:+ message = f"llama.cpp is now running on {new_backend or backend_request}.{reload_hint}"+ elif kept_existing:+ # The phase only runs when a newer release was offered, so this is a failed+ # update the installer answered by keeping the tree, not a current install.+ # Naming the old release either way sends the user looking for a fix that+ # shipped in the new one.+ message = (+ f"llama.cpp could not be updated right now, so the existing {new_tag} "+ "install was kept. Try again later."+ )+ else:+ message = f"Updated llama.cpp to {new_tag}.{reload_hint}"return {"to_tag": new_tag,"backend": new_backend,"reload_required": model_was_active,- "message": (- f"llama.cpp is now running on {new_backend or backend_request}.{reload_hint}"- if backend_request is not None- else f"Updated llama.cpp to {new_tag}.{reload_hint}"- ),+ "kept_existing": kept_existing,+ "message": message,}except _flow.InstallerExit as exc:# Raw "installer exited 4: <log tail>" says nothing actionable in the UI.diff --git a/studio/frontend/src/features/chat/mcp-composer-button.tsx b/studio/frontend/src/features/chat/mcp-composer-button.tsxindex 1fd89b5503b..57fd9784af5 100644--- a/studio/frontend/src/features/chat/mcp-composer-button.tsx+++ b/studio/frontend/src/features/chat/mcp-composer-button.tsx@@ -192,7 +192,7 @@ export function McpComposerButton({(s) => !PRESET_URLS.has(normalizeMcpUrl(s.url)),);const enabledCount = servers.filter((s) => s.is_enabled).length;- const active = mcpEnabledForChat && enabledCount > 0;+ const active = usable && mcpEnabledForChat && enabledCount > 0;async function toggleServer(args: {url: string;@@ -241,9 +241,7 @@ export function McpComposerButton({}}- // One dropdown row. Enabled rows get a green underlay and a tick that becomes- // an X on hover (click removes). The hint tooltip anchor is pointer-events-none- // so the row stays clickable (a Radix TooltipTrigger would swallow the select).+ // Keep the tooltip anchor pointer-events-none so it cannot swallow row clicks.const renderRow = (opts: {key: string;label: string;@@ -256,6 +254,7 @@ export function McpComposerButton({}) => (<DropdownMenuItemkey={opts.key}+ // Server configuration remains available when the loaded model lacks tools.disabled={!serversLoaded || pendingUrls.has(normalizeMcpUrl(opts.url))}onSelect={(e) => {e.preventDefault();@@ -297,147 +296,118 @@ export function McpComposerButton({return (<>- {usable ? (- <DropdownMenu- open={menuOpen}- onOpenChange={(open) => {- setMenuOpen(open);- if (open) void refresh();- }}- >- <DropdownMenuTrigger asChild={true}>- <button- type="button"- className="composer-pill-btn"- data-pill-label="MCP"- data-active={active ? "true" : "false"}- aria-label="MCP servers"- >- {/* Icon doubles as an off switch: hover swaps to an X; clicking- it turns MCP off without opening the menu. In compact- icon-only mode the glyph is the whole button, so clicks fall- through to the trigger and open the menu instead. */}- <span- role="button"- aria-label="Turn off MCP"- tabIndex={-1}- onPointerDown={(e) => {- if (e.currentTarget.closest('[data-pill-compact="true"]'))- return;- e.stopPropagation();- }}- onClick={(e) => {- if (e.currentTarget.closest('[data-pill-compact="true"]'))- return;- e.stopPropagation();- setMcpEnabledForChat(false);- }}- className="composer-pill-glyph cursor-pointer"- >- <HugeiconsIcon- icon={McpServerIcon}- className="size-[15px]"- strokeWidth={2}- />- <XIcon className="composer-pill-x" />- </span>- <span>MCP</span>- <ArrowDownStandardIcon className="composer-pill-caret size-[15px]" />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent- side={side}- align="start"- sideOffset={0}- avoidCollisions={true}- className="unsloth-plus-menu mcp-menu w-[232px]"+ <DropdownMenu+ open={menuOpen}+ onOpenChange={(open) => {+ setMenuOpen(open);+ if (open) void refresh();+ }}+ >+ <DropdownMenuTrigger asChild={true}>+ <button+ type="button"+ className={`composer-pill-btn ${usable ? "" : "opacity-40"}`}+ data-pill-label="MCP"+ data-active={active ? "true" : "false"}+ aria-label={+ usable+ ? "MCP servers"+ : "MCP servers, unavailable for the loaded model"+ }>- <DropdownMenuLabel>MCP Servers</DropdownMenuLabel>- {MCP_PRESETS.map((preset) => {- const norm = normalizeMcpUrl(preset.url);- return renderRow({- key: preset.id,- label: preset.label ?? preset.displayName,- url: preset.url,- displayName: preset.displayName,- enabled: enabledUrls.has(norm),- existing: servers.find((s) => normalizeMcpUrl(s.url) === norm),- hint: preset.hint,- disablesWebSearch: preset.disablesWebSearch,- });- })}- {customServers.length > 0 ? <DropdownMenuSeparator /> : null}- {customServers.map((server) =>- renderRow({- key: server.id,- label: server.display_name,- url: server.url,- displayName: server.display_name,- enabled: server.is_enabled,- existing: server,- }),- )}- <DropdownMenuSeparator />- <DropdownMenuItem- onSelect={() => {- setMenuOpen(false);- setDialogOpen(true);+ {/* Outside compact mode, the hover X disables MCP without opening the menu. */}+ <span+ role="button"+ aria-label="Turn off MCP"+ tabIndex={-1}+ onPointerDown={(e) => {+ if (e.currentTarget.closest('[data-pill-compact="true"]'))+ return;+ e.stopPropagation();}}- >- Manage MCP servers- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- ) : (- <Tooltip>- <TooltipTrigger asChild={true}>- {/* Not disabled, so the tooltip still fires on hover. */}- <button- type="button"- className="composer-pill-btn cursor-not-allowed opacity-40"- data-active="false"- aria-disabled={true}- aria-label="MCP servers"+ onClick={(e) => {+ if (e.currentTarget.closest('[data-pill-compact="true"]'))+ return;+ e.stopPropagation();+ setMcpEnabledForChat(false);+ }}+ className="composer-pill-glyph cursor-pointer"><HugeiconsIconicon={McpServerIcon}className="size-[15px]"strokeWidth={2}/>- <span>MCP</span>- </button>- </TooltipTrigger>- <TooltipContent>- MCP works with local tool-capable models- </TooltipContent>- </Tooltip>- )}+ <XIcon className="composer-pill-x" />+ </span>+ <span>MCP</span>+ <ArrowDownStandardIcon className="composer-pill-caret size-[15px]" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ side={side}+ align="start"+ sideOffset={0}+ avoidCollisions={true}+ className="unsloth-plus-menu mcp-menu w-[232px]"+ >+ <DropdownMenuLabel>MCP Servers</DropdownMenuLabel>+ {usable ? null : (+ <DropdownMenuLabel className="text-muted-foreground text-xs font-normal">+ The loaded model cannot use MCP tools+ </DropdownMenuLabel>+ )}+ {MCP_PRESETS.map((preset) => {+ const norm = normalizeMcpUrl(preset.url);+ return renderRow({+ key: preset.id,+ label: preset.label ?? preset.displayName,+ url: preset.url,+ displayName: preset.displayName,+ enabled: enabledUrls.has(norm),+ existing: servers.find((s) => normalizeMcpUrl(s.url) === norm),+ hint: preset.hint,+ disablesWebSearch: preset.disablesWebSearch,+ });+ })}+ {customServers.length > 0 ? <DropdownMenuSeparator /> : null}+ {customServers.map((server) =>+ renderRow({+ key: server.id,+ label: server.display_name,+ url: server.url,+ displayName: server.display_name,+ enabled: server.is_enabled,+ existing: server,+ }),+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onSelect={() => {+ setMenuOpen(false);+ setDialogOpen(true);+ }}+ >+ Manage MCP servers+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu></>);}-/**- * The dialog itself, plus the chord that opens it, mounted for the chat rather- * than for the pill above: MCP ships off and the pill only renders once it is- * on, so anything living there is out of the shortcut's reach.- */+/** Mount the dialog independently so its shortcut works while MCP is disabled. */export function McpServersDialogMount() {const open = useMcpServersDialogStore((s) => s.open);const setOpen = useMcpServersDialogStore((s) => s.setOpen);- // Not gated on tool support: this is where servers are configured, and a- // model that cannot use them yet is the usual reason to come here.+ // Server configuration does not require tool support from the loaded model.const chatActive = useChatActive();useShortcut("openMcpServers", () => setOpen(true), { enabled: chatActive });- // Leaving the chat closes it for good rather than parking it: the flag- // outlives this subtree, so a dialog left open would come back on the next- // visit as a ghost of the last one.+ // Clear the shared open state when leaving chat.useEffect(() => {if (!chatActive && open) setOpen(false);}, [chatActive, open, setOpen]);- // Going off-route is not the only way to leave. Logout, or a session that- // expires, moves the root to /login and takes this whole subtree with it, so- // no chatActive=false render ever happens and the flag above survives to- // reopen the dialog on the next visit. Close on the way out as well.+ // Also clear it when logout or expiry unmounts this subtree directly.useEffect(() => {return () => useMcpServersDialogStore.getState().setOpen(false);}, []);diff --git a/studio/frontend/tests/mcp-server-arguments.test.ts b/studio/frontend/tests/mcp-server-arguments.test.tsindex 3fc20f02044..02d634e2d60 100644--- a/studio/frontend/tests/mcp-server-arguments.test.ts+++ b/studio/frontend/tests/mcp-server-arguments.test.ts@@ -375,7 +375,23 @@ test("composer applies mutation responses before releasing each preset", () => {);assert.match(composer,- /disabled=\{\s*!serversLoaded \|\| pendingUrls\.has\(normalizeMcpUrl\(opts\.url\)\)/,+ /disabled=\{!serversLoaded \|\| pendingUrls\.has\(normalizeMcpUrl\(opts\.url\)\)\}/,+ );+});++test("MCP configuration remains reachable when the loaded model lacks tools", () => {+ const composer = readFileSync(+ new URL("../src/features/chat/mcp-composer-button.tsx", import.meta.url),+ "utf8",+ );++ assert.doesNotMatch(composer, /aria-disabled=\{true\}/);+ assert.match(composer, /The loaded model cannot use MCP tools/);+ // Presets remain configurable without a loaded model.+ assert.doesNotMatch(composer, /disabled=\{[^}]*!usable/);+ assert.match(+ composer,+ /<DropdownMenuItem\s+onSelect=\{\(\) => \{\s*setMenuOpen\(false\);\s*setDialogOpen\(true\);/,);});diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex 401642953e7..d45a96d28fe 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -60,6 +60,7 @@ from backend.utils.prebuilt.llama_backend import ( # noqa: E402environment_backend_override,install_kinds_for_backend,is_requestable_backend,+ marker_backend,marker_backend_request,normalize_backend_request,)@@ -6466,6 +6467,8 @@ def write_prebuilt_metadata(# the arch, and a stale copy would outlive its GPU.**({"rocm_gfx": rocm_gfx} if rocm_gfx and _persisted_backend == "auto" else {}),"asset_sha256": choice.expected_sha256,+ # Records whether this install includes the paired Windows cudart archive.+ "runtime_asset": choice.runtime_name,"source": choice.source_label,# Binary-side repo/tag for non-fork sources (e.g. the ggml-org upstream# CPU/HIP prebuilts). published_repo/release_tag always refer to the@@ -6632,6 +6635,12 @@ def _marker_selection_patch(sms = [str(s).strip() for s in (choice.supported_sms or []) if str(s).strip()]if sms and marker.get("supported_sms") != sms:patch["supported_sms"] = sms+ # Same shape as the targets above: the paired cudart archive is in the fingerprint but+ # not readable back out of it, so an install predating the field only gains it here.+ # Set, never cleared: reuse requires a fingerprint match, so a bundle with no pair is+ # one the marker already describes as pair-less.+ if choice.runtime_name and marker.get("runtime_asset") != choice.runtime_name:+ patch["runtime_asset"] = choice.runtime_namereturn patch@@ -6794,8 +6803,14 @@ def installed_llama_ggml_tree(install_dir: Path | None = None) -> str | None:return tree if isinstance(tree, str) and tree else None-def runtime_payload_health_groups(choice: AssetChoice) -> list[list[str]]:- if choice.install_kind in {"linux-cpu", "linux-arm64"}:+def runtime_payload_health_groups(+ install_kind: str,+ *,+ source_label: str | None = None,+ runtime_name: str | None = None,+) -> list[list[str]]:+ """Return required runtime file groups for an install kind."""+ if install_kind in {"linux-cpu", "linux-arm64"}:return [["libllama-common.so*"],["libllama.so*"],@@ -6804,7 +6819,7 @@ def runtime_payload_health_groups(choice: AssetChoice) -> list[list[str]]:["libggml-cpu*.so*"],["libmtmd.so*"],]- if choice.install_kind in {"linux-cuda", "linux-arm64-cuda"}:+ if install_kind in {"linux-cuda", "linux-arm64-cuda"}:return [["libllama-common.so*"],["libllama.so*"],@@ -6814,13 +6829,13 @@ def runtime_payload_health_groups(choice: AssetChoice) -> list[list[str]]:["libmtmd.so*"],["libggml-cuda.so*"],]- if choice.install_kind in {"macos-arm64", "macos-x64"}:+ if install_kind in {"macos-arm64", "macos-x64"}:return [["libllama*.dylib"],["libggml*.dylib"],["libmtmd*.dylib"],]- if choice.install_kind == "linux-rocm":+ if install_kind == "linux-rocm":return [["libllama-common.so*"],["libllama.so*"],@@ -6830,7 +6845,7 @@ def runtime_payload_health_groups(choice: AssetChoice) -> list[list[str]]:["libmtmd.so*"],["libggml-hip.so*"],]- if choice.install_kind == "linux-vulkan":+ if install_kind == "linux-vulkan":groups = [["libllama-common.so*"],["libllama.so*"],@@ -6844,31 +6859,24 @@ def runtime_payload_health_groups(choice: AssetChoice) -> list[list[str]]:["libmtmd.so*"],["libggml-vulkan.so*"],]- if choice.source_label == "published":+ if source_label == "published":groups.append(["llama-diffusion-gemma-visual-server"])return groups- if choice.install_kind in {"windows-cpu", "windows-arm64"}:+ if install_kind in {"windows-cpu", "windows-arm64"}:return [["llama.dll"]]- if choice.install_kind == "windows-cuda":+ if install_kind == "windows-cuda":groups = [["llama.dll"], ["ggml-cuda.dll"]]- # When the cudart bundle was paired in (#5106) require all- # three of its DLLs alongside the main archive's payload.- # install_kind alone is not enough -- legacy installs without- # the cudart pair must still pass the health check on the- # no-pair fallback path, otherwise pair-less builds would loop- # on reinstall forever. The upstream cudart bundle ships- # cudart64_X.dll + cublas64_X.dll + cublasLt64_X.dll; missing- # any one of them still breaks GPU initialisation.- if choice.runtime_name:+ # Require the complete cudart trio only when it was paired with this install.+ if runtime_name:groups.append(["cudart64_*.dll"])groups.append(["cublas64_*.dll"])groups.append(["cublasLt64_*.dll"])return groups- if choice.install_kind in {"windows-hip", "windows-rocm"}:+ if install_kind in {"windows-hip", "windows-rocm"}:return [["llama.dll"], ["*hip*.dll"]]- if choice.install_kind == "windows-vulkan":+ if install_kind == "windows-vulkan":groups = [["llama.dll"], ["ggml-vulkan.dll"]]- if choice.source_label == "published":+ if source_label == "published":groups.append(["llama-diffusion-gemma-visual-server.exe"])return groupsreturn []@@ -6880,11 +6888,11 @@ def install_runtime_dir(install_dir: Path, host: HostInfo) -> Path:return install_dir / "build" / "bin"-def runtime_payload_is_healthy(install_dir: Path, host: HostInfo, choice: AssetChoice) -> bool:+def _runtime_payload_has(install_dir: Path, host: HostInfo, groups: list[list[str]]) -> bool:runtime_dir = install_runtime_dir(install_dir, host)if not runtime_dir.exists():return False- for pattern_group in runtime_payload_health_groups(choice):+ for pattern_group in groups:matched = Falsefor pattern in pattern_group:if any(runtime_dir.glob(pattern)):@@ -6895,6 +6903,145 @@ def runtime_payload_is_healthy(install_dir: Path, host: HostInfo, choice: AssetCreturn True+def runtime_payload_is_healthy(install_dir: Path, host: HostInfo, choice: AssetChoice) -> bool:+ return _runtime_payload_has(+ install_dir,+ host,+ runtime_payload_health_groups(+ choice.install_kind,+ source_label = choice.source_label,+ runtime_name = choice.runtime_name,+ ),+ )+++def _kept_install_payload_is_healthy(install_dir: Path, host: HostInfo) -> bool:+ """Check the payload shared by install kinds allowed by the tree's marker."""+ marker = load_prebuilt_metadata(install_dir)+ backend = marker_backend(marker)+ platform_prefix = "windows-" if host.is_windows else "macos-" if host.is_macos else "linux-"+ kinds = sorted(+ kind for kind in install_kinds_for_backend(backend) if kind.startswith(platform_prefix)+ )+ if not kinds:+ # Unknown markers still owe the payload shared by every kind on this platform.+ kinds = sorted(kind for kind in INSTALL_KIND_BACKENDS if kind.startswith(platform_prefix))+ if not kinds:+ return True+ # A backend can map to multiple kinds, so require only their shared payload.+ runtime_asset = (marker or {}).get("runtime_asset")+ source_label = (marker or {}).get("source")+ shared = set.intersection(+ *(+ {+ tuple(group)+ for group in runtime_payload_health_groups(+ kind, source_label = source_label, runtime_name = runtime_asset+ )+ }+ for kind in kinds+ )+ )+ return _runtime_payload_has(install_dir, host, [list(group) for group in sorted(shared)])+++# Broken image, not something intervening: SIGKILL is absent because it is an OOM.+_BROKEN_IMAGE_SIGNALS = frozenset(+ {signal.SIGSEGV, signal.SIGILL, signal.SIGFPE}+ | ({signal.SIGBUS} if hasattr(signal, "SIGBUS") else set())+)+# Windows' "%1 is not a valid Win32 application", its answer to a corrupt image.+_ERROR_BAD_EXE_FORMAT = 193+# A Windows loader failure is not a signal: CreateProcess succeeds and the process exits+# the NTSTATUS (0xC0000135 missing DLL), which Python reports as a large POSITIVE code.+# Unreachable on POSIX, where an exit status is 0-255, so no host guard is needed.+_NTSTATUS_FAILURE_FLOOR = 0xC0000000+++def _binary_image_runs(+ path: Path,+ install_dir: Path,+ host: HostInfo,+ runtime_line: str | None = None,+) -> bool:+ """Whether the OS will actually start ``path``.++ ``os.access`` asks "may I execute this", not "is this an executable": a truncated file+ keeps its mode bits and ``ldd`` on a non-ELF only says it is not a dynamic executable.+ execve sees it -- measured on Linux, zero-byte and non-ELF both raise ENOEXEC.++ The exit code is NOT the verdict: llama-quantize answers ``--version`` by printing its+ table and exiting non-zero, the same reason ``macos_dyld_load_issues`` reads output. So+ a timeout, a failed spawn or an ordinary non-zero exit all read as healthy, because a+ false positive here spends a source build on a working install.+ """+ try:+ result = run_capture(+ [str(path), "--version"],+ timeout = 60,+ # runtime_line as validate_prebuilt_choice passes it: it is what puts the+ # CUDA toolkit on PATH, and a pair-less Windows install dies 0xC0000135 without it.+ env = binary_env(path, install_dir, host, runtime_line = runtime_line),+ )+ except OSError as exc:+ if exc.errno == errno.ENOEXEC or getattr(exc, "winerror", None) == _ERROR_BAD_EXE_FORMAT:+ log(f"kept install rejected: {path.name} is not an executable image ({exc})")+ return False+ return True+ except Exception:+ return True+ if result.returncode < 0 and -result.returncode in _BROKEN_IMAGE_SIGNALS:+ log(f"kept install rejected: {path.name} died on signal {-result.returncode}")+ return False+ if result.returncode >= _NTSTATUS_FAILURE_FLOOR:+ log(f"kept install rejected: {path.name} exited 0x{result.returncode:08X} (loader failure)")+ return False+ return True+++def _existing_install_runs(install_dir: Path, host: HostInfo) -> bool:+ """Check whether the setup scripts could reuse and run this install."""+ if not _install_tree_is_usable(install_dir, host):+ return False+ if not _kept_install_payload_is_healthy(install_dir, host):+ return False+ recorded_runtime_line = (load_prebuilt_metadata(install_dir) or {}).get("runtime_line")+ if not isinstance(recorded_runtime_line, str):+ recorded_runtime_line = None+ runtime_dir = install_runtime_dir(install_dir, host)+ ext = ".exe" if host.is_windows else ""+ binaries = [runtime_dir / f"llama-{name}{ext}" for name in ("server", "quantize")]+ if not all(os.access(binary, os.X_OK) for binary in binaries):+ return False+ try:+ # Each preflight is a no-op outside its platform.+ preflight_linux_installed_binaries(binaries, install_dir, host)+ preflight_macos_installed_binaries(binaries, install_dir, host)+ except Exception:+ return False+ # Root copies first: _find_llama_server_binary searches <install>/llama-server BEFORE+ # build/bin, so that is what inference launches. resolve() collapses the usual symlink;+ # when symlinking was unavailable it is a separate file that can rot alone.+ probes: list[Path] = []+ seen: set[Path] = set()+ for binary in [install_dir / p.name for p in binaries] + binaries:+ if not binary.exists():+ continue+ try:+ key = binary.resolve()+ except OSError:+ key = binary+ if key in seen:+ continue+ seen.add(key)+ probes.append(binary)+ # Last, because it is the only check that spawns anything: neither preflight runs on+ # Windows, and on Linux ldd cannot see a file that is not an executable image at all.+ return all(+ _binary_image_runs(binary, install_dir, host, recorded_runtime_line) for binary in probes+ )++def existing_install_matches_choice(install_dir: Path,host: HostInfo,@@ -7856,6 +8003,21 @@ def install_prebuilt(instruction_cleanup_root: Path | None = None,) -> None:choice: AssetChoice | None = None+ # Anything this RUN asked for that keeping the old tree would silently ignore. Read+ # from the parameters before the body mutates them (force_cpu becomes True further+ # down for a stored "cpu" choice, which is the opposite of a request made here).+ # backend_mandatory joins it in the handler, because it is only known after the+ # marker is read; it starts False, so a failure before that keeps today's behaviour.+ explicit_version_request = (+ normalized_requested_llama_tag(llama_tag) != "latest"+ or bool((published_release_tag or "").strip())+ or (bool((published_repo or "").strip()) and published_repo != DEFAULT_PUBLISHED_REPO)+ # --cpu-fallback only ever arrives from setup.sh's deliberate arm64 recovery, so+ # it is a mechanism this run chose. --has-rocm and --rocm-gfx are NOT: both setup+ # entrypoints forward their DETECTED GPU on every AMD host, so counting them here+ # would take the keep path away from essentially every AMD update.+ or force_cpu+ )# The failure handler can run before selection assigns these.host: HostInfo | None = Nonebackend = "auto"@@ -8122,6 +8284,26 @@ def install_prebuilt(# A stored choice that could not be served was already replaced by "auto"# above, so a concrete name here is one this run must not walk away from.preserve_backend = backend in CONCRETE_BACKENDS and host is not None and not host.is_macos+ # A stored preference may reuse a matching install. A backend requested on this+ # run must still be satisfied by this run.+ satisfied_stored_backend = (+ preserve_backend+ and not backend_mandatory+ and marker_backend(load_prebuilt_metadata(install_dir)) == backend+ )+ if (+ (not preserve_backend or satisfied_stored_backend)+ and not explicit_version_request+ # A backend named on this run is a live instruction even when it is "auto":+ # that asks for re-detection, and answering it with the tree already on disk+ # leaves both the old backend and its marker exactly as they were.+ and not backend_mandatory+ and host is not None+ and _existing_install_runs(install_dir, host)+ ):+ log("prebuilt update unavailable; keeping the existing complete install")+ log(f"prebuilt update reason: {exc}")+ returnlog("prebuilt install failed; preserving the selected backend"if preserve_backenddiff --git a/studio/setup.ps1 b/studio/setup.ps1index afdf91cf13d..efbbc36bcdc 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -529,10 +529,12 @@ function Test-UnslothCmdShimFile {return ($text -like "*unsloth-studio-managed-launcher*" -and $text -like "*from unsloth_cli import app*")}-# Shared default cache, or the custom Unsloth home's llama.cpp tree.+# Explicit staging root, shared default cache, or the custom Unsloth home's tree.function Get-ManagedLlamaCppDir {- if ($StageRoot) {- return (Join-Path $StageRoot "llama.cpp")+ param([AllowNull()][string]$StagingRoot = $null)++ if ($StagingRoot) {+ return (Join-Path $StagingRoot "llama.cpp")}if (-not (Test-StudioHomeIsCustom)) {return (Join-Path $env:USERPROFILE ".unsloth\llama.cpp")@@ -542,9 +544,11 @@ function Get-ManagedLlamaCppDir {# Failure reason when the managed tree is denied; never touches its ACLs.function Invoke-ManagedLlamaCppPreflight {+ param([AllowNull()][string]$StagingRoot = $null)+# Let the existing profile validation handle a missing USERPROFILE later.if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { return $null }- $dir = Get-ManagedLlamaCppDir+ $dir = Get-ManagedLlamaCppDir -StagingRoot $StagingRootif ((Get-LlamaCppInstallReadState -Path $dir) -ne "Denied") { return $null }Write-StudioLine ""# A denied custom home cannot be claimed as an Unsloth-managed cache.@@ -1970,11 +1974,11 @@ $StudioOwnedMarker = ".unsloth-studio-owned"$NoTorchMarker = ".unsloth-no-torch"$LegacyStudioHome = Join-Path $env:USERPROFILE ".unsloth\studio"$StudioHomeIsCustom = Test-StudioHomeIsCustom-$LlamaCppDir = Get-ManagedLlamaCppDir+$LlamaCppDir = Get-ManagedLlamaCppDir -StagingRoot $StageRoot$UnslothHome = Split-Path -Parent $LlamaCppDir$WithLlamaCppDir = $null-$llamaPreflightFailure = Invoke-ManagedLlamaCppPreflight+$llamaPreflightFailure = Invoke-ManagedLlamaCppPreflight -StagingRoot $StageRootif ($llamaPreflightFailure) {Exit-SetupFailure $llamaPreflightFailure}@@ -6141,6 +6145,11 @@ if ($LocalLlamaCppLinked) {if ($prebuiltExit -eq 0) {if ($prebuiltOutput -match "already matches") {step "llama.cpp" "prebuilt up to date and validated"+ } elseif ($prebuiltOutput -match "keeping the existing complete install") {+ # Exit 0 can also mean the installer kept the tree already on disk after a+ # transient failure. "installed and validated" would name a release nothing+ # fetched.+ step "llama.cpp" "update unavailable, existing prebuilt kept" "Yellow"} else {step "llama.cpp" "prebuilt installed and validated"}diff --git a/studio/setup.sh b/studio/setup.shindex a9056d995ef..8e9ae8410c4 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -2768,6 +2768,11 @@ elseif [ "$_PREBUILT_STATUS" -eq 0 ]; thenif grep -Fq "already matches" "$_PREBUILT_LOG"; thenstep "llama.cpp" "prebuilt up to date and validated"+ elif grep -Fq "keeping the existing complete install" "$_PREBUILT_LOG"; then+ # Exit 0 can also mean the installer kept the tree already on disk after a+ # transient failure. "installed and validated" would name a release nothing+ # fetched.+ step "llama.cpp" "update unavailable, existing prebuilt kept" "$C_WARN"elsestep "llama.cpp" "prebuilt installed and validated"fidiff --git a/tests/python/test_install_python_stack.py b/tests/python/test_install_python_stack.pyindex 69bad6b9f1f..6094cfb7142 100644--- a/tests/python/test_install_python_stack.py+++ b/tests/python/test_install_python_stack.py@@ -416,6 +416,9 @@ class TestSdistOnlyBuildArgs:for name in ips.SDIST_ONLY_PACKAGES:assert name in allow, f"{name} missing from clean-machine-assert.sh nobuild allowlist"assert f"'{name}'" in ps1, f"{name} missing from assert-nobuild.ps1 allowlist"+ # overlay:false releases still need the temporary Diffusers sdist exemption.+ assert "diffusers" in allow+ assert "'diffusers'" in ps1class TestHardenedPipConfigRelaxation:diff --git a/tests/security/test_scan_packages.py b/tests/security/test_scan_packages.pyindex 0fa572d66eb..45e8e1d01f9 100644--- a/tests/security/test_scan_packages.py+++ b/tests/security/test_scan_packages.py@@ -447,6 +447,76 @@ def test_annotation_only_network_entries_are_digest_pinned():assert seen == credential_adjacent, f"missing entries for {credential_adjacent - seen}"+def test_context_dependent_unsloth_zoo_findings_are_digest_pinned():+ """Require a new review when context around an approved finding changes."""+ import json+ import pathlib++ path = pathlib.Path(__file__).resolve().parents[2] / "scripts" / "scan_packages_baseline.json"+ entries = json.loads(path.read_text(encoding = "utf-8"))["entries"]+ expected = {+ (+ "unsloth_zoo/vision_utils.py",+ "Harvests environment variables/secrets AND makes network calls",+ ): "7c6266737b14cb08e136c0fcc5d63dc5047f416daa1fad4f16298a6269b73ce4",+ (+ "unsloth_zoo/vision_utils.py",+ "Accesses cloud metadata/IMDS AND makes network calls",+ ): "7c6266737b14cb08e136c0fcc5d63dc5047f416daa1fad4f16298a6269b73ce4",+ (+ "unsloth_zoo/compiler.py",+ "Advanced obfuscation (marshal/compile/zlib) + exec/eval",+ ): "58f43e3b6ddeefff69cb345baec7642eb10e3f081b0753f236be6571550d54e3",+ }+ actual = {+ (entry["file"], entry["check"]): entry.get("file_sha256")+ for entry in entries+ if entry.get("package") == "unsloth-zoo"+ and (entry.get("file"), entry.get("check")) in expected+ }+ assert actual == expected+++def test_context_dependent_unsloth_zoo_pins_reopen_on_other_file_changes():+ """Unchanged matched lines cannot approve a changed surrounding file."""+ import json+ import pathlib++ path = pathlib.Path(__file__).resolve().parents[2] / "scripts" / "scan_packages_baseline.json"+ entries = json.loads(path.read_text(encoding = "utf-8"))["entries"]+ targets = [+ entry+ for entry in entries+ if entry.get("package") == "unsloth-zoo"+ and entry.get("file") in {"unsloth_zoo/vision_utils.py", "unsloth_zoo/compiler.py"}+ and entry.get("file_sha256")+ ]+ assert len(targets) == 3+ baseline = sp._load_baseline(str(path))+ for entry in targets:+ reviewed = _mk(+ entry["severity"],+ entry["package"],+ entry["file"],+ entry["check"],+ entry["evidence"],+ )+ reviewed.file_sha256 = entry["file_sha256"]+ changed = _mk(+ entry["severity"],+ entry["package"],+ entry["file"],+ entry["check"],+ entry["evidence"],+ )+ changed.file_sha256 = "0" * 64++ active, suppressed = sp._partition_baseline([reviewed], baseline)+ assert active == [] and suppressed == [reviewed]+ active, suppressed = sp._partition_baseline([changed], baseline)+ assert active == [changed] and suppressed == []++def test_the_hf_backoff_suppression_is_narrow():"""The huggingface-hub `http_backoff` allowlist must not cover a second loop.diff --git a/tests/sh/test_setup_staged_root.sh b/tests/sh/test_setup_staged_root.shindex 71b8056ba1a..d54a4aa4538 100755--- a/tests/sh/test_setup_staged_root.sh+++ b/tests/sh/test_setup_staged_root.sh@@ -80,7 +80,7 @@ check "setup.sh does not install global uv while staging" \check "setup.ps1 stages the managed Node runtime" \"$(has "$SETUP_PS1" '$NodeParent = $StageRoot')"check "setup.ps1 stages llama.cpp and whisper.cpp" \- "$(has "$SETUP_PS1" 'return (Join-Path $StageRoot "llama.cpp")')"+ "$(grep -qF 'return (Join-Path $StagingRoot "llama.cpp")' "$SETUP_PS1" && grep -qF '$LlamaCppDir = Get-ManagedLlamaCppDir -StagingRoot $StageRoot' "$SETUP_PS1" && grep -qF '$llamaPreflightFailure = Invoke-ManagedLlamaCppPreflight -StagingRoot $StageRoot' "$SETUP_PS1" && echo 0 || echo 1)"check "setup.ps1 does not persist User PATH while staging" \"$(has "$SETUP_PS1" 'Get-Variable -Name StageRoot -ValueOnly -ErrorAction SilentlyContinue')"check "setup.ps1 leaves vcredist unchanged while staging" \diff --git a/tests/sh/test_studio_home_node_dir.sh b/tests/sh/test_studio_home_node_dir.shindex 2b10915cbdc..9963d08304d 100755--- a/tests/sh/test_studio_home_node_dir.sh+++ b/tests/sh/test_studio_home_node_dir.sh@@ -46,8 +46,10 @@ case "$blockB" in *'NODE_DIR="$_NODE_PARENT/node"'*) : ;; *) echo "FAIL: blockBcase "$blockB" in *'_STUDIO_HOME_IS_CUSTOM'*) : ;; *) echo "FAIL: blockB missed the custom-home branch"; exit 1 ;; esaccase "$blockB" in *'STAGE_ROOT'*) : ;; *) echo "FAIL: blockB missed the staging branch"; exit 1 ;; esac-node_dir_for() { # HOME UNSLOTH_STUDIO_HOME STUDIO_HOME- env -i HOME="$1" UNSLOTH_STUDIO_HOME="$2" STUDIO_HOME="$3" PATH="$PATH" \+# Block A derives STAGE_ROOT from UNSLOTH_STUDIO_STAGE_ROOT.+node_dir_for() { # HOME UNSLOTH_STUDIO_HOME STUDIO_HOME [UNSLOTH_STUDIO_STAGE_ROOT]+ env -i HOME="$1" UNSLOTH_STUDIO_HOME="$2" STUDIO_HOME="$3" \+ UNSLOTH_STUDIO_STAGE_ROOT="${4:-}" PATH="$PATH" \bash -c "$SNIP" 2>/dev/null | tail -1}diff --git a/tests/studio/appimage_model_download_webdriver.py b/tests/studio/appimage_model_download_webdriver.pyindex 46e775e0b14..b492e8d86a0 100644--- a/tests/studio/appimage_model_download_webdriver.py+++ b/tests/studio/appimage_model_download_webdriver.py@@ -212,11 +212,16 @@ def _write_backend_fixture(home: Path, request_log: Path) -> None:self.send_header("Content-Type", "application/json")self.send_header("Content-Length", str(len(raw)))self.send_header("Access-Control-Allow-Origin", "tauri://localhost")- self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-HF-Token")+ self.send_header("Access-Control-Allow-Headers", self.allowed_headers())self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")self.end_headers()self.wfile.write(raw)+ def allowed_headers(self):+ # Echo requested headers so this fixture follows frontend changes.+ asked = self.headers.get("Access-Control-Request-Headers")+ return asked or "Authorization, Content-Type, X-HF-Token"+def do_OPTIONS(self):# Recorded like GET and POST. A preflight the browser rejects means the# real request is never sent, so without this the request log showsdiff --git a/tests/studio/install/test_denied_llama_cpp_preflight.py b/tests/studio/install/test_denied_llama_cpp_preflight.pyindex 5943173ea2e..6379b5a65e6 100644--- a/tests/studio/install/test_denied_llama_cpp_preflight.py+++ b/tests/studio/install/test_denied_llama_cpp_preflight.py@@ -95,6 +95,10 @@ def test_setup_and_the_installer_use_the_same_probe() -> None:assert '$llamaDirState -eq "Denied"' in SETUP_PS1assert '$llamaDirState -eq "Readable"' in SETUP_PS1assert '(Get-LlamaCppInstallReadState -Path $dir) -ne "Denied"' in INSTALL_PS1+ assert (+ "$llamaPreflightFailure = Invoke-ManagedLlamaCppPreflight -StagingRoot $StageRoot"+ in SETUP_PS1+ )def test_the_probe_keeps_all_three_answers() -> None:@@ -239,6 +243,13 @@ def test_a_tree_the_user_pointed_at_is_never_called_a_cache_we_own() -> None:def test_the_managed_path_rule_is_not_duplicated_in_the_installer() -> None:"""Keep managed path selection in one resolver."""resolver = _function_source(INSTALL_PS1, "Get-ManagedLlamaCppDir")+ assert "param([AllowNull()][string]$StagingRoot = $null)" in resolver+ assert 'Join-Path $StagingRoot "llama.cpp"' in resolver+ assert "$StageRoot" not in resolver+ preflight = _function_source(INSTALL_PS1, "Invoke-ManagedLlamaCppPreflight")+ assert "param([AllowNull()][string]$StagingRoot = $null)" in preflight+ assert "Get-ManagedLlamaCppDir -StagingRoot $StagingRoot" in preflight+ assert "$StageRoot" not in preflightassert 'Join-Path $env:USERPROFILE ".unsloth\\llama.cpp"' in resolverassert 'Join-Path (Get-CanonicalDir -Path $StudioHome) "llama.cpp"' in resolverassert INSTALL_PS1.count('Join-Path $StudioHome "llama.cpp"') == 0@@ -265,7 +276,7 @@ def test_both_entrypoints_resolve_and_reuse_the_same_managed_directory() -> None"""Both entrypoints must resolve and reuse one managed path."""assert '$LegacyStudioHome = Join-Path $env:USERPROFILE ".unsloth\\studio"' in SETUP_PS1assert "$StudioHomeIsCustom = Test-StudioHomeIsCustom" in SETUP_PS1- assert SETUP_PS1.count("$LlamaCppDir = Get-ManagedLlamaCppDir") == 1+ assert SETUP_PS1.count("$LlamaCppDir = Get-ManagedLlamaCppDir -StagingRoot $StageRoot") == 1assert "$UnslothHome = Split-Path -Parent $LlamaCppDir" in SETUP_PS1for name in ("Get-CanonicalDir",diff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.pyindex 8ae391e2f74..e5a071ee261 100644--- a/tests/studio/install/test_install_llama_prebuilt_logic.py+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py@@ -3081,6 +3081,93 @@ def test_every_reuse_path_syncs_the_arch_coverage():assert 'patch["mapped_targets"] = targets' in patch[email protected]("visual_server", [True, False], ids = ["present", "missing"])+def test_a_published_bundle_owes_its_visual_server(tmp_path, monkeypatch, visual_server):+ """The marker's source label decides, exactly as it does on the canonical reuse path.++ runtime_payload_health_groups only adds llama-diffusion-gemma-visual-server for a+ published bundle, so omitting the label let an incomplete published Vulkan tree read+ as validated. setup.sh's source build has its own target for the binary, so exit 2 is+ a recovery here rather than a detour.+ """+ _listing_failure(monkeypatch, linux_host)+ install_dir = _complete_existing_llama_install(+ tmp_path, backend = "vulkan", source = "published", visual_server = visual_server+ )++ if visual_server:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")+ else:+ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")+ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+++def test_an_upstream_bundle_does_not_owe_a_visual_server(tmp_path, monkeypatch):+ """Only "published" carries it; requiring it of an upstream tree would source build."""+ _listing_failure(monkeypatch, linux_host)+ install_dir = _complete_existing_llama_install(+ tmp_path, backend = "vulkan", source = "upstream", visual_server = False+ )++ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ assert (install_dir / "llama-server").exists()+++def test_a_reused_install_backfills_the_paired_runtime_asset(tmp_path: Path):+ """An install predating runtime_asset only gains it on the reuse path.++ The pairing is in install_fingerprint, but that is a hash: the kept-install payload+ check reads the field, so without this backfill a paired Windows CUDA tree stays+ "pair-less" forever and its cudart trio is never required.+ """+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"+ marker_path.write_text(+ json.dumps({"release_tag": "release-1", "llama_backend": "auto", "force_cpu": False}),+ encoding = "utf-8",+ )+ choice = AssetChoice(+ repo = "unslothai/llama.cpp",+ tag = "b9002",+ name = "app-b9002-windows-cuda-x64.zip",+ url = "https://example/x",+ source_label = "published",+ install_kind = "windows-cuda",+ runtime_name = "cudart-llama-bin-win-cuda-13.0-x64.zip",+ )++ INSTALL_LLAMA_PREBUILT.sync_marker_selection(install_dir, choice = choice, backend_request = "auto")++ marker = json.loads(marker_path.read_text(encoding = "utf-8"))+ assert marker["runtime_asset"] == "cudart-llama-bin-win-cuda-13.0-x64.zip"+++def test_a_pair_less_reuse_does_not_invent_a_runtime_asset(tmp_path: Path):+ """Set, never cleared: a bundle with no pair is one the marker already describes."""+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"+ marker_path.write_text(+ json.dumps({"release_tag": "release-1", "llama_backend": "auto", "force_cpu": False}),+ encoding = "utf-8",+ )+ choice = AssetChoice(+ repo = "unslothai/llama.cpp",+ tag = "b9002",+ name = "app-b9002-windows-cpu-x64.zip",+ url = "https://example/x",+ source_label = "published",+ install_kind = "windows-cpu",+ )++ INSTALL_LLAMA_PREBUILT.sync_marker_selection(install_dir, choice = choice, backend_request = "auto")++ assert "runtime_asset" not in json.loads(marker_path.read_text(encoding = "utf-8"))++def test_marker_rewrite_preserves_arch_fields(tmp_path: Path):"""A sync that touches other fields must not drop the arch ones (#7624).sync_marker_selection reads the marker, applies a patch and writes the whole dict@@ -5516,6 +5603,472 @@ def test_release_listing_failure_exits_fallback_not_error(tmp_path, monkeypatch,assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+# Shared platform payload plus any files required by a named backend.+_SHARED_PAYLOAD = {+ "linux": [+ "libllama-common.so",+ "libllama.so",+ "libggml.so",+ "libggml-base.so",+ "libggml-cpu.so",+ "libmtmd.so",+ ],+ "windows": ["llama.dll"],+}+_BACKEND_PAYLOAD = {+ ("windows", "cuda"): ["ggml-cuda.dll"],+ ("linux", "vulkan"): ["libggml-vulkan.so"],+}+# Only a published bundle owes this one, which is why the marker's source label has to+# reach runtime_payload_health_groups.+_PUBLISHED_PAYLOAD = {"linux": ["llama-diffusion-gemma-visual-server"]}+++def _complete_existing_llama_install(+ tmp_path,+ *,+ executable = True,+ backend = None,+ payload = True,+ windows = False,+ backend_request = None,+ runtime_asset = None,+ paired_runtime = True,+ runnable = True,+ runnable_root = None,+ runtime_line = None,+ source = None,+ visual_server = True,+):+ install_dir = tmp_path / "llama.cpp"+ runtime_dir = (+ install_dir / "build" / "bin" / "Release" if windows else install_dir / "build" / "bin"+ )+ runtime_dir.mkdir(parents = True)+ ext = ".exe" if windows else ""+ marker = {"release_tag": "old-release", "tag": "old-upstream"}+ if backend is not None:+ marker["backend"] = backend+ if backend_request is not None:+ marker["backend_request"] = backend_request+ if runtime_asset is not None:+ marker["runtime_asset"] = runtime_asset+ if runtime_line is not None:+ marker["runtime_line"] = runtime_line+ if source is not None:+ marker["source"] = source+ for path in (+ install_dir / f"llama-server{ext}",+ install_dir / f"llama-quantize{ext}",+ runtime_dir / f"llama-server{ext}",+ runtime_dir / f"llama-quantize{ext}",+ install_dir / "convert_hf_to_gguf.py",+ install_dir / "gguf-py",+ install_dir / "UNSLOTH_PREBUILT_INFO.json",+ ):+ if path.name == "gguf-py":+ path.mkdir()+ elif path.name == "UNSLOTH_PREBUILT_INFO.json":+ path.write_text(json.dumps(marker) + "\n", encoding = "utf-8")+ elif path.name.startswith("llama-"):+ # The root copy is what _find_llama_server_binary reaches first, and it can+ # rot alone when symlinking was unavailable.+ ok = (+ runnable+ if path.parent != install_dir+ else (runnable if runnable_root is None else runnable_root)+ )+ # A runnable stub, not an empty file: the kept-install check execs these, and+ # a zero-byte file that kept its mode bits is the ENOEXEC case below.+ path.write_text("#!/bin/sh\nexit 0\n" if ok else "", encoding = "utf-8")+ # Match setup.sh's executable reuse gate.+ os.chmod(path, 0o755 if executable else 0o644)+ else:+ path.write_text("", encoding = "utf-8")+ os.chmod(path, 0o755 if executable else 0o644)+ platform = "windows" if windows else "linux"+ if payload:+ # Complete installs always carry the shared platform payload.+ for name in _SHARED_PAYLOAD[platform]:+ (runtime_dir / name).write_text("", encoding = "utf-8")+ for name in _BACKEND_PAYLOAD.get((platform, backend), ()):+ (runtime_dir / name).write_text("", encoding = "utf-8")+ if source == "published" and visual_server:+ for name in _PUBLISHED_PAYLOAD[platform]:+ (runtime_dir / name).write_text("", encoding = "utf-8")+ if runtime_asset is not None and paired_runtime:+ for name in ("cudart64_13.dll", "cublas64_13.dll", "cublasLt64_13.dll"):+ (runtime_dir / name).write_text("", encoding = "utf-8")+ return install_dir+++def test_release_listing_failure_keeps_a_complete_existing_install(tmp_path, monkeypatch):+ """An unpinned transient update failure must keep a complete local runtime."""++ def boom(*args, **kwargs):+ raise urllib.error.URLError("connection reset")++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)++ install_dir = _complete_existing_llama_install(tmp_path)++ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ assert (install_dir / "llama-server").exists()+++def test_release_listing_failure_does_not_keep_a_non_executable_install(tmp_path, monkeypatch):+ """Do not keep a tree that fails setup.sh's executable reuse gate."""++ def boom(*args, **kwargs):+ raise urllib.error.URLError("connection reset")++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")++ install_dir = _complete_existing_llama_install(tmp_path, executable = False)++ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+ assert (install_dir / "llama-server").exists()+++def _windows_host() -> HostInfo:+ return HostInfo(+ system = "Windows",+ machine = "AMD64",+ is_windows = True,+ is_linux = False,+ is_macos = False,+ is_x86_64 = True,+ is_arm64 = False,+ nvidia_smi = None,+ driver_cuda_version = None,+ compute_caps = [],+ visible_cuda_devices = None,+ has_physical_nvidia = False,+ has_usable_nvidia = False,+ )+++ ("windows", "host", "backend"),+ [+ (False, linux_host, "cpu"),+ (True, _windows_host, "cuda"),+ ],+ ids = ["linux", "windows"],+)+def test_release_listing_failure_does_not_keep_a_gutted_runtime(+ tmp_path, monkeypatch, windows, host, backend+):+ """Do not keep a tree that has lost its runtime payload."""++ def boom(*args, **kwargs):+ raise urllib.error.URLError("connection reset")++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", host)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")++ kept = _complete_existing_llama_install(tmp_path / "kept", backend = backend, windows = windows)+ install_prebuilt(kept, "latest", "unslothai/llama.cpp", "")++ gutted = _complete_existing_llama_install(+ tmp_path / "gutted", backend = backend, payload = False, windows = windows+ )+ with pytest.raises(SystemExit) as caught:+ install_prebuilt(gutted, "latest", "unslothai/llama.cpp", "")++ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+++def _listing_failure(monkeypatch, host):+ def boom(*args, **kwargs):+ raise urllib.error.URLError("connection reset")++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", host)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")+++ ("runtime_asset", "paired_runtime", "kept"),+ [+ ("cudart-llama-bin-win-cuda-13.0-x64.zip", True, True),+ ("cudart-llama-bin-win-cuda-13.0-x64.zip", False, False),+ (None, False, True),+ ],+ ids = ["paired-intact", "paired-gutted", "pair-less"],+)+def test_a_paired_cuda_install_needs_its_cudart_trio(+ tmp_path, monkeypatch, runtime_asset, paired_runtime, kept+):+ """Require the cudart trio only from installs that recorded the paired archive."""+ _listing_failure(monkeypatch, _windows_host)+ install_dir = _complete_existing_llama_install(+ tmp_path,+ backend = "cuda",+ windows = True,+ runtime_asset = runtime_asset,+ paired_runtime = paired_runtime,+ )++ if kept:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")+ else:+ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")+ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+++ ("windows", "host"),+ [(True, _windows_host), (False, linux_host)],+ ids = ["windows", "linux"],+)[email protected]("payload", [True, False], ids = ["intact", "gutted"])+def test_a_marker_that_names_no_backend_still_owes_the_shared_payload(+ tmp_path, monkeypatch, windows, host, payload+):+ """Unknown markers still require the platform's shared payload."""+ _listing_failure(monkeypatch, host)+ install_dir = _complete_existing_llama_install(tmp_path, windows = windows, payload = payload)++ if payload:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")+ else:+ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")+ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+++def test_a_stored_backend_choice_the_install_already_satisfies_is_kept(tmp_path, monkeypatch):+ """Keep a working install that already satisfies its recorded backend."""+ _listing_failure(monkeypatch, linux_host)+ install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu", backend_request = "cpu")++ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ assert (install_dir / "llama-server").exists()+++def test_a_backend_named_on_this_run_still_refuses_to_answer_with_the_old_install(+ tmp_path, monkeypatch+):+ """backend_mandatory is a live instruction, not a stored preference."""+ _listing_failure(monkeypatch, linux_host)+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_BACKEND", "cpu")+ install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu", backend_request = "cpu")++ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_BACKEND_UNAVAILABLE+++def test_a_stored_backend_the_install_does_not_run_is_not_answered_with_it(tmp_path, monkeypatch):+ """A recorded request the tree does not satisfy is still exit 5, never a source build."""+ _listing_failure(monkeypatch, linux_host)+ install_dir = _complete_existing_llama_install(+ tmp_path, backend = "cpu", backend_request = "vulkan"+ )++ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_BACKEND_UNAVAILABLE+++ ("windows", "host"),+ [(True, _windows_host), (False, linux_host)],+ ids = ["windows", "linux"],+)+def test_release_listing_failure_does_not_keep_a_corrupt_binary(+ tmp_path, monkeypatch, windows, host+):+ """A truncated llama-server keeps its mode bits, so os.access says yes and ldd on a+ non-ELF finds nothing. On Windows neither preflight runs at all. execve sees it."""+ _listing_failure(monkeypatch, host)+ install_dir = _complete_existing_llama_install(+ tmp_path, windows = windows, backend = "cuda" if windows else "cpu", runnable = False+ )+ ext = ".exe" if windows else ""+ runtime = install_dir / "build" / "bin" / ("Release" if windows else "")+ assert os.access(runtime / f"llama-server{ext}", os.X_OK), "the mode bits must survive"++ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+++def test_a_rotten_root_entrypoint_is_not_saved_by_a_healthy_build_bin(tmp_path, monkeypatch):+ """_find_llama_server_binary searches <install>/llama-server before build/bin, so the+ root copy is what runs; without a symlink it is a separate file that can rot alone."""+ _listing_failure(monkeypatch, linux_host)+ install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu", runnable_root = False)+ assert os.access(install_dir / "build" / "bin" / "llama-server", os.X_OK)++ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+++def test_a_windows_loader_status_is_not_a_successful_probe(tmp_path, monkeypatch):+ """A missing DLL exits 0xC0000135, which Python reports POSITIVE, so "not negative"+ reads it as healthy. The payload groups cannot cover it: windows-cpu is only llama.dll."""+ _listing_failure(monkeypatch, _windows_host)+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "run_capture",+ lambda *a, **k: subprocess.CompletedProcess(a[0] if a else [], 0xC0000135, "", ""),+ )+ install_dir = _complete_existing_llama_install(tmp_path, backend = "cuda", windows = True)++ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+++ "kwargs",+ [{"llama_backend": "auto"}, {"force_cpu": True}],+ ids = ["backend-auto", "cpu-fallback"],+)+def test_a_selection_named_on_this_run_is_not_answered_with_the_old_install(+ tmp_path, monkeypatch, kwargs+):+ """ "auto" asks to re-detect; answering it with the old tree leaves the backend and its+ marker untouched while reporting success."""+ _listing_failure(monkeypatch, linux_host)+ install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu", backend_request = "cpu")++ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "", **kwargs)++ assert caught.value.code in (+ INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK,+ INSTALL_LLAMA_PREBUILT.EXIT_BACKEND_UNAVAILABLE,+ )+++ "kwargs",+ [{"override_has_rocm": True}, {"override_rocm_gfx": "gfx1151"}],+ ids = ["has-rocm", "rocm-gfx"],+)+def test_forwarded_gpu_detection_is_not_a_selection_change(tmp_path, monkeypatch, kwargs):+ """setup.sh builds --rocm-gfx/--has-rocm into _PREBUILT_CMD from its own probe and+ setup.ps1 does the same, so counting them would lose the keep path on every AMD host."""+ _listing_failure(monkeypatch, linux_host)+ install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu")++ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "", **kwargs)++ assert (install_dir / "llama-server").exists()+++def test_the_probe_gets_the_runtime_line_the_marker_recorded(tmp_path, monkeypatch):+ """binary_env puts the CUDA toolkit on PATH from runtime_line and+ validate_prebuilt_choice passes it, so probing without it kills a pair-less install."""+ _listing_failure(monkeypatch, linux_host)+ seen: list = []+ real_binary_env = INSTALL_LLAMA_PREBUILT.binary_env++ def _record(*args, **kwargs):+ seen.append(kwargs.get("runtime_line"))+ return real_binary_env(*args, **kwargs)++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "binary_env", _record)+ install_dir = _complete_existing_llama_install(+ tmp_path, backend = "cpu", runtime_line = "cuda-12.4"+ )++ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ # preflight_linux_installed_binaries also builds an env and correctly passes none,+ # since it only matters on Windows; what is asserted is that the probe kept it.+ assert (+ "cuda-12.4" in seen+ ), f"the kept-install probe built its env without the marker's runtime_line: {seen}"+++def test_a_non_default_published_repo_is_not_answered_with_the_old_install(tmp_path, monkeypatch):+ """A different release repo is a live choice the old tree cannot satisfy."""+ _listing_failure(monkeypatch, linux_host)+ install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu")++ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "someone-else/llama.cpp", "")++ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+++def test_release_listing_failure_does_not_keep_an_unloadable_install(tmp_path, monkeypatch):+ """Executable is not runnable: a binary whose link graph is broken source builds."""++ def boom(*args, **kwargs):+ raise urllib.error.URLError("connection reset")++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT, "linux_missing_libraries", lambda *a, **k: ["libcuda.so.1"]+ )++ install_dir = _complete_existing_llama_install(tmp_path)++ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+ assert (install_dir / "llama-server").exists()+++ ("llama_tag", "published_release_tag"),+ [+ ("b9002", ""),+ ("latest", "release-2"),+ ("b9002", "release-2"),+ ],+ ids = ["upstream-tag", "published-release", "both-pins"],+)+def test_release_listing_failure_does_not_ignore_an_explicit_version(+ tmp_path, monkeypatch, llama_tag, published_release_tag+):+ """A usable older install cannot satisfy an explicit version request."""++ def boom(*args, **kwargs):+ raise urllib.error.URLError("connection reset")++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")++ install_dir = _complete_existing_llama_install(tmp_path)++ with pytest.raises(SystemExit) as caught:+ install_prebuilt(+ install_dir,+ llama_tag,+ "unslothai/llama.cpp",+ published_release_tag,+ )++ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+ assert (install_dir / "llama-server").exists()++@pytest.mark.parametrize("error",[diff --git a/tests/studio/install/test_keep_install_backcompat_9979.py b/tests/studio/install/test_keep_install_backcompat_9979.pynew file mode 100644index 00000000000..fce4f84c711--- /dev/null+++ b/tests/studio/install/test_keep_install_backcompat_9979.py@@ -0,0 +1,768 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Back-compat for the kept-install path against every marker shape that has shipped.++``UNSLOTH_PREBUILT_INFO.json`` is append-only across twelve shapes with no version field+and no migration, so an absent key is the normal case for anything installed before the+release that added it. The existing keep-path tests drive ``install_prebuilt`` with a+hand-built two-key marker; these call the deciders directly with the shapes real installs+carry.++Platforms are simulated through ``HostInfo`` as the rest of this suite does. That covers+the path decisions and payload tables, not the Windows loader or macOS dyld.+"""++import importlib.util+import json+import os+import signal+import subprocess+import sys+from pathlib import Path++import pytest+++PACKAGE_ROOT = Path(__file__).resolve().parents[3]+MODULE_PATH = PACKAGE_ROOT / "studio" / "install_llama_prebuilt.py"+SPEC = importlib.util.spec_from_file_location("studio_install_llama_prebuilt", MODULE_PATH)+assert SPEC is not None and SPEC.loader is not None+ILP = importlib.util.module_from_spec(SPEC)+sys.modules[SPEC.name] = ILP+SPEC.loader.exec_module(ILP)++HostInfo = ILP.HostInfo+++def _host(**kw) -> HostInfo:+ base = dict(+ system = "Linux",+ machine = "x86_64",+ is_windows = False,+ is_linux = True,+ is_macos = False,+ is_x86_64 = True,+ is_arm64 = False,+ nvidia_smi = None,+ driver_cuda_version = None,+ compute_caps = [],+ visible_cuda_devices = None,+ has_physical_nvidia = False,+ has_usable_nvidia = False,+ )+ base.update(kw)+ return HostInfo(**base)+++LINUX = _host()+WINDOWS = _host(system = "Windows", machine = "AMD64", is_windows = True, is_linux = False)+MACOS = _host(+ system = "Darwin",+ machine = "arm64",+ is_windows = False,+ is_linux = False,+ is_macos = True,+ is_x86_64 = False,+ is_arm64 = True,+ macos_version = (15, 5),+)++# The payload each platform's kinds share, as runtime_payload_health_groups computes it.+_SHARED_PAYLOAD = {+ "linux": [+ "libllama-common.so",+ "libllama.so",+ "libggml.so",+ "libggml-base.so",+ "libggml-cpu.so",+ "libmtmd.so",+ ],+ "windows": ["llama.dll"],+ "macos": ["libllama.dylib", "libggml.dylib", "libmtmd.dylib"],+}+_BACKEND_PAYLOAD = {+ ("linux", "cuda"): ["libggml-cuda.so"],+ ("linux", "rocm"): ["libggml-hip.so"],+ ("linux", "vulkan"): ["libggml-vulkan.so"],+ ("windows", "cuda"): ["ggml-cuda.dll"],+ ("windows", "rocm"): ["ggml-hip.dll"],+ ("windows", "vulkan"): ["ggml-vulkan.dll"],+}+# Only a published bundle owes the visual server.+_PUBLISHED_PAYLOAD = {+ "linux": ["llama-diffusion-gemma-visual-server"],+ "windows": ["llama-diffusion-gemma-visual-server.exe"],+ "macos": [],+}+_CUDART_TRIO = ("cudart64_13.dll", "cublas64_13.dll", "cublasLt64_13.dll")+++def _platform_of(host: HostInfo) -> str:+ return "windows" if host.is_windows else "macos" if host.is_macos else "linux"+++def build_install(+ tmp_path,+ *,+ host = LINUX,+ marker = "default",+ executable = True,+ runnable = True,+ runnable_root = None,+ payload = True,+ payload_backend = "unset",+ cudart = False,+ visual_server = True,+):+ """Write an install tree. ``marker`` is the literal object to serialise.++ ``marker="default"`` writes a minimal current-shape marker; ``marker=None`` writes no+ marker file at all (a source build); a ``str`` is written verbatim (corrupt markers).+ """+ install_dir = tmp_path / "llama.cpp"+ platform = _platform_of(host)+ runtime_dir = (+ install_dir / "build" / "bin" / "Release"+ if host.is_windows+ else install_dir / "build" / "bin"+ )+ runtime_dir.mkdir(parents = True)+ ext = ".exe" if host.is_windows else ""++ for path in (+ install_dir / f"llama-server{ext}",+ install_dir / f"llama-quantize{ext}",+ runtime_dir / f"llama-server{ext}",+ runtime_dir / f"llama-quantize{ext}",+ ):+ ok = (+ runnable+ if path.parent != install_dir+ else (runnable if runnable_root is None else runnable_root)+ )+ # A real runnable stub: the keep path execs these, and an empty file that kept+ # its mode bits is the ENOEXEC case.+ path.write_text("#!/bin/sh\nexit 0\n" if ok else "", encoding = "utf-8")+ os.chmod(path, 0o755 if executable else 0o644)+ (install_dir / "convert_hf_to_gguf.py").write_text("", encoding = "utf-8")+ (install_dir / "gguf-py").mkdir()++ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"+ if marker == "default":+ marker = {"release_tag": "old-release", "tag": "old-upstream"}+ if marker is not None:+ marker_path.write_text(+ marker if isinstance(marker, str) else json.dumps(marker) + "\n",+ encoding = "utf-8",+ )++ if payload:+ for name in _SHARED_PAYLOAD[platform]:+ (runtime_dir / name).write_text("", encoding = "utf-8")+ if payload_backend != "unset":+ for name in _BACKEND_PAYLOAD.get((platform, payload_backend), ()):+ (runtime_dir / name).write_text("", encoding = "utf-8")+ if visual_server:+ for name in _PUBLISHED_PAYLOAD[platform]:+ (runtime_dir / name).write_text("", encoding = "utf-8")+ if cudart:+ for name in _CUDART_TRIO:+ (runtime_dir / name).write_text("", encoding = "utf-8")+ return install_dir+++# The twelve marker shapes, oldest first, as write_prebuilt_metadata wrote them,+# trimmed to the keys the keep path reads.++S1 = { # 2026-03-25 #4562: no release_tag, no backend, no asset_sha256+ "requested_tag": "b6099",+ "tag": "b6099",+ "asset": "llama-b6099-bin-ubuntu-x64.tar.gz",+ "source": "upstream",+ "bundle_profile": "full",+ "runtime_line": None,+ "coverage_class": None,+ "prebuilt_fallback_used": False,+ "installed_at_utc": "2026-03-26T04:11:07Z",+}+S2 = { # 2026-04-01 #4741: release_tag + fingerprint arrive+ **S1,+ "release_tag": "b6210",+ "published_repo": "unslothai/llama.cpp",+ "asset": "app-b6210-linux-x64-cuda12.tar.gz",+ "asset_sha256": "3f" * 32,+ "source": "published",+ "runtime_line": "cuda12",+ "install_fingerprint": "aa" * 32,+}+S5 = {**S2, "force_cpu": False} # 2026-07-20 #7228+S6 = {+ **S5,+ "llama_backend": "vulkan", # 2026-07-27 #7373+ "asset": "llama-b7001-bin-ubuntu-vulkan-x64.tar.gz",+ "runtime_line": None,+}+S7 = {**S5, "ggml_tree": "b7440"} # 2026-08-04 #7817+S8 = {+ **S7,+ "rocm_gfx": "gfx1151", # 2026-08-08 #8050+ "asset": "app-b9001-linux-x64-rocm-gfx110X.tar.gz",+ "runtime_line": None,+}+S9 = {**S7, "backend": "cuda", "backend_request": "auto"} # 2026-08-13 #8520+S10 = {**S9, "gfx_target": None, "mapped_targets": []} # 2026-08-13 #7670+S11 = {**S10, "supported_sms": ["80", "86", "89", "90"]} # 2026-08-18 #8841 == main+S12 = {**S11, "runtime_asset": None} # this PR++# A real marker, produced by actually running studio/install_llama_prebuilt.py.+S12_REAL = {+ "requested_tag": "latest",+ "tag": "b10698",+ "release_tag": "b10698-mix-67dfc8b",+ "published_repo": "unslothai/llama.cpp",+ "asset": "app-b10698-mix-67dfc8b-linux-x64-cuda13-newer.tar.gz",+ "force_cpu": False,+ "llama_backend": None,+ "backend": "cuda",+ "backend_request": "auto",+ "asset_sha256": "d4" * 32,+ "runtime_asset": None,+ "source": "published",+ "ggml_tree": "0034c6eb",+ "bundle_profile": "cuda13-newer",+ "runtime_line": "cuda13",+ "coverage_class": "newer",+ "gfx_target": None,+ "mapped_targets": [],+ "supported_sms": ["86", "89", "90", "100", "103", "120"],+ "install_fingerprint": "36" * 32,+ "prebuilt_fallback_used": False,+ "installed_at_utc": "2026-08-31T06:40:37Z",+}++ALL_SHAPES = [+ ("S1-upstream-cpu", S1, None),+ ("S2-published-cuda", S2, "cuda"),+ ("S5-force-cpu-field", S5, "cuda"),+ ("S6-legacy-vulkan", S6, "vulkan"),+ ("S7-ggml-tree", S7, "cuda"),+ ("S8-rocm-gfx", S8, "rocm"),+ ("S9-backend-key", S9, "cuda"),+ ("S10-gfx-target", S10, "cuda"),+ ("S11-main-today", S11, "cuda"),+ ("S12-this-pr", S12, "cuda"),+ ("S12-real-install", S12_REAL, "cuda"),+]++[email protected](("name", "marker", "backend"), ALL_SHAPES, ids = [s[0] for s in ALL_SHAPES])+def test_every_shipped_marker_shape_keeps_a_complete_linux_install(tmp_path, name, marker, backend):+ """Kept whatever release wrote the marker.++ S1-S8 have no ``backend`` key, so it comes back out of the asset name; S1's upstream+ CPU asset names none either and must fail open.+ """+ install_dir = build_install(tmp_path, marker = marker, payload_backend = backend)+ assert ILP._kept_install_payload_is_healthy(install_dir, LINUX) is True+ assert ILP._existing_install_runs(install_dir, LINUX) is True++[email protected](("name", "marker", "backend"), ALL_SHAPES, ids = [s[0] for s in ALL_SHAPES])+def test_no_shipped_marker_shape_is_kept_once_its_backend_payload_is_gutted(+ tmp_path, name, marker, backend+):+ """Deleting the shared payload must be caught for every shape, old or new."""+ install_dir = build_install(tmp_path, marker = marker, payload_backend = backend)+ runtime_dir = install_dir / "build" / "bin"+ for lib in _SHARED_PAYLOAD["linux"]:+ (runtime_dir / lib).unlink()+ assert ILP._kept_install_payload_is_healthy(install_dir, LINUX) is False+ assert ILP._existing_install_runs(install_dir, LINUX) is False+++def test_a_pre_runtime_asset_windows_cuda_install_is_not_asked_for_the_cudart_trio(tmp_path):+ """S11 and older cannot record a pairing, so demanding one would loop forever.++ Every Windows CUDA install today predates ``runtime_asset``, and would be rejected on+ every run if the trio were required of a marker that cannot say it was paired.+ """+ install_dir = build_install(+ tmp_path,+ host = WINDOWS,+ marker = S11,+ payload_backend = "cuda",+ cudart = False,+ )+ assert ILP._kept_install_payload_is_healthy(install_dir, WINDOWS) is True+++def test_a_paired_windows_cuda_install_still_owes_its_cudart_trio(tmp_path):+ """Once the marker names the pairing, the trio becomes required."""+ paired = {**S12, "runtime_asset": "cudart-llama-bin-win-cuda-13.0-x64.zip"}+ gutted = build_install(+ tmp_path / "gutted",+ host = WINDOWS,+ marker = paired,+ payload_backend = "cuda",+ cudart = False,+ )+ intact = build_install(+ tmp_path / "intact",+ host = WINDOWS,+ marker = paired,+ payload_backend = "cuda",+ cudart = True,+ )+ assert ILP._kept_install_payload_is_healthy(gutted, WINDOWS) is False+ assert ILP._kept_install_payload_is_healthy(intact, WINDOWS) is True+++def test_a_source_build_is_never_kept_because_it_has_no_marker(tmp_path):+ """The keep path is for prebuilts only.++ ``confirm_install_tree`` requires the marker, so a source build never reaches the+ payload check and falls through to the source-build fallback as before.+ """+ install_dir = build_install(tmp_path, marker = None, payload_backend = "cuda")+ assert (install_dir / "llama-server").exists()+ assert not (install_dir / "UNSLOTH_PREBUILT_INFO.json").exists()+ assert ILP._install_tree_is_usable(install_dir, LINUX) is False+ assert ILP._existing_install_runs(install_dir, LINUX) is False+++ "corrupt",+ ["not json", "", "[]", "null", '"cuda"', "123", '{"release_tag": "b1"', "{}", "{}"],+ ids = [+ "garbage",+ "empty",+ "list",+ "null",+ "string",+ "number",+ "truncated",+ "bom",+ "empty-object",+ ],+)+def test_a_corrupt_marker_is_still_kept_but_owes_the_whole_platform_payload(tmp_path, corrupt):+ """An unreadable marker cannot name a backend, so it owes every kind's shared set.++ The asymmetry with the test above: present-but-unreadable still satisfies+ ``confirm_install_tree``, so the tree stays eligible and is judged on what is on disk.+ """+ install_dir = build_install(tmp_path, marker = corrupt, payload_backend = "cuda")+ assert ILP._kept_install_payload_is_healthy(install_dir, LINUX) is True+ assert ILP._existing_install_runs(install_dir, LINUX) is True++ for lib in _SHARED_PAYLOAD["linux"]:+ (install_dir / "build" / "bin" / lib).unlink()+ assert ILP._kept_install_payload_is_healthy(install_dir, LINUX) is False+++def test_a_marker_from_a_newer_unsloth_is_ignored_key_by_key(tmp_path):+ """Forwards compatibility: unknown keys must not disturb the decision."""+ future = {**S12, "install_generation": 3, "unknown_future_field": {"a": [1, 2]}}+ install_dir = build_install(tmp_path, marker = future, payload_backend = "cuda")+ assert ILP._kept_install_payload_is_healthy(install_dir, LINUX) is True+ assert ILP._existing_install_runs(install_dir, LINUX) is True+++def test_a_backend_this_unsloth_does_not_know_falls_back_to_the_asset_name(tmp_path):+ """An unrecognised ``backend`` is not the end of the derivation.++ ``marker_backend`` tries the recorded backend, then the install kind, then the asset+ name, so a backend this build has never heard of is still held to what the asset name+ says. Asserted both ways so the fallback order is pinned.+ """+ named = {**S12, "backend": "sycl"} # asset is ...linux-x64-cuda12.tar.gz+ assert ILP.marker_backend(named) == "cuda"++ without_cuda_lib = build_install(tmp_path / "a", marker = named, payload_backend = None)+ assert ILP._kept_install_payload_is_healthy(without_cuda_lib, LINUX) is False++ with_cuda_lib = build_install(tmp_path / "b", marker = named, payload_backend = "cuda")+ assert ILP._kept_install_payload_is_healthy(with_cuda_lib, LINUX) is True+++def test_a_backend_no_source_can_name_falls_open_to_the_shared_payload(tmp_path):+ """When neither the backend nor the asset name resolves, do not reject a good tree."""+ opaque = {**S12, "backend": "sycl", "asset": "bundle.tar.gz"}+ assert ILP.marker_backend(opaque) is None++ install_dir = build_install(tmp_path, marker = opaque, payload_backend = None)+ assert ILP._kept_install_payload_is_healthy(install_dir, LINUX) is True+++def test_the_macos_keep_path_requires_the_dylibs(tmp_path):+ """macOS reaches the same decider and owes its own shared payload.++ Simulated through ``HostInfo``: this covers the path and the payload table, not dyld.+ """+ install_dir = build_install(tmp_path / "ok", host = MACOS, marker = S12)+ assert ILP._kept_install_payload_is_healthy(install_dir, MACOS) is True++ gutted = build_install(tmp_path / "gutted", host = MACOS, marker = S12)+ (gutted / "build" / "bin" / "libggml.dylib").unlink()+ assert ILP._kept_install_payload_is_healthy(gutted, MACOS) is False+++def test_a_legacy_published_vulkan_install_without_the_visual_server_is_refused(tmp_path):+ """``source`` has been recorded since the first shape, so this reaches old installs.++ A published Vulkan install predating ``ensure_diffusion_visual_server`` is held to a+ file it never had. The one case where an old install is rebuilt rather than kept.+ """+ install_dir = build_install(+ tmp_path,+ marker = S6 | {"source": "published"},+ payload_backend = "vulkan",+ visual_server = False,+ )+ assert ILP._kept_install_payload_is_healthy(install_dir, LINUX) is False+++def test_a_binary_that_dies_on_sigsegv_is_not_a_working_install(tmp_path, monkeypatch):+ """A crashing image must be rejected, not treated as a successful probe."""+ install_dir = build_install(tmp_path, marker = S12, payload_backend = "cuda")+ monkeypatch.setattr(+ ILP,+ "run_capture",+ lambda *a, **k: subprocess.CompletedProcess(a[0] if a else [], -signal.SIGSEGV, "", ""),+ )+ assert ILP._existing_install_runs(install_dir, LINUX) is False+++def test_a_binary_that_hangs_is_treated_as_healthy(tmp_path, monkeypatch):+ """Pins the deliberate fail-open: a timeout must not spend a source build."""+ install_dir = build_install(tmp_path, marker = S12, payload_backend = "cuda")++ def hang(*a, **k):+ raise subprocess.TimeoutExpired(a[0] if a else ["llama-server"], 60)++ monkeypatch.setattr(ILP, "run_capture", hang)+ assert ILP._existing_install_runs(install_dir, LINUX) is True+++def test_a_windows_loader_failure_is_rejected_even_though_it_exits_zero_ish(tmp_path, monkeypatch):+ """0xC0000135 is a positive exit code, not a signal. Simulated: no Windows here."""+ install_dir = build_install(+ tmp_path,+ host = WINDOWS,+ marker = S12,+ payload_backend = "cuda",+ )+ monkeypatch.setattr(+ ILP,+ "run_capture",+ lambda *a, **k: subprocess.CompletedProcess(a[0] if a else [], 0xC0000135, "", ""),+ )+ assert ILP._existing_install_runs(install_dir, WINDOWS) is False+++def test_a_non_executable_tree_fails_the_same_gate_setup_sh_uses(tmp_path):+ """setup.sh reuses on ``[ -x build/bin/llama-server ]``; the keep path must agree."""+ install_dir = build_install(+ tmp_path,+ marker = S12,+ payload_backend = "cuda",+ executable = False,+ )+ assert ILP._existing_install_runs(install_dir, LINUX) is False+++def test_a_rotten_root_entrypoint_is_caught_even_when_build_bin_is_fine(tmp_path):+ """Inference launches the root copy first, so it cannot be excused by build/bin."""+ install_dir = build_install(+ tmp_path,+ marker = S12,+ payload_backend = "cuda",+ runnable_root = False,+ )+ assert ILP._existing_install_runs(install_dir, LINUX) is False+++ ("marker", "expected"),+ [+ (S1, "auto"),+ (S2, "auto"),+ (S5 | {"force_cpu": True}, "cpu"),+ (S6, "vulkan"),+ (S9, "auto"),+ (S9 | {"backend_request": "cuda"}, "cuda"),+ ({}, "auto"),+ ],+ ids = ["s1", "s2", "s5-forced-cpu", "s6-legacy-vulkan", "s9-auto", "s9-pinned", "empty"],+)+def test_the_stored_backend_choice_reads_the_same_from_every_shape(tmp_path, marker, expected):+ """The keep path gates on this, so old shapes must not read as a pinned choice."""+ install_dir = build_install(tmp_path, marker = marker)+ assert ILP.persisted_backend_request(install_dir) == expected+++# ---------------------------------------------------------------------------+# The [Windows, Linux, WSL, macOS] x [NVIDIA, AMD, CPU-only] product, through the+# same two deciders. Hosts are simulated by HostInfo, which is what the deciders+# branch on, so these prove the payload tables and the platform-prefix filtering,+# not the Windows loader or macOS dyld. WSL gets its own row because "WSL is just+# Linux here" is the claim worth pinning.+# ---------------------------------------------------------------------------++ARM64_LINUX = _host(machine = "aarch64", is_x86_64 = False, is_arm64 = True)+MACOS_X64 = _host(+ system = "Darwin",+ machine = "x86_64",+ is_windows = False,+ is_linux = False,+ is_macos = True,+ is_x86_64 = True,+ is_arm64 = False,+ macos_version = (14, 6),+)+WINDOWS_ARM64 = _host(+ system = "Windows",+ machine = "ARM64",+ is_windows = True,+ is_linux = False,+ is_x86_64 = False,+ is_arm64 = True,+)+# WSL reports itself as Linux; these flags are what a WSL2 ROCDXG host carries.+WSL_ROCM = _host(has_rocm = True, rocm_gfx_target = "gfx1151")+LINUX_NVIDIA = _host(+ compute_caps = ["10.0"],+ has_physical_nvidia = True,+ has_usable_nvidia = True,+)+LINUX_ROCM = _host(has_rocm = True, rocm_gfx_target = "gfx1100")+WINDOWS_NVIDIA = _host(+ system = "Windows",+ machine = "AMD64",+ is_windows = True,+ is_linux = False,+ compute_caps = ["8.9"],+ has_physical_nvidia = True,+ has_usable_nvidia = True,+)+WINDOWS_ROCM = _host(+ system = "Windows",+ machine = "AMD64",+ is_windows = True,+ is_linux = False,+ has_rocm = True,+ rocm_gfx_target = "gfx1151",+)++# (id, host, marker backend, the payload the tree must carry to be kept)+MATRIX = [+ ("linux-nvidia", LINUX_NVIDIA, "cuda", "cuda"),+ ("linux-arm64-nvidia", ARM64_LINUX, "cuda", "cuda"),+ ("linux-amd", LINUX_ROCM, "rocm", "rocm"),+ ("linux-cpu", LINUX, "cpu", None),+ ("linux-arm64-cpu", ARM64_LINUX, "cpu", None),+ ("linux-vulkan", LINUX, "vulkan", "vulkan"),+ ("wsl-amd", WSL_ROCM, "rocm", "rocm"),+ ("wsl-cpu", WSL_ROCM, "cpu", None),+ ("windows-nvidia", WINDOWS_NVIDIA, "cuda", "cuda"),+ ("windows-amd", WINDOWS_ROCM, "rocm", "rocm"),+ ("windows-cpu", WINDOWS, "cpu", None),+ ("windows-arm64-cpu", WINDOWS_ARM64, "cpu", None),+ ("windows-vulkan", WINDOWS, "vulkan", "vulkan"),+ ("macos-arm64", MACOS, "metal", None),+ ("macos-x64", MACOS_X64, "metal", None),+]+++ ("cell", "host", "backend", "payload_backend"),+ MATRIX,+ ids = [m[0] for m in MATRIX],+)+def test_a_complete_install_is_kept_in_every_os_and_accelerator_cell(+ tmp_path, cell, host, backend, payload_backend+):+ marker = {**S12, "backend": backend, "asset": f"app-b1-{cell}.tar.gz"}+ install_dir = build_install(+ tmp_path,+ host = host,+ marker = marker,+ payload_backend = payload_backend,+ )+ assert ILP._kept_install_payload_is_healthy(install_dir, host) is True, cell+ assert ILP._existing_install_runs(install_dir, host) is True, cell+++ ("cell", "host", "backend", "payload_backend"),+ MATRIX,+ ids = [m[0] for m in MATRIX],+)+def test_a_gutted_install_is_refused_in_every_os_and_accelerator_cell(+ tmp_path, cell, host, backend, payload_backend+):+ """Every cell must fail closed, or the keep path hands back a broken tree."""+ marker = {**S12, "backend": backend, "asset": f"app-b1-{cell}.tar.gz"}+ install_dir = build_install(+ tmp_path,+ host = host,+ marker = marker,+ payload_backend = payload_backend,+ )+ runtime_dir = (+ install_dir / "build" / "bin" / "Release"+ if host.is_windows+ else install_dir / "build" / "bin"+ )+ (runtime_dir / _SHARED_PAYLOAD[_platform_of(host)][0]).unlink()+ assert ILP._kept_install_payload_is_healthy(install_dir, host) is False, cell+++ ("cell", "host", "backend"),+ [(c, h, b) for c, h, b, p in MATRIX if p is not None],+ ids = [m[0] for m in MATRIX if m[3] is not None],+)+def test_an_accelerator_install_missing_its_own_backend_library_is_refused(+ tmp_path, cell, host, backend+):+ """The shared payload alone must not be enough for a CUDA/ROCm/Vulkan tree.++ The partial-extraction case: everything generic is present and only the accelerator+ library is gone, so the binaries start and fail once a model loads.+ """+ marker = {**S12, "backend": backend, "asset": f"app-b1-{cell}.tar.gz"}+ install_dir = build_install(+ tmp_path,+ host = host,+ marker = marker,+ payload_backend = None,+ )+ assert ILP._kept_install_payload_is_healthy(install_dir, host) is False, cell+++def test_wsl_is_treated_exactly_like_linux_by_the_keep_path(tmp_path):+ """Pin the assumption rather than leaving it implicit.++ ``HostInfo`` has no WSL flag and the WSL2 ROCDXG handling is upstream of here, so a+ WSL install is judged by the Linux tables.+ """+ marker = {**S12, "backend": "rocm", "asset": "app-b1-linux-x64-rocm-gfx1151.tar.gz"}+ for host in (LINUX_ROCM, WSL_ROCM):+ ok = build_install(+ tmp_path / f"ok-{host.rocm_gfx_target}",+ host = host,+ marker = marker,+ payload_backend = "rocm",+ )+ gutted = build_install(+ tmp_path / f"gutted-{host.rocm_gfx_target}",+ host = host,+ marker = marker,+ payload_backend = None,+ )+ assert ILP._kept_install_payload_is_healthy(ok, host) is True+ assert ILP._kept_install_payload_is_healthy(gutted, host) is False+++def test_a_marker_naming_another_platforms_backend_falls_open(tmp_path):+ """A tree carried between machines must not be judged by the wrong table.++ "metal" on a Linux host filters to no linux kind, so the decider falls back to every+ kind this platform has rather than refusing a payload that is actually complete.+ """+ marker = {**S12, "backend": "metal", "asset": "app-b1-macos-arm64.tar.gz"}+ install_dir = build_install(tmp_path, host = LINUX, marker = marker, payload_backend = None)+ assert ILP.marker_backend(marker) == "metal"+ assert ILP._kept_install_payload_is_healthy(install_dir, LINUX) is True+++def test_an_install_whose_keys_were_backfilled_onto_an_old_marker_is_kept(tmp_path):+ """Real markers are not the clean shapes: ``sync_marker_selection`` grafts.++ An install made at S2 and reused since carries an S2 base with later keys grafted on,+ which is where a reader would expect the shapes to disagree.+ """+ grafted = {+ **S2,+ "backend": "cuda",+ "backend_request": "auto",+ "ggml_tree": "b9415",+ "supported_sms": ["80", "86"],+ "runtime_asset": None,+ }+ install_dir = build_install(tmp_path, marker = grafted, payload_backend = "cuda")+ assert ILP._kept_install_payload_is_healthy(install_dir, LINUX) is True+ assert ILP._existing_install_runs(install_dir, LINUX) is True+++# Forwards compatibility through install_prebuilt, so the exit code the setup+# scripts branch on is what is under test.+++def _transient_listing_failure(monkeypatch, host = LINUX):+ """Make the release listing fail the way a flaky network does."""+ import urllib.error++ def boom(*args, **kwargs):+ raise urllib.error.URLError("connection reset")++ monkeypatch.setattr(ILP, "_fork_manifest_release_plans", boom)+ monkeypatch.setattr(ILP, "detect_host", lambda *a, **k: host)+ monkeypatch.setattr(ILP, "collect_system_report", lambda *a, **k: "report")+++def test_a_marker_from_a_newer_unsloth_refuses_rather_than_keeping(tmp_path, monkeypatch):+ """A backend choice this build cannot read must stop the install, not be kept.++ ``effective_backend_request`` raises ``UnknownBackendRequest`` and the handler exits+ ``EXIT_ERROR`` before the keep branch runs. That ordering was unasserted.+ """+ _transient_listing_failure(monkeypatch)+ install_dir = build_install(+ tmp_path,+ marker = {**S12, "backend": "cuda", "backend_request": "sycl"},+ payload_backend = "cuda",+ )+ with pytest.raises(SystemExit) as caught:+ ILP.install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")+ assert caught.value.code == ILP.EXIT_ERROR+ # And the install is left alone for a newer Unsloth to find.+ assert (install_dir / "llama-server").exists()+++def test_a_transient_failure_keeps_each_shipped_shape_and_returns_exit_zero(tmp_path, monkeypatch):+ """End to end: the exit code setup.sh and setup.ps1 branch on, per shape."""+ _transient_listing_failure(monkeypatch)+ for name, marker, backend in ALL_SHAPES:+ install_dir = build_install(+ tmp_path / name,+ marker = marker,+ payload_backend = backend,+ )+ # Returns rather than raising SystemExit: main() turns that into exit 0.+ ILP.install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")+ assert (install_dir / "llama-server").exists(), name+++def test_a_transient_failure_still_falls_back_when_the_tree_is_not_runnable(tmp_path, monkeypatch):+ """The other half: a broken tree must still reach the source-build fallback.++ Exit 2 is what tells setup.sh it may build from source; swallowing it would leave a+ user with a half-deleted install told everything was fine.+ """+ _transient_listing_failure(monkeypatch)+ install_dir = build_install(tmp_path, marker = S12, payload_backend = None)+ with pytest.raises(SystemExit) as caught:+ ILP.install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")+ assert caught.value.code == ILP.EXIT_FALLBACK+++def test_an_explicit_version_request_is_never_answered_with_the_old_install(tmp_path, monkeypatch):+ """Asking for a specific release and getting the one already there is a lie."""+ _transient_listing_failure(monkeypatch)+ install_dir = build_install(tmp_path, marker = S12, payload_backend = "cuda")+ with pytest.raises(SystemExit) as caught:+ ILP.install_prebuilt(install_dir, "b9999", "unslothai/llama.cpp", "")+ assert caught.value.code in (ILP.EXIT_FALLBACK, ILP.EXIT_ERROR)diff --git a/tests/studio/test_zoo_suite_parallel_isolation.py b/tests/studio/test_zoo_suite_parallel_isolation.pyindex 396bdf0a8fd..3425d695712 100644--- a/tests/studio/test_zoo_suite_parallel_isolation.py+++ b/tests/studio/test_zoo_suite_parallel_isolation.py@@ -1,64 +1,6 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-"""-The unsloth_zoo suite runs in parallel, minus two files that must not share a worker.--Measured on a staging runner, whole suite, all three matrix cells:-- cell serial -n 4 --dist loadfile- HF=latest + TRL=latest 580s 253s- HF=4.57.6 + TRL<1 517s 229s- HF=default + TRL=default 568s 246s--Across two runs of all three cells, four agreed exactly -- failure sets and skip-sets both -- and two produced 14 failures serial does not: 8 in-test_mlx_generate.py, 6 in test_moe_bnb4bit_per_expert_conversions.py.--The same 14 every time, and not the same cell: the second run moved them from-HF=default to HF=latest. That rules out a dependency combination and leaves worker-scheduling, with roughly one cell per run drawing the losing order. It also means a-single green run proves nothing here, which is why the pin stays even though four-of six observations were clean.--Both files pass alone, and pass under xdist alone, so they are self-contained; what-breaks them is another file running first in the same worker, an ordering serial-never produces because serial is alphabetical. Both causes are now known, and they-are different:-- test_moe_bnb4bit_per_expert_conversions.py -- test_vllm_to_hf_conversion.py put a- bitsandbytes.functional carrying only dequantize_4bit into sys.modules and never- removed it, so the later `from bitsandbytes.functional import QuantState` that- temporary_patches/moe_utils_bnb4bit.py does at import time failed with "(unknown- location)". m sorts before v, so serial never saw it. Fixed upstream in- unsloth_zoo#1076, with a teardown hook that fails the next one.-- test_mlx_generate.py -- CAUSE NOT ESTABLISHED. It installs the MLX-on-torch shim- at its own import time and the shim's docstring requires that to happen "BEFORE- any unsloth_zoo MLX module is imported", which looked like the answer: the eight- failures are all isinstance checks reporting-- TypeError: requests[0] must be GenerationRequest.-- which is what two copies of a class look like. But conftest imports unsloth_zoo- and pulls unsloth_zoo.mlx in before any test module loads, so that precondition- is violated on every run INCLUDING the ones that pass, and the file passes alone.- So the ordering contract is not the trigger, or not the whole one. I checked this- by asserting the precondition and watching it fail a green run.-- The pin stands on the observation rather than the explanation: eight tests here- fail under xdist and pass serially, reproducibly, on the same commit. Whoever- picks this up next should not start from the shim docstring -- I did, and it is a- dead end.--So the pair is ignored from the parallel pass and run again in a process of their-own. That pairing is the thing this file guards, because half of it is silent:-drop the serial pass and the ignores simply delete 51 tests from CI while the job-stays green. That is strictly worse than the 14 failures, which at least announce-themselves.--Same shape as test_backend_ci_parallel_isolation for studio-backend-ci, and for the-same reason: an ignore and its serial rerun are two edits held together by nothing.-"""+"""Guard the parallel zoo run and the serial reruns for tests that cannot share workers."""from __future__ import annotations@@ -78,16 +20,25 @@ ISOLATED = ["tests/test_moe_bnb4bit_per_expert_conversions.py","6 failures under xdist that serial does not produce",),- # Not ordering: wall clock. 27 sub-second sleeps against a stall detector, one of- # them commented "within the unmeasurable window". Under four workers it reported- # "no progress for 0s" -- nothing stalled, the test was descheduled.+ # This test has sub-second wall-clock assertions that fail under CPU contention.("tests/test_hf_xet_fallback.py", "sub-second wall-clock margins under CPU contention"),+ # MLX shims alter sys.modules, so these files each need a fresh process.+ ("tests/test_mlx_neftune_quant_map.py", "the mlx shim un-skips it and the stub then raises"),+ ("tests/test_mlx_gated_delta_vjp.py", "the mlx shim changes which backend it exercises"),+ (+ "tests/test_gemma3_forced_float32_boundary_dtype.py",+ "the mlx shim leaves patch_Gemma3MLP unable to install its forward",+ ),]-# The zoo suite is the only pytest run in this workflow driven out of the cloned zoo-# checkout, and it is told apart by the deselect it carries rather than by step order,-# so re-ordering or renaming steps does not quietly point this guard at another command.-ZOO_MARKER = "tests/test_mlx_finetune_last_n_layers.py::test_get_peft_model_passes_finetune_last_n_layers_through"+# Identify the cloned zoo's parallel pytest command independently of step ordering.+ZOO_MARKER = "--dist loadfile tests/"++# Deselected because it needs a GPU. It rides whichever command owns its file.+MLX_DESELECT = (+ "tests/test_mlx_finetune_last_n_layers.py::"+ "test_get_peft_model_passes_finetune_last_n_layers_through"+)def _commands() -> list[str]:@@ -110,11 +61,17 @@ def _zoo_parallel() -> str:return hits[0]-def _zoo_serial() -> str:- hits = [c for c in _commands() if "-n 4" not in c and all(path in c for path, _ in ISOLATED)]- assert (- len(hits) == 1- ), f"expected exactly one serial rerun naming both isolated files, found {len(hits)}"+def _zoo_mlx_group() -> str:+ """Return the serial MLX group command."""+ hits = [c for c in _commands() if "$mlx_group" in c]+ assert len(hits) == 1, f"expected exactly one serial mlx group run, found {len(hits)}"+ return hits[0]+++def _zoo_serial(path: str) -> str:+ """Return the dedicated rerun command for one isolated file."""+ hits = [c for c in _commands() if "-n 4" not in c and path in c]+ assert len(hits) == 1, f"expected exactly one serial rerun naming {path}, found {len(hits)}"return hits[0]@@ -130,7 +87,13 @@ def test_the_zoo_suite_actually_runs_in_parallel() -> None:@pytest.mark.parametrize("path,reason", ISOLATED, ids = lambda v: v.split("/")[-1])def test_an_isolated_file_is_ignored_by_the_parallel_run(path: str, reason: str) -> None:- assert f"--ignore={path}" in _zoo_parallel(), (+ cmd = _zoo_parallel()+ # The family glob automatically covers newly added MLX tests.+ covered = f"--ignore={path}" in cmd or (+ path.rsplit("/", 1)[-1].startswith("test_mlx_")+ and "--ignore-glob='tests/test_mlx_*.py'" in cmd+ )+ assert covered, (f"{path} ({reason}) is not ignored by the parallel zoo run, so it goes back to "f"failing intermittently depending on which worker picks it up")@@ -139,27 +102,106 @@ def test_an_isolated_file_is_ignored_by_the_parallel_run(path: str, reason: str)@pytest.mark.parametrize("path,reason", ISOLATED, ids = lambda v: v.split("/")[-1])def test_an_isolated_file_still_runs_serially(path: str, reason: str) -> None:"""The silent half. An ignore with no rerun deletes the tests and stays green."""- assert path in _zoo_serial(), (+ assert path in _zoo_serial(path), (f"{path} is ignored from the parallel run but never run again. Its tests are "f"simply not executed, and nothing else in CI would say so.")-def test_the_serial_rerun_is_not_itself_parallel() -> None:- """Rerunning the pair under xdist would reproduce exactly what it exists to avoid."""- assert "-n " not in _zoo_serial(), (- "the serial rerun of the isolated files passes -n, which puts them back in the "- "parallel session whose ordering is what breaks them"[email protected]("path,reason", ISOLATED, ids = lambda v: v.split("/")[-1])+def test_the_serial_rerun_is_not_itself_parallel(path: str, reason: str) -> None:+ """Rerunning these under xdist would reproduce exactly what it exists to avoid."""+ assert "-n " not in _zoo_serial(path), (+ f"the serial rerun of {path} passes -n, which puts it back in the parallel "+ f"session whose ordering is what breaks it"+ )+++def test_the_serial_reruns_tolerate_an_empty_collection() -> None:+ """Treat pytest exit 5 from a module-level skip as non-fatal."""+ for path, _ in ISOLATED:+ assert "_keep" in _zoo_serial(path), (+ f"the rerun of {path} feeds its status straight into rc, so a module-level "+ f"skip (pytest exit 5, nothing collected) fails the whole job"+ )+ assert 'if [ "$1" = 5 ]' in WORKFLOW.read_text(+ encoding = "utf-8"+ ), "the isolated rerun no longer tolerates pytest's no-tests-collected exit"++[email protected]("path,reason", ISOLATED, ids = lambda v: v.split("/")[-1])+def test_an_isolated_file_does_not_share_its_rerun(path: str, reason: str) -> None:+ """Give every contaminating file its own process."""+ cmd = _zoo_serial(path)+ others = [other for other, _ in ISOLATED if other != path and other in cmd]+ assert not others, (+ f"{path} shares its rerun process with {others}. These files are isolated "+ f"because they cannot share a process, and that includes each other.")def test_the_deselects_survive_on_the_parallel_run() -> None:- """- The three deselects are the CUDA-only and known-broken cases. They lived on the- single command that this change split in two; a split that dropped them would turn- a deliberate 'deselected' into a runtime failure on a GPU-less runner.- """+ """Keep each deselect with the command that owns its file."""cmd = _zoo_parallel()assert (- cmd.count("--deselect") == 3- ), f"the parallel zoo run carries {cmd.count('--deselect')} deselects, expected 3"+ cmd.count("--deselect") == 2+ ), f"the parallel zoo run carries {cmd.count('--deselect')} deselects, expected 2"+ group = _zoo_mlx_group()+ assert MLX_DESELECT in group, (+ f"{MLX_DESELECT} is deselected nowhere now that test_mlx_finetune_last_n_layers.py "+ f"runs in the serial mlx group, so it fails on a GPU-less runner instead"+ )+++def test_the_mlx_family_leaves_the_parallel_run_as_a_glob() -> None:+ """Exclude all MLX tests because their partial shims contaminate workers."""+ assert "--ignore-glob='tests/test_mlx_*.py'" in _zoo_parallel(), (+ "the parallel zoo run no longer excludes the mlx family as a glob, so the next "+ "test_mlx_*.py added upstream goes back to poisoning whichever file follows it"+ )+++def test_the_mlx_group_runs_serially_and_skips_the_per_file_three() -> None:+ """The group is serial on purpose, and must not double-run the per-file isolated mlx."""+ assert (+ "-n " not in _zoo_mlx_group()+ ), "the mlx group runs under xdist, which is the arrangement it exists to avoid"+ # Per-file exclusions are applied while building the group, not on pytest itself.+ text = WORKFLOW.read_text(encoding = "utf-8")+ for path, _ in ISOLATED:+ name = path.rsplit("/", 1)[-1]+ if not name.startswith("test_mlx_"):+ continue+ stem = name[len("test_mlx_") : -len(".py")]+ assert f"{stem}|" in text or f"{stem})" in text, (+ f"{path} has its own process but is not excluded from the mlx group's file "+ f"list, so it runs twice and brings its shim back into that session"+ )+++def test_an_empty_mlx_group_stops_the_step_instead_of_collecting_everything() -> None:+ """The group is passed unquoted, so an empty list is not an empty run.++ With nothing in ``mlx_group`` the command collects the whole rootdir instead:+ green, far slower, and not this group. The glob only has to stop matching+ once, upstream renaming the family for instance.+ """+ text = WORKFLOW.read_text(encoding = "utf-8")+ assert 'if [ -z "$mlx_group" ]' in text, (+ "nothing checks that the mlx group glob matched anything, so an empty glob "+ "silently turns this step into a serial run of the entire suite"+ )+++def test_a_skipped_isolated_file_is_named_in_the_log() -> None:+ """Exit 5 is tolerated, so the file that produced it has to be identifiable.++ An expected module-level skip and a file that stopped collecting for a new+ reason both exit 5 and both stay green.+ """+ text = WORKFLOW.read_text(encoding = "utf-8")+ for path, _ in ISOLATED:+ assert f'_keep "$?" {path}' in text, (+ f"the rerun of {path} does not pass its own name to _keep, so a silent "+ f"empty collection is reported without saying which file it was"+ )