Skip to content

Fix Windows llama.cpp prebuilt setup with inaccessible PATH entries - #7696

Merged
danielhanchen merged 13 commits into
unslothai:mainfrom
Etherll:llamacpp-fatal
Aug 1, 2026
Merged

danielhanchen merged 13 commits into
unslothai:mainfrom
Etherll:llamacpp-fatal

Conversation

@Etherll

@Etherll Etherll commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Summary

Keep Windows llama.cpp prebuilt setup from failing when the inherited PATH contains directories the current user cannot inspect. Unexpected helper errors now stop setup with the original diagnostic instead of launching a resource-heavy source build.

Motivation

A normal Windows user can inherit this SYSTEM-profile entry:

C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps

Calling Path.is_dir() on it can raise PermissionError: [WinError 5] Access is denied. Runtime discovery treated every PATH entry as required, so the prebuilt helper failed. The setup scripts then treated any nonzero exit as permission to compile llama.cpp from source.

Changes

  • Add an opt-in mode to skip inaccessible discovery directories while preserving the strict default in studio/install_llama_prebuilt.py:4411.
  • Treat Windows runtime-discovery candidates and inherited PATH entries as optional in studio/install_llama_prebuilt.py:4718 and studio/install_llama_prebuilt.py:4988.
  • Keep the binary directory and selected runtime directories strict. Missing or inaccessible required directories still raise an error.
  • Start the llama.cpp source build only when the prebuilt helper returns the expected fallback status (2) in studio/setup.ps1:4059 and studio/setup.sh:1580.
  • Report unexpected helper failures and retain or restore an existing installation instead of attempting a source build.
  • Add regressions covering the exact SYSTEM-profile path, required-path strictness, ordering, deduplication, and setup fallback routing in tests/studio/install/test_install_llama_prebuilt_logic.py:909.

How to test

python -m pytest -q -p no:cacheprovider tests/studio/install/test_install_llama_prebuilt_logic.py -k "not test_setup_sh_cleanup_unlinks_instruction_symlink_only and not test_diffusion_visual_server_uses_approved_checksum_download"
ruff check studio/install_llama_prebuilt.py tests/studio/install/test_install_llama_prebuilt_logic.py
python -m py_compile studio/install_llama_prebuilt.py tests/studio/install/test_install_llama_prebuilt_logic.py
git diff --check

@Etherll
Etherll requested a review from danielhanchen as a code owner July 31, 2026 16:16
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 91238ebfde

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Narrowing the source build to helper exit 2 made every other nonzero exit
fatal, but the helper reports a rate-limited or unreachable api.github.com
as EXIT_ERROR: fetch_json raises a bare RuntimeError for HTTP 403, and the
fork branch of the release resolver has no wrapper of its own where the
ggml-org branch does. Unauthenticated GitHub API calls are limited to 60 an
hour per IP, so a shared runner or a NAT'd network hits this routinely, and
a source build clones over git rather than the API, which is why falling
back used to recover. This PR's own macos-14 kill@torch run failed exactly
that way.

Classify release-listing failures on the install path as PrebuiltFallback so
they exit 2 again. Scoped to install_prebuilt rather than the resolver:
--resolve-prebuilt turns PrebuiltFallback into a successful
{"prebuilt_available": false} payload and update_flow caches any exit-0
answer for RESOLVE_TTL_SECONDS, so wrapping there would pin a transient 403
as "no prebuilt" for 24 hours.

Also close the paths that stayed fatal:

- collect_system_report ran inside the PrebuiltFallback handler, so a probe
  that raised replaced the in-flight fallback with EXIT_ERROR.
- python_runtime_dirs and windows_runtime_dirs stat sys.path entries and
  %ProgramFiles% outside dedupe_existing_dirs, so skip_unusable could not
  protect them and a denied entry still aborted Windows discovery.
- binary_env still required inherited LD_LIBRARY_PATH and DYLD_LIBRARY_PATH
  to be readable, the same thing the Windows branch stopped requiring.
- sync_marker_force_cpu and sync_marker_llama_backend guarded the marker
  read but not the write, so a read-only marker on an otherwise up to date
  install failed setup.
- runtime_libs.python_runtime_dirs, the serve-time copy, had the same
  unguarded sys.path stat; the sidecar turns the raise into an empty dir
  list and loses every CUDA wheel dir.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Reviewed this end to end and pushed fb30484 to the branch. The dedupe_existing_dirs half is a real fix for a real bug; the exit-code half was correct in principle but shipped a regression, which the follow-up commit repairs.

The regression

