Skip to content

Unsloth Studio Installer: ask Python for a path identity before giving up on an exact one - #11104

Merged
danielhanchen merged 28 commits into
mainfrom
av-fp-early-python
Sep 28, 2026
Merged

danielhanchen merged 28 commits into
mainfrom
av-fp-early-python

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

The gap

Resolve-StudioFinalPathInfo has two rungs: the native GetFinalPathNameByHandleW helper, and a lexical fallback that answers but reports Exact = $false.

Exact is what the install and runtime locks key on. So every host that cannot build the native helper keys its locks on an identity nobody vouches for. That includes every host under WDAC Dynamic Code Security that stays in FullLanguage, since Dynamic Code Security always blocks unsigned reflection-emit assemblies and has no audit mode before 24H2.

Constrained Language Mode is out of scope. There, Resolve-StudioFinalPathInfo throws at its first [System.IO.Path]::GetFullPath call, before any rung runs, and the install lock cannot be created, so the installer stops before it needs an identity.

The rung

A third source exists and costs nothing to try. pathlib.Path.resolve calls GetFinalPathNameByHandleW on Windows, so it follows junctions, symlinks and SUBST drives, expands 8.3 names and reports stored casing. Same API, same answer.

It is also the expression unsloth_cli/_studio_runtime_gate.py already uses (_resolved_windows_path). The probe uses strict=True, which returns the same string for any path that resolves and raises on a link loop or dangling component, so those fall back to the lexical answer with Exact = $false. Interpreters older than 3.8 are refused, because their Windows resolve does not follow links. The answer is taken verbatim, without trimming. A runtime lock name derived from this rung agrees with a running Unsloth by construction, rather than by two implementations happening to match. That is stronger than the status quo, not weaker.

Why this cannot affect a healthy host

The rung sits inside the branch that runs only when the native helper returned nothing. Verified from the AST rather than by reading:

call sites of Get-StudioPythonFinalPath: 1
  in function : Resolve-StudioFinalPathInfo
  guarded by  : [string]::IsNullOrEmpty($resolved)

One call site, one guard. A host that resolves natively executes exactly the code it did before.

Finding an interpreter without installing one

This runs before the install lock, so it must not mutate anything. It is Get-Command and Test-Path only:

  1. a previous install's own venv python, since reaching it through $VenvDir follows an alias of the root without canonicalising anything
  2. python3 then python on PATH

Never Install-PythonFromPythonOrg, and never Find-CompatiblePython, which is defined thousands of lines further down and would not be callable this early.

The probe is a resolve call on the interpreter's own directory rather than a version check, so an interpreter that cannot answer one is rejected where it is found instead of passing a check and failing later.

A miss taken before $VenvDir is assigned (the --tauri path gets here first) is probed once more after it is assigned. Answers are cached per distinct path, because the process scan asks for the same image paths repeatedly.

Safety

  • -I -S, so PYTHONPATH, the user site directory and a system sitecustomize cannot change the answer. -I alone still imports site.
  • A wall-clock deadline with a kill. A wedged interpreter must not wedge an installer that has not yet taken its lock. Tested: a deliberately hung interpreter returns null and is killed at the deadline.
  • A relative answer, or one naming a path that does not exist, is rejected rather than trusted.
  • UNSLOTH_EARLY_PYTHON_PROBE=0 disables the rung and restores the previous ladder exactly, matching the existing UNSLOTH_NVIDIA_LIBRARY_PROBE switch.

A real bug this caught

The first version probed with $PSScriptRoot, which is empty under irm | iex because there is no script file. That is the primary install route, so the probe would have failed there every time. It now probes the interpreter's own parent directory, which exists by construction since the executable in it just passed Test-Path.

Tests

tests/studio/test_early_python_path_resolver.ps1, wired into cross-platform-parity-ci.yml on both the pwsh and Windows PowerShell 5.1 legs with paths: entries in both trigger blocks.

The control is about Exact, not about the string, and the reason is worth recording: on pwsh 7 the lexical resolver already folds a symlink, because Resolve-StudioLinkTarget can call ResolveLinkTarget there. My first control asserted it did not, and it failed, correctly. On Windows PowerShell 5.1 it sees only the raw reparse target, and it can never expand an 8.3 name or recover stored casing on any version. What it can never do on any host is claim the answer is exact, so that is what the control asserts.

