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
Carry over five temp-scanner fixes that landed after #11217 merged (#11280)
Daniel Han40e94577fb0b
diff --git a/.github/scripts/Watch-ForCompiler.ps1 b/.github/scripts/Watch-ForCompiler.ps1index cda6ec85e03..7f10b1846d5 100644--- a/.github/scripts/Watch-ForCompiler.ps1+++ b/.github/scripts/Watch-ForCompiler.ps1@@ -64,6 +64,41 @@ function Get-StudioTempRoots {return $result}+function Test-StudioPathIsGone {+ <#+ .SYNOPSIS+ Did this enumeration failure mean the directory does not exist, as opposed to could not+ be read?++ .DESCRIPTION+ The distinction decides whether a directory is dropped or recorded as a gap, so it has to+ come from the error itself. Test-Path cannot answer it. Measured under pwsh with+ $ErrorActionPreference = 'Stop':++ missing directory -> ItemNotFoundException, Test-Path returns $false+ denied directory -> Test-Path THROWS "Access to the path ... is denied"++ So probing with Test-Path both mis-answers the ACL case and can raise from inside the+ catch that was meant to contain the failure.++ Fails safe. Anything not positively identified as a missing path is reported as still+ present, which records the directory as unread: over-reporting a gap costs a withheld+ path or a voided run, while under-reporting one silently drops a directory out of the+ comparison, which is the defect this whole file exists to prevent.+ #>+ param([Parameter(Mandatory = $true)]$ErrorRecord)+ $exception = $ErrorRecord.Exception+ while ($null -ne $exception) {+ if ($exception -is [System.Management.Automation.ItemNotFoundException] -or+ $exception -is [System.IO.DirectoryNotFoundException] -or+ $exception -is [System.IO.FileNotFoundException]) {+ return $true+ }+ $exception = $exception.InnerException+ }+ return $false+}+function Get-StudioTempSubtree {<#.SYNOPSIS@@ -132,10 +167,19 @@ function Get-StudioTempSubtree {# A directory that no longer exists is not a gap. It cannot contribute a file to# a later listing of itself, and re-reading a path that raised for any other# reason is how a transient lock gets a second chance.- if (Test-Path -LiteralPath $dir) {- try { $entries = @(Get-ChildItem -LiteralPath $dir -Force -ErrorAction Stop) }- catch { $unread.Add($dir); continue }- } else {+ #+ # Classified from the error, never by probing the path. Test-Path answers $false+ # for a missing directory but THROWS on an ACL-denied one, so probing would both+ # call an unreadable directory deleted - dropping it silently, which is the exact+ # defect this file exists to prevent - and raise from inside the catch meant to+ # contain the failure.+ if (Test-StudioPathIsGone -ErrorRecord $_) { continue }+ try { $entries = @(Get-ChildItem -LiteralPath $dir -Force -ErrorAction Stop) }+ catch {+ # Re-classified rather than assumed: the deletion race can land in the window+ # between the two reads, and recording that as unread would void a run for the+ # ordinary temp deletion this change exists to tolerate.+ if (-not (Test-StudioPathIsGone -ErrorRecord $_)) { $unread.Add($dir) }continue}}@@ -326,11 +370,21 @@ function Start-StudioTempWatch {$identifier = "StudioTempWatch-" + [guid]::NewGuid().ToString('N')$null = Register-ObjectEvent -InputObject $watcher -EventName Created `-SourceIdentifier $identifier+ # The Error event, subscribed for the same reason the buffer was enlarged above. An+ # overflow raises Error and drops the events it could not queue, silently, and a+ # watcher that dropped events is one the caller must not count as covering its root:+ # an artifact can then be missing from the live stream AND from the listing, which+ # reads as a clean run. Without this subscription the failure is not observable at+ # all, so the handle would stay in $watchedRoots looking healthy.+ $errorIdentifier = $identifier + "-error"+ $null = Register-ObjectEvent -InputObject $watcher -EventName Error `+ -SourceIdentifier $errorIdentifier$watcher.EnableRaisingEvents = $true$handles += [pscustomobject]@{- Watcher = $watcher- SourceIdentifier = $identifier- Root = $root+ Watcher = $watcher+ SourceIdentifier = $identifier+ ErrorSourceIdentifier = $errorIdentifier+ Root = $root}} catch {continue@@ -355,6 +409,7 @@ function Stop-StudioTempWatch {Start-Sleep -Milliseconds 750$seen = @()+ $failedRoots = @()foreach ($entry in $Handle) {try { $entry.Watcher.EnableRaisingEvents = $false } catch { }try {@@ -366,10 +421,30 @@ function Stop-StudioTempWatch {Remove-Event -EventIdentifier $record.EventIdentifier -ErrorAction SilentlyContinue}} catch { }+ # Any Error at all condemns the root. There is no partial credit available here: the+ # event carries the exception, not the list of creations it dropped, so a watcher that+ # raised once cannot say what it missed and the caller cannot treat it as covering+ # anything.+ if ($entry.PSObject.Properties['ErrorSourceIdentifier']) {+ try {+ $errors = @(Get-Event -SourceIdentifier $entry.ErrorSourceIdentifier `+ -ErrorAction SilentlyContinue)+ if ($errors.Count -gt 0) { $failedRoots += $entry.Root }+ foreach ($record in $errors) {+ Remove-Event -EventIdentifier $record.EventIdentifier `+ -ErrorAction SilentlyContinue+ }+ } catch { }+ Unregister-Event -SourceIdentifier $entry.ErrorSourceIdentifier `+ -ErrorAction SilentlyContinue+ }Unregister-Event -SourceIdentifier $entry.SourceIdentifier -ErrorAction SilentlyContinuetry { $entry.Watcher.Dispose() } catch { }}- return ,[string[]]$seen+ return [pscustomobject]@{+ Paths = [string[]]$seen+ FailedRoots = [string[]]$failedRoots+ }}function Get-StudioEventField {@@ -575,6 +650,7 @@ function Invoke-WithCompilerWatch {$failure = $null$live = @()+ $watchFailedRoots = @()try {# Out-Host, not the success stream. The installer action tees its log, and those# lines would be emitted as function output ahead of the result hashtable, making@@ -587,7 +663,12 @@ function Invoke-WithCompilerWatch {$failure = $_} finally {# In the finally, so an action that threw still closes its subscriptions.- $live = @(Stop-StudioTempWatch -Handle $watch)+ $drained = Stop-StudioTempWatch -Handle $watch+ $live = @($drained.Paths)+ # Roots whose watcher raised. Carried out of the finally so the coverage check+ # below can refuse to count them, and initialised above so an action that threw+ # before the watch started still leaves the variable defined.+ $watchFailedRoots = @($drained.FailedRoots)}# Closed before the temp sweep, which can take seconds: anything the machine@@ -614,23 +695,34 @@ function Invoke-WithCompilerWatch {# $left, and which directories those were is recorded in the evidence rather than# dropped silently.$unread = @($beforeScan.Unread + $afterScan.Unread | Sort-Object -Unique)+ # Only the roots whose watcher stayed healthy. A FileSystemWatcher that overflowed its+ # buffer raises Error and drops the creations it could not queue, and its handle is still+ # in $watch looking exactly like a working one. Counting it as coverage is what would let+ # an artifact go missing from the live stream AND from the listing at once, which is the+ # only combination that reports a compile as a clean run.$watchedRoots = New-Object 'System.Collections.Generic.HashSet[string]' (- [string[]]@($watch | ForEach-Object { $_.Root }), [StringComparer]::OrdinalIgnoreCase)- if ($unread.Count -gt 0) {- foreach ($dir in $unread) {- # Withholding is only safe while the watcher is covering that root: it reports- # creations live, so a compile inside an unread directory still lands in- # $transient. With no watcher on the root the listing is the only evidence there- # is, and withholding part of it would report a hole as a clean result. That is- # the same call as the traversal cap in Get-StudioTempSubtree, for the same- # reason, so it is the same answer: declare the measurement void.- $covered = @($watchedRoots | Where-Object { Test-StudioPathUnder -Path $dir -Directory $_ })- if ($covered.Count -eq 0) {- throw ("the temp sweep could not read $dir, and no file watcher is attached " +- "to the root containing it. The listing is the only evidence here and " +- "it is incomplete, so this run cannot say whether a compiler ran.")+ [string[]]@(+ $watch | ForEach-Object { $_.Root } | Where-Object {+ $watchFailedRoots -notcontains $_}- }+ ), [StringComparer]::OrdinalIgnoreCase)+ # Collected, not thrown on. Withholding is only safe while the watcher is covering that+ # root: it reports creations live, so a compile inside an unread directory still lands in+ # $transient. With no watcher on the root the listing is the only evidence there is, and+ # withholding part of it would report a hole as a clean result. That is the same call as+ # the traversal cap in Get-StudioTempSubtree, for the same reason, so it is the same+ # answer: declare the measurement void.+ #+ # Raised at the END of this function rather than here. The action may already have thrown,+ # and that failure is held in $failure to be written to <name>-error.txt and rethrown+ # below. Voiding from this point would run before either, so an installer that genuinely+ # died would be reported as a scanner problem and its promised evidence file would never+ # be written. The scan being incomplete is worth failing on; it is not worth failing on+ # INSTEAD of what the caller was actually measuring.+ $uncovered = @()+ foreach ($dir in $unread) {+ $covered = @($watchedRoots | Where-Object { Test-StudioPathUnder -Path $dir -Directory $_ })+ if ($covered.Count -eq 0) { $uncovered += $dir }}$left = @(@@ -659,16 +751,49 @@ function Invoke-WithCompilerWatch {# Written even when empty, so "the sweep read everything" is a statement the evidence# makes rather than the absence of a file, which is also what a crash looks like.$unread | Out-File -FilePath "$stem-unread-dirs.txt" -Encoding utf8+ # Written even when empty, for the same reason as the unread list: "every watcher stayed+ # healthy" should be a statement the evidence makes, not the absence of a file.+ $watchFailedRoots | Out-File -FilePath "$stem-watch-failures.txt" -Encoding utf8if ($failure) {$failure | Out-String | Out-File -FilePath "$stem-error.txt" -Encoding utf8}+ # The action's own failure first, always. It is the thing under measurement, it is already+ # on disk as <name>-error.txt, and an incomplete sweep is the lesser report of the two.if ($failure) { throw $failure }+ # Only once the action itself succeeded and all the evidence is written does an incomplete+ # measurement void the run. Both reasons are reported together rather than racing each+ # other, so the caller is told everything that was wrong with the sweep at once.+ $incomplete = @()+ if ($watchFailedRoots.Count -gt 0) {+ # A watcher that raised is not merely "not covering unread directories". This half of+ # the detector exists for artifacts that never reach the listing at all: CodeDom+ # deletes its intermediate directory once the assembly is loaded, so a compile can be+ # invisible to the before/after diff and visible only as live events. An overflow drops+ # those events silently, so two clean scans plus a failed watcher is exactly the shape+ # of a missed compile, with nothing in $uncovered to notice it.+ $incomplete += ("the file watcher on " + ($watchFailedRoots -join ', ') + " raised an " ++ "error, so creations under it may have been dropped. A compile whose " ++ "intermediates were deleted before the final sweep is visible only in " ++ "those events")+ }+ if ($uncovered.Count -gt 0) {+ $incomplete += ("the temp sweep could not read " + ($uncovered -join ', ') + ", and no " ++ "file watcher is attached to the root containing it, so the listing is " ++ "the only evidence here and it is incomplete")+ }+ if ($incomplete.Count -gt 0) {+ # $uncovered and $watchFailedRoots are in the evidence either way, through+ # <name>-unread-dirs.txt and <name>-watch-failures.txt.+ throw (($incomplete -join '; ') + ". This run cannot say whether a compiler ran.")+ }+return @{Compilers = $compilersTempLibraries = $newLibrariesTempArtifacts = $newArtifactsUnreadDirs = $unread+ WatchFailures = $watchFailedRoots}}diff --git a/tests/python/test_compiler_watch_temp_scan.py b/tests/python/test_compiler_watch_temp_scan.pyindex 76e048b1ed8..874ac5d4d82 100644--- a/tests/python/test_compiler_watch_temp_scan.py+++ b/tests/python/test_compiler_watch_temp_scan.py@@ -26,6 +26,7 @@ from __future__ import annotationsimport osimport pathlib+import reimport shutilimport subprocess@@ -38,6 +39,34 @@ PWSH = shutil.which("pwsh")pytestmark = pytest.mark.skipif(PWSH is None, reason = "needs PowerShell")+_ANSI = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")+# PowerShell's error formatter gutters every wrapped continuation line with " | ".+_GUTTER = re.compile(r"^\s*\|\s?")+++def _says(proc: subprocess.CompletedProcess, phrase: str) -> bool:+ """Did PowerShell emit this sentence, however it chose to format it?++ A `throw` reaches the caller through PowerShell's error formatter, and on Windows that+ wraps the message across terminal-width lines, interleaves ANSI colour codes AND prefixes+ each continuation with a gutter, so the sentence arrives as++ ...so this run cannot+ | say whether a compiler ran.++ Linux pwsh does not wrap the same way, so a plain substring match passes there and fails on+ Windows against an error that was in fact raised and in fact said the right thing.++ Three things therefore have to come off, and the gutter is the one that is easy to miss:+ stripping colour codes alone still leaves a `|` sitting in the middle of the sentence, so a+ match would keep failing for a new reason. Colour codes, then the gutter, then every run of+ whitespace collapsed, which makes this a test of the message rather than of console width.+ """+ text = _ANSI.sub("", proc.stdout + proc.stderr)+ text = "\n".join(_GUTTER.sub("", line) for line in text.splitlines())+ return " ".join(phrase.split()) in " ".join(text.split())++def _run_pwsh(body: str) -> subprocess.CompletedProcess:script = f"$ErrorActionPreference = 'Stop'\n. '{SCRIPT}'\n{body}"return subprocess.run(@@ -80,7 +109,8 @@ def _walk(root: pathlib.Path, patterns: str = "'*.dll','*.cmdline'") -> list[strreason = ("POSIX permissions only. Windows has no os.geteuid, and chmod there sets the read-only ""attribute rather than making a directory unopenable, so this would not deny anything. "- "The Windows half of the same question is the ACL-based control below."+ "There is deliberately NO Windows equivalent of this row: see the note below on what "+ "Windows does and does not cover here."),)def test_an_unreadable_directory_costs_only_itself(tmp_path: pathlib.Path) -> None:@@ -107,6 +137,26 @@ def test_an_unreadable_directory_costs_only_itself(tmp_path: pathlib.Path) -> Noassert not any(name.endswith("hidden.dll") for name in found), found+# What Windows covers here, and what it does not.+#+# Three rows in this file are POSIX-only and SKIP on Windows: the two chmod-denial walks and the+# vanished-directory row. Nothing replaces them, so on a Windows runner the denial behaviour of+# this walk is not exercised at all. An earlier version of this comment claimed an ACL-based+# Windows control existed "below". It never did.+#+# Writing one means icacls-denying a directory to the running account and undoing it in a finally,+# and it cannot be authored honestly from a Linux host: the failure mode worth catching is a+# control that silently denies nothing and passes, which is exactly what happened when an ACL+# denial was first tried as a stand-in for the race (see the note below). So it is recorded as a+# gap rather than guessed at.+#+# What Windows DOES cover is the rest of the file, which is platform-neutral and drives the real+# PowerShell: the traversal ceiling, the extension filter, the withholding comparison, the+# coverage check and the path-prefix rules. That is not nothing. The separator bug in+# Test-StudioPathUnder - DirectorySeparatorChar being '/' under pwsh on Linux, which made every+# Windows-shaped path compare false - is precisely the class those rows catch, and it is why they+# are written against Windows-shaped literals rather than tmp_path.+## There is no control here for "the old shape really would have died", and that is deliberate.## The CI failure was a RACE: a directory in the shared temp root disappeared partway through a@@ -167,7 +217,9 @@ def test_the_scan_refuses_to_report_a_truncated_snapshot(tmp_path: pathlib.Path)assert ("NO-THROW" not in proc.stdout), "the walk returned a partial snapshot instead of declaring the measurement void"- assert "cannot say whether a compiler ran" in (proc.stdout + proc.stderr)+ assert _says(+ proc, "cannot say whether a compiler ran"+ ), f"the walk raised, but not with the message that explains why:\n{proc.stdout}\n{proc.stderr}"def test_the_artifact_filter_still_selects_by_extension(tmp_path: pathlib.Path) -> None:@@ -376,17 +428,20 @@ def test_the_prefix_test_does_not_match_a_sibling_by_name() -> None:def _shipped_coverage_check() -> str:- """The `if ($unread.Count -gt 0) { ... }` block from Invoke-WithCompilerWatch.+ """The uncovered-directory collection and the throw it feeds, from the shipped file.- Read from the shipped file for the same reason as the `$left` expression: a copy here- would keep passing after the real check changed.+ These are no longer adjacent: the loop collects and the raise happens at the very end of+ the measurement, after the evidence is written and after the action's own failure is+ rethrown. Both halves are lifted so this drives the real pair rather than a copy, and so+ the test keeps working if more code lands between them."""- text = SCRIPT.read_text(encoding = "utf-8")- start = text.index(" if ($unread.Count -gt 0) {")- end = text.index("\n }\n", start) + len("\n }\n")- block = text[start:end]- assert "Test-StudioPathUnder" in block and "throw" in block, block- return block+ body = _measured_action_body()+ loop_start = body.index(" $uncovered = @()")+ loop_end = body.index(" $left = @(", loop_start)+ raise_start = body.index(" $incomplete = @()")+ raise_end = body.index("This run cannot say whether a compiler ran.", raise_start)+ raise_end = body.index("\n }\n", raise_end) + len("\n }\n")+ return body[loop_start:loop_end] + body[raise_start:raise_end]def test_an_unreadable_root_with_a_watcher_on_it_does_not_void_the_run() -> None:@@ -399,11 +454,9 @@ def test_an_unreadable_root_with_a_watcher_on_it_does_not_void_the_run() -> None"""proc = _run_pwsh(r"$unread = @('C:\t')" + "\n"- r"$watch = @([pscustomobject]@{ Root = 'C:\t' })" + "\n"- "$watchedRoots = New-Object 'System.Collections.Generic.HashSet[string]' "- "([string[]]@($watch | ForEach-Object { $_.Root }), [StringComparer]::OrdinalIgnoreCase)\n"- + _shipped_coverage_check()- + "Write-Output 'SURVIVED'\n"+ r"$watchedRoots = New-Object 'System.Collections.Generic.HashSet[string]' ([string[]]@('C:\t'), [StringComparer]::OrdinalIgnoreCase)"+ + "\n"+ "$watchFailedRoots = @()\n" + _shipped_coverage_check() + "Write-Output 'SURVIVED'\n")assert proc.returncode == 0, proc.stdout + proc.stderrassert "SURVIVED" in proc.stdout, (@@ -422,13 +475,260 @@ def test_an_unreadable_root_with_no_watcher_still_voids_the_run() -> None:r"$unread = @('C:\t')" + "\n""$watchedRoots = New-Object 'System.Collections.Generic.HashSet[string]' ""([string[]]@(), [StringComparer]::OrdinalIgnoreCase)\n"- + _shipped_coverage_check()- + "Write-Output 'SURVIVED'\n"+ "$watchFailedRoots = @()\n" + _shipped_coverage_check() + "Write-Output 'SURVIVED'\n")assert "SURVIVED" not in proc.stdout, ("an unread directory with no watcher on its root was treated as a complete "f"measurement:\n{proc.stdout}")- assert "cannot say whether a compiler ran" in (- proc.stdout + proc.stderr+ assert _says(+ proc, "cannot say whether a compiler ran"), f"the run was voided without saying why:\n{proc.stdout}\n{proc.stderr}"+++def test_the_error_subscription_exists_and_condemns_its_root() -> None:+ """A watcher that dropped events must not count as covering its root.++ FileSystemWatcher raises Error on buffer overflow and drops the creations it could not+ queue. The handle stays in the list looking exactly like a working one, so without this the+ coverage check treats the root as watched, the unread directories under it are withheld,+ and an artifact missing from BOTH the live stream and the listing reports as a clean run.+ That is the only combination that turns a real compile into a pass.++ The wiring is asserted on the shipped source rather than by forcing a real overflow, which+ needs a Windows host and thousands of creations to land reliably.+ """+ text = SCRIPT.read_text(encoding = "utf-8")+ assert "-EventName Error" in text, (+ "no Error subscription on the watcher, so an overflow is not observable at all and the "+ "root keeps counting as covered"+ )+ assert "FailedRoots" in text, "the drained errors never reach the caller"+ assert "$watchFailedRoots -notcontains $_" in text, (+ "the coverage set no longer excludes roots whose watcher failed, so an overflowed "+ "watcher still counts as coverage"+ )+++def test_a_failed_watcher_root_is_dropped_from_the_coverage_set() -> None:+ """Driven: the filter that builds $watchedRoots, read out of the shipped file."""+ text = SCRIPT.read_text(encoding = "utf-8")+ start = text.index(" $watchedRoots = New-Object")+ end = text.index("OrdinalIgnoreCase)", start) + len("OrdinalIgnoreCase)")+ expression = text[start:end]+ proc = _run_pwsh(+ r"$watch = @([pscustomobject]@{ Root = 'C:\good' }, [pscustomobject]@{ Root = 'C:\bad' })"+ + "\n"+ r"$watchFailedRoots = @('C:\bad')"+ + "\n"+ + expression+ + "\nforeach ($r in $watchedRoots) { Write-Output $r }\n"+ )+ assert proc.returncode == 0, proc.stdout + proc.stderr+ roots = sorted(line.strip() for line in proc.stdout.splitlines() if line.strip())+ assert roots == [+ r"C:\good"+ ], f"a root whose watcher raised Error was still counted as covering it: {roots}"++[email protected](os.name == "nt", reason = "POSIX permissions only; see the note above.")+def test_an_inaccessible_directory_is_recorded_not_mistaken_for_a_deleted_one(+ tmp_path: pathlib.Path,+) -> None:+ """An ACL denial must not read as "the directory is gone".++ This is why the walk classifies the ERROR instead of probing the path. Measured under pwsh+ with $ErrorActionPreference = 'Stop':++ missing directory -> ItemNotFoundException, Test-Path returns $false+ denied directory -> Test-Path THROWS "Access to the path ... is denied"++ So a Test-Path probe both calls an unreadable directory deleted, dropping it silently out+ of the comparison, and can raise from inside the catch that was meant to contain the+ failure. Here the PARENT is denied, so the child cannot be enumerated or probed: the walk+ must still report the child's parent as unread rather than skipping it.+ """+ outer = tmp_path / "denied"+ outer.mkdir()+ (outer / "inner").mkdir()+ (outer / "inner" / "hidden.dll").write_text("x")+ os.chmod(outer, 0o000)+ try:+ if os.geteuid() == 0:+ pytest.skip("root reads every directory, so nothing here can be made unreadable")+ scan = _scan(tmp_path)+ finally:+ os.chmod(outer, 0o700)++ assert [d for d in scan["unread"] if d.endswith("denied")], (+ "an unreadable directory was treated as deleted and dropped. Pre-existing files under "+ f"it then read as new in the other snapshot, or a real artifact is hidden: {scan}"+ )+++def test_the_walk_classifies_the_error_and_never_probes_with_test_path() -> None:+ """The shape that makes the row above possible, pinned so it cannot regress quietly."""+ text = SCRIPT.read_text(encoding = "utf-8")+ body = text[+ text.index("function Get-StudioTempSubtree") : text.index(+ "function Get-StudioTempArtifacts"+ )+ ]+ # Comments stripped first, like the -Recurse guard above: this function EXPLAINS why it+ # does not probe, and the prose naming Test-Path is not a call to it.+ code = "\n".join(line for line in body.splitlines() if not line.strip().startswith("#"))+ assert "Test-Path" not in code, (+ "the walk probes with Test-Path again. That throws on an ACL-denied directory and "+ "answers False for one that merely cannot be read, so it cannot decide deleted "+ "versus unreadable."+ )+ assert body.count("Test-StudioPathIsGone") >= 2, (+ "both the first failure and the retry must classify the error; otherwise a directory "+ "deleted inside the retry window is recorded as unread and can void the run"+ )+++def test_a_missing_directory_is_still_not_recorded_as_unread(tmp_path: pathlib.Path) -> None:+ """The control for the row above: fail-safe must not become fail-always.++ Test-StudioPathIsGone returning $false for everything would make every temp deletion a+ gap, and an unread directory under an unwatched root voids the run. That would fail the+ job for exactly the race this change exists to tolerate.+ """+ scan = _scan(tmp_path / "never-existed")+ assert scan["files"] == [] and scan["unread"] == [], (+ f"a missing directory was recorded as a gap, which voids runs for ordinary temp "+ f"deletions: {scan}"+ )+++def test_the_classifier_answers_both_cases() -> None:+ """Driven against the real helper: missing is gone, denied is not."""+ proc = _run_pwsh(+ "$missing = $null\n"+ "try { Get-ChildItem -LiteralPath '/nonexistent-xyz-123' -Force -ErrorAction Stop | Out-Null }\n"+ "catch { $missing = $_ }\n"+ "Write-Output ('missing=' + (Test-StudioPathIsGone -ErrorRecord $missing))\n"+ "$denied = New-Object System.Management.Automation.ErrorRecord ("+ "(New-Object System.UnauthorizedAccessException 'denied'), 'x', 'PermissionDenied', $null)\n"+ "Write-Output ('denied=' + (Test-StudioPathIsGone -ErrorRecord $denied))\n"+ )+ assert proc.returncode == 0, proc.stdout + proc.stderr+ out = dict(line.split("=", 1) for line in proc.stdout.splitlines() if "=" in line)+ assert out["missing"] == "True", out+ assert out["denied"] == "False", (+ "an access-denied error was classified as a deleted directory, so the directory is "+ f"dropped out of the comparison instead of recorded as a gap: {out}"+ )+++def _measured_action_body() -> str:+ """Invoke-WithCompilerWatch, as shipped."""+ text = SCRIPT.read_text(encoding = "utf-8")+ return text[text.index("function Invoke-WithCompilerWatch") :]+++def test_the_action_failure_is_persisted_and_rethrown_before_the_scan_is_rejected() -> None:+ """An installer that died must not be reported as a scanner problem.++ The void-the-run throw and the action's own failure can both be pending at the end of a+ measurement. If the void fires first, the caller loses the thing it was actually measuring+ AND the <name>-error.txt this function promises, because the write and the rethrow both+ come later in the body.++ Ordering is the whole claim here, so ordering is what is asserted: the offsets are taken+ from the shipped function rather than from a re-implementation.+ """+ body = _measured_action_body()+ write_error = body.index('"$stem-error.txt"')+ rethrow = body.index("if ($failure) { throw $failure }")+ void = body.index("$uncovered.Count -gt 0")++ assert write_error < rethrow, (+ "the action's failure is rethrown before it is written to disk, so the evidence file "+ "this function promises is never produced"+ )+ assert rethrow < void, (+ "the incomplete-scan throw runs before the action's own failure is rethrown. An "+ "installer that genuinely died is then reported as a scanner problem."+ )+++def test_the_coverage_check_no_longer_throws_from_inside_the_loop() -> None:+ """The collect-then-raise shape, pinned.++ A throw inside the per-directory loop is what put the rejection ahead of the evidence in+ the first place, and it is an easy thing to reintroduce while editing that loop.+ """+ body = _measured_action_body()+ loop_start = body.index("foreach ($dir in $unread) {")+ loop_end = body.index("$left = @(", loop_start)+ loop = body[loop_start:loop_end]+ assert "throw" not in loop, (+ "the coverage loop raises directly again, which puts it ahead of the evidence write "+ f"and the action's own failure:\n{loop}"+ )+ assert "$uncovered += $dir" in loop, "the uncovered directories are no longer collected"+++def test_an_overflowed_watcher_voids_the_measurement_on_its_own() -> None:+ """A dropped event stream is an incomplete measurement, with or without unread directories.++ This half of the detector exists for artifacts that never reach the listing: CodeDom deletes+ its intermediate directory once the assembly is loaded, so a compile can be invisible to the+ before/after diff and present only as live events. An overflow drops those silently, so two+ clean scans plus a failed watcher is the exact shape of a missed compile - and there is+ nothing in $uncovered to notice it, because no directory was unreadable.++ Excluding the root from $watchedRoots is therefore not enough on its own. That only changes+ the answer when $unread happens to hold something beneath the same root.+ """+ proc = _run_pwsh(+ "$unread = @()\n"+ "$watchedRoots = New-Object 'System.Collections.Generic.HashSet[string]' "+ "([string[]]@(), [StringComparer]::OrdinalIgnoreCase)\n"+ r"$watchFailedRoots = @('C:\t')"+ + "\n"+ + _shipped_coverage_check()+ + "Write-Output 'SURVIVED'\n"+ )+ assert "SURVIVED" not in proc.stdout, (+ "a watcher that raised was accepted as a complete measurement because no directory "+ f"happened to be unreadable:\n{proc.stdout}"+ )+ assert _says(+ proc, "may have been dropped"+ ), f"the run was voided without naming the dropped events:\n{proc.stdout}\n{proc.stderr}"+++def test_a_healthy_watcher_and_a_readable_sweep_still_pass() -> None:+ """The control: voiding on watcher health must not void every ordinary run."""+ proc = _run_pwsh(+ "$unread = @()\n"+ "$watchedRoots = New-Object 'System.Collections.Generic.HashSet[string]' "+ r"([string[]]@('C:\t'), [StringComparer]::OrdinalIgnoreCase)" + "\n"+ "$watchFailedRoots = @()\n" + _shipped_coverage_check() + "Write-Output 'SURVIVED'\n"+ )+ assert proc.returncode == 0, proc.stdout + proc.stderr+ assert (+ "SURVIVED" in proc.stdout+ ), f"a clean measurement was voided, which would fail every run:\n{proc.stdout}\n{proc.stderr}"+++def test_both_incompleteness_reasons_are_reported_together() -> None:+ """One throw naming everything wrong, rather than whichever check happened to run first."""+ proc = _run_pwsh(+ r"$unread = @('C:\gap')" + "\n"+ "$watchedRoots = New-Object 'System.Collections.Generic.HashSet[string]' "+ "([string[]]@(), [StringComparer]::OrdinalIgnoreCase)\n"+ r"$watchFailedRoots = @('C:\t')"+ + "\n"+ + _shipped_coverage_check()+ + "Write-Output 'SURVIVED'\n"+ )+ assert "SURVIVED" not in proc.stdout, proc.stdout+ assert _says(proc, "may have been dropped"), proc.stdout + proc.stderr+ assert _says(proc, "could not read"), (+ "only one of the two reasons reached the caller, so fixing that one would leave the "+ f"run failing again for a reason never reported:\n{proc.stdout}\n{proc.stderr}"+ )