fetch_json raises a bare RuntimeError for an api.github.com 403 (prebuilt_core.py:675), and the fork branch of resolve_simple_install_release_plans has no wrapper of its own where the ggml-org branch has one at install_llama_prebuilt.py:1166-1169. So a rate-limited release listing escapes as EXIT_ERROR. Before this PR that hit the else and source-built; after it, setup aborts.

Unauthenticated GitHub API calls are capped at 60 per hour per IP, so any user without GH_TOKEN behind NAT or on a shared runner hits this routinely, and a source build clones over git rather than the API, which is exactly why the fallback worked. It is what failed macos-14 kill@torch on this PR while passing on #7718 and #7720:

[llama-prebuilt] fetch failed (1/4) ... HTTP Error 403: rate limit exceeded; retrying
[llama-prebuilt] fatal helper error: GitHub API returned 403 ...
[TAURI:ERROR] llama.cpp prebuilt helper failed unexpectedly (exit code 1).

Driving each version's own setup.sh routing block under bash:

helper exit before this PR this PR with fb30484
network / rate limit 1 -> source build 1 -> abort 2 -> source build
0 / 3 / 4 unchanged unchanged unchanged
genuine helper defect 1 -> source build 1 -> abort 1 -> abort

So the intent of the PR is preserved: an unexpected error still refuses to source-build. Only transient transport failures go back to falling back. setup.ps1 gets the same repair for free, since the fix is in the shared helper.

Also fixed in fb30484

  • collect_system_report ran inside the except PrebuiltFallback handler, so a probe that raised replaced the in-flight fallback with EXIT_ERROR.
  • python_runtime_dirs stats sys.path entries and windows_runtime_dirs stats %ProgramFiles% outside dedupe_existing_dirs, so skip_unusable could not protect them. A denied sys.path entry still aborted Windows discovery on this branch.
  • binary_env still required inherited LD_LIBRARY_PATH / DYLD_LIBRARY_PATH to be readable. Same bug class the Windows branch just stopped having.
  • sync_marker_force_cpu / sync_marker_llama_backend guarded the marker read but not the write, so a read-only marker on an otherwise up to date install failed setup.
  • runtime_libs.python_runtime_dirs, the serve-time copy its own docstring says is kept in sync, had the same unguarded sys.path stat. The sidecar turns the raise into an empty dir list and loses every CUDA wheel dir.

Verification

  • 35-cell matrix, [Windows, Linux, WSL, macOS-arm64, macOS-x86_64] x [NVIDIA cu12, cu13, AMD gfx1030/gfx1151/gfx942, Vulkan, CPU] over 15 selection and env-construction functions: 525/525 identical to pre-PR on clean hosts. Fault injection across 2954 triples: 0 cases where pre-PR returned and the branch now raises.
  • setup.sh and setup.ps1 routing driven for statuses 0/1/2/3/4/126/127/130/137/139/143/255 across vulkan, install-present and studio-owned combinations, under bash and pwsh: identical decisions, no shell/PowerShell asymmetry.
  • PATH assembly: 37293 input combinations covering duplicates within and across both lists, symlink aliases, missing entries, empty components and trailing separators. Byte-identical to the single-pass version.
  • Bare uv venv on Python 3.9, 3.10, 3.11, 3.12 and 3.13: the helper imports with no third-party packages, exit-code constants hold, and is_dir() propagates EACCES on every one, which is what makes the original fix necessary.
  • tests/studio: 2107 passed, 3 skipped. The 3 test_managed_node_runtime failures under tests/studio/install/ are pre-existing on origin/main.

test_setup_source_build_fallback_requires_expected_prebuilt_exit asserted a < b < c over str.index(needle, start), which cannot return less than start, so it passed whenever the three literals merely existed in order. Injecting the exact regression it guards left it green. It is replaced with a matrix that runs the real routing block under bash, plus regression tests for the exit-2 classification.

Not changed here, worth separate PRs

  • prebuilt_core.py:1287 folds the inherited LD_LIBRARY_PATH into linux_runtime_dirs_for_required_libraries strictly. Same bug class, Linux side, present before this PR. It needs care rather than blanket leniency: linux_cuda_choice_from_release is fail-closed, so skipping a dir there silently downgrades the host to CPU instead of reordering preferences.
  • install_whisper_prebuilt.py shares fetch_json and has the identical 403 misclassification. Its exit 2 means EXIT_INCOMPATIBLE, not fallback, and setup.sh routes whisper fail-open, so porting this fix verbatim would print a misleading release-skew message. Better handled on its own.
  • argparse also exits 2, and it is reachable: UNSLOTH_LLAMA_TAG="--bogus" makes argparse consume the value as a flag and exit 2, which now silently starts a source build. Pre-existing, but exit 2 being load-bearing makes it worth tightening.
  • setup.sh:2119 still uses "any nonzero implies CPU rebuild" for --validate-install, which is the loose semantics this PR argues against everywhere else.

