Skip to content

Ask Python for the process image table when the native helper is unavailable - #11115

Merged
danielhanchen merged 65 commits into
mainfrom
av-fp-ctypes-helper
Sep 28, 2026
Merged

danielhanchen merged 65 commits into
mainfrom
av-fp-ctypes-helper

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Stacked on #11104. Review the top commit only; the base will disappear from this diff once #11104 merges.

What this changes

Get-StudioProcessImagePath is how the installer decides whether a virtual environment is in use by a running Unsloth before it writes over one. The comment above that ladder already states the stakes: a host that cannot see running processes finds none, and the installer overwrites a venv Unsloth has open.

Today the ladder has three rungs, and there are hosts where all three decline:

Rung What it needs Where it fails
native helper a type defined at runtime Constrained Language Mode, WDAC Dynamic Code Security
Get-Process PROCESS_VM_READ, because .Path is MainModule.FileName any process across a security boundary
Win32_Process a healthy WMI repository a corrupted or disabled repository

This adds a fourth rung between the second and third: ctypes calling QueryFullProcessImageNameW with PROCESS_QUERY_LIMITED_INFORMATION, which is exactly the right that is granted where PROCESS_VM_READ is refused, and which needs no WMI. It runs in one child interpreter for the whole installer run rather than one per process, because Get-RunningStudioVenvProcesses calls this ladder once for every process on the machine.

Why it is additive only

A host where the native helper works never reaches any of this.

The refactor

Invoke-StudioEarlyPython from #11104 is split into a generic Invoke-StudioEarlyPythonScript runner and a thin realpath wrapper, so both rungs share one implementation of the process spawn, the Windows PowerShell 5.1 command line branch (5.1 has no ProcessStartInfo.ArgumentList, since that is .NET Core only), the UTF-8 stdout decoding and the timeout kill. The existing rung's behaviour is unchanged; its tests are untouched apart from the helper extraction bundles.

Two defects found and fixed while building it

The probe re-ran on every miss. Caching on $null -eq $table cannot tell "not asked yet" from "asked, got nothing", so on a host where the rung declines the installer would have spawned one child process per process on the machine: slower than the WMI rung it is meant to sit in front of. It now gates on a separate probed flag. tests/studio/test_early_python_process_image.ps1 asserts the runner is invoked once across three lookups, and reverting the flag makes that check fail.

ctypes truncated the handle. ctypes defaults every return value to a C int. An untyped OpenProcess returns a HANDLE truncated to a signed 32 bit value, which is sign extended again on the way into CloseHandle, so the handle closed is not the handle opened and the child leaks one per process it inspects. The signatures are now declared, and the test asserts the declarations are present.

Testing

New tests/studio/test_early_python_process_image.ps1, 19 checks, wired into cross-platform-parity-ci.yml on both the pwsh 7 and the Windows PowerShell 5.1 legs, since the runner takes a different branch on 5.1.

The generic runner is exercised for real on this host: stdout round trip, argument quoting including a space and a trailing backslash, refusal of a non-zero exit with a passing control on the identical script exiting 0, a hung child killed inside its timeout, non-ASCII output surviving the console codepage, and a missing interpreter returning nothing rather than throwing. The table itself is Windows only, so its parsing and caching are driven through a stubbed runner, and the embedded probe is extracted from the AST, compiled as Python and checked for the handle signatures, the limited-information right and the buffer-growth termination condition.

Three mutations were introduced and each was caught by its own check and no other: reverting the probed flag, dropping the OpenProcess return type, and accepting a possibly truncated EnumProcesses result.

Full sweep of tests/python and tests/studio: 14833 passed, 385 skipped. The failures in that run were compared against the parent commit and are identical there, so none is introduced here.

No effect on installation, update, shortcuts or login

Nothing about what gets installed, where, or how it is launched changes. The only behaviour difference is that on a host where the ladder previously ran out of rungs, a running Unsloth is now seen rather than missed, which is the direction that protects a live environment rather than risking one.

@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 ⚠️ Failed 2026-09-28T04:39:31.083364Z 8c7b8f9 New commits
ℹ️ 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

Copy link
Copy Markdown

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

Reviewed commit: 3c3acb6fed

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

I pushed 24d1f05 to this branch to clear the red parity jobs. Shout if you would rather own it and I will back it out.

What was failing. parity (ubuntu-latest) and parity (windows-latest), with

Invoke-StudioEarlyPython:
The term 'Invoke-StudioEarlyPythonScript' is not recognized as a name of a cmdlet, function, script file, or executable program.

Why. tests/studio/test_early_python_path_resolver.ps1 is not touched by this PR, but it extracts named functions out of install.ps1 by AST and evaluates them, and its list is hand-written. Moving the body of Invoke-StudioEarlyPython into Invoke-StudioEarlyPythonScript left the new helper unlisted, so the function loaded without the thing it now calls. tests/studio/test_early_python_process_image.ps1, which this PR does add, lists it correctly, which is why only the older sibling broke.

Nothing is wrong with the refactor. It is a call-site this PR could not see from the files it changed.

