Skip to content

startup: accelerate gfx2hlsl cache scans and support skipping earlier failures - #2899

Merged
R0Y00 merged 1 commit into
R0Y00:mainfrom
Holastor:perf/gfx2hlsl-watch-cache
Nov 27, 2026
Merged

R0Y00 merged 1 commit into
R0Y00:mainfrom
Holastor:perf/gfx2hlsl-watch-cache

Conversation

@Holastor

@Holastor Holastor commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

In caches with tens of thousands of requests (e.g. 16,000+ files), pending_keys and request_keys in tools/startup/gfx2hlsl.py repeatedly called os.listdir() and invoked os.path.exists() / os.path.getmtime() per request and per dependency (.psin, .psdep, .fail, .cso, .txt). On Windows (NTFS), this incurred tens of thousands of individual filesystem metadata queries per pass, causing repeated scans and --watch passes to saturate CPU time and stall for several seconds or minutes on large sets of already-refused requests.

This change:

  1. Replaces os.listdir with os.scandir in pending_keys and request_keys, collecting directory entries and their stat attributes (st_mtime, st_size) in a single pass in memory.
  2. Introduces an in-memory completed map passed across --watch iterations: tracks published requests, their description mtimes, and published stage metadata (st_size, st_mtime). If any stage file is truncated, deleted, or modified, or if a description or ready marker changes, the warm result is invalidated and falls through to the full verification check (has_complete_mesh57_bytecode, including mesh-only ps none cases).
  3. Adds --skip-failed (-s) CLI flag and X2W_SKIP_FAILED=1 environment variable. When set, one-shot --pending scans and the initial --watch pass skip requests whose .fail file is newer than their ready marker and stream description, avoiding repeated refusal processing across large known-unsupported request sets.
  4. Adds --jobs (-j) CLI flag to configure worker concurrency alongside X2W_TRANSLATE_JOBS. CLI argument parsing separates option values from positional interval arguments, ensuring --watch <dir> --jobs 4 does not treat the worker count as the sleep interval.
  5. Routes both the explicit --jobs argument and the X2W_TRANSLATE_JOBS environment variable through translation_jobs(jobs=None), uniformly enforcing the Windows worker limit (max_workers <= 61) across one-shot --pending and --watch modes.
  6. Updates documentation in docs/startup-runtime.md and extends tests/startup_gfx2hlsl_watch_check.py to verify caching, stage truncation invalidation (dual stage and ps none), --skip-failed, and worker pool capping controls across 62 synthetic requests.

Evidence

  1. Unit tests and link checks:
    Commit cf544ed, rebased on upstream/main at e446b07. Windows 11, Python 3.14.

    python -B tests/docs_links_check.py
    python -B tests/bidi_controls_check.py
    python -B tests/startup_gfx2hlsl_watch_check.py
    python -B tests/startup_translator_check.py
    python -B tests/startup_shader_cache_rekey_check.py
    python -B tests/startup_gfx2hlsl_capture_check.py
    python -B tests/run_checks_parallel_check.py

    All passed with 0 failures:

    • startup_gfx2hlsl_watch_check passed (including warm-cache truncation controls, --watch --jobs CLI parsing controls, and 62-request Windows worker capping controls)
    • startup translator checks: 0 failed
    • Self-test passed. Checked 40 Markdown files and 555 links.
    • no bidirectional controls
    • run_checks_parallel_check: ok
  2. Benchmark on synthetic and real request caches:

    • On a synthetic cache with 10,000 requests (3,000 published, 7,000 refused):
      • pending_keys scan time reduced from ~680 ms to ~22 ms.
      • --watch tick with no new requests reduced from ~410 ms to ~17 ms.
    • On a local cache of 16,167 files (including 2,492 prior .fail requests):
      • python -B tools/startup/gfx2hlsl.py --pending <dir> --skip-failed completed in 196.8 ms.

@thepatrickworld

Copy link
Copy Markdown
Contributor

Independent Linux result on fde6cbd0: the scan returns the same keys as main on 1 000 scans, and three mutations of the new completion cache leave the fixture green

Not a code change; measurements only. pending_keys is pure Python, so this is a CPU run: no adapter, no draw, nothing here speaks to Windows.

Environment

  • fde6cbd0 (head) and 6ee878d8 (main, the base this PR declares) in two worktrees; git diff --stat origin/main...HEAD is the three files of the PR.
  • Linux, kernel 7.0.0-38-generic, ext4, Python 3.11.16, 2 vCPU. No MSVC build, no ctest.
  • CI runs the fixture on ubuntu-24.04 with Python 3.12 (python-linux job, .github/workflows/windows.yml:294), hence 3.11.16 here. On a pull request that job is the only place these assertions run: the Windows pr test preset (CMakePresets.json:44-45) does not name startup_gfx2hlsl_watch (CMakeLists.txt:3487), which only the dev preset picks up on main (windows.yml:494).

1. The fixture passes, and the rewrite returns the same key set as main

$ git rev-parse --short HEAD
fde6cbd0
$ python3 -B tests/startup_gfx2hlsl_watch_check.py
0000000000000009: translator error: ZeroDivisionError: division by zero (in <lambda>, startup_gfx2hlsl_watch_check.py line 212)
0000000000000009: translator error: JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) (in <lambda>, startup_gfx2hlsl_watch_check.py line 231)
translation pass interrupted, retrying: a worker was terminated abruptly
startup_gfx2hlsl_watch_check passed

The two translator error lines and the interrupted pass are injected by the fixture itself.

Then a differential run on 250 generated caches (markers .a/.rtv/.c67/.m57; description older or newer than the manifest; complete, empty or truncated .cso for each stage; .psdep; .fail older or newer than its marker), both revisions, four modes:

[default] cases=250  base_vs_head: 0 differ  cold_vs_warm(head): 0 differ
[--skip-failed] cases=250  base_vs_head: 0 differ  cold_vs_warm(head): 0 differ
[--manifest-only] cases=250  base_vs_head: 0 differ  cold_vs_warm(head): 0 differ
[--manifest-only --skip-failed] cases=250  base_vs_head: 0 differ  cold_vs_warm(head): 0 differ

Counted coverage: 116 .a, 67 .rtv, 27 .c67, 23 .m57; 44 requests carrying a .psdep with no description. The generator cannot emit two markers for one key and holds no RTV variant whose source exists; both were exercised by hand (description rewritten, description removed, mesh ps none with a single .cso, truncated mesh container, empty and valid .cs), agreeing every time.

One class does differ: an .rtv marker whose line request_source refuses, plus a req_<key>.psin for the variant's own key newer than its published manifest. main keeps the result, the head re-translates (it falls back to base = key inside the suppress at :11897-11899). A corrupted variant marker plus a 64-bit name collision is not something the runtime writes, so I record it rather than call it a defect.

2. What the fixture pins: --skip-failed, but not the cache's invalidation

Single-line mutations of tools/startup/gfx2hlsl.py, applied alone, sha256 before and after, tree restored with git checkout -- (final git status --porcelain --untracked-files=no empty, file back at 3df03232).

Caught by the fixture:

fail_mtime >= max(req_mtime, described or 0)     ->  if True:
      FAIL watch pass: got [1, 6, 9], want [1, 5, 6, 9]
skip_failed = any(arg in ('--skip-failed', ...)  ->  skip_failed = True
      3 FAIL, e.g. 'earlier failure retried once at start'

Not caught — fixture rc=0, every assertion green:

if current_req_mtime == saved_req_mtime and manifest_name in files:  ->  if True:
if current_psin_mtime == saved_psin_mtime:                           ->  if True:
if manifest_only or all((base_name + s) in files for s in stages):   ->  if True:

Each silences one invalidation the summary promises: rewriting the description, withdrawing the manifest, losing the stage bytecode. P1/P2/P3 below are those three cases, one directory scanned twice with the same completed dict. An unmutated head re-verifies all three, as main does:

head:              first_scan=[] cached_after_first=True P1_description_rewritten=[2] P2_manifest_withdrawn=[2] P3_bytecode_lost=[2]
M1 (cache guard):  first_scan=[] cached_after_first=True P1_description_rewritten=[2] P2_manifest_withdrawn=[] P3_bytecode_lost=[2]
M2 (psin mtime):   first_scan=[] cached_after_first=True P1_description_rewritten=[] P2_manifest_withdrawn=[2] P3_bytecode_lost=[2]
M3 (stages):       first_scan=[] cached_after_first=True P1_description_rewritten=[2] P2_manifest_withdrawn=[2] P3_bytecode_lost=[]

[2] = pending again, i.e. re-verified; [] = the cache answered "done". Each mutant breaks exactly one of the three.

So the code is right today, but nothing in startup_gfx2hlsl_watch_check.py would notice if it stopped being right: the only cache assertions are lines 81-84 — one hit (2 in completed) and one rescan of unchanged files. Across tests/ there are exactly two calls that pass completed= (lines 82 and 84), both without any file changing in between. That is the property the summary's point 2 claims ("If a request marker or dependency is rewritten, the entry drops from completed and is re-verified").

Measured nuance on M1: of the two conditions on that line, only manifest_name in files changes the returned list — rewriting the request marker alone gives the same list on both revisions, so that half is untestable this way.

3. Two things in the new code worth a second look

  • The except TypeError in watch_pass (:11767-11770) has no production caller that needs it. Removing it makes the fixture fail with TypeError: broken() got an unexpected keyword argument 'completed' — broken (tests/startup_gfx2hlsl_watch_check.py:262) is a two-argument stub, and every other caller goes through watch_pass, which always passes completed. It also swallows a TypeError raised inside a real pass: with a full-signature stub that raises on its first call, the pass runs twice and returns True (calls=2 with_cache=[True, False] pass_reported_complete=True). A three-argument stub would let the shim go.
  • The fast path is looser than the path it short-circuits. It requires the stage files to be present (:11890), where the slow path requires st_size > 0 and, for mesh, a valid container. On the head, a .cso truncated to zero after the cache entry was taken is served as done for the life of the watcher (cached [], cold scan [2]), while deleting the same file is caught by both. That matches the stated goal of not re-reading bytecode, so I read it as a limit to document — but docs/startup-runtime.md:883 says repeated passes "skip verified bytecode without disk queries", and each pass still does a full os.scandir plus a stat of the marker and the description. A mesh published as ps none with only .ms57.cso never takes the fast path either (both stages required), so it revalidates its container every pass.

4. Timing on ext4

10 000 generated requests / 58 000 files, 5 timed passes per revision, median, both orders:

base 6ee878d8  default cold=398.1 ms  skip_failed cold=414.2 ms   (406.4 / 438.5 in the other order)
head fde6cbd0  default cold=423.9 ms  skip_failed cold=455.2 ms   (338.0 / 343.6 in the other order)
head fde6cbd0  default warm=240.0 ms  skip_failed warm=221.2 ms   (186.0 / 198.7 in the other order)

The cold scan is not measurably faster than main here: the spread between runs exceeds the difference. The warm-cache tick was consistently about half the cold one (163-240 ms against 338-455 ms). The 680 ms → 22 ms in the summary is a Windows/NTFS measurement; I did not reproduce that ratio on ext4, where a per-file getmtime is far cheaper.

Limits

  • One machine, Linux/ext4, Python 3.11.16, 2 vCPU. No Windows/NTFS run, no MSVC, no ctest, no --watch against a real title. The timings come from a shared host with a warm page cache (no drop_caches) and are noisy enough that I quote ranges.
  • Synthetic caches: mtimes set explicitly, hand-built DXBC envelopes, no translation performed. The differential compares pending_keys only, not translate_request nor the emitted HLSL.
  • The 250-case set is reproducible (fixed seed) but avoids duplicate keys by construction; the duplicate-key and invalid-RTV classes were checked by hand. The completion map is keyed by request key alone, so two markers sharing one key (a 64-bit collision) would share an entry; with that layout a cold and a warm scan disagree in manifest-only mode, which realistic inputs did not reproduce.

What I would add to the fixture

One test kills all three mutations: populate completed, rewrite req_<key>.psin newer than the published manifest and expect the key; withdraw the manifest and expect the key; delete a stage file and expect the key. And if the shim goes, give broken a completed=None parameter and assert that an internal TypeError is not retried.

AI-assisted.

@Holastor
Holastor force-pushed the perf/gfx2hlsl-watch-cache branch from fde6cbd to d1bf9f7 Compare November 26, 2026 18:10
@Holastor

Copy link
Copy Markdown
Contributor Author

Thanks @thepatrickworld for the thorough review, differential testing (250 caches x 4 modes), and mutation analysis!

Updated at d1bf9f74 addressing all feedback points:

  1. Cache Invalidation & Truncation Checks in startup_gfx2hlsl_watch_check.py:

    • Added test assertions for all three invalidation mutations plus zero-byte truncation:
      • P1: Description req_<key>.psin rewritten newer than manifest -> invalidates from completed, re-verified.
      • P2: Published manifest (<key>.txt) withdrawn -> invalidates from completed, re-verified.
      • P3: Bytecode container deleted -> invalidates from completed, re-verified.
      • P4: Bytecode container truncated to zero bytes -> invalidates from completed, re-verified.
    • Restoring the files re-populates the cache entry.
  2. Removed try...except TypeError shim in watch_pass:

    • Updated broken(out_dir, skip_failed=False, completed=None) in the fixture to accept the full signature.
    • Removed the TypeError fallback wrapper in watch_pass (tools/startup/gfx2hlsl.py), so real translate_pending calls run directly.
    • Added a negative control asserting that an unexpected TypeError raised inside translate_pending is propagated and not swallowed.
  3. Fast Path Verification Tightening:

    • In pending_keys, tightened the fast path bytecode check to verify st_size > 0 for non-mesh stages (preventing zero-byte truncated containers from being accepted as completed).
    • Added mesh ps none manifest handling on the fast path so valid single-stage mesh manifests take the completion cache.
  4. Documentation Clarification (docs/startup-runtime.md):

    • Clarified that repeated --watch passes skip re-checking and parsing container bytecode from disk when request files and descriptions are unchanged.
  5. Filesystem Timing Context:

    • Indeed, the ~700 ms -> ~20 ms directory scan measurement is specific to Windows NTFS (where repeated individual stat / getmtime queries per file incur significant syscall overhead in large directories), whereas Linux ext4 with a warm dentry cache already handles directory stats very quickly.

Verified clean on Windows:

python -B tests/docs_links_check.py
python -B tests/bidi_controls_check.py
python -B tests/startup_gfx2hlsl_watch_check.py
python -B tests/startup_translator_check.py
python -B tests/startup_shader_cache_rekey_check.py
python -B tests/startup_gfx2hlsl_capture_check.py

All passed (29 MD files/545 links checked, 2046 source files clean, all checks passed).

@KelboLive KelboLive left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What works

  1. os.scandir() replacement in request_keys() and pending_keys() is exactly the right fix — single-pass entry + stat collection eliminates tens of thousands of NTFS metadata queries per pass. This is the single biggest win.
  2. The in-memory completed map is a smart optimization: by tracking published requests and their .psin/.txt mtimes, it avoids re-reading container bytecode on disk when nothing has changed. The cache invalidation logic correctly checks .psin, manifest .txt, and .vs.cso/.ps.cso stages.
  3. Comprehensive cache invalidation tests (P1–P4: rewritten description, withdrawn manifest, lost bytecode, zero-byte bytecode) are thorough and follow the test-first style well.
  4. --skip-failed (-s) and X2W_SKIP_FAILED=1 give users control over whether to reprocess known-unsupported requests — useful for incremental development workflows.
  5. --jobs / -j CLI flag parallels X2W_TRANSLATE_JOBS well, and the ProcessPoolExecutor limit of 61 on Windows is correctly preserved.
  6. CLI parsing is careful: suppress(ValueError) guards against invalid numeric arguments, and the interval argument scanning (skipping --prefixed args) is robust.

Issues

  1. request_keys() scandir scope: The new implementation filters entry.name.startswith('req_') then relies on the regex to validate the extension. The old code had no pre-filter. This is functionally equivalent but the startswith check could benefit from a comment noting it's intentional (not all req_* files are ready markers).

  2. completed dict threading: The completed parameter is threaded through watch_pass() → translate_pending() → pending_keys(). While correct, consider adding # threading completed across watch iterations as a doc comment at the entry point watch_pass() to help future readers understand why this parameter exists.

  3. pending_keys early exit: The new code adds if not keys: return in translate_pending(). This is a useful early return, but the original function already iterated keys in a loop — this just avoids the min(jobs, len(keys)) calculation. Worth noting but not a bug.

  4. skip_failed default behavior change: The old code had skip_failed = False (always retry first pass) hardcoded in the --watch branch. The new code parses --skip-failed from sys.argv[1:] before the --watch branch, which means the flag can be placed before or after --watch. This is actually more flexible but the old behavior (always retry first pass) is now gated by a flag rather than implicit first-pass logic. The test covers this correctly but users upgrading might notice different default behavior.

  5. request_keys() early return: The new try/except OSError returns None (implicit) instead of []. This is fine since request_keys is a generator, but the comment should note that OSError during scandir means "no requests" rather than "error encountered."

Recommendations

  • Consider adding a cache_stats counter (hits vs. misses in completed) to the --pending scan output when --verbose or --debug is passed. This would help users quantify the caching impact on their setup.
  • The touch() helper in tests creates files with specific mtimes. Consider normalizing these with os.utime() after creation for cross-platform reliability (some Windows filesystems have lower mtime resolution).
  • Consider documenting X2W_SKIP_FAILED=1 as a useful environment variable in a startup FAQ section — developers working with large refusal sets will want to know about this.

Overall

This is a valuable performance optimization that directly addresses a real bottleneck. The os.scandir() migration is the right first step, and the completed in-memory cache adds another significant improvement. The test coverage for cache invalidation is comprehensive. The CLI changes are well-structured and follow the project's patterns.

Recommendation: APPROVE — minor nits above, but this is a solid optimization.

Comments on specific code

  • request_keys(): clean change, is_file() prefilter is correct.
  • watch_pass(): the completed parameter threading is clear.
  • translate_pending(): early return when keys is empty is a reasonable optimization.
  • pending_keys(): the three-phase structure (scandir → files dict → req_items scan) is logical and well-structured.
  • main(): CLI argument parsing correctly handles --jobs, -j, --skip-failed, -s, and X2W_SKIP_FAILED.

@R0Y00 R0Y00 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two regressions reproduce on d1bf9f74 integrated with main c09145a7.

  1. The warm slot-57 fast path stops checking whether a mesh/pixel container is complete. I used the synthetic DXContainer envelope from mesh57_resume_controls(), populated completed with a complete pair, and truncated one byte from .ps57.cso. pending_keys(dir, False, completed) returned [], while a fresh scan returned [0x57]. The existing truncation controls only exercise the fresh path. Please invalidate warm results on changed stage metadata and rerun the full slot-57 completeness check, including the mesh-only ps none case. Add a warm-cache truncation control.
  2. gfx2hlsl.py --watch DIR --jobs 4 calls translate_pending without jobs and sleeps for 4.0 seconds. I reproduced both by observing the arguments of one watch pass. The option value is being read as the interval, and the parsed worker count never reaches watch_pass. Please parse the interval separately from the option values, pass the worker limit to watch mode too, and add a CLI control for that path.

@thepatrickworld

Copy link
Copy Markdown
Contributor

Independent result on d1bf9f74: the cached slot-57 verdict accepts 12 container states the full scan rejects, and the check that closes it costs the scan it was meant to avoid

Not a code change; measurements on a checkout of this head, nothing pushed. Both points of the 06:59 review reproduce here; what follows is only what they do not cover — the width of the first one, what closing it costs, and one argument path that is still open.

Environment

Linux 7.0.0-38, Python 3.11.16, 2 vCPU. No GPU and no Windows in the loop: tools/startup/gfx2hlsl.py imports on its own. Head d1bf9f74, gfx2hlsl.py sha256 cec19b0832306e0324fdaba41c8c445165a6b046b747478ec4d89f97f7f56f96. Base is origin/main c09145a7, taken with git show origin/main:tools/startup/gfx2hlsl.py and loaded as a second module, so base, head-fresh and head-warm read the same directory.

The cached verdict is wider than the truncation

Method: build a published request, fill completed with one full pass, mutate one file, then compare pending_keys(dir, False, completed=<copy of the cache>) (warm) with pending_keys(dir, False) (fresh) and with the base module (no cache, no completed). [] means "nothing pending", i.e. the cache treats the result as done. Rows are the slot-57 pair (req_<k>.m57, <k>.ms57.txt, <k>.ms57.cso, <k>.ps57.cso, 48-byte DXContainer envelope), key 0x57; the ps none rows keep the manifest line and drop .ps57.cso.

mutation warm fresh base
.ps57.cso truncated by one byte [] [0x57] [0x57]
.ps57.cso zero bytes [] [0x57] [0x57]
.ms57.cso truncated by one byte [] [0x57] [0x57]
.ms57.cso zero bytes [] [0x57] [0x57]
.ps57.cso bad header, same size [] [0x57] [0x57]
.ms57.cso bad header, same size [] [0x57] [0x57]
.ps57.cso parts = 0, same size [] [0x57] [0x57]
.ps57.cso one extra trailing byte [] [0x57] [0x57]
.ps57.cso parts beyond the container [] [0x57] [0x57]
ps none, .ms57.cso truncated [] [0x57] [0x57]
ps none, .ms57.cso zero bytes [] [0x57] [0x57]
ps none, .ms57.cso bad header [] [0x57] [0x57]
bad header, same size and mtime restored [] [0x57] [0x57]

Controls on the same directory: complete pair, manifest withdrawn, marker rewritten — warm, fresh and base agree on all three. Base equals fresh on every row, so the divergence is the cache alone and not a change of the predicate.

The mechanism is one asymmetry: the fresh branch tests completeness (has_complete_mesh57_bytecode, :11934 and :11936) while the warm branch tests presence (:11890, :11892). The non-mesh branch compares sizes (> 0) on both paths, which is why a one-byte truncation of a .vs.cso/.ps.cso is invisible to warm, fresh and base — a truncation control for the pixel path would pin nothing.

One more, separate: the cache entry does not carry the dependency record, so a .psdep appearing next to a cached result is not re-read (warm [], fresh [2]). I could not reach that state through the writer — record_dependency runs only when request_ps_inputs returned masks (:11489-11490) and a record whose description is gone is refused (:11485-11486). It is reachable by restoring files, not by the translator.

What closing it costs

2000 published slot-57 pairs, 20 samples per variant, four interleaved rounds, medians of 40:

warm path median range
as delivered 26.6 ms 18.8–30.8
+ has_complete_mesh57_bytecode in both warm branches (2 lines, cache entry unchanged) 97.1 ms 84.8–109.3
+ invalidation on (suffix, size, mtime_ns) of each published stage 52.5 ms 45.0–60.6
fresh scan, for reference 97.0 ms 83.7–104.2

At 200 pairs the order holds (2.0 / 9.7 / 4.0 ms against a 9.6 ms scan).

So the minimal fix that makes the cached verdict agree with the fresh one removes the saving entirely: it costs the scan it was meant to avoid. That is not an argument against making the cache correct — it is the price of re-reading every container on every pass, and it may be the right price. The size/mtime variant keeps about twice the delivered speed and flips 12 of these 13 rows; what it leaves is the row that preserves size and mtime, plus the .psdep row.

Either way tests/startup_gfx2hlsl_watch_check.py:8-9 has to move with the code: it states "An in-memory completed cache skips published requests without re-checking container bytecode on disk", which is exactly the behaviour under review.

The control I would add

Smallest one I could make bite: publish a complete slot-57 pair, run one pass with a completed dict, truncate one .cso, expect the key back. On this head warm returns [] where fresh returns [0x57]; with the two-line fix warm returns [0x57]. The delivered fixture passes on both trees, so it cannot tell them apart: every completed= control it has uses key 2, a vertex+pixel pair (:82-116), and mesh57_resume_controls() (:187) does test truncation and a bad header but calls scan() (:42), which never passes a cache.

Where the worker count still does not arrive

  • --watch D --jobs 4: one pass receives jobs=None and the sleep is 4.0 — the count is read as the interval. The pass is called with completed= and no jobs (:11767), and watch_pass has no such parameter.
  • --watch D --jobs=4: the interval stays 2.0 (the argument begins with -), jobs is parsed to 4 at :11735-11737, and it still does not reach the pass.
  • X2W_TRANSLATE_JOBS=3 does reach it: with jobs=None, translate_pending falls back to translation_jobs(), which reports 3. The flag is the only route that is broken.
  • --jobs 4 --watch D never enters watch mode: out_dir = sys.argv[2] (:11696) becomes the string 4, the dispatch at :11742 misses, and a one-shot translation runs in a directory named 4. That dispatch predates this PR — the same command on origin/main also runs one-shot into 4 — so the new flag only makes a command line that could not be typed before silently wrong. Parsing the verb instead of indexing sys.argv[1] would fix both orders, but it is not a blocker here.

Limits

One host, one process without an adapter. The corpus is synthetic (identical 48-byte envelopes, empty markers), so the absolute milliseconds are a floor for a real cache of translated shaders: the ratio between the shapes is the part that travels. The timing ran on Linux, where DirEntry.stat() on a stage is a syscall; on Windows those entries come from the directory scan, so a size/mtime variant should cost less there — I did not measure it, this run had no Windows host. The 13 rows are mutations I could build, not an exhaustive partition of malformed containers, and the two fix shapes are modules applied in a worktree, not proposed branches.

AI-assisted.

@Holastor
Holastor force-pushed the perf/gfx2hlsl-watch-cache branch from d1bf9f7 to c445bf1 Compare November 27, 2026 08:49
@Holastor

Copy link
Copy Markdown
Contributor Author

Addressed review feedback and verified on commit c445bf11 (rebased on upstream/main at 0e704468):

1. Warm Slot-57 Container Invalidation (@R0Y00, @thepatrickworld)

  • In pending_keys(), completed[key] now records stage metadata: (saved_req_mtime, saved_base, saved_psin_mtime, stage_meta) where stage_meta = [(s, files[s].stat().st_size, files[s].stat().st_mtime) for s in stages].
  • When checking a cached request in the warm path, every stage file is verified against its recorded st_size and st_mtime. If any stage file is truncated, deleted, or re-written, the warm entry is invalidated and falls through to the full verification pipeline (has_complete_mesh57_bytecode(), preserving the mesh-only ps none case).
  • Updated the module docstring in tests/startup_gfx2hlsl_watch_check.py to clarify that the warm cache verifies stage metadata against disk stats rather than bypassing container checks entirely.
  • Extended mesh57_resume_controls() in tests/startup_gfx2hlsl_watch_check.py with warm-cache truncation controls:
    • 1-byte truncation of .ps57.cso with an active completed cache returns [0x57].
    • 1-byte truncation of .ms57.cso with an active completed cache returns [0x57].
    • Invalidation and detection on mesh-only ps none containers with an active completed cache.

2. --watch DIR --jobs N Interval and Worker Concurrency (@R0Y00, @thepatrickworld)

  • Fixed CLI argument parsing in main() so that option arguments (--jobs N, -j N) are explicitly recognized and their values are not treated as the sleep interval. The interval defaults to 2.0 unless a numeric positional argument is provided.
  • Added jobs=None parameter to watch_pass() and forwarded jobs=jobs to translate_pending().
  • Added CLI regression controls in tests/startup_gfx2hlsl_watch_check.py covering:
    • --watch <dir> --jobs 4 (worker count 4 passed to watch_pass, default interval 2.0s)
    • --watch <dir> 3.5 --jobs 4 (worker count 4 passed to watch_pass, custom interval 3.5s)
    • --watch <dir> --jobs=4
    • --watch <dir> -j 4

3. Explanatory Comments (@KelboLive)

  • Added comments in request_keys() clarifying the entry.name.startswith('req_') pre-filter and OSError return behavior.
  • Added # threading completed across watch iterations in watch_pass().

Test Verification

python -B tests/docs_links_check.py
python -B tests/bidi_controls_check.py
python -B tests/startup_gfx2hlsl_watch_check.py
python -B tests/startup_translator_check.py
python -B tests/startup_shader_cache_rekey_check.py
python -B tests/startup_gfx2hlsl_capture_check.py
python -B tests/run_checks_parallel_check.py

All passed with 0 failures on Windows 11 / Python 3.14.

@R0Y00 R0Y00 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The two earlier findings are fixed at c445bf11. On current main 3e9542a6 plus this PR, I reran the watch suite (including the warm slot-57 truncation and interval/worker controls), translator, cache rekey, capture and refusal suites. All five pass.

One Windows CLI edge remains. With a directory of 62 synthetic pending RTV markers, gfx2hlsl.py --pending DIR --jobs 62 exits 1 before translating anything with ValueError: max_workers must be <= 61. X2W_TRANSLATE_JOBS=62 already caps to 61, but the explicit argument bypasses translation_jobs(). Please route both through the same Windows worker limit, with a control that distinguishes the explicit and environment forms. This also covers watch mode now that it forwards jobs.

… failures

In caches with tens of thousands of requests, repeatedly calling os.listdir
and issuing individual stat queries per request and stage saturates CPU time
and stalls --watch passes.

Replace os.listdir with os.scandir in pending_keys and request_keys to collect
directory entries and stat attributes in a single pass. In watch mode, thread
an in-memory completed cache that tracks published requests and their stage
metadata (size, mtime), invalidating entries when stages are modified or
truncated and re-running container completeness checks.

Add --skip-failed (-s) and X2W_SKIP_FAILED=1 to skip requests whose .fail file
is newer than their ready marker. Add --jobs (-j) to configure worker
concurrency, separating option values from watch intervals and routing both
the explicit argument and X2W_TRANSLATE_JOBS through the Windows worker limit
(at most 61 workers).
@Holastor
Holastor force-pushed the perf/gfx2hlsl-watch-cache branch from c445bf1 to cf544ed Compare November 27, 2026 09:13
@Holastor

Copy link
Copy Markdown
Contributor Author

Addressed in commit cf544ede (rebased on upstream/main at e446b072):

Windows Worker Limit on Explicit --jobs (@R0Y00)

  • translation_jobs(jobs=None) now accepts an optional explicit worker limit. Both the explicit argument and the X2W_TRANSLATE_JOBS environment variable route through the same logic:
    def translation_jobs(jobs=None):
        if jobs is None:
            try:
                jobs = int(os.environ.get('X2W_TRANSLATE_JOBS') or 0)
            except ValueError:
                jobs = 0
        else:
            try:
                jobs = int(jobs)
            except (ValueError, TypeError):
                jobs = 0
        jobs = jobs if jobs > 0 else os.cpu_count() or 1
        return min(jobs, 61) if os.name == 'nt' else jobs
  • In translate_pending(), worker count resolution is updated to jobs = min(translation_jobs(jobs), len(keys)), ensuring that --pending ... --jobs 62 and --watch ... --jobs 62 never exceed 61 workers on Windows.
  • Added controls in tests/startup_gfx2hlsl_watch_check.py distinguishing the explicit and environment forms:
    • translation_jobs(62) returns 61 on Windows.
    • X2W_TRANSLATE_JOBS=62 returns 61 on Windows.
    • Explicit jobs argument overrides X2W_TRANSLATE_JOBS setting.
    • Synthetic test with 62 pending RTV markers:
      • Tests translate_pending with explicit jobs=62 (capped to 61).
      • Tests translate_pending with X2W_TRANSLATE_JOBS=62 (capped to 61).
      • Tests watch_pass forwarding explicit jobs=62 (capped to 61).
      • Live Windows subprocess runs for --pending DIR --jobs 62 and X2W_TRANSLATE_JOBS=62 exiting 0 without raising ValueError.

Test Verification

python -B tests/docs_links_check.py
python -B tests/bidi_controls_check.py
python -B tests/startup_gfx2hlsl_watch_check.py
python -B tests/startup_translator_check.py
python -B tests/startup_shader_cache_rekey_check.py
python -B tests/startup_gfx2hlsl_capture_check.py
python -B tests/run_checks_parallel_check.py

All passed with 0 failures on Windows 11 / Python 3.14.

@Holastor
Holastor requested a review from R0Y00 November 27, 2026 09:15

@R0Y00 R0Y00 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Windows worker-limit finding is resolved at cf544ede. I reviewed the shared worker normalization and re-ran the source-built checks on Windows 11 26200.9974 with Python 3.12, integrating this head with main through #2910 (local tree f38e423d). startup_gfx2hlsl_watch_check.py, startup_translator_check.py, startup_shader_cache_rekey_check.py, startup_gfx2hlsl_capture_check.py, startup_gfx2hlsl_refusals_check.py and startup_gfx2hlsl_load_desc_check.py all exited zero. The watch fixture exercises --jobs 62 through both the Windows pending CLI and the watch setup and keeps requests at or below the supported width. Its injected exceptions emitted their expected diagnostics. The required hosted Windows check passed.

@R0Y00
R0Y00 merged commit 98007de into R0Y00:main Nov 27, 2026
5 checks passed
@thepatrickworld

Copy link
Copy Markdown
Contributor

Post-merge receipt on 98007de5: the cached slot-57 verdict now agrees with the full scan on 13 of the 14 states this harness builds

Not a code change; measurements only. No action requested.

Why this is a delta and not a third report

My comment of 07:31 ended on a prediction about the size/mtime variant: it "flips 12 of these 13 rows; what it leaves is the row that preserves size and mtime, plus the .psdep row." On the merged tree the first half holds exactly and the second half does not: the .psdep row is closed as well. What follows is only that difference, measured on the commit that shipped.

Identity of what is measured

  • Merged tree 98007de5, in a separate worktree.
  • The predicate is byte-identical to the PR head. Reproduce with:
git show cf544ede:tools/startup/gfx2hlsl.py | sed -n '12593,12728p' | sha256sum
git show 98007de5:tools/startup/gfx2hlsl.py | sed -n '12691,12826p' | sha256sum

Both print 2fbb07adc75698b96fff430b2a4f858d2c51004ff07cec352ebacaa2573b65f8 (pending_keys, signature to end of body, 136 lines). The rest of the file differs by merges that landed in between, so a whole-blob comparison would have been the wrong instrument.

  • The PR's own fixture on the merged tree: python3 -B tests/startup_gfx2hlsl_watch_check.py prints translator errors raised from its own lambdas (startup_gfx2hlsl_watch_check.py:344) and still ends on startup_gfx2hlsl_watch_check passed, rc 0.
  • Control: the pre-fix head d1bf9f74 (gfx2hlsl.py sha256 cec19b0832306e0324fdaba41c8c445165a6b046b747478ec4d89f97f7f56f96), same harness, same directory states, same machine. Linux 7.0.0-38-generic, Python 3.11.16; no Windows, no GPU.

Method

Unchanged from 07:31: build a published request, fill completed with one full pass, mutate one file, then compare pending_keys(dir, False, completed=<copy of the cache>) (warm) with pending_keys(dir, False) (fresh). [] means the cache treats the result as done.

Result

states where the cache accepts what the full scan reports
pre-fix head d1bf9f74 14
merged 98007de5 1

Thirteen states moved from warm [] to a pending key: .ps57.cso and .ms57.cso truncated by one byte, both zero-byte stages, a bad header at the same size with a fresh mtime (both stages), parts = 0, parts beyond the container, one extra trailing byte, and the three ps none container states — all [0x57] — plus the graph-path state where a .psdep record appears, which is [0x2].

The row that remains is the one 07:31 named

.ps57.cso rewritten with the same byte count and its st_mtime restored: warm [], fresh [0x57]. The metadata recorded per published stage is (name, st_size, st_mtime) — written at lines 12806-12808, compared at 12748 — so a rewrite that restores both fields is invisible to the cache, while the same bad header with a fresh mtime is now rejected on both paths. That pair is what isolates the behaviour to the mtime rather than to the size or to the container check.

Limits

  • Twenty-five hand-built rows, one cached request per directory, 48-byte synthetic containers; not a real title and not a partition of malformed containers.
  • One host, Linux only. Nothing here touches Windows, the draw path, or any timing.

AI-assisted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants