diff --git a/README.md b/README.md index 0860ff63f3..475f2a1617 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ translates every shader again. A `disasm` folder that is a symlink is refused wh |---|---|---|---|---| | your package | `--game` | your copy of the game; only read, never written | as copied | yes, in place (`game_path.txt`) | | work | `--work` (default `\work`) | `shaders` (carved, disassembled, translated) and `assets` (exports) | about 30 GB + about 370 GB | only `shaders\spirv` (`shader_path.txt`) | -| port | `--out` (default `Documents\Leonida`) | `gta6rt.exe`, its DLL, the path files, the pipeline cache, `overlay` | small | yes | +| port | `--out` (default `Documents\Leonida`) | `gta6rt.exe`, its DLL, the path files, `pipeline_cache.d`, `overlay` | small | yes | The free-space check before a build counts the `--work` drive only, because that is where the large files go. Nothing in `\assets` is read by the game, so with a small SSD you can keep what the game loads on the SSD and @@ -221,11 +221,10 @@ upgrading. Stages: `check` always runs first; then `shaders`, `assets` and `runtime` run together when selected (they do not depend on each other). `pipelines` starts once the translated shaders are ready and, when this run includes runtime, -that stage has finished rebuilding `vk_pipeline_check`, so it can overlap the rest of assets; it creates every -translated shader on your GPU driver, reports any it has to skip, and saves a pipeline cache to `pipeline_cache.bin` -in `--out`, which also holds `gta6rt.exe` after the `runtime` stage. The runtime seeds its Vulkan pipeline cache -from the file beside the executable when its header matches the device and pipeline cache UUID. It falls back to -an empty cache if the file is missing, incompatible, or rejected by the driver. Shader translation is the longest +that stage has finished building `gta6rt.exe`, so it can overlap the rest of assets; it runs +`gta6rt.exe --precompile-pipelines` (under Wine off Windows) to fill the runtime's own compute pipeline journal in +`pipeline_cache.d` under `--out`, and reports any failures or crashing entries (writing `pipeline_crashes.json` if +any entry crashed the driver). Shader translation is the longest CPU step. It runs on `--jobs` processes (half the CPU threads by default). When shaders and assets share the machine, that budget is split between them and passed to `rpf9dump` as `--jobs`. A solo assets run still lets `rpf9dump` use every core. Progress lines include percent and a rough ETA for translation shards, asset steps, and overall stage @@ -250,8 +249,8 @@ cmake --build runtime/build/linux --parallel Pass the directory containing `index.json` and the translated SPIR-V files to `vk_pipeline_check`. -`make_game.py` runs on Linux too. The `pipelines` stage uses the `vk_pipeline_check` built above -(`runtime/build/linux`, or `runtime/build`), and builds it there itself before any other work if it is missing. +`make_game.py` runs on Linux too. Its `pipelines` stage runs `gta6rt.exe --precompile-pipelines` under Wine +(honouring `WINE`) to populate `/pipeline_cache.d`, rather than `vk_pipeline_check`. ### Running the loader on Linux diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index bd9f62ec04..b8255a0321 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2637,7 +2637,7 @@ Pipeline creation: - Request the subgroup size each shader was translated for (`requiredSubgroupSize` 64 or 32) where the device lists the stage in `requiredSubgroupSizeStages`, and say so in the log where it cannot (section 3.2, "Subgroup size"). - Pipeline caches: graphics and compute PSOs use one `VkPipelineCache` per device. On first use the runtime reads - the `pipelines` build stage's `pipeline_cache.bin` beside the executable if its Vulkan header matches the device + an offline `pipeline_cache.bin` beside the executable if its Vulkan header matches the device and pipeline-cache UUID. When the file is absent or incompatible, the runtime starts with an empty cache. The offline checker matches the runtime's layout and subgroup request for compute shaders with no descriptor bindings and the standard 144-byte push-constant range. @@ -2713,8 +2713,8 @@ Pipeline creation: folders can share one; the file names and the driver's checks keep a pipeline from one build from being taken for another's. `gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--all] [--smallest-first] [--limit N] - [--min-bytes N] [--max-bytes N] [--filter PART]... [--skip-listed] [--list]` fills the journal ahead of play, with - no game: it + [--min-bytes N] [--max-bytes N] [--filter PART]... [--skip-listed] [--list]` (which `make_game.py --stages + pipelines` runs) fills the journal ahead of play, with no game: it creates the Vulkan device as `--run` does (so the same environment gives the same journal names and driver keys: LEONIDA_SHADERS, LEONIDA_PIPELINE_CACHE_DIR, and LEONIDA_DEVICE_FAULT/LEONIDA_AFTERMATH, whose diagnostics config makes other pipelines) and builds every compute entry of the library through the dispatch path diff --git a/docs/linux.md b/docs/linux.md index c9ea03b84c..4e33724774 100644 --- a/docs/linux.md +++ b/docs/linux.md @@ -11,7 +11,7 @@ names; the build lists anything it can't find before it starts. | Piece | On Linux | How it is checked | |---|---|---| -| `make_game.py`: check, shaders, assets, pipelines | Native | CI (`stdlib-tests-linux`, `translator-tests`, `semantic-tests`) | +| `make_game.py`: check, shaders, assets | Native | CI (`stdlib-tests-linux`, `translator-tests`, `semantic-tests`) | | `Build.sh`, `Mods.sh` | Native (`/bin/sh`) | `tests/test_shell_launchers.py`, in the standard-library loop of `stdlib-tests-linux` | | Shader translator, its tests and the GPU test tools (`vk_harness`, `vk_pipeline_check`, ...) | Native, GCC or Clang | CI (`linux-gpu-tools`: GCC, tests on llvmpipe); Clang builds them too, but no CI job uses it yet | | `rpf9dump` (asset export) | Native, .NET 8 or newer | CI builds it on Windows only (the `check` job) | @@ -32,7 +32,7 @@ sudo apt install git python3 \ # llvm-21, spirv-tools the shaders stage: llvm-mc with the AMDGPU target, spirv-as and spirv-val # dotnet-sdk-10.0 the assets stage builds rpf9dump; Ubuntu 26.04 packages no .NET 8 SDK, and 10 builds the # net8.0 project through global.json's roll-forward -# cmake ... libvulkan-dev the pipelines stage builds vk_pipeline_check +# cmake ... libvulkan-dev optional: standalone native Vulkan test tools (vk_harness, vk_pipeline_check) # ffmpeg optional: XMA2 audio and --wav # zenity, python3-tk optional: the --pick folder dialog and the mod manager window ``` @@ -48,8 +48,8 @@ cd leonida ``` `./Build.sh` is `python3 -I make_game.py` with the newest Python 3.12+ it finds, so every `make_game.py` option in -the README works with it (`--game`, `--out`, `--work`, `--stages`, ...). Without the cross-build tools below, the -default stages leave `runtime` out (`check,shaders,assets,pipelines`). +the README works with it (`--game`, `--out`, `--work`, `--stages`, ...). Without the cross-build tools below (or +`--runtime-build`), the default stages leave `runtime` and `pipelines` out (`check,shaders,assets`). Notes: diff --git a/docs/linux_proton.md b/docs/linux_proton.md index 42487ed496..aea732d127 100644 --- a/docs/linux_proton.md +++ b/docs/linux_proton.md @@ -35,9 +35,10 @@ scripts/linux-boot/configure-worktree.sh # XWIN_DIR=, SDL3_ cmake --build /runtime/build/boot --target gta6rt -j6 ``` -`gta6rt_tls_host.dll` is built with the `gta6rt` target and must stay next to the executable. Unit tests are Windows -executables too and run under Wine (`scripts/run_wine_tests.py`, or directly with the same `wine` binary and a -prefix of their own: sharing the game's prefix with tests breaks its window). +`gta6rt_tls_host.dll` is built with the `gta6rt` target and must stay next to the executable. `make_game.py --stages pipelines` +runs `gta6rt.exe --precompile-pipelines` under Wine (honouring `WINE`) to fill `/pipeline_cache.d/`. Unit tests +are Windows executables too and run under Wine (`scripts/run_wine_tests.py`, or directly with the same `wine` binary +and a prefix of their own: sharing the game's prefix with tests breaks its window). ## Booting on Linux @@ -194,13 +195,14 @@ they were found. translator no longer does that for single-wave programs ([design.md](design.md), row "Wave64 emulation: single-wave barrier fallback"). The auto mode now leaves CPU devices out when a GPU is listed and names the device that decided. -3. **Fill the pipeline journal with the runtime itself.** `gta6rt --precompile-pipelines --threads 16`, under Wine, +3. **Fill the pipeline journal with the runtime itself.** `make_game.py --stages pipelines` (or + `gta6rt --precompile-pipelines --threads 16` directly), under Wine, with the environment of the game run (`LEONIDA_SHADERS`, `LEONIDA_PIPELINE_CACHE_DIR`, `LEONIDA_DEVICE_FAULT`; `--precompile-pipelines` in [d3d12_vulkan.md](d3d12_vulkan.md)). It built 3,693 compute pipelines; the next boot took 1,900 of them from the journal in 0.1 s of driver time, and the menus ran at 30 frames/s instead of under one. That run left out the programs `LEONIDA_SKIP_COMPUTE` named, which kept them out of the journal; the pre-compile now builds them too unless it is given `--skip-listed`. - The `pipeline_cache.bin` that `make_game.py`'s pipelines stage writes with `vk_pipeline_check` gave no hits: 0 of + The `pipeline_cache.bin` that `make_game.py`'s pipelines stage previously wrote with `vk_pipeline_check` gave no hits: 0 of 5,526 journal pipeline keys were in its 29,861 objects (9 shader binaries were identical, so the machine code matched and the keys did not). Each of three differences is enough for a miss on RADV: - **The set of shaders:** the runtime's warm-up builds the library's compute programs (`library/index.json`, diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md index 4d5be5e352..569cc6e5ce 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -42,8 +42,8 @@ Build with `make_game.py --stages shaders --compact-spirv` to run SPIRV-Tools lo | `--stats FILE` | Write the driver's per-shader statistics as CSV rows `name,stage,statistic,value`. Needs `VK_KHR_pipeline_executable_properties`; use it without `cache.bin`, because a cached pipeline may come without statistics. | | `--cache-feedback` | Group successful pipeline creations by `VkPipelineCreationFeedback`: cache hits, no hit reported, and unavailable. | | `--isolate` | POSIX only: check in child processes, `--isolate-batch N` modules at a time (default 256), so a crashing module is recorded as `MODULE CRASH` and the pass continues. Not compatible with `--stats`. | -| `--inflight-file F` | Keep the modules currently in the driver in F as `namephase` lines. It is rewritten by the watchdog and when a large module enters or leaves, and emptied at the end; `make_game.py`'s pipelines stage reads it. | -| `--skip-file F` | Do not compile modules named one per line in F; each is reported as `MODULE CRASH` and counted as a failed pipeline. `make_game.py` writes F after a crash so the next run checks the rest. | +| `--inflight-file F` | Keep the modules currently in the driver in F as `namephase` lines. It is rewritten by the watchdog and when a large module enters or leaves, and emptied at the end. | +| `--skip-file F` | Do not compile modules named one per line in F; each is reported as `MODULE CRASH` and counted as a failed pipeline. | `--isolate-child` is internal to the parent/child protocol and is not meant to be passed directly. A module with a missing partner stub is skipped; without `--isolate`, a driver crash ends the run. @@ -283,7 +283,7 @@ of the arenas (16 modules, 6 threads: 6.2 GB; with `MALLOC_ARENA_MAX=1`: 2.1 GB) - `--large-parallel N` caps how many large modules compile at once: `0` (default) by the budget, `1` alone with the other threads waiting (the behaviour before), `N` at most N without a budget. - `--inflight-file` names every module in flight when a large one enters or leaves the driver, so with several - large modules in flight it names all of them; the `pipelines` stage of `make_game.py` checks each alone. + large modules in flight it names all of them. ## Skipping huge modules @@ -344,39 +344,21 @@ the loader's `cl` line in `scripts/build_runtime.ps1`). The CTest `gta6rt_stack` with `dwStackSize` 0 both report 8 MB. Not covered: a thread the title creates with an explicit smaller size keeps that size. Which threads the game creates pipelines on is not known without its executable. -## Build-stage batches (BUILD-1030) - -`make_game.py` runs the pipelines stage in fresh checker processes over at most **500 index entries** each, on -Windows and POSIX. The ranges partition the same name-sorted index as `--start` / `--count`, including the final -short range. Each finished process saves to the same `pipeline_cache.bin`, and the next loads that checkpoint. -This bounds each invocation to a range that can be split further if concurrent heavy compiles exceed available -memory. A work folder with at most 500 entries keeps the single invocation. An older checker without the range -options keeps the older invocation; rebuild the runtime to get batching. - -If a batch crashes, its in-flight modules are checked alone in fresh processes. A module that reproducibly crashes -is recorded as failed, and the rest is checked. If none crashes alone, the entire failed range is retried in -smaller processes, down to one entry; healthy modules are not added to the crash list. An unrecoverable crash, -an interrupted check or a setup error stops the stage. A validation failure in one batch remains a failure even -when subsequent batches succeed; it does not prevent those later batches from being checked. - -The native checker returns 1 for initialization failures as well as validation failures. A completed shader pass -writes/clears its in-flight report even when validation fails. Exit 1 without a new report stops the stage instead -of repeating failed setup for the remaining batches; diagnostic probes use the same distinction. Each process -starts with a cleared report path, so an earlier process's report cannot hide an initialization failure. - -An abnormal diagnostic-probe exit confirms a module crash only when that probe's fresh in-flight report names -the selected module. A missing, empty or unrelated report makes the result inconclusive and stops the stage -without blaming that module. The native report is periodic for small modules, so even a real fast crash can -leave no evidence; this conservative fallback does not guess its cause or add an unconfirmed crash-list entry. - -The batch size limits the index range, **not total memory usage**. Concurrent heavy modules, loading a large -saved cache or compiling one large shader can still exceed a process's available memory; a range that -cannot complete even alone fails with a diagnostic rather than being counted as checked. - -`tests/test_make_game_pipeline_batches.py` runs the real build-stage orchestration against scripted child processes: -bounded coverage and cache checkpoints, collective memory-crash recovery, a genuinely crashing module, validation -failures, interruptions, setup failures, inconclusive probes and compatibility with older checkers. It needs no -game files or GPU. +## Relationship to `make_game.py --stages pipelines` + +`make_game.py`'s `pipelines` stage no longer drives `vk_pipeline_check`: it runs `gta6rt.exe --precompile-pipelines` +(directly on Windows, or under `WINE` / `wine` elsewhere) so the stage populates the runtime's own compute pipeline +journal in `/pipeline_cache.d` with matching device features and driver keys. If a driver crash kills `gta6rt` +mid-build, `make_game.py` retries up to `PIPELINE_CRASH_RETRIES` times so the runtime can move stale entries from +`pipeline_cache.d/requests/inflight.txt` to `requests/crashed.txt` and skip them, then writes `/pipeline_crashes.json`. +A crash is held against that module file on that device and driver: once the module is translated again or the +driver changes, the next run builds it again, and a build that returns clears it from the list. +`gta6rt --precompile-pipelines --all` tries every recorded entry again now. Exit 3 means another precompile holds +the journal folder (`requests/precompile.lock`). For tests, `LEONIDA_PRECOMPILE_CRASH_TEST=` ends the +precompile just before that entry's pipeline create, as a driver crash there would. + +`vk_pipeline_check` remains a standalone diagnostic tool (and CI test binary) for corpus-wide module/pipeline checks, +Mesa DRM-shim profiling, `--stats`, `--cache-feedback`, and `--isolate` crash bisection. ## Crash isolation (`--isolate`) diff --git a/docs/running.md b/docs/running.md index 3b71966d95..163e494e56 100644 --- a/docs/running.md +++ b/docs/running.md @@ -47,9 +47,10 @@ reasons behind each step: [linux_proton.md](linux_proton.md#amd-on-linux-what-go with SDL3 for the keyboard pad. - **Shaders:** `python -I make_game.py --stages shaders --wave64-emulate off --work --out `. The GPU runs wave64 natively; emulation is not needed. (`auto` picks the same here since llvmpipe no longer decides.) -- **Pipeline pre-compile:** `wine /gta6rt.exe --precompile-pipelines --threads 16` with the run's +- **Pipeline pre-compile:** `make_game.py --stages pipelines` (which runs `gta6rt.exe --precompile-pipelines` under + Wine off Windows), or `wine /gta6rt.exe --precompile-pipelines --threads 16` directly, with the run's `LEONIDA_SHADERS`, `LEONIDA_PIPELINE_CACHE_DIR` and `LEONIDA_DEVICE_FAULT`, before the first run. It built 3,693 - compute pipelines. Not `make_game.py --stages pipelines`: its cache never matches the runtime's driver keys. + compute pipelines. `make_game.py --stages pipelines` now runs this pre-compile. The pre-compile builds the programs `LEONIDA_SKIP_COMPUTE` names too (`--skip-listed` leaves them out) and ends with one line that counts what it built, what was journaled already and what it left out. - **Driver and OS:** `amdgpu.lockup_timeout=30000,60000,10000,10000` on the kernel command line (the default is diff --git a/make_game.py b/make_game.py index f1af5a172d..3c96e5a8f2 100644 --- a/make_game.py +++ b/make_game.py @@ -27,15 +27,14 @@ runtime build the loader (needs the game's executable to run, not to build). On Linux it is cross-built with clang-cl and an xwin SDK (docs/testing.md) and gta6rt.sh starts it with Wine; --runtime-build DIR takes a Windows build of runtime/ instead (the runtime-windows artifact of the Runtime workflow) - pipelines create every translated shader on your GPU's driver as a pipeline, report anything the driver - rejects or that has to be skipped, and save the pipeline cache next to the port (the runtime doesn't - load that cache yet) + pipelines precompile compute shaders into /pipeline_cache.d with gta6rt --precompile-pipelines, reporting + any failures or crashing entries shaders, assets and runtime do not depend on each other and run together after check. pipelines starts once the -translated shaders are ready and, when this run includes runtime, that stage has finished rebuilding -vk_pipeline_check (a checker already on disk is enough only when runtime is not selected), so it can overlap -the rest of assets. When shaders and assets share the machine, --jobs is split between them and passed to -rpf9dump; a solo assets run still lets rpf9dump use every core. +translated shaders are ready and, when this run includes runtime, that stage has finished building gta6rt.exe +(a gta6rt.exe already on disk is enough only when runtime is not selected), so it can overlap the rest of assets. +When shaders and assets share the machine, --jobs is split between them and passed to rpf9dump; a solo assets run +still lets rpf9dump use every core. Long steps log percent and a rough ETA (shader translation shards, asset exports, XMA decode, and overall weighted stage completion while they overlap). @@ -74,7 +73,6 @@ import leonida_tui # noqa: E402 from shader_stage_manifest import shader_stems # noqa: E402 from replace_retry import replace as replace_retry # noqa: E402 -from stale_build import newer_sources # noqa: E402 VERSIONS = os.path.join(ROOT, "game") STAGES = ["check", "shaders", "assets", "runtime", "pipelines"] @@ -127,8 +125,8 @@ def fmt_duration(seconds: float) -> str: return f"{hours}h {minutes:02d}m" -# Rough relative cost of each stage when run alone (docs: translate ~80 min, assets largest on disk, -# pipelines ~2.8 h wall). Used only for overall percent while stages overlap; not a schedule. +# Rough relative cost of each stage when run alone (translate ~80 min, assets largest on disk, +# compute pipeline journal precompile is a long stage). Used only for overall percent while stages overlap. STAGE_WEIGHTS = {"shaders": 40, "assets": 45, "runtime": 2, "pipelines": 55} @@ -900,19 +898,8 @@ def assets_bytes_on_disk(work: str) -> int: return total -def pipeline_check_prerequisite(runtime_selected: bool = False) -> str: - """Why the pipelines stage can't run yet. Kept here so preflight can fail before a long shader build; - pipelines() prints its own, more detailed message when the stage is reached. On Windows the runtime stage - only builds the checker when VULKAN_SDK is set (scripts/build_runtime.ps1).""" - if runtime_selected: - return ("VULKAN_SDK (the runtime stage builds vk_pipeline_check only when it is set, and the pipelines " - "stage needs that executable)") - return ("vk_pipeline_check (needed by the pipelines stage; run the runtime stage on Windows, or build it " - "with CMake as described in README.md)") - - def preflight(stages: list, work: str, wav: bool = False, runtime_build: str | None = None, *, - emulate: bool = False, keep_emulated: bool = False, + out: str | None = None, emulate: bool = False, keep_emulated: bool = False, fallbacks: tuple[str, ...] = (), jobs: int = 1) -> None: """Find every missing prerequisite before a long build starts, and list them all at once.""" if "runtime" in stages and runtime_build: @@ -940,17 +927,19 @@ def preflight(stages: list, work: str, wav: bool = False, runtime_build: str | N missing.append("Visual Studio 2022 with 'Desktop development with C++'") if os.name != "nt" and not runtime_build and any(s in WINDOWS_ONLY for s in stages): missing.extend(f"{s} (for the runtime stage, or pass --runtime-build)" for s in cross_build_missing()) - # The pipelines stage needs a checker the runtime stage builds (on Windows only with VULKAN_SDK set). + # The pipelines stage runs gta6rt.exe --precompile-pipelines (under Wine off Windows). # Without this check a build with shaders and pipelines spends hours before failing at the very end. - if "pipelines" in stages and not pipeline_check_exe(runtime_build): - if os.name != "nt": - if not shutil.which("cmake"): - missing.append("CMake 3.24 or newer, a C++20 compiler and the Vulkan headers, to build " - "vk_pipeline_check for the pipelines stage") - else: - runtime_building = "runtime" in stages and not runtime_build - if not runtime_building or not os.environ.get("VULKAN_SDK"): - missing.append(pipeline_check_prerequisite(runtime_building)) + if "pipelines" in stages: + if "runtime" not in stages: + if not runtime_exe(out, runtime_build): + missing.append("gta6rt.exe (needed by the pipelines stage; run the runtime stage or pass " + "--runtime-build)") + elif os.name == "nt" and not runtime_build and not os.environ.get("VULKAN_SDK"): + missing.append("VULKAN_SDK (the runtime stage builds gta6rt.exe with Vulkan support only when it is " + "set, and the pipelines stage needs it)") + if os.name != "nt" and not wine_available(): + missing.append(f"{wine_exe()} (Wine, needed to run gta6rt.exe in the pipelines stage; " + "install Wine or set WINE)") if missing: fail("Install these first, then run the build again:\n - " + "\n - ".join(dict.fromkeys(missing))) if os.name == "nt" and "runtime" in stages and not runtime_build and not os.environ.get("VULKAN_SDK"): @@ -991,16 +980,6 @@ def preflight(stages: list, work: str, wav: bool = False, runtime_build: str | N "Free some space or choose another drive with --work." + hint) if os.name != "nt" and not runtime_build and any(s in WINDOWS_ONLY for s in stages): cross_configure() - if "pipelines" in stages and os.name != "nt": - checker = pipeline_check_exe() - # A checker built before a pull is rebuilt too; cmake --build only recompiles what changed. Without CMake - # the pipelines stage says it is out of date and uses it. - if not checker or (stale_checker(checker) and shutil.which("cmake")): - build_pipeline_check(jobs) - if not pipeline_check_exe(): - fail("vk_pipeline_check built, but not as runtime/build/linux/vk_pipeline_check (a multi-config " - "generator puts it in a subfolder): unset CMAKE_GENERATOR if it names one, delete " - "runtime/build/linux and run the build again.") if "assets" in stages: ensure_submodule() @@ -2594,7 +2573,7 @@ def cross_configure() -> str: cmake_configure(build, "--toolchain", os.path.join(ROOT, "runtime", "cmake", "clang-cl-xwin.cmake"), f"-DXWIN_DIR={xwin}", *tools, hint="CMake's error above says what the cross-build lacks " "(docs/testing.md, \"The Windows runtime on Linux\"). Or pass --runtime-build, or drop " - "runtime from --stages (the default without it: check,shaders,assets,pipelines).") + "runtime and pipelines from --stages (the default without them: check,shaders,assets).") return build @@ -2606,15 +2585,6 @@ def cross_build_runtime(jobs: int) -> str: return build -def build_pipeline_check(jobs: int) -> None: - build = os.path.join(ROOT, "runtime", "build", "linux") - log("pipelines: building vk_pipeline_check") - cmake_configure(build) - cmake_build(build, ["vk_pipeline_check"], jobs, - "It needs a C++20 compiler and the Vulkan headers (your distribution's Vulkan headers package, " - "or VULKAN_SDK); the CMake output above says which is missing.") - - def runtime(game: str, out: str, v: dict, runtime_build: str | None = None, jobs: int = 1, *, work: str | None = None) -> None: destinations = [*RUNTIME_FILES, "game_path.txt"] @@ -2708,28 +2678,58 @@ def positive_int(text: str) -> int: return value -def pipeline_check_exe(runtime_build: str | None = None) -> str | None: - """Find the checker for this host, using a supplied Windows build before the local Windows build.""" +def wine_exe() -> str: + """Wine command for running Windows binaries off Windows (honours WINE).""" + return os.environ.get("WINE") or "wine" + + +def wine_available() -> bool: + cmd = wine_exe() + return bool(cmd and (os.path.isfile(cmd) or shutil.which(cmd))) + + +def wine_path(path: str) -> str: + """Absolute path formatted for a Windows process: native on Windows, Z:\\... under Wine.""" + full = os.path.abspath(path) + if os.name == "nt": + return full + return "Z:" + full.replace("/", "\\") + + +def _host_cache_dir(out: str, env_value: str | None) -> str: + if not env_value: + return out + if os.name != "nt" and len(env_value) >= 2 and env_value[0].upper() == "Z" and env_value[1] == ":": + return env_value[2:].replace("\\", "/") or "/" + return env_value + + +def runtime_exe(out: str | None = None, runtime_build: str | None = None) -> str | None: + """Find gta6rt.exe in , then --runtime-build, then this checkout's default build folder.""" build = os.path.join(ROOT, "runtime", "build") - windows = os.name == "nt" - if windows: - windows_builds = (runtime_build, build) if runtime_build else (build,) - found = [os.path.join(d, "vk_pipeline_check.exe") for d in windows_builds] - else: - found = [os.path.join(build, "linux", "vk_pipeline_check"), os.path.join(build, "vk_pipeline_check")] - return next((p for p in found if os.path.isfile(p) and (windows or os.access(p, os.X_OK))), None) + default_dir = build if os.name == "nt" else cross_build_dir() + dirs = [d for d in (out, runtime_build, default_dir) if d] + return next((p for d in dirs if os.path.isfile(p := os.path.join(d, "gta6rt.exe"))), None) -def stale_checker(exe: str) -> list: - """The sources of vk_pipeline_check changed after `exe` was built, when `exe` is in this checkout's runtime/build. - A checker from elsewhere (--runtime-build) isn't compared: its time stamp says nothing about these sources.""" - build = os.path.abspath(os.path.join(ROOT, "runtime", "build")) - try: - if os.path.commonpath([build, os.path.abspath(exe)]) != build: - return [] - except ValueError: # another drive - return [] - return newer_sources(exe, ROOT, "vk_pipeline_check") +def precompile_command(exe: str, jobs: int) -> list[str]: + """Command line to run gta6rt --precompile-pipelines directly on Windows or under Wine elsewhere.""" + base = [exe, "--precompile-pipelines", "--threads", str(jobs)] + return base if os.name == "nt" else [wine_exe(), *base] + + +def precompile_env(spirv: str, out: str) -> dict[str, str]: + """Child environment for gta6rt --precompile-pipelines, preserving user-set shader/cache paths.""" + env = dict(os.environ) + if env.get("LEONIDA_SHADERS"): + log(f"pipelines: using LEONIDA_SHADERS from environment: {env['LEONIDA_SHADERS']}") + else: + env["LEONIDA_SHADERS"] = wine_path(spirv) + if env.get("LEONIDA_PIPELINE_CACHE_DIR"): + log(f"pipelines: using LEONIDA_PIPELINE_CACHE_DIR from environment: {env['LEONIDA_PIPELINE_CACHE_DIR']}") + else: + env["LEONIDA_PIPELINE_CACHE_DIR"] = wine_path(out) + return env def require_translated_shaders(work: str) -> str: @@ -2745,127 +2745,138 @@ def require_translated_shaders(work: str) -> str: "run the shaders stage again.") if not translated: # A build from before the shaders stage refused an empty merge can carry this marker. - fail(f"The translated shader index {index} is empty, so there is nothing to check. Run the shaders stage again.") + fail(f"The translated shader index {index} is empty, so there is nothing to precompile. Run the shaders stage again.") return spirv +PRECOMPILE_PROGRESS_RE = re.compile(r"^\[precompile\]\s+(\d+)/(\d+)\s+") + + +def read_crashed_names(cache_root: str) -> "list[str]": + """Entry names the runtime recorded in /pipeline_cache.d/requests/crashed.txt.""" + path = os.path.join(cache_root, "pipeline_cache.d", "requests", "crashed.txt") + try: + with open(path, encoding="utf-8", errors="replace") as f: + # " " per line (runtime/src/precompile_inflight.h); the key says which build crashed. + return list(dict.fromkeys(line.strip().rsplit(" ", 1)[0] for line in f if line.strip())) + except OSError: + return [] + + +def _run_precompile(cmd: list[str], env: dict[str, str], progress_box: list) -> int: + """Run one gta6rt --precompile-pipelines process, streaming output and driving Progress/StageBoard.""" + log(" " + " ".join(os.path.basename(str(a)) if i == 0 else str(a) for i, a in enumerate(cmd))) + board = leonida_tui.current_board() + kw: dict = { + "stdout": subprocess.PIPE, + "stderr": subprocess.STDOUT, + "text": True, + "encoding": "utf-8", + "errors": "replace", + "env": env, + } + if os.name == "nt" and board is not None: + kw["creationflags"] = subprocess.CREATE_NO_WINDOW + try: + proc = subprocess.Popen([str(a) for a in cmd], **kw) + except OSError as error: + fail(f"pipelines: could not start {cmd[0]}: {error.strerror or error}") + leonida_tui.register_live_process(proc) + try: + stream = proc.stdout + if stream is not None: + while True: + if board is not None and getattr(board, "_stop", None) is not None and board._stop.is_set(): + leonida_tui.kill_live_processes() + break + raw = stream.readline() + if raw == "": + break + for piece in raw.replace("\r", "\n").split("\n"): + line = piece.strip() + if not line: + continue + m = PRECOMPILE_PROGRESS_RE.match(line) + if m: + done, total = int(m.group(1)), int(m.group(2)) + prog = progress_box[0] + if prog is None or prog.total != total: + prog = Progress("pipelines", total, every_s=5.0) + progress_box[0] = prog + prog.set(done) + if board is not None and total > 0: + board.set_summary(f"pipelines: {done}/{total} ({100 * done // total}%)") + else: + log(line) + try: + stream.close() + except OSError: + pass + return proc.wait() + except BaseException: + _stop_procs([proc]) + raise + finally: + leonida_tui.unregister_live_process(proc) + + def pipelines(work: str, out: str, jobs: "int | None" = None, *, runtime_build: str | None = None) -> None: - exe = pipeline_check_exe(runtime_build) - if not exe and os.name == "nt": - fail("vk_pipeline_check.exe wasn't built: run the runtime stage with the Vulkan SDK installed.") + exe = runtime_exe(out, runtime_build) if not exe: - fail("vk_pipeline_check wasn't built. With CMake 3.24+, a C++20 compiler and the Vulkan headers and " - "loader installed, run: cmake -S runtime -B runtime/build/linux && " - "cmake --build runtime/build/linux --parallel") - newer = stale_checker(exe) - if newer: - rebuild = ("run the runtime stage with VULKAN_SDK set" if os.name == "nt" else - "cmake --build runtime/build/linux --target vk_pipeline_check") - more = f" and {len(newer) - 3} more" if len(newer) > 3 else "" - log(f"pipelines: WARNING: {exe} is older than {', '.join(newer[:3])}{more}, so it is not this checkout's " - f"checker; to rebuild it, {rebuild}") + hint = ("run the runtime stage with the Vulkan SDK installed, or pass --runtime-build." + if os.name == "nt" else + "run the runtime stage (clang-cl + xwin) or pass --runtime-build.") + fail(f"gta6rt.exe was not found: {hint}") spirv = require_translated_shaders(work) - log("pipelines: creating every shader module and pipeline (compute and graphics) on this GPU") + threads = jobs if jobs else max(1, (os.cpu_count() or 2) // 2) + cmd = precompile_command(exe, threads) + if os.name != "nt" and cmd[0] == wine_exe() and not wine_available(): + fail(f"'{wine_exe()}' was not found: install Wine or set WINE to run gta6rt.exe in the pipelines stage.") os.makedirs(out, exist_ok=True) - cache = os.path.join(out, "pipeline_cache.bin") - inflight = os.path.join(out, "pipeline_inflight.txt") - skip = os.path.join(out, "pipeline_crashes.txt") report = os.path.join(out, "pipeline_crashes.json") - drop(inflight, skip, report) # every module gets a fresh chance on each run (a new translator may have fixed it) - # --jobs: make_game.py's own; without it vk_pipeline_check uses half the hardware threads whatever was asked - jobs_args = ["--jobs", str(jobs)] if jobs else [] - base = [exe, spirv, cache, *jobs_args] - - def seed_bvh() -> None: - bvh = os.path.join(spirv, "bvh") - if not os.path.isfile(os.path.join(bvh, "index.json")): - return - log("pipelines: creating XboxBvhBuilder compute pipelines") - run([exe, bvh, cache, *jobs_args]) - - if not checker_supports(exe, "--inflight-file", "--skip-file"): - # An older build takes any argument it doesn't know as the cache path, so it would write the cache into - # pipeline_inflight.txt and exit 0. Run it as before: a module that kills it stops the stage. - log("pipelines: this vk_pipeline_check has no --inflight-file; rebuild the runtime stage so a module that " - "crashes the driver is skipped instead of stopping the stage") - run(base) - seed_bvh() - log("pipelines: done") - return - base += ["--inflight-file", inflight] - # Bound each checker invocation to a range that recovery can split further when concurrent heavy compiles - # exceed available memory, without starting the entire corpus again (BUILD-1030). - names = pipeline_names(spirv) if checker_supports(exe, "--start", "--count") else [] - crashed: "list[str]" = [] - - def check_range(start: int = 0, count: "int | None" = None) -> int: - selection = ["--start", str(start), "--count", str(count)] if count is not None else [] - allowed = set(names[start:start + count]) if count is not None else None - for _ in range(PIPELINE_CRASH_RETRIES + 1): - drop(inflight) # a crash during setup must not inherit another process's in-flight module names - code = run(base + selection + (["--skip-file", skip] if crashed else []), check=False) - # Native setup failures also return 1. A finished pass writes/clears this report even when shaders - # fail validation; setup failures return before writing it. Do not repeat setup for every batch. - if code == 1 and not os.path.isfile(inflight): - fail("vk_pipeline_check exited with 1 before writing its work report; check Vulkan initialization " - "and report-file access in the output above") - if code in (0, 1, 2) or interrupted(code): - return code - suspects = list(dict.fromkeys(n for n in read_names(inflight) - if n not in crashed and (allowed is None or n in allowed))) - # Even the last in-flight module can be innocent after other heavy compiles in the batch. - if count is not None or len(suspects) > 1: - suspects = [n for n in suspects if crashes_alone(exe, spirv, cache, n, inflight)] - if not suspects: - if count is not None and count > 1: - # All suspects survived in fresh processes: do not blacklist them. Re-check the entire failed - # range in smaller processes; completed earlier batches retain their cache checkpoints. - log(f"pipelines: shaders {start + 1}-{start + count} exited with {exit_label(code)} without " - "a reproducible module crash; retrying this range in smaller batches") - half = count // 2 - first = check_range(start, half) - if first == 2 or interrupted(first): - return first - second = check_range(start + half, count - half) - return second or first - # The give-up path is exactly when a durable record matters: a module was named earlier, - # but the driver now aborts before it can name another one. fail() raises, so write first. - if crashed: - record_crashes(out, spirv, crashed) - fail(f"vk_pipeline_check exited with {exit_label(code)} while no module could be named as the cause; " - "the checker could not finish even this range in a fresh process; check available memory " - "and report it if it keeps happening") - for n in suspects: - log(f"pipelines: {n} took vk_pipeline_check down ({exit_label(code)}); checking the rest without it") - crashed.extend(suspects) - with open(skip, "w", encoding="utf-8", newline="\n") as f: - f.write("".join(n + "\n" for n in crashed)) - if crashed: - record_crashes(out, spirv, crashed) - fail(f"vk_pipeline_check still crashed after {PIPELINE_CRASH_RETRIES} retries; modules that took it down: " - + ", ".join(crashed)) - + drop(report) + env = precompile_env(spirv, out) + cache_root = _host_cache_dir(out, os.environ.get("LEONIDA_PIPELINE_CACHE_DIR")) + log("pipelines: precompiling compute shaders into pipeline_cache.d with gta6rt") + + def collect_crashes() -> "list[str]": + names = read_crashed_names(cache_root) + if not names and cache_root != out: + names = read_crashed_names(out) + if names: + log(f"pipelines: WARNING: {len(names)} compute entry(ies) crashed the driver and were skipped " + f"(recorded in pipeline_crashes.json): {', '.join(names)}. The stage tries one again once it is " + "translated again or the driver changes; gta6rt --precompile-pipelines --all tries them all now") + record_crashes(out, spirv, names) + return names + + progress_box: list = [None] code = 0 - ranges = [(s, min(PIPELINE_BATCH_SIZE, len(names) - s)) - for s in range(0, len(names), PIPELINE_BATCH_SIZE)] if names else [(0, None)] - for start, count in ranges: - if count is not None: - log(f"pipelines: checking shaders {start + 1}-{start + count} of {len(names)} in a fresh process") - result = check_range(start, count) - if result: - code = result # a later successful batch must not erase an earlier validation failure - if result == 2 or interrupted(result): + for attempt in range(PIPELINE_CRASH_RETRIES + 1): + code = _run_precompile(cmd, env, progress_box) + if code == 0: + break + if code == 2: break - if crashed and not code: - code = 1 - if crashed: - record_crashes(out, spirv, crashed) - drop(inflight) - if code != 0: - why = f"; {len(crashed)} module(s) took the driver down and were counted as failed (with their SPIR-V " \ - f"hashes in pipeline_crashes.json): " + ", ".join(crashed) if crashed else "" - fail(f"vk_pipeline_check exited with {exit_label(code)}{why}") - seed_bvh() + if code == 1: + fail("pipelines: gta6rt could not open the Vulkan device or shader library (exit 1); " + "see the output above") + if code == 3: + fail("pipelines: another gta6rt --precompile-pipelines is using this pipeline journal (exit 3); " + "let it finish or stop it, then run the stage again") + if interrupted(code): + fail(f"pipelines: gta6rt interrupted ({exit_label(code)})") + if attempt < PIPELINE_CRASH_RETRIES: + log(f"pipelines: gta6rt crashed ({exit_label(code)}); retrying " + f"({attempt + 1}/{PIPELINE_CRASH_RETRIES}) so the runtime skips the in-flight entry") + else: + crashed = collect_crashes() + why = f"; crashed entries: {', '.join(crashed)}" if crashed else "" + fail(f"pipelines: gta6rt still crashed after {PIPELINE_CRASH_RETRIES} retries " + f"(last exit {exit_label(code)}){why}") + + if not collect_crashes() and code == 2: + log("pipelines: WARNING: some compute pipelines failed to build (exit 2); see the summary above") log("pipelines: done") @@ -2873,11 +2884,16 @@ def record_crashes(out: str, spirv: str, crashed: "list[str]") -> None: """pipeline_crashes.json: name and SHA-256 of each module that took the driver down, so a report names the exact translation without attaching the shader. OSError (a missing .spv) leaves that module's hash null.""" def digest(name: str) -> "str | None": - try: - with open(os.path.join(spirv, name + ".spv"), "rb") as f: - return hashlib.sha256(f.read()).hexdigest() - except OSError: - return None + candidates = [os.path.join(spirv, name + ".spv")] + [ + os.path.join(spirv, sub, name + ".spv") for sub in ("library", "bvh", "fspx", "fspx_compute", "exe") + ] + for path in candidates: + try: + with open(path, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + except OSError: + continue + return None doc = {"modules": [{"name": n, "spv_sha256": digest(n)} for n in crashed]} try: with open(os.path.join(out, "pipeline_crashes.json"), "w", encoding="utf-8", newline="\n") as f: @@ -2885,14 +2901,13 @@ def digest(name: str) -> "str | None": f.write("\n") except OSError as error: # The durable record is best-effort. A report path that cannot be written must not - # replace the checker diagnostic that names the modules which took the driver down. + # replace the diagnostic that names the modules which took the driver down. log(f"pipelines: cannot write pipeline_crashes.json: {error.strerror or error}") -# How many times the pipelines stage restarts vk_pipeline_check after a module takes it down (each costs at most the -# 10 minutes since the last cache checkpoint, plus loading the cache). Looked up when pipelines() runs. +# How many times the pipelines stage restarts gta6rt after a module takes it down; the next start moves any stale +# in-flight entry to requests/crashed.txt and skips it. PIPELINE_CRASH_RETRIES = 5 -PIPELINE_BATCH_SIZE = 500 # fresh compiler process and cache checkpoint after at most this many index entries def interrupted(code: int) -> bool: @@ -2907,67 +2922,6 @@ def exit_label(code: int) -> str: return f"{code} ({code:#010x})" if code > 255 else str(code) -def checker_supports(exe: str, *options: str) -> bool: - """Whether this vk_pipeline_check build knows the options: run without arguments, it prints its usage (and exits - 2) before touching Vulkan. Builds before --inflight-file don't reject unknown arguments, so asking is the only way - to tell.""" - try: - r = subprocess.run([exe], capture_output=True, text=True, timeout=60) - except (OSError, subprocess.SubprocessError): - return False - usage = (r.stdout or "") + (r.stderr or "") - return all(o in usage for o in options) - - -def read_names(path: str) -> "list[str]": - """The module names in vk_pipeline_check's --inflight-file ("namephase" lines).""" - try: - with open(path, encoding="utf-8", errors="replace") as f: - return [n for n in (line.split("\t", 1)[0].strip() for line in f) if n] - except OSError: - return [] - - -def pipeline_names(spirv: str) -> "list[str]": - """The checker's name-sorted index (byte order, as its std::map); ranges and diagnostic probes share it.""" - path = os.path.join(spirv, "index.json") - try: - with open(path, encoding="utf-8-sig") as f: - index = json.load(f) - except (OSError, ValueError) as e: - fail(f"pipelines: cannot read {path}: {getattr(e, 'strerror', None) or e}") - if not isinstance(index, dict): - fail(f"pipelines: {path} must contain a JSON object") - return sorted(index, key=lambda n: n.encode("utf-8")) - - -def crashes_alone(exe: str, spirv: str, cache: str, name: str, inflight: str | None = None) -> bool: - """Confirm a crash only when this probe's fresh report names the selected module as in flight.""" - names = pipeline_names(spirv) - if name not in names: - return False - args = [exe, spirv, cache, "--jobs", "1", "--start", str(names.index(name)), "--count", "1"] - if inflight: - drop(inflight) - args += ["--inflight-file", inflight] - code = run(args, check=False) - if code == 1 and inflight and not os.path.isfile(inflight): - fail(f"pipelines: checking {name} alone exited with 1 before writing its work report; " - "check Vulkan initialization and report-file access in the output above") - if interrupted(code) or code == 2: - fail(f"pipelines: checking {name} alone stopped with {exit_label(code)}") - if code in (0, 1): - return False - # The process may have died during setup or after finishing, rather than inside this module. The native - # report is periodic for small modules, so a fast real crash can also leave no evidence: stop conservatively - # in that case instead of blaming an innocent module or retrying more ranges with an unreliable checker. - if not inflight or name not in read_names(inflight): - fail(f"pipelines: checking {name} alone exited with {exit_label(code)} without a fresh report naming it " - "as in flight; the diagnostic result is inconclusive, so no crash is attributed to this module. " - "Check the checker output, available memory and report-file access before retrying") - return True - - def path_is_within(path: str, directory: str) -> bool: try: return os.path.commonpath([path, directory]) == directory @@ -3078,9 +3032,9 @@ def wait(name: str) -> bool: if "pipelines" in stages: shaders_ok = wait("shaders") if "shaders" in futures else True if shaders_ok: - # When runtime is in this run it rebuilds vk_pipeline_check at the same path: wait for it so - # pipelines does not validate with a stale binary or race the Windows linker. A checker already - # on disk is enough only when this run is not rebuilding it. + # When runtime is in this run it rebuilds gta6rt.exe at the same path: wait for it so + # pipelines does not precompile with a stale binary or race the Windows linker. A gta6rt.exe + # already on disk is enough only when this run is not rebuilding it. runtime_ok = wait("runtime") if "runtime" in futures else True if runtime_ok: futures["pipelines"] = ex.submit(_invoke_stage, "pipelines", fn_pipelines) @@ -3125,9 +3079,9 @@ def main() -> int: ap.add_argument("--jobs", type=positive_int, default=max(1, (os.cpu_count() or 2) // 2)) ap.add_argument("--find", action="store_true", help="only list the game copies found on this PC") ap.add_argument("--runtime-build", metavar="DIR", type=nonempty_path, - help="a Windows build of runtime/ (gta6rt.exe and gta6rt_tls_host.dll) for the runtime stage " - "instead of building it (off Windows: instead of the clang-cl + xwin cross-build); " - "on Windows, also use vk_pipeline_check.exe from DIR if present") + help="a Windows build of runtime/ (gta6rt.exe and gta6rt_tls_host.dll) for the runtime and " + "pipelines stages instead of building it (off Windows: instead of the clang-cl + xwin " + "cross-build)") ap.add_argument("--wave64-emulate", choices=WAVE64_MODES, default="auto", help="translate wave64 compute and mesh shaders to be exact on any subgroup size (needed on " "32-wide GPUs: NVIDIA, Intel). auto (default) checks GPU subgroup support and prefers " @@ -3139,8 +3093,7 @@ def main() -> int: help="run the translator's compact binary pass on all shader libraries (requires spirv-opt)") ap.add_argument("--no-float-controls", action="store_true", help="translate without SignedZeroInfNanPreserve and DenormPreserve (Depends on: #664), for " - "devices whose vk_pipeline_check skips a shader without " - "shaderSignedZeroInfNanPreserveFloat32 or shaderDenormPreserveFloat16") + "devices without shaderSignedZeroInfNanPreserveFloat32 or shaderDenormPreserveFloat16") ap.add_argument("--bary-fallback", action="store_true", help="translate raw barycentric reads from an interpolated vec3 input (with a pass-through " "geometry shader the runtime draws), for devices without " @@ -3225,8 +3178,11 @@ def main() -> int: if a.stages is None and os.name != "nt" and not runtime_build: lacking = cross_build_missing() if lacking: - stages = [s for s in stages if s not in WINDOWS_ONLY] - log(f"{', '.join(WINDOWS_ONLY)}: left out, the cross-build needs {'; '.join(lacking)} " + dropped = list(WINDOWS_ONLY) + if "pipelines" in stages and (not runtime_exe(out, runtime_build) or not wine_available()): + dropped.append("pipelines") + stages = [s for s in stages if s not in dropped] + log(f"{', '.join(dropped)}: left out, the cross-build needs {'; '.join(lacking)} " "(or pass --runtime-build)") if "shaders" in stages and not a.mesh_compute and not a.native_mesh: crash = runtime_gpu_mesh_draws_crash() @@ -3282,7 +3238,7 @@ def main() -> int: cfg = leonida_tui.run_setup(a.jobs, default_overlap=True) a.jobs = leonida_tui.clamp_jobs(cfg.jobs) overlap = cfg.overlap - preflight(stages, work, a.wav, runtime_build, emulate=emulate, keep_emulated=keep_emulated, + preflight(stages, work, a.wav, runtime_build, out=out, emulate=emulate, keep_emulated=keep_emulated, fallbacks=fallbacks, jobs=a.jobs) if not a.out and icloud_documents(): for note in icloud_default_notes(): diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 7bcfa9ef62..b3863bb9c5 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -895,6 +895,11 @@ if(BUILD_TESTING) add_executable(pipeline_cache_journal_test test/pipeline_cache_journal_test.cpp) add_test(NAME pipeline_cache_journal COMMAND pipeline_cache_journal_test) + # gta6rt --precompile-pipelines: entries a dead run left in the driver are skipped next time (precompile_inflight.h). + add_executable(precompile_inflight_test test/precompile_inflight_test.cpp) + target_link_libraries(precompile_inflight_test PRIVATE Threads::Threads) + add_test(NAME precompile_inflight COMMAND precompile_inflight_test) + # The compile helper's request files and building markers (shims/d3d12_compile_helper.h): Win32 file calls only. if(WIN32) add_executable(compile_helper_test test/compile_helper_test.cpp) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e7980daeed..abf46fb652 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -54,6 +54,7 @@ #include "../src/pipeline_cache_journal.h" #include "../src/pipeline_order.h" #include "../src/pipeline_prewarm.h" +#include "../src/precompile_inflight.h" #include "../src/large_module_gate.h" #include "../src/dev_status.h" #include "../src/conservative_raster.h" @@ -22928,6 +22929,71 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { return 0; } + // One precompile per journal folder, so that what requests/inflight.txt lists at a start can only be a dead run's + // (precompile_inflight.h). The lock goes with the process, however it ends. Exit 3: another run has the folder. + const std::filesystem::path requests = pipeline_journal_dir() / L"requests"; + { + std::error_code ec; + std::filesystem::create_directories(requests, ec); + } + const HANDLE run_lock = CreateFileW((requests / L"precompile.lock").c_str(), GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + if (run_lock == INVALID_HANDLE_VALUE) { + std::fprintf(stderr, "[precompile] another --precompile-pipelines is using %ls (error %lu)\n", + requests.c_str(), GetLastError()); + return 3; + } + // A crash is held against what was built: this module file (its size and last write, so a new translation of it + // is a new key, with no read of the module) on this device and driver. --all tries every one again. + const std::uint32_t driver = host.state().pso_identity.driver, device_id = host.state().pso_identity.device; + const auto crash_key = [&](const leonida::ShaderEntry& entry) { + leonida::pipeline_journal::Hasher hash; + hash.text("precompile-crash"); + hash.value(driver); + hash.value(device_id); + std::error_code ec; + const std::filesystem::path file = library->spirv_path(entry); + const std::uint64_t size = std::filesystem::file_size(file, ec); + const auto written = std::filesystem::last_write_time(file, ec).time_since_epoch().count(); + hash.value(ec ? 0 : size); + hash.value(static_cast(ec ? 0 : written)); + char text[17]; + std::snprintf(text, sizeof text, "%016llx", static_cast(hash.digest())); + return std::string(text); + }; + leonida::precompile_inflight::Record inflight(requests, options.rebuild); + char crash_buffer[512]{}; // LEONIDA_PRECOMPILE_CRASH_TEST: an entry name, for tests only + const DWORD crash_length = GetEnvironmentVariableA("LEONIDA_PRECOMPILE_CRASH_TEST", crash_buffer, sizeof crash_buffer); + const char* crash_test = crash_length && crash_length < sizeof crash_buffer ? crash_buffer : nullptr; + for (const auto& [name, key] : inflight.left_in_flight()) + std::fprintf(stderr, "[precompile] %s: the last run died while the driver built it\n", name.c_str()); + std::vector keys; + keys.reserve(jobs.size()); + std::size_t crashed = 0; + std::uint64_t crashed_bytes = 0; + { + std::vector kept; + kept.reserve(jobs.size()); + for (const Job& job : jobs) { + std::string key = crash_key(*job.entry); + if (inflight.is_crashed(job.entry->name, key)) { + ++crashed; + crashed_bytes += job.bytes; + std::fprintf(stderr, "[precompile] %s: not built (a run died building this module on this driver; " + "listed in %ls, a new translation or driver or --all tries it again)\n", + job.entry->name.c_str(), inflight.crashed_path().c_str()); + continue; + } + kept.push_back(job); + keys.push_back(std::move(key)); + } + jobs.swap(kept); + total_bytes -= crashed_bytes; + } + if (crashed) + std::fprintf(stderr, "[precompile] %zu compute entries to build after leaving out %zu that crashed a run\n", + jobs.size(), crashed); + std::atomic next{0}; std::mutex progress_mutex; std::size_t done = 0, compiled = 0, skipped = 0, hits = 0, failed = 0, journaled = 0, elsewhere = 0; @@ -22954,11 +23020,15 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { build_options.use_helper = options.via_helper; build_options.mark_building = !options.via_helper; // an entry another process is compiling is left to it ComputeBuild build; + inflight.begin(job.entry->name, keys[i]); // on disk before the driver sees the module + // Tests: end the process here, as a driver crash inside this module's create would. + if (crash_test && job.entry->name == crash_test) TerminateProcess(GetCurrentProcess(), 0xC0000005u); try { build = host.build(*job.entry, build_options); } catch (const std::exception& e) { std::fprintf(stderr, "[precompile] %s: %s\n", job.entry->name.c_str(), e.what()); } + inflight.end(job.entry->name); host.destroy(build.pipeline); if (big) { std::lock_guard lock(big_mutex); @@ -22990,11 +23060,13 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { // One line for the whole run: what was built, what was there already, and what was left out and why. std::fprintf(stderr, "[precompile] done: %zu built (%zu compiled, %zu from a cache), %zu journaled already, %zu " "being built by another process, %zu failed; left out: %zu of %zu listed in " - "LEONIDA_SKIP_COMPUTE%s, %zu not buildable, %zu filtered out; in %.0f s\n", + "LEONIDA_SKIP_COMPUTE%s, %zu not buildable, %zu filtered out%s; in %.0f s\n", compiled + hits, compiled, hits, journaled, elsewhere, failed, listed_left_out, listed, options.skip_listed ? " (--skip-listed)" : "", not_buildable, filtered, + crashed ? (", " + std::to_string(crashed) + " crashed a run").c_str() : "", std::chrono::duration(Clock::now() - began).count()); - return failed ? 2 : 0; + CloseHandle(run_lock); + return failed || crashed ? 2 : 0; } // What a compute pipeline's journal name depends on besides its module: a name remembered for a module is good for diff --git a/runtime/src/precompile_inflight.h b/runtime/src/precompile_inflight.h new file mode 100644 index 0000000000..f207318489 --- /dev/null +++ b/runtime/src/precompile_inflight.h @@ -0,0 +1,114 @@ +// gta6rt --precompile-pipelines: which compute entries are inside the driver right now, kept on disk so that a module +// that takes the whole process down (a driver crash, an abort in the compiler) is known on the next run. +// +// requests/inflight.txt lists, one per line, " " for the entries this process is building; an entry is +// added before its pipeline create and removed after it. The key names what was built: the module's bytes and the +// driver (the caller makes it), so a crash is held against that module on that driver only. The file is rewritten and +// closed at each change, so what it says survives the process (the OS keeps a closed file's data when the process +// dies; an OS crash is not what this is for). +// requests/crashed.txt collects what a dead run left in flight. A run starts by moving a leftover inflight.txt into +// crashed.txt. An entry is not built again while its current key is the one that crashed (it is reported); a new +// translation of the module or a new driver gives a new key, and the entry is tried again. The caller can forget every +// crash (--all). +// +// One precompile per journal folder: the caller holds its own lock (d3d12_vulkan_device.cpp) while this is in use, so +// a leftover inflight.txt can only be a dead run's. Standard library only. +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace leonida::precompile_inflight { + +class Record { +public: + using Entries = std::map; // name -> key + + // `requests`: the journal's requests folder. `retry_crashed`: forget the earlier runs' crashes (--all). + Record(std::filesystem::path requests, bool retry_crashed) + : inflight_(requests / "inflight.txt"), crashed_file_(requests / "crashed.txt") { + std::error_code ec; + std::filesystem::create_directories(requests, ec); + crashed_ = read(crashed_file_); + left_in_flight_ = read(inflight_); + for (const auto& [name, key] : left_in_flight_) crashed_[name] = key; + if (retry_crashed) crashed_.clear(); + write(crashed_file_, crashed_); + std::filesystem::remove(inflight_, ec); + } + + // What the run before this one left inside the driver (now also in crashed()). + const Entries& left_in_flight() const { return left_in_flight_; } + // Every entry a run died building, with the key it died on (until a build of it returns). + const Entries& crashed() const { return crashed_; } + // Whether `name`, as it is now (`key`), is what a run died building. + bool is_crashed(const std::string& name, const std::string& key) const { + const auto it = crashed_.find(name); + return it != crashed_.end() && it->second == key; + } + + // Around one entry's pipeline create, from any thread. + void begin(const std::string& name, const std::string& key) { + std::lock_guard lock(mutex_); + active_[name] = key; + write(inflight_, active_); + } + // The build returned: it is out of the driver, and a crash recorded for an earlier key of it no longer stands. + void end(const std::string& name) { + std::lock_guard lock(mutex_); + active_.erase(name); + write(inflight_, active_); + if (crashed_.erase(name)) write(crashed_file_, crashed_); + } + + const std::filesystem::path& crashed_path() const { return crashed_file_; } + +private: + // " " per line; a line with no key (an older file) has an empty one, which no build matches. + static Entries read(const std::filesystem::path& path) { + Entries entries; + std::ifstream in(path, std::ios::binary); + std::string line; + while (std::getline(in, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.empty()) continue; + const auto space = line.rfind(' '); + if (space == std::string::npos) entries[line] = std::string(); + else entries[line.substr(0, space)] = line.substr(space + 1); + } + return entries; + } + // Written beside and renamed over, so a reader never sees half a list; an empty list is no file. + static void write(const std::filesystem::path& path, const Entries& entries) { + std::error_code ec; + if (entries.empty()) { + std::filesystem::remove(path, ec); + return; + } + auto next = path; + next += ".new"; + const auto put = [&](const std::filesystem::path& to) { + std::ofstream out(to, std::ios::binary | std::ios::trunc); + for (const auto& [name, key] : entries) out << name << ' ' << key << '\n'; + }; + put(next); + std::filesystem::rename(next, path, ec); + if (ec) { // a reader holding the old file open (Windows): write in place instead + std::filesystem::remove(next, ec); + put(path); + } + } + + std::filesystem::path inflight_; + std::filesystem::path crashed_file_; + Entries crashed_; + Entries left_in_flight_; + Entries active_; + std::mutex mutex_; +}; + +} // namespace leonida::precompile_inflight diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 7699dfbb0d..cd4d64b0ae 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -1145,6 +1145,19 @@ class ShaderLibrary { return ec ? 0 : static_cast(size); } + // The module's file: /.spv, or the entry's spv_file when that one is missing. + std::filesystem::path spirv_path(const ShaderEntry& entry) const { + auto path = dir_; + path += "/" + entry.name + ".spv"; + std::error_code ec; + if (!std::filesystem::exists(path, ec) && !entry.spv_file.empty()) { + auto alt = dir_; + alt += "/" + entry.spv_file; + return alt; + } + return path; + } + // Every entry of `stage` once, in name order, from every index (an entry reachable both by its FSSM and its FSPX // hash is one entry). gta6rt --precompile-pipelines builds them all. std::vector stage_entries(std::string_view stage) const { diff --git a/runtime/test/precompile_inflight_test.cpp b/runtime/test/precompile_inflight_test.cpp new file mode 100644 index 0000000000..42468642a2 --- /dev/null +++ b/runtime/test/precompile_inflight_test.cpp @@ -0,0 +1,119 @@ +// precompile_inflight.h: an entry left in flight by a run that died is known to the next run and skipped there while +// it is the same module on the same driver; a new key (a new translation, a new driver) or --all tries it again. +// Standard library only, no GPU. +#include "../src/precompile_inflight.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace fs = std::filesystem; +using leonida::precompile_inflight::Record; + +namespace { + +std::set lines(const fs::path& path) { + std::set out; + std::ifstream in(path, std::ios::binary); + for (std::string line; std::getline(in, line);) + if (!line.empty()) out.insert(line); + return out; +} + +int run(const fs::path& dir) { + const fs::path inflight = dir / "inflight.txt", crashed = dir / "crashed.txt"; + + { // A clean run: nothing crashed, the file lists what is being built and goes when nothing is. + Record r(dir, false); + EXPECT(r.crashed().empty() && r.left_in_flight().empty()); + r.begin("lib_cs_a", "k1"); + r.begin("lib_cs_b", "k2"); + EXPECT((lines(inflight) == std::set{"lib_cs_a k1", "lib_cs_b k2"})); + r.end("lib_cs_a"); + EXPECT((lines(inflight) == std::set{"lib_cs_b k2"})); + r.end("lib_cs_b"); + EXPECT(!fs::exists(inflight)); + EXPECT(!fs::exists(crashed)); + } + { // A run that dies inside the driver: its record is left as it was (no end()). + Record r(dir, false); + r.begin("lib_cs_big", "k7"); + r.begin("lib_cs_other", "k8"); + r.end("lib_cs_other"); + } + { // The next run learns which entry and key it was, moves it to crashed.txt and starts with no in-flight list. + Record r(dir, false); + EXPECT(r.left_in_flight().size() == 1 && r.left_in_flight().at("lib_cs_big") == "k7"); + EXPECT(r.is_crashed("lib_cs_big", "k7") && !r.is_crashed("lib_cs_other", "k8")); + EXPECT(!fs::exists(inflight)); + EXPECT((lines(crashed) == std::set{"lib_cs_big k7"})); + } + { // A later run still skips it while it is the same module on the same driver... + Record r(dir, false); + EXPECT(r.left_in_flight().empty()); + EXPECT(r.is_crashed("lib_cs_big", "k7")); + // ...and tries it again once the key changes (a new translation of it, or a new driver). + EXPECT(!r.is_crashed("lib_cs_big", "k9")); + } + { // A new build of it that dies again records the new key. + { Record r(dir, false); r.begin("lib_cs_big", "k9"); } + Record r(dir, false); + EXPECT(r.is_crashed("lib_cs_big", "k9") && !r.is_crashed("lib_cs_big", "k7")); + } + { // A build of a new key that returns clears the entry from crashed.txt. + Record r(dir, false); + r.begin("lib_cs_big", "k10"); + r.end("lib_cs_big"); + EXPECT(r.crashed().empty() && !fs::exists(crashed)); + { Record dead(dir, false); dead.begin("lib_cs_big", "k11"); } // and dies once more for the --all case + } + { // --all: every entry is tried again, the list is cleared. + Record r(dir, true); + EXPECT(r.crashed().empty()); + EXPECT(!fs::exists(crashed)); + } + { // Many threads at once: the file always holds whole lines, and nothing is left when all are done. + Record r(dir, false); + std::vector pool; + for (int t = 0; t < 8; ++t) + pool.emplace_back([&r, t] { + for (int i = 0; i < 50; ++i) { + const std::string name = "cs_" + std::to_string(t) + "_" + std::to_string(i); + r.begin(name, "k"); + r.end(name); + } + }); + for (std::thread& t : pool) t.join(); + EXPECT(!fs::exists(inflight)); + EXPECT(r.crashed().empty()); + } + { // A Windows line ending in a hand-edited list is not part of the key; a line with no key matches no build. + { std::ofstream(crashed, std::ios::binary) << "lib_cs_crlf k3\r\nlib_cs_nokey\n"; } + Record r(dir, false); + EXPECT(r.is_crashed("lib_cs_crlf", "k3")); + EXPECT(!r.is_crashed("lib_cs_nokey", "k4")); + } + return 0; +} + +} // namespace + +int main() { + const fs::path dir = fs::temp_directory_path() / ("leonida_precompile_inflight_" + std::to_string( + std::hash{}(std::this_thread::get_id()))); + std::error_code ec; + fs::remove_all(dir, ec); + const int result = run(dir); + fs::remove_all(dir, ec); + if (!result) std::printf("precompile_inflight_test: ok\n"); + return result; +} diff --git a/tests/test_leonida_tui.py b/tests/test_leonida_tui.py index 72e9c2f323..53b67c1c93 100644 --- a/tests/test_leonida_tui.py +++ b/tests/test_leonida_tui.py @@ -340,8 +340,7 @@ def fn(*a, **k): mock.patch.object(make_game, "assets", side_effect=record("assets")), \ mock.patch.object(make_game, "runtime", side_effect=record("runtime")), \ mock.patch.object(make_game, "pipelines", side_effect=record("pipelines")), \ - mock.patch.object(make_game, "log"), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value="x"): + mock.patch.object(make_game, "log"): make_game.run_build_stages( ["shaders", "assets", "runtime", "pipelines"], game=game, work=work, out=out, v={}, wav=False, jobs=2, @@ -349,8 +348,8 @@ def fn(*a, **k): overlap=False) self.assertEqual(order, ["shaders", "assets", "runtime", "pipelines"]) - def test_overlap_waits_for_runtime_before_pipelines_even_if_checker_exists(self): - """Flyander/#1797: a stale vk_pipeline_check on disk must not start pipelines mid-rebuild.""" + def test_overlap_waits_for_runtime_before_pipelines_even_if_exe_exists(self): + """Flyander/#1797: a stale gta6rt.exe on disk must not start pipelines mid-rebuild.""" import threading import time @@ -377,7 +376,7 @@ def fn(*a, **k): mock.patch.object(make_game, "runtime", side_effect=record("runtime", hold=0.15)), \ mock.patch.object(make_game, "pipelines", side_effect=record("pipelines")), \ mock.patch.object(make_game, "log"), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value="stale_checker"): + mock.patch.object(make_game, "runtime_exe", return_value="stale_gta6rt.exe"): make_game.run_build_stages( ["shaders", "assets", "runtime", "pipelines"], game=game, work=work, out=out, v={}, wav=False, jobs=2, @@ -464,7 +463,6 @@ def boom(*a, **k): mock.patch.object(make_game, "runtime"), \ mock.patch.object(make_game, "pipelines"), \ mock.patch.object(make_game, "log"), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value="x"), \ mock.patch.object(make_game.sys, "stderr", err), \ self.assertRaises(SystemExit) as ctx: make_game.run_build_stages( diff --git a/tests/test_make_game_argparse.py b/tests/test_make_game_argparse.py index 39d7a5b886..47af6da3ce 100644 --- a/tests/test_make_game_argparse.py +++ b/tests/test_make_game_argparse.py @@ -269,13 +269,12 @@ def test_independent_stages_all_run_when_listed_out_of_order(self): with patch("make_game.check", return_value={"expected_exe": "Leonida.exe"}): with patch("make_game.preflight"): with patch("make_game.log"): - with patch("make_game.pipeline_check_exe", return_value="vk_pipeline_check"): - with patch("make_game.shaders", manager.shaders): - with patch("make_game.assets", manager.assets): - with patch("make_game.runtime", manager.runtime): - with patch("make_game.pipelines", manager.pipelines): - ret = make_game.main() - self.assertEqual(ret, 0) + with patch("make_game.shaders", manager.shaders): + with patch("make_game.assets", manager.assets): + with patch("make_game.runtime", manager.runtime): + with patch("make_game.pipelines", manager.pipelines): + ret = make_game.main() + self.assertEqual(ret, 0) manager.shaders.assert_called_once_with( os.path.abspath(self.game_dir), os.path.abspath(self.work_dir), unittest.mock.ANY, @@ -371,7 +370,8 @@ def test_custom_jobs_forwarded_to_shaders(self): probe.assert_called_once_with("auto", mesh_compute=False) mock_preflight.assert_called_once_with( ["shaders"], os.path.abspath(work), False, None, - emulate=True, keep_emulated=True, fallbacks=(), jobs=6) + out=os.path.abspath(out), emulate=True, keep_emulated=True, fallbacks=(), + jobs=6) mock_shaders.assert_called_once_with(os.path.abspath(game), os.path.abspath(work), 6, emulate=True, keep_emulated=True, fallbacks=()) diff --git a/tests/test_make_game_dry_run.py b/tests/test_make_game_dry_run.py index 27c8f4cb04..2fbdcf1d3c 100644 --- a/tests/test_make_game_dry_run.py +++ b/tests/test_make_game_dry_run.py @@ -200,7 +200,7 @@ def test_skip_assets_preflight_bypasses_dotnet_sdk_and_submodule_checks(self) -> mock.patch.object(make_game, "dotnet_sdk_ok") as mock_dotnet, \ mock.patch.object(make_game, "ensure_submodule") as mock_submodule, \ mock.patch.object(make_game, "tool_available", return_value=True), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value="/bin/vk_pipeline_check"), \ + mock.patch.object(make_game, "runtime_exe", return_value="/out/gta6rt.exe"), \ mock.patch("shutil.which", return_value="/usr/bin/tool"), \ mock.patch("shutil.disk_usage", return_value=mock.Mock(free=100 * (2**30))): make_game.preflight(["shaders", "pipelines"], self.work_dir, wav=True) # no runtime: Windows-only @@ -272,10 +272,10 @@ def setUp(self) -> None: os.makedirs(self.out_dir, exist_ok=True) def test_pipelines_fails_when_spirv_index_is_missing(self) -> None: - dummy_exe = os.path.join(self.tmp.name, "vk_pipeline_check.exe") + dummy_exe = os.path.join(self.tmp.name, "gta6rt.exe") with open(dummy_exe, "w", encoding="utf-8") as f: f.write("dummy") - with mock.patch("make_game.pipeline_check_exe", return_value=dummy_exe): + with mock.patch("make_game.runtime_exe", return_value=dummy_exe): stderr_buf = io.StringIO() with mock.patch("sys.stderr", stderr_buf): with self.assertRaises(SystemExit) as ctx: @@ -283,67 +283,61 @@ def test_pipelines_fails_when_spirv_index_is_missing(self) -> None: self.assertEqual(ctx.exception.code, 1) self.assertIn("No translated shaders yet: run the shaders stage first.", stderr_buf.getvalue()) - def test_pipelines_fails_when_pipeline_check_exe_not_built_on_windows(self) -> None: + def test_pipelines_fails_when_runtime_exe_not_built_on_windows(self) -> None: spirv_dir = os.path.join(self.work_dir, "shaders", "spirv") os.makedirs(spirv_dir, exist_ok=True) with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8") as f: f.write("{}") - with mock.patch("make_game.pipeline_check_exe", return_value=None), \ + with mock.patch("make_game.runtime_exe", return_value=None), \ mock.patch.object(make_game.os, "name", "nt"): stderr_buf = io.StringIO() with mock.patch("sys.stderr", stderr_buf): with self.assertRaises(SystemExit) as ctx: make_game.pipelines(self.work_dir, self.out_dir) self.assertEqual(ctx.exception.code, 1) - self.assertIn("vk_pipeline_check.exe wasn't built", stderr_buf.getvalue()) + self.assertIn("gta6rt.exe was not found", stderr_buf.getvalue()) - def test_pipelines_fails_when_pipeline_check_exe_not_built_on_posix(self) -> None: + def test_pipelines_fails_when_runtime_exe_not_built_on_posix(self) -> None: spirv_dir = os.path.join(self.work_dir, "shaders", "spirv") os.makedirs(spirv_dir, exist_ok=True) with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8") as f: f.write("{}") - with mock.patch("make_game.pipeline_check_exe", return_value=None), \ + with mock.patch("make_game.runtime_exe", return_value=None), \ mock.patch.object(make_game.os, "name", "posix"): stderr_buf = io.StringIO() with mock.patch("sys.stderr", stderr_buf): with self.assertRaises(SystemExit) as ctx: make_game.pipelines(self.work_dir, self.out_dir) self.assertEqual(ctx.exception.code, 1) - self.assertIn("vk_pipeline_check wasn't built", stderr_buf.getvalue()) + self.assertIn("gta6rt.exe was not found", stderr_buf.getvalue()) - def test_pipelines_executes_compiler_isolated_with_expected_command_line(self) -> None: + def test_pipelines_executes_precompiler_isolated_with_expected_command_line(self) -> None: spirv_dir = os.path.join(self.work_dir, "shaders", "spirv") os.makedirs(spirv_dir, exist_ok=True) index_path = os.path.join(spirv_dir, "index.json") with open(index_path, "w", encoding="utf-8") as f: f.write('{"shader_0": {}}') # a finished translation is never empty - dummy_exe = os.path.join(self.tmp.name, "vk_pipeline_check.exe") + dummy_exe = os.path.join(self.tmp.name, "gta6rt.exe") with open(dummy_exe, "w", encoding="utf-8") as f: f.write("binary") - expected_cache = os.path.join(self.out_dir, "pipeline_cache.bin") executed_cmds = [] - def fake_run(args: list[str], **kwargs: object) -> int: - executed_cmds.append(args) + def fake_run_precompile(cmd: list[str], env: dict[str, str], progress_box: list) -> int: + executed_cmds.append(cmd) return 0 - # The usage probe (checker_supports) really launches the checker, so it is stubbed too: CreateProcess on a - # text file named .exe makes native Windows show a modal "Unsupported 16-Bit Application" dialog that blocks - # the run. A checker without --inflight-file is what the old dummy answered. - with mock.patch("make_game.pipeline_check_exe", return_value=dummy_exe), \ - mock.patch("make_game.checker_supports", return_value=False) as supports, \ - mock.patch("make_game.run", side_effect=fake_run), \ - mock.patch.object(make_game.subprocess, "run", side_effect=AssertionError("launched the dummy")), \ + with mock.patch("make_game.runtime_exe", return_value=dummy_exe), \ + mock.patch.object(make_game.os, "name", "nt"), \ + mock.patch("make_game._run_precompile", side_effect=fake_run_precompile), \ mock.patch("make_game.log"): - make_game.pipelines(self.work_dir, self.out_dir) + make_game.pipelines(self.work_dir, self.out_dir, jobs=4) - supports.assert_called_once() self.assertEqual(len(executed_cmds), 1) - self.assertEqual(executed_cmds[0], [dummy_exe, spirv_dir, expected_cache]) + self.assertEqual(executed_cmds[0], [dummy_exe, "--precompile-pipelines", "--threads", "4"]) def test_pipelines_stage_alone_invokes_no_asset_or_shader_compilers(self) -> None: game_dir = os.path.join(self.tmp.name, "game") diff --git a/tests/test_make_game_pipeline_batches.py b/tests/test_make_game_pipeline_batches.py deleted file mode 100644 index 49e3ad2720..0000000000 --- a/tests/test_make_game_pipeline_batches.py +++ /dev/null @@ -1,247 +0,0 @@ -"""Pipeline batching and memory-crash recovery through the real make_game.pipelines orchestration. - -The child is a small scripted checker speaking the production CLI/file protocol. Each invocation is a real -process, with synthetic index entries and controlled exits; no GPU, compiler, game data or packages are needed. -""" -import contextlib -import io -import json -import os -from pathlib import Path -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT)) -import make_game # noqa: E402 - - -CHECKER = r''' -import json -import os -from pathlib import Path -import signal -import sys - -spirv, cache, *args = sys.argv[1:] -spirv, cache = Path(spirv), Path(cache) -config = json.loads((spirv / "control.json").read_text(encoding="utf-8")) -names = sorted(json.loads((spirv / "index.json").read_text(encoding="utf-8")), key=lambda n: n.encode("utf-8")) -def option(flag, default=None): - return args[args.index(flag) + 1] if flag in args else default -start = int(option("--start", 0)) -count = int(option("--count", len(names))) -selected = names[start:start + count] -skip_path = option("--skip-file") -skipped = Path(skip_path).read_text(encoding="utf-8").splitlines() if skip_path else [] -active = [name for name in selected if name not in skipped] -inflight = option("--inflight-file") -def record(event): - with (spirv / "calls.jsonl").open("a", encoding="utf-8", newline="\n") as f: - f.write(json.dumps(dict(event=event, pid=os.getpid(), selected=selected, active=active, args=args)) + "\n") -record("started") -if config.get("setup_error") or config.get("probe_setup_error") and count == 1 and option("--jobs") == "1": - print("no Vulkan physical devices found", file=sys.stderr) - sys.exit(config.get("setup_exit", 2)) -if config.get("interrupt") or config.get("interrupt_probe") and count == 1 and option("--jobs") == "1": - if os.name == "nt": - import ctypes - ctypes.windll.kernel32.ExitProcess(0xC000013A) - else: - os.kill(os.getpid(), signal.SIGTERM) -if config.get("crash_before_work"): - sys.exit(70) -if config.get("probe_crash_before_work") and count == 1 and option("--jobs") == "1": - report = config.get("probe_report", "missing") - if inflight and report != "missing": - Path(inflight).write_text("unrelated\tpipeline\n" if report == "other" else "", - encoding="utf-8", newline="\n") - sys.exit(70) -crasher = config.get("crasher") -if crasher in active or len(active) > config.get("max_batch", 1000000): - if inflight: - suspects = [crasher] if crasher in active else active[:config.get("suspects", 2)] - Path(inflight).write_text("".join(n + "\tpipeline\n" for n in suspects), encoding="utf-8", newline="\n") - sys.exit(70) -# This stand-in's cache contains completed names so the test can detect lost checkpoints and repeated work. -completed = json.loads(cache.read_text(encoding="utf-8")) if cache.exists() else [] -cache.write_text(json.dumps(completed + active), encoding="utf-8", newline="\n") -record("completed") -if inflight: - Path(inflight).write_text("", encoding="utf-8", newline="\n") -sys.exit(1 if skipped and set(selected).intersection(skipped) or config.get("invalid") in active else 0) -''' - - -class PipelineBatchesTest(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory(prefix="pipeline batches ") - self.addCleanup(tmp.cleanup) - self.root = Path(tmp.name) - self.work = self.root / "work" - self.spirv = self.work / "shaders" / "spirv" - self.spirv.mkdir(parents=True) - self.out = self.root / "out" - self.names = [f"m_{i:02d}" for i in range(7)] - self.write_index(self.names) - self.child = self.root / "checker.py" - self.child.write_text(CHECKER, encoding="utf-8", newline="\n") - self.commands = [] - - def write_index(self, names): - (self.spirv / "index.json").write_text(json.dumps({n: {} for n in reversed(names)}), - encoding="utf-8", newline="\n") - - def invoke(self, control=None, range_support=True): - (self.spirv / "control.json").write_text(json.dumps(control or {}), encoding="utf-8", newline="\n") - def run(args, hint="", check=True, **kwargs): - args = [str(a) for a in args] - self.commands.append(args) - done = subprocess.run([sys.executable, "-I", str(self.child), *args[1:]], - capture_output=True, text=True, timeout=15) - if check and done.returncode: - raise SystemExit(1) - return done.returncode - def supports(exe, *options): - return range_support or "--start" not in options - logs, err = [], io.StringIO() - # create=True keeps the regression runnable on the old implementation, which lacks this constant. - with mock.patch.object(make_game, "pipeline_check_exe", return_value="synthetic-checker"), \ - mock.patch.object(make_game, "checker_supports", side_effect=supports), \ - mock.patch.object(make_game, "PIPELINE_BATCH_SIZE", 3, create=True), \ - mock.patch.object(make_game, "run", side_effect=run), \ - mock.patch.object(make_game, "log", side_effect=logs.append), contextlib.redirect_stderr(err): - try: - make_game.pipelines(str(self.work), str(self.out), jobs=2) - except SystemExit as exc: - return exc.code, logs, err.getvalue() - return 0, logs, err.getvalue() - - def calls(self, event=None): - path = self.spirv / "calls.jsonl" - rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] if path.exists() else [] - return [row for row in rows if event is None or row["event"] == event] - - def test_bounded_processes_cover_the_sorted_index_and_tail(self): - code, _, err = self.invoke() - self.assertEqual(code, 0, err) - completed = self.calls("completed") - self.assertEqual([r["selected"] for r in completed], [self.names[:3], self.names[3:6], self.names[6:]]) - self.assertEqual(len({r["pid"] for r in completed}), 3) - self.assertEqual(json.loads((self.out / "pipeline_cache.bin").read_text(encoding="utf-8")), self.names) - self.assertTrue(all(r["args"][r["args"].index("--jobs") + 1] == "2" for r in completed)) - - def test_bvh_pipelines_are_added_to_the_runtime_seed(self): - bvh = self.spirv / "bvh" - bvh.mkdir() - (bvh / "index.json").write_text('{"b_0": {}}', encoding="utf-8") - (bvh / "control.json").write_text("{}", encoding="utf-8") - code, _, err = self.invoke() - self.assertEqual(code, 0, err) - self.assertEqual(json.loads((self.out / "pipeline_cache.bin").read_text(encoding="utf-8")), - self.names + ["b_0"]) - rows = [json.loads(line) for line in (bvh / "calls.jsonl").read_text(encoding="utf-8").splitlines()] - self.assertEqual([row["selected"] for row in rows if row["event"] == "completed"], [["b_0"]]) - - def test_collective_memory_crash_splits_without_skipping_healthy_modules(self): - code, logs, err = self.invoke({"max_batch": 2}) - self.assertEqual(code, 0, err) - # Diagnostic one-module probes are also successful; the final bounded work must still cover every name. - checked = {n for row in self.calls("completed") for n in row["active"]} - self.assertEqual(checked, set(self.names)) - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - self.assertTrue(any("smaller" in line for line in logs), logs) - - def test_a_real_crasher_stays_failed_when_later_batches_pass(self): - code, _, err = self.invoke({"crasher": "m_01"}) - self.assertNotEqual(code, 0) - self.assertEqual((self.out / "pipeline_crashes.txt").read_text(encoding="utf-8"), "m_01\n") - self.assertIn("m_01", err) - checked = {n for row in self.calls("completed") for n in row["active"]} - self.assertEqual(checked, set(self.names) - {"m_01"}) - - def test_one_inflight_module_is_not_blacklisted_when_it_survives_alone(self): - self.write_index(self.names[:2]) # small corpora need the same protection as multi-batch runs - code, _, err = self.invoke({"max_batch": 1, "suspects": 1}) - self.assertEqual(code, 0, err) - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - self.assertEqual({n for row in self.calls("completed") for n in row["active"]}, set(self.names[:2])) - - def test_interrupting_a_diagnostic_probe_stops_before_more_batches(self): - code, _, _ = self.invoke({"max_batch": 2, "interrupt_probe": True}) - self.assertNotEqual(code, 0) - self.assertEqual(len(self.calls()), 2) # the failed batch and the interrupted diagnostic probe - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - - def test_a_validation_failure_does_not_hide_the_remaining_batches(self): - code, _, _ = self.invoke({"invalid": "m_01"}) - self.assertNotEqual(code, 0) - self.assertEqual([n for row in self.calls("completed") for n in row["active"]], self.names) - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - - def test_setup_errors_and_interrupts_stop_immediately(self): - for control in ({"setup_error": True}, {"interrupt": True}): - with self.subTest(control=control): - trace = self.spirv / "calls.jsonl" - if trace.exists(): - trace.unlink() - self.commands.clear() - code, _, _ = self.invoke(control) - self.assertNotEqual(code, 0) - self.assertEqual(len(self.calls()), 1) - - def test_native_setup_exit_one_stops_instead_of_checking_every_range(self): - code, _, _ = self.invoke({"setup_error": True, "setup_exit": 1}) - self.assertNotEqual(code, 0) - self.assertEqual(len(self.calls()), 1) - - def test_native_setup_exit_one_in_a_probe_stops_before_splitting(self): - code, _, _ = self.invoke({"max_batch": 2, "probe_setup_error": True, "setup_exit": 1}) - self.assertNotEqual(code, 0) - self.assertEqual(len(self.calls()), 2) - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - - def assert_inconclusive_probe_stops(self, report): - code, logs, err = self.invoke({"max_batch": 2, "probe_crash_before_work": True, - "probe_report": report}) - self.assertNotEqual(code, 0) - self.assertEqual(len(self.calls()), 2) # failed batch, then the first inconclusive probe - self.assertEqual(self.calls()[-1]["selected"], [self.names[0]]) - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - self.assertFalse(any("took vk_pipeline_check down" in line for line in logs), logs) - self.assertIn("inconclusive", err) - - def test_abnormal_probe_without_a_report_does_not_blacklist_a_module(self): - self.assert_inconclusive_probe_stops("missing") - - def test_abnormal_probe_with_an_empty_report_does_not_blacklist_a_module(self): - self.assert_inconclusive_probe_stops("empty") - - def test_abnormal_probe_reporting_another_module_does_not_blacklist_the_selected_one(self): - self.assert_inconclusive_probe_stops("other") - - def test_a_crash_before_work_cannot_retry_forever_or_claim_success(self): - code, _, err = self.invoke({"crash_before_work": True}) - self.assertNotEqual(code, 0) - self.assertLessEqual(len(self.calls()), 4) - self.assertTrue(err) - - def test_an_older_checker_gets_no_unsupported_range_arguments(self): - code, _, err = self.invoke(range_support=False) - self.assertEqual(code, 0, err) - self.assertEqual(len(self.commands), 1) - self.assertNotIn("--start", self.commands[0]) - self.assertNotIn("--count", self.commands[0]) - - def test_small_indices_keep_the_single_run(self): - self.write_index(self.names[:2]) - code, _, err = self.invoke() - self.assertEqual(code, 0, err) - self.assertEqual(len(self.commands), 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_pipeline_preflight.py b/tests/test_make_game_pipeline_preflight.py index 227f52bbcf..082df4a44e 100644 --- a/tests/test_make_game_pipeline_preflight.py +++ b/tests/test_make_game_pipeline_preflight.py @@ -1,4 +1,4 @@ -"""make_game.py: a missing vk_pipeline_check is reported in preflight, before a long shader build. +"""make_game.py: pipelines stage preflight checks (gta6rt.exe, Wine off Windows, VULKAN_SDK on Windows). python -I tests/test_make_game_pipeline_preflight.py @@ -25,48 +25,58 @@ def setUp(self): self.addCleanup(tmp.cleanup) self.root = tmp.name self.work = os.path.join(self.root, "work") + self.out = os.path.join(self.root, "out") os.makedirs(self.work) - # Satisfy every other prerequisite so only the checker under test can make preflight fail. + os.makedirs(self.out) + # Satisfy every other prerequisite so only the pipelines requirements under test can make preflight fail. for patcher in (mock.patch("sys.version_info", (3, 12, 0)), mock.patch.dict(os.environ, {"LLVM_MC": "llvm-mc"}), mock.patch("shutil.which", return_value="/bin/tool"), - mock.patch("shutil.disk_usage", return_value=mock.Mock(free=500 * 2**30))): + mock.patch("shutil.disk_usage", return_value=mock.Mock(free=500 * 2**30)), + mock.patch.object(make_game, "ROOT", self.root)): patcher.start() self.addCleanup(patcher.stop) def write_shader_index(self): spirv = os.path.join(self.work, "shaders", "spirv") - os.makedirs(spirv) - with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8") as f: - f.write('{"shader_0": {}}') # a finished translation is never empty + os.makedirs(spirv, exist_ok=True) + with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: + f.write('{"shader_0": {}}\n') + + def write_runtime_exe(self, folder=None): + dest = folder or self.out + os.makedirs(dest, exist_ok=True) + path = os.path.join(dest, "gta6rt.exe") + with open(path, "wb"): + pass + return path - def assert_preflight_fails(self, stages, match): + def assert_preflight_fails(self, stages, match, **kw): err = io.StringIO() with mock.patch("sys.stderr", err): with self.assertRaises(SystemExit) as ctx: - make_game.preflight(stages, self.work) + make_game.preflight(stages, self.work, out=self.out, **kw) self.assertEqual(ctx.exception.code, 1) self.assertIn(match, err.getvalue()) return err.getvalue() class PipelinePreflightTest(PreflightEnv, unittest.TestCase): - def test_pipelines_without_checker_fails_in_preflight(self): - with mock.patch("os.name", "nt"), mock.patch.object(make_game, "pipeline_check_exe", return_value=None): - err = self.assert_preflight_fails(["shaders", "pipelines"], "vk_pipeline_check") - self.assertIn("Install these first, then run the build again:", err) + def test_pipelines_without_runtime_or_exe_fails_in_preflight(self): + for platform in ("nt", "posix"): + with self.subTest(platform=platform), mock.patch("os.name", platform): + err = self.assert_preflight_fails(["shaders", "pipelines"], "gta6rt.exe") + self.assertIn("Install these first, then run the build again:", err) - def test_main_does_not_start_shaders_when_checker_is_missing(self): + def test_main_does_not_start_shaders_when_runtime_exe_is_missing(self): game = os.path.join(self.root, "game") - out = os.path.join(self.root, "out") os.makedirs(game) - argv = ["make_game.py", "--game", game, "--work", self.work, "--out", out, + argv = ["make_game.py", "--game", game, "--work", self.work, "--out", self.out, "--stages", "shaders,pipelines", "--no-tui"] with mock.patch.object(sys, "argv", argv), \ mock.patch("os.name", "nt"), \ mock.patch.object(make_game, "below_normal"), \ mock.patch.object(make_game, "check", return_value={"expected_exe": "game.exe"}), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value=None), \ mock.patch.object(make_game, "shaders") as shaders, \ mock.patch.object(make_game, "pipelines") as pipelines, \ mock.patch.object(make_game, "log"), \ @@ -77,54 +87,71 @@ def test_main_does_not_start_shaders_when_checker_is_missing(self): shaders.assert_not_called() pipelines.assert_not_called() - def test_checker_already_built_still_requires_shaders(self): - with mock.patch("os.name", "nt"), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value="vk_pipeline_check.exe"): + def test_exe_already_built_still_requires_shaders(self): + self.write_runtime_exe() + with mock.patch("os.name", "nt"): self.assert_preflight_fails(["pipelines"], "No translated shaders yet") - def test_checker_already_built_passes_preflight(self): - self.write_shader_index() - with mock.patch.object(make_game, "pipeline_check_exe", return_value="/bin/vk_pipeline_check"): - make_game.preflight(["pipelines"], self.work) - - @unittest.skipUnless(os.name == "posix", "requires POSIX execute permissions") - def test_non_executable_linux_checker_without_cmake_fails_preflight(self): + def test_exe_in_out_passes_preflight(self): self.write_shader_index() - checker_dir = os.path.join(self.root, "runtime", "build", "linux") - os.makedirs(checker_dir) - checker = os.path.join(checker_dir, "vk_pipeline_check") - with open(checker, "wb"): - pass - os.chmod(checker, 0o644) - with mock.patch.object(make_game, "ROOT", self.root), \ - mock.patch("shutil.which", return_value=None), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - self.assert_preflight_fails(["pipelines"], "CMake 3.24 or newer") - build.assert_not_called() + self.write_runtime_exe(self.out) + for platform in ("nt", "posix"): + with self.subTest(platform=platform), mock.patch("os.name", platform): + make_game.preflight(["pipelines"], self.work, out=self.out) - def test_runtime_stage_builds_the_checker_so_it_is_not_required(self): - # On Windows runtime produces vk_pipeline_check.exe when the Vulkan SDK is installed. + def test_runtime_stage_builds_gta6rt_so_existing_exe_is_not_required(self): self.write_shader_index() with mock.patch("os.name", "nt"), \ mock.patch.dict(os.environ, {"VULKAN_SDK": r"C:\Vulkan"}), \ - mock.patch.object(make_game, "visual_cpp_tools_ok", return_value=True), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value=None): - make_game.preflight(["runtime", "pipelines"], self.work) + mock.patch.object(make_game, "visual_cpp_tools_ok", return_value=True): + make_game.preflight(["runtime", "pipelines"], self.work, out=self.out) - def test_runtime_without_vulkan_sdk_does_not_build_the_checker(self): - # scripts/build_runtime.ps1 builds vk_pipeline_check.exe only 'if defined VULKAN_SDK': a combined - # Windows run without it would still spend hours in the shaders stage and fail in pipelines. + def test_windows_runtime_and_pipelines_without_vulkan_sdk_fails_preflight(self): for sdk in (None, ""): with self.subTest(sdk=sdk), mock.patch("os.name", "nt"), \ mock.patch.dict(os.environ), \ - mock.patch.object(make_game, "visual_cpp_tools_ok", return_value=True), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value=None): + mock.patch.object(make_game, "visual_cpp_tools_ok", return_value=True): if sdk is None: os.environ.pop("VULKAN_SDK", None) else: os.environ["VULKAN_SDK"] = sdk err = self.assert_preflight_fails(["runtime", "pipelines"], "VULKAN_SDK") - self.assertIn("vk_pipeline_check", err) + self.assertIn("gta6rt.exe", err) + + def test_windows_prebuilt_runtime_with_pipelines_does_not_require_vulkan_sdk(self): + self.write_shader_index() + build = os.path.join(self.root, "prebuilt") + os.makedirs(build) + for name in make_game.RUNTIME_FILES: + with open(os.path.join(build, name), "wb"): + pass + env = {k: v for k, v in os.environ.items() if k != "VULKAN_SDK"} + with mock.patch("os.name", "nt"), mock.patch.dict(os.environ, env, clear=True): + make_game.preflight(["runtime", "pipelines"], self.work, runtime_build=build, out=self.out) + + def test_posix_pipelines_requires_wine_or_wine_env(self): + self.write_shader_index() + self.write_runtime_exe(self.out) + env = {k: v for k, v in os.environ.items() if k != "WINE"} + with mock.patch("os.name", "posix"), \ + mock.patch.dict(os.environ, env, clear=True), \ + mock.patch("shutil.which", side_effect=lambda t: None if t == "wine" else "/bin/tool"): + self.assert_preflight_fails(["pipelines"], "Wine") + # Setting WINE to an existing executable file satisfies preflight even when wine is not on PATH. + with mock.patch("os.name", "posix"), \ + mock.patch.dict(os.environ, {"WINE": sys.executable}), \ + mock.patch("shutil.which", return_value=None): + make_game.preflight(["pipelines"], self.work, out=self.out) + + def test_posix_runtime_and_pipelines_requires_wine(self): + self.write_shader_index() + env = {k: v for k, v in os.environ.items() if k != "WINE"} + with mock.patch("os.name", "posix"), \ + mock.patch.dict(os.environ, env, clear=True), \ + mock.patch.object(make_game, "cross_build_missing", return_value=[]), \ + mock.patch.object(make_game, "cross_configure"), \ + mock.patch("shutil.which", side_effect=lambda t: None if t == "wine" else "/bin/tool"): + self.assert_preflight_fails(["runtime", "pipelines"], "Wine") def run_runtime_preflight(self, system, vulkan_sdk, runtime_build=None): with mock.patch("os.name", system), \ @@ -135,7 +162,7 @@ def run_runtime_preflight(self, system, vulkan_sdk, runtime_build=None): os.environ.pop("VULKAN_SDK", None) else: os.environ["VULKAN_SDK"] = vulkan_sdk - make_game.preflight(["runtime"], self.work, runtime_build=runtime_build) + make_game.preflight(["runtime"], self.work, runtime_build=runtime_build, out=self.out) return [call.args[0] for call in log.call_args_list] def test_runtime_without_vulkan_sdk_warns_that_the_vulkan_device_may_be_missing(self): @@ -162,141 +189,12 @@ def test_runtime_warning_is_skipped_for_a_prebuilt_runtime_and_other_systems(sel self.assertFalse([line for line in self.run_runtime_preflight("posix", None) if "VULKAN_SDK" in line]) - def test_missing_checker_is_listed_with_other_missing_prerequisites(self): + def test_missing_exe_is_listed_with_other_missing_prerequisites(self): with mock.patch("os.name", "nt"), \ - mock.patch("shutil.which", side_effect=lambda t: None if t == "llvm-mc" else "/bin/tool"), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value=None): - err = self.assert_preflight_fails(["shaders", "pipelines"], "vk_pipeline_check") + mock.patch("shutil.which", side_effect=lambda t: None if t == "llvm-mc" else "/bin/tool"): + err = self.assert_preflight_fails(["shaders", "pipelines"], "gta6rt.exe") self.assertIn("llvm-mc (LLVM 21+ with the AMDGPU target)", err) - self.assertEqual(err.count("vk_pipeline_check"), 1) - - - -class LinuxPipelineCheckTest(PreflightEnv, unittest.TestCase): - """Off Windows preflight builds the checker itself once every other prerequisite is there.""" - - def setUp(self): - super().setUp() - for patcher in (mock.patch("os.name", "posix"), - mock.patch.object(make_game, "pipeline_check_exe", return_value=None)): - patcher.start() - self.addCleanup(patcher.stop) - - def test_missing_shader_index_stops_before_building_checker(self): - with mock.patch.object(make_game, "pipeline_check_exe", side_effect=[None, None, "/bin/vk_pipeline_check"]), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - self.assert_preflight_fails(["pipelines"], "No translated shaders yet") - build.assert_not_called() - - def test_builds_the_checker_after_the_checks(self): - self.write_shader_index() - with mock.patch.object(make_game, "pipeline_check_exe", side_effect=[None, None, "/bin/vk_pipeline_check"]), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - make_game.preflight(["pipelines"], self.work, jobs=3) - build.assert_called_once_with(3) - - def test_a_checker_built_where_it_isnt_looked_for_fails_in_preflight(self): - with mock.patch.object(make_game, "build_pipeline_check") as build: - self.assert_preflight_fails(["shaders", "pipelines"], "delete runtime/build/linux") - build.assert_called_once() - - def test_missing_built_checker_does_not_initialize_asset_submodule(self): - with mock.patch.object(make_game, "dotnet_sdk_ok", return_value=True), \ - mock.patch.object(make_game, "build_pipeline_check") as build, \ - mock.patch.object(make_game, "ensure_submodule") as initialize: - self.assert_preflight_fails(["shaders", "assets", "pipelines"], "delete runtime/build/linux") - build.assert_called_once() - initialize.assert_not_called() - - def test_without_cmake_nothing_is_built(self): - with mock.patch("shutil.which", side_effect=lambda t: None if t == "cmake" else "/bin/tool"), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - err = self.assert_preflight_fails(["pipelines"], "CMake 3.24 or newer") - self.assertIn("vk_pipeline_check", err) - build.assert_not_called() - - def test_another_missing_prerequisite_stops_before_the_build(self): - with mock.patch("shutil.which", side_effect=lambda t: None if t == "llvm-mc" else "/bin/tool"), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - self.assert_preflight_fails(["shaders", "pipelines"], "llvm-mc") - build.assert_not_called() - - def test_a_built_checker_is_not_rebuilt(self): - self.write_shader_index() - with mock.patch.object(make_game, "pipeline_check_exe", return_value="/bin/vk_pipeline_check"), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - make_game.preflight(["pipelines"], self.work) - build.assert_not_called() - - def put_checker_older_than_its_source(self): - """runtime/build/linux/vk_pipeline_check built before its source last changed (a pull since the build).""" - build = os.path.join(self.root, "runtime", "build", "linux") - test = os.path.join(self.root, "runtime", "test") - os.makedirs(build) - os.makedirs(test) - checker = os.path.join(build, "vk_pipeline_check") - for path, text in ((checker, ""), (os.path.join(test, "vk_pipeline_check.cpp"), '#include "gate.h"\n'), - (os.path.join(test, "gate.h"), "")): - with open(path, "w", encoding="utf-8") as f: - f.write(text) - os.utime(checker, (1_000_000, 1_000_000)) - os.utime(os.path.join(test, "vk_pipeline_check.cpp"), (500_000, 500_000)) - return checker - - def test_a_checker_older_than_its_sources_is_rebuilt(self): - # Old #7148: a checker from before a pull was taken as it was, and the stage checked with the old program. - self.write_shader_index() - checker = self.put_checker_older_than_its_source() - with mock.patch.object(make_game, "ROOT", self.root), mock.patch.object(make_game, "pipeline_check_exe", return_value=checker), mock.patch.object(make_game, "build_pipeline_check") as build: - self.assertEqual(make_game.stale_checker(checker), ["runtime/test/gate.h"]) - make_game.preflight(["pipelines"], self.work, jobs=4) - build.assert_called_once_with(4) - - def test_a_current_checker_in_the_build_folder_is_not_rebuilt(self): - self.write_shader_index() - checker = self.put_checker_older_than_its_source() - future = os.path.getmtime(os.path.join(self.root, "runtime", "test", "gate.h")) + 60 - os.utime(checker, (future, future)) - with mock.patch.object(make_game, "ROOT", self.root), mock.patch.object(make_game, "pipeline_check_exe", return_value=checker), mock.patch.object(make_game, "build_pipeline_check") as build: - self.assertEqual(make_game.stale_checker(checker), []) - make_game.preflight(["pipelines"], self.work) - build.assert_not_called() - - def test_a_stale_checker_without_cmake_is_used_with_a_warning(self): - self.write_shader_index() - checker = self.put_checker_older_than_its_source() - with mock.patch.object(make_game, "ROOT", self.root), mock.patch("shutil.which", side_effect=lambda t: None if t == "cmake" else "/bin/tool"), mock.patch.object(make_game, "pipeline_check_exe", return_value=checker), mock.patch.object(make_game, "build_pipeline_check") as build: - make_game.preflight(["pipelines"], self.work) - build.assert_not_called() - with mock.patch.object(make_game, "log") as log, mock.patch.object(make_game, "checker_supports", side_effect=SystemExit(0)): - with self.assertRaises(SystemExit): - make_game.pipelines(self.work, os.path.join(self.root, "out")) - warning = log.call_args_list[0].args[0] - self.assertIn("WARNING", warning) - self.assertIn("runtime/test/gate.h", warning) - self.assertIn("cmake --build runtime/build/linux --target vk_pipeline_check", warning) - - def test_a_checker_outside_the_build_folder_is_not_compared(self): - # --runtime-build and the like: their time stamps say nothing about this checkout's sources. - self.put_checker_older_than_its_source() - elsewhere = os.path.join(self.root, "elsewhere", "vk_pipeline_check") - os.makedirs(os.path.dirname(elsewhere)) - with open(elsewhere, "w", encoding="utf-8"): - pass - os.utime(elsewhere, (1_000_000, 1_000_000)) - with mock.patch.object(make_game, "ROOT", self.root): - self.assertEqual(make_game.stale_checker(elsewhere), []) - - def test_the_build_uses_the_readme_folder(self): - with mock.patch.object(make_game, "ROOT", self.root), \ - mock.patch.object(make_game, "log"), \ - mock.patch.object(make_game, "run") as run: - make_game.build_pipeline_check(2) - configure, build = (c.args[0] for c in run.call_args_list) - folder = os.path.join(self.root, "runtime", "build", "linux") - self.assertEqual(configure[:5], ["cmake", "-S", os.path.join(self.root, "runtime"), "-B", folder]) - self.assertEqual(build, ["cmake", "--build", folder, "--parallel", "2", "--target", "vk_pipeline_check"]) - self.assertIn("Vulkan headers", run.call_args_list[1].kwargs["hint"]) + self.assertEqual(err.count("gta6rt.exe"), 1) if __name__ == "__main__": diff --git a/tests/test_make_game_pipelines.py b/tests/test_make_game_pipelines.py index e0f15ba6fc..a809456880 100644 --- a/tests/test_make_game_pipelines.py +++ b/tests/test_make_game_pipelines.py @@ -1,367 +1,393 @@ -"""make_game.py: vk_pipeline_check selection and arguments in the pipelines stage. +"""make_game.py: gta6rt --precompile-pipelines invocation, progress, env and crash handling. -Standard library only; no GPU, no Vulkan SDK, no game data: the checker is mocked. + python -I tests/test_make_game_pipelines.py + +Standard library only; no GPU, no Vulkan SDK, no Wine, no game data: uses a small Python script +as a fake gta6rt executed via sys.executable. """ +import hashlib import io import json import os import sys import tempfile +import textwrap import unittest from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) import make_game # noqa: E402 -class PipelinesJobsTest(unittest.TestCase): +FAKE_GTA6RT = textwrap.dedent("""\ + import json, os, sys + + state_file = os.environ["FAKE_STATE"] + plan = json.loads(os.environ["FAKE_PLAN"]) + if os.path.isfile(state_file): + with open(state_file, encoding="utf-8") as f: + state = json.load(f) + else: + state = {"calls": []} + + idx = len(state["calls"]) + state["calls"].append({ + "argv": sys.argv[1:], + "LEONIDA_SHADERS": os.environ.get("LEONIDA_SHADERS"), + "LEONIDA_PIPELINE_CACHE_DIR": os.environ.get("LEONIDA_PIPELINE_CACHE_DIR"), + "CUSTOM_PASSTHROUGH": os.environ.get("CUSTOM_PASSTHROUGH"), + }) + with open(state_file, "w", encoding="utf-8", newline="\\n") as f: + json.dump(state, f) + + step = plan[min(idx, len(plan) - 1)] + cache_root = os.environ.get("FAKE_CACHE_ROOT", "") + req_dir = os.path.join(cache_root, "pipeline_cache.d", "requests") if cache_root else "" + inflight_path = os.path.join(req_dir, "inflight.txt") if req_dir else "" + crashed_path = os.path.join(req_dir, "crashed.txt") if req_dir else "" + + # Mirror the runtime's crash recovery: stale inflight.txt -> append to crashed.txt and remove inflight.txt. + if inflight_path and os.path.isfile(inflight_path): + with open(inflight_path, encoding="utf-8") as f: + stale = [line.strip() for line in f if line.strip()] + os.remove(inflight_path) + if stale: + os.makedirs(req_dir, exist_ok=True) + with open(crashed_path, "a", encoding="utf-8", newline="\\n") as f: + for name in stale: + f.write(name + "\\n") + + if step.get("leave_inflight") and inflight_path: + os.makedirs(req_dir, exist_ok=True) + with open(inflight_path, "w", encoding="utf-8", newline="\\n") as f: + for name in step["leave_inflight"]: + f.write(name + "\\n") + + if step.get("write_crashed") and crashed_path: + os.makedirs(req_dir, exist_ok=True) + with open(crashed_path, "w", encoding="utf-8", newline="\\n") as f: + for name in step["write_crashed"]: + f.write(name + "\\n") + + for line in step.get("stderr", []): + print(line, file=sys.stderr, flush=True) + for line in step.get("stdout", []): + print(line, flush=True) + sys.exit(int(step.get("exit", 0))) +""") + + +class PipelinesRuntimeHelpersTest(unittest.TestCase): def setUp(self): tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) self.root = tmp.name - self.game = os.path.join(self.root, "game") - self.work = os.path.join(self.root, "work") - self.out = os.path.join(self.root, "out") - spirv = os.path.join(self.work, "shaders", "spirv") - os.makedirs(self.game) - os.makedirs(spirv) - with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8") as f: - f.write('{"shader_0": {}}') # a finished translation is never empty - - def checker_args(self, call): - with mock.patch.object(make_game, "pipeline_check_exe", return_value="vk_pipeline_check.exe"), \ - mock.patch.object(make_game, "run", return_value=0) as run, \ - mock.patch.object(make_game, "log", lambda *a: None): - call() - self.assertEqual(run.call_count, 1) - return [str(a) for a in run.call_args.args[0]] - - def jobs_of(self, args): - self.assertEqual(args.count("--jobs"), 1, args) - return args[args.index("--jobs") + 1] - - def main_with(self, *extra): - argv = ["make_game.py", "--game", self.game, "--work", self.work, "--out", self.out, - "--stages", "pipelines", "--no-tui", *extra] - with mock.patch.object(sys, "argv", argv), mock.patch.object(make_game, "below_normal"), \ - mock.patch.object(make_game, "check", return_value={"expected_exe": "g.exe"}), \ - mock.patch.object(make_game, "preflight"): - self.assertEqual(make_game.main(), 0) - - def test_the_stage_passes_its_jobs(self): - args = self.checker_args(lambda: make_game.pipelines(self.work, self.out, 7)) - self.assertEqual(self.jobs_of(args), "7") - self.assertEqual(args[1:3], [os.path.join(self.work, "shaders", "spirv"), - os.path.join(self.out, "pipeline_cache.bin")]) - - def test_jobs_on_the_command_line_reach_the_checker(self): - # main() clamps --jobs to the machine's hardware threads; pin them so 5 is in range anywhere (the - # GitHub Windows runners have 4). - with mock.patch.object(make_game.leonida_tui.os, "cpu_count", return_value=16): - self.assertEqual(self.jobs_of(self.checker_args(lambda: self.main_with("--jobs", "5"))), "5") - - def test_windows_reuses_the_checker_from_the_supplied_runtime_build(self): - supplied = os.path.join(self.root, "unpacked runtime") - os.makedirs(supplied) - checker = os.path.join(supplied, "vk_pipeline_check.exe") - for name in (*make_game.RUNTIME_FILES, "vk_pipeline_check.exe"): - with open(os.path.join(supplied, name), "wb"): - pass - argv = ["make_game.py", "--game", self.game, "--work", self.work, "--out", self.out, - "--stages", "runtime,pipelines", "--runtime-build", supplied, "--jobs", "3"] - # main() clamps --jobs to the hardware threads; pin them so 3 is in range anywhere (the - # GitHub Windows runners have 4, but a 2-vCPU machine would otherwise compare the clamped 2). - with mock.patch.object(make_game.leonida_tui.os, "cpu_count", return_value=16), \ - mock.patch.object(sys, "argv", argv), mock.patch.object(make_game, "ROOT", self.root), \ - mock.patch("os.name", "nt"), mock.patch.object(make_game, "below_normal"), \ - mock.patch.object(make_game, "check", return_value={"expected_exe": "g.exe"}), \ - mock.patch.object(make_game, "log"), mock.patch.object(make_game, "run") as run: - self.assertEqual(make_game.main(), 0) - run.assert_called_once() - self.assertEqual(run.call_args.args[0][0], checker) - self.assertEqual(self.jobs_of(run.call_args.args[0]), "3") - - def test_the_default_matches_the_checker_default(self): - # vk_pipeline_check's own default is half the hardware threads, as is make_game.py's --jobs. - want = str(max(1, (os.cpu_count() or 2) // 2)) - self.assertEqual(self.jobs_of(self.checker_args(lambda: self.main_with())), want) - - def test_the_stage_log_names_compute_and_graphics_pipelines(self): - # The stage runs vk_pipeline_check without --stage, and its default is all: cs become compute pipelines, - # ps/vs/ms/gs become graphics pipelines with partner stubs, so the announce line must not claim compute only. - logs = [] - with mock.patch.object(make_game, "pipeline_check_exe", return_value="vk_pipeline_check.exe"), \ - mock.patch.object(make_game, "checker_supports", return_value=False), \ - mock.patch.object(make_game, "run", return_value=0), \ - mock.patch.object(make_game, "log", logs.append): - make_game.pipelines(self.work, self.out) - announce = [m for m in logs if "creating" in m] - self.assertEqual(len(announce), 1, logs) - self.assertIn("graphics", announce[0]) - self.assertIn("compute", announce[0]) - - -ABORT = 0x80000003 # how Windows reports the driver's LLVM abort (#884) - - -class PipelinesCrashRetryTest(unittest.TestCase): - """A module that takes vk_pipeline_check down is skipped and the rest is checked; the checker is scripted.""" + def touch(self, *parts): + path = os.path.join(self.root, *parts) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb"): + pass + return path + + def test_runtime_exe_search_order_windows(self): + out = os.path.join(self.root, "out") + supplied = os.path.join(self.root, "supplied") + default_exe = self.touch("runtime", "build", "gta6rt.exe") + with mock.patch.object(make_game, "ROOT", self.root), mock.patch.object(make_game.os, "name", "nt"): + self.assertEqual(make_game.runtime_exe(out, supplied), default_exe) + supplied_exe = self.touch("supplied", "gta6rt.exe") + self.assertEqual(make_game.runtime_exe(out, supplied), supplied_exe) + out_exe = self.touch("out", "gta6rt.exe") + self.assertEqual(make_game.runtime_exe(out, supplied), out_exe) + + def test_runtime_exe_search_order_posix(self): + out = os.path.join(self.root, "out") + supplied = os.path.join(self.root, "supplied") + default_exe = self.touch("runtime", "build", "windows", "gta6rt.exe") + with mock.patch.object(make_game, "ROOT", self.root), mock.patch.object(make_game.os, "name", "posix"): + self.assertEqual(make_game.runtime_exe(out, supplied), default_exe) + supplied_exe = self.touch("supplied", "gta6rt.exe") + self.assertEqual(make_game.runtime_exe(out, supplied), supplied_exe) + out_exe = self.touch("out", "gta6rt.exe") + self.assertEqual(make_game.runtime_exe(out, supplied), out_exe) + + def test_precompile_command_windows_and_wine(self): + with mock.patch.object(make_game.os, "name", "nt"): + self.assertEqual( + make_game.precompile_command(r"C:\Port\gta6rt.exe", 6), + [r"C:\Port\gta6rt.exe", "--precompile-pipelines", "--threads", "6"], + ) + env = {k: v for k, v in os.environ.items() if k != "WINE"} + with mock.patch.object(make_game.os, "name", "posix"), mock.patch.dict(os.environ, env, clear=True): + self.assertEqual( + make_game.precompile_command("/port/gta6rt.exe", 4), + ["wine", "/port/gta6rt.exe", "--precompile-pipelines", "--threads", "4"], + ) + with mock.patch.object(make_game.os, "name", "posix"), \ + mock.patch.dict(os.environ, {"WINE": "/opt/proton/files/bin/wine"}): + self.assertEqual( + make_game.precompile_command("/port/gta6rt.exe", 4), + ["/opt/proton/files/bin/wine", "/port/gta6rt.exe", "--precompile-pipelines", "--threads", "4"], + ) + + def test_wine_path_conversion(self): + with mock.patch.object(make_game.os, "name", "posix"), \ + mock.patch.object(make_game.os.path, "abspath", return_value="/tmp/work/shaders/spirv"): + self.assertEqual(make_game.wine_path("ignored"), r"Z:\tmp\work\shaders\spirv") + with mock.patch.object(make_game.os, "name", "nt"), \ + mock.patch.object(make_game.os.path, "abspath", return_value=r"D:\work\shaders\spirv"): + self.assertEqual(make_game.wine_path("ignored"), r"D:\work\shaders\spirv") + + +class PipelinesStageTest(unittest.TestCase): def setUp(self): tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) - self.work = os.path.join(tmp.name, "work") - self.out = os.path.join(tmp.name, "out") + self.root = tmp.name + self.game = os.path.join(self.root, "game") + self.work = os.path.join(self.root, "work") + self.out = os.path.join(self.root, "out") self.spirv = os.path.join(self.work, "shaders", "spirv") + os.makedirs(self.game) os.makedirs(self.spirv) - with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8") as f: - f.write('{"b_mod": {}, "a_mod": {}, "c_mod": {}}') - self.inflight = os.path.join(self.out, "pipeline_inflight.txt") - self.skip = os.path.join(self.out, "pipeline_crashes.txt") - self.calls = [] - - def stage(self, script, supports=True): - """script(args, call_number) -> exit code; it may write the in-flight file first.""" - def fake_run(args, hint="", check=True, **kw): - args = [str(a) for a in args] - self.calls.append(args) - code = script(args, len(self.calls)) - if code in (0, 1) and "--inflight-file" in args: - # A native checker that finishes its shader pass clears this report, even on validation failure. - with open(args[args.index("--inflight-file") + 1], "w", encoding="utf-8", newline="\n") as f: - f.write("") - if check and code != 0: # as run() does - raise SystemExit(1) - return code + os.makedirs(self.out) + with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: + f.write('{"cs_a": {}, "cs_b": {}}\n') + self.fake_exe = os.path.join(self.out, "gta6rt.exe") + with open(self.fake_exe, "w", encoding="utf-8", newline="\n") as f: + f.write(FAKE_GTA6RT) + self.state_file = os.path.join(self.root, "state.json") + + def run_stage(self, plan, *, jobs=4, env_extra=None, os_name=None, runtime_build=None, board=None): + env = {k: v for k, v in os.environ.items() + if k not in ("LEONIDA_SHADERS", "LEONIDA_PIPELINE_CACHE_DIR", "WINE")} + env["FAKE_STATE"] = self.state_file + env["FAKE_PLAN"] = json.dumps(plan) + env["FAKE_CACHE_ROOT"] = self.out + env["CUSTOM_PASSTHROUGH"] = "keep-me" + if env_extra: + env.update(env_extra) logs = [] - with mock.patch.object(make_game, "pipeline_check_exe", return_value="vk_pipeline_check.exe"), \ - mock.patch.object(make_game, "checker_supports", return_value=supports), \ - mock.patch.object(make_game, "run", side_effect=fake_run), \ - mock.patch.object(make_game, "log", logs.append): + stderr = io.StringIO() + + def fake_cmd(exe, threads): + return [sys.executable, exe, "--precompile-pipelines", "--threads", str(threads)] + + patches = [ + mock.patch.dict(os.environ, env, clear=True), + mock.patch.object(make_game, "precompile_command", side_effect=fake_cmd), + mock.patch.object(make_game, "log", logs.append), + mock.patch("sys.stderr", stderr), + ] + if os_name is not None: + patches.append(mock.patch.object(make_game.os, "name", os_name)) + if board is not None: + patches.append(mock.patch.object(make_game.leonida_tui, "current_board", return_value=board)) + + with context_stack(patches): + exit_code = None try: - make_game.pipelines(self.work, self.out) - return None, logs - except SystemExit: - return sys.stderr, logs - - def inflight_is(self, *names): - """As vk_pipeline_check writes it: namephase, where a module can die in either phase.""" - with open(self.inflight, "w", encoding="utf-8") as f: - f.write("".join(f"{n}\t{'module' if i % 2 else 'pipeline'}\n" for i, n in enumerate(names))) - - def skipped(self, args): - return args[args.index("--skip-file") + 1] if "--skip-file" in args else None - - def is_probe(self, args): - return ("--count" in args and args[args.index("--count") + 1] == "1" - and "--jobs" in args and args[args.index("--jobs") + 1] == "1") - - def test_bom_marked_index_reaches_the_native_checker_and_preserves_range(self): - with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8-sig", newline="\n") as f: - f.write('{"b_mod": {}, "a_mod": {}, "c_mod": {}}') - failed, _ = self.stage(lambda args, n: 0) - self.assertIsNone(failed) - self.assertEqual(len(self.calls), 1) - self.assertEqual(self.calls[0][self.calls[0].index("--count") + 1], "3") - self.assertEqual(make_game.pipeline_names(self.spirv), ["a_mod", "b_mod", "c_mod"]) - - def test_a_named_module_is_skipped_and_the_rest_checked(self): - def script(args, n): - if self.is_probe(args): - self.inflight_is("b_mod") - return ABORT # it must reproduce alone before it is added to the crash list - if n == 1: - self.inflight_is("b_mod") - return ABORT - self.assertEqual(self.skipped(args), self.skip) - with open(self.skip, encoding="utf-8") as f: - self.assertEqual(f.read(), "b_mod\n") - return 1 # the skipped module counts as failed - err = io.StringIO() - with mock.patch("sys.stderr", err): - failed, logs = self.stage(script) - self.assertIsNotNone(failed) - self.assertEqual(len(self.calls), 3) - self.assertIn("--inflight-file", self.calls[0]) - self.assertIsNone(self.skipped(self.calls[0])) - self.assertTrue(any("b_mod took vk_pipeline_check down" in m and "0x80000003" in m for m in logs), logs) - self.assertIn("1 module(s) took the driver down", err.getvalue()) - self.assertIn("b_mod", err.getvalue()) - self.assertFalse(os.path.exists(self.inflight)) - - def test_several_in_flight_are_tried_alone_and_only_the_crasher_is_skipped(self): - def script(args, n): - if self.is_probe(args): # the global index is name-sorted, so a_mod=0, b_mod=1, c_mod=2 - self.assertEqual(args[args.index("--count") + 1], "1") - if args[args.index("--start") + 1] == "2": - self.inflight_is("c_mod") - return ABORT if args[args.index("--start") + 1] == "2" else 0 - if n == 1: - self.inflight_is("a_mod", "c_mod") - return ABORT - with open(self.skip, encoding="utf-8") as f: - self.assertEqual(f.read(), "c_mod\n") - return 1 - with mock.patch("sys.stderr", io.StringIO()): - failed, _ = self.stage(script) - self.assertIsNotNone(failed) - starts = [c[c.index("--start") + 1] for c in self.calls if self.is_probe(c)] - self.assertEqual(starts, ["0", "2"]) - - def test_a_crash_with_nothing_in_flight_stops_after_reaching_one_entry(self): - err = io.StringIO() - with mock.patch("sys.stderr", err): - failed, _ = self.stage(lambda args, n: ABORT) - self.assertIsNotNone(failed) - self.assertEqual(len(self.calls), 2) # range of 3, then its first single-entry subrange - self.assertIn("no module could be named", err.getvalue()) - - def test_ctrl_c_is_not_retried(self): - def script(args, n): - self.inflight_is("b_mod") - return 0xC000013A - with mock.patch("sys.stderr", io.StringIO()): - failed, _ = self.stage(script) - self.assertIsNotNone(failed) - self.assertEqual(len(self.calls), 1) - - def test_the_retries_stop(self): - all_names = [f"m{i}" for i in range(20)] - with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({name: {} for name in all_names}, f) - names = iter(all_names) - def script(args, n): - if self.is_probe(args): - self.inflight_is(sorted(all_names)[int(args[args.index("--start") + 1])]) - return ABORT - self.inflight_is(next(names)) - return ABORT - err = io.StringIO() - with mock.patch("sys.stderr", err): - failed, _ = self.stage(script) - self.assertIsNotNone(failed) - self.assertEqual(len([c for c in self.calls if not self.is_probe(c)]), make_game.PIPELINE_CRASH_RETRIES + 1) - self.assertIn("still crashed after", err.getvalue()) - - def test_the_crash_report_names_the_module_and_its_spirv_hash(self): - blob = b"\x03\x02\x23\x07" - with open(os.path.join(self.spirv, "b_mod.spv"), "wb") as f: - f.write(blob) + make_game.pipelines(self.work, self.out, jobs, runtime_build=runtime_build) + except SystemExit as exc: + exit_code = exc.code + calls = [] + if os.path.isfile(self.state_file): + with open(self.state_file, encoding="utf-8") as f: + calls = json.load(f)["calls"] + return exit_code, calls, logs, stderr.getvalue() + + def test_args_env_progress_and_summary(self): + plan = [{ + "stderr": [ + "[precompile] 2 compute entries to build (0.1 MB of SPIR-V; 0 filtered out, 0 not buildable)", + "[precompile] 1/2 cs_a (128 B): compiled and journaled in 0.1 s (VkResult 0) | 1 compiled, 0 from a cache, 0 skipped, 0 failed; 0 s elapsed, ~0 s left by size", + "[precompile] 2/2 cs_b (128 B): compiled and journaled in 0.1 s (VkResult 0) | 2 compiled, 0 from a cache, 0 skipped, 0 failed; 0 s elapsed, ~0 s left by size", + "[precompile] done: 2 compiled, 0 from a cache, 0 journaled already, 0 failed, 0 not buildable, in 1 s", + ], + "exit": 0, + }] + fake_board = mock.Mock() + fake_board._stop = mock.Mock(is_set=mock.Mock(return_value=False)) + code, calls, logs, err = self.run_stage(plan, jobs=7, board=fake_board) + self.assertIsNone(code, err) + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0]["argv"], ["--precompile-pipelines", "--threads", "7"]) + self.assertEqual(calls[0]["LEONIDA_SHADERS"], make_game.wine_path(self.spirv)) + self.assertEqual(calls[0]["LEONIDA_PIPELINE_CACHE_DIR"], make_game.wine_path(self.out)) + self.assertEqual(calls[0]["CUSTOM_PASSTHROUGH"], "keep-me") + # Progress parsed 1/2 and 2/2, updated TUI summary, and logged the done summary line. + self.assertTrue(any("pipelines: 0/2 (0%)" in line for line in logs), logs) + self.assertTrue(any("pipelines: 2/2 (100%)" in line for line in logs), logs) + self.assertTrue(any("[precompile] done: 2 compiled" in line for line in logs), logs) + self.assertIn("pipelines: done", logs) + fake_board.set_summary.assert_any_call("pipelines: 1/2 (50%)") + fake_board.set_summary.assert_any_call("pipelines: 2/2 (100%)") + + @unittest.skipIf(os.name == "nt", "exercises POSIX WINE launcher path directly") + def test_posix_runs_via_wine_env_without_patching_command(self): + plan = [{ + "stderr": [ + "[precompile] 1/1 cs_a (64 B): compiled and journaled in 0.1 s (VkResult 0)", + "[precompile] done: 1 compiled, 0 from a cache, 0 journaled already, 0 failed, 0 not buildable, in 0 s", + ], + "exit": 0, + }] + env = {k: v for k, v in os.environ.items() if k not in ("LEONIDA_SHADERS", "LEONIDA_PIPELINE_CACHE_DIR")} + env.update({ + "WINE": sys.executable, + "FAKE_STATE": self.state_file, + "FAKE_PLAN": json.dumps(plan), + "FAKE_CACHE_ROOT": self.out, + }) + logs = [] + with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(make_game, "log", logs.append): + make_game.pipelines(self.work, self.out, 3) + with open(self.state_file, encoding="utf-8") as f: + calls = json.load(f)["calls"] + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0]["argv"], ["--precompile-pipelines", "--threads", "3"]) + self.assertEqual(calls[0]["LEONIDA_SHADERS"], "Z:" + os.path.abspath(self.spirv).replace("/", "\\")) + self.assertEqual(calls[0]["LEONIDA_PIPELINE_CACHE_DIR"], "Z:" + os.path.abspath(self.out).replace("/", "\\")) + + def test_user_set_shader_and_cache_env_are_preserved_and_logged(self): + plan = [{"stderr": ["[precompile] done: 0 compiled, 0 from a cache, 0 journaled already, 0 failed, 0 not buildable, in 0 s"], "exit": 0}] + custom_shaders = r"D:\custom\spirv" + custom_cache = r"D:\custom\cache" + code, calls, logs, err = self.run_stage( + plan, + env_extra={"LEONIDA_SHADERS": custom_shaders, "LEONIDA_PIPELINE_CACHE_DIR": custom_cache}, + ) + self.assertIsNone(code, err) + self.assertEqual(calls[0]["LEONIDA_SHADERS"], custom_shaders) + self.assertEqual(calls[0]["LEONIDA_PIPELINE_CACHE_DIR"], custom_cache) + self.assertTrue(any("LEONIDA_SHADERS" in line and custom_shaders in line for line in logs), logs) + self.assertTrue(any("LEONIDA_PIPELINE_CACHE_DIR" in line and custom_cache in line for line in logs), logs) + + def test_exit_2_logs_warning_and_completes_stage(self): + plan = [{ + "stderr": ["[precompile] done: 1 compiled, 0 from a cache, 0 journaled already, 1 failed, 0 not buildable, in 1 s"], + "exit": 2, + }] + code, calls, logs, err = self.run_stage(plan) + self.assertIsNone(code, err) + self.assertEqual(len(calls), 1) + self.assertTrue(any("WARNING" in line and "exit 2" in line for line in logs), logs) + self.assertIn("pipelines: done", logs) - def script(args, n): - if self.is_probe(args): - self.inflight_is("b_mod") - return ABORT - if n == 1: - self.inflight_is("b_mod") - return ABORT - return 1 + def test_exit_1_fails_stage_without_retrying(self): + plan = [{"stderr": ["[precompile] failed to create Vulkan device"], "exit": 1}] + code, calls, logs, err = self.run_stage(plan) + self.assertEqual(code, 1) + self.assertEqual(len(calls), 1) + self.assertIn("could not open the Vulkan device or shader library", err) + def test_interrupted_exit_does_not_retry(self): + # Use a direct mock on _run_precompile for exact negative/NT status codes on any platform. + logs = [] err = io.StringIO() - with mock.patch("sys.stderr", err): - failed, _ = self.stage(script) - self.assertIsNotNone(failed) - with open(os.path.join(self.out, "pipeline_crashes.json"), encoding="utf-8") as f: - doc = json.load(f) - self.assertEqual(doc, {"modules": [{"name": "b_mod", "spv_sha256": - __import__("hashlib").sha256(blob).hexdigest()}]}) - self.assertIn("pipeline_crashes.json", err.getvalue()) - - def test_the_crash_report_survives_a_range_that_cannot_name_a_module(self): - # A module was already named and recorded, then the driver aborts without naming - # another one. The give-up path must keep the report instead of skipping it. - blob = b"\x03\x02\x23\x07" - with open(os.path.join(self.spirv, "b_mod.spv"), "wb") as f: + with mock.patch.object(make_game, "wine_available", return_value=True), \ + mock.patch.object(make_game, "_run_precompile", return_value=0xC000013A) as run_mock, \ + mock.patch.object(make_game, "log", logs.append), \ + mock.patch("sys.stderr", err): + with self.assertRaises(SystemExit) as ctx: + make_game.pipelines(self.work, self.out, 2) + self.assertEqual(ctx.exception.code, 1) + self.assertEqual(run_mock.call_count, 1) + self.assertIn("interrupted", err.getvalue()) + + def test_crash_retries_and_writes_pipeline_crashes_json_from_crashed_txt(self): + lib_dir = os.path.join(self.spirv, "library") + os.makedirs(lib_dir) + blob = b"\x03\x02\x23\x07crash-spv" + with open(os.path.join(lib_dir, "lib_cs_00042.spv"), "wb") as f: f.write(blob) - named = [] - def script(args, n): - if self.is_probe(args): - self.inflight_is("b_mod") - return ABORT - if not named: - named.append(n) - self.inflight_is("b_mod") - return ABORT - - err = io.StringIO() - with mock.patch("sys.stderr", err): - failed, _ = self.stage(script) - self.assertIsNotNone(failed) - self.assertIn("no module could be named", err.getvalue()) + plan = [ + # The runtime writes " " (runtime/src/precompile_inflight.h); the stage reports the name. + {"leave_inflight": ["lib_cs_00042 0123456789abcdef"], "exit": 139}, + { + "stderr": ["[precompile] done: 1 compiled, 0 from a cache, 0 journaled already, 1 failed, 0 not buildable, in 1 s"], + "exit": 2, + }, + ] + code, calls, logs, err = self.run_stage(plan) + self.assertIsNone(code, err) + self.assertEqual(len(calls), 2) + self.assertTrue(any("crashed" in line and "retrying (1/" in line for line in logs), logs) + self.assertTrue(any("lib_cs_00042" in line and "pipeline_crashes.json" in line for line in logs), logs) + report = os.path.join(self.out, "pipeline_crashes.json") + with open(report, encoding="utf-8") as f: + doc = json.load(f) + self.assertEqual(doc, {"modules": [{"name": "lib_cs_00042", "spv_sha256": hashlib.sha256(blob).hexdigest()}]}) + # One warning for the crashed entry, not a second generic one for the same exit 2; it says how to retry. + warnings = [line for line in logs if "WARNING" in line] + self.assertEqual(len(warnings), 1, warnings) + self.assertIn("--all", warnings[0]) + + def test_exit_3_another_precompile_fails_with_its_own_message(self): + plan = [{"stderr": ["[precompile] another --precompile-pipelines is using X (error 32)"], "exit": 3}] + code, calls, logs, err = self.run_stage(plan) + self.assertEqual(code, 1) + self.assertEqual(len(calls), 1) + self.assertIn("another gta6rt --precompile-pipelines is using this pipeline journal", err) + self.assertNotIn("Vulkan device", err) + + def test_crash_stops_after_retry_limit(self): + plan = [{"leave_inflight": ["cs_bad"], "exit": 99}] + with mock.patch.object(make_game, "PIPELINE_CRASH_RETRIES", 2): + code, calls, logs, err = self.run_stage(plan) + self.assertEqual(code, 1) + self.assertEqual(len(calls), 3) # initial attempt + 2 retries + self.assertIn("still crashed after 2 retries", err) + # By attempt 2, attempt 1's inflight was moved to crashed.txt, so pipeline_crashes.json is written. with open(os.path.join(self.out, "pipeline_crashes.json"), encoding="utf-8") as f: doc = json.load(f) - self.assertEqual([m["name"] for m in doc["modules"]], ["b_mod"]) - self.assertEqual(doc["modules"][0]["spv_sha256"], - __import__("hashlib").sha256(blob).hexdigest()) - - def test_a_failed_crash_report_does_not_hide_the_checker_diagnostic(self): - # The report is best-effort: a path that cannot be written warns, then the normal - # checker failure still names the modules. - os.makedirs(os.path.join(self.out, "pipeline_crashes.json")) - - def script(args, n): - if self.is_probe(args): - self.inflight_is("b_mod") - return ABORT - if n == 1: - self.inflight_is("b_mod") - return ABORT - return 1 - - with mock.patch("sys.stderr", io.StringIO()): - err, logs = self.stage(script) - self.assertIsNotNone(err) - self.assertIn("vk_pipeline_check", err.getvalue()) - self.assertIn("b_mod", err.getvalue()) - self.assertTrue(any("cannot write pipeline_crashes.json" in line for line in logs)) - - def test_a_clean_run_drops_an_old_crash_report(self): - os.makedirs(self.out) + self.assertEqual([m["name"] for m in doc["modules"]], ["cs_bad"]) + + def test_clean_run_drops_stale_pipeline_crashes_json(self): report = os.path.join(self.out, "pipeline_crashes.json") - with open(report, "w", encoding="utf-8") as f: - f.write('{"modules": []}') - failed, _ = self.stage(lambda args, n: 0) - self.assertIsNone(failed) + with open(report, "w", encoding="utf-8", newline="\n") as f: + f.write('{"modules": []}\n') + code, _, _, err = self.run_stage([{"exit": 0}]) + self.assertIsNone(code, err) self.assertFalse(os.path.exists(report)) - def test_a_clean_run_is_one_call_and_an_old_skip_list_is_dropped(self): - os.makedirs(self.out) - with open(self.skip, "w", encoding="utf-8") as f: - f.write("b_mod\n") # from an earlier build: every module gets a fresh chance - failed, logs = self.stage(lambda args, n: 0) - self.assertIsNone(failed) - self.assertEqual(len(self.calls), 1) - self.assertIsNone(self.skipped(self.calls[0])) - self.assertFalse(os.path.exists(self.skip)) - self.assertIn("pipelines: done", logs) + def test_main_forwards_jobs_and_runtime_build(self): + supplied = os.path.join(self.root, "supplied") + os.makedirs(supplied) + for name in make_game.RUNTIME_FILES: + with open(os.path.join(supplied, name), "wb"): + pass + argv = ["make_game.py", "--game", self.game, "--work", self.work, "--out", self.out, + "--stages", "pipelines", "--runtime-build", supplied, "--jobs", "5", "--no-tui"] + with mock.patch.object(make_game.leonida_tui.os, "cpu_count", return_value=16), \ + mock.patch.object(sys, "argv", argv), \ + mock.patch.object(make_game, "below_normal"), \ + mock.patch.object(make_game, "check", return_value={"expected_exe": "g.exe"}), \ + mock.patch.object(make_game, "preflight"), \ + mock.patch.object(make_game, "log"), \ + mock.patch.object(make_game, "pipelines") as stage: + self.assertEqual(make_game.main(), 0) + stage.assert_called_once_with( + os.path.abspath(self.work), os.path.abspath(self.out), 5, runtime_build=os.path.abspath(supplied) + ) + + +class context_stack: + def __init__(self, patches): + self._patches = patches + def __enter__(self): + for p in self._patches: + p.start() - def test_an_older_checker_gets_the_old_invocation(self): - # Before --inflight-file the checker took unknown arguments as the cache path (it would write the cache into - # pipeline_inflight.txt), so an older build runs as before: one call, no new flags, a crash stops the stage. - def script(args, n): - self.inflight_is("b_mod") - return ABORT - with mock.patch("sys.stderr", io.StringIO()): - failed, logs = self.stage(script, supports=False) - self.assertIsNotNone(failed) - self.assertEqual(len(self.calls), 1) - self.assertNotIn("--inflight-file", self.calls[0]) - self.assertNotIn("--skip-file", self.calls[0]) - self.assertTrue(any("has no --inflight-file" in m for m in logs), logs) - - def test_support_is_read_from_the_usage_line(self): - new = "usage: vk_pipeline_check ... [--inflight-file F] [--skip-file F]\n" - old = "usage: vk_pipeline_check [cache.bin] [--jobs N] [--isolate [--isolate-batch N]]\n" - for usage, want in ((new, True), (old, False)): - done = mock.Mock(stdout="", stderr=usage, returncode=2) - with mock.patch.object(make_game.subprocess, "run", return_value=done) as sp: - self.assertEqual(make_game.checker_supports("vk.exe", "--inflight-file", "--skip-file"), want) - self.assertEqual(sp.call_args.args[0], ["vk.exe"]) # no arguments: usage only, no Vulkan - with mock.patch.object(make_game.subprocess, "run", side_effect=OSError("not an executable")): - self.assertFalse(make_game.checker_supports("vk.exe", "--inflight-file")) + def __exit__(self, *exc): + for p in reversed(self._patches): + p.stop() + return False if __name__ == "__main__": diff --git a/tests/test_make_game_platform.py b/tests/test_make_game_platform.py index 9da2133677..174ce26056 100644 --- a/tests/test_make_game_platform.py +++ b/tests/test_make_game_platform.py @@ -1,4 +1,4 @@ -"""Platform-specific build stages, runtime packaging and vk_pipeline_check discovery. +"""Platform-specific build stages, runtime packaging and gta6rt.exe discovery. python -I tests/test_make_game_platform.py @@ -36,6 +36,7 @@ def run_main(self, os_name, *args, lacking=("clang-cl",)): argv = ["make_game.py", "--game", self.game, "--out", os.path.join(self.tmp.name, "out"), "--no-tui", *args] mocks = {n: mock.MagicMock() for n in STAGE_FUNCS} with mock.patch.object(sys, "argv", argv), \ + mock.patch.object(make_game, "ROOT", self.tmp.name), \ mock.patch.object(make_game.os, "name", os_name), \ mock.patch.object(make_game, "cross_build_missing", return_value=list(lacking)), \ mock.patch.object(make_game, "below_normal"), \ @@ -46,10 +47,10 @@ def run_main(self, os_name, *args, lacking=("clang-cl",)): self.assertEqual(make_game.main(), 0) return preflight.call_args.args[0], {n: m.called for n, m in mocks.items()} - def test_default_stages_leave_runtime_out_off_windows_without_the_cross_build(self): + def test_default_stages_leave_runtime_and_pipelines_out_off_windows_without_the_cross_build(self): stages, ran = self.run_main("posix") - self.assertEqual(stages, ["check", "shaders", "assets", "pipelines"]) - self.assertEqual(ran, {"shaders": True, "assets": True, "runtime": False, "pipelines": True}) + self.assertEqual(stages, ["check", "shaders", "assets"]) + self.assertEqual(ran, {"shaders": True, "assets": True, "runtime": False, "pipelines": False}) def test_default_stages_keep_runtime_off_windows_with_the_cross_build(self): stages, ran = self.run_main("posix", lacking=()) @@ -486,11 +487,13 @@ def test_off_windows_copies_the_build_and_writes_a_wine_launcher(self): self.assertTrue(os.access(launcher, os.X_OK)) -class PipelineCheckExeTest(unittest.TestCase): +class RuntimeExeTest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.build = os.path.join(self.tmp.name, "runtime", "build") - os.makedirs(os.path.join(self.build, "linux")) + self.out = os.path.join(self.tmp.name, "out") + os.makedirs(os.path.join(self.build, "windows")) + os.makedirs(self.out) self.root = mock.patch.object(make_game, "ROOT", self.tmp.name) self.root.start() @@ -503,63 +506,57 @@ def touch(self, *parts): open(p, "w").close() return p - def exe(self, os_name, runtime_build=None): + def exe(self, os_name, out=None, runtime_build=None): with mock.patch.object(make_game.os, "name", os_name): - return make_game.pipeline_check_exe(runtime_build) - - def test_linux_prefers_the_readme_build_folder(self): - self.assertIsNone(self.exe("posix")) - plain = self.touch("vk_pipeline_check") - os.chmod(plain, 0o755) - self.assertEqual(self.exe("posix"), plain) - readme = self.touch("linux", "vk_pipeline_check") - os.chmod(readme, 0o755) - self.assertEqual(self.exe("posix"), readme) - - @unittest.skipUnless(os.name == "posix", "requires POSIX execute permissions") - def test_non_executable_linux_checker_does_not_hide_the_fallback(self): - preferred = self.touch("linux", "vk_pipeline_check") - os.chmod(preferred, 0o644) - fallback = self.touch("vk_pipeline_check") - os.chmod(fallback, 0o755) - self.assertEqual(self.exe("posix"), fallback) - - def test_windows_finds_only_the_exe(self): - self.touch("linux", "vk_pipeline_check") - self.assertIsNone(self.exe("nt")) - exe = self.touch("vk_pipeline_check.exe") - self.assertEqual(self.exe("nt"), exe) - - def test_windows_prefers_supplied_checker_and_falls_back_to_local_build(self): - local = self.touch("vk_pipeline_check.exe") + return make_game.runtime_exe(out, runtime_build) + + def test_posix_uses_cross_build_folder_and_prefers_out_then_runtime_build(self): + self.assertIsNone(self.exe("posix", self.out)) + cross = self.touch("windows", "gta6rt.exe") + self.assertEqual(self.exe("posix", self.out), cross) + with tempfile.TemporaryDirectory() as supplied: + bundled = os.path.join(supplied, "gta6rt.exe") + open(bundled, "wb").close() + self.assertEqual(self.exe("posix", self.out, supplied), bundled) + packaged = os.path.join(self.out, "gta6rt.exe") + open(packaged, "wb").close() + self.assertEqual(self.exe("posix", self.out, supplied), packaged) + + def test_windows_uses_runtime_build_folder_and_prefers_out_then_supplied(self): + self.touch("windows", "gta6rt.exe") + self.assertIsNone(self.exe("nt", self.out)) + local = self.touch("gta6rt.exe") + self.assertEqual(self.exe("nt", self.out), local) with tempfile.TemporaryDirectory() as supplied: - self.assertEqual(self.exe("nt", supplied), local) - bundled = os.path.join(supplied, "vk_pipeline_check.exe") - with open(bundled, "wb"): - pass - self.assertEqual(self.exe("nt", supplied), bundled) - - def test_pipelines_off_windows_runs_the_linux_build(self): - exe = self.touch("linux", "vk_pipeline_check") - os.chmod(exe, 0o755) - self.touch("vk_pipeline_check.exe") + self.assertEqual(self.exe("nt", self.out, supplied), local) + bundled = os.path.join(supplied, "gta6rt.exe") + open(bundled, "wb").close() + self.assertEqual(self.exe("nt", self.out, supplied), bundled) + packaged = os.path.join(self.out, "gta6rt.exe") + open(packaged, "wb").close() + self.assertEqual(self.exe("nt", self.out, supplied), packaged) + + def test_pipelines_off_windows_runs_gta6rt_under_wine(self): + exe = self.touch("windows", "gta6rt.exe") work = os.path.join(self.tmp.name, "work") os.makedirs(os.path.join(work, "shaders", "spirv")) with open(os.path.join(work, "shaders", "spirv", "index.json"), "w") as f: - f.write('{"shader_0": {}}') # a finished translation is never empty - out = os.path.join(self.tmp.name, "out") + f.write('{"shader_0": {}}') with mock.patch.object(make_game.os, "name", "posix"), \ + mock.patch.dict(os.environ, {"WINE": "/usr/bin/wine"}), \ + mock.patch.object(make_game, "wine_available", return_value=True), \ mock.patch.object(make_game, "log"), \ - mock.patch.object(make_game, "run", return_value=0) as run: - make_game.pipelines(work, out, runtime_build=self.build) - self.assertEqual(run.call_args.args[0][0], exe) + mock.patch.object(make_game, "_run_precompile", return_value=0) as run_pre: + make_game.pipelines(work, self.out, jobs=3) + self.assertEqual(run_pre.call_args.args[0], ["/usr/bin/wine", exe, "--precompile-pipelines", "--threads", "3"]) - def test_pipelines_off_windows_without_the_build_says_how_to_build_it(self): + def test_pipelines_off_windows_without_gta6rt_says_how_to_get_it(self): err = io.StringIO() with mock.patch.object(make_game.os, "name", "posix"), mock.patch("sys.stderr", err): with self.assertRaises(SystemExit): - make_game.pipelines(os.path.join(self.tmp.name, "work"), os.path.join(self.tmp.name, "out")) - self.assertIn("cmake -S runtime -B runtime/build/linux", err.getvalue()) + make_game.pipelines(os.path.join(self.tmp.name, "work"), self.out) + self.assertIn("gta6rt.exe was not found", err.getvalue()) + self.assertIn("--runtime-build", err.getvalue()) class RuntimeStageCopyTest(unittest.TestCase): diff --git a/tests/test_make_game_preflight.py b/tests/test_make_game_preflight.py index 8c816a09f3..977c3d259d 100644 --- a/tests/test_make_game_preflight.py +++ b/tests/test_make_game_preflight.py @@ -750,7 +750,7 @@ def test_low_disk_cli_suggests_a_working_stage_selection(self): visual_cpp_tools_ok=mock.Mock(return_value=True), cross_build_missing=mock.Mock(return_value=[]), cross_configure=mock.DEFAULT, - pipeline_check_exe=mock.Mock(return_value="vk_pipeline_check"), + runtime_exe=mock.Mock(return_value="gta6rt.exe"), assets_exported=mock.Mock(return_value=False), shader_outputs_reusable=mock.Mock(return_value=False), wave64_settings=mock.Mock(return_value=(False, False)), @@ -760,7 +760,8 @@ def test_low_disk_cli_suggests_a_working_stage_selection(self): assets=mock.DEFAULT, runtime=mock.DEFAULT, pipelines=mock.DEFAULT, - ) as stages, mock.patch("shutil.which", return_value="available-tool"), \ + ) as stages, mock.patch.dict(os.environ, {"VULKAN_SDK": "C:\\Vulkan"}), \ + mock.patch("shutil.which", return_value="available-tool"), \ mock.patch("shutil.disk_usage") as disk: argv = ["make_game.py", "--game", os.path.join(tmp, "input"), "--out", os.path.join(tmp, "out")] with mock.patch.object(sys, "argv", argv):