Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -1105,19 +1105,19 @@ Archive each run's logs together with a copy of `shader_cache/`, and leave the c

When the translator handles more, the next `--pending` pass retries the waiting requests from the same cache. This holds only while the pipeline key is unchanged. The key hashes a translation revision string (`x2w-startup-shader-N`, in `pipeline_key` in `gfx2hlsl.py` and in the runtime). After a revision change the runtime asks for new keys, and the old requests stay in the cache.

**Re-key the old requests after a revision change.** The new cache is cold, so a run would have to request every pipeline again. `tools/startup/shader_cache_rekey.py` copies the graphics, RTV variant and slot 67 compute requests of the old cache under the keys of the current revision, computed with `pipeline_key` and `compute_key` of the `gfx2hlsl.py` next to it. Stop the title and any `--pending` loop first; nothing else may write the cache. Then:
**Re-key the old requests after a revision change.** The new cache is cold, so a run would have to request every pipeline again. `tools/startup/shader_cache_rekey.py` copies graphics, RTV variant, slot 67 compute and slot 57 mesh requests under their current keys. It uses `pipeline_key`, `compute_key` and `mesh57_key` from the adjacent `gfx2hlsl.py` and updates each RTV variant with its new graphics key. Stop the title and any `--pending` loop first; nothing else may write the cache. Then:

```powershell
.\out\pe-env\Scripts\python.exe -B tools\startup\shader_cache_rekey.py out\startup\shader_cache out\startup\shader_cache_rekeyed
.\out\pe-env\Scripts\python.exe -B tools\startup\gfx2hlsl.py --pending out\startup\shader_cache_rekeyed
robocopy out\startup\shader_cache_rekeyed out\startup\shader_cache /XC /XN /XO
```

1. The re-key step only reads the old cache and writes request files (`req_*`) only, never results or `.fail`. A file already in the new directory is left as it is, so a second run writes nothing. It reads every request before it writes: if a part is missing or unreadable, or an RTV variant is malformed or names a base that is not in the cache, it prints how many, writes nothing and exits with 1. Slot 57 and slot 86 mesh requests have their own key strings and are not re-keyed. `X2W_TRANSLATE_JOBS` sets the number of hashing processes.
1. The re-key step reads the old cache and writes only request files (`req_*`). A file already in the new directory is left as it is, so a second run writes nothing. It reads every request before it writes. If a part is missing or unreadable, or an RTV variant is malformed or names a base that is not in the cache, it prints how many, writes nothing and exits with 1. A slot 57 request requires `.ps57`, `.root` and the `.m57` ready marker. The `.ps57` file is empty when there is no pixel stage. Slot 86 mesh requests are only counted. `X2W_TRANSLATE_JOBS` sets the number of hashing processes.
2. `--pending` translates the re-keyed requests offline, as it does for a running title's cache.
3. The `robocopy` switches skip every file that already exists in the cache, so results the runtime or a later pass wrote are kept. A `robocopy` exit code below 8 means success: 1 is set when files were copied, and 2 is set because the cache holds files that the new directory does not. A code of 8 or more is a failure. On Linux, run the same steps with `./out/pe-env/bin/python` and merge with `cp -rn out/startup/shader_cache_rekeyed/. out/startup/shader_cache/`, which also keeps existing files.

`tests/startup_shader_cache_rekey_check.py` checks the tool on synthetic requests only: the names match the current keys, a newer revision gives other names, a second run and a current cache change nothing, and an incomplete request or an RTV variant without its base writes nothing. Re-keying recovers the requests, not the translations: some re-keyed pipelines can still fail to translate, which is separate from the cache key. Nothing here shows that a title runs.
`tests/startup_shader_cache_rekey_check.py` checks the tool on synthetic requests only: the names match the current keys, a newer graphics and compute revision gives other names for those requests, a second run and a current cache change nothing, and an incomplete request or an RTV variant without its base writes nothing. Re-keying recovers the requests, not the translations: some re-keyed pipelines can still fail to translate, which is separate from the cache key. Nothing here shows that a title runs.

