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. --- docs/game_gate.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/game_gate.md b/docs/game_gate.md index 4849a85f6..1178a5dc2 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -28,6 +28,12 @@ pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir - **Reaching the world.** The gate does not drive the menus. Pass key presses with `LEONIDA_KEYS`; they are timed from the start of the process, so allow for the precompile. - **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 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`). - **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. @@ -62,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`), 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`, `memory` with the limit passed in `memory_why`), whether it was killed, whether the cache was saved, whether the suspend was in time | | `verdict` | `result`, `reasons`, `warnings`, `min_world_s` | ## The verdict @@ -81,6 +87,7 @@ Times are seconds since the run started. The summary holds numbers, switch names - `exited_before_stop`; - `present_gap`; - `world_time_short`: the time limit came first; +- `memory_stop`: the memory stop ended the run, which was on its way to running out; - `not_alive_at_stop`; - `world_not_reached`, when the game ended before reaching the world. -- 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 'docs') 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 7150b7fe0c06488a99239cdfd65477f352c0c54f Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:45:30 +0100 Subject: gate: memory.csv and a pile-up's numbers beside the summary (D3D12-GATE-MEMORY-SERIES) Testers read a pile-up by its slope and by the reaper's queue, which the summary's peaks do not show. The parser now also reads the runtime's census line written with each memory line (objects let go that wait for their submissions, and the reaper thread's queue) and writes memory.csv beside summary.json: one row per memory line with the private bytes, the PC's memory free and left to commit, the card's video memory budget and in use, the shared memory in use and the two queues. The summary's memory block gets the reaper queue at its longest and when, the most objects waiting, and the least-squares slope of the private bytes in the world (MB a minute). The census strings join the contract test. --- docs/game_gate.md | 3 +- tests/test_game_gate.py | 37 +++++++++++++++++++++-- tools/game_gate.py | 80 ++++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 113 insertions(+), 7 deletions(-) (limited to 'docs') diff --git a/docs/game_gate.md b/docs/game_gate.md index d0cf38cb0..049c52b69 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -50,6 +50,7 @@ The run folder (under `-RunRoot`, by default `\gate-runs`, refused inside | `events.jsonl` | What the gate did and saw: the game found, the stop asked for and why, a kill, the exit code | | `data\` | The run's copy of the template, and the runtime's `crashes.log` | | `summary.json` | The result, below | +| `memory.csv` | One row per runtime memory line (every 5 s, builds with diagnostics): time, private bytes, of them in physical memory, the PC's memory free and left to commit, the card's video memory budget and in use, the shared memory in use, the objects let go that wait for their submissions, and the reaper thread's queue. Only when the run has memory lines | ## summary.json (`leonida-gate-summary/1`) @@ -65,7 +66,7 @@ Times are seconds since the run started. The summary holds numbers, switch names | `times.world_s` | Seconds from `world_at_s` to the stop request | | `fps` | From the presents, after the first 60 s in the world: frames, median, p5, frame p95 (ms), median of the last 60 s (`end_median`), the first second with fewer than 2 frames, from 60 s in the world on too (`under_2_at_s`), the longest gap with no frame presented from the world on (`longest_present_gap_s`, `longest_gap_at_s`; on purpose from the world on: a freeze on pipeline compiles comes right after arrival, and 10 s with no frame is what a player sees), draws a frame. Without the present lines (a build without diagnostics), the median and p5 come from the frame lines, with a warning | | `pipelines` | Waits that ran out (`missed_waits`), the most pipelines being made at once | -| `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. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop) | +| `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. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop). Also the reaper thread's queue at its longest and when (`reaper_queue_max`), the most objects waiting for their submissions, and how fast the private bytes grew in the world in MB a minute (`private_mb_per_min_in_world`, a least-squares slope: on a short run it is the loading's climb, on a long one a pile-up's slope), and `series`: the name of `memory.csv` | | `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` 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 | diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index 23cfbabea..58da38ea5 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -1,6 +1,9 @@ """tools/game_gate.py on synthetic run folders: every log line below is made up by the test, in the runtime's formats (no game data). The contract test checks that those formats are still in the runtime's source.""" +import contextlib +import csv import datetime as dt +import io import json import os import re @@ -50,8 +53,12 @@ class Fake: self.log.append(f"{stamp(t)} DEBUG leonida_gpu::frame: present token=1") t += gap - def memory(self, t, private, used, budget=8000, left=3000, shared=500): - """The runtime's video memory line and memory line, as a diagnostics build writes them every 5 s.""" + def memory(self, t, private, used, budget=8000, left=3000, shared=500, waiting=0, reaper=0): + """The runtime's video memory line, census line and memory line, as a diagnostics build writes them every 5 s.""" + self.log.append(f"{stamp(t)} INFO leonida_gpu::census: memory, what waits to be let go: {waiting} objects let " + f"go that wait for the submissions that may use them (LEONIDA_BURY_LAG), {reaper} retired " + f"objects, landed host lists and lists' fronts handed to the thread that lets them go and not " + f"let go yet (LEONIDA_REAPER=0: let go by the submitting thread)") self.log.append(f"{stamp(t)} INFO leonida_gpu::host: video memory as the system counts it, with the memory " f"line: the card's own: budget {budget} MB, in use {used} MB, 100 MB could still be reserved, " f"0 MB reserved; the PC's shared with the card: budget 16000 MB, in use {shared} MB, 0 MB could " @@ -298,12 +305,38 @@ class Measures(unittest.TestCase): f.event(83, "game_exited", exit_code=0) self.assertEqual(f.summarize()["verdict"]["reasons"], ["memory_stop"]) + def test_the_memory_series_and_a_pile_ups_slope(self): + f = passing() + for i, t in enumerate(range(10, 390, 5)): + # From the world on (70 s) the private bytes grow 10 MB every 5 s and the reaper's queue grows. + grown = max(0, t - 70) // 5 + f.memory(t, 20000 + 10 * grown, 7000, waiting=3, reaper=100 * grown) + s = f.summarize() + m = s["memory"] + self.assertEqual(m["private_mb_per_min_in_world"], 120.0) + self.assertEqual((m["reaper_queue_max"], m["reaper_queue_max_at_s"]), (100 * 63, 385.0)) + self.assertEqual(m["waiting_objects_max"], 3) + self.assertEqual(m["series"], "memory.csv") + # `summary` writes the series beside summary.json, one row per memory line, numbers only. + with contextlib.redirect_stdout(io.StringIO()): + game_gate.main(["game_gate.py", "summary", f.dir]) + with open(os.path.join(f.dir, "memory.csv"), encoding="utf-8") as fh: + rows = list(csv.DictReader(fh)) + self.assertEqual(len(rows), 76) + self.assertEqual(tuple(rows[0]), game_gate.SERIES_COLUMNS) + self.assertEqual(rows[-1]["private_mb"], "20630") + self.assertEqual(rows[-1]["reaper_queue"], "6300") + self.assertEqual(rows[-1]["vram_in_use_mb"], "7000") + def test_a_build_without_memory_lines_gives_no_memory_peaks(self): m = passing().summarize()["memory"] self.assertIsNone(m["source"]) self.assertEqual(m["lines"], 0) self.assertIsNone(m["private_max_mb"]) self.assertIsNone(m["vram_in_use_max_mb"]) + self.assertIsNone(m["series"]) + self.assertIsNone(m["reaper_queue_max"]) + self.assertIsNone(m["private_mb_per_min_in_world"]) def test_without_present_lines_the_frame_lines_give_the_rate(self): f = Fake() diff --git a/tools/game_gate.py b/tools/game_gate.py index c2748cde8..076c57175 100644 --- a/tools/game_gate.py +++ b/tools/game_gate.py @@ -8,6 +8,7 @@ script's output: the precompile lines), leonida.log (the runtime's log) and data numbers, switch names and verdicts only: no path, no user or machine name, nothing the title printed. Schema and rules: docs/game_gate.md. """ +import csv import datetime as dt import glob import json @@ -51,6 +52,14 @@ MEMORY = re.compile(r"^memory: (\d+) MB private \((\d+) MB of it in memory; the r"left to commit\)") VIDEO = re.compile(r"^video memory as the system counts it, [^:]*: the card's own: budget (\d+) MB, in use (\d+) MB, " r".*?; the PC's shared with the card: budget (\d+) MB, in use (\d+) MB") +# The census line with them: objects let go that wait for their submissions, and those handed to the reaper thread +# and not let go yet (the reaper's queue, the number a pile-up shows first). +WAITS = re.compile(r"^memory, what waits to be let go: (\d+) objects let go that wait for the submissions that may use " + r"them \(LEONIDA_BURY_LAG\), (\d+) retired objects, landed host lists and lists' fronts handed to the " + r"thread that lets them go") +SERIES = "memory.csv" +SERIES_COLUMNS = ("t_s", "private_mb", "in_memory_mb", "pc_free_mb", "pc_commit_left_mb", "vram_budget_mb", + "vram_in_use_mb", "shared_in_use_mb", "waiting_objects", "reaper_queue") # The runtime's own words this parser reads, and where they are written: tests/test_game_gate.py checks that # each is still there, so a reworded line fails the test, not the next gate. @@ -78,6 +87,11 @@ SOURCES = { "d3d12/crates/leonida-gpu/src/host.rs", "the PC's shared with the card: budget {} MB, in use {} MB": "d3d12/crates/leonida-gpu/src/host.rs", 'h.log_video_memory("with the memory line")': "d3d12/crates/leonida-gpu/src/copystat.rs", + "memory, what waits to be let go: {waiting} objects let go that wait for the submissions that may use them " + "(LEONIDA_BURY_LAG)": "d3d12/crates/leonida-gpu/src/census.rs", + "{handed} retired objects, landed host lists and lists' fronts handed to the thread that lets them go": + "d3d12/crates/leonida-gpu/src/census.rs", + "crate::census::log();": "d3d12/crates/leonida-gpu/src/copystat.rs", } @@ -126,6 +140,7 @@ class Run: self.missed = [] # t of each pipeline not made within its wait self.memory = [] # (t, private MB, in memory MB, PC free MB, PC left to commit MB) self.video = [] # (t, card budget MB, card in use MB, shared budget MB, shared in use MB) + self.waits = [] # (t, objects waiting for their submissions, the reaper's queue) self.settings = None # from the runtime's settings line self.suspend = None self.ended_at = None @@ -157,6 +172,8 @@ class Run: self.memory.append((t,) + tuple(int(x) for x in MEMORY.match(text).groups())) elif text.startswith("video memory as the system counts it") and VIDEO.match(text): self.video.append((t,) + tuple(int(x) for x in VIDEO.match(text).groups())) + elif text.startswith("memory, what waits to be let go") and WAITS.match(text): + self.waits.append((t,) + tuple(int(x) for x in WAITS.match(text).groups())) elif text.startswith("a pipeline not made within its wait"): self.missed.append(t) elif target == "settings": @@ -368,12 +385,66 @@ def fps_block(run, world, end): return out -def memory_block(run): - """Peaks of the runtime's memory lines over the whole run (none from a build without diagnostics).""" +def slope_per_min(points): + """Least-squares slope of (t in s, value) points, per minute; None under 3 points or with no time spread.""" + if len(points) < 3: + return None + mt = sum(t for t, _ in points) / len(points) + mv = sum(v for _, v in points) / len(points) + spread = sum((t - mt) ** 2 for t, _ in points) + if spread == 0: + return None + return 60.0 * sum((t - mt) * (v - mv) for t, v in points) / spread + + +def near(rows, t, within=2.0): + """The row of `rows` (sorted by time) nearest to t, if within `within` seconds.""" + best = min(rows, key=lambda r: abs(r[0] - t), default=None) + return best if best is not None and abs(best[0] - t) <= within else None + + +def memory_rows(run): + """One row per memory line, with the video memory and census lines written with it (`memory.csv`).""" + rows = [] + for t, private, in_memory, free, left in run.memory: + v = near(run.video, t) + w = near(run.waits, t) + rows.append({"t_s": round(t, 3), "private_mb": private, "in_memory_mb": in_memory, "pc_free_mb": free, + "pc_commit_left_mb": left, "vram_budget_mb": v[1] if v else None, + "vram_in_use_mb": v[2] if v else None, "shared_in_use_mb": v[4] if v else None, + "waiting_objects": w[1] if w else None, "reaper_queue": w[2] if w else None}) + return rows + + +def write_series(run, folder): + """Writes memory.csv beside summary.json when the run has memory lines; returns its name or None.""" + rows = memory_rows(run) + if not rows: + return None + with open(os.path.join(folder, SERIES), "w", encoding="utf-8", newline="") as f: + out = csv.DictWriter(f, fieldnames=SERIES_COLUMNS, lineterminator="\n") + out.writeheader() + out.writerows(rows) + return SERIES + + +def memory_block(run, world=None): + """Peaks of the runtime's memory lines over the whole run (none from a build without diagnostics), the + reaper's queue at its longest, and how fast the private bytes grew in the world (a pile-up's slope).""" out = {"source": None, "lines": 0, "private_max_mb": None, "private_max_at_s": None, "in_memory_max_mb": None, "pc_commit_left_min_mb": None, "pc_commit_left_min_at_s": None, "vram_in_use_max_mb": None, "vram_max_at_s": None, "vram_budget_at_max_mb": None, "vram_over_budget_s": None, - "shared_in_use_max_mb": None} + "shared_in_use_max_mb": None, "reaper_queue_max": None, "reaper_queue_max_at_s": None, + "waiting_objects_max": None, "private_mb_per_min_in_world": None, "series": None} + if run.waits: + t, queue = max(((w[0], w[2]) for w in run.waits), key=lambda x: x[1]) + out["reaper_queue_max"], out["reaper_queue_max_at_s"] = queue, round(t, 3) + out["waiting_objects_max"] = max(w[1] for w in run.waits) + if run.memory and world is not None: + slope = slope_per_min([(m[0], m[1]) for m in run.memory if m[0] >= world]) + out["private_mb_per_min_in_world"] = round(slope, 1) if slope is not None else None + if run.memory: + out["series"] = SERIES if run.memory: out["source"], out["lines"] = "memory lines", len(run.memory) t, private = max(((t, p) for t, p, *_ in run.memory), key=lambda x: x[1]) @@ -473,7 +544,7 @@ def summary(run): }, "fps": fps, "pipelines": {"missed_waits": len(run.missed), "making_max": max((m for *_, m in run.frames), default=0)}, - "memory": dict(memory_block(run), stop_limits=run.meta.get("memory_stop")), + "memory": dict(memory_block(run, world), stop_limits=run.meta.get("memory_stop")), "crash": { "kind": crash_kind, "at_s": round(first["at_s"], 3) if first and first["at_s"] is not None else None, @@ -502,6 +573,7 @@ def main(argv): print(json.dumps(state(run))) return 0 out = summary(run) + write_series(run, argv[2]) with open(os.path.join(argv[2], "summary.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=2) f.write("\n") -- 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 'docs') 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 bb6ff131273a9782c3ac7cb7c24bcfd5dd7a48d5 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 02:55:26 +0100 Subject: gate: no stale memory.csv, and the docs say what the series holds (review) `write_series` returned before an older memory.csv was touched, so a folder summarized again from a log without memory lines kept old rows beside `series: null`: it now removes that file. Two tests go through `main()`: no memory lines writes no file, and an older file goes. The docs list the CSV header, how its video memory and census columns are picked (the nearest line within 2 s), `reaper_queue_max_at_s` and `waiting_objects_max`, and that the summary's video memory peak counts every video memory line, the swap chain's too, so it can come from a line with no row in the CSV. "Not in this version" no longer lists the time series and the VRAM and RAM peaks. The census line's fixture is the runtime's sentence as it is now, with the reaper's bound (LEONIDA_REAPER_LIMIT) at its end; the part the parser reads did not change. --- docs/game_gate.md | 6 ++---- tests/test_game_gate.py | 24 ++++++++++++++++++++++-- tools/game_gate.py | 8 ++++++-- 3 files changed, 30 insertions(+), 8 deletions(-) (limited to 'docs') diff --git a/docs/game_gate.md b/docs/game_gate.md index 049c52b69..4eb842ec2 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -50,7 +50,7 @@ The run folder (under `-RunRoot`, by default `\gate-runs`, refused inside | `events.jsonl` | What the gate did and saw: the game found, the stop asked for and why, a kill, the exit code | | `data\` | The run's copy of the template, and the runtime's `crashes.log` | | `summary.json` | The result, below | -| `memory.csv` | One row per runtime memory line (every 5 s, builds with diagnostics): time, private bytes, of them in physical memory, the PC's memory free and left to commit, the card's video memory budget and in use, the shared memory in use, the objects let go that wait for their submissions, and the reaper thread's queue. Only when the run has memory lines | +| `memory.csv` | One row per runtime memory line (every 5 s, builds with diagnostics): time, private bytes, of them in physical memory, the PC's memory free and left to commit, the card's video memory budget and in use, the shared memory in use, the objects let go that wait for their submissions, and the reaper thread's queue. Its header is `t_s,private_mb,in_memory_mb,pc_free_mb,pc_commit_left_mb,vram_budget_mb,vram_in_use_mb,shared_in_use_mb,waiting_objects,reaper_queue`. The video memory columns come from the video memory line nearest the memory line, and the last two from the census line nearest it, each within 2 s; a cell is empty when there is none. Only when the run has memory lines: a summary made again from a log without them removes an older `memory.csv` | ## summary.json (`leonida-gate-summary/1`) @@ -66,7 +66,7 @@ Times are seconds since the run started. The summary holds numbers, switch names | `times.world_s` | Seconds from `world_at_s` to the stop request | | `fps` | From the presents, after the first 60 s in the world: frames, median, p5, frame p95 (ms), median of the last 60 s (`end_median`), the first second with fewer than 2 frames, from 60 s in the world on too (`under_2_at_s`), the longest gap with no frame presented from the world on (`longest_present_gap_s`, `longest_gap_at_s`; on purpose from the world on: a freeze on pipeline compiles comes right after arrival, and 10 s with no frame is what a player sees), draws a frame. Without the present lines (a build without diagnostics), the median and p5 come from the frame lines, with a warning | | `pipelines` | Waits that ran out (`missed_waits`), the most pipelines being made at once | -| `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. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop). Also the reaper thread's queue at its longest and when (`reaper_queue_max`), the most objects waiting for their submissions, and how fast the private bytes grew in the world in MB a minute (`private_mb_per_min_in_world`, a least-squares slope: on a short run it is the loading's climb, on a long one a pile-up's slope), and `series`: the name of `memory.csv` | +| `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. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop). Also, from the runtime's census line, the reaper thread's queue at its longest and when (`reaper_queue_max`, `reaper_queue_max_at_s`) and the most objects let go that wait for their submissions (`waiting_objects_max`); how fast the private bytes grew in the world in MB a minute (`private_mb_per_min_in_world`, a least-squares slope: on a short run it is the loading's climb, on a long one a pile-up's slope); and `series`, the name of `memory.csv` (null without memory lines). The video memory peak and the time over the budget count every video memory line, the ones the runtime writes when it makes the swap chain too. `memory.csv` has only the one nearest each memory line, so the summary's peak can come from a line with no row there | | `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` 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 | @@ -104,8 +104,6 @@ A crash after the stop request is a warning, except a device loss or a panic, wh - A driver for the menus and a fixed route (a Lua mod). - An ABBA runner over several runs. -- A time series beside the summary (memory, census, reaping queue). - A "memory rising" warning. -- VRAM and RAM peaks. - The distance walked. - The Vulkan runtime (`gta6rt`). diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index 58da38ea5..ddfd4fbe9 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -58,7 +58,9 @@ class Fake: self.log.append(f"{stamp(t)} INFO leonida_gpu::census: memory, what waits to be let go: {waiting} objects let " f"go that wait for the submissions that may use them (LEONIDA_BURY_LAG), {reaper} retired " f"objects, landed host lists and lists' fronts handed to the thread that lets them go and not " - f"let go yet (LEONIDA_REAPER=0: let go by the submitting thread)") + f"let go yet (LEONIDA_REAPER=0: let go by the submitting thread); 0 let go by the thread done " + f"with them instead, since the start, the reaper thread's line holding LEONIDA_REAPER_LIMIT=0 or " + f"more (0: no bound)") self.log.append(f"{stamp(t)} INFO leonida_gpu::host: video memory as the system counts it, with the memory " f"line: the card's own: budget {budget} MB, in use {used} MB, 100 MB could still be reserved, " f"0 MB reserved; the PC's shared with the card: budget 16000 MB, in use {shared} MB, 0 MB could " @@ -329,7 +331,8 @@ class Measures(unittest.TestCase): self.assertEqual(rows[-1]["vram_in_use_mb"], "7000") def test_a_build_without_memory_lines_gives_no_memory_peaks(self): - m = passing().summarize()["memory"] + f = passing() + m = f.summarize()["memory"] self.assertIsNone(m["source"]) self.assertEqual(m["lines"], 0) self.assertIsNone(m["private_max_mb"]) @@ -337,6 +340,23 @@ class Measures(unittest.TestCase): self.assertIsNone(m["series"]) self.assertIsNone(m["reaper_queue_max"]) self.assertIsNone(m["private_mb_per_min_in_world"]) + # And `summary` writes no series file: not even a header alone. + with contextlib.redirect_stdout(io.StringIO()): + game_gate.main(["game_gate.py", "summary", f.dir]) + self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv"))) + + def test_a_folder_summarized_again_without_memory_lines_keeps_no_old_series(self): + # A memory.csv from an earlier summary, and a log that has no memory lines now: the old rows must not sit + # beside `series: null`. + f = passing() + f.summarize() + with open(os.path.join(f.dir, "memory.csv"), "w", encoding="utf-8", newline="\n") as fh: + fh.write(",".join(game_gate.SERIES_COLUMNS) + "\n70.0,1000,500,15000,4000,8000,7000,500,0,0\n") + with contextlib.redirect_stdout(io.StringIO()): + game_gate.main(["game_gate.py", "summary", f.dir]) + with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh: + self.assertIsNone(json.load(fh)["memory"]["series"]) + self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv"))) def test_without_present_lines_the_frame_lines_give_the_rate(self): f = Fake() diff --git a/tools/game_gate.py b/tools/game_gate.py index 076c57175..d567c46fa 100644 --- a/tools/game_gate.py +++ b/tools/game_gate.py @@ -417,11 +417,15 @@ def memory_rows(run): def write_series(run, folder): - """Writes memory.csv beside summary.json when the run has memory lines; returns its name or None.""" + """Writes memory.csv beside summary.json when the run has memory lines; returns its name or None. Without them + it removes a memory.csv already there (a folder summarized again), so no old rows sit beside `series: null`.""" + path = os.path.join(folder, SERIES) rows = memory_rows(run) if not rows: + if os.path.exists(path): + os.remove(path) return None - with open(os.path.join(folder, SERIES), "w", encoding="utf-8", newline="") as f: + with open(path, "w", encoding="utf-8", newline="") as f: out = csv.DictWriter(f, fieldnames=SERIES_COLUMNS, lineterminator="\n") out.writeheader() out.writerows(rows) -- cgit v1.2.3 From 01203fb3bf08de1b2bd019b00032514af1b07e66 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:21:51 +0100 Subject: gate: a negative memory limit is off, and the poll's order tested in full (review) A negative -StopOverBudgetSeconds stopped every run at its first video memory line: 0 s over the budget passed a negative limit. Every limit is now off at 0 or less, with a test for each, and a line at exactly the private limit is tested not to stop. The poll test gets a memory limit at the time limit (memory wins), and the script text test checks the target and time limits the loop passes and that the memory stop's sentence reaches the stop event. The docs give the poll's whole order (a STOP file and the world time at the same check give `target`), say that `world_time_short` and `world_not_reached` are not added to `memory_stop`, and name `memory.stop_limits`. --- docs/game_gate.md | 8 ++++---- tests/test_game_gate.py | 14 ++++++++++++-- tools/game_gate.py | 8 ++++---- 3 files changed, 20 insertions(+), 10 deletions(-) (limited to 'docs') diff --git a/docs/game_gate.md b/docs/game_gate.md index 9f0722cfc..d0cf38cb0 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -27,13 +27,13 @@ pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir - **The play script's switches.** `-PlayArgs` passes them on as they are, for example `-SeriesS -NoFrameGen`. - **Reaching the world.** The gate does not drive the menus. Pass key presses with `LEONIDA_KEYS`; they are timed from the start of the process, so allow for the precompile. - **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). +- **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). It checks every 5 s. When two reasons come at the same check, the first of these wins: the title relaunched, the world time (`target`), the memory stop (below), the `STOP` file, the time limit. So a `STOP` file and the world time at the same check give `target`. - **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: 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). - 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. + 0 turns a limit off. The limits go into `run.json` (`memory_stop`) and the summary (`memory.stop_limits`). 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. @@ -65,7 +65,7 @@ Times are seconds since the run started. The summary holds numbers, switch names | `times.world_s` | Seconds from `world_at_s` to the stop request | | `fps` | From the presents, after the first 60 s in the world: frames, median, p5, frame p95 (ms), median of the last 60 s (`end_median`), the first second with fewer than 2 frames, from 60 s in the world on too (`under_2_at_s`), the longest gap with no frame presented from the world on (`longest_present_gap_s`, `longest_gap_at_s`; on purpose from the world on: a freeze on pipeline compiles comes right after arrival, and 10 s with no frame is what a player sees), draws a frame. Without the present lines (a build without diagnostics), the median and p5 come from the frame lines, with a warning | | `pipelines` | Waits that ran out (`missed_waits`), the most pipelines being made at once | -| `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 | +| `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. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop) | | `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` 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 | @@ -87,7 +87,7 @@ Times are seconds since the run started. The summary holds numbers, switch names - `exited_before_stop`; - `present_gap`; - `world_time_short`: the time limit came first; -- `memory_stop`: the memory stop ended the run, which was on its way to running out; +- `memory_stop`: the memory stop ended the run, which was on its way to running out. `world_time_short` and `world_not_reached` are not added to it: the stop is why the run was short; - `not_alive_at_stop`; - `world_not_reached`, when the game ended before reaching the world. diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index bae6302bf..23cfbabea 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -264,13 +264,17 @@ class Measures(unittest.TestCase): } for why, rows in cases.items(): self.assertEqual(self.memory_run(limits, rows).state()["memory_stop"], why) - # Under each limit, or not for long enough: no stop. - for rows in (calm, calm + [(24000, 7000, 150)] * 4, calm + [(24000, 9000, 3000)] * 12): + # Under each limit, at the private limit itself, or not for long enough: no stop. + for rows in (calm, calm + [(30000, 7000, 3000)], calm + [(24000, 7000, 150)] * 4, + calm + [(24000, 9000, 3000)] * 12): self.assertIsNone(self.memory_run(limits, rows).state()["memory_stop"]) # 0 turns a limit off, and a run.json without limits (an older gate) never stops for memory. off = {"private_max_mb": 0, "commit_left_min_mb": 0, "over_budget_s": 0} self.assertIsNone(self.memory_run(off, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"]) self.assertIsNone(self.memory_run(None, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"]) + # A negative limit is off too, not a stop at the first line (`-StopOverBudgetSeconds -1` stopped every run). + for name in limits: + self.assertIsNone(self.memory_run(dict(limits, **{name: -1}), calm).state()["memory_stop"], name) def test_a_run_stopped_for_memory_fails_with_its_reason(self): limits = {"private_max_mb": 30000, "commit_left_min_mb": 200, "over_budget_s": 60} @@ -401,6 +405,9 @@ class Script(unittest.TestCase): ({"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"), + # A memory limit at the time limit: the memory stop names the real reason. + ({"relaunched": False, "world_s": 100.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 45, + "memory"), ({"relaunched": False, "world_s": 0.0, "memory_stop": None}, False, 45, "timeout"), ({"relaunched": False, "world_s": 100.0, "memory_stop": None}, False, 20, "none"), ] @@ -410,7 +417,10 @@ class Script(unittest.TestCase): 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.assertIn("-TargetSeconds $WorldSeconds -LimitMinutes $MaxMinutes", text) self.assertEqual(text.count("$stopReason = "), 2) # set to $null before the loop, then only from the function + # The memory stop's sentence goes into the stop_requested event (`stop.memory_why`). + self.assertIn("if ($stopReason -eq 'memory') { $memoryWhy = $state.memory_stop }", text) pwsh = shutil.which("pwsh") if not pwsh: self.skipTest("no PowerShell 7 here") diff --git a/tools/game_gate.py b/tools/game_gate.py index 0c9772c28..c2748cde8 100644 --- a/tools/game_gate.py +++ b/tools/game_gate.py @@ -285,19 +285,19 @@ def since_end(rows, low): def memory_alarm(run): """Why scripts/game-gate.ps1 must stop the run for memory now, or None, from the latest memory lines and the - limits it wrote in run.json (`memory_stop`; 0 turns one off).""" + limits it wrote in run.json (`memory_stop`; 0 or less turns one off).""" limits = run.meta.get("memory_stop") or {} private_max = limits.get("private_max_mb") or 0 left_min = limits.get("commit_left_min_mb") or 0 over_s = limits.get("over_budget_s") or 0 if run.memory: private = run.memory[-1][1] - if private_max and private > private_max: + if private_max > 0 and private > private_max: return f"private bytes {private} MB, over {private_max} MB" - low = since_end(run.memory, lambda m: m[4] < left_min) if left_min else 0.0 + low = since_end(run.memory, lambda m: m[4] < left_min) if left_min > 0 else 0.0 if low >= COMMIT_LOW_S: return f"the PC had under {left_min} MB left to commit for {low:.0f} s" - if over_s and run.video: + if over_s > 0 and run.video: over = since_end(run.video, lambda v: v[2] > v[1]) if over >= over_s: return f"video memory over its budget for {over:.0f} s" -- cgit v1.2.3 From 0e5ebd0c697d62fcac20adeb60b38044ec8b96c1 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:25:39 +0100 Subject: gate: the summary even when memory.csv cannot be written, the slope up to the stop (review) `summary` wrote memory.csv before summary.json, so a memory.csv open in another program left no summary and exit 1. A file it cannot write or remove is now said on stderr, `series` is null and summary.json is written. The private bytes' slope counted the memory lines written while the title ends after the stop request; it now covers the world up to the stop, as the frame rates do. New tests: the 2 s window and the empty cells of memory.csv, its LF line ends, the slope with lines after the stop and with fewer than 3 lines in the world, and a memory.csv that cannot be written. The census sentence's contract is one key over the whole part WAITS reads, the ", " between its two numbers too. The docs name every video memory line the peak counts (the swap chain made, its buffers made again, a budget change of 256 MB or more) and when the slope and `series` are null. --- docs/game_gate.md | 2 +- tests/test_game_gate.py | 65 ++++++++++++++++++++++++++++++++++++++++++++++++- tools/game_gate.py | 40 +++++++++++++++++------------- 3 files changed, 88 insertions(+), 19 deletions(-) (limited to 'docs') diff --git a/docs/game_gate.md b/docs/game_gate.md index 4eb842ec2..ec6e3eece 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -66,7 +66,7 @@ Times are seconds since the run started. The summary holds numbers, switch names | `times.world_s` | Seconds from `world_at_s` to the stop request | | `fps` | From the presents, after the first 60 s in the world: frames, median, p5, frame p95 (ms), median of the last 60 s (`end_median`), the first second with fewer than 2 frames, from 60 s in the world on too (`under_2_at_s`), the longest gap with no frame presented from the world on (`longest_present_gap_s`, `longest_gap_at_s`; on purpose from the world on: a freeze on pipeline compiles comes right after arrival, and 10 s with no frame is what a player sees), draws a frame. Without the present lines (a build without diagnostics), the median and p5 come from the frame lines, with a warning | | `pipelines` | Waits that ran out (`missed_waits`), the most pipelines being made at once | -| `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. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop). Also, from the runtime's census line, the reaper thread's queue at its longest and when (`reaper_queue_max`, `reaper_queue_max_at_s`) and the most objects let go that wait for their submissions (`waiting_objects_max`); how fast the private bytes grew in the world in MB a minute (`private_mb_per_min_in_world`, a least-squares slope: on a short run it is the loading's climb, on a long one a pile-up's slope); and `series`, the name of `memory.csv` (null without memory lines). The video memory peak and the time over the budget count every video memory line, the ones the runtime writes when it makes the swap chain too. `memory.csv` has only the one nearest each memory line, so the summary's peak can come from a line with no row there | +| `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. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop). Also, from the runtime's census line, the reaper thread's queue at its longest and when (`reaper_queue_max`, `reaper_queue_max_at_s`) and the most objects let go that wait for their submissions (`waiting_objects_max`); how fast the private bytes grew in the world in MB a minute (`private_mb_per_min_in_world`, a least-squares slope over the memory lines from `world_at_s` to the stop request: on a short run it is the loading's climb, on a long one a pile-up's slope; null with fewer than 3 lines there); and `series`, the name of `memory.csv` (null without memory lines, or when the file could not be written, for example open in another program: `game_gate.py` says so on stderr and writes `summary.json` all the same). The video memory peak and the time over the budget count every video memory line: the one written with each memory line, and the ones the runtime writes right before and after it makes the swap chain, right after the swap chain's buffers are made again for another size or format, and right after the system changes the card's budget by 256 MB or more. `memory.csv` has only the one nearest each memory line, so the summary's peak can come from a line with no row there | | `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` 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 | diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index ddfd4fbe9..b842660f9 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py @@ -309,7 +309,7 @@ class Measures(unittest.TestCase): def test_the_memory_series_and_a_pile_ups_slope(self): f = passing() - for i, t in enumerate(range(10, 390, 5)): + for t in range(10, 390, 5): # From the world on (70 s) the private bytes grow 10 MB every 5 s and the reaper's queue grows. grown = max(0, t - 70) // 5 f.memory(t, 20000 + 10 * grown, 7000, waiting=3, reaper=100 * grown) @@ -329,6 +329,69 @@ class Measures(unittest.TestCase): self.assertEqual(rows[-1]["private_mb"], "20630") self.assertEqual(rows[-1]["reaper_queue"], "6300") self.assertEqual(rows[-1]["vram_in_use_mb"], "7000") + # The same bytes on every machine: LF line ends, never CRLF. + with open(os.path.join(f.dir, "memory.csv"), "rb") as fh: + self.assertNotIn(b"\r", fh.read()) + + def summary_files(self, f): + """`game_gate.py summary` on the folder: (exit code, summary.json, memory.csv rows or None, stderr).""" + f.summarize() + err = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + code = game_gate.main(["game_gate.py", "summary", f.dir]) + with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh: + s = json.load(fh) + path = os.path.join(f.dir, "memory.csv") + rows = None + if os.path.isfile(path): + with open(path, encoding="utf-8") as fh: + rows = list(csv.DictReader(fh)) + return code, s, rows, err.getvalue() + + def test_the_series_takes_the_lines_within_2_s_of_each_memory_line(self): + f = passing() + f.memory(100, 20000, 7000, waiting=3, reaper=40) # the three lines at once, as the runtime writes them + f.memory(200, 21000, 7500, waiting=5, reaper=50) + census, video, memory = f.log[-3:] + # The video memory line 2 s before (taken), the census line 2.5 s after (too far: empty cells). + f.log[-3:] = [census.replace(stamp(200), stamp(202.5)), video.replace(stamp(200), stamp(198)), memory] + f.memory(300, 22000, 8000) + f.log[-3:] = f.log[-1:] # a memory line alone + _, _, rows, _ = self.summary_files(f) + got = [(r["t_s"], r["vram_in_use_mb"], r["shared_in_use_mb"], r["waiting_objects"], r["reaper_queue"]) + for r in rows] + self.assertEqual(got, [("100.0", "7000", "500", "3", "40"), ("200.0", "7500", "500", "", ""), + ("300.0", "", "", "", "")]) + + def test_the_slope_counts_the_world_up_to_the_stop(self): + f = Fake() + f.event(1, "game", pid=1) + f.frames(10, 70, 60.0, 13) + f.frames(70, 420, 50.0, 4000) + for t in range(70, 420, 5): + # 120 MB a minute in the world, then a jump while the title ends after the stop request (390 s). + f.memory(t, 20000 + 2 * (t - 70) if t <= 390 else 40000, 7000) + f.event(390, "stop_requested", reason="target") + f.event(420, "game_exited", exit_code=0) + self.assertEqual(f.summarize()["memory"]["private_mb_per_min_in_world"], 120.0) + # Fewer than 3 memory lines in the world: no slope. + f = passing() + for t in (40, 50, 60, 100, 200): + f.memory(t, 20000 + t, 7000) + self.assertIsNone(f.summarize()["memory"]["private_mb_per_min_in_world"]) + + def test_a_series_it_cannot_write_still_leaves_the_summary(self): + # memory.csv held by another program: the summary is written all the same, with no series named. + f = passing() + for t in range(70, 390, 5): + f.memory(t, 20000, 7000) + os.makedirs(os.path.join(f.dir, "memory.csv")) # opening it to write fails, as a locked file does + code, s, _, err = self.summary_files(f) + self.assertEqual(code, 0) + self.assertEqual(s["verdict"]["result"], "PASS") + self.assertIsNone(s["memory"]["series"]) + self.assertEqual(s["memory"]["lines"], 64) + self.assertIn("memory.csv not written or removed", err) def test_a_build_without_memory_lines_gives_no_memory_peaks(self): f = passing() diff --git a/tools/game_gate.py b/tools/game_gate.py index d567c46fa..b88ec9535 100644 --- a/tools/game_gate.py +++ b/tools/game_gate.py @@ -87,10 +87,10 @@ SOURCES = { "d3d12/crates/leonida-gpu/src/host.rs", "the PC's shared with the card: budget {} MB, in use {} MB": "d3d12/crates/leonida-gpu/src/host.rs", 'h.log_video_memory("with the memory line")': "d3d12/crates/leonida-gpu/src/copystat.rs", + # One key over the whole part WAITS reads, the ", " between its two numbers too. "memory, what waits to be let go: {waiting} objects let go that wait for the submissions that may use them " - "(LEONIDA_BURY_LAG)": "d3d12/crates/leonida-gpu/src/census.rs", - "{handed} retired objects, landed host lists and lists' fronts handed to the thread that lets them go": - "d3d12/crates/leonida-gpu/src/census.rs", + "(LEONIDA_BURY_LAG), {handed} retired objects, landed host lists and lists' fronts handed to the thread that " + "lets them go": "d3d12/crates/leonida-gpu/src/census.rs", "crate::census::log();": "d3d12/crates/leonida-gpu/src/copystat.rs", } @@ -418,23 +418,29 @@ def memory_rows(run): def write_series(run, folder): """Writes memory.csv beside summary.json when the run has memory lines; returns its name or None. Without them - it removes a memory.csv already there (a folder summarized again), so no old rows sit beside `series: null`.""" + it removes a memory.csv already there (a folder summarized again), so no old rows sit beside `series: null`. + A file it cannot write or remove (open in another program) is said on stderr: the summary is written anyway.""" path = os.path.join(folder, SERIES) rows = memory_rows(run) - if not rows: - if os.path.exists(path): - os.remove(path) + try: + if not rows: + if os.path.exists(path): + os.remove(path) + return None + with open(path, "w", encoding="utf-8", newline="") as f: + out = csv.DictWriter(f, fieldnames=SERIES_COLUMNS, lineterminator="\n") + out.writeheader() + out.writerows(rows) + except OSError as e: + print(f"{SERIES} not written or removed: {e.__class__.__name__}: {e.strerror or e}", file=sys.stderr) return None - with open(path, "w", encoding="utf-8", newline="") as f: - out = csv.DictWriter(f, fieldnames=SERIES_COLUMNS, lineterminator="\n") - out.writeheader() - out.writerows(rows) return SERIES -def memory_block(run, world=None): +def memory_block(run, world=None, end=None): """Peaks of the runtime's memory lines over the whole run (none from a build without diagnostics), the - reaper's queue at its longest, and how fast the private bytes grew in the world (a pile-up's slope).""" + reaper's queue at its longest, and how fast the private bytes grew in the world up to `end` (a pile-up's + slope; the lines written while the title ends after the stop request do not count).""" out = {"source": None, "lines": 0, "private_max_mb": None, "private_max_at_s": None, "in_memory_max_mb": None, "pc_commit_left_min_mb": None, "pc_commit_left_min_at_s": None, "vram_in_use_max_mb": None, "vram_max_at_s": None, "vram_budget_at_max_mb": None, "vram_over_budget_s": None, @@ -445,11 +451,10 @@ def memory_block(run, world=None): out["reaper_queue_max"], out["reaper_queue_max_at_s"] = queue, round(t, 3) out["waiting_objects_max"] = max(w[1] for w in run.waits) if run.memory and world is not None: - slope = slope_per_min([(m[0], m[1]) for m in run.memory if m[0] >= world]) + slope = slope_per_min([(m[0], m[1]) for m in run.memory if world <= m[0] and (end is None or m[0] <= end)]) out["private_mb_per_min_in_world"] = round(slope, 1) if slope is not None else None if run.memory: out["series"] = SERIES - if run.memory: out["source"], out["lines"] = "memory lines", len(run.memory) t, private = max(((t, p) for t, p, *_ in run.memory), key=lambda x: x[1]) out["private_max_mb"], out["private_max_at_s"] = private, round(t, 3) @@ -548,7 +553,7 @@ def summary(run): }, "fps": fps, "pipelines": {"missed_waits": len(run.missed), "making_max": max((m for *_, m in run.frames), default=0)}, - "memory": dict(memory_block(run, world), stop_limits=run.meta.get("memory_stop")), + "memory": dict(memory_block(run, world, end), stop_limits=run.meta.get("memory_stop")), "crash": { "kind": crash_kind, "at_s": round(first["at_s"], 3) if first and first["at_s"] is not None else None, @@ -577,7 +582,8 @@ def main(argv): print(json.dumps(state(run))) return 0 out = summary(run) - write_series(run, argv[2]) + # `series` names the file only when it was written. + out["memory"]["series"] = write_series(run, argv[2]) with open(os.path.join(argv[2], "summary.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=2) f.write("\n") -- 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 'docs') 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 'docs') 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 'docs') 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 'docs') 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 3b3e5ee5dadd0e028d4d6a63186ea57830d0f4bf Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:12:01 +0100 Subject: docs/testing.md: red_green.py --work-dir leaves its worktree registered; git worktree remove /tree removes it (review) --- docs/testing.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/testing.md b/docs/testing.md index a7b1b4ea9..4ec81fec6 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -148,7 +148,8 @@ python -I scripts/red_green.py 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. + delete the folder (and run `git worktree prune`) when done. With `--work-dir `, the worktree stays registered + in git: `git worktree remove /tree` removes it, then delete ``. - 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`, -- 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 'docs') 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 'docs') 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 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 'docs') 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 'docs') 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 2051ccd0aadb43ef42aa3fe3cf7bd5a1d43fde1d Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:59:33 +0100 Subject: docs/testing.md: red_green.py --mutate results include compiler crashed; one way to remove the worktree, default folder or --work-dir (review) --- docs/testing.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'docs') diff --git a/docs/testing.md b/docs/testing.md index becb61310..11b184ff4 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -147,9 +147,9 @@ python -I scripts/red_green.py 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. With `--work-dir `, the worktree stays registered - in git: `git worktree remove /tree` removes it, then delete ``. + and the target dir stay for the next run, which then builds only what changed. The target dir takes several GB. + The worktree stays registered in git, in the default folder as with `--work-dir`: when done, run + `git worktree remove --force /tree` and delete the folder, or delete the folder and run `git worktree prune`. - 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`, @@ -162,9 +162,9 @@ python -I scripts/red_green.py - `--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). 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 + 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. - Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it. -- 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 'docs') 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