The fix. Invoke-StudioEarlyPythonScript and Remove-StudioTrailingNewline are added to that list; the latter is on the same new path and this harness never had it either.

I also closed the list over what it loads, because it will go stale again the next time install.ps1 is refactored, and today it says so only when some later check happens to call the missing name. Any install.ps1 function the extracted bodies can reach that is neither extracted nor stubbed in that file is now named up front. The check asks the session, not the list, so the file's existing stubs for Initialize-StudioFinalPathNativeType and Write-StudioLine still count as answers.

Verification, all local, reproduced before and confirmed after:

  • Before: test_early_python_path_resolver.ps1 fails with exactly the CI error.
  • After: All early-Python path resolver checks passed, and the two sibling scripts, test_early_python_process_image.ps1 and test_native_path_resolver_degrades.ps1, both pass.
  • Removing Invoke-StudioEarlyPythonScript from the list again makes the new guard fail with install.ps1 functions these checks can reach but nothing here defines: ... instead of the old not recognized, so the guard is doing the work and not just passing.

Separately, the (Python 3.13, ...) shards are red here for a different reason and not because of anything in this PR: test_projects_home_under_a_granted_root_hides_other_accounts and test_sandbox_home_under_a_granted_root_hides_other_accounts die with Exception occurred in preexec_fn. That was a landlock race where a rule path removed between the rules walk and the child's os.open took the whole call down; it is fixed on main in #11111 (1e6908d), which this branch predates. A rebase should clear those four.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 0271b2fab9

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

Confirmed this only runs in install.ps1 where Get-StudioProcessImagePath has already exhausted the native and Get-Process rungs, so a healthy host keeps today's path, and the shared runner keeps the 5.1 command line branch intact. Will get this reviewed once the base lands.

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed this only runs in install.ps1 where Get-StudioProcessImagePath has already exhausted the native and Get-Process rungs, so a healthy host keeps today's path, and the shared runner keeps the 5.1 command line branch intact. Will get this reviewed once the base lands.

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. Can't wait for the next one!

Reviewed commit: 6e7fbe5898

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

danielhanchen and others added 6 commits September 17, 2026 12:49
…g up on an exact one

Resolve-StudioFinalPathInfo had 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, which is every host under Constrained Language Mode and every host
under WDAC Dynamic Code Security, keys its locks on an identity nobody vouches
for.

There is a third source available and it costs nothing to try. os.path.realpath
calls GetFinalPathNameByHandleW on Windows, so it follows junctions, symlinks and
SUBST drives, expands 8.3 names and reports stored casing: the same answer the
native helper gives. It is also the answer unsloth_cli/_studio_runtime_gate.py
already computes, so a runtime lock name derived from this rung agrees with a
running Unsloth by construction rather than by two implementations happening to
match.

The rung is strictly additive. It sits inside the branch that runs only when the
native helper returned nothing, which an AST check confirms is its single call
site and its only guard, so a host that resolves natively today executes exactly
the same code it did before. Where no interpreter is found it returns null and
the lexical fallback runs, which is the previous behaviour unchanged.

Finding an interpreter mutates nothing, because this runs before the install lock
is taken. It is Get-Command and Test-Path only: a previous install's own venv
python first, since reaching it through $VenvDir follows an alias of the root
without canonicalising anything, then python3 and 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 anyway.

The probe is a realpath call 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. It runs with -I so a PYTHONPATH, a sitecustomize or a user site
directory cannot change the answer, and under a wall-clock deadline with a kill,
because a wedged interpreter must not wedge an installer that has not yet taken
its lock. 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, matching the existing
UNSLOTH_NVIDIA_LIBRARY_PROBE switch, and restores the previous ladder exactly.

The probe directory is the interpreter's own parent rather than $PSScriptRoot,
which is empty under `irm | iex` and would have made the probe fail on the
primary install route.
… fail closed on a loop

Two defects in the rung as first written, both found by deliberately adversarial
review rather than by the test suite, and both silent.

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 in an install root came back corrupted and the installer computed a
different name from the one unsloth_cli/_studio_runtime_gate.py computes for the
same directory. Neither side would then exclude the other, which is the failure
the path identity exists to prevent. The child now writes UTF-8 bytes and
StandardOutputEncoding reads them as UTF-8. A Linux run could never have caught
this; the test that covers it is the one that matters on Windows.

The probe also now uses the same expression the runtime gate uses,
Path(...).resolve(...), rather than os.path.realpath. The two agree today, but
matching the expression removes a class of divergence instead of relying on two
spellings staying equivalent.

Second, resolve(strict=False) does not raise on a symlink loop: it returns the
path UNRESOLVED. Test-Path then passes, because it is true for the loop's own
symlink, so an unresolved path was being reported as an exact identity. A caller
would take that as licence to decide two paths are different when it cannot know,
failing open where the whole ladder is built to fail closed. strict=True returns
the identical string for every path that genuinely resolves and raises on a loop
or a dangling component, so the byte-identity above is unaffected and the
unresolvable cases fall through to the lexical answer with Exact = $false.

The test gained checks for both, plus one for a bug in the test itself: it
stubbed the interpreter finder for the no-interpreter case and never restored it,
so every later check silently exercised the disabled rung. That is how both
defects above survived the first run, and the restore is now asserted.
…5.1 can, and refuse a pre-3.8 interpreter

Two fixes from review, both of which made the rung fail on exactly the host it
exists for.

ProcessStartInfo.ArgumentList is .NET Core only. Windows PowerShell 5.1, the host
the desktop installer launches, gets ProcessStartInfo from .NET Framework where
the property does not exist, so .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 while doing it,
because the finder simply reports "no Python". The 5.1 test did not expose this:
it exits successfully as the no-interpreter case. Arguments are now built through
ArgumentList where it exists and through a correctly quoted string where it does
not, doubling any trailing backslash run so a path ending in one cannot escape
its own closing quote.

Python did not follow junctions or symlinks when resolving a Windows path before
3.8. Such an interpreter passes the probe, because the probe only resolves the
interpreter's own ordinary directory, and then hands back the ALIAS spelling for
an aliased Studio root, which this rung would mark exact. Test-StudioPathEqual
would read the 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 the interpreter is refused
and the ladder falls through to the lexical answer with Exact = $false.

Covered by a spaced path, which exercises whichever argument branch the host
takes, a stub interpreter that exits non-zero, and source assertions that neither
guard can be quietly dropped.
test_the_extracted_helpers_can_call_everything_they_call scans the extracted
harness text for function names, comments included, so a comment that explains
what a change protects against is indistinguishable from a call to it. A comment
in the new Python path rung names Test-StudioPathEqual while describing the
failure the version gate prevents, and the test demanded that function be added
to two extraction lists that have no need of it.

Growing an extraction list to satisfy a mention rather than a dependency makes
the harness less like the thing it stands in for, so strip whole-line comments
before scanning instead. tests/python/test_uv_requirements_path_space.py already
drops comment lines before asserting, for the same reason.

Whole-line comments only. A trailing # inside a string literal is not a comment,
and cutting there would hide real calls.

Verified the check still bites: removing a genuinely called helper from an
extraction list still fails with the name it is missing.
Isolated mode implies -E, -P and -s, but not -S, so site is still imported and
a system-level sitecustomize still runs before the probe script. On a corporate
host that is instrumentation, and each of the three things it can do breaks
this rung in a different way: printing to stdout corrupts the single line read
back, hanging burns the timeout and rejects a working interpreter, and patching
pathlib would let an influenced answer be marked exact, which is the one thing
this rung must never do wrongly because the install and runtime locks key on
it.

Nothing in the probe needs site-packages. It is three stdlib imports.

Checked against the real interpreter under test rather than against the
documentation: -I alone reports sys.flags.no_site as 0 and -I -S reports 1, so
an interpreter that ever did imply -S would show up as a stale justification
instead of a silent pass. The end-to-end drive is not available, and the check
says why: sitecustomize resolves on sys.path with the stdlib directory ahead of
site-packages, so a planted copy is shadowed on any host that has its own.
…ailable

Get-StudioProcessImagePath is how the installer decides whether a venv is in
use by a running Unsloth. Every rung that cannot answer makes it likelier to
conclude nothing is running and overwrite an environment that is open, which
is what the comment above that ladder already warns about.

The rungs it has are the native helper (needs a type defined at runtime,
which Constrained Language Mode and WDAC Dynamic Code Security both refuse),
Get-Process (.Path is MainModule, which needs PROCESS_VM_READ and is refused
across a security boundary) and Win32_Process (needs a healthy WMI
repository). A host that loses the first two and has a damaged repository
finds no processes at all.

This adds a rung that needs none of them: ctypes calling
QueryFullProcessImageNameW with PROCESS_QUERY_LIMITED_INFORMATION, the right
that is granted where PROCESS_VM_READ is not. It runs in one child for the
whole installer run, not one per process, because
Get-RunningStudioVenvProcesses calls the ladder once per process on the
machine.

Strictly additive. It sits below Get-Process and above WMI, declines off
Windows and whenever there is no usable interpreter, and returning nothing
leaves the WMI rung reached exactly as before.

Invoke-StudioEarlyPython is split into a generic bounded runner and a thin
realpath wrapper so both rungs share the process spawn, the Windows
PowerShell 5.1 command-line branch, the UTF-8 stdout decoding and the
timeout kill. Behaviour of the existing rung is unchanged.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 430991f455

ℹ️ 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 27, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 55e1fa3d43

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

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3a8e7d6cc4

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

@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. 🎉

Reviewed commit: da1a2d4425

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

Base automatically changed from av-fp-early-python to main September 28, 2026 04:36
# Conflicts:
#	.github/workflows/cross-platform-parity-ci.yml
#	install.ps1
#	tests/python/test_windows_installer_concurrency_guard.py
#	tests/python/test_windows_installer_native_type_fallback.py
#	tests/studio/test_early_python_path_resolver.ps1
#	tests/studio/test_native_path_resolver_degrades.ps1
@danielhanchen
danielhanchen merged commit 7e107f8 into main Sep 28, 2026
43 of 44 checks passed
@danielhanchen
danielhanchen deleted the av-fp-ctypes-helper branch September 28, 2026 04:39
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