Size the shader cache readers for the machine and fall back to serial reads on any failure

pack_shader_cache.py picked 8 readers on every machine. It now takes half the logical CPUs, 1 to 8, so a 1- or
2-CPU PC reads one file at a time, and reads serially with less than 512 MiB free RAM (tools/hostmem.py, as the
compile and lift workers use). --read-workers still overrides; the log names the choice.

The read-ahead is also capped at 32 MiB of file data by the listed sizes, beside the two files per reader; a file
larger than the cap is read alone.

Any failure of the parallel path (a thread that does not start, a MemoryError in a reader, an executor error) prints
a line and reads the remaining files serially, so the pack still completes with the same bytes.

Tests cover the worker choice, the byte cap and the three fallbacks, each giving the same pack as a serial run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Valiantsin DzerakhandClaude Opus 5.5 committed 2026-11-23 14:27:09 +03:00
1 parent a80cb1e35d
commit c581b779fa
2 files changed
+219 -31

No files matched your search

+110 -4
View File
@@ -1,15 +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
import shutil
from concurrent.futures import Future
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
@@ -25,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()
@@ -120,13 +144,95 @@ class PackTest(unittest.TestCase):
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.
from unittest.mock import patch
with patch.object(psc, 'read_loose', return_value=b'data') as read:
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')