From 80930f0d1152dc1aef630a3538caeeea49eba3e7 Mon Sep 17 00:00:00 2001 From: budanga Date: Thu, 26 Nov 2026 12:56:44 -0300 Subject: [PATCH 1/3] rdna2spirv: start a tool again when a Windows job refuses it with ERROR_NOT_ENOUGH_QUOTA (COMPUTE-WORKER-SPAWN-QUOTA) The Windows compute worker runs in a job that allows two active processes, itself and one tool. The job can still count a tool that has just exited, so CreateProcess refuses the next one with winerror 1816 and the worker fails (test_translate_pipeline_compute: 9 of 12 runs on a busy Windows 11 host). _run_spirv_tool now starts a refused tool again with a doubling delay for at most 2 s, then raises as before; other errors are unchanged. Co-Authored-By: Claude Opus 5.5 --- tests/test_rdna2spirv_spawn_quota.py | 131 +++++++++++++++++++++++++++ tools/rdna2spirv.py | 29 ++++-- 2 files changed, 153 insertions(+), 7 deletions(-) create mode 100644 tests/test_rdna2spirv_spawn_quota.py diff --git a/tests/test_rdna2spirv_spawn_quota.py b/tests/test_rdna2spirv_spawn_quota.py new file mode 100644 index 0000000000..7336fbc6bc --- /dev/null +++ b/tests/test_rdna2spirv_spawn_quota.py @@ -0,0 +1,131 @@ +"""tools/rdna2spirv.py: _run_spirv_tool starts a tool again when Windows refuses it with ERROR_NOT_ENOUGH_QUOTA. + + python -I tests/test_rdna2spirv_spawn_quota.py -v + +The Windows compute worker (scripts/compute_workers_win.py) runs in a job that allows two active processes: itself +and one tool. The job can still count a tool that has just exited when the next one is started, and CreateProcess +then fails with winerror 1816. The unit tests fake that error; the Windows-only test starts real processes in such +a job. No game data. +""" +import errno +import json +import os +from pathlib import Path +import subprocess +import sys +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "scripts")) + +import rdna2spirv # noqa: E402 + +QUOTA = 1816 # ERROR_NOT_ENOUGH_QUOTA + + +def win_error(code): + """An OSError as CreateProcess raises it, with the Win32 code in .winerror (a plain attribute off Windows).""" + e = OSError(errno.ENOMEM, "Not enough quota is available to process this command") + e.winerror = code + return e + + +class Clock: + """time.monotonic and time.sleep stand-ins: sleeping moves the clock, nothing waits.""" + + def __init__(self): + self.now = 0.0 + self.sleeps = [] + + def monotonic(self): + return self.now + + def sleep(self, seconds): + self.sleeps.append(seconds) + self.now += seconds + + +class RunSpirvToolTests(unittest.TestCase): + def setUp(self): + self.clock = Clock() + for name in ("monotonic", "sleep"): + patcher = mock.patch.object(rdna2spirv.time, name, getattr(self.clock, name)) + patcher.start() + self.addCleanup(patcher.stop) + + def test_quota_refusals_are_started_again(self): + done = subprocess.CompletedProcess(["spirv-val"], 0) + with mock.patch.object(rdna2spirv.subprocess, "run", + side_effect=[win_error(QUOTA), win_error(QUOTA), done]) as run: + self.assertIs(rdna2spirv._run_spirv_tool(["spirv-val", "x.spv"], capture_output=True), done) + self.assertEqual(run.call_count, 3) + for call in run.call_args_list: + self.assertEqual(call, mock.call(["spirv-val", "x.spv"], capture_output=True)) + self.assertEqual(len(self.clock.sleeps), 2) + + def test_a_refusal_that_lasts_is_raised_once_the_time_is_up(self): + with mock.patch.object(rdna2spirv.subprocess, "run", side_effect=win_error(QUOTA)) as run: + with self.assertRaises(OSError) as raised: + rdna2spirv._run_spirv_tool(["spirv-as", "-"]) + self.assertEqual(raised.exception.winerror, QUOTA) + self.assertGreater(run.call_count, 1) + self.assertLessEqual(self.clock.now, rdna2spirv.SPAWN_RETRY_SECONDS) + self.assertGreaterEqual(self.clock.now, rdna2spirv.SPAWN_RETRY_SECONDS - max(self.clock.sleeps)) + + def test_other_errors_are_not_retried(self): + for error in (win_error(5), OSError(errno.ENOMEM, "out of memory")): + with self.subTest(error=error): + with mock.patch.object(rdna2spirv.subprocess, "run", side_effect=error) as run: + with self.assertRaises(OSError) as raised: + rdna2spirv._run_spirv_tool(["spirv-val"]) + self.assertIs(raised.exception, error) + self.assertEqual(run.call_count, 1) + self.assertEqual(self.clock.sleeps, []) + + def test_a_missing_tool_still_names_itself(self): + missing = FileNotFoundError(errno.ENOENT, "The system cannot find the file specified") + missing.winerror = 2 + with mock.patch.object(rdna2spirv.subprocess, "run", side_effect=missing) as run: + with self.assertRaises(FileNotFoundError) as raised: + rdna2spirv._run_spirv_tool(["spirv-as", "-"]) + self.assertEqual(raised.exception.filename, "spirv-as") + self.assertEqual(run.call_count, 1) + + +CHILD = """ +import json, sys +sys.path.insert(0, sys.argv[1]) +import rdna2spirv +sys.stdin.readline() # in the job from here on +for _ in range(int(sys.argv[2])): + rdna2spirv._run_spirv_tool(["cmd", "/c", "rem"], capture_output=True, check=True) +print(json.dumps("ok")) +""" + + +@unittest.skipUnless(os.name == "nt", "Windows job objects") +class TwoProcessJobTests(unittest.TestCase): + def test_back_to_back_tools_in_the_worker_job(self): + # Before the retry, 15 to 28 of 300 such starts failed (5-9 %) with winerror 1816 on a Windows 11 host. + import compute_workers_win as win + mib = 1024 + with win.job(mib, True) as job: + p = subprocess.Popen([sys.executable, "-I", "-c", CHILD, str(ROOT / "tools"), "150"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + creationflags=win.LOW) + try: + win.check(win.assign(job, int(p._handle))) + win.verify(job, int(p._handle), mib, True) + out, err = p.communicate("go\n", timeout=300) + finally: + if p.poll() is None: + p.kill() + p.wait(timeout=10) + self.assertEqual(p.returncode, 0, err) + self.assertEqual(json.loads(out), "ok") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 73df48ed8e..bcfd0b0b5a 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -19934,14 +19934,29 @@ def merge_shard_parts(out): return merged +SPAWN_RETRY_SECONDS = 2.0 +_NOT_ENOUGH_QUOTA = 1816 # ERROR_NOT_ENOUGH_QUOTA + + def _run_spirv_tool(cmd, **kwargs): - try: - return subprocess.run(cmd, **kwargs) - except FileNotFoundError as exc: - # Windows CreateProcess omits the executable name from WinError 2. - if getattr(exc, "winerror", None) == 2 and exc.filename is None: - exc.filename = cmd[0] - raise + # A Windows job's active-process limit can still count a tool that has just exited, and CreateProcess then + # refuses the next one with ERROR_NOT_ENOUGH_QUOTA: the compute worker's job allows itself and one tool + # (scripts/compute_workers_win.py). The refused tool never started, so it is started again for a bounded time. + deadline = time.monotonic() + SPAWN_RETRY_SECONDS + delay = 0.005 + while True: + try: + return subprocess.run(cmd, **kwargs) + except FileNotFoundError as exc: + # Windows CreateProcess omits the executable name from WinError 2. + if getattr(exc, "winerror", None) == 2 and exc.filename is None: + exc.filename = cmd[0] + raise + except OSError as exc: + if getattr(exc, "winerror", None) != _NOT_ENOUGH_QUOTA or time.monotonic() >= deadline: + raise + time.sleep(min(delay, max(0.0, deadline - time.monotonic()))) + delay = min(delay * 2, 0.1) # Keep resource bindings, specialization constants and stage interfaces used by the runtime linker. From 1860dc591b516e313c9b14fff0b4edf8a0e6ad74 Mon Sep 17 00:00:00 2001 From: budanga Date: Thu, 26 Nov 2026 17:39:12 -0300 Subject: [PATCH 2/3] rdna2spirv: measured 10 s spawn retry budget, and say when it runs out (COMPUTE-WORKER-SPAWN-QUOTA) Review follow-up. With every hardware thread busy at the workers' priority, the longest run of ERROR_NOT_ENOUGH_QUOTA refusals in the worker's job was 3.76 s, past the 2 s budget, so SPAWN_RETRY_SECONDS is now 10 s, with the measurement in a comment. When the budget runs out, the OSError gets a note with how many times the tool was refused and for how long, so the traceback shows that the retry ran and ran out. The comment says why the backoff is not shared with tools/replace_retry.py. The unit test checks the note, and that other errors get none. Co-Authored-By: Claude Opus 5.5 --- tests/test_rdna2spirv_spawn_quota.py | 5 +++++ tools/rdna2spirv.py | 15 ++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/tests/test_rdna2spirv_spawn_quota.py b/tests/test_rdna2spirv_spawn_quota.py index 7336fbc6bc..78e69ab593 100644 --- a/tests/test_rdna2spirv_spawn_quota.py +++ b/tests/test_rdna2spirv_spawn_quota.py @@ -73,6 +73,10 @@ def test_a_refusal_that_lasts_is_raised_once_the_time_is_up(self): self.assertGreater(run.call_count, 1) self.assertLessEqual(self.clock.now, rdna2spirv.SPAWN_RETRY_SECONDS) self.assertGreaterEqual(self.clock.now, rdna2spirv.SPAWN_RETRY_SECONDS - max(self.clock.sleeps)) + # The traceback says the retry ran out, not only what the first refusal said. + self.assertEqual(raised.exception.__notes__, + [f"spirv-as: refused {run.call_count} times in {self.clock.now:.1f} s " + f"(SPAWN_RETRY_SECONDS = {rdna2spirv.SPAWN_RETRY_SECONDS})"]) def test_other_errors_are_not_retried(self): for error in (win_error(5), OSError(errno.ENOMEM, "out of memory")): @@ -81,6 +85,7 @@ def test_other_errors_are_not_retried(self): with self.assertRaises(OSError) as raised: rdna2spirv._run_spirv_tool(["spirv-val"]) self.assertIs(raised.exception, error) + self.assertFalse(hasattr(error, "__notes__")) self.assertEqual(run.call_count, 1) self.assertEqual(self.clock.sleeps, []) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index bcfd0b0b5a..0326290229 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -19934,7 +19934,8 @@ def merge_shard_parts(out): return merged -SPAWN_RETRY_SECONDS = 2.0 +# The longest run of refusals measured was 3.8 s, with every hardware thread busy at the workers' priority. +SPAWN_RETRY_SECONDS = 10.0 _NOT_ENOUGH_QUOTA = 1816 # ERROR_NOT_ENOUGH_QUOTA @@ -19942,9 +19943,13 @@ def _run_spirv_tool(cmd, **kwargs): # A Windows job's active-process limit can still count a tool that has just exited, and CreateProcess then # refuses the next one with ERROR_NOT_ENOUGH_QUOTA: the compute worker's job allows itself and one tool # (scripts/compute_workers_win.py). The refused tool never started, so it is started again for a bounded time. - deadline = time.monotonic() + SPAWN_RETRY_SECONDS + # Same backoff as tools/replace_retry.py, kept apart because that one retries a rename, not a process start. + start = time.monotonic() + deadline = start + SPAWN_RETRY_SECONDS delay = 0.005 + attempts = 0 while True: + attempts += 1 try: return subprocess.run(cmd, **kwargs) except FileNotFoundError as exc: @@ -19953,7 +19958,11 @@ def _run_spirv_tool(cmd, **kwargs): exc.filename = cmd[0] raise except OSError as exc: - if getattr(exc, "winerror", None) != _NOT_ENOUGH_QUOTA or time.monotonic() >= deadline: + if getattr(exc, "winerror", None) != _NOT_ENOUGH_QUOTA: + raise + if time.monotonic() >= deadline: + exc.add_note(f"{cmd[0]}: refused {attempts} times in {time.monotonic() - start:.1f} s " + f"(SPAWN_RETRY_SECONDS = {SPAWN_RETRY_SECONDS})") raise time.sleep(min(delay, max(0.0, deadline - time.monotonic()))) delay = min(delay * 2, 0.1) From 913b9aa4dd8d30dc85f9def1ec96d34e81e9035e Mon Sep 17 00:00:00 2001 From: budanga Date: Sat, 28 Nov 2026 10:42:21 -0300 Subject: [PATCH 3/3] test_rdna2spirv_spawn_quota: run the job child on the base interpreter, check it is alone (COMPUTE-WORKER-SPAWN-QUOTA) Maintainer review: the Windows job test failed from a virtual environment. A venv's python.exe is a launcher that runs the base interpreter as a second process, so in the worker's two-process job the pair took both slots and every tool start was refused (refused 102 times in 10.0 s). The child is now started with sys._base_executable (sys.executable outside a venv). It reports its PID, and the test reads the job's process list: if the interpreter that starts the tools is not the job's only process, the test is skipped with that reason instead of failing. The check is made from the parent, since the venv launcher puts the real interpreter in a nested job of its own where it sees one process. Co-Authored-By: Claude Opus 5.5 --- tests/test_rdna2spirv_spawn_quota.py | 29 ++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/tests/test_rdna2spirv_spawn_quota.py b/tests/test_rdna2spirv_spawn_quota.py index 78e69ab593..469cec8642 100644 --- a/tests/test_rdna2spirv_spawn_quota.py +++ b/tests/test_rdna2spirv_spawn_quota.py @@ -7,6 +7,8 @@ then fails with winerror 1816. The unit tests fake that error; the Windows-only test starts real processes in such a job. No game data. """ +import ctypes +from ctypes import wintypes import errno import json import os @@ -100,15 +102,30 @@ def test_a_missing_tool_still_names_itself(self): CHILD = """ -import json, sys +import json, os, sys sys.path.insert(0, sys.argv[1]) import rdna2spirv +print(os.getpid(), flush=True) sys.stdin.readline() # in the job from here on for _ in range(int(sys.argv[2])): rdna2spirv._run_spirv_tool(["cmd", "/c", "rem"], capture_output=True, check=True) print(json.dumps("ok")) """ +# A venv's python.exe is a launcher that runs the base interpreter as a second process, and in the worker's job that +# pair takes both slots, so no tool could start. The base interpreter is what runs inside the job. +PYTHON = getattr(sys, "_base_executable", None) or sys.executable + + +class ProcessIds(ctypes.Structure): # JOBOBJECT_BASIC_PROCESS_ID_LIST, room for 8 (the worker job allows 2) + _fields_ = [("assigned", wintypes.DWORD), ("listed", wintypes.DWORD), ("ids", ctypes.c_size_t * 8)] + + +def job_processes(win, job): + ids = ProcessIds() + win.check(win.query_job(job, 3, ctypes.byref(ids), ctypes.sizeof(ids), None)) + return sorted(ids.ids[:ids.listed]) + @unittest.skipUnless(os.name == "nt", "Windows job objects") class TwoProcessJobTests(unittest.TestCase): @@ -117,12 +134,20 @@ def test_back_to_back_tools_in_the_worker_job(self): import compute_workers_win as win mib = 1024 with win.job(mib, True) as job: - p = subprocess.Popen([sys.executable, "-I", "-c", CHILD, str(ROOT / "tools"), "150"], + p = subprocess.Popen([PYTHON, "-I", "-c", CHILD, str(ROOT / "tools"), "150"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, creationflags=win.LOW) try: win.check(win.assign(job, int(p._handle))) win.verify(job, int(p._handle), mib, True) + ready = p.stdout.readline() + if not ready: # the child ended before it got going + self.fail(p.stderr.read()) + # The precondition: the interpreter that starts the tools is the job's one process, as the worker is. + processes = job_processes(win, job) + if processes != [int(ready)]: + self.skipTest(f"{PYTHON} is not the worker job's only process ({processes}, runner {int(ready)}): " + "a launcher in between leaves the tools no slot") out, err = p.communicate("go\n", timeout=300) finally: if p.poll() is None: