A pipeline archive flush period is handed over at its 2,000th capture, during a compacting prewarm too, and a pipeline the capture refuses is built by the plain compiler: one period of 8,693 bases filled Metal's archiver store (MDB_MAP_FULL, a 10 MB LMDB map per serializer) and Ocarina of Time's Kakariko Village lost 1,502 pipelines at 30-70 ms a frame

While a compacting prewarm ran, arch_flush waited for its end so the recaptured bases would make one file, so a period had no size limit; once its store was full every compile through the period's compiler failed and the host took that as the pipeline's failure. Now arch_capture / arch_capture_cs hand a period over at ARCH_PERIOD_MAX captures (arch_flush_from, periods of 3,508 were written whole), a compaction spans its periods and removes the old files once every one of them is written (kept when a write failed or a base was not captured again), and a refused capture builds with g_comp4: a period that holds captures is handed over once, a failure in one that holds none stops capturing for the run, a pipeline both compilers refuse returns the plain compiler's error. t_pso_archive (135 checks): the hand-over, the stop, both refusing, a compaction over periods of 4; t_pso_stall: a base Apple's compiler cannot build fails on both and leaves capturing on. Reference entry, game note, symptom index.

Diagnosis, fallback and reference entry from PR #1735; Ocarina of Time played on the Mac with this host: its archive's first compaction since Nov 6 (70 files into one, no capture failures).

Co-authored-by: Romen Adama Caetano Ramírez <[email protected]>
This commit is contained in:
seeddsandRomen Adama Caetano Ramírez committed 2026-11-08 10:45:19 +08:00
1 parent e940e1f3eb
commit eed7c42958
6 files changed
+153 -53

No files matched your search

