Repository navigation
Recover CUDA compute capabilities without emitting a P/Invoke type - #11173
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex security review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
…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.
The early-Python rungs exist for hosts that cannot define a type at runtime. There are two such policies, Constrained Language Mode and WDAC Dynamic Code Security, and the launcher only worked on one of them. Measured, not assumed: CLM allows method calls only on a small set of core types, and System.Diagnostics.Process is not among them, so both New-Object ProcessStartInfo and [Process]::Start are refused there. The rung was therefore absent from half the population it was written for, while looking perfectly healthy everywhere it was not needed. The catch now falls through to a second launcher built from cmdlets only: Start-Process, Wait-Process and Get-Content. The script goes to a file rather than through -c, because Start-Process builds one command line out of -ArgumentList and a body carrying newlines and quotes cannot survive that. Three things the tests found while building it: Start-Process does not quote -ArgumentList, so an argument containing a space arrived as two. It is quoted here with the same rule the 5.1 branch uses. Start-Process redirection appends a trailing newline the child never wrote, so the two launchers returned different strings for the same program. Both ends are normalised now. No current caller could see it, since each trims or splits, but that was luck rather than a contract. [math]::Ceiling is itself blocked under CLM, in the one function written to run there. It is arithmetic and a cast now. The check that covers this is driven in a runspace created with InitialSessionState.LanguageMode set, not by assigning $ExecutionContext.SessionState.LanguageMode partway through a script. The latter was tried first and proves nothing: PowerShell fixes a function's language mode when the function is defined, so the primary launcher kept succeeding and the check passed without ever reaching the fallback.
The parity job went red with "The term 'Invoke-StudioEarlyPythonScript' is not recognized", raised from inside Invoke-StudioEarlyPython. This harness 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 a new helper left the helper unlisted, so the function loaded without the thing it now calls. Listed, along with Remove-StudioTrailingNewline, which the same refactor put on that path and which this harness never had either. A list that has to be updated by hand every time install.ps1 is refactored will go stale again, and it says so only when some later check happens to call the missing name. The extracted bodies are now closed over: any install.ps1 function they can reach that neither the list extracts nor this file stubs is named here, before the checks run.
… built The shared runner inherited the resolver's isolation flags and its comment, which claimed -I covers a sitecustomize. It does not: isolated mode implies -E, -P and -s, not -S, and sys.flags.no_site stays 0. Corrected in the rebase, and the cmdlet-only launcher beside it gets the same pair. Those two are asserted to return the same string byte for byte, and a sitecustomize running in one but not the other is exactly the difference that assertion exists to catch. The check moved with it. Naming one function does not survive this refactor, since the resolver assembles its own vector at the bottom of the stack and delegates to the runner once that exists. It now reads every argument vector that starts with -I and requires -S in each, with a bites control so a regex that stops matching anything fails instead of passing vacuously.
…per really does The claim that both launchers return the same string byte for byte was false, and the check that asserted it used a single-line payload with no newline in it, so it passed anyway. Measured: a child writing the bytes 61 0d 0a 62 comes back 61 0d 0a 62 through the ProcessStartInfo launcher and 61 0a 62 through the cmdlet launcher, whose redirection goes through a file. No current consumer breaks on that, because they trim, split on \r?\n, or compare a single token, but the contract was still being asserted and was still not true. CRLF is now folded to LF before the trailing newline is stripped, which makes the contract hold for real. The helper's name also undersold what it does, so both normalisations are written down. It removes EVERY trailing newline rather than one: .NET's $ matches before a final \n as well as at the end, so "a\n\n" measures as "a". That is deliberate rather than tolerated, because Start-Process redirection appends a newline the child never wrote while the other launcher does not, so removing exactly one would leave the two disagreeing whenever the child's own output ends in a newline, which is what print() does. The cost, that a payload whose meaningful content ends in blank lines cannot pass through here, is stated with the reason no current consumer pays it. The check is now driven over a table of the shapes a child really produces: embedded CRLF, embedded LF, trailing CRLF, several trailing LFs, no newline, and a tab. Two controls assert the comparison can see a difference at all and that a payload really round-tripped, so the group cannot pass by not running.
Each table is a snapshot taken once per run and keyed only by PID, so a reused PID yields the path of the process that is gone. That is the existing WMI rung's contract, stated only as "queried once per run, not once per process", and the ctypes rung above it deliberately matches rather than inventing a second one. An audit read the new snapshot as a staleness this PR introduced; it is not, and the consumer asks about PIDs it enumerated moments earlier in the same run, so the window is short. Recorded rather than changed, because the change would be asking per process, which is what these rungs exist to avoid.
The conversion used the +999 idiom, which is a C integer-DIVISION trick. PowerShell's / is floating point and [int] rounds to nearest rather than truncating, so every exact multiple gained a second: measured, 10000 ms became 11 s and 20000 ms became 21 s. Wait-Process then waited a second longer than the caller asked, and the two launchers stopped sharing a deadline. Done with integer arithmetic instead. [math]::Ceiling is the obvious spelling and Constrained Language Mode refuses it, which is the entire reason this launcher exists; % and / are operators and the [int] cast is permitted there. Driven over the boundary values, because the failure was confined to the ones that look obviously right. The rows execute the installer's own expression, sliced out of the function, rather than a copy retyped into the test, which would have passed with the old idiom still shipping. A control asserts the old idiom really did disagree on an exact multiple, and another that the slice is not empty, so the group cannot pass by not running.
The degradation harness never got past the Get-Process rung. This shell can read its own .Path, so Get-StudioProcessImagePath returned two rungs above the Python and WMI ones, and the whole lower half of the ladder was unexercised while the check read as though it covered the fallback. Get-Process now answers nothing for that scenario, which is what a process this shell cannot inspect looks like from in here, and the ladder is driven all the way down. Get-StudioPythonProcessImageTable is also added to the extraction list. It was missing, and an unlisted helper is a command-not-found waiting for the first scenario that reaches it. This file's own history is the argument: a suite that stopped extracting what it needed took a SKIP branch and CI recorded a pass. Worth recording that the reported symptom was not reproducible. The claim was that the Linux step throws today; it does not, on this host or in this harness, because the ladder returns at Get-Process before reaching the missing helper. The gap was real and latent rather than active, and the new check is what turns it from latent into caught: removing the helper from the list now fails, where before it passed.
…ed Language Mode Windows PowerShell 5.1 on windows-latest fails three checks in the early-python suite: the cmdlet fallback returns no answer, interpreter discovery throws, and the path resolver throws. The two controls beside them pass, so the runspace really is constrained and CLM really does refuse ProcessStartInfo. The fallback simply could not run on the hosts it was written for. The cause is documented rather than guessed. Per about_Language_Modes for 5.1: "Only allowed types can be used in PowerShell. Other types aren't permitted." "Users can get all properties of allowed types." "[ref] - Casting an object to type [ref] ... is not permitted." System.IO.FileInfo, System.Diagnostics.Process, System.IO.Path and CommandInfo are none of them on that list. Six sites used them: - New-TemporaryFile three times, then a path read off each FileInfo. Now the paths are composed as strings from $env:TEMP and a [guid], both allowed. - $proc.ExitCode. Now Select-Object -ExpandProperty, which keeps the read inside compiled cmdlet code where the language mode does not reach. - $cmd.Source in interpreter discovery. Same treatment. - [System.IO.Path]::GetDirectoryName in interpreter discovery, now Split-Path -Parent. - [System.IO.Path]::IsPathRooted guarding what the final-path resolver returns, now Split-Path -IsAbsolute. - [int]::TryParse($pidText, [ref]$parsed) in the process-image table, which casts to [ref] and so was refused outright. Now an anchored -match and an [int] cast in a try. The sixth was not in the CI failure and was not on my list: the new static check below found it. That check is the more important half of this commit. The behavioural suite runs these helpers inside a genuinely constrained runspace, and it passed green on Linux under pwsh 7 for a build in which three of them could not run on Windows at all, because a constrained runspace off Windows does not enforce the allowed-type list. So a runtime test on the runners we have cannot be the guard. tests/python/test_installer_clm_safe_helpers.py is static: for every helper reachable while the session may be constrained it rejects a static call on a type outside the documented allowed list, a property read off one of the types known to break, a cmdlet that hands back an object script cannot read under CLM, and any [ref] cast. It carries its own not-vacuous test, since a rule of this shape passes just as happily when its regex never fires. All existing suites stay green, including the early-python behavioural suite and the native-type fallback and AV-shape suites.
… type The installer tells Explorer about each shortcut it writes with SHChangeNotify. The per-item notification is the one that matters: the global SHCNE_ASSOCCHANGED broadcast misses a same-name .lnk rewritten in place, which is what an update does every time. That call needs a type defined at runtime, which Constrained Language Mode and WDAC Dynamic Code Security both refuse. On those hosts the whole block threw into its own catch and the refresh simply did not happen: the shortcut worked, the icon stayed stale until something else invalidated Explorer's cache. The catch now sends the same two notifications, same constants, same order, through a child interpreter with ctypes. The type-defining rung is untouched and still tried first, so a host where it works never reaches this. Cosmetic in both directions, and it cannot fail an install: the rung declines off Windows and with no usable interpreter, and returns false rather than throwing on anything else.
It is the only new code that writes anything at all: three temporary files per call. Idempotency means the tenth install leaves the machine as the first one found it, so every exit path has to clean up and not just the happy one. The timeout path is the one that matters, since it returns while the child is still being killed. Measured across ten successful runs, five non-zero exits, two timeout kills and a missing interpreter: the temp directory is unchanged. Removing the finally block makes the check fail.
The two rungs have to return the same string for the same process, or Test-StudioProtectedPathMatch compares a path produced by one against a path recorded by the other and sees a difference that is not there. They agree by construction only if the underlying call is identical, so the three things that decide it are read out of both and compared: the access right (PROCESS_QUERY_LIMITED_INFORMATION), the flags argument (0 is the Win32 path form, 1 would return the \\Device\\HarddiskVolume form instead) and the buffer size. Each of the three mutations is caught by its own check and no other: the probe asking for the device form, the probe using a MAX_PATH buffer, and the native rung asking for PROCESS_QUERY_INFORMATION.
… Mode Fixing the launcher was necessary and not sufficient, and the check that covered it gave a false pass by testing the launcher in isolation. Driven end to end in a runspace created with InitialSessionState.LanguageMode set, the rung was still dead: Get-StudioEarlyPython THREW on [System.IO.Path]::GetDirectoryName before the launcher was ever reached. CLM refuses method calls on System.IO.Path and on Int32, and it throws rather than returning null, so the ladder did not degrade to the rung below, it failed outright. Measured, per call: [string]::IsNullOrWhiteSpace allowed [System.IO.Path]::GetDirectoryName blocked [System.IO.Path]::IsPathRooted blocked [int]::TryParse blocked Split-Path -Parent, -IsAbsolute allowed So discovery uses Split-Path -Parent, the resolver uses Split-Path -IsAbsolute, and the process image table parses its pid with a regex and a cast. Invoke-StudioPythonShellIconRefresh also called discovery outside its own try, so its promise never to throw was false on exactly the hosts it serves. The caller's catch happened to cover it; the promise is now true on its own. The check runs every function between the entry point and the answer, not just the launcher, and asserts discovery and the resolver both answer rather than throw. Restoring either blocked call makes it fail.
…acted helper sets
# Conflicts: # tests/python/test_windows_installer_concurrency_guard.py # tests/python/test_windows_installer_native_type_fallback.py
…, so a CUDA stand-in is not an NVIDIA GPU
Both warnings fire before the Python rung runs, so they cannot promise that paths are compared as written: an interpreter may still resolve them exactly.
On Windows the reader names the driver libraries under it, so the behaviour rows threw there.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Stacked on #11116. Review the last commit only.
What this fixes
Get-NvidiaLibraryInventorysupplies the CUDA version and the per-device compute capabilitiesused when
nvidia-smicannot answer. It reaches the driver throughUnslothNvidiaProbeV2, atype built at runtime, so on a host where that cannot be built it returns nothing at all.
Three policies do that: Constrained Language Mode, WDAC, and Dynamic Code Security.
The capabilities are the part no registry or WMI source can supply:
ComputeCaps[0]becomes$CudaArchand then-DCMAKE_CUDA_ARCHITECTURESfor the llama.cppsource build. Without it the build turns CUDA off (studio/setup.sh: validate source-built llama.cpp and guard empty CUDA arch detection #5854).
Get-NvidiaCu126Verdict.The display driver version is not the CUDA driver API compatibility value, and a marketing
device name does not imply a capability, so neither is a substitute.
What this adds
A second rung underneath the emitted one: the same NVML and CUDA driver calls made through
CPython's
ctypes, whichstudio/nvidia_probe.pyalready performs in production. It emits thesame
source;major;minor;cap,capstring, so nothing downstream changes shape.The emitted rung still goes first and still wins whenever it answers. Nothing is removed
here. This is the capability that has to exist before the emitted types can go, not their
removal.
Semantics preserved from the emitted reader
Each one is deliberate and each one is tested:
CUDA_VISIBLE_DEVICEScleared aroundcuInit, restored afternvidia-smiOne budget, not two
Both rungs share a single deadline. A driver that wedges inside the emitted rung for the whole
timeout leaves nothing behind and is not retried, so the worst-case wall clock is unchanged
rather than doubled.
The launcher
Cmdlets only. Constrained Language Mode refuses
New-Object ProcessStartInfo,[Process]::Start,[System.IO.Path]and[math], and CLM is one of the policies that makethe emitted rung decline, so a launcher needing any of them would be missing from exactly the
population this rung exists for.
Nothing with a space in it reaches the command line either. Windows PowerShell 5.1 appends each
native argument verbatim, so a script under
C:\Users\First Last\AppData\Local\Tempor a hintunder
C:\Program Files\NVIDIA Corporation\NVSMIwould split on its spaces and the child wouldrun something else, silently answering no. The script arrives on stdin and the two library
hints in the environment; the only arguments left are
-I -S -.Get-NvidiaProbePythonExeis per-file on purpose:install.ps1uses its early read-onlyinterpreter ladder, which installs nothing, and
setup.ps1uses the venv a previous run built.No interpreter simply means the rung declines.
UNSLOTH_NVIDIA_PYTHON_PROBE=0turns it off.Tests
tests/studio/test_nvidia_python_probe_parity.ps1pins the text: the embedded probe isbyte-identical in both files, sits at column 0 so its indentation survives both, and agrees
with
studio/nvidia_probe.pyon every NVML symbol, on attribute numbers 75 and 76, and on themajor*1000 + minor*10arithmetic. Wired intocross-platform-parity-ci.ymlon pwsh 7 and onWindows PowerShell 5.1.
tests/python/test_installer_embedded_nvidia_probe.pypins the behaviour by running theprobe against a fake NVML and CUDA library. That is what catches a defect edited identically
into both copies, which a parity check cannot see.
Verification
This host has eight NVIDIA GPUs, so the probe was exercised for real rather than only in CI.
nvml;13;1and eight capabilities, matchingnvidia-smiexactly, in about 130 ms, with noscratch files left behind.
CUDA_VISIBLE_DEVICES=6. With the mask clearing removed it reports two, so that check is notvacuous.
this was committed: the argument-splitting hazard above, and a here-string variable named
$probethat made an existing suite read this probe instead of the emit probe.definition.
Scope
install.ps1is signed in place byrelease-desktop.yml, so the bytes changing has releaseconsequences even though the behaviour is additive. The behavioural change is confined to hosts
where the emitted rung declines today: those move from no inventory at all to a full one. On
every other host the emitted rung answers first and the Python rung is never reached.