mirror of
https://github.com/valentderah/totk-pc-recomp.git
synced 2026-11-24 13:45:57 +00:00
Merge pull request #1372: the shader-cache packer reads the loose files on up to 8 threads (half the logical CPUs, 1 below 512 MiB free memory, 32 MiB read ahead, serial reads on any failure), with a byte-identical pack (ShannoonRuaaa)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
1b303282a3
2 files changed
+269
-15
No files matched your search
@@ -1,14 +1,20 @@
|
||||
"""tools/pack_shader_cache.py on a fake shader cache: the pack layout gfx_shader.c reads (sorted index, bounds, data),
|
||||
loose files folded in and deleted, a second run merging new loose files, a loose file winning over its packed copy,
|
||||
malformed files skipped and --keep. No game files; stdlib only.
|
||||
malformed files skipped, --keep, and the parallel reads: same bytes as serial, the worker choice, the read-ahead caps
|
||||
and the fallback to serial reads when the parallel path fails. No game files; stdlib only.
|
||||
|
||||
Run: python tests/pack_shader_cache_test.py
|
||||
"""
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import shutil
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from concurrent.futures import Future
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
@@ -24,6 +30,25 @@ def name(seed):
|
||||
return hashlib.sha256(seed.encode()).hexdigest()
|
||||
|
||||
|
||||
class InlinePool:
|
||||
"""Stands in for ThreadPoolExecutor: runs each read at submit, records the submits, and raises the error of a
|
||||
thread that does not start after fail_after of them."""
|
||||
|
||||
def __init__(self, submitted, fail_after=None):
|
||||
self.submitted, self.fail_after = submitted, fail_after
|
||||
|
||||
def submit(self, fn, *args):
|
||||
if self.fail_after is not None and len(self.submitted) >= self.fail_after:
|
||||
raise RuntimeError("can't start new thread")
|
||||
self.submitted.append(args)
|
||||
future = Future()
|
||||
future.set_result(fn(*args))
|
||||
return future
|
||||
|
||||
def shutdown(self, wait=True, cancel_futures=False):
|
||||
pass
|
||||
|
||||
|
||||
def read_pack(path):
|
||||
"""{(kind, name hex): bytes}, checking what gfx_shader.c pack_open checks."""
|
||||
b = path.read_bytes()
|
||||
@@ -102,6 +127,112 @@ class PackTest(unittest.TestCase):
|
||||
self.assertTrue((self.cache / f'{k}.spv').exists())
|
||||
self.assertEqual(len(read_pack(self.cache / psc.PACK)), 4)
|
||||
|
||||
def test_parallel_pack_is_byte_identical_for_fresh_and_incremental_inputs(self):
|
||||
for i in range(80):
|
||||
self.shader(str(i))
|
||||
serial = self.cache.parent / 'serial'
|
||||
shutil.copytree(self.cache, serial)
|
||||
self.assertEqual(psc.pack(self.cache, read_workers=8), psc.pack(serial, read_workers=1))
|
||||
self.assertEqual((self.cache / psc.PACK).read_bytes(), (serial / psc.PACK).read_bytes())
|
||||
self.shader('new')
|
||||
(self.cache / f'{name("0")}.res.json').write_bytes(b'{"changed":true}')
|
||||
(self.cache / f'{name("use1")}.use').write_bytes(b'invalid loose copy')
|
||||
shutil.copytree(self.cache, serial, dirs_exist_ok=True)
|
||||
self.assertEqual(psc.pack(self.cache, read_workers=8), psc.pack(serial, read_workers=1))
|
||||
self.assertEqual((self.cache / psc.PACK).read_bytes(), (serial / psc.PACK).read_bytes())
|
||||
|
||||
def test_prefetch_preserves_order_and_bounds_inflight_reads(self):
|
||||
keys = [(1, bytes([i])) for i in range(100)]
|
||||
# The first yielded result must not require reading every file; only the bounded prefetch can start.
|
||||
with mock.patch.object(psc, 'read_loose', return_value=b'data') as read:
|
||||
iterator = psc.prefetched_files(keys, dict.fromkeys(keys, Path('fixture')), 3)
|
||||
self.assertEqual(next(iterator), (keys[0], b'data'))
|
||||
self.assertLessEqual(read.call_count, 6)
|
||||
self.assertEqual([key for key, _ in iterator], keys[1:])
|
||||
|
||||
def test_read_workers_follow_the_cpus_and_free_memory(self):
|
||||
plenty = 8 << 30
|
||||
for cpus, want in ((None, 1), (1, 1), (2, 1), (3, 1), (4, 2), (6, 3), (8, 4), (12, 6), (16, 8), (64, 8)):
|
||||
with self.subTest(cpus=cpus):
|
||||
self.assertEqual(psc.read_workers(cpus, plenty), want)
|
||||
self.assertEqual(psc.read_workers(cpus, None), want) # free memory unknown: by the CPUs alone
|
||||
self.assertEqual(psc.read_workers(24, psc.LOW_FREE_RAM - 1), 1)
|
||||
self.assertEqual(psc.read_workers(24, psc.LOW_FREE_RAM), 8)
|
||||
self.assertEqual(psc.read_workers(24, 0), 1)
|
||||
|
||||
def test_pack_without_read_workers_uses_the_machine_choice(self):
|
||||
self.shader('a')
|
||||
with mock.patch.object(psc, 'machine_read_workers', return_value=(1, 'test')) as choice:
|
||||
self.assertEqual(psc.pack(self.cache)[0], 4)
|
||||
choice.assert_called_once()
|
||||
with mock.patch.object(psc.hostmem, 'available_ram', side_effect=OSError('no answer')):
|
||||
self.assertEqual(psc.machine_read_workers()[0], psc.read_workers(psc.os.cpu_count(), None))
|
||||
|
||||
def test_read_ahead_stays_under_the_byte_cap_and_a_large_file_goes_alone(self):
|
||||
mib = 1 << 20
|
||||
keys = [(1, bytes([i])) for i in range(40)]
|
||||
sizes = {k: 10 * mib for k in keys}
|
||||
sizes[keys[20]] = 100 * mib # larger than the cap on its own
|
||||
loose = dict.fromkeys(keys, Path('fixture'))
|
||||
submitted = []
|
||||
with mock.patch.object(psc, 'ThreadPoolExecutor', lambda max_workers: InlinePool(submitted)), \
|
||||
mock.patch.object(psc, 'read_loose', return_value=b'x'):
|
||||
got = []
|
||||
for key, _ in psc.prefetched_files(keys, loose, 8, sizes, max_bytes=32 * mib):
|
||||
ahead = keys[len(got):len(submitted)] # read and not yet given out, this one included
|
||||
self.assertTrue(sum(sizes[k] for k in ahead) <= 32 * mib or ahead == [key], (key, len(ahead)))
|
||||
self.assertLessEqual(len(ahead), 16)
|
||||
got.append(key)
|
||||
self.assertEqual(got, keys)
|
||||
|
||||
def test_a_failing_parallel_path_falls_back_to_serial_reads(self):
|
||||
for i in range(80):
|
||||
self.shader(str(i))
|
||||
reference = self.cache.parent / 'reference'
|
||||
shutil.copytree(self.cache, reference)
|
||||
psc.pack(reference, read_workers=1)
|
||||
main_thread = threading.main_thread()
|
||||
|
||||
def no_thread_after_forty(max_workers):
|
||||
return InlinePool([], fail_after=40)
|
||||
|
||||
def no_executor(max_workers):
|
||||
raise RuntimeError("can't start new thread")
|
||||
|
||||
real_read = psc.read_loose
|
||||
calls = [0]
|
||||
|
||||
def out_of_memory_in_a_reader(path):
|
||||
if threading.current_thread() is not main_thread:
|
||||
calls[0] += 1
|
||||
if calls[0] > 30:
|
||||
raise MemoryError()
|
||||
return real_read(path)
|
||||
|
||||
failures = {
|
||||
'thread start': mock.patch.object(psc, 'ThreadPoolExecutor', no_thread_after_forty),
|
||||
'executor': mock.patch.object(psc, 'ThreadPoolExecutor', no_executor),
|
||||
'reader MemoryError': mock.patch.object(psc, 'read_loose', out_of_memory_in_a_reader),
|
||||
}
|
||||
for what, failure in failures.items():
|
||||
with self.subTest(failure=what):
|
||||
cache = self.cache.parent / what.replace(' ', '-')
|
||||
shutil.copytree(self.cache, cache)
|
||||
out = io.StringIO()
|
||||
with failure, contextlib.redirect_stdout(out):
|
||||
n, new, skipped, _ = psc.pack(cache, read_workers=8)
|
||||
self.assertIn('parallel reads failed', out.getvalue())
|
||||
self.assertEqual((n, new, skipped), (320, 320, 0))
|
||||
self.assertEqual((cache / psc.PACK).read_bytes(), (reference / psc.PACK).read_bytes())
|
||||
self.assertEqual(sorted(p.name for p in cache.iterdir()), [psc.PACK])
|
||||
|
||||
def test_an_error_of_the_caller_is_not_taken_for_a_reader_failure(self):
|
||||
keys = [(1, bytes([i])) for i in range(10)]
|
||||
iterator = psc.prefetched_files(keys, {}, 4)
|
||||
next(iterator)
|
||||
with self.assertRaises(ValueError):
|
||||
iterator.throw(ValueError('disk full'))
|
||||
|
||||
def test_a_broken_pack_is_rebuilt_from_the_loose_files(self):
|
||||
self.shader('a')
|
||||
(self.cache / psc.PACK).write_bytes(b'garbage')
|
||||
|
||||
+137
-14
@@ -15,23 +15,39 @@ bytes sorted by (kind, name): name (the 32 bytes the file name's 64 hex digits s
|
||||
--keep leaves the loose files in place. Close the game first: a running totk.exe has read the old pack's index.
|
||||
"""
|
||||
import argparse
|
||||
from collections import deque
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from itertools import islice
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import hostmem
|
||||
|
||||
MAGIC = b'TKSPACK1'
|
||||
PACK = 'shader-cache.pack'
|
||||
KINDS = {'.spv': 1, '.res.json': 2, '.use': 3, '.in': 4}
|
||||
NAME = re.compile(r'([0-9a-f]{64})(\.spv|\.res\.json|\.use|\.in)')
|
||||
USE_SIZE = 20 # gfx_shader.c use_store: magic, version, three masks
|
||||
MAX_ENTRIES = 1 << 24 # gfx_shader.c pack_open's index limit
|
||||
MAX_READERS = 8
|
||||
# File data read ahead of the writer. The cache's files are 20 B to ~0.5 MiB (a 1.4.3 install: 117k files, 1.5 GiB),
|
||||
# so the count limit (two files per reader) binds first; this cap keeps a cache of unusually large files from holding
|
||||
# 16 of them in memory at once.
|
||||
READ_AHEAD_BYTES = 32 << 20
|
||||
# Below this much free RAM the files are read one at a time, as before the readers existed. It is 16 times the
|
||||
# read-ahead cap, so the parallel path never asks for more than a sixteenth of what is free; under it the machine is
|
||||
# already paging, and extra concurrent reads only compete with the page-ins of the other programs.
|
||||
LOW_FREE_RAM = 512 << 20
|
||||
|
||||
|
||||
def loose_files(cache):
|
||||
"""{(kind, name): path} of the cache's loose files; *.in only in in/."""
|
||||
found = {}
|
||||
"""({(kind, name): path}, {(kind, name): size}) of the cache's loose files; *.in only in in/. The sizes come with
|
||||
the directory listing on Windows and bound the read-ahead in prefetched_files."""
|
||||
found, sizes = {}, {}
|
||||
for folder, kinds in ((cache, (1, 2, 3)), (cache / 'in', (4,))):
|
||||
if not folder.is_dir():
|
||||
continue
|
||||
@@ -42,8 +58,10 @@ def loose_files(cache):
|
||||
continue
|
||||
kind = KINDS[m.group(2)]
|
||||
if kind in kinds:
|
||||
found[(kind, bytes.fromhex(m.group(1)))] = Path(e.path)
|
||||
return found
|
||||
key = (kind, bytes.fromhex(m.group(1)))
|
||||
found[key] = Path(e.path)
|
||||
sizes[key] = e.stat().st_size
|
||||
return found, sizes
|
||||
|
||||
|
||||
def read_pack(path):
|
||||
@@ -80,11 +98,102 @@ def valid(kind, data):
|
||||
return len(data) == USE_SIZE if kind == 3 else len(data) > 0
|
||||
|
||||
|
||||
def pack(cache, keep=False):
|
||||
def read_workers(cpus=None, free=None):
|
||||
"""Readers for this machine: one per two logical CPUs (one per core on SMT CPUs), 1 to MAX_READERS, and 1 when
|
||||
less than LOW_FREE_RAM is free. A reader spends its time in the kernel and in the antivirus scan of each opened
|
||||
file, which runs on threads of its own, so half the logical CPUs keep the disk and the scanner busy and leave the
|
||||
rest to them and to the setup window; a 1- or 2-CPU machine reads one file at a time. cpus: os.cpu_count();
|
||||
free: hostmem.available_ram(), None when unknown."""
|
||||
if free is not None and free < LOW_FREE_RAM:
|
||||
return 1
|
||||
return min(MAX_READERS, max(1, (cpus or 1) // 2))
|
||||
|
||||
|
||||
def machine_read_workers():
|
||||
"""read_workers() for this machine and a line saying why, for the log."""
|
||||
cpus = os.cpu_count()
|
||||
try:
|
||||
free = hostmem.available_ram()
|
||||
except (OSError, AttributeError, ValueError): # no answer from the OS: decide by the CPU count alone
|
||||
free = None
|
||||
n = read_workers(cpus, free)
|
||||
known = 'free memory unknown' if free is None else f'{free / 2**20:.0f} MiB free memory'
|
||||
return n, f'{n} reader{"s" if n > 1 else ""} ({cpus} CPUs, {known})'
|
||||
|
||||
|
||||
def read_loose(path):
|
||||
if path is not None:
|
||||
try:
|
||||
return path.read_bytes()
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def parallel_reads(keys, loose, workers, sizes, max_bytes):
|
||||
"""(key, data) in the order of keys, read on a pool of workers threads. At most 2 * workers files and max_bytes of
|
||||
their data (by the listed size) are read ahead of the caller; a file larger than max_bytes is read alone."""
|
||||
pool = ThreadPoolExecutor(max_workers=workers)
|
||||
try:
|
||||
pending, held = deque(), 0 # (key, future or None, bytes reserved), and the reserved bytes in total
|
||||
following = iter(keys)
|
||||
key = next(following, None)
|
||||
while True:
|
||||
while key is not None and len(pending) < 2 * workers:
|
||||
size = sizes.get(key, 0) if key in loose else 0
|
||||
if pending and held + size > max_bytes:
|
||||
break
|
||||
pending.append((key, pool.submit(read_loose, loose[key]) if key in loose else None, size))
|
||||
held += size
|
||||
key = next(following, None)
|
||||
if not pending:
|
||||
return
|
||||
done, future, size = pending.popleft()
|
||||
data = future.result() if future else None
|
||||
held -= size
|
||||
yield done, data
|
||||
finally:
|
||||
pool.shutdown(wait=True, cancel_futures=True)
|
||||
|
||||
|
||||
def prefetched_files(keys, loose, workers, sizes=None, max_bytes=READ_AHEAD_BYTES):
|
||||
"""(key, loose file's bytes or None) for every key in order, the same bytes as a serial read so the pack comes out
|
||||
identical. workers > 1 reads ahead on threads (parallel_reads). Any failure of that path (a thread that does not
|
||||
start, a MemoryError in a reader, an executor error) switches to serial reads from the first key not yet given
|
||||
out, so the pack still completes; a file that cannot be read gives None in either path."""
|
||||
given = 0
|
||||
if workers > 1:
|
||||
reads = parallel_reads(keys, loose, workers, sizes or {}, max_bytes)
|
||||
while True:
|
||||
try:
|
||||
item = next(reads)
|
||||
except StopIteration:
|
||||
return
|
||||
except Exception as e: # noqa: BLE001 the serial path below reads the rest
|
||||
print(f'pack-cache: parallel reads failed ({type(e).__name__}: {e}); reading the remaining '
|
||||
f'{len(keys) - given} files one at a time', flush=True)
|
||||
try:
|
||||
reads.close()
|
||||
except Exception: # noqa: BLE001 the pool is dropped either way
|
||||
pass
|
||||
break
|
||||
yield item # outside the try: errors of the caller never reach the fallback
|
||||
given += 1
|
||||
for key in islice(keys, given, None):
|
||||
yield key, read_loose(loose.get(key))
|
||||
|
||||
|
||||
def pack(cache, keep=False, read_workers=None, progress=None):
|
||||
"""Fold the loose files into the pack. read_workers: concurrent file reads, 1..16; None picks them for the
|
||||
machine (machine_read_workers)."""
|
||||
if read_workers is None:
|
||||
read_workers = machine_read_workers()[0]
|
||||
if not 1 <= read_workers <= 16:
|
||||
raise ValueError('read_workers must be 1..16')
|
||||
cache = Path(cache)
|
||||
out = cache / PACK
|
||||
packed = read_pack(out)
|
||||
loose = loose_files(cache)
|
||||
loose, sizes = loose_files(cache)
|
||||
if not loose:
|
||||
# Nothing to fold in: every file of the cache is already in the pack, so writing it again copies the same
|
||||
# bytes over the same entries (1.37 GiB here, 2.6 s, and a file system that then has the old pack's blocks to
|
||||
@@ -97,13 +206,10 @@ def pack(cache, keep=False):
|
||||
try:
|
||||
with open(tmp, 'wb') as f:
|
||||
f.write(bytes(offset)) # header and index, written once the offsets are known
|
||||
for key in keys:
|
||||
data = None
|
||||
for done, (key, data) in enumerate(prefetched_files(keys, loose, read_workers, sizes), 1):
|
||||
if progress and (done == len(keys) or done % 128 == 0):
|
||||
progress('read', done, len(keys))
|
||||
if key in loose: # a valid loose file, else the packed copy, else nothing
|
||||
try:
|
||||
data = loose[key].read_bytes()
|
||||
except OSError:
|
||||
pass
|
||||
if data is not None and valid(key[0], data):
|
||||
written.append(loose[key])
|
||||
else:
|
||||
@@ -126,8 +232,10 @@ def pack(cache, keep=False):
|
||||
old.close()
|
||||
os.replace(tmp, out)
|
||||
if not keep:
|
||||
for p in written:
|
||||
for done, p in enumerate(written, 1):
|
||||
p.unlink(missing_ok=True)
|
||||
if progress and (done == len(written) or done % 128 == 0):
|
||||
progress('cleanup', done, len(written))
|
||||
try:
|
||||
(cache / 'in').rmdir() # only when empty
|
||||
except OSError:
|
||||
@@ -139,10 +247,25 @@ def main():
|
||||
ap = argparse.ArgumentParser(description='Fold a shader cache into shader-cache.pack.')
|
||||
ap.add_argument('cache', type=Path, help='the shader-cache folder next to totk.exe')
|
||||
ap.add_argument('--keep', action='store_true', help='keep the loose files')
|
||||
ap.add_argument('--read-workers', type=int, choices=range(1, 17), metavar='1..16',
|
||||
help='concurrent file reads (default: half the logical CPUs, 1 to 8, and 1 with less than '
|
||||
f'{LOW_FREE_RAM >> 20} MiB free memory; 1 reads serially)')
|
||||
a = ap.parse_args()
|
||||
if not a.cache.is_dir():
|
||||
sys.exit(f'{a.cache} is not a folder')
|
||||
n, new, skipped, size = pack(a.cache, a.keep)
|
||||
if a.read_workers:
|
||||
workers = a.read_workers
|
||||
print(f'pack-cache: {workers} reader{"s" if workers > 1 else ""} (--read-workers)', flush=True)
|
||||
else:
|
||||
workers, why = machine_read_workers()
|
||||
print(f'pack-cache: {why}', flush=True)
|
||||
last_progress = [0.0]
|
||||
def progress(phase, done, total):
|
||||
now = time.monotonic()
|
||||
if done == total or now - last_progress[0] >= 5:
|
||||
print(f'pack-cache: {phase}: {done} of {total} files', flush=True)
|
||||
last_progress[0] = now
|
||||
n, new, skipped, size = pack(a.cache, a.keep, workers, progress)
|
||||
print(f'{a.cache / PACK}: {n} files, {size / 2**20:.0f} MiB ({new} loose files folded in'
|
||||
f'{", " + str(skipped) + " unreadable or empty skipped" if skipped else ""})', flush=True)
|
||||
|
||||
|
||||
Reference in new issue
Block a user