mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
The compile cache is one file read and written in place, with nothing unpacked for a build, and one tool venv serves every game
The cache was a folder of a few files per shader, kept as a tar between builds and written back for each build that ran: 24,131 files and 10,150 folders on Skyward Sword HD, over 900,000 entries on Tears of the Kingdom. dm/tools/shader_cache.py keeps it as one SQLite file, shader/cache/cas.db, whose entries go in and out by name. Bytes are stored by their hash, since a library under its MSL's digest and its shader's digest was one APFS clone. dmsh_build.py and dmsh_mtlcache.py use it directly, so the chain version moves and each game translates again at its next build, with Metal compiles reused. A shader's entry is one transaction, several threads and processes share the file, pruning is a query that gives its pages back, a damaged file is made anew and a full drive is one red line.
A cas/ or cas.tar from before this moves in by itself at the next shader step. Only the Metal compile results come along: per-shader entries cannot hit after the chain change, and older fetch variants hold their source's file name (from before f2a50f35), so their bytes differ from a fresh compile's. Twelve recompiled to the bytes of a fresh baseline, none to the older entries'. That is what regress.py reported as changed variants with no change of MSL. A revision from before this keeps its own folder, regress/cas.
Measured on Skyward Sword HD: a 281 MB cas.tar became a 226 MB cas.db, restoring all 2,470 shaders took 6 s against 9 to 13 s, and a Mac build's shader folder holds 7 files. It also ran on an exFAT volume with three processes writing at once.
pack_quiet no longer tars a Python virtual environment, which would have broken the scripts that run it by path 14 days after it was last changed. .github/requirements/tools.txt pins what the tools import, for one venv at the top of the games' drive that work folders link to.
Tested: the game built and booted on the Mac on this chain with no red lines; all Python suites and the graphics tests; regress.py chain on Blasphemous passes, 617 of 617 shaders with no change of MSL, reflection or variants, on the chain before the final small edit to restore_cache. IPA and Mac app builds passed two chain versions earlier. No regress game runs, as asked. Not run on an iPhone.
Front-ends: interface: DMSH_CAS and the build folder's compile cache are the file shader/cache/cas.db instead of the folder shader/cache/cas or cas.tar, which moves in by itself.
This commit is contained in:
1 parent
cb34473fed
commit
7249ee9f95
22 files changed
+560
-143
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# What the repository's tools import beyond the standard library, pinned: the rewriter (capstone, lz4), the shader tools, and the rarer packers (zstandard, zbic, nsz, texture2ddecoder).
|
||||
# One environment serves every game: python3 -m venv <drive with the games>/venv && <that>/bin/pip install -r .github/requirements/tools.txt
|
||||
capstone==5.0.9
|
||||
fonttools==4.68.0
|
||||
lz4==4.4.5
|
||||
nsz==5.0.0
|
||||
numpy==2.5.4
|
||||
pillow==13.0.0
|
||||
texture2ddecoder==1.0.6
|
||||
zbic==1.0.1.post1
|
||||
zstandard==0.25.0
|
||||
@@ -19,7 +19,7 @@
|
||||
- Per-build knowledge is keyed by the NSO build ID: rewriter cuts, observation gates and frame-step stubs in the profile's `patches.py` (a game's own modules) or `dm/tools/sdk_patches.py` (Nintendo's `sdk` modules, which several games ship), which `dm/tools/patch_nso.py` (the general rewriter) loads, the profile's `build` rows (the builds the game was brought up on, and their display versions; the NSP script packs any other version from a derived profile, without those builds' fixes), and host behaviour that uses fixed module addresses checks `module_t.build_id` (from `fixups.tsv`; `dm_main_build()`). When a new game build appears, carry addresses over with `dm/tools/nso_fnmap.py` and check them by disassembly; never let fixed addresses run on a build they were not found in. For automatic cuts across updates, opt individual patches into `MATCH_CUTS` only after verifying their function fingerprints and assumptions; follow [Function-matched cuts](docs/reference/rewriter.md#function-matched-cuts-for-unregistered-builds). The shared matcher derives addresses from code; fixed addresses remain build-gated.
|
||||
- To analyse or port **another** Switch title, first run `scripts/build_ipa_from_nsp.py` on its NSP folder. With no matching profile, it writes a survey to `<NSP folder>/<title ID>_survey/survey.md`, then a provisional profile guessed from the game files (`dm/games/profile_guess.py`; `<build folder>/profile/<title ID>/`; found by the tools through `DM_GAMES_DIR`), with a short heap check on the Mac when the game has virtual address memory, and a best-effort IPA that may not boot. Then follow [docs/agents](docs/agents/README.md) (extraction, binary survey, host bring-up, graphics specifics, debugging recipes; the [symptom index](docs/agents/symptoms.md) for each failure) and add a profile with its note.
|
||||
- Scripts the user runs live in `scripts/` at the repository root. Each one runs from a terminal (non-zero exit on error). `build_ipa_from_nsp.py` also runs in Spyder (F5, configured by the settings block at its top; command-line options override those settings). Tools that only agents or other scripts call stay under `dm/`.
|
||||
- Game files, keys and anything extracted from them live in the game's NSP folder, never in this repository and never in the home folder (it is nearly full): the work folder `<NSP folder>/<id>-work` for extraction, runs and analysis, beside the NSP script's `<id>_build/`. Tool venvs and other large scratch data go on that drive too. Do not print key values.
|
||||
- Game files, keys and anything extracted from them live in the game's NSP folder, never in this repository and never in the home folder (it is nearly full): the work folder `<NSP folder>/<id>-work` for extraction, runs and analysis, beside the NSP script's `<id>_build/`. One tool venv serves every game (`<drive>/venv`); other large scratch data goes there too. Do not print key values.
|
||||
- Language: everything is in English. Red log lines (something unimplemented or wrong) start with `[RED] `. Text that must match a game's own Chinese data is written as escapes (`"\xE8\xB5\xB7"`), never as characters.
|
||||
- The shader translation chain has one version for every game, `DMSH_CHAIN` in `dm/gfx/nvn/dmsh_chain.h`, which the host is compiled with and loads only libraries of. It covers the chain's tools: `dm/gfx/tools/dmsh_*` (`dmsh_build.py`, `dmsh_chain.py`, `dmsh_fetch.py`, `dmsh_vin.py`, `dmsh_pull.py` with its decoder `dmsh_pull.metal`, `dmsh_geometry.py`, `dmsh_facts.py`), `Program.cs`, `ios_metal.py`, `dm/gfx/nvn/dmsh_abi.h` and `dmsh_chain.lock`. A profile's own inputs (`shader_map.tsv`, `shader_facts.tsv`, `shader_pairs.tsv`, `bf_want.tsv`, its `shader_*` / `nvn_*` keys) are not part of it: they are in each shader's cache key, and their digest stamps the libraries (`b-<V>/inputs.tsv`). The procedure:
|
||||
1. After changing a chain tool, run `dmsh_chain.py --header` once and commit `dm/gfx/nvn/dmsh_chain.h` with the change (`dm/tools/tests/test_nsp_chain.py` fails on a stale one).
|
||||
|
||||
@@ -35,6 +35,7 @@ The work folder is `<NSP folder>/01002DA013484000-work`, with `boot.sh`, `ctl.sh
|
||||
|
||||
General host changes first needed here; each applies to every game:
|
||||
|
||||
- **The compile cache as one file, read in place** (`shader_cache.py`): [The compile cache was unpacked for each build](../../../docs/reference/packing.md#the-compile-cache-was-unpacked-for-each-build).
|
||||
- **The shader libraries as one file, read in place** (`shader_lib.py`, `msl_image.h`): [Shader libraries take a file per shader variant](../../../docs/reference/packing.md#shader-libraries-take-a-file-per-shader-variant). Measured here: the route from `save_ref` to the file list, 6,600 frames from the folder and from the image, with no `[RED]` line in either and pictures alike.
|
||||
- **Logic operations on normalized targets** (`dmsh_logic.py` `dm_logic_norm`, `nvn_mtl.m` `lop_key`, `unorm_chan_masks`): [Logic operations through a library of its own](../../../docs/reference/rendering.md#logic-operations-through-a-library-of-its-own).
|
||||
- **Plain gzip around a shader archive** (`shader_split.py` `ungzip`): [Gzip-wrapped shader archives](../../../docs/reference/shaders.md#gzip-wrapped-shader-archives).
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
// Generated file (dm/gfx/tools/dmsh_chain.py --header): the B shader library translation chain version this source tree expects (default options), one for every game;
|
||||
// the host loads only <library dir>/b-<V>/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change
|
||||
#define DMSH_CHAIN "6e0c43ea7b30"
|
||||
#define DMSH_CHAIN "223f10d34f97"
|
||||
+35
-31
@@ -4,17 +4,17 @@
|
||||
# Source of query answers: the answer table in the game profile, dm/games/<id>/shader_facts.tsv (dmsh_facts.py) - texture types, vertex attribute / fragment output component types, compute thread group size and shared memory.
|
||||
# Usage: dmsh_build.py <Switch package dir> <output cache dir> [key...] (no keys = all); build output is actually written to <output cache dir>/b-<chain version>/ (same for IOSOUT), for the chain version see dmsh_chain.py.
|
||||
# A full build (no keys) also stamps both directories with the game and the digest of its profile inputs (inputs.tsv) and writes the profile's c1_full.tsv and cb_extent.tsv (c1_guard.py, cb_extent.py)
|
||||
# from its Mac outputs. One output directory per game: the chain version is the same for every game Environment: DM_GAME=game profile (required, dm/games/<id>), XLATE=path to the translation tool (default the in-repo dmsh_xlate_bin), DMSH_CAS=content-addressed cache dir (default <output cache dir>/cas), DMSH_PREFILL=Mac library root[=iOS library root] (separated by :, their b-*/ go into the MSL-keyed compile cache first; sibling b-*/ always do), J=concurrency
|
||||
# from its Mac outputs. One output directory per game: the chain version is the same for every game Environment: DM_GAME=game profile (required, dm/games/<id>), XLATE=path to the translation tool (default the in-repo dmsh_xlate_bin), DMSH_CAS=the compile cache, one file (shader_cache.py; default <output cache dir>/cas.db), DMSH_PREFILL=Mac library root[=iOS library root] (separated by :, their b-*/ go into the MSL-keyed compile cache first; sibling b-*/ always do), J=concurrency
|
||||
# Build output: <key>_b.metallib, <key>_b.json (replay reflection, including drv_reads, the runtime read offsets into driver segments c0 / c2), <key>_b.metal (MSL)
|
||||
# Environment IOSOUT=dir: the same MSL also goes through dm/ios/tools/ios_metal.compile to produce an iphoneos metallib + reflection (chain_metal records the iOS compile convention)
|
||||
# Final summary: success / failure counts and the distribution of reasons; distribution of driver segment read offsets (those outside the range the replay layer can fill are listed separately);
|
||||
# a [RED] line per shader that built but lost something (shader_regressions.report_losses), which does not change the exit status
|
||||
import inspect, os, re, sys, json, mmap, struct, hashlib, shutil, subprocess, tempfile, collections, threading, concurrent.futures as cf
|
||||
import atexit, inspect, os, re, sys, json, mmap, struct, hashlib, shutil, subprocess, tempfile, collections, threading, concurrent.futures as cf
|
||||
import dmsh_geometry, dmsh_atomic, dmsh_wide, dmsh_meshstage, dmsh_abi as abi # abi: the driver segment layout and the binding kinds the host shares (dm/gfx/nvn/dmsh_abi.h)
|
||||
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # Workspace root (game files, build outputs and run artifacts are all under it)
|
||||
HOME = os.path.expanduser('~')
|
||||
dm_dir, out = sys.argv[1:3]; want = set(sys.argv[3:]); cache_root = out
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))); import dmsh_chain, dmsh_fetch, dmsh_facts, dmsh_mtlcache, dmsh_pch, dmsh_vin, dmsh_pull, dmsh_side, dmsh_mesh, dmsh_ampere, shader_regressions, tool_lock # translation chain version: verify the tools against the lock file first; build output goes into b-<V>/
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))); import dmsh_chain, dmsh_fetch, dmsh_facts, dmsh_mtlcache, dmsh_pch, dmsh_vin, dmsh_pull, dmsh_side, dmsh_mesh, dmsh_ampere, shader_regressions, shader_cache, tool_lock # translation chain version: verify the tools against the lock file first; build output goes into b-<V>/
|
||||
_bad = tool_lock.check_tools()
|
||||
if _bad: sys.exit('\n'.join('[RED] translation chain tools do not match the lock file: ' + b for b in _bad) + '\n(if the tools changed, run tool_lock.py --update-lock and commit the lock file; if the translator just was not rebuilt, rebuild it)')
|
||||
CHAIN = dmsh_chain.version(); out = os.path.join(out, 'b-' + CHAIN)
|
||||
@@ -233,7 +233,8 @@ def border_emu(msl):
|
||||
twin = f'spvDescriptorSet0.{m.group(2)}{abi.BORDER_TWIN}'
|
||||
msl = msl[:m.start()] + f'dm_bs({msl[m.start():i]}, spvDescriptorSet0.{abi.BORDER_MEMBER}, {bit[m.group(2)]}u, spvDescriptorSet0.{m.group(1)}, {twin}, {args})' + msl[i:]
|
||||
return msl.replace('using namespace metal;\n', 'using namespace metal;\n' + BORDER_HELPERS, 1)
|
||||
CAS =os.environ.get('DMSH_CAS', os.path.join(cache_root, 'cas'))
|
||||
STORE = shader_cache.Store(os.environ.get('DMSH_CAS', os.path.join(cache_root, 'cas.db')))
|
||||
atexit.register(STORE.close) # folds its log into the one file
|
||||
CAS_LOCKS, CAS_LOCKS_GUARD = {}, threading.Lock()
|
||||
PRE_STATS = collections.Counter()
|
||||
# -fpreserve-invariance: vertex positions are marked [[invariant]], but without this flag Metal does not promise that two different shaders compute the same expression to the same value; on Maxwell the same multiply-adds always agree.
|
||||
@@ -305,8 +306,8 @@ def shader_key(key, name, rec):
|
||||
def pair_keyed(digest, pixel_digests): # a vertex shader's key with its pixel shaders' keys (vs_pad)
|
||||
return hashlib.sha256((digest + '\0' + ','.join(pixel_digests)).encode()).hexdigest()
|
||||
|
||||
def cache_meta_path(key): return os.path.join(CAS, 'index', key + '.json')
|
||||
def cache_path(digest): return os.path.join(CAS, 'shader', digest)
|
||||
def cache_meta_path(key): return f'index/{key}.json'
|
||||
def cache_path(digest): return f'shader/{digest}'
|
||||
CAS_USED = '_b_cas.txt' # in the Mac library directory b-<V>/: the cache_path digests of its last full build, one per line
|
||||
|
||||
def cache_outputs(key, digest, cached=False):
|
||||
@@ -316,10 +317,10 @@ def cache_outputs(key, digest, cached=False):
|
||||
# fin(), paired vertex padding and the profile tables also need these on an iOS-only cache hit.
|
||||
required = [key + '_b.json'] + ([key + '_b.metal'] if label == 'mac' else [])
|
||||
if label in TARGETS: required.append(key + '_b.metallib')
|
||||
base = os.path.join(root, label) if cached else directory
|
||||
have = STORE.names(f'{root}/{label}/') if cached else set()
|
||||
names = required + [key + s + ext for s in ('_bg0', '_bg1', '_bg2', '_bg3', '_bg4', '_bgv', '_bl0', '_bl1', '_bl3') for ext in ('.metallib', '.json', '.metal')
|
||||
if (label == 'mac' or ext != '.metal') and (ext != '.metallib' or label in TARGETS)]
|
||||
found = [n for n in names if os.path.exists(os.path.join(base, n))]
|
||||
found = [n for n in names if (f'{root}/{label}/{n}' in have if cached else os.path.exists(os.path.join(directory, n)))]
|
||||
if not all(n in found for n in required): return None
|
||||
files[label] = found
|
||||
return root, files
|
||||
@@ -331,19 +332,21 @@ def restore_cache(key, digest):
|
||||
for label, names in files.items():
|
||||
directory = out if label == 'mac' else IOSOUT
|
||||
for name in names:
|
||||
src = os.path.join(root, label, name); dst = os.path.join(directory, name)
|
||||
src = f'{root}/{label}/{name}'; dst = os.path.join(directory, name)
|
||||
if name.endswith('.json'):
|
||||
data = STORE.get(src)
|
||||
if data is None: return False # pruned by another build since the look above: a miss, which builds it
|
||||
tmp = dst + '.tmp-' + str(os.getpid()) + '-' + str(threading.get_ident())
|
||||
with open(tmp, 'wb') as f: f.write(re.sub(rb'("chain"\s*:\s*")[^"]*"', rb'\g<1>' + CHAIN.encode() + b'"', open(src, 'rb').read(), count=1))
|
||||
with open(tmp, 'wb') as f: f.write(re.sub(rb'("chain"\s*:\s*")[^"]*"', rb'\g<1>' + CHAIN.encode() + b'"', data, count=1))
|
||||
os.replace(tmp, dst)
|
||||
else: clone(src, dst)
|
||||
elif not STORE.to_file(src, dst): return False
|
||||
return True
|
||||
|
||||
def cache_lookup(key, digest, rule_fp, code_fp):
|
||||
with CAS_LOCKS_GUARD: lock = CAS_LOCKS.setdefault(('shader', key), threading.Lock())
|
||||
with lock:
|
||||
if restore_cache(key, digest): PRE_STATS['hit'] += 1; return True, 'hit'
|
||||
old = json.load(open(cache_meta_path(key))) if os.path.exists(cache_meta_path(key)) else None
|
||||
old = json.loads(STORE.get(cache_meta_path(key)) or b'null')
|
||||
if old and old.get('code_fp') != code_fp: reason = 'code fingerprint changed: all rebuilt'
|
||||
elif old and old.get('rule_fp') != rule_fp: reason = 'rule changed'
|
||||
else: reason = 'new key'
|
||||
@@ -355,15 +358,15 @@ def publish_cache(key, digest, rule_fp, code_fp):
|
||||
found = cache_outputs(key, digest)
|
||||
if not found: return
|
||||
root, files = found
|
||||
for label, names in files.items():
|
||||
d = os.path.join(root, label); os.makedirs(d, exist_ok=True)
|
||||
for name in names: clone(os.path.join(out if label == 'mac' else IOSOUT, name), os.path.join(d, name))
|
||||
for name in names:
|
||||
if name.endswith('.json'):
|
||||
with STORE.batch(): # a stop leaves the whole entry or none of it
|
||||
for label, names in files.items():
|
||||
for name in names:
|
||||
src = os.path.join(out if label == 'mac' else IOSOUT, name)
|
||||
value = json.load(open(src)); value.pop('fetch', None); value.pop('vin', None); value.pop('pull', None); value.pop('alpha', None); value.pop('logic', None) # the side libraries are made again from the restored MSL (fetch_finish, vin_finish, pull_finish, alpha_finish, logic_finish)
|
||||
atomic_json(os.path.join(d, name), value)
|
||||
atomic_json(cache_meta_path(key), {'digest': digest, 'rule_fp': rule_fp, 'code_fp': code_fp})
|
||||
if name.endswith('.json'):
|
||||
value = json.load(open(src)); value.pop('fetch', None); value.pop('vin', None); value.pop('pull', None); value.pop('alpha', None); value.pop('logic', None) # the side libraries are made again from the restored MSL (fetch_finish, vin_finish, pull_finish, alpha_finish, logic_finish)
|
||||
STORE.put(f'{root}/{label}/{name}', json.dumps(value, ensure_ascii=False, indent=1).encode())
|
||||
else: STORE.put_file(f'{root}/{label}/{name}', src)
|
||||
STORE.put(cache_meta_path(key), json.dumps({'digest': digest, 'rule_fp': rule_fp, 'code_fp': code_fp}).encode())
|
||||
|
||||
BF_STATS = collections.Counter()
|
||||
|
||||
@@ -376,24 +379,25 @@ def bf_digest(msl, key):
|
||||
h.update(b'\0bf-want\0' + (b'1' if key in BF_WANT else b'0'))
|
||||
return h.hexdigest()
|
||||
|
||||
def bf_cache_root(digest): return os.path.join(CAS, 'variant', digest)
|
||||
def bf_cache_root(digest): return f'variant/{digest}'
|
||||
|
||||
def bf_cache_restore(key, digest, fmeta, fmsl):
|
||||
root = bf_cache_root(digest)
|
||||
names = ['metal'] + (['mac.metallib'] if 'mac' in TARGETS else []) + (['ios.metallib'] if IOSOUT else [])
|
||||
if not all(os.path.exists(os.path.join(root, n)) for n in names): return False
|
||||
clone(os.path.join(root, 'metal'), fmsl)
|
||||
if 'mac' in TARGETS: clone(os.path.join(root, 'mac.metallib'), os.path.join(out, key + '_bf.metallib'))
|
||||
if IOSOUT: clone(os.path.join(root, 'ios.metallib'), os.path.join(IOSOUT, key + '_bf.metallib'))
|
||||
if not all(STORE.has(f'{root}/{n}') for n in names): return False
|
||||
STORE.to_file(f'{root}/metal', fmsl)
|
||||
if 'mac' in TARGETS: STORE.to_file(f'{root}/mac.metallib', os.path.join(out, key + '_bf.metallib'))
|
||||
if IOSOUT: STORE.to_file(f'{root}/ios.metallib', os.path.join(IOSOUT, key + '_bf.metallib'))
|
||||
BF_STATS['hit'] += 1
|
||||
return True
|
||||
|
||||
def bf_cache_publish(digest, fmsl, maclib, ioslib, fmeta):
|
||||
root = bf_cache_root(digest); os.makedirs(root, exist_ok=True)
|
||||
clone(fmsl, os.path.join(root, 'metal'))
|
||||
if maclib: clone(maclib, os.path.join(root, 'mac.metallib'))
|
||||
if IOSOUT: clone(ioslib, os.path.join(root, 'ios.metallib'))
|
||||
atomic_json(os.path.join(root, 'fetch.json'), fmeta)
|
||||
root = bf_cache_root(digest)
|
||||
with STORE.batch():
|
||||
STORE.put_file(f'{root}/metal', fmsl)
|
||||
if maclib: STORE.put_file(f'{root}/mac.metallib', maclib)
|
||||
if IOSOUT: STORE.put_file(f'{root}/ios.metallib', ioslib)
|
||||
STORE.put(f'{root}/fetch.json', json.dumps(fmeta, ensure_ascii=False, indent=1).encode())
|
||||
|
||||
def write_refl(key, refl):
|
||||
for target, d in (('mac', out),) + ((('ios', IOSOUT),) if IOSOUT else ()):
|
||||
@@ -1466,7 +1470,7 @@ for _d in [out] + ([IOSOUT] if IOSOUT else []):
|
||||
if (not want or STAMP_BEFORE != INPUTS) and os.path.exists(os.path.join(_d, dmsh_chain.STAMP)): os.unlink(os.path.join(_d, dmsh_chain.STAMP))
|
||||
if not want and os.path.exists(os.path.join(_d, CAS_USED)): os.unlink(os.path.join(_d, CAS_USED)) # written again at the end, with the stamp
|
||||
w = tempfile.mkdtemp(prefix='dmsh_', dir=os.environ.get('WORK'))
|
||||
MTL = dmsh_mtlcache.Cache(os.path.join(CAS, 'metallib'), {'mac': ('macosx', MAC_RECORD, mac_compile), **({'ios': ('iphoneos', ios_metal.RECORD, ios_metal.compile)} if IOSOUT else {})}, w)
|
||||
MTL = dmsh_mtlcache.Cache(STORE, {'mac': ('macosx', MAC_RECORD, mac_compile), **({'ios': ('iphoneos', ios_metal.RECORD, ios_metal.compile)} if IOSOUT else {})}, w)
|
||||
# first take the libraries earlier chain versions left on disk: the b-*/ beside the output (iOS: the folder of the same name) and the roots DMSH_PREFILL lists
|
||||
for _spec in [cache_root + ('=' + os.path.dirname(IOSOUT) if IOSOUT else '')] + [x for x in os.environ.get('DMSH_PREFILL', '').split(os.pathsep) if x]:
|
||||
_mac, _, _ios = _spec.partition('=')
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# that leaves a shader's MSL as it was (a translator fix, a new rule for other shaders) costs that shader no Metal compile. The Metal compiler is deterministic:
|
||||
# the same MSL with the same flags gives a byte-identical metallib (checked for macOS and iOS), which is what makes reuse safe. Its input is the text alone: dmsh_pch.compile passes the source on
|
||||
# standard input, as a file's name reaches the library of a source with function constants.
|
||||
# Layout: <cache>/<target>/<2 hex>/<digest>.metallib, digest = sha256 over FORMAT, the target's compile convention (the record written into json chain_metal),
|
||||
# Entries of the compile cache's one file (shader_cache.py): metallib/<target>/<digest>.metallib, digest = sha256 over FORMAT, the target's compile convention (the record written into json chain_metal),
|
||||
# the compiler's identity (metal / metallib --version without the install path, the SDK version and build) and the MSL bytes.
|
||||
# Filling from earlier builds: every imported library must record the current compiler identity and flags in its reflection. Legacy libraries without that identity are not imported.
|
||||
# A fresh compile of two shaders per stage also checks their bytes. Each folder is read once per compiler identity (filled.json remembers its number of libraries).
|
||||
@@ -11,6 +11,7 @@
|
||||
import os, re, sys, json, shutil, ctypes, hashlib, threading, subprocess, collections
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'tools'))
|
||||
import romfs, shader_lib # the libraries of an earlier build may be one file (shader_lib.py), read in place
|
||||
STAMPS = 'metallib/filled.json' # the earlier builds' folders already read
|
||||
|
||||
FORMAT = b'dmsh_mtlcache 2' # earlier prefill could misclassify an unsampled library from another compiler
|
||||
OUTPUT = re.compile(r'[0-9a-f]{16}_b\.metal') # a shader's MSL in dmsh_build.py's outputs: <key>_b.metal
|
||||
@@ -23,13 +24,6 @@ def clone(src, dst):
|
||||
os.replace(tmp, dst)
|
||||
|
||||
|
||||
def copy_in(src, dst): # clone, from a file that may lie inside a library's image
|
||||
if os.path.isfile(src): return clone(src, dst)
|
||||
tmp = f'{dst}.tmp-{os.getpid()}-{threading.get_ident()}'
|
||||
with romfs.open(src, 'rb') as f, open(tmp, 'wb') as o: shutil.copyfileobj(f, o)
|
||||
os.replace(tmp, dst)
|
||||
|
||||
|
||||
def compiler_id(sdk):
|
||||
def run(*a): return subprocess.run(['xcrun', '-sdk', sdk, *a], capture_output=True, text=True).stdout
|
||||
tools = ''.join(run(t, '--version') for t in ('metal', 'metallib'))
|
||||
@@ -37,15 +31,15 @@ def compiler_id(sdk):
|
||||
|
||||
|
||||
class Cache:
|
||||
def __init__(self, root, targets, work):
|
||||
"""targets: {name: (sdk, record, compile)}, compile(msl, air, lib) as ios_metal.compile; work: a folder for temporary .air files"""
|
||||
self.root, self.targets, self.work = root, targets, work
|
||||
def __init__(self, store, targets, work):
|
||||
"""store: shader_cache.Store; targets: {name: (sdk, record, compile)}, compile(msl, air, lib) as ios_metal.compile; work: a folder for temporary .air files"""
|
||||
self.store, self.targets, self.work = store, targets, work
|
||||
self.ident = {t: hashlib.sha256(FORMAT + b'\0' + rec.encode() + b'\0' + compiler_id(sdk).encode()).digest() for t, (sdk, rec, _) in targets.items()}
|
||||
self.stats, self.lock = collections.Counter(), threading.Lock()
|
||||
|
||||
def path(self, target, src):
|
||||
d = hashlib.sha256(self.ident[target] + b'\0' + src).hexdigest()
|
||||
return os.path.join(self.root, target, d[:2], d + '.metallib')
|
||||
return f'metallib/{target}/{d}.metallib'
|
||||
|
||||
def with_compiler(self, target, refl):
|
||||
return dict(refl, chain_metal=self.targets[target][1], chain_compiler=self.ident[target].hex())
|
||||
@@ -62,19 +56,18 @@ class Cache:
|
||||
def compile(self, target, msl, lib):
|
||||
"""msl → lib for target: a clone of the library that the same source compiled to before, or a compile (then kept). Raises CalledProcessError as the compile does"""
|
||||
p = self.path(target, open(msl, 'rb').read())
|
||||
if os.path.exists(p):
|
||||
clone(p, lib); self.count((target, 'reused')); return
|
||||
if self.store.to_file(p, lib): self.count((target, 'reused')); return
|
||||
tmp = f'{lib}.tmp-{os.getpid()}-{threading.get_ident()}'
|
||||
self._compile(target, msl, tmp)
|
||||
os.replace(tmp, lib)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True); clone(lib, p); self.count((target, 'compiled'))
|
||||
self.store.put_file(p, lib); self.count((target, 'compiled'))
|
||||
|
||||
def compile_split(self, target, msl, a, b, split):
|
||||
"""msl → two libraries cut from its one compile, split(the library's bytes) → (a's bytes, b's bytes): clones of what the same source gave before, or a compile (then both kept, not the whole
|
||||
library, so an output stays a clone as compile's are). Raises CalledProcessError as the compile does, and what split raises"""
|
||||
p = self.path(target, open(msl, 'rb').read()); q = p[:-len('.metallib')] + '_x.metallib'
|
||||
if os.path.exists(p) and os.path.exists(q):
|
||||
clone(p, a); clone(q, b); self.count((target, 'reused')); return
|
||||
if self.store.has(p) and self.store.has(q):
|
||||
self.store.to_file(p, a); self.store.to_file(q, b); self.count((target, 'reused')); return
|
||||
whole = f'{a}.tmp-{os.getpid()}-{threading.get_ident()}'
|
||||
self._compile(target, msl, whole)
|
||||
try:
|
||||
@@ -83,7 +76,8 @@ class Cache:
|
||||
for lib, data in zip((a, b), pieces):
|
||||
with open(whole, 'wb') as f: f.write(data)
|
||||
os.replace(whole, lib)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True); clone(b, q); clone(a, p); self.count((target, 'compiled'))
|
||||
with self.store.batch(): self.store.put_file(q, b); self.store.put_file(p, a)
|
||||
self.count((target, 'compiled'))
|
||||
|
||||
def _check(self, target, d, stems, mac_dir):
|
||||
"""None if folder d was built with the current convention and compiler, else why not"""
|
||||
@@ -99,7 +93,8 @@ class Cache:
|
||||
msl = os.path.join(mac_dir, stem + '.metal')
|
||||
inside = mac_dir.endswith('.img') # the compiler is then given a file of its own, which goes with the check
|
||||
if inside:
|
||||
copy_in(msl, os.path.join(self.work, f'mtlcache-check-{stem}.metal')); msl = os.path.join(self.work, f'mtlcache-check-{stem}.metal')
|
||||
with romfs.open(msl, 'rb') as f, open(os.path.join(self.work, f'mtlcache-check-{stem}.metal'), 'wb') as o: shutil.copyfileobj(f, o)
|
||||
msl = os.path.join(self.work, f'mtlcache-check-{stem}.metal')
|
||||
try: self._compile(target, msl, tmp)
|
||||
except subprocess.CalledProcessError: return f'{stem}.metal does not compile now'
|
||||
finally:
|
||||
@@ -112,9 +107,8 @@ class Cache:
|
||||
"""Takes the libraries of an earlier build: mac_dir = its Mac b-<chain>/ folder, ios_dir = the iOS folder of the same chain (or None). Returns the lines to print"""
|
||||
mac_dir, ios_dir = str(shader_lib.view(mac_dir)), ios_dir and str(shader_lib.view(ios_dir))
|
||||
if not romfs.os.path.isdir(mac_dir): return [] # a stopped pack's .part beside the libraries
|
||||
stamp_file = os.path.join(self.root, 'filled.json')
|
||||
try: stamps = json.load(open(stamp_file))
|
||||
except (OSError, ValueError): stamps = {}
|
||||
try: stamps = json.loads(self.store.get(STAMPS) or b'{}')
|
||||
except ValueError: stamps = {}
|
||||
names = set(romfs.os.listdir(mac_dir)) # a library with a side library was cut from another source than its .metal (compile_split, dmsh_side.py), and a compile of that source is never asked for
|
||||
stems = sorted(n[:-6] for n in names if OUTPUT.fullmatch(n) and n[:-6] + 'x.metallib' not in names) # not an AppleDouble ._<name> (exFAT / FAT drives)
|
||||
todo, notes = {}, []
|
||||
@@ -135,12 +129,11 @@ class Cache:
|
||||
src = romfs.open(os.path.join(mac_dir, stem + '.metal'), 'rb').read()
|
||||
for t in ts:
|
||||
p = self.path(t, src)
|
||||
if os.path.exists(p): continue
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True); copy_in(os.path.join(todo[t][0], stem + '.metallib'), p); added[t] += 1
|
||||
if self.store.has(p): continue
|
||||
self.store.put(p, romfs.open(os.path.join(todo[t][0], stem + '.metallib'), 'rb').read()); added[t] += 1
|
||||
for t, (d, have) in todo.items():
|
||||
self.count((t, 'filled'), added[t]); notes.append(f'Metal cache: {added[t]} {t} libraries added from {d} ({len(have)} there)')
|
||||
os.makedirs(self.root, exist_ok=True)
|
||||
tmp = f'{stamp_file}.tmp-{os.getpid()}'; json.dump(stamps, open(tmp, 'w'), indent=1); os.replace(tmp, stamp_file)
|
||||
self.store.put(STAMPS, json.dumps(stamps, indent=1).encode())
|
||||
return notes
|
||||
|
||||
def summary(self):
|
||||
|
||||
@@ -104,7 +104,8 @@ dm/tools/romfs_image.py *:* RomFS image packing: every game's files
|
||||
dm/tools/romfs.py *:* RomFS image input: every game's build tools
|
||||
dm/gfx/nvn/msl_image.h *:* reads each shader from the one-file library: every NVN game
|
||||
dm/tools/shader_lib.py *:* the shader libraries as one file: every NVN game build and regress chain
|
||||
dm/tools/tree_tar.py *:* one tar in place of the compile cache and Xcode derived data folders: every game build
|
||||
dm/tools/shader_cache.py *:* the compile cache as one file: every NVN game build and regress chain
|
||||
dm/tools/tree_tar.py *:* one tar in place of Xcode's derived data and quiet work folders: every game build
|
||||
dm/tools/nro_collect.py *:* NRO discovery from game resources during packing
|
||||
dm/tools/nx_extract/* *:* NSP extraction: every game's resource inputs
|
||||
dm/mac/launcher.c *:* Mac app resource discovery and host launch
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 54.
|
@@ -8,10 +8,10 @@ pyright dm/gfx/tools/cb_extent.py reportArgumentType 1 Argument of type "Unknown
|
||||
pyright dm/gfx/tools/cb_extent.py reportArgumentType 1 Argument of type "Unknown | None" cannot be assigned to parameter "arg2" of type "SupportsRichComparisonT@max" in function "max" Type "Unknown | None" is not assignable to type "int" "None" is not assignable to "int"
|
||||
pyright dm/gfx/tools/cb_extent.py reportOptionalOperand 1 Operator "<" not supported for "None"
|
||||
pyright dm/gfx/tools/dmsh_build.py reportArgumentType 1 Argument of type "str | None" cannot be assigned to parameter "file" of type "FileDescriptorOrPath" in function "open" Type "str | None" is not assignable to type "FileDescriptorOrPath" Type "None" is not assignable to type "FileDescriptorOrPath" "None" is not assignable to "int" "None" is not assignable to "str" "None" is not assignable to "bytes" "None" is incompatible with protocol "PathLike[str]" "__fspath__" is not present "None" is incompatible with protocol "PathLike[bytes]" ...
|
||||
pyright dm/gfx/tools/dmsh_build.py reportArgumentType 3 Argument of type "str | None" cannot be assigned to parameter "a" of type "BytesPath" in function "join" Type "str | None" is not assignable to type "BytesPath" Type "str" is not assignable to type "BytesPath" "str" is not assignable to "bytes" "str" is incompatible with protocol "PathLike[bytes]" "__fspath__" is not present
|
||||
pyright dm/gfx/tools/dmsh_build.py reportArgumentType 2 Argument of type "str | None" cannot be assigned to parameter "a" of type "BytesPath" in function "join" Type "str | None" is not assignable to type "BytesPath" Type "str" is not assignable to type "BytesPath" "str" is not assignable to "bytes" "str" is incompatible with protocol "PathLike[bytes]" "__fspath__" is not present
|
||||
pyright dm/gfx/tools/dmsh_build.py reportAttributeAccessIssue 1 Cannot access attribute "items" for class "str" Attribute "items" is unknown
|
||||
pyright dm/gfx/tools/dmsh_build.py reportCallIssue 1 No overloads for "open" match the provided arguments
|
||||
pyright dm/gfx/tools/dmsh_build.py reportCallIssue 3 No overloads for "join" match the provided arguments
|
||||
pyright dm/gfx/tools/dmsh_build.py reportCallIssue 2 No overloads for "join" match the provided arguments
|
||||
pyright dm/gfx/tools/dmsh_build.py reportGeneralTypeIssues 2 "None" is not iterable "__iter__" method not defined
|
||||
pyright dm/gfx/tools/dmsh_build.py reportOptionalMemberAccess 3 "group" is not a known attribute of "None"
|
||||
pyright dm/gfx/tools/dmsh_build.py reportOptionalSubscript 13 Object of type "None" is not subscriptable
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python3
|
||||
# The shader build's compile cache as one file, cas.db, read and written in place. It was a folder of a few files per shader (Metroid Dread: 84,541 files), kept as a tar between builds and unpacked
|
||||
# for each build that ran. Nothing is unpacked now: an entry goes in and comes out by its name, and a file a tool needs is written only then.
|
||||
# SQLite, as it is in Python and takes several writers: dmsh_build.py's threads share one connection, and regress.py's chain builds and the NSP script can share a game's file at once (the wait is SQLite's).
|
||||
# Two tables: entry (name, the blob it names, when it was written) and blob (the bytes, once each). A library kept under its MSL's digest and under its shader's digest was one APFS clone of the other; inside
|
||||
# one file it would be two copies, so bytes are stored by their hash. A file removed from the cache gives its pages back at the next prune (incremental vacuum), with no copy of the file.
|
||||
# It only saves work: a damaged file costs the work it held and is made anew, and a full drive is one [RED] line. An entry is written and read whole, so its file is never seen half written.
|
||||
# Names, as in the folder this replaces: metallib/<target>/<digest>[_x].metallib (dmsh_mtlcache.py), shader/<digest>/<mac|ios>/<output>, index/<key>.json, variant/<digest>/<file> (dmsh_build.py).
|
||||
# Not part of the translation chain: it decides no output (dmsh_chain.py), like dmsh_mtlcache.py.
|
||||
import contextlib, hashlib, json, os, re, shutil, sqlite3, tarfile, threading, time
|
||||
|
||||
SCHEMA = ('CREATE TABLE IF NOT EXISTS blob(id INTEGER PRIMARY KEY, hash BLOB UNIQUE NOT NULL, data BLOB NOT NULL)',
|
||||
'CREATE TABLE IF NOT EXISTS entry(name TEXT PRIMARY KEY, blob INTEGER NOT NULL, mtime REAL NOT NULL) WITHOUT ROWID')
|
||||
SHADER_ENTRY = re.compile(r'shader/([0-9a-f]{64})/')
|
||||
WAIT = 600 # seconds another process's write may hold this one up
|
||||
_DAMAGED = ('malformed', 'not a database', 'disk image')
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, path, say=print):
|
||||
self.path, self.say = os.fspath(path), say
|
||||
self.lock = threading.RLock() # one connection, for dmsh_build.py's threads: a read or a write of an entry takes microseconds next to a compile
|
||||
self.full = False
|
||||
self._open()
|
||||
|
||||
def _open(self):
|
||||
os.makedirs(os.path.dirname(os.path.abspath(self.path)), exist_ok=True)
|
||||
self.db = sqlite3.connect(self.path, timeout=WAIT, check_same_thread=False, isolation_level=None)
|
||||
try:
|
||||
self.db.execute('PRAGMA page_size=16384'); self.db.execute('PRAGMA auto_vacuum=INCREMENTAL') # both only before the first table
|
||||
# WAL: a reader in another process does not wait for a writer, and a commit needs no fsync. A drive that cannot share its memory file stays on the rollback journal, unsynced: a stop costs the cache at worst
|
||||
if self.db.execute('PRAGMA journal_mode=WAL').fetchone()[0].lower() == 'wal': self.db.execute('PRAGMA synchronous=NORMAL')
|
||||
else: self.db.execute('PRAGMA synchronous=OFF')
|
||||
for s in SCHEMA: self.db.execute(s)
|
||||
except sqlite3.DatabaseError as e:
|
||||
if not self._damage(e): raise
|
||||
|
||||
def _damage(self, e): # True when e says the file is damaged, which is now made anew
|
||||
if not any(w in str(e) for w in _DAMAGED): return False
|
||||
self.say(f'[RED] the shader compile cache {self.path} is damaged, and is made anew: {e}')
|
||||
with contextlib.suppress(sqlite3.Error): self.db.close()
|
||||
for suffix in ('', '-wal', '-shm', '-journal'):
|
||||
with contextlib.suppress(FileNotFoundError): os.unlink(self.path + suffix)
|
||||
self._open()
|
||||
return True
|
||||
|
||||
def _run(self, sql, *args): # a statement's rows, or [] when the file was damaged
|
||||
with self.lock:
|
||||
try: return self.db.execute(sql, args).fetchall()
|
||||
except sqlite3.DatabaseError as e:
|
||||
if not self._damage(e): raise
|
||||
return []
|
||||
|
||||
def has(self, name): return bool(self._run('SELECT 1 FROM entry WHERE name=?', name))
|
||||
|
||||
def get(self, name): # an entry's bytes, None when there is none
|
||||
rows = self._run('SELECT b.data FROM entry e JOIN blob b ON b.id=e.blob WHERE e.name=?', name)
|
||||
return bytes(rows[0][0]) if rows else None
|
||||
|
||||
def names(self, prefix): # the set of names starting with prefix
|
||||
return {r[0] for r in self._run('SELECT name FROM entry WHERE name>=? AND name<?', prefix, prefix + '\U0010ffff')}
|
||||
|
||||
def put(self, name, data, when=None):
|
||||
"""An entry's bytes, replacing what it held. A cache that cannot be written (a full drive) is one [RED] line: the build goes on without it"""
|
||||
digest = hashlib.blake2b(data, digest_size=16).digest()
|
||||
with self.lock:
|
||||
try:
|
||||
with self.batch():
|
||||
row = self.db.execute('SELECT id FROM blob WHERE hash=?', (digest,)).fetchone()
|
||||
blob = row[0] if row else self.db.execute('INSERT INTO blob(hash, data) VALUES(?, ?)', (digest, data)).lastrowid
|
||||
self.db.execute('INSERT OR REPLACE INTO entry(name, blob, mtime) VALUES(?, ?, ?)', (name, blob, time.time() if when is None else when))
|
||||
except sqlite3.OperationalError as e:
|
||||
if any(w in str(e) for w in _DAMAGED): self._damage(e)
|
||||
elif not self.full: self.full = True; self.say(f'[RED] the shader compile cache {self.path} cannot be written, the build goes on without it: {e}')
|
||||
except sqlite3.DatabaseError as e:
|
||||
if not self._damage(e): raise
|
||||
|
||||
def put_file(self, name, path):
|
||||
with open(path, 'rb') as f: self.put(name, f.read())
|
||||
|
||||
def to_file(self, name, path): # an entry written to path, whole or not at all; False when there is none
|
||||
data = self.get(name)
|
||||
if data is None: return False
|
||||
tmp = f'{path}.tmp-{os.getpid()}-{threading.get_ident()}'
|
||||
with open(tmp, 'wb') as f: f.write(data)
|
||||
os.replace(tmp, path)
|
||||
return True
|
||||
|
||||
@contextlib.contextmanager
|
||||
def batch(self):
|
||||
"""Several entries as one write: a stop leaves all of them or none (a shader's outputs and the index naming them), and thousands take one commit. Nests; the outermost commits"""
|
||||
with self.lock:
|
||||
if self.db.in_transaction: yield; return
|
||||
self.db.execute('BEGIN IMMEDIATE')
|
||||
try: yield
|
||||
except BaseException:
|
||||
if self.db.in_transaction: self.db.rollback()
|
||||
raise
|
||||
else: self.db.commit()
|
||||
|
||||
def prune_shaders(self, keep, since):
|
||||
"""Remove the shader/<64 hex digits>/ entries not in keep and all written before since, and the bytes nothing names any more, giving their pages back. Other names stay.
|
||||
Returns (shaders removed, bytes of their sources and reflection: their libraries are shared with metallib/)"""
|
||||
rows = self._run("SELECT e.name, e.mtime, length(b.data) FROM entry e JOIN blob b ON b.id=e.blob WHERE e.name>='shader/' AND e.name<'shader0'")
|
||||
newest, size, names = {}, {}, {}
|
||||
for name, mtime, n in rows:
|
||||
m = SHADER_ENTRY.match(name)
|
||||
if not m: continue
|
||||
d = m.group(1); newest[d] = max(newest.get(d, 0), mtime); names.setdefault(d, []).append(name)
|
||||
if not name.endswith('.metallib'): size[d] = size.get(d, 0) + n
|
||||
gone = [d for d in newest if d not in keep and newest[d] < since]
|
||||
if not gone: return 0, 0
|
||||
with self.lock, self.batch():
|
||||
self.db.executemany('DELETE FROM entry WHERE name=?', ((n,) for d in gone for n in names[d]))
|
||||
self.db.execute('DELETE FROM blob WHERE id NOT IN (SELECT blob FROM entry)')
|
||||
self._run('PRAGMA incremental_vacuum')
|
||||
return len(gone), sum(size.get(d, 0) for d in gone)
|
||||
|
||||
def close(self): # also folds the write-ahead log into the file, so that one file is left
|
||||
with self.lock, contextlib.suppress(sqlite3.Error): self.db.close()
|
||||
|
||||
|
||||
def _adopted_name(name):
|
||||
"""What a file of the old folder is called here, None for one not taken. A shader/ or index/ entry's digest covers the chain's code, which the change to this file moved, so none can hit. A variant/ entry from
|
||||
before shader compiles read their source from standard input (f2a50f35) holds its source's file name in its function constants, so its bytes differ from a fresh compile's: few, and cheap to compile again.
|
||||
The compile results are the ones worth keeping, and their digests cover the MSL and the compiler alone"""
|
||||
m = re.fullmatch(r'metallib/([^/]+)/[0-9a-f]{2}/([^/]+\.metallib)', name)
|
||||
return f'metallib/{m.group(1)}/{m.group(2)}' if m else None
|
||||
|
||||
|
||||
def adopt(old, path, say=print):
|
||||
"""A compile cache from before this file (the folder old, or old.tar: tree_tar.py) into the file path, and the old one removed, so a build folder converts by itself at its next build. A damaged tar costs the work it held.
|
||||
Returns the number of entries taken"""
|
||||
folder, tar = os.fspath(old), f'{os.fspath(old)}.tar'
|
||||
leftovers = [p for p in (f'{folder}.gone', f'{folder}.unpack', f'{tar}.part') if os.path.lexists(p)]
|
||||
if not (os.path.isdir(folder) or os.path.isfile(tar) or leftovers): return 0
|
||||
n, store = 0, None
|
||||
def take(name, read):
|
||||
nonlocal n, store
|
||||
new = _adopted_name(name.removeprefix('./'))
|
||||
if new is None or os.path.basename(name).startswith('._'): return
|
||||
store = store or Store(path, say)
|
||||
store.put(new, read()); n += 1
|
||||
def in_batches(items):
|
||||
for i, item in enumerate(items):
|
||||
if not i % 2000 and store is not None and store.db.in_transaction: store.db.commit()
|
||||
if store is not None and not store.db.in_transaction: store.db.execute('BEGIN IMMEDIATE')
|
||||
yield item
|
||||
if store is not None and store.db.in_transaction: store.db.commit()
|
||||
try:
|
||||
if os.path.isfile(tar):
|
||||
say(f'moving the compile cache {tar} into one file read in place')
|
||||
with tarfile.open(tar, 'r:') as t:
|
||||
for m in in_batches(t):
|
||||
source = t.extractfile(m) if m.isfile() else None
|
||||
if source: take(m.name, source.read)
|
||||
except (tarfile.TarError, OSError) as e: say(f'[RED] could not read {tar}, the build goes on without it: {e}')
|
||||
if os.path.isdir(folder): # the newer of the two, when a stopped build left both
|
||||
say(f'moving the compile cache {folder} into one file read in place')
|
||||
def files():
|
||||
for d, _, fs in os.walk(folder):
|
||||
for f in fs: yield os.path.join(d, f)
|
||||
for p in in_batches(files()):
|
||||
def read(p=p):
|
||||
with open(p, 'rb') as f: return f.read()
|
||||
take(os.path.relpath(p, folder), read)
|
||||
if store is not None: store.close()
|
||||
for p in [folder, tar] + leftovers:
|
||||
try:
|
||||
if os.path.isdir(p) and not os.path.islink(p): shutil.rmtree(p, onexc=lambda f, q, e: None if isinstance(e, FileNotFoundError) else (_ for _ in ()).throw(e))
|
||||
elif os.path.lexists(p): os.unlink(p)
|
||||
except OSError as e: say(f'[RED] could not remove the old compile cache {p}: {e}')
|
||||
return n
|
||||
|
||||
|
||||
def exists(path): return os.path.isfile(os.fspath(path))
|
||||
|
||||
|
||||
def main():
|
||||
import sys
|
||||
if len(sys.argv) != 2: sys.exit('usage: shader_cache.py <cas.db>: what it holds')
|
||||
s = Store(sys.argv[1])
|
||||
kinds = {}
|
||||
for name, in s._run('SELECT name FROM entry'): kinds[name.split('/', 1)[0]] = kinds.get(name.split('/', 1)[0], 0) + 1
|
||||
print(json.dumps({'entries': kinds, 'blobs': s._run('SELECT count(*) FROM blob')[0][0], 'bytes': os.path.getsize(sys.argv[1])}))
|
||||
s.close()
|
||||
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
@@ -169,7 +169,7 @@ class Nvn(Base):
|
||||
for n in ('cas', 'b-notahexchain', 'b-0123456789abcd', 'mine'): (self.sh / 'cache' / n).mkdir()
|
||||
(self.sh / 'cache' / 'b-ffffffffffff').write_text('a file, not a library folder')
|
||||
self.build(False)
|
||||
self.assertEqual(sorted(p.name for p in (self.sh / 'cache').iterdir()), sorted(['b-0123456789abcd', 'b-ffffffffffff', 'b-notahexchain', f'b-{CHAIN}.img', 'cas.tar', 'mine']))
|
||||
self.assertEqual(sorted(p.name for p in (self.sh / 'cache').iterdir()), sorted(['b-0123456789abcd', 'b-ffffffffffff', 'b-notahexchain', f'b-{CHAIN}.img', 'mine'])) # an empty old cache's folder goes
|
||||
|
||||
def test_a_folder_from_before_becomes_one_file_without_a_build(self): # a reused step: nothing is translated again
|
||||
self.build(True); lib = self.sh / 'cache' / f'b-{CHAIN}'
|
||||
@@ -243,52 +243,56 @@ class Nvn(Base):
|
||||
with mock.patch.object(nsp, 'main'): self.assertEqual(nsp.cli([]), 0)
|
||||
self.assertEqual([c.args[0].name for c in tidy.call_args_list], ['0100000000000000-work'])
|
||||
|
||||
def test_cache_is_one_file_between_builds(self): # a folder from before cas.tar is packed even by a reused build; a build that runs takes it back
|
||||
self.build(False); self.cas(LIVE)
|
||||
def test_a_cache_from_before_moves_into_the_one_file(self): # even by a reused build, and a build that runs never finds a folder
|
||||
self.build(False)
|
||||
old = self.sh / 'cache/cas/metallib/mac/ab'; old.mkdir(parents=True); (old / 'abcd.metallib').write_bytes(b'compiled')
|
||||
self.build(False)
|
||||
self.assertEqual(self.ran, [])
|
||||
self.assertFalse((self.sh / 'cache/cas').exists()); self.assertTrue((self.sh / 'cache/cas.tar').is_file())
|
||||
self.assertFalse((self.sh / 'cache/cas').exists())
|
||||
self.assertEqual(self.store().get('metallib/mac/abcd.metallib'), b'compiled')
|
||||
(self.sh / 'ios' / f'b-{CHAIN}.key').unlink()
|
||||
seen = []
|
||||
real = nsp.run
|
||||
def looks(cmd, log, env=None, cwd=None, on_line=None):
|
||||
seen.append(sorted(p.name for p in (self.sh / 'cache/cas/shader').iterdir()))
|
||||
seen.append((self.sh / 'cache/cas').exists())
|
||||
return real(cmd, log, env=env, cwd=cwd, on_line=on_line)
|
||||
with mock.patch.object(nsp, 'run', looks): self.build(False)
|
||||
self.assertEqual(seen, [[LIVE]])
|
||||
self.assertFalse((self.sh / 'cache/cas').exists()); self.assertTrue((self.sh / 'cache/cas.tar').is_file())
|
||||
self.assertEqual(seen, [False])
|
||||
|
||||
def entries(self): # the cache's entries, as the next build that runs would read them
|
||||
nsp.tree_tar.unpack(self.sh / 'cache/cas')
|
||||
return self.sh / 'cache/cas/shader'
|
||||
def store(self):
|
||||
s = nsp.shader_cache.Store(self.sh / 'cache/cas.db'); self.addCleanup(s.close)
|
||||
return s
|
||||
|
||||
def cas(self, *names, when=0): # cache entries with a source and a library (a clone of the compile cache's), last changed at when
|
||||
def entries(self): # the shaders the cache holds, as the next build that runs would read them
|
||||
return {n.split('/')[1] for n in self.store().names('shader/')}
|
||||
|
||||
def cas(self, *names, when=0): # cache entries with a source and a library, last changed at when
|
||||
s = self.store()
|
||||
for n in names:
|
||||
d = self.sh / 'cache/cas/shader' / n / 'mac'; d.mkdir(parents=True)
|
||||
(d / 'k_b.metal').write_bytes(b'm' * 100); (d / 'k_b.metallib').write_bytes(b'l' * 1000)
|
||||
nsp.os.utime(d.parent, (when, when))
|
||||
s.put(f'shader/{n}/mac/k_b.metal', b'm' * 100 + n.encode()[:0], when); s.put(f'shader/{n}/mac/k_b.metallib', b'l' * 1000, when)
|
||||
s.close()
|
||||
|
||||
def test_prune_shader_cache(self): # entries the build did not list go once it succeeded; a listed one, one newer than the list and other names stay; only the sources count
|
||||
self.cas(LIVE, OLD, 'notadigest')
|
||||
said = []
|
||||
with mock.patch.object(nsp, 'say', said.append): self.build(False)
|
||||
self.entries(); self.cas(NEW, when=nsp.time.time() + 3600) # published by another build sharing the cache after this one's list
|
||||
self.assertEqual(sorted(p.name for p in (self.sh / 'cache/cas/shader').iterdir()), sorted([LIVE, NEW, 'notadigest']))
|
||||
self.cas(NEW, when=nsp.time.time() + 3600) # published by another build sharing the cache after this one's list
|
||||
self.assertEqual(self.entries(), {LIVE, NEW, 'notadigest'})
|
||||
self.assertEqual([m for m in said if 'shader cache entries' in m], ['removed old shader cache entries: 1 (0.1 KB)'])
|
||||
self.cas(OLD); said.clear() # a reused build prunes too
|
||||
with mock.patch.object(nsp, 'say', said.append): self.build(False)
|
||||
self.assertEqual(self.ran, []); self.assertFalse((self.entries() / OLD).exists()); self.assertTrue((self.entries() / NEW).exists())
|
||||
self.assertEqual(self.ran, []); self.assertNotIn(OLD, self.entries()); self.assertIn(NEW, self.entries())
|
||||
|
||||
def test_prune_shader_cache_needs_success_and_the_list(self): # a failed build, or libraries from before the list, keep every entry
|
||||
self.build(False); self.cas(OLD)
|
||||
(self.sh / 'ios' / f'b-{CHAIN}.key').unlink() # not reused: the step runs, and fails
|
||||
def failing(cmd, log, env=None, cwd=None, on_line=None): raise nsp.BuildError('translator failed')
|
||||
with mock.patch.object(nsp, 'run', failing), self.assertRaises(nsp.BuildError): self.build(False)
|
||||
self.assertTrue((self.sh / 'cache/cas/shader' / OLD).exists())
|
||||
self.build(False); self.assertFalse((self.entries() / OLD).exists())
|
||||
self.assertIn(OLD, self.entries())
|
||||
self.build(False); self.assertNotIn(OLD, self.entries())
|
||||
nsp.shader_lib.expand(self.sh / 'cache' / f'b-{CHAIN}'); (self.sh / 'cache' / f'b-{CHAIN}' / '_b_cas.txt').unlink(); self.cas(OLD)
|
||||
self.build(False)
|
||||
self.assertEqual(self.ran, []); self.assertTrue((self.entries() / OLD).exists())
|
||||
self.assertEqual(self.ran, []); self.assertIn(OLD, self.entries())
|
||||
|
||||
def test_no_stamp(self): # Mac libraries no full build stamped (an interrupted one): no table can name them, so neither key reuses them
|
||||
self.build(False)
|
||||
|
||||
@@ -875,7 +875,7 @@ class SeenShaders(unittest.TestCase): # --seen-shaders: the keys, the partial
|
||||
self.assertEqual(len(self.ran), 1, self.ran) # own_compilers.py alone
|
||||
cmd, env = self.ran[0]
|
||||
self.assertEqual(cmd[2:], [str(self.sh / 'pkg'), str(self.sh / 'partial'), a, b])
|
||||
self.assertEqual((env['DMSH_CAS'], env['DMSH_TARGETS']), (str(self.sh / 'cache/cas'), 'mac')); self.assertNotIn('IOSOUT', env)
|
||||
self.assertEqual((env['DMSH_CAS'], env['DMSH_TARGETS']), (str(self.sh / 'cache/cas.db'), 'mac')); self.assertNotIn('IOSOUT', env)
|
||||
self.assertFalse(old.exists()); self.assertTrue((self.sh / f'partial/b-{self.CHAIN}/k_b.metallib').is_file())
|
||||
self.assertFalse((self.sh / f'partial/b-{self.CHAIN}/inputs.tsv').exists()); self.assertFalse((self.tmp / 'c1_full.tsv').exists()) # no stamp: unlisted shaders are not proven safe
|
||||
self.assertEqual(self.build([a, b]), self.sh / 'partial'); self.assertEqual(self.ran, []) # reused
|
||||
|
||||
@@ -405,6 +405,20 @@ class Regress(unittest.TestCase):
|
||||
hashed.assert_called_once() # a manifest of the current hashes is reused as it is
|
||||
self.assertTrue((out / 'b-v').is_dir()) # a revision from before shader_lib.py: its host reads only the folder
|
||||
|
||||
def test_chain_builds_share_the_players_one_file_cache(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td); build = root / 'build'; g = NS(id='game', kind='nvn', folder=root, build=build)
|
||||
new = root / 'new'; (new / 'dm/tools').mkdir(parents=True); (new / 'dm/tools/shader_cache.py').write_text('')
|
||||
with patch.object(regress, 'ROOT', root):
|
||||
own = regress.game_root(g)
|
||||
self.assertEqual(regress.chain_cache(NS(path=new), g), own / 'cas.db') # no player's build yet
|
||||
old = build / 'shader/cache/cas/metallib/mac/ab'; old.mkdir(parents=True); (old / 'abcd.metallib').write_bytes(b'compiled')
|
||||
self.assertEqual(regress.chain_cache(NS(path=new), g), build / 'shader/cache/cas.db') # a cache from before it moves in
|
||||
self.assertFalse((build / 'shader/cache/cas').exists())
|
||||
s = regress.shader_cache.Store(build / 'shader/cache/cas.db'); self.addCleanup(s.close)
|
||||
self.assertEqual(s.get('metallib/mac/abcd.metallib'), b'compiled')
|
||||
self.assertEqual(regress.chain_cache(NS(path=root / 'revision-from-before'), g), own / 'cas') # its dmsh_build.py wants a folder
|
||||
|
||||
def test_a_chain_build_becomes_one_file_with_the_same_hashes(self):
|
||||
k = '0123456789abcdef'
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python3
|
||||
# The compile cache as one file (dm/tools/shader_cache.py): entries in and out, bytes stored once, several threads and processes, a damaged file, pruning, and taking in a cache from before it.
|
||||
import os, subprocess, sys, tarfile, tempfile, threading, time, unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
sys.path.insert(0, str(REPO / 'dm/tools'))
|
||||
import shader_cache
|
||||
|
||||
D1, D2, D3 = 'a' * 64, 'b' * 64, 'c' * 64
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def setUp(self):
|
||||
t = tempfile.TemporaryDirectory(); self.addCleanup(t.cleanup)
|
||||
self.root = Path(t.name); self.path = self.root / 'cas.db'; self.said = []
|
||||
self.store = shader_cache.Store(self.path, self.said.append); self.addCleanup(self.store.close)
|
||||
|
||||
def blobs(self): return self.store.db.execute('SELECT count(*) FROM blob').fetchone()[0]
|
||||
|
||||
|
||||
class Entries(Base):
|
||||
def test_in_and_out(self):
|
||||
self.store.put('x/y', b'bytes')
|
||||
self.assertEqual(self.store.get('x/y'), b'bytes'); self.assertTrue(self.store.has('x/y'))
|
||||
self.assertIsNone(self.store.get('absent')); self.assertFalse(self.store.has('absent'))
|
||||
self.store.put('x/y', b'new'); self.assertEqual(self.store.get('x/y'), b'new')
|
||||
|
||||
def test_empty_entry(self):
|
||||
self.store.put('e', b''); self.assertEqual(self.store.get('e'), b''); self.assertTrue(self.store.has('e'))
|
||||
out = self.root / 'out'; self.assertTrue(self.store.to_file('e', out)); self.assertEqual(out.read_bytes(), b'')
|
||||
|
||||
def test_names_take_a_prefix_only(self):
|
||||
for n in ('shader/a/mac/x', 'shader/a/ios/x', 'shader/ab/mac/x', 'shader0'): self.store.put(n, b'1')
|
||||
self.assertEqual(self.store.names('shader/a/'), {'shader/a/mac/x', 'shader/a/ios/x'})
|
||||
|
||||
def test_the_same_bytes_are_stored_once(self): # a library under its MSL's digest and its shader's digest was one APFS clone
|
||||
self.store.put('metallib/mac/d.metallib', b'L' * 100000); self.store.put('shader/d/mac/k_b.metallib', b'L' * 100000)
|
||||
self.assertEqual(self.blobs(), 1)
|
||||
self.assertEqual(self.store.get('shader/d/mac/k_b.metallib'), b'L' * 100000)
|
||||
|
||||
def test_to_file_and_from_file(self):
|
||||
src, dst = self.root / 'src', self.root / 'dst'; src.write_bytes(b'data')
|
||||
self.store.put_file('f', src)
|
||||
self.assertTrue(self.store.to_file('f', dst)); self.assertEqual(dst.read_bytes(), b'data')
|
||||
self.assertFalse(self.store.to_file('absent', self.root / 'none')); self.assertFalse((self.root / 'none').exists())
|
||||
|
||||
def test_one_file_is_left(self):
|
||||
self.store.put('x', b'1'); self.store.close()
|
||||
self.assertEqual(os.listdir(self.root), ['cas.db'])
|
||||
again = shader_cache.Store(self.path); self.addCleanup(again.close)
|
||||
self.assertEqual(again.get('x'), b'1')
|
||||
|
||||
|
||||
class Writers(Base):
|
||||
def test_threads_share_it(self):
|
||||
def work(i):
|
||||
for j in range(200):
|
||||
self.store.put(f't{i}/{j}', f'{i}.{j}'.encode()); self.assertEqual(self.store.get(f't{i}/{j}'), f'{i}.{j}'.encode())
|
||||
ts = [threading.Thread(target=work, args=(i,)) for i in range(8)]
|
||||
for t in ts: t.start()
|
||||
for t in ts: t.join()
|
||||
self.assertEqual(len(self.store.names('t')), 1600)
|
||||
|
||||
def test_a_batch_is_all_or_nothing(self):
|
||||
with self.assertRaises(ZeroDivisionError):
|
||||
with self.store.batch():
|
||||
self.store.put('a', b'1'); self.store.put('b', b'2'); raise ZeroDivisionError
|
||||
self.assertEqual(self.store.names(''), set())
|
||||
with self.store.batch():
|
||||
with self.store.batch(): self.store.put('a', b'1')
|
||||
self.store.put('b', b'2')
|
||||
self.assertEqual(self.store.names(''), {'a', 'b'})
|
||||
|
||||
def test_processes_share_it(self): # regress.py's chain builds and the NSP script on one game's file
|
||||
code = ("import sys; sys.path.insert(0, sys.argv[1]); import shader_cache\ns = shader_cache.Store(sys.argv[2])\n"
|
||||
"for j in range(300): s.put(f'{sys.argv[3]}/{j}', sys.argv[3].encode() * 1000); assert s.get(f'{sys.argv[3]}/{j}') == sys.argv[3].encode() * 1000\ns.close()\n")
|
||||
ps = [subprocess.Popen([sys.executable, '-c', code, str(REPO / 'dm/tools'), str(self.path), f'p{i}']) for i in range(4)]
|
||||
self.assertEqual([p.wait() for p in ps], [0, 0, 0, 0])
|
||||
self.assertEqual(len(self.store.names('p')), 1200)
|
||||
|
||||
def test_a_killed_writer_loses_only_what_it_had_not_committed(self):
|
||||
code = ("import os, sys; sys.path.insert(0, sys.argv[1]); import shader_cache\ns = shader_cache.Store(sys.argv[2]); s.put('done', b'1')\n"
|
||||
"s.db.execute('BEGIN IMMEDIATE'); s.put('half', b'2'); os.kill(os.getpid(), 9)\n")
|
||||
subprocess.run([sys.executable, '-c', code, str(REPO / 'dm/tools'), str(self.path)])
|
||||
self.assertEqual(self.store.names(''), {'done'})
|
||||
|
||||
|
||||
class Damage(unittest.TestCase):
|
||||
def setUp(self):
|
||||
t = tempfile.TemporaryDirectory(); self.addCleanup(t.cleanup)
|
||||
self.path = Path(t.name) / 'cas.db'; self.said = []
|
||||
|
||||
def test_a_file_that_is_no_database_costs_the_work_it_held(self):
|
||||
self.path.write_bytes(b'not a database at all' * 2000)
|
||||
s = shader_cache.Store(self.path, self.said.append); self.addCleanup(s.close)
|
||||
self.assertIn('[RED]', self.said[0])
|
||||
s.put('x', b'1'); self.assertEqual(s.get('x'), b'1')
|
||||
|
||||
def test_damage_found_in_use(self):
|
||||
s = shader_cache.Store(self.path, self.said.append)
|
||||
for i in range(300): s.put(f'x{i}', os.urandom(40000))
|
||||
s.close()
|
||||
b = bytearray(self.path.read_bytes()); b[16384:len(b) // 2] = b'\xee' * (len(b) // 2 - 16384); self.path.write_bytes(b)
|
||||
s = shader_cache.Store(self.path, self.said.append)
|
||||
for i in range(300): s.get(f'x{i}') # a miss or an entry, never an exception
|
||||
s.put('after', b'1'); self.assertEqual(s.get('after'), b'1')
|
||||
s.close()
|
||||
self.assertTrue(any('[RED]' in m for m in self.said))
|
||||
|
||||
|
||||
class Prune(Base):
|
||||
def shader(self, digest, when):
|
||||
self.store.put(f'shader/{digest}/mac/k_b.metal', digest.encode() * 10, when); self.store.put(f'shader/{digest}/mac/k_b.metallib', b'L' + digest.encode(), when)
|
||||
|
||||
def test_old_ones_go_with_their_bytes(self):
|
||||
now = time.time()
|
||||
for d in (D1, D2): self.shader(d, now - 100)
|
||||
self.shader(D3, now + 100); self.store.put('shader/notadigest/mac/x', b'k', now - 100); self.store.put('metallib/mac/m.metallib', b'L' + D2.encode(), now - 100)
|
||||
before = self.blobs()
|
||||
self.assertEqual(self.store.prune_shaders({D1}, now), (1, 640)) # the source's bytes, not the library's
|
||||
self.assertEqual({n.split('/')[1] for n in self.store.names('shader/')}, {D1, D3, 'notadigest'})
|
||||
self.assertEqual(self.blobs(), before - 1) # D2's source; its library's bytes stay under metallib/
|
||||
self.assertEqual(self.store.get('metallib/mac/m.metallib'), b'L' + D2.encode())
|
||||
|
||||
def test_the_file_gives_back_its_pages(self):
|
||||
now = time.time()
|
||||
for i in range(40): self.store.put(f'shader/{i:064x}/mac/k_b.metal', os.urandom(100000), now - 100)
|
||||
self.store.db.execute('PRAGMA wal_checkpoint(TRUNCATE)'); big = self.path.stat().st_size
|
||||
self.assertEqual(self.store.prune_shaders(set(), now)[0], 40)
|
||||
self.store.db.execute('PRAGMA wal_checkpoint(TRUNCATE)')
|
||||
self.assertLess(self.path.stat().st_size, big // 4)
|
||||
|
||||
|
||||
class Adopt(unittest.TestCase):
|
||||
def setUp(self):
|
||||
t = tempfile.TemporaryDirectory(); self.addCleanup(t.cleanup)
|
||||
self.root = Path(t.name); self.old = self.root / 'cas'; self.path = self.root / 'cas.db'; self.said = []
|
||||
|
||||
def fill(self):
|
||||
for name, data in (('metallib/mac/ab/abcd.metallib', b'compiled'), ('metallib/mac/ab/abcd_x.metallib', b'cut'), ('metallib/ios/cd/cdef.metallib', b'ios'), ('metallib/filled.json', b'{}'),
|
||||
(f'shader/{D1}/mac/k_b.metal', b'old chain'), ('index/k.json', b'{}'), ('variant/ee/metal', b'msl'), ('variant/ee/mac.metallib', b'v'), ('metallib/mac/ab/._abcd.metallib', b'appledouble')):
|
||||
p = self.old / name; p.parent.mkdir(parents=True, exist_ok=True); p.write_bytes(data)
|
||||
|
||||
def check(self):
|
||||
s = shader_cache.Store(self.path)
|
||||
self.assertEqual(s.names(''), {'metallib/mac/abcd.metallib', 'metallib/mac/abcd_x.metallib', 'metallib/ios/cdef.metallib'})
|
||||
self.assertEqual(s.get('metallib/mac/abcd.metallib'), b'compiled')
|
||||
s.close()
|
||||
self.assertEqual(sorted(os.listdir(self.root)), ['cas.db'])
|
||||
|
||||
def test_a_folder(self):
|
||||
self.fill(); self.assertEqual(shader_cache.adopt(self.old, self.path, self.said.append), 3); self.check()
|
||||
|
||||
def test_a_tar_read_without_unpacking(self):
|
||||
self.fill()
|
||||
with tarfile.open(f'{self.old}.tar', 'w', format=tarfile.PAX_FORMAT) as t: t.add(self.old, '.')
|
||||
import shutil; shutil.rmtree(self.old)
|
||||
self.assertEqual(shader_cache.adopt(self.old, self.path, self.said.append), 3); self.check()
|
||||
|
||||
def test_a_damaged_tar_costs_what_it_held(self):
|
||||
Path(f'{self.old}.tar').write_bytes(b'not a tar' * 100)
|
||||
self.assertEqual(shader_cache.adopt(self.old, self.path, self.said.append), 0)
|
||||
self.assertFalse(Path(f'{self.old}.tar').exists()); self.assertTrue(any('[RED]' in m for m in self.said))
|
||||
|
||||
def test_nothing_there(self):
|
||||
self.assertEqual(shader_cache.adopt(self.old, self.path, self.said.append), 0)
|
||||
self.assertEqual(os.listdir(self.root), []); self.assertFalse(shader_cache.exists(self.path))
|
||||
|
||||
def test_what_a_stopped_build_left(self):
|
||||
for p in (f'{self.old}.gone', f'{self.old}.unpack'): os.makedirs(p); (Path(p) / 'x').write_bytes(b'1')
|
||||
Path(f'{self.old}.tar.part').write_bytes(b'1')
|
||||
shader_cache.adopt(self.old, self.path, self.said.append)
|
||||
self.assertEqual(os.listdir(self.root), [])
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -25,6 +25,7 @@ TOOLS = REPO / 'dm/gfx/tools'
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
import dmsh_chain # noqa: E402
|
||||
import dmsh_mtlcache # noqa: E402
|
||||
import shader_cache # noqa: E402
|
||||
|
||||
spec = importlib.util.spec_from_file_location('nsp_toolchain_cache', REPO / 'scripts/build_ipa_from_nsp.py')
|
||||
assert spec and spec.loader
|
||||
@@ -40,7 +41,7 @@ class ShaderCache(unittest.TestCase):
|
||||
XC=['--msl'], MAC_RECORD='mac flags', IOSOUT=None, TARGETS={'mac'},
|
||||
ios_metal=types.SimpleNamespace(RECORD='ios flags'), METAL_FP='tested Metal and SDK',
|
||||
FACTS={}, MAP_ROWS={}, MAP_CONFLICT_ROWS={}, CODE_FP='source', PROFILE_ROWS=b'', PAIRS={},
|
||||
DUAL_WANT=set(), BF_WANT=set(), BF_STATS=collections.Counter(), CAS=str(root / 'cas'), out=str(root / 'out'),
|
||||
DUAL_WANT=set(), BF_WANT=set(), BF_STATS=collections.Counter(), STORE=shader_cache.Store(root / 'cas.db'), out=str(root / 'out'),
|
||||
CHAIN='test-chain', clone=shutil.copyfile, shader_rule_source=lambda name: b'')
|
||||
(root / 'out').mkdir()
|
||||
names = {'tool_fingerprint', 'shader_key', 'cache_path', 'cache_outputs', 'restore_cache', 'publish_cache', 'atomic_json', 'cache_meta_path',
|
||||
@@ -66,10 +67,10 @@ class ShaderCache(unittest.TestCase):
|
||||
self.ns['METAL_FP'] = 'override Metal and SDK'
|
||||
old = self.digest()
|
||||
for target in ('mac', 'ios') if ios else ('mac',):
|
||||
d = Path(self.ns['cache_path'](old)) / target; d.mkdir(parents=True, exist_ok=True)
|
||||
(d / 'key_b.metallib').write_bytes(b'untested compiled library')
|
||||
(d / 'key_b.json').write_text('{}')
|
||||
if target == 'mac': (d / 'key_b.metal').write_text('MSL')
|
||||
d = self.ns['cache_path'](old) + '/' + target
|
||||
self.ns['STORE'].put(d + '/key_b.metallib', b'untested compiled library')
|
||||
self.ns['STORE'].put(d + '/key_b.json', b'{}')
|
||||
if target == 'mac': self.ns['STORE'].put(d + '/key_b.metal', b'MSL')
|
||||
self.assertTrue(self.ns['restore_cache']('key', old))
|
||||
self.ns['METAL_FP'] = 'tested Metal and SDK'
|
||||
self.assertFalse(self.ns['restore_cache']('key', self.digest()))
|
||||
@@ -78,7 +79,7 @@ class ShaderCache(unittest.TestCase):
|
||||
for ios in (False, True):
|
||||
for listed in (False, True):
|
||||
with self.subTest(ios=ios, listed=listed):
|
||||
self.ns['CAS'] = str(Path(self.tmp.name) / f'cas-{ios}-{listed}')
|
||||
self.ns['STORE'] = shader_cache.Store(Path(self.tmp.name) / f'cas-{ios}-{listed}.db')
|
||||
self.ns['IOSOUT'] = str(Path(self.tmp.name) / 'ios') if ios else None
|
||||
self.ns['TARGETS'] = {'mac', 'ios'} if ios else {'mac'}
|
||||
self.ns['DUAL_WANT'] = {'key'} if listed else set()
|
||||
@@ -113,8 +114,8 @@ class ShaderCache(unittest.TestCase):
|
||||
def test_fetch_variants_do_not_restore_override_libraries(self):
|
||||
self.ns['METAL_FP'] = 'override Metal and SDK'
|
||||
old = self.ns['bf_digest']('same fetch MSL', 'key')
|
||||
d = Path(self.ns['bf_cache_root'](old)); d.mkdir(parents=True)
|
||||
(d / 'metal').write_text('same fetch MSL'); (d / 'mac.metallib').write_bytes(b'untested variant')
|
||||
d = self.ns['bf_cache_root'](old)
|
||||
self.ns['STORE'].put(d + '/metal', b'same fetch MSL'); self.ns['STORE'].put(d + '/mac.metallib', b'untested variant')
|
||||
self.ns['METAL_FP'] = 'tested Metal and SDK'
|
||||
current = self.ns['bf_digest']('same fetch MSL', 'key')
|
||||
self.assertFalse(self.ns['bf_cache_restore']('key', current, {}, str(Path(self.tmp.name) / 'fetch.metal')))
|
||||
@@ -142,22 +143,27 @@ class ShaderCache(unittest.TestCase):
|
||||
self.ns['TARGETS'] = {'mac', 'ios'}
|
||||
self.assertFalse(self.ns['restore_cache']('key', 'digest'))
|
||||
|
||||
def test_an_entry_pruned_during_a_restore_is_a_miss(self): # another build sharing the cache removed it after the look at its names
|
||||
root = self.ns['cache_path']('digest')
|
||||
for name, data in (('key_b.json', b'{}'), ('key_b.metal', b'MSL'), ('key_b.metallib', b'library')): self.ns['STORE'].put(f'{root}/mac/{name}', data)
|
||||
real = self.ns['STORE'].get
|
||||
self.ns['STORE'].get = lambda name: None if name.endswith('key_b.json') else real(name)
|
||||
self.addCleanup(lambda: setattr(self.ns['STORE'], 'get', real))
|
||||
self.assertFalse(self.ns['restore_cache']('key', 'digest'))
|
||||
|
||||
def test_cache_without_analysis_source_is_a_miss(self):
|
||||
self.ns.update(TARGETS={'ios'}, IOSOUT=str(Path(self.tmp.name) / 'ios'))
|
||||
root = Path(self.ns['cache_path']('digest'))
|
||||
for label in ('mac', 'ios'):
|
||||
(root / label).mkdir(parents=True)
|
||||
(root / label / 'key_b.json').write_text('{}')
|
||||
(root / 'ios/key_b.metallib').write_bytes(b'library')
|
||||
root = self.ns['cache_path']('digest')
|
||||
for label in ('mac', 'ios'): self.ns['STORE'].put(f'{root}/{label}/key_b.json', b'{}')
|
||||
self.ns['STORE'].put(f'{root}/ios/key_b.metallib', b'library')
|
||||
self.assertFalse(self.ns['restore_cache']('key', 'digest'))
|
||||
|
||||
def test_dual_target_cache_restores_only_requested_ios_libraries(self):
|
||||
root = Path(self.ns['cache_path']('digest'))
|
||||
root = self.ns['cache_path']('digest')
|
||||
for label in ('mac', 'ios'):
|
||||
(root / label).mkdir(parents=True)
|
||||
(root / label / 'key_b.json').write_text('{}')
|
||||
(root / label / 'key_b.metallib').write_bytes(label.encode())
|
||||
(root / 'mac/key_b.metal').write_text('MSL')
|
||||
self.ns['STORE'].put(f'{root}/{label}/key_b.json', b'{}')
|
||||
self.ns['STORE'].put(f'{root}/{label}/key_b.metallib', label.encode())
|
||||
self.ns['STORE'].put(f'{root}/mac/key_b.metal', b'MSL')
|
||||
self.ns.update(TARGETS={'ios'}, IOSOUT=str(Path(self.tmp.name) / 'ios'))
|
||||
Path(self.ns['IOSOUT']).mkdir()
|
||||
self.assertTrue(self.ns['restore_cache']('key', 'digest'))
|
||||
@@ -215,7 +221,7 @@ class ShaderCache(unittest.TestCase):
|
||||
(out / 'vertex_b.metallib').write_bytes(b'un-padded library')
|
||||
(out / 'vertex_b.json').write_text(json.dumps({'stage': 'vs', 'vs_pad': []}))
|
||||
self.ns['publish_cache']('vertex', 'digest', 'rule', 'source')
|
||||
self.assertFalse(Path(self.ns['cache_meta_path']('vertex')).exists())
|
||||
self.assertFalse(self.ns['STORE'].has(self.ns['cache_meta_path']('vertex')))
|
||||
self.assertFalse(self.ns['restore_cache']('vertex', 'digest'))
|
||||
|
||||
def test_vertex_only_request_retains_padding_on_subsequent_full_cache_reuse(self):
|
||||
@@ -330,7 +336,7 @@ class MetalPrefill(unittest.TestCase):
|
||||
self.root = Path(self.tmp.name); self.old = self.root / 'b-old'; self.old.mkdir()
|
||||
def compile_current(msl, air, lib): Path(lib).write_bytes(b'TESTED ' + Path(msl).read_bytes())
|
||||
with mock.patch.object(dmsh_mtlcache, 'compiler_id', return_value='tested compiler and SDK'):
|
||||
self.cache = dmsh_mtlcache.Cache(str(self.root / 'cas'), {'mac': ('macosx', 'flags', compile_current)}, str(self.root))
|
||||
self.cache = dmsh_mtlcache.Cache(shader_cache.Store(self.root / 'cas.db'), {'mac': ('macosx', 'flags', compile_current)}, str(self.root))
|
||||
|
||||
def earlier_libraries(self, third_identity):
|
||||
for i in range(3):
|
||||
@@ -347,7 +353,7 @@ class MetalPrefill(unittest.TestCase):
|
||||
def test_every_prefilled_library_requires_matching_compiler_identity(self):
|
||||
for identity in (None, 'other compiler'):
|
||||
with self.subTest(identity=identity):
|
||||
if (self.root / 'cas').exists(): shutil.rmtree(self.root / 'cas')
|
||||
self.cache.store = shader_cache.Store(self.root / f'cas-{identity}.db')
|
||||
self.earlier_libraries(identity)
|
||||
self.cache.fill(str(self.old))
|
||||
result = self.root / 'result.metallib'
|
||||
@@ -371,8 +377,7 @@ class MetalPrefill(unittest.TestCase):
|
||||
src = b'MSL'; msl = self.root / 'shader.metal'; msl.write_bytes(src)
|
||||
old_ident = hashlib.sha256(b'dmsh_mtlcache 1\0flags\0tested compiler and SDK').digest()
|
||||
digest = hashlib.sha256(old_ident + b'\0' + src).hexdigest()
|
||||
old_path = self.root / 'cas/mac' / digest[:2] / (digest + '.metallib')
|
||||
old_path.parent.mkdir(parents=True); old_path.write_bytes(b'WRONG OVERRIDE LIBRARY')
|
||||
self.cache.store.put(f'metallib/mac/{digest}.metallib', b'WRONG OVERRIDE LIBRARY')
|
||||
result = self.root / 'result.metallib'; self.cache.compile('mac', str(msl), str(result))
|
||||
self.assertEqual(result.read_bytes(), b'TESTED MSL')
|
||||
|
||||
|
||||
@@ -121,6 +121,11 @@ class PackQuiet(unittest.TestCase):
|
||||
self.assertEqual((self.w / 'kept.tar').read_bytes(), b'mine')
|
||||
self.assertTrue((self.w / 'kept').is_dir()); self.assertTrue((self.w / 'regress').is_dir()); self.assertTrue((self.w / 'small').is_dir())
|
||||
|
||||
def test_a_virtual_environment_stays(self): # scripts run it by its path, and nothing writes to it, so it looks untouched
|
||||
self.folder('venv'); (self.w / 'venv/pyvenv.cfg').write_text('home = /x\n'); self.folder('py'); (self.w / 'py/pyvenv.cfg').write_text('home = /x\n')
|
||||
self.assertEqual(self.run_old(), [])
|
||||
self.assertTrue((self.w / 'venv').is_dir()); self.assertTrue((self.w / 'py').is_dir())
|
||||
|
||||
def test_a_folder_with_a_recent_file_stays(self):
|
||||
self.folder('busy')
|
||||
self.assertEqual(tree_tar.pack_quiet(self.w, self.lines.append), []) # 14 days: everything here is newer
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# One uncompressed tar in place of a folder of many small files that only a build reads: the Metal and shader compile cache (shader/cache/cas, Metroid Dread's 84,541 files) and
|
||||
# Xcode's derived data (ipa/build/ios/pkg/dd). A build unpacks the folder, uses it with ordinary paths and packs it at the end, so the tools that read it do not change. The tar sits
|
||||
# One uncompressed tar in place of a folder of many small files that only a build reads: Xcode's derived data (ipa/build/ios/pkg/dd), which Xcode wants as a folder. A build unpacks the folder, uses it with ordinary paths and packs it at the end, so the tools that read it do not change. The tar sits
|
||||
# beside the folder as <folder>.tar. A build that stops leaves the folder as it is, and the next one takes it. Times are kept: Xcode's incremental build and prune_shader_cache go by them.
|
||||
# Every state a stop can leave is handled by unpack:
|
||||
# folder alone a stopped build, or a build folder from before this: used as it is
|
||||
@@ -101,14 +100,15 @@ def _quiet_size(folder, since): # (files, bytes) under folder; None as soon as
|
||||
|
||||
def pack_quiet(work, say=print, days: float = QUIET_DAYS, min_files=QUIET_MIN_FILES):
|
||||
"""Each top-level folder of a game's work folder (<NSP folder>/<id>-work) untouched for days becomes <name>.tar, `tar --xattrs -xf <name>.tar -C <name>` in a new folder bringing it back:
|
||||
what agents and investigations leave there, hundreds of thousands of files nothing reads again. regress/ is regress.py's own, and a folder of few files is left readable.
|
||||
what agents and investigations leave there, hundreds of thousands of files nothing reads again. regress/ is regress.py's own, a folder of few files is left readable, and a Python virtual
|
||||
environment (pyvenv.cfg) stays, however long it goes unchanged: its files are read and not written, and scripts run it by its path.
|
||||
An existing <name>.tar is never overwritten. The tar must fit on the drive beside the folder, with QUIET_FREE to spare. Returns the names packed"""
|
||||
done, since = [], time.time() - days * 86400
|
||||
try:
|
||||
with os.scandir(work) as it: entries = sorted((e for e in it if e.is_dir(follow_symlinks=False)), key=lambda e: e.name)
|
||||
except OSError: return done
|
||||
for e in entries:
|
||||
if e.name == 'regress' or e.name.endswith(('.gone', '.unpack')) or tar_of(e.path).exists(): continue
|
||||
if e.name == 'regress' or e.name.endswith(('.gone', '.unpack')) or tar_of(e.path).exists() or os.path.isfile(os.path.join(e.path, 'pyvenv.cfg')): continue
|
||||
try:
|
||||
if os.stat(e.path).st_ctime >= since or not (size := _quiet_size(e.path, since)) or size[0] < min_files: continue
|
||||
if shutil.disk_usage(work).free < size[1] + QUIET_FREE:
|
||||
|
||||
@@ -20,6 +20,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- a `--romfs separate` app whose image was copied into its Documents folder by hand (Finder, the Files app, a LiveContainer guest) logs `boot: game files not found (Documents/romfs.img, Documents/romfs or <App>/romfs)`, and a build with `romfs.id` shows "There is no game file image on this device.", though the complete image is there. Renaming it to `romfs.img` makes the game start. → [A hand-copied RomFS.img is not found on iOS](../reference/packing.md#a-hand-copied-romfsimg-is-not-found-on-ios)
|
||||
- reducing the iPhone transfer to one image still creates thousands of resource files on the Mac, and build scanners require the expanded folder. → [Building creates a full RomFS tree before packing its image](../reference/packing.md#building-creates-a-full-romfs-tree-before-packing-its-image)
|
||||
- a game's `<id>_build` folder is slow to count, copy or delete: Metroid Dread's held 160,331 files in 48,782 folders, 84,541 of them in the compile cache. → [A build folder holds hundreds of thousands of small files](../reference/packing.md#a-build-folder-holds-hundreds-of-thousands-of-small-files)
|
||||
- a build that runs the shader step writes the compile cache's files back and removes them again, on Skyward Sword HD 24,131 files and 10,150 folders each time, Tears of the Kingdom over 900,000 entries. Removing old entries took up to half an hour on an external drive. → [The compile cache was unpacked for each build](../reference/packing.md#the-compile-cache-was-unpacked-for-each-build)
|
||||
- a game's shader libraries are slow to copy or delete: Skyward Sword HD's `b-<chain>/` held 12,064 files for 2,470 shaders, a third of its build folder's files, and each `regress.py` chain build held another set. A tar would not do: the host reads these files at every run. → [Shader libraries take a file per shader variant](../reference/packing.md#shader-libraries-take-a-file-per-shader-variant)
|
||||
- a game's `<id>-work` folder is too slow to count: Tears of the Kingdom's held 8,893,028 files and 509 GB, and its count ran past ten minutes. → [A work folder holds millions of small files](../reference/packing.md#a-work-folder-holds-millions-of-small-files)
|
||||
- the NSP script stops at the shader split of a registered profile with `[RED] 13744 file(s) could not be read, their shaders are left out (first: AI/FileEntry/FileEntry.Product.100.byml.zs: CalledProcessError: Command ['zstd', '-d', '-c', '-q', '…/extract/v0/RomFS.img/AI/…'] returned non-zero exit status 1.)`. → [The zstd command given a path inside the image](../reference/packing.md#the-zstd-command-given-a-path-inside-the-image)
|
||||
|
||||
+5
-3
@@ -431,7 +431,9 @@ A repeat build skips work whose inputs have not changed. The extraction is kept
|
||||
|
||||
The shader libraries are one file, `shader/cache/b-<chain>.img` for the Mac and `shader/ios/b-<chain>.img` for the iPhone, which the host and the tools read in place and which is never unpacked (`dm/tools/shader_lib.py`, [Shader libraries take a file per shader variant](reference/packing.md#shader-libraries-take-a-file-per-shader-variant)). A build writes the folder `b-<chain>/` and packs it at the end. To look inside: `shader_lib.py cat <lib> <name>`, or `romfs.Path` in Python.
|
||||
|
||||
Two folders of many small files that only a build reads are one uncompressed file between builds: the compile cache, `shader/cache/cas.tar`, and Xcode's derived data, `ipa/build/ios/pkg/dd.tar` (`dm/tools/tree_tar.py`). A step that runs unpacks its folder first and packs it at the end, and a reused step touches neither. A build folder from before this converts by itself on the next build, and a build that stops leaves the folder for the next one to take up ([Build folders of many small files](reference/packing.md#a-build-folder-holds-hundreds-of-thousands-of-small-files)).
|
||||
The compile cache is one file too, `shader/cache/cas.db` (`dm/tools/shader_cache.py`), which a build reads and writes in place, and into which a `cas/` or `cas.tar` from before it moves by itself ([The compile cache was unpacked for each build](reference/packing.md#the-compile-cache-was-unpacked-for-each-build)). Xcode's derived data, which Xcode wants as a folder, is one uncompressed file between builds, `ipa/build/ios/pkg/dd.tar` (`dm/tools/tree_tar.py`): the step that runs unpacks it first and packs it at the end, and a reused step does not touch it ([Build folders of many small files](reference/packing.md#a-build-folder-holds-hundreds-of-thousands-of-small-files)).
|
||||
|
||||
The Python tools need one venv, for every game: `python3 -m venv <drive with the games>/venv`, then `<that>/bin/pip install -r .github/requirements/tools.txt`. A game's work folder can link to it (`ln -s <drive>/venv <NSP folder>/<id>-work/venv`), so a script keeps running `venv/bin/python`.
|
||||
|
||||
Derived profiles keep generated files while `<id>.derived.key` matches and every source-generated data row remains intact, including repeated rows. Provisional and derived shader keys include their profile files and each RomFS or capture file's path, size and modification time. Re-extraction or a new capture timestamp therefore runs the split or Vulkan/GL translation again, even with identical bytes. Registered RomFS keys use paths and sizes; NVN split tables are still checked against the profile.
|
||||
|
||||
@@ -475,7 +477,7 @@ cd "<NSP folder>/<id>_build/run" && DM_ROOT="<NSP folder>/<id>_build" DM_ROMFS="
|
||||
|
||||
The save is in `<id>_build/run/save` and stays there from run to run. `DM_AOC_DIR` is added when the folder has DLC. `DM_NVN_SHMAP` is added for an NVN game; it names the profile's shader map, or the derived or provisional profile's. A Vulkan or GL game's `DM_MSL_DIR` is `<id>_build/shader`. The switches of `--env-file` are added to the command.
|
||||
|
||||
Reuse works as for the IPA. Each shader output has its own key, named after the one chain version: `shader/ios/b-<chain>.key` for the iOS libraries and `shader/mac-b-<chain>.key` for the Mac's (`shader/ios/vk.key` and `shader/vk.key` for a Vulkan game, the same with `gl` for a GL game). An NVN build writes only the requested target's key and compiles only its libraries, with one exception: an iOS build of a folder that holds the current chain's Mac libraries (a Mac-only build's, which its run command loads) builds them again too and writes both keys, since a full `dmsh_build.py` run removes every library of the folder before it rebuilds ([An iOS build after a Mac-only build kept no Mac libraries](reference/shaders.md#an-ios-build-after-a-mac-only-build-kept-no-mac-libraries)). The Mac sources and reflection are written and cached for either target, since paired vertex shaders, `c1_full.tsv` and `cb_extent.tsv` need them. A Mac-only build of a folder already packed as an IPA therefore translates again and compiles the Mac libraries. Either key is taken only while the Mac outputs carry a full build's stamp; `c1_full.tsv` or `cb_extent.tsv` that does not name it is made again from them, as for the IPA. Switching targets translates again because `dmsh_build.py`'s per-shader keys include the iOS compile convention; returning to a target reuses its previously compiled MSL from the Metal compile cache (`shader/cache/cas/metallib`). Vulkan and GL builds still compile both targets for an IPA. After a successful shader build, the script removes the libraries of other chain versions (`b-<other>` in `shader/cache` and `shader/ios`, and their keys) and logs `removed old shader libraries b-… (N GB)`. A chain change used to leave about 2 GB per update for Breath of the Wild. It then removes the per-shader cache entries (`shader/cache/cas/shader`) the current chain's last full build did not list, and logs `removed old shader cache entries: N (X GB)`; Tears of the Kingdom kept 12 GB of them from six updates ([Old per-shader cache entries](reference/shaders.md#old-per-shader-cache-entries-grew-a-games-build-folder-with-each-chain-change)). The Metal compile cache is not touched.
|
||||
Reuse works as for the IPA. Each shader output has its own key, named after the one chain version: `shader/ios/b-<chain>.key` for the iOS libraries and `shader/mac-b-<chain>.key` for the Mac's (`shader/ios/vk.key` and `shader/vk.key` for a Vulkan game, the same with `gl` for a GL game). An NVN build writes only the requested target's key and compiles only its libraries, with one exception: an iOS build of a folder that holds the current chain's Mac libraries (a Mac-only build's, which its run command loads) builds them again too and writes both keys, since a full `dmsh_build.py` run removes every library of the folder before it rebuilds ([An iOS build after a Mac-only build kept no Mac libraries](reference/shaders.md#an-ios-build-after-a-mac-only-build-kept-no-mac-libraries)). The Mac sources and reflection are written and cached for either target, since paired vertex shaders, `c1_full.tsv` and `cb_extent.tsv` need them. A Mac-only build of a folder already packed as an IPA therefore translates again and compiles the Mac libraries. Either key is taken only while the Mac outputs carry a full build's stamp; `c1_full.tsv` or `cb_extent.tsv` that does not name it is made again from them, as for the IPA. Switching targets translates again because `dmsh_build.py`'s per-shader keys include the iOS compile convention; returning to a target reuses its previously compiled MSL from the Metal compile cache (`metallib/` in `shader/cache/cas.db`). Vulkan and GL builds still compile both targets for an IPA. After a successful shader build, the script removes the libraries of other chain versions (`b-<other>` in `shader/cache` and `shader/ios`, and their keys) and logs `removed old shader libraries b-… (N GB)`. A chain change used to leave about 2 GB per update for Breath of the Wild. It then removes the per-shader cache entries (`shader/cache/cas/shader`) the current chain's last full build did not list, and logs `removed old shader cache entries: N (X GB)`; Tears of the Kingdom kept 12 GB of them from six updates ([Old per-shader cache entries](reference/shaders.md#old-per-shader-cache-entries-grew-a-games-build-folder-with-each-chain-change)). The Metal compile cache is not touched.
|
||||
|
||||
### A benchmark on the Mac
|
||||
|
||||
@@ -687,7 +689,7 @@ GAME=$G W=$W dm/ios/tools/build_ipa.sh [out.ipa]
|
||||
Notes on these steps:
|
||||
- `dmsh_build.py` stops when a tool differs from `dm/gfx/tools/dmsh_chain.lock`. To try another Metal compiler, run `DM_ALLOW_OTHER_METAL=1 dm/gfx/tools/own_compilers.py` with the same arguments and environment. It reports the actual compiler and keeps its cached libraries separate from the tested compiler's; the translator and SPIRV-Cross must still match.
|
||||
- After a chain change, `python3 dm/gfx/tools/shader_regressions.py $W/build/cache/metal_shader_cache` lists the shaders that translated in the previous `b-*/` there and fail in the current one (exit status 1), as the NSP script does after its shader step.
|
||||
- `dmsh_build.py` compiles each shader's Metal source through a cache keyed by that source, the compile flags and the compiler (`dm/gfx/tools/dmsh_mtlcache.py`, in `<cache>/cas/metallib/`). A chain change that leaves a shader's MSL unchanged costs that shader no Metal compile while the cache format and compiler stay unchanged. Before building, the cache takes libraries from earlier `b-*/` folders beside its output (and beside `IOSOUT`), and from `DMSH_PREFILL=<Mac root>[=<iOS root>]` (several separated by `:`). Every imported library must record the current flags and compiler identity in its reflection; unmarked legacy libraries are rebuilt. A fresh compile of two shaders per stage also checks their bytes. The summary line `Metal cache:` shows reused, compiled and filled counts per target.
|
||||
- `dmsh_build.py` compiles each shader's Metal source through a cache keyed by that source, the compile flags and the compiler (`dm/gfx/tools/dmsh_mtlcache.py`, as `metallib/` entries of `<cache>/cas.db`). A chain change that leaves a shader's MSL unchanged costs that shader no Metal compile while the cache format and compiler stay unchanged. Before building, the cache takes libraries from earlier `b-*/` folders beside its output (and beside `IOSOUT`), and from `DMSH_PREFILL=<Mac root>[=<iOS root>]` (several separated by `:`). Every imported library must record the current flags and compiler identity in its reflection; unmarked legacy libraries are rebuilt. A fresh compile of two shaders per stage also checks their bytes. The summary line `Metal cache:` shows reused, compiled and filled counts per target.
|
||||
- Its Metal compiles use a precompiled header of Metal's texture classes (`dm/gfx/tools/dmsh_pch.py`), about half of a compile's CPU, with byte-identical output ([Each Metal compile instantiates Metal's texture classes again](reference/shaders.md#each-metal-compile-instantiates-metals-texture-classes-again)). `DMSH_PCH=0` compiles without it.
|
||||
- Each shader's cache key (`shader_key`) includes `CODE_FP`, a hash of the *code form* (`dmsh_chain.code_form`: the AST, with docstrings and the rule functions' bodies removed) of `dmsh_build.py` and its helper modules. An edit that cannot change the output (a comment, a docstring, blank lines, formatting) keeps every shader's key, so the next build restores them all instead of translating them again; any change to code, a constant, a string literal or a default argument still rebuilds all of them. The chain version is not touched by this: it still hashes whole files.
|
||||
- `build_ipa.sh` takes the rewritten modules from `$W/build/patched_<package>` and the RomFS image from `$W/data/<package>/RomFS.img` (legacy folders are also accepted); `PATCHED` and `ROMFS` override them. In unsigned IPA mode, `pack_ipa.py` packs the shader libraries, RomFS and add-on content beside the app Xcode built, as `DmIOS.app/msl/b-<chain version>`, `romfs` and `aoc`. Prepared Xcode projects instead sync these resources into the app before signing.
|
||||
|
||||
@@ -117,10 +117,18 @@
|
||||
### A build folder holds hundreds of thousands of small files
|
||||
|
||||
- **Symptom:** a game's `<id>_build` folder is slow to count, copy or delete: Metroid Dread's held 160,331 files in 48,782 folders, 84,541 of them in the compile cache.
|
||||
- **Cause:** the compile cache (`shader/cache/cas`) keeps a few files per shader, and Xcode's derived data (`ipa/build/ios/pkg/dd`) over a thousand. Both are needed to make the next build fast, and only while a build runs.
|
||||
- **Cause:** the compile cache (`shader/cache/cas`) keeps a few files per shader, and Xcode's derived data (`ipa/build/ios/pkg/dd`) over a thousand. Both are needed to make the next build fast, and only while a build runs. The cache has since become [one file read in place](#the-compile-cache-was-unpacked-for-each-build), and the tar remains for the derived data.
|
||||
- **Fix:** `dm/tools/tree_tar.py` keeps each as one uncompressed tar beside where the folder was. `build_shaders` unpacks the cache only when `dmsh_build.py` will run, and packs it after pruning; the NSP script does the same for the derived data around `build_ipa.sh`. Keeping real folders during the build leaves `dmsh_build.py`, its chain version and Xcode unchanged. A build folder from before this converts by itself. Restored files keep their times, and Xcode's incremental build holds across the round trip (1 file compiled, against 262 for a full build). A build that stops leaves the folder, and a damaged tar costs only the cache it held. `regress.py`'s chain builds share the cache under the same lock. The cost is time on each build that runs the step, and a cache that no longer shares its libraries' blocks through APFS clones. The shader libraries (`b-<chain>`) stay folders: the host reads them one by one.
|
||||
- **Found on:** [ANIMAL WELL](../../dm/games/010020D01AD24000/README.md#found-on-this-game) (the round trip) and [Metroid Dread](../../dm/games/010093801237C000/README.md#found-on-this-game) (84,541 cache files: 51 s to pack, 22 s to restore on a T7).
|
||||
|
||||
### The compile cache was unpacked for each build
|
||||
|
||||
- **Symptom:** a build that runs the shader step writes the compile cache's files back and removes them again, on Skyward Sword HD 24,131 files and 10,150 folders each time, Tears of the Kingdom over 900,000 entries. Removing old entries took up to half an hour on an external drive.
|
||||
- **Cause:** the cache was a folder of a few files per shader, read and written by path, so a tar could only hold it between builds.
|
||||
- **Fix:** `dm/tools/shader_cache.py` keeps it as one SQLite file, `cas.db`, whose entries go in and out by name, with nothing unpacked. Bytes are stored by their hash, since a library under its MSL's digest and its shader's digest was one APFS clone. `dmsh_build.py` and `dmsh_mtlcache.py` use it directly; a shader's entry is written in one transaction, so a stop leaves all of it or none. Several writers wait for each other: `dmsh_build.py`'s threads share a connection, and `regress.py`'s chain builds and the NSP script share the file. Pruning is a query that gives its pages back. A `cas/` or `cas.tar` from before this moves in by itself at the next shader step, without unpacking a tar: the Metal compile results come along. The per-shader entries do not, as the change of chain they came with means they cannot hit, and neither do the fetch variants, whose older entries hold their source's file name, so that a fresh compile's bytes differ (`regress.py` reports these as changed variants with no change of MSL). A damaged file costs the work it held and is made anew, and a full drive is one `[RED]` line. A revision from before this keeps its own folder, `regress/cas`.
|
||||
- **Measured** on Skyward Sword HD: a 281 MB `cas.tar` became a 226 MB `cas.db`, restoring all 2,470 shaders from the cache took 6 s (9 to 13 s with the tar), and the build folder's `shader/` holds 8 files. It also ran on an exFAT volume, with three processes writing at once.
|
||||
- **Found on:** [Skyward Sword HD](../../dm/games/01002DA013484000/README.md#found-on-this-game).
|
||||
|
||||
### Shader libraries take a file per shader variant
|
||||
|
||||
- **Symptom:** a game's shader libraries are slow to copy or delete: Skyward Sword HD's `b-<chain>/` held 12,064 files for 2,470 shaders, a third of its build folder's files, and each `regress.py` chain build held another set. A tar would not do: the host reads these files at every run.
|
||||
@@ -133,7 +141,7 @@
|
||||
|
||||
- **Symptom:** a game's `<id>-work` folder is too slow to count: Tears of the Kingdom's held 8,893,028 files and 509 GB, and its count ran past ten minutes.
|
||||
- **Cause:** `regress.py` kept one whole shader build per chain version in `regress/chain` (45 there; Breath of the Wild held 57), and agents' investigations leave folders nothing reads again (`build` alone over 351,000 files).
|
||||
- **Fix:** `prune_chains` in `scripts/regress.py` removes chain builds after each chain step, beyond the 3 used last, any used within 24 hours and those of the 3 newest stored baselines; a check that needs one builds it again. `tree_tar.pack_quiet` packs each other top-level folder untouched for 14 days, with 100 files or more, into `<name>.tar` at the end of an NSP script or `regress.py` run. These tars keep extended attributes, so a RomFS folder's case-collision names survive, and `tar --xattrs -xf` restores them (plain `tar -xf` does not). It frees no space beyond the chain builds: a folder of APFS clones can take more as a tar, so each tar must fit with 20 GB to spare. A player's NSP folder has no work folder.
|
||||
- **Fix:** `prune_chains` in `scripts/regress.py` removes chain builds after each chain step, beyond the 3 used last, any used within 24 hours and those of the 3 newest stored baselines; a check that needs one builds it again. `tree_tar.pack_quiet` packs each other top-level folder untouched for 14 days, with 100 files or more, into `<name>.tar` at the end of an NSP script or `regress.py` run. These tars keep extended attributes, so a RomFS folder's case-collision names survive, and `tar --xattrs -xf` restores them (plain `tar -xf` does not). A Python virtual environment stays a folder, as scripts run it by its path and nothing writes to it, which made it look untouched. It frees no space beyond the chain builds: a folder of APFS clones can take more as a tar, so each tar must fit with 20 GB to spare. A player's NSP folder has no work folder.
|
||||
- **Found on:** [Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md#found-on-this-game).
|
||||
|
||||
### The zstd command given a path inside the image
|
||||
|
||||
@@ -1682,7 +1682,7 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
|
||||
- **Symptom:** `<id>_build/shader/cache/cas/shader/` holds several entries for each shader, and grows by a full set with every upstream update that changes the shader chain. Tears of the Kingdom ([seedds/nxnative#1033](https://github.com/seedds/nxnative/issues/1033)): 172,014 entries after six builds for 28,669 shaders, 11.85 GB of `.metal` and `.json` that no build read; the test Mac's copy held 934,955, of which the prune (dry run) found 906,286 unused: 70.2 GB of sources and reflection, scanned in 18 minutes on an external SSD.
|
||||
- **Cause:** each shader's cache digest (`dmsh_build.py` `shader_key`) covers the chain's code and tools, so a chain change misses every entry and publishes a new one. [Old shader library folders](#old-shader-library-folders-grew-a-games-build-folder-with-each-chain-change) removed the old `b-<chain>/` folders, not these entries. `cas/index/<key>.json` cannot tell which entry is in use: a cache hit does not rewrite it, so after a checkout of an older commit it can name a newer digest than the one the build restores. The digests also cover the iOS compile convention, so a Mac-only and an iOS build of one chain use different entries, and `regress.py` builds other chains into the same cache.
|
||||
- **Fix:** a full `dmsh_build.py` run lists the digests it used, `b-<chain>/_b_cas.txt` beside the Mac outputs (every full build writes those; the iOS folder goes whole into the IPA). The NSP script (`prune_shader_cache`, called with `prune_stale_chains` after a successful or reused build) removes the `cas/shader/<64 hex digits>` entries the list does not name and that are older than it, and logs `removed old shader cache entries: N (X GB)`, the space of their sources and reflection (an entry's libraries are clones of the compile cache's). No list (libraries built before it), a failed or stopped build, or a regress run: nothing goes. `cas/metallib` and `cas/variant` are keyed by the MSL and stay, so a chain that comes back, or a build for the other target, translates again but compiles in Metal only MSL it has not seen. A partial `dmsh_build.py` run (named keys) does not rewrite the list, so the next prune can remove the entries it published; the next full build translates those shaders again.
|
||||
- **Fix:** a full `dmsh_build.py` run lists the digests it used, `b-<chain>/_b_cas.txt` beside the Mac outputs (every full build writes those; the iOS folder goes whole into the IPA). The NSP script (`prune_shader_cache`, called with `prune_stale_chains` after a successful or reused build) removes the `shader/<64 hex digits>` entries of the compile cache that the list does not name and that are older than it, and logs `removed old shader cache entries: N (X GB)`, the space of their sources and reflection (an entry's libraries are clones of the compile cache's). No list (libraries built before it), a failed or stopped build, or a regress run: nothing goes. `cas/metallib` and `cas/variant` are keyed by the MSL and stay, so a chain that comes back, or a build for the other target, translates again but compiles in Metal only MSL it has not seen. A partial `dmsh_build.py` run (named keys) does not rewrite the list, so the next prune can remove the entries it published; the next full build translates those shaders again.
|
||||
- **Found on:** [Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md#found-on-this-game) (resolved).
|
||||
- **Check:** `test_nsp_mac.py` (`test_prune_shader_cache`, `test_prune_shader_cache_needs_success_and_the_list`).
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ import romfs as rfs
|
||||
import nso # the code module loader: nso.Error is a damaged module (its file cut short or not what its header says)
|
||||
import tree_tar # one file in place of a build's folders of many small files
|
||||
import shader_lib # the shader libraries as one file, read in place
|
||||
import shader_cache # the compile cache as one file, read in place
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import pack_dump # a folder of a game's files instead of NSPs
|
||||
import pack_nup # a game in a NUP container instead of NSPs
|
||||
@@ -2328,29 +2329,20 @@ def prune_stale_chains(sh, chain):
|
||||
|
||||
|
||||
def prune_shader_cache(sh, chain):
|
||||
"""Remove the per-shader cache entries (sh/cache/cas/shader/<digest>) the current chain's last full build did not use, with prune_stale_chains and under the same conditions (issue #1033).
|
||||
"""Remove the per-shader cache entries (shader/<digest> in sh/cache/cas.db) the current chain's last full build did not use, with prune_stale_chains and under the same conditions (issue #1033).
|
||||
A shader's digest covers the chain's code, so each chain change translated every shader again into a new entry and left the old ones: Tears of the Kingdom's held six sets for 28,669 shaders,
|
||||
11.85 GB of sources and reflection nothing read. The digests in use are listed by dmsh_build.py's full build in b-<chain>/_b_cas.txt beside the Mac outputs (every full build writes them);
|
||||
cas/index cannot tell, since a cache hit does not rewrite it. No list (libraries from before the list): nothing goes. An entry newer than the list stays (regress.py's chain builds share this
|
||||
index/ cannot tell, since a cache hit does not rewrite it. No list (libraries from before the list): nothing goes. An entry newer than the list stays (regress.py's chain builds share this
|
||||
cache and may publish meanwhile). The digests also cover the iOS compile convention, so a build of the other target translates again, as switching targets did before; the Metal compile cache
|
||||
(cas/metallib) and the fetch variants (cas/variant) are keyed by the MSL and stay. Only names of 64 hex digits go. Removals that fail are one [RED] line, as for the libraries.
|
||||
(metallib/) and the fetch variants (variant/) are keyed by the MSL and stay. Only names of 64 hex digits go. Removals that fail are one [RED] line, as for the libraries.
|
||||
Logs the space of the sources and reflection: an entry's libraries are clones of the compile cache's. Returns the number removed"""
|
||||
used = shader_lib.view(sh / 'cache' / f'b-{chain}') / '_b_cas.txt'
|
||||
try: keep, since = set(used.read_text().split()), used.stat().st_mtime
|
||||
except OSError: return 0
|
||||
n = size = 0; failed = []
|
||||
try: it = os.scandir(sh / 'cache' / 'cas' / 'shader')
|
||||
except OSError: return 0
|
||||
with it:
|
||||
for e in it:
|
||||
try:
|
||||
if e.name in keep or not re.fullmatch(r'[0-9a-f]{64}', e.name) or not e.is_dir(follow_symlinks=False) or e.stat(follow_symlinks=False).st_mtime >= since: continue
|
||||
if not n and not failed: say('removing the shader cache of other chain versions (the first time, up to half an hour for a large game on an external drive)') # Tears of the Kingdom: 906,286 entries scanned in 18 minutes on a T7
|
||||
b = sum(f.stat().st_size for f in Path(e.path).rglob('*') if f.is_file() and f.suffix != '.metallib')
|
||||
rmtree(Path(e.path))
|
||||
except OSError as x: failed.append(f'{e.path}: {x}'); continue
|
||||
n += 1; size += b
|
||||
if failed: say(f'[RED] could not remove {len(failed):,} old shader cache entries, the first {failed[0]}')
|
||||
if not shader_cache.exists(sh / 'cache/cas.db'): return 0
|
||||
store = shader_cache.Store(sh / 'cache/cas.db', say)
|
||||
try: n, size = store.prune_shaders(keep, since)
|
||||
finally: store.close()
|
||||
if n: say(f'removed old shader cache entries: {n:,} ({amount(size, "B")})')
|
||||
return n
|
||||
|
||||
@@ -2404,12 +2396,13 @@ def build_shaders(py, repo, sh, xlate, env, logs, g, pkg_key=None, mac=False, se
|
||||
while the Mac sources and reflection carry a full build's stamp (inputs.tsv) for c1_full.tsv and cb_extent.tsv to name (chain_tables).
|
||||
Switching targets translates again (the per-shader keys include the iOS compile convention); the Metal compile cache (dmsh_mtlcache.py) reuses previously compiled MSL for that target.
|
||||
After success the libraries of other chain versions and the cache entries this chain's build did not use are removed (prune_stale_chains, prune_shader_cache), the libraries become one file each,
|
||||
b-<chain>.img beside the folder's name, read in place (shader_lib.py), and the cache becomes one file, sh/cache/cas.tar (tree_tar.py), which only a build that runs dmsh_build.py unpacks: a reused step touches none of their files.
|
||||
b-<chain>.img beside the folder's name, read in place (shader_lib.py), and the compile cache is one file, sh/cache/cas.db (shader_cache.py), read in place and into which a cache from before it moves: a reused step touches none of their files.
|
||||
seen (--seen-shaders, a Mac-only build): only those keys, into sh/partial/b-<chain>, emptied first, with its key inside; the full build's libraries, its key and the cache are left as they are, and the
|
||||
per-shader cache (DMSH_CAS) is the full build's, so a later full build reuses this work. It gets no stamp and no c1_full.tsv or cb_extent.tsv, on purpose: beside a stamp the host would take the tables'
|
||||
silence on a shader the partial build never saw as proof it is safe (no chain_tables, no shader_regressions, no pruning; the host logs the missing stamp in red at each start)
|
||||
pull: an iPhone build's ios_wants_pulling. False neither compiles the pulling libraries nor keeps them in its image; True does not reuse an image without them"""
|
||||
ios, log, cas = sh / 'ios', logs / 'dmsh_build.log', sh / 'cache/cas'
|
||||
ios, log, cas = sh / 'ios', logs / 'dmsh_build.log', sh / 'cache/cas.db'
|
||||
shader_cache.adopt(sh / 'cache/cas', cas, say)
|
||||
PROG.stage('Mac shaders' if mac else 'iOS shaders')
|
||||
chain = chain_of(repo)
|
||||
out = sh / 'partial' if seen else sh / 'cache' if mac else ios
|
||||
@@ -2425,7 +2418,7 @@ def build_shaders(py, repo, sh, xlate, env, logs, g, pkg_key=None, mac=False, se
|
||||
lost_pull = pull and not mac and not seen and shader_lib.left_out_pulling(libs) # now this app reads them: --gpu, the profile's pso_mtl4, IOS_PULL or --prepare-xcode changed
|
||||
if lost_pull: say('the app now needs the pulling vertex libraries, which this image left out: building them')
|
||||
if shader_lib.has_library(libs) and note is not None and not lost_pull and (seen or chain_tables(py, repo, sh, env, logs, g, chain)):
|
||||
if not seen: prune_stale_chains(sh, chain); prune_shader_cache(sh, chain); pack_libraries(sh, chain, None if mac else pull); tree_tar.pack(cas, say) # folders from before the two files become them here
|
||||
if not seen: prune_stale_chains(sh, chain); prune_shader_cache(sh, chain); pack_libraries(sh, chain, None if mac else pull) # folders from before this become the one file here
|
||||
PROG.end(f'{note}, reused (inputs unchanged)'); return out
|
||||
else: key = None
|
||||
rmtree(kmac)
|
||||
@@ -2446,8 +2439,6 @@ def build_shaders(py, repo, sh, xlate, env, logs, g, pkg_key=None, mac=False, se
|
||||
if mac: del benv['IOSOUT'] # dmsh_build.py builds the iOS libraries only with IOSOUT
|
||||
elif pull is False: benv['DMSH_IOS_PULL'] = '0' # nothing in this app reads them
|
||||
if seen: benv['DMSH_CAS'] = str(cas)
|
||||
PROG.set(step='unpacking the shader cache')
|
||||
tree_tar.unpack(cas, say)
|
||||
try: stale = None if seen else stale_shaders(py, repo, env, [sh / 'cache'] if mac else [sh / 'cache', ios] if keep_mac else [ios], chain, g)
|
||||
except Exception: stale = None # a note never stops the build
|
||||
if stale:
|
||||
@@ -2485,7 +2476,6 @@ def build_shaders(py, repo, sh, xlate, env, logs, g, pkg_key=None, mac=False, se
|
||||
if not seen: # last: a build that stopped before here keeps the old libraries and cache entries
|
||||
prune_stale_chains(sh, chain); prune_shader_cache(sh, chain); pack_libraries(sh, chain, None if mac else pull)
|
||||
if mac: rmtree(sh / 'partial') # the whole library replaces a partial one; partial-keys.txt stays
|
||||
tree_tar.pack(cas, say)
|
||||
return out
|
||||
|
||||
|
||||
|
||||
+17
-5
@@ -87,7 +87,8 @@ def load_module(name, path): # a module from a file (another script, or a tool
|
||||
bench = load_module('bench', REPO / 'scripts/bench.py')
|
||||
shader_regressions = load_module('shader_regressions', REPO / 'dm/gfx/tools/shader_regressions.py')
|
||||
usage = load_module('usage', REPO / 'dm/tools/usage.py') # usage manifests and change impact (regress.py usage / impact)
|
||||
tree_tar = load_module('tree_tar', REPO / 'dm/tools/tree_tar.py') # the player's build keeps the compile cache this shares as one file
|
||||
tree_tar = load_module('tree_tar', REPO / 'dm/tools/tree_tar.py') # a work folder's quiet folders as one file each, and an old revision's compile cache
|
||||
shader_cache = load_module('shader_cache', REPO / 'dm/tools/shader_cache.py') # the player's build keeps the compile cache this shares as one file, read in place
|
||||
shader_lib = load_module('shader_lib', REPO / 'dm/tools/shader_lib.py') # a chain build's libraries as one file, read in place
|
||||
rfs = shader_lib.romfs
|
||||
# Where they are depends on the machine (a drive with room for the trees and the games' NSP folders): set with --root / --games-dir or REGRESS_ROOT / REGRESS_GAMES, checked in main
|
||||
@@ -414,6 +415,17 @@ def prune_chains(g):
|
||||
return gone
|
||||
|
||||
|
||||
def chain_cache(tree, g):
|
||||
"""The compile cache a chain build of this revision uses: the player's build's one file when there is one, which a cache from before it moves into first, else the work folder's. A revision from before
|
||||
shader_cache.py wants a folder, regress/cas, kept as a tar between builds. Its chain key differs, as it covers dmsh_mtlcache.py, and its compiles are not shared"""
|
||||
if not (tree.path / 'dm/tools/shader_cache.py').is_file(): return game_root(g) / 'cas'
|
||||
shared, own = g.build / 'shader/cache/cas.db', game_root(g) / 'cas.db'
|
||||
shader_cache.adopt(g.build / 'shader/cache/cas', shared, say)
|
||||
if shared.is_file(): return shared
|
||||
shader_cache.adopt(game_root(g) / 'cas', own, say)
|
||||
return own
|
||||
|
||||
|
||||
def chain_lib(out): # a chain build's library, to read: its folder or its one file
|
||||
return shader_lib.view(next(p for p in sorted(out.glob('b-*')) if not p.name.endswith('.part')))
|
||||
|
||||
@@ -443,20 +455,20 @@ def chain_build_locked(tree, g, a, v, inp, key, out):
|
||||
done = (out / 'built.ok').is_file() # a build whose outputs are complete (a run stopped while hashing, or a build made by hand); its manifest is made again
|
||||
if g.kind == 'nvn':
|
||||
tools_dir = tree.path / 'dm/gfx/tools'
|
||||
cas = g.build / 'shader/cache/cas'
|
||||
env.update(XLATE=str(tools_dir / 'dmsh_xlate_bin/dmsh_xlate'), DMSH_CAS=str(cas if tree_tar.exists(cas) else game_root(g) / 'cas'))
|
||||
cas = chain_cache(tree, g)
|
||||
env.update(XLATE=str(tools_dir / 'dmsh_xlate_bin/dmsh_xlate'), DMSH_CAS=str(cas))
|
||||
entry = tools_dir / ('own_compilers.py' if (tools_dir / 'own_compilers.py').is_file() else 'dmsh_build.py')
|
||||
lib = out / f'b-{v}'
|
||||
if not done:
|
||||
say(f' {g.id}: chain {v} (inputs {inp}) of {tree.id}: translating the shaders ({jobs} workers) → {out}')
|
||||
if tree_tar.exists(cas): tree_tar.unpack(cas, say)
|
||||
if cas.suffix != '.db': tree_tar.unpack(cas, say)
|
||||
rc, paused = run_heavy([sys.executable, entry, g.build / 'shader/pkg', out], log, tree.path, env, a, f'{g.id} shader build'); t0 += paused
|
||||
if rc or not (lib / '_b_build.json').is_file():
|
||||
raise HarnessError(f'{g.id}: dmsh_build.py of {tree.id} failed (exit {rc}); last lines of {log}:\n' + ''.join(collections.deque(open(log, errors='replace'), maxlen=8)))
|
||||
prof = out / 'profile'; prof.mkdir(exist_ok=True) # the tables the host reads beside the shader map, as this build made them
|
||||
for src in g.profile_dir(tree).glob('*.tsv'): shutil.copyfile(src, prof / src.name)
|
||||
(out / 'built.ok').write_text(f'{tree.id}\n')
|
||||
tree_tar.pack(cas, say)
|
||||
if cas.suffix != '.db': tree_tar.pack(cas, say)
|
||||
say(f' {g.id}: hashing the outputs of chain {v}')
|
||||
shaders = nvn_manifest(lib, jobs)
|
||||
else:
|
||||
|
||||
Reference in new issue
Block a user