From cf544ede87bdf1f4628b86bccac880060dc27058 Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:49:00 +0500 Subject: [PATCH] startup: accelerate gfx2hlsl cache scans and support skipping earlier 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). --- docs/startup-runtime.md | 19 +- tests/startup_gfx2hlsl_watch_check.py | 290 +++++++++++++++++++++++++- tools/startup/gfx2hlsl.py | 249 +++++++++++++++++----- 3 files changed, 489 insertions(+), 69 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 886a6dc4fd..1348572d76 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -907,23 +907,28 @@ and Dispatch takes). The cache persists: a later run reads every published `.fail` is newer than its ready marker is not retried during the run (the runtime writes each request once and never rewrites -it). The one-shot `--pending` scan retries every failure. An unexpected translator error is written -to `.fail` as `translator error: ...`, ending with the function, file name and line that raised -it, skipping standard-library frames (`(in scalar_select, gfx2hlsl.py line 1234)`), instead of -stopping the scan. An operand refusal +it). The one-shot `--pending` scan retries every failure unless `--skip-failed` (`-s`) or +`X2W_SKIP_FAILED=1` is set, which skips requests whose `.fail` is already up to date with their +ready marker and stream description. During `--watch`, published requests are kept in an in-memory +completion set so repeated passes skip re-reading container bytecode from disk when +request files, descriptions and published stage metadata are unchanged. An unexpected +translator error is written to `.fail` as `translator error: ...`, ending with the function, file +name and line that raised it, skipping standard-library frames (`(in scalar_select, gfx2hlsl.py line 1234)`), +instead of stopping the scan. An operand refusal in `.fail` names the instruction that refused it (`operand '-v30' in v_and_b32_e64`); the refusal's own message, which `--refusals` counts, stays `operand '-v30'`. A worker killed from outside (for example out of memory) ends that watcher pass only; its requests are retried on the next pass. FXC is located as described for `X2W_SHADER_CACHE` under [Switches](#switches). A scan with more than one pending request translates them in parallel processes, one per logical processor (at most 61 on -Windows, the `ProcessPoolExecutor` limit) unless `X2W_TRANSLATE_JOBS` sets the count; each request -writes only its own files. On a 16-thread host, +Windows, the `ProcessPoolExecutor` limit) unless `--jobs ` (`-j ` or `--jobs=`) or +`X2W_TRANSLATE_JOBS` sets the count; each request writes only its own files. On a 16-thread host, 3,513 requests (132 translated, 3,381 refused) took 56.9 s with one process and 7.8 s in parallel, with byte-identical results. Check with `python3 -B tests/startup_gfx2hlsl_watch_check.py` (ctest `startup_gfx2hlsl_watch`): a request without its ready marker is not consumed, the watcher retries an earlier failure once and -then leaves failures alone, it translates a request written while it runs, four parallel workers +then leaves failures alone, `--skip-failed` skips up-to-date failures, the in-memory cache skips +published requests without re-checking container bytecode, four parallel workers print the same results and write the same failures as one, an unexpected translator error becomes `.fail`, and an invalid `X2W_TRANSLATE_JOBS` falls back to the processor count. `startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it together diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py index 946900b026..548df23a86 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -3,13 +3,15 @@ A request is consumed only once its ready marker (.a or .rtv) exists and it is not finished: a published .txt with both .cso files (or a .txt under X2W_FXC='') is done; a .txt without bytecode is resumed. After the watcher's first pass, a request whose .fail is newer than its marker is not -retried; the first pass and the one-shot --pending scan retry it. The --watch process must retry an -earlier failure once, translate a new request while it runs and not rewrite a failure on later -passes. A --pending scan with four parallel workers must print the same results and write the same -failures as one worker, an unexpected translator error must become .fail, a broken process -pool must end one watcher pass and not the watcher, and an invalid X2W_TRANSLATE_JOBS must fall -back to the processor count. +retried; the first pass and the one-shot --pending scan retry it unless --skip-failed (-s) or +X2W_SKIP_FAILED=1 is set. The --watch process must retry an earlier failure once, translate a new +request while it runs and not rewrite a failure on later passes. An in-memory completed cache skips +published requests whose stage metadata has not changed without re-reading container bytecode on disk. A --pending scan with four +parallel workers must print the same results and write the same failures as one worker, an +unexpected translator error must become .fail, a broken process pool must end one watcher pass +and not the watcher, and an invalid X2W_TRANSLATE_JOBS falls back to the processor count. """ +from contextlib import suppress import json import os import re @@ -77,6 +79,135 @@ def local(text): # the temporary directory differs between runs; keep the file touch(d / ('%016x.txt' % 9)) expect('watch pass', scan(d, True), [1, 5, 6, 9]) expect('one-shot pass', scan(d, False), [1, 4, 5, 6, 9]) + completed = {} + expect('pass with completed dict', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + expect('published key cached in completed', 2 in completed, True) + expect('rescan with completed matches', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + + # Cache invalidation P1: req_.psin rewritten newer than published manifest drops key 2 from completed and rechecks + touch(d / ('req_%016x.psin' % 2), b'new description', mtime=now + 5) + expect('cache invalidation on rewritten description', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 2, 4, 5, 6, 9]) + expect('key 2 invalidated from completed', 2 in completed, False) + (d / ('req_%016x.psin' % 2)).unlink() + expect('cache re-populates completed', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + expect('key 2 re-cached', 2 in completed, True) + + # Cache invalidation P2: manifest withdrawn (deleted) drops key 2 from completed and rechecks + (d / ('%016x.txt' % 2)).unlink() + expect('cache invalidation on withdrawn manifest', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 2, 4, 5, 6, 9]) + expect('key 2 invalidated on withdrawn manifest', 2 in completed, False) + touch(d / ('%016x.txt' % 2)) + expect('cache re-populates after manifest restored', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + expect('key 2 re-cached', 2 in completed, True) + + # Cache invalidation P3: bytecode lost (deleted stage file) drops key 2 from completed and rechecks + (d / ('%016x.vs.cso' % 2)).unlink() + expect('cache invalidation on lost bytecode stage', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 2, 4, 5, 6, 9]) + expect('key 2 invalidated on lost stage', 2 in completed, False) + touch(d / ('%016x.vs.cso' % 2), b'DXBC') + expect('cache re-populates after bytecode restored', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + expect('key 2 re-cached', 2 in completed, True) + + # Cache invalidation P4: bytecode truncated to zero size drops key 2 from completed and rechecks + touch(d / ('%016x.vs.cso' % 2), b'') + expect('cache invalidation on zero-byte bytecode stage', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 2, 4, 5, 6, 9]) + expect('key 2 invalidated on zero-byte stage', 2 in completed, False) + touch(d / ('%016x.vs.cso' % 2), b'DXBC') + expect('cache re-populates after zero-byte restored', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + expect('key 2 re-cached', 2 in completed, True) + +with tempfile.TemporaryDirectory() as tmp: + d_cli = Path(tmp) + now = time.time() + for ext in ('.b', '.root'): + touch(d_cli / ('req_%016x%s' % (4, ext))) + touch(d_cli / ('req_%016x.a' % 4), mtime=now - 10) + touch(d_cli / ('%016x.fail' % 4), b'prior refusal\n', mtime=now - 5) + # Default one-shot --pending retries key 4 (failure is present but retried) + out_default = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_cli), '--jobs=1'], + capture_output=True, text=True, timeout=30) + expect('default --pending retries failure', ('%016x:' % 4) in out_default.stdout, True) + # With --skip-failed, key 4 is skipped and no translation is performed + out_skip = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_cli), '--skip-failed', '-j', '1'], + capture_output=True, text=True, timeout=30) + expect('--skip-failed skips up-to-date failure', ('%016x:' % 4) in out_skip.stdout, False) + # With -s short flag + out_s = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_cli), '-s', '--jobs=1'], + capture_output=True, text=True, timeout=30) + expect('-s skips up-to-date failure', ('%016x:' % 4) in out_s.stdout, False) + # With X2W_SKIP_FAILED=1 + env_skip = dict(os.environ, X2W_SKIP_FAILED='1') + out_env = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_cli), '--jobs=1'], + capture_output=True, text=True, timeout=30, env=env_skip) + expect('X2W_SKIP_FAILED=1 skips up-to-date failure', ('%016x:' % 4) in out_env.stdout, False) + + # --watch CLI argument parsing: worker count (--jobs / -j) must reach watch_pass and interval must be parsed separately. + observed_watch = [] + real_watch_pass = gfx2hlsl.watch_pass + real_sleep = time.sleep + try: + def mock_watch_pass_single(out_dir, skip_failed, jobs=None, completed=None): + observed_watch.append(('pass', jobs)) + raise KeyboardInterrupt + + def mock_sleep(secs): + observed_watch.append(('sleep', secs)) + + gfx2hlsl.watch_pass = mock_watch_pass_single + time.sleep = mock_sleep + + saved_argv = sys.argv + try: + # --watch --jobs 4: jobs must be 4, interval must remain default 2.0 (not read 4 as interval) + sys.argv = ['gfx2hlsl.py', '--watch', str(d_cli), '--jobs', '4'] + observed_watch.clear() + with suppress(KeyboardInterrupt): + gfx2hlsl.main() + expect('--watch --jobs 4 passes jobs to watch_pass', observed_watch, [('pass', 4)]) + + # --watch 3.5 --jobs 4: interval is 3.5, jobs is 4 + pass_count = [0] + def mock_watch_pass_multi(out_dir, skip_failed, jobs=None, completed=None): + pass_count[0] += 1 + observed_watch.append(('pass', jobs)) + if pass_count[0] >= 2: + raise KeyboardInterrupt + return True + + gfx2hlsl.watch_pass = mock_watch_pass_multi + sys.argv = ['gfx2hlsl.py', '--watch', str(d_cli), '3.5', '--jobs', '4'] + observed_watch.clear() + with suppress(KeyboardInterrupt): + gfx2hlsl.main() + expect('--watch 3.5 --jobs 4 parses interval and passes jobs', observed_watch, + [('pass', 4), ('sleep', 3.5), ('pass', 4)]) + + # --watch --jobs=4: jobs is 4, interval is default 2.0 + pass_count[0] = 0 + sys.argv = ['gfx2hlsl.py', '--watch', str(d_cli), '--jobs=4'] + observed_watch.clear() + with suppress(KeyboardInterrupt): + gfx2hlsl.main() + expect('--watch --jobs=4 passes jobs and keeps default interval', observed_watch, + [('pass', 4), ('sleep', 2.0), ('pass', 4)]) + + # --watch -j 4: jobs is 4, interval is default 2.0 + pass_count[0] = 0 + sys.argv = ['gfx2hlsl.py', '--watch', str(d_cli), '-j', '4'] + observed_watch.clear() + with suppress(KeyboardInterrupt): + gfx2hlsl.main() + expect('--watch -j 4 passes jobs and keeps default interval', observed_watch, + [('pass', 4), ('sleep', 2.0), ('pass', 4)]) + finally: + sys.argv = saved_argv + finally: + gfx2hlsl.watch_pass = real_watch_pass + time.sleep = real_sleep def mesh57_fixture(ms, ps, expected, tamper=False): root = (b'DXBC' + bytes(24) + struct.pack('= 1, True) + expect('translation_jobs(%r)' % value, gfx2hlsl.translation_jobs(value) >= 1, True) os.environ['X2W_TRANSLATE_JOBS'] = '2' expect('X2W_TRANSLATE_JOBS=2', gfx2hlsl.translation_jobs(), 2) if saved is None: @@ -252,6 +435,97 @@ def broken(out_dir, skip_failed=False): else: os.environ['X2W_TRANSLATE_JOBS'] = saved +# Both environment variable and explicit argument route through the Windows limit of 61 workers. +saved_os_name = os.name +saved_env = os.environ.get('X2W_TRANSLATE_JOBS') +try: + os.name = 'nt' + # Environment form + os.environ['X2W_TRANSLATE_JOBS'] = '62' + expect('X2W_TRANSLATE_JOBS=62 capped to 61 on Windows', gfx2hlsl.translation_jobs(), 61) + os.environ['X2W_TRANSLATE_JOBS'] = '60' + expect('X2W_TRANSLATE_JOBS=60 not capped on Windows', gfx2hlsl.translation_jobs(), 60) + # Explicit argument form + os.environ.pop('X2W_TRANSLATE_JOBS', None) + expect('translation_jobs(62) capped to 61 on Windows', gfx2hlsl.translation_jobs(62), 61) + expect('translation_jobs(60) not capped on Windows', gfx2hlsl.translation_jobs(60), 60) + # Explicit argument overrides environment variable + os.environ['X2W_TRANSLATE_JOBS'] = '10' + expect('explicit jobs 62 overrides environment variable to 61 on Windows', gfx2hlsl.translation_jobs(62), 61) + expect('explicit jobs 4 overrides environment variable to 4 on Windows', gfx2hlsl.translation_jobs(4), 4) +finally: + os.name = saved_os_name + if saved_env is None: + os.environ.pop('X2W_TRANSLATE_JOBS', None) + else: + os.environ['X2W_TRANSLATE_JOBS'] = saved_env + +# 62 synthetic pending RTV markers: verify worker pool capping across explicit and environment forms. +with tempfile.TemporaryDirectory() as tmp: + d_62 = Path(tmp) + for n in range(62): + req = b'rtv1 %d 28' % (0x9000 + n) + touch(d_62 / ('req_%016x.rtv' % gfx2hlsl.fnv(req)), req) + + from concurrent.futures import ProcessPoolExecutor as RealExecutor + observed_workers = [] + + class MockExecutor: + def __init__(self, max_workers=None, **kwargs): + observed_workers.append(max_workers) + + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + def map(self, fn, *iterables, **kwargs): + return [] + + sys.modules['concurrent.futures'].ProcessPoolExecutor = MockExecutor + try: + saved_os = os.name + os.name = 'nt' + try: + # 1. Explicit argument in translate_pending + del observed_workers[:] + gfx2hlsl.translate_pending(str(d_62), jobs=62) + expect('translate_pending with explicit jobs=62 capped to 61 on Windows', observed_workers, [61]) + + # 2. Environment variable in translate_pending + del observed_workers[:] + os.environ['X2W_TRANSLATE_JOBS'] = '62' + try: + gfx2hlsl.translate_pending(str(d_62)) + expect('translate_pending with X2W_TRANSLATE_JOBS=62 capped to 61 on Windows', observed_workers, [61]) + finally: + os.environ.pop('X2W_TRANSLATE_JOBS', None) + + # 3. Watch mode forwarding explicit jobs=62 + del observed_workers[:] + gfx2hlsl.watch_pass(str(d_62), skip_failed=True, jobs=62) + expect('watch_pass with explicit jobs=62 capped to 61 on Windows', observed_workers, [61]) + finally: + os.name = saved_os + finally: + sys.modules['concurrent.futures'].ProcessPoolExecutor = RealExecutor + + if os.name == 'nt': + # Live Windows CLI control: --pending with --jobs 62 executes without raising ValueError + res = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_62), '--jobs', '62'], + capture_output=True, text=True, timeout=120) + expect('CLI --pending --jobs 62 exits 0 on Windows', res.returncode, 0) + expect('no ValueError in stderr for --jobs 62', 'ValueError: max_workers must be <= 61' in res.stderr, False) + + res_env = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_62)], + capture_output=True, text=True, timeout=120, + env=dict(os.environ, X2W_TRANSLATE_JOBS='62')) + expect('CLI --pending X2W_TRANSLATE_JOBS=62 exits 0 on Windows', res_env.returncode, 0) + expect('no ValueError in stderr for env form', 'ValueError: max_workers must be <= 61' in res_env.stderr, False) + with tempfile.TemporaryDirectory() as tmp: d = Path(tmp) # A failure from an earlier run, newer than its marker: the watcher's first pass retries it once. diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 703e1f2d16..a1f62a33be 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -12242,7 +12242,16 @@ def translate_request(out_dir, key): def request_keys(out_dir, compute=False): """Graphics request keys (ready marker .a or .rtv), or with compute, slot 67 compute keys (.c67).""" pattern = r'req_([0-9a-f]{16})\.c67' if compute else r'req_([0-9a-f]{16})\.(?:a|rtv)' - for name in sorted(os.listdir(out_dir)): + names = [] + try: + for entry in os.scandir(out_dir): + # Fast filename pre-filter before regex matching. + if entry.name.startswith('req_') and entry.is_file(): + names.append(entry.name) + except OSError: + # Directory does not exist or cannot be scanned; yields no requests. + return + for name in sorted(names): match = re.fullmatch(pattern, name) if match: yield int(match.group(1), 16) @@ -12448,27 +12457,59 @@ def main(): for ext, blob in (('.a', a), ('.b', b), ('.root', root)): open(os.path.join(out_dir, 'req_%016x%s' % (key, ext)), 'wb').write(blob) print('pso %x -> request %016x' % (w & 0xffffff, key)) + skip_failed = any(arg in ('--skip-failed', '-s') for arg in sys.argv[1:]) or os.environ.get('X2W_SKIP_FAILED') in ('1', 'true', 'True') + jobs = None + args = sys.argv[1:] + i = 0 + while i < len(args): + arg = args[i] + if arg.startswith('--jobs='): + with suppress(ValueError): + jobs = int(arg.split('=', 1)[1]) + elif arg in ('-j', '--jobs') and i + 1 < len(args): + i += 1 + with suppress(ValueError): + jobs = int(args[i]) + i += 1 + if sys.argv[1] == '--watch': # --watch [seconds]: translate requests as a running title writes them, until stopped - interval = float(sys.argv[3]) if len(sys.argv) > 3 else 2.0 - # The first pass retries earlier failures once (the runtime never rewrites a request, so a - # translator fix would otherwise not reach them); later passes skip failures already written. - skip_failed = False + interval = 2.0 + args3 = sys.argv[3:] + i = 0 + while i < len(args3): + arg = args3[i] + if arg in ('-j', '--jobs'): + i += 2 + continue + if arg.startswith('-'): + i += 1 + continue + with suppress(ValueError): + interval = float(arg) + break + i += 1 + # The first pass retries earlier failures once unless --skip-failed / X2W_SKIP_FAILED is set; + # later passes skip failures already written. + completed = {} while True: - if watch_pass(out_dir, skip_failed): + if watch_pass(out_dir, skip_failed, jobs=jobs, completed=completed): skip_failed = True time.sleep(interval) - translate_pending(out_dir) + translate_pending(out_dir, skip_failed=skip_failed, jobs=jobs) -def watch_pass(out_dir, skip_failed): +def watch_pass(out_dir, skip_failed, jobs=None, completed=None): """One --watch pass. A worker killed from outside (out of memory) breaks the pool; the pass is - reported and its requests are retried on the next pass instead of ending the watcher.""" + reported and its requests are retried on the next pass instead of ending the watcher. + + The completed dict is threaded across watch iterations to avoid re-reading published stage bytecode. + """ from concurrent.futures.process import BrokenProcessPool try: - translate_pending(out_dir, skip_failed=skip_failed) + translate_pending(out_dir, skip_failed=skip_failed, jobs=jobs, completed=completed) return True except BrokenProcessPool as error: print('translation pass interrupted, retrying: %s' % error, file=sys.stderr, flush=True) @@ -12513,23 +12554,31 @@ def translate_one(out_dir, key): return reason -def translation_jobs(): - try: - jobs = int(os.environ.get('X2W_TRANSLATE_JOBS') or 0) - except ValueError: - jobs = 0 +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 # ProcessPoolExecutor refuses more than 61 on Windows -def translate_pending(out_dir, skip_failed=False, jobs=None): +def translate_pending(out_dir, skip_failed=False, jobs=None, completed=None): """Translate every request that has no result yet. The runtime writes the ready markers last. Requests are independent (each writes only its own .* files), so several run in parallel - processes; X2W_TRANSLATE_JOBS (default: the processor count, at most 61 on Windows) sets how many. + processes; X2W_TRANSLATE_JOBS or --jobs (default: the processor count, at most 61 on Windows) sets how many. """ - keys = pending_keys(out_dir, skip_failed) - jobs = min(jobs or translation_jobs(), len(keys)) + keys = pending_keys(out_dir, skip_failed, completed=completed) + if not keys: + return + jobs = min(translation_jobs(jobs), len(keys)) if jobs < 2: for key in keys: print('%016x: %s' % (key, translate_one(out_dir, key)), flush=True) @@ -12541,48 +12590,140 @@ def translate_pending(out_dir, skip_failed=False, jobs=None): print('%016x: %s' % (key, result), flush=True) -def pending_keys(out_dir, skip_failed): +def pending_keys(out_dir, skip_failed, completed=None): keys = [] manifest_only = os.environ.get('X2W_FXC') == '' - for name in sorted(os.listdir(out_dir)): - m = re.fullmatch(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57)', name) - if not m: + try: + entries = list(os.scandir(out_dir)) + except OSError: + return keys + + files = {} + req_items = [] + for entry in entries: + try: + if entry.is_file(): + files[entry.name] = entry + if entry.name.startswith('req_'): + m = re.fullmatch(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57)', entry.name) + if m: + req_items.append((entry.name, entry, m)) + except OSError: continue + + req_items.sort(key=lambda item: item[0]) + + for name, entry, m in req_items: key = int(m.group(1), 16) - result = os.path.join(out_dir, '%016x' % key) - mesh = m.group(2) == 'm57' - stages = ('.cs.cso',) if m.group(2) == 'c67' else ('.ms57.cso', '.ps57.cso') if mesh else ('.vs.cso', '.ps.cso') - ready_bytecode = has_complete_mesh57_bytecode if mesh else has_bytecode - manifest = result + ('.ms57.txt' if mesh else '.txt') - # A published manifest with bytecode (or manifest-only mode) is done; otherwise resume (#2008). The stream - # description the translation reads (request_source: the request's own, or an RTV variant's source - # pipeline's) is a dependency like the request file. Rewritten after the result was published, the result - # is checked again, so one translated with other masks is not kept in silence; rewritten after a refusal, - # the request is retried. + ext = m.group(2) + base_name = '%016x' % key + mesh = ext == 'm57' + stages = ('.cs.cso',) if ext == 'c67' else ('.ms57.cso', '.ps57.cso') if mesh else ('.vs.cso', '.ps.cso') + manifest_name = base_name + ('.ms57.txt' if mesh else '.txt') + + if completed is not None and key in completed: + saved = completed[key] + saved_req_mtime, saved_base, saved_psin_mtime = saved[:3] + saved_stage_meta = saved[3] if len(saved) > 3 else None + try: + current_req_mtime = entry.stat().st_mtime + except OSError: + current_req_mtime = None + if current_req_mtime == saved_req_mtime and manifest_name in files: + psin_name = 'req_%016x.psin' % saved_base + psin_entry = files.get(psin_name) + try: + current_psin_mtime = psin_entry.stat().st_mtime if psin_entry else None + except OSError: + current_psin_mtime = None + lost = current_psin_mtime is None and ((base_name + '.psdep') in files) + if current_psin_mtime == saved_psin_mtime and not lost: + if manifest_only: + continue + if saved_stage_meta is not None: + def stage_valid(s_name, s_size, s_mtime): + se = files.get(s_name) + if se is None: + return False + try: + st = se.stat() + return st.st_size == s_size and st.st_mtime == s_mtime + except OSError: + return False + if saved_stage_meta and all(stage_valid(sn, sz, mt) for sn, sz, mt in saved_stage_meta): + continue + described = None lost = False - if m.group(2) in ('a', 'rtv'): - with suppress(Unsupported, OSError, UnicodeError): # no description, or a variant line refused later - described = os.path.getmtime(request_source(out_dir, key)[3]) - # A result translated with a description recorded it (dependency_record). With that description gone, - # the result is checked again and withdrawn; a legacy request without a record is not read again. - lost = described is None and os.path.isfile(result + '.psdep') - if os.path.isfile(manifest) and not lost and not ( - described is not None and described > os.path.getmtime(manifest)): - if manifest_only or all(ready_bytecode(result + s) for s in stages): + base = key + if ext in ('a', 'rtv'): + if ext == 'rtv': + with suppress(Unsupported, OSError, UnicodeError): + _, base, _, _ = request_source(out_dir, key) + psin_name = 'req_%016x.psin' % base + psin_entry = files.get(psin_name) + if psin_entry is not None: + with suppress(OSError): + described = psin_entry.stat().st_mtime + lost = described is None and ((base_name + '.psdep') in files) + + manifest_entry = files.get(manifest_name) + manifest_mtime = None + if manifest_entry is not None: + with suppress(OSError): + manifest_mtime = manifest_entry.stat().st_mtime + + if manifest_entry is not None and not lost and not ( + described is not None and manifest_mtime is not None and described > manifest_mtime): + ready = False + published_stages = [] + if manifest_only: + ready = True + published_stages = [manifest_name] + elif mesh: + if all((base_name + s) in files and has_complete_mesh57_bytecode(os.path.join(out_dir, base_name + s)) for s in stages): + ready = True + published_stages = [manifest_name] + [base_name + s for s in stages] + elif (base_name + '.ms57.cso') in files and has_complete_mesh57_bytecode(os.path.join(out_dir, base_name + '.ms57.cso')): + with suppress(OSError), open(os.path.join(out_dir, manifest_name), 'rb') as published: + if b'ps none' in published.read().splitlines(): + ready = True + published_stages = [manifest_name, base_name + '.ms57.cso'] + else: + def stage_ok(s): + se = files.get(base_name + s) + if se is None: + return False + try: + return se.stat().st_size > 0 + except OSError: + return False + if all(stage_ok(s) for s in stages): + ready = True + published_stages = [manifest_name] + [base_name + s for s in stages] + + if ready: + if completed is not None: + with suppress(OSError): + stage_meta = tuple((name, files[name].stat().st_size, files[name].stat().st_mtime) + for name in published_stages if name in files) + completed[key] = (entry.stat().st_mtime, base, described, stage_meta) continue - if mesh and has_complete_mesh57_bytecode(result + '.ms57.cso'): - with suppress(OSError), open(manifest, 'rb') as published: - if b'ps none' in published.read().splitlines(): - continue - fail = os.path.join(out_dir, '%016x.fail' % key) - # A repeated pass retries a failure only once its request or its stream description is rewritten. A result - # still published without its recorded description is checked even with an older .fail, which a success on - # the manifest-only path leaves in place. - recheck = lost and os.path.isfile(manifest) - if skip_failed and not recheck and os.path.exists(fail) and os.path.getmtime(fail) >= max( - os.path.getmtime(os.path.join(out_dir, name)), described or 0): - continue + + if completed is not None: + completed.pop(key, None) + + fail_name = base_name + '.fail' + fail_entry = files.get(fail_name) + recheck = lost and (manifest_entry is not None) + if skip_failed and not recheck and fail_entry is not None: + try: + fail_mtime = fail_entry.stat().st_mtime + req_mtime = entry.stat().st_mtime + if fail_mtime >= max(req_mtime, described or 0): + continue + except OSError: + pass keys.append(key) return keys