Also covered: non-ASCII and trailing U+00A0 names survive, a link loop is not reported as exact, a hung interpreter is killed at the deadline, finding an interpreter writes nothing, the re-probe once $VenvDir is known, the per-path cache, and with no interpreter the identity is inexact exactly as before.

Test surface updated

Three suites extract helper bundles by name and verify every function they call is present, so they correctly failed until the new helpers were added to their lists. Two suites construct a deliberately degraded ladder and assert the answer is inexact; those now set UNSLOTH_EARLY_PYTHON_PROBE=0, since an exact answer is the opposite of the state they exercise.

Verification

1100 passed, 24 skipped across test_installer_av_shapes.py, test_windows_installer_native_type_fallback.py, test_windows_installer_concurrency_guard.py, tests/security/, test_ci_shell_suite_coverage.py, test_workflow_guards_run_unfiltered.py. On pwsh 7.4 (Linux), the early python path resolver, native path resolver degrades and install lock alias exclusion suites pass.

Scope

No user-visible output change, no change to what gets installed, no new native imports, and no Add-Type. The runtime mutex naming contract shared with studio/src-tauri/src/process.rs and unsloth_cli/_studio_runtime_gate.py is unchanged, and this rung makes the installer agree with the Python side more often rather than less.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-28T04:26:11.596059Z 1a77ef4 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed two fixes for defects found by adversarial review of this PR, both silent and neither caught by the first test run.

1. Non-ASCII install roots were corrupted. Windows PowerShell 5.1 decodes a child process's stdout with the console codepage. The resolved path is hashed into a lock name, so any non-ASCII character produced a different name from the one unsloth_cli/_studio_runtime_gate.py computes for the same directory, and neither side would exclude the other. The child now writes UTF-8 bytes and StandardOutputEncoding reads them as UTF-8.

A run on Linux could never have caught this, and the existing test that would have, test_unicode_custom_root_mutex_name_matches_python, is Windows-only and skips here. There is now a direct check that a non-ASCII path survives the child boundary and that the answer matches the gate's own resolve() byte-for-byte.

The probe also now uses the gate's own expression, Path(...).resolve(...), rather than os.path.realpath. They agree today; matching the expression removes a class of divergence rather than relying on two spellings staying equivalent.

2. A symlink loop was reported as an exact identity. resolve(strict=False) does not raise on a loop, it returns the path unresolved, and Test-Path then passes because it is true for the loop's own symlink. So an unresolved path was marked Exact = $true, which would let a caller decide two paths are different when it cannot know, failing open where this ladder is built to fail closed.

strict=True returns the identical string for every path that genuinely resolves, so the byte-identity above is unaffected, and raises on a loop or a dangling component so those fall through to the lexical answer with Exact = $false.

3. A bug in the test itself, which is how the first two survived. It stubbed the interpreter finder for the no-interpreter case and never restored it, so every later check silently ran against the disabled rung. The restore is now explicit and asserted.

Re-verified: 1092 passed, 24 skipped, and four pwsh suites pass (native path resolver degrades, early python path resolver, install lock alias exclusion, NVIDIA library inventory).

@danielhanchen

Copy link
Copy Markdown
Member Author

Both findings were real, and both would have made this rung fail on precisely the host it exists for. Fixed and pushed.

P1, ArgumentList on 5.1. Correct. It is .NET Core only, so on Windows PowerShell 5.1 the .Add() threw, the catch returned null, and every candidate was rejected. The rung would never have supplied an exact identity on the primary Windows host, and it would have looked healthy doing it, because the finder simply reports "no Python". Your point about the 5.1 test not exposing it is exactly right: it exits successfully as the no-interpreter case.

Arguments now go through ArgumentList where the property exists and a quoted string where it does not, doubling any trailing backslash run so a path ending in one cannot escape its own closing quote. Covered by a spaced path, which exercises whichever branch the host takes, plus a source assertion that the branch cannot be quietly dropped.

P1, pre-3.8 interpreters. Correct, and the reason it is dangerous is the one you gave: the probe only resolves the interpreter's own ordinary directory, so an old Python passes it and then returns the alias spelling, which this rung would mark exact. Test-StudioPathEqual would then read an alias and its target as definitively different rather than taking both runtime locks, and that is permission to install over a live managed environment.

The probe now exits non-zero below 3.8, so such an interpreter is refused and the ladder falls through to the lexical answer with Exact = $false. I chose the version gate over probing a real alias because creating one needs privileges the installer should not assume, and refusing is the safe direction.