+2
View File
@@ -38,6 +38,7 @@ Measured on an M6 Mac with 16 GB, headless, on one walk with camera turns (`walk
- The roughly 1 ms the [wind fix](../../../docs/reference/shaders.md#dead-code-removal-dropped-a-coordinate-of-a-multi-output-instruction) seemed to add: 0.66 ms of it is the upscaler, 416 → 1076 µs, because its variants then read what they had lost. It is doing its real work.
- Attachment traffic was not the cost it looked: 254 MB load and 277 MB store remain, and the cheapest passes move 20 MB in about 30 µs. The pass count was the cost.
- Resolved: 25-40 ms frames while the GPU sat idle with the next command buffer committed, 51-75 per 2,700 in a bad run: [the GPU idles with the next command buffer already committed](../../../docs/reference/frame-rate.md#the-gpu-idles-with-the-next-command-buffer-already-committed). What holds Metal's submission queue in the kernel is still unknown.
- Resolved: Kakariko Village at 30-70 ms a frame with 1,502 `background render pipeline creation failed … MDB_MAP_FULL` lines after a compacting prewarm of 40,000 rows put 8,693 bases into one archive period: [Metal's archiver store filled by one flush period](../../../docs/reference/rendering.md#metals-archiver-store-filled-by-one-flush-period).
- The title movie's network took 14.8 ms of compute a frame here (median from frame 3,000), so the title held 60 fps with almost nothing to spare, and slower GPUs fell below it: [issue 1375](https://github.com/seedds/nxnative/issues/1375), 35 ms on an M1 Max. Since [HMMA chains keep their matrices in the SIMD-group](../../../docs/reference/shaders.md#hmma-chains-keep-their-matrices-in-the-simd-group), 11.4 ms, and the GPU span 11.9 ms instead of 15.6 (26.7 → 18.9 ms of compute on an M4 with 8 GPU cores). Not measured on an M1 Max since.
- In a run that takes shots, each shot costs its frame 60–100 ms, and `DM_NVN_GPUPROF` and pass dumps slow the frames they cover.
- Open: frames of 100–650 ms when an area first loads (640 first uploads, 321 MB, in one frame of 294 ms; another 640 ms of submit with 68 MB).
@@ -131,6 +132,7 @@ From an empty save: at about 45 s `A` (title), `A` (New Game), then the movie. F
- [A texture ID with no texture kept its cached view](../../../docs/reference/rendering.md#a-texture-id-with-no-texture-kept-its-cached-view): the page faults at f3,677 and f4,851 with the render-target reclaim on.
- [Compute pipelines compiled at first use](../../../docs/reference/shaders.md#compute-pipelines-compiled-at-first-use): the offline archive holds a compute pipeline for each of the 4,125 compute shaders (480 MB, 204 s on an `applegpu_g18g` Mac). From `save_ref` to the village with an empty prewarm list, all 103 compute pipelines came from it and none were built. PR #1522 measured what that saves with the Metal cache cold: 195 s of pipelines on the submit thread before, 155 s of it in the title movie's twelve kernels.
- [Compute pipelines outside the bundled archive built at every start](../../../docs/reference/shaders.md#compute-pipelines-outside-the-bundled-archive-built-at-every-start): without the bundle, the first start's flushes wrote 88 compute pipelines into the device's archive, and the second start took 88 from it.
- [Metal's archiver store filled by one flush period](../../../docs/reference/rendering.md#metals-archiver-store-filled-by-one-flush-period): a compacting prewarm of 40,000 rows filled the archiver's store, Kakariko drawn without 1,502 pipelines (PR #1735).
- [Texture IDs of one storage share one packaged texture](../../../docs/reference/nvn-objects.md#texture-ids-of-one-storage-share-one-packaged-texture)
- [A texture shared by its packaged texture's serials left the residency set with one of them](../../../docs/reference/nvn-objects.md#a-texture-shared-by-its-packaged-textures-serials-left-the-residency-set-with-one-of-them): GPU page faults 15-45 minutes into play (issue #1326), on 260x260 terrain tiles made GPU textures at the GPU's first write.
- [Finalizing a copy of a texture object](../../../docs/reference/nvn-objects.md#finalizing-a-copy-of-a-texture-object)
+88 -41
View File
@@ -7604,11 +7604,15 @@ static id<MTL4Compiler> g_comp4;
static NSArray<id<MTL4Archive>> *g_arch4, *g_arch4p; static NSString *g_arch_dir; static int g_arch_seq;
// Compaction: every start writes a file or more (each flush captures only what is new), Breath of the Wild 5-7 per start, and each file a base is not in costs a lookup about 0.06 ms.
// With more than PSO_ARCH_COMPACT files of bases with a vertex layout, the bases the prewarm takes from them are captured again from the original shader functions, so the flush
// after the prewarm writes them into one file; the old files are then removed (open archives stay usable for the rest of the run). Bases the
// prewarm did not take (pso_user.tsv never named them) go with them and are built again when drawn. The prebuild's files (p<seq>) are left as they are
// after the prewarm writes them into one file, or one per ARCH_PERIOD_MAX of them; once every period that may hold them is written, the old files are removed (open archives stay
// usable for the rest of the run). Bases the prewarm did not take (pso_user.tsv never named them) go with them and are built again when drawn. The prebuild's files (p<seq>) are
// left as they are
enum { PSO_ARCH_COMPACT = 8 };
static int g_compact_enabled; // immutable after pso4_init; unlike g_compact_files, never cleared by the archive queue
static NSArray<NSString *> *g_compact_files; static _Atomic int g_compacted, g_compact_taken; // g_compact_taken: a flush period holds the recaptured bases (arch_flush)
static NSArray<NSString *> *g_compact_files; static _Atomic int g_compacted;
// g_compact_periods: periods that may hold recaptured bases, handed over and not written yet; g_compact_closed: the last of them is handed over (the first flush after the prewarm);
// g_compact_bad: one was not written, or a base the prewarm took from an old file was not captured again: the old files stay (arch_compact_finish)
static _Atomic int g_compact_periods, g_compact_closed, g_compact_bad;
// Keep the crash-recovery guard if a compaction still fails in Metal. Markers name the OS build and capture method: a marker from the old archive-import path must not
// disable the safer original-function capture. A failed flush of this method disables compaction on this OS build until it changes; ordinary archive reads remain available.
static NSString *arch_compact_marker(void) { return [g_arch_dir stringByAppendingPathComponent:@"compacting"]; }
@@ -7632,8 +7636,9 @@ static dispatch_queue_t g_arch_q; static _Atomic int g_arch_new, g_arch_new_vd,
// pipeline found in the files. The flush used to hold a lock against every such compile instead, and one compile that did not return (Super Mario Odyssey's alRenderMaterialUber
// with the front end at -O2: 33.7 minutes until Metal gave up, GitHub issue #294) held the flush, and the flush every compile and draw that came after it. Now such a compile
// holds back the file of its own period and nothing else
@interface ArchEpoch : NSObject { @public id<MTL4Compiler> comp; id<MTL4PipelineDataSetSerializer> ser; dispatch_group_t busy; _Atomic int active, n, vd, cs; int compacting; } @end
// n: pipelines captured; vd, cs: those of them that are bases with a vertex layout, compute pipelines
@interface ArchEpoch : NSObject { @public id<MTL4Compiler> comp; id<MTL4PipelineDataSetSerializer> ser; dispatch_group_t busy; _Atomic int active, n, vd, cs, failed; int compacting; } @end
// n: pipelines captured; vd, cs: those of them that are bases with a vertex layout, compute pipelines; failed: a capture in it failed (arch_cap_failed); compacting: it may hold
// recaptured bases (arch_flush)
@implementation ArchEpoch @end
static ArchEpoch *g_ep; static os_unfair_lock g_ep_lock = OS_UNFAIR_LOCK_INIT; // the current period
static int g_arch_cap; // compiles are captured (an archive folder, a serializer): immutable after pso4_init
@@ -7766,23 +7771,55 @@ static ArchEpoch *ep_enter(void) { // the current period, joined: a flush hand
return ep;
}
static void ep_leave(ArchEpoch *ep) { atomic_fetch_sub(&ep->active, 1); dispatch_group_leave(ep->busy); }
// A compile the archive captures, in the current flush period, counted there when it built (vd: the base has a vertex layout). No task options: a captured base never imports
// archive entries (see the compaction crash below)
static id<MTLRenderPipelineState> arch_capture(MTL4RenderPipelineDescriptor *d, NSError **e, int vd) {
if (!g_arch_cap) return [g_comp4 newRenderPipelineStateWithDescriptor:d compilerTaskOptions:nil error:e];
ArchEpoch *ep = ep_enter();
id<MTLRenderPipelineState> ps = [ep->comp newRenderPipelineStateWithDescriptor:d compilerTaskOptions:nil error:e];
if (ps) { atomic_fetch_add(&ep->n, 1); atomic_fetch_add(&g_arch_new, 1); if (vd) { atomic_fetch_add(&ep->vd, 1); atomic_fetch_add(&g_arch_new_vd, 1); } }
// A flush period's size. Metal keeps each serializer's state in an LMDB environment of fixed map size (10 MB, in its own com.apple.gpuarchiver/gpuarchiver-* folder under the
// user cache folder, PersistentState), and once that is full every compile through the period's compiler fails ("cannot commit transaction …: MDB_MAP_FULL", "cannot write
// 'UNITSMAPPINGS' database"), not only its capture. Periods of 3,508 bases were written whole; Ocarina of Time's compacting prewarm of a 40,000-row list, whose flushes waited
// for the prewarm's end, put 8,693 bases into one and filled it, and 1,502 pipelines failed to build (GitHub PR #1735). So the ARCH_PERIOD_MAX-th capture of a period
// hands it over (arch_flush_from), compaction or not, and each period gets a fresh environment. g_arch_period_max: the tests lower it
enum { ARCH_PERIOD_MAX = 2000 };
static int g_arch_period_max = ARCH_PERIOD_MAX;
static _Atomic int g_arch_cap_off; // capturing failed in a period that held nothing yet: the store was not full, so no more captures this run (arch_cap_failed)
static int arch_capturing(void) { return g_arch_cap && !atomic_load_explicit(&g_arch_cap_off, memory_order_relaxed); }
static void arch_flush_from(ArchEpoch *only);
// The capture refused a pipeline the plain compiler built. The archive is a cache and never a condition of drawing: the pipeline is used all the same. A period that has captured
// pipelines is taken as full and handed over, so the next captures go into a fresh environment (once per period: compiles under way in it fail too); a failure in a period that
// has captured nothing is not the store's size, and the run captures no more
static void arch_cap_failed(ArchEpoch *ep, NSError *ce, const char *what) {
const char *why = ce ? ce.localizedDescription.UTF8String : "no error given";
int n = atomic_load(&ep->n);
if (!n) { if (!atomic_exchange(&g_arch_cap_off, 1)) MLOG("[RED] pipeline archive: capturing a %s pipeline failed in a new flush period (%s): no more captures this run, pipelines are built without the archive", what, why); return; }
if (atomic_exchange(&ep->failed, 1)) return;
MLOG("[RED] pipeline archive: capturing a %s pipeline failed after %d in its flush period (%s): built without the archive, the captures go on in a new period", what, n, why);
arch_flush_from(ep);
}
// A compile the archive captures, in the current flush period, counted there when it built (vd: the base has a vertex layout; *captured: it is in the period). No task options: a
// captured base never imports archive entries (see the compaction crash below). One the capture refuses is built by the plain compiler (arch_cap_failed); a pipeline both refuse
// returns the plain compiler's error, or the capture's when it gave none
static id<MTLRenderPipelineState> arch_capture(MTL4RenderPipelineDescriptor *d, NSError **e, int vd, int *captured) {
if (captured) *captured = 0;
if (!arch_capturing()) return [g_comp4 newRenderPipelineStateWithDescriptor:d compilerTaskOptions:nil error:e];
ArchEpoch *ep = ep_enter(); NSError *ce = nil;
id<MTLRenderPipelineState> ps = [ep->comp newRenderPipelineStateWithDescriptor:d compilerTaskOptions:nil error:&ce];
int full = 0;
if (ps) { atomic_fetch_add(&g_arch_new, 1); if (vd) { atomic_fetch_add(&ep->vd, 1); atomic_fetch_add(&g_arch_new_vd, 1); } full = atomic_fetch_add(&ep->n, 1) + 1 == g_arch_period_max; }
ep_leave(ep);
if (ps) { if (captured) *captured = 1; if (full) arch_flush_from(ep); return ps; }
ps = [g_comp4 newRenderPipelineStateWithDescriptor:d compilerTaskOptions:nil error:e];
if (ps) arch_cap_failed(ep, ce, "render"); else if (e && !*e) *e = ce;
return ps;
}
// The same for a compute pipeline (cps_new). It counts as a base with a vertex layout does: its file is a plain one, never a p<seq> file, so its lookups skip the prebuild's files
static id<MTLComputePipelineState> arch_capture_cs(MTL4ComputePipelineDescriptor *d, NSError **e) {
if (!g_arch_cap) return [g_comp4 newComputePipelineStateWithDescriptor:d compilerTaskOptions:nil error:e];
ArchEpoch *ep = ep_enter();
id<MTLComputePipelineState> ps = [ep->comp newComputePipelineStateWithDescriptor:d compilerTaskOptions:nil error:e];
if (ps) { atomic_fetch_add(&ep->n, 1); atomic_fetch_add(&g_arch_new, 1); atomic_fetch_add(&ep->cs, 1); }
static id<MTLComputePipelineState> arch_capture_cs(MTL4ComputePipelineDescriptor *d, NSError **e, int *captured) {
if (captured) *captured = 0;
if (!arch_capturing()) return [g_comp4 newComputePipelineStateWithDescriptor:d compilerTaskOptions:nil error:e];
ArchEpoch *ep = ep_enter(); NSError *ce = nil;
id<MTLComputePipelineState> ps = [ep->comp newComputePipelineStateWithDescriptor:d compilerTaskOptions:nil error:&ce];
int full = 0;
if (ps) { atomic_fetch_add(&g_arch_new, 1); atomic_fetch_add(&ep->cs, 1); full = atomic_fetch_add(&ep->n, 1) + 1 == g_arch_period_max; }
ep_leave(ep);
if (ps) { if (captured) *captured = 1; if (full) arch_flush_from(ep); return ps; }
ps = [g_comp4 newComputePipelineStateWithDescriptor:d compilerTaskOptions:nil error:e];
if (ps) arch_cap_failed(ep, ce, "compute"); else if (e && !*e) *e = ce;
return ps;
}
// Metal opens a pipeline archive through NSData with "mapped if safe", and Foundation takes a file on an external drive as not safe: it reads it into memory, whole and for the whole run (docs/reference/memory.md). newArchiveWithURL has no option for this, so while the host
@@ -7861,11 +7898,14 @@ static dispatch_queue_t cps_harvest_q(void) { // one capture at a time, at uti
}
// d into the flush period, in the background; compact: a compaction's capture of a pipeline the prewarm took from an old file (as pso_build's bases)
static void cps_harvest(MTL4ComputePipelineDescriptor *d, int compact) {
if (!g_arch_cap || !d) return;
if (!d) return;
if (!arch_capturing()) { if (compact) g_compact_bad = 1; return; }
dispatch_async(cps_harvest_q(), ^{ @autoreleasepool {
NSError *ce = nil;
if (arch_capture_cs(d, &ce)) { if (compact) g_compacted++; arch_note_new(); }
else MLOG("[RED] compute pipeline %s: the Metal 4 compiler refused it (%s): not kept in the pipeline archive", d.computeFunctionDescriptor ? [(MTL4LibraryFunctionDescriptor *)d.computeFunctionDescriptor name].UTF8String : "(unnamed)",
NSError *ce = nil; int cap = 0;
id<MTLComputePipelineState> ps = arch_capture_cs(d, &ce, &cap);
if (cap) { if (compact) g_compacted++; arch_note_new(); }
else if (compact) g_compact_bad = 1;
if (!ps) MLOG("[RED] compute pipeline %s: the Metal 4 compiler refused it (%s): not kept in the pipeline archive", d.computeFunctionDescriptor ? [(MTL4LibraryFunctionDescriptor *)d.computeFunctionDescriptor name].UTF8String : "(unnamed)",
ce ? ce.localizedDescription.UTF8String : "no error given");
} });
}
@@ -7888,13 +7928,16 @@ static id<MTLComputePipelineState> cps_new(id<MTLFunction> f, NSError **e) {
if (ps) { atomic_fetch_add(&g_cps_built, 1); atomic_fetch_add(&g_cps_build_ns, bp_now() - t1); cps_harvest(d, 0); }
return ps;
}
// Writes one flush period's captures as the next file of the archive, on g_arch_q once every compile in the period has returned; g_arch_flush_ok: the last one wrote its file
static int g_arch_flush_ok;
// Writes one flush period's captures as the next file of the archive, on g_arch_q once every compile in the period has returned
static void arch_compact_finish(void);
static void arch_write_file(ArchEpoch *ep);
static void arch_write(ArchEpoch *ep) {
arch_write_file(ep);
if (ep->compacting && atomic_fetch_sub(&g_compact_periods, 1) == 1 && atomic_load(&g_compact_closed)) arch_compact_finish(); // the compaction's last period to be written
}
static void arch_write_file(ArchEpoch *ep) {
int n = atomic_load(&ep->n), vd = atomic_load(&ep->vd), cs = atomic_load(&ep->cs); // exact: no compile of the period is under way
if (!n) return;
g_arch_flush_ok = 0;
[NSFileManager.defaultManager createDirectoryAtPath:g_arch_dir withIntermediateDirectories:YES attributes:nil error:nil];
uint64_t t0 = bp_now(); NSError *e = nil;
NSString *path = [g_arch_dir stringByAppendingPathComponent:[NSString stringWithFormat:vd || cs ? @"%05d.mtl4a" : @"p%05d.mtl4a", g_arch_seq++]], *tmp = [path stringByAppendingString:@".tmp"];
@@ -7903,45 +7946,48 @@ static void arch_write(ArchEpoch *ep) {
if (ep->compacting) unlink(arch_compact_marker().fileSystemRepresentation);
atomic_fetch_sub(&g_arch_new, n); atomic_fetch_sub(&g_arch_new_vd, vd);
ok = ok && !rename(tmp.fileSystemRepresentation, path.fileSystemRepresentation);
if (!ok) { MLOG("[RED] pipeline archive: writing %s failed%s%s", path.UTF8String, e ? ": " : "", e ? e.localizedDescription.UTF8String : ""); unlink(tmp.fileSystemRepresentation); }
if (!ok) { MLOG("[RED] pipeline archive: writing %s failed%s%s", path.UTF8String, e ? ": " : "", e ? e.localizedDescription.UTF8String : ""); unlink(tmp.fileSystemRepresentation); if (ep->compacting) g_compact_bad = 1; }
else {
g_arch_flush_ok = 1;
MLOG("pipeline archive: %d new pipeline bases%s written to %s (%.1f MB, %.0f ms)", n - cs, cs ? [NSString stringWithFormat:@" and %d compute pipelines", cs].UTF8String : "", path.lastPathComponent.UTF8String,
[[NSFileManager.defaultManager attributesOfItemAtPath:path error:nil] fileSize] / 1048576.0, (bp_now() - t0) / 1e6);
}
if (ep->compacting) arch_compact_finish();
}
// A flush: the compiles from here on capture into a new period, and the current one is written once its compiles have returned. Returns at once, on any thread; a compile that
// does not return holds back only its own period's file
static void arch_flush(void) {
// Keep all recaptured bases in one serialization, even when a prewarm lasts beyond the timer.
if (!g_arch_cap || (g_compact_enabled && atomic_load(&g_warm_running))) return;
os_unfair_lock_lock(&g_ep_lock); int any = atomic_load(&g_ep->n) || atomic_load(&g_ep->active); os_unfair_lock_unlock(&g_ep_lock);
// does not return holds back only its own period's file. only: hand over that period alone, and only while it is the current one (a full period, a failed capture); those go
// ahead during a compacting prewarm, where the timer's flushes wait so that the recaptured bases make as few files as they can
static void arch_flush_from(ArchEpoch *only) {
if (!g_arch_cap || (!only && g_compact_enabled && atomic_load(&g_warm_running))) return;
os_unfair_lock_lock(&g_ep_lock); int any = (!only || g_ep == only) && (atomic_load(&g_ep->n) || atomic_load(&g_ep->active)); os_unfair_lock_unlock(&g_ep_lock);
if (!any) return; // nothing captured or under way: the period goes on
ArchEpoch *ne = ep_new();
if (!ne) { MLOG("[RED] pipeline archive: Metal made no compiler for a new flush period: the captures go on into the current one"); return; }
os_unfair_lock_lock(&g_ep_lock);
ArchEpoch *old = g_ep; any = atomic_load(&old->n) || atomic_load(&old->active); // again: another flush may just have handed it over
ArchEpoch *old = g_ep; any = (!only || old == only) && (atomic_load(&old->n) || atomic_load(&old->active)); // again: another flush may just have handed it over
if (any) {
g_ep = ne;
old->compacting = g_compact_enabled && atomic_load(&g_compacted) && !atomic_exchange(&g_compact_taken, 1); // this period holds the recaptured bases (see arch_compact_allowed)
// Every period from the first recaptured base on may hold some (see arch_compact_allowed); the first one handed over after the prewarm is the compaction's last
if (g_compact_enabled && atomic_load(&g_compacted) && !atomic_load(&g_compact_closed)) {
old->compacting = 1; atomic_fetch_add(&g_compact_periods, 1);
if (!atomic_load(&g_warm_running)) atomic_store(&g_compact_closed, 1);
}
}
os_unfair_lock_unlock(&g_ep_lock);
if (!any) return;
dispatch_group_enter(g_arch_pending);
dispatch_group_notify(old->busy, g_arch_q, ^{ @autoreleasepool { arch_write(old); } dispatch_group_leave(g_arch_pending); });
}
static void arch_flush(void) { arch_flush_from(nil); }
// A flush, then every period handed over is written (not on g_arch_q, which writes them)
static void arch_flush_wait(void) { arch_flush(); if (g_arch_pending) dispatch_group_wait(g_arch_pending, DISPATCH_TIME_FOREVER); }
static void arch_note_new(void) { // a base was compiled: flush 10 s later (one flush for a burst of them)
if (!g_arch_q || atomic_exchange(&g_arch_sched, 1)) return;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * (int64_t)NSEC_PER_SEC), g_arch_q, ^{ atomic_store(&g_arch_sched, 0); arch_flush(); });
}
static void arch_compact_finish(void) { // after the period that holds the recaptured bases is written (arch_write): the old files go once their bases are in the new one
static void arch_compact_finish(void) { // after every period that may hold recaptured bases is written (arch_write): the old files go once their bases are in the new ones
if (!g_compact_files || !g_compacted) return;
if (!g_arch_flush_ok) { MLOG("[RED] pipeline archive: compaction left the old files (the flush failed)"); return; }
if (g_compact_bad) { MLOG("[RED] pipeline archive: compaction left the old files (a flush failed, or a base was not captured again)"); return; }
for (NSString *f in g_compact_files) unlink(f.fileSystemRepresentation);
MLOG("pipeline archive compacted: %lu files of bases with a vertex layout gave %d bases to the file just written and were removed", (unsigned long)g_compact_files.count, (int)g_compacted);
MLOG("pipeline archive compacted: %lu files of bases with a vertex layout gave %d bases to the files just written and were removed", (unsigned long)g_compact_files.count, (int)g_compacted);
g_compact_files = nil;
}
static void pso_col4(MTL4RenderPipelineColorAttachmentDescriptor *a, MTLRenderPipelineColorAttachmentDescriptor *c) {
@@ -8059,13 +8105,14 @@ static id<MTLRenderPipelineState> pso_build_ex(MTLRenderPipelineDescriptor *d, N
if (base && from_run && g_compact_enabled && atomic_load(&g_warm_running)) {
// Metal can crash in materializeAirNTFromOnlineForSlice when serializing archive imports mixed with fresh bases (#342).
// Work around that framework bug by capturing the original shader functions, without lookupArchives. The normal compiler cache still applies.
id<MTLRenderPipelineState> cb = arch_capture(b, nil, vd);
if (cb) { base = cb; g_compacted++; }
int cap = 0; id<MTLRenderPipelineState> cb = arch_capturing() ? arch_capture(b, nil, vd, &cap) : nil;
if (cb) base = cb;
if (cap) g_compacted++; else g_compact_bad = 1; // not in the new files: the old ones stay
}
if (!base) {
if (g_arch4.count + g_arch4p.count) { g_pt_miss_n++; g_pt_miss_ns += t1 - t0; }
if (compile) {
NSError *be = nil; base = arch_capture(b, &be, vd); job->error = be; job->compiled = 1;
NSError *be = nil; base = arch_capture(b, &be, vd, NULL); job->error = be; job->compiled = 1;
g_pt_comp_ns += bp_now() - t1;
if (base) { g_pb_built++; if (g_arch_cap) arch_note_new(); }
}
@@ -8322,7 +8369,7 @@ static void pre_pair(NSString *vk, NSString *fk, int zero) {
if (!m) { g_pre_skipped++; return; }
for (id<MTL4Archive> a in g_arch4p) if ([a newRenderPipelineStateWithDescriptor:m error:nil]) { g_pre_archived++; return; }
for (id<MTL4Archive> a in g_arch4) if ([a newRenderPipelineStateWithDescriptor:m error:nil]) { g_pre_archived++; return; }
NSError *e = nil; id ps = arch_capture(m, &e, 0);
NSError *e = nil; id ps = arch_capture(m, &e, 0, NULL);
if (ps) g_pre_built++;
else {
if (g_pre_failed++ < 4) MLOG("[RED] pipeline prebuild: the base of %s + %s failed: %s", vk.UTF8String, fk.UTF8String, e.localizedDescription.UTF8String);
+47 -11
View File
@@ -1,10 +1,10 @@
// Metal 4 pipelines (pso_build): one base per pipeline with its colour state unspecialized, made into pipelines by specialization, kept in the pipeline archive.
// Checks: pipelines that differ only in colour state share one base; a specialized pipeline draws the same pixels as one built through the MTLDevice; a flushed archive
// file serves the base again without compiling; a flush of bases without a vertex layout is a p<seq> file, where a base with a layout is not looked up; a function with no
// Metal 4 descriptor keeps the MTLDevice path; pso_key_norm drops what no pipeline depends on; compaction merges the files the prewarm took bases from into one despite a
// mid-prewarm flush, and a compaction that did not finish is not tried again on the same system build; depth-only draws write depth; concurrent colour variants compile
// Metal 4 descriptor keeps the MTLDevice path; pso_key_norm drops what no pipeline depends on; compaction merges the files the prewarm took bases from into one per full period despite a
// mid-prewarm timer flush, removing them only after its last period, and a compaction that did not finish is not tried again on the same system build; depth-only draws write depth; concurrent colour variants compile
// one base; archive flushes preserve unrelated compiler state; a function with function constants is specialized by its pipeline's descriptor, not through its library,
// and an MTLDevice pipeline gets it specialized; the descriptor for a specialization is the caller's whether the driver returns it retained or autoreleased; a compute pipeline is captured into a plain file and taken from it later, one without a Metal 4 descriptor never looked up
// and an MTLDevice pipeline gets it specialized; the descriptor for a specialization is the caller's whether the driver returns it retained or autoreleased; a compute pipeline is captured into a plain file and taken from it later, one without a Metal 4 descriptor never looked up; a capture that fails builds the pipeline all the same and hands a full period over, or stops capturing after a failure in a period that captured nothing
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
@@ -269,6 +269,10 @@ static void depth_only(void) {
}
static void concurrent_bases(int fail) {
nvn_hm_clear(&g_pbase, hm_rel);
if (fail) { // the period has captured a pipeline: a capture that fails then means its store is full
MTLRenderPipelineDescriptor *pd = desc(MTLPixelFormatRGBA8Unorm, 0, MTLPixelFormatRGBA8Unorm, MTLColorWriteMaskAll, 1); pd.vertexDescriptor.layouts[16].stride = 2048;
NSError *err = nil; EXPECT("failed capture: a capture before", 1, pso_build(pd, &err) != nil && atomic_load(&g_ep->n) > 0);
}
ArchEpoch *ep = g_ep; ArchiveGateCompiler *gate = [ArchiveGateCompiler new]; gate->compiler = ep->comp; gate->fail = fail;
gate->entered = dispatch_semaphore_create(0); gate->release = dispatch_semaphore_create(0); ep->comp = (id<MTL4Compiler>)gate;
NSMutableArray<MTLRenderPipelineDescriptor *> *ds = [NSMutableArray array];
@@ -279,7 +283,7 @@ static void concurrent_bases(int fail) {
dispatch_group_t group = dispatch_group_create(); __block int good = 0; NSObject *lock = [NSObject new];
for (MTLRenderPipelineDescriptor *d in ds) dispatch_group_async(group, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
@autoreleasepool { NSError *err = nil; id ps = pso_build(d, &err);
@synchronized(lock) { good += fail ? !ps && [err.domain isEqualToString:@"test"] : ps != nil; }
@synchronized(lock) { good += ps != nil && !err; } // a capture that fails builds the pipeline by the plain compiler all the same
}
});
EXPECT("concurrent: first compiler entered", 0, dispatch_semaphore_wait(gate->entered, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)));
@@ -294,7 +298,31 @@ static void concurrent_bases(int fail) {
if (!fail) EXPECT("concurrent: one compile per base", 2, gate->calls);
EXPECT("concurrent: no unfinished builds", 0, g_pbase_pending.n);
ep->comp = gate->compiler;
if (fail) { NSError *err = nil; EXPECT("concurrent: failed base can retry", 1, pso_build(ds[0], &err) != nil); }
if (!fail) return;
// the full period was handed over once, and the run still captures, into a fresh period
EXPECT("failed capture: a new period", 1, g_ep != ep);
EXPECT("failed capture: handed over once", 1, ep->failed);
EXPECT("failed capture: still capturing", 1, arch_capturing());
NSError *err = nil; int n0 = atomic_load(&g_ep->n); nvn_hm_clear(&g_pbase, hm_rel);
EXPECT("failed capture: the base captured in the new period", 1, pso_build(ds[0], &err) != nil && atomic_load(&g_ep->n) == n0 + 1);
// a capture that fails in a period that has captured nothing: not the store's size, so the run captures no more, and builds the pipeline all the same
arch_flush_wait();
ArchEpoch *fresh = g_ep; ArchiveGateCompiler *fg = [ArchiveGateCompiler new]; fg->compiler = fresh->comp; fg->fail = 1; fg->calls = 1; fresh->comp = (id<MTL4Compiler>)fg;
nvn_hm_clear(&g_pbase, hm_rel); err = nil;
EXPECT("failed capture in a new period: built", 1, pso_build(ds[1], &err) != nil && !err);
EXPECT("failed capture in a new period: no more captures", 0, arch_capturing());
int calls = fg->calls; nvn_hm_clear(&g_pbase, hm_rel);
EXPECT("no more captures: built by the plain compiler", 1, pso_build(ds[2], &err) != nil && fg->calls == calls && g_ep == fresh);
// a pipeline both compilers refuse fails, with the plain compiler's error
atomic_store(&g_arch_cap_off, 0); id<MTL4Compiler> plain = g_comp4;
ArchiveGateCompiler *pg = [ArchiveGateCompiler new]; pg->compiler = plain; pg->fail = 1; pg->calls = 1; g_comp4 = (id<MTL4Compiler>)pg;
atomic_store(&fresh->n, 1); // as a period that holds a capture, so the failure is not taken for a broken capture
nvn_hm_clear(&g_pbase, hm_rel); err = nil;
EXPECT("both refuse: no pipeline, the error", 1, pso_build(ds[3], &err) == nil && [err.domain isEqualToString:@"test"]);
EXPECT("both refuse: not a failed capture", 0, fresh->failed);
atomic_store(&fresh->n, 0); g_comp4 = plain; fresh->comp = fg->compiler;
nvn_hm_clear(&g_pbase, hm_rel); err = nil;
EXPECT("concurrent: failed base can retry", 1, pso_build(ds[0], &err) != nil);
}
static void capture_preserves_foreign_folder(void) {
arch_flush_wait(); // Finish earlier captures: the captures below go into a new flush period
@@ -476,6 +504,7 @@ int main(int argc, char **argv) { @autoreleasepool {
for (NSString *n in names.reverseObjectEnumerator) { NSString *f = [@(cdir) stringByAppendingPathComponent:n]; [paths addObject:f]; [open addObject:[g_dev newArchiveWithURL:[NSURL fileURLWithPath:f] error:&err]]; }
nvn_hm_clear(&g_pbase, hm_rel); g_arch4 = open; // as a new start with that many files
g_compact_enabled = 1; g_compact_files = paths; g_compacted = 0;
g_arch_period_max = 4; // the recaptured bases fill two periods and part of a third: each full one is handed over, the timer's flushes wait
uint64_t arch0 = g_pb_archived, built0 = g_pb_built;
ArchEpoch *ep = g_ep; ArchiveGateCompiler *gate = [ArchiveGateCompiler new]; gate->compiler = ep->comp; gate->calls = 1; ep->comp = (id<MTL4Compiler>)gate;
atomic_store(&g_warm_running, 1);
@@ -483,8 +512,11 @@ int main(int argc, char **argv) { @autoreleasepool {
EXPECT("compaction: captures original shader functions, not archive imports", 0, gate->lookup_calls);
ep->comp = gate->compiler;
dispatch_sync(g_arch_q, ^{ arch_flush(); }); // the timer fires while prewarm still has other work
EXPECT("compaction: timed flush keeps recaptured bases pending", descs.count, g_arch_new);
EXPECT("compaction: timed flush adds no partial file", PSO_ARCH_COMPACT + 1, [NSFileManager.defaultManager contentsOfDirectoryAtPath:@(cdir) error:nil].count);
arch_flush_wait(); // the timer's flush waits for the prewarm; the full periods are written
EXPECT("compaction: timed flush keeps the last recaptured bases pending", descs.count % 4, g_arch_new);
EXPECT("compaction: a file per full period", PSO_ARCH_COMPACT + 1 + descs.count / 4, [NSFileManager.defaultManager contentsOfDirectoryAtPath:@(cdir) error:nil].count);
int kept = 0; for (NSString *f in paths) kept += [NSFileManager.defaultManager fileExistsAtPath:f];
EXPECT("compaction: the old files stay until its last period is written", paths.count, kept);
atomic_store(&g_warm_running, 0);
EXPECT("compaction: every base from the archive", arch0 + descs.count, g_pb_archived);
EXPECT("compaction: none compiled", built0, g_pb_built);
@@ -494,7 +526,9 @@ int main(int argc, char **argv) { @autoreleasepool {
EXPECT("compaction: the marker exists while the flush writes", 1, ms->calls == 1 && ms->marked == 1);
EXPECT("compaction: the flush that returned removed the marker", 0, [NSFileManager.defaultManager fileExistsAtPath:arch_compact_marker()]);
names = [NSFileManager.defaultManager contentsOfDirectoryAtPath:@(cdir) error:nil];
EXPECT("compaction: one file left", 1, names.count);
EXPECT("compaction: a file per period left", (descs.count + 3) / 4, names.count);
EXPECT("compaction: done", 0, g_compact_periods + !g_compact_closed + g_compact_bad);
g_arch_period_max = ARCH_PERIOD_MAX;
// a marker left by a compaction that did not finish: the next start on this system build does not compact, one from another build is removed and compaction tried
EXPECT("compaction: allowed without a marker", 1, arch_compact_allowed());
[arch_compact_stamp() writeToFile:arch_compact_marker() atomically:YES encoding:NSUTF8StringEncoding error:nil];
@@ -507,11 +541,13 @@ int main(int argc, char **argv) { @autoreleasepool {
EXPECT("compaction: old archive-import marker permits the new capture method", 1, arch_compact_allowed());
EXPECT("compaction: old capture marker removed", 0, [NSFileManager.defaultManager fileExistsAtPath:arch_compact_marker()]);
nvn_hm_clear(&g_pbase, hm_rel); g_compact_enabled = 0; g_compacted = 0;
g_arch4 = @[[g_dev newArchiveWithURL:[NSURL fileURLWithPath:[@(cdir) stringByAppendingPathComponent:names.firstObject]] error:&err]];
NSMutableArray<id<MTL4Archive>> *left = [NSMutableArray array];
for (NSString *n in names) [left addObject:[g_dev newArchiveWithURL:[NSURL fileURLWithPath:[@(cdir) stringByAppendingPathComponent:n]] error:&err]];
g_arch4 = left;
arch0 = g_pb_archived; built0 = g_pb_built;
for (MTLRenderPipelineDescriptor *cd in descs) pso_build(cd, &err);
EXPECT("compaction: the new file holds every base", arch0 + descs.count, g_pb_archived);
EXPECT("compaction: none compiled from the new file", built0, g_pb_built);
EXPECT("compaction: the new files hold every base", arch0 + descs.count, g_pb_archived);
EXPECT("compaction: none compiled from the new files", built0, g_pb_built);
[NSFileManager.defaultManager removeItemAtPath:@(cdir) error:nil]; g_arch_dir = saved; g_arch4 = @[];
}
compute_pipelines();
+6 -1
View File
@@ -85,7 +85,7 @@ int main(void) { @autoreleasepool {
MTL4RenderPipelineDescriptor *m = pre_desc(@"v1", @"f4", 0);
EXPECT("held: a descriptor for the draw", 1, m != nil);
dispatch_group_t draw = dispatch_group_create(); __block id drawn = nil;
dispatch_group_async(draw, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ @autoreleasepool { NSError *e = nil; drawn = arch_capture(m, &e, 0); } });
dispatch_group_async(draw, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ @autoreleasepool { NSError *e = nil; drawn = arch_capture(m, &e, 0, NULL); } });
EXPECT("held: a draw's compile returns", 0, dispatch_group_wait(draw, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC)));
EXPECT("held: a draw's compile built", 1, drawn != nil);
arch_flush();
@@ -123,9 +123,13 @@ int main(void) { @autoreleasepool {
g_arch_dir = arch2; g_arch4 = @[]; g_arch4p = @[];
put([tables stringByAppendingPathComponent:@"shader_pairs.tsv"], @"# pairs\nv1\tf5\nv1\tf6\n");
HoldCompiler *failc = [HoldCompiler new]; // armed in the current period before each run (one worker: both compiles in it; the run's last flush begins another)
// Apple's compiler fails it outside the archive too: a base the capture refuses is built by the plain compiler (arch_capture)
HoldCompiler *plainc = [HoldCompiler new]; id<MTL4Compiler> plain = g_comp4; plainc->compiler = plain; g_comp4 = (id<MTL4Compiler>)plainc;
arm(failc); reset_counts();
EXPECT("failing: two pairs", 2, pso_prebuild(1, 1, QOS_CLASS_USER_INITIATED));
EXPECT("failing: asked once", 1, failc->bad);
EXPECT("failing: the plain compiler asked too", 1, plainc->bad);
EXPECT("failing: still capturing", 1, arch_capturing());
EXPECT("failing: one failed", 1, g_pre_failed);
EXPECT("failing: one built", 1, g_pre_built);
EXPECT("failing: stamped all the same", 1, slurp(stamp) != nil);
@@ -153,6 +157,7 @@ int main(void) { @autoreleasepool {
EXPECT("other build: the list is for this build now", 1, [slurp(failp) containsString:arch_os_build()]);
// it builds after a system update (the real compiler, the list from another build): the list goes
if ((id)g_ep->comp == failc) g_ep->comp = failc->compiler;
g_comp4 = plain;
put(failp, [slurp(failp) stringByReplacingOccurrencesOfString:arch_os_build() withString:@"os\t1A1\n"]); reopen(arch2); reset_counts();
EXPECT("fixed: two pairs", 2, pso_prebuild(1, 1, QOS_CLASS_USER_INITIATED));
EXPECT("fixed: built", 1, g_pre_built);
+1
View File
@@ -722,6 +722,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- `FATAL deferred encoding: DmRecEnc has no stand-in for -drawMeshThreadgroupsWithIndirectBuffer:threadsPerObjectThreadgroup:threadsPerMeshThreadgroup:`, then `CRASH sig=6` under `mtk_encode`, with Metal encoding on its own thread (`DM_NVN_ENC_THREAD=1`, the default on iOS), at the first indirect task / mesh draw. → [Indirect task / mesh draws on the encode thread](../reference/rendering.md#indirect-task--mesh-draws-on-the-encode-thread)
- a scene opens near white and fades to its normal colours over several seconds, at each scene change, while the settled picture is right. → [Pending clears land before a compute dispatch](../reference/rendering.md#pending-clears-land-before-a-compute-dispatch)
- a regular lattice of dots over the ground, and the light wrong: three of four layers of an interleaved ambient occlusion array stay empty, while the draws and their bindings look right. → [`[[primitive_id]]` in a specialized Metal 4 pipeline](../reference/rendering.md#primitive_id-in-a-specialized-metal-4-pipeline)
- hundreds of `[RED] background render pipeline creation failed: error: cannot commit transaction no. '50463' on '…/com.apple.gpuarchiver/gpuarchiver-…/PersistentState': MDB_MAP_FULL: Environment mapsize limit reached` (or `cannot write 'UNITSMAPPINGS' database: MDB_MAP_FULL`), then `pipeline archive: compaction left the old files (the flush failed)`; the draws of those pipelines are missing and the frame rate falls (Ocarina of Time's Kakariko Village at 30-70 ms a frame, 1,502 such lines in one session). → [Metal's archiver store filled by one flush period](../reference/rendering.md#metals-archiver-store-filled-by-one-flush-period)
- with Metal 4 pipelines on (`DM_PSO_MTL4=1`), the iOS app crashes before its first frame, right after `pipeline prewarm list … lines`: `CRASH sig=11 pc=objc_release+0x10`, `bt: objc_autoreleasePoolPop warm_task __warm_prepare_block_invoke`, on several prepare workers at once. The Mac runs the same pipelines. → [A specialization descriptor iOS 26.0 returns autoreleased](../reference/rendering.md#a-specialization-descriptor-ios-260-returns-autoreleased)
- a Switch 2 game calls `nvnCommandBufferEvaluateDlss` and its builder functions, which the host did not have. → [NVN2's DLSS on MetalFX](../reference/rendering.md#nvn2s-dlss-on-metalfx)
- `[RED] NVN unimplemented function called: nvnDlssNetworkResize (x0=… x1=0x300 x2=0x1b0)` at the title. → [The DLSS network resized](../reference/rendering.md#the-dlss-network-resized)
+9
View File
@@ -1081,6 +1081,15 @@ The replay on Metal (`dm/gfx/nvn/nvn_mtl.m`) and the Vulkan and OpenGL layers. E
- **Check:** `t_image_primitive_id` draws four full-screen triangles that store into the layer of their primitive ID through the host's draw path (an attachment-less pass, a metallib loaded as game shaders are). Each of the four layers holds its own primitive's value; without the flag, layers 1 to 3 stay empty (macOS 27.0.1, M3 Pro). `test_pso_offline.py` checks that such a pair is left out.
- **Found on:** [Fire Emblem Fortune's Weave](../../dm/games/04007EF01F8AE000/README.md): `b6726be4afc44691`.
### Metal's archiver store filled by one flush period
- **Symptom:** hundreds of `[RED] background render pipeline creation failed: error: cannot commit transaction no. '50463' on '…/com.apple.gpuarchiver/gpuarchiver-…/PersistentState': MDB_MAP_FULL: Environment mapsize limit reached` (or `cannot write 'UNITSMAPPINGS' database: MDB_MAP_FULL`), then `pipeline archive: compaction left the old files (the flush failed)`; the draws of those pipelines are missing and the frame rate falls (Ocarina of Time's Kakariko Village at 30-70 ms a frame, 1,502 such lines in one session).
- **Cause:** a pipeline the run captures for its archive is compiled through the flush period's Metal 4 compiler, bound to that period's pipeline data set serializer (`ep->comp`, `arch_capture`). Metal keeps each serializer's state in an LMDB environment of its own, a `gpuarchiver-*` folder under `com.apple.gpuarchiver` in the user cache folder, with a fixed map size of 10 MB (the `PersistentState` meta page). Once it is full every compile through that compiler fails, not only the capture, and the host took the error as the pipeline's: the pipeline was never built, and the period's file was not written either. A period had no size limit while a compacting prewarm ran: the timer's flushes waited for the prewarm's end so that the recaptured bases would make one file, and a prewarm of 40,000 rows put 8,693 bases into one period. Periods of 3,508 bases were written whole.
- **Fix:** a period is handed over at its 2,000th capture (`ARCH_PERIOD_MAX`, `arch_flush_from`), during a compacting prewarm too, so each gets a fresh environment; a compaction now writes a file per period and removes the old files once every period that may hold recaptured bases is written, and keeps them when one was not written or a base was not captured again. A pipeline the capture refuses is built by the plain compiler (`g_comp4`), since the archive is a cache, never a condition of drawing; the failing period is handed over once, and a failure in a period that has captured nothing (so not a full store) stops capturing for the run, said in red. A pipeline both compilers refuse returns the plain compiler's error, and costs a second compile.
- **Check:** `t_pso_archive`: concurrent bases with a failing capture compiler all get a pipeline and the period is handed over once; a failure in a new period stops the captures; both compilers refusing returns the error; a compaction with a period of 4 writes a file per period and keeps the old files until its last period is written. `t_pso_stall`: a base Apple's compiler cannot build fails on both compilers and leaves capturing on. In the log, `pipeline archive: capturing a render pipeline failed after N in its flush period`.
- **See also:** [Metal's build folders left by pipeline archive flushes](shaders.md#metals-build-folders-left-by-pipeline-archive-flushes): the folders stay on the Mac; they take disk space but do not fill later runs' stores, each period making a new one.
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md) on an M3 Pro.
### A specialization descriptor iOS 26.0 returns autoreleased
- **Symptom:** with Metal 4 pipelines on (`DM_PSO_MTL4=1`), the iOS app crashes before its first frame, right after `pipeline prewarm list … lines`: `CRASH sig=11 pc=objc_release+0x10`, `bt: objc_autoreleasePoolPop warm_task __warm_prepare_block_invoke`, on several prepare workers at once. The Mac runs the same pipelines.