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
Unbreak main, and fix the five causes reddening the PR backlog (#10832)
Daniel Hanfc6694816e3a
diff --git a/.github/scripts/Watch-ForCompiler.ps1 b/.github/scripts/Watch-ForCompiler.ps1index 776e39c7c5c..e4b42e01be7 100644--- a/.github/scripts/Watch-ForCompiler.ps1+++ b/.github/scripts/Watch-ForCompiler.ps1@@ -20,6 +20,11 @@ is not the code under test:silently overridden by machine policy. csc.exe writes the source and theresponse file next to the assembly, so those names are watched too.+ A DLL is only reported when a compile is evidenced in ITS OWN directory; see+ Select-StudioCompilerLibraries. Reporting every DLL under TEMP is not the same+ claim, and an installer that unpacks a verified archive there makes the+ difference the whole result.+Watched live, with a FileSystemWatcher, and not only by comparing a listingtaken before the action against one taken after. CodeDom deletes its wholeintermediate directory once the assembly is loaded, so on a hosted runner the@@ -82,7 +87,75 @@ function Get-StudioTempArtifacts {}$script:ArtifactPattern = '\.(dll|cmdline|rsp|cs|err|out)$'-$script:LibraryPattern = '\.(dll|cmdline|rsp)$'+# A compiler's own files, wherever they appear. Nothing else writes a .cmdline.+$script:CompilerFilePattern = '\.(cmdline|rsp)$'+# What csc leaves beside the assembly it produced: the response file, the generated+# source, and the captured streams.+$script:CompilerSiblingPattern = '\.(cmdline|rsp|cs|err|out)$'++function Get-StudioParentPath {+ <#+ .SYNOPSIS+ The directory part of $Path, split on either separator.+ .DESCRIPTION+ Not Split-Path, for the reason Select-StudioCompilerHits splits by hand: under the+ Linux pwsh these functions are tested on, a backslash is an ordinary character and a+ Windows path comes back whole. The paths here are always Windows paths whatever reads+ them.+ #>+ param([Parameter(Mandatory = $true)][string]$Path)++ $at = [Math]::Max($Path.LastIndexOf('\'), $Path.LastIndexOf('/'))+ if ($at -lt 0) { return '' }+ return $Path.Substring(0, $at)+}++function Select-StudioCompilerLibraries {+ <#+ .SYNOPSIS+ The paths among $Artifacts that a C# compile accounts for.+ .DESCRIPTION+ A .cmdline or .rsp is a compiler's own file wherever it lands. A .dll on its own is+ not, and treating it as one is what failed this job on every run since it was added:+ the installer unpacks llama.cpp's checksum-verified prebuilt release into a staging+ directory under TEMP, which lands ~25 DLLs there with no compiler within reach. The+ shape under test is the one that was blocked in the field,++ powershell.exe -> csc.exe -> %TEMP%\<random>.dll++ and an unpacked archive is not it.++ So a DLL counts only when a compile is evidenced in the SAME directory. CodeDom, which+ is what Add-Type uses and what Bitdefender flagged, writes the response file, the+ generated source and the captured streams into the per-invocation directory it puts the+ assembly in, so the pairing holds for the shape this exists to catch. The workflow's+ positive control compiles a real type and REQUIRES this to fire, so a narrowing that+ went too far fails there rather than passing quietly.+ #>+ param([Parameter(Mandatory = $true)][AllowEmptyCollection()][string[]]$Artifacts)++ $compileDirs = New-Object 'System.Collections.Generic.HashSet[string]' (+ [StringComparer]::OrdinalIgnoreCase)+ foreach ($path in $Artifacts) {+ if ($path -match $script:CompilerSiblingPattern) {+ $null = $compileDirs.Add((Get-StudioParentPath -Path $path))+ }+ }++ $libraries = @()+ foreach ($path in $Artifacts) {+ if ($path -match $script:CompilerFilePattern) {+ $libraries += $path+ } elseif ($path -match '\.dll$' -and+ $compileDirs.Contains((Get-StudioParentPath -Path $path))) {+ $libraries += $path+ }+ }+ # Returned plain, not comma-wrapped like the functions above: the caller normalises+ # with @(), and wrapping an empty array there yields a one-element array holding an+ # empty array, which reads downstream as one unnamed temporary library.+ return $libraries+}function Start-StudioTempWatch {<#@@ -157,27 +230,58 @@ function Stop-StudioTempWatch {return ,[string[]]$seen}-function Get-StudioProcessImageName {+function Get-StudioEventField {<#.SYNOPSIS- The image a 4688 record says was created, from the record's own field.+ One named EventData field of a 4688 record, from the record's own XML..DESCRIPTION- NewProcessName, read out of the event XML by name rather than by position, so a- schema that gains a field still means the same thing. Nothing else is consulted:- the rendered message also carries the command line, so matching it would score- `cmd.exe /c echo csc.exe` as a compiler.+ Read by name rather than by position, so a schema that gains a field still means the+ same thing. The rendered message is never consulted: it carries the command line too,+ so matching that would score `cmd.exe /c echo csc.exe` as a compiler.#>- param([Parameter(Mandatory = $true)]$Event)+ param(+ [Parameter(Mandatory = $true)]$Event,+ [Parameter(Mandatory = $true)][string]$Name+ )try {$xml = [xml]$Event.ToXml()foreach ($field in $xml.Event.EventData.Data) {- if ($field.Name -eq 'NewProcessName') { return [string]$field.'#text' }+ if ($field.Name -eq $Name) { return [string]$field.'#text' }}} catch { }return ''}+function Get-StudioProcessImageName {+ <#+ .SYNOPSIS+ The image a 4688 record says was created.+ #>+ param([Parameter(Mandatory = $true)]$Event)++ return Get-StudioEventField -Event $Event -Name 'NewProcessName'+}++function Test-StudioCompilerImage {+ <#+ .SYNOPSIS+ True when $Image is one of the compiler binaries, matched on the whole leaf name.+ #>+ param([string]$Image)++ if ([string]::IsNullOrEmpty($Image)) { return $false }+ # Split explicitly, not via [System.IO.Path]::GetFileName, which splits on the HOST's+ # separators: under the Linux pwsh where this is tested a backslash is an ordinary+ # character and the whole path came back as the leaf. The records are always Windows+ # paths whatever reads them.+ $leaf = ($Image -split '[\\/]')[-1]+ foreach ($name in $script:CompilerNames) {+ if ($leaf -eq $name) { return $true }+ }+ return $false+}+function Select-StudioCompilerHits {<#.SYNOPSIS@@ -191,21 +295,28 @@ function Select-StudioCompilerHits {$hits = @()foreach ($record in $Events) {$image = Get-StudioProcessImageName -Event $record- if ([string]::IsNullOrEmpty($image)) { continue }- # Split explicitly, not via [System.IO.Path]::GetFileName, which splits on the- # HOST's separators: under the Linux pwsh where this is tested a backslash is an- # ordinary character and the whole path came back as the leaf. The records are- # always Windows paths whatever reads them.- $leaf = ($image -split '[\\/]')[-1]- foreach ($name in $script:CompilerNames) {- if ($leaf -eq $name) {- $rendered = ''- try { $rendered = [string]$record.Message } catch { }- $hits += ("{0:o} {1} :: {2}" -f $record.TimeCreated, $image,- ($rendered -replace '\s+', ' '))- break- }+ if (-not (Test-StudioCompilerImage -Image $image)) { continue }+ # A compiler started BY a compiler is a step of a compile that is already being+ # scored, not a new one. csc.exe shells out to cvtres.exe to build its resource+ # blob, and counting that as a second hit says the action compiled twice.+ #+ # It also decides the cross-step bleed the $prior subtraction could not, because+ # the Security log is written with latency: the positive control's csc.exe started+ # before the installer's window, its cvtres.exe child landed inside, and neither+ # was in the log yet when the baseline was taken. The child is the only part that+ # was ever in range.+ #+ # Detection is unchanged for a compile the action really starts, because its ROOT+ # compiler is spawned by the installer's shell, not by another compiler, and the+ # window opens before the action does. What this drops is only ever the second+ # process of a chain whose first was already seen or was never in range at all.+ if (Test-StudioCompilerImage -Image (Get-StudioEventField -Event $record -Name 'ParentProcessName')) {+ continue}+ $rendered = ''+ try { $rendered = [string]$record.Message } catch { }+ $hits += ("{0:o} {1} :: {2}" -f $record.TimeCreated, $image,+ ($rendered -replace '\s+', ' '))}return ,[string[]]$hits}@@ -297,6 +408,15 @@ function Invoke-WithCompilerWatch {# of the sweep above, so a compiler started in that second is counted: a deliberate# trade towards a loud false alarm rather than a dropped real compile.$since = (Get-Date).AddSeconds(-1)+ # That second reaches backwards, so it can reach into whatever ran BEFORE this action.+ # It did: the positive control compiles a type one step earlier, and its+ # csc.exe -> cvtres.exe landed inside the installer measurement's lookback and was+ # reported as "the installer spawned 1 compiler process(es)".+ #+ # Recorded and subtracted below, rather than moving the floor forward: a hit already in+ # the window before the action starts cannot be the action's, while moving the floor to+ # "now" would give up the same-tick protection the second is there to provide.+ $prior = @(Get-StudioCompilerEvents -Since $since -Until (Get-Date))# Opened here, with the 4688 window, and not before the baseline: a file the# machine creates during that recursive sweep predates the action.$watch = Start-StudioTempWatch@@ -321,7 +441,13 @@ function Invoke-WithCompilerWatch {# Closed before the temp sweep, which can take seconds: anything the machine# starts during that walk belongs to nobody's measurement.$until = Get-Date- $compilers = @(Get-StudioCompilerEvents -Since $since -Until $until)+ # Each hit string carries its own round-trip timestamp, image and message, so it+ # identifies the record. Anything that was already there before the action ran is+ # dropped by identity.+ $compilers = @(+ Get-StudioCompilerEvents -Since $since -Until $until |+ Where-Object { $prior -notcontains $_ }+ )$after = Get-StudioTempArtifacts$left = @($after | Where-Object { -not $before.Contains($_) })@@ -333,7 +459,7 @@ function Invoke-WithCompilerWatch {foreach ($path in ($left + $transient)) {if ($union.Add($path)) { $newArtifacts += $path }}- $newLibraries = @($newArtifacts | Where-Object { $_ -match $script:LibraryPattern })+ $newLibraries = @(Select-StudioCompilerLibraries -Artifacts ([string[]]$newArtifacts))$stem = Join-Path $EvidenceRoot $Name$compilers | Out-File -FilePath "$stem-compilers.txt" -Encoding utf8diff --git a/.github/workflows/windows-no-compiler-ci.yml b/.github/workflows/windows-no-compiler-ci.ymlindex f9a7120b256..4a268fee500 100644--- a/.github/workflows/windows-no-compiler-ci.yml+++ b/.github/workflows/windows-no-compiler-ci.yml@@ -143,29 +143,39 @@ jobs:# that. Not --tauri, which refuses the UNSLOTH_STUDIO_HOME that keeps# every step reading one tree.New-Item -ItemType Directory -Force -Path logs | Out-Null+ # 'Continue' only around the child. Under 'Stop', a native command writing+ # ANY line to stderr raises NativeCommandError, so one progress line the+ # installer reports there kills the measurement before the detectors are+ # read. The exit code below is the gate, which is what this is measuring.+ $outer = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'& powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `-File "$env:GITHUB_WORKSPACE\install.ps1" --no-torch *>&1 |Tee-Object -FilePath "$env:UNSLOTH_EVIDENCE\install.log"$exit = $LASTEXITCODE+ $ErrorActionPreference = $outer$global:LASTEXITCODE = 0if ($exit -ne 0) { throw "install.ps1 exited $exit" }}$seen = Invoke-WithCompilerWatch -Name 'installer' -Action $install `-EvidenceRoot $env:UNSLOTH_EVIDENCE+ # Interpolated, not -f: the format operator binds tighter than the string+ # concatenation above it, so it applied to the last fragment only and the+ # message reported a literal "{0}" every time it fired.if ($seen.Compilers) {$seen.Compilers | ForEach-Object { Write-Host "COMPILER: $_" }- throw ("the installer spawned {0} compiler process(es). This is the chain that was " +- "blocked in the field: a windowless PowerShell launching csc.exe and dropping " +- "a DLL in TEMP. Declare native methods with New-StudioEmittedNativeType." -f `- $seen.Compilers.Count)+ throw ("the installer spawned $($seen.Compilers.Count) compiler process(es). This is " ++ "the chain that was blocked in the field: a windowless PowerShell launching " ++ "csc.exe and dropping a DLL in TEMP. Declare native methods with " ++ "New-StudioEmittedNativeType.")}if ($seen.TempLibraries) {$seen.TempLibraries | ForEach-Object { Write-Host "TEMP DLL: $_" }- throw ("the installer wrote {0} DLL(s) into a temporary directory. Even without a " +- "compiler process this is the artefact half of the same shape. Cleaning one " +- "up does not clear it: the watcher records the creation." -f `- $seen.TempLibraries.Count)+ throw ("the installer left $($seen.TempLibraries.Count) compiler artefact(s) in a " ++ "temporary directory. Even without a compiler process this is the artefact " ++ "half of the same shape. Cleaning one up does not clear it: the watcher " ++ "records the creation.")}Write-Host "no compiler, no temporary DLL"@@ -189,10 +199,18 @@ jobs:# void, not clean.$desktop = {Remove-Item Env:\UNSLOTH_STUDIO_HOME -ErrorAction SilentlyContinue+ # Same reason as the shell leg, and this leg needs it more: it deliberately+ # does NOT gate on exit 0, yet a single stderr line from the child raised+ # NativeCommandError under 'Stop' and failed the step anyway. The observed+ # one was "[TAURI:ERROR_CLEAR] create virtual environment recovered", which+ # is the installer reporting that it recovered.+ $outer = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'& powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass `-File "$env:GITHUB_WORKSPACE\install.ps1" --tauri --local --no-torch *>&1 |Tee-Object -FilePath "$env:UNSLOTH_EVIDENCE\install-tauri.log"$exit = $LASTEXITCODE+ $ErrorActionPreference = $outer$global:LASTEXITCODE = 0# Not gated on exit 0: a desktop-mode install can decline for unrelated# reasons, and the question is only whether a compiler ran on the way.diff --git a/scripts/scan_packages_baseline.json b/scripts/scan_packages_baseline.jsonindex 067b3aa686a..869934f24ab 100644--- a/scripts/scan_packages_baseline.json+++ b/scripts/scan_packages_baseline.json@@ -1836,6 +1836,65 @@"severity": "CRITICAL","evidence": "L461: while True: sha256:a8f95a987a45a8eb67ee78dd9d98674c7b88c97e7722f63dd446f77e3dcfe0e7","evidence_hash": "20a717b5faac68b3a57b11859f90d21959c29302e413bf3cd36e1263ccfbb00b"+ },+ {+ "package": "scikit-learn",+ "file": "sklearn/datasets/_openml.py",+ "check": "C2 polling/beaconing loop detected",+ "severity": "CRITICAL",+ "evidence": "L122: while True: sha256:8b044e656cc30b7456c66ef639158ba5712db35847626e17339ee55d16b2eb3f",+ "evidence_hash": "e7232e73f5faaeca3e5bd26f5096ddbf20ece6787c3c92ba9fc903f9a167621a",+ "file_sha256": "f70fbb46f8523a1eadf67bac45d5a0fb8ffae9762b43964cfb0db0729d76e543"+ },+ {+ "package": "scikit-learn",+ "file": "sklearn/externals/array_api_compat/cupy/__init__.py",+ "check": "Downloads and executes remote code",+ "severity": "CRITICAL",+ "evidence": "L12: __import__(__spec__.parent + '.linalg') | L13: __import__(__spec__.parent + '.fft')",+ "evidence_hash": "2602c1c446ee242b8222f1f7e0a2edbeb7d951ca7c734de66fd03f3a538fda59"+ },+ {+ "package": "scikit-learn",+ "file": "sklearn/externals/array_api_compat/dask/array/__init__.py",+ "check": "Downloads and executes remote code",+ "severity": "CRITICAL",+ "evidence": "L16: __import__(__spec__.parent + '.linalg') | L17: __import__(__spec__.parent + '.fft')",+ "evidence_hash": "2602c1c446ee242b8222f1f7e0a2edbeb7d951ca7c734de66fd03f3a538fda59"+ },+ {+ "package": "scikit-learn",+ "file": "sklearn/externals/array_api_compat/numpy/__init__.py",+ "check": "Downloads and executes remote code",+ "severity": "CRITICAL",+ "evidence": "L22: __import__(__spec__.parent + \".linalg\") | L24: __import__(__spec__.parent + \".fft\")",+ "evidence_hash": "29ea7226545670c67c75aaf06bb2763a2b5199076ce62728fbe5c25b1bb08606"+ },+ {+ "package": "scikit-learn",+ "file": "sklearn/externals/array_api_compat/torch/__init__.py",+ "check": "Downloads and executes remote code",+ "severity": "CRITICAL",+ "evidence": "L13: __import__(__spec__.parent + '.linalg') | L14: __import__(__spec__.parent + '.fft')",+ "evidence_hash": "2602c1c446ee242b8222f1f7e0a2edbeb7d951ca7c734de66fd03f3a538fda59"+ },+ {+ "package": "unsloth-zoo",+ "file": "unsloth_zoo/compiler.py",+ "check": "Advanced obfuscation (marshal/compile/zlib) + exec/eval",+ "severity": "HIGH",+ "evidence": "Obfusc: L1496: _mod = __import__(model_location, fromlist=items) | L5835: f\" {chr(92)}{chr(92)} /| Num examples = {num_examples:,} | Num Epochs = {num_train_epochs:,} | Total steps = {max_steps:,}\\\\n\"\\\\\nL5836: f\"O^O/ {chr(92)}_/ {chr(92)} Batch size per device = {self._train_batch_size:,} | Gradient accumulation steps = {args.gradient_accumulation_steps}\\\\n\"\\\\\nL5837: f\"{chr(92)} / Data Parallel GPUs = {args.world_size} | Total batch size ({self._train_batch_size} x {args.gradient_accumulation_steps} x {args.world_size}) = {total_train_batch_size: sha256:b7ea9cdbe360ad323911014caf12a9d4ec87cb36195a511080e4e484c2fb80d2\nL5838: f' \"-____-\" Trainable parameters = {get_model_param_count(model, trainable_only=True):,} of {get_model_param_count(model):,} ({get_model_param_count(model, trainable_only=True)/get_model_p sha256:9e832c1e7b2815aa44dc42638d821cb9df22550db88d85bd4bfb29c13f984b53 | L5836: f\"O^O/ {chr(92)}_/ {chr(92)} Batch size per device = {self._train_batch_size:,} | Gradient accumulation steps = {args.gradient_accumulation_steps}\\\\n\"\\\\\nL5837: f\"{chr(92)} / Data Parallel GPUs = {args.world_size} | Total batch size ({self._train_batch_size} x {args.gradient_accumulation_steps} x {args.world_size}) = {total_train_batch_size: sha256:b7ea9cdbe360ad323911014caf12a9d4ec87cb36195a511080e4e484c2fb80d2\nL5838: f' \"-____-\" Trainable parameters = {get_model_param_count(model, trainable_only=True):,} of {get_model_param_count(model):,} ({get_model_param_count(model, trainable_only=True)/get_model_p sha256:9e832c1e7b2815aa44dc42638d821cb9df22550db88d85bd4bfb29c13f984b53 | L5835: f\" {chr(92)}{chr(92)} /| Num examples = {num_examples:,} | Num Epochs = {num_train_epochs:,} | Total steps = {max_steps:,}\\\\n\"\\\\\nL5836: f\"O^O/ {chr(92)}_/ {chr(92)} Batch size per device = {self._train_batch_size:,} | Gradient accumulation steps = {args.gradient_accumulation_steps}\\\\n\"\\\\\nL5837: f\"{chr(92)} / Data Parallel GPUs = {args.world_size} | Total batch size ({self._train_batch_size} x {args.gradient_accumulation_steps} x {args.world_size}) = {total_train_batch_size: sha256:b7ea9cdbe360ad323911014caf12a9d4ec87cb36195a511080e4e484c2fb80d2\nExec: L1425: _modeling_file = eval(model_location) | L2131: f = eval(f\"{model_location}.{module}\") | L2461: exec(f\"def raise_{j}(*args, **kwargs): print('{function}')\", globals(), locals()) | L2462: try: exec(f\"EMPTY_LOGITS.{function} = raise_{j}\", globals(), locals()) | L3887: exec(f\"import {parent}\", locals(), globals()) | L4018: dir(eval(parent)), | L4022: exec(f\"{parent}.{child}.forward = forward\", globals(), locals()) | L4096: module = eval(f\"modeling_file.{module}\") | L4123: inner_class = eval(f\"modeling_file.{inner_class}\") | L4253: exec(f\"from timm.layers.norm_act import {norm}\") | L4261: forward = eval(norm).forward | L4267: exec(f\"timm.layers.norm_act.{norm}.forward = forward\") | L4284: exec(f\"from timm.models._efficientnet_blocks import {block}\") | L4292: forward = eval(block).forward | L4298: exec(f\"timm.models._efficientnet_blocks.{block}.forward = forward\") | L4532: exec(\nL4533: f\"{model_location}.torch.nn.{module}.forward = forward\",\nL4534: globals(),\nL4535: locals(),\nL4536: ) | L4538: exec(f\"{model_location}.nn.{module}.forward = forward\", globals(), locals()) | L4542: exec(\nL4543: f\"combined_module.torch.nn.{module}.forward = forward\",\nL4544: globals(),\nL4545: locals(),\nL4546: ) | L4548: exec(f\"combined_module.nn.{module}.forward = forward\", globals(), locals()) | L4625: source = eval(f\"{model_location}.torch\") | L4632: function = eval(f\"source.nn.{module}\") | L4826: exec(\"import transformers\", globals()) | L4839: exec(\nL4840: \"model_logger.addFilter(HideLoggingMessage('`use_cache`'))\", globals(), locals()\nL4841: ) | L4843: exec(\nL4844: \"model_logger.addFilter(HideLoggingMessage('compile_config'))\",\nL4845: globals(),\nL4846: locals(),\nL4847: ) | L5081: source = eval(f\"modeling_file.{module}\") | L5095: source = eval(f\"modeling_file.{module}\") | L5196: source = eval(f\"modeling_file.{module}\") | L5234: source = eval(f\"{model_location}.{module}\") | L5314: source = eval(f\"{model_location}.{module}\") | L5362: source = eval(f\"{model_location}.{module}\") | L5598: source = eval(f\"{model_location}.{module}\") | L5609: exec(\nL5610: f\"{model_location}.{module}._update_causal_mask = no_update_causal_mask\",\nL5611: globals(),\nL5612: ) | L5675: source = eval(f\"{model_location}.{module}\") | L5716: module_cls = eval(f\"{model_location}.{module}\") | L5753: module_cls = eval(f\"{model_location}.{module}\") | L5820: exec(\nL5821: \"from transformers.trainer import (\" + \", \".join(x for x in good_items) + \")\",\nL5822: globals(),\nL5823: ) | L5885: exec(inner_training_loop, globals()) | L5893: function = eval(f\"{model_location}.{module}\") | L5974: function = eval(f\"{model_location}.{module}\") | L6115: exec(\nL6116: f\"{model_location}.{module} = combined_module.{module}\",\nL6117: globals(),\nL6118: locals(),\nL6119: ) | L6129: check_dicts = dir(eval(f\"{model_location}\")) | L6131: item = eval(f\"{model_location}.{check}\") | L6141: exec(\nL6142: f\"{model_location}.{check}['{key}'] = combined_module.{replaced_class}\",\nL6143: globals(),\nL6144: locals(),\nL6145: )",+ "evidence_hash": "bdfae4c24572c2a86fa6a2dede720ebb0723746963e43c2cd42701de5fc48fdb",+ "file_sha256": "5e14926abb64b32ca68139938e8b745c7a4d352324dd18c7a3d9a70eed56a15c"+ },+ {+ "package": "unsloth-zoo",+ "file": "unsloth_zoo/mlx/loader.py",+ "check": "Advanced obfuscation (marshal/compile/zlib) + exec/eval",+ "severity": "HIGH",+ "evidence": "Obfusc: L4662: _mod = __import__(module_name, fromlist=[\"_\"])\nExec: L157: mx.eval(model.parameters()) | L191: mx.eval([v for k, v in tree_flatten(casted) if is_mlx_norm_parameter_path(k)]) | L1170: mx.eval(model.parameters()) | L1171: mx.eval(mx.distributed.all_sum(mx.array(1.0), stream=mx.cpu)) | L1238: mx.eval(model.parameters()) | L1241: mx.eval(mx.distributed.all_sum(mx.array(1.0), stream=mx.cpu)) | L2576: mx.eval(altup.correct(predictions, activated)) | L3017: mx.eval(baseline, perturbed) | L4310: model.eval() | L5049: mx.eval(model.parameters()) | L5164: mx.eval(module.weight) | L8557: lambda: mx.eval(model.parameters()), | L8617: lambda: mx.eval(model.parameters()), | L8770: mx.eval(model.parameters())",+ "evidence_hash": "cf9c8ed7bf9c33f83b6280d7d2d60b072262a04ce3e886a1f38c4003fbef01f4",+ "file_sha256": "d18e7eb087b09c360d02d6e274e92cca153768e8a8b61bc978e2a40f1981043d"}]}diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.pyindex e9acb94b78d..93e14a60f65 100644--- a/studio/backend/core/inference/tool_call_parser.py+++ b/studio/backend/core/inference/tool_call_parser.py@@ -951,15 +951,56 @@ def _only_a_code_fence(between: str) -> bool:_FENCE_ONLY_RE = re.compile(r"[\w.\-]*[ \t]*\n?[ \t]*`{3,}[a-zA-Z0-9_+-]*")+# Cap on the NON-BLANK part of the gap between a wrapper marker and its object, which is the+# only part ``_only_a_code_fence`` decides on: a name, an optional newline, backticks and a+# language tag. This is orders of magnitude more than a fence can be, so the cap only refuses+# what was never one. The blank part is unbounded, as it is in real output, and is answered+# without reading it. Capping the RAW gap instead would have refused a genuine fence trailed by+# blank space, and refusing wrongly is not free: an untrusted wrapper body gets masked, which is+# how a tool ends up receiving a run of U+E000 in place of the model's text.+_MAX_FENCE_CHARS = 4096++def _inference_wrapper_spans(text: str) -> list:"""Spans covering the argument object of each inference-only wrapped call."""spans: list = []for opener in _INFERENCE_WRAPPER_OPENERS:pos = text.find(opener)+ brace = -2 # Not yet sought. Distinct from -1, which means there is none left.+ # The gap with its blank ends removed, as ``_only_a_code_fence`` would strip it. Held+ # as indices so the gap is never copied; both walks stop at the first non-blank, and+ # the runs they cross are disjoint across distinct braces, so they cost nothing+ # amortised. Recomputed only when the brace or the opener moves past them.+ core_end = 0+ core_start = -1while pos != -1:- brace = text.find("{", pos + len(opener))+ after = pos + len(opener)+ # The next ``{`` is re-sought only once the last one falls behind this opener.+ # Both indices only move forward, so the whole loop reads the text once instead+ # of once per opener. Seeking per opener is quadratic on a body that is all+ # opener and no object, which is what+ # ``test_deepseek_r1_huge_fenceless_body_is_linear`` measures.+ if brace != -1 and brace < after:+ brace = text.find("{", after)+ core_end = brace+ while core_end > 0 and text[core_end - 1].isspace():+ core_end -= 1+ core_start = -1+ # None at or after this opener means none at or after any later one either.+ if brace == -1:+ break# Only the object that follows the marker directly; anything else is not its body.- if brace != -1 and _only_a_code_fence(text[pos + len(opener) : brace]):+ if core_end <= after:+ trusted = True # Blank all the way to the object, however long.+ else:+ if core_start < after:+ core_start = after+ while core_start < core_end and text[core_start].isspace():+ core_start += 1+ trusted = core_end - core_start <= _MAX_FENCE_CHARS and _only_a_code_fence(+ text[core_start:core_end]+ )+ if trusted:end = _balanced_brace_end(text, brace)if end is not None:spans.append((pos, end + 1))diff --git a/studio/backend/tests/data/refactor_guard/ast_inventory.json b/studio/backend/tests/data/refactor_guard/ast_inventory.jsonindex 5b03f960ec0..3944ad2730f 100644--- a/studio/backend/tests/data/refactor_guard/ast_inventory.json+++ b/studio/backend/tests/data/refactor_guard/ast_inventory.json@@ -1487,6 +1487,9 @@"_MARKUP_OPENERS": {"kind": "assign"},+ "_MAX_FENCE_CHARS": {+ "kind": "assign"+ },"_MAX_GEMMA_PREFIX_TAIL": {"kind": "assign"},diff --git a/studio/backend/tests/data/refactor_guard/runtime_inventory.json b/studio/backend/tests/data/refactor_guard/runtime_inventory.jsonindex 1d52aad4036..c990b9b26fd 100644--- a/studio/backend/tests/data/refactor_guard/runtime_inventory.json+++ b/studio/backend/tests/data/refactor_guard/runtime_inventory.json@@ -78,6 +78,7 @@"_LLAMA3_WS_RE","_MARKERLESS_TRUSTED_PREFIXES","_MARKUP_OPENERS",+ "_MAX_FENCE_CHARS","_MAX_GEMMA_PREFIX_TAIL","_MISTRAL_ARGS_MARKER","_MISTRAL_CALL_ID_MARKER",diff --git a/studio/backend/tests/test_pr5624_regressions.py b/studio/backend/tests/test_pr5624_regressions.pyindex 642cd9f5b55..edc13de474c 100644--- a/studio/backend/tests/test_pr5624_regressions.py+++ b/studio/backend/tests/test_pr5624_regressions.py@@ -222,46 +222,92 @@ def test_kimi_bare_counter_id_is_dropped():# DeepSeek truncated mid-stream-def test_deepseek_v3_1_huge_truncated_body_is_linear():- """Adversarial input: DeepSeek envelope with no JSON brace and a- 50k-char body. A regex-based ``[^\\n<]+?`` name capture is O(N^2)- here; the parser uses ``str.find`` on the sep marker so it stays- linear. Budget 1s to flag any future regression."""+def _growth(+ build,+ units: int,+ factor: int = 4,+ repeats: int = 3,+) -> tuple[float, float, list]:+ """How much more `factor` times the input costs. Returns (ratio, big_seconds, big_result).++ Best-of-`repeats` at each size, not a mean: contention on a shared runner only ever ADDS+ time, so the minimum is the closest each size gets to its own true cost, and dividing one+ minimum by the other cancels the machine out.++ This replaces an absolute ``elapsed < 1.0`` budget at one size. That budget read 0.20s on+ a quiet runner and 1.41s on a busy one, so it failed for the wrong reason on unrelated+ PRs, and it also sat close enough to the line that a REAL regression (#10507, which made+ the R1 path quadratic again) only tipped it over some of the time. A ratio answers the+ question these tests are named for: linear is ~`factor`, quadratic is ~`factor ** 2`.+ """import time as _time- text = "<|tool▁calls▁begin|><|tool▁call▁begin|>fn<|tool▁sep|>" + "x" * 50_000- start = _time.time()- calls = parse_tool_calls_from_text(text)- elapsed = _time.time() - start- assert elapsed < 1.0, f"V3 path is non-linear: {elapsed:.2f}s"- assert calls == []+ def cost(n: int) -> tuple[float, list]:+ text, best, result = build(n), None, None+ for _ in range(repeats):+ start = _time.perf_counter()+ result = parse_tool_calls_from_text(text)+ elapsed = _time.perf_counter() - start+ best = elapsed if best is None else min(best, elapsed)+ return best, result++ small, _ = cost(units)+ big, result = cost(units * factor)+ # A timer's own resolution must not read as superlinear growth on a very fast machine.+ return big / max(small, 1e-4), big, result+++def _assert_linear(+ build,+ label: str,+ units: int,+ *,+ factor: int = 4,+ tolerance: float = 6.0,+):+ """`build(n)` must cost ~`factor`x, not ~`factor ** 2`x, for `factor`x the input."""+ ratio, big, result = _growth(build, units, factor)+ # Backstop: a regression bad enough to make the ratio unmeasurable still has to fail, and+ # fail quickly, rather than run until the job's own timeout kills it with no explanation.+ assert big < 60.0, f"{label} path took {big:.1f}s on {units * factor} units"+ assert ratio < tolerance, (+ f"{label} path is not linear: {factor}x the input cost {ratio:.1f}x the time "+ f"(linear is ~{factor}, quadratic is ~{factor ** 2})"+ )+ return result+++def test_deepseek_v3_1_huge_truncated_body_is_linear():+ """Adversarial input: DeepSeek envelope with no JSON brace and a long+ body. A regex-based ``[^\\n<]+?`` name capture is O(N^2) here; the+ parser uses ``str.find`` on the sep marker so it stays linear."""+ build = lambda n: "<|tool▁calls▁begin|><|tool▁call▁begin|>fn<|tool▁sep|>" + "x" * n+ assert _assert_linear(build, "V3", 50_000) == []def test_deepseek_r1_huge_fenceless_body_is_linear():"""R1 detection used a greedy ``([^\\n]+)\\n```json`` regex that is O(N^2) on afence-less body of repeated ``function<sep>`` tokens. The parser now scans with- ``str.find``; budget 1s to flag any regression."""- import time as _time+ ``str.find``."""+ build = lambda n: "<|tool▁calls▁begin|>" + "function<|tool▁sep|>a" * n+ assert _assert_linear(build, "R1", 10_000) == []- text = "<|tool▁calls▁begin|>" + "function<|tool▁sep|>a" * 40_000- start = _time.time()- calls = parse_tool_calls_from_text(text)- elapsed = _time.time() - start- assert elapsed < 1.0, f"R1 path is non-linear: {elapsed:.2f}s"- assert calls == []++def test_deepseek_r1_fenceless_body_with_one_distant_object_is_linear():+ """The same body with a single ``{`` after it, which is the shape that survived the+ first fix for #10507: seeking the next object per marker found one every time and+ rescanned the tail to reach it, so the sweep stayed quadratic while the fence-less+ case above had gone linear."""+ build = lambda n: "<|tool▁calls▁begin|>" + "function<|tool▁sep|>a" * n + '{"a": 1}'+ _assert_linear(build, "R1 distant-object", 10_000)def test_glm_unclosed_body_many_arg_keys_is_linear():"""An unclosed GLM ``<tool_call>`` body runs to EOF; a lazy-group ``finditer``over many bare ``<arg_key>`` tokens was O(N^2). The parser now walks pairs with- ``str.find``; budget 1s."""- import time as _time-- text = "<tool_call>foo\n" + "<arg_key>k" * 40_000- start = _time.time()- parse_tool_calls_from_text(text)- elapsed = _time.time() - start- assert elapsed < 1.0, f"GLM path is non-linear: {elapsed:.2f}s"+ ``str.find``."""+ build = lambda n: "<tool_call>foo\n" + "<arg_key>k" * n+ _assert_linear(build, "GLM", 10_000)def test_deepseek_r1_fenced_json_parses():diff --git a/studio/frontend/tests/media-status-sequencing.test.ts b/studio/frontend/tests/media-status-sequencing.test.tsindex 01c3333420c..61de0a6ca2d 100644--- a/studio/frontend/tests/media-status-sequencing.test.ts+++ b/studio/frontend/tests/media-status-sequencing.test.ts@@ -21,15 +21,81 @@ const PAGES = [["video", "features/video/video-page.tsx", "getVideoStatus", "unloadVideoModel"],] as const;+/** The argument list of `const NAME = useCallback(...)`, parentheses balanced. */+function callbackBody(source: string, name: string): string {+ const declaration = `const ${name} = useCallback`;+ const at = source.indexOf(declaration);+ assert.ok(at >= 0, `${name} is not declared as a useCallback`);+ const start = source.indexOf("(", at + declaration.length);+ let depth = 0;+ for (let i = start; i < source.length; i += 1) {+ if (source[i] === "(") depth += 1;+ else if (source[i] === ")") {+ depth -= 1;+ if (depth === 0) return source.slice(start + 1, i);+ }+ }+ assert.fail(`${name}'s callback never closes`);+}+for (const [name, path, read, unload] of PAGES) {test(`the ${name} page lets only the newest status read write`, () => {const page = readSrc(path);assert.match(page, /const statusTicket = useRef\(0\);/);- assert.match(- page,- /if \(ticket === statusTicket\.current\) setStatus\(next\);/,- "a superseded read must not write",+ // Read the GUARD, not the one line that spelled it. #10788 rewrote this as an early+ // return, which admits exactly the same reads, and the exact-text form went red over a+ // refactor that changed nothing. Both spellings are checked against the callback's own+ // body, so a guard that lives somewhere else in the file cannot stand in for it.+ const body = callbackBody(page, "setStatusIfNewest");+ const write = body.indexOf("setStatus(");+ assert.notEqual(write, -1, "setStatusIfNewest no longer writes the status");+ const held = /if\s*\(\s*ticket\s*===\s*statusTicket\.current\s*\)[\s{]*setStatus\(/.exec(body);+ // The stale branch's return must be BARE. `return setStatus(next);` also reads as an+ // early return and also precedes the normal write, while writing the superseded+ // status out of the return expression itself.+ const early = /if\s*\(\s*ticket\s*!==\s*statusTicket\.current\s*\)[\s{]*return\s*(?:[;}]|\r?\n)/.exec(+ body,+ );+ const guard = held ?? early;+ assert.ok(guard, "a superseded read must not write");+ // Ordering, not just presence. Either spelling can be present while the write happens+ // FIRST, and `setStatus(next); if (ticket !== statusTicket.current) return;` has already+ // published the superseded status by the time it returns, which is the whole bug.+ assert.ok(+ guard.index < write,+ "the ticket guard must come before the status write, not after it",+ );+ // And there is only the one write. Guarding the first while a second sits unguarded+ // after it leaves every stale response overwriting the status, which is the same bug+ // with an extra line in front of it.+ assert.equal(+ (body.match(/setStatus\(/g) ?? []).length,+ 1,+ "setStatusIfNewest must write the status exactly once, under the ticket guard",);+ // Ordering says the write comes after the early return. It does not say the write is+ // still REACHED: `if (ticket !== current) { return; setStatus(next); }` returns first+ // and satisfies every rule above while never publishing anything. So when the stale+ // branch has a block of its own, the write has to live past the end of it. The+ // `ticket === current` spelling needs no such rule, since its regex ties the write to+ // the guard directly.+ if (early && !held && /\{/.test(early[0])) {+ const open = body.indexOf("{", early.index);+ let depth = 0;+ let close = -1;+ for (let i = open; i < body.length; i += 1) {+ if (body[i] === "{") depth += 1;+ else if (body[i] === "}") {+ depth -= 1;+ if (depth === 0) {+ close = i;+ break;+ }+ }+ }+ assert.notEqual(close, -1, "the stale branch never closes");+ assert.ok(write > close, "the status write is stranded inside the stale branch");+ }// Every writer goes through it, so none can be the one that slips past.assert.doesNotMatch(page,diff --git a/tests/studio/_js_source.py b/tests/studio/_js_source.pyindex fd9c4ea715b..8a654be2626 100644--- a/tests/studio/_js_source.py+++ b/tests/studio/_js_source.py@@ -19,6 +19,7 @@ that appear in the files these tests actually read, and fails loudly rather thanwhen it meets something it cannot represent."""+import itertoolsimport re@@ -171,22 +172,144 @@ def assert_guard_holds()-def binding_joining(source: str, operator: str, required: set[str]) -> str | None:- """Name of the first `const NAME = ...` whose operands cover `required`, else None.+# A line ending in one of these is a declaration still in progress, not one that ended+# where the newline is. Prettier breaks a long `a &&\n b` exactly there.+_CONTINUES = ("&&", "||", "??", "?", ":", ",", "+", "-", "*", "/", "=", "(", "[", "{", ".")+++def _declaration_bodies(source: str):+ """Each `const NAME = <body>` in `source`, as `(name, body)` read from the original.Declarations are LOCATED in the blanked source, so a commented-out or quoted copycannot answer, and then READ from the original at the same offsets, because blankingis length-preserving. Reading the blanked text instead would be self-defeating here:it empties string literals, and `status === "running"` is a required operand.++ The terminator is a `;` at bracket depth zero OR an end of line that closes the+ expression, because this codebase does not write semicolons everywhere: `sidebar.tsx`+ has exactly one in 500 lines, so a semicolon-only scan found no declarations at all in+ it and answered None for a binding that was plainly there. A newline alone is not+ enough either, since a wrapped expression has newlines inside it, so a line only ends a+ declaration when its brackets are balanced and it does not trail an operator."""blanked = blank_literals_and_comments(source)- for match in re.finditer(r"const (\w+) =([^;]*);", blanked):- operand_text = source[match.start(2) : match.end(2)]- if required <= set(split_operands(re.sub(r"\s+", " ", operand_text), operator)):- return match.group(1)+ for match in re.finditer(r"\bconst (\w+)\s*=(?!=)", blanked):+ i, depth, n = match.end(), 0, len(blanked)+ while i < n:+ char = blanked[i]+ if char in "([{":+ depth += 1+ elif char in ")]}":+ if depth == 0:+ break+ depth -= 1+ elif depth == 0 and char == ";":+ break+ elif depth == 0 and char == "\n":+ so_far = blanked[match.end() : i].rstrip()+ if so_far and not so_far.endswith(_CONTINUES):+ break+ i += 1+ yield match.group(1), source[match.end() : i]+++def binding_joining(source: str, operator: str, required: set[str]) -> str | None:+ """Name of the first `const NAME = ...` whose operands cover `required`, else None."""+ for name, body in _declaration_bodies(source):+ if required <= set(split_operands(re.sub(r"\s+", " ", body), operator)):+ return namereturn None+def expand_bindings(+ source: str,+ expression: str,+ *,+ stop = (),+ limit: int = 8,+) -> str:+ """`expression` with every local `const NAME = ...` it names inlined, transitively.++ Operand presence answers "is this condition still consulted". It cannot answer "does+ this condition still mean the same thing", because a named binding can be given a new+ exception without the name at the call site changing at all. Inlining gets back to the+ primitives so the caller can ask about the resulting behaviour instead.++ `stop` names the primitives to inline DOWN TO. Without it the walk keeps going past+ them: `hasPinMode` is itself a const somewhere up the file, and expanding it too drags+ in the prop plumbing that decides whether pin mode exists, which is a different+ contract belonging to a different component.+ """+ bodies = {+ name: re.sub(r"\s+", " ", body).strip()+ for name, body in _declaration_bodies(source)+ if name not in stop+ }+ for _ in range(limit):+ grown = re.sub(+ r"\b\w+\b",+ lambda match: f"({bodies[match.group(0)]})"+ if match.group(0) in bodies+ else match.group(0),+ expression,+ )+ if grown == expression:+ return expression+ expression = grown+ raise AssertionError(f"{expression!r} never stopped expanding; a binding cycle?")+++def boolean_table(expression: str, names) -> dict:+ """Every value a purely boolean JS expression takes over `names`, keyed by assignment.++ For contracts about WHEN something happens rather than how it is written. Two spellings+ that admit exactly the same states have the same table, so a rename, a rewrap or a+ hoisted const is invisible here, while an exception that is dropped or inverted is not.++ Only `&& || ! ( )`, names and `undefined` are accepted. Anything else (a comparison, a+ ternary, a call) raises rather than being silently mistranslated: `!==` would otherwise+ become `not ==` and read as valid Python for a moment.+ """+ python = re.sub(r"\bundefined\b", "False", expression)+ python = python.replace("&&", " and ").replace("||", " or ").replace("!", " not ")+ leftover = re.sub(r"\b(?:and|or|not|False)\b|[()\s]|\b[A-Za-z_]\w*\b", "", python)+ assert not leftover, f"{expression!r} is not a plain boolean expression: {leftover!r} left"+ reads = set(re.findall(r"\b[A-Za-z_]\w*\b", python)) - {"and", "or", "not", "False"}+ assert reads <= set(+ names+ ), f"{expression!r} reads names this contract does not cover: {sorted(reads - set(names))}"+ table = {}+ for combination in itertools.product((False, True), repeat = len(names)):+ table[combination] = bool(+ eval(python, {"__builtins__": {}}, dict(zip(names, combination))) # noqa: S307+ )+ return table+++def attribute_expressions(source: str, attribute: str) -> list[str]:+ """Each `attribute={...}` expression in `source`, braces balanced, whitespace collapsed.++ For contracts about what an attribute is WIRED TO rather than how it is spelled. Located+ in the blanked source so a mention in a comment or a string cannot answer, and read back+ from the original so a literal inside the expression survives.+ """+ blanked = blank_literals_and_comments(source)+ found = []+ for match in re.finditer(rf"(?<![\w-]){re.escape(attribute)}\s*=\s*{{", blanked):+ depth, i = 0, match.end() - 1+ while i < len(blanked):+ char = blanked[i]+ if char == "{":+ depth += 1+ elif char == "}":+ depth -= 1+ if depth == 0:+ found.append(re.sub(r"\s+", " ", source[match.end() : i]).strip())+ break+ i += 1+ return found++def gates_the_markup(source: str, name: str) -> bool:"""True when `name` conditions mounted markup, by `&&` or by a ternary's TRUE arm.diff --git a/tests/studio/playwright_find_in_page.py b/tests/studio/playwright_find_in_page.pyindex 73145d53f59..dd752ffe89c 100644--- a/tests/studio/playwright_find_in_page.py+++ b/tests/studio/playwright_find_in_page.py@@ -16,6 +16,7 @@ import sysimport timefrom pathlib import Path+from playwright.sync_api import TimeoutError as PlaywrightTimeoutfrom playwright.sync_api import sync_playwrightsys.path.insert(0, str(Path(__file__).resolve().parent))@@ -109,9 +110,29 @@ def open_bar(page, mod: str) -> None:)+def settle(+ page,+ condition: str,+ *,+ timeout: int = 10000,+) -> None:+ """Give `condition` until `timeout` to hold, and do not fail here if it never does.++ A flat sleep before reading the state asserts the runner's speed alongside the+ behaviour, and a busy runner failed the chord re-focus check on a build that only+ touched a PowerShell script. Waiting on the condition lets a slow machine take its+ time, while a genuinely broken one spends the timeout and then fails on the SAME check+ with the same message, so nothing is swallowed here.+ """+ try:+ page.wait_for_function(condition, timeout = timeout)+ except PlaywrightTimeout:+ pass++def close_bar(page) -> None:page.keyboard.press("Escape")- page.wait_for_timeout(250)+ settle(page, "() => !window.__findSmoke.state().open")def check_chord(page, engine: str, mode: str, mod: str) -> None:@@ -134,7 +155,10 @@ def check_chord(page, engine: str, mode: str, mod: str) -> None:state(page).get("focused") is False,)page.keyboard.press(f"{mod}+f")- page.wait_for_timeout(200)+ settle(+ page,+ "() => { const s = window.__findSmoke.state(); return s.open && s.focused; }",+ )check(engine,mode,diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pyindex 332eb8f01e4..a2378a71c71 100644--- a/tests/studio/test_desktop_reliability_frontend_contract.py+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -5,7 +5,13 @@import refrom pathlib import Path-from tests.studio._js_source import binding_joining, gates_the_markup+from tests.studio._js_source import (+ attribute_expressions,+ binding_joining,+ boolean_table,+ expand_bindings,+ gates_the_markup,+)REPO = Path(__file__).resolve().parents[2]@@ -676,8 +682,28 @@ def test_tauri_collapse_removes_the_icon_rail_but_web_keeps_it():assert offset is not None and offset > 0, (name, values)assert titlebar is not None, (name, values)assert offset + button <= titlebar, (name, offset, button, titlebar)- assert "aria-hidden={(hasPinMode && !pinned && collapseToZero) || undefined}" in primitive- assert "inert={(hasPinMode && !pinned && collapseToZero) || undefined}" in primitive+ # Read the CONDITION, not the text that spells it. The exact-string form this replaces+ # pinned the inlined expression, so #10706 broke it by hoisting that expression into a+ # named const and giving it a peek exception: a refactor that changed nothing this+ # contract protects, and it left main and every open PR red for a day. What must hold is+ # that a sidebar collapsing to nothing leaves the accessibility tree, and that it goes+ # inert on exactly the same condition, since hidden-but-focusable is the actual bug.+ hidden = attribute_expressions(primitive, "aria-hidden")+ inert = attribute_expressions(primitive, "inert")+ assert len(hidden) == 1 and len(inert) == 1, (hidden, inert)+ assert hidden == inert, (hidden, inert)+ # Asking only that the held-out condition still appears would accept dropping the peek+ # exception with it, and a peeked sidebar is on screen: aria-hidden on a visible panel+ # is the same defect this guards, pointing the other way. So state WHEN the panel leaves+ # the accessibility tree, over every combination of the four inputs, and let any+ # spelling that admits exactly those states pass.+ inputs = ("hasPinMode", "pinned", "collapseToZero", "peeking")+ table = boolean_table(expand_bindings(primitive, hidden[0], stop = inputs), inputs)+ for combination, removed in table.items():+ has_pin_mode, is_pinned, collapses_to_zero, is_peeking = combination+ assert removed == (+ has_pin_mode and not is_pinned and collapses_to_zero and not is_peeking+ ), (combination, hidden[0])def test_fixed_sheets_start_below_the_custom_titlebar():diff --git a/tests/studio/test_installer_av_shapes.py b/tests/studio/test_installer_av_shapes.pyindex 1f869d67f37..26e4666df8d 100644--- a/tests/studio/test_installer_av_shapes.py+++ b/tests/studio/test_installer_av_shapes.py@@ -313,11 +313,43 @@ def test_a_ci_lane_fails_when_a_compiler_actually_runs() -> None:_WATCHER = REPO / ".github" / "scripts" / "Watch-ForCompiler.ps1"+# The .NET host tearing itself down, as opposed to the script under test deciding something.+# Seen on a hosted runner as `System.IO.FileLoadException: The given assembly name was+# invalid.` out of AssemblyName.ParseAsAssemblySpec, followed by "The PowerShell process will+# exit" and SIGABRT, on a probe that passes everywhere else and had no assembly of its own.+_PWSH_HOST_FAULT = (+ "An error has occurred that was not properly handled",+ "System.IO.FileLoadException",+ "Unhandled exception.",+)+++def _run_pwsh(script: Path, *, timeout: int):+ """Run `script` under pwsh, skipping rather than failing when the HOST aborts.++ Only an abnormal termination is forgiven, and only with a fault banner on stderr to back+ it up: a clean non-zero exit, or the wrong answer on stdout, is the script under test+ being wrong and still fails. Retried once first, because the fault has never repeated.+ """+ command = ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(script)]+ for attempt in range(2):+ result = subprocess.run(command, capture_output = True, text = True, timeout = timeout)+ crashed = result.returncode < 0 and any(+ marker in result.stderr for marker in _PWSH_HOST_FAULT+ )+ if not crashed:+ return result+ if attempt:+ pytest.skip(f"pwsh host aborted ({result.returncode}): {result.stderr.strip()[:400]}")+ raise AssertionError("unreachable")++_FAKE_EVENTS = r"""function New-FakeEvent {- param([string]$Image, [string]$CommandLine)+ param([string]$Image, [string]$CommandLine, [string]$Parent = 'C:\Windows\System32\cmd.exe')$xml = "<Event><EventData>" +"<Data Name='NewProcessName'>$Image</Data>" ++ "<Data Name='ParentProcessName'>$Parent</Data>" +"<Data Name='CommandLine'>$CommandLine</Data>" +"</EventData></Event>"$record = [pscustomobject]@{@@ -363,16 +395,100 @@ def test_the_watcher_scores_the_image_that_ran_not_the_words_in_the_message(),encoding = "utf-8",)- result = subprocess.run(- ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(script)],- capture_output = True,- text = True,- timeout = 120,+ result = _run_pwsh(script, timeout = 120)+ assert result.returncode == 0, result.stderr + result.stdout+ assert f"HITS:{expected}" in result.stdout, result.stdout+++_CSC = r"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe"+_CVTRES = r"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\cvtres.exe"++[email protected](shutil.which("pwsh") is None, reason = "needs PowerShell")+ ("image", "parent", "expected"),+ [+ (_CSC, r"C:\Program Files\PowerShell\7\pwsh.exe", 1),+ (_CVTRES, r"C:\Program Files\PowerShell\7\pwsh.exe", 1),+ (_CVTRES, _CSC, 0),+ ],+ ids = [+ "a-compile-the-shell-started",+ "a-resource-step-with-no-compiler-parent",+ "a-resource-step-the-compiler-started",+ ],+)+def test_a_compiler_started_by_a_compiler_is_one_compile_not_two(+ tmp_path, image: str, parent: str, expected: int+) -> None:+ """csc.exe shells out to cvtres.exe, so a single compile creates two 4688 records and+ scoring both says the action compiled twice.++ It also decides the cross-step bleed the timestamp baseline could not. The Security log+ is written with latency: the positive control's csc.exe started before the installer's+ window opened, its cvtres.exe child landed just inside, and neither was in the log yet+ when the baseline was read, so the subtraction had nothing to subtract and the+ installer was failed for a compile one step earlier.++ A compile the action really starts is still caught, because its ROOT compiler is+ spawned by the installer's shell and the window opens before the action does. That is+ the middle case here: an orphaned resource step with a non-compiler parent still counts.+ """+ script = tmp_path / "probe.ps1"+ script.write_text(+ "\n".join(+ [+ '$ErrorActionPreference = "Stop"',+ f'. "{_WATCHER}"',+ _FAKE_EVENTS,+ f"$e = New-FakeEvent -Image '{image}' -CommandLine 'x' -Parent '{parent}'",+ "$hits = Select-StudioCompilerHits -Events @($e)",+ 'Write-Output "HITS:$($hits.Count)"',+ ]+ ),+ encoding = "utf-8",)+ result = _run_pwsh(script, timeout = 120)assert result.returncode == 0, result.stderr + result.stdoutassert f"HITS:{expected}" in result.stdout, result.stdout[email protected](shutil.which("pwsh") is None, reason = "needs PowerShell")+def test_a_record_with_no_parent_field_is_still_scored(tmp_path) -> None:+ """The whole chain is reported when the schema does not carry ParentProcessName. An+ absent field reads as empty, and empty must not be mistaken for a compiler parent, or a+ log that predates the field would report nothing at all."""+ script = tmp_path / "probe.ps1"+ script.write_text(+ "\n".join(+ [+ '$ErrorActionPreference = "Stop"',+ f'. "{_WATCHER}"',+ # The pre-parent schema: NewProcessName and nothing else.+ "function New-OldEvent {",+ " param([string]$Image)",+ " $xml = \"<Event><EventData><Data Name='NewProcessName'>$Image</Data>\" +",+ ' "</EventData></Event>"',+ " $record = [pscustomobject]@{",+ " TimeCreated = [datetime]'2026-01-01T00:00:00Z'",+ ' Message = "New Process Name: $Image"',+ " }",+ " $body = [scriptblock]::Create(\"return @'`n$xml`n'@\")",+ " return ($record | Add-Member -MemberType ScriptMethod -Name ToXml "+ "-Value $body -PassThru)",+ "}",+ f"$e = New-OldEvent -Image '{_CSC}'",+ "$hits = Select-StudioCompilerHits -Events @($e)",+ 'Write-Output "HITS:$($hits.Count)"',+ ]+ ),+ encoding = "utf-8",+ )+ result = _run_pwsh(script, timeout = 120)+ assert result.returncode == 0, result.stderr + result.stdout+ assert "HITS:1" in result.stdout, result.stdout++_FAKE_WINEVENT = r"""function Get-WinEvent {# Off Windows there is no such cmdlet, so this resolves the call. Empty rather than@@ -406,12 +522,7 @@ def _run_watch(tmp_path, action: str) -> tuple[str, list[str]]:),encoding = "utf-8",)- result = subprocess.run(- ["pwsh", "-NoProfile", "-NonInteractive", "-File", str(script)],- capture_output = True,- text = True,- timeout = 300,- )+ result = _run_pwsh(script, timeout = 300)assert result.returncode == 0, result.stderr + result.stdoutlibraries = [line[len("LIB:") :] for line in result.stdout.splitlines() if line.startswith("LIB:")@@ -447,14 +558,65 @@ def test_the_watcher_sees_intermediates_the_compiler_cleaned_up(tmp_path) -> Non@pytest.mark.skipif(shutil.which("pwsh") is None, reason = "needs PowerShell")def test_the_watcher_still_reports_intermediates_that_were_left_behind(tmp_path) -> None:- """The listing half must keep working; the watcher is added to it, not swapped for it."""+ """The listing half must keep working; the watcher is added to it, not swapped for it.++ A compile that was NOT cleaned up, so the response file is still next to the assembly.+ This asserted a bare ``leftover.dll`` before, which read as "any DLL under TEMP is a+ compiler artefact"; that is the rule the job died on, and it is not what this test is+ for. The vehicle changed, the listing half it checks did not.+ """action = ('$dir = Join-Path $env:TEMP "leftover"; '"New-Item -ItemType Directory -Force -Path $dir | Out-Null; "+ 'Set-Content -LiteralPath (Join-Path $dir "leftover.cmdline") -Value "/noconfig"; ''Set-Content -LiteralPath (Join-Path $dir "leftover.dll") -Value "MZ"')_, libraries = _run_watch(tmp_path, action)assert any(lib.endswith("leftover.dll") for lib in libraries), libraries+ assert any(lib.endswith("leftover.cmdline") for lib in libraries), libraries++[email protected](shutil.which("pwsh") is None, reason = "needs PowerShell")+def test_an_unpacked_archive_is_not_scored_as_a_compile(tmp_path) -> None:+ """What actually ran on every red run of this job.++ The installer unpacks llama.cpp's checksum-verified prebuilt release into a staging+ directory under TEMP, which lands ~25 DLLs there with no compiler anywhere near them.+ The shape under test is ``csc.exe -> %TEMP%\\<random>.dll``; an unpacked archive is a+ different thing and must not read as one, or the job can never pass and stops meaning+ anything.+ """+ action = (+ '$dir = Join-Path $env:TEMP "unsloth-llama-prebuilt-ay5ptbfd"; '+ '$dir = Join-Path $dir "extract-w613j_am"; '+ "New-Item -ItemType Directory -Force -Path $dir | Out-Null; "+ 'foreach ($n in @("ggml.dll", "llama.dll", "mtmd.dll", "ggml-cpu-x64.dll")) { '+ ' Set-Content -LiteralPath (Join-Path $dir $n) -Value "MZ" '+ "}; "+ # A README ships in the archive too, and must stay just as uninteresting.+ 'Set-Content -LiteralPath (Join-Path $dir "LICENSE.txt") -Value "MIT"; '+ "Start-Sleep -Milliseconds 400"+ )+ stdout, libraries = _run_watch(tmp_path, action)+ assert not libraries, f"an unpacked release archive was scored as a compile: {stdout}"++[email protected](shutil.which("pwsh") is None, reason = "needs PowerShell")+def test_a_compile_beside_an_unpacked_archive_is_still_caught(tmp_path) -> None:+ """The narrowing is per-directory, so unpacking an archive cannot cover a real compile."""+ action = (+ '$extract = Join-Path $env:TEMP "unsloth-llama-prebuilt-zz\\extract-zz"; '+ "New-Item -ItemType Directory -Force -Path $extract | Out-Null; "+ 'Set-Content -LiteralPath (Join-Path $extract "ggml.dll") -Value "MZ"; '+ '$compile = Join-Path $env:TEMP "vpmyd5eq"; '+ "New-Item -ItemType Directory -Force -Path $compile | Out-Null; "+ 'Set-Content -LiteralPath (Join-Path $compile "vpmyd5eq.cmdline") -Value "/noconfig"; '+ 'Set-Content -LiteralPath (Join-Path $compile "vpmyd5eq.dll") -Value "MZ"; '+ "Start-Sleep -Milliseconds 400"+ )+ _, libraries = _run_watch(tmp_path, action)+ assert any(lib.endswith("vpmyd5eq.dll") for lib in libraries), libraries+ assert not any(lib.endswith("ggml.dll") for lib in libraries), libraries@pytest.mark.skipif(shutil.which("pwsh") is None, reason = "needs PowerShell")