When `fxc` is available, a request that later translates loses its `.fail`. In manifest-only mode (`X2W_FXC` empty) the old `.fail` stays, so on a kept cache the `.fail` categories in `triage.md` can include pipelines that now have a `.txt`. That table counts category tokens over all `.fail` files, up to `--max-items`.

Expand Down
57 changes: 41 additions & 16 deletions tests/startup_shader_cache_rekey_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@

- An old cache holds requests of the older revision (two graphics requests, one with an input layout, one
compute request, an RTV variant of the first graphics request), one current-revision graphics request, the same
pipeline as the first at the current revision, a mesh request, a result and a .fail. Their old names differ
from pipeline_key / compute_key of the current revision.
pipeline as the first at the current revision, an old and a current slot 57 mesh request, a slot 86 marker,
a result and a .fail. Old request names differ from the current pipeline_key, compute_key or mesh57_key.
- The tool, run as a script with two hashing processes, writes exactly the current names with the same bytes
(the RTV variant re-keyed to its new base), no results or .fail, and gfx2hlsl.pending_keys lists them.
- With the newer revision the same requests get other names again.
- With the newer graphics and compute revision those requests and the RTV variant get other names again.
- A second run writes nothing; re-keying a current cache keeps every name.
- A missing request part, a truncated RTV variant or an RTV variant whose base request is missing exits with 1
and creates nothing.
Expand Down Expand Up @@ -75,12 +75,19 @@ def gkey(module, parts):
COMPUTE = {'.desc': struct.pack('<12Q', *range(12)), '.sa': struct.pack('<7I', *range(7)), '.sb': b'\x05' * 20,
'.data': struct.pack('<2Q', 0x1122334455667788, 0x99), '.root': b'RTS0 synthetic compute root',
'.c67': struct.pack('<2I', 0x7e020280, 0xbf810000)}
MESH_OLD = {'.ps57': b'', '.root': b'RTS0 synthetic mesh root', '.m57': b'synthetic mesh'}
MESH_CURRENT = {'.ps57': b'synthetic pixel stage', '.root': b'RTS0 synthetic mesh root',
'.m57': b'another synthetic mesh'}


def ckey(module, parts):
return module.compute_key(parts['.c67'], parts['.data'], parts['.root'], parts['.desc'], parts['.sa'], parts['.sb'])


def mkey(module, parts):
return module.mesh57_key(parts['.m57'], parts['.ps57'], parts['.root'])


def rtv_text(base):
return 'rtv1 %d 28 87' % base

Expand Down Expand Up @@ -108,7 +115,7 @@ def run(src, dst, jobs='2'):
env=env, timeout=120)


def expected_files(module, requests, computes, rtv_bases):
def expected_files(module, requests, computes, rtv_bases, meshes):
"""{name: bytes} of the requests named under module's revision."""
files = {}
for parts in requests:
Expand All @@ -120,6 +127,9 @@ def expected_files(module, requests, computes, rtv_bases):
for parts in rtv_bases:
text = rtv_text(gkey(module, parts)).encode('ascii')
files['req_%016x.rtv' % G.fnv(text)] = text
for parts in meshes:
for ext, data in parts.items():
files['req_%016x%s' % (mkey(module, parts), ext)] = data
return files