One side effect worth flagging: the comment explaining that fix names Test-StudioPathEqual, and test_the_extracted_helpers_can_call_everything_they_call scans comments too, so it demanded that function be added to two extraction lists with no need of it. Rather than grow a harness to satisfy a mention rather than a dependency, that scan now strips whole-line comments, matching what test_uv_requirements_path_space.py already does. Verified it still bites: removing a genuinely called helper still fails with the name it is missing.

Re-verified after rebasing onto the updated base: 363 passed, 18 skipped, plus the early-python and install-lock pwsh suites.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

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. Already looking forward to the next diff.

Reviewed commit: 2f2b343057

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

Copy link
Copy Markdown
Member Author

Checked that the new rung in install.ps1 sits behind the empty-resolved guard in Resolve-StudioFinalPathInfo, so hosts that resolve natively run the same code as before, and that the probe matches the expression in unsloth_cli/_studio_runtime_gate.py. Will get this reviewed after the base lands.

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

Checked that the new rung in install.ps1 sits behind the empty-resolved guard in Resolve-StudioFinalPathInfo, so hosts that resolve natively run the same code as before, and that the probe matches the expression in unsloth_cli/_studio_runtime_gate.py. Will get this reviewed after the base lands.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 31d4dd32bb

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

Comment thread install.ps1 Outdated
return $null
}
if ($proc.ExitCode -ne 0) { return $null }
$answer = "$($stdout.Result)".Trim()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve trailing whitespace in resolved paths

When resolving an NTFS path whose final component ends in whitespace (possible through an extended \\?\ path), .Trim() changes the canonical path. If a sibling without that whitespace also exists, the subsequent Test-Path validates the sibling and this result is marked exact, while the Python runtime gate hashes the original whitespace-preserving path; the installer can therefore take the wrong mutex and misclassify the two paths. Since the Python snippet writes no line delimiter, preserve $stdout.Result verbatim rather than trimming valid filename characters.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting this one, and the reason is upstream of the Trim rather than in it.

Resolve-StudioFinalPathInfo opens with [System.IO.Path]::GetFullPath($Path), and on Windows GetFullPath strips trailing spaces and dots from a non-extended path. So a component ending in whitespace is already gone before Python is asked anything, and the extended \\?\ spelling that could carry one does not survive that first line either.

The same normalisation is on both sides of every comparison this could affect. Get-StudioPathHash and Test-StudioPathEqual normalise with GetFullPath(...).TrimEnd('\\', '/'), and unsloth_cli/_studio_runtime_gate.py strips \\?\ unconditionally, so the runtime gate does not preserve such a name either. The resolver's own return does $resolved.TrimEnd('\\', '/'). Removing the one Trim you name would therefore not preserve a trailing-whitespace path; it would leave four other places that drop it, which is a worse state than the current consistent one.

That leaves the harm needing a host where all of an NTFS trailing-space component, a sibling without it, and a Studio install at that path hold at once, reached through a code path that normalises it away first. That is the standing reject family here: hardening against input the code does not receive.

For what it is worth the trailing-newline concern the Trim also covers is real and is handled separately by Remove-StudioTrailingNewline, so the Trim is belt and braces rather than the load-bearing part.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Trim this pointed at is gone in a2a36b1. The follow-up in 4049586182 found a character GetFullPath does not strip (U+00A0), so the answer is now taken verbatim.

@danielhanchen
danielhanchen force-pushed the av-fp-install-lock-file branch 3 times, most recently from 7d08ece to 98639ec Compare September 17, 2026 12:48
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

…ctable candidate and bound the stdout read by the deadline
danielhanchen added a commit that referenced this pull request Sep 26, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 5de90b2ad5

ℹ️ 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 added a commit that referenced this pull request Sep 26, 2026
danielhanchen added a commit that referenced this pull request Sep 27, 2026
# Conflicts:
#	tests/studio/test_early_python_path_resolver.ps1
#	tests/studio/test_native_path_resolver_degrades.ps1
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: bc2024bea5

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

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 27, 2026
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. Bravo.

Reviewed commit: c230700541

ℹ️ 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 Sep 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 1a77ef4e87

ℹ️ 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 72acc86 into main Sep 28, 2026
59 of 66 checks passed
@danielhanchen
danielhanchen deleted the av-fp-early-python branch September 28, 2026 04:36
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants