Repository navigation
startup: accelerate gfx2hlsl cache scans and support skipping earlier failures - #2899
Conversation
|
Independent Linux result on Not a code change; measurements only. Environment
1. The fixture passes, and the rewrite returns the same key set as
|
fde6cbd to
d1bf9f7
Compare
|
Thanks @thepatrickworld for the thorough review, differential testing (250 caches x 4 modes), and mutation analysis! Updated at
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.pyAll passed (29 MD files/545 links checked, 2046 source files clean, all checks passed). |
KelboLive
left a comment
There was a problem hiding this comment.
What works
os.scandir()replacement inrequest_keys()andpending_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.- The in-memory
completedmap is a smart optimization: by tracking published requests and their.psin/.txtmtimes, 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.csostages. - Comprehensive cache invalidation tests (P1–P4: rewritten description, withdrawn manifest, lost bytecode, zero-byte bytecode) are thorough and follow the test-first style well.
--skip-failed(-s) andX2W_SKIP_FAILED=1give users control over whether to reprocess known-unsupported requests — useful for incremental development workflows.--jobs/-jCLI flag parallelsX2W_TRANSLATE_JOBSwell, and the ProcessPoolExecutor limit of 61 on Windows is correctly preserved.- CLI parsing is careful:
suppress(ValueError)guards against invalid numeric arguments, and the interval argument scanning (skipping--prefixed args) is robust.
Issues
-
request_keys()scandir scope: The new implementation filtersentry.name.startswith('req_')then relies on the regex to validate the extension. The old code had no pre-filter. This is functionally equivalent but thestartswithcheck could benefit from a comment noting it's intentional (not allreq_*files are ready markers). -
completeddict threading: Thecompletedparameter is threaded throughwatch_pass()→translate_pending()→pending_keys(). While correct, consider adding# threading completed across watch iterationsas a doc comment at the entry pointwatch_pass()to help future readers understand why this parameter exists. -
pending_keysearly exit: The new code addsif not keys: returnintranslate_pending(). This is a useful early return, but the original function already iteratedkeysin a loop — this just avoids themin(jobs, len(keys))calculation. Worth noting but not a bug. -
skip_faileddefault behavior change: The old code hadskip_failed = False(always retry first pass) hardcoded in the--watchbranch. The new code parses--skip-failedfromsys.argv[1:]before the--watchbranch, 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. -
request_keys()early return: The newtry/except OSErrorreturnsNone(implicit) instead of[]. This is fine sincerequest_keysis a generator, but the comment should note thatOSErrorduring scandir means "no requests" rather than "error encountered."
Recommendations
- Consider adding a
cache_statscounter (hits vs. misses incompleted) to the--pendingscan output when--verboseor--debugis 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 withos.utime()after creation for cross-platform reliability (some Windows filesystems have lower mtime resolution). - Consider documenting
X2W_SKIP_FAILED=1as 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(): thecompletedparameter threading is clear.translate_pending(): early return whenkeysis 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, andX2W_SKIP_FAILED.
R0Y00
left a comment
There was a problem hiding this comment.
Two regressions reproduce on d1bf9f74 integrated with main c09145a7.
- 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(), populatedcompletedwith 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-onlyps nonecase. Add a warm-cache truncation control. gfx2hlsl.py --watch DIR --jobs 4callstranslate_pendingwithoutjobsand sleeps for4.0seconds. 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 reacheswatch_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.
|
Independent result on 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. EnvironmentLinux 7.0.0-38, Python 3.11.16, 2 vCPU. No GPU and no Windows in the loop: The cached verdict is wider than the truncationMethod: build a published request, fill
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 ( One more, separate: the cache entry does not carry the dependency record, so a What closing it costs2000 published slot-57 pairs, 20 samples per variant, four interleaved rounds, medians of 40:
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 Either way The control I would addSmallest one I could make bite: publish a complete slot-57 pair, run one pass with a Where the worker count still does not arrive
LimitsOne 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 AI-assisted. |
d1bf9f7 to
c445bf1
Compare
|
Addressed review feedback and verified on commit 1. Warm Slot-57 Container Invalidation (@R0Y00, @thepatrickworld)
2.
|
R0Y00
left a comment
There was a problem hiding this comment.
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).
c445bf1 to
cf544ed
Compare
|
Addressed in commit Windows Worker Limit on Explicit
|
R0Y00
left a comment
There was a problem hiding this comment.
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.
|
Post-merge receipt on Not a code change; measurements only. No action requested. Why this is a delta and not a third reportMy 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 Identity of what is measured
Both print
MethodUnchanged from 07:31: build a published request, fill Result
Thirteen states moved from warm The row that remains is the one 07:31 named
Limits
AI-assisted. |
Summary
In caches with tens of thousands of requests (e.g. 16,000+ files),
pending_keysandrequest_keysintools/startup/gfx2hlsl.pyrepeatedly calledos.listdir()and invokedos.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--watchpasses to saturate CPU time and stall for several seconds or minutes on large sets of already-refused requests.This change:
os.listdirwithos.scandirinpending_keysandrequest_keys, collecting directory entries and their stat attributes (st_mtime,st_size) in a single pass in memory.completedmap passed across--watchiterations: 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-onlyps nonecases).--skip-failed(-s) CLI flag andX2W_SKIP_FAILED=1environment variable. When set, one-shot--pendingscans and the initial--watchpass skip requests whose.failfile is newer than their ready marker and stream description, avoiding repeated refusal processing across large known-unsupported request sets.--jobs(-j) CLI flag to configure worker concurrency alongsideX2W_TRANSLATE_JOBS. CLI argument parsing separates option values from positional interval arguments, ensuring--watch <dir> --jobs 4does not treat the worker count as the sleep interval.--jobsargument and theX2W_TRANSLATE_JOBSenvironment variable throughtranslation_jobs(jobs=None), uniformly enforcing the Windows worker limit (max_workers <= 61) across one-shot--pendingand--watchmodes.docs/startup-runtime.mdand extendstests/startup_gfx2hlsl_watch_check.pyto verify caching, stage truncation invalidation (dual stage andps none),--skip-failed, and worker pool capping controls across 62 synthetic requests.Evidence
Unit tests and link checks:
Commit cf544ed, rebased on upstream/main at e446b07. Windows 11, Python 3.14.
All passed with 0 failures:
startup_gfx2hlsl_watch_check passed(including warm-cache truncation controls,--watch --jobsCLI parsing controls, and 62-request Windows worker capping controls)startup translator checks: 0 failedSelf-test passed. Checked 40 Markdown files and 555 links.no bidirectional controlsrun_checks_parallel_check: okBenchmark on synthetic and real request caches:
pending_keysscan time reduced from ~680 ms to ~22 ms.--watchtick with no new requests reduced from ~410 ms to ~17 ms..failrequests):python -B tools/startup/gfx2hlsl.py --pending <dir> --skip-failedcompleted in 196.8 ms.