Expand All @@ -143,7 +153,12 @@ def main():
old_rtv = write_rtv(src, gkey(older, g1))
write_request(src, gkey(G, g1), g1) # the same pipeline at the current revision
write_request(src, gkey(G, g3), g3) # current only
write_request(src, 0x123456789abcdef0, {'.ps57': b'', '.root': b'RTS0 mesh', '.m57': b'\x01' * 8})
meshes = (MESH_OLD, MESH_CURRENT)
old_mesh = mkey(G, MESH_OLD) ^ 1
mesh_keys = {mkey(G, parts) for parts in meshes}
write_request(src, old_mesh, MESH_OLD)
write_request(src, mkey(G, MESH_CURRENT), MESH_CURRENT)
write_request(src, 0x123456789abcdef0, {'.m86': b'synthetic slot 86 marker'})
(src / ('%016x.txt' % gkey(older, g1))).write_text('synthetic result\n')
(src / ('%016x.fail' % gkey(older, g2))).write_text('synthetic refusal\n')
before = snapshot(src)
Expand All @@ -152,22 +167,26 @@ def main():
current_names = {gkey(G, g1), gkey(G, g2), ckey(G, COMPUTE)}
check('older-revision names differ from the current keys', not old_names & current_names)

# (a) re-keyed names are pipeline_key / compute_key of the current revision, with the same bytes.
# (a) re-keyed names use the current key functions, with the same bytes.
dst = tmp / 'rekeyed'
first = run(src, dst)
check('re-key exits 0', first.returncode == 0, first.stderr.strip())
want = expected_files(G, (g1, g2, g3), (COMPUTE,), (g1,))
want = expected_files(G, (g1, g2, g3), (COMPUTE,), (g1,), meshes)
got = contents(dst) if dst.is_dir() else {}
check('re-keyed files are exactly the current requests', got == want,
'extra %s missing %s' % (sorted(set(got) - set(want)), sorted(set(want) - set(got))))
check('no results or .fail written', all(name.startswith('req_') for name in got))
check('graphics summary counts the duplicate and the current request',
'graphics: 4 requests, 2 already current -> 3 keys' in first.stdout, first.stdout)
check('mesh request counted, not re-keyed', 'm57 1, m86 0' in first.stdout, first.stdout)
check('mesh summary counts the old and current slot 57 requests',
'm57: 2 requests, 1 already current -> 2 keys' in first.stdout, first.stdout)
check('slot 86 marker is only counted', 'not re-keyed (own key strings): m86 1' in first.stdout,
first.stdout)
pending = G.pending_keys(str(dst), False)
rtv_new = G.fnv(rtv_text(gkey(G, g1)).encode('ascii'))
check('gfx2hlsl.pending_keys lists the re-keyed requests',
pending == sorted({gkey(G, g1), gkey(G, g2), gkey(G, g3), ckey(G, COMPUTE), rtv_new}), pending)
pending == sorted({gkey(G, g1), gkey(G, g2), gkey(G, g3), ckey(G, COMPUTE), rtv_new} | mesh_keys),
pending)

# (e) the RTV variant names the new base and is named by the hash of its new text.
rtv_file = dst / ('req_%016x.rtv' % rtv_new)
Expand All @@ -186,7 +205,8 @@ def main():
third = run(dst, again, jobs='1')
check('current requests keep their names', third.returncode == 0 and contents(again) == want
and 'graphics: 3 requests, 3 already current -> 3 keys' in third.stdout
and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout, third.stdout + third.stderr)
and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout
and 'm57: 2 requests, 2 already current -> 2 keys' in third.stdout, third.stdout + third.stderr)

# (b) under a newer revision the same requests get other names (in process: one job keeps the patch).
R.g, saved = newer, R.g
Expand All @@ -198,18 +218,23 @@ def main():
R.g = saved
got_newer = contents(newest) if newest.is_dir() else {}
check('newer revision re-keys to its own names', code == 0
and got_newer == expected_files(newer, (g1, g2, g3), (COMPUTE,), (g1,)))
check('newer names differ from the current names', not set(got_newer) & set(want))
and got_newer == expected_files(newer, (g1, g2, g3), (COMPUTE,), (g1,), meshes))
check('only mesh names are shared between the graphics and compute revisions',
set(got_newer) & set(want) == set(expected_files(G, (), (), (), meshes)))

