tests: add opt-in DXC compile cache for the Python shader checks #2349

Merged
tedin7 merged 11 commits from upstream-pr/2357 into main 2026-11-25 23:01:38 +00:00
tedin7 commented 2026-11-25 13:33:52 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T13:33:52Z.


Part of #448

What this unblocks: identical DXC compiles in the Python shader checks can be reused across ctest runs (dev, release and PR reruns), cutting the DXC share of WARP test time that #448 measured at about 19% of pixel_aot_warp.

What changes

  • New tools/dxc_cache.py with run_dxc(compiler, args, **options). It mirrors subprocess.run([compiler, *args]).
  • Opt-in only: active when X2W_DXC_CACHE=<dir> is set. Unset, every call is a plain subprocess.run, so CI and local runs behave exactly as before.
  • The key covers the compiler path, size and mtime, the DXC libraries next to it, the arguments (output paths replaced by tokens) and the source bytes.
  • Never cached: #include/#import in the source, -I, -Fi, response files (@file), unknown -F outputs, unknown file-like arguments, extra subprocess.run options.
  • Shell launchers that delegate to Wine (a #! script mentioning wine) bypass the cache, because the real compiler behind them cannot be fingerprinted.
  • Only successful compiles are stored. A failed compile always runs for real (it may be transient, for example a missing output directory), and a stored failure record is never replayed. check=True still raises.
  • Entries are written atomically (tempfile + os.replace), so parallel ctest jobs can share one directory.
  • tests/pixel_aot_check.py compile_shader calls run_dxc.
  • tests/compute_store_check.py routes only DXC-shaped subprocess.run calls (-T and -Fo present) through the cache with a small proxy, instead of editing its 44 call sites (many open PRs touch that file).
  • tests/dxc_cache_check.py uses a fake compiler: hit, miss on source/argument/mtime/library change, failures not cached, missing-output-directory retry, Wine launcher bypass, unset variable, include bypass. It runs in the Linux job of windows.yml.

Verification

Head 384f505d950ba46e09e3d8e0299da223156dc5d8.

Linux:

python3 -B tests/dxc_cache_check.py                       -> dxc_cache_check: ok
git diff --check                                          -> clean

CI on this head: all required jobs green.

Windows Server 2025 WARP at the same head (x2w_pipe.py win2025 2357 --regex '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --keep-release, default 5-slot pool), receipt comment posted on this PR:

cmake --build --preset dev -- -j 2
ctest --preset dev -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure   -> 2/2 passed
cmake --build --preset release -- -j 2
ctest --preset release -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure -> 2/2 passed

The planned Windows Python checks also passed (exit 0).

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6605671216 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T13:33:52Z. --- Part of #448 What this unblocks: identical DXC compiles in the Python shader checks can be reused across ctest runs (dev, release and PR reruns), cutting the DXC share of WARP test time that #448 measured at about 19% of `pixel_aot_warp`. ## What changes - New `tools/dxc_cache.py` with `run_dxc(compiler, args, **options)`. It mirrors `subprocess.run([compiler, *args])`. - Opt-in only: active when `X2W_DXC_CACHE=<dir>` is set. Unset, every call is a plain `subprocess.run`, so CI and local runs behave exactly as before. - The key covers the compiler path, size and mtime, the DXC libraries next to it, the arguments (output paths replaced by tokens) and the source bytes. - Never cached: `#include`/`#import` in the source, `-I`, `-Fi`, response files (`@file`), unknown `-F` outputs, unknown file-like arguments, extra `subprocess.run` options. - Shell launchers that delegate to Wine (a `#!` script mentioning `wine`) bypass the cache, because the real compiler behind them cannot be fingerprinted. - Only successful compiles are stored. A failed compile always runs for real (it may be transient, for example a missing output directory), and a stored failure record is never replayed. `check=True` still raises. - Entries are written atomically (`tempfile` + `os.replace`), so parallel ctest jobs can share one directory. - `tests/pixel_aot_check.py` `compile_shader` calls `run_dxc`. - `tests/compute_store_check.py` routes only DXC-shaped `subprocess.run` calls (`-T` and `-Fo` present) through the cache with a small proxy, instead of editing its 44 call sites (many open PRs touch that file). - `tests/dxc_cache_check.py` uses a fake compiler: hit, miss on source/argument/mtime/library change, failures not cached, missing-output-directory retry, Wine launcher bypass, unset variable, include bypass. It runs in the Linux job of `windows.yml`. ## Verification Head `384f505d950ba46e09e3d8e0299da223156dc5d8`. Linux: ``` python3 -B tests/dxc_cache_check.py -> dxc_cache_check: ok git diff --check -> clean ``` CI on this head: all required jobs green. Windows Server 2025 WARP at the same head (`x2w_pipe.py win2025 2357 --regex '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --keep-release`, default 5-slot pool), receipt comment posted on this PR: ``` cmake --build --preset dev -- -j 2 ctest --preset dev -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure -> 2/2 passed cmake --build --preset release -- -j 2 ctest --preset release -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure -> 2/2 passed ``` The planned Windows Python checks also passed (exit 0). AI-assisted; commands listed were executed locally.
RavenCurseBurg commented 2026-11-25 15:02:00 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by RavenCurseBurg on 2026-11-25T14:34:32Z.


One failed-compile case changes observable output files on Windows at 5a619a41. After a successful DXC compile to previous.cso (2,052 bytes), I compiled an invalid compute shader to two different output paths using DXC 1.9.2609, -T cs_6_0 -E main -Fo <output> bad.hlsl. All four error returns were 0x80004005.

Invocation Output before Output after
Direct DXC → previous.cso 2,052 bytes unchanged
Direct DXC → fresh.cso absent absent
Cache miss → previous.cso 2,052 bytes unchanged
Cache hit → fresh.cso absent 2,052 bytes copied from previous.cso

run_dxc collects every existing output on a miss, even if the failed invocation left an older file untouched. The replay then materializes unrelated bytecode at the new path. A regression control can seed an output with a successful shader, run a failing compile to that path, and repeat the same failure at an absent path. The fresh output should stay absent. A conservative fix could restrict failure caching to calls with initially absent outputs and replay a cached failure only under the same precondition.

For successful compiles I also ran tests/compute_store_check.py draw-mubuf-format on WARP and RTX 4060. For each adapter a disabled/cold cache launched DXC 8 times, while both warm passes launched it 0 times. All 12 shader-bytecode hashes presented to the renderer matched in order, with eight 320-word positive dispatches and all four wrong-channel controls. End-to-end times overlapped on the physical adapter.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7165487876 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#issuecomment-7165487876). Originally posted by [RavenCurseBurg](https://github.com/RavenCurseBurg) on 2026-11-25T14:34:32Z. --- One failed-compile case changes observable output files on Windows at `5a619a41`. After a successful DXC compile to `previous.cso` (2,052 bytes), I compiled an invalid compute shader to two different output paths using DXC 1.9.2609, `-T cs_6_0 -E main -Fo <output> bad.hlsl`. All four error returns were `0x80004005`. | Invocation | Output before | Output after | | --- | --- | --- | | Direct DXC → previous.cso | 2,052 bytes | unchanged | | Direct DXC → fresh.cso | absent | absent | | Cache miss → previous.cso | 2,052 bytes | unchanged | | Cache hit → fresh.cso | absent | **2,052 bytes copied from previous.cso** | `run_dxc` collects every existing output on a miss, even if the failed invocation left an older file untouched. The replay then materializes unrelated bytecode at the new path. A regression control can seed an output with a successful shader, run a failing compile to that path, and repeat the same failure at an absent path. The fresh output should stay absent. A conservative fix could restrict failure caching to calls with initially absent outputs and replay a cached failure only under the same precondition. For successful compiles I also ran `tests/compute_store_check.py draw-mubuf-format` on WARP and RTX 4060. For each adapter a disabled/cold cache launched DXC 8 times, while both warm passes launched it 0 times. All 12 shader-bytecode hashes presented to the renderer matched in order, with eight 320-word positive dispatches and all four wrong-channel controls. End-to-end times overlapped on the physical adapter.
tedin7 commented 2026-11-25 15:02:00 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T14:46:12Z.


Thanks @RavenCurseBurg, good catch. You were right: a failed compile was cached together with any output file that already existed, so a later hit with a new output path could copy old bytecode that direct DXC would never write.

What changed in tools/dxc_cache.py:

  • A failed compile is cached only when every output path was absent before the call.
  • A cached failure stores no output files, and a hit replays only the exit code, stdout and stderr.

New case in tests/dxc_cache_check.py (stub compiler): seed an output with a successful compile, run a failing compile to that path, then repeat the same failing compile to an absent path. The absent path must stay absent. It fails on the previous head and passes now.

Verification:

  • python3 -B tests/dxc_cache_check.py before the fix: failed compile replayed an output file the compiler never wrote
  • same command after the fix: dxc_cache_check: ok

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7165785982 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#issuecomment-7165785982). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T14:46:12Z. --- Thanks @RavenCurseBurg, good catch. You were right: a failed compile was cached together with any output file that already existed, so a later hit with a new output path could copy old bytecode that direct DXC would never write. What changed in `tools/dxc_cache.py`: - A failed compile is cached only when every output path was absent before the call. - A cached failure stores no output files, and a hit replays only the exit code, stdout and stderr. New case in `tests/dxc_cache_check.py` (stub compiler): seed an output with a successful compile, run a failing compile to that path, then repeat the same failing compile to an absent path. The absent path must stay absent. It fails on the previous head and passes now. Verification: - `python3 -B tests/dxc_cache_check.py` before the fix: `failed compile replayed an output file the compiler never wrote` - same command after the fix: `dxc_cache_check: ok` AI-assisted; commands listed were executed locally.
RavenCurseBurg commented 2026-11-25 15:02:01 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by RavenCurseBurg on 2026-11-25T14:53:03Z.


I reran the Windows DXC case at e0f7d479. A fresh cache now behaves correctly: the old output stays unchanged and a different output path stays absent. A second failing compile from the fresh cache replayed the diagnostic with zero extra compiler launches.

One upgrade case remains for a persistent X2W_DXC_CACHE. I populated a cache with the actual 5a619a41 implementation, then ran the exact same failing shader using e0f7d479 against that directory. The new implementation made zero compiler launches and wrote the old 2,052-byte shader to a previously absent output path. Both versions use key version 1; the read path still replays the nonempty files from the old failure record. Skipping output restoration for a nonzero cached return code would also protect existing directories while retaining successful entries. A key-version bump would also resolve this for users who keep their cache between builds.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7165964988 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#issuecomment-7165964988). Originally posted by [RavenCurseBurg](https://github.com/RavenCurseBurg) on 2026-11-25T14:53:03Z. --- I reran the Windows DXC case at `e0f7d479`. A fresh cache now behaves correctly: the old output stays unchanged and a different output path stays absent. A second failing compile from the fresh cache replayed the diagnostic with zero extra compiler launches. One upgrade case remains for a persistent `X2W_DXC_CACHE`. I populated a cache with the actual `5a619a41` implementation, then ran the exact same failing shader using `e0f7d479` against that directory. The new implementation made zero compiler launches and wrote the old 2,052-byte shader to a previously absent output path. Both versions use key version 1; the read path still replays the nonempty `files` from the old failure record. Skipping output restoration for a nonzero cached return code would also protect existing directories while retaining successful entries. A key-version bump would also resolve this for users who keep their cache between builds.
tedin7 commented 2026-11-25 16:05:22 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T15:05:01Z.


Thank you for rerunning the upgrade case. You were right: an existing cache directory could still replay output files from an old failure record.

What changed:

  • Read path: a cached record with a nonzero return code never writes output files. Only successful entries restore files.
  • KEY_VERSION is now 2, so records written by the old version are not found at all.

New checks in tests/dxc_cache_check.py:

  • Old failure record with non-empty files under the current key: the output path stays absent.
  • Old failure record under key version 1 with non-empty files: it is not reused, the compiler runs, and the output path stays absent.

Commands run (Linux):

  • python3 tests/dxc_cache_check.py before the change: fails ("cached failure with files restored an output file").
  • Same command with only the version bump reverted: fails ("a record from an older key version was reused").
  • Same command after the change: dxc_cache_check: ok.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7166275157 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#issuecomment-7166275157). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T15:05:01Z. --- Thank you for rerunning the upgrade case. You were right: an existing cache directory could still replay output files from an old failure record. What changed: - Read path: a cached record with a nonzero return code never writes output files. Only successful entries restore files. - `KEY_VERSION` is now `2`, so records written by the old version are not found at all. New checks in `tests/dxc_cache_check.py`: - Old failure record with non-empty `files` under the current key: the output path stays absent. - Old failure record under key version `1` with non-empty `files`: it is not reused, the compiler runs, and the output path stays absent. Commands run (Linux): - `python3 tests/dxc_cache_check.py` before the change: fails ("cached failure with files restored an output file"). - Same command with only the version bump reverted: fails ("a record from an older key version was reused"). - Same command after the change: `dxc_cache_check: ok`. AI-assisted; commands listed were executed locally.
RavenCurseBurg commented 2026-11-25 16:05:22 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by RavenCurseBurg on 2026-11-25T15:07:40Z.


Confirmed on fdec33c4 with DXC 1.9.2609 on Windows. Using the same persistent directory written by 5a619a41 (an actual failure record containing 2,052 bytes under -Fo), the new head launched DXC once, returned the original 0x80004005, and left the fresh output absent. A second identical failure in a fresh v2 cache used zero additional compiler launches and still left its output absent. The original pre-existing-output check also passed.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7166345455 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#issuecomment-7166345455). Originally posted by [RavenCurseBurg](https://github.com/RavenCurseBurg) on 2026-11-25T15:07:40Z. --- Confirmed on `fdec33c4` with DXC 1.9.2609 on Windows. Using the same persistent directory written by `5a619a41` (an actual failure record containing 2,052 bytes under `-Fo`), the new head launched DXC once, returned the original `0x80004005`, and left the fresh output absent. A second identical failure in a fresh v2 cache used zero additional compiler launches and still left its output absent. The original pre-existing-output check also passed.
tedin7 commented 2026-11-25 16:05:23 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T15:12:37Z.


Thanks for confirming on fdec33c4 with a real cache written by 5a619a41, and for the upgrade case that led to the key-version bump. No further changes planned for this cache slice unless you see another case.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7166476946 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#issuecomment-7166476946). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T15:12:37Z. --- Thanks for confirming on `fdec33c4` with a real cache written by `5a619a41`, and for the upgrade case that led to the key-version bump. No further changes planned for this cache slice unless you see another case. AI-assisted; commands listed were executed locally.
chatgpt-codex-connector[bot commented 2026-11-25 22:01:54 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-25T21:55:46Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: da1e52d17a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6065525527 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#pullrequestreview-6065525527). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-25T21:55:46Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `da1e52d17a` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". </details>
tedin7 commented 2026-11-25 22:02:17 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T21:13:02Z.


Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit 9beb7e19c71a68bfc965e82643c8b5cc13d9aafb:

  • Windows Python checks: tests/compute_alu_bcnt64_check.py ok (0.6s), tests/compute_alu_cmp_ne_check.py ok (0.5s), tests/compute_alu_lane_gaps_check.py ok (0.6s), tests/compute_entry_layout_check.py ok (0.2s), tests/compute_heap_store_check.py ok (0.6s), tests/compute_heap_view_check.py ok (0.6s), tests/compute_load_format_check.py ok (0.6s), tests/form_coverage_check.py ok (11.7s), tests/mesh_clip_cull_check.py ok (4.5s), tests/mesh_heap_sampler_check.py ok (0.8s), tests/pso_readiness_check.py ok (1.1s), tests/rdna2_tools_check.py ok (2.6s), tests/vk_offscreen.py ok (1.2s)
  • sccache: -37/-38 hits; wall 37.9s

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7174769595 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#issuecomment-7174769595). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T21:13:02Z. --- Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit `9beb7e19c71a68bfc965e82643c8b5cc13d9aafb`: - **Windows Python checks**: `tests/compute_alu_bcnt64_check.py` ok (`0.6s`), `tests/compute_alu_cmp_ne_check.py` ok (`0.5s`), `tests/compute_alu_lane_gaps_check.py` ok (`0.6s`), `tests/compute_entry_layout_check.py` ok (`0.2s`), `tests/compute_heap_store_check.py` ok (`0.6s`), `tests/compute_heap_view_check.py` ok (`0.6s`), `tests/compute_load_format_check.py` ok (`0.6s`), `tests/form_coverage_check.py` ok (`11.7s`), `tests/mesh_clip_cull_check.py` ok (`4.5s`), `tests/mesh_heap_sampler_check.py` ok (`0.8s`), `tests/pso_readiness_check.py` ok (`1.1s`), `tests/rdna2_tools_check.py` ok (`2.6s`), `tests/vk_offscreen.py` ok (`1.2s`) - `sccache`: -37/-38 hits; wall `37.9s` AI-assisted; commands listed were executed locally.
tedin7 commented 2026-11-25 22:02:22 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T21:50:07Z.


Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit da1e52d17a5da826506fbac1372be6ea7869bf36:

  • Debug (--preset dev):
    • Build (cmake --build --preset dev -- -j 2): 102.23s (configure 3.17s)
    • Test (ctest --preset dev -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure): 2/2 passed (16.71s: pixel_aot_warp 14.56s, compute_store_aot_heap_view_load_warp 16.53s)
  • Release /O2 (--preset release):
    • Build (cmake --build --preset release -- -j 2): 143.35s (configure 3.54s)
    • Test (ctest --preset release -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure): 2/2 passed (24.19s: pixel_aot_warp 19.96s, compute_store_aot_heap_view_load_warp 23.92s)
  • Windows Python checks: tests/compute_alu_bcnt64_check.py ok (1.0s), tests/compute_alu_cmp_ne_check.py ok (0.8s), tests/compute_alu_lane_gaps_check.py ok (0.8s), tests/compute_buffer_atomics_check.py ok (0.8s), tests/compute_entry_layout_check.py ok (0.2s), tests/compute_heap_store_check.py ok (0.8s), tests/compute_heap_view_check.py ok (0.8s), tests/compute_load_format_check.py ok (0.8s), tests/form_coverage_check.py ok (16.0s), tests/mesh_clip_cull_check.py ok (6.6s), tests/mesh_heap_sampler_check.py ok (1.0s), tests/pso_readiness_check.py ok (1.3s), tests/rdna2_tools_check.py ok (3.8s), tests/vk_offscreen.py ok (2.0s)
  • sccache: 74/401 hits; wall 330.0s

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7175598763 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#issuecomment-7175598763). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T21:50:07Z. --- Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit `da1e52d17a5da826506fbac1372be6ea7869bf36`: - **Debug (`--preset dev`)**: - Build (`cmake --build --preset dev -- -j 2`): `102.23s` (configure `3.17s`) - Test (`ctest --preset dev -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure`): **2/2 passed** (`16.71s`: `pixel_aot_warp` `14.56s`, `compute_store_aot_heap_view_load_warp` `16.53s`) - **Release `/O2` (`--preset release`)**: - Build (`cmake --build --preset release -- -j 2`): `143.35s` (configure `3.54s`) - Test (`ctest --preset release -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure`): **2/2 passed** (`24.19s`: `pixel_aot_warp` `19.96s`, `compute_store_aot_heap_view_load_warp` `23.92s`) - **Windows Python checks**: `tests/compute_alu_bcnt64_check.py` ok (`1.0s`), `tests/compute_alu_cmp_ne_check.py` ok (`0.8s`), `tests/compute_alu_lane_gaps_check.py` ok (`0.8s`), `tests/compute_buffer_atomics_check.py` ok (`0.8s`), `tests/compute_entry_layout_check.py` ok (`0.2s`), `tests/compute_heap_store_check.py` ok (`0.8s`), `tests/compute_heap_view_check.py` ok (`0.8s`), `tests/compute_load_format_check.py` ok (`0.8s`), `tests/form_coverage_check.py` ok (`16.0s`), `tests/mesh_clip_cull_check.py` ok (`6.6s`), `tests/mesh_heap_sampler_check.py` ok (`1.0s`), `tests/pso_readiness_check.py` ok (`1.3s`), `tests/rdna2_tools_check.py` ok (`3.8s`), `tests/vk_offscreen.py` ok (`2.0s`) - `sccache`: 74/401 hits; wall `330.0s` AI-assisted; commands listed were executed locally.
chatgpt-codex-connector[bot commented 2026-11-25 22:02:23 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-25T21:50:25Z.


Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T21:55:48.679149Z da1e52d Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7175605056 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#issuecomment-7175605056). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-25T21:50:25Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"da1e52d17a5da826506fbac1372be6ea7869bf36","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-25T21:55:48.679149Z">2026-11-25T21:55:48.679149Z</relative-time> | `da1e52d` | Draft marked ready | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review" or "@codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
chatgpt-codex-connector[bot commented 2026-11-25 22:02:24 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-25T21:55:46Z.

Code review location: tools/dxc_cache.py; line 153

@@ -0,0 +1,227 @@
+"""Opt-in content-addressed cache for DXC compiles in the Python shader tests.
+
+Active only when the environment variable X2W_DXC_CACHE names a directory.
+Unset, run_dxc is a plain subprocess.run. Anything the cache cannot reason
+about (includes, -I, response files, unknown -F outputs, extra run options)
+bypasses it, so a cached result is never reused for a different compile.
+"""
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+ENV_VAR = "X2W_DXC_CACHE"
+OUTPUT_FLAGS = ("-Fo", "-Fc", "-Fh", "-Fre", "-Fd")
+SUPPORTED_KWARGS = {"check", "capture_output", "text", "timeout"}
+INCLUDE_RE = re.compile(rb"#\s*(include|import)\b|@import")
+KEY_VERSION = "2"
+
+
+def _plan(compiler, args):
+    """Return (key_args, input_path, outputs) or None when the compile is not cacheable."""
+    args = [str(a) for a in args]
+    if not args:
+        return None
+    source = args[-1]
+    if source.startswith("-") or not os.path.isfile(source):
+        return None
+    key_args = []
+    outputs = {}
+    for index, arg in enumerate(args[:-1]):
+        if arg.startswith("@") or arg.startswith("-I") or arg.startswith("-Fi"):
+            return None
+        if arg.startswith("-F") and arg not in OUTPUT_FLAGS:
+            return None
+        if index > 0 and args[index - 1] in OUTPUT_FLAGS:
+            continue  # output path value, handled with its flag
+        if arg in OUTPUT_FLAGS:
+            if index + 1 >= len(args) - 1:
+                return None
+            path = args[index + 1]
+            if path.endswith(("/", "\\")) or os.path.isdir(path) or path in outputs.values() or path == source:
+                return None
+            outputs[arg] = path
+            key_args.append(arg)
+            key_args.append("<out:%s>" % arg)
+        elif os.path.exists(arg):
+            return None  # unknown file-like argument
+        else:
+            key_args.append(arg)
+    if not outputs:
+        return None
+    return key_args + ["<in>"], source, outputs
+
+
+def _scrub(data, mapping):
+    for text, token in mapping:
+        data = data.replace(text.encode(), token.encode())
+    return data
+
+
+def _restore(data, mapping):
+    for text, token in mapping:
+        data = data.replace(token.encode(), text.encode())
+    return data
+
+
+def _store(path, payload):
+    handle, temp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-")
+    try:
+        with os.fdopen(handle, "wb") as out:
+            out.write(payload)
+        os.replace(temp, path)
+    except BaseException:
+        if os.path.exists(temp):
+            os.unlink(temp)
+        raise
+
+
+def _write_file(path, data):
+    _store_dir = os.path.dirname(os.path.abspath(path))
+    os.makedirs(_store_dir, exist_ok=True)
+    with open(path, "wb") as out:
+        out.write(data)
+
+
+def _emit(result_bytes, text, stream):
+    stream.write(result_bytes.decode(errors="replace") if text else result_bytes)  # pragma: no cover
+    stream.flush()
+
+
+def _passthrough(options, check):
+    """Keyword arguments exactly as the caller gave them (check only when given)."""
+    return dict(options, check=check) if check is not None else dict(options)
+
+
+def _resolve(compiler):
+    """Absolute path of the compiler (a file, else found on PATH), or None when it is neither."""
+    name = os.fspath(compiler)
+    if os.path.isfile(name):
+        return os.path.abspath(name)
+    found = shutil.which(name)
+    return os.path.abspath(found) if found else None
+
+
+COMPILER_LIBRARIES = ("dxcompiler.dll", "dxil.dll", "libdxcompiler.so", "libdxil.so")
+
+
+def _libraries(resolved):
+    """Name, size and mtime of the DXC libraries next to the compiler (missing ones are skipped)."""
+    folder = os.path.dirname(resolved)
+    found = []
+    for name in COMPILER_LIBRARIES:
+        try:
+            info = os.stat(os.path.join(folder, name))
+        except OSError:
+            continue
+        found.append([name, info.st_size, info.st_mtime_ns])
+    return found
+
+
+def run_dxc(compiler, args, **options):
+    """Mirror subprocess.run([compiler, *args]) with an optional on-disk cache."""
+    command = [compiler, *args]
+    check = options.pop("check", None)
+    capture_output = options.get("capture_output", False)
+    text = options.get("text", False)
+    timeout = options.get("timeout")
+    extra = {k: v for k, v in options.items() if k not in SUPPORTED_KWARGS}
+    cache_dir = os.environ.get(ENV_VAR)
+    plan = None
+    resolved = None
+    if cache_dir and not extra:
+        resolved = _resolve(compiler)
+        if resolved is not None:
+            plan = _plan(compiler, args)
+    if plan is None:
+        return subprocess.run(command, **_passthrough(options, check))
+    key_args, source, outputs = plan
+    with open(source, "rb") as handle:
+        source_bytes = handle.read()
+    if INCLUDE_RE.search(source_bytes):
+        return subprocess.run(command, **_passthrough(options, check))
+    try:
+        info = os.stat(resolved)
+    except OSError:
+        return subprocess.run(command, **_passthrough(options, check))
+    digest = hashlib.sha256()
+    digest.update(json.dumps([KEY_VERSION, resolved, info.st_size, info.st_mtime_ns,
+                              _libraries(resolved), key_args]).encode())

P2 Badge Fingerprint the actual compiler behind the Wine launcher

With caching enabled in the documented Wine setup (docs/non-windows-hosts.md:236-248), _resolve() identifies the shell launcher, while its exec wine "$DXC" runs an SDK compiler in another directory. This key therefore fingerprints the launcher and probes its adjacent libraries, not the actual dxc.exe or DLLs. Updating the SDK files at the same path leaves the key unchanged and replays old shader binaries, so the checks can validate stale results against an updated toolchain. Fingerprint the delegated compiler and its libraries, or bypass caching for launchers whose compiler identity cannot be established.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4701330327 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#discussion_r4701330327). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-25T21:55:46Z. **Code review location:** `tools/dxc_cache.py`; line 153 ~~~~diff @@ -0,0 +1,227 @@ +"""Opt-in content-addressed cache for DXC compiles in the Python shader tests. + +Active only when the environment variable X2W_DXC_CACHE names a directory. +Unset, run_dxc is a plain subprocess.run. Anything the cache cannot reason +about (includes, -I, response files, unknown -F outputs, extra run options) +bypasses it, so a cached result is never reused for a different compile. +""" +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile + +ENV_VAR = "X2W_DXC_CACHE" +OUTPUT_FLAGS = ("-Fo", "-Fc", "-Fh", "-Fre", "-Fd") +SUPPORTED_KWARGS = {"check", "capture_output", "text", "timeout"} +INCLUDE_RE = re.compile(rb"#\s*(include|import)\b|@import") +KEY_VERSION = "2" + + +def _plan(compiler, args): + """Return (key_args, input_path, outputs) or None when the compile is not cacheable.""" + args = [str(a) for a in args] + if not args: + return None + source = args[-1] + if source.startswith("-") or not os.path.isfile(source): + return None + key_args = [] + outputs = {} + for index, arg in enumerate(args[:-1]): + if arg.startswith("@") or arg.startswith("-I") or arg.startswith("-Fi"): + return None + if arg.startswith("-F") and arg not in OUTPUT_FLAGS: + return None + if index > 0 and args[index - 1] in OUTPUT_FLAGS: + continue # output path value, handled with its flag + if arg in OUTPUT_FLAGS: + if index + 1 >= len(args) - 1: + return None + path = args[index + 1] + if path.endswith(("/", "\\")) or os.path.isdir(path) or path in outputs.values() or path == source: + return None + outputs[arg] = path + key_args.append(arg) + key_args.append("<out:%s>" % arg) + elif os.path.exists(arg): + return None # unknown file-like argument + else: + key_args.append(arg) + if not outputs: + return None + return key_args + ["<in>"], source, outputs + + +def _scrub(data, mapping): + for text, token in mapping: + data = data.replace(text.encode(), token.encode()) + return data + + +def _restore(data, mapping): + for text, token in mapping: + data = data.replace(token.encode(), text.encode()) + return data + + +def _store(path, payload): + handle, temp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-") + try: + with os.fdopen(handle, "wb") as out: + out.write(payload) + os.replace(temp, path) + except BaseException: + if os.path.exists(temp): + os.unlink(temp) + raise + + +def _write_file(path, data): + _store_dir = os.path.dirname(os.path.abspath(path)) + os.makedirs(_store_dir, exist_ok=True) + with open(path, "wb") as out: + out.write(data) + + +def _emit(result_bytes, text, stream): + stream.write(result_bytes.decode(errors="replace") if text else result_bytes) # pragma: no cover + stream.flush() + + +def _passthrough(options, check): + """Keyword arguments exactly as the caller gave them (check only when given).""" + return dict(options, check=check) if check is not None else dict(options) + + +def _resolve(compiler): + """Absolute path of the compiler (a file, else found on PATH), or None when it is neither.""" + name = os.fspath(compiler) + if os.path.isfile(name): + return os.path.abspath(name) + found = shutil.which(name) + return os.path.abspath(found) if found else None + + +COMPILER_LIBRARIES = ("dxcompiler.dll", "dxil.dll", "libdxcompiler.so", "libdxil.so") + + +def _libraries(resolved): + """Name, size and mtime of the DXC libraries next to the compiler (missing ones are skipped).""" + folder = os.path.dirname(resolved) + found = [] + for name in COMPILER_LIBRARIES: + try: + info = os.stat(os.path.join(folder, name)) + except OSError: + continue + found.append([name, info.st_size, info.st_mtime_ns]) + return found + + +def run_dxc(compiler, args, **options): + """Mirror subprocess.run([compiler, *args]) with an optional on-disk cache.""" + command = [compiler, *args] + check = options.pop("check", None) + capture_output = options.get("capture_output", False) + text = options.get("text", False) + timeout = options.get("timeout") + extra = {k: v for k, v in options.items() if k not in SUPPORTED_KWARGS} + cache_dir = os.environ.get(ENV_VAR) + plan = None + resolved = None + if cache_dir and not extra: + resolved = _resolve(compiler) + if resolved is not None: + plan = _plan(compiler, args) + if plan is None: + return subprocess.run(command, **_passthrough(options, check)) + key_args, source, outputs = plan + with open(source, "rb") as handle: + source_bytes = handle.read() + if INCLUDE_RE.search(source_bytes): + return subprocess.run(command, **_passthrough(options, check)) + try: + info = os.stat(resolved) + except OSError: + return subprocess.run(command, **_passthrough(options, check)) + digest = hashlib.sha256() + digest.update(json.dumps([KEY_VERSION, resolved, info.st_size, info.st_mtime_ns, + _libraries(resolved), key_args]).encode()) ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Fingerprint the actual compiler behind the Wine launcher** With caching enabled in the documented Wine setup (`docs/non-windows-hosts.md:236-248`), `_resolve()` identifies the shell launcher, while its `exec wine "$DXC"` runs an SDK compiler in another directory. This key therefore fingerprints the launcher and probes its adjacent libraries, not the actual `dxc.exe` or DLLs. Updating the SDK files at the same path leaves the key unchanged and replays old shader binaries, so the checks can validate stale results against an updated toolchain. Fingerprint the delegated compiler and its libraries, or bypass caching for launchers whose compiler identity cannot be established. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-25 22:02:24 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-25T21:55:46Z.

Code review location: tools/dxc_cache.py; line 185

@@ -0,0 +1,227 @@
+"""Opt-in content-addressed cache for DXC compiles in the Python shader tests.
+
+Active only when the environment variable X2W_DXC_CACHE names a directory.
+Unset, run_dxc is a plain subprocess.run. Anything the cache cannot reason
+about (includes, -I, response files, unknown -F outputs, extra run options)
+bypasses it, so a cached result is never reused for a different compile.
+"""
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+ENV_VAR = "X2W_DXC_CACHE"
+OUTPUT_FLAGS = ("-Fo", "-Fc", "-Fh", "-Fre", "-Fd")
+SUPPORTED_KWARGS = {"check", "capture_output", "text", "timeout"}
+INCLUDE_RE = re.compile(rb"#\s*(include|import)\b|@import")
+KEY_VERSION = "2"
+
+
+def _plan(compiler, args):
+    """Return (key_args, input_path, outputs) or None when the compile is not cacheable."""
+    args = [str(a) for a in args]
+    if not args:
+        return None
+    source = args[-1]
+    if source.startswith("-") or not os.path.isfile(source):
+        return None
+    key_args = []
+    outputs = {}
+    for index, arg in enumerate(args[:-1]):
+        if arg.startswith("@") or arg.startswith("-I") or arg.startswith("-Fi"):
+            return None
+        if arg.startswith("-F") and arg not in OUTPUT_FLAGS:
+            return None
+        if index > 0 and args[index - 1] in OUTPUT_FLAGS:
+            continue  # output path value, handled with its flag
+        if arg in OUTPUT_FLAGS:
+            if index + 1 >= len(args) - 1:
+                return None
+            path = args[index + 1]
+            if path.endswith(("/", "\\")) or os.path.isdir(path) or path in outputs.values() or path == source:
+                return None
+            outputs[arg] = path
+            key_args.append(arg)
+            key_args.append("<out:%s>" % arg)
+        elif os.path.exists(arg):
+            return None  # unknown file-like argument
+        else:
+            key_args.append(arg)
+    if not outputs:
+        return None
+    return key_args + ["<in>"], source, outputs
+
+
+def _scrub(data, mapping):
+    for text, token in mapping:
+        data = data.replace(text.encode(), token.encode())
+    return data
+
+
+def _restore(data, mapping):
+    for text, token in mapping:
+        data = data.replace(token.encode(), text.encode())
+    return data
+
+
+def _store(path, payload):
+    handle, temp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-")
+    try:
+        with os.fdopen(handle, "wb") as out:
+            out.write(payload)
+        os.replace(temp, path)
+    except BaseException:
+        if os.path.exists(temp):
+            os.unlink(temp)
+        raise
+
+
+def _write_file(path, data):
+    _store_dir = os.path.dirname(os.path.abspath(path))
+    os.makedirs(_store_dir, exist_ok=True)
+    with open(path, "wb") as out:
+        out.write(data)
+
+
+def _emit(result_bytes, text, stream):
+    stream.write(result_bytes.decode(errors="replace") if text else result_bytes)  # pragma: no cover
+    stream.flush()
+
+
+def _passthrough(options, check):
+    """Keyword arguments exactly as the caller gave them (check only when given)."""
+    return dict(options, check=check) if check is not None else dict(options)
+
+
+def _resolve(compiler):
+    """Absolute path of the compiler (a file, else found on PATH), or None when it is neither."""
+    name = os.fspath(compiler)
+    if os.path.isfile(name):
+        return os.path.abspath(name)
+    found = shutil.which(name)
+    return os.path.abspath(found) if found else None
+
+
+COMPILER_LIBRARIES = ("dxcompiler.dll", "dxil.dll", "libdxcompiler.so", "libdxil.so")
+
+
+def _libraries(resolved):
+    """Name, size and mtime of the DXC libraries next to the compiler (missing ones are skipped)."""
+    folder = os.path.dirname(resolved)
+    found = []
+    for name in COMPILER_LIBRARIES:
+        try:
+            info = os.stat(os.path.join(folder, name))
+        except OSError:
+            continue
+        found.append([name, info.st_size, info.st_mtime_ns])
+    return found
+
+
+def run_dxc(compiler, args, **options):
+    """Mirror subprocess.run([compiler, *args]) with an optional on-disk cache."""
+    command = [compiler, *args]
+    check = options.pop("check", None)
+    capture_output = options.get("capture_output", False)
+    text = options.get("text", False)
+    timeout = options.get("timeout")
+    extra = {k: v for k, v in options.items() if k not in SUPPORTED_KWARGS}
+    cache_dir = os.environ.get(ENV_VAR)
+    plan = None
+    resolved = None
+    if cache_dir and not extra:
+        resolved = _resolve(compiler)
+        if resolved is not None:
+            plan = _plan(compiler, args)
+    if plan is None:
+        return subprocess.run(command, **_passthrough(options, check))
+    key_args, source, outputs = plan
+    with open(source, "rb") as handle:
+        source_bytes = handle.read()
+    if INCLUDE_RE.search(source_bytes):
+        return subprocess.run(command, **_passthrough(options, check))
+    try:
+        info = os.stat(resolved)
+    except OSError:
+        return subprocess.run(command, **_passthrough(options, check))
+    digest = hashlib.sha256()
+    digest.update(json.dumps([KEY_VERSION, resolved, info.st_size, info.st_mtime_ns,
+                              _libraries(resolved), key_args]).encode())
+    digest.update(b"\0")
+    digest.update(source_bytes)
+    entry = os.path.join(cache_dir, digest.hexdigest() + ".json")
+    mapping = [(source, "<in>")] + [(path, "<out:%s>" % flag) for flag, path in outputs.items()]
+    mapping.sort(key=lambda item: -len(item[0]))
+    cached = None
+    try:
+        with open(entry, "r", encoding="utf-8") as handle:
+            cached = json.load(handle)
+    except (OSError, ValueError):
+        cached = None
+    if cached is not None:
+        try:
+            files = {flag: bytes.fromhex(cached["files"][flag]) for flag in cached["files"]}
+            stdout = _restore(bytes.fromhex(cached["stdout"]), mapping)
+            stderr = _restore(bytes.fromhex(cached["stderr"]), mapping)
+            returncode = int(cached["returncode"])
+        except (KeyError, ValueError, TypeError):
+            cached = None
+    if cached is None:
+        existed = any(os.path.lexists(path) for path in outputs.values())
+        done = subprocess.run(command, capture_output=True, timeout=timeout)
+        stdout, stderr, returncode = done.stdout, done.stderr, done.returncode
+        files = {}
+        for flag, path in outputs.items():
+            if os.path.isfile(path):
+                with open(path, "rb") as handle:
+                    files[flag] = handle.read()
+        # A failure is cached only when no output existed beforehand, and never with files.
+        if returncode != 0:
+            files = {}
+        if returncode == 0 or not existed:

P2 Badge Avoid persisting transient compiler failures

With caching enabled, any nonzero exit is cached when no output existed beforehand, including failures caused by output I/O or temporary resource exhaustion rather than invalid source. Because _plan() removes output paths from the key, a failure targeting a missing output directory is subsequently replayed even when a valid directory is supplied. A synthetic compiler reproduced this: the cached retry failed without launching the compiler, while the equivalent uncached call succeeded. Such failures poison subsequent shader checks until the cache is cleared. Restrict cached failures to errors known to be deterministic, or leave nonzero results uncached.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4701330337 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#discussion_r4701330337). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-25T21:55:46Z. **Code review location:** `tools/dxc_cache.py`; line 185 ~~~~diff @@ -0,0 +1,227 @@ +"""Opt-in content-addressed cache for DXC compiles in the Python shader tests. + +Active only when the environment variable X2W_DXC_CACHE names a directory. +Unset, run_dxc is a plain subprocess.run. Anything the cache cannot reason +about (includes, -I, response files, unknown -F outputs, extra run options) +bypasses it, so a cached result is never reused for a different compile. +""" +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile + +ENV_VAR = "X2W_DXC_CACHE" +OUTPUT_FLAGS = ("-Fo", "-Fc", "-Fh", "-Fre", "-Fd") +SUPPORTED_KWARGS = {"check", "capture_output", "text", "timeout"} +INCLUDE_RE = re.compile(rb"#\s*(include|import)\b|@import") +KEY_VERSION = "2" + + +def _plan(compiler, args): + """Return (key_args, input_path, outputs) or None when the compile is not cacheable.""" + args = [str(a) for a in args] + if not args: + return None + source = args[-1] + if source.startswith("-") or not os.path.isfile(source): + return None + key_args = [] + outputs = {} + for index, arg in enumerate(args[:-1]): + if arg.startswith("@") or arg.startswith("-I") or arg.startswith("-Fi"): + return None + if arg.startswith("-F") and arg not in OUTPUT_FLAGS: + return None + if index > 0 and args[index - 1] in OUTPUT_FLAGS: + continue # output path value, handled with its flag + if arg in OUTPUT_FLAGS: + if index + 1 >= len(args) - 1: + return None + path = args[index + 1] + if path.endswith(("/", "\\")) or os.path.isdir(path) or path in outputs.values() or path == source: + return None + outputs[arg] = path + key_args.append(arg) + key_args.append("<out:%s>" % arg) + elif os.path.exists(arg): + return None # unknown file-like argument + else: + key_args.append(arg) + if not outputs: + return None + return key_args + ["<in>"], source, outputs + + +def _scrub(data, mapping): + for text, token in mapping: + data = data.replace(text.encode(), token.encode()) + return data + + +def _restore(data, mapping): + for text, token in mapping: + data = data.replace(token.encode(), text.encode()) + return data + + +def _store(path, payload): + handle, temp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-") + try: + with os.fdopen(handle, "wb") as out: + out.write(payload) + os.replace(temp, path) + except BaseException: + if os.path.exists(temp): + os.unlink(temp) + raise + + +def _write_file(path, data): + _store_dir = os.path.dirname(os.path.abspath(path)) + os.makedirs(_store_dir, exist_ok=True) + with open(path, "wb") as out: + out.write(data) + + +def _emit(result_bytes, text, stream): + stream.write(result_bytes.decode(errors="replace") if text else result_bytes) # pragma: no cover + stream.flush() + + +def _passthrough(options, check): + """Keyword arguments exactly as the caller gave them (check only when given).""" + return dict(options, check=check) if check is not None else dict(options) + + +def _resolve(compiler): + """Absolute path of the compiler (a file, else found on PATH), or None when it is neither.""" + name = os.fspath(compiler) + if os.path.isfile(name): + return os.path.abspath(name) + found = shutil.which(name) + return os.path.abspath(found) if found else None + + +COMPILER_LIBRARIES = ("dxcompiler.dll", "dxil.dll", "libdxcompiler.so", "libdxil.so") + + +def _libraries(resolved): + """Name, size and mtime of the DXC libraries next to the compiler (missing ones are skipped).""" + folder = os.path.dirname(resolved) + found = [] + for name in COMPILER_LIBRARIES: + try: + info = os.stat(os.path.join(folder, name)) + except OSError: + continue + found.append([name, info.st_size, info.st_mtime_ns]) + return found + + +def run_dxc(compiler, args, **options): + """Mirror subprocess.run([compiler, *args]) with an optional on-disk cache.""" + command = [compiler, *args] + check = options.pop("check", None) + capture_output = options.get("capture_output", False) + text = options.get("text", False) + timeout = options.get("timeout") + extra = {k: v for k, v in options.items() if k not in SUPPORTED_KWARGS} + cache_dir = os.environ.get(ENV_VAR) + plan = None + resolved = None + if cache_dir and not extra: + resolved = _resolve(compiler) + if resolved is not None: + plan = _plan(compiler, args) + if plan is None: + return subprocess.run(command, **_passthrough(options, check)) + key_args, source, outputs = plan + with open(source, "rb") as handle: + source_bytes = handle.read() + if INCLUDE_RE.search(source_bytes): + return subprocess.run(command, **_passthrough(options, check)) + try: + info = os.stat(resolved) + except OSError: + return subprocess.run(command, **_passthrough(options, check)) + digest = hashlib.sha256() + digest.update(json.dumps([KEY_VERSION, resolved, info.st_size, info.st_mtime_ns, + _libraries(resolved), key_args]).encode()) + digest.update(b"\0") + digest.update(source_bytes) + entry = os.path.join(cache_dir, digest.hexdigest() + ".json") + mapping = [(source, "<in>")] + [(path, "<out:%s>" % flag) for flag, path in outputs.items()] + mapping.sort(key=lambda item: -len(item[0])) + cached = None + try: + with open(entry, "r", encoding="utf-8") as handle: + cached = json.load(handle) + except (OSError, ValueError): + cached = None + if cached is not None: + try: + files = {flag: bytes.fromhex(cached["files"][flag]) for flag in cached["files"]} + stdout = _restore(bytes.fromhex(cached["stdout"]), mapping) + stderr = _restore(bytes.fromhex(cached["stderr"]), mapping) + returncode = int(cached["returncode"]) + except (KeyError, ValueError, TypeError): + cached = None + if cached is None: + existed = any(os.path.lexists(path) for path in outputs.values()) + done = subprocess.run(command, capture_output=True, timeout=timeout) + stdout, stderr, returncode = done.stdout, done.stderr, done.returncode + files = {} + for flag, path in outputs.items(): + if os.path.isfile(path): + with open(path, "rb") as handle: + files[flag] = handle.read() + # A failure is cached only when no output existed beforehand, and never with files. + if returncode != 0: + files = {} + if returncode == 0 or not existed: ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Avoid persisting transient compiler failures** With caching enabled, any nonzero exit is cached when no output existed beforehand, including failures caused by output I/O or temporary resource exhaustion rather than invalid source. Because `_plan()` removes output paths from the key, a failure targeting a missing output directory is subsequently replayed even when a valid directory is supplied. A synthetic compiler reproduced this: the cached retry failed without launching the compiler, while the equivalent uncached call succeeded. Such failures poison subsequent shader checks until the cache is cleared. Restrict cached failures to errors known to be deterministic, or leave nonzero results uncached. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
tedin7 commented 2026-11-25 23:01:45 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T22:29:11Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6065870383 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#pullrequestreview-6065870383). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T22:29:11Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-25 23:01:45 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T22:29:14Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6065870856 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#pullrequestreview-6065870856). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T22:29:14Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-25 23:02:05 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T22:29:08Z.


Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit 384f505d950ba46e09e3d8e0299da223156dc5d8:

  • Debug (--preset dev):
    • Build (cmake --build --preset dev -- -j 2): 184.74s (configure 2.91s)
    • Test (ctest --preset dev -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure): 2/2 passed (15.26s: pixel_aot_warp 11.65s, compute_store_aot_heap_view_load_warp 15.04s)
  • Release /O2 (--preset release):
    • Build (cmake --build --preset release -- -j 2): 165.22s (configure 4.19s)
    • Test (ctest --preset release -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure): 2/2 passed (9.08s: pixel_aot_warp 7.00s, compute_store_aot_heap_view_load_warp 8.97s)
  • Windows Python checks: tests/compute_alu_bcnt64_check.py ok (0.6s), tests/compute_alu_cmp_ne_check.py ok (0.6s), tests/compute_alu_lane_gaps_check.py ok (0.6s), tests/compute_buffer_atomics_check.py ok (0.7s), tests/compute_entry_layout_check.py ok (0.2s), tests/compute_heap_store_check.py ok (0.6s), tests/compute_heap_view_check.py ok (0.6s), tests/compute_load_format_check.py ok (0.7s), tests/form_coverage_check.py ok (17.1s), tests/mesh_clip_cull_check.py ok (5.9s), tests/mesh_heap_sampler_check.py ok (1.0s), tests/pso_readiness_check.py ok (1.2s), tests/rdna2_tools_check.py ok (3.0s), tests/vk_offscreen.py ok (1.6s)
  • sccache: 238/607 hits; wall 412.3s
<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7176419805 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#issuecomment-7176419805). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T22:29:08Z. --- Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit `384f505d950ba46e09e3d8e0299da223156dc5d8`: - **Debug (`--preset dev`)**: - Build (`cmake --build --preset dev -- -j 2`): `184.74s` (configure `2.91s`) - Test (`ctest --preset dev -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure`): **2/2 passed** (`15.26s`: `pixel_aot_warp` `11.65s`, `compute_store_aot_heap_view_load_warp` `15.04s`) - **Release `/O2` (`--preset release`)**: - Build (`cmake --build --preset release -- -j 2`): `165.22s` (configure `4.19s`) - Test (`ctest --preset release -R '^(pixel_aot_warp|compute_store_aot_heap_view_load_warp)$' --parallel 2 --no-tests=error --output-on-failure`): **2/2 passed** (`9.08s`: `pixel_aot_warp` `7.00s`, `compute_store_aot_heap_view_load_warp` `8.97s`) - **Windows Python checks**: `tests/compute_alu_bcnt64_check.py` ok (`0.6s`), `tests/compute_alu_cmp_ne_check.py` ok (`0.6s`), `tests/compute_alu_lane_gaps_check.py` ok (`0.6s`), `tests/compute_buffer_atomics_check.py` ok (`0.7s`), `tests/compute_entry_layout_check.py` ok (`0.2s`), `tests/compute_heap_store_check.py` ok (`0.6s`), `tests/compute_heap_view_check.py` ok (`0.6s`), `tests/compute_load_format_check.py` ok (`0.7s`), `tests/form_coverage_check.py` ok (`17.1s`), `tests/mesh_clip_cull_check.py` ok (`5.9s`), `tests/mesh_heap_sampler_check.py` ok (`1.0s`), `tests/pso_readiness_check.py` ok (`1.2s`), `tests/rdna2_tools_check.py` ok (`3.0s`), `tests/vk_offscreen.py` ok (`1.6s`) - `sccache`: 238/607 hits; wall `412.3s`
R0Y00 commented 2026-11-25 23:02:08 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-25T22:57:56Z.


I reproduced an output-path mismatch with real Windows SDK DXC at 384f505d: after warming the cache, a compile to a missing parent directory returned 0 and created the file, while a direct DXC invocation returned 1. I pushed a6f8d0b7, which routes that request through the compiler and adds the warm-cache regression. With real DXC, the normal cold and warm outputs remained byte-identical, and the missing-parent case returned 1 without creating a directory. The fake-compiler regression runs in the Linux job.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7176990329 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#issuecomment-7176990329). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-25T22:57:56Z. --- I reproduced an output-path mismatch with real Windows SDK DXC at `384f505d`: after warming the cache, a compile to a missing parent directory returned 0 and created the file, while a direct DXC invocation returned 1. I pushed `a6f8d0b7`, which routes that request through the compiler and adds the warm-cache regression. With real DXC, the normal cold and warm outputs remained byte-identical, and the missing-parent case returned 1 without creating a directory. The fake-compiler regression runs in the Linux job.
tedin7 commented 2026-11-25 23:02:09 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T22:29:11Z.

Code review location: tools/dxc_cache.py; line 153

@@ -0,0 +1,227 @@
+"""Opt-in content-addressed cache for DXC compiles in the Python shader tests.
+
+Active only when the environment variable X2W_DXC_CACHE names a directory.
+Unset, run_dxc is a plain subprocess.run. Anything the cache cannot reason
+about (includes, -I, response files, unknown -F outputs, extra run options)
+bypasses it, so a cached result is never reused for a different compile.
+"""
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+ENV_VAR = "X2W_DXC_CACHE"
+OUTPUT_FLAGS = ("-Fo", "-Fc", "-Fh", "-Fre", "-Fd")
+SUPPORTED_KWARGS = {"check", "capture_output", "text", "timeout"}
+INCLUDE_RE = re.compile(rb"#\s*(include|import)\b|@import")
+KEY_VERSION = "2"
+
+
+def _plan(compiler, args):
+    """Return (key_args, input_path, outputs) or None when the compile is not cacheable."""
+    args = [str(a) for a in args]
+    if not args:
+        return None
+    source = args[-1]
+    if source.startswith("-") or not os.path.isfile(source):
+        return None
+    key_args = []
+    outputs = {}
+    for index, arg in enumerate(args[:-1]):
+        if arg.startswith("@") or arg.startswith("-I") or arg.startswith("-Fi"):
+            return None
+        if arg.startswith("-F") and arg not in OUTPUT_FLAGS:
+            return None
+        if index > 0 and args[index - 1] in OUTPUT_FLAGS:
+            continue  # output path value, handled with its flag
+        if arg in OUTPUT_FLAGS:
+            if index + 1 >= len(args) - 1:
+                return None
+            path = args[index + 1]
+            if path.endswith(("/", "\\")) or os.path.isdir(path) or path in outputs.values() or path == source:
+                return None
+            outputs[arg] = path
+            key_args.append(arg)
+            key_args.append("<out:%s>" % arg)
+        elif os.path.exists(arg):
+            return None  # unknown file-like argument
+        else:
+            key_args.append(arg)
+    if not outputs:
+        return None
+    return key_args + ["<in>"], source, outputs
+
+
+def _scrub(data, mapping):
+    for text, token in mapping:
+        data = data.replace(text.encode(), token.encode())
+    return data
+
+
+def _restore(data, mapping):
+    for text, token in mapping:
+        data = data.replace(token.encode(), text.encode())
+    return data
+
+
+def _store(path, payload):
+    handle, temp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-")
+    try:
+        with os.fdopen(handle, "wb") as out:
+            out.write(payload)
+        os.replace(temp, path)
+    except BaseException:
+        if os.path.exists(temp):
+            os.unlink(temp)
+        raise
+
+
+def _write_file(path, data):
+    _store_dir = os.path.dirname(os.path.abspath(path))
+    os.makedirs(_store_dir, exist_ok=True)
+    with open(path, "wb") as out:
+        out.write(data)
+
+
+def _emit(result_bytes, text, stream):
+    stream.write(result_bytes.decode(errors="replace") if text else result_bytes)  # pragma: no cover
+    stream.flush()
+
+
+def _passthrough(options, check):
+    """Keyword arguments exactly as the caller gave them (check only when given)."""
+    return dict(options, check=check) if check is not None else dict(options)
+
+
+def _resolve(compiler):
+    """Absolute path of the compiler (a file, else found on PATH), or None when it is neither."""
+    name = os.fspath(compiler)
+    if os.path.isfile(name):
+        return os.path.abspath(name)
+    found = shutil.which(name)
+    return os.path.abspath(found) if found else None
+
+
+COMPILER_LIBRARIES = ("dxcompiler.dll", "dxil.dll", "libdxcompiler.so", "libdxil.so")
+
+
+def _libraries(resolved):
+    """Name, size and mtime of the DXC libraries next to the compiler (missing ones are skipped)."""
+    folder = os.path.dirname(resolved)
+    found = []
+    for name in COMPILER_LIBRARIES:
+        try:
+            info = os.stat(os.path.join(folder, name))
+        except OSError:
+            continue
+        found.append([name, info.st_size, info.st_mtime_ns])
+    return found
+
+
+def run_dxc(compiler, args, **options):
+    """Mirror subprocess.run([compiler, *args]) with an optional on-disk cache."""
+    command = [compiler, *args]
+    check = options.pop("check", None)
+    capture_output = options.get("capture_output", False)
+    text = options.get("text", False)
+    timeout = options.get("timeout")
+    extra = {k: v for k, v in options.items() if k not in SUPPORTED_KWARGS}
+    cache_dir = os.environ.get(ENV_VAR)
+    plan = None
+    resolved = None
+    if cache_dir and not extra:
+        resolved = _resolve(compiler)
+        if resolved is not None:
+            plan = _plan(compiler, args)
+    if plan is None:
+        return subprocess.run(command, **_passthrough(options, check))
+    key_args, source, outputs = plan
+    with open(source, "rb") as handle:
+        source_bytes = handle.read()
+    if INCLUDE_RE.search(source_bytes):
+        return subprocess.run(command, **_passthrough(options, check))
+    try:
+        info = os.stat(resolved)
+    except OSError:
+        return subprocess.run(command, **_passthrough(options, check))
+    digest = hashlib.sha256()
+    digest.update(json.dumps([KEY_VERSION, resolved, info.st_size, info.st_mtime_ns,
+                              _libraries(resolved), key_args]).encode())

Fixed in 9c5dfb08 (head now 384f505d). A launcher script that delegates to Wine (#! script mentioning wine) now bypasses the cache, since the real dxc.exe behind it cannot be fingerprinted. Covered in tests/dxc_cache_check.py. Ran python3 -B tests/dxc_cache_check.py (ok) and Win2025 WARP dev+release on 384f505d (receipt in the PR).

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4701622316 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#discussion_r4701622316). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T22:29:11Z. **Code review location:** `tools/dxc_cache.py`; line 153 ~~~~diff @@ -0,0 +1,227 @@ +"""Opt-in content-addressed cache for DXC compiles in the Python shader tests. + +Active only when the environment variable X2W_DXC_CACHE names a directory. +Unset, run_dxc is a plain subprocess.run. Anything the cache cannot reason +about (includes, -I, response files, unknown -F outputs, extra run options) +bypasses it, so a cached result is never reused for a different compile. +""" +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile + +ENV_VAR = "X2W_DXC_CACHE" +OUTPUT_FLAGS = ("-Fo", "-Fc", "-Fh", "-Fre", "-Fd") +SUPPORTED_KWARGS = {"check", "capture_output", "text", "timeout"} +INCLUDE_RE = re.compile(rb"#\s*(include|import)\b|@import") +KEY_VERSION = "2" + + +def _plan(compiler, args): + """Return (key_args, input_path, outputs) or None when the compile is not cacheable.""" + args = [str(a) for a in args] + if not args: + return None + source = args[-1] + if source.startswith("-") or not os.path.isfile(source): + return None + key_args = [] + outputs = {} + for index, arg in enumerate(args[:-1]): + if arg.startswith("@") or arg.startswith("-I") or arg.startswith("-Fi"): + return None + if arg.startswith("-F") and arg not in OUTPUT_FLAGS: + return None + if index > 0 and args[index - 1] in OUTPUT_FLAGS: + continue # output path value, handled with its flag + if arg in OUTPUT_FLAGS: + if index + 1 >= len(args) - 1: + return None + path = args[index + 1] + if path.endswith(("/", "\\")) or os.path.isdir(path) or path in outputs.values() or path == source: + return None + outputs[arg] = path + key_args.append(arg) + key_args.append("<out:%s>" % arg) + elif os.path.exists(arg): + return None # unknown file-like argument + else: + key_args.append(arg) + if not outputs: + return None + return key_args + ["<in>"], source, outputs + + +def _scrub(data, mapping): + for text, token in mapping: + data = data.replace(text.encode(), token.encode()) + return data + + +def _restore(data, mapping): + for text, token in mapping: + data = data.replace(token.encode(), text.encode()) + return data + + +def _store(path, payload): + handle, temp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-") + try: + with os.fdopen(handle, "wb") as out: + out.write(payload) + os.replace(temp, path) + except BaseException: + if os.path.exists(temp): + os.unlink(temp) + raise + + +def _write_file(path, data): + _store_dir = os.path.dirname(os.path.abspath(path)) + os.makedirs(_store_dir, exist_ok=True) + with open(path, "wb") as out: + out.write(data) + + +def _emit(result_bytes, text, stream): + stream.write(result_bytes.decode(errors="replace") if text else result_bytes) # pragma: no cover + stream.flush() + + +def _passthrough(options, check): + """Keyword arguments exactly as the caller gave them (check only when given).""" + return dict(options, check=check) if check is not None else dict(options) + + +def _resolve(compiler): + """Absolute path of the compiler (a file, else found on PATH), or None when it is neither.""" + name = os.fspath(compiler) + if os.path.isfile(name): + return os.path.abspath(name) + found = shutil.which(name) + return os.path.abspath(found) if found else None + + +COMPILER_LIBRARIES = ("dxcompiler.dll", "dxil.dll", "libdxcompiler.so", "libdxil.so") + + +def _libraries(resolved): + """Name, size and mtime of the DXC libraries next to the compiler (missing ones are skipped).""" + folder = os.path.dirname(resolved) + found = [] + for name in COMPILER_LIBRARIES: + try: + info = os.stat(os.path.join(folder, name)) + except OSError: + continue + found.append([name, info.st_size, info.st_mtime_ns]) + return found + + +def run_dxc(compiler, args, **options): + """Mirror subprocess.run([compiler, *args]) with an optional on-disk cache.""" + command = [compiler, *args] + check = options.pop("check", None) + capture_output = options.get("capture_output", False) + text = options.get("text", False) + timeout = options.get("timeout") + extra = {k: v for k, v in options.items() if k not in SUPPORTED_KWARGS} + cache_dir = os.environ.get(ENV_VAR) + plan = None + resolved = None + if cache_dir and not extra: + resolved = _resolve(compiler) + if resolved is not None: + plan = _plan(compiler, args) + if plan is None: + return subprocess.run(command, **_passthrough(options, check)) + key_args, source, outputs = plan + with open(source, "rb") as handle: + source_bytes = handle.read() + if INCLUDE_RE.search(source_bytes): + return subprocess.run(command, **_passthrough(options, check)) + try: + info = os.stat(resolved) + except OSError: + return subprocess.run(command, **_passthrough(options, check)) + digest = hashlib.sha256() + digest.update(json.dumps([KEY_VERSION, resolved, info.st_size, info.st_mtime_ns, + _libraries(resolved), key_args]).encode()) ~~~~ --- Fixed in 9c5dfb08 (head now 384f505d). A launcher script that delegates to Wine (`#!` script mentioning `wine`) now bypasses the cache, since the real `dxc.exe` behind it cannot be fingerprinted. Covered in `tests/dxc_cache_check.py`. Ran `python3 -B tests/dxc_cache_check.py` (ok) and Win2025 WARP dev+release on 384f505d (receipt in the PR). AI-assisted; commands listed were executed locally.
tedin7 commented 2026-11-25 23:02:09 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T22:29:14Z.

Code review location: tools/dxc_cache.py; line 185

@@ -0,0 +1,227 @@
+"""Opt-in content-addressed cache for DXC compiles in the Python shader tests.
+
+Active only when the environment variable X2W_DXC_CACHE names a directory.
+Unset, run_dxc is a plain subprocess.run. Anything the cache cannot reason
+about (includes, -I, response files, unknown -F outputs, extra run options)
+bypasses it, so a cached result is never reused for a different compile.
+"""
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+ENV_VAR = "X2W_DXC_CACHE"
+OUTPUT_FLAGS = ("-Fo", "-Fc", "-Fh", "-Fre", "-Fd")
+SUPPORTED_KWARGS = {"check", "capture_output", "text", "timeout"}
+INCLUDE_RE = re.compile(rb"#\s*(include|import)\b|@import")
+KEY_VERSION = "2"
+
+
+def _plan(compiler, args):
+    """Return (key_args, input_path, outputs) or None when the compile is not cacheable."""
+    args = [str(a) for a in args]
+    if not args:
+        return None
+    source = args[-1]
+    if source.startswith("-") or not os.path.isfile(source):
+        return None
+    key_args = []
+    outputs = {}
+    for index, arg in enumerate(args[:-1]):
+        if arg.startswith("@") or arg.startswith("-I") or arg.startswith("-Fi"):
+            return None
+        if arg.startswith("-F") and arg not in OUTPUT_FLAGS:
+            return None
+        if index > 0 and args[index - 1] in OUTPUT_FLAGS:
+            continue  # output path value, handled with its flag
+        if arg in OUTPUT_FLAGS:
+            if index + 1 >= len(args) - 1:
+                return None
+            path = args[index + 1]
+            if path.endswith(("/", "\\")) or os.path.isdir(path) or path in outputs.values() or path == source:
+                return None
+            outputs[arg] = path
+            key_args.append(arg)
+            key_args.append("<out:%s>" % arg)
+        elif os.path.exists(arg):
+            return None  # unknown file-like argument
+        else:
+            key_args.append(arg)
+    if not outputs:
+        return None
+    return key_args + ["<in>"], source, outputs
+
+
+def _scrub(data, mapping):
+    for text, token in mapping:
+        data = data.replace(text.encode(), token.encode())
+    return data
+
+
+def _restore(data, mapping):
+    for text, token in mapping:
+        data = data.replace(token.encode(), text.encode())
+    return data
+
+
+def _store(path, payload):
+    handle, temp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-")
+    try:
+        with os.fdopen(handle, "wb") as out:
+            out.write(payload)
+        os.replace(temp, path)
+    except BaseException:
+        if os.path.exists(temp):
+            os.unlink(temp)
+        raise
+
+
+def _write_file(path, data):
+    _store_dir = os.path.dirname(os.path.abspath(path))
+    os.makedirs(_store_dir, exist_ok=True)
+    with open(path, "wb") as out:
+        out.write(data)
+
+
+def _emit(result_bytes, text, stream):
+    stream.write(result_bytes.decode(errors="replace") if text else result_bytes)  # pragma: no cover
+    stream.flush()
+
+
+def _passthrough(options, check):
+    """Keyword arguments exactly as the caller gave them (check only when given)."""
+    return dict(options, check=check) if check is not None else dict(options)
+
+
+def _resolve(compiler):
+    """Absolute path of the compiler (a file, else found on PATH), or None when it is neither."""
+    name = os.fspath(compiler)
+    if os.path.isfile(name):
+        return os.path.abspath(name)
+    found = shutil.which(name)
+    return os.path.abspath(found) if found else None
+
+
+COMPILER_LIBRARIES = ("dxcompiler.dll", "dxil.dll", "libdxcompiler.so", "libdxil.so")
+
+
+def _libraries(resolved):
+    """Name, size and mtime of the DXC libraries next to the compiler (missing ones are skipped)."""
+    folder = os.path.dirname(resolved)
+    found = []
+    for name in COMPILER_LIBRARIES:
+        try:
+            info = os.stat(os.path.join(folder, name))
+        except OSError:
+            continue
+        found.append([name, info.st_size, info.st_mtime_ns])
+    return found
+
+
+def run_dxc(compiler, args, **options):
+    """Mirror subprocess.run([compiler, *args]) with an optional on-disk cache."""
+    command = [compiler, *args]
+    check = options.pop("check", None)
+    capture_output = options.get("capture_output", False)
+    text = options.get("text", False)
+    timeout = options.get("timeout")
+    extra = {k: v for k, v in options.items() if k not in SUPPORTED_KWARGS}
+    cache_dir = os.environ.get(ENV_VAR)
+    plan = None
+    resolved = None
+    if cache_dir and not extra:
+        resolved = _resolve(compiler)
+        if resolved is not None:
+            plan = _plan(compiler, args)
+    if plan is None:
+        return subprocess.run(command, **_passthrough(options, check))
+    key_args, source, outputs = plan
+    with open(source, "rb") as handle:
+        source_bytes = handle.read()
+    if INCLUDE_RE.search(source_bytes):
+        return subprocess.run(command, **_passthrough(options, check))
+    try:
+        info = os.stat(resolved)
+    except OSError:
+        return subprocess.run(command, **_passthrough(options, check))
+    digest = hashlib.sha256()
+    digest.update(json.dumps([KEY_VERSION, resolved, info.st_size, info.st_mtime_ns,
+                              _libraries(resolved), key_args]).encode())
+    digest.update(b"\0")
+    digest.update(source_bytes)
+    entry = os.path.join(cache_dir, digest.hexdigest() + ".json")
+    mapping = [(source, "<in>")] + [(path, "<out:%s>" % flag) for flag, path in outputs.items()]
+    mapping.sort(key=lambda item: -len(item[0]))
+    cached = None
+    try:
+        with open(entry, "r", encoding="utf-8") as handle:
+            cached = json.load(handle)
+    except (OSError, ValueError):
+        cached = None
+    if cached is not None:
+        try:
+            files = {flag: bytes.fromhex(cached["files"][flag]) for flag in cached["files"]}
+            stdout = _restore(bytes.fromhex(cached["stdout"]), mapping)
+            stderr = _restore(bytes.fromhex(cached["stderr"]), mapping)
+            returncode = int(cached["returncode"])
+        except (KeyError, ValueError, TypeError):
+            cached = None
+    if cached is None:
+        existed = any(os.path.lexists(path) for path in outputs.values())
+        done = subprocess.run(command, capture_output=True, timeout=timeout)
+        stdout, stderr, returncode = done.stdout, done.stderr, done.returncode
+        files = {}
+        for flag, path in outputs.items():
+            if os.path.isfile(path):
+                with open(path, "rb") as handle:
+                    files[flag] = handle.read()
+        # A failure is cached only when no output existed beforehand, and never with files.
+        if returncode != 0:
+            files = {}
+        if returncode == 0 or not existed:

Fixed in 9c5dfb08 (head now 384f505d). Only successful compiles are cached now, and a stored failure record is never replayed. The new test in tests/dxc_cache_check.py fails on the old code: a compile into a missing output directory is retried after the directory exists. Ran python3 -B tests/dxc_cache_check.py (ok) and Win2025 WARP dev+release on 384f505d (receipt in the PR).

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4701622750 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2357#discussion_r4701622750). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T22:29:14Z. **Code review location:** `tools/dxc_cache.py`; line 185 ~~~~diff @@ -0,0 +1,227 @@ +"""Opt-in content-addressed cache for DXC compiles in the Python shader tests. + +Active only when the environment variable X2W_DXC_CACHE names a directory. +Unset, run_dxc is a plain subprocess.run. Anything the cache cannot reason +about (includes, -I, response files, unknown -F outputs, extra run options) +bypasses it, so a cached result is never reused for a different compile. +""" +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile + +ENV_VAR = "X2W_DXC_CACHE" +OUTPUT_FLAGS = ("-Fo", "-Fc", "-Fh", "-Fre", "-Fd") +SUPPORTED_KWARGS = {"check", "capture_output", "text", "timeout"} +INCLUDE_RE = re.compile(rb"#\s*(include|import)\b|@import") +KEY_VERSION = "2" + + +def _plan(compiler, args): + """Return (key_args, input_path, outputs) or None when the compile is not cacheable.""" + args = [str(a) for a in args] + if not args: + return None + source = args[-1] + if source.startswith("-") or not os.path.isfile(source): + return None + key_args = [] + outputs = {} + for index, arg in enumerate(args[:-1]): + if arg.startswith("@") or arg.startswith("-I") or arg.startswith("-Fi"): + return None + if arg.startswith("-F") and arg not in OUTPUT_FLAGS: + return None + if index > 0 and args[index - 1] in OUTPUT_FLAGS: + continue # output path value, handled with its flag + if arg in OUTPUT_FLAGS: + if index + 1 >= len(args) - 1: + return None + path = args[index + 1] + if path.endswith(("/", "\\")) or os.path.isdir(path) or path in outputs.values() or path == source: + return None + outputs[arg] = path + key_args.append(arg) + key_args.append("<out:%s>" % arg) + elif os.path.exists(arg): + return None # unknown file-like argument + else: + key_args.append(arg) + if not outputs: + return None + return key_args + ["<in>"], source, outputs + + +def _scrub(data, mapping): + for text, token in mapping: + data = data.replace(text.encode(), token.encode()) + return data + + +def _restore(data, mapping): + for text, token in mapping: + data = data.replace(token.encode(), text.encode()) + return data + + +def _store(path, payload): + handle, temp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-") + try: + with os.fdopen(handle, "wb") as out: + out.write(payload) + os.replace(temp, path) + except BaseException: + if os.path.exists(temp): + os.unlink(temp) + raise + + +def _write_file(path, data): + _store_dir = os.path.dirname(os.path.abspath(path)) + os.makedirs(_store_dir, exist_ok=True) + with open(path, "wb") as out: + out.write(data) + + +def _emit(result_bytes, text, stream): + stream.write(result_bytes.decode(errors="replace") if text else result_bytes) # pragma: no cover + stream.flush() + + +def _passthrough(options, check): + """Keyword arguments exactly as the caller gave them (check only when given).""" + return dict(options, check=check) if check is not None else dict(options) + + +def _resolve(compiler): + """Absolute path of the compiler (a file, else found on PATH), or None when it is neither.""" + name = os.fspath(compiler) + if os.path.isfile(name): + return os.path.abspath(name) + found = shutil.which(name) + return os.path.abspath(found) if found else None + + +COMPILER_LIBRARIES = ("dxcompiler.dll", "dxil.dll", "libdxcompiler.so", "libdxil.so") + + +def _libraries(resolved): + """Name, size and mtime of the DXC libraries next to the compiler (missing ones are skipped).""" + folder = os.path.dirname(resolved) + found = [] + for name in COMPILER_LIBRARIES: + try: + info = os.stat(os.path.join(folder, name)) + except OSError: + continue + found.append([name, info.st_size, info.st_mtime_ns]) + return found + + +def run_dxc(compiler, args, **options): + """Mirror subprocess.run([compiler, *args]) with an optional on-disk cache.""" + command = [compiler, *args] + check = options.pop("check", None) + capture_output = options.get("capture_output", False) + text = options.get("text", False) + timeout = options.get("timeout") + extra = {k: v for k, v in options.items() if k not in SUPPORTED_KWARGS} + cache_dir = os.environ.get(ENV_VAR) + plan = None + resolved = None + if cache_dir and not extra: + resolved = _resolve(compiler) + if resolved is not None: + plan = _plan(compiler, args) + if plan is None: + return subprocess.run(command, **_passthrough(options, check)) + key_args, source, outputs = plan + with open(source, "rb") as handle: + source_bytes = handle.read() + if INCLUDE_RE.search(source_bytes): + return subprocess.run(command, **_passthrough(options, check)) + try: + info = os.stat(resolved) + except OSError: + return subprocess.run(command, **_passthrough(options, check)) + digest = hashlib.sha256() + digest.update(json.dumps([KEY_VERSION, resolved, info.st_size, info.st_mtime_ns, + _libraries(resolved), key_args]).encode()) + digest.update(b"\0") + digest.update(source_bytes) + entry = os.path.join(cache_dir, digest.hexdigest() + ".json") + mapping = [(source, "<in>")] + [(path, "<out:%s>" % flag) for flag, path in outputs.items()] + mapping.sort(key=lambda item: -len(item[0])) + cached = None + try: + with open(entry, "r", encoding="utf-8") as handle: + cached = json.load(handle) + except (OSError, ValueError): + cached = None + if cached is not None: + try: + files = {flag: bytes.fromhex(cached["files"][flag]) for flag in cached["files"]} + stdout = _restore(bytes.fromhex(cached["stdout"]), mapping) + stderr = _restore(bytes.fromhex(cached["stderr"]), mapping) + returncode = int(cached["returncode"]) + except (KeyError, ValueError, TypeError): + cached = None + if cached is None: + existed = any(os.path.lexists(path) for path in outputs.values()) + done = subprocess.run(command, capture_output=True, timeout=timeout) + stdout, stderr, returncode = done.stdout, done.stderr, done.returncode + files = {} + for flag, path in outputs.items(): + if os.path.isfile(path): + with open(path, "rb") as handle: + files[flag] = handle.read() + # A failure is cached only when no output existed beforehand, and never with files. + if returncode != 0: + files = {} + if returncode == 0 or not existed: ~~~~ --- Fixed in 9c5dfb08 (head now 384f505d). Only successful compiles are cached now, and a stored failure record is never replayed. The new test in `tests/dxc_cache_check.py` fails on the old code: a compile into a missing output directory is retried after the directory exists. Ran `python3 -B tests/dxc_cache_check.py` (ok) and Win2025 WARP dev+release on 384f505d (receipt in the PR). AI-assisted; commands listed were executed locally.
upstream-sync closed this pull request 2026-11-26 00:00:43 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
R0Y00/Xbox2Windows!2349
No description provided.