Repository navigation
Remove the reflection-emit apparatus and all four emitted types - #11193
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
Security findingsFinding details are still loading. Check the individual review comments. ℹ️ 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. |
|
Staging CI, first pass. Run on owned staging repos rather than the org queue, so the lanes that matter here actually got to run. Green so far, and three of these are the ones this change is really about:
The installer differential is the important one: it diffs the full installer transcript base against head, and it is empty. Removing four P/Invoke types and the apparatus that built them changed nothing an installing user sees. Application Control CI matters more here than it did before, not less. Constrained Language Mode is one of the two policies the deleted gate existed for, and every replacement rung is cmdlet-only for exactly that reason, so a green AppLocker lane is the evidence that the ladder still runs where the emitted one could not. One failure, and it is not from this branch: The remaining lanes are still queued. I will post the rest when they land, along with the full |
|
Full local sweep, and the rest of staging CI. tests/python plus tests/studioHead: 10 failed, 14833 passed, 385 skipped in 30 minutes. All ten are pre-existing, and that is measured rather than asserted. Re-run at identical scope over just the five files that carry them, base branch against head:
The five that reproduce in isolation are Worth naming what the last two actually report, because they read like they could be mine and are not. Staging CI, complete
Cross-platform parity is the lane that runs the rewritten |
|
@codex security review |
…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.
…, so a CUDA stand-in is not an NVIDIA GPU
# Conflicts: # install.ps1 # studio/setup.ps1 # tests/studio/test_nvidia_library_inventory.ps1
Both Python children now share one deadline like main's two readers did, so a hung driver costs at most 60 s instead of 64 s.
CLM refuses ProcessStartInfo, so the integrity label and the elevation read both failed there and the Python NVIDIA reader always declined, losing the inventory it gave before this change. Also hand the resolver test's extracted reader main's Get-NvidiaSystem32Dir.
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.
# Conflicts: # install.ps1 # tests/studio/test_early_python_path_resolver.ps1
On Windows the reader names the driver libraries under it, so the behaviour rows threw there.
# Conflicts: # tests/studio/test_nvidia_python_probe_parity.ps1
The label and elevation checks stubbed icacls on PATH and emptied PATH, but both tools are called by their System32 path, so on a standard account the real ones answered and the checks failed; they only passed on administrator runners.
…the others in this file
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! 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". |
# Conflicts: # .github/workflows/cross-platform-parity-ci.yml # install.ps1 # studio/setup.ps1 # tests/python/test_windows_installer_concurrency_guard.py # tests/python/test_windows_installer_resolver_fallback.py # tests/studio/test_early_python_icon_refresh.ps1 # tests/studio/test_early_python_path_resolver.ps1 # tests/studio/test_early_python_process_image.ps1 # tests/studio/test_native_path_resolver_degrades.ps1 # tests/studio/test_nvidia_python_probe_parity.ps1
Removes the reflection-emit apparatus from
install.ps1andstudio/setup.ps1, and with it all four P/Invoke types the installer built at runtime.Stacked on #11173. Review only the top commit; the base branch carries the NVIDIA probe this one depends on.
Why
Skyhigh (Trellix / McAfee Enterprise) scores the shipped
install.ps1asBehavesLike.PS.Suspicious, 1 engine out of 74. Controlled experiments localised it to the emit region, and a matched pair on the real file settles it. Same tree with and without this commit, both first-seen so both got a fresh pass, same engine buildv2021.2.0+4045, same definitions20260916, 74 engines reporting and zero timeouts on each:malicious,BehavesLike.PS.Suspicious.jrundetectedA 550 byte file containing nothing but a
DefinePInvokeMethodcall scans 0 / 62, and identical-length comment filler in place of the apparatus also scans clean. So this is aggregate threshold scoring rather than a construct match: the apparatus is the largest single contributor pushing the file over the line, not something independently malicious-looking. Both halves of it were independently sufficient, so partial removal bought nothing and only full removal could help.Two things that do NOT move the verdict, both measured rather than assumed:
.ps1at all, so that input exists only for the.exebundles.What replaces each type
Every one reaches the same system call without emitting anything.
UnslothStudioFinalPathV3CreateFileW,GetFinalPathNameByHandleWpathlib.Path.resolvethrough a child interpreter, which ISGetFinalPathNameByHandleWon WindowsUnslothStudioProcessImageV1OpenProcess,QueryFullProcessImageNameWUnslothShellIconRefreshSHChangeNotifyUnslothNvidiaProbeV2Then the apparatus itself:
Test-StudioCanDefineNativeTypes,Test-StudioEmitInChildProcess,New-StudioDynamicAssemblyandNew-StudioEmittedNativeType, from both files, along with the state variables that existed only to serve them.AMSI does not scan CPython, so the interop leaves the scanned surface rather than moving within it.
The one behaviour change, stated plainly
The path resolver's ladder is now Python then lexical, where it was native, Python, lexical.
On a first install on a host carrying no Python of its own, identity falls to the lexical answer and
Exactis$false. That makesTest-StudioPathEqualreturn$nulland the caller take BOTH runtime locks, so the degradation fails closed rather than open. It is now said out loud rather than inferred: the degraded warning fires on that path too.The population that reaches it is small and benign by construction.
Get-StudioEarlyPythonfinds a previous install's venv interpreter through$VenvDir, so every update, repair and re-run resolves exactly. Only a genuine first install with no Python anywhere falls through, and on such a host there is no prior installation to overwrite and Studio cannot already be running.Tests
The suites asserted the apparatus was PRESENT, which is the opposite of the contract now, so they are repointed rather than patched.
tests/studio/test_native_path_resolver_degrades.ps1is replaced bytests/studio/test_path_resolver_degrades.ps1. It runs both directions on one host:python3is present, so the interpreter rung really answers andExact = $trueis earned rather than asserted, andUNSLOTH_EARLY_PYTHON_PROBE=0reproduces a Python-less host exactly. Its source contract is inverted: neither script may compile C#, emit a P/Invoke stub, define a dynamic assembly, declare a native import, or mention any of the four deleted type names. Every one of those rules is then checked against a sample that contains the construct, so a rule that cannot fire is caught rather than passing silently.tests/python/test_windows_installer_native_type_fallback.pyis renamed totest_windows_installer_resolver_fallback.py. The emit-policy tail goes with the apparatus it described. The tests worth keeping are retargeted:%TEMP%can still cost the exact answer. What it may not cost is the install.AV_SHAPES_RECORDintests/studio/test_installer_av_shapes.pygains the measurement above and the two non-results.Each new check was mutation tested: dropping the degradation warning, claiming a lexical answer is exact, and removing the process-image latch each turn the suite red, and the suite goes green again when restored.
Verification
windows-no-compiler-ci.ymlstill applies unchanged: 4688 process auditing unioned with a liveFileSystemWatcherover every temp root, positive control firing, zero compiler launches across a full install. Its remedy message no longer points at a function that does not exist.windows-application-control-ci.ymlmatters more than before, not less. Constrained Language Mode is one of the two policies the deleted gate existed for, and the replacement rungs are cmdlet-only for exactly that reason.Honest limits
This host has no Windows and no NVIDIA GPU. Every runtime claim above comes from CI or from the VirusTotal pair, not from a local Windows run.