From aa75f13197627391579e7c282b353cfa85f466ff Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:39:51 +0100 Subject: gate: a memory stop ends a run before memory runs out (D3D12-GATE-MEMORY-STOP) A memory pile-up has taken a PC's whole Windows down, not only the device, and a fixed 80 GB cap never triggers on a PC with a 40 GB commit limit. The supervisor now asks `game_gate.py state` for a memory stop, read from the runtime's latest memory lines: the game's private bytes past -StopPrivateMB (default 90 % of this PC's commit limit), the PC under -StopCommitLeftMB left to commit for 20 s (default the larger of 128 MB and 0.25 % of the limit), or video memory over the system's budget for -StopOverBudgetSeconds (60). 0 turns one off. The run then stops the same clean way, with the reason `memory`; the limits go into run.json and the summary, the limit passed into `stop.memory_why`, and the verdict is FAIL `memory_stop`. `start` forwards the limits to the detached run. --- scripts/game-gate.ps1 | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) (limited to 'scripts') diff --git a/scripts/game-gate.ps1 b/scripts/game-gate.ps1 index 6ab0c11a9..1192cd096 100644 --- a/scripts/game-gate.ps1 +++ b/scripts/game-gate.ps1 @@ -15,6 +15,10 @@ # saved) when -WorldSeconds were spent in the world, when a STOP file appears in the run folder, or after # -MaxMinutes; it kills the game only if it has not ended 60 s later. Exit code: 0 PASS, 1 FAIL, 2 ERROR. # Options: -WorldSeconds (300), -MaxMinutes (45), -More 'LEONIDA_X=1;LEONIDA_Y=2', -PlayArgs '-SeriesS -NoFrameGen'. +# Memory stop (from the runtime's memory lines, every 5 s, builds with diagnostics): the run is stopped the same +# clean way, with the reason `memory`, when the game's private bytes pass -StopPrivateMB (90 % of this PC's commit +# limit), when the PC has less than -StopCommitLeftMB left to commit for 20 s (the larger of 128 MB and 0.25 % of +# the limit), or when video memory stays over the system's budget for -StopOverBudgetSeconds (60). 0 turns one off. param( [Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb, [string]$Game = '', @@ -27,7 +31,10 @@ param( [int]$MaxMinutes = 45, [string]$More = '', [string]$PlayArgs = '', - [string]$Python = '' + [string]$Python = '', + [int]$StopPrivateMB = -1, + [int]$StopCommitLeftMB = -1, + [int]$StopOverBudgetSeconds = 60 ) $ErrorActionPreference = 'Stop' $repo = Split-Path -Parent $PSScriptRoot @@ -96,7 +103,8 @@ if ($Verb -eq 'start') { $line = @(& $quote $pwsh; '-NoProfile'; '-ExecutionPolicy'; 'Bypass'; '-File'; & $quote $PSCommandPath; 'run' '-Game'; & $quote $Game; '-Data'; & $quote $Data; '-DataTemplate'; & $quote $DataTemplate; '-Name'; & $quote $Name '-RunRoot'; & $quote $RunRoot; '-RunDir'; & $quote $RunDir; '-WorldSeconds'; $WorldSeconds; '-MaxMinutes'; $MaxMinutes - '-More'; & $quote $More; '-PlayArgs'; & $quote $PlayArgs; '-Python'; & $quote $Python) -join ' ' + '-More'; & $quote $More; '-PlayArgs'; & $quote $PlayArgs; '-Python'; & $quote $Python + '-StopPrivateMB'; $StopPrivateMB; '-StopCommitLeftMB'; $StopCommitLeftMB; '-StopOverBudgetSeconds'; $StopOverBudgetSeconds) -join ' ' # Created by Windows, not as a child of this shell: an agent's or a console's end does not end the run. $startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0 } $made = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ @@ -140,6 +148,11 @@ $moreText & '$play' -Game '$Game' -Data '$Data' -More `$settings $PlayArgs @args "@ +# The memory stop's limits, from this PC's commit limit unless given (0 turns one off). On a PC with no page file a +# normal run can leave a few hundred MB to commit: the floor is low and must hold for 20 s. +$commitLimitMB = [math]::Floor((Get-CimInstance Win32_OperatingSystem).TotalVirtualMemorySize / 1KB) +if ($StopPrivateMB -lt 0) { $StopPrivateMB = [int]($commitLimitMB * 0.9) } +if ($StopCommitLeftMB -lt 0) { $StopCommitLeftMB = [int][math]::Max(128, $commitLimitMB * 0.0025) } $gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterRAM } -Descending | Select-Object -First 1 [ordered]@{ name = $Name @@ -155,6 +168,7 @@ $gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterR world_seconds = $WorldSeconds max_minutes = $MaxMinutes f1_settings_file = $hadMenuFile + memory_stop = [ordered]@{ private_max_mb = $StopPrivateMB; commit_left_min_mb = $StopCommitLeftMB; over_budget_s = $StopOverBudgetSeconds } } | ConvertTo-Json | Set-Content (Join-Path $RunDir 'run.json') & pwsh -NoProfile -ExecutionPolicy Bypass -File $launch -DryRun *> (Join-Path $RunDir 'settings.txt') @@ -196,6 +210,7 @@ public static class GateWindow { $began = Get-Date $title = $null # the game process ($Game, the same name in any case, is its folder) $stopReason = $null +$memoryWhy = $null try { while ($true) { Start-Sleep -Seconds 5 @@ -211,6 +226,7 @@ while ($true) { if (-not $title -and $launcher.HasExited) { break } $state = & $Python -I $tool state $RunDir | ConvertFrom-Json if ($state.relaunched) { $stopReason = 'relaunched' } + elseif ($state.memory_stop) { $stopReason = 'memory'; $memoryWhy = $state.memory_stop } elseif (Test-Path (Join-Path $RunDir 'STOP')) { $stopReason = 'stop_file' } elseif ($state.world_s -ge $WorldSeconds) { $stopReason = 'target' } elseif (((Get-Date) - $began).TotalMinutes -ge $MaxMinutes) { $stopReason = 'timeout' } @@ -218,7 +234,7 @@ while ($true) { } if ($stopReason -and $title -and -not $title.HasExited) { - Add-Event 'stop_requested' @{ reason = $stopReason } + Add-Event 'stop_requested' @{ reason = $stopReason; why = $memoryWhy } if ([GateWindow]::Close($title.Id)) { Add-Event 'close_sent' } if (-not $title.WaitForExit(60000)) { Stop-Process -Id $title.Id -Force @@ -226,7 +242,7 @@ if ($stopReason -and $title -and -not $title.HasExited) { $title.WaitForExit() } } elseif ($stopReason) { - Add-Event 'stop_requested' @{ reason = $stopReason } + Add-Event 'stop_requested' @{ reason = $stopReason; why = $memoryWhy } } if ($title) { Add-Event 'game_exited' @{ exit_code = $title.ExitCode } } if (-not $launcher.WaitForExit(30000)) { Stop-Process -Id $launcher.Id -Force } -- cgit v1.2.3 From cb5bcfc2058e44cc4dea3197d6cf18d855f173ff Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:42:44 +0100 Subject: gate: the private-bytes stop also follows the PC's memory (review) With a large page file the commit limit is far above what a PC survives: two Windows crashes (0x10E) came at about 100 GB private on a PC with 64 GB of memory and a 175 GB limit, where 90 % of the limit is 158 GB. The default is now the lower of 90 % of the commit limit and 1.25 x the physical memory (80 GB there, 36 GB here); the video memory stop stays on by default. --- docs/game_gate.md | 2 +- scripts/game-gate.ps1 | 12 ++++++++---- tests/test_game_gate.py | 3 +++ 3 files changed, 12 insertions(+), 5 deletions(-) (limited to 'scripts') diff --git a/docs/game_gate.md b/docs/game_gate.md index 1178a5dc2..2d5677e1e 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -29,7 +29,7 @@ pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir - **The caches.** `-Data` keeps its caches (`cache-2`); only the saves are copied. The first start after a translator change translates every shader again: run once before measuring. - **Ending the run.** It stops when the time in the world reaches `-WorldSeconds`, when a `STOP` file appears in the run folder (`stop`), or after `-MaxMinutes` (45). - **Memory stop.** It also stops the run, the same clean way and with the reason `memory`, before memory runs out. A memory pile-up has taken a PC's whole Windows down, not only the device. It reads the runtime's memory lines (every 5 s, builds with diagnostics) and stops when: - - the game's private bytes pass `-StopPrivateMB` (default: 90 % of this PC's commit limit); + - the game's private bytes pass `-StopPrivateMB` (default: the lower of 90 % of this PC's commit limit and 1.25 times its physical memory; with a large page file the limit is far above what a PC survives, and two Windows crashes came at about 100 GB private on a PC with 64 GB); - the PC has less than `-StopCommitLeftMB` left to commit for 20 s (default: the larger of 128 MB and 0.25 % of the limit; on a PC with no page file a normal run can leave a few hundred MB); - video memory stays over the system's budget for `-StopOverBudgetSeconds` (60). diff --git a/scripts/game-gate.ps1 b/scripts/game-gate.ps1 index 1192cd096..b2a3c88c1 100644 --- a/scripts/game-gate.ps1 +++ b/scripts/game-gate.ps1 @@ -16,9 +16,10 @@ # -MaxMinutes; it kills the game only if it has not ended 60 s later. Exit code: 0 PASS, 1 FAIL, 2 ERROR. # Options: -WorldSeconds (300), -MaxMinutes (45), -More 'LEONIDA_X=1;LEONIDA_Y=2', -PlayArgs '-SeriesS -NoFrameGen'. # Memory stop (from the runtime's memory lines, every 5 s, builds with diagnostics): the run is stopped the same -# clean way, with the reason `memory`, when the game's private bytes pass -StopPrivateMB (90 % of this PC's commit -# limit), when the PC has less than -StopCommitLeftMB left to commit for 20 s (the larger of 128 MB and 0.25 % of -# the limit), or when video memory stays over the system's budget for -StopOverBudgetSeconds (60). 0 turns one off. +# clean way, with the reason `memory`, when the game's private bytes pass -StopPrivateMB (the lower of 90 % of this +# PC's commit limit and 1.25 x its memory), when the PC has less than -StopCommitLeftMB left to commit for 20 s +# (the larger of 128 MB and 0.25 % of the limit), or when video memory stays over the system's budget for +# -StopOverBudgetSeconds (60). 0 turns one off. param( [Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb, [string]$Game = '', @@ -151,7 +152,10 @@ $moreText # The memory stop's limits, from this PC's commit limit unless given (0 turns one off). On a PC with no page file a # normal run can leave a few hundred MB to commit: the floor is low and must hold for 20 s. $commitLimitMB = [math]::Floor((Get-CimInstance Win32_OperatingSystem).TotalVirtualMemorySize / 1KB) -if ($StopPrivateMB -lt 0) { $StopPrivateMB = [int]($commitLimitMB * 0.9) } +$physicalMB = [math]::Floor((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1MB) +# With a large page file the commit limit is far above what the PC survives: two Windows crashes (0x10E) came at +# about 100 GB private on a PC with 64 GB of memory and a 175 GB limit. So also no more than 1.25 x the memory. +if ($StopPrivateMB -lt 0) { $StopPrivateMB = [int][math]::Min($commitLimitMB * 0.9, $physicalMB * 1.25) } if ($StopCommitLeftMB -lt 0) { $StopCommitLeftMB = [int][math]::Max(128, $commitLimitMB * 0.0025) } $gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterRAM } -Descending | Select-Object -First 1 [ordered]@{ diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index c73c2485d..8bba0d756 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -381,6 +381,9 @@ class Script(unittest.TestCase): # `start` rebuilds the command line of the detached `run`: a limit left out would be lost there. self.assertIn(f"'-{name}'; ${name}", text) self.assertIn("memory_stop = [ordered]@{", text) + # The private default follows the PC's memory too, not only its commit limit (a large page file). + self.assertIn("TotalPhysicalMemory", text) + self.assertIn("[math]::Min($commitLimitMB * 0.9, $physicalMB * 1.25)", text) self.assertIn("$stopReason = 'memory'", text) def test_no_variable_takes_a_parameters_name_in_another_case(self): -- cgit v1.2.3 From eac2b61d2f012c764c08eacda411ef76a5581d88 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 02:52:41 +0100 Subject: gate: the world time comes before the memory stop, the commit floor tested at 20 s (review) A run that reached -WorldSeconds at the same poll as a memory limit was reported FAIL `memory_stop`. It is a measurement, and its memory peaks are in the summary all the same, so the supervisor now checks the target first. The poll's order is one function, Get-StopReason, which the test takes out of the script and puts to PowerShell 7 with synthetic polls. The commit floor's boundary is now tested at exactly 20 s, and the docs say what `stop.memory_why` holds: the gate's whole sentence. --- docs/game_gate.md | 4 ++-- scripts/game-gate.ps1 | 20 ++++++++++++++------ tests/test_game_gate.py | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 62 insertions(+), 9 deletions(-) (limited to 'scripts') diff --git a/docs/game_gate.md b/docs/game_gate.md index 2d5677e1e..9f0722cfc 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -33,7 +33,7 @@ pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir - the PC has less than `-StopCommitLeftMB` left to commit for 20 s (default: the larger of 128 MB and 0.25 % of the limit; on a PC with no page file a normal run can leave a few hundred MB); - video memory stays over the system's budget for `-StopOverBudgetSeconds` (60). - 0 turns a limit off. The limits go into `run.json` (`memory_stop`) and the summary (`memory.stop_limits`). + 0 turns a limit off. The limits go into `run.json` (`memory_stop`) and the summary (`memory.stop_limits`). The gate checks every 5 s, and the world time comes first: a run that reaches `-WorldSeconds` at the same check as a limit stops with `target`. It is a measurement, and its memory peaks are in the summary all the same. - **How it stops.** With `WM_SYSCOMMAND`/`SC_CLOSE`, the runtime's own end: the title is suspended and the pipeline cache saved. It kills the game only if it has not ended 60 s later. - **Exit code.** 0 PASS, 1 FAIL, 2 ERROR. `start` exits when the detached run is created. @@ -68,7 +68,7 @@ Times are seconds since the run started. The summary holds numbers, switch names | `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card | | `crash` | `kind` is `none`, `device_lost`, `panic` or `fault`. It also gives the time, the code, the module kind (`runtime`, `title`, `driver`, `system`, `unknown`) and the access (read/write). `title_watchdog` marks a write at address 0 in the title more than 25 s after the last frame line. `count` is the number of crashes | | `exit` | The game's exit code, and its kind: `clean`, `device_lost` (0x887A0005), `killed` or `other` | -| `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched`, `memory` with the limit passed in `memory_why`), whether it was killed, whether the cache was saved, whether the suspend was in time | +| `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched` or `memory`), whether it was killed, whether the cache was saved, whether the suspend was in time. After a memory stop, `memory_why` is the gate's whole sentence for it, with its numbers: `private bytes 31000 MB, over 30000 MB`, `the PC had under 200 MB left to commit for 25 s` or `video memory over its budget for 60 s`, for example. It is null for the other reasons | | `verdict` | `result`, `reasons`, `warnings`, `min_world_s` | ## The verdict diff --git a/scripts/game-gate.ps1 b/scripts/game-gate.ps1 index b2a3c88c1..1a153a8ae 100644 --- a/scripts/game-gate.ps1 +++ b/scripts/game-gate.ps1 @@ -19,7 +19,7 @@ # clean way, with the reason `memory`, when the game's private bytes pass -StopPrivateMB (the lower of 90 % of this # PC's commit limit and 1.25 x its memory), when the PC has less than -StopCommitLeftMB left to commit for 20 s # (the larger of 128 MB and 0.25 % of the limit), or when video memory stays over the system's budget for -# -StopOverBudgetSeconds (60). 0 turns one off. +# -StopOverBudgetSeconds (60). 0 turns one off. A run that reaches -WorldSeconds at the same poll stops with `target`. param( [Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb, [string]$Game = '', @@ -211,6 +211,16 @@ public static class GateWindow { '@ } +# Why this poll stops the run, or nothing. The target comes before the memory stop: a run that reached its world time +# in the same poll as a memory limit is a measurement, and its memory peaks are in the summary all the same. +function Get-StopReason($Poll, [bool]$StopFile, [double]$Minutes, [int]$TargetSeconds, [int]$LimitMinutes) { + if ($Poll.relaunched) { 'relaunched' } + elseif ($Poll.world_s -ge $TargetSeconds) { 'target' } + elseif ($Poll.memory_stop) { 'memory' } + elseif ($StopFile) { 'stop_file' } + elseif ($Minutes -ge $LimitMinutes) { 'timeout' } +} + $began = Get-Date $title = $null # the game process ($Game, the same name in any case, is its folder) $stopReason = $null @@ -229,11 +239,9 @@ while ($true) { if ($title -and $title.HasExited) { break } if (-not $title -and $launcher.HasExited) { break } $state = & $Python -I $tool state $RunDir | ConvertFrom-Json - if ($state.relaunched) { $stopReason = 'relaunched' } - elseif ($state.memory_stop) { $stopReason = 'memory'; $memoryWhy = $state.memory_stop } - elseif (Test-Path (Join-Path $RunDir 'STOP')) { $stopReason = 'stop_file' } - elseif ($state.world_s -ge $WorldSeconds) { $stopReason = 'target' } - elseif (((Get-Date) - $began).TotalMinutes -ge $MaxMinutes) { $stopReason = 'timeout' } + $stopReason = Get-StopReason -Poll $state -StopFile (Test-Path (Join-Path $RunDir 'STOP')) ` + -Minutes ((Get-Date) - $began).TotalMinutes -TargetSeconds $WorldSeconds -LimitMinutes $MaxMinutes + if ($stopReason -eq 'memory') { $memoryWhy = $state.memory_stop } if ($stopReason) { break } } diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index 8bba0d756..bae6302bf 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -257,6 +257,9 @@ class Measures(unittest.TestCase): cases = { "private bytes 31000 MB, over 30000 MB": calm + [(31000, 7000, 3000)], "the PC had under 200 MB left to commit for 25 s": calm + [(24000, 7000, 150)] * 6, + # Exactly 20 s under the floor (five lines 5 s apart) is enough: the floor's boundary, as 60 s is the + # video memory's. + "the PC had under 200 MB left to commit for 20 s": calm + [(24000, 7000, 150)] * 5, "video memory over its budget for 60 s": calm + [(24000, 9000, 3000)] * 13, } for why, rows in cases.items(): @@ -384,7 +387,49 @@ class Script(unittest.TestCase): # The private default follows the PC's memory too, not only its commit limit (a large page file). self.assertIn("TotalPhysicalMemory", text) self.assertIn("[math]::Min($commitLimitMB * 0.9, $physicalMB * 1.25)", text) - self.assertIn("$stopReason = 'memory'", text) + + # What one poll of the supervisor reads (`game_gate.py state`, a STOP file, the minutes since the start) and the + # reason it stops the run for, with -WorldSeconds 300 and -MaxMinutes 45. + POLLS = [ + # The world time reached in the same poll as a memory limit: a measurement, not a memory stop. + ({"relaunched": False, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20, + "target"), + ({"relaunched": False, "world_s": 295.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20, + "memory"), + ({"relaunched": True, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20, + "relaunched"), + ({"relaunched": False, "world_s": 100.0, "memory_stop": "video memory over its budget for 60 s"}, True, 20, + "memory"), + ({"relaunched": False, "world_s": 100.0, "memory_stop": None}, True, 20, "stop_file"), + ({"relaunched": False, "world_s": 0.0, "memory_stop": None}, False, 45, "timeout"), + ({"relaunched": False, "world_s": 100.0, "memory_stop": None}, False, 20, "none"), + ] + + def test_a_poll_stops_for_the_target_before_the_memory_stop(self): + # The supervisor's own function is taken out of the script and put to PowerShell 7 with each poll above. + with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: + text = f.read() + self.assertIn("$stopReason = Get-StopReason -Poll $state ", text) + self.assertEqual(text.count("$stopReason = "), 2) # set to $null before the loop, then only from the function + pwsh = shutil.which("pwsh") + if not pwsh: + self.skipTest("no PowerShell 7 here") + script = ("$ErrorActionPreference = 'Stop'; " + "$language = 'System.Management.Automation.Language'; " + "$ast = ($language + '.Parser' -as [type])::ParseFile($env:GATE_SCRIPT, [ref]$null, [ref]$null); " + "$fn = $ast.Find({ $args[0].GetType().Name -eq 'FunctionDefinitionAst' -and " + "$args[0].Name -eq 'Get-StopReason' }, $true); " + "if (-not $fn) { throw 'the gate has no Get-StopReason' }; " + ". ([scriptblock]::Create($fn.Extent.Text)); " + "foreach ($p in ($env:GATE_POLLS | ConvertFrom-Json)) " + "{ $r = Get-StopReason -Poll $p[0] -StopFile $p[1] -Minutes $p[2] -TargetSeconds 300 " + "-LimitMinutes 45; if ($r) { $r } else { 'none' } }") + env = dict(os.environ, GATE_SCRIPT=os.path.join(ROOT, "scripts", "game-gate.ps1"), + GATE_POLLS=json.dumps([p[:3] for p in self.POLLS])) + done = subprocess.run([pwsh, "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True, + text=True, timeout=120, env=env) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(done.stdout.split(), [p[3] for p in self.POLLS]) def test_no_variable_takes_a_parameters_name_in_another_case(self): # PowerShell names ignore case: a `$game` process held in the `[string]$Game` parameter became its name, -- cgit v1.2.3 From dc63e371ce211540f50f8cfb640f1daab97b285f Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:09:56 +0100 Subject: scripts: red_green.py --mutate checks that the tests catch the change itself (TEST-RED-GREEN-MUTATION) Verifiers remove a line of the fix by hand on nearly every test pull request to see the new test fail. --mutate does it for each hunk of the pull request's code outside its tests (Rust and Python files it changes; hunks taken without context, so a test changed next to the code stays out): after the green side, it undoes that hunk alone, runs the tests again and reports it as caught (a test that went red then green fails), not caught, does not build or does not apply, up to --mutate-max hunks (10); the hunk is put back after each run. Python tests now run with -B: an undone change of the same size within the same second would otherwise run the stale bytecode. --- docs/testing.md | 6 ++++ scripts/red_green.py | 90 +++++++++++++++++++++++++++++++++++++++++++++++-- tests/test_red_green.py | 42 +++++++++++++++++++++++ 3 files changed, 135 insertions(+), 3 deletions(-) (limited to 'scripts') diff --git a/docs/testing.md b/docs/testing.md index a5686330c..b213c71d2 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -157,6 +157,12 @@ python -I scripts/red_green.py and the report says so; a second crash gives `compiler crashed`. Run it again later, or on another machine. - `red does not build` is the case the fork-CI steps above call "does not build without the pull request's new file": the test needs the new code, which does not show that it catches the bug. +- `--mutate` also checks that the tests catch the change itself, what verifiers do by hand by removing a line of the + fix. After the green side, it undoes each hunk of the pull request's code alone (Rust and Python files it changes, + outside the tests and `#[cfg(test)]` code) and runs the tests again. A hunk is `caught` when a test that went red + then green fails, `not caught` when they all still pass, `does not build`, or `does not apply` (`main` moved those + lines since). It tries at most `--mutate-max` hunks (10). A `not caught` hunk is code no new test looks at; it + does not change the verdict. - `--crate ` adds a crate, `--no-cargo` or `--no-python` leaves one kind out, `--base ` tests on another base, and `--no-fetch` uses the refs as they are. diff --git a/scripts/red_green.py b/scripts/red_green.py index 7d8305f45..57dd8de6a 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -35,6 +35,7 @@ import re import subprocess import sys import tempfile +from collections import Counter from pathlib import Path IDENTITY = { @@ -325,7 +326,9 @@ def python_tests(tree: Path, files: list[str]) -> dict: tests, no_build = {}, [] for f in files: start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) - r = subprocess.run([sys.executable, "-I", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, "-v"], + # -B: no bytecode. An undone change of the same size within the same second would run the stale .pyc. + r = subprocess.run([sys.executable, "-I", "-B", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, + "-v"], cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = r.stdout.decode("utf-8", "replace") found = 0 @@ -423,6 +426,12 @@ def report(r: dict) -> str: if len(rows[key]) > 40: out.append(f" ... {len(rows[key]) - 40} more") out.append(f"pass on both: {rows['pass_on_both']}") + if r.get("mutations") is not None: + counts = Counter(m["result"] for m in r["mutations"]) + out.append(f"mutations ({len(r['mutations'])} hunks undone one at a time): " + + ", ".join(f"{n} {k}" for k, n in sorted(counts.items())) if r["mutations"] else + "mutations: no code hunk outside the tests") + out += [f" {m['file']}:{m['line']}: {m['result']}" for m in r["mutations"]] out.append(f"verdict: {r['verdict']}") return "\n".join(out) @@ -439,6 +448,9 @@ def main(argv: list[str] | None = None) -> int: p.add_argument("--no-python", action="store_true", help="skip the Python tests") p.add_argument("--cargo", default="cargo", help="the cargo to run (a .py file runs with this Python)") p.add_argument("--json", action="store_true", help="print the result as JSON") + p.add_argument("--mutate", action="store_true", + help="undo each code hunk alone on green and run the tests again (caught or not)") + p.add_argument("--mutate-max", type=int, default=10, help="the most hunks --mutate tries (10)") a = p.parse_args(argv) try: repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) @@ -503,15 +515,87 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer else: print("red_green: green side...", file=sys.stderr) green = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) + rows = compare(red, green) + mutations = None + if a.mutate and green is not None: + targets = list(rows["red_to_green"]) + if targets: + print("red_green: mutations...", file=sys.stderr) + mutations = mutate(repo, tree, merge_base, head, targets, crates, py_files, a.cargo, target, a.mutate_max) + if mutations is None: + checkout(repo, tree, base_commit) + git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) checkout(repo, tree, base_commit) - rows = compare(red, green) return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, - "python_files": py_files, "red": red, "green": green, "rows": rows, + "python_files": py_files, "red": red, "green": green, "rows": rows, "mutations": mutations, "verdict": verdict(red_why, green_why, red, green, rows)} +def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, str]]: + """(file, first changed line in the pull request, patch) for each hunk of its code outside its tests: the hunks + a mutation undoes one at a time. Without context, so that a test changed next to the code is a hunk of its own (a + hunk does not apply where `main` moved the lines since).""" + out = [] + for path in git(repo, "diff", "--name-only", "--no-renames", "--diff-filter=M", merge_base, head).splitlines(): + if is_test_file(path) or not (path.endswith(".rs") or (path.endswith(".py") and not path.startswith("tests/"))): + continue + lines = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path).split("\n") + first = next((i for i, line in enumerate(lines) if line.startswith("@@")), None) + if first is None: + continue + header = "\n".join(lines[:first]) + hunks: list[list[str]] = [] + for line in lines[first:]: + if line.startswith("@@"): + hunks.append([line]) + else: + hunks[-1].append(line) + tests_new = test_lines(blob(repo, head, path) or b"") if path.endswith(".rs") else set() + for hunk in hunks: + m = HUNK.match(hunk[0]) + if not m: + continue + at, added = int(m.group(3)) - 1, [] # 0-based line of the pull request's side + for line in hunk[1:]: + if line.startswith("+"): + added.append(at) + at += 1 + elif line.startswith(" "): + at += 1 + # A hunk that only adds test code is the tests' own, not the fix. + if added and all(i in tests_new for i in added): + continue + out.append((path, int(m.group(3)), header + "\n" + "\n".join(hunk).rstrip("\n") + "\n")) + return out + + +def mutate(repo: Path, tree: Path, merge_base: str, head: str, targets: list[str], crates: list[str], + py_files: list[str], cargo: str, target: Path, most: int) -> list[dict] | None: + """Undoes each code hunk alone on the green tree and runs the tests again: a hunk is caught when one of the tests + that went red then green fails. Returns None when the tree could not be put back (the caller rebuilds it).""" + results = [] + for path, line, patch in code_hunks(repo, merge_base, head)[:most]: + entry = {"file": path, "line": line, "result": None} + undo = run(["git", "apply", "-R", "--unidiff-zero", "-"], tree, data=patch.encode()) + if undo.returncode != 0: + entry["result"] = "does not apply" + results.append(entry) + continue + s = side(tree, crates, [f for f in py_files if (tree / f).is_file()], cargo, target) + if s.get("compiler_crashed"): + entry["result"] = "compiler crashed" + elif not any(t in s["tests"] for t in targets): + entry["result"] = "does not build" + else: + entry["result"] = "caught" if any(s["tests"].get(t) == "failed" for t in targets) else "not caught" + results.append(entry) + if run(["git", "apply", "--unidiff-zero", "-"], tree, data=patch.encode()).returncode != 0: + return None + return results + + if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 5f4b89529..be4a60c2e 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -236,6 +236,48 @@ class Python(unittest.TestCase): self.assertEqual(code, 1) +class Mutation(unittest.TestCase): + # Two code changes far enough apart to be two hunks: the tested one and one no test looks at. + BASE = ("pub fn value() -> u32 {\n 1\n}\n\n" + "".join(f"// padding line {i}\n" for i in range(10)) + + "\npub fn spare() -> u32 {\n 5\n}\n" + LIB[LIB.index("\n#[cfg(test)]"):]) + + def test_each_code_hunk_undone_alone_is_caught_or_not(self): + repo = Repo(self) + repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n', + "d3d12/crates/foo/src/lib.rs": self.BASE}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace( + " 5\n", " 6\n").replace("fn value_is_one() {\n assert_eq!(super::value(), 1);", + "fn value_is_two() {\n assert_eq!(super::value(), 2);")}) + code, r, _ = repo.run("--mutate") + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, "not caught")]) + text = rg.report(r) + self.assertIn("mutations (2 hunks undone one at a time): 1 caught, 1 not caught", text) + self.assertIn("d3d12/crates/foo/src/lib.rs:17: not caught", text) + # The worktree is back on the base afterwards: the mutations left nothing behind. + tree = os.path.join(repo.dir, ".git", "red-green", "tree") + status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout + self.assertEqual(status, "") + + def test_a_python_fix_undone_is_caught(self): + repo = Repo(self) + repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": Python.TEST}) + code, r, _ = repo.run("--no-cargo", "--mutate") + self.assertEqual(r["verdict"], "red then green", r) + self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")]) + + def test_no_mutation_without_the_option(self): + repo = Repo(self) + repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": Python.TEST}) + _code, r, _ = repo.run("--no-cargo") + self.assertIsNone(r["mutations"]) + + class CompilerCrash(unittest.TestCase): def fixed_repo(self): repo = crate_repo(self) -- cgit v1.2.3 From de6db4b7337a09e57f49f2f4d727521e3e6df811 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:03:10 +0100 Subject: scripts: red_green.py removes the work tree's __pycache__ before each Python run, so no test runs stale bytecode (review) -B only stops writing bytecode. An ignored .pyc left in the work tree (git clean keeps it) ran instead of the reverted source: red passed and an undone hunk was not caught. -X pycache_prefix would cover the unittest process only, not the processes its tests start; removing the folders covers both. --- docs/testing.md | 9 +++++---- scripts/red_green.py | 13 ++++++++++++- tests/test_red_green.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 5 deletions(-) (limited to 'scripts') diff --git a/docs/testing.md b/docs/testing.md index b213c71d2..d5d6cfbc7 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -144,10 +144,11 @@ python -I scripts/red_green.py cherry-picked with a 3-way merge. A conflict, or a pull request that changes no test, is "red not constructible". A hunk that mixes test and other code stays on the green side only. - It runs `cargo test --no-fail-fast` for the crates under `d3d12/crates` and `d3d12/apps` the pull request touches, - from `d3d12/` so the pinned toolchain applies. It also runs each changed `tests/**/test*.py` with unittest. Both - sides run in one worktree with one cargo target dir, red first, under `/red-green` (`--work-dir` - to move it). The worktree and the target dir stay for the next run, which then builds only what changed. The - target dir takes several GB; delete the folder (and run `git worktree prune`) when done. + from `d3d12/` so the pinned toolchain applies. It also runs each changed `tests/**/test*.py` with unittest, after + removing the worktree's `__pycache__` folders so that no test runs stale bytecode. Both sides run in one worktree + with one cargo target dir, red first, under `/red-green` (`--work-dir` to move it). The worktree + and the target dir stay for the next run, which then builds only what changed. The target dir takes several GB; + delete the folder (and run `git worktree prune`) when done. - It prints the tests that go from red to green, those that pass on red and fail on green, those that fail on both (failing on `main` too), and those found on one side only. The verdict is one of: `red then green` (exit 0), `no red`, `red does not build`, `green fails`, `red not constructible`, `green not constructible`, `no tests ran`, diff --git a/scripts/red_green.py b/scripts/red_green.py index 57dd8de6a..6c5102857 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -32,6 +32,7 @@ import argparse import json import os import re +import shutil import subprocess import sys import tempfile @@ -322,11 +323,21 @@ PY_TEST = re.compile(r"^(\w+) \(([\w.]+)\)(?:\n[^\n]*?)? \.\.\. (ok|FAIL|ERROR|s re.M) +def drop_bytecode(tree: Path) -> None: + """Removes every `__pycache__` folder of the work tree. Python runs a .pyc instead of its source when the source + time and size it records still match (an undone change of the same size within the same second) or when it is an + unchecked-hash one, and `git clean` keeps them (they are ignored). An option of the run's own Python, such as + `-X pycache_prefix`, would not reach the processes its tests start.""" + for folder in [p for p in tree.rglob("__pycache__") if p.is_dir()]: + shutil.rmtree(folder) + + def python_tests(tree: Path, files: list[str]) -> dict: tests, no_build = {}, [] + drop_bytecode(tree) for f in files: start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) - # -B: no bytecode. An undone change of the same size within the same second would run the stale .pyc. + # -B only stops writing bytecode, not reading it: drop_bytecode() above keeps stale bytecode out. r = subprocess.run([sys.executable, "-I", "-B", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, "-v"], cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) diff --git a/tests/test_red_green.py b/tests/test_red_green.py index be4a60c2e..e28f87c68 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -2,6 +2,7 @@ import io import json import os +import py_compile import subprocess import sys import tempfile @@ -235,6 +236,36 @@ class Python(unittest.TestCase): self.assertIn("does not import", r["red"]["no_build"][0]) self.assertEqual(code, 1) + # The same test, and once more in a process it starts, as the tests of a command-line tool do. + CHILD_TEST = TEST + ( + "\n def test_two_in_a_child(self):\n" + " import subprocess\n" + " tools = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools')\n" + " code = 'import sys; sys.path.insert(0, sys.argv[1]); import bar; print(bar.two())'\n" + " out = subprocess.run([sys.executable, '-I', '-c', code, tools], capture_output=True, text=True)\n" + " self.assertEqual(out.stdout.strip(), '2')\n") + + def test_stale_bytecode_in_the_work_tree_is_never_run(self): + repo = Repo(self) + repo.commit("base", {".gitignore": "__pycache__/\n", "tools/bar.py": "def two():\n return 1\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": self.CHILD_TEST}) + self.assertEqual(repo.run("--no-cargo")[1]["verdict"], "red then green") + # An ignored .pyc of the fixed bar.py left in the work tree (`git clean` keeps ignored files). An unchecked-hash + # .pyc is taken without looking at the source, like a timestamp one whose time and size still match. + tools = os.path.join(repo.dir, ".git", "red-green", "tree", "tools") + src = os.path.join(repo.tmp.name, "bar_fixed.py") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write("def two():\n return 2\n") + py_compile.compile(src, cfile=os.path.join(tools, "__pycache__", f"bar.{sys.implementation.cache_tag}.pyc"), + doraise=True, invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH) + code, r, _ = repo.run("--no-cargo", "--mutate") + # Read, it would make red pass in both processes and the undone fix not caught. + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual(r["rows"]["red_to_green"], ["tests/test_bar.py::test_bar.T.test_two", + "tests/test_bar.py::test_bar.T.test_two_in_a_child"]) + self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")]) + class Mutation(unittest.TestCase): # Two code changes far enough apart to be two hunks: the tested one and one no test looks at. -- cgit v1.2.3 From 745808fc3b3d4779e1165633775f7463fdb105be Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:07:04 +0100 Subject: scripts: red_green.py --mutate-timeout stops a mutated run that hangs and reports it as caught by timeout (review) Each command of a mutated run (cargo test, one Python test file) is stopped after --mutate-timeout seconds (600) together with the processes it started (taskkill /T on Windows, the process group elsewhere): a test binary or a process a test starts would otherwise keep the output pipe open. The hunk is then 'caught by timeout', apart from 'caught'. The red and green sides have no timeout, as before. --- docs/testing.md | 3 ++ scripts/red_green.py | 113 ++++++++++++++++++++++++++++++++++-------------- tests/test_red_green.py | 25 +++++++++++ 3 files changed, 109 insertions(+), 32 deletions(-) (limited to 'scripts') diff --git a/docs/testing.md b/docs/testing.md index d5d6cfbc7..0cd88f7df 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -164,6 +164,9 @@ python -I scripts/red_green.py then green fails, `not caught` when they all still pass, `does not build`, or `does not apply` (`main` moved those lines since). It tries at most `--mutate-max` hunks (10). A `not caught` hunk is code no new test looks at; it does not change the verdict. +- Each command of a mutated run (`cargo test`, one Python test file) is stopped with the processes it started after + `--mutate-timeout` seconds (600), and the hunk is `caught by timeout`: the undone code made a test hang, or the + build took longer than that (raise the option for a crate that builds slowly). - `--crate ` adds a crate, `--no-cargo` or `--no-python` leaves one kind out, `--base ` tests on another base, and `--no-fetch` uses the refs as they are. diff --git a/scripts/red_green.py b/scripts/red_green.py index 6c5102857..08c5ebc35 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -3,6 +3,7 @@ python -I scripts/red_green.py [--base REF] [--remote NAME] [--no-fetch] [--work-dir DIR] [--crate NAME ...] [--no-cargo] [--no-python] [--cargo PATH] [--json] + [--mutate [--mutate-max N] [--mutate-timeout SECONDS]] Green is the base (`/main` after a fetch, by default) with the pull request merged. Red is the base with only the pull request's tests. A test that fails on red and passes on green shows that the change is what makes it @@ -33,6 +34,7 @@ import json import os import re import shutil +import signal import subprocess import sys import tempfile @@ -53,6 +55,42 @@ def run(args: list[str], cwd: Path, env: dict | None = None, data: bytes | None return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True) +def kill_tree(p: subprocess.Popen) -> None: + """Stops `p` and the processes it started (a test binary under cargo, a process a test starts).""" + if os.name == "nt": + subprocess.run(["taskkill", "/F", "/T", "/PID", str(p.pid)], capture_output=True) + else: + try: + os.killpg(p.pid, signal.SIGKILL) + except ProcessLookupError: + pass + p.kill() + + +def run_output(cmd: list[str], cwd: Path, env: dict | None = None, + timeout: float | None = None) -> tuple[int | None, str]: + """The exit code and the output (error output included) of `cmd`. Past `timeout` seconds it is stopped with the + processes it started, whose copies of the output pipe would hold the read open, and the exit code is None.""" + if timeout is None: + r = subprocess.run(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + return r.returncode, r.stdout.decode("utf-8", "replace") + p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + start_new_session=os.name != "nt") + try: + out, _ = p.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + kill_tree(p) + try: + out, _ = p.communicate(timeout=60) + except subprocess.TimeoutExpired: # a process outside the tree still holds the pipe: leave its output + out = b"" + return None, out.decode("utf-8", "replace") + except BaseException: # Ctrl+C: on POSIX the new session keeps it from the processes started + kill_tree(p) + raise + return p.returncode, out.decode("utf-8", "replace") + + def git(cwd: Path, *args: str, env: dict | None = None, data: bytes | None = None, check: bool = True) -> str: r = run(["git", *args], cwd, env, data) if check and r.returncode != 0: @@ -284,12 +322,11 @@ COMPILER_CRASH = re.compile( r"|(internal compiler error)|(the compiler unexpectedly panicked)|(memory allocation of \d+ bytes failed)") -def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: +def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path, timeout: float | None) -> dict: cmd = [sys.executable, cargo] if cargo.endswith(".py") else [cargo] cmd += ["test", "--locked", "--no-fail-fast"] + [a for c in crates for a in ("-p", c)] env = dict(os.environ, CARGO_TARGET_DIR=str(target)) - r = subprocess.run(cmd, cwd=tree / "d3d12", env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - out = r.stdout.decode("utf-8", "replace") + code, out = run_output(cmd, tree / "d3d12", env, timeout) tests, unit, error = {}, "?", None for line in out.splitlines(): m = UNIT.match(line) @@ -301,19 +338,20 @@ def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: tests[f"{unit}::{m.group(1)}"] = {"ok": "ok", "FAILED": "failed", "ignored": "ignored"}[m.group(2)] elif error is None and CARGO_ERROR.match(line): error = line.strip() - no_build = r.returncode != 0 and not tests + no_build = code is not None and code != 0 and not tests crash = COMPILER_CRASH.search(out) if no_build else None - return {"tests": tests, "no_build": (error or f"cargo exit {r.returncode}") if no_build and not crash else None, - "crash": next(g for g in crash.groups() if g) if crash else None} + return {"tests": tests, "no_build": (error or f"cargo exit {code}") if no_build and not crash else None, + "crash": next(g for g in crash.groups() if g) if crash else None, "timed_out": code is None} -def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: - first = cargo_once(tree, crates, cargo, target) +def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path, timeout: float | None) -> dict: + first = cargo_once(tree, crates, cargo, target, timeout) if not first["crash"]: - return {"tests": first["tests"], "no_build": first["no_build"]} + return {"tests": first["tests"], "no_build": first["no_build"], "timed_out": first["timed_out"]} print(f"red_green: the compiler crashed ({first['crash']}), running again", file=sys.stderr) - again = cargo_once(tree, crates, cargo, target) - result = {"tests": again["tests"], "no_build": again["no_build"], "rerun_after": first["crash"]} + again = cargo_once(tree, crates, cargo, target, timeout) + result = {"tests": again["tests"], "no_build": again["no_build"], "rerun_after": first["crash"], + "timed_out": again["timed_out"]} if again["crash"]: result["compiler_crashed"] = again["crash"] return result @@ -332,16 +370,15 @@ def drop_bytecode(tree: Path) -> None: shutil.rmtree(folder) -def python_tests(tree: Path, files: list[str]) -> dict: - tests, no_build = {}, [] +def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict: + tests, no_build, timed_out = {}, [], False drop_bytecode(tree) for f in files: start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) # -B only stops writing bytecode, not reading it: drop_bytecode() above keeps stale bytecode out. - r = subprocess.run([sys.executable, "-I", "-B", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, - "-v"], - cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - out = r.stdout.decode("utf-8", "replace") + code, out = run_output([sys.executable, "-I", "-B", "-m", "unittest", "discover", "-s", start, + "-p", Path(f).name, "-v"], tree, timeout=timeout) + timed_out |= code is None found = 0 for name, where, status in PY_TEST.findall(out): if "_FailedTest" in where: @@ -350,19 +387,22 @@ def python_tests(tree: Path, files: list[str]) -> dict: key = where if where.endswith("." + name) else f"{where}.{name}" tests[f"{f}::{key}"] = {"ok": "ok", "skipped": "ignored", "expected failure": "ok"}.get(status, "failed") found += 1 - if not found and r.returncode != 0 and f"{f}: does not import" not in no_build: - no_build.append(f"{f}: exit {r.returncode}") - return {"tests": tests, "no_build": "; ".join(no_build) or None} - - -def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path) -> dict: - result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None} - for part in ([cargo_tests(tree, crates, cargo, target)] if crates else []) + \ - ([python_tests(tree, py_files)] if py_files else []): + if not found and code not in (0, None) and f"{f}: does not import" not in no_build: + no_build.append(f"{f}: exit {code}") + return {"tests": tests, "no_build": "; ".join(no_build) or None, "timed_out": timed_out} + + +def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path, + timeout: float | None = None) -> dict: + """The tests of one side. With a timeout (the mutated runs), a command that runs past it is stopped and the side + is marked `timed_out`.""" + result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None, "timed_out": False} + for part in ([cargo_tests(tree, crates, cargo, target, timeout)] if crates else []) + \ + ([python_tests(tree, py_files, timeout)] if py_files else []): result["tests"].update(part["tests"]) if part["no_build"]: result["no_build"].append(part["no_build"]) - for key in ("compiler_crashed", "rerun_after"): + for key in ("compiler_crashed", "rerun_after", "timed_out"): result[key] = result[key] or part.get(key) return result @@ -462,6 +502,9 @@ def main(argv: list[str] | None = None) -> int: p.add_argument("--mutate", action="store_true", help="undo each code hunk alone on green and run the tests again (caught or not)") p.add_argument("--mutate-max", type=int, default=10, help="the most hunks --mutate tries (10)") + p.add_argument("--mutate-timeout", type=float, default=600, metavar="SECONDS", + help="stop a command of a mutated run (cargo test, one Python test file) after this long and count " + "the hunk as caught by timeout (600)") a = p.parse_args(argv) try: repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) @@ -532,7 +575,8 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer targets = list(rows["red_to_green"]) if targets: print("red_green: mutations...", file=sys.stderr) - mutations = mutate(repo, tree, merge_base, head, targets, crates, py_files, a.cargo, target, a.mutate_max) + mutations = mutate(repo, tree, merge_base, head, targets, crates, py_files, a.cargo, target, a.mutate_max, + a.mutate_timeout) if mutations is None: checkout(repo, tree, base_commit) git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) @@ -583,9 +627,10 @@ def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, s def mutate(repo: Path, tree: Path, merge_base: str, head: str, targets: list[str], crates: list[str], - py_files: list[str], cargo: str, target: Path, most: int) -> list[dict] | None: + py_files: list[str], cargo: str, target: Path, most: int, timeout: float) -> list[dict] | None: """Undoes each code hunk alone on the green tree and runs the tests again: a hunk is caught when one of the tests - that went red then green fails. Returns None when the tree could not be put back (the caller rebuilds it).""" + that went red then green fails, or caught by timeout when a command runs past `timeout` seconds. Returns None + when the tree could not be put back (the caller rebuilds it).""" results = [] for path, line, patch in code_hunks(repo, merge_base, head)[:most]: entry = {"file": path, "line": line, "result": None} @@ -594,13 +639,17 @@ def mutate(repo: Path, tree: Path, merge_base: str, head: str, targets: list[str entry["result"] = "does not apply" results.append(entry) continue - s = side(tree, crates, [f for f in py_files if (tree / f).is_file()], cargo, target) + s = side(tree, crates, [f for f in py_files if (tree / f).is_file()], cargo, target, timeout) if s.get("compiler_crashed"): entry["result"] = "compiler crashed" + elif any(s["tests"].get(t) == "failed" for t in targets): + entry["result"] = "caught" + elif s["timed_out"]: + entry["result"] = "caught by timeout" elif not any(t in s["tests"] for t in targets): entry["result"] = "does not build" else: - entry["result"] = "caught" if any(s["tests"].get(t) == "failed" for t in targets) else "not caught" + entry["result"] = "not caught" results.append(entry) if run(["git", "apply", "--unidiff-zero", "-"], tree, data=patch.encode()).returncode != 0: return None diff --git a/tests/test_red_green.py b/tests/test_red_green.py index e28f87c68..655ba13d6 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -6,6 +6,7 @@ import py_compile import subprocess import sys import tempfile +import time import unittest from contextlib import redirect_stderr, redirect_stdout @@ -300,6 +301,30 @@ class Mutation(unittest.TestCase): self.assertEqual(r["verdict"], "red then green", r) self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")]) + def test_a_mutated_run_that_hangs_is_caught_by_timeout(self): + # Undone alone, the second hunk makes the test start a process that sleeps. Red has neither hunk, so it does + # not hang there. + base = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) + + "\ndef settled():\n return False\n") + test = ("import os, subprocess, sys, unittest\n" + "sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools'))\n" + "import bar\n\n\nclass T(unittest.TestCase):\n def test_two(self):\n" + " if bar.two() == 2 and not bar.settled():\n" + " subprocess.run([sys.executable, '-c', 'import time; time.sleep(120)'])\n" + " self.assertEqual(bar.two(), 2)\n") + repo = Repo(self) + repo.commit("base", {"tools/bar.py": base}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2").replace("False", "True"), + "tests/test_bar.py": test}) + start = time.monotonic() + _code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "5") + self.assertEqual(r["verdict"], "red then green", r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "caught by timeout")]) + self.assertIn("mutations (2 hunks undone one at a time): 1 caught, 1 caught by timeout", rg.report(r)) + # The sleeping process was stopped with the test's: left running, it would hold the output pipe for 120 s. + self.assertLess(time.monotonic() - start, 60) + def test_no_mutation_without_the_option(self): repo = Repo(self) repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) -- cgit v1.2.3 From 89274bac6e991f404608a371c2cab614bb1475aa Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:11:01 +0100 Subject: scripts: red_green.py --mutate says when it stopped, why nothing was undone, and which added files it does not mutate (review) A hunk that cannot be put back no longer drops the whole mutations section: the report and --json (mutations_stopped) name the hunk, the reason and how many hunks were not tried. With --mutate, mutations is always a list and mutations_not_run says why none was undone: nothing to undo (a test-only pull request), or no test went red then green. Files the pull request adds stay unmutated, and the report and --json (added_not_mutated) now list them. Verdicts and exit codes are unchanged. --- docs/testing.md | 7 +++++ scripts/red_green.py | 79 +++++++++++++++++++++++++++++++------------------ tests/test_red_green.py | 67 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 125 insertions(+), 28 deletions(-) (limited to 'scripts') diff --git a/docs/testing.md b/docs/testing.md index 0cd88f7df..a7b1b4ea9 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -164,6 +164,13 @@ python -I scripts/red_green.py then green fails, `not caught` when they all still pass, `does not build`, or `does not apply` (`main` moved those lines since). It tries at most `--mutate-max` hunks (10). A `not caught` hunk is code no new test looks at; it does not change the verdict. +- Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it. + The report lists them (`not mutated, added by the pull request`), so a fix whose code sits in a new file is not + read as covered. When no hunk is undone, the report says why: `nothing to undo` when the pull request changes no + Rust or Python code outside its tests (a test-only one, whose `no red` then says nothing against its test), or + `not run` when no test went red then green. A hunk that cannot be put back (a test wrote into the code) stops the + mutations, and the report names that hunk and the reason. `--json` has these in `mutations_not_run`, + `mutations_stopped` and `added_not_mutated`. - Each command of a mutated run (`cargo test`, one Python test file) is stopped with the processes it started after `--mutate-timeout` seconds (600), and the hunk is `caught by timeout`: the undone code made a test hang, or the build took longer than that (raise the option for a crate that builds slowly). diff --git a/scripts/red_green.py b/scripts/red_green.py index 08c5ebc35..69d9d18b7 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -478,11 +478,19 @@ def report(r: dict) -> str: out.append(f" ... {len(rows[key]) - 40} more") out.append(f"pass on both: {rows['pass_on_both']}") if r.get("mutations") is not None: - counts = Counter(m["result"] for m in r["mutations"]) - out.append(f"mutations ({len(r['mutations'])} hunks undone one at a time): " - + ", ".join(f"{n} {k}" for k, n in sorted(counts.items())) if r["mutations"] else - "mutations: no code hunk outside the tests") - out += [f" {m['file']}:{m['line']}: {m['result']}" for m in r["mutations"]] + if r.get("mutations_not_run"): + out.append(f"mutations: {r['mutations_not_run']}") + else: + counts = Counter(m["result"] for m in r["mutations"]) + out.append(f"mutations ({len(r['mutations'])} hunks undone one at a time): " + + ", ".join(f"{n} {k}" for k, n in sorted(counts.items()))) + out += [f" {m['file']}:{m['line']}: {m['result']}" for m in r["mutations"]] + stop = r.get("mutations_stopped") + if stop: + out.append(f"mutations stopped at {stop['file']}:{stop['line']}: {stop['why']}; " + f"hunks not tried: {stop['untried']}") + if r.get("added_not_mutated"): + out.append("not mutated, added by the pull request: " + ", ".join(r["added_not_mutated"])) out.append(f"verdict: {r['verdict']}") return "\n".join(out) @@ -570,32 +578,44 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer print("red_green: green side...", file=sys.stderr) green = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) rows = compare(red, green) - mutations = None - if a.mutate and green is not None: - targets = list(rows["red_to_green"]) - if targets: + # With --mutate, `mutations` is a list (empty when no hunk was undone, and `mutations_not_run` says why). + mutations, not_run, stopped, added = None, None, None, None + if a.mutate: + hunks, added, mutations = code_hunks(repo, merge_base, head), code_files(repo, merge_base, head, "A"), [] + if green is None: + not_run = "not run: there is no green side" + elif not hunks: + not_run = ("nothing to undo in the files it modifies: its code changes are in files it adds" if added else + "nothing to undo: the diff changes no Rust or Python code outside its tests") + elif not rows["red_to_green"]: + not_run = "not run: no test went red then green, so none can catch a hunk" + else: print("red_green: mutations...", file=sys.stderr) - mutations = mutate(repo, tree, merge_base, head, targets, crates, py_files, a.cargo, target, a.mutate_max, - a.mutate_timeout) - if mutations is None: - checkout(repo, tree, base_commit) - git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) + mutations, stopped = mutate(tree, hunks[:a.mutate_max], rows["red_to_green"], crates, py_files, a.cargo, + target, a.mutate_timeout) checkout(repo, tree, base_commit) return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, "python_files": py_files, "red": red, "green": green, "rows": rows, "mutations": mutations, + "mutations_not_run": not_run, "mutations_stopped": stopped, "added_not_mutated": added, "verdict": verdict(red_why, green_why, red, green, rows)} +def code_files(repo: Path, merge_base: str, head: str, status: str) -> list[str]: + """The Rust and Python files outside the tests that the pull request changes with git status `status` (M + modified, A added). Added files are not mutated: undoing one deletes it, which only shows that something uses it.""" + paths = git(repo, "diff", "--name-only", "--no-renames", f"--diff-filter={status}", merge_base, head).splitlines() + return [p for p in paths if not is_test_file(p) + and (p.endswith(".rs") or (p.endswith(".py") and not p.startswith("tests/")))] + + def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, str]]: - """(file, first changed line in the pull request, patch) for each hunk of its code outside its tests: the hunks - a mutation undoes one at a time. Without context, so that a test changed next to the code is a hunk of its own (a - hunk does not apply where `main` moved the lines since).""" + """(file, first changed line in the pull request, patch) for each hunk of its code outside its tests in the files + it modifies: the hunks a mutation undoes one at a time. Without context, so that a test changed next to the code is + a hunk of its own (a hunk does not apply where `main` moved the lines since).""" out = [] - for path in git(repo, "diff", "--name-only", "--no-renames", "--diff-filter=M", merge_base, head).splitlines(): - if is_test_file(path) or not (path.endswith(".rs") or (path.endswith(".py") and not path.startswith("tests/"))): - continue + for path in code_files(repo, merge_base, head, "M"): lines = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path).split("\n") first = next((i for i, line in enumerate(lines) if line.startswith("@@")), None) if first is None: @@ -626,13 +646,13 @@ def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, s return out -def mutate(repo: Path, tree: Path, merge_base: str, head: str, targets: list[str], crates: list[str], - py_files: list[str], cargo: str, target: Path, most: int, timeout: float) -> list[dict] | None: +def mutate(tree: Path, hunks: list[tuple[str, int, str]], targets: list[str], crates: list[str], py_files: list[str], + cargo: str, target: Path, timeout: float) -> tuple[list[dict], dict | None]: """Undoes each code hunk alone on the green tree and runs the tests again: a hunk is caught when one of the tests - that went red then green fails, or caught by timeout when a command runs past `timeout` seconds. Returns None - when the tree could not be put back (the caller rebuilds it).""" + that went red then green fails, or caught by timeout when a command runs past `timeout` seconds. Stops at a hunk + that cannot be put back (a test wrote into the code): the second value says where and why.""" results = [] - for path, line, patch in code_hunks(repo, merge_base, head)[:most]: + for path, line, patch in hunks: entry = {"file": path, "line": line, "result": None} undo = run(["git", "apply", "-R", "--unidiff-zero", "-"], tree, data=patch.encode()) if undo.returncode != 0: @@ -651,9 +671,12 @@ def mutate(repo: Path, tree: Path, merge_base: str, head: str, targets: list[str else: entry["result"] = "not caught" results.append(entry) - if run(["git", "apply", "--unidiff-zero", "-"], tree, data=patch.encode()).returncode != 0: - return None - return results + back = run(["git", "apply", "--unidiff-zero", "-"], tree, data=patch.encode()) + if back.returncode != 0: + why = back.stderr.decode("utf-8", "replace").strip().splitlines() + return results, {"file": path, "line": line, "untried": len(hunks) - len(results), + "why": "git apply could not put the hunk back" + (f" ({why[-1]})" if why else "")} + return results, None if __name__ == "__main__": diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 655ba13d6..29ec4e365 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -325,6 +325,72 @@ class Mutation(unittest.TestCase): # The sleeping process was stopped with the test's: left running, it would hold the output pipe for 120 s. self.assertLess(time.monotonic() - start, 60) + def test_a_hunk_that_cannot_be_put_back_stops_the_mutations_and_says_where(self): + # The test writes over the code it tests when it finds it wrong, so the undone hunk no longer applies back. + base = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) + + "\ndef spare():\n return 5\n") + test = Python.TEST.replace( + " def test_two(self):\n", + " def test_two(self):\n if bar.two() != 2:\n" + " with open(bar.__file__, 'w', encoding='utf-8', newline='\\n') as f:\n" + " f.write('def two():\\n return 3\\n')\n") + repo = Repo(self) + repo.commit("base", {"tools/bar.py": base}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2").replace("return 5", "return 6"), + "tests/test_bar.py": test}) + code, r, _ = repo.run("--no-cargo", "--mutate") + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught")]) + stop = r["mutations_stopped"] + self.assertEqual((stop["file"], stop["line"], stop["untried"]), ("tools/bar.py", 2, 1), stop) + self.assertIn("could not put the hunk back", stop["why"]) + self.assertIn("mutations stopped at tools/bar.py:2: git apply could not put the hunk back", rg.report(r)) + self.assertIn("hunks not tried: 1", rg.report(r)) + tree = os.path.join(repo.dir, ".git", "red-green", "tree") + status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout + self.assertEqual(status, "") + + def test_a_test_only_pull_request_has_nothing_to_undo(self): + repo = Repo(self) + repo.commit("base", {"tools/bar.py": "def two():\n return 2\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("test", {"tests/test_bar.py": Python.TEST}) + code, r, _ = repo.run("--no-cargo", "--mutate") + # The verdict and exit code are those of any test that passes on both. + self.assertEqual((code, r["verdict"]), (1, "no red"), r) + self.assertEqual(r["mutations"], []) + self.assertEqual(r["mutations_not_run"], "nothing to undo: the diff changes no Rust or Python code outside its " + "tests") + self.assertIn("mutations: nothing to undo: the diff changes no Rust or Python code outside its tests", + rg.report(r)) + + def test_code_with_no_test_gone_red_is_not_mutated_and_said_so(self): + repo = Repo(self) + repo.commit("base", {"tools/bar.py": "def two():\n return 2\n\n\ndef three():\n return 3\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("change", {"tools/bar.py": "def two():\n return 2\n\n\ndef three():\n return 4\n", + "tests/test_bar.py": Python.TEST}) + code, r, _ = repo.run("--no-cargo", "--mutate") + self.assertEqual((code, r["verdict"]), (1, "no red"), r) + self.assertEqual(r["mutations"], []) + self.assertIn("mutations: not run: no test went red then green", rg.report(r)) + + def test_files_the_pull_request_adds_are_listed_as_not_mutated(self): + repo = Repo(self) + repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/helper.py": "def value():\n return 2\n", + "tools/bar.py": "from helper import value\n\n\ndef two():\n return value()\n", + "tests/test_bar.py": Python.TEST}) + code, r, _ = repo.run("--no-cargo", "--mutate") + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], + [("tools/bar.py", "caught"), ("tools/bar.py", "caught")]) + # helper.py holds the change and is never undone: the report says so rather than read as full coverage. + self.assertEqual(r["added_not_mutated"], ["tools/helper.py"]) + self.assertIn("not mutated, added by the pull request: tools/helper.py", rg.report(r)) + def test_no_mutation_without_the_option(self): repo = Repo(self) repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) @@ -332,6 +398,7 @@ class Mutation(unittest.TestCase): repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": Python.TEST}) _code, r, _ = repo.run("--no-cargo") self.assertIsNone(r["mutations"]) + self.assertNotIn("mutations", rg.report(r)) class CompilerCrash(unittest.TestCase): -- cgit v1.2.3 From df480832d78e0ce33af4b5be7837c7cd48602374 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:42:20 +0100 Subject: scripts: red_green.py keeps the test files a tree has in one place, side() (review) --- scripts/red_green.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'scripts') diff --git a/scripts/red_green.py b/scripts/red_green.py index 69d9d18b7..20bfd50b6 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -394,8 +394,9 @@ def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict: def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path, timeout: float | None = None) -> dict: - """The tests of one side. With a timeout (the mutated runs), a command that runs past it is stopped and the side - is marked `timed_out`.""" + """The tests of one side: the crates, and those of the Python test files that this tree has. With a timeout (the + mutated runs), a command that runs past it is stopped and the side is marked `timed_out`.""" + py_files = [f for f in py_files if (tree / f).is_file()] result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None, "timed_out": False} for part in ([cargo_tests(tree, crates, cargo, target, timeout)] if crates else []) + \ ([python_tests(tree, py_files, timeout)] if py_files else []): @@ -566,7 +567,7 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer red_why = "not constructible: the tests conflict with the base in " + ", ".join(stuck) else: print("red_green: red side...", file=sys.stderr) - red = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) + red = side(tree, crates, py_files, a.cargo, target) green, green_why = None, None checkout(repo, tree, base_commit) @@ -576,7 +577,7 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer green_why = "not constructible: the pull request conflicts with the base in " + ", ".join(stuck) else: print("red_green: green side...", file=sys.stderr) - green = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) + green = side(tree, crates, py_files, a.cargo, target) rows = compare(red, green) # With --mutate, `mutations` is a list (empty when no hunk was undone, and `mutations_not_run` says why). mutations, not_run, stopped, added = None, None, None, None @@ -659,7 +660,7 @@ def mutate(tree: Path, hunks: list[tuple[str, int, str]], targets: list[str], cr entry["result"] = "does not apply" results.append(entry) continue - s = side(tree, crates, [f for f in py_files if (tree / f).is_file()], cargo, target, timeout) + s = side(tree, crates, py_files, cargo, target, timeout) if s.get("compiler_crashed"): entry["result"] = "compiler crashed" elif any(s["tests"].get(t) == "failed" for t in targets): -- cgit v1.2.3 From a7a22ff874b88414b606b082c1250724f8ea8c9b Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:43:16 +0100 Subject: scripts: red_green.py removes only the work tree's own __pycache__ folders, never through a link or junction (review) Path.rglob follows directory junctions on Windows, so a junction in the tree to an outside folder had that folder's __pycache__ deleted, and a link itself named __pycache__ made shutil.rmtree raise. The walk now skips symbolic links and every reparse point (junctions included). --- scripts/red_green.py | 14 ++++++++++++-- tests/test_red_green.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) (limited to 'scripts') diff --git a/scripts/red_green.py b/scripts/red_green.py index 20bfd50b6..db2320f8d 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -35,6 +35,7 @@ import os import re import shutil import signal +import stat import subprocess import sys import tempfile @@ -365,8 +366,17 @@ def drop_bytecode(tree: Path) -> None: """Removes every `__pycache__` folder of the work tree. Python runs a .pyc instead of its source when the source time and size it records still match (an undone change of the same size within the same second) or when it is an unchecked-hash one, and `git clean` keeps them (they are ignored). An option of the run's own Python, such as - `-X pycache_prefix`, would not reach the processes its tests start.""" - for folder in [p for p in tree.rglob("__pycache__") if p.is_dir()]: + `-X pycache_prefix`, would not reach the processes its tests start. Links (symbolic links, and junctions, which + `is_symlink()` does not see) are neither followed nor removed: what they point at is not the tree's.""" + folders, todo = [], [tree] + while todo: + with os.scandir(todo.pop()) as entries: + for e in entries: + link = e.is_symlink() or bool(getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0) + & stat.FILE_ATTRIBUTE_REPARSE_POINT) + if not link and e.is_dir(follow_symlinks=False): + (folders if e.name == "__pycache__" else todo).append(e.path) + for folder in folders: shutil.rmtree(folder) diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 29ec4e365..cfdf1b20d 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -9,6 +9,7 @@ import tempfile import time import unittest from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "scripts")) @@ -268,6 +269,41 @@ class Python(unittest.TestCase): self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")]) +def link_dir(test, link, target): + """A directory junction on Windows (no privilege needed), a symbolic link elsewhere; removed at the end of `test` + before its temporary folder, so that the folder's cleanup does not go through it.""" + if os.name == "nt": + subprocess.run(["cmd", "/c", "mklink", "/J", link, target], check=True, capture_output=True) + test.addCleanup(os.rmdir, link) + else: + os.symlink(target, link, target_is_directory=True) + test.addCleanup(os.unlink, link) + + +class DropBytecode(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory(prefix="red-green-test-", ignore_cleanup_errors=True) + self.addCleanup(tmp.cleanup) + self.tree, self.outside = os.path.join(tmp.name, "tree"), os.path.join(tmp.name, "outside") + for folder in (os.path.join(self.tree, "tools", "__pycache__"), os.path.join(self.outside, "__pycache__")): + os.makedirs(folder) + with open(os.path.join(folder, "x.pyc"), "wb") as f: + f.write(b"x") + + def check(self): + rg.drop_bytecode(Path(self.tree)) + self.assertFalse(os.path.exists(os.path.join(self.tree, "tools", "__pycache__"))) + self.assertTrue(os.path.isfile(os.path.join(self.outside, "__pycache__", "x.pyc"))) + + def test_a_link_out_of_the_tree_is_not_followed(self): + link_dir(self, os.path.join(self.tree, "tools", "link"), self.outside) + self.check() + + def test_a_link_named_pycache_is_left_alone(self): + link_dir(self, os.path.join(self.tree, "__pycache__"), os.path.join(self.outside, "__pycache__")) + self.check() + + class Mutation(unittest.TestCase): # Two code changes far enough apart to be two hunks: the tested one and one no test looks at. BASE = ("pub fn value() -> u32 {\n 1\n}\n\n" + "".join(f"// padding line {i}\n" for i in range(10)) -- cgit v1.2.3 From 312bf7c892aab1838980385edb039d47ff1c00de Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:49:46 +0100 Subject: scripts: red_green.py stops what a mutated run leaves behind, so an orphan holding its output does not hold the run (review) taskkill /T on a command that has already ended finds no tree: a child it left behind kept the output pipe open, the run waited for the timeout and a real caught read caught by timeout. A mutated run now writes its output to a temporary file and, on Windows, runs in a job object (kill on close) that its children join; once the command ends or times out, the job (the process group elsewhere) is stopped. --- docs/testing.md | 3 +- scripts/red_green.py | 92 +++++++++++++++++++++++++++++++++++++------------ tests/test_red_green.py | 42 +++++++++++++++------- 3 files changed, 102 insertions(+), 35 deletions(-) (limited to 'scripts') diff --git a/docs/testing.md b/docs/testing.md index 4ec81fec6..c0d1d7c49 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -174,7 +174,8 @@ python -I scripts/red_green.py `mutations_stopped` and `added_not_mutated`. - Each command of a mutated run (`cargo test`, one Python test file) is stopped with the processes it started after `--mutate-timeout` seconds (600), and the hunk is `caught by timeout`: the undone code made a test hang, or the - build took longer than that (raise the option for a crate that builds slowly). + build took longer than that (raise the option for a crate that builds slowly). When the command ends, the + processes it left behind are stopped too (a Windows job object, the process group elsewhere). - `--crate ` adds a crate, `--no-cargo` or `--no-python` leaves one kind out, `--base ` tests on another base, and `--no-fetch` uses the refs as they are. diff --git a/scripts/red_green.py b/scripts/red_green.py index db2320f8d..f4eec79c6 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -56,40 +56,88 @@ def run(args: list[str], cwd: Path, env: dict | None = None, data: bytes | None return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True) -def kill_tree(p: subprocess.Popen) -> None: - """Stops `p` and the processes it started (a test binary under cargo, a process a test starts).""" - if os.name == "nt": - subprocess.run(["taskkill", "/F", "/T", "/PID", str(p.pid)], capture_output=True) - else: +if os.name == "nt": + import ctypes + from ctypes import wintypes + + class _JobLimits(ctypes.Structure): + """JOBOBJECT_EXTENDED_LIMIT_INFORMATION; only LimitFlags is set.""" + _fields_ = [("per_process_user_time", ctypes.c_int64), ("per_job_user_time", ctypes.c_int64), + ("limit_flags", wintypes.DWORD), ("min_working_set", ctypes.c_size_t), + ("max_working_set", ctypes.c_size_t), ("active_process_limit", wintypes.DWORD), + ("affinity", ctypes.c_size_t), ("priority_class", wintypes.DWORD), + ("scheduling_class", wintypes.DWORD), ("io_counters", ctypes.c_uint64 * 6), + ("process_memory_limit", ctypes.c_size_t), ("job_memory_limit", ctypes.c_size_t), + ("peak_process_memory_used", ctypes.c_size_t), ("peak_job_memory_used", ctypes.c_size_t)] + + _KERNEL32 = ctypes.WinDLL("kernel32", use_last_error=True) + _KERNEL32.CreateJobObjectW.restype = wintypes.HANDLE + _KERNEL32.CreateJobObjectW.argtypes = (ctypes.c_void_p, wintypes.LPCWSTR) + _KERNEL32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) + _KERNEL32.OpenProcess.restype = wintypes.HANDLE + _KERNEL32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) + _KERNEL32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE) + _KERNEL32.TerminateJobObject.argtypes = (wintypes.HANDLE, wintypes.UINT) + _KERNEL32.CloseHandle.argtypes = (wintypes.HANDLE,) + + +def job_of(p: subprocess.Popen): + """On Windows, a job object holding `p`, or None. The processes `p` starts join it, and closing it stops every + process in it (JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE): a process that outlives `p` is stopped with the job, where + `taskkill /T` no longer finds it once `p` has ended. A process `p` starts before it joins (its first instants) + stays out.""" + job = _KERNEL32.CreateJobObjectW(None, None) + if not job: + return None + limits = _JobLimits(limit_flags=0x2000) # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + handle = _KERNEL32.OpenProcess(0x0101, False, p.pid) # PROCESS_TERMINATE | PROCESS_SET_QUOTA + # 9: JobObjectExtendedLimitInformation + joined = (handle and _KERNEL32.SetInformationJobObject(job, 9, ctypes.byref(limits), ctypes.sizeof(limits)) + and _KERNEL32.AssignProcessToJobObject(job, handle)) + if handle: + _KERNEL32.CloseHandle(handle) + if not joined: + _KERNEL32.CloseHandle(job) + return None + return job + + +def stop_all(p: subprocess.Popen, job) -> None: + """Stops `p` and every process it started, still running or left behind: the job on Windows, the process group + elsewhere.""" + if job is not None: + _KERNEL32.TerminateJobObject(job, 1) + _KERNEL32.CloseHandle(job) + elif os.name != "nt": try: os.killpg(p.pid, signal.SIGKILL) except ProcessLookupError: pass - p.kill() + if p.poll() is None: + p.kill() def run_output(cmd: list[str], cwd: Path, env: dict | None = None, timeout: float | None = None) -> tuple[int | None, str]: - """The exit code and the output (error output included) of `cmd`. Past `timeout` seconds it is stopped with the - processes it started, whose copies of the output pipe would hold the read open, and the exit code is None.""" + """The exit code and the output (error output included) of `cmd`. With a timeout, the output goes to a file, so + that a process left behind holding it does not hold the run; once `cmd` ends, or after `timeout` seconds (then + the exit code is None), it is stopped with every process it started.""" if timeout is None: r = subprocess.run(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return r.returncode, r.stdout.decode("utf-8", "replace") - p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - start_new_session=os.name != "nt") - try: - out, _ = p.communicate(timeout=timeout) - except subprocess.TimeoutExpired: - kill_tree(p) + with tempfile.TemporaryFile() as log: + p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=log, stderr=subprocess.STDOUT, + start_new_session=os.name != "nt") + job = job_of(p) if os.name == "nt" else None try: - out, _ = p.communicate(timeout=60) - except subprocess.TimeoutExpired: # a process outside the tree still holds the pipe: leave its output - out = b"" - return None, out.decode("utf-8", "replace") - except BaseException: # Ctrl+C: on POSIX the new session keeps it from the processes started - kill_tree(p) - raise - return p.returncode, out.decode("utf-8", "replace") + code = p.wait(timeout=timeout) + except subprocess.TimeoutExpired: + code = None + finally: # Ctrl+C too: on POSIX the new session keeps it from the processes started + stop_all(p, job) + p.wait() + log.seek(0) + return code, log.read().decode("utf-8", "replace") def git(cwd: Path, *args: str, env: dict | None = None, data: bytes | None = None, check: bool = True) -> str: diff --git a/tests/test_red_green.py b/tests/test_red_green.py index cfdf1b20d..a3e724a37 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -337,22 +337,28 @@ class Mutation(unittest.TestCase): self.assertEqual(r["verdict"], "red then green", r) self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")]) - def test_a_mutated_run_that_hangs_is_caught_by_timeout(self): - # Undone alone, the second hunk makes the test start a process that sleeps. Red has neither hunk, so it does - # not hang there. - base = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) - + "\ndef settled():\n return False\n") + # tools/bar.py with two hunks far apart, two() at line 2 (the fix) and settled() at line 15; a test of two(). + BAR = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) + + "\ndef settled():\n return False\n") + + def bar_repo(self, body, base_files=None): test = ("import os, subprocess, sys, unittest\n" - "sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools'))\n" - "import bar\n\n\nclass T(unittest.TestCase):\n def test_two(self):\n" - " if bar.two() == 2 and not bar.settled():\n" - " subprocess.run([sys.executable, '-c', 'import time; time.sleep(120)'])\n" - " self.assertEqual(bar.two(), 2)\n") + "tools = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools')\n" + "sys.path.insert(0, tools)\n" + "import bar\n\n\nclass T(unittest.TestCase):\n def test_two(self):\n" + body + + " self.assertEqual(bar.two(), 2)\n") repo = Repo(self) - repo.commit("base", {"tools/bar.py": base}) + repo.commit("base", {"tools/bar.py": self.BAR, **(base_files or {})}) repo.git("switch", "-q", "-c", "pr") - repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2").replace("False", "True"), + repo.commit("fix", {"tools/bar.py": self.BAR.replace("return 1", "return 2").replace("False", "True"), "tests/test_bar.py": test}) + return repo + + def test_a_mutated_run_that_hangs_is_caught_by_timeout(self): + # Undone alone, the second hunk makes the test start a process that sleeps. Red has neither hunk, so it does + # not hang there. + repo = self.bar_repo(" if bar.two() == 2 and not bar.settled():\n" + " subprocess.run([sys.executable, '-c', 'import time; time.sleep(120)'])\n") start = time.monotonic() _code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "5") self.assertEqual(r["verdict"], "red then green", r) @@ -361,6 +367,18 @@ class Mutation(unittest.TestCase): # The sleeping process was stopped with the test's: left running, it would hold the output pipe for 120 s. self.assertLess(time.monotonic() - start, 60) + def test_a_process_left_behind_does_not_hold_a_mutated_run(self): + # Undone alone, the fix makes the test leave a process behind that outlives it with its output; the test still + # fails, so the hunk is caught, as soon as the test ends and not when the timeout runs out. (Kept in T, so + # that no ResourceWarning cuts the test's line in the verbose output.) + repo = self.bar_repo(" if bar.two() != 2 and bar.settled():\n" + " T.left = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)'])\n") + start = time.monotonic() + _code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "20") + self.assertEqual(r["verdict"], "red then green", r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")]) + self.assertLess(time.monotonic() - start, 20) + def test_a_hunk_that_cannot_be_put_back_stops_the_mutations_and_says_where(self): # The test writes over the code it tests when it finds it wrong, so the undone hunk no longer applies back. base = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) -- cgit v1.2.3 From 29712017c4c22eb61368504932e5844328b01868 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:52:03 +0100 Subject: scripts: red_green.py starts each mutation from a commit of the green merge, reset and cleaned (review) A put-back that applies did not prove the tree green again: a test that wrote into a tracked file changed the result of the next hunk. The green merge is now committed with the tool's identity before its tests run, and each mutation resets the tree to it and cleans it before undoing its hunk. A hunk can no longer fail to go back, so mutations_stopped and its test are gone; a test that dirties the tree now has its own. --- docs/testing.md | 7 +++---- scripts/red_green.py | 34 +++++++++++++++------------------- tests/test_red_green.py | 30 ++++++++++-------------------- 3 files changed, 28 insertions(+), 43 deletions(-) (limited to 'scripts') diff --git a/docs/testing.md b/docs/testing.md index c0d1d7c49..301f12888 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -163,15 +163,14 @@ python -I scripts/red_green.py fix. After the green side, it undoes each hunk of the pull request's code alone (Rust and Python files it changes, outside the tests and `#[cfg(test)]` code) and runs the tests again. A hunk is `caught` when a test that went red then green fails, `not caught` when they all still pass, `does not build`, or `does not apply` (`main` moved those - lines since). It tries at most `--mutate-max` hunks (10). A `not caught` hunk is code no new test looks at; it + lines since). Each mutation starts from the green tree, reset and cleaned, so what a test writes into the tree + changes no other. It tries at most `--mutate-max` hunks (10). A `not caught` hunk is code no new test looks at; it does not change the verdict. - Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it. The report lists them (`not mutated, added by the pull request`), so a fix whose code sits in a new file is not read as covered. When no hunk is undone, the report says why: `nothing to undo` when the pull request changes no Rust or Python code outside its tests (a test-only one, whose `no red` then says nothing against its test), or - `not run` when no test went red then green. A hunk that cannot be put back (a test wrote into the code) stops the - mutations, and the report names that hunk and the reason. `--json` has these in `mutations_not_run`, - `mutations_stopped` and `added_not_mutated`. + `not run` when no test went red then green. `--json` has these in `mutations_not_run` and `added_not_mutated`. - Each command of a mutated run (`cargo test`, one Python test file) is stopped with the processes it started after `--mutate-timeout` seconds (600), and the hunk is `caught by timeout`: the undone code made a test hang, or the build took longer than that (raise the option for a crate that builds slowly). When the command ends, the diff --git a/scripts/red_green.py b/scripts/red_green.py index f4eec79c6..a08344ed6 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -544,10 +544,6 @@ def report(r: dict) -> str: out.append(f"mutations ({len(r['mutations'])} hunks undone one at a time): " + ", ".join(f"{n} {k}" for k, n in sorted(counts.items()))) out += [f" {m['file']}:{m['line']}: {m['result']}" for m in r["mutations"]] - stop = r.get("mutations_stopped") - if stop: - out.append(f"mutations stopped at {stop['file']}:{stop['line']}: {stop['why']}; " - f"hunks not tried: {stop['untried']}") if r.get("added_not_mutated"): out.append("not mutated, added by the pull request: " + ", ".join(r["added_not_mutated"])) out.append(f"verdict: {r['verdict']}") @@ -627,18 +623,21 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer print("red_green: red side...", file=sys.stderr) red = side(tree, crates, py_files, a.cargo, target) - green, green_why = None, None + green, green_why, green_commit = None, None, None checkout(repo, tree, base_commit) git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) stuck = conflicts(tree) if stuck: green_why = "not constructible: the pull request conflicts with the base in " + ", ".join(stuck) else: + if a.mutate: # the merge as it is now, before a test can write into the tree: each mutation starts from it + green_commit = git(tree, "commit-tree", git(tree, "write-tree"), "-p", base_commit, "-p", head, + "-m", f"red_green: {head[:12]} merged", env=env) print("red_green: green side...", file=sys.stderr) green = side(tree, crates, py_files, a.cargo, target) rows = compare(red, green) # With --mutate, `mutations` is a list (empty when no hunk was undone, and `mutations_not_run` says why). - mutations, not_run, stopped, added = None, None, None, None + mutations, not_run, added = None, None, None if a.mutate: hunks, added, mutations = code_hunks(repo, merge_base, head), code_files(repo, merge_base, head, "A"), [] if green is None: @@ -650,14 +649,14 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer not_run = "not run: no test went red then green, so none can catch a hunk" else: print("red_green: mutations...", file=sys.stderr) - mutations, stopped = mutate(tree, hunks[:a.mutate_max], rows["red_to_green"], crates, py_files, a.cargo, - target, a.mutate_timeout) + mutations = mutate(tree, green_commit, hunks[:a.mutate_max], rows["red_to_green"], crates, py_files, + a.cargo, target, a.mutate_timeout) checkout(repo, tree, base_commit) return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, "python_files": py_files, "red": red, "green": green, "rows": rows, "mutations": mutations, - "mutations_not_run": not_run, "mutations_stopped": stopped, "added_not_mutated": added, + "mutations_not_run": not_run, "added_not_mutated": added, "verdict": verdict(red_why, green_why, red, green, rows)} @@ -705,14 +704,16 @@ def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, s return out -def mutate(tree: Path, hunks: list[tuple[str, int, str]], targets: list[str], crates: list[str], py_files: list[str], - cargo: str, target: Path, timeout: float) -> tuple[list[dict], dict | None]: +def mutate(tree: Path, green: str, hunks: list[tuple[str, int, str]], targets: list[str], crates: list[str], + py_files: list[str], cargo: str, target: Path, timeout: float) -> list[dict]: """Undoes each code hunk alone on the green tree and runs the tests again: a hunk is caught when one of the tests - that went red then green fails, or caught by timeout when a command runs past `timeout` seconds. Stops at a hunk - that cannot be put back (a test wrote into the code): the second value says where and why.""" + that went red then green fails, or caught by timeout when a command runs past `timeout` seconds. Each one starts + from the commit `green`, reset and cleaned, so what a test wrote into the tree changes no other.""" results = [] for path, line, patch in hunks: entry = {"file": path, "line": line, "result": None} + git(tree, "reset", "--hard", "-q", green) + git(tree, "clean", "-fdq") undo = run(["git", "apply", "-R", "--unidiff-zero", "-"], tree, data=patch.encode()) if undo.returncode != 0: entry["result"] = "does not apply" @@ -730,12 +731,7 @@ def mutate(tree: Path, hunks: list[tuple[str, int, str]], targets: list[str], cr else: entry["result"] = "not caught" results.append(entry) - back = run(["git", "apply", "--unidiff-zero", "-"], tree, data=patch.encode()) - if back.returncode != 0: - why = back.stderr.decode("utf-8", "replace").strip().splitlines() - return results, {"file": path, "line": line, "untried": len(hunks) - len(results), - "why": "git apply could not put the hunk back" + (f" ({why[-1]})" if why else "")} - return results, None + return results if __name__ == "__main__": diff --git a/tests/test_red_green.py b/tests/test_red_green.py index a3e724a37..41b18101c 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -379,28 +379,18 @@ class Mutation(unittest.TestCase): self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")]) self.assertLess(time.monotonic() - start, 20) - def test_a_hunk_that_cannot_be_put_back_stops_the_mutations_and_says_where(self): - # The test writes over the code it tests when it finds it wrong, so the undone hunk no longer applies back. - base = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) - + "\ndef spare():\n return 5\n") - test = Python.TEST.replace( - " def test_two(self):\n", - " def test_two(self):\n if bar.two() != 2:\n" - " with open(bar.__file__, 'w', encoding='utf-8', newline='\\n') as f:\n" - " f.write('def two():\\n return 3\\n')\n") - repo = Repo(self) - repo.commit("base", {"tools/bar.py": base}) - repo.git("switch", "-q", "-c", "pr") - repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2").replace("return 5", "return 6"), - "tests/test_bar.py": test}) + def test_a_test_that_dirties_the_tree_does_not_change_the_next_hunk(self): + # When it finds two() wrong, the test writes into a tracked file that it also checks. Each mutation starts from + # the green tree, so the second hunk (settled(), which no test looks at) is not caught for that. + repo = self.bar_repo(" flag = os.path.join(tools, 'flag.txt')\n" + " if bar.two() != 2:\n" + " with open(flag, 'w', encoding='utf-8', newline='\\n') as f:\n" + " f.write('dirty\\n')\n" + " with open(flag, encoding='utf-8') as f:\n" + " self.assertEqual(f.read(), 'clean\\n')\n", {"tools/flag.txt": "clean\n"}) code, r, _ = repo.run("--no-cargo", "--mutate") self.assertEqual((code, r["verdict"]), (0, "red then green"), r) - self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught")]) - stop = r["mutations_stopped"] - self.assertEqual((stop["file"], stop["line"], stop["untried"]), ("tools/bar.py", 2, 1), stop) - self.assertIn("could not put the hunk back", stop["why"]) - self.assertIn("mutations stopped at tools/bar.py:2: git apply could not put the hunk back", rg.report(r)) - self.assertIn("hunks not tried: 1", rg.report(r)) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")]) tree = os.path.join(repo.dir, ".git", "red-green", "tree") status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout self.assertEqual(status, "") -- cgit v1.2.3 From 0d2dea6c70699e1e3156a9bc6d885d26ee743b0a Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:53:42 +0100 Subject: scripts: red_green.py tells a hunk of test code only with one rule, for the red side and for the mutations (review) code_hunks looked only at the lines a hunk adds, so a hunk that deletes an obsolete test inside a #[cfg(test)] module was mutated and read as not caught, while the red side took it as a test hunk. Both now use test_hunk_flags: every removed or added line is test code, blank or a comment, and one at least is test code. --- scripts/red_green.py | 55 ++++++++++++++++++++++++------------------------- tests/test_red_green.py | 18 ++++++++++++++++ 2 files changed, 45 insertions(+), 28 deletions(-) (limited to 'scripts') diff --git a/scripts/red_green.py b/scripts/red_green.py index a08344ed6..3e2e2726d 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -269,17 +269,24 @@ def hunks(diff: str) -> list[tuple[int, int, int, int]]: return out -def test_hunks(old: bytes, new: bytes, diff: str) -> bytes | None: - """`old` with only the hunks of `diff` (made with -U0) that change test code; None when there is none.""" +def test_hunk_flags(old: bytes, new: bytes, diff: str) -> list[bool]: + """For each hunk of `diff` (a Rust file's, made with -U0), in order, whether it changes only test code: each line + it removes or adds is in a `#[cfg(test)]` item, blank or a comment, and one at least is in such an item. The red + side takes these hunks, and a mutation leaves them alone.""" old_lines, new_lines = lines_of(old), lines_of(new) old_tests, new_tests = test_lines(old), test_lines(new) - keep = [] + flags = [] for a, b, c, d in hunks(diff): - removed = range(a - 1, a - 1 + b) - added = range(c - 1, c - 1 + d) - lines = [(i in old_tests, old_lines[i]) for i in removed] + [(i in new_tests, new_lines[i]) for i in added] - if lines and all(t or neutral(line) for t, line in lines) and any(t for t, _ in lines): - keep.append((a, b, c, d)) + lines = [(i in old_tests, old_lines[i]) for i in range(a - 1, a - 1 + b)] + \ + [(i in new_tests, new_lines[i]) for i in range(c - 1, c - 1 + d)] + flags.append(bool(lines) and all(t or neutral(line) for t, line in lines) and any(t for t, _ in lines)) + return flags + + +def test_hunks(old: bytes, new: bytes, diff: str) -> bytes | None: + """`old` with only the hunks of `diff` (made with -U0) that change test code; None when there is none.""" + old_lines, new_lines = lines_of(old), lines_of(new) + keep = [h for h, test in zip(hunks(diff), test_hunk_flags(old, new, diff)) if test] if not keep: return None out = list(old_lines) @@ -674,33 +681,25 @@ def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, s a hunk of its own (a hunk does not apply where `main` moved the lines since).""" out = [] for path in code_files(repo, merge_base, head, "M"): - lines = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path).split("\n") + diff = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path) + lines = diff.split("\n") first = next((i for i, line in enumerate(lines) if line.startswith("@@")), None) if first is None: continue header = "\n".join(lines[:first]) - hunks: list[list[str]] = [] + blocks: list[list[str]] = [] for line in lines[first:]: if line.startswith("@@"): - hunks.append([line]) + blocks.append([line]) else: - hunks[-1].append(line) - tests_new = test_lines(blob(repo, head, path) or b"") if path.endswith(".rs") else set() - for hunk in hunks: - m = HUNK.match(hunk[0]) - if not m: - continue - at, added = int(m.group(3)) - 1, [] # 0-based line of the pull request's side - for line in hunk[1:]: - if line.startswith("+"): - added.append(at) - at += 1 - elif line.startswith(" "): - at += 1 - # A hunk that only adds test code is the tests' own, not the fix. - if added and all(i in tests_new for i in added): - continue - out.append((path, int(m.group(3)), header + "\n" + "\n".join(hunk).rstrip("\n") + "\n")) + blocks[-1].append(line) + # A hunk of test code only is the tests' own, not the fix: the same rule as the red side's. + tests_only = (test_hunk_flags(blob(repo, merge_base, path) or b"", blob(repo, head, path) or b"", diff) + if path.endswith(".rs") else [False] * len(blocks)) + for block, test in zip(blocks, tests_only): + m = HUNK.match(block[0]) + if m and not test: + out.append((path, int(m.group(3)), header + "\n" + "\n".join(block).rstrip("\n") + "\n")) return out diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 41b18101c..ff8928b6e 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -328,6 +328,24 @@ class Mutation(unittest.TestCase): status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout self.assertEqual(status, "") + def test_a_hunk_that_only_deletes_a_test_is_not_mutated(self): + # The pull request also deletes an obsolete test: a hunk of test code only, like the one that renames the + # other test. Neither is mutated; only the fix is. + spare_test = "\n #[test]\n fn spare_is_five() {\n assert_eq!(super::spare(), 5);\n }\n" + base = ("pub fn value() -> u32 {\n 1\n}\n\npub fn spare() -> u32 {\n 5\n}\n" + + LIB[LIB.index("\n#[cfg(test)]"):LIB.rindex("}")] + + "".join(f" // padding line {i}\n" for i in range(10)) + spare_test + "}\n") + repo = Repo(self) + repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n', + "d3d12/crates/foo/src/lib.rs": base}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": base.replace(" 1\n", " 2\n").replace(spare_test, "") + .replace("fn value_is_one() {\n assert_eq!(super::value(), 1);", + "fn value_is_two() {\n assert_eq!(super::value(), 2);")}) + code, r, _ = repo.run("--mutate") + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught")]) + def test_a_python_fix_undone_is_caught(self): repo = Repo(self) repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) -- cgit v1.2.3 From 4a0aa701d04616e4b2024f90390f67b2ba576bac Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:54:50 +0100 Subject: scripts: red_green.py lists the hunks --mutate-max leaves out (review) With more code hunks than --mutate-max, the report read as if every hunk was tried. The hunks left out are now in --json (mutations_skipped, file and line) and in the text (not tried, past --mutate-max). --- docs/testing.md | 5 +++-- scripts/red_green.py | 8 ++++++-- tests/test_red_green.py | 14 ++++++++++++++ 3 files changed, 23 insertions(+), 4 deletions(-) (limited to 'scripts') diff --git a/docs/testing.md b/docs/testing.md index 301f12888..339283e1b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -164,8 +164,9 @@ python -I scripts/red_green.py outside the tests and `#[cfg(test)]` code) and runs the tests again. A hunk is `caught` when a test that went red then green fails, `not caught` when they all still pass, `does not build`, or `does not apply` (`main` moved those lines since). Each mutation starts from the green tree, reset and cleaned, so what a test writes into the tree - changes no other. It tries at most `--mutate-max` hunks (10). A `not caught` hunk is code no new test looks at; it - does not change the verdict. + changes no other. It tries at most `--mutate-max` hunks (10) and lists the others as `not tried, past + --mutate-max` (`mutations_skipped` in `--json`). A `not caught` hunk is code no new test looks at; it does not + change the verdict. - Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it. The report lists them (`not mutated, added by the pull request`), so a fix whose code sits in a new file is not read as covered. When no hunk is undone, the report says why: `nothing to undo` when the pull request changes no diff --git a/scripts/red_green.py b/scripts/red_green.py index 3e2e2726d..8d748d534 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -551,6 +551,9 @@ def report(r: dict) -> str: out.append(f"mutations ({len(r['mutations'])} hunks undone one at a time): " + ", ".join(f"{n} {k}" for k, n in sorted(counts.items()))) out += [f" {m['file']}:{m['line']}: {m['result']}" for m in r["mutations"]] + if r.get("mutations_skipped"): + out.append("not tried, past --mutate-max: " + + ", ".join(f"{m['file']}:{m['line']}" for m in r["mutations_skipped"])) if r.get("added_not_mutated"): out.append("not mutated, added by the pull request: " + ", ".join(r["added_not_mutated"])) out.append(f"verdict: {r['verdict']}") @@ -644,7 +647,7 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer green = side(tree, crates, py_files, a.cargo, target) rows = compare(red, green) # With --mutate, `mutations` is a list (empty when no hunk was undone, and `mutations_not_run` says why). - mutations, not_run, added = None, None, None + mutations, not_run, skipped, added = None, None, None, None if a.mutate: hunks, added, mutations = code_hunks(repo, merge_base, head), code_files(repo, merge_base, head, "A"), [] if green is None: @@ -658,12 +661,13 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer print("red_green: mutations...", file=sys.stderr) mutations = mutate(tree, green_commit, hunks[:a.mutate_max], rows["red_to_green"], crates, py_files, a.cargo, target, a.mutate_timeout) + skipped = [{"file": path, "line": line} for path, line, _ in hunks[a.mutate_max:]] checkout(repo, tree, base_commit) return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, "python_files": py_files, "red": red, "green": green, "rows": rows, "mutations": mutations, - "mutations_not_run": not_run, "added_not_mutated": added, + "mutations_not_run": not_run, "mutations_skipped": skipped, "added_not_mutated": added, "verdict": verdict(red_why, green_why, red, green, rows)} diff --git a/tests/test_red_green.py b/tests/test_red_green.py index ff8928b6e..49bc7b188 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -413,6 +413,20 @@ class Mutation(unittest.TestCase): status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout self.assertEqual(status, "") + def test_hunks_past_mutate_max_are_listed_as_not_tried(self): + base = "".join(f"def f{n}():\n return 1\n" + "# padding\n" * 4 for n in range(1, 5)) + test = Python.TEST.replace("bar.two(), 2", "bar.f1(), 2") + repo = Repo(self) + repo.commit("base", {"tools/bar.py": base}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2"), "tests/test_bar.py": test}) + code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-max", "2") + self.assertEqual((code, r["verdict"]), (0, "red then green"), r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (8, "not caught")]) + self.assertEqual(r["mutations_skipped"], [{"file": "tools/bar.py", "line": 14}, + {"file": "tools/bar.py", "line": 20}]) + self.assertIn("not tried, past --mutate-max: tools/bar.py:14, tools/bar.py:20", rg.report(r)) + def test_a_test_only_pull_request_has_nothing_to_undo(self): repo = Repo(self) repo.commit("base", {"tools/bar.py": "def two():\n return 2\n"}) -- cgit v1.2.3 From fc0ce37ac47d4e0c57308bf24ced4a090ecbe1ea Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:57:39 +0100 Subject: scripts: red_green.py reports a cargo run stopped before any test ran as timed out building, not caught (review) A mutated cargo run that times out before its first Running line was still a build: it says nothing about the tests, so it is no longer counted as caught by timeout. A stub cargo that hangs in its build or in a test binary now covers the cargo timeout path, which no test reached before. --- docs/testing.md | 7 ++++--- scripts/red_green.py | 24 +++++++++++++++--------- tests/test_red_green.py | 25 +++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 12 deletions(-) (limited to 'scripts') diff --git a/docs/testing.md b/docs/testing.md index 339283e1b..becb61310 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -173,9 +173,10 @@ python -I scripts/red_green.py Rust or Python code outside its tests (a test-only one, whose `no red` then says nothing against its test), or `not run` when no test went red then green. `--json` has these in `mutations_not_run` and `added_not_mutated`. - Each command of a mutated run (`cargo test`, one Python test file) is stopped with the processes it started after - `--mutate-timeout` seconds (600), and the hunk is `caught by timeout`: the undone code made a test hang, or the - build took longer than that (raise the option for a crate that builds slowly). When the command ends, the - processes it left behind are stopped too (a Windows job object, the process group elsewhere). + `--mutate-timeout` seconds (600). The hunk is then `caught by timeout` when a test was running (the undone code + made it hang), or `timed out building` when cargo had not started a test yet, which says nothing about the tests + (raise the option for a crate that builds slowly). When the command ends, the processes it left behind are + stopped too (a Windows job object, the process group elsewhere). - `--crate ` adds a crate, `--no-cargo` or `--no-python` leaves one kind out, `--base ` tests on another base, and `--no-fetch` uses the refs as they are. diff --git a/scripts/red_green.py b/scripts/red_green.py index 8d748d534..d487d9315 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -383,11 +383,11 @@ def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path, timeout: cmd += ["test", "--locked", "--no-fail-fast"] + [a for c in crates for a in ("-p", c)] env = dict(os.environ, CARGO_TARGET_DIR=str(target)) code, out = run_output(cmd, tree / "d3d12", env, timeout) - tests, unit, error = {}, "?", None + tests, unit, error, ran = {}, "?", None, False for line in out.splitlines(): m = UNIT.match(line) if m: - unit = m.group(1) or "doc:" + m.group(2) + unit, ran = m.group(1) or "doc:" + m.group(2), True continue m = CARGO_TEST.match(line) if m: @@ -396,8 +396,10 @@ def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path, timeout: error = line.strip() no_build = code is not None and code != 0 and not tests crash = COMPILER_CRASH.search(out) if no_build else None + # Stopped by the timeout: while building (no test binary had started) or while running the tests. + timed_out = None if code is not None else "running" if ran else "building" return {"tests": tests, "no_build": (error or f"cargo exit {code}") if no_build and not crash else None, - "crash": next(g for g in crash.groups() if g) if crash else None, "timed_out": code is None} + "crash": next(g for g in crash.groups() if g) if crash else None, "timed_out": timed_out} def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path, timeout: float | None) -> dict: @@ -436,14 +438,15 @@ def drop_bytecode(tree: Path) -> None: def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict: - tests, no_build, timed_out = {}, [], False + tests, no_build, timed_out = {}, [], None drop_bytecode(tree) for f in files: start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) # -B only stops writing bytecode, not reading it: drop_bytecode() above keeps stale bytecode out. code, out = run_output([sys.executable, "-I", "-B", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, "-v"], tree, timeout=timeout) - timed_out |= code is None + if code is None: + timed_out = "running" found = 0 for name, where, status in PY_TEST.findall(out): if "_FailedTest" in where: @@ -460,9 +463,10 @@ def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict: def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path, timeout: float | None = None) -> dict: """The tests of one side: the crates, and those of the Python test files that this tree has. With a timeout (the - mutated runs), a command that runs past it is stopped and the side is marked `timed_out`.""" + mutated runs), a command that runs past it is stopped and `timed_out` says when: "building" (cargo, before any + test binary ran) or "running".""" py_files = [f for f in py_files if (tree / f).is_file()] - result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None, "timed_out": False} + result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None, "timed_out": None} for part in ([cargo_tests(tree, crates, cargo, target, timeout)] if crates else []) + \ ([python_tests(tree, py_files, timeout)] if py_files else []): result["tests"].update(part["tests"]) @@ -576,8 +580,8 @@ def main(argv: list[str] | None = None) -> int: help="undo each code hunk alone on green and run the tests again (caught or not)") p.add_argument("--mutate-max", type=int, default=10, help="the most hunks --mutate tries (10)") p.add_argument("--mutate-timeout", type=float, default=600, metavar="SECONDS", - help="stop a command of a mutated run (cargo test, one Python test file) after this long and count " - "the hunk as caught by timeout (600)") + help="stop a command of a mutated run (cargo test, one Python test file) after this long: the hunk " + "is caught by timeout, or timed out building if cargo had not started a test (600)") a = p.parse_args(argv) try: repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) @@ -727,6 +731,8 @@ def mutate(tree: Path, green: str, hunks: list[tuple[str, int, str]], targets: l entry["result"] = "compiler crashed" elif any(s["tests"].get(t) == "failed" for t in targets): entry["result"] = "caught" + elif s["timed_out"] == "building": # no answer: the build was too slow, or the undone code made it hang + entry["result"] = "timed out building" elif s["timed_out"]: entry["result"] = "caught by timeout" elif not any(t in s["tests"] for t in targets): diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 49bc7b188..04d996cc8 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -69,6 +69,18 @@ runpy.run_path(os.path.join(here, "cargo_stub.py"), run_name="__main__") ''' +def hang_stub(repo, where): + """STUB_CARGO that sleeps when value() is 2 and spare() is 5 (Mutation.BASE's second hunk undone alone): before + its `Running` line, as a build that hangs, or after it, as a test that hangs.""" + hang = "sys.stdout.flush()\nif fns.get('value') == '2' and fns.get('spare') == '5':\n __import__('time').sleep(120)\n" + text = STUB_CARGO.replace('print(" Running', (hang if where == "build" else "") + 'print(" Running') + text = text.replace("failed = False\n", "failed = False\n" + (hang if where == "test" else "")) + path = os.path.join(repo.tmp.name, f"cargo_hang_{where}.py") + with open(path, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + return path + + class Repo: def crash_stub(self, mode): path = os.path.join(self.tmp.name, f"cargo_crash_{mode}.py") @@ -328,6 +340,19 @@ class Mutation(unittest.TestCase): status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout self.assertEqual(status, "") + def test_a_cargo_run_that_hangs_is_stopped_and_said_where(self): + repo = Repo(self) + repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n', + "d3d12/crates/foo/src/lib.rs": self.BASE}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace( + " 5\n", " 6\n").replace("fn value_is_one() {\n assert_eq!(super::value(), 1);", + "fn value_is_two() {\n assert_eq!(super::value(), 2);")}) + # A test binary that hangs is caught; a build that hangs (no `Running` line yet) is no answer. + for where, result in (("test", "caught by timeout"), ("build", "timed out building")): + _code, r, _ = repo.run("--mutate", "--mutate-timeout", "5", "--cargo", hang_stub(repo, where)) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, result)], where) + def test_a_hunk_that_only_deletes_a_test_is_not_mutated(self): # The pull request also deletes an obsolete test: a hunk of test code only, like the one that renames the # other test. Neither is mutated; only the fix is. -- cgit v1.2.3 From 0ab167f754585795b0f1912c29211264c73c4f3b Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:58:56 +0100 Subject: scripts: red_green.py refuses --mutate-max below 1, a --mutate-timeout that is not above 0, and both without --mutate (review) --- scripts/red_green.py | 12 ++++++++++-- tests/test_red_green.py | 11 +++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) (limited to 'scripts') diff --git a/scripts/red_green.py b/scripts/red_green.py index d487d9315..9276c5462 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -578,11 +578,19 @@ def main(argv: list[str] | None = None) -> int: p.add_argument("--json", action="store_true", help="print the result as JSON") p.add_argument("--mutate", action="store_true", help="undo each code hunk alone on green and run the tests again (caught or not)") - p.add_argument("--mutate-max", type=int, default=10, help="the most hunks --mutate tries (10)") - p.add_argument("--mutate-timeout", type=float, default=600, metavar="SECONDS", + p.add_argument("--mutate-max", type=int, help="the most hunks --mutate tries, 1 or more (10)") + p.add_argument("--mutate-timeout", type=float, metavar="SECONDS", help="stop a command of a mutated run (cargo test, one Python test file) after this long: the hunk " "is caught by timeout, or timed out building if cargo had not started a test (600)") a = p.parse_args(argv) + if not a.mutate and (a.mutate_max is not None or a.mutate_timeout is not None): + p.error("--mutate-max and --mutate-timeout go with --mutate") + if a.mutate_max is not None and a.mutate_max < 1: + p.error("--mutate-max must be 1 or more") + if a.mutate_timeout is not None and not a.mutate_timeout > 0: # NaN too + p.error("--mutate-timeout must be more than 0 seconds") + a.mutate_max = 10 if a.mutate_max is None else a.mutate_max + a.mutate_timeout = 600.0 if a.mutate_timeout is None else a.mutate_timeout try: repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) common = Path(git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir")) diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 04d996cc8..741944d54 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -492,6 +492,17 @@ class Mutation(unittest.TestCase): self.assertEqual(r["added_not_mutated"], ["tools/helper.py"]) self.assertIn("not mutated, added by the pull request: tools/helper.py", rg.report(r)) + def test_mutate_options_are_checked(self): + for args, why in ((["--mutate", "--mutate-max", "0"], "--mutate-max"), + (["--mutate", "--mutate-timeout", "0"], "--mutate-timeout"), + (["--mutate", "--mutate-timeout", "nan"], "--mutate-timeout"), + (["--mutate-max", "3"], "--mutate"), (["--mutate-timeout", "60"], "--mutate")): + err = io.StringIO() + with redirect_stderr(err), self.assertRaises(SystemExit) as stop: + rg.main(["pr", "--no-fetch", *args]) + self.assertEqual(stop.exception.code, 2, args) + self.assertIn(why, err.getvalue().splitlines()[-1], args) + def test_no_mutation_without_the_option(self): repo = Repo(self) repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) -- cgit v1.2.3 From 673ac44a1bd5a8fc642c7ada4a8764fcaf497a37 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:00:51 +0100 Subject: tests: red_green.py checks that the process a mutated run leaves behind is stopped, not only that it does not hold the run (review) With the output in a file the run no longer waits for such a process, so only a mark it would write later shows that the job (the process group elsewhere) stopped it. drop_bytecode reads a folder's attributes only for folders. --- scripts/red_green.py | 9 +++++---- tests/test_red_green.py | 16 +++++++++++----- 2 files changed, 16 insertions(+), 9 deletions(-) (limited to 'scripts') diff --git a/scripts/red_green.py b/scripts/red_green.py index 9276c5462..ec6c31d49 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -429,10 +429,11 @@ def drop_bytecode(tree: Path) -> None: while todo: with os.scandir(todo.pop()) as entries: for e in entries: - link = e.is_symlink() or bool(getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0) - & stat.FILE_ATTRIBUTE_REPARSE_POINT) - if not link and e.is_dir(follow_symlinks=False): - (folders if e.name == "__pycache__" else todo).append(e.path) + if not e.is_dir(follow_symlinks=False) or e.is_symlink(): + continue + if getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT: + continue # a junction (Windows) + (folders if e.name == "__pycache__" else todo).append(e.path) for folder in folders: shutil.rmtree(folder) diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 8f6c85935..84d09d49b 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -407,20 +407,26 @@ class Mutation(unittest.TestCase): self.assertEqual(r["verdict"], "red then green", r) self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "caught by timeout")]) self.assertIn("mutations (2 hunks undone one at a time): 1 caught, 1 caught by timeout", rg.report(r)) - # The sleeping process was stopped with the test's: left running, it would hold the output pipe for 120 s. + # The run did not wait for the sleeping process. self.assertLess(time.monotonic() - start, 60) def test_a_process_left_behind_does_not_hold_a_mutated_run(self): # Undone alone, the fix makes the test leave a process behind that outlives it with its output; the test still - # fails, so the hunk is caught, as soon as the test ends and not when the timeout runs out. (Kept in T, so - # that no ResourceWarning cuts the test's line in the verbose output.) - repo = self.bar_repo(" if bar.two() != 2 and bar.settled():\n" - " T.left = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)'])\n") + # fails, so the hunk is caught, as soon as the test ends and not when the timeout runs out. The process left + # behind is stopped then: 5 s later, it would write a file beside the work tree. (Kept in T, so that no + # ResourceWarning cuts the test's line in the verbose output.) + repo = self.bar_repo( + " if bar.two() != 2 and bar.settled():\n" + " mark = os.path.join(os.path.dirname(os.path.dirname(tools)), 'left-behind')\n" + " T.left = subprocess.Popen([sys.executable, '-c', 'import sys, time; time.sleep(5); " + "open(sys.argv[1], \"w\").close()', mark])\n") start = time.monotonic() _code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "20") self.assertEqual(r["verdict"], "red then green", r) self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")]) self.assertLess(time.monotonic() - start, 20) + time.sleep(6) # it started before the run ended + self.assertFalse(os.path.exists(os.path.join(repo.dir, ".git", "red-green", "left-behind"))) def test_a_test_that_dirties_the_tree_does_not_change_the_next_hunk(self): # When it finds two() wrong, the test writes into a tracked file that it also checks. Each mutation starts from -- cgit v1.2.3 From bf65aa4505aeccd8feb9bfca2c93a33d103747c8 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:19:38 +0100 Subject: scripts: red_green.py skips a folder it cannot list, stops with the tree put back on a __pycache__ it cannot remove, and four smaller fixes (review) drop_bytecode skips a folder it may not list (Python cannot import from it either). A __pycache__ it cannot remove is now a usage error naming it (exit 2), and any such error during a run puts the tree back on the base, where before the undone hunk stayed. --mutate-timeout must also be finite. In a mutated run, a Python test stopped while running outweighs a cargo build that was stopped. job_of says once on stderr when it has no job object. docs/testing.md: one line rewrapped. --- docs/testing.md | 7 ++-- scripts/red_green.py | 65 +++++++++++++++++++++++++----------- tests/test_red_green.py | 87 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 137 insertions(+), 22 deletions(-) (limited to 'scripts') diff --git a/docs/testing.md b/docs/testing.md index 11b184ff4..31ab93653 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -164,9 +164,10 @@ python -I scripts/red_green.py outside the tests and `#[cfg(test)]` code) and runs the tests again. A hunk is `caught` when a test that went red then green fails, `not caught` when they all still pass, `does not build` when those tests no longer run, `compiler crashed` when the compiler crashed twice, or `does not apply` when `main` moved those lines since. Each - mutation starts from the green tree, reset and cleaned, so what a test writes into the tree changes no other. It tries at most `--mutate-max` hunks (10) and lists the others as `not tried, past - --mutate-max` (`mutations_skipped` in `--json`). A `not caught` hunk is code no new test looks at; it does not - change the verdict. + mutation starts from the green tree, reset and cleaned, so what a test writes into the tree changes no other. It + tries at most `--mutate-max` hunks (10) and lists the others as `not tried, past --mutate-max` + (`mutations_skipped` in `--json`). A `not caught` hunk is code no new test looks at; it does not change the + verdict. - Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it. The report lists them (`not mutated, added by the pull request`), so a fix whose code sits in a new file is not read as covered. When no hunk is undone, the report says why: `nothing to undo` when the pull request changes no diff --git a/scripts/red_green.py b/scripts/red_green.py index ec6c31d49..e15b1c23f 100644 --- a/scripts/red_green.py +++ b/scripts/red_green.py @@ -31,6 +31,7 @@ from __future__ import annotations import argparse import json +import math import os import re import shutil @@ -81,25 +82,33 @@ if os.name == "nt": _KERNEL32.CloseHandle.argtypes = (wintypes.HANDLE,) +_JOB_WARNED = False # job_of() says once that it has no job object + + def job_of(p: subprocess.Popen): """On Windows, a job object holding `p`, or None. The processes `p` starts join it, and closing it stops every process in it (JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE): a process that outlives `p` is stopped with the job, where `taskkill /T` no longer finds it once `p` has ended. A process `p` starts before it joins (its first instants) - stays out.""" + stays out. Without one, it says so on stderr once.""" + global _JOB_WARNED job = _KERNEL32.CreateJobObjectW(None, None) - if not job: - return None limits = _JobLimits(limit_flags=0x2000) # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE - handle = _KERNEL32.OpenProcess(0x0101, False, p.pid) # PROCESS_TERMINATE | PROCESS_SET_QUOTA + handle = job and _KERNEL32.OpenProcess(0x0101, False, p.pid) # PROCESS_TERMINATE | PROCESS_SET_QUOTA # 9: JobObjectExtendedLimitInformation joined = (handle and _KERNEL32.SetInformationJobObject(job, 9, ctypes.byref(limits), ctypes.sizeof(limits)) and _KERNEL32.AssignProcessToJobObject(job, handle)) + error = ctypes.get_last_error() if handle: _KERNEL32.CloseHandle(handle) - if not joined: + if joined: + return job + if job: _KERNEL32.CloseHandle(job) - return None - return job + if not _JOB_WARNED: + _JOB_WARNED = True + print(f"red_green: no Windows job object for the mutated runs (error {error}): a process one leaves behind " + "is not stopped", file=sys.stderr) + return None def stop_all(p: subprocess.Popen, job) -> None: @@ -424,18 +433,26 @@ def drop_bytecode(tree: Path) -> None: time and size it records still match (an undone change of the same size within the same second) or when it is an unchecked-hash one, and `git clean` keeps them (they are ignored). An option of the run's own Python, such as `-X pycache_prefix`, would not reach the processes its tests start. Links (symbolic links, and junctions, which - `is_symlink()` does not see) are neither followed nor removed: what they point at is not the tree's.""" + `is_symlink()` does not see) are neither followed nor removed: what they point at is not the tree's. A folder it + cannot list is skipped: Python cannot import from it either. A `__pycache__` it cannot remove stops the run.""" folders, todo = [], [tree] while todo: - with os.scandir(todo.pop()) as entries: - for e in entries: - if not e.is_dir(follow_symlinks=False) or e.is_symlink(): - continue - if getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT: - continue # a junction (Windows) - (folders if e.name == "__pycache__" else todo).append(e.path) + try: + with os.scandir(todo.pop()) as entries: + for e in entries: + if not e.is_dir(follow_symlinks=False) or e.is_symlink(): + continue + if getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0) \ + & stat.FILE_ATTRIBUTE_REPARSE_POINT: + continue # a junction (Windows) + (folders if e.name == "__pycache__" else todo).append(e.path) + except OSError: + continue for folder in folders: - shutil.rmtree(folder) + try: + shutil.rmtree(folder) + except OSError as e: + raise Failure(f"cannot remove {folder}, whose bytecode could run instead of the code: {e}") from None def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict: @@ -473,8 +490,10 @@ def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: result["tests"].update(part["tests"]) if part["no_build"]: result["no_build"].append(part["no_build"]) - for key in ("compiler_crashed", "rerun_after", "timed_out"): + for key in ("compiler_crashed", "rerun_after"): result[key] = result[key] or part.get(key) + if part.get("timed_out") and result["timed_out"] != "running": # a test stopped running outweighs a build + result["timed_out"] = part["timed_out"] return result @@ -588,8 +607,8 @@ def main(argv: list[str] | None = None) -> int: p.error("--mutate-max and --mutate-timeout go with --mutate") if a.mutate_max is not None and a.mutate_max < 1: p.error("--mutate-max must be 1 or more") - if a.mutate_timeout is not None and not a.mutate_timeout > 0: # NaN too - p.error("--mutate-timeout must be more than 0 seconds") + if a.mutate_timeout is not None and not (math.isfinite(a.mutate_timeout) and a.mutate_timeout > 0): + p.error("--mutate-timeout must be a number of seconds above 0") a.mutate_max = 10 if a.mutate_max is None else a.mutate_max a.mutate_timeout = 600.0 if a.mutate_timeout is None else a.mutate_timeout try: @@ -615,6 +634,14 @@ def main(argv: list[str] | None = None) -> int: os.close(fd) try: result = check(repo, work, a, base, base_commit, head, merge_base) + except Failure: + # Stopped midway (a side, a mutation): the tree goes back on the base, as at the end of a run. + if (work / "tree" / ".git").exists(): + try: + checkout(repo, work / "tree", base_commit) + except Failure: + pass + raise finally: lock.unlink(missing_ok=True) except Failure as e: diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 84d09d49b..85ccae0ee 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py @@ -10,6 +10,7 @@ import time import unittest from contextlib import redirect_stderr, redirect_stdout from pathlib import Path +from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "scripts")) @@ -280,6 +281,24 @@ class Python(unittest.TestCase): "tests/test_bar.py::test_bar.T.test_two_in_a_child"]) self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")]) + def test_bytecode_it_cannot_remove_stops_the_run_with_the_tree_put_back(self): + repo = Repo(self) + repo.commit("base", {".gitignore": "__pycache__/\n", "tools/bar.py": "def two():\n return 1\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": self.TEST}) + self.assertEqual(repo.run("--no-cargo")[1]["verdict"], "red then green") + tree = os.path.join(repo.dir, ".git", "red-green", "tree") + cache = os.path.join(tree, "tools", "__pycache__") + os.makedirs(cache, exist_ok=True) + block_removal(self, cache) + code, r, err = repo.run("--no-cargo") + self.assertEqual((code, r), (2, None), err) + self.assertIn("cannot remove", err) + self.assertIn(os.path.join("tools", "__pycache__"), err) + # The red side had begun: the tree is back on the base all the same. + status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout + self.assertEqual(status, "") + def link_dir(test, link, target): """A directory junction on Windows (no privilege needed), a symbolic link elsewhere; removed at the end of `test` @@ -292,6 +311,34 @@ def link_dir(test, link, target): test.addCleanup(os.unlink, link) +def deny_listing(test, folder): + """Takes away the right to list `folder` (a deny entry for Everyone on Windows, mode 0 elsewhere) until the end of + `test`.""" + if os.name == "nt": + subprocess.run(["icacls", folder, "/deny", "*S-1-1-0:(RD)"], check=True, capture_output=True) + test.addCleanup(subprocess.run, ["icacls", folder, "/remove:d", "*S-1-1-0"], check=True, capture_output=True) + else: + if os.geteuid() == 0: + test.skipTest("root lists any folder") + os.chmod(folder, 0) + test.addCleanup(os.chmod, folder, 0o700) + + +def block_removal(test, folder): + """Keeps `folder` from being removed until the end of `test`: a file in it held open on Windows, the folder + read-only elsewhere.""" + path = os.path.join(folder, "held.pyc") + if os.name == "nt": + held = open(path, "wb") + test.addCleanup(held.close) + else: + if os.geteuid() == 0: + test.skipTest("root removes any file") + open(path, "wb").close() + os.chmod(folder, 0o500) + test.addCleanup(os.chmod, folder, 0o700) + + class DropBytecode(unittest.TestCase): def setUp(self): tmp = tempfile.TemporaryDirectory(prefix="red-green-test-", ignore_cleanup_errors=True) @@ -315,6 +362,23 @@ class DropBytecode(unittest.TestCase): link_dir(self, os.path.join(self.tree, "__pycache__"), os.path.join(self.outside, "__pycache__")) self.check() + def test_a_folder_it_cannot_list_is_skipped(self): + locked = os.path.join(self.tree, "locked") + os.makedirs(os.path.join(locked, "__pycache__")) + deny_listing(self, locked) + self.check() + + +@unittest.skipUnless(os.name == "nt", "job objects are Windows'") +class Job(unittest.TestCase): + def test_a_job_object_that_cannot_be_joined_is_said_once(self): + err = io.StringIO() + with mock.patch.object(rg._KERNEL32, "AssignProcessToJobObject", return_value=0), \ + mock.patch.object(rg, "_JOB_WARNED", False, create=True), redirect_stderr(err): + runs = [rg.run_output([sys.executable, "-c", "print(1)"], Path(ROOT), timeout=60) for _ in range(2)] + self.assertEqual([(code, out.strip()) for code, out in runs], [(0, "1"), (0, "1")]) + self.assertEqual(err.getvalue().count("no Windows job object"), 1, err.getvalue()) + class Mutation(unittest.TestCase): # Two code changes far enough apart to be two hunks: the tested one and one no test looks at. @@ -353,6 +417,28 @@ class Mutation(unittest.TestCase): _code, r, _ = repo.run("--mutate", "--mutate-timeout", "5", "--cargo", hang_stub(repo, where)) self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, result)], where) + def test_a_test_stopped_running_outweighs_a_build_stopped(self): + # Undone alone, the second hunk makes cargo hang in its build and a Python test hang while running: the hunk + # is caught by timeout, since a test did hang. + watch = ("import os, time, unittest\n\n\nclass T(unittest.TestCase):\n def test_lib(self):\n" + " root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n" + " with open(os.path.join(root, 'd3d12', 'crates', 'foo', 'src', 'lib.rs'), encoding='utf-8') as f:\n" + " text = f.read()\n" + " if ' 2\\n' in text and ' 5\\n' in text:\n" + " time.sleep(120)\n") + repo = Repo(self) + repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n', + "d3d12/crates/foo/src/lib.rs": self.BASE}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tests/test_watch.py": watch, + "d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace( + " 5\n", " 6\n").replace( + "fn value_is_one() {\n assert_eq!(super::value(), 1);", + "fn value_is_two() {\n assert_eq!(super::value(), 2);")}) + _code, r, _ = repo.run("--mutate", "--mutate-timeout", "5", "--cargo", hang_stub(repo, "build")) + self.assertEqual(r["verdict"], "red then green", r) + self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, "caught by timeout")]) + def test_a_hunk_that_only_deletes_a_test_is_not_mutated(self): # The pull request also deletes an obsolete test: a hunk of test code only, like the one that renames the # other test. Neither is mutated; only the fix is. @@ -514,6 +600,7 @@ class Mutation(unittest.TestCase): for args, why in ((["--mutate", "--mutate-max", "0"], "--mutate-max"), (["--mutate", "--mutate-timeout", "0"], "--mutate-timeout"), (["--mutate", "--mutate-timeout", "nan"], "--mutate-timeout"), + (["--mutate", "--mutate-timeout", "inf"], "--mutate-timeout"), (["--mutate-max", "3"], "--mutate"), (["--mutate-timeout", "60"], "--mutate")): err = io.StringIO() with redirect_stderr(err), self.assertRaises(SystemExit) as stop: -- cgit v1.2.3