One behaviour change worth calling out as intended rather than accidental: Ctrl-C during the prebuilt step (130) used to start a source build and now aborts, which is the better outcome.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 1, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 7da172d26e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…rker

Three follow-ups from cross-platform validation.

The resolver wrapper caught Exception, so a TypeError or AttributeError from
a bug in host-conditional resolver code (per-gfx ROCm, Windows arm64, the
macOS walk-back) also exited 2 and bought a source build, logged under a
message that blames the network. Narrow it to OSError, RuntimeError and
ValueError, which covers every transient shape by MRO: URLError, HTTPError,
SSLError and TimeoutError are OSError, JSONDecodeError is a ValueError, and
fetch_json raises a bare RuntimeError for HTTP 403. Code defects go back to
EXIT_ERROR, with a test pinning that direction.

Guarding the marker write stopped a read-only marker from failing setup, but
it also let a deliberate --force-cpu go unrecorded while setup reported
success, which is how the updater re-routes a CPU user onto a GPU bundle
(unslothai#7213). Write through atomic_write_bytes first, which swaps in a sibling
temp file and so lands on a read-only marker in a writable dir, and warn
loudly when it genuinely cannot be recorded.

Skip the setup.sh routing test on Windows: setup.sh is the POSIX installer,
Windows runs setup.ps1, and driving a POSIX script through Git Bash with
Windows paths proves nothing about either. The PowerShell branch of the same
routing stays covered by the platform-independent textual test.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…marker

Guarding only the search root left the strict dedupe on python_runtime_dirs'
own return to raise, so a readable site-packages with a denied torch/lib or
nvidia/*/lib child still aborted Windows discovery. That is the same shape as
the bug this branch is about, one level down: the parent lists fine and the
entry underneath is denied. These candidates are optional CUDA wheel dirs
found by globbing, and one that cannot be stat'd could not have served DLLs
to the loader either, so skip them like the serve-time copy already does.

Drop the in-place retry in the marker rewrite. It opened a valid marker with
truncation, so an ENOSPC or I/O error mid-write would strand a partial
UNSLOTH_PREBUILT_INFO.json and later updates would stop recognising the
install. The atomic path already covers the case the retry was there for, a
read-only marker in a writable dir; when it fails, leave the old marker alone
and warn.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026
os.replace keeps the source file's mode and NamedTemporaryFile is 0600, so
refreshing a shared install's marker left UNSLOTH_PREBUILT_INFO.json readable
only by whoever ran setup, and other users could no longer recognise or
update that installation. Reproduced: a 0444 marker came back 0600.

Build the temp file here instead of calling atomic_write_bytes, so the
original mode is restored before the swap rather than after, leaving no
window where the marker is private. Clean up the temp file if the replace
fails, so a failed refresh strands nothing next to the marker.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 1, 2026
@unslothai unslothai deleted a comment from Etherll Aug 1, 2026
@unslothai unslothai deleted a comment from Etherll Aug 1, 2026
@unslothai unslothai deleted a comment from Etherll Aug 1, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 1, 2026 13:12
A plain OSError is not evidence of a network problem. EMFILE after file
descriptor exhaustion, ENOMEM, or a local EACCES reading TLS configuration
were all being converted to EXIT_FALLBACK, so setup started the resource
heavy source build that this branch otherwise refuses for unexpected helper
failures, and a build needs more descriptors and more memory, not fewer.
Name the transport shapes instead: URLError covers HTTPError and the
socket/DNS errors urllib wraps, plus SSLError, ConnectionError, TimeoutError,
and the RuntimeError and ValueError that fetch_json raises for a 403 and for
an undecodable payload. ENOSPC still reaches EXIT_NO_SPACE, now through
__main__'s classifier rather than install_prebuilt's, and the test asserts it
the same way __main__ decides it.

The marker temp file was only unlinked when the chmod or the replace failed.
A write, flush or fsync that raised, which is the ENOSPC case this is built
to tolerate, jumped straight past the cleanup and left a partial
UNSLOTH_PREBUILT_INFO.json.tmp-* beside the valid marker, one per attempt on
a full volume. Track it across every failure path instead.

Also restore the original owner and group on the replacement where the caller
is permitted to, since os.replace installs the temp file's ownership and a
shared marker would otherwise pick up the invoking user's primary group.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 224cb83d0e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 1, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 1, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 091db7444a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 1faa037 into unslothai:main Aug 1, 2026
72 of 76 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants