From baadbfaea3d968d451781ccd2ac5abf512c75049 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Tue, 24 Nov 2026 19:03:45 +0100 Subject: [PATCH 1/4] startup: translate shader requests in parallel and during a run gfx2hlsl.py --pending translated one request at a time. Requests are independent, so a scan with more than one pending request now runs them in parallel processes (X2W_TRANSLATE_JOBS, default the processor count, at most 61 on Windows). Results are byte-identical; 3,513 requests went from 44.0 s to 6.1 s on a 16-thread host. gfx2hlsl.py --watch [seconds] repeats that scan until stopped, and run.ps1 -Translate (with -Render) starts it beside the debugger and stops it when the debugger returns, so a pipeline created during a run is translated within seconds instead of on the next run. In watch mode a failure is not retried until its request is rewritten. Tests: startup_gfx2hlsl_watch (ready markers, failure retry rule, a live watcher, parallel equals serial) and startup_run_ps1 (-Translate starts the watcher on the cache and stops it; a mutant that leaves it running is detected). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 4 + docs/startup-runtime.md | 25 +++++- tests/startup_gfx2hlsl_watch_check.py | 105 ++++++++++++++++++++++++++ tests/startup_run_ps1_check.py | 51 ++++++++++++- tools/startup/gfx2hlsl.py | 39 +++++++++- tools/startup/run.ps1 | 19 ++++- 8 files changed, 233 insertions(+), 12 deletions(-) create mode 100644 tests/startup_gfx2hlsl_watch_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 7817ba089..97856455c 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -173,6 +173,7 @@ jobs: tests/startup_image_2d_array_check.py \ tests/startup_host_cpu_check.py \ tests/startup_gfx2hlsl_capture_check.py \ + tests/startup_gfx2hlsl_watch_check.py \ tests/startup_translator_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ tests/startup_triage_run_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 0e942257f..f3f0ae3c9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -148,6 +148,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_host_cpu_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_capture_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_watch_check.py ./out/pe-env/bin/python -B tests/startup_translator_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_smem_offset_check.py ./out/pe-env/bin/python -B tests/startup_flat_param_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index f53e8843e..66f285f60 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1643,6 +1643,10 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl refuses a binary32 or integer vector operation with a source too few or too many. add_test(NAME startup_gfx2hlsl_operand_count COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_operand_count_check.py") + # gfx2hlsl.py --watch consumes only ready requests and does not retry an unchanged failure. + add_test(NAME startup_gfx2hlsl_watch COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_watch_check.py") + set_tests_properties(startup_gfx2hlsl_watch PROPERTIES TIMEOUT 120) # VOP1/VOP2 sub-dword addressing (SDWA) in the translator (#1141), checked against the pixel AOT # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 7d736f480..d10660d81 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -249,7 +249,7 @@ Then: ```powershell .\tools\startup\run.ps1 -Exe \.exe -DataDir <package root> -LogDir out\startup\run1 ` - -Seconds 180 -Render -FakeUser -GpuMirror -ContinueAsserts 1000 -InputScript "4@70" + -Seconds 180 -Render -Translate -FakeUser -GpuMirror -ContinueAsserts 1000 -InputScript "4@70" ``` `run.ps1` copies the stand-ins next to the executable and starts `tools/startup/debug_launch.py`. @@ -276,6 +276,27 @@ It writes: | `<log>/events.txt` | module loads and every exception with its time | | `<log>/stderr.txt` | the stand-ins' logs (`x2w-d3d12`, `x2w-dstorage`, `x2w-xmem`, `x2w-runtime`, ...) | | `<log>/files.txt` | every file the process opened | +| `<log>/translate.txt` | with `-Translate`: one line per shader request translated during the run | + +### Translating shaders during a run + +With `-Render -Translate`, `run.ps1` starts `tools/startup/gfx2hlsl.py --watch <shader cache>` beside +the debugger and stops it when the debugger returns. The watcher repeats the `--pending` scan every +2 seconds (`--watch <dir> <seconds>` sets another interval), so a pipeline the title creates during +the run is translated within seconds, and the runtime picks it up on a later draw instead of on the +next run. The cache persists: a later run reads every published `<key>.txt` and translates only new +requests. In watch mode a request whose `<key>.fail` is newer than its ready marker is not retried +until the runtime rewrites the request; the one-shot `--pending` scan still retries every failure. +FXC is located as described for `X2W_SHADER_CACHE` under [Switches](#switches). A scan with more than +one pending request translates them in parallel processes, one per logical processor unless +`X2W_TRANSLATE_JOBS` sets the count; each request writes only its own files. On a 16-thread host, +3,513 requests (132 translated, 3,381 refused) took 44.0 s with one process and 6.1 s in parallel, +with byte-identical results. + +Check with `python3 -B tests/startup_gfx2hlsl_watch_check.py` (ctest `startup_gfx2hlsl_watch`): a +request without its ready marker is not consumed, a failure is not retried until its request is +rewritten, the watcher translates a request written while it runs, and four parallel workers print +the same results and write the same failures as one. `startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it. `run.ps1` prints the first five lines of `<log>.out` and exits with the debugger's exit code: 2 when the process could not be created, 0 when the debugger finished its report, whatever the process @@ -367,7 +388,7 @@ ctest --preset dev --no-tests=error -R '^startup_local_log(_guard_drop_control)? | `X2W_XMEM_GPU_MIRROR=1` | pairs a no-access graphics reservation with the read-write reservation of the same size made just before it, and maps every physical page into both (same section) | | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` | -| `X2W_SHADER_CACHE=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}` and, when needed, RTV variants `req_<key>.rtv`. Run `tools/startup/gfx2hlsl.py --pending <dir>` while the process is running. Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\<version>\x64`, else `PATH`. When none exists it writes `<key>.fail` naming `X2W_FXC` and no manifest; `X2W_FXC=` (empty) skips compilation and publishes the manifest alone. | +| `X2W_SHADER_CACHE=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}` and, when needed, RTV variants `req_<key>.rtv`. Run `tools/startup/gfx2hlsl.py --pending <dir>` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\<version>\x64`, else `PATH`. When none exists it writes `<key>.fail` naming `X2W_FXC` and no manifest; `X2W_FXC=` (empty) skips compilation and publishes the manifest alone. | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_D3D12_DUMP_SURFACE=<bmp>` | writes the last presented surface | | `X2W_DRAW_DUMP_FRAME=<n>`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py new file mode 100644 index 000000000..df4b1ac59 --- /dev/null +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -0,0 +1,105 @@ +"""gfx2hlsl.py pending scan and --watch on synthetic request files (pure Python, no Windows, no GPU). + +A request is consumed only once its ready marker (.a or .rtv) exists and it has no published .txt. +In watch mode a request whose .fail is newer than its marker is not retried until the marker is +rewritten; the one-shot --pending scan still retries it. The --watch process must translate a new +request while it runs and must not rewrite a failure on later passes. A --pending scan with four +parallel workers must print the same results and write the same failures as one worker. +""" +import os +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +import gfx2hlsl # noqa: E402 + +failures = [] + + +def expect(label, got, want): + if got != want: + failures.append('%s: got %s, want %s' % (label, got, want)) + + +def touch(path, data=b'', mtime=None): + path.write_bytes(data) + if mtime is not None: + os.utime(path, (mtime, mtime)) + + +def scan(directory, skip_failed): + return gfx2hlsl.pending_keys(str(directory), skip_failed) + + +def pending_run(directory, jobs): + env = dict(os.environ, X2W_TRANSLATE_JOBS=str(jobs)) + out = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), '--pending', str(directory)], + capture_output=True, text=True, timeout=120, env=env) + fails = {p.name: p.read_bytes() for p in Path(directory).glob('*.fail')} + return out.returncode, sorted(out.stdout.splitlines()), fails + + +with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + now = time.time() + # 1: complete request; 2: already published; 3: no ready marker yet (negative control); + # 4: failed after its marker was written; 5: marker rewritten after the failure; 6: RTV variant. + for key in (1, 2, 4, 5): + for ext in ('.b', '.root'): + touch(d / ('req_%016x%s' % (key, ext))) + touch(d / ('req_%016x.a' % 1)) + touch(d / ('req_%016x.a' % 2)) + touch(d / ('%016x.txt' % 2)) + touch(d / ('req_%016x.b' % 3)) + touch(d / ('req_%016x.root' % 3)) + touch(d / ('req_%016x.a' % 4), mtime=now - 10) + touch(d / ('%016x.fail' % 4), mtime=now - 5) + touch(d / ('%016x.fail' % 5), mtime=now - 10) + touch(d / ('req_%016x.a' % 5), mtime=now - 5) + touch(d / ('req_%016x.rtv' % 6)) + expect('watch pass', scan(d, True), [1, 5, 6]) + expect('one-shot pass', scan(d, False), [1, 4, 5, 6]) + +# Parallel --pending must give the same results as one worker: eight invalid RTV requests fail alike. +with tempfile.TemporaryDirectory() as one, tempfile.TemporaryDirectory() as many: + for d in (one, many): + for key in range(8): + touch(Path(d) / ('req_%016x.rtv' % (0x100 + key)), b'not an rtv request %d' % key) + serial, parallel = pending_run(one, 1), pending_run(many, 4) + expect('parallel --pending output and failures', parallel, serial) + expect('every request answered', len(serial[1]), 8) + +with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + watch = subprocess.Popen([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--watch', str(d), '0.1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + time.sleep(0.5) + # Written while the watcher runs; an invalid RTV request fails without a GPU or compiler. + touch(d / ('req_%016x.rtv' % 7), b'not an rtv request') + fail = d / ('%016x.fail' % 7) + deadline = time.time() + 20 + while not fail.exists() and time.time() < deadline and watch.poll() is None: + time.sleep(0.1) + expect('watcher wrote a failure for the new request', fail.exists(), True) + first = fail.stat().st_mtime_ns if fail.exists() else None + time.sleep(1.0) + expect('failure left unchanged by later passes', fail.stat().st_mtime_ns if fail.exists() else None, first) + expect('watcher still running', watch.poll(), None) + finally: + watch.kill() + out, err = watch.communicate(timeout=20) + lines = [line for line in out.splitlines() if line.strip()] + expect('watcher output lines', len(lines), 1) + if err.strip(): + failures.append('watcher stderr: %r' % err.strip()[-500:]) + +for item in failures: + print('FAIL', item) +if failures: + sys.exit(1) +print('startup_gfx2hlsl_watch_check passed') diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index fe2ec68db..65bc65e9b 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -25,13 +25,32 @@ STUB = """\ import json import sys +import time from pathlib import Path Path(__file__).with_name("argv.json").write_text(json.dumps(sys.argv[1:]), encoding="utf-8") +# Under -Translate, wait until the watcher stub has started so run.ps1 cannot stop it before then. +deadline = time.time() + 30 +while Path(__file__).with_name("translate.flag").exists() and not Path(__file__).with_name("watch.json").exists() \\ + and time.time() < deadline: + time.sleep(0.05) for n in range(1, 8): print("stub debugger line", n) sys.exit({code}) """ +# Stands in for tools/startup/gfx2hlsl.py under -Translate: records its arguments and process id, +# then waits to be stopped. +WATCH_STUB = """\ +import json +import os +import sys +import time +from pathlib import Path + +Path(__file__).with_name("watch.json").write_text(json.dumps([os.getpid()] + sys.argv[1:]), encoding="utf-8") +time.sleep(120) +""" +STOP = "Stop-Process -Id $translator.Id" CAPTURE = re.compile(r"\$(\w+)\s*=\s*\$LASTEXITCODE", re.I) EXIT = re.compile(r"exit\s+\$(\w+)", re.I) HEAD = 'Get-Content "$LogDir.out" -TotalCount 5' @@ -43,13 +62,20 @@ def decode(raw): return raw.decode("utf-16" if wide else "utf-8-sig", errors="replace") -def run_case(shell, script, code, work): +def alive(pid): + out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/FO", "CSV", "/NH"], + capture_output=True, text=True, errors="replace") + return f'"{pid}"' in out.stdout + + +def run_case(shell, script, code, work, translate=False): """Run one copy of the script on a stub that exits with `code`; return what is wrong.""" root = Path(tempfile.mkdtemp(dir=work)) startup = root / "tools" / "startup" startup.mkdir(parents=True) (startup / "run.ps1").write_bytes(script.encode("utf-8")) (startup / "debug_launch.py").write_text(STUB.format(code=code), encoding="utf-8") + (startup / "gfx2hlsl.py").write_text(WATCH_STUB, encoding="utf-8") (root / "bld").mkdir() for dll in DLLS: # the stand-ins the script copies next to the executable (root / "bld" / f"{dll}.dll").write_bytes(b"") @@ -64,6 +90,9 @@ def run_case(shell, script, code, work): command = [shell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(startup / "run.ps1"), "-Exe", str(exe), "-DataDir", str(data), "-LogDir", str(log), "-BuildDir", "bld", "-Seconds", "9", "-MemoryGiB", "3", "-ContinueAsserts", "4"] + if translate: + command += ["-Render", "-Translate", "-ShaderCache", "cache"] + (startup / "translate.flag").write_bytes(b"") try: out = subprocess.run(command, cwd=root, env=env, capture_output=True, text=True, errors="replace", timeout=120) @@ -87,6 +116,16 @@ def run_case(shell, script, code, work): got = json.loads(record.read_text(encoding="utf-8")) if record.is_file() else None if got != want: found.append(f"stub exit {code}: the debugger received {got}, expected {want}") + watch = startup / "watch.json" + if translate: + started = json.loads(watch.read_text(encoding="utf-8")) if watch.is_file() else None + if not started or started[1:] != ["--watch", str(root / "cache")]: + found.append(f"-Translate: the translator received {started}, expected --watch {root / 'cache'}") + elif alive(started[0]): + subprocess.run(["taskkill", "/PID", str(started[0]), "/F"], capture_output=True) + found.append("-Translate: the translator was still running after run.ps1 exited") + elif watch.is_file(): + found.append(f"stub exit {code}: the translator started without -Translate") return found @@ -95,8 +134,8 @@ def run_problems(shell, script, work, first_only): for code in (2, 0, 7): # 2 is the debugger's "CreateProcess failed"; 7 rules out a fixed code found += run_case(shell, script, code, work) if found and first_only: - break - return found + return found + return found + run_case(shell, script, 7, work, translate=True) def text_problems(script): @@ -171,7 +210,11 @@ def main(): failures += [f"{name}: {item}" for item in bad] if bad: continue - for label, mutant in mutants_of(script).items(): + mutants = mutants_of(script) + if shells: # only an executed run can see the translator outlive the script + stopless = "\n".join(line for line in script.splitlines() if STOP not in line) + "\n" + mutants["translator left running"] = None if stopless == script else stopless + for label, mutant in mutants.items(): if mutant is None or not check(mutant, True): failures.append(f"{name}: mutant '{label}' was not detected") for item in failures: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 605f580a3..5b712aa3f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -9,6 +9,7 @@ import re import struct import sys +import time sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) import disasm_rdna2 as D # noqa: E402 @@ -1481,7 +1482,36 @@ def main(): for ext, blob in (('.a', a), ('.b', b), ('.root', root)): open(os.path.join(out_dir, 'req_%016x%s' % (key, ext)), 'wb').write(blob) print('pso %x -> request %016x' % (w & 0xffffff, key)) - # translate every request that has no result yet + if sys.argv[1] == '--watch': + # --watch <dir> [seconds]: translate requests as a running title writes them, until stopped + interval = float(sys.argv[3]) if len(sys.argv) > 3 else 2.0 + while True: + translate_pending(out_dir, skip_failed=True) + time.sleep(interval) + translate_pending(out_dir) + + +def translate_pending(out_dir, skip_failed=False, jobs=None): + """Translate every request that has no result yet. The runtime writes .a and .rtv last, as ready markers. + + Requests are independent (each writes only its own <key>.* files), so several run in parallel + processes; X2W_TRANSLATE_JOBS (default: the processor count) sets how many. + """ + keys = pending_keys(out_dir, skip_failed) + jobs = jobs or int(os.environ.get('X2W_TRANSLATE_JOBS', 0)) or os.cpu_count() or 1 + if len(keys) < 2 or jobs < 2: + for key in keys: + print('%016x: %s' % (key, translate_request(out_dir, key)), flush=True) + return + from concurrent.futures import ProcessPoolExecutor + # ProcessPoolExecutor refuses more than 61 workers on Windows + with ProcessPoolExecutor(max_workers=min(jobs, len(keys), 61 if os.name == 'nt' else jobs)) as pool: + for key, result in zip(keys, pool.map(translate_request, [out_dir] * len(keys), keys, chunksize=8)): + print('%016x: %s' % (key, result), flush=True) + + +def pending_keys(out_dir, skip_failed): + keys = [] for name in sorted(os.listdir(out_dir)): m = re.fullmatch(r'req_([0-9a-f]{16})\.(?:a|rtv)', name) if not m: @@ -1489,7 +1519,12 @@ def main(): key = int(m.group(1), 16) if os.path.exists(os.path.join(out_dir, '%016x.txt' % key)): continue - print('%016x: %s' % (key, translate_request(out_dir, key))) + fail = os.path.join(out_dir, '%016x.fail' % key) + # A repeated pass retries a failure only once its request is rewritten. + if skip_failed and os.path.exists(fail) and os.path.getmtime(fail) >= os.path.getmtime(os.path.join(out_dir, name)): + continue + keys.append(key) + return keys if __name__ == '__main__': diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index 2b3832cdc..ffd67eca3 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -25,7 +25,8 @@ param( [switch]$Render, # draw through translated pipelines [switch]$FakeUser, # answer the user API for one local user [switch]$GpuMirror, # map CPU-view pages into the paired GPU-view reservation - [switch]$HostCpu # rewrite instructions the host processor lacks (X2W_HOST_CPU) + [switch]$HostCpu, # rewrite instructions the host processor lacks (X2W_HOST_CPU) + [switch]$Translate # with -Render: translate new shader requests during the run (gfx2hlsl.py --watch) ) $ErrorActionPreference = "Stop" $repo = Resolve-Path (Join-Path $PSScriptRoot "..\..") @@ -54,8 +55,18 @@ if ($Render) { New-Item -ItemType Directory -Force $LogDir | Out-Null $python = Join-Path $repo "out\pe-env\Scripts\python.exe" if (-not (Test-Path -LiteralPath $python)) { $python = "python" } -& $python -B (Join-Path $PSScriptRoot "debug_launch.py") $Exe $DataDir $LogDir --timeout $Seconds --memory-gib $MemoryGiB ` - --trace-files 1 --continue-asserts $ContinueAsserts *> "$LogDir.out" -$debuggerExit = $LASTEXITCODE +$translator = $null +if ($Translate -and $Render) { + $translator = Start-Process -FilePath $python -PassThru -NoNewWindow ` + -ArgumentList "-B", "`"$(Join-Path $PSScriptRoot 'gfx2hlsl.py')`"", "--watch", "`"$env:X2W_SHADER_CACHE`"" ` + -RedirectStandardOutput (Join-Path $LogDir "translate.txt") -RedirectStandardError (Join-Path $LogDir "translate_err.txt") +} +try { + & $python -B (Join-Path $PSScriptRoot "debug_launch.py") $Exe $DataDir $LogDir --timeout $Seconds --memory-gib $MemoryGiB ` + --trace-files 1 --continue-asserts $ContinueAsserts *> "$LogDir.out" + $debuggerExit = $LASTEXITCODE +} finally { + if ($translator) { Stop-Process -Id $translator.Id -Force -ErrorAction SilentlyContinue } +} Get-Content "$LogDir.out" -TotalCount 5 exit $debuggerExit From 7b4275cbc2c198117a8537746de0c2ac06dffaf2 Mon Sep 17 00:00:00 2001 From: NiiRoZz <simonin.remi25@gmail.com> Date: Tue, 24 Nov 2026 19:26:28 +0100 Subject: [PATCH 2/4] startup: address review findings in the shader translation watcher - The runtime writes each request once and never rewrites it, so the watcher's "retry once the request is rewritten" never happened. Its first pass now retries earlier failures once; later passes skip them. - run.ps1 stops the watcher with taskkill /T so its parallel workers and their fxc.exe do not outlive the run. -Translate without -Render warns. - Batches are sized to keep every worker busy (len // (jobs * 4)) instead of a fixed 8, which left most workers idle on small scans. - An unexpected translator error is written to <key>.fail instead of ending the scan and with it the watcher. - An empty or invalid X2W_TRANSLATE_JOBS falls back to the processor count; the Windows cap of 61 is applied in one place and documented. Tests cover each change, and a mutation of each is detected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/startup-runtime.md | 26 ++++++++----- tests/startup_gfx2hlsl_watch_check.py | 54 ++++++++++++++++++++++----- tests/startup_run_ps1_check.py | 22 +++++++---- tools/startup/gfx2hlsl.py | 40 ++++++++++++++++---- tools/startup/run.ps1 | 4 +- 5 files changed, 111 insertions(+), 35 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index d10660d81..b2c8f6114 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -281,22 +281,30 @@ It writes: ### Translating shaders during a run With `-Render -Translate`, `run.ps1` starts `tools/startup/gfx2hlsl.py --watch <shader cache>` beside -the debugger and stops it when the debugger returns. The watcher repeats the `--pending` scan every +the debugger and stops it, with its worker processes, when the debugger returns (`-Translate` +without `-Render` is ignored with a warning). The watcher repeats the `--pending` scan every 2 seconds (`--watch <dir> <seconds>` sets another interval), so a pipeline the title creates during the run is translated within seconds, and the runtime picks it up on a later draw instead of on the next run. The cache persists: a later run reads every published `<key>.txt` and translates only new -requests. In watch mode a request whose `<key>.fail` is newer than its ready marker is not retried -until the runtime rewrites the request; the one-shot `--pending` scan still retries every failure. +requests. The watcher's first pass retries every earlier failure once, so a translator update reaches +requests that failed in an earlier run; after that, a request whose `<key>.fail` is newer than its +ready marker is not retried during the run (the runtime writes each request once and never rewrites +it). The one-shot `--pending` scan retries every failure. An unexpected translator error is written +to `<key>.fail` as `translator error: ...` instead of stopping the scan. FXC is located as described for `X2W_SHADER_CACHE` under [Switches](#switches). A scan with more than -one pending request translates them in parallel processes, one per logical processor unless -`X2W_TRANSLATE_JOBS` sets the count; each request writes only its own files. On a 16-thread host, -3,513 requests (132 translated, 3,381 refused) took 44.0 s with one process and 6.1 s in parallel, +one pending request translates them in parallel processes, one per logical processor (at most 61 on +Windows, the `ProcessPoolExecutor` limit) unless `X2W_TRANSLATE_JOBS` sets the count; each request +writes only its own files. On a 16-thread host, +3,513 requests (132 translated, 3,381 refused) took 56.9 s with one process and 7.8 s in parallel, with byte-identical results. Check with `python3 -B tests/startup_gfx2hlsl_watch_check.py` (ctest `startup_gfx2hlsl_watch`): a -request without its ready marker is not consumed, a failure is not retried until its request is -rewritten, the watcher translates a request written while it runs, and four parallel workers print -the same results and write the same failures as one. `startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it. +request without its ready marker is not consumed, the watcher retries an earlier failure once and +then leaves failures alone, it translates a request written while it runs, four parallel workers +print the same results and write the same failures as one, an unexpected translator error becomes +`<key>.fail`, and an invalid `X2W_TRANSLATE_JOBS` falls back to the processor count. +`startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it together +with a child process. `run.ps1` prints the first five lines of `<log>.out` and exits with the debugger's exit code: 2 when the process could not be created, 0 when the debugger finished its report, whatever the process diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py index df4b1ac59..ff8da352d 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -1,10 +1,12 @@ """gfx2hlsl.py pending scan and --watch on synthetic request files (pure Python, no Windows, no GPU). A request is consumed only once its ready marker (.a or .rtv) exists and it has no published .txt. -In watch mode a request whose .fail is newer than its marker is not retried until the marker is -rewritten; the one-shot --pending scan still retries it. The --watch process must translate a new -request while it runs and must not rewrite a failure on later passes. A --pending scan with four -parallel workers must print the same results and write the same failures as one worker. +After the watcher's first pass, a request whose .fail is newer than its marker is not retried; the +first pass and the one-shot --pending scan retry it. The --watch process must retry an earlier +failure once, translate a new request while it runs and not rewrite a failure on later passes. A +--pending scan with four parallel workers must print the same results and write the same failures +as one worker, an unexpected translator error must become <key>.fail, and an invalid +X2W_TRANSLATE_JOBS must fall back to the processor count. """ import os import subprocess @@ -64,17 +66,49 @@ def pending_run(directory, jobs): expect('watch pass', scan(d, True), [1, 5, 6]) expect('one-shot pass', scan(d, False), [1, 4, 5, 6]) -# Parallel --pending must give the same results as one worker: eight invalid RTV requests fail alike. +# Parallel --pending must give the same results as one worker: sixteen invalid RTV requests fail +# alike; with four workers each batch holds one request, so the work is spread over the workers. with tempfile.TemporaryDirectory() as one, tempfile.TemporaryDirectory() as many: for d in (one, many): - for key in range(8): + for key in range(16): touch(Path(d) / ('req_%016x.rtv' % (0x100 + key)), b'not an rtv request %d' % key) serial, parallel = pending_run(one, 1), pending_run(many, 4) expect('parallel --pending output and failures', parallel, serial) - expect('every request answered', len(serial[1]), 8) + expect('every request answered', len(serial[1]), 16) +# An unexpected translator error becomes <key>.fail instead of ending the scan. with tempfile.TemporaryDirectory() as tmp: d = Path(tmp) + touch(d / ('req_%016x.rtv' % 9)) + real = gfx2hlsl.translate_request + gfx2hlsl.translate_request = lambda out_dir, key: 1 / 0 + try: + gfx2hlsl.translate_pending(str(d), jobs=1) + except ZeroDivisionError: + failures.append('a translator error escaped translate_pending') + finally: + gfx2hlsl.translate_request = real + fail = d / ('%016x.fail' % 9) + expect('translator error recorded', fail.read_text().startswith('translator error: ZeroDivisionError') if fail.exists() else None, True) + +# An invalid job count falls back to the processor count instead of raising. +saved = os.environ.get('X2W_TRANSLATE_JOBS') +for value in ('', 'abc', '-3'): + os.environ['X2W_TRANSLATE_JOBS'] = value + expect('X2W_TRANSLATE_JOBS=%r' % value, gfx2hlsl.translation_jobs() >= 1, True) +os.environ['X2W_TRANSLATE_JOBS'] = '2' +expect('X2W_TRANSLATE_JOBS=2', gfx2hlsl.translation_jobs(), 2) +if saved is None: + del os.environ['X2W_TRANSLATE_JOBS'] +else: + os.environ['X2W_TRANSLATE_JOBS'] = saved + +with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + # A failure from an earlier run, newer than its marker: the watcher's first pass retries it once. + now = time.time() + touch(d / ('req_%016x.rtv' % 8), b'not an rtv request either', mtime=now - 20) + touch(d / ('%016x.fail' % 8), b'stale reason\n', mtime=now - 10) watch = subprocess.Popen([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), '--watch', str(d), '0.1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) try: @@ -89,12 +123,14 @@ def pending_run(directory, jobs): first = fail.stat().st_mtime_ns if fail.exists() else None time.sleep(1.0) expect('failure left unchanged by later passes', fail.stat().st_mtime_ns if fail.exists() else None, first) + old = (d / ('%016x.fail' % 8)).read_text().strip() + expect('earlier failure retried once at start', old, 'invalid RTV variant request') expect('watcher still running', watch.poll(), None) finally: watch.kill() out, err = watch.communicate(timeout=20) - lines = [line for line in out.splitlines() if line.strip()] - expect('watcher output lines', len(lines), 1) + lines = sorted(line for line in out.splitlines() if line.strip()) + expect('watcher output (each request translated once)', [line[:16] for line in lines], ['%016x' % 7, '%016x' % 8]) if err.strip(): failures.append('watcher stderr: %r' % err.strip()[-500:]) diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index 65bc65e9b..904b79917 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -38,19 +38,21 @@ print("stub debugger line", n) sys.exit({code}) """ -# Stands in for tools/startup/gfx2hlsl.py under -Translate: records its arguments and process id, -# then waits to be stopped. +# Stands in for tools/startup/gfx2hlsl.py under -Translate: starts a child process, as the parallel +# workers are, records its own and the child's process ids and its arguments, then waits to be stopped. WATCH_STUB = """\ import json import os +import subprocess import sys import time from pathlib import Path -Path(__file__).with_name("watch.json").write_text(json.dumps([os.getpid()] + sys.argv[1:]), encoding="utf-8") +child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"]) +Path(__file__).with_name("watch.json").write_text(json.dumps([os.getpid(), child.pid] + sys.argv[1:]), encoding="utf-8") time.sleep(120) """ -STOP = "Stop-Process -Id $translator.Id" +STOP = "taskkill.exe /T /F /PID $translator.Id" CAPTURE = re.compile(r"\$(\w+)\s*=\s*\$LASTEXITCODE", re.I) EXIT = re.compile(r"exit\s+\$(\w+)", re.I) HEAD = 'Get-Content "$LogDir.out" -TotalCount 5' @@ -119,11 +121,13 @@ def run_case(shell, script, code, work, translate=False): watch = startup / "watch.json" if translate: started = json.loads(watch.read_text(encoding="utf-8")) if watch.is_file() else None - if not started or started[1:] != ["--watch", str(root / "cache")]: + if not started or started[2:] != ["--watch", str(root / "cache")]: found.append(f"-Translate: the translator received {started}, expected --watch {root / 'cache'}") - elif alive(started[0]): - subprocess.run(["taskkill", "/PID", str(started[0]), "/F"], capture_output=True) - found.append("-Translate: the translator was still running after run.ps1 exited") + else: + for pid, what in ((started[0], "translator"), (started[1], "translator's child process")): + if alive(pid): + subprocess.run(["taskkill", "/T", "/PID", str(pid), "/F"], capture_output=True) + found.append(f"-Translate: the {what} was still running after run.ps1 exited") elif watch.is_file(): found.append(f"stub exit {code}: the translator started without -Translate") return found @@ -214,6 +218,8 @@ def main(): if shells: # only an executed run can see the translator outlive the script stopless = "\n".join(line for line in script.splitlines() if STOP not in line) + "\n" mutants["translator left running"] = None if stopless == script else stopless + parent_only = script.replace(STOP, "Stop-Process -Id $translator.Id -Force") + mutants["translator's workers left running"] = None if parent_only == script else parent_only for label, mutant in mutants.items(): if mutant is None or not check(mutant, True): failures.append(f"{name}: mutant '{label}' was not detected") diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 5b712aa3f..9166b9fc6 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1485,28 +1485,52 @@ def main(): if sys.argv[1] == '--watch': # --watch <dir> [seconds]: translate requests as a running title writes them, until stopped interval = float(sys.argv[3]) if len(sys.argv) > 3 else 2.0 + # The first pass retries earlier failures once (the runtime never rewrites a request, so a + # translator fix would otherwise not reach them); later passes skip failures already written. + skip_failed = False while True: - translate_pending(out_dir, skip_failed=True) + translate_pending(out_dir, skip_failed=skip_failed) + skip_failed = True time.sleep(interval) translate_pending(out_dir) +def translate_one(out_dir, key): + """translate_request, with an unexpected translator error recorded as <key>.fail instead of raised.""" + try: + return translate_request(out_dir, key) + except Exception as error: # noqa: BLE001 - one bad request must not stop a scan or the watcher + reason = 'translator error: %s: %s' % (type(error).__name__, error) + with open(os.path.join(out_dir, '%016x.fail' % key), 'w') as fail: + fail.write(reason + '\n') + return reason + + +def translation_jobs(): + try: + jobs = int(os.environ.get('X2W_TRANSLATE_JOBS') or 0) + except ValueError: + jobs = 0 + jobs = jobs if jobs > 0 else os.cpu_count() or 1 + return min(jobs, 61) if os.name == 'nt' else jobs # ProcessPoolExecutor refuses more than 61 on Windows + + def translate_pending(out_dir, skip_failed=False, jobs=None): """Translate every request that has no result yet. The runtime writes .a and .rtv last, as ready markers. Requests are independent (each writes only its own <key>.* files), so several run in parallel - processes; X2W_TRANSLATE_JOBS (default: the processor count) sets how many. + processes; X2W_TRANSLATE_JOBS (default: the processor count, at most 61 on Windows) sets how many. """ keys = pending_keys(out_dir, skip_failed) - jobs = jobs or int(os.environ.get('X2W_TRANSLATE_JOBS', 0)) or os.cpu_count() or 1 - if len(keys) < 2 or jobs < 2: + jobs = min(jobs or translation_jobs(), len(keys)) + if jobs < 2: for key in keys: - print('%016x: %s' % (key, translate_request(out_dir, key)), flush=True) + print('%016x: %s' % (key, translate_one(out_dir, key)), flush=True) return from concurrent.futures import ProcessPoolExecutor - # ProcessPoolExecutor refuses more than 61 workers on Windows - with ProcessPoolExecutor(max_workers=min(jobs, len(keys), 61 if os.name == 'nt' else jobs)) as pool: - for key, result in zip(keys, pool.map(translate_request, [out_dir] * len(keys), keys, chunksize=8)): + chunk = max(1, len(keys) // (jobs * 4)) # small batches keep every worker busy + with ProcessPoolExecutor(max_workers=jobs) as pool: + for key, result in zip(keys, pool.map(translate_one, [out_dir] * len(keys), keys, chunksize=chunk)): print('%016x: %s' % (key, result), flush=True) diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index ffd67eca3..9375ad642 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -56,6 +56,7 @@ New-Item -ItemType Directory -Force $LogDir | Out-Null $python = Join-Path $repo "out\pe-env\Scripts\python.exe" if (-not (Test-Path -LiteralPath $python)) { $python = "python" } $translator = $null +if ($Translate -and -not $Render) { Write-Warning "-Translate needs -Render (no shader cache without it); ignored" } if ($Translate -and $Render) { $translator = Start-Process -FilePath $python -PassThru -NoNewWindow ` -ArgumentList "-B", "`"$(Join-Path $PSScriptRoot 'gfx2hlsl.py')`"", "--watch", "`"$env:X2W_SHADER_CACHE`"" ` @@ -66,7 +67,8 @@ try { --trace-files 1 --continue-asserts $ContinueAsserts *> "$LogDir.out" $debuggerExit = $LASTEXITCODE } finally { - if ($translator) { Stop-Process -Id $translator.Id -Force -ErrorAction SilentlyContinue } + # /T: the watcher's parallel workers (and their fxc.exe) are separate processes + if ($translator) { & taskkill.exe /T /F /PID $translator.Id 2>&1 | Out-Null } } Get-Content "$LogDir.out" -TotalCount 5 exit $debuggerExit From 95d59d2f7a6211708eca110e1d495638eaad9576 Mon Sep 17 00:00:00 2001 From: NiiRoZz <simonin.remi25@gmail.com> Date: Tue, 24 Nov 2026 19:34:18 +0100 Subject: [PATCH 3/4] startup: catch results reported against the wrong key in the parallel scan test The sixteen synthetic requests all failed with the same message, so a parallel scan that printed results against the wrong keys still matched the serial one. Each request is now an RTV variant naming a different missing base request, so every failure names its own base, and the test checks each printed result against its key. A mutant that reverses the key order is detected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- tests/startup_gfx2hlsl_watch_check.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py index ff8da352d..d06722cb4 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -9,6 +9,7 @@ X2W_TRANSLATE_JOBS must fall back to the processor count. """ import os +import re import subprocess import sys import tempfile @@ -41,8 +42,10 @@ def pending_run(directory, jobs): env = dict(os.environ, X2W_TRANSLATE_JOBS=str(jobs)) out = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), '--pending', str(directory)], capture_output=True, text=True, timeout=120, env=env) - fails = {p.name: p.read_bytes() for p in Path(directory).glob('*.fail')} - return out.returncode, sorted(out.stdout.splitlines()), fails + def local(text): # the temporary directory differs between runs; keep the file name only + return re.sub(r"'[^']*?(req_[0-9a-f]{16}\.\w+)'", r"'\1'", text) + fails = {p.name: local(p.read_text()) for p in Path(directory).glob('*.fail')} + return out.returncode, sorted(local(line) for line in out.stdout.splitlines()), fails with tempfile.TemporaryDirectory() as tmp: @@ -66,15 +69,22 @@ def pending_run(directory, jobs): expect('watch pass', scan(d, True), [1, 5, 6]) expect('one-shot pass', scan(d, False), [1, 4, 5, 6]) -# Parallel --pending must give the same results as one worker: sixteen invalid RTV requests fail -# alike; with four workers each batch holds one request, so the work is spread over the workers. +# Parallel --pending must give the same results as one worker. Sixteen RTV variants each name a +# different missing base request, so each failure names its own base and a result reported against +# the wrong key is visible. With four workers each batch holds one request. +bases = {} with tempfile.TemporaryDirectory() as one, tempfile.TemporaryDirectory() as many: - for d in (one, many): - for key in range(16): - touch(Path(d) / ('req_%016x.rtv' % (0x100 + key)), b'not an rtv request %d' % key) + for n in range(16): + request = b'rtv1 %d 28' % (0x7000 + n) + bases[gfx2hlsl.fnv(request)] = 0x7000 + n + for d in (one, many): + touch(Path(d) / ('req_%016x.rtv' % gfx2hlsl.fnv(request)), request) serial, parallel = pending_run(one, 1), pending_run(many, 4) expect('parallel --pending output and failures', parallel, serial) expect('every request answered', len(serial[1]), 16) + for line in parallel[1]: + key = int(line[:16], 16) + expect('result for %016x names its own base' % key, 'req_%016x.a' % bases.get(key, -1) in line, True) # An unexpected translator error becomes <key>.fail instead of ending the scan. with tempfile.TemporaryDirectory() as tmp: From d4bfa263ea8b7d3daf7398ed209dd9163d663e65 Mon Sep 17 00:00:00 2001 From: NiiRoZz <simonin.remi25@gmail.com> Date: Tue, 24 Nov 2026 21:07:30 +0100 Subject: [PATCH 4/4] startup: keep the shader watcher running when a worker is killed A pool worker killed from outside (for example out of memory) raised BrokenProcessPool out of pool.map and ended --watch for the rest of the run. watch_pass() reports such a pass as incomplete; the next pass retries its requests. Tested by injecting a BrokenProcessPool; a mutant that drops the catch is detected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/startup-runtime.md | 3 ++- tests/startup_gfx2hlsl_watch_check.py | 24 ++++++++++++++++++++++-- tools/startup/gfx2hlsl.py | 16 ++++++++++++++-- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 4e281e574..fd0f8567f 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -377,7 +377,8 @@ requests. The watcher's first pass retries every earlier failure once, so a tran requests that failed in an earlier run; after that, a request whose `<key>.fail` is newer than its ready marker is not retried during the run (the runtime writes each request once and never rewrites it). The one-shot `--pending` scan retries every failure. An unexpected translator error is written -to `<key>.fail` as `translator error: ...` instead of stopping the scan. +to `<key>.fail` as `translator error: ...` instead of stopping the scan. A worker killed from outside +(for example out of memory) ends that watcher pass only; its requests are retried on the next pass. FXC is located as described for `X2W_SHADER_CACHE` under [Switches](#switches). A scan with more than one pending request translates them in parallel processes, one per logical processor (at most 61 on Windows, the `ProcessPoolExecutor` limit) unless `X2W_TRANSLATE_JOBS` sets the count; each request diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py index d06722cb4..2aea5a772 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -5,8 +5,9 @@ first pass and the one-shot --pending scan retry it. The --watch process must retry an earlier failure once, translate a new request while it runs and not rewrite a failure on later passes. A --pending scan with four parallel workers must print the same results and write the same failures -as one worker, an unexpected translator error must become <key>.fail, and an invalid -X2W_TRANSLATE_JOBS must fall back to the processor count. +as one worker, an unexpected translator error must become <key>.fail, a broken process pool must +end one watcher pass and not the watcher, and an invalid X2W_TRANSLATE_JOBS must fall back to the +processor count. """ import os import re @@ -101,6 +102,25 @@ def local(text): # the temporary directory differs between runs; keep the file fail = d / ('%016x.fail' % 9) expect('translator error recorded', fail.read_text().startswith('translator error: ZeroDivisionError') if fail.exists() else None, True) +# A broken process pool (a worker killed from outside) ends one pass, not the watcher. +from concurrent.futures.process import BrokenProcessPool # noqa: E402 + + +def broken(out_dir, skip_failed=False): + raise BrokenProcessPool('a worker was terminated abruptly') + + +real = gfx2hlsl.translate_pending +gfx2hlsl.translate_pending = broken +try: + expect('broken pool: pass reported as incomplete', gfx2hlsl.watch_pass('.', True), False) +except BrokenProcessPool: + failures.append('a broken process pool escaped watch_pass') +finally: + gfx2hlsl.translate_pending = real +with tempfile.TemporaryDirectory() as tmp: + expect('normal pass reported as complete', gfx2hlsl.watch_pass(tmp, True), True) + # An invalid job count falls back to the processor count instead of raising. saved = os.environ.get('X2W_TRANSLATE_JOBS') for value in ('', 'abc', '-3'): diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index d8bc0b3d9..bf479eebc 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1632,12 +1632,24 @@ def main(): # translator fix would otherwise not reach them); later passes skip failures already written. skip_failed = False while True: - translate_pending(out_dir, skip_failed=skip_failed) - skip_failed = True + if watch_pass(out_dir, skip_failed): + skip_failed = True time.sleep(interval) translate_pending(out_dir) +def watch_pass(out_dir, skip_failed): + """One --watch pass. A worker killed from outside (out of memory) breaks the pool; the pass is + reported and its requests are retried on the next pass instead of ending the watcher.""" + from concurrent.futures.process import BrokenProcessPool + try: + translate_pending(out_dir, skip_failed=skip_failed) + return True + except BrokenProcessPool as error: + print('translation pass interrupted, retrying: %s' % error, file=sys.stderr, flush=True) + return False + + def translate_one(out_dir, key): """translate_request, with an unexpected translator error recorded as <key>.fail instead of raised.""" try: