Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Measure whether a hardening change alters what the installer does, instead of arguing that it does not (#10992)
Daniel Han6370afe095e0
diff --git a/.github/scripts/Collect-InstallerEvidence.ps1 b/.github/scripts/Collect-InstallerEvidence.ps1new file mode 100644index 00000000000..76b29df6795--- /dev/null+++ b/.github/scripts/Collect-InstallerEvidence.ps1@@ -0,0 +1,436 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++<#+.SYNOPSIS+ Record what an Unsloth install left behind, so two commits can be compared.++.DESCRIPTION+ Runs after install.ps1 and writes three files that compare_installer_evidence.py consumes:++ shortcuts.json every .lnk the installer created, read back through the shell, with the+ fields that constitute the launch contract: target, arguments (which carry+ -WindowStyle and -ExecutionPolicy), working directory, window style, icon.+ artifacts.json the installed files, with the content of the two whose content is a contract+ (launch-studio.ps1 and unsloth.cmd), plus which files a second install run+ rewrote.+ (the transcript is captured by the workflow, which owns the installer's stdout)++ Reading the .lnk files back through the shell rather than trusting the installer's own log is+ the point: a change to the launch transport is invisible in the transcript, and the transcript+ is what a prose review looks at.++ This script never fails the job. A collection error is recorded in the JSON as an error field so+ the comparer can call the run VOID, which is a different and more honest outcome than a step+ that went red for a reason nobody reads.+#>++[CmdletBinding()]+param(+ # Where the installer put Studio.+ [Parameter(Mandatory = $true)][string]$StudioHome,++ # Where the installer put the generated launcher and the Studio data. On a normal-profile+ # install this is %LOCALAPPDATA%\Unsloth Studio, which is OUTSIDE $StudioHome, and+ # launch-studio.ps1 is written there ($appDir = $StudioDataDir, install.ps1:2971). Searching+ # only $StudioHome meant the launcher was absent from every manifest on a normal run.+ [string]$StudioDataDir,++ # Where to write the evidence.+ [Parameter(Mandatory = $true)][string]$OutDir,++ # Comma-free list of directories to search for .lnk files. Defaults to the desktop and the+ # user's Start Menu programs folder, which is where install.ps1 writes them.+ [string[]]$ShortcutRoot,++ # Set when this is the second install of the same commit: the manifest from the first run is+ # read back and the two compared, so "a reinstall writes nothing" is measured rather than+ # assumed. Several changes in this area touch content-comparison paths.+ [string]$CompareAgainst+)++$ErrorActionPreference = 'Continue'++New-Item -ItemType Directory -Force -Path $OutDir | Out-Null++# ---------------------------------------------------------------------------+# Shortcuts+# ---------------------------------------------------------------------------++if (-not $ShortcutRoot -or $ShortcutRoot.Count -eq 0) {+ $ShortcutRoot = @(+ [Environment]::GetFolderPath('Desktop'),+ [Environment]::GetFolderPath('CommonDesktopDirectory')+ )+ # Guarded rather than assumed: Join-Path throws on a null Path, and %APPDATA% is unset off+ # Windows, so composing it unconditionally turned a parse-clean script into one that printed a+ # binding error before doing any work. Observed running this under pwsh on Linux.+ if ($env:APPDATA) {+ $ShortcutRoot += (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs')+ }+}++function Get-UnslothRootLabel {+ <#+ .SYNOPSIS+ A stable name for a shortcut root that does not vary between the two workspaces.++ Split-Path -Leaf was not stable ENOUGH: it maps the per-user Desktop and CommonDesktopDirectory+ to the same "Desktop", so a candidate that moved a shortcut from one to the other produced an+ identical key with identical fields and compared equal.+ #>+ param([Parameter(Mandatory = $true)][string]$Path)+ $known = [ordered]@{+ UserDesktop = [Environment]::GetFolderPath('Desktop')+ CommonDesktop = [Environment]::GetFolderPath('CommonDesktopDirectory')+ CommonPrograms = [Environment]::GetFolderPath('CommonPrograms')+ }+ if ($env:APPDATA) {+ $known['UserPrograms'] = (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs')+ }+ foreach ($entry in $known.GetEnumerator()) {+ if ($entry.Value -and $Path -ieq $entry.Value) { return $entry.Key }+ }+ # Not one of the known roots: fall back to the leaf, which is still better than nothing, and+ # say so in the label so a reader is not misled into thinking it is canonical.+ return "other:" + (Split-Path $Path -Leaf)+}++$shortcuts = New-Object System.Collections.ArrayList+$shell = $null+try {+ # WScript.Shell is the only shortcut reader available to Windows PowerShell 5.1 without+ # IShellLink interop, and it is what the installer itself uses to write them.+ $shell = New-Object -ComObject WScript.Shell+} catch {+ [void]$shortcuts.Add([ordered]@{+ name = '<collection failed>'+ error = "could not create WScript.Shell: $($_.Exception.Message)"+ })+}++if ($shell) {+ foreach ($root in ($ShortcutRoot | Where-Object { $_ })) {+ if (-not (Test-Path -LiteralPath $root)) { continue }+ $found = @(Get-ChildItem -LiteralPath $root -Filter '*.lnk' -Recurse -ErrorAction SilentlyContinue |+ Where-Object { $_.Name -like '*nsloth*' })+ foreach ($file in $found) {+ try {+ $lnk = $shell.CreateShortcut($file.FullName)+ # Keyed on a canonical root label plus the path RELATIVE to that root, never the+ # absolute path: the two sides run in different workspaces, so an absolute path+ # would differ for a reason that is not a behaviour change. The leaf of the root+ # is not enough on its own -- the per-user and the common Desktop are both called+ # "Desktop", and every Start Menu entry is under "Programs" however deeply it is+ # nested -- so moving a shortcut between them kept the same key and compared equal.+ $relative = $file.FullName+ if ($file.FullName.StartsWith($root, [StringComparison]::OrdinalIgnoreCase)) {+ $relative = $file.FullName.Substring($root.Length).TrimStart('\', '/')+ }+ [void]$shortcuts.Add([ordered]@{+ name = $relative+ root = (Get-UnslothRootLabel $root)+ # Same reason the content contracts carry one: a regression that calls Save()+ # unconditionally leaves every property identical, so the manifests compare+ # equal and the reinstall looks like it wrote nothing.+ lastWriteUtc = $file.LastWriteTimeUtc.ToString('o')+ targetPath = $lnk.TargetPath+ arguments = $lnk.Arguments+ workingDirectory = $lnk.WorkingDirectory+ windowStyle = [string]$lnk.WindowStyle+ iconLocation = $lnk.IconLocation+ description = $lnk.Description+ })+ } catch {+ [void]$shortcuts.Add([ordered]@{+ name = $file.Name+ error = "could not read: $($_.Exception.Message)"+ })+ }+ }+ }+}++# -Depth, because ConvertTo-Json truncates at 2 by default and silently emits the type name instead+# of the object. An evidence file that says "System.Collections.Hashtable" compares equal to another+# one that says the same thing, which is a green run that measured nothing.+#+# Always an array, even for one entry. ConvertTo-Json unwraps a single-element collection into a+# bare object, and -AsArray does not exist on Windows PowerShell 5.1, so the shape of this file+# would depend on how many shortcuts happened to exist. The consumer also tolerates an object, but+# evidence whose schema varies with its contents is a trap either way.+$shortcutJson = $shortcuts | ConvertTo-Json -Depth 6+if ($shortcuts.Count -le 1) { $shortcutJson = "[$($shortcutJson)]" }+Set-Content -LiteralPath (Join-Path $OutDir 'shortcuts.json') -Value $shortcutJson -Encoding utf8++Write-Host "collected $($shortcuts.Count) shortcut(s)"+foreach ($s in $shortcuts) {+ Write-Host (" {0}: {1} {2}" -f $s.name, $s.targetPath, $s.arguments)+}++# ---------------------------------------------------------------------------+# Installed files+# ---------------------------------------------------------------------------++# Content is compared for these two only. They are generated by the installer from templates, so+# their text is a contract; everything else is either a downloaded binary (compares by hash, which+# drifts with upstream) or a venv (tens of thousands of files, and not what this lane is about).+# Each contract is a LIST of places it can legitimately live, because the layout depends on the+# redirect mode: a normal install puts the launcher and the shim at the install root, and an+# env-override install puts them under share\ and bin\. Looking in one place only meant that under+# the other layout both files were silently absent from the evidence, leaving directory-presence+# entries behind and no content comparison at all for two of the three contracts.+#+# Windows contracts only. studio.conf was listed here and is never written on Windows: the only+# writer in the repository is install.sh, and both install.ps1 and studio/setup.ps1 merely Test-Path+# it (install.ps1:1652, :5215, studio/setup.ps1:4486). Listing it was harmless while an unresolved+# contract was silently skipped, and became fatal the moment that turned into a collection error,+# because every clean Windows run would then VOID on a file that is correct to be absent. Anything+# added here has to be something the WINDOWS installer actually writes.+$contentFiles = [ordered]@{+ 'launch-studio.ps1' = @('launch-studio.ps1', 'share\launch-studio.ps1')+ 'unsloth.cmd' = @('unsloth.cmd', 'bin\unsloth.cmd')+}++$files = [ordered]@{}+$artifactError = $null++# Ordered, and $StudioHome first, so a layout that has a file in both places reports the one the+# installer treats as canonical.+$searchRoots = [ordered]@{ 'home' = $StudioHome }+if ($StudioDataDir -and $StudioDataDir -ne $StudioHome) { $searchRoots['data'] = $StudioDataDir }++if (Test-Path -LiteralPath $StudioHome) {+ foreach ($contract in $contentFiles.Keys) {+ $full = $null+ $foundAt = $null+ foreach ($rootLabel in $searchRoots.Keys) {+ $root = $searchRoots[$rootLabel]+ if (-not $root -or -not (Test-Path -LiteralPath $root)) { continue }+ foreach ($candidate in $contentFiles[$contract]) {+ $probe = Join-Path $root $candidate+ if (Test-Path -LiteralPath $probe) { $full = $probe; $foundAt = "$rootLabel/$candidate"; break }+ }+ if ($full) { break }+ }+ if (-not $full) {+ # Recorded as an error, not skipped. Skipping removed the contract from both manifests+ # whenever it was missing on both sides -- a shim writer that fails the same way on two+ # identical runners, an endpoint policy that deletes the same generated file, or simply+ # a supported layout nobody listed above -- and the remaining entries kept both maps+ # non-empty, so the key sets matched and the run could report agreement about a file it+ # never looked at. The comparer already voids on a per-file error.+ $files[$contract] = [ordered]@{+ error = "not found at any supported location under " ++ (($searchRoots.Keys | ForEach-Object { $_ }) -join ', ')+ }+ continue+ }+ try {+ $item = Get-Item -LiteralPath $full -ErrorAction Stop+ $files[$contract] = [ordered]@{+ # Where it actually was. A contract that moves between layouts is itself a+ # behaviour change, and keying on the contract name alone would hide the move.+ foundAt = $foundAt+ content = (Get-Content -Raw -LiteralPath $full -ErrorAction Stop)+ sha256 = (Get-FileHash -LiteralPath $full -Algorithm SHA256).Hash+ # The byte order mark, separately from the text. Get-Content -Raw decodes and+ # discards it, so a candidate that stops writing the UTF-8 BOM on launch-studio.ps1+ # leaves identical text and compared equal. That is not cosmetic: the shortcut runs+ # the launcher under Windows PowerShell 5.1, which reads a BOM-less file as ANSI, so+ # dropping it breaks any install whose paths carry non-ASCII characters.+ bom = (& {+ $head = [byte[]]::new(3)+ $stream = [System.IO.File]::OpenRead($full)+ try { $read = $stream.Read($head, 0, 3) } finally { $stream.Dispose() }+ if ($read -ge 3 -and $head[0] -eq 0xEF -and $head[1] -eq 0xBB -and $head[2] -eq 0xBF) { 'utf-8' }+ elseif ($read -ge 2 -and $head[0] -eq 0xFF -and $head[1] -eq 0xFE) { 'utf-16le' }+ elseif ($read -ge 2 -and $head[0] -eq 0xFE -and $head[1] -eq 0xFF) { 'utf-16be' }+ else { 'none' }+ })+ # For idempotency. Content equality cannot show that nothing was WRITTEN, only that+ # the bytes ended up the same, and an unconditional rewrite of identical bytes is+ # precisely the regression the second install exists to catch.+ lastWriteUtc = $item.LastWriteTimeUtc.ToString('o')+ length = $item.Length+ }+ } catch {+ $files[$contract] = [ordered]@{ error = $_.Exception.Message }+ }+ }+ # The shape of the tree, without its contents: a change that stops creating a directory, or+ # starts creating one, shows up here and nowhere else.+ try {+ $tops = @(Get-ChildItem -LiteralPath $StudioHome -ErrorAction Stop |+ Select-Object -ExpandProperty Name | Sort-Object)+ foreach ($name in $tops) {+ if (-not $files.Contains($name)) { $files[$name] = [ordered]@{ present = $true } }+ }+ } catch {+ $artifactError = "could not enumerate ${StudioHome}: $($_.Exception.Message)"+ }+} else {+ $artifactError = "the install root $StudioHome does not exist, so the installer did not finish"+}++# ---------------------------------------------------------------------------+# Idempotency, when asked+# ---------------------------------------------------------------------------++# Built BEFORE the comparison below, which reads it. Keyed the same way the comparer keys shortcuts,+# and kept in the artifact manifest rather than in shortcuts.json, because the idempotency+# comparison reads the first run's artifacts.json.+$shortcutWrites = [ordered]@{}+foreach ($s in $shortcuts) {+ if ($s.Contains('lastWriteUtc')) { $shortcutWrites["$($s.root)/$($s.name)"] = $s.lastWriteUtc }+}++$rewritten = $null+if ($CompareAgainst) {+ if (-not (Test-Path -LiteralPath $CompareAgainst)) {+ # Deliberately NOT an empty list. An empty list means "measured, nothing was rewritten",+ # and $null means "not measured"; the comparer treats those differently and must.+ Write-Host "::warning::no first-run manifest at $CompareAgainst, so idempotency was not measured"+ } else {+ $rewritten = New-Object System.Collections.ArrayList+ try {+ $before = Get-Content -Raw -LiteralPath $CompareAgainst | ConvertFrom-Json+ foreach ($contract in $contentFiles.Keys) {+ $b = $before.files.$contract+ $a = $files[$contract]+ if (-not $b -and -not $a) { continue }+ if (-not $b -or -not $a) { [void]$rewritten.Add($contract); continue }+ if ($b.sha256 -and $a.sha256 -and $b.sha256 -ne $a.sha256) {+ [void]$rewritten.Add("$contract (contents changed)")+ continue+ }+ # The stricter half: the modification time moving means the file was written, even+ # though the bytes it was written with are identical. That is the timestamp-moving+ # rewrite this lane says it tests for, and a hash comparison cannot see it.+ if ($b.lastWriteUtc -and $a.lastWriteUtc -and $b.lastWriteUtc -ne $a.lastWriteUtc) {+ [void]$rewritten.Add("$contract (rewritten with identical bytes at $($a.lastWriteUtc))")+ continue+ }+ if ($b.foundAt -and $a.foundAt -and $b.foundAt -ne $a.foundAt) {+ [void]$rewritten.Add("$contract (moved from $($b.foundAt) to $($a.foundAt))")+ }+ }+ # The whole tree, not only the two contracts. Every top-level name is already in+ # $files (the `present = $true` entries above), and the contract loop looks at two of+ # them, so a candidate that creates a file or directory on a fresh install and removes+ # it on reinstall was invisible: the second collector overwrites artifacts.json with the+ # post-reinstall tree, so both final manifests match the base and nothing is reported.+ # Where-Object, because member enumeration over an EMPTY PSObject.Properties yields+ # $null and @($null) has Count 1. Without the filter a first run that recorded no files+ # produced one phantom key named '' and every clean run reported it as removed.+ $beforeFileKeys = @($before.files.PSObject.Properties.Name | Where-Object { $_ })+ $nowFileKeys = @($files.Keys | Where-Object { $_ })+ $contractNames = @($contentFiles.Keys)+ foreach ($name in $beforeFileKeys) {+ # The contracts are handled above, with their hash, write time and location; adding+ # them here too would report the same file twice.+ if ($contractNames -contains $name) { continue }+ if ($nowFileKeys -notcontains $name) {+ [void]$rewritten.Add("$name (removed by the second run)")+ }+ }+ foreach ($name in $nowFileKeys) {+ if ($contractNames -contains $name) { continue }+ if ($beforeFileKeys -notcontains $name) {+ [void]$rewritten.Add("$name (created by the second run)")+ }+ }+ # The shortcuts too. Their properties are compared between the two SIDES elsewhere; this+ # is the other question, whether the second install on ONE side rewrote them.+ if ($before.PSObject.Properties.Name -contains 'shortcutWrites' -and $before.shortcutWrites) {+ $beforeKeys = @($before.shortcutWrites.PSObject.Properties.Name | Where-Object { $_ })+ foreach ($key in $shortcutWrites.Keys) {+ if ($beforeKeys -notcontains $key) {+ # Present now, absent after the first install. A reinstall that CREATES a+ # shortcut is as much a second-run write as one that rewrites it, and the+ # final manifest looks identical to a normal run, so ignoring a key with no+ # prior timestamp let that pass.+ [void]$rewritten.Add("shortcut $key (created by the second run)")+ continue+ }+ $wasWritten = $before.shortcutWrites.$key+ if ($wasWritten -and $wasWritten -ne $shortcutWrites[$key]) {+ [void]$rewritten.Add("shortcut $key (rewritten at $($shortcutWrites[$key]))")+ }+ }+ # And the other direction. The loop above walks the CURRENT keys, so a shortcut that+ # existed after the first install and was deleted by the second was never looked at.+ # The second collector overwrites shortcuts.json with the final state, so a candidate+ # that creates an extra shortcut on a fresh install and removes it on reinstall ends+ # with manifests that match the base and an empty rewrittenOnSecondRun: a false PASS+ # on a shortcut a user watched disappear.+ foreach ($key in $beforeKeys) {+ # `-contains` on .Keys, not ContainsKey: $shortcutWrites is an+ # [ordered]@{}, which is an OrderedDictionary and has Contains rather than+ # ContainsKey, and calling the wrong one throws into the catch below and reports+ # idempotency as unmeasured.+ if (@($shortcutWrites.Keys | Where-Object { $_ }) -notcontains $key) {+ [void]$rewritten.Add("shortcut $key (removed by the second run)")+ }+ }+ } elseif ($shortcuts.Count -gt 0) {+ # Shortcuts exist now and the first run recorded nothing about them, so the shortcut+ # half of this measurement did not happen. VOID rather than a silent pass: the+ # comparer treats a missing rewrittenOnSecondRun as unmeasured for the same reason.+ Write-Host '::warning::the first-run manifest carries no shortcut write times, so second-run shortcut writes could not be measured'+ throw 'first-run shortcut evidence is missing'+ }+ } catch {+ Write-Host "::warning::could not compare against $CompareAgainst : $($_.Exception.Message)"+ $rewritten = $null+ }+ }+}++# The install ID, both where it is persisted and where it is embedded. install.ps1 writes+# share\studio_install_id and bakes the same value into the generated launcher as+# $_ExpectedStudioRootId, which the launcher compares against the backend's studio_root_id before+# accepting it (install.ps1:3018, :3085, :3095). If those two ever disagree Studio does not launch+# at all -- and the content comparison cannot see it, because the transcript normaliser rewrites+# every 64-character hex token, so any ID change compares equal. The two values are only meaningful+# against EACH OTHER within one install; they are expected to differ between base and head.+$installId = $null+foreach ($rootLabel in $searchRoots.Keys) {+ $root = $searchRoots[$rootLabel]+ if (-not $root) { continue }+ foreach ($candidate in @('share\studio_install_id', 'studio_install_id')) {+ $probe = Join-Path $root $candidate+ if (Test-Path -LiteralPath $probe) {+ try { $installId = (Get-Content -Raw -LiteralPath $probe -ErrorAction Stop).Trim() } catch {}+ break+ }+ }+ if ($installId) { break }+}++$embeddedId = $null+if ($files['launch-studio.ps1'] -and $files['launch-studio.ps1'].Contains('content')) {+ $m = [regex]::Match($files['launch-studio.ps1'].content, "_ExpectedStudioRootId\s*=\s*'([^']*)'")+ if ($m.Success) { $embeddedId = $m.Groups[1].Value }+}++$artifacts = [ordered]@{+ studioHome = $StudioHome+ files = $files+ shortcutWrites = $shortcutWrites+ installId = $installId+ embeddedId = $embeddedId+}+if ($artifactError) { $artifacts['error'] = $artifactError }+if ($null -ne $rewritten) { $artifacts['rewrittenOnSecondRun'] = @($rewritten) }++$artifacts | ConvertTo-Json -Depth 8 |+ Set-Content -LiteralPath (Join-Path $OutDir 'artifacts.json') -Encoding utf8++Write-Host "collected $($files.Count) artifact entr(ies)$(if ($artifactError) { " [$artifactError]" })"+if ($null -ne $rewritten) {+ Write-Host "second run rewrote: $(if ($rewritten.Count) { $rewritten -join ', ' } else { 'nothing' })"+}++# Always zero. A collection failure is data for the comparer, not a red step.+exit 0diff --git a/.github/scripts/compare_installer_evidence.py b/.github/scripts/compare_installer_evidence.pynew file mode 100644index 00000000000..0a608ce71ae--- /dev/null+++ b/.github/scripts/compare_installer_evidence.py@@ -0,0 +1,970 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Decide whether two installer runs behaved the same, given evidence collected on Windows.++This is the half of the base-vs-head functional lane that does not need Windows, so it lives in a+file with unit tests rather than inline in YAML. The Windows jobs run an installer and write+evidence; this compares two sets of it and produces a verdict.++The comparison is deliberately narrow: it answers "did the user-visible behaviour change", not "are+these runs identical". Two installs of the same commit are never byte-identical -- they differ in+timings, in temp directory names, in which mirror answered, in a `uv` patch release that shipped+between the two jobs. Every one of those is normalised away, and the normalisation rules are the+interesting part of this file: each one is a specific observed source of noise, and widening one to+silence a failure is how a lane like this stops being able to fail.++Three things are compared, because they fail independently:++- **transcript**: every line the installer printed, normalised. A hardening change must not alter+ what a user reads.+- **shortcuts**: the `.lnk` properties read back through the shell. This is where a change to the+ launch transport shows up, and it is invisible in the transcript.+- **artifacts**: a manifest of the files the installer wrote, with hashes for the ones whose content+ is a contract (`launch-studio.ps1`, `unsloth.cmd`).++`VOID` is a first-class outcome and not a pass. If the two sides are the same commit, or the+evidence is missing, or an installer did not finish, there is nothing to compare and saying "no+differences" would be a lie of exactly the kind this lane exists to prevent.+"""++from __future__ import annotations++import argparse+import json+import re+import sys+from pathlib import Path+++# ---------------------------------------------------------------------------+# Normalisation+# ---------------------------------------------------------------------------++# Each entry is (pattern, replacement, why). The `why` is not decoration: the next person to widen+# one of these needs to know what it was for, and a rule with no recorded cause is a rule nobody can+# argue with.+_NORMALISERS: tuple[tuple[re.Pattern[str], str, str, bool], ...] = (+ (re.compile(r"\b\d+\.\d+s\b"), "<duration>", "elapsed times, printed by every step", False),+ (re.compile(r"\b\d{1,3}(?:\.\d+)?\s?%"), "<percent>", "download progress", False),+ (+ re.compile(r"\b\d+(?:\.\d+)?\s?(?:[KMGT]i?B|bytes)\b", re.I),+ "<size>",+ "download sizes, which differ with a CDN or a patch release",+ False,+ ),+ (re.compile(r"\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}\S*"), "<timestamp>", "timestamps", True),+ (+ re.compile(r"\b[0-9a-f]{40}\b|\b[0-9A-F]{64}\b|\b[0-9a-f]{64}\b"),+ "<hash>",+ "commit SHAs and file digests: the two sides are different commits by construction",+ True,+ ),+ (+ re.compile(r"(\.?unsloth-[A-Za-z][A-Za-z-]*[.-])[0-9a-fA-F]{8}[0-9a-fA-F-]*"),+ r"\1<temp>",+ "the random tail of an unsloth-* scratch name: unsloth-probe-<hex8>.tmp, the "+ "unsloth-uv-<hex8> work directory, .unsloth-write-probe.<guid>, "+ "unsloth-torch-overrides-<guid>.txt. Anchored on the random part on purpose. The rule "+ "this replaces matched any six characters after 'unsloth-', which also erased "+ "unsloth-studio-managed-launcher becoming unsloth-desktop-managed-launcher inside "+ "unsloth.cmd, a file whose text this lane treats as a contract",+ True,+ ),+ (+ re.compile(r"\\Temp\\[A-Za-z0-9._-]{6,}"),+ r"\\Temp\\<temp>",+ "Windows temp directory names",+ True,+ ),+ (re.compile(r"\b(pid|PID)[= ]\d+"), r"\1=<pid>", "process ids", False),+ (+ re.compile(r"127\.0\.0\.1:\d+|localhost:\d+"),+ "127.0.0.1:<port>",+ "the port Studio bound, which is chosen from what is free",+ False,+ ),+ (+ re.compile(r"\x1b\[[0-9;?]*[A-Za-z]"),+ "",+ "ANSI sequences, in case a run was not redirected after all",+ False,+ ),+ (re.compile(r"[\r\x08]"), "", "carriage returns and backspaces from progress redraws", False),+)++# Volatile only because the two jobs ran minutes apart. A version drift is not a behaviour change,+# but it IS worth printing, so these are normalised and separately reported.+_VERSION_PATTERN = re.compile(+ r"\b(uv|python|Python|CPython|git|cmake|torch|node|npm)[\s/-]+v?(\d+\.\d+(?:\.\d+)?)",+)+++def collect_versions(text: str) -> dict[str, set[str]]:+ """What each side reported installing, reported rather than compared.++ A `uv` patch release that shipped between the two jobs is not a behaviour change and must not+ fail the lane. But a *deliberate* pin bump looks identical after normalisation, so the versions+ are printed side by side: silently normalising something away and never mentioning it is how a+ lane loses the ability to tell you anything.+ """+ found: dict[str, set[str]] = {}+ for match in _VERSION_PATTERN.finditer(text):+ found.setdefault(match.group(1).lower(), set()).add(match.group(2))+ return found+++def report_version_drift(base: str, head: str, where: str, verdict: "Verdict") -> None:+ """Print what the version normaliser erased, wherever it was applied.++ `normalise_line` runs on shortcut fields and on generated-file content too, not only on the+ transcript, so a launcher retargeted from a python-3.11 directory to a python-3.13 one is+ erased in exactly the same way. That is the right call for a patch release that shipped between+ the two jobs, and the wrong one to make silently: this is the only rule in the set that can+ reach a deliberate change, so everywhere it reaches, the drift is said out loud.+ """+ base_versions = collect_versions(base)+ head_versions = collect_versions(head)+ for tool in sorted(set(base_versions) | set(head_versions)):+ before = ",".join(sorted(base_versions.get(tool, {"-"})))+ after = ",".join(sorted(head_versions.get(tool, {"-"})))+ if before != after:+ verdict.notes.append(+ f"version drift in the {where} (normalised away, not a failure): "+ f"{tool} base={before} head={after}"+ )+++def normalise_line(line: str) -> str:+ out = line+ for pattern, replacement, _why, _in_scripts in _NORMALISERS:+ out = pattern.sub(replacement, out)+ out = _VERSION_PATTERN.sub(lambda m: f"{m.group(1)}/<version>", out)+ # Trailing whitespace only. Leading whitespace is load-bearing: `step` pads its label to exactly+ # 15 columns and REQUIRED_OUTPUT pins the indent, so stripping the left side would hide the one+ # regression class most likely to slip through a prose review.+ return out.rstrip()+++def normalise_contract_value(value: str) -> str:+ """One persisted value, with only the per-run VALUES rewritten.++ Deliberately not `normalise_line`. That one is built for console output, where `10MB`, `0.5s` and+ `127.0.0.1:8123` are noise. In a shortcut's `arguments` or `targetPath` the same text is the+ launch contract: a `--limit 10MB` that becomes `20MB`, a timeout that changes, or a port written+ into the command line are exactly the changes this lane exists to see, and rewriting both sides+ to the same token reported every field equal.++ No rstrip either. Trailing whitespace in an argument string is part of the value, and the+ transcript rule that strips it exists because `step` pads its labels.+ """+ return _VERSION_PATTERN.sub(+ lambda m: f"{m.group(1)}/<version>", _apply_value_normalisers(value)+ )+++def normalise_script(text: str) -> list[str]:+ """A generated script, with only the volatile VALUES rewritten.++ Deliberately not `normalise_transcript`. That one is built for captured console output: it drops+ blank lines, rstrips every line, and discards lines starting with runner noise like `Run `,+ `shell: ` or `env:`. Every one of those is destructive applied to a script. Trailing whitespace+ in a CMD `set` value is part of the value, a dropped blank line changes a here-string, and an+ echoed line that happens to begin with `Run ` is content. A candidate could change any of them+ and both sides would still compare equal.+ """+ return [+ # The scratch names, the embedded install ID, temp directories, timestamps and version+ # strings still have to go: they differ between the two sides for reasons that are not+ # behaviour. Nothing else is touched -- see `_apply_value_normalisers` -- and the line is+ # kept exactly as it is otherwise, trailing spaces and all.+ _VERSION_PATTERN.sub(+ lambda m: f"{m.group(1)}/<version>",+ _apply_value_normalisers(raw),+ )+ for raw in text.splitlines()+ ]+++def _apply_value_normalisers(line: str) -> str:+ """Only the rules whose fourth field says the value is per-run volatile in a FILE.++ The other rules exist for captured console output and are content in a generated script. A+ launcher whose health probe moved from port 8888 to 9999, or a `unsloth.cmd` whose upload limit+ went from 10MB to 20MB, is a behaviour change, and the transcript rules rewrite both sides to+ the same token and report PASS. What genuinely differs between two installs of two commits is+ the embedded studio_root_id, the scratch names, the temp directory and any timestamp, so those+ four are all that a script is normalised for.+ """+ out = line+ for pattern, replacement, _why, in_scripts in _NORMALISERS:+ if not in_scripts:+ continue+ out = pattern.sub(replacement, out)+ return out+++def normalise_transcript(text: str) -> list[str]:+ lines = []+ for raw in text.splitlines():+ line = normalise_line(raw)+ if not line.strip():+ continue+ # Runner-injected noise, and ONLY what the runner injects. These carry the workflow's own+ # group names and the side's SHA, so they differ between sides for nothing to do with the+ # installer.+ #+ # `Run `, `shell: ` and `env:` were in this list and are now gone, because they were never in+ # the file. The workflow tees the child powershell.exe stream into transcript.txt+ # (windows-installer-differential-ci.yml:273-274), so GitHub's step headers never reach it,+ # while the installers print at least six lines that begin with `Run ` once indentation is+ # stripped: install.ps1:1518 and studio/setup.ps1:2245, :2526, :3073, :3526, :4506. Every one+ # of those is user-visible guidance on an exercised path, and this rule deleted them from+ # both sides, so changing or dropping one of them compared equal. Matching a prose prefix is+ # the wrong shape for this job; if the capture ever widens to include the step's own output,+ # the honest fix is to narrow the capture, not to delete lines that might be ours.+ #+ # Left anchored at column 0: nothing the installers print starts in column 0 with these.+ if line.startswith(("##[group]", "##[endgroup]", "::group::", "::endgroup::", "##[debug]")):+ continue+ lines.append(line)+ return lines+++# ---------------------------------------------------------------------------+# Comparison+# ---------------------------------------------------------------------------+++class Verdict:+ """The outcome, with every difference kept rather than only the first."""++ def __init__(self) -> None:+ self.void: list[str] = []+ self.differences: list[str] = []+ self.notes: list[str] = []++ @property+ def is_void(self) -> bool:+ return bool(self.void)++ @property+ def passed(self) -> bool:+ return not self.void and not self.differences++ def exit_code(self) -> int:+ # VOID and DIFFERENT are both non-zero, and deliberately distinct: 2 means "measured, and it+ # changed"; 3 means "could not measure", which must never read as a pass.+ if self.void:+ return 3+ if self.differences:+ return 2+ return 0+++def _unified(+ base: list[str],+ head: list[str],+ label: str,+ limit: int = 60,+) -> list[str]:+ import difflib++ diff = list(+ difflib.unified_diff(+ base, head, fromfile = f"base/{label}", tofile = f"head/{label}", lineterm = "", n = 2+ )+ )+ if len(diff) > limit:+ omitted = len(diff) - limit+ diff = diff[:limit] + [f"... {omitted} more diff lines omitted; the artifact has all of it"]+ return diff+++def compare_transcripts(+ base: str,+ head: str,+ verdict: Verdict,+ label: str = "transcript",+) -> None:+ base_lines = normalise_transcript(base)+ head_lines = normalise_transcript(head)+ if not base_lines or not head_lines:+ verdict.void.append(+ f"one side's {label} is empty after normalisation, so there is nothing to compare. "+ f"An installer that printed nothing did not run."+ )+ return+ report_version_drift(base, head, label, verdict)++ if base_lines == head_lines:+ verdict.notes.append(f"{label}: identical over {len(base_lines)} normalised lines")+ return+ verdict.differences.append(+ f"the installer's user-visible output changed in the {label}:\n"+ + "\n".join(_unified(base_lines, head_lines, label))+ )+++def _shortcut_key(entry: dict) -> str:+ """Location AND file name.++ A normal install writes the same file name to the Desktop and to the Start Menu, so a key of+ just the name collapses the pair into one entry. If one of the two stopped being created and+ the survivor kept its fields, both maps still held one identical key and the comparison+ reported equality -- the disappearance of a shortcut being exactly what this lane is for. The+ collector already records `root` as a leaf name, so it costs nothing and does not reintroduce+ the workspace path that deliberately is not part of the key.+ """+ name = str(entry.get("name") or entry.get("path") or "<unnamed>")+ root = entry.get("root")+ return f"{root}/{name}" if root else name+++# Read back from the shell, and every one of them is a contract. Arguments especially: it carries+# -WindowStyle and -ExecutionPolicy, which is the pair this whole effort is about, and a change+# there is completely invisible in the transcript.+_SHORTCUT_FIELDS = (+ "targetPath",+ "arguments",+ "workingDirectory",+ "windowStyle",+ "iconLocation",+ # The tooltip. It is user-visible, the collector records it, and install.ps1 reads it back at+ # :3455 as part of deciding whether a shortcut is already correct, so a change to it is both a+ # behaviour change and invisible in the transcript. Leaving it out made those compare equal.+ "description",+)+++# The two files this lane treats as contracts by their TEXT, kept in step with the collector's+# $contentFiles (.github/scripts/Collect-InstallerEvidence.ps1). A name here without captured content+# is VOID rather than skipped, and the list is explicit so adding a third place to the collector+# without adding it here is visible rather than silent.+_CONTENT_CONTRACTS = ("launch-studio.ps1", "unsloth.cmd")+++def _as_list(value) -> list[dict]:+ """ConvertTo-Json unwraps a one-element collection into a bare object.++ The collector forces an array, but this side must not depend on that: a schema that changes with+ the number of shortcuts found would make the single-shortcut case iterate dictionary *keys* and+ compare strings, which reports agreement for entirely the wrong reason.+ """+ if value is None:+ return []+ if isinstance(value, dict):+ return [value]+ return [item for item in value if isinstance(item, dict)]+++def _shape_problem(value) -> str | None:+ """Anything that is not a list of objects, or one unwrapped object, is not a manifest.++ `_as_list` used to absorb the difference silently: handed a bare string it iterated characters,+ kept none of them, and produced an empty list, which then compared against a populated side as+ "every shortcut disappeared". That reads as a behaviour change and is nothing of the kind, so+ the shape is checked rather than coerced.+ """+ if value is None or isinstance(value, dict):+ return None+ if isinstance(value, list):+ bad = sum(1 for item in value if not isinstance(item, dict))+ if bad:+ return f"{bad} of {len(value)} entries are not objects"+ return None+ return f"the manifest is a {type(value).__name__}, not a list of shortcut objects"+++def compare_shortcuts(base, head, verdict: Verdict) -> None:+ for side, value in (("base", base), ("head", head)):+ problem = _shape_problem(value)+ if problem:+ verdict.void.append(+ f"{side}'s shortcut manifest is not the shape this lane writes: {problem}. "+ f"Evidence that cannot be parsed was not measured."+ )+ if verdict.is_void:+ return++ before_differences = len(verdict.differences)+ base, head = _as_list(base), _as_list(head)+ if not base and not head:+ verdict.void.append(+ "neither side reported any shortcut. The installer creates a desktop and a Start Menu "+ "entry, so zero on both sides means the evidence was not collected, not that they agree."+ )+ return+ # A collection error on both sides compares equal to itself. Observed while wiring this up: two+ # runs that both failed to read any shortcut reported "1 compared, every field equal" and exited+ # zero. Failures are symmetric far more often than behaviour changes are -- they usually come+ # from the host, which both sides share -- so the symmetry is no comfort at all.+ for side, entries in (("base", base), ("head", head)):+ for entry in entries:+ if entry.get("error"):+ verdict.void.append(+ f"{side} could not read shortcut {_shortcut_key(entry)!r}: {entry['error']}. "+ f"Two sides that both failed to collect evidence agree with each other and "+ f"prove nothing."+ )+ continue+ # An entry with no identity and no launch contract is not a shortcut. `{}` survives+ # `_shape_problem` (it IS an object), `_as_list` counts it as one, and `_shortcut_key`+ # names it `<unnamed>`, so two empty objects compared equal and the run reported "1+ # compared, every field equal". The same collector writes both sides, so a schema+ # regression is symmetric and this is the shape it takes.+ if not (entry.get("name") or entry.get("path")):+ verdict.void.append(+ f"{side} reported a shortcut with no name and no path, so there is nothing to "+ f"identify it by and nothing was measured: {entry!r}"+ )+ continue+ if not any(entry.get(field) for field in _SHORTCUT_FIELDS):+ verdict.void.append(+ f"{side}'s shortcut {_shortcut_key(entry)!r} carries none of the launch contract "+ f"fields {list(_SHORTCUT_FIELDS)}, so the contract this lane exists to compare "+ f"was never collected"+ )+ if verdict.is_void:+ return++ base_map = {_shortcut_key(e): e for e in base}+ head_map = {_shortcut_key(e): e for e in head}++ def _fields(entries: list[dict]) -> str:+ return "\n".join(str(e.get(f, "")) for e in entries for f in _SHORTCUT_FIELDS)++ report_version_drift(_fields(base), _fields(head), "shortcut fields", verdict)++ for missing in sorted(set(base_map) - set(head_map)):+ verdict.differences.append(f"shortcut {missing!r} exists on base and not on head")+ for added in sorted(set(head_map) - set(base_map)):+ verdict.differences.append(f"shortcut {added!r} exists on head and not on base")++ for name in sorted(set(base_map) & set(head_map)):+ for field in _SHORTCUT_FIELDS:+ before = normalise_contract_value(str(base_map[name].get(field, "")))+ after = normalise_contract_value(str(head_map[name].get(field, "")))+ if before != after:+ verdict.differences.append(+ f"shortcut {name!r} field {field!r} changed:\n base: {before}\n head: {after}"+ )+ # Scoped to this comparison. Reading the whole verdict here meant a transcript difference+ # suppressed the shortcut note, so a run that reported a changed line also stopped saying+ # whether the launch contract had been looked at.+ if len(verdict.differences) == before_differences:+ verdict.notes.append(f"shortcuts: {len(base_map)} compared, every field equal")+++def compare_artifacts(base: dict, head: dict, verdict: Verdict) -> None:+ """The installed files. Paths on both sides, content only where content is a contract."""+ # The same reasoning as for shortcuts, which this did not have. The collector records a+ # collection failure as an `error` field rather than a red step, and an error read as data is a+ # green run: two sides that both failed to enumerate the install root list no files, compare+ # equal, and report agreement. A per-file error is worse, because the entry still exists with+ # the same key and only the `content` is gone, so the content check below skips it silently and+ # the file that was never compared is the one whose text is the contract.+ for side, data in (("base", base), ("head", head)):+ if not isinstance(data, dict):+ verdict.void.append(+ f"{side}'s artifact manifest is a {type(data).__name__}, not an object"+ )+ continue+ if data.get("error"):+ verdict.void.append(+ f"{side} could not collect its artifact manifest: {data['error']}. A collection "+ f"failure is not evidence, and it is symmetric far more often than a behaviour "+ f"change is."+ )+ if verdict.is_void:+ return++ base_files = base.get("files") or {}+ head_files = head.get("files") or {}+ for side, files in (("base", base_files), ("head", head_files)):+ if not isinstance(files, dict):+ verdict.void.append(+ f"{side}'s artifact manifest lists files as a {type(files).__name__}, not an object"+ )+ continue+ for name in sorted(files):+ entry = files[name]+ if isinstance(entry, dict) and entry.get("error"):+ verdict.void.append(+ f"{side} could not read {name!r}: {entry['error']}. The file is still listed, "+ f"so without this the content check below would skip it and the run would "+ f"report agreement about a file it never read."+ )+ if verdict.is_void:+ return++ if not base_files and not head_files:+ verdict.void.append("neither side listed any installed file, so nothing was measured")+ return++ for missing in sorted(set(base_files) - set(head_files)):+ verdict.differences.append(f"base installed {missing!r} and head did not")+ for added in sorted(set(head_files) - set(base_files)):+ verdict.differences.append(f"head installed {added!r} and base did not")++ for name in sorted(set(base_files) & set(head_files)):+ before, after = base_files[name], head_files[name]+ if not isinstance(before, dict) or not isinstance(after, dict):+ # VOID, not skipped. The SAME collector runs on both legs, so a malformed entry is+ # malformed identically on both and skipping it left the maps non-empty, the key sets+ # matching and nothing compared, which the run then reported as agreement. The shortcut+ # manifest and the top-level manifests are already validated this way.+ sides = [+ side+ for side, value in (("base", before), ("head", after))+ if not isinstance(value, dict)+ ]+ verdict.void.append(+ f"{name!r} is a {type(before).__name__ if 'base' in sides else type(after).__name__}"+ f" and not an object on {' and '.join(sides)}, so its evidence could not be read"+ )+ continue+ # The two entries whose CONTENT is the contract. An empty object on both sides made the+ # asymmetry check below false and the comparison below that false too, so the loop compared+ # nothing and the run passed. Symmetric malformed evidence is the likely failure mode here,+ # because the candidate collector writes both manifests.+ if name in _CONTENT_CONTRACTS and not before.get("error") and not after.get("error"):+ absent = [+ side+ for side, value in (("base", before), ("head", after))+ if "content" in value and value.get("content") is not None+ ]+ if len(absent) != 2:+ verdict.void.append(+ f"{name!r} is one of the files whose text is the contract, and its content was "+ f"not captured on "+ f"{' or '.join(s for s in ('base', 'head') if s not in absent)}. Nothing was "+ f"compared, and two sides that both captured nothing agree with each other."+ )+ continue+ if ("content" in before) != ("content" in after):+ # One side captured the text and the other did not. Skipping quietly, which is what+ # happened before, means the file whose content is the whole reason it is in the+ # manifest goes uncompared while the run still reports agreement.+ side = "head" if "content" in before else "base"+ verdict.void.append(+ f"{name!r} has captured content on one side only, so {side} never contributed the "+ f"text this lane compares"+ )+ continue+ if "content" in before and "content" in after:+ # The drift note first, on the RAW text, exactly as the transcript and shortcut+ # comparisons do it. Without this a launcher retargeted from python-3.11.9 to+ # python-3.13.0 was normalised away and the lane returned PASS with no note at all,+ # which is the one thing normalisation is supposed to buy back.+ report_version_drift(before["content"], after["content"], f"generated {name}", verdict)+ b = normalise_script(before["content"])+ a = normalise_script(after["content"])+ if b != a:+ verdict.differences.append(+ f"the generated {name} changed:\n" + "\n".join(_unified(b, a, name))+ )+ # Encoding is part of the contract and is invisible in the decoded text. Windows PowerShell+ # 5.1 reads a BOM-less file as ANSI, so a launcher that silently stops carrying its UTF-8+ # BOM breaks every install whose paths contain non-ASCII characters while comparing equal.+ bom_before, bom_after = before.get("bom"), after.get("bom")+ if name in _CONTENT_CONTRACTS and not (bom_before and bom_after):+ # VOID, not skipped. The same collector writes both manifests, so a regression that drops+ # the field drops it on both sides, and skipping quietly reported a pass for an encoding+ # contract that was never measured. This is the field whose absence in the FILE breaks+ # every install with a non-ASCII path, so unmeasured is not a pass.+ missing = [+ side for side, value in (("base", bom_before), ("head", bom_after)) if not value+ ]+ verdict.void.append(+ f"{name!r} carries no bom metadata on {' and '.join(missing)}, so the encoding "+ f"contract was not measured. Windows PowerShell 5.1 reads a file with no BOM as ANSI."+ )+ elif bom_before and bom_after and bom_before != bom_after:+ verdict.differences.append(+ f"{name!r} changed encoding: base wrote {bom_before} and head wrote {bom_after}. "+ f"Windows PowerShell 5.1 reads a file with no BOM as ANSI."+ )+ # Where it landed, not only what is in it. The collector probes each contract at several+ # supported locations and records the one it found, so a candidate that moves studio.conf+ # between `share\studio.conf` and `studio.conf` without touching a byte keeps the same key+ # and the same content. Comparing content alone reports that as agreement, while everything+ # that has to open the file now looks in the wrong place.+ found_before, found_after = before.get("foundAt"), after.get("foundAt")+ if found_before and found_after and found_before != found_after:+ verdict.differences.append(+ f"{name!r} moved: base wrote it to {found_before} and head wrote it to "+ f"{found_after}. The bytes may match, but consumers must now look elsewhere."+ )++ # The install ID, checked WITHIN each side rather than across them. The launcher embeds the ID+ # it will accept from the backend, and the backend reads the persisted one, so if those two+ # disagree Studio refuses its own server and never starts. They are expected to differ between+ # base and head, which is precisely why a cross-side comparison cannot see this and why the+ # transcript normaliser rewriting every 64-hex token hides it completely.+ for side, data in (("base", base), ("head", head)):+ persisted, embedded = data.get("installId"), data.get("embeddedId")+ if persisted and embedded and persisted != embedded:+ verdict.differences.append(+ f"{side}: the launcher expects studio_root_id {embedded!r} but the install "+ f"persisted {persisted!r}. Studio would refuse its own backend."+ )+ elif embedded and not persisted:+ verdict.void.append(+ f"{side}: the launcher embeds an expected studio_root_id but no persisted "+ f"studio_install_id was found, so the pair could not be checked"+ )++ # Idempotency is reported by the Windows side, which is the only place it can be observed: it+ # runs the installer twice and records whether the second run rewrote anything.+ for side, data in (("base", base), ("head", head)):+ rewritten = data.get("rewrittenOnSecondRun")+ if rewritten is None:+ # VOID, not a note. `None` and `[]` mean different things here and the collector is+ # careful to keep them apart: `[]` is "measured, nothing was rewritten" and `None` is+ # "not measured". Treating the second as optional evidence let the lane report equality+ # while one of the four contracts it advertises had never been checked, which happens+ # whenever the first collector or the non-terminating Copy-Item ahead of the second+ # install fails while everything after it succeeds.+ verdict.void.append(+ f"{side}: idempotency was never measured, so there is no evidence that a reinstall "+ f"writes nothing. That is one of this lane's four contracts, and an unmeasured "+ f"contract is not a passing one."+ )+ elif rewritten:+ verdict.differences.append(+ f"{side}: running the installer a second time rewrote {sorted(rewritten)}. "+ f"A reinstall that changed nothing must write nothing."+ )+ else:+ verdict.notes.append(f"{side}: the second run rewrote nothing")+++# The installer's own exit status, which the transcript does not carry. Recorded by the workflow,+# which is the only thing that sees it.+_RUN_CODES = (+ ("installExit", "the installer"),+ ("secondInstallExit", "the second, idempotency install"),+)+++def compare_run_status(base, head, verdict: Verdict) -> None:+ """An installer that failed measured nothing, however tidy its transcript looks.++ This is the most dangerous symmetry the lane has. A host problem, a mirror outage, a Defender+ definition push: any of them fails both installs the same way, at the same point, printing the+ same lines. The transcripts then match, the shortcut manifests are both empty in the same way,+ and the lane reports "no behaviour difference" about two installs that never happened. The exit+ status is the only thing that distinguishes that from a real pass, so a missing one is VOID too:+ the comparer is taken from the candidate on both sides, so evidence without it is evidence from+ a run that was never in a position to say the installer finished.+ """+ for side, data in (("base", base), ("head", head)):+ if not isinstance(data, dict):+ verdict.void.append(+ f"{side} recorded no usable installer exit status, so nothing establishes that its "+ f"installer finished"+ )+ continue+ for key, what in _RUN_CODES:+ code = data.get(key)+ if not isinstance(code, int) or isinstance(code, bool):+ verdict.void.append(+ f"{side} recorded no exit status for {what} ({key!r} is {code!r}). Two runs "+ f"that both failed print matching transcripts, so a comparison that cannot see "+ f"the exit status cannot tell a pass from a shared failure."+ )+ elif code != 0:+ verdict.void.append(+ f"{side}: {what} exited {code}. Nothing it left behind is evidence of what a "+ f"successful install does."+ )+++def _load(path: Path, verdict: Verdict, what: str):+ if not path.is_file():+ verdict.void.append(f"{what} is missing at {path}, so this side produced no evidence")+ return None+ try:+ # utf-8-sig, not utf-8: Windows PowerShell 5.1 writes a BOM for `Set-Content -Encoding+ # utf8`, and a BOM makes json.loads fail on a file that is otherwise perfectly good.+ if path.suffix == ".json":+ return json.loads(path.read_text(encoding = "utf-8-sig", errors = "replace"))+ return path.read_text(encoding = "utf-8-sig", errors = "replace")+ except (OSError, ValueError) as exc:+ verdict.void.append(f"{what} at {path} could not be read: {exc}")+ return None+++def compare_directories(+ base_dir: Path,+ head_dir: Path,+ base_sha: str = "",+ head_sha: str = "",+) -> Verdict:+ verdict = Verdict()++ if base_sha and head_sha and base_sha == head_sha:+ verdict.void.append(+ f"both sides are {base_sha[:12]}. Comparing a commit with itself cannot show that a "+ f"change preserved behaviour; it shows only that the lane is deterministic."+ )+ return verdict++ base_transcript = _load(base_dir / "transcript.txt", verdict, "the base transcript")+ head_transcript = _load(head_dir / "transcript.txt", verdict, "the head transcript")+ # The reinstall output, which the workflow has always captured and this comparer never read. A+ # candidate that changes what the installer prints only when an installation already exists --+ # a reinstall warning added or dropped, a "nothing to do" line reworded -- leaves the first-run+ # transcripts identical and the artifacts untouched, so without this the lane reported PASS on+ # a user-visible change. Required rather than optional: the step that writes it runs under+ # `if: always()`, so a side that does not have one did not produce the evidence.+ base_second = _load(+ base_dir / "transcript-second-run.txt",+ verdict,+ "the base second-run transcript",+ )+ head_second = _load(+ head_dir / "transcript-second-run.txt",+ verdict,+ "the head second-run transcript",+ )+ base_shortcuts = _load(base_dir / "shortcuts.json", verdict, "the base shortcut manifest")+ head_shortcuts = _load(head_dir / "shortcuts.json", verdict, "the head shortcut manifest")+ base_artifacts = _load(base_dir / "artifacts.json", verdict, "the base artifact manifest")+ head_artifacts = _load(head_dir / "artifacts.json", verdict, "the head artifact manifest")+ base_run = _load(base_dir / "run.json", verdict, "the base run status")+ head_run = _load(head_dir / "run.json", verdict, "the head run status")++ if verdict.is_void:+ return verdict++ compare_run_status(base_run, head_run, verdict)+ if verdict.is_void:+ return verdict++ compare_transcripts(base_transcript, head_transcript, verdict, "first-run transcript")+ compare_transcripts(base_second, head_second, verdict, "second-run transcript")+ # Passed through as loaded, not coerced with `or []` / `or {}`. The coercion turned a manifest+ # of the wrong shape into an empty one of the right shape, and an empty manifest against a+ # populated one reads as "every file disappeared" -- a behaviour difference, reported about+ # evidence that was never parsed.+ compare_shortcuts(base_shortcuts, head_shortcuts, verdict)+ compare_artifacts(base_artifacts, head_artifacts, verdict)+ return verdict+++# ---------------------------------------------------------------------------+# The positive control+# ---------------------------------------------------------------------------++# A differ that reports no differences looks exactly the same whether it is working or broken. So+# before the real comparison is trusted, it is handed a pair it MUST call different, and a pair it+# MUST call equal. Both directions matter: a differ that flags everything is as useless as one that+# flags nothing, it just fails more loudly.+_CONTROL_TRANSCRIPT = "\n".join(+ [+ " python 3.13.14 ready",+ " studio installed in 12.4s",+ " shortcut desktop and Start Menu",+ ]+)+++def self_test() -> list[str]:+ failures: list[str] = []++ noisy = "\n".join(+ [+ " python 3.13.9 ready",+ " studio installed in 41.9s",+ " shortcut desktop and Start Menu",+ ]+ )+ v = Verdict()+ compare_transcripts(_CONTROL_TRANSCRIPT, noisy, v)+ if v.differences:+ failures.append(+ "the normaliser is too strict: a version drift and a timing difference were reported "+ "as a behaviour change, which would make this lane fail on every run and get disabled. "+ f"Reported: {v.differences}"+ )++ changed = _CONTROL_TRANSCRIPT.replace("desktop and Start Menu", "desktop only")+ v = Verdict()+ compare_transcripts(_CONTROL_TRANSCRIPT, changed, v)+ if not v.differences:+ failures.append(+ "the normaliser is too loose: a changed output line was NOT reported. Every 'no "+ "differences' verdict this lane has ever produced would be worthless."+ )++ indented = _CONTROL_TRANSCRIPT.replace(" python", " python")+ v = Verdict()+ compare_transcripts(_CONTROL_TRANSCRIPT, indented, v)+ if not v.differences:+ failures.append(+ "an indentation change was not reported. `step` pads its label to exactly 15 columns "+ "and the output lock pins the indent, so a lost space is a real regression."+ )++ v = Verdict()+ compare_shortcuts(+ [+ {+ "name": "Unsloth.lnk",+ "arguments": "-NoProfile -WindowStyle Hidden -ExecutionPolicy RemoteSigned -File x",+ }+ ],+ [+ {+ "name": "Unsloth.lnk",+ "arguments": "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File x",+ }+ ],+ v,+ )+ if not v.differences:+ failures.append(+ "a shortcut whose execution policy changed from RemoteSigned to Bypass was NOT "+ "reported. That is the single substitution this entire effort is about."+ )++ v = Verdict()+ compare_shortcuts([], [], v)+ if not v.is_void:+ failures.append(+ "two empty shortcut manifests were treated as agreement rather than as VOID"+ )++ v = compare_directories(Path("/nonexistent/base"), Path("/nonexistent/head"), "aaa", "bbb")+ if not v.is_void or v.exit_code() != 3:+ failures.append("missing evidence did not produce VOID with exit code 3")++ # The normaliser that erased a renamed launcher marker. `unsloth-studio-managed-launcher` is+ # written into unsloth.cmd and is how the installer recognises its own shim, so a rename is a+ # behaviour change; the rule meant for `unsloth-uv-<hex8>` swallowed it.+ v = Verdict()+ compare_transcripts(+ " cmd rem unsloth-studio-managed-launcher",+ " cmd rem unsloth-desktop-managed-launcher",+ v,+ )+ if not v.differences:+ failures.append(+ "a renamed unsloth-* marker was normalised away. The temp-name rule is anchored on a "+ "random hex tail precisely so that it cannot reach a name that means something."+ )+ v = Verdict()+ compare_transcripts(+ r" work C:\Temp\unsloth-uv-1a2b3c4d\bin",+ r" work C:\Temp\unsloth-uv-99ffee00\bin",+ v,+ )+ if v.differences:+ failures.append(+ f"a random temp directory name was reported as a behaviour change: {v.differences}"+ )++ v = Verdict()+ compare_artifacts(+ {"files": {"launch-studio.ps1": {"content": "x\n"}}},+ {"files": {"launch-studio.ps1": {"error": "access denied"}}},+ v,+ )+ if not v.is_void:+ failures.append(+ "an artifact entry carrying an error was treated as data. The entry still has its key, "+ "so the content check skips it and the run agrees about a file it never read."+ )++ v = Verdict()+ compare_run_status(+ {"installExit": 1, "secondInstallExit": 1}, {"installExit": 1, "secondInstallExit": 1}, v+ )+ if not v.is_void:+ failures.append(+ "two installers that both exited non-zero were not VOID. A shared failure produces "+ "matching transcripts, which is the one symmetry that looks exactly like a pass."+ )+ v = Verdict()+ compare_run_status({}, {}, v)+ if not v.is_void:+ failures.append("evidence with no recorded installer exit status was not VOID")+ v = Verdict()+ compare_run_status(+ {"installExit": 0, "secondInstallExit": 0}, {"installExit": 0, "secondInstallExit": 0}, v+ )+ if v.is_void or v.differences:+ failures.append(f"two successful installs were not accepted: {v.void} {v.differences}")++ return failures+++# ---------------------------------------------------------------------------+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description = __doc__)+ parser.add_argument("--base", type = Path, help = "directory holding the base side's evidence")+ parser.add_argument("--head", type = Path, help = "directory holding the head side's evidence")+ parser.add_argument("--base-sha", default = "")+ parser.add_argument("--head-sha", default = "")+ parser.add_argument(+ "--self-test", action = "store_true", help = "run the positive controls and exit"+ )+ args = parser.parse_args(argv)++ if args.self_test:+ failures = self_test()+ for failure in failures:+ print(f"::error::self-test: {failure}")+ if failures:+ print(+ "::error::the comparer's own controls failed, so no verdict it produces can be "+ "trusted. Refusing to compare."+ )+ return 1+ print("self-test: the comparer reports real changes and ignores known noise")+ return 0++ if not args.base or not args.head:+ parser.error("--base and --head are required unless --self-test is given")++ verdict = compare_directories(args.base, args.head, args.base_sha, args.head_sha)++ for note in verdict.notes:+ print(f" {note}")++ if verdict.is_void:+ print()+ for reason in verdict.void:+ print(f"::error::VOID: {reason}")+ print(+ "::error::VOID is not a pass. Nothing was compared, so nothing was shown to be "+ "unchanged."+ )+ return verdict.exit_code()++ if verdict.differences:+ print()+ for difference in verdict.differences:+ print(f"::error::{difference}")+ print(+ f"::error::{len(verdict.differences)} behaviour difference(s) between "+ f"{args.base_sha[:12] or 'base'} and {args.head_sha[:12] or 'head'}. A hardening "+ f"change must not alter what the installer does or what a user sees."+ )+ return verdict.exit_code()++ print()+ print(+ f"PASS: {args.base_sha[:12] or 'base'} and {args.head_sha[:12] or 'head'} produced the "+ f"same user-visible output, the same shortcuts and the same installed files."+ )+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/workflows/windows-installer-differential-ci.yml b/.github/workflows/windows-installer-differential-ci.ymlnew file mode 100644index 00000000000..bd8637e21c6--- /dev/null+++ b/.github/workflows/windows-installer-differential-ci.yml@@ -0,0 +1,445 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++# Does a change to the Windows installer alter what it does?+#+# Six antivirus-hardening passes have shipped, each argued safe in prose. This lane replaces the+# argument with a measurement: install from the merge base and from the candidate on two identical+# Windows runners, and compare the user-visible transcript, the .lnk launch contract read back+# through the shell, the generated launcher files, and whether a second install rewrites anything.+# Zero differences is the pass condition.+#+# Three things make this different from the install lanes that already exist:+#+# * It is DIFFERENTIAL. A single absolute verdict on a 443 KB script is noise; a delta is not. The+# two sides run in parallel, so the wall clock is one install rather than two.+# * VOID is a first-class outcome. Same commit on both sides, missing evidence, an installer that+# did not finish -- each of those is reported as "nothing was measured" and exits non-zero, with+# a distinct exit code from "it changed". A lane whose broken state looks like its clean state is+# worse than no lane.+# * The comparer runs its own positive controls BEFORE it compares anything, and refuses to+# produce a verdict if they fail. Unit tests for it are in+# tests/python/test_installer_differential_comparer.py, and they test the failure direction+# harder than the pass direction.+#+# Deliberately not a required check and deliberately not on every push: two full clean-machine+# installs is expensive, and the installer changes it judges are rare. Run it with the+# `installer-differential` label, by dispatch, or wait for the weekly schedule.+#+# What this lane cannot answer: anything about a third-party antivirus. Hosted runners have none,+# and installing an endpoint agent per run is neither fast nor faithful. It also cannot answer+# anything about Windows PowerShell 5.1 at a real console -- see windows-vt-preflight.yml for that.++name: "Windows: installer differential (base vs head)"++on:+ workflow_dispatch:+ inputs:+ base_ref:+ description: "What to compare against (default: the PR merge base, or main)"+ required: false+ default: ''+ pull_request:+ types: [labeled, synchronize]+ paths:+ # Only what this lane actually runs. The measurement invokes install.ps1, which hands off to+ # studio/setup.ps1, and nothing here executes studio/setup.bat or scripts/uninstall.ps1 --+ # a PR touching either used to start this workflow, produce identical evidence on both legs+ # because neither file was ever read, and report PASS without having tested the change. A+ # green lane that did not exercise the thing is worse than no lane, so the trigger now+ # matches the coverage. studio/setup.bat is covered by tests/studio/test_installer_av_shapes.py+ # and scripts/uninstall.ps1 by tests/studio/test_uninstall_dual_install_icon.ps1.+ - 'install.ps1'+ - 'studio/setup.ps1'+ - '.github/scripts/Collect-InstallerEvidence.ps1'+ - '.github/scripts/compare_installer_evidence.py'+ - '.github/workflows/windows-installer-differential-ci.yml'+ schedule:+ # Weekly, against main's own merge base, so the lane is known to work before it is relied on to+ # judge a change. A differential lane that has not run in a month is not evidence of anything.+ - cron: '17 5 * * 1'++permissions:+ contents: read++concurrency:+ # The label is part of the group, not only of the step gate. Workflow concurrency is evaluated+ # before any job runs, so a step that decides to do nothing still cancelled the measurement that+ # was in flight: applying any label to a PR whose files match the filter above started a run,+ # that run took this group, and the installs already going were killed. Label events that are not+ # `installer-differential` now share a group of their own, so they cancel each other and never a+ # measurement.+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ (github.event.action == 'labeled' && github.event.label.name != 'installer-differential') && 'unrelated-label' || 'measure' }}+ cancel-in-progress: true++env:+ UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK: '1'+ UNSLOTH_SKIP_AUTOSTART: '1'+ # No colour and no spinner: this lane diffs the transcript, and a redraw is noise the comparer+ # would have to strip. It strips it anyway, but not needing to is better.+ NO_COLOR: '1'++jobs:+ resolve:+ name: is there anything to compare+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ outputs:+ base_sha: ${{ steps.pick.outputs.base_sha }}+ head_sha: ${{ steps.pick.outputs.head_sha }}+ proceed: ${{ steps.pick.outputs.proceed }}+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ fetch-depth: 0+ persist-credentials: false++ - name: Skip unless the label asked for it+ id: gate+ env:+ EVENT: ${{ github.event_name }}+ ACTION: ${{ github.event.action }}+ NEW_LABEL: ${{ github.event.label.name }}+ LABELS: ${{ toJSON(github.event.pull_request.labels.*.name) }}+ run: |+ set -euo pipefail+ if [ "$EVENT" != "pull_request" ]; then+ echo "wanted=1" >> "$GITHUB_OUTPUT"; exit 0+ fi+ # On a `labeled` event, the label that was just applied, not the PR's whole list. With the+ # full list, adding ANY label to a PR that already carries this one started the lane again,+ # and the concurrency group has cancel-in-progress, so a measurement already running was+ # cancelled and restarted by an unrelated label. `synchronize` still reads the full list,+ # because there no single label was applied and the question is whether the PR has opted in.+ if [ "$ACTION" = "labeled" ]; then+ if [ "$NEW_LABEL" = "installer-differential" ]; then+ echo "wanted=1" >> "$GITHUB_OUTPUT"+ else+ echo "wanted=0" >> "$GITHUB_OUTPUT"+ echo "the label just applied is '$NEW_LABEL', not 'installer-differential'; not restarting two clean installs for it"+ fi+ exit 0+ fi+ # Two full installs per run, so a pull_request only opts in by label. `synchronize` is in+ # the trigger list so that a labelled PR keeps being re-measured as it is pushed to;+ # without it the verdict would be about whichever commit happened to be there when the+ # label was applied.+ # The quotes are part of the match. A bare substring would also fire on a future+ # `installer-differential-skip`, which is the one label that must not start two installs.+ if echo "$LABELS" | grep -q '"installer-differential"'; then+ echo "wanted=1" >> "$GITHUB_OUTPUT"+ else+ echo "wanted=0" >> "$GITHUB_OUTPUT"+ echo "no 'installer-differential' label; this lane costs two clean installs so it opts in"+ fi++ - name: Pick the two commits+ id: pick+ if: steps.gate.outputs.wanted == '1'+ env:+ BASE_INPUT: ${{ inputs.base_ref }}+ DEFAULT_BRANCH: ${{ github.event.repository.default_branch || 'main' }}+ PR_BASE: ${{ github.event.pull_request.base.sha }}+ PR_HEAD: ${{ github.event.pull_request.head.sha }}+ run: |+ set -euo pipefail+ head="${PR_HEAD:-$(git rev-parse HEAD)}"++ if [ -n "$BASE_INPUT" ]; then+ git fetch --no-tags --depth=1 origin "$BASE_INPUT" 2>/dev/null || true+ # --verify --quiet on every one of these, not `2>/dev/null`. rev-parse ECHOES an+ # argument it cannot resolve to stdout before failing, so `a || b` captured the literal+ # AND the fallback's SHA and $base became two lines. base_ref=main is the documented+ # input and hits it every time: a checkout has origin/main and no local main.+ base="$(git rev-parse --verify --quiet "$BASE_INPUT^{commit}" || git rev-parse --verify --quiet FETCH_HEAD || true)"+ if [ -z "$base" ]; then+ echo "::error::base_ref '$BASE_INPUT' could not be resolved to a commit, so there is no baseline to measure against."+ echo "proceed=0" >> "$GITHUB_OUTPUT"+ exit 1+ fi+ elif [ -n "${PR_BASE:-}" ]; then+ # The merge base, not the base branch tip. Comparing against a tip that has moved on+ # attributes somebody else's merged change to this PR.+ base="$(git merge-base "$PR_BASE" "$head")"+ else+ # The default branch's merge base, which is what the base_ref input documents. HEAD~1 was+ # wrong for the case this branch actually serves: a manual dispatch on a feature branch+ # with more than one commit, where an installer change from an earlier commit is already+ # in both HEAD and HEAD~1, so the lane compared two trees that share it and reported PASS+ # without ever testing it against main.+ git fetch --no-tags origin "$DEFAULT_BRANCH" 2>/dev/null || true+ default_tip="$(git rev-parse --verify --quiet FETCH_HEAD || git rev-parse --verify --quiet "origin/$DEFAULT_BRANCH" || true)"+ base="$(git merge-base "$default_tip" "$head" 2>/dev/null || true)"+ if [ -n "$default_tip" ] && [ "$head" = "$default_tip" ]; then+ # We ARE the tip of the default branch: the weekly health run, and a manual dispatch+ # from main. The merge base of main with main is main, and the same-commit guard below+ # would VOID every scheduled run, so the baseline here is the previous commit. That is+ # the right question for a health run, whose job is to show the lane still works.+ #+ # Compared against the fetched TIP, not inferred from the merge base being head. Head+ # being an ancestor of the default branch also makes that merge base head -- a dispatch+ # at an older main commit, or a branch with no commits of its own -- and substituting+ # HEAD~1 there measured two adjacent historical commits and could report PASS for a+ # comparison nobody asked for. Those cases fall through to the same-commit guard and+ # are VOID, which is the honest answer: there is nothing of this branch to measure.+ echo "head is the tip of $DEFAULT_BRANCH, so this compares it against the previous commit on that branch"+ base="$(git rev-parse HEAD~1)"+ elif [ -z "$base" ]; then+ # Said out loud. HEAD~1 answers a narrower question than this lane claims to, and a+ # reader has to know which one they got.+ echo "::warning::could not resolve $DEFAULT_BRANCH, so this compares against HEAD~1. That is the previous commit, not the default branch, and an installer change older than one commit is present on both sides."+ base="$(git rev-parse HEAD~1)"+ fi+ fi++ echo "base_sha=$base" >> "$GITHUB_OUTPUT"+ echo "head_sha=$head" >> "$GITHUB_OUTPUT"+ echo "base $base"+ echo "head $head"++ if [ "$base" = "$head" ]; then+ # Not a pass. Comparing a commit with itself shows the lane is deterministic and+ # nothing else, and reporting "no differences" for it would be a lie.+ echo "::error::base and head are the same commit ($base), so there is nothing to compare."+ echo "::error::VOID. Pass base_ref explicitly if you meant to compare against something else."+ echo "proceed=0" >> "$GITHUB_OUTPUT"+ exit 1+ fi++ changed="$(git diff --name-only "$base".."$head" -- install.ps1 studio/setup.ps1 \+ studio/setup.bat scripts/uninstall.ps1 install.sh | tr '\n' ' ')"+ if [ -n "$changed" ]; then+ echo "installer files changed between the two: $changed"+ else+ # Still worth running. It measures the lane itself, and it is the only way to learn+ # that two installs of adjacent commits differ for reasons outside these files.+ echo "::notice::no installer file changed between the two commits; this run measures the lane"+ fi+ echo "proceed=1" >> "$GITHUB_OUTPUT"++ - name: Prove the comparer can still fail+ if: steps.gate.outputs.wanted == '1'+ run: |+ set -euo pipefail+ # Before either install starts. If the comparer's normalisation has drifted wide enough to+ # swallow a real change, the two installs are 90 minutes of runner time spent producing a+ # green check that means nothing, and it is far better to learn that here.+ python .github/scripts/compare_installer_evidence.py --self-test++ measure:+ name: install from ${{ matrix.side }}+ needs: resolve+ if: needs.resolve.outputs.proceed == '1'+ runs-on: windows-latest+ timeout-minutes: 60+ strategy:+ fail-fast: false+ matrix:+ side: [base, head]+ steps:+ - name: Check out the ${{ matrix.side }} commit+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: ${{ matrix.side == 'base' && needs.resolve.outputs.base_sha || needs.resolve.outputs.head_sha }}+ persist-credentials: false++ - name: Confirm this really is the ${{ matrix.side }} commit+ shell: pwsh+ env:+ WANT: ${{ matrix.side == 'base' && needs.resolve.outputs.base_sha || needs.resolve.outputs.head_sha }}+ run: |+ # Without this, a checkout that silently resolved to the default branch would make both+ # sides the same tree, the comparison trivially pass, and the lane report that a change+ # broke nothing while never having seen the change.+ $got = (git rev-parse HEAD).Trim()+ Write-Host "checked out $got, wanted $env:WANT"+ if ($got -ne $env:WANT) {+ Write-Host "::error::checkout resolved to $got instead of $env:WANT. Refusing to measure: both sides would be the same tree and the comparison would pass for the wrong reason."+ exit 1+ }++ # The collector and the comparer come from the HEAD of this branch on both sides on purpose.+ # A base commit that predates them has neither, and even where it has both, measuring the two+ # sides with two different rulers is not a measurement.+ - name: Take the measuring tools from the candidate, not from each side+ shell: pwsh+ env:+ TOOLS_REF: ${{ needs.resolve.outputs.head_sha }}+ run: |+ $tools = Join-Path $env:RUNNER_TEMP 'tools'+ New-Item -ItemType Directory -Force -Path $tools | Out-Null+ git fetch --no-tags --depth=1 origin $env:TOOLS_REF 2>&1 | Out-Null+ foreach ($f in @('.github/scripts/Collect-InstallerEvidence.ps1',+ '.github/scripts/compare_installer_evidence.py')) {+ $leaf = Split-Path $f -Leaf+ $dest = Join-Path $tools $leaf+ git show "$($env:TOOLS_REF):$f" | Set-Content -LiteralPath $dest -Encoding utf8+ # Test-Path is not the check it looks like: a failed `git show` writes nothing down the+ # pipeline, Set-Content still creates the file, and the guard passes on a zero-byte+ # collector that then collects nothing. Both the exit status and the size are checked.+ $code = $LASTEXITCODE+ $size = if (Test-Path -LiteralPath $dest) { (Get-Item -LiteralPath $dest).Length } else { -1 }+ if ($code -ne 0 -or $size -lt 1) {+ Write-Host "::error::could not extract $f from $env:TOOLS_REF (git exit $code, $size bytes); the two sides would be measured differently"+ exit 1+ }+ }+ "UNSLOTH_EVIDENCE_TOOLS=$tools" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8+ Write-Host "measuring tools taken from $env:TOOLS_REF"++ - name: Install, capturing every line it prints+ id: install+ shell: pwsh+ env:+ # Without this, install.ps1 installs `unsloth` from PyPI and the `studio setup` handoff+ # resolves studio/setup.ps1 from the RELEASED wheel, so both legs would exercise the same+ # released setup code and report PASS without ever running the candidate -- even though+ # studio/setup.ps1 and studio/setup.bat are two of this workflow's own triggers.+ # install.ps1:7172-7185 documents the mechanism; the overlay makes _PACKAGE_ROOT resolve+ # to this leg's checkout by PEP 660 __file__.+ UNSLOTH_CI_SOURCE_OVERLAY: ${{ github.workspace }}+ run: |+ $ErrorActionPreference = 'Continue'+ # Deliberately NO UNSLOTH_STUDIO_HOME. Setting it puts install.ps1 into+ # StudioRedirectMode 'env', and New-StudioShortcuts returns before creating any .lnk+ # (install.ps1:3398), because in that mode a shortcut may point at a deleted workspace.+ # Both manifests then came back empty, so the shortcut comparison -- the one that sees a+ # change to -WindowStyle or -ExecutionPolicy, which is what this whole effort is about --+ # compared nothing at all. Isolation does not need the override: base and head are+ # separate matrix legs on separate throwaway runners.+ $out = Join-Path $env:RUNNER_TEMP 'evidence'+ New-Item -ItemType Directory -Force -Path $out | Out-Null+ $transcript = Join-Path $out 'transcript.txt'++ # Tee, not redirect: the log has to stay readable in the run's own output, and a lane+ # nobody can debug from the web UI gets deleted the first time it is inconvenient.+ & powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File ./install.ps1 2>&1 |+ Tee-Object -FilePath $transcript+ $code = $LASTEXITCODE+ if ($null -eq $code) { $code = -1 }+ Write-Host "installer exited $code"+ "install_exit=$code" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8+ # Into the evidence directory, not only into a step output. A step output does not cross+ # into the compare job, so without this the comparer never sees whether the installer+ # finished -- and two installs that failed the same way print matching transcripts, leave+ # matching empty manifests, and read as "no behaviour difference".+ [ordered]@{ side = '${{ matrix.side }}'; installExit = $code } |+ ConvertTo-Json -Depth 4 |+ Set-Content -LiteralPath (Join-Path $out 'run.json') -Encoding utf8+ # Not a failure here. An installer that did not finish is recorded, and the comparer calls+ # the run VOID -- which is the honest outcome, and distinguishable from "it changed".+ exit 0++ - name: Record what it left behind+ if: always()+ shell: pwsh+ run: |+ # The default install root, matching the install above. install.ps1 derives it the same+ # way when no override is set (install.ps1:1566).+ $studioHome = Join-Path $env:USERPROFILE '.unsloth\studio'+ # The launcher lives here on a normal-profile install, not under $StudioHome.+ $studioData = if ($env:LOCALAPPDATA) { Join-Path $env:LOCALAPPDATA 'Unsloth Studio' } else { $studioHome }+ & (Join-Path $env:UNSLOTH_EVIDENCE_TOOLS 'Collect-InstallerEvidence.ps1') `+ -StudioHome $studioHome -StudioDataDir $studioData `+ -OutDir (Join-Path $env:RUNNER_TEMP 'evidence')++ - name: Install a second time, and check it rewrote nothing+ if: always()+ shell: pwsh+ env:+ UNSLOTH_CI_SOURCE_OVERLAY: ${{ github.workspace }}+ run: |+ $ErrorActionPreference = 'Continue'+ $studioHome = Join-Path $env:USERPROFILE '.unsloth\studio'+ $studioData = if ($env:LOCALAPPDATA) { Join-Path $env:LOCALAPPDATA 'Unsloth Studio' } else { $studioHome }+ $out = Join-Path $env:RUNNER_TEMP 'evidence'+ $first = Join-Path $env:RUNNER_TEMP 'first-run-artifacts.json'+ Copy-Item -LiteralPath (Join-Path $out 'artifacts.json') -Destination $first -Force++ # Several of the changes this lane judges touch content-comparison paths -- the code that+ # decides whether a launcher needs rewriting at all -- so "a reinstall writes nothing" is+ # a contract that can break silently.+ & powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File ./install.ps1 2>&1 |+ Tee-Object -FilePath (Join-Path $out 'transcript-second-run.txt') | Out-Null+ $code = $LASTEXITCODE+ if ($null -eq $code) { $code = -1 }+ Write-Host "second install exited $code"++ & (Join-Path $env:UNSLOTH_EVIDENCE_TOOLS 'Collect-InstallerEvidence.ps1') `+ -StudioHome $studioHome -StudioDataDir $studioData -OutDir $out -CompareAgainst $first++ # Merged rather than overwritten, so a second-install step that runs after a failed first+ # one cannot quietly drop the first install's exit status and leave the evidence looking+ # complete.+ $runFile = Join-Path $out 'run.json'+ $run = if (Test-Path -LiteralPath $runFile) {+ Get-Content -Raw -LiteralPath $runFile | ConvertFrom-Json+ } else { $null }+ $first_code = if ($run -and $null -ne $run.installExit) { [int]$run.installExit } else { -1 }+ [ordered]@{+ side = '${{ matrix.side }}'+ installExit = $first_code+ secondInstallExit = $code+ } | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $runFile -Encoding utf8+ Get-Content -Raw -LiteralPath $runFile+ exit 0++ - name: Upload this side's evidence+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: installer-evidence-${{ matrix.side }}+ path: ${{ runner.temp }}/evidence+ if-no-files-found: warn+ retention-days: 30++ compare:+ name: did anything the user sees change+ needs: [resolve, measure]+ # always(), so a side that failed still produces a verdict. The verdict in that case is VOID,+ # which is the point: "we could not measure" has to be visible and must not read as a pass.+ if: always() && needs.resolve.outputs.proceed == '1'+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: ${{ needs.resolve.outputs.head_sha }}+ persist-credentials: false++ - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1+ continue-on-error: true+ id: dl_base+ with:+ name: installer-evidence-base+ path: evidence/base++ - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1+ continue-on-error: true+ id: dl_head+ with:+ name: installer-evidence-head+ path: evidence/head++ - name: Prove the comparer can still fail, then compare+ run: |+ set -euo pipefail+ # Again, immediately before the verdict. The run above was 10 minutes and two installs+ # ago, and this is the assertion the whole lane rests on.+ python .github/scripts/compare_installer_evidence.py --self-test+ echo+ set +e+ python .github/scripts/compare_installer_evidence.py \+ --base evidence/base --head evidence/head \+ --base-sha '${{ needs.resolve.outputs.base_sha }}' \+ --head-sha '${{ needs.resolve.outputs.head_sha }}'+ code=$?+ set -e+ case "$code" in+ 0) echo "VERDICT: no behaviour difference." ;;+ 2) echo "::error::VERDICT: the installer's behaviour changed. See the differences above."+ echo "::error::If the change is intended, say so in the PR and update whichever test pins the old behaviour. Do not widen the comparer's normalisation to make this green." ;;+ 3) echo "::error::VERDICT: VOID. Nothing was compared, so nothing was shown to be unchanged." ;;+ *) echo "::error::VERDICT: the comparer itself failed (exit $code); no verdict." ;;+ esac+ exit "$code"diff --git a/tests/python/test_installer_differential_comparer.py b/tests/python/test_installer_differential_comparer.pynew file mode 100644index 00000000000..76934159d1f--- /dev/null+++ b/tests/python/test_installer_differential_comparer.py@@ -0,0 +1,1695 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The base-vs-head installer comparer has to be able to fail.++This is the lane that answers "did hardening break anything", and its whole value rests on one+property: that a real change produces a non-zero exit. A comparer whose normalisation has drifted+wide reports "no differences" forever and every hardening PR after it ships unverified, with a green+check saying the opposite.++So the failure direction is tested first here, and harder than the pass direction. The pass+direction matters too, but only because a lane that fails on every run gets disabled, which costs+the same coverage by a slower route.+"""++from __future__ import annotations++import copy+import json+import re+import subprocess+import sys+from pathlib import Path++import pytest+++REPO = Path(__file__).resolve().parents[2]+SCRIPT = REPO / ".github" / "scripts" / "compare_installer_evidence.py"++sys.path.insert(0, str(SCRIPT.parent))+import compare_installer_evidence as cmp # noqa: E402+++BASELINE = "\n".join(+ [+ " python 3.13.14 ready",+ " uv 0.12.1 installed",+ " studio installed in 12.4s",+ " shortcut desktop and Start Menu",+ " next run: unsloth studio",+ ]+)++SHORTCUTS = [+ {+ "name": "Unsloth.lnk",+ "targetPath": r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",+ "arguments": "-NoProfile -WindowStyle Hidden -ExecutionPolicy RemoteSigned -File launch-studio.ps1",+ "workingDirectory": r"C:\Users\runneradmin\.unsloth\studio",+ "windowStyle": "1",+ "iconLocation": r"C:\Users\runneradmin\.unsloth\studio\unsloth.ico,0",+ }+]++# `bom` is part of this because the collector always writes it for a contract it could read+# (Collect-InstallerEvidence.ps1:242-250), and the comparer now requires it: a fixture that is+# thinner than the real evidence is how a test passes without exercising the check it names.+ARTIFACTS = {+ "files": {+ "launch-studio.ps1": {+ "content": "Start-Process -WindowStyle Hidden pwsh\n",+ "bom": "utf-8",+ },+ "unsloth.cmd": {"content": "@echo off\n", "bom": "none"},+ },+ "rewrittenOnSecondRun": [],+}++# The installer's own exit status, which the workflow records because nothing else sees it.+RUN = {"side": "base", "installExit": 0, "secondInstallExit": 0}+++def _write(+ directory: Path,+ transcript: str = BASELINE,+ shortcuts = None,+ artifacts = None,+ run = None,+ second: str | None = None,+) -> Path:+ directory.mkdir(parents = True, exist_ok = True)+ (directory / "transcript.txt").write_text(transcript, encoding = "utf-8")+ # Defaults to the first-run text. The reinstall prints something different on a real runner, but+ # what these fixtures need is a second-run transcript that exists and that matches its opposite+ # side unless a test deliberately changes it.+ (directory / "transcript-second-run.txt").write_text(+ transcript if second is None else second, encoding = "utf-8"+ )+ (directory / "shortcuts.json").write_text(+ json.dumps(SHORTCUTS if shortcuts is None else shortcuts), encoding = "utf-8"+ )+ (directory / "artifacts.json").write_text(+ json.dumps(ARTIFACTS if artifacts is None else artifacts), encoding = "utf-8"+ )+ (directory / "run.json").write_text(json.dumps(RUN if run is None else run), encoding = "utf-8")+ return directory+++def _run(base: Path, head: Path) -> subprocess.CompletedProcess:+ return subprocess.run(+ [+ sys.executable,+ str(SCRIPT),+ "--base",+ str(base),+ "--head",+ str(head),+ "--base-sha",+ "a" * 40,+ "--head-sha",+ "b" * 40,+ ],+ capture_output = True,+ text = True,+ timeout = 120,+ )+++# ---------------------------------------------------------------------------+# It must be able to fail+# ---------------------------------------------------------------------------+++ "mutation, why",+ [+ ("shortcut desktop only", "a line of user-visible output changed"),+ (" shortcut desktop and Start Menu ", "trailing space only, which must NOT fail"),+ ],+)+def test_a_changed_output_line_is_reported(tmp_path: Path, mutation: str, why: str) -> None:+ base = _write(tmp_path / "base")+ mutated = BASELINE.replace(" shortcut desktop and Start Menu", mutation)+ head = _write(tmp_path / "head", transcript = mutated)+ result = _run(base, head)+ if "must NOT fail" in why:+ assert (+ result.returncode == 0+ ), f"trailing whitespace was treated as a change: {result.stdout}"+ else:+ assert result.returncode == 2, f"{why} was not reported: {result.stdout}\n{result.stderr}"+++def test_a_lost_indent_is_reported(tmp_path: Path) -> None:+ """`step` pads its label to exactly 15 columns and the output lock pins the indent."""+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head", transcript = BASELINE.replace(" python", " python"))+ assert _run(base, head).returncode == 2+++def test_a_relaxed_execution_policy_in_a_shortcut_is_reported(tmp_path: Path) -> None:+ """The single substitution this whole effort is about, and invisible in the transcript."""+ base = _write(tmp_path / "base")+ relaxed = [+ dict(SHORTCUTS[0], arguments = SHORTCUTS[0]["arguments"].replace("RemoteSigned", "Bypass"))+ ]+ head = _write(tmp_path / "head", shortcuts = relaxed)+ result = _run(base, head)+ assert result.returncode == 2+ assert "arguments" in result.stdout and "Bypass" in result.stdout+++def test_a_shortcut_that_stopped_being_created_is_reported(tmp_path: Path) -> None:+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head", shortcuts = [])+ assert _run(base, head).returncode in (2, 3)+++def test_a_changed_generated_launcher_is_reported(tmp_path: Path) -> None:+ base = _write(tmp_path / "base")+ changed = json.loads(json.dumps(ARTIFACTS))+ changed["files"]["launch-studio.ps1"]["content"] = "Start-Process pwsh\n"+ head = _write(tmp_path / "head", artifacts = changed)+ assert _run(base, head).returncode == 2+++def test_a_second_run_that_rewrites_files_is_reported(tmp_path: Path) -> None:+ """Several changes here touch content-comparison paths, so idempotency is a real risk."""+ base = _write(tmp_path / "base")+ noisy = json.loads(json.dumps(ARTIFACTS))+ noisy["rewrittenOnSecondRun"] = ["launch-studio.ps1"]+ head = _write(tmp_path / "head", artifacts = noisy)+ result = _run(base, head)+ assert result.returncode == 2+ assert "second time" in result.stdout+++# ---------------------------------------------------------------------------+# It must not fail on noise, or it gets disabled+# ---------------------------------------------------------------------------+++def test_known_noise_does_not_fail(tmp_path: Path) -> None:+ noisy = "\n".join(+ [+ " python 3.13.9 ready",+ " uv 0.12.4 installed",+ " studio installed in 41.9s",+ " shortcut desktop and Start Menu",+ " next run: unsloth studio",+ ]+ )+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head", transcript = noisy)+ result = _run(base, head)+ assert result.returncode == 0, f"noise failed the lane: {result.stdout}"+++def test_version_drift_is_normalised_but_still_printed(tmp_path: Path) -> None:+ """Normalising something away without saying so is how a lane stops telling you anything."""+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head", transcript = BASELINE.replace("0.12.1", "0.12.4"))+ result = _run(base, head)+ assert result.returncode == 0+ assert (+ "version drift in the first-run transcript" in result.stdout and "0.12.4" in result.stdout+ )+++# ---------------------------------------------------------------------------+# VOID is not a pass+# ---------------------------------------------------------------------------+++def test_missing_evidence_is_void_and_not_a_pass(tmp_path: Path) -> None:+ base = _write(tmp_path / "base")+ result = _run(base, tmp_path / "absent")+ assert result.returncode == 3, "a side with no evidence must not read as agreement"+ assert "VOID" in result.stdout+++def test_an_empty_transcript_is_void(tmp_path: Path) -> None:+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head", transcript = "\n\n \n")+ result = _run(base, head)+ assert result.returncode == 3+ assert "did not run" in result.stdout+++def test_comparing_a_commit_with_itself_is_void() -> None:+ verdict = cmp.compare_directories(Path("/x"), Path("/y"), "c" * 40, "c" * 40)+ assert verdict.is_void+ assert verdict.exit_code() == 3+ assert any("itself" in reason for reason in verdict.void)+++def test_two_empty_shortcut_manifests_are_void_not_agreement() -> None:+ verdict = cmp.Verdict()+ cmp.compare_shortcuts([], [], verdict)+ assert verdict.is_void+++def test_void_and_different_have_distinct_exit_codes() -> None:+ """A workflow that treats every non-zero the same cannot tell "it changed" from "we did not+ look", and those need different reactions from whoever reads the run."""+ void = cmp.Verdict()+ void.void.append("x")+ different = cmp.Verdict()+ different.differences.append("y")+ assert void.exit_code() == 3+ assert different.exit_code() == 2+ assert cmp.Verdict().exit_code() == 0+++# ---------------------------------------------------------------------------+# The comparer's own controls+# ---------------------------------------------------------------------------+++def test_the_self_test_passes() -> None:+ """CI runs this before any real comparison, so a broken normaliser refuses to produce a+ verdict instead of producing a reassuring one."""+ result = subprocess.run(+ [sys.executable, str(SCRIPT), "--self-test"], capture_output = True, text = True, timeout = 120+ )+ assert result.returncode == 0, result.stdout + result.stderr+++def test_the_self_test_can_fail() -> None:+ """A control that cannot fail is decoration. Widen the normaliser until it swallows a real+ change and the self-test must notice."""+ original = cmp._NORMALISERS+ try:+ import re++ cmp._NORMALISERS = original + ((re.compile(r".*"), "", "everything", True),)+ failures = cmp.self_test()+ assert failures, "a normaliser that erases every line still passed the controls"+ assert any("too loose" in f for f in failures)+ finally:+ cmp._NORMALISERS = original+++def test_every_normaliser_records_why_it_exists() -> None:+ """A rule with no recorded cause is a rule nobody can argue with, and this list is exactly+ where a future 'just make the lane green' change would land."""+ for pattern, _replacement, why, in_scripts in cmp._NORMALISERS:+ assert why and len(why) > 8, f"the normaliser {pattern.pattern!r} has no stated reason"+ assert isinstance(in_scripts, bool), (+ f"the normaliser {pattern.pattern!r} does not say whether it applies to a generated "+ f"script, and defaulting that wrong is how a behaviour change gets normalised away"+ )+++def test_the_shortcut_fields_compared_include_the_launch_contract() -> None:+ for field in ("arguments", "targetPath", "windowStyle"):+ assert field in cmp._SHORTCUT_FIELDS+++def test_a_single_shortcut_serialised_as_an_object_still_compares(tmp_path: Path) -> None:+ """ConvertTo-Json unwraps a one-element collection into a bare object.++ Observed while smoke-running the collector: with one shortcut found, shortcuts.json was an+ object rather than an array. Iterating that yields dictionary *keys*, so two different launch+ contracts would have compared as agreement for entirely the wrong reason.+ """+ base = _write(tmp_path / "base")+ (base / "shortcuts.json").write_text(json.dumps(SHORTCUTS[0]), encoding = "utf-8")+ head = _write(tmp_path / "head")+ relaxed = dict(+ SHORTCUTS[0], arguments = SHORTCUTS[0]["arguments"].replace("RemoteSigned", "Bypass")+ )+ (head / "shortcuts.json").write_text(json.dumps(relaxed), encoding = "utf-8")++ result = _run(base, head)+ assert (+ result.returncode == 2+ ), f"an unwrapped single shortcut was not compared as a shortcut: {result.stdout}"+ assert "Bypass" in result.stdout+++def test_a_symmetric_collection_failure_is_void_not_a_pass(tmp_path: Path) -> None:+ """The hole this closes was live: two sides that both failed to read any shortcut reported+ "1 compared, every field equal" and exited zero.++ Collection failures are symmetric far more often than behaviour changes are, because they come+ from the host and both sides share it.+ """+ failed = [{"name": "<collection failed>", "error": "could not create WScript.Shell"}]+ base = _write(tmp_path / "base", shortcuts = failed)+ head = _write(tmp_path / "head", shortcuts = failed)+ result = _run(base, head)+ assert result.returncode == 3, f"a shared collection failure read as agreement: {result.stdout}"+ assert "prove nothing" in result.stdout+++# ---------------------------------------------------------------------------+# The installer's exit status+# ---------------------------------------------------------------------------+#+# The transcript does not carry it, and it is the only thing that separates a pass from the most+# likely shared failure this lane will ever see. A mirror outage, a runner image change, a Defender+# definition push: each fails both installs at the same point, printing the same lines, leaving the+# same empty manifests. Everything the comparer looks at then matches.+++def test_two_installers_that_both_failed_are_void_not_a_pass(tmp_path: Path) -> None:+ dead = {"installExit": 1, "secondInstallExit": 1}+ base = _write(tmp_path / "base", transcript = BASELINE, run = dead)+ head = _write(tmp_path / "head", transcript = BASELINE, run = dead)+ result = _run(base, head)+ assert result.returncode == 3, f"two failed installs read as agreement: {result.stdout}"+ assert "exited 1" in result.stdout+++def test_one_installer_that_failed_is_void(tmp_path: Path) -> None:+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head", run = {"installExit": 5, "secondInstallExit": 0})+ assert _run(base, head).returncode == 3+++def test_a_failed_second_install_is_void(tmp_path: Path) -> None:+ """The idempotency install is a measurement too, and one that did not run measured nothing."""+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head", run = {"installExit": 0, "secondInstallExit": 3})+ assert _run(base, head).returncode == 3+++def test_evidence_with_no_recorded_exit_status_is_void(tmp_path: Path) -> None:+ """Both sides are measured with the candidate's tools, so evidence without a run status came+ from a workflow that was never in a position to say the installer finished."""+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head")+ (head / "run.json").unlink()+ result = _run(base, head)+ assert result.returncode == 3+ assert "VOID" in result.stdout++[email protected]("bad", [{"installExit": "0"}, {"installExit": True}, {}, []])+def test_an_unusable_exit_status_is_void(tmp_path: Path, bad) -> None:+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head")+ (head / "run.json").write_text(json.dumps(bad), encoding = "utf-8")+ assert _run(base, head).returncode == 3+++# ---------------------------------------------------------------------------+# An error in the artifact manifest is not data+# ---------------------------------------------------------------------------+#+# The shortcut side of this was already closed. The artifact side was not, and it fails more+# quietly: the entry keeps its key and loses only its `content`, so the content check skips it and+# the file that goes uncompared is the one whose text is the contract.+++def test_an_unreadable_artifact_is_void_not_a_skipped_comparison(tmp_path: Path) -> None:+ broken = json.loads(json.dumps(ARTIFACTS))+ broken["files"]["launch-studio.ps1"] = {"error": "access is denied"}+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head", artifacts = broken)+ result = _run(base, head)+ assert result.returncode == 3, f"an unreadable contract file read as agreement: {result.stdout}"+ assert "never read" in result.stdout+++def test_a_symmetric_artifact_read_failure_is_void(tmp_path: Path) -> None:+ broken = json.loads(json.dumps(ARTIFACTS))+ broken["files"]["unsloth.cmd"] = {"error": "access is denied"}+ base = _write(tmp_path / "base", artifacts = broken)+ head = _write(tmp_path / "head", artifacts = broken)+ assert _run(base, head).returncode == 3+++def test_an_install_root_that_does_not_exist_is_void(tmp_path: Path) -> None:+ """What the collector writes when the installer did not finish. It is an error field, and an+ error field on both sides compares equal to itself."""+ failed = {"studioHome": r"C:\x", "files": {}, "error": "the install root C:\\x does not exist"}+ base = _write(tmp_path / "base", artifacts = failed)+ head = _write(tmp_path / "head", artifacts = failed)+ result = _run(base, head)+ assert result.returncode == 3+ assert "not evidence" in result.stdout+++def test_content_captured_on_one_side_only_is_void(tmp_path: Path) -> None:+ half = json.loads(json.dumps(ARTIFACTS))+ half["files"]["launch-studio.ps1"] = {"sha256": "a" * 64}+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head", artifacts = half)+ assert _run(base, head).returncode == 3+++# ---------------------------------------------------------------------------+# Evidence of the wrong shape was not measured+# ---------------------------------------------------------------------------++[email protected]("blob", ['"nothing here"', "42", '["Unsloth.lnk"]'])+def test_a_shortcut_manifest_of_the_wrong_shape_is_void(tmp_path: Path, blob: str) -> None:+ """Coercing it to an empty list made it compare against a populated side as "every shortcut+ disappeared", which is a behaviour difference reported about evidence nobody parsed."""+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head")+ (head / "shortcuts.json").write_text(blob, encoding = "utf-8")+ assert _run(base, head).returncode == 3++[email protected]("blob", ["[]", '"x"'])+def test_an_artifact_manifest_of_the_wrong_shape_is_void(tmp_path: Path, blob: str) -> None:+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head")+ (head / "artifacts.json").write_text(blob, encoding = "utf-8")+ assert _run(base, head).returncode == 3++[email protected]("name", ["shortcuts.json", "artifacts.json", "run.json"])+def test_a_byte_order_mark_does_not_turn_good_evidence_into_void(tmp_path: Path, name: str) -> None:+ """Windows PowerShell 5.1 writes a BOM for `Set-Content -Encoding utf8`, and json.loads+ rejects one. A lane that goes VOID on a valid file stops being read."""+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head")+ text = (head / name).read_text(encoding = "utf-8")+ (head / name).write_bytes(b"\xef\xbb\xbf" + text.encode("utf-8"))+ assert _run(base, head).returncode == 0+++def test_a_byte_order_mark_does_not_hide_a_real_change(tmp_path: Path) -> None:+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head")+ relaxed = [+ dict(SHORTCUTS[0], arguments = SHORTCUTS[0]["arguments"].replace("RemoteSigned", "Bypass"))+ ]+ (head / "shortcuts.json").write_bytes(b"\xef\xbb\xbf" + json.dumps(relaxed).encode("utf-8"))+ result = _run(base, head)+ assert result.returncode == 2+ assert "Bypass" in result.stdout+++# ---------------------------------------------------------------------------+# The normalisers, and how far each one reaches+# ---------------------------------------------------------------------------+++ "before, after",+ [+ (+ r" work C:\Temp\unsloth-uv-1a2b3c4d\bin",+ r" work C:\Temp\unsloth-uv-99ffee00\bin",+ ),+ (+ " probe unsloth-probe-1a2b3c4d.tmp",+ " probe unsloth-probe-ffee9900.tmp",+ ),+ (+ " probe .unsloth-write-probe.1a2b3c4d5e6f7a8b",+ " probe .unsloth-write-probe.ffee99001a2b3c4d",+ ),+ ],+)+def test_a_random_scratch_name_is_still_normalised(before: str, after: str) -> None:+ verdict = cmp.Verdict()+ cmp.compare_transcripts(BASELINE + "\n" + before, BASELINE + "\n" + after, verdict)+ assert not verdict.differences, verdict.differences+++ "before, after",+ [+ ("unsloth-studio-managed-launcher", "unsloth-desktop-managed-launcher"),+ ("pip install unsloth-studio", "pip install unsloth-nightly"),+ (".unsloth-studio-owned", ".unsloth-desktop-owned"),+ ],+)+def test_a_renamed_unsloth_marker_is_not_a_scratch_name(before: str, after: str) -> None:+ """`unsloth-studio-managed-launcher` is written into unsloth.cmd and is how the installer+ recognises its own shim, so a rename is a behaviour change. The rule meant for+ `unsloth-uv-<hex8>` matched any six characters after `unsloth-` and swallowed it."""+ verdict = cmp.Verdict()+ cmp.compare_transcripts(+ BASELINE + "\n cmd " + before, BASELINE + "\n cmd " + after, verdict+ )+ assert verdict.differences, f"{before!r} -> {after!r} was normalised away"+++def test_a_renamed_launcher_marker_inside_unsloth_cmd_is_reported(tmp_path: Path) -> None:+ marked = json.loads(json.dumps(ARTIFACTS))+ marked["files"]["unsloth.cmd"]["content"] = "@echo off\nrem unsloth-studio-managed-launcher\n"+ renamed = json.loads(json.dumps(marked))+ renamed["files"]["unsloth.cmd"]["content"] = "@echo off\nrem unsloth-desktop-managed-launcher\n"+ base = _write(tmp_path / "base", artifacts = marked)+ head = _write(tmp_path / "head", artifacts = renamed)+ assert _run(base, head).returncode == 2+++def test_a_version_drift_inside_a_shortcut_is_printed_even_though_it_is_normalised(+ tmp_path: Path,+) -> None:+ """normalise_line runs on shortcut fields too, so a launcher retargeted at a different python+ is erased in exactly the same way a patch release is. That is the right call and the wrong one+ to make silently, so wherever the rule reaches, the drift is said out loud."""+ base = _write(tmp_path / "base")+ retargeted = [+ dict(+ SHORTCUTS[0],+ targetPath = r"C:\Users\runneradmin\.unsloth\python-3.13.14\python.exe",+ )+ ]+ bumped = [+ dict(+ SHORTCUTS[0],+ targetPath = r"C:\Users\runneradmin\.unsloth\python-3.11.9\python.exe",+ )+ ]+ base = _write(tmp_path / "base", shortcuts = retargeted)+ head = _write(tmp_path / "head", shortcuts = bumped)+ result = _run(base, head)+ assert result.returncode == 0+ assert "version drift in the shortcut fields" in result.stdout, result.stdout+ assert "3.11.9" in result.stdout+++def test_the_shortcut_note_is_not_suppressed_by_a_transcript_difference(tmp_path: Path) -> None:+ """Reading the whole verdict meant a changed output line also stopped the run saying whether+ the launch contract had been looked at at all."""+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head", transcript = BASELINE.replace("ready", "prepared"))+ result = _run(base, head)+ assert result.returncode == 2+ assert "every field equal" in result.stdout+++# ---------------------------------------------------------------------------+# The collector, run for real+# ---------------------------------------------------------------------------+++def test_the_collector_parses_and_emits_json_the_comparer_accepts(tmp_path: Path) -> None:+ """`ConvertTo-Json` unwraps a one-element collection and 5.1 has no `-AsArray`, so the collector+ forces the array itself. Run rather than reasoned about: the shape of that file is the one thing+ that decides whether a single shortcut is compared as a shortcut or as a bag of dictionary keys.+ """+ sys.path.insert(0, str(REPO / "tests" / "_shared"))+ from unsloth_pwsh_runner import PWSH, run_pwsh # noqa: PLC0415++ if PWSH is None:+ pytest.skip("no PowerShell on this host")++ collector = REPO / ".github" / "scripts" / "Collect-InstallerEvidence.ps1"+ out = tmp_path / "evidence"+ script = f"""+$ErrorActionPreference = 'Stop'+$errors = $null+[System.Management.Automation.Language.Parser]::ParseFile(+ '{collector.as_posix()}', [ref]$null, [ref]$errors) | Out-Null+if ($errors) {{ $errors | ForEach-Object {{ "PARSE: $_" }}; exit 1 }}++& '{collector.as_posix()}' -StudioHome '{(tmp_path / "home").as_posix()}' -OutDir '{out.as_posix()}' |+ Out-Null++# The forcing, exercised directly with exactly one entry, which is the case that produced an+# object on a real run.+$one = New-Object System.Collections.ArrayList+[void]$one.Add([ordered]@{{ name = 'Unsloth.lnk'; arguments = '-ExecutionPolicy RemoteSigned' }})+$json = $one | ConvertTo-Json -Depth 6+if ($one.Count -le 1) {{ $json = "[$($json)]" }}+Set-Content -LiteralPath '{(tmp_path / "one.json").as_posix()}' -Value $json -Encoding utf8+Write-Output 'COLLECTOR-OK'+"""+ result = run_pwsh(+ [PWSH, "-NoProfile", "-NonInteractive", "-Command", script],+ capture_output = True,+ text = True,+ verdict = "COLLECTOR-OK",+ timeout = 300,+ )+ assert "COLLECTOR-OK" in result.stdout, result.stdout + result.stderr++ one = json.loads((tmp_path / "one.json").read_text(encoding = "utf-8-sig"))+ assert (+ isinstance(one, list) and len(one) == 1+ ), f"a single shortcut did not serialise as a list: {one!r}"+ assert one[0]["arguments"] == "-ExecutionPolicy RemoteSigned"++ shortcuts = json.loads((out / "shortcuts.json").read_text(encoding = "utf-8-sig"))+ assert isinstance(shortcuts, list), f"shortcuts.json is not a list: {shortcuts!r}"++ # Off Windows there is no WScript.Shell, so the collector records an error rather than data.+ # That is the shape the comparer must call VOID, and the one that used to compare equal to+ # itself and exit zero.+ artifacts = json.loads((out / "artifacts.json").read_text(encoding = "utf-8-sig"))+ verdict = cmp.Verdict()+ cmp.compare_shortcuts(shortcuts, shortcuts, verdict)+ cmp.compare_artifacts(artifacts, artifacts, verdict)+ assert verdict.is_void, "the collector's own failure output did not read as VOID"+ assert verdict.exit_code() == 3+++# ---------------------------------------------------------------------------+# The lane must actually be in a mode where there is something to measure+# ---------------------------------------------------------------------------+++def _differential_workflow() -> dict:+ import yaml+ path = REPO / ".github" / "workflows" / "windows-installer-differential-ci.yml"+ return yaml.safe_load(path.read_text(encoding = "utf-8"))+++def test_the_lane_never_installs_in_env_override_mode() -> None:+ """Setting UNSLOTH_STUDIO_HOME silently removes the shortcut comparison entirely.++ `install.ps1` selects `StudioRedirectMode = 'env'` from that variable, and+ `New-StudioShortcuts` then returns before writing any `.lnk`, because in that mode a shortcut+ can point at a deleted workspace. Both manifests come back empty, so the comparison that would+ see a changed `-WindowStyle` or `-ExecutionPolicy` -- the pair this entire effort is about --+ compares nothing. It does not even fail loudly: empty against empty is equal.++ Isolation was the reason it was there, and it is not needed: base and head are separate matrix+ legs on separate throwaway runners.+ """+ workflow = _differential_workflow()+ offenders = []+ for job_name, job in workflow["jobs"].items():+ for step in job.get("steps") or []:+ env = step.get("env") or {}+ if "UNSLOTH_STUDIO_HOME" in env:+ offenders.append(f"{job_name}/{step.get('name', '<unnamed>')}")+ assert not offenders, (+ f"these steps set UNSLOTH_STUDIO_HOME: {offenders}. That puts the installer into "+ f"env-override mode, where it creates no shortcuts at all, so the lane measures no "+ f"shortcuts on either side and reports them equal."+ )+++def test_a_desktop_and_a_start_menu_shortcut_stay_separate() -> None:+ """Same file name, two locations. Keyed on the name alone they collapse into one entry.++ A normal install writes `Unsloth Studio.lnk` to both the Desktop and the Start Menu. If one+ stopped being created and the survivor kept its fields, both sides still held one identical key+ and the comparer reported equality, which is precisely the regression it exists to catch.+ """+ both = [+ {"name": "Unsloth Studio.lnk", "root": "Desktop", "targetPath": "p", "arguments": "a"},+ {"name": "Unsloth Studio.lnk", "root": "Programs", "targetPath": "p", "arguments": "a"},+ ]+ desktop_only = [both[0]]++ keys = {cmp._shortcut_key(e) for e in both}+ assert len(keys) == 2, f"the two locations collapsed to one key: {keys}"++ verdict = cmp.Verdict()+ cmp.compare_shortcuts(both, desktop_only, verdict)+ assert verdict.differences, "losing the Start Menu shortcut was reported as no change"+ assert any("Programs" in d for d in verdict.differences), verdict.differences+++def test_unmeasured_idempotency_is_void_not_a_note() -> None:+ """`None` and `[]` are different answers and the collector keeps them apart deliberately.++ `[]` means measured and nothing was rewritten; `None` means not measured. Treating the second+ as optional evidence let the lane report equality while one of its four advertised contracts+ had never been checked, which is what happens when the first collector, or the non-terminating+ Copy-Item ahead of the second install, fails while everything after it succeeds.+ """+ # Deliberately well-formed and identical apart from the missing idempotency evidence, so the+ # only thing that can void this is the thing under test. An empty `files` map voids for its own+ # reason and would let this pass without the fix.+ complete = {+ "studioHome": "X",+ "files": {+ "launch-studio.ps1": {+ "foundAt": "data/launch-studio.ps1",+ "content": "a",+ "sha256": "A",+ "bom": "utf-8",+ },+ "unsloth.cmd": {+ "foundAt": "home/bin\\unsloth.cmd",+ "content": "b",+ "sha256": "B",+ "bom": "none",+ },+ },+ }+ measured = dict(complete, rewrittenOnSecondRun = [])++ ok = cmp.Verdict()+ cmp.compare_artifacts(measured, dict(measured), ok)+ assert not ok.is_void, f"the control case voided for an unrelated reason: {ok.void}"++ verdict = cmp.Verdict()+ cmp.compare_artifacts(complete, dict(complete), verdict)+ assert verdict.is_void, "a run that never measured idempotency was still eligible to pass"+ assert verdict.exit_code() == 3, verdict.void+ assert any("idempotency" in row for row in verdict.void), verdict.void+++def test_the_lane_overlays_the_checkout_so_setup_ps1_is_the_candidates() -> None:+ """Without the overlay both legs run the RELEASED studio/setup.ps1 and agree about nothing.++ `install.ps1` installs `unsloth` from PyPI, and the `studio setup` handoff resolves its scripts+ from that wheel, so a change to studio/setup.ps1 or studio/setup.bat -- both of which are+ triggers for this very workflow -- would never execute. install.ps1:7172-7185 documents the+ mechanism and the overlay is the supported CI answer to it.+ """+ workflow = _differential_workflow()+ installs = [+ step+ for job in workflow["jobs"].values()+ for step in (job.get("steps") or [])+ # Steps that EXECUTE it, not ones that merely name the file (the commit-picking step+ # mentions it in a path list).+ if "-File ./install.ps1" in str(step.get("run", ""))+ ]+ assert installs, "no step invokes install.ps1 any more"+ for step in installs:+ env = step.get("env") or {}+ assert "UNSLOTH_CI_SOURCE_OVERLAY" in env, (+ f"step {step.get('name')!r} runs install.ps1 without UNSLOTH_CI_SOURCE_OVERLAY, so the "+ f"Python side including studio/setup.ps1 comes from the released wheel rather than "+ f"from this leg's checkout"+ )+++def test_the_collector_is_given_the_data_directory_too() -> None:+ """On a normal-profile install the launcher is written outside $StudioHome.++ `$appDir = $StudioDataDir` (install.ps1:2971) and in that mode `$StudioDataDir` is+ `%LOCALAPPDATA%\\Unsloth Studio`, so a collector pointed only at `$StudioHome` never sees+ launch-studio.ps1 and a candidate that changes only its generated contents passes.+ """+ workflow = _differential_workflow()+ calls = [+ step+ for job in workflow["jobs"].values()+ for step in (job.get("steps") or [])+ # Invocations, not the step that copies the tools into place.+ if "& (Join-Path $env:UNSLOTH_EVIDENCE_TOOLS 'Collect-InstallerEvidence.ps1')"+ in str(step.get("run", ""))+ ]+ assert calls, "nothing invokes the collector any more"+ for step in calls:+ assert "-StudioDataDir" in str(step["run"]), (+ f"step {step.get('name')!r} calls the collector without -StudioDataDir, so "+ f"launch-studio.ps1 is absent from its manifest on a normal-profile install"+ )+++def test_a_contract_that_moved_without_changing_its_bytes_is_a_difference() -> None:+ """The collector records where it found each contract, and the comparer never read it.++ Each contract is probed at several supported locations, so a candidate that writes+ `studio.conf` to `share\\studio.conf` instead of the install root keeps both the manifest key+ and every byte of the content. Comparing content alone calls that agreement, while everything+ that opens the file now has to look somewhere else. That is exactly the layout change `foundAt`+ was added to make observable.+ """++ def side(found_at: str) -> dict:+ return {+ "studioHome": "X",+ "files": {"studio.conf": {"foundAt": found_at, "content": "a", "sha256": "A"}},+ "rewrittenOnSecondRun": [],+ }++ same = cmp.Verdict()+ cmp.compare_artifacts(side("home/studio.conf"), side("home/studio.conf"), same)+ assert not same.differences, f"an unmoved contract was reported as moved: {same.differences}"++ verdict = cmp.Verdict()+ cmp.compare_artifacts(side("home/studio.conf"), side("home/share\\studio.conf"), verdict)+ assert verdict.differences, "a relocated contract with identical bytes was reported as equal"+ assert any("moved" in row for row in verdict.differences), verdict.differences+++def test_the_collector_builds_shortcut_timestamps_before_it_compares_them() -> None:+ """The shortcut half of the idempotency check read a map that did not exist yet.++ `$shortcutWrites` was constructed after the `CompareAgainst` block that reads it, so under+ `Set-StrictMode -Version Latest` the loop either saw no keys or threw into the catch that voids+ the measurement. Either way an installer regression that calls Save() unconditionally and+ rewrites identical .lnk files left `rewrittenOnSecondRun` empty and could pass.+ """+ script = (+ Path(__file__).resolve().parents[2]+ / ".github"+ / "scripts"+ / "Collect-InstallerEvidence.ps1"+ )+ text = script.read_text(encoding = "utf-8")+ built = text.index("$shortcutWrites = [ordered]@{}")+ read = text.index("foreach ($key in $shortcutWrites.Keys)")+ assert built < read, (+ "$shortcutWrites is still built after the comparison that reads it, so the shortcut half of "+ "the idempotency measurement cannot run"+ )+++def test_a_shortcut_description_change_is_a_difference() -> None:+ """The tooltip is collected, is user-visible, and was excluded from the comparison.++ `install.ps1` sets the shortcut Description and reads it back when deciding whether an existing+ shortcut is already correct, so a candidate that changes only that value leaves both installs+ succeeding, the transcript identical and idempotency clean. With `description` outside the+ compared field set the two manifests matched and the lane returned PASS.+ """++ def side(description: str) -> list[dict]:+ return [+ {+ "root": "desktop",+ "name": "Unsloth Studio.lnk",+ "targetPath": "C:\\ps.exe",+ "arguments": "-File x",+ "workingDirectory": "C:\\",+ "windowStyle": 7,+ "iconLocation": "C:\\i.ico,0",+ "description": description,+ }+ ]++ same = cmp.Verdict()+ cmp.compare_shortcuts(side("Launch Unsloth Studio"), side("Launch Unsloth Studio"), same)+ assert not same.differences, same.differences++ verdict = cmp.Verdict()+ cmp.compare_shortcuts(side("Launch Unsloth Studio"), side("Start Unsloth"), verdict)+ assert verdict.differences, "a changed shortcut description was reported as no change"+ assert any("description" in row for row in verdict.differences), verdict.differences+++def test_the_collector_treats_a_second_run_shortcut_creation_as_a_write() -> None:+ """A reinstall that creates a shortcut is a second-run write, and it measured as nothing.++ The loop read the first run's timestamp for each key it found now. A key with no prior entry+ got a null timestamp and fell through both branches, so a candidate that failed to create the+ shortcut on the first install and created it on the second produced an empty+ `rewrittenOnSecondRun` and a final manifest indistinguishable from a normal run.+ """+ script = (+ Path(__file__).resolve().parents[2]+ / ".github"+ / "scripts"+ / "Collect-InstallerEvidence.ps1"+ )+ text = script.read_text(encoding = "utf-8")+ assert "created by the second run" in text, (+ "a shortcut present now and absent from the first-run manifest is still ignored, so a "+ "reinstall that created one measures as writing nothing"+ )+ assert "first-run shortcut evidence is missing" in text, (+ "a first-run manifest with no shortcut write times still yields a clean measurement "+ "rather than voiding the half it could not measure"+ )+++def test_a_contract_missing_on_both_sides_is_void_not_agreement() -> None:+ """Absence on both sides is the one kind of agreement that proves nothing.++ The collector used to skip a contract it could not find at any supported location, so a shim+ writer that fails the same way on two identical runners, or an endpoint policy that deletes the+ same generated file, removed it from BOTH manifests. The other entries kept the maps non-empty,+ the key sets matched, and the run reported agreement about a file it never looked at.+ """+ missing = {+ "studioHome": "X",+ "files": {+ "launch-studio.ps1": {+ "foundAt": "data/launch-studio.ps1",+ "content": "a",+ "sha256": "A",+ },+ "unsloth.cmd": {"error": "not found at any supported location under home, data"},+ },+ "rewrittenOnSecondRun": [],+ }+ verdict = cmp.Verdict()+ cmp.compare_artifacts(missing, dict(missing), verdict)+ assert verdict.is_void, "a contract missing on both sides was treated as agreement"+ assert verdict.exit_code() == 3, verdict.void++ script = (+ Path(__file__).resolve().parents[2]+ / ".github"+ / "scripts"+ / "Collect-InstallerEvidence.ps1"+ )+ assert "not found at any supported location" in script.read_text(+ encoding = "utf-8"+ ), "the collector still drops an unresolved contract instead of recording it as an error"+++def test_two_roots_with_the_same_leaf_name_stay_distinct() -> None:+ """The per-user and the common Desktop are both called `Desktop`.++ Keying the root on `Split-Path -Leaf` mapped them to one label, and every Start Menu entry to+ `Programs` however deeply nested, so moving `Unsloth Studio.lnk` from the user's desktop to the+ public one, or into a Programs subdirectory, kept the same key with identical fields.+ """+ script = (+ Path(__file__).resolve().parents[2]+ / ".github"+ / "scripts"+ / "Collect-InstallerEvidence.ps1"+ )+ text = script.read_text(encoding = "utf-8")+ assert "Get-UnslothRootLabel" in text, "the root is no longer canonicalised"+ assert (+ "CommonDesktop" in text and "UserDesktop" in text+ ), "the two desktops are not distinguished, so a move between them compares equal"+ assert (+ "root = (Split-Path $root -Leaf)" not in text+ ), "the shortcut root is still keyed on the leaf name alone"+ # The nested case: the name has to carry the path relative to its root, not just the file name.+ assert "$file.FullName.Substring($root.Length)" in text, (+ "a shortcut nested under Programs is still keyed on its bare file name, so a move into or "+ "out of a subdirectory is invisible"+ )++ # And the two keys must genuinely differ once the labels do.+ assert cmp._shortcut_key(+ {"name": "Unsloth Studio.lnk", "root": "UserDesktop"}+ ) != cmp._shortcut_key({"name": "Unsloth Studio.lnk", "root": "CommonDesktop"})+++def test_every_collected_contract_is_one_the_windows_installer_writes() -> None:+ """A contract Windows never writes turns the missing-contract VOID into a permanent VOID.++ `studio.conf` was in the list and is only ever written by `install.sh`; `install.ps1` and+ `studio/setup.ps1` merely `Test-Path` it. That was harmless while an unresolved contract was+ silently skipped, and became fatal as soon as absence started being recorded as a collection+ error, because then every clean normal-profile Windows run voided on a file that is correct to+ be absent. This lane runs on windows-latest only, so the list has to stay Windows-specific.+ """+ repo = Path(__file__).resolve().parents[2]+ script = (repo / ".github" / "scripts" / "Collect-InstallerEvidence.ps1").read_text(+ encoding = "utf-8"+ )+ block = script[script.index("$contentFiles = [ordered]@{") :]+ block = block[: block.index("\n}")]+ contracts = re.findall(r"^\s*'([^']+)'\s*=", block, re.M)+ assert contracts, "the contract list is empty"++ windows_sources = "\n".join(+ (repo / name).read_text(encoding = "utf-8", errors = "ignore")+ for name in ("install.ps1", "studio/setup.ps1")+ )+ # Move-Item counts: unsloth.cmd is written atomically, WriteAllBytes to a temp then renamed+ # onto the destination, so the destination variable never appears next to a write API.+ writers = (+ "Set-Content",+ "Out-File",+ "WriteAllText",+ "WriteAllBytes",+ "WriteAllLines",+ "Move-Item",+ )+ for contract in contracts:+ # The file name is assigned to a variable and that VARIABLE is what gets written, so the+ # check follows the assignment rather than looking for the literal next to a write call.+ holders = set(+ re.findall(r"\$(\w+)\s*=\s*Join-Path[^\n]*" + re.escape(contract), windows_sources)+ )+ assert holders, (+ f"{contract!r} is collected as a contract but no variable in install.ps1 or "+ f"studio/setup.ps1 is ever set to its path"+ )+ written = any(+ re.search(r"(?:" + "|".join(writers) + r")[^\n]*\$" + holder, windows_sources)+ for holder in holders+ )+ assert written, (+ f"{contract!r} is collected as a contract but nothing in install.ps1 or "+ f"studio/setup.ps1 writes it -- it is only read -- so a clean Windows run records it "+ f"as missing and the lane voids every time. That is exactly what studio.conf did."+ )+++def test_a_launcher_that_loses_its_bom_is_a_difference() -> None:+ """Encoding is part of the contract and `Get-Content -Raw` decodes it away.++ The shortcut runs `launch-studio.ps1` under Windows PowerShell 5.1, which reads a file with no+ BOM as ANSI, so a candidate that stops writing the UTF-8 BOM breaks every install whose paths+ carry non-ASCII characters. The text is identical, so content comparison called it agreement.+ """++ def side(bom: str) -> dict:+ return {+ "studioHome": "X",+ "files": {+ "launch-studio.ps1": {+ "foundAt": "data/launch-studio.ps1",+ "content": "Write-Host 'hi'\n",+ "sha256": "A",+ "bom": bom,+ }+ },+ "rewrittenOnSecondRun": [],+ }++ same = cmp.Verdict()+ cmp.compare_artifacts(side("utf-8"), side("utf-8"), same)+ assert not same.differences, same.differences++ verdict = cmp.Verdict()+ cmp.compare_artifacts(side("utf-8"), side("none"), verdict)+ assert verdict.differences, "a launcher that lost its BOM compared equal"+ assert any("encoding" in row for row in verdict.differences), verdict.differences+++def test_version_drift_in_a_generated_file_is_reported() -> None:+ """The normaliser exists so drift does not fail the lane, not so it disappears.++ The transcript and shortcut comparisons both call `report_version_drift` on the raw text before+ normalising. The generated-file comparison normalised without it, so a launcher retargeted from+ one Python to another returned PASS with nothing said at all.+ """++ def side(version: str) -> dict:+ return {+ "studioHome": "X",+ "files": {+ "launch-studio.ps1": {+ "foundAt": "data/launch-studio.ps1",+ "content": f"& 'C:\\\\py\\\\python-{version}\\\\python.exe' -m unsloth\n",+ "sha256": "A",+ "bom": "utf-8",+ }+ },+ "rewrittenOnSecondRun": [],+ }++ verdict = cmp.Verdict()+ cmp.compare_artifacts(side("3.11.9"), side("3.13.0"), verdict)+ reported = verdict.differences + verdict.notes+ assert any(+ "3.11.9" in row or "3.13.0" in row or "version" in row.lower() for row in reported+ ), f"a retargeted launcher produced no drift note at all: {reported}"+++def test_a_launcher_that_expects_the_wrong_install_id_is_reported() -> None:+ """The launcher refuses a backend whose studio_root_id is not the one it was built with.++ `install.ps1` persists the ID and bakes the same value into the generated launcher as+ `$_ExpectedStudioRootId`, which the launcher compares against the backend's `studio_root_id`+ before accepting it. If a candidate makes those diverge Studio never starts, and nothing else+ here can see it: the two IDs legitimately differ between base and head, so a cross-side+ comparison is meaningless, and the transcript normaliser rewrites every 64-character hex token,+ so the launcher contents compare equal regardless.+ """++ def side(persisted: str, embedded: str) -> dict:+ return {+ "studioHome": "X",+ "files": {+ "launch-studio.ps1": {+ "foundAt": "data/launch-studio.ps1",+ "content": "x",+ "sha256": "A",+ "bom": "utf-8",+ }+ },+ "rewrittenOnSecondRun": [],+ "installId": persisted,+ "embeddedId": embedded,+ }++ good = cmp.Verdict()+ cmp.compare_artifacts(side("a" * 64, "a" * 64), side("b" * 64, "b" * 64), good)+ assert (+ not good.differences+ ), f"two healthy installs with different IDs were reported as a difference: {good.differences}"++ verdict = cmp.Verdict()+ cmp.compare_artifacts(side("a" * 64, "a" * 64), side("b" * 64, "c" * 64), verdict)+ assert verdict.differences, "a launcher expecting the wrong install ID was not reported"+ assert any("refuse its own backend" in row for row in verdict.differences), verdict.differences+++def test_a_malformed_artifact_entry_is_void_not_skipped() -> None:+ """The same collector runs on both legs, so malformed evidence is malformed symmetrically.++ A non-object entry was skipped, which left both file maps non-empty and their key sets matching+ while nothing about that contract was compared at all. The run then reported agreement. The+ shortcut manifest and the top-level manifests are already validated this way; this one was not.+ """++ def side(entry) -> dict:+ return {+ "studioHome": "X",+ "files": {+ "launch-studio.ps1": {+ "foundAt": "data/launch-studio.ps1",+ "content": "a",+ "sha256": "A",+ "bom": "utf-8",+ },+ "unsloth.cmd": entry,+ },+ "rewrittenOnSecondRun": [],+ }++ ok = cmp.Verdict()+ cmp.compare_artifacts(+ side({"foundAt": "home/bin\\unsloth.cmd", "content": "b", "sha256": "B", "bom": "none"}),+ side({"foundAt": "home/bin\\unsloth.cmd", "content": "b", "sha256": "B", "bom": "none"}),+ ok,+ )+ assert not ok.is_void, f"the control voided for an unrelated reason: {ok.void}"++ verdict = cmp.Verdict()+ cmp.compare_artifacts(side("not-an-object"), side("not-an-object"), verdict)+ assert verdict.is_void, "symmetrically malformed artifact evidence was reported as agreement"+ assert verdict.exit_code() == 3, verdict.void+++def test_the_trigger_only_lists_files_this_lane_actually_runs() -> None:+ """A workflow that starts on a file it never reads reports PASS about an untested change.++ `studio/setup.bat` and `scripts/uninstall.ps1` were in the trigger while the measurement only+ invokes `install.ps1`, which hands off to `studio/setup.ps1`. A PR touching either produced+ identical evidence on both legs, because neither file was ever read, and a green differential+ lane that did not exercise the change is worse than no lane at all.+ """+ import yaml as _yaml++ repo = Path(__file__).resolve().parents[2]+ path = repo / ".github" / "workflows" / "windows-installer-differential-ci.yml"+ workflow = _yaml.safe_load(path.read_text(encoding = "utf-8"))+ # `on` parses as the boolean True in YAML 1.1, which is what PyYAML implements.+ triggers = workflow.get("on", workflow.get(True))+ paths = triggers["pull_request"]["paths"]++ body = path.read_text(encoding = "utf-8")+ for script in ("studio/setup.bat", "scripts/uninstall.ps1"):+ if script in paths:+ # Only legitimate if something in the workflow actually invokes it.+ assert re.search(+ re.escape(Path(script).name) + r"[^\n]*(&|Start-Process|cmd|-File)", body+ ), (+ f"{script} starts this workflow but nothing in it runs the file, so a PR that "+ f"changes only that script gets a PASS from a lane that never read it"+ )+ assert "install.ps1" in paths, "the lane no longer starts on the file it actually measures"+++def test_generated_scripts_are_not_normalised_like_console_output() -> None:+ """`normalise_transcript` is built for captured output and destroys script content.++ It drops blank lines, rstrips every line, and discards lines beginning with runner noise such+ as `Run `, `shell: ` or `env:`. Applied to a generated script each of those hides a real change:+ trailing whitespace in a CMD `set` value is part of the value, a dropped blank line changes a+ here-string, and an echoed line starting with `Run ` is content rather than noise.+ """++ def side(body: str) -> dict:+ return {+ "studioHome": "X",+ "files": {+ "unsloth.cmd": {+ "foundAt": "home/bin\\unsloth.cmd",+ "content": body,+ "sha256": "A",+ "bom": "none",+ }+ },+ "rewrittenOnSecondRun": [],+ }++ for before, after, what in (+ (+ "set UNSLOTH_HOME=C:\\u \r\n",+ "set UNSLOTH_HOME=C:\\u\r\n",+ "a trailing space in a set value",+ ),+ ("@echo off\n\necho hi\n", "@echo off\necho hi\n", "a dropped blank line"),+ ("echo Run the installer\n", "echo Run the setup\n", "a line starting with Run"),+ ):+ verdict = cmp.Verdict()+ cmp.compare_artifacts(side(before), side(after), verdict)+ assert verdict.differences, f"{what} was normalised away and compared equal"++ # And the volatile values must still be normalised, or every run would differ.+ same = cmp.Verdict()+ cmp.compare_artifacts(+ side("echo C:\\Users\\r\\AppData\\Local\\Temp\\unsloth-aaaaaa\\x\n"),+ side("echo C:\\Users\\r\\AppData\\Local\\Temp\\unsloth-bbbbbb\\x\n"),+ same,+ )+ assert not same.differences, f"a scratch name was not normalised: {same.differences}"+++def test_a_reinstall_only_output_change_is_reported(tmp_path: Path) -> None:+ """The failure mode the second-run transcript exists to catch.++ The workflow has always captured `transcript-second-run.txt` and the comparer never read it, so+ a candidate that changes what a REINSTALL prints -- the one population every existing user is in+ -- left the first-run transcripts identical and the artifacts untouched and the lane said PASS.+ """+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head", second = BASELINE + "\n warning already installed\n")+ result = _run(base, head)+ assert result.returncode == 2, result.stdout + result.stderr+ assert "second-run transcript" in result.stdout+ assert "already installed" in result.stdout+++def test_a_missing_second_run_transcript_is_void_not_a_pass(tmp_path: Path) -> None:+ base = _write(tmp_path / "base")+ head = _write(tmp_path / "head")+ (head / "transcript-second-run.txt").unlink()+ result = _run(base, head)+ assert result.returncode != 0, result.stdout + result.stderr+ assert "second-run transcript" in result.stdout+++def test_script_normalisation_does_not_erase_a_changed_port_or_limit(tmp_path: Path) -> None:+ """The transcript rules are wrong for a generated file.++ `<port>` and `<size>` exist because a console transcript reports the port Studio bound and the+ bytes a download moved. Inside `launch-studio.ps1` the same text is behaviour, and rewriting+ both sides to the same token made a retargeted health probe and a changed upload limit compare+ equal.+ """+ before = "$url = 'http://127.0.0.1:8888/api/health'\nset LIMIT=10MB\n"+ after = "$url = 'http://127.0.0.1:9999/api/health'\nset LIMIT=20MB\n"+ assert cmp.normalise_script(before) != cmp.normalise_script(after)+ # And the control: the values that DO vary between two installs of two commits still go, or the+ # lane would report a difference on every clean run.+ root = "a" * 64+ assert cmp.normalise_script(f"$expected = '{root}'") == cmp.normalise_script(+ "$expected = '" + "b" * 64 + "'"+ )+ assert cmp.normalise_script("$p = 'C:\\Temp\\unsloth-probe-0a1b2c3d.tmp'") == (+ cmp.normalise_script("$p = 'C:\\Temp\\unsloth-probe-9f8e7d6c.tmp'")+ )+++def test_a_shortcut_the_second_run_deletes_is_recorded(tmp_path: Path) -> None:+ """Run, not reasoned about: the collector is driven with a first-run manifest whose shortcut is+ gone by the second run.++ The idempotency loop walked the CURRENT shortcut keys, so a shortcut that existed after the+ first install and was deleted by the second was never looked at. The second collector overwrites+ shortcuts.json with the final state, so a candidate that creates an extra shortcut on a fresh+ install and removes it on reinstall ended with manifests matching the base and an empty+ `rewrittenOnSecondRun`: a PASS on a shortcut the user watched disappear.+ """+ sys.path.insert(0, str(REPO / "tests" / "_shared"))+ from unsloth_pwsh_runner import PWSH, run_pwsh # noqa: PLC0415++ if PWSH is None:+ pytest.skip("no PowerShell on this host")++ collector = REPO / ".github" / "scripts" / "Collect-InstallerEvidence.ps1"+ first = tmp_path / "first-run-artifacts.json"+ first.write_text(+ json.dumps(+ {+ "studioHome": str(tmp_path / "home"),+ "files": {},+ "shortcutWrites": {+ "UserDesktop/Unsloth Studio.lnk": "2026-01-01T00:00:00.0000000Z"+ },+ "installId": None,+ "embeddedId": None,+ }+ ),+ encoding = "utf-8",+ )+ out = tmp_path / "evidence"+ (tmp_path / "home").mkdir()+ script = f"""+$ErrorActionPreference = 'Stop'+& '{collector.as_posix()}' -StudioHome '{(tmp_path / "home").as_posix()}' `+ -OutDir '{out.as_posix()}' -CompareAgainst '{first.as_posix()}' | Out-Null+Write-Output 'COLLECTOR-OK'+"""+ result = run_pwsh(+ [PWSH, "-NoProfile", "-NonInteractive", "-Command", script],+ capture_output = True,+ text = True,+ verdict = "COLLECTOR-OK",+ timeout = 300,+ )+ assert "COLLECTOR-OK" in result.stdout, result.stdout + result.stderr+ artifacts = json.loads((out / "artifacts.json").read_text(encoding = "utf-8-sig"))+ rewritten = artifacts.get("rewrittenOnSecondRun")+ assert rewritten is not None, "idempotency was not measured at all"+ assert any(+ "removed by the second run" in entry for entry in rewritten+ ), f"a shortcut deleted by the reinstall was not recorded: {rewritten!r}"+++def _collect(tmp_path: Path, home_names: list[str], first_files: dict) -> list:+ """Run the collector against a home directory and a hand-made first-run manifest."""+ sys.path.insert(0, str(REPO / "tests" / "_shared"))+ from unsloth_pwsh_runner import PWSH, run_pwsh # noqa: PLC0415++ if PWSH is None:+ pytest.skip("no PowerShell on this host")++ home = tmp_path / "home"+ home.mkdir()+ for name in home_names:+ (home / name).write_text("x", encoding = "utf-8")+ first = tmp_path / "first-run-artifacts.json"+ first.write_text(+ json.dumps(+ {+ "studioHome": str(home),+ "files": first_files,+ "shortcutWrites": {},+ "installId": None,+ "embeddedId": None,+ }+ ),+ encoding = "utf-8",+ )+ out = tmp_path / "evidence"+ collector = REPO / ".github" / "scripts" / "Collect-InstallerEvidence.ps1"+ result = run_pwsh(+ [+ PWSH,+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ f"& '{collector.as_posix()}' -StudioHome '{home.as_posix()}' "+ f"-OutDir '{out.as_posix()}' -CompareAgainst '{first.as_posix()}' | Out-Null; "+ f"Write-Output 'COLLECTOR-OK'",+ ],+ capture_output = True,+ text = True,+ verdict = "COLLECTOR-OK",+ timeout = 300,+ )+ assert "COLLECTOR-OK" in result.stdout, result.stdout + result.stderr+ artifacts = json.loads((out / "artifacts.json").read_text(encoding = "utf-8-sig"))+ rewritten = artifacts.get("rewrittenOnSecondRun")+ assert rewritten is not None, "idempotency was not measured at all"+ return rewritten+++def test_a_transient_top_level_artifact_is_reported(tmp_path: Path) -> None:+ """The idempotency loop walked the two content contracts only.++ Every top-level name is already in the manifest, so a candidate that creates a file or directory+ on a fresh install and removes it on reinstall was invisible: the second collector overwrites+ artifacts.json with the post-reinstall tree, both final manifests match the base, and the lane+ reported PASS on an install that left an extra artifact behind.+ """+ rewritten = _collect(tmp_path, ["kept"], {"kept": {"present": True}, "gone": {"present": True}})+ assert any("gone (removed by the second run)" == e for e in rewritten), rewritten+ assert not any(+ e.startswith("kept ") for e in rewritten+ ), f"a file present on both runs was reported as a change: {rewritten!r}"+++def test_an_empty_first_run_map_invents_no_phantom_key(tmp_path: Path) -> None:+ """Member enumeration over an EMPTY `PSObject.Properties` yields `$null`, and `@($null)` has+ Count 1. Without filtering, a first run that recorded nothing produced one key named `''` and+ every clean run reported it as removed, which fails a lane that should pass."""+ rewritten = _collect(tmp_path, [], {})+ assert not any("removed by the second run" in e for e in rewritten), rewritten+++def test_an_unrelated_label_does_not_restart_the_two_installs() -> None:+ """`labeled` fires for every label, and the concurrency group cancels in progress.++ Reading the PR's whole label list meant that adding any label to a PR that already carried+ `installer-differential` evaluated true and started the lane again, which with+ `cancel-in-progress: true` cancels a measurement that is already running. The `labeled` event+ has to look at the label that was just applied; `synchronize` still reads the full list, because+ there no single label was applied.+ """+ body = (REPO / ".github" / "workflows" / "windows-installer-differential-ci.yml").read_text(+ encoding = "utf-8"+ )+ gate = body[body.index("name: Skip unless the label asked for it") :]+ gate = gate[: gate.index("name: Pick the two commits")]+ assert (+ "github.event.label.name" in gate+ ), "the gate never reads the label that was applied, so any label restarts two clean installs"+ assert '[ "$ACTION" = "labeled" ]' in gate, "there is no branch for the labeled event"+ # And the full-list check has to survive for synchronize, or a labelled PR stops being+ # re-measured as it is pushed to.+ assert '"installer-differential"' in gate+ assert gate.index('[ "$ACTION" = "labeled" ]') < gate.index(+ "grep -q"+ ), "the full label list is consulted before the labeled branch, so the branch cannot help"+ # And the step gate alone is not enough. Workflow concurrency is evaluated before any job runs,+ # so an unrelated label took the group and cancelled the installs already in flight however+ # quickly the step then decided to do nothing. The group has to separate those events.+ group = body[body.index("concurrency:") : body.index("env:", body.index("concurrency:"))]+ assert "github.event.label.name" in group, (+ "the concurrency group does not distinguish the label, so an unrelated label still cancels "+ "a measurement in progress before this gate can run"+ )+ assert "unrelated-label" in group and "cancel-in-progress: true" in group+++def test_installer_output_that_looks_like_a_runner_header_survives() -> None:+ """The normaliser dropped any line beginning with `Run `, and the installers print several.++ `transcript.txt` is the child `powershell.exe` stream teed by the workflow+ (windows-installer-differential-ci.yml:273-274), so GitHub's `Run `, `shell: ` and `env:` step+ headers never enter it. The rule therefore removed genuine user-visible guidance from both sides,+ and changing or dropping one of those lines compared equal.+ """+ real = [+ " Run install.ps1 without --tauri for custom-root shell installs,",+ " Run 'setx HIP_VISIBLE_DEVICES 1' and reopen your terminal",+ " Run this manually in an Admin terminal:",+ " env: the managed environment is ready",+ " shell: powershell is what this install used",+ ]+ kept = cmp.normalise_transcript("\n".join(real))+ assert len(kept) == len(real), f"normalisation dropped installer output: {kept!r}"+ # And a changed one has to show up as a difference.+ changed = list(real)+ changed[0] = changed[0].replace("without --tauri", "with --tauri")+ assert cmp.normalise_transcript("\n".join(real)) != cmp.normalise_transcript("\n".join(changed))+ # The control: what the runner really injects, at column 0, still goes.+ assert cmp.normalise_transcript("##[group]Install\n::endgroup::\n##[debug]x") == []+++def test_the_lines_this_rule_used_to_eat_are_really_in_the_installers() -> None:+ """The reason the rule was wrong is a fact about the shipped files, so it is asserted rather+ than described. If these lines ever stop existing the comment above the rule is stale."""+ found = 0+ for name in ("install.ps1", "studio/setup.ps1"):+ text = (REPO / name).read_text(encoding = "utf-8")+ for line in text.splitlines():+ if re.search(r'"\s*Run ', line) and ("Write-StudioLine" in line or "substep" in line):+ found += 1+ assert found >= 5, (+ f"only {found} printed lines start with 'Run '; the normaliser comment cites six and needs "+ f"updating if that changed"+ )+++def test_a_manual_dispatch_compares_against_the_default_branch() -> None:+ """`HEAD~1` answers a narrower question than the input documents.++ `base_ref` advertises "the PR merge base, or main". For a manual dispatch with no input the+ resolver picked `HEAD~1`, so on a feature branch with more than one commit an installer change+ older than one commit sat in both trees and the lane reported PASS without ever comparing it+ against the default branch.+ """+ body = (REPO / ".github" / "workflows" / "windows-installer-differential-ci.yml").read_text(+ encoding = "utf-8"+ )+ step = body[body.index("name: Pick the two commits") :]+ step = step[: step.index("- name:", 10)]+ assert "DEFAULT_BRANCH" in step, "the resolver never looks at the default branch"+ assert (+ 'merge-base "$default_tip"' in step+ ), "the manual-dispatch path does not take a merge base against the default branch"+ # HEAD~1 may remain only as a last resort, and only with the difference stated. Keyed on the+ # command rather than on the string, which also appears in the comment explaining why it was+ # wrong.+ # Every use of HEAD~1 has to say what it is. Two are legitimate now: the default branch, where+ # the previous commit IS the intended baseline, and the fallback where the default branch could+ # not be resolved at all, which is a degradation and says so as a warning.+ lines = step.splitlines()+ for i, line in enumerate(lines):+ if "rev-parse HEAD~1" not in line:+ continue+ window = "\n".join(lines[max(0, i - 6) : i])+ assert "::warning::" in window or "previous commit on that branch" in window, (+ "HEAD~1 is used here without saying that it is the previous commit and not the default "+ f"branch:\n{window}\n{line}"+ )+++def test_a_default_branch_run_gets_a_distinct_base() -> None:+ """The weekly health run and a dispatch from main both have head == the default branch tip.++ Taking the merge base of the default branch with itself yields head, and the same-commit guard+ then VOIDs the run, so the advertised weekly health run could never reach the measurement jobs.+ On the default branch the baseline is the previous commit, which is the right question for a run+ whose job is to show the lane still works.+ """+ body = (REPO / ".github" / "workflows" / "windows-installer-differential-ci.yml").read_text(+ encoding = "utf-8"+ )+ assert "schedule:" in body, "there is no scheduled run any more, so this test is describing"+ step = body[body.index("name: Pick the two commits") :]+ step = step[: step.index("- name:", 10)]+ # Keyed on the message, not on the comparison: the same-commit GUARD tests `$base` = `$head`+ # too, so asserting on the expression alone is satisfied by the very code this is about.+ assert "the tip of $DEFAULT_BRANCH" in step, (+ "nothing notices that the merge base resolved to head, so every scheduled run VOIDs before "+ "it reaches the measurement jobs"+ )+ # And it has to be handled BEFORE the guard that aborts on a same-commit pair.+ assert step.index("the tip of $DEFAULT_BRANCH") < body.index(+ "base and head are the same commit"+ ), "the same-commit guard runs before the default-branch case is handled"+ # The resolution has to actually change the base, or the guard still fires.+ after = step[step.index("the tip of $DEFAULT_BRANCH") :]+ assert (+ "rev-parse HEAD~1" in after[:900]+ ), "the default-branch case is detected and then does not pick a different baseline"+ # And it has to be decided by comparing head with the fetched TIP. Head being an ancestor of the+ # default branch also makes the merge base equal head -- a dispatch at an older main commit, or a+ # branch with no commits of its own -- and substituting HEAD~1 there measures two adjacent+ # historical commits and can report PASS for a comparison nobody asked for.+ assert '[ "$head" = "$default_tip" ]' in step, (+ "the health-run baseline is chosen from the merge base equalling head, which is also true "+ "for any commit that is merely an ancestor of the default branch"+ )+ assert "default_tip=" in step, "the default branch tip is never resolved"+++def test_an_empty_shortcut_object_is_void_not_one_compared(tmp_path: Path) -> None:+ """`{}` is an object, so it survived every shape check and became one `<unnamed>` shortcut.++ Both sides then held the same key with the same absent fields, and the run reported "1 compared,+ every field equal" and exited zero without a launch contract having been measured. The workflow+ runs the candidate collector on both legs on purpose, so a schema regression is symmetric and+ this is the shape it takes.+ """+ base = _write(tmp_path / "base", shortcuts = [{}])+ head = _write(tmp_path / "head", shortcuts = [{}])+ result = _run(base, head)+ assert result.returncode == 3, result.stdout + result.stderr+ assert "no name and no path" in result.stdout, result.stdout+++def test_a_shortcut_with_a_name_but_no_launch_contract_is_void(tmp_path: Path) -> None:+ base = _write(+ tmp_path / "base", shortcuts = [{"name": "Unsloth Studio.lnk", "root": "UserDesktop"}]+ )+ head = _write(+ tmp_path / "head", shortcuts = [{"name": "Unsloth Studio.lnk", "root": "UserDesktop"}]+ )+ result = _run(base, head)+ assert result.returncode == 3, result.stdout + result.stderr+ assert "none of the launch contract fields" in result.stdout, result.stdout+++def test_a_content_contract_with_no_content_on_either_side_is_void(tmp_path: Path) -> None:+ """Both sides listing `launch-studio.ps1` as `{}` compared nothing and passed.++ The asymmetry check is false when neither side has `content`, and the comparison below it is+ false for the same reason, so the loop fell through with the entry uncompared.+ """+ artifacts = copy.deepcopy(ARTIFACTS)+ artifacts["files"]["launch-studio.ps1"] = {}+ base = _write(tmp_path / "base", artifacts = artifacts)+ head = _write(tmp_path / "head", artifacts = copy.deepcopy(artifacts))+ result = _run(base, head)+ assert result.returncode == 3, result.stdout + result.stderr+ assert "whose text is the contract" in result.stdout, result.stdout+ # The control: with content present on both sides the same pair is a clean pass, so the new+ # rule is not simply voiding everything.+ ok_base = _write(tmp_path / "ok-base")+ ok_head = _write(tmp_path / "ok-head")+ assert _run(ok_base, ok_head).returncode == 0+++def test_a_shortcut_argument_change_is_not_normalised_away(tmp_path: Path) -> None:+ """Shortcut fields were run through the CONSOLE normaliser.++ `--limit 10MB` becoming `20MB`, a timeout moving from `10.0s` to `30.0s`, or a port written into+ the command line are the launch contract, not download noise, and `normalise_line` rewrote both+ sides to the same token so the lane reported every field equal.+ """++ def _sc(arguments: str) -> list[dict]:+ return [+ {+ "name": "Unsloth Studio.lnk",+ "root": "UserDesktop",+ "targetPath": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",+ "arguments": arguments,+ "windowStyle": 7,+ }+ ]++ base = _write(+ tmp_path / "base", shortcuts = _sc("-File launcher.ps1 --limit 10MB --timeout 10.0s")+ )+ head = _write(+ tmp_path / "head", shortcuts = _sc("-File launcher.ps1 --limit 20MB --timeout 30.0s")+ )+ result = _run(base, head)+ assert result.returncode == 2, result.stdout + result.stderr+ assert "arguments" in result.stdout and "20MB" in result.stdout, result.stdout+ # The control: what really does vary between two installs of two commits still goes, or the lane+ # would report a difference on every clean run.+ same_base = _write(+ tmp_path / "sb", shortcuts = _sc("-File C:\\Temp\\unsloth-probe-0a1b2c3d\\l.ps1")+ )+ same_head = _write(+ tmp_path / "sh", shortcuts = _sc("-File C:\\Temp\\unsloth-probe-9f8e7d6c\\l.ps1")+ )+ assert _run(same_base, same_head).returncode == 0+++def test_missing_bom_metadata_is_void_not_skipped(tmp_path: Path) -> None:+ """The collector always writes `bom` for a contract it could read, so its absence is a+ regression, and the same collector writes both manifests, so it goes missing symmetrically."""+ artifacts = copy.deepcopy(ARTIFACTS)+ del artifacts["files"]["launch-studio.ps1"]["bom"]+ base = _write(tmp_path / "base", artifacts = artifacts)+ head = _write(tmp_path / "head", artifacts = copy.deepcopy(artifacts))+ result = _run(base, head)+ assert result.returncode == 3, result.stdout + result.stderr+ assert "carries no bom metadata on base and head" in result.stdout, result.stdout+++def test_no_rev_parse_fallback_can_echo_its_argument() -> None:+ """`git rev-parse` prints an argument it cannot resolve to STDOUT before failing.++ So `base="$(git rev-parse "$X" 2>/dev/null || git rev-parse FETCH_HEAD)"` captured the literal+ `main^{commit}` AND the fallback's SHA, and `$base` became two lines. `base_ref=main` is the+ documented input and hits it every time, because a checkout has `origin/main` and no local+ `main`. Reproduced in a scratch repository before fixing:++ $ out=$(git rev-parse "main^{commit}" 2>/dev/null || git rev-parse HEAD)+ main^{commit}+ 69691fa0f5b84f2cc802bf7ff3950a674213a9e6++ `--verify --quiet` prints nothing on failure, so every rev-parse that has a fallback uses it.+ """+ body = (+ REPO / ".github" / "workflows" / "windows-installer-differential-ci.yml"+ ).read_text(encoding = "utf-8")+ step = body[body.index("name: Pick the two commits"):]+ step = step[:step.index("- name:", 10)]+ for line in step.splitlines():+ if "rev-parse" not in line or "||" not in line:+ continue+ for call in line.split("||"):+ if "rev-parse" not in call:+ continue+ assert "--verify --quiet" in call, (+ "this rev-parse has a fallback and can echo its argument into the captured value:\n"+ f"{line.strip()}"+ )