Skip to content

Windows: do not abort setup on an unreadable llama.cpp install - #7735

Merged
danielhanchen merged 12 commits into
mainfrom
fix/setup-ps1-denied-llama-install
Aug 2, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
fix/setup-ps1-denied-llama-install

Conversation

@shimmyshimmer

Copy link
Copy Markdown
Member

Problem

A Windows install fails at the llama.cpp prebuilt step with a raw PowerShell error:

Existing llama.cpp install detected -- validating staged prebuilt update before replacement
Test-Path : Access is denied
At <studio_home>\unsloth_studio\Lib\site-packages\studio\setup.ps1:3904 char:13
+         if (Test-Path $existingMetaPath) {
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (...UNSLOTH_PREBUILT_INFO.json:String) [Test-Path], UnauthorizedAccessException

Three things combine here:

  1. Test-Path does not return $false when an ACL denies the probe, it raises UnauthorizedAccessException. setup.ps1 runs under $ErrorActionPreference = "Stop", so that probe was a terminating error with no handler and setup died with exit code 1.
  2. The only failure marker left for the desktop app was [TAURI:ERROR_DEFAULT], so the UI showed Installation failed: unsloth studio setup failed (exit code 1) and the real cause stayed buried in the log.
  3. $LlamaCppDir is %USERPROFILE%\.unsloth\llama.cpp for a default studio home, which lives beside the app rather than inside it. Reinstalling reused the same unreadable folder, so a second install to D:\ died on the identical line and there was no way forward.

The installer does not create this state itself: it never sets ACLs and never elevates on Windows (elevation is Linux/apt only). The denial comes from the machine, for example antivirus or Controlled folder access, a tree created by another or elevated account, or a junction pointing at a locked target. Rare, but a permanent hard stop when it happens.

Fix

studio/setup.ps1:

  • New Test-AccessDeniedError, Get-PathState (Present / Absent / Denied), Test-PathQuiet and Get-PathDenialDetail. Get-PathState keeps Denied distinct from Absent so a denial gets reported rather than silently retried.

  • The crash site now branches on Denied and stops through Exit-SetupFailure, which emits [TAURI:ERROR]. install.rs prefers that over its generic exit-code message, so the desktop app now shows:

    Installation failed: Access denied reading the existing llama.cpp install at C:\Users....unsloth\llama.cpp. Delete or rename that folder (Unsloth reinstalls it) or restore access with takeown/icacls, then re-run setup. Reinstalling the app does not reset it.

    The console adds the steps: close Unsloth, delete or rename the folder, takeown / icacls if deleting is also denied, and check antivirus or Controlled folder access. If the folder is a junction, the message names the link target.

  • The other probes that read inside an install tree we do not own now use Test-PathQuiet: the studio-owned marker checks, the llama-server.exe candidate scans, the .git source-build probe, and the whisper.cpp read of the llama.cpp marker. That last one matters on its own, since whisper failures are non-fatal by contract but this probe could still abort setup.

  • Assert-StudioOwnedOrAbsent reports "cannot be read: access is denied" instead of the misleading "not marked as an Unsloth-owned install". Ownership is unknowable while the tree is unreadable. Both branches stay gated on $StudioHomeIsCustom, so default-home behaviour is unchanged.

Nothing outside the denied path changes: a readable install still takes the exact same route it did before.

Tests

tests/studio/test_path_probe_access_denied.ps1 (new, 30 checks, wired into the PowerShell installer unit test step):

  • Runs the real functions against a genuinely unreadable directory, icacls /deny on Windows and chmod elsewhere.
  • Negative control that the old bare Test-Path still terminates on the same path, which also gates the suite so it cannot pass vacuously on a host where the denial does not take.
  • Runs the real Denied branch with the real Exit-SetupFailure under UNSLOTH_TAURI_MODE=1 and asserts the [TAURI:ERROR] line the UI consumes, the exit code, and that the branch does not fall through into the install.

tests/studio/install/test_setup_denied_install_tree.py (new, 7 tests, runs in Backend CI) covers the source contract, including a scan that fails if a bare Test-Path reappears inside the llama.cpp tree.

Two anchors in tests/test_studio_install_workspace_guard.py were updated to the new call text. Their assertions are unchanged and all 45 tests in that file pass.

Local run of tests/studio/install, tests/test_studio_install_workspace_guard.py, tests/python/test_cross_platform_parity.py, tests/studio/test_ci_shell_suite_coverage.py and tests/test_profile_startup_gate.py: 1625 passed. The 26 failures left in test_rocm_support.py and test_managed_node_runtime.py fail identically on an unmodified tree, they are pre-existing on macOS and unrelated.

Note

This fixes the handling, not the cause of the denial, which I could not determine from the report alone. Anyone hitting it still has to clear the folder, but they now get told which folder and why a reinstall will not help. The [TAURI:ERROR] text also makes further reports easy to identify in the diagnostics if a systemic cause turns out to be behind it.

Workaround for anyone on the current build: delete or rename %USERPROFILE%\.unsloth\llama.cpp and retry. It is a managed cache and gets reinstalled.

Reported in unsloth-test/unsloth-test#9

Test-Path raises UnauthorizedAccessException instead of returning $false
when an ACL denies the probe. setup.ps1 runs under $ErrorActionPreference
= "Stop", so the bare probe of UNSLOTH_PREBUILT_INFO.json in the llama.cpp
prebuilt phase killed setup with a raw "Test-Path : Access is denied" and
exit code 1. The desktop app had nothing but [TAURI:ERROR_DEFAULT] to fall
back on, so it showed "unsloth studio setup failed (exit code 1)".

~/.unsloth/llama.cpp sits beside the app, not inside it, so reinstalling
reused the unreadable folder and hit the same line again, including a
reinstall to a different drive.

Add Get-PathState (Present / Absent / Denied) plus Test-PathQuiet, route
the probes that read inside install trees we do not own through them, and
report a denied llama.cpp install through Exit-SetupFailure so the reason
and the recovery steps reach the desktop UI.

Reported in unsloth-test/unsloth-test#9
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Review follow-ups:

- Assert-StudioOwnedOrAbsent treated a denied root as absent and returned,
  so the caller could go on to replace a tree it cannot read. Probe the
  root three-state and stop on Denied, still gated on $StudioHomeIsCustom
  so default-home behaviour is unchanged.
- The source-build .git probe treated a denied checkout as "no checkout"
  and cloned a replacement. The swap that follows recursively removes the
  original and moves the temp tree over it under "Continue" and unchecked,
  so a denied child could leave a half-deleted install. Stop instead.
  This path already treated denied as absent before the previous commit
  (that probe runs under "Continue", so it printed an error and took the
  false branch), so the hazard is older than this branch, but it is in
  scope for the same reason.
- Probe $LlamaCppDir itself three-state, so an unreadable parent is
  reported rather than dying on the bare probe under "Stop".
- takeown and icacls were printed joined by "then", which is not a
  PowerShell separator: takeown would swallow the rest as arguments and
  icacls would never run. Print them on separate lines.

Fold the repeated guidance into Exit-PathAccessDenied so all five denial
routes report the same thing.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Went through all three. Two are correct as written, one identifies a real hazard but misattributes where it came from. Fixed in 4c136b8.

1. Denied root treated as absent in Assert-StudioOwnedOrAbsent (P1): correct.

Test-PathQuiet collapsed Denied into $false, so the guard returned before it ever checked the marker and the caller carried on against a tree it cannot read. That is exactly the case the guard exists to catch. The root is now probed three-state, and Denied routes to the same actionable stop. Both stops stay gated on $StudioHomeIsCustom, deliberately: the sidecar venv call sites run under Continue, where the old bare probe printed an error and returned false rather than terminating, so an ungated stop would turn a previously-proceeding default-home path into a hard failure. Custom homes, which is the scenario in the comment, are fully covered.

2. Denied .git checkout in the source-build path (P2): real hazard, wrong attribution.

The hazard is right. The fresh-clone branch ends in a swap that does Remove-Item -Recurse -Force on the original and then Move-Item over it, and that block runs under $ErrorActionPreference = "Continue" (set at the top of Phase 4) with neither operation checked, so a denied child can leave a half-deleted install and a silently failed move.

What is not right is that this branch caused it. That probe also sits under Continue, and Test-Path there never terminated, it emitted a non-terminating error and the if took the false branch. Verified:

EAP=Continue result: FALSE-branch     # error printed, treated as absent
EAP=Stop:            TERMINATED

So the clone-over-a-denied-checkout behaviour predates this branch; the previous commit only stopped printing the error. Fixed anyway, since it is the same class of bug and cheap to close: the probe is three-state and Denied stops before the swap can run.

3. then between takeown and icacls (P2): correct, and a bad one.

then is not a statement separator, so a copy-paste would hand then icacls ... to takeown as arguments and icacls would never run, leaving the user exactly where they started. They are on separate lines now, with a test that asserts the two commands never share an output line.

Also folded in while I was there

$LlamaCppDir itself is now probed three-state, so an unreadable parent is reported instead of dying on the bare probe under Stop. All five denial routes go through one Exit-PathAccessDenied helper rather than repeating the guidance text.

Verification

36 checks in test_path_probe_access_denied.ps1 and 9 in test_setup_denied_install_tree.py, all passing. I re-introduced both real bugs to confirm the new checks are not vacuous:

FAIL  the ownership guard stops on a denied root instead of returning
FAIL  icacls is not appended to the takeown line

Both fail on the old code and pass on the new. Surrounding suites: 1627 passed, with the same 26 pre-existing failures in test_rocm_support.py and test_managed_node_runtime.py that fail identically on an unmodified tree.

Ran the real decision blocks against simulated filesystems (denied file,
denied parent, traverse-only and list-only dirs, symlinks, dangling links,
wildcard and unicode paths, 3000 random paths) plus PSScriptAnalyzer's
5.1/6.2/7.0 syntax check. Two things came out of it:

- Get-PathDenialDetail threw a parameter-binding exception on an empty
  path. It runs while a failure is being reported, so it would have
  replaced the actionable message with a raw binding error at exactly the
  wrong moment. Null and empty are now accepted and return no detail.
- The link-target lookup used an empty catch, which PSScriptAnalyzer flags
  and which hid the intent. It assigns $null explicitly now.

Both are covered by new checks. Also promoted the strongest invariant from
the simulation into the suite: Get-PathState must agree with a bare
Test-Path on every probe that did not throw, and Denied may only appear
where the old probe threw, so no path that worked before can take a
different branch now.

Verified: PSUseCompatibleSyntax reports nothing for 5.1, 6.2 and 7.0; the
Python contract tests pass on 3.10 through 3.13 in separate uv venvs; the
tauri install:: unit tests pass (17), which is the code that prefers the
[TAURI:ERROR] line over the generic exit-code message.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Ran a simulation pass over this branch rather than trusting the unit tests alone. Seven suites, 158 assertions, in throwaway sandboxes under a gitignored temp/. Two real defects came out of it, both fixed in 11e5b5e.

What it actually proves

The reported failure, reproduced and then fixed on the same fixture. The pre-PR block is pulled straight out of git show bba8e39:studio/setup.ps1, not retyped, and driven against an install dir whose metadata cannot be read:

pre-PR  : Test-Path: ... if (Test-Path $existingMetaPath) {   Access to the path ... is denied
          exit 1, no [TAURI:ERROR] for the app to show
this PR : STEP|permissions|llama.cpp install at ... cannot be read: access is denied
          SUBSTEP|This folder lives outside the app, so reinstalling ... reuses it
          SUBSTEP|takeown /F "..." /R /D Y
          SUBSTEP|icacls "..." /reset /T
          [TAURI:ERROR] Access denied reading the existing llama.cpp install at ...
          exit 1

The real decision blocks, not a re-implementation. Slices of setup.ps1 are extracted and validated with [Parser]::ParseFile before running, with only side-effecting commands stubbed. 26 assertions across the prebuilt phase, the source-build .git branch and the ownership guard: absent, readable-with-metadata and readable-without-metadata all reach the installer exactly as before; denied metadata, denied parent and denied .git all stop; the denied .git case never reaches the destructive swap; a default-home denial still returns from the guard rather than gaining a new hard stop.

Exit code is 1 in every stop path. Asserted explicitly, because install.rs treats code 2 with pending packages as an elevation request, so a denial exiting 2 would have shown the wrong dialog.

No behaviour change outside denials. The load-bearing invariant, now in the suite: Get-PathState must agree with a bare Test-Path on every probe that did not throw, and Denied may only appear where the old probe threw. Swept 111 probe/PathType combinations locally.

Copy-paste correctness of the recovery commands, checked by parsing each emitted line with the PowerShell parser across four awkward paths (spaces, parentheses, brackets, unicode): one CommandAst per line, takeown gets exactly /F <path> /R /D Y, the quoted path survives as a single argument, and icacls is never swallowed. Negative control: the joined then form parses as one command with then and icacls as arguments, which is the bug that was fixed.

Two defects found and fixed

  1. Get-PathDenialDetail threw on an empty path. A mandatory [string] rejects null and empty, so the helper that builds the error message could throw a binding exception while a failure was already being reported, replacing the actionable message with a raw error at the worst moment. Null and empty are accepted now and return no detail. Not reachable from today's call sites, but an error path that can itself error is not worth keeping.
  2. Empty catch on the link-target lookup, flagged by PSScriptAnalyzer and unclear to read. Assigns $null explicitly now.

Both have checks that fail if the fix is reverted, verified by reverting them.

Coverage and gaps

Area Result
Filesystem matrix (denied file, denied parent, traverse-only 111, list-only 444, symlink, dangling link, link to denied target, PathType mismatch, vanished mid-probe) 35/35
Real decision blocks 26/26
Message and copy-paste contract 58/58
PS 5.1 / 6.2 / 7.0 syntax (PSUseCompatibleSyntax) 0 findings
Fuzz: 40 hostile inputs x 3 PathTypes, 3000 random paths, 5000-deep exception chain, idempotence 21/21
Python contract tests on 3.10 / 3.11 / 3.12 / 3.13, separate uv venvs 55 passed each
cargo test install:: (the code that picks the message the UI shows) 17 passed
Repo suites 1628 passed, 26 pre-existing failures identical on an unmodified tree

Gaps worth stating: this ran on macOS, so Windows ACL denials via icacls are covered by the CI job on windows-latest, not here, and 5.1 is covered by static syntax analysis rather than a live 5.1 engine. POSIX mode bits stand in for ACLs in the local matrix, which exercises the same UnauthorizedAccessException path in .NET. No browser or frontend surface is touched by this branch, so there is nothing to check across Firefox, Safari, Chrome or Edge.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

studio-windows-inference-smoke.yml runs six PowerShell unit tests out of
tests/studio, but its pull_request paths filter matched none of them, and
no other workflow runs them. A PR touching only one of those tests never
ran it. Five predate this branch; the sixth is the ACL test added here.

Scope the filter to tests/studio/*.ps1 rather than tests/studio/**, so a
python-only change under that directory does not pull in the GGUF smoke
jobs. This matches what the other two workflows already do: parity-ci
lists its .ps1 test outright and update-smoke uses a scoped glob.

Guard it in test_ci_shell_suite_coverage.py, which exists for this exact
failure (tests/sh had the same hole): every tests/*.ps1 a workflow invokes
must be matched by that workflow's paths filter, and must exist. The
GitHub glob matcher it needs has its own table-driven test, since a wrong
matcher would make the guard pass on everything.

Verified by reverting the one-line filter change: the guard then names all
six unrun tests.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Checked this one against the YAML rather than taking it on faith. It is correct, and the repo's own convention backs it up.

Mapping every workflow that invokes a tests/**.ps1 file against its pull_request.paths:

workflow .ps1 tests it runs covered by its paths filter
cross-platform-parity-ci.yml 1 yes, listed outright
studio-windows-update-smoke.yml 3 yes, via tests/studio/test_uninstall_*.ps1 and an explicit entry
studio-windows-inference-smoke.yml 6 none

So the gap is real, and it is not only mine: five of those six predate this branch (test_resolve_cuda_toolkit, test_torch_flavor, test_node_decision, test_node_probe_guard, test_uninstall_dual_install_icon). A PR touching only one of them never ran it, and no other workflow picks them up.

Fixed in c6eff68 with tests/studio/*.ps1, deliberately not tests/studio/**: the directory holds a lot of Python tests, and the broad form would pull the three GGUF smoke jobs into every python-only change there. The scoped glob matches what update-smoke already does.

Guarded it in test_ci_shell_suite_coverage.py, which exists for precisely this failure mode on the tests/sh side. It now also asserts that every tests/*.ps1 a workflow invokes is matched by that workflow's paths filter, and that the file exists. GitHub's glob rules are not fnmatch (* does not cross /, ** does), so the matcher has its own table-driven test; a wrong matcher would make the guard pass on everything.

Verified by reverting the one-line filter change, which makes the guard fail and name all six:

AssertionError: these PowerShell tests can break without any PR running them; add the
path (or a scoped glob) to the workflow's paths filter:
['studio-windows-inference-smoke.yml runs tests/studio/test_node_decision.ps1 but its paths filter never matches it',
 ... six entries ...]

Restoring the filter turns it green. Full local pass afterwards: 1641 passed, with the same 26 pre-existing failures in test_rocm_support.py and test_managed_node_runtime.py that fail identically on an unmodified tree, and the contract tests still pass on Python 3.10 through 3.13.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: c6eff68d06

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

Verifying the path-filter fix turned up a second hole in the same step. A
`shell: pwsh` step inherits only the LAST command's exit code, and this
step ran five tests as five bare commands, so only the last one could fail
the build. test_resolve_cuda_toolkit.ps1 has been printing

    FAIL  exits non-zero      (scenario 2, forced source build)
    FAIL  exits non-zero      (scenario 6, no toolkit, forced)
    2 check(s) FAILED

on every Windows run, exiting 1, and the job reported success. Confirmed
on main (run 30723608191, sha c67410a), so it predates this branch, and
it reproduces locally.

The cause is in the test, not the installer. Resolve-CudaToolkit
-RequireOrExit leaves through Exit-SetupFailure, which the child harness
never stubbed, so under ErrorActionPreference=Continue the call was an
ignored command-not-found, the child fell through and exited 0. The
harness already injects the real Resolve-CudaToolkit and
Write-CudaDriverToolkitMismatch by AST, so inject the real
Exit-SetupFailure the same way. That test now passes 25/25.

With it green, add the exit-code checks after each invocation, matching
what studio-windows-update-smoke.yml already does, and guard the pattern
in test_ci_shell_suite_coverage.py: any step running more than one
PowerShell test must check $LASTEXITCODE after each.

Verified by reverting each piece: dropping one check makes the guard name
that test, and dropping the Exit-SetupFailure injection brings both
scenario failures straight back.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

The latest Codex pass came back clean, so I re-checked the four earlier points against HEAD rather than take that as the last word. All nine sub-assertions are closed: the guard probes its root three-state and stops on Denied, the .git probe stops before the clone and swap, the two recovery commands sit on their own lines with no then joining them, and all six PowerShell tests this workflow runs are now matched by its paths filter.

While verifying that last one I found a second hole in the same step, and it is a bigger one.

The Windows step was reporting green over a failing test

A shell: pwsh step inherits only the last command's exit code. That step ran five tests as five bare commands, so only the fifth could ever fail the build. test_resolve_cuda_toolkit.ps1 has been printing this on every Windows run:

Scenario 2: forced source build, newer-major toolkit (-RequireOrExit) -> hard exit
  FAIL  exits non-zero
Scenario 6: no toolkit, forced (-RequireOrExit) -> winget attempted then exit
  FAIL  exits non-zero
2 check(s) FAILED

and exiting 1, while the job reported success. Same two failures on main (run 30723608191, sha c67410a7), so it predates this branch, and it reproduces locally.

The cause is the test, not the installer. Resolve-CudaToolkit -RequireOrExit leaves through Exit-SetupFailure, which the child harness never stubbed, so under ErrorActionPreference=Continue the call was an ignored command-not-found, the child fell through and exited 0. The harness already injects the real Resolve-CudaToolkit and Write-CudaDriverToolkitMismatch by AST, so I inject the real Exit-SetupFailure the same way. That test now passes 25/25, and the two scenarios genuinely exercise the exit path they were written for.

With it green, the exit-code checks are in, matching what studio-windows-update-smoke.yml already does and comments as "Propagate each child test's failure before continuing". The pattern is guarded in test_ci_shell_suite_coverage.py, which exists for this class of bug: any step running more than one PowerShell test must check $LASTEXITCODE after each.

Verification

Both fixes were checked by reverting them:

# drop one exit-code check
AssertionError: these tests can fail without failing their step; add
`if ($LASTEXITCODE) { exit $LASTEXITCODE }` after each:
['studio-windows-inference-smoke.yml: tests/studio/test_torch_flavor.ps1 runs without an exit-code check']

# drop the Exit-SetupFailure injection
2 FAIL lines return

All five tests in that step pass locally with exit 0. Repo suites: 1642 passed, with the same 26 pre-existing failures in test_rocm_support.py and test_managed_node_runtime.py that fail identically on an unmodified tree. Contract tests still green on Python 3.10 through 3.13.

Worth saying plainly: the CUDA harness fix is outside this PR's subject. I took it because the exit-code fix could not go in without it, and leaving a test that fails on every run while CI shows green seemed worse than the extra diff. Happy to split it into its own PR if you would rather keep this one narrow.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

When UNSLOTH_LOCAL_LLAMA_CPP_DIR points at the canonical $LlamaCppDir and
the llama-server.exe there is ACL-denied, Test-PathQuiet collapsed Denied
to $false, $LocalLlamaServerFound stayed false, and the canonical branch
reported "nothing built there yet; running the normal install". The
prebuilt installer then moves that tree aside and replaces it, which is
exactly what the branch's own comment says it exists to prevent. The old
bare probe stopped first, by throwing under "Stop".

Probe the candidates three-state and stop on Denied. Same for the
directory probe itself, which reported an unreadable dir as "does not
exist" and sent the user after the wrong problem.

The generic message could not be reused as-is here: it tells the user to
delete the folder because Unsloth reinstalls it, which is true of the
managed cache and wrong for a build they pointed us at. Exit-PathAccessDenied
takes -UserSupplied, which swaps that advice for restoring access or
repointing UNSLOTH_LOCAL_LLAMA_CPP_DIR, and keeps the takeown/icacls lines.

Verified by driving the real block through every state: a readable build
is still reused, a genuinely empty canonical dir still falls through to
the normal install, a missing dir still reports "does not exist", and a
denied build now stops with exit 1 instead of being replaced. Reverting
the probe puts the fall-through back, and the user-supplied path never
prints "delete or rename" or "managed cache".
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Correct, and it is the sharpest one so far. Fixed in 2a61343, along with something it did not mention that would have made my own message actively harmful here.

The report checks out

The canonical branch says what it is for in its own comment:

Reuse an existing build here (skip prebuilt + source) so the staged prebuilt installer can't replace a build the user asked to reuse

A denied llama-server.exe made Test-PathQuiet return $false, $LocalLlamaServerFound stayed false, and the branch took the other road: "nothing built there yet; running the normal install". The prebuilt installer then moves that tree aside and replaces it, which is the exact outcome the branch exists to prevent. The old bare probe stopped first, by throwing under Stop. Driving the real block through the states with the old probe restored reproduces it:

FAIL  denied build STOPS instead of being replaced
      outcome=fallthrough
      SUBSTEP|UNSLOTH_LOCAL_LLAMA_CPP_DIR points to the canonical install location
              with nothing built there yet; running the normal install

Both candidate probes are three-state now. So is the directory probe above them, which reported an unreadable directory as does not exist and would have sent the user after the wrong problem.

What the report missed

My shared failure message says:

Simplest fix: close Unsloth, delete or rename <path>, then re-run setup (it is a managed cache and gets reinstalled)

True of ~/.unsloth/llama.cpp. Wrong for a tree the user pointed at with --with-llama-cpp-dir, which is their own build and which Unsloth must not touch. Routing this new case through the helper unchanged would have told people to delete work Unsloth cannot replace. Exit-PathAccessDenied now takes -UserSupplied, which swaps that line for restoring access or repointing UNSLOTH_LOCAL_LLAMA_CPP_DIR, and keeps the takeown / icacls lines. The canonical case still gets the managed wording, since there the path really is the managed cache.

Verification

Fourteen assertions driving the real block through every state, with the Windows-only mklink stubbed:

state outcome
canonical, readable build reused, installer never runs
canonical, nothing built falls through to the normal install
canonical, denied build stops, exit 1, [TAURI:ERROR], managed wording
user-supplied, readable proceeds to link
user-supplied, denied stops, exit 1, no "delete or rename", no "managed cache"
user-supplied, missing still "does not exist", not "cannot be read"

Denied is also no longer misdiagnosed as "no llama-server.exe was found".

One place I deliberately left Test-PathQuiet: the disk-space branch's preserved-server scan. It only decides whether a surviving binary is usable, and an unreadable one is not, so collapsing Denied there is correct. The contract test is scoped accordingly rather than banning the helper outright, with a comment saying why.

Repo suites: 1644 passed, same 26 pre-existing failures. All seven simulation suites still green (35, 58, 21, 26, 11, 14 assertions plus the 5.1/6.2/7.0 syntax check), the 41-check PowerShell regression test passes, and the contract tests pass on Python 3.10 through 3.13.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Three review points, all reproduced before fixing:

- The canonical --with-llama-cpp-dir override still got the managed
  advice ("delete it, Unsloth reinstalls it"). The override means the
  user asked to reuse whatever is in that tree, so deleting it is wrong
  wherever it sits. Both candidate denials now pass -UserSupplied, which
  collapses the branch to one call.
- Phase 1b's git prerequisite scan probes the same candidate binaries
  with a bare Test-Path under "Stop", thousands of lines before the
  Phase 4 guards, so a denied override terminated the run with the raw
  error this change exists to replace. Reproduced, then guarded.
- Test-StudioOwnedAdoptable collapsed a denied prebuilt marker to $false,
  so Assert-StudioOwnedOrAbsent called an Unsloth tree an unrelated
  directory and told the user to move it aside. Get-StudioAdoptableState
  returns Yes/No/Denied and the guard reports the denial first;
  Test-StudioOwnedAdoptable stays as the boolean view for the cosmetic
  cleanup gate.

A denied file under a readable directory is a Windows-ACL-only state:
POSIX keeps a mode-000 file stat-able, and a symlink into a denied
directory still answers Test-Path. The local run injects that one state
at the lowest seam and lets the real functions run; the Windows leg of
test_path_probe_access_denied.ps1 builds it for real with icacls and
skips elsewhere with the reason.

test_setup_ps1_adopts_existing_whisper_prebuilt_marker sliced between two
function names and the marker scan moved, so its anchor now points at
Get-StudioAdoptableState. Its assertion is unchanged.

Reverting each fix individually puts the original behaviour back: the
ownership misdiagnosis, the raw "Access to the path ... is denied" from
Phase 1b, and the delete-your-own-build advice.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

All three check out. Fixed in de486ff, each reproduced first and each re-checked by reverting it.

1. The canonical override is still the user's build

You are right and my reasoning was wrong. I gated on "is this path the managed cache" when the question is "did the user tell us to reuse this tree". --with-llama-cpp-dir pointed at the canonical location means exactly that, so the delete-it advice is wrong there too, and it may be a custom compile Unsloth cannot reproduce. Both candidate denials now pass -UserSupplied, which collapses that branch to a single call.

2. Phase 1b runs first, and it was still bare

Confirmed at line 1863, inside the if (-not $HasGit) prerequisite scan, probing the same three candidate binaries under ErrorActionPreference = "Stop". With the old probe restored, the simulation gets the original failure back:

FAIL  denied build stops the run instead of throwing a raw error
      Access to the path '.../mybuild/llama-server.exe' is denied.

Guarded, with the user-supplied wording since it is the same override.

3. A denied adoption marker was reported as an unrelated directory

Also correct. Get-StudioAdoptableState now returns Yes / No / Denied, and the guard reports the denial before the ownership wording. Test-StudioOwnedAdoptable stays as the boolean view for the cosmetic cleanup gate. With the collapse restored:

FAIL  guard/custom_denied_adoption_marker: denied_stop
      actual=ownership_stop
      [TAURI:ERROR] llama.cpp install path is not an Unsloth-owned install: ...

which is the misdiagnosis you described.

One thing worth recording about that last case

A denied file under a readable directory cannot be built on POSIX. A mode-000 file is still stat-able, so Test-Path returns True, and pointing the marker at a symlink into a denied directory also answers True. I checked both before concluding. It is a Windows-ACL-only state.

So the local run injects that single state at the lowest seam, one exact path, and lets the real Get-StudioAdoptableState and Assert-StudioOwnedOrAbsent run unchanged. Real-ACL coverage lives in the Windows leg of test_path_probe_access_denied.ps1, which denies the marker with icacls, verifies the denial actually took, and skips elsewhere with the reason printed rather than passing quietly.

Verification

Nine denial routes now, all reported rather than collapsed. Simulations: 35, 58, 21, 28, 11, 20 assertions plus the 5.1/6.2/7.0 syntax check, all green. Reverting each of the three fixes individually fails its own contract test and its own simulation assertion.

test_setup_ps1_adopts_existing_whisper_prebuilt_marker sliced between two function names and the marker scan moved into the new function, so its anchor points at Get-StudioAdoptableState now. The assertion is untouched, and I retargeted the anchor rather than reordering the code to keep a stale slice working.

Repo suites: 1646 passed, same 26 pre-existing failures in test_rocm_support.py and test_managed_node_runtime.py. Contract tests green on Python 3.10 through 3.13.



- tests/sh/test_with_llama_cpp_dir_flag.sh anchored the literal
  'if ($ResolvedLocal -eq $LlamaCppDir) {', which 2a61343 hoisted into
  $LocalIsCanonical. Re-pin it to the comparison, not the branch.
- The junction path deleted and replaced $LlamaCppDir behind a bare
  Test-Path, so a denied destination still threw raw under a default home.
  Probe it three-state, and treat Denied as surviving removal.
- Get-Content on the prebuilt metadata still globbed while the probes
  gating it went literal, so a path holding [ or ] passed the probe and
  threw into the catch. Make both reads literal, with a test.
- Get-PathDenialDetail could throw on a non-filesystem provider item whose
  .Attributes has no -band overload, replacing the failure being reported.
- Win32Exception keeps E_FAIL in HResult and the code in NativeErrorCode,
  so the HRESULT check never matched it. Fix the comment and the check.
- test_windows_git_gate.py ran the layout scan in a child that never
  defined Get-PathState, so de486ff had it silently report nothing built.
  Inject the real helpers, as test_resolve_cuda_toolkit.ps1 does.
- Relax the exact Exit-PathAccessDenied count to a floor and key the
  -UserSupplied rule on the path reported rather than on position.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed 44e14f7 on top of de486ff. Six things, one of which is a regression that commit introduced.

The CI failure

Repo tests (CPU) has been red since 2a61343. tests/sh/test_with_llama_cpp_dir_flag.sh:162 anchors the literal if ($ResolvedLocal -eq $LlamaCppDir) {, which that commit hoisted into $LocalIsCanonical. The guarded behaviour never changed, only the text. Re-pinned to the comparison rather than the branch, so the anchor still guards the self-link footgun it was written for.

Confirmed it is this branch and not something pre-existing: the file is 24/24 on origin/main, was 23/24 here, and reverting the hoist in a scratch tree turns the new anchor red again.

A regression in de486ff

tests/python/test_windows_git_gate.py slices the Phase 1b layout scan into a child pwsh and never defined Get-PathState. Once that commit routed the scan through it, the call was a command-not-found under Continue, $_cState came back $null, $_localLlamaBuilt stayed false, and _needs_git returned True where it must return False. test_a_built_local_llama_dir_drops_the_source_build_git_requirement fails on de486ff with no other changes applied.

Same shape as the Exit-SetupFailure gap in test_resolve_cuda_toolkit.ps1, so it is fixed the same way: inject the real Test-AccessDeniedError and Get-PathState by brace-matched extraction, plus a throwing Exit-PathAccessDenied stub so a denial in that scan cannot pass silently.

Denied destination in the junction path

setup.ps1:4052 deleted and replaced $LlamaCppDir behind a bare Test-Path. The guards added so far cover $LocalLlamaCppSrc and the candidates under $ResolvedLocal, which is the source, not the destination. Under a custom home Assert-StudioOwnedOrAbsent catches it two lines up; under a default home nothing had probed it three-state, so a denied ~/.unsloth/llama.cpp still died with the raw Test-Path : Access is denied this PR exists to remove. It is now three-state.

The re-probe after Remove-Item moved to -ne "Absent" rather than Test-PathQuiet. That check asks whether the tree survived removal, and collapsing Denied to $false there would report an unreadable survivor as gone and then junction over it. Unreadable is not gone.

Literal probe, globbing read

Get-InstalledLlamaPrebuiltRelease and the install_kind check went to -LiteralPath on the probe but the Get-Content each one gates still used -Path, three lines apart, while the whisper marker read at 4337 already had it right. On a path holding [ or ] the probe now passes and the read throws into the catch, so the metadata is still unreadable and the net outcome is unchanged. Both reads are literal now, with a test, since reverting the change on its own kept the suite green.

Worth noting the direction of that earlier change, because it is not only about denials: the old bare Test-Path $existingMetaPath was wrong in both directions on bracket paths, reading an existing file as absent and a missing one as present when a glob sibling existed, and an unterminated [ threw ParameterBindingException, which terminates under Stop.

Two smaller ones

Get-PathDenialDetail could throw on an item whose .Attributes has no -band overload, which would replace the failure being reported with a RuntimeException. Reproducible on 6.2 through 7.6. Not reachable today, but an error path that can itself error is worth closing given the comment promises otherwise.

Test-AccessDeniedError claimed Win32Exception carries the HRESULT for error 5. It does not: Win32Exception(int) only sets NativeErrorCode, and ExternalException(string) puts E_FAIL in HResult. Measured -2147467259, not -2147024891, on five runtimes. True for IOException, and true by coincidence for UnauthorizedAccessException, which is the one that actually arrives from Test-Path. Comment corrected and a NativeErrorCode arm added.

Test contracts

The exact Exit-PathAccessDenied -Path count is now a floor. Losing a denial route is the bug; adding a legitimate one should not fail the suite, which is exactly what happened here.

test_user_supplied_paths_are_never_told_to_delete_themselves asserted that every call in the local block passes -UserSupplied. That block now also reports the managed destination, where "delete or rename, Unsloth reinstalls it" is the correct advice and the user's own build at --with-llama-cpp-dir is untouched. The rule is keyed on the path being reported instead of on position, and now also asserts the managed destination does not get the user-supplied wording.

Verification

12 PowerShell suites, 28 shell installer tests and 1272 Python tests pass. The only Python failures left are the 4 in test_managed_node_runtime.py and test_tokenizers_and_torch_constraint.py that fail identically on an unmodified tree.

Each fix was checked by reverting it: dropping the helper injection returns the git-gate failure, dropping the anchor returns 23/24, and dropping -LiteralPath fails the new metadata test. The -LiteralPath change had no coverage at all until that test was added, which is why it is there.

Also ran the branch through a staging repo to get real Windows coverage, since icacls /deny behaves differently from POSIX mode bits. Windows Unsloth GGUF CI and Windows Unsloth Update CI both green across all jobs, including VS 2022, VS 2026, the VC++ runtime round-trip and the no-Visual-Studio install, with no SKIP cannot deny access on this host in the log and the bare Test-Path still terminates on a denied path negative control firing, so the denial genuinely took. Clean machine install was green there too, which makes the earlier virgin win container / probe red look like the astral.sh timeout it reported rather than anything on this branch.

Left alone

The whisper phase still violates its own "failures are never fatal" contract under a custom home, where a denied tree kills the whole setup. Every $WhisperCppDir line is byte-identical before and after this PR, so it is pre-existing and belongs in its own change rather than widening this one.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

The ownership guard stops precisely because it could not read the marker,
so it cannot claim the folder is ours either. It was still emitting the
managed-cache text, telling the user to delete it. Eleven lines below, the
readable-but-unowned branch says 'move it aside' instead, so we were being
gentler when we could prove the tree was not ours than when we could not
read it at all. New -OwnershipUnverified wording for those three stops.

Also from re-reading the previous commit:

- The reparse-point unlink above the junction path ran before the new
  three-state probe, and a link reports Present, so the probe could not
  cover it. A denied unlink still terminated on the raw .Delete() throw.
- That junction destination probe had no test at all; reverting it left
  the suite green, since the count floor cannot see a swap. Pinned by
  name like every other route.
- The re-pinned shell anchor accepted an assignment that nothing consumed.
  Pin the branch that uses it too.
- Get-PathDenialDetail now checks the item type rather than the attribute
  type, which also covers a provider item with no Attributes at all.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The guard above the clone path probes only .git, but its own comment names
any unreadable child as the risk. A forced source build over a non-git
install with a denied child elsewhere reads Absent, clones into a temp dir,
and reaches the swap.

Both steps there are non-terminating under Continue and neither was
checked. Reproduced: Remove-Item partially fails, the original survives,
and Move-Item then moves the temp dir INSIDE it, so the new binary lands at
llama.cpp/llama.cpp.build.<pid>/llama-server.exe while $LlamaServerBin
points at llama.cpp/build/bin/Release. Setup carries on reporting success
with no usable server and a half-deleted install.

Check the removal before moving, so the stop happens while the temp build
is still whole, and check the move afterwards. Denied routes through
Exit-PathAccessDenied; anything else surviving exits 3 like the other
blocked-replacement paths.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 2, 2026
@unslothai unslothai deleted a comment from shimmyshimmer Aug 2, 2026
@unslothai unslothai deleted a comment from shimmyshimmer Aug 2, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1d662445bd

ℹ️ 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 ebfefcf into main Aug 2, 2026
71 of 73 checks passed
@danielhanchen
danielhanchen deleted the fix/setup-ps1-denied-llama-install branch August 2, 2026 14:25
danielhanchen added a commit that referenced this pull request Aug 3, 2026
…le install tree (#7757)

* Windows: guard the source-build and whisper.cpp probes on an unreadable install tree

Follow-up to #7735, which routed the prebuilt llama.cpp probes through
three-state path probing but left two gaps.

Phase 4 read $LlamaServerBin with a bare Test-Path under "Stop". A forced
compile, a pinned PR or a custom llama source skips Phase 3.4 entirely, so on
those routes this was the first probe inside the tree and a denied build\
aborted with the raw "Test-Path : Access is denied" the merged PR set out to
remove. It now probes three-state, and the CMakeCache.txt read below it is
guarded too: a listed file can still deny the read, which the probe cannot see.
The probe is skipped for a linked UNSLOTH_LOCAL_LLAMA_CPP_DIR, where it would
read through the junction into the user's own checkout, and the denial reports
-OwnershipUnverified under a custom home, where nothing on this route has
proven the tree is ours.

The whisper.cpp phase promises failure is never fatal, but under a custom
UNSLOTH_STUDIO_HOME an unreadable tree exited the whole run, taking llama.cpp
inference down with it. Assert-StudioOwnedOrAbsent gains a -NonFatal mode that
hands the denial back instead; an unowned tree still stops. The check stays
behind the installer-exists gate it used to sit inside, so a tree without
install_whisper_prebuilt.py remains the no-op it was.

Backend: _is_runnable let Path.is_file() propagate EACCES. Now that setup
leaves a denied whisper.cpp in place, that turned into a 500 out of
/api/inference/audio/stt/status, the one endpoint reporting both dictation
engines, so the setup message promising Transformers dictation still works was
not true. It reads as engine-unavailable instead.

* Harden the denial contract tests against surviving mutations

Mutation testing found six ways to reintroduce the bugs this branch fixes
while the tests stayed green.

Assert-StudioOwnedOrAbsent: the -NonFatal returns were counted, not ordered.
Moving one below its Exit-PathAccessDenied makes it dead code and the whisper
phase fatal again; hoisting one above the custom-home gate reports a fresh
install as unreadable. Each return is now pinned immediately above the exit it
pre-empts, with no unpaired return allowed.

The whisper denial branch had no assertion scoped to its own body. Both
phrases it was checked for already occur elsewhere in the phase, so the branch
could be turned back into an Exit-SetupFailure and stay green. The branch is
now sliced out and checked for step/Yellow, both phrases, and the absence of
any exit.

The installer gate was checked for presence, not for being a conjunct, so
-or-joining or negating it reopened the installer-less tree the test is named
for. The denial subject was unpinned, so it could name llama-server.exe and
tell the user to move aside one file instead of the tree.

Slice terminators are now asserted through one helper: an unasserted
terminator does not fail, it silently widens the window to end-of-file and
makes everything inside it near-vacuous.

The whisper binary probe test gated its only behavioural case on geteuid() == 0,
which silently drops it in any root container. It probes for a real denial
instead. Two pre-existing exact counts in the ownership guard tests become
floors: this branch consumed the last of their headroom, so the next
legitimate route added there would break two tests that say nothing about it.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix the -NonFatal negative control for Windows ACL semantics

The control probed a marker file that did not exist. Windows reports a
missing child of a denied directory as absent rather than throwing, so the
control read as "this host cannot deny" and failed the suite on
windows-latest while passing under chmod on Linux. It now probes a file that
exists inside the locked tree, matching the control the suite already uses.

That difference also splits the routes by platform for a tree with no
ownership marker, which is the fresh custom-home case: Linux catches it on the
marker probe, Windows has to catch it on the adoptable-state read. Added a
case that accepts either route and rejects anything but Denied, so the Windows
one is exercised for the first time.

* Detect a denied tree that has no ownership marker on Windows

Staging CI on windows-latest caught this. Get-StudioAdoptableState decided
"denied" only from probes of two marker files inside the tree, but Windows
reports a MISSING child of an unreadable directory as absent rather than
throwing. A denied tree holding neither marker therefore returned "No", and
Assert-StudioOwnedOrAbsent fell through to "path is not an Unsloth-owned
install" and exited: the wrong cause, and fatal, on the only platform any of
this runs on. It also defeated the whisper -NonFatal path, since an unowned
tree is still fatal by design.

Listing the directory itself distinguishes "no markers here" from "cannot
look", so that is the fallback when neither probe reported a denial. A
readable tree with no markers still returns "No" as before, and the catch
swallows anything that is not a denial because this helper must not throw.

This also corrects the message a denied custom-home llama.cpp tree produced on
Windows, which reported the same wrong cause.

chmod 000 blocks the child probes outright, so it never reached the new code.
chmod 111 allows stat of a named child while forbidding a listing, which is
exactly the Windows shape, so the test now covers both and the negative
control fires only on the 111 case.

* Tighten comments in the denied-tree and whisper install changes

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Aug 3, 2026
…else's (#7771)

* Linux/macOS: tell an unreadable llama.cpp install apart from someone else's

setup.ps1 learned this in #7735 and #7757; setup.sh never did.

A tree that is ours, carrying our own marker, reads as somebody else's the
moment it stops being searchable, because every probe inside it reports the
marker absent. The ownership guard then said the folder is not an
Unsloth-owned install and told the user to move it aside or pick an empty
UNSLOTH_STUDIO_HOME, when the actual fix is a permission change. Search (+x)
is what those probes need, not read (+r): a directory can be readable and
unsearchable (mode 444) or searchable and unreadable (mode 111), so the new
probe tests search.

The two destructive replaces also ran blind. Under errexit a failing rm -rf
aborts on a raw permission error with no [TAURI:ERROR], so the desktop app
shows a bare exit code and the freshly built llama.cpp is left in the temp
directory with nothing saying where. Both sites now tolerate the failed
remove, check that the directory is actually gone, and report either the
permission problem or where the new build was left, exiting 3 as the Windows
side does for a build that succeeded but could not be installed.

Neither message tells the user to delete a folder Unsloth cannot prove is its
own, matching the rule the Windows guard follows.

* Keep the rm error when a replace fails

The redirect this PR added swallowed the one line that names which subtree
refused to go. rm reports the deepest failing path, llama.cpp/build say, while
the message below it can only name the install root, so a user whose build
directory alone is locked lost the part that told them where to look.

|| true is what keeps errexit from aborting; the redirect was never doing that
job, so stderr stays.

* Tighten the comments on the denied-install-tree guards
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