From aaa1f78937f181b39417e2fa242448f5ab94bbb7 Mon Sep 17 00:00:00 2001 From: bettterlabs <279109819+bettterlabs@users.noreply.github.com> Date: Sun, 8 Nov 2026 15:30:43 -0800 Subject: [PATCH 1/2] A cold start's prewarm writes the pipeline archive a file per full period, not a file per 10 s timer flush, and the prepare line counts the bases a compaction captures again: on Ocarina of Time a cold start left 80 run files, so the next start compacted them all, 762 s before the first frame with 0 compiled in the log; now the cold start leaves 5 files and the next start takes 3.3 s (GitHub issue #1747) The timer's flush (10 s after a burst of new bases) ran during a prewarm that does not compact, so a cold start wrote a file every 10 s (80 files here; #1747's left 43). More than PSO_ARCH_COMPACT run files make the next start a compaction, whose prewarm captures every base it takes from them again from the original functions (the #342 workaround), a full compile each, and a capture counted neither as compiled nor apart from the lookups. Now arch_flush_from holds the timer's flushes for any prewarm, as it did for a compacting one, so a prewarm writes a file per ARCH_PERIOD_MAX; full periods and failed captures are still handed over at once. The prepare line says how many bases were captured again, the bases line their time. A cold start that ends in its prewarm now leaves about a period of captures unwritten, built again at the next start, where it left up to 10 s of them. t_pso_archive (135 -> 145 checks): nine new bases in a prewarm with a timer flush after each make 3 files with a period of 4; a compaction counts its recaptures and their time. test_pso_archive.py, fresh processes: that cold start then a next start that compacts and builds nothing; a cold start ended after 6 bases, then a next start that takes the 4 written and builds the other 5. On bd979ced with eed7c429 (this Mac's library chain), copies of the device archive's prebuilt files with a 30,838-line list: before, a cold start wrote 80 files and the next took 761.61 s; with the change 5 files and 3.30 s. Reference entry, game note, development.md, symptom index. --- dm/games/0400486024DEC000/README.md | 1 + dm/gfx/nvn/nvn_mtl.m | 17 +++++---- dm/gfx/tests/t_pso_archive.m | 53 +++++++++++++++++++++++++++-- dm/gfx/tests/test_pso_archive.py | 24 +++++++++++++ docs/agents/symptoms.md | 1 + docs/development.md | 2 +- docs/reference/rendering.md | 9 +++++ 7 files changed, 96 insertions(+), 11 deletions(-) diff --git a/dm/games/0400486024DEC000/README.md b/dm/games/0400486024DEC000/README.md index 44c0e40660..55c8117244 100644 --- a/dm/games/0400486024DEC000/README.md +++ b/dm/games/0400486024DEC000/README.md @@ -157,6 +157,7 @@ From an empty save: at about 45 s `A` (title), `A` (New Game), then the movie. F - [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). +- [A cold start leaves a file per timer flush, and the next start compacts them all](../../../docs/reference/rendering.md#a-cold-start-leaves-a-file-per-timer-flush-and-the-next-start-compacts-them-all): a cold start wrote 80 run files and the next start captured 8,859 pipelines again, 762 s before the first frame on an M4 with 16 GB; with the change 5 files, and 3.3 s (issue #1747). - [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) diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index 7af870c549..ad6fc75749 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -7696,6 +7696,7 @@ static int pso4_on(void) { // 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 _Atomic int g_compact_bases; static _Atomic uint64_t g_compact_ns; // render bases captured again and their time (the prepare line) static NSArray *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) @@ -8041,9 +8042,10 @@ static void arch_write_file(ArchEpoch *ep) { } // 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. 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 +// ahead during the prewarm, where the timer's flushes wait so that its bases, compiled or captured again, make as few files as they can: a cold start's timer flushes wrote a +// file each 10 s (Ocarina of Time: 67 files; GitHub issue #1747's, 43), more than PSO_ARCH_COMPACT, and the next start compacted them all static void arch_flush_from(ArchEpoch *only) { - if (!g_arch_cap || (!only && g_compact_enabled && atomic_load(&g_warm_running))) return; + if (!g_arch_cap || (!only && 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(); @@ -8193,8 +8195,9 @@ static void pbase_key_of(MTLRenderPipelineDescriptor *d, pbase_key *k) { // 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. int cap = 0; id cb = arch_capturing() ? arch_capture(b, nil, vd, &cap) : nil; + g_compact_ns += bp_now() - t1; if (cb) base = cb; - if (cap) g_compacted++; else g_compact_bad = 1; // not in the new files: the old ones stay + if (cap) { g_compacted++; g_compact_bases++; } 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; } @@ -8833,8 +8836,8 @@ static void warm_task(WarmTask *t) { static void warm_finish(void) { MLOG("pipeline prewarm done: shaders %llu / render pipelines %llu (specialized fragment skipped %llu) / compute pipelines %llu, background time %.1f ms; shader keys not in the shader map (another game version) %llu", (unsigned long long)g_warm_shaders, (unsigned long long)g_warm_rps, (unsigned long long)g_warm_skip_fz, (unsigned long long)g_warm_cps, (bp_now() - g_warm_t0) / 1e6, (unsigned long long)g_warm_skip_stale); - if (g_comp4) MLOG("pipeline bases so far: %llu compiled, %llu from the archive, %llu reused (%.1f ms for the bases); %llu specializations (their descriptors %s), %llu pipelines without a base (MTLDevice)", - (unsigned long long)g_pb_built, (unsigned long long)g_pb_archived, (unsigned long long)g_pb_reused, g_pb_base_ns / 1e6, (unsigned long long)g_pb_spec, + if (g_comp4) MLOG("pipeline bases so far: %llu compiled, %llu from the archive (%d of them captured again for the compaction, %.1f ms), %llu reused (%.1f ms for the bases); %llu specializations (their descriptors %s), %llu pipelines without a base (MTLDevice)", + (unsigned long long)g_pb_built, (unsigned long long)g_pb_archived, (int)g_compact_bases, g_compact_ns / 1e6, (unsigned long long)g_pb_reused, g_pb_base_ns / 1e6, (unsigned long long)g_pb_spec, (const char *[]){"not asked for yet", "returned retained", "returned autoreleased"}[atomic_load(&g_spec_own) % 3], (unsigned long long)g_pb_legacy); if (g_arch_bundle || g_arch_cap) MLOG("compute pipelines so far: %llu from the archive bundled with the app, %llu from this device's archive, %llu built (%.1f ms looking up, %.1f ms building)", (unsigned long long)g_cps_arch, (unsigned long long)g_cps_run, (unsigned long long)g_cps_built, g_cps_look_ns / 1e6, g_cps_build_ns / 1e6); @@ -8891,9 +8894,9 @@ static void warm_prepare(NSArray *tasks, long lines) { } if (shown) front_progress(NULL, lines, lines); MLOG("pipeline prepare: %ld lines (%llu shaders, %llu render pipelines, %llu compute pipelines) in %.2f s on %d workers before the first frame, progress screen %s; " - "bases %llu compiled, %llu from the archive, %llu reused; %llu specializations", + "bases %llu compiled, %llu from the archive (%d of them captured again for the compaction), %llu reused; %llu specializations", lines, (unsigned long long)g_warm_shaders, (unsigned long long)g_warm_rps, (unsigned long long)g_warm_cps, (bp_now() - t0) / 1e9, workers, shown ? "shown" : "not shown", - (unsigned long long)(g_pb_built - built0), (unsigned long long)(g_pb_archived - arch0), (unsigned long long)(g_pb_reused - reused0), (unsigned long long)(g_pb_spec - spec0)); + (unsigned long long)(g_pb_built - built0), (unsigned long long)(g_pb_archived - arch0), (int)g_compact_bases, (unsigned long long)(g_pb_reused - reused0), (unsigned long long)(g_pb_spec - spec0)); } // The prebuild in the prepare step: the bases of every shader pair are made before the game's first frame, behind the progress screen ("Preparing pipelines"), once per chain // version, depth mode and pair list (prebuilt.tsv), so a running game never compiles them meanwhile. Built in the background while playing, they took an iPhone 17 Pro Max's GPU diff --git a/dm/gfx/tests/t_pso_archive.m b/dm/gfx/tests/t_pso_archive.m index 6bdbc1de16..8fa8d22b67 100644 --- a/dm/gfx/tests/t_pso_archive.m +++ b/dm/gfx/tests/t_pso_archive.m @@ -2,7 +2,7 @@ // 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 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 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 +// mid-prewarm timer flush, removing them only after its last period, counting them for the prepare line, and a compaction that did not finish is not tried again on the same system build; a timer flush waits for any prewarm, so a cold start writes a file per full period; 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; 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 @@ -399,7 +399,7 @@ int main(int argc, char **argv) { @autoreleasepool { if (getenv("DM_TEST_ARCHIVE_CONSTANTS")) src = [src stringByReplacingOccurrencesOfString:@"fragment O fs() { return" withString:@"constant bool enabled [[function_constant(0)]]; fragment O fs() { if (is_function_constant_defined(enabled) && enabled) discard_fragment(); return"]; if (argc == 3) { NSString *metal = [@(argv[2]) stringByAppendingPathComponent:@"fixture.metal"], *library = [metal stringByAppendingString:@"lib"]; - if (!strcmp(argv[1], "--compact-seed")) { + if (strstr(argv[1], "-seed")) { // a mode that writes the archive builds the shader library [src writeToFile:metal atomically:YES encoding:NSUTF8StringEncoding error:nil]; NSTask *task = [NSTask new]; task.executableURL = [NSURL fileURLWithPath:@"/usr/bin/xcrun"]; task.arguments = @[@"-sdk", @"macosx", @"metal", metal, @"-o", library]; @@ -410,6 +410,31 @@ int main(int argc, char **argv) { @autoreleasepool { } else g_lib = [g_dev newLibraryWithSource:src options:nil error:&err]; if (!g_lib) { fprintf(stderr, "%s\n", err.localizedDescription.UTF8String); return 1; } g_lib2 = [g_dev newLibraryWithSource:[src stringByAppendingString:@"// another library: the same source would come back as the same library\n"] options:nil error:&err]; + if (argc == 3 && !strncmp(argv[1], "--cold-", 7)) { // across fresh processes: a cold start's prewarm with a timer flush after each new base, then the next start + g_arch_period_max = 4; int seed = !strcmp(argv[1], "--cold-seed"), cut = !strcmp(argv[1], "--cold-cut-seed"), after_cut = !strcmp(argv[1], "--cold-after-cut"); + pso4_init(); + EXPECT("cold restart: no compaction", 0, g_compact_enabled); + uint64_t arch0 = g_pb_archived, built0 = g_pb_built; + atomic_store(&g_warm_running, 1); + for (int i = 0; i <= PSO_ARCH_COMPACT; i++) { + MTLRenderPipelineDescriptor *cd = desc(MTLPixelFormatRGBA8Unorm, 0, MTLPixelFormatRGBA8Unorm, MTLColorWriteMaskAll, 1); + cd.vertexDescriptor.layouts[16].stride = 16 * (i + 70); + EXPECT("cold restart: pipeline", 1, pso_build(cd, &err) != nil); + if (seed || cut) dispatch_sync(g_arch_q, ^{ arch_flush(); }); // the timer's + if (cut && i == 5) { // the cold start ends here, in its prewarm: the full period is written, the 2 captures after it are not + dispatch_group_wait(g_arch_pending, DISPATCH_TIME_FOREVER); + printf("t_pso_archive %s: %d checks, %d failed\n", argv[1], checks, failed); + _exit(failed != 0); + } + } + atomic_store(&g_warm_running, 0); arch_flush_wait(); + int expect_archived = seed ? 0 : after_cut ? 4 : PSO_ARCH_COMPACT + 1; + EXPECT("cold restart: compiled in the cold start, from the archive in the next", expect_archived, (int)(g_pb_archived - arch0)); + EXPECT("cold restart: compiled where not in the archive", PSO_ARCH_COMPACT + 1 - expect_archived, (int)(g_pb_built - built0)); + [NSFileManager.defaultManager removeItemAtPath:@(dir) error:nil]; + printf("t_pso_archive %s: %d checks, %d failed\n", argv[1], checks, failed); + return failed != 0; + } // A fresh process is essential: a compiler that built the source archives still has their online binaries. if (argc == 3) { int seed = !strcmp(argv[1], "--compact-seed"); @@ -503,7 +528,7 @@ int main(int argc, char **argv) { @autoreleasepool { NSMutableArray> *open = [NSMutableArray array]; NSMutableArray *paths = [NSMutableArray array]; 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_compact_enabled = 1; g_compact_files = paths; g_compacted = 0; g_compact_bases = 0; g_compact_ns = 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)gate; @@ -521,6 +546,8 @@ int main(int argc, char **argv) { @autoreleasepool { EXPECT("compaction: every base from the archive", arch0 + descs.count, g_pb_archived); EXPECT("compaction: none compiled", built0, g_pb_built); EXPECT("compaction: every base captured again", descs.count, g_compacted); + EXPECT("compaction: the prepare line counts them", descs.count, g_compact_bases); + EXPECT("compaction: and their time", 1, g_compact_ns > 0); MarkerSerializer *ms = [MarkerSerializer new]; ms->ser = g_ep->ser; g_ep->ser = (id)ms; // the period being written arch_flush_wait(); EXPECT("compaction: the marker exists while the flush writes", 1, ms->calls == 1 && ms->marked == 1); @@ -551,6 +578,26 @@ int main(int argc, char **argv) { @autoreleasepool { [NSFileManager.defaultManager removeItemAtPath:@(cdir) error:nil]; g_arch_dir = saved; g_arch4 = @[]; } compute_pipelines(); + // a timer's flush waits for the prewarm's end, compacting or not, and so a cold start writes a file per full period, not one per 10 s: here 3 files for 9 new bases, + // where a file per timer flush made 9, more than PSO_ARCH_COMPACT, and the next start compacted them all + { + char cdir[] = "/tmp/t_pso_cold.XXXXXX"; if (!mkdtemp(cdir)) abort(); + NSString *saved = g_arch_dir; g_arch_dir = @(cdir); nvn_hm_clear(&g_pbase, hm_rel); g_arch4 = @[]; g_arch4p = @[]; + g_arch_period_max = 4; atomic_store(&g_warm_running, 1); + for (int i = 0; i <= PSO_ARCH_COMPACT; i++) { + MTLRenderPipelineDescriptor *cd = desc(MTLPixelFormatRGBA8Unorm, 0, MTLPixelFormatRGBA8Unorm, MTLColorWriteMaskAll, 1); + cd.vertexDescriptor.layouts[16].stride = 16 * (i + 70); + if (!pso_build(cd, &err)) { fprintf(stderr, "cold: no pipeline %d\n", i); failed++; } + ArchEpoch *ep = g_ep; + dispatch_sync(g_arch_q, ^{ arch_flush(); }); // the timer's + if (i % 4 != 3) EXPECT("cold: the timer's flush waits for the prewarm's end", 1, g_ep == ep); + } + atomic_store(&g_warm_running, 0); arch_flush_wait(); + NSUInteger files = [NSFileManager.defaultManager contentsOfDirectoryAtPath:@(cdir) error:nil].count; + EXPECT("cold: a file per full period and one for the rest", (PSO_ARCH_COMPACT + 4) / 4, files); + nvn_hm_clear(&g_pbase, hm_rel); g_arch_period_max = ARCH_PERIOD_MAX; + [NSFileManager.defaultManager removeItemAtPath:@(cdir) error:nil]; g_arch_dir = saved; g_arch4 = @[]; + } // a function with no Metal 4 descriptor: the MTLDevice path uint64_t legacy = g_pb_legacy; id l = pso_build(desc(MTLPixelFormatRGBA8Unorm, 0, MTLPixelFormatRGBA8Unorm, MTLColorWriteMaskAll, 0), &err); diff --git a/dm/gfx/tests/test_pso_archive.py b/dm/gfx/tests/test_pso_archive.py index 2d13fc84b6..3b47537ccd 100644 --- a/dm/gfx/tests/test_pso_archive.py +++ b/dm/gfx/tests/test_pso_archive.py @@ -9,6 +9,30 @@ @unittest.skipUnless(__name__ == '__main__', 'run test_pso_archive.py with the native t_pso_archive path') class ArchiveRestartTests(unittest.TestCase): + def test_cold_start_then_next(self): + with tempfile.TemporaryDirectory(prefix='pso-cold-') as folder: + env = dict(os.environ, DM_PSO_MTL4='1', MTL_DEBUG_LAYER='1') + for name in ('DM_GPU_CAPTURE', 'MTL_CAPTURE_ENABLED', 'DM_TEST_ARCHIVE_CONSTANTS', 'DM_TEST_ARCHIVE_MIXED'): + env.pop(name, None) + # nine new bases with a timer flush after each: a file per full period of 4 and one for the rest, which the next start does not compact + for phase, files in (('seed', 3), ('next', 3)): + result = subprocess.run([executable, '--cold-' + phase, folder], + env=env, capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, phase + '\n' + result.stdout + result.stderr) + self.assertEqual(len(list(Path(folder).glob('*.mtl4a'))), files, phase) + + def test_cold_start_cut_short(self): + with tempfile.TemporaryDirectory(prefix='pso-cold-cut-') as folder: + env = dict(os.environ, DM_PSO_MTL4='1', MTL_DEBUG_LAYER='1') + for name in ('DM_GPU_CAPTURE', 'MTL_CAPTURE_ENABLED', 'DM_TEST_ARCHIVE_CONSTANTS', 'DM_TEST_ARCHIVE_MIXED'): + env.pop(name, None) + # ended in its prewarm after 6 new bases: the full period's file alone; the next start takes those 4 and builds the other 5 + for phase, files in (('cut-seed', 1), ('after-cut', 3)): + result = subprocess.run([executable, '--cold-' + phase, folder], + env=env, capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, phase + '\n' + result.stdout + result.stderr) + self.assertEqual(len(list(Path(folder).glob('*.mtl4a'))), files, phase) + def test_compaction_with_fresh_bases_and_restart(self): for constants in (False, True): with self.subTest(constants=constants), tempfile.TemporaryDirectory(prefix='pso-restart-') as folder: diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index 0537795511..1819d78389 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -732,6 +732,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - 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) +- the start after a cold start spends minutes in the prepare step ("Preparing shaders"), with MTLCompilerService at 700-980% CPU, yet the log says no base was compiled: `pipeline prepare: 30838 lines (…) in 761.61 s on 10 workers before the first frame, progress screen shown; bases 0 compiled, 8608 from the archive, 637 reused`, then `pipeline archive compacted: 80 files of bases with a vertex layout gave 8859 bases to the files just written and were removed` (issue #1747: a cold start of 457 s, then a warm one of 309 s with 0 compiled). → [A cold start leaves a file per timer flush, and the next start compacts them all](../reference/rendering.md#a-cold-start-leaves-a-file-per-timer-flush-and-the-next-start-compacts-them-all) - 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) diff --git a/docs/development.md b/docs/development.md index 9a5f169b19..c9af78c6c3 100644 --- a/docs/development.md +++ b/docs/development.md @@ -761,7 +761,7 @@ Every start adds a file or more: Breath of the Wild wrote 5–7 per start, and e The log shows `pipeline archive …: N files, … MB, opened in … ms` at start, `pipeline archive: N new pipeline bases written to …` after each flush (`… and M compute pipelines …` when it holds compute pipelines), and after the prewarm a line counting the bases compiled, taken from the archive and reused. `DM_PSO_ARCHIVE=off` turns the archive off; `DM_PSO_ARCHIVE=` puts it elsewhere. `DM_PSO_MTL4=0` builds every pipeline through the `MTLDevice` as before, with no bases and no archive. The Metal 4 path, with the hybrid pipelines and the prebuild, is on by default on the Mac. On iOS it is on for a game whose profile sets `pso_mtl4 on` (Breath of the Wild, tested on an iPhone 17 Pro Max) or with `DM_PSO_MTL4=1`, and off otherwise: the archive's memory is not measured against an iPhone's limit yet. For such a game the standard on iOS is the prebuild's bases made on the Mac and shipped in the app ([The pipeline archive made offline](#the-pipeline-archive-made-offline)); the device builds them itself only as a fallback. Pipelines whose functions have no Metal 4 descriptor (the diagnostic `DM_NVN_HILITE` and `DM_NVN_MAGSCAN` overrides) always take the `MTLDevice` path. -During compaction, timed flushes defer while prewarm runs. Once it finishes, one archive-queue task flushes the recaptured bases and removes the old files. The pending count and serializer capture are protected by the same compile/flush lock, so a flush consumes the count for the bases it writes. +Timed flushes defer while the prewarm runs, compacting or not, so a cold start writes a file per 2,000 bases, not one per 10 s ([A cold start leaves a file per timer flush](reference/rendering.md#a-cold-start-leaves-a-file-per-timer-flush-and-the-next-start-compacts-them-all)); a period that reaches 2,000 captures is handed over all the same. Once the prewarm finishes, the first flush hands over its last period, and a compaction's old files are removed once every period that may hold recaptured bases is written. The prepare line says how many bases a compaction captured again. ### Hybrid pipelines diff --git a/docs/reference/rendering.md b/docs/reference/rendering.md index baff592694..83fb3c97ab 100644 --- a/docs/reference/rendering.md +++ b/docs/reference/rendering.md @@ -1098,6 +1098,15 @@ The replay on Metal (`dm/gfx/nvn/nvn_mtl.m`) and the Vulkan and OpenGL layers. E - **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 cold start leaves a file per timer flush, and the next start compacts them all + +- **Symptom:** the start after a cold start spends minutes in the prepare step ("Preparing shaders"), with MTLCompilerService at 700-980% CPU, yet the log says no base was compiled: `pipeline prepare: 30838 lines (…) in 761.61 s on 10 workers before the first frame, progress screen shown; bases 0 compiled, 8608 from the archive, 637 reused`, then `pipeline archive compacted: 80 files of bases with a vertex layout gave 8859 bases to the files just written and were removed` ([issue #1747](https://github.com/seedds/nxnative/issues/1747): a cold start of 457 s, then a warm one of 309 s with 0 compiled). +- **Cause:** the timer's flush (10 s after a burst of new bases) ran during a prewarm that does not compact, so a cold start wrote a file every 10 s: 80 files on Ocarina of Time here, 43 in #1747. More than `PSO_ARCH_COMPACT` run files make the next start a compaction, and its prewarm captures every base it takes from them again from the original shader functions ([the #342 workaround](shaders.md#a-compaction-flush-that-crashes-then-crashes-every-start)), a full compile each. A capture counted neither as compiled nor apart from the lookups, so the prepare line read 0 compiled. +- **Fix:** the timer's flushes wait for the prewarm's end whether it compacts or not (`arch_flush_from`), as they already did during a compacting one, so a prewarm writes a file per `ARCH_PERIOD_MAX` bases. The prepare line says how many bases were captured again, `pipeline bases so far` also their time. A cold start that ends before its prewarm does now leaves about a period's captures unwritten (up to `ARCH_PERIOD_MAX`, plus compute pipelines still queued), to be built again at the next start, where it left up to 10 s of them. A cold start of more than `PSO_ARCH_COMPACT` x `ARCH_PERIOD_MAX` (16,000) bases still writes more than `PSO_ARCH_COMPACT` files, and the next start compacts them (from the code, not seen). +- **Check:** `t_pso_archive`: nine new bases in a prewarm with a timer flush after each make one file per full period of 4 and one for the rest, 3 files, no more than `PSO_ARCH_COMPACT`; a compaction counts its recaptured bases and their time. `test_pso_archive.py`, in fresh processes: that cold start, then a next start that compacts nothing and builds nothing; and a cold start ended in its prewarm after 6 bases, which leaves the full period's file alone, so the next start takes those 4 and builds the other 5. In the game (Ocarina of Time on an M4 with 16 GB, macOS 27.2, main bd979ced with eed7c429, copies of the device archive's prebuilt files with a 30,838-line list, stopped at the title): before, the cold start took 861.94 s writing 80 run files and the next start captured 8,859 pipelines again, 761.61 s before the first frame; with the change the cold start took 716.20 s writing 5 files (4 full periods and the rest) and the next start 3.30 s, with no compaction (one run each, nothing else running; an earlier pair with a build overlapping both cold starts: 854 and 725 s, then 736 and 3.67 s). +- **See also:** [Metal's archiver store filled by one flush period](#metals-archiver-store-filled-by-one-flush-period). +- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md) on an M4 (16 GB, macOS 27.2 26B123); #1747 on an M4 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. From 23b03671ebfdc7894d1c29b0ebe23d57165d0a64 Mon Sep 17 00:00:00 2001 From: bettterlabs <279109819+bettterlabs@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:00:49 -0800 Subject: [PATCH 2/2] The prepare line and the bases line name the bases captured again only on a compacting start: a start that does not compact no longer prints "0 of them captured again for the compaction" --- dm/gfx/nvn/nvn_mtl.m | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index ad6fc75749..0372e7bd4c 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -8836,8 +8836,10 @@ static void warm_task(WarmTask *t) { static void warm_finish(void) { MLOG("pipeline prewarm done: shaders %llu / render pipelines %llu (specialized fragment skipped %llu) / compute pipelines %llu, background time %.1f ms; shader keys not in the shader map (another game version) %llu", (unsigned long long)g_warm_shaders, (unsigned long long)g_warm_rps, (unsigned long long)g_warm_skip_fz, (unsigned long long)g_warm_cps, (bp_now() - g_warm_t0) / 1e6, (unsigned long long)g_warm_skip_stale); - if (g_comp4) MLOG("pipeline bases so far: %llu compiled, %llu from the archive (%d of them captured again for the compaction, %.1f ms), %llu reused (%.1f ms for the bases); %llu specializations (their descriptors %s), %llu pipelines without a base (MTLDevice)", - (unsigned long long)g_pb_built, (unsigned long long)g_pb_archived, (int)g_compact_bases, g_compact_ns / 1e6, (unsigned long long)g_pb_reused, g_pb_base_ns / 1e6, (unsigned long long)g_pb_spec, + char again[96] = ""; // only a compacting start captures bases again + if (g_compact_enabled) snprintf(again, sizeof again, " (%d of them captured again for the compaction, %.1f ms)", (int)g_compact_bases, g_compact_ns / 1e6); + if (g_comp4) MLOG("pipeline bases so far: %llu compiled, %llu from the archive%s, %llu reused (%.1f ms for the bases); %llu specializations (their descriptors %s), %llu pipelines without a base (MTLDevice)", + (unsigned long long)g_pb_built, (unsigned long long)g_pb_archived, again, (unsigned long long)g_pb_reused, g_pb_base_ns / 1e6, (unsigned long long)g_pb_spec, (const char *[]){"not asked for yet", "returned retained", "returned autoreleased"}[atomic_load(&g_spec_own) % 3], (unsigned long long)g_pb_legacy); if (g_arch_bundle || g_arch_cap) MLOG("compute pipelines so far: %llu from the archive bundled with the app, %llu from this device's archive, %llu built (%.1f ms looking up, %.1f ms building)", (unsigned long long)g_cps_arch, (unsigned long long)g_cps_run, (unsigned long long)g_cps_built, g_cps_look_ns / 1e6, g_cps_build_ns / 1e6); @@ -8893,10 +8895,12 @@ static void warm_prepare(NSArray *tasks, long lines) { if (shown) front_progress("Preparing shaders", g_warm_done, lines); } if (shown) front_progress(NULL, lines, lines); + char again[64] = ""; // only a compacting start captures bases again + if (g_compact_enabled) snprintf(again, sizeof again, " (%d of them captured again for the compaction)", (int)g_compact_bases); MLOG("pipeline prepare: %ld lines (%llu shaders, %llu render pipelines, %llu compute pipelines) in %.2f s on %d workers before the first frame, progress screen %s; " - "bases %llu compiled, %llu from the archive (%d of them captured again for the compaction), %llu reused; %llu specializations", + "bases %llu compiled, %llu from the archive%s, %llu reused; %llu specializations", lines, (unsigned long long)g_warm_shaders, (unsigned long long)g_warm_rps, (unsigned long long)g_warm_cps, (bp_now() - t0) / 1e9, workers, shown ? "shown" : "not shown", - (unsigned long long)(g_pb_built - built0), (unsigned long long)(g_pb_archived - arch0), (int)g_compact_bases, (unsigned long long)(g_pb_reused - reused0), (unsigned long long)(g_pb_spec - spec0)); + (unsigned long long)(g_pb_built - built0), (unsigned long long)(g_pb_archived - arch0), again, (unsigned long long)(g_pb_reused - reused0), (unsigned long long)(g_pb_spec - spec0)); } // The prebuild in the prepare step: the bases of every shader pair are made before the game's first frame, behind the progress screen ("Preparing pipelines"), once per chain // version, depth mode and pair list (prebuilt.tsv), so a running game never compiles them meanwhile. Built in the background while playing, they took an iPhone 17 Pro Max's GPU