# (f) negative controls: an incomplete request, a truncated RTV variant or an RTV variant without its base
# request writes nothing. Without the base's ready marker (.a) there is one graphics request less: 5, not 6.
# request writes nothing. Without the base's ready marker (.a), the request count drops from 8 to 7.
for label, total, reason, damage in (
('missing .root', 6, 'unreadable req_%016x.root' % gkey(older, g2),
('missing .root', 8, 'unreadable req_%016x.root' % gkey(older, g2),
lambda d: (d / ('req_%016x.root' % gkey(older, g2))).unlink()),
('truncated RTV variant', 6, '.rtv text does not hash to its name',
('missing slot 57 .root', 8, 'unreadable req_%016x.root' % old_mesh,
lambda d: (d / ('req_%016x.root' % old_mesh)).unlink()),
('missing slot 57 .ps57', 8, 'unreadable req_%016x.ps57' % old_mesh,
lambda d: (d / ('req_%016x.ps57' % old_mesh)).unlink()),
('truncated RTV variant', 8, '.rtv text does not hash to its name',
lambda d: (d / ('req_%016x.rtv' % old_rtv)).write_bytes(
rtv_text(gkey(older, g1)).encode('ascii')[:-3])),
('missing RTV base', 5, '.rtv base request %016x is not a complete graphics request' % gkey(older, g1),
('missing RTV base', 7, '.rtv base request %016x is not a complete graphics request' % gkey(older, g1),
lambda d: (d / ('req_%016x.a' % gkey(older, g1))).unlink())):
bad = tmp / ('bad_' + label.replace(' ', '_'))
shutil.copytree(src, bad)
Expand Down
4 changes: 2 additions & 2 deletions tests/startup_shader_cache_rekey_cli_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def test_positive_main_argv_none_and_subprocess(self):
rc, stdout, stderr = _run_main([str(src), str(dst_argv)])
self.assertEqual(rc, 0, stderr)
self.assertEqual(stderr, "")
self.assertIn("m57 0, m86 1", stdout)
self.assertIn("not re-keyed (own key strings): m86 1", stdout)
expected_names = sorted([
f"req_{keys['g']:016x}.a",
f"req_{keys['g']:016x}.b",
Expand Down Expand Up @@ -116,7 +116,7 @@ def test_positive_main_argv_none_and_subprocess(self):
)
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertEqual(proc.stderr, "")
self.assertIn("m57 0, m86 1", proc.stdout)
self.assertIn("not re-keyed (own key strings): m86 1", proc.stdout)
self.assertEqual(sorted(p.name for p in dst_sub.iterdir()), expected_names)

def test_usage_and_path_guards(self):
Expand Down
30 changes: 17 additions & 13 deletions tools/startup/shader_cache_rekey.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@

usage: shader_cache_rekey.py <old cache dir> <new request dir>

The key of a graphics request (req_<key>.a), of an RTV variant (req_<key>.rtv) and of a device slot 67 compute
request (req_<key>.c67) hashes the translation revision string (pipeline_key and compute_key in gfx2hlsl.py).
Graphics (req_<key>.a), slot 67 compute (req_<key>.c67) and slot 57 mesh (req_<key>.m57) request keys hash their
translation revision strings (pipeline_key, compute_key and mesh57_key in gfx2hlsl.py). RTV variants
(req_<key>.rtv) hash text containing the graphics key.
After a revision change the runtime asks for new keys, so a kept cache is cold again. This tool recomputes the
key of every such request with the gfx2hlsl.py next to it and copies the request files under the new names into
<new request dir>. `gfx2hlsl.py --pending <new request dir>` can then translate them without a running title.

The old cache is only read. Only request files (req_*) are written; results and .fail files are not, and a file
that already exists in <new request dir> is left as it is. Each file is written to a temporary name and renamed;
the ready marker (.a, .c67) goes last, as the runtime writes it. Slot 57 and slot 86 mesh requests have their own
key strings and are only counted.
the ready marker (.a, .c67, .m57) goes last, as the runtime writes it. Slot 86 mesh requests are only counted.

All requests are read before anything is written. When a request part is missing or unreadable, or an RTV
variant is malformed, does not match its own name or names a base request that is not in the cache, the tool
Expand All @@ -29,7 +29,8 @@

REQUEST = re.compile(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57|m86)')
# Request files of each kind; the ready marker is last.
PARTS = {'g': ('.b', '.root', '.ia', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67')}
PARTS = {'g': ('.b', '.root', '.ia', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67'),
'm57': ('.ps57', '.root', '.m57')}
OPTIONAL = {'.ia'} # a graphics request without an input layout has no .ia


Expand Down Expand Up @@ -61,6 +62,8 @@ def current_key(job):
return kind, key, None, 'unreadable %s: %s' % (os.path.basename(error.filename or ''), error.strerror)
if kind == 'g':
return kind, key, g.pipeline_key(p['.a'], p['.b'], p['.root'], p.get('.ia', b'')), None
if kind == 'm57':
return kind, key, g.mesh57_key(p['.m57'], p['.ps57'], p['.root']), None
return kind, key, g.compute_key(p['.c67'], p['.data'], p['.root'], p['.desc'], p['.sa'], p['.sb']), None


Expand Down Expand Up @@ -111,7 +114,8 @@ def rekey(src, dst, jobs=None, out=None):
if os.path.exists(dst) and os.path.samefile(src, dst):
print('error: the new request dir must not be the old cache', file=sys.stderr)
return 2
found = {'g': [], 'c': [], 'rtv': [], 'm57': 0, 'm86': 0}
found = {kind: [] for kind in (*PARTS, 'rtv')}
m86 = 0
try:
entries = sorted(os.listdir(src))
except OSError as error:
Expand All @@ -122,12 +126,12 @@ def rekey(src, dst, jobs=None, out=None):
if not m:
continue
key, ext = int(m.group(1), 16), m.group(2)
if ext in ('m57', 'm86'):
found[ext] += 1
if ext == 'm86':
m86 += 1
else:
found[{'a': 'g', 'c67': 'c', 'rtv': 'rtv'}[ext]].append(key)
found[{'a': 'g', 'c67': 'c'}.get(ext, ext)].append(key)

work = [(src, kind, key) for kind in ('g', 'c') for key in found[kind]]
work = [(src, kind, key) for kind in PARTS for key in found[kind]]
jobs = min(jobs or g.translation_jobs(), len(work))
if jobs < 2:
results = [current_key(job) for job in work]
Expand All @@ -136,7 +140,7 @@ def rekey(src, dst, jobs=None, out=None):
with ProcessPoolExecutor(max_workers=jobs) as pool:
results = list(pool.map(current_key, work, chunksize=max(1, len(work) // (jobs * 4))))

new = {'g': {}, 'c': {}}
new = {kind: {} for kind in PARTS}
bad = []
for kind, old, key, reason in results:
if reason:
Expand Down Expand Up @@ -165,7 +169,7 @@ def rekey(src, dst, jobs=None, out=None):
return 1
stats = {'written': 0, 'kept': 0}
try:
for kind, label in (('g', 'graphics'), ('c', 'compute')):
for kind, label in (('g', 'graphics'), ('c', 'compute'), ('m57', 'm57')):
done = set()
for old, key in sorted(new[kind].items()):
if key in done: # requests of the same pipeline from several revisions
Expand All @@ -182,7 +186,7 @@ def rekey(src, dst, jobs=None, out=None):
print('error: failed writing %s: %s' % (dst, error), file=sys.stderr)
return 1
print('rtv variants: %d requests -> %d keys' % (len(found['rtv']), len(rtv)), file=out)
print('not re-keyed (own key strings): m57 %d, m86 %d' % (found['m57'], found['m86']), file=out)
print('not re-keyed (own key strings): m86 %d' % m86, file=out)
print('files: %d written, %d already present in %s' % (stats['written'], stats['kept'], dst), file=out)
return 0

Expand Down
Loading