diff --git a/README.md b/README.md
index 1bce720..2dbaab0 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,20 @@
-# macbox: macOS, Xcode and the iOS Simulator on Linux, GPU-accelerated, for AI coding agents
+# macbox
-**Run the real iOS Simulator on a Linux machine, without a Mac and without a cloud service.**
-macbox runs a full macOS VM in Docker with real GPU acceleration (Metal, through Reims vGPU on
-your Vulkan GPU), with Xcode, a pool of iOS Simulators, T3 Code's Device panel, and the tools AI
-coding agents (Claude Code, Codex, T3 Code) need to build, run, drive and check iOS apps on their
-own. One command, `macbox`, sets it up and runs it.
+### The real iOS Simulator and Xcode on your Linux machine. GPU-accelerated. No Mac.
+
+macbox runs a full macOS VM in Docker that draws with **Metal on your Linux GPU**, so Xcode and
+the iOS Simulator run on hardware you already have. An iPhone 17 Pro simulator at full 3x
+resolution, in a heavy Liquid Glass scene, runs at **117 fps on an Intel integrated GPU**. Before
+macbox's patches the same GPU managed 17. It's built for AI coding agents: Claude Code, Codex and
+T3 Code each get their own simulator to build, run, tap, screenshot and record iOS apps on their own.
+One command, `macbox`, builds it and runs it.
+
+| | |
+|---|---|
+| **117 fps** | iPhone 17 Pro simulator at 3x (1206×2622), Liquid Glass, on an Arrow Lake iGPU; 17.2 before |
+| **3 at once** | three 3x simulators side by side, ~32 fps each |
+| **No Mac, no cloud** | a Linux host with KVM and Docker; nothing billed per minute |
+| **Agent-ready** | `mac-sim` gives every checkout its own simulator; `sim-fps` checks 60 fps; T3 Code's Device panel streams it live |
**Website and guides:** [tuna-nope.github.io/macbox](https://tuna-nope.github.io/macbox/): macOS, Xcode and
the iOS Simulator on Linux, Expo apps, the GPU path, and AI coding agents with T3 Code.
@@ -27,8 +37,8 @@ Linux host (KVM + a Vulkan GPU + Docker)
- **macOS draws on your GPU.** [Reims vGPU](https://github.com/steelbrain/reims-vgpu) gives QEMU
Apple's paravirtual GPU, and macOS's own driver talks to it, so Metal works with no guest
driver. [metal2vulkan](https://github.com/steelbrain/metal2vulkan) runs Metal's work on Vulkan.
- macbox builds both, with patches that took a 3x iOS Simulator from 17 to 50 fps on the GPU it
- was measured on, and to 70 with the experimental Coherent switch (see [Performance](#performance)).
+ macbox builds both, with patches that took a 3x iOS Simulator from 17 to 117 fps on the GPU it
+ was measured on (see [Performance](#performance)).
- **The screen** opens in a window on your Linux desktop, or in a browser tab (Selkies: H.264 on
the GPU, its bitrate following the link). Agents can see it and click and type into it
(`macbox screenshot`, `click`, `type`), so an agent can drive the macOS installer too.
@@ -90,34 +100,37 @@ floating glass toolbar, counted at the simulator's own screen (frames per second
-
+
| iOS Simulator at 3x (1206x2622, an iPhone's pixels), glass | fps |
|---|---|
| Reims 2ce3209, as upstream shipped it on 2026-10-26 | 17.2 |
| macbox, 2026-10-28: rendering guest-RAM textures in place | 38.5 / 39.5 |
-| **macbox build now** (cohwl, 2026-11-05) | **50.6** (p95 21 ms) |
-| macbox build with `MACBOX_COHERENT=on` (experimental) | **70.0** (p95 18 ms) |
-
-| | Reims 2ce3209 | macbox, 2026-10-28 | macbox now, Coherent on |
-|---|---|---|---|
-| iOS Simulator 1x (402x874), glass | 53.5 | 95.8 / 92.5 | not measured yet |
-| iOS Simulator 2x (804x1748), glass | 33.5 | 67.8 / 60.5 | not measured yet |
-| macOS desktop, dragging a window (presents/s) | | 105 (Coherent off) | 130 |
-| macOS desktop, Safari scrolling (presents/s) | | 75–79 (Coherent off) | 110 |
-| macOS desktop, Genie minimize at 3440x1440 (frames per animation) | ~12 | 19.5 | 29.5 / 30.5 |
-
-Coherent keeps the GPU's image of the simulator's and the desktop's surfaces ahead of guest RAM,
-and syncs a page only when the guest's CPU touches it: the copies that were left are gone, and the
-GPU drops from 97% to 70% busy at 3x. It is off by default for now: it hung the GPU once on its
-first day of daily use (the next boot came up without it, as designed), and the cause isn't
-settled. [docs/performance.md](docs/performance.md#coherent-experimental-off-by-default) has the details.
-
-The GPU is the limit: without Coherent a 3x simulator keeps this iGPU 96 to 98% busy. On a faster
-GPU every number moves up. [docs/performance.md](docs/performance.md) has what the patches do, the method, what
-didn't help, and the known limits (an idle macOS display gets no vblank from its driver, so an
-animation starts about 0.1 s late: [reims-vgpu#141](https://github.com/steelbrain/reims-vgpu/issues/141)).
+| macbox, 2026-11-05: flat32 | 50.6 |
+| macbox, 2026-11-05: + Coherent, zero-copy surfaces | 70.0 |
+| **macbox now** (2026-11-09): + grouped completion, staged page-ups, inline checks | **117** (114–121; the screen's limit is 120) |
+
+| The build macbox makes now | |
+|---|---|
+| two 3x simulators at once | 51–54 fps each |
+| three 3x simulators at once | 31–32 fps each |
+| macOS desktop (3440x1440), dragging a window | 240 display-link ticks a second alone; 126 with a simulator running |
+| copying frames back to guest RAM | 0.2% of what eager copies would cost: about 5 µs a frame |
+
+Coherent keeps the GPU's image of the simulator's and the desktop's surfaces ahead of guest RAM and
+syncs a page only when the guest's CPU touches it, so the copies between them are gone. The rest
+removed per-page mappings, per-batch completions and a scheduling round per batch. It's on by
+default with an Arrow Lake iGPU, where it runs every day, and a crash guard falls back to the plain
+path after a bad run. One rare GPU hang under repeated boots of three simulators is still open.
+[docs/performance.md](docs/performance.md) has the details.
+
+The GPU is the limit: one 3x simulator takes about 7.7 ms of this iGPU's time per frame, and several
+simulators share about 105 frames a second. On a faster GPU every number moves up.
+[docs/performance.md](docs/performance.md) breaks a frame down (what is real rendering and what the
+translation adds), lists what didn't help, and the known limits (an idle macOS display gets no
+vblank from its driver, so an animation starts about 0.1 s late:
+[reims-vgpu#141](https://github.com/steelbrain/reims-vgpu/issues/141)).
## Questions people ask
diff --git a/docs/architecture.md b/docs/architecture.md
index d4730ac..4ed355e 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -61,7 +61,8 @@ and the QEMU command line; `reims-ctl command mac` (inside the container) prints
- Before each start: `WAYLAND_DISPLAY` (sway's, or the host's), and the GPU tuning:
`M2V_LIVE=$MACBOX_HOME/run/live.conf` with `host_rt_in_place=1`,
`REIMS_VGPU_PRIVATE_SKIP_PAGE_UP=1`, `M2V_ARL_FACTS` on an Arrow Lake GPU, and with
- `MACBOX_COHERENT=on` the census and Coherent switches ([performance.md](performance.md)).
+ Coherent (`MACBOX_COHERENT`, on by default with an Arrow Lake GPU) the census, Coherent and the
+ switches measured with it, in `live.conf` and Reims's environment ([performance.md](performance.md)).
The disk's options in `extra_args` are written again, so a changed `MACBOX_DISK_CACHE` applies.
The system disk starts on SATA, because macOS's installer may not find a disk on NVMe, and moves to
diff --git a/docs/images/fps-dark.svg b/docs/images/fps-dark.svg
index db56b45..69d4660 100644
--- a/docs/images/fps-dark.svg
+++ b/docs/images/fps-dark.svg
@@ -1,34 +1,44 @@
-
-
+
+
iOS Simulator at 3x (1206×2622), Liquid Glass benchmark
Frames per second on an Intel Arrow Lake iGPU (Core Ultra 7 265). Higher is better.
-
-0
-
-20
-
-40
-
-60
-
-80
-frames per second
-
-60 fps
-Upstream
-Reims 2ce3209, 2026-10-26
-
-17.2
-macbox, Oct 28
-in place rendering
-
-39.0
-macbox now
-cohwl, the default
-
-50.6
-+ Coherent
-experimental, off by default
-
-70.0
+
+0
+
+20
+
+40
+
+60
+
+80
+
+100
+
+120
+frames per second
+
+60 fps
+
+120 Hz screen
+Upstream
+Reims 2ce3209, 2026-10-26
+
+17.2
+macbox, Oct 28
+in place rendering
+
+39.0
+macbox, Nov 5
+cohwl: flat32
+
+50.6
++ Coherent
+zero-copy surfaces, Nov 5
+
+70.0
+macbox now
+Coherent + grouped completion
+
+117.0
diff --git a/docs/images/fps-light.svg b/docs/images/fps-light.svg
index 6eeefda..debc91c 100644
--- a/docs/images/fps-light.svg
+++ b/docs/images/fps-light.svg
@@ -1,34 +1,44 @@
-
-
+
+
iOS Simulator at 3x (1206×2622), Liquid Glass benchmark
Frames per second on an Intel Arrow Lake iGPU (Core Ultra 7 265). Higher is better.
-
-0
-
-20
-
-40
-
-60
-
-80
-frames per second
-
-60 fps
-Upstream
-Reims 2ce3209, 2026-10-26
-
-17.2
-macbox, Oct 28
-in place rendering
-
-39.0
-macbox now
-cohwl, the default
-
-50.6
-+ Coherent
-experimental, off by default
-
-70.0
+
+0
+
+20
+
+40
+
+60
+
+80
+
+100
+
+120
+frames per second
+
+60 fps
+
+120 Hz screen
+Upstream
+Reims 2ce3209, 2026-10-26
+
+17.2
+macbox, Oct 28
+in place rendering
+
+39.0
+macbox, Nov 5
+cohwl: flat32
+
+50.6
++ Coherent
+zero-copy surfaces, Nov 5
+
+70.0
+macbox now
+Coherent + grouped completion
+
+117.0
diff --git a/docs/images/make-chart.py b/docs/images/make-chart.py
index 51ea13a..12ab1e2 100644
--- a/docs/images/make-chart.py
+++ b/docs/images/make-chart.py
@@ -1,21 +1,22 @@
#!/usr/bin/env python3
"""Writes fps-light.svg and fps-dark.svg, the README's frame-rate chart (docs/performance.md's numbers).
-Colors: the validated categorical slots 1 and 2 (blue, orange) for each mode's surface; the
-experimental bar is the macbox blue at reduced opacity, and its label says so."""
+Colors: the validated categorical slots 1 and 2 (blue, orange) for each mode's surface: orange for
+upstream, blue for macbox's builds, the build macbox makes now at full strength and the earlier ones lighter."""
import os
ROWS = [ # label, sublabel, fps (3x, mean of the valid rounds), kind
("Upstream", "Reims 2ce3209, 2026-10-26", 17.2, "before"),
("macbox, Oct 28", "in place rendering", (38.5 + 39.5) / 2, "after"),
- ("macbox now", "cohwl, the default", 50.6, "after"),
- ("+ Coherent", "experimental, off by default", 70.0, "exp"),
+ ("macbox, Nov 5", "cohwl: flat32", 50.6, "after"),
+ ("+ Coherent", "zero-copy surfaces, Nov 5", 70.0, "after"),
+ ("macbox now", "Coherent + grouped completion", 117.0, "now"),
]
MODES = {
"light": dict(surface="#fcfcfb", text="#0b0b0b", text2="#52514e", grid="#e4e3df", before="#eb6834", after="#2a78d6"),
"dark": dict(surface="#1a1a19", text="#f0efec", text2="#c3c2b7", grid="#3a3a37", before="#d95926", after="#3987e5"),
}
-W, H = 900, 320
-X0, X1, MAX = 230, 840, 80 # bar area and its scale (fps)
+W, H = 900, 380
+X0, X1, MAX = 250, 830, 130 # bar area and its scale (fps)
BAR, GAP = 30, 16 # bar thickness, space between bars
TOP = 96
FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif"
@@ -34,19 +35,20 @@ def svg(m):
f'iOS Simulator at 3x (1206×2622), Liquid Glass benchmark ',
f'Frames per second on an Intel Arrow Lake iGPU (Core Ultra 7 265). Higher is better. ']
bottom = TOP + len(ROWS) * BAR + (len(ROWS) - 1) * GAP
- for v in (0, 20, 40, 60, 80):
+ for v in (0, 20, 40, 60, 80, 100, 120):
o.append(f' ')
o.append(f'{v} ')
o.append(f'frames per second ')
- # the 60 fps target
- o.append(f' ')
- o.append(f'60 fps ')
+ # 60 fps, and the iPhone 17 Pro's 120 Hz screen: the most its simulator can show
+ for v, t in ((60, "60 fps"), (120, "120 Hz screen")):
+ o.append(f' ')
+ o.append(f'{t} ')
y = TOP
for label, sub, v, kind in ROWS:
col = c["before"] if kind == "before" else c["after"]
o.append(f'{label} ')
o.append(f'{sub} ')
- o.append(bar(y, v, col, 0.55 if kind == "exp" else 1.0))
+ o.append(bar(y, v, col, 1.0 if kind in ("before", "now") else 0.55))
o.append(f'{v:.1f} ')
y += BAR + GAP
o.append(" ")
diff --git a/docs/performance.md b/docs/performance.md
index 73b902c..866b0c3 100644
--- a/docs/performance.md
+++ b/docs/performance.md
@@ -2,21 +2,35 @@
## Where the time goes
-On every GPU measured so far, the GPU is the limit. A 3x iOS Simulator keeps an Arrow Lake iGPU
-96 to 98% busy at its full clock, while QEMU's CPU threads have room to spare. So the frame rate
-follows two things: how many pixels are drawn (1x, 2x, 3x; the desktop's resolution), and how much
-work the translation adds per frame (Metal → Vulkan).
+On every GPU measured so far, the GPU is the limit. With the build macbox makes now, one 3x iOS
+Simulator reaches its screen's 120 Hz on an Arrow Lake iGPU at about 7.7 ms of GPU time per frame,
+and with two or three simulators the GPU runs 80 to 93% busy at its top clock (1950 MHz) while
+QEMU's CPU threads have room to spare. So the frame rate follows two things: how many pixels are
+drawn (1x, 2x, 3x; the desktop's resolution), and how much work the translation adds per frame
+(Metal → Vulkan).
Before macbox's patches, most of that added work was copies: macOS's framebuffer and the
simulator's display surface lie in guest RAM, and metal2vulkan copied each into a GPU image and back
around every render pass. Those shadow copies were 51% of all GPU time with the simulator and 67%
with the desktop. Patch 0004 renders those textures in place, and Coherent (patches 0009 onwards,
with QEMU's census) removes most of the copies left ([patches/README.md](../patches/README.md)).
+What is left of a 3x simulator frame, measured with the pass timer on 2026-11-09:
+
+| GPU time per 3x frame (~7.7–8.2 ms) | ms | |
+|---|---|---|
+| the simulator's own render passes on its screen | ~3.2 | the real rendering |
+| iOS's own full-screen compute pass (a masked copy of the screen) | ~1.5 | the real rendering, near the memory bandwidth |
+| copies for draws that read the pass they draw into (Liquid Glass backdrops) | ~0.76 | translation: Vulkan can't read an attachment where Metal can |
+| between command buffers: barriers, pipeline drains, ~200 command buffers | ~2.4 | translation, and the open work |
+
+Copying a frame back to guest RAM, the cost Coherent was built to remove, is down to bookkeeping: in
+a 90-minute census of the desktop at 3440x1440, 0.2% of what eager copies back would have cost
+(about 5 µs a frame), and 2% for the simulators' screens.
## Measurements
The reference host: Intel Core Ultra 7 265 (Arrow Lake iGPU), 128 GB DDR5 at 4400 MT/s, Mesa 26.2.4,
-a NVMe disk; the VM had 8 vCPUs and 12 GB, macOS 26.7.1, iOS 26.5, one simulator booted at a time.
+a NVMe disk; the VM had 8 vCPUs and 12 GB, macOS 26.7.1, iOS 26.5.
### iOS Simulator at 3x, step by step
@@ -27,15 +41,39 @@ Pro at 3x (1206x2622), frames per second counted at the simulator's own screen:
|---|---|---|
| Reims 2ce3209 as upstream shipped it (2026-10-26) | 17.2 | |
| macbox, 2026-10-28 (in place rendering, 0004) | 38.5 / 39.5 | 25.0 ms/frame |
-| macbox cohwl, Coherent off (flat32) | **50.6** (p95 21.4 ms, p99 25.8 ms) | 97% busy |
-| macbox cohwl, `MACBOX_COHERENT=on` | **70.0** (p95 17.7 ms, p99 22.0 ms); 63–66 in a later run | 70% busy |
+| macbox cohwl, Coherent off (flat32), 2026-11-05 | 50.6 (p95 21.4 ms, p99 25.8 ms) | 97% busy |
+| macbox cohwl, Coherent on, 2026-11-05 | 70.0 (p95 17.7 ms, p99 22.0 ms) | 70% busy |
+| **macbox now** (Coherent and the switches below, 2026-11-09) | **117** (114–121 over runs) | 7.7 ms/frame |
+
+The iPhone 17 Pro's screen runs at up to 120 Hz, so 117 is close to the most a single simulator can
+show; GlassBench's own content animates at 60 Hz, and the simulator redraws on top of it. The
+cohwl rows are one A/B in one window; the last row comes from the soak and A/B runs of 2026-11-09
+and -10 (fresh headless boots, Simulator.app closed). flat32 also has an A/B of its own against the
+build before it: 41.6 → 48–50 fps.
+
+### Several simulators at once, and the desktop under load
+
+The build macbox makes now, 3x iPhone 17 Pro simulators all running GlassBench, the macOS desktop at
+3440x1440 (2026-11-09, soak with simulators booted and shut down in cycles, 0 GPU hangs):
-The last two rows are one A/B in one window on 2026-11-05: fresh headless boots, a quiet gate
-before each round (guest background CPU and `mediaanalysisd` low), means of the valid rounds. The
-first two are earlier days, on the same host but not in the same window. With Coherent, QEMU's CPU
-use rises by about 1.6 cores (333% to 491%): the GPU waits less, the CPU traps more.
+| Load | Each simulator, fps | GPU |
+|---|---|---|
+| 1 simulator | 114–121 | 7.7 ms/frame |
+| 1 simulator while a window is dragged on the desktop | 99–102 | |
+| 2 simulators | 51–54 each (~105 frames/s in total) | 80–85% busy, ~8 ms/frame |
+| 3 simulators | 31–32 each (~95 in total) | 93% busy |
+
+| Desktop: dragging a window (display-link ticks per second, p99 interval) | |
+|---|---|
+| alone | 240/s, p99 10 ms |
+| with 1 simulator running | 126–128/s, p99 22–26 ms |
+| with 2 simulators running | 96–102/s, p99 32–38 ms |
-flat32 also has an A/B of its own against the build before it: 41.6 → 48–50 fps at 3x.
+Two or more simulators share the GPU: about 105 simulator frames a second in total on this iGPU,
+whatever their number. All guest work reaches the GPU in one order, so the desktop's frames wait
+behind the simulators' earlier work; that, not the desktop's own cost, is its latency under load.
+These runs placed the VM's vCPUs on the CPU's performance cores and QEMU's other threads on all
+cores (`MACBOX_CPUSET` pins all of QEMU instead).
### Earlier measurements, the 2026-10-28 build
@@ -46,17 +84,17 @@ flat32 also has an A/B of its own against the build before it: 41.6 → 48–50
| 3x (1206x2622) | 17.2 | 19.2 | 21.9 | 38.5 / 39.5 (25.0 ms) |
| Safari at 3x, blurred floating bar | n/a | 39.5 | 44.5 | 66.4 / 64.2 |
-1x and 2x haven't been measured again on cohwl.
+1x and 2x haven't been measured again since.
-### The macOS desktop
+### The macOS desktop, 2026-11-05
-| 3440x1440 desktop | Coherent off | Coherent on |
+| 3440x1440 desktop (cohwl) | Coherent off | Coherent on |
|---|---|---|
| dragging a 600x400 window (presents per second) | 105–107 | 129–130 |
| Safari scrolling a local page (presents per second) | 75–79 | 110 |
| Genie minimize of a 2400x1100 window (frames per animation; ~12 upstream) | 19.5 (the 10-28 build) | 29.5 / 30.5 |
-The first two rows are the same A/B as above. The Genie number with Coherent comes from a smoke
+The first two rows are the cohwl A/B above. The Genie number with Coherent comes from a smoke
check, not a matched A/B. A 0.5 s animation at 60 Hz would be 30 frames.
### Disk
@@ -99,6 +137,7 @@ With the macbox build (`MACBOX_GPU_TUNING=auto`, the default), `macbox up` sets:
| `M2V_LIVE=$MACBOX_HOME/run/live.conf` | metal2vulkan's live switches (patch 0003). The file holds `host_rt_in_place=1` |
| `M2V_ARL_FACTS=<11 facts>` | only on an Arrow Lake GPU (PCI ids 7d67, 7dd1, 7d41, 7d51, 7d45) |
| `REIMS_VGPU_PRIVATE_SKIP_PAGE_UP=1` | skips a new Private texture's first page-up (Reims patch 0013) |
+| Coherent and the switches below | with `MACBOX_COHERENT=auto` (the default) on an Arrow Lake GPU |
`host_rt_in_place` is read when a texture is made: change it in `live.conf`, then remake the
surfaces (change the resolution, or restart the VM). `MACBOX_GPU_TUNING=off` turns all of it off.
@@ -107,25 +146,42 @@ On another GPU, in place rendering still runs its device check per memory kind a
the check fails; it has only been measured on Arrow Lake. Measure your own GPU before and after:
the facts list is specific to Arrow Lake and is never set elsewhere.
-### Coherent (experimental, off by default)
+### Coherent and the switches measured with it (on by default on Arrow Lake)
-`MACBOX_COHERENT=on` in the config, then `macbox down && macbox up`. macbox then also sets
-`REIMS_VGPU_CENSUS=$MACBOX_HOME/run/coherent`, `REIMS_VGPU_COHERENT=1` and a report a minute, and
-adds `surface_lazy=1`, `surface_lazy_scoped=1` and `surface_coherent=1` to `live.conf`.
-`MACBOX_COHERENT=off` removes them all again.
+`MACBOX_COHERENT=auto` (the default) turns this on with an Arrow Lake iGPU, the GPU it runs on day
+to day; `on` turns it on with any GPU, `off` turns it off. A change applies at the next
+`macbox down && macbox up`. With it, macbox sets:
-It is off by default because it isn't settled yet:
-- **One GPU hang with it on.** On 2026-11-05, the day it went into daily use, i915
- reset the GPU's render engine and QEMU stopped. The guard did its job: the next boot came up without
- coherent pages. A later hang with Coherent off, on a newer development build, has the same error
- code, so the cause is open, not pinned on Coherent.
-- **A write-loss risk the counters flagged once,** during a test that killed Safari mid-frame
- (`overwrite_risk` 1 in the census report), and that hasn't been reproduced or ruled out since.
-
-If a coherent run crashes, `$MACBOX_HOME/run/coherent/coherent.running` stays behind and every later
-start boots without coherent pages. `macbox coherent status` says so; `macbox coherent reset`
-(VM stopped) allows the next try. It needs a kernel with `UFFD_USER_MODE_ONLY` (Linux 5.11 or
-later), which works with `vm.unprivileged_userfaultfd=0`.
+| | |
+|---|---|
+| `REIMS_VGPU_CENSUS=$MACBOX_HOME/run/coherent`, `REIMS_VGPU_COHERENT=1` | QEMU's census traps the guest CPU's touches of the surfaces metal2vulkan keeps on the GPU (a report a minute) |
+| `surface_lazy`, `surface_lazy_scoped`, `surface_coherent` | the simulator's and the desktop's surfaces stay on the GPU; a page syncs only when the guest's CPU touches it |
+| `surface_lazy_max_texels=6000000`, `surface_twin_reader_first`, `surface_coherent_own_back`, `surface_lazy_open_ids`, `surface_twin_make_once` | fixes the lanes and the census found on top of it: which surfaces qualify, a race between two textures over one surface (`make_once`: 91 → 100 fps over 12 boots), and exact answers about committed command buffers |
+| `inline_lazy`, `inline_checks` | a lazy surface's first pass instance is recorded inline; a batch's submission checks run in the scheduler's pass, so no chained batch waits a round for them |
+| `REIMS_VGPU_GROUPED=1`, `group_batches=64`, `group_deadline_us=500`, `group_keep=0`, `group_events=0` | grouped completion: up to 64 batches complete together; keep and events off, which ended a class of fence timeouts under several simulators |
+| `REIMS_VGPU_STAGED_PAGE_UP`, `REIMS_VGPU_STAGED_ZERO` | a new texture's first page-up copies guest pages into a staging buffer instead of mapping a view per page run (55k mappings a second and a storm of TLB shootdowns before: simulator 89 → 101 fps), and pages of zeros write nothing |
+| `REIMS_VGPU_PIPELINE_EXEC`, `REIMS_VGPU_IRQ_MODERATE` | a FIFO's execs pipelined (8 in flight), and one interrupt outstanding at a time |
+| `facts_on=SubmissionsWithoutSignalsMerge` | Arrow Lake only: submissions without signals merge |
+
+The four `REIMS_VGPU_*` switches that name a file are on while the file exists
+(`$MACBOX_HOME/run/switches/`), so each can be turned off without a restart. `live.conf` lines are
+re-read every second; macbox rewrites its own lines at every start and leaves yours alone.
+
+What to know before relying on it:
+- **The crash guard.** If a coherent run crashes, `$MACBOX_HOME/run/coherent/coherent.running`
+ stays behind and every later start boots without coherent pages. `macbox coherent status` says
+ so; `macbox coherent reset` (VM stopped) allows the next try. A fault costs one crash, not a crash
+ loop.
+- **It needs** a kernel with `UFFD_USER_MODE_ONLY` (Linux 5.11 or later), which works with
+ `vm.unprivileged_userfaultfd=0`. In the cohwl A/B QEMU used about 1.6 more CPU cores with it:
+ the GPU waits less, the CPU traps more.
+- **A rare GPU hang is still open.** Under repeated boots and shutdowns of three simulators, a
+ command buffer is occasionally begun again while the GPU still runs it, and i915 resets the GPU.
+ It is traced to command-buffer reuse in metal2vulkan's submission path, not to Coherent's pages,
+ and is being hunted with an exact detector in Mesa.
+- **Write-loss check.** The census counts `overwrite_risk`, a guest write a held GPU copy could
+ overwrite. It was flagged once in an early test that killed Safari mid-frame; across 64
+ production boots since 2026-11-08 (16,850 reports) it stayed at 0.
## Tried, no gain
@@ -147,6 +203,13 @@ later), which works with `vm.unprivileged_userfaultfd=0`.
| a reaper for deleted textures | Safari 5–8 fps slower, and Genie breaks |
| executing the FIFO from its own thread (fifoexec) | a GPU hang on its first day; rolled back |
| merging adjacent page runs of a mapping | negligible: 49 merges in 629,632 pages of a real trace |
+| chaining a submission's primary command buffers in ANV (one preamble, one end) | 13 → 2 µs per command buffer in a micro benchmark, 0–1% on a real frame: the barrier before already drains the GPU |
+| precise barriers (no L3 flush between images) | within boot-to-boot noise: real frames leave little dirty |
+| lossless compression (CCS) on the simulator's surfaces, in three forms | no GPU time saved; a lone simulator lost a third of its frames to host copies |
+| several Vulkan queues (`ANV_QUEUE_OVERRIDE=gc=18`) | about 0% (+4% with three simulators): the GPU is already busy; one i915 context per queue (`gc=8`) was unstable |
+| keeping groups of batches open (`group_keep=1`) | +6–7% with two simulators, but held groups stalled frames up to 200 ms |
+| lowering a simulator's draws on a second thread | 90 → 72 fps: the first thread waits for it |
+| a deeper FIFO pipeline (32 execs instead of 8) | slower: 109 → 97 fps, desktop p99 27 → 37 ms |
## Known limits
@@ -154,7 +217,8 @@ later), which works with `vm.unprivileged_userfaultfd=0`.
sends no vblank while nothing is presenting, so the first frame of an animation waits a median
114 ms for display timing (8 ms when something already animates).
[steelbrain/reims-vgpu#141](https://github.com/steelbrain/reims-vgpu/issues/141).
-- **3x is GPU-bound** at about 50 fps on this iGPU in heavy Liquid Glass scenes (70 with Coherent).
+- **The GPU is shared.** One 3x simulator reaches 120 Hz; two or three share about 105 frames a
+ second on this iGPU, and the desktop's frames wait behind theirs.
- **x86-64 macOS ends with macOS 26.** iOS 27 simulators are arm64 only.
- **Recording** uses `simctl io recordVideo`, H.264 in software in the VM: about 50 fps with one
simulator animating, 18 each with three. `sim-fps` counts what the simulator wrote, and it writes
diff --git a/docs/setup.md b/docs/setup.md
index 5949bf0..df86c43 100644
--- a/docs/setup.md
+++ b/docs/setup.md
@@ -38,7 +38,7 @@ node), makes an SSH key `~/.ssh/macbox_ed25519`, and adds a `Host macbox` block
| `MACBOX_CPUSET` | empty | pin QEMU to some cores, e.g. a hybrid CPU's performance cores (`0-7`) |
| `MACBOX_BUILD_CPUSET` | empty | cores for `macbox build`, e.g. the efficiency cores |
| `MACBOX_DISK_CACHE` | none | `writeback` panicked macOS's NVMe driver under heavy swap; `unsafe` is faster, but a crash of the host itself can corrupt the VM's disk. Applies at the next `macbox up` |
-| `MACBOX_COHERENT` | off | `on`: Coherent, zero-copy surfaces, about 40% faster at 3x and experimental ([performance.md](performance.md#coherent-experimental-off-by-default)) |
+| `MACBOX_COHERENT` | auto | `auto`: on with an Arrow Lake iGPU. Coherent, zero-copy surfaces, and the switches measured with it: a 3x simulator 50 → 117 fps there ([performance.md](performance.md#coherent-and-the-switches-measured-with-it-on-by-default-on-arrow-lake)); `on` with any GPU, `off` |
| `MACBOX_HOME` | ~/.local/share/macbox | everything macbox keeps |
Then:
diff --git a/llms.txt b/llms.txt
index e80aabe..b73681e 100644
--- a/llms.txt
+++ b/llms.txt
@@ -1,6 +1,6 @@
# macbox
-> Run macOS, Xcode and the real iOS Simulator on a Linux host, in Docker, with GPU acceleration (Metal through Reims vGPU and metal2vulkan on the host's Vulkan GPU), for AI coding agents such as Claude Code, Codex and T3 Code. No Mac and no cloud service: one CLI, `macbox`, builds and runs it, and `mac-sim` gives each agent checkout its own iOS Simulator to build, run, tap, screenshot, record and measure at 60 fps.
+> Run macOS, Xcode and the real iOS Simulator on a Linux host, in Docker, with GPU acceleration (Metal through Reims vGPU and metal2vulkan on the host's Vulkan GPU), for AI coding agents such as Claude Code, Codex and T3 Code. An iPhone 17 Pro simulator at 3x runs a Liquid Glass benchmark at 117 fps on an Intel Arrow Lake iGPU (17 before macbox's patches). No Mac and no cloud service: one CLI, `macbox`, builds and runs it, and `mac-sim` gives each agent checkout its own iOS Simulator to build, run, tap, screenshot, record and measure at 60 fps.
License: PolyForm Noncommercial 1.0.0 for macbox's own code (noncommercial use; commercial use needs permission); the patches stay GPL-2.0-or-later OR LGPL-3.0-or-later (GPL-2.0-or-later for the QEMU ones).
@@ -33,7 +33,7 @@ publishing on their behalf.
## How it works
- [Architecture](https://github.com/TUNA-NOPE/macbox/blob/main/docs/architecture.md): the container, QEMU and Reims vGPU, the display stream, the network, the guest, the simulator pool
-- [Performance](https://github.com/TUNA-NOPE/macbox/blob/main/docs/performance.md): the patches (in place rendering, flat32, experimental Coherent), measurements, tuning, known limits
+- [Performance](https://github.com/TUNA-NOPE/macbox/blob/main/docs/performance.md): the patches (in place rendering, flat32, Coherent zero-copy surfaces, grouped completion, staged page-ups), measurements for one to three simulators and the desktop, a frame broken down, tuning, known limits
- [Patches](https://github.com/TUNA-NOPE/macbox/blob/main/patches/README.md)
- [Troubleshooting](https://github.com/TUNA-NOPE/macbox/blob/main/docs/troubleshooting.md)
- [Credits](https://github.com/TUNA-NOPE/macbox/blob/main/CREDITS.md)
diff --git a/macbox b/macbox
index 1f5bfc0..4b4c056 100755
--- a/macbox
+++ b/macbox
@@ -15,7 +15,7 @@ eval "$_env"
: "${MACBOX_GUEST_USER:=dev}" "${MACBOX_CPUS:=8}" "${MACBOX_MEMORY:=12G}" "${MACBOX_DISK_SIZE:=160G}"
: "${MACBOX_RESOLUTION:=1920x1080}" "${MACBOX_REFRESH:=60}" "${MACBOX_CPUSET:=}"
: "${MACBOX_RENDER_NODE:=/dev/dri/renderD128}" "${MACBOX_DISK_CACHE:=none}" "${MACBOX_GPU_TUNING:=auto}"
-: "${MACBOX_COHERENT:=off}"
+: "${MACBOX_COHERENT:=auto}"
: "${MACBOX_SIM_PREFIX:=macbox}" "${MACBOX_POOL:=full slim-1 slim-2 sharp small}"
: "${MACBOX_T3_HOST_ID:=$MACBOX_SSH_HOST}" "${MACBOX_T3_SETTINGS:=$HOME/.t3/userdata/settings.json}"
DOCKER="${MACBOX_DOCKER:-docker}"
@@ -95,28 +95,65 @@ tuning_on() {
*) [[ "$(build_id)" == *-macbox ]] ;;
esac
}
+# Coherent with the switches measured on top of it, the build that runs day to day on the Arrow
+# Lake iGPU ("production I", docs/performance.md): metal2vulkan's live lines, then Reims's switches
+# (each of the file-named ones is on while its file exists, so it can be flipped without a restart).
+COHERENT_LIVE="surface_lazy surface_lazy_scoped surface_lazy_max_texels surface_coherent surface_twin_reader_first surface_coherent_own_back surface_lazy_open_ids surface_twin_make_once inline_lazy inline_checks group_batches group_deadline_us group_keep group_events facts_on"
+COHERENT_ENV="REIMS_VGPU_CENSUS REIMS_VGPU_COHERENT REIMS_VGPU_CENSUS_FLUSH_MS REIMS_VGPU_GROUPED REIMS_VGPU_STAGED_PAGE_UP REIMS_VGPU_STAGED_ZERO REIMS_VGPU_PIPELINE_EXEC REIMS_VGPU_IRQ_MODERATE"
+coherent_on() { # auto: on with the Arrow Lake iGPU it was measured on
+ case "$MACBOX_COHERENT" in
+ on) return 0 ;; off) return 1 ;;
+ *) gpu_is_arl ;;
+ esac
+}
+drop_managed() { # drop_managed : the lines macbox writes, so a change of mode applies
+ [ -f "$1" ] || return 0
+ local k
+ for k in $COHERENT_LIVE; do sed -i "/^$k=/d" "$1"; done
+}
apply_tuning() { # before each start
- local live="$RUN/live.conf"
+ local live="$RUN/live.conf" k
if tuning_on; then
[ -s "$live" ] || printf '# metal2vulkan live switches (patches/metal2vulkan), re-read every second\nhost_rt_in_place=1\n' >"$live"
- sed -i '/^surface_\(lazy\|lazy_scoped\|coherent\)=/d' "$live"
+ drop_managed "$live"
local env=(--env "M2V_LIVE=$live" --env REIMS_VGPU_PRIVATE_SKIP_PAGE_UP=1)
if gpu_is_arl; then env+=(--env "M2V_ARL_FACTS=$ARL_FACTS"); else env+=(--env "M2V_ARL_FACTS="); fi
- if [ "$MACBOX_COHERENT" = on ]; then
+ if coherent_on; then
# QEMU's census traps the guest CPU's touches of the surfaces metal2vulkan renders in place.
# A run that doesn't end well leaves coherent/coherent.running, and every later start then
# boots without Coherent until that file is removed (macbox coherent reset).
- mkdir -p "$RUN/coherent"
- printf 'surface_lazy=1\nsurface_lazy_scoped=1\nsurface_coherent=1\n' >>"$live"
- env+=(--env "REIMS_VGPU_CENSUS=$RUN/coherent" --env REIMS_VGPU_COHERENT=1 --env REIMS_VGPU_CENSUS_FLUSH_MS=60000)
+ mkdir -p "$RUN/coherent" "$RUN/switches"
+ cat >>"$live" <<'LIVE'
+surface_lazy=1
+surface_lazy_scoped=1
+surface_lazy_max_texels=6000000
+surface_coherent=1
+surface_twin_reader_first=1
+surface_coherent_own_back=1
+surface_lazy_open_ids=1
+surface_twin_make_once=1
+inline_lazy=1
+inline_checks=1
+group_batches=64
+group_deadline_us=500
+group_keep=0
+group_events=0
+LIVE
+ gpu_is_arl && echo 'facts_on=SubmissionsWithoutSignalsMerge' >>"$live"
+ for k in staged-page-up staged-zero pipeline-exec irq-moderate; do : >"$RUN/switches/$k"; done
+ env+=(--env "REIMS_VGPU_CENSUS=$RUN/coherent" --env REIMS_VGPU_COHERENT=1 --env REIMS_VGPU_CENSUS_FLUSH_MS=60000
+ --env REIMS_VGPU_GROUPED=1 --env "REIMS_VGPU_STAGED_PAGE_UP=$RUN/switches/staged-page-up"
+ --env "REIMS_VGPU_STAGED_ZERO=$RUN/switches/staged-zero" --env "REIMS_VGPU_PIPELINE_EXEC=$RUN/switches/pipeline-exec"
+ --env "REIMS_VGPU_IRQ_MODERATE=$RUN/switches/irq-moderate")
else
- env+=(--env REIMS_VGPU_CENSUS= --env REIMS_VGPU_COHERENT= --env REIMS_VGPU_CENSUS_FLUSH_MS=)
+ for k in $COHERENT_ENV; do env+=(--env "$k="); done
fi
ctl set "$MACBOX_VM" "${env[@]}" >/dev/null
else
- [ -f "$live" ] && sed -i '/^surface_\(lazy\|lazy_scoped\|coherent\)=/d' "$live"
- ctl set "$MACBOX_VM" --env "M2V_LIVE=" --env "M2V_ARL_FACTS=" --env REIMS_VGPU_PRIVATE_SKIP_PAGE_UP= \
- --env REIMS_VGPU_CENSUS= --env REIMS_VGPU_COHERENT= --env REIMS_VGPU_CENSUS_FLUSH_MS= >/dev/null
+ drop_managed "$live"
+ local env=(--env "M2V_LIVE=" --env "M2V_ARL_FACTS=" --env REIMS_VGPU_PRIVATE_SKIP_PAGE_UP=)
+ for k in $COHERENT_ENV; do env+=(--env "$k="); done
+ ctl set "$MACBOX_VM" "${env[@]}" >/dev/null
fi
}
@@ -169,7 +206,8 @@ MACBOX_RENDER_NODE=${node:-$MACBOX_RENDER_NODE}
MACBOX_DISK_CACHE=$MACBOX_DISK_CACHE
# auto: macbox's metal2vulkan tuning with the macbox build; on; off
MACBOX_GPU_TUNING=$MACBOX_GPU_TUNING
-# on: Coherent, zero-copy IOSurfaces (docs/performance.md). Experimental: one GPU hang with it on
+# auto (on with an Arrow Lake iGPU, where it runs day to day), on, off: Coherent, zero-copy
+# IOSurfaces, and the switches measured with it (docs/performance.md)
MACBOX_COHERENT=$MACBOX_COHERENT
# iOS Simulator pool: names are " ( )"
MACBOX_SIM_PREFIX=$MACBOX_SIM_PREFIX
@@ -542,7 +580,7 @@ PY
}
coherent_state() {
- if [ "$MACBOX_COHERENT" != on ] || ! tuning_on; then echo "off (MACBOX_COHERENT=on to try it)"
+ if ! coherent_on || ! tuning_on; then echo "off (MACBOX_COHERENT=on to turn it on)"
elif [ -e "$RUN/coherent/coherent.running" ] && ! vm_running; then
echo "on, but held off: the last coherent run did not end well (macbox coherent reset)"
else echo "on"; fi
@@ -601,7 +639,7 @@ Day to day:
macbox ssh [command]
macbox screenshot [out.png] | click X Y [right|double] | move X Y | scroll X Y N
macbox type TEXT|- | key COMBO... | wait SECONDS [out.png]
- macbox coherent [status|reset] Coherent's crash guard (MACBOX_COHERENT=on, experimental)
+ macbox coherent [status|reset] Coherent's crash guard (MACBOX_COHERENT=auto|on|off)
macbox backup
EOF
}
diff --git a/patches/README.md b/patches/README.md
index efc2de2..0e50ce0 100644
--- a/patches/README.md
+++ b/patches/README.md
@@ -3,15 +3,17 @@
`macbox build` applies these on top of the commits [versions.env](../versions.env) pins
(`container/build-reims.sh`). `macbox build --upstream` applies none of them.
-Together they are **cohwl**, the build that has run day to day since 2026-11-05 on an Intel Arrow
-Lake iGPU (Core Ultra 7 265, Mesa 26.2.4 ANV). Each series rebuilds that build's sources exactly:
-metal2vulkan 1502180e, QEMU 82cef5aac4, and Reims 1f87b16 without its local build wiring (the
-path of the metal2vulkan checkout, the `vendor/qemu` pointer). None of it is upstream yet.
+Together they are the build that has run day to day since 2026-11-09 on an Intel Arrow Lake iGPU
+(Core Ultra 7 265, Mesa 26.2.4 ANV), "production I". Each series rebuilds that build's sources
+exactly: metal2vulkan 7fee47f5, QEMU 3999026c68, and Reims 8dea1e59 without its local build wiring
+(the path of the metal2vulkan checkout, the `vendor/qemu` pointer) and without core dumps that had
+been committed by accident. Patches up to metal2vulkan 0034, Reims 0025 and QEMU 0009 are the
+earlier "cohwl" build (2026-11-05). None of it is upstream yet.
Most of the new code sits behind a switch and does nothing until it is set. What macbox turns on
is in [docs/performance.md](../docs/performance.md#gpu-tuning-switches).
-## metal2vulkan (on `development` at 0db5825a), 34 patches
+## metal2vulkan (on `development` at 0db5825a), 92 patches
| Patches | What they do |
|---|---|
@@ -25,8 +27,16 @@ is in [docs/performance.md](../docs/performance.md#gpu-tuning-switches).
| 0009–0012 `surface_lazy` | a large surface's optimal image is kept beside its pages, and its bytes are brought up to date only when something reads them, instead of after every pass |
| 0013–0024, 0027–0034 Coherent (`surface_coherent`) | trap-coherent surfaces: QEMU write-protects or poisons a surface's guest pages (patches/qemu), so the GPU's image can stay ahead of the pages and the guest CPU's first touch of a page syncs exactly that page. This removes the remaining copies between guest RAM and the GPU. The later patches fix ordering cases the lanes found: copies back and in around held batches, writes that reach a held batch past later command buffers, and counters for each fallback. |
| 0025, 0026 flat32 | a flat dispatch whose grid fits counts in 32 bits (64 bits past 2^32 threads). The simulator's 1206x2622 masked-blit kernel went from 4.85 to 1.13 ms. Always on. |
+| 0035–0039, 0041, 0049 grouped completion | batches complete in groups (live `group_batches`, up to 64; `group_deadline_us`), a held group goes when a host waits on a shared event or Coherent waits to settle, and `group_keep=0` / `group_events=0` port a fix that ended fence timeouts under several simulators. On with Coherent |
+| 0040 flat variant | the flat dispatch stays SIMD16 and counts a 1-D workgroup from its id. Always on |
+| 0042–0044 render lowering lanes | lowering render calls on a worker thread and on lanes per queue; off unless Reims sets `REIMS_VGPU_RENDER_LOWERING=worker`, which it refuses while the census runs |
+| 0045, 0046 recycled images | host-copied textures' images that the host writes too are recycled |
+| 0050, 0051, 0058–0061, 0069, 0070 surface fixes | `surface_lazy_max_texels`, `surface_twin_reader_first`, `surface_usage_shadow_image`, `surface_coherent_own_back`, `surface_lazy_open_ids`, `surface_twin_make_once` (a race between two textures over one surface: 91 → 100 fps over 12 boots). All but `surface_usage_shadow_image` on with Coherent |
+| 0085 `inline_lazy`, 0092 `inline_checks` | a lazy surface's first pass instance recorded inline; a batch's submission checks run in the scheduler's pass. On with Coherent |
+| 0062, 0068, 0076, 0077, 0080, 0081, 0083, 0084, 0086, 0090 experiments | `xr_unused_bits_off`, `surface_coherent_writer_wins`, `M2V_FLAT_TILE`, `shared_ccs`, `host_mutable`, `batch_end_light`, `view_render_direct`, `precise_barriers`, `checks_first`: live switches, all off. Most are in [docs/performance.md](../docs/performance.md#tried-no-gain) |
+| 0047, 0048, 0052–0057, 0063–0067, 0071–0075, 0078, 0079, 0082, 0086–0089, 0091 diagnostics | the pass timer's units and censuses, logs of views, twins, barriers and the scheduler, counters of why shadows copy back, and `M2V_PENDING_AUDIT` (command buffers begun while their submission is pending). Off unless their variable is set |
-## Reims vGPU (on 7198fe6), 25 patches
+## Reims vGPU (on 7198fe6), 33 patches
| Patches | What they do |
|---|---|
@@ -41,13 +51,20 @@ is in [docs/performance.md](../docs/performance.md#gpu-tuning-switches).
| 0013 `REIMS_VGPU_PRIVATE_SKIP_PAGE_UP` | skips a new Private texture's first page-up, which nothing can read; macbox sets it |
| 0015, 0017 NVMe boot tests | coherent pages through NVMe DMA, in the census's boot tests |
| 0025 upstream f6b7e927, video acceleration off | upstream's own commit, cherry-picked: `reims-ctl set --video-acceleration=false` leaves out the VideoToolbox and M2 scaler devices. macbox sets it, so the VM's devices are the ones it was measured with. |
+| 0026 `REIMS_VGPU_PIPELINE_EXEC` | a FIFO's execs pipelined, up to 8 in flight; on with Coherent while the named file exists |
+| 0027 `REIMS_VGPU_GROUPED=1` | grouped completion (metal2vulkan 0035 onwards); on with Coherent |
+| 0028 `REIMS_VGPU_IRQ_MODERATE` | one interrupt raise outstanding at a time, a held one goes after 2 ms; on with Coherent while the named file exists |
+| 0029 render lowering and multi-queue tests | `REIMS_VGPU_RENDER_LOWERING` (off) and regression tests for several queues |
+| 0030 `REIMS_VGPU_PAGED_BUFFER_BY_PAGES` | finds kept paged buffers by their guest pages; off |
+| 0031–0033 staged page-ups | `REIMS_VGPU_STAGED_PAGE_UP`, `REIMS_VGPU_STAGED_ZERO`: a new texture's first page-up copies its pages into a staging buffer (one copy per run) when no live view covers them, and pages of zeros write nothing. Before, each page run took its own mapping: 55k a second and a storm of TLB shootdowns; the simulator went from 89 to 101 fps. On with Coherent |
-## QEMU (`vendor/qemu` at bd95509, github.com/steelbrain/qemu-reims-vgpu), 9 patches
+## QEMU (`vendor/qemu` at bd95509, github.com/steelbrain/qemu-reims-vgpu), 13 patches
| Patches | What they do |
|---|---|
| 0001–0003, 0006–0009 the census | memslots move to a second mapping of guest RAM that only KVM uses, and userfaultfd markers there report the guest CPU's touches of tracked pages (`UFFD_USER_MODE_ONLY`: no capability or `/dev/userfaultfd` needed). QEMU's own loads, stores and DMA reach it too. Off unless `REIMS_VGPU_CENSUS` is set. |
| 0004, 0005 coherent pages | with `REIMS_VGPU_COHERENT=1` the same markers serve metal2vulkan's trap-coherent surfaces. A run that doesn't end well leaves `coherent.running` in the census directory, and every later start boots without coherent pages until it's removed (`macbox coherent reset`), so a fault there costs one crash, not a crash loop. |
+| 0010–0013 KVM shortcuts for the GPU device | `x-irqfd` (interrupts through a KVM irqfd), `x-halt-poll-ns`, `x-ioeventfd` (doorbells through KVM ioeventfds): device properties, all off unless set |
## Licenses
diff --git a/patches/metal2vulkan/0035-group_batches-live-switch-groups-up-to-16-batches.patch b/patches/metal2vulkan/0035-group_batches-live-switch-groups-up-to-16-batches.patch
new file mode 100644
index 0000000..f269f60
--- /dev/null
+++ b/patches/metal2vulkan/0035-group_batches-live-switch-groups-up-to-16-batches.patch
@@ -0,0 +1,124 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Thu, 5 Nov 2026 15:26:13 +0000
+Subject: [PATCH 35/92] group_batches live switch, groups up to 16 batches
+
+The batches a group holds before it goes are the live switch group_batches (default 4, as before;
+at most 16, the bound of the submission arrays). Lab on the Arrow Lake iGPU (Mesa 26.2.4, i915):
+each kernel submission a merge saves is ~50 us of render-engine time in the Simulator's frame shape.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/command_buffer/group.rs | 25 +++++++++++++++----
+ .../src/command_buffer/mod.rs | 2 +-
+ .../metal2vulkan-runtime/src/scheduler/mod.rs | 6 ++---
+ 3 files changed, 24 insertions(+), 9 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/group.rs b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+index dc2c7a37..a87bd837 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/group.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+@@ -94,9 +94,21 @@ use std::collections::BTreeSet;
+ use std::sync::atomic::Ordering;
+ use std::sync::Arc;
+
+-/// The most batches one kernel submission holds: the first is seen complete late by the GPU time
+-/// of at most this many less one.
+-pub(crate) const GROUP_BATCHES: usize = 4;
++/// The most batches one kernel submission may hold, the bound of the arrays below: the first is
++/// seen complete late by the GPU time of at most this many less one. LOCAL (Atlas): a group holds
++/// [`group_batches`] of them, the live switch `group_batches` (default 4, the upstream bound).
++pub(crate) const GROUP_BATCHES: usize = 16;
++
++/// LOCAL (Atlas): the batches a group holds before it goes at once, the live switch
++/// `group_batches` (`live.rs`), 4 where unset, at least 1 and at most [`GROUP_BATCHES`]. Measured
++/// on the Arrow Lake iGPU (Mesa 26.2.4, i915): each kernel submission a merge saves is about 50 us
++/// of render-engine time in a Simulator frame's shape (DEEP-GPU lane, 2026-11-05).
++pub(crate) fn group_batches() -> usize {
++ crate::live::get("group_batches")
++ .and_then(|value| value.parse::().ok())
++ .unwrap_or(4)
++ .clamp(1, GROUP_BATCHES)
++}
+
+ /// The most `VkSubmitInfo`s a batch names: its work's and its finale's (`submit.rs`).
+ const BATCH_INFOS: usize = 2;
+@@ -255,6 +267,8 @@ struct Member {
+ #[derive(Default)]
+ pub(crate) struct Group {
+ queue: usize,
++ /// LOCAL (Atlas): the batches it holds before it goes, [`group_batches`] as it opened.
++ cap: usize,
+ members: Vec,
+ /// It stayed held past a pass for the work its queue ran ([`keeps`](Group::keeps)).
+ kept: bool,
+@@ -305,7 +319,7 @@ impl Group {
+ /// first: the group is empty, or the batch may wait in it (`joins`) on its queue with room.
+ pub(crate) fn admits(&self, queue: usize, joins: bool) -> bool {
+ self.members.is_empty()
+- || (joins && self.queue == queue && self.members.len() < GROUP_BATCHES)
++ || (joins && self.queue == queue && self.members.len() < self.cap)
+ }
+
+ /// Whether a batch held signals the event of `semaphore` to `index` or above: only the group's
+@@ -319,7 +333,7 @@ impl Group {
+ /// may join, found with room, goes with at most a batch less held, so no submission holds
+ /// more.
+ pub(crate) fn full(&self) -> bool {
+- self.members.len() >= GROUP_BATCHES
++ self.members.len() >= self.cap.max(1)
+ }
+
+ /// A batch on `VkQueue` `queue` is held, before its submission changes the scheduler's
+@@ -328,6 +342,7 @@ impl Group {
+ pub(crate) fn open(&mut self, queue: usize, waited: &[u64]) {
+ if self.members.is_empty() {
+ self.queue = queue;
++ self.cap = group_batches();
+ self.waited.clear();
+ self.waited.extend_from_slice(waited);
+ }
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+index e553cecf..c660f223 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+@@ -55,7 +55,7 @@ pub(super) use first_submission::{NotedTable, ReplayTable};
+ /// (`tests::batches::only_drivers_measured_to_merge_their_submissions_group_their_batches`).
+ #[cfg(test)]
+ pub(crate) use group::merges_submissions;
+-pub(super) use group::{Group, GroupEnd, GROUP_BATCHES};
++pub(super) use group::{group_batches, Group, GroupEnd};
+ use rebound_use::{ReboundUse, Unlogged};
+ pub(super) use submit::{BatchLists, Submitting};
+
+diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs
+index c750a0ff..ff6f6367 100644
+--- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs
++++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs
+@@ -144,7 +144,7 @@ use super::command_buffer::gate::Hold;
+ use super::command_buffer::kept_barriers::KeptBarriers;
+ use super::command_buffer::BatchLists;
+ use super::command_buffer::CommandBufferShared;
+-use super::command_buffer::{Group, GroupEnd, Submitting, GROUP_BATCHES};
++use super::command_buffer::{group_batches, Group, GroupEnd, Submitting};
+ use super::device::functions::Functions;
+ use super::device::lock;
+ use super::error::{CommandBufferError, Error, MemoryKind};
+@@ -1689,7 +1689,7 @@ type Work = (Hold, usize);
+ /// Where the line's batches may go in one kernel submission (`command_buffer/group.rs`), the
+ /// batches right behind a head that goes (its checks in `left` or none due, otherwise ready, its
+ /// events' values reached on the device or by the host) are looked at too, at most
+-/// [`GROUP_BATCHES`] less one and none committed after another line's batch
++/// [`group_batches`] less one and none committed after another line's batch
+ /// ([`Order::leading_mut`]), each that goes taking its checks to `left` likewise: so the next pass
+ /// finds them ready together. Each check still runs in commit order before its own batch's
+ /// submission, within the pass before it, where a head's alone runs after the batch before it
+@@ -1697,7 +1697,7 @@ type Work = (Hold, usize);
+ fn check_heads(state: &mut State, behind: &[u64], left: &mut Left, awaits: &Awaits) -> bool {
+ let State { order, binary, .. } = state;
+ let mut landing = false;
+- order.leading_mut(behind, GROUP_BATCHES - 1, |held, head| {
++ order.leading_mut(behind, group_batches() - 1, |held, head| {
+ let otherwise_ready = binary.ready(&held.binary_needs)
+ && !(held.segments && held.buffer.needs_host_step(held.index));
+ let due = held.checked
diff --git a/patches/metal2vulkan/0036-no-group-kept-while-Coherent-s-wait_settled-waits-Ho.patch b/patches/metal2vulkan/0036-no-group-kept-while-Coherent-s-wait_settled-waits-Ho.patch
new file mode 100644
index 0000000..832481a
--- /dev/null
+++ b/patches/metal2vulkan/0036-no-group-kept-while-Coherent-s-wait_settled-waits-Ho.patch
@@ -0,0 +1,127 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Thu, 5 Nov 2026 16:05:56 +0000
+Subject: [PATCH 36/92] no group kept while Coherent's wait_settled waits
+ (HostWait)
+
+VM-A review of grouped submissions: wait_settled is bounded (50 ms) and counts overwrite_risk on
+timeout, so a record held in a kept group must not make it wait. While a host waiter waits,
+Group::keeps keeps nothing, and the waiter wakes the scheduler to send a group kept before.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/command_buffer/group.rs | 32 ++++++++++++++++++-
+ .../src/command_buffer/mod.rs | 1 +
+ .../src/shadow_coherent.rs | 13 ++++++++
+ .../metal2vulkan-runtime/src/shadow_lazy.rs | 5 +++
+ 4 files changed, 50 insertions(+), 1 deletion(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/group.rs b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+index a87bd837..179ed0f6 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/group.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+@@ -181,6 +181,34 @@ impl CommandBufferShared {
+ }
+ }
+
++/// LOCAL (Atlas, DEEP-GPU): how many host waiters outside a command buffer's own wait (Coherent's
++/// `wait_settled`, which waits for the GPU writes of running command buffers over a surface's
++/// pages within a bounded time) wait now. While any waits, no group is kept ([`Group::keeps`]),
++/// so a record held in a group never makes such a wait time out; [`HostWait`] wakes each
++/// scheduler it is given as it begins, which then sends a group kept before.
++static HOST_WAITERS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
++
++/// LOCAL (Atlas, DEEP-GPU): a host waiter of [`HOST_WAITERS`], counted until dropped.
++pub(crate) struct HostWait(());
++
++impl HostWait {
++ /// Begins a host wait: no group is kept until it ends, and `device`'s scheduler is woken to
++ /// send one kept now.
++ pub(crate) fn begin(device: Option<&Device>) -> HostWait {
++ HOST_WAITERS.fetch_add(1, Ordering::SeqCst);
++ if let Some(device) = device {
++ device.shared().scheduler.wake();
++ }
++ HostWait(())
++ }
++}
++
++impl Drop for HostWait {
++ fn drop(&mut self) {
++ HOST_WAITERS.fetch_sub(1, Ordering::SeqCst);
++ }
++}
++
+ /// A command buffer's `group_hold` bit: a batch of it is held in the scheduler's group.
+ const IN_GROUP: u8 = 1;
+
+@@ -401,7 +429,9 @@ impl Group {
+ return None;
+ }
+ let counts = &device.shared().counts;
+- if (self.members.iter()).any(|member| member.submission.buffer().is_waited_for()) {
++ if HOST_WAITERS.load(Ordering::SeqCst) != 0
++ || (self.members.iter()).any(|member| member.submission.buffer().is_waited_for())
++ {
+ if self.kept {
+ counts.group_sent_for_wait();
+ }
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+index c660f223..18824b72 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+@@ -56,6 +56,7 @@ pub(super) use first_submission::{NotedTable, ReplayTable};
+ #[cfg(test)]
+ pub(crate) use group::merges_submissions;
+ pub(super) use group::{group_batches, Group, GroupEnd};
++pub(crate) use group::HostWait; // LOCAL (Atlas, DEEP-GPU)
+ use rebound_use::{ReboundUse, Unlogged};
+ pub(super) use submit::{BatchLists, Submitting};
+
+diff --git a/crates/metal2vulkan-runtime/src/shadow_coherent.rs b/crates/metal2vulkan-runtime/src/shadow_coherent.rs
+index 7cbcbee4..dee6bf93 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_coherent.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_coherent.rs
+@@ -1204,6 +1204,10 @@ impl Coherent {
+ skip_held: bool,
+ ) -> (MutexGuard<'a, State>, bool) {
+ let until = Instant::now() + Duration::from_millis(knob("surface_coherent_wait_ms", DEFAULT_WAIT_MS));
++ // LOCAL (Atlas, DEEP-GPU): while it waits, no submission group is kept, so a record held
++ // in one goes now and is seen complete at its own end, not after later batches
++ // (`command_buffer::HostWait`, VM-A's review of grouped submissions).
++ let mut host_wait = None;
+ loop {
+ // With `skip_held`, a record held for an event is not waited for: on the command
+ // thread (an encoder's take, a reader's copy back) its signal comes from the guest
+@@ -1220,6 +1224,15 @@ impl Coherent {
+ if left.is_zero() {
+ return (state, false);
+ }
++ if host_wait.is_none() {
++ // The scheduler is woken without this surface's lock held (its submissions take
++ // it, `before_flush`), and what is busy is looked at again after.
++ drop(state);
++ let lazy = self.lazy.upgrade();
++ host_wait = Some(super::command_buffer::HostWait::begin(lazy.as_deref().and_then(Lazy::device)));
++ state = self.lock();
++ continue;
++ }
+ let (guard, _) = self.moved.wait_timeout(state, left).unwrap_or_else(|e| e.into_inner());
+ state = guard;
+ }
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index f0cce7be..bc393926 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -1117,6 +1117,11 @@ pub(crate) struct Lazy {
+ }
+
+ impl Lazy {
++ /// LOCAL (Atlas, DEEP-GPU): the [`Device`] its queue comes from.
++ pub(crate) fn device(&self) -> Option<&Device> {
++ self.device.downcast_ref::()
++ }
++
+ /// The state of a new shadow of `size` and `texels` texels of `device` with `surface` as its
+ /// backing over the host addresses `pages`, where the switch takes it.
+ pub(super) fn of(
diff --git a/patches/metal2vulkan/0037-group-cap-64-live-group_batches-up-to-64-hold-delay-.patch b/patches/metal2vulkan/0037-group-cap-64-live-group_batches-up-to-64-hold-delay-.patch
new file mode 100644
index 0000000..a5b7171
--- /dev/null
+++ b/patches/metal2vulkan/0037-group-cap-64-live-group_batches-up-to-64-hold-delay-.patch
@@ -0,0 +1,114 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Thu, 5 Nov 2026 17:20:37 +0000
+Subject: [PATCH 37/92] group cap 64 (live group_batches up to 64), hold-delay
+ stats line every 10 s
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/command_buffer/group.rs | 64 ++++++++++++++++++-
+ 1 file changed, 63 insertions(+), 1 deletion(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/group.rs b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+index 179ed0f6..781237a2 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/group.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+@@ -97,7 +97,7 @@ use std::sync::Arc;
+ /// The most batches one kernel submission may hold, the bound of the arrays below: the first is
+ /// seen complete late by the GPU time of at most this many less one. LOCAL (Atlas): a group holds
+ /// [`group_batches`] of them, the live switch `group_batches` (default 4, the upstream bound).
+-pub(crate) const GROUP_BATCHES: usize = 16;
++pub(crate) const GROUP_BATCHES: usize = 64;
+
+ /// LOCAL (Atlas): the batches a group holds before it goes at once, the live switch
+ /// `group_batches` (`live.rs`), 4 where unset, at least 1 and at most [`GROUP_BATCHES`]. Measured
+@@ -181,6 +181,64 @@ impl CommandBufferShared {
+ }
+ }
+
++/// LOCAL (Atlas, DEEP-GPU): what the groups held, for the VM A/B of grouped submissions: each
++/// group's batches and how long each batch waited in its group before the group's
++/// `vkQueueSubmit` (its added queueing delay), written to stderr at most every 10 s as one
++/// `m2v groups:` line (totals since the process began, and the window's histogram).
++struct HoldStats {
++ groups: std::sync::atomic::AtomicU64,
++ batches: std::sync::atomic::AtomicU64,
++ held_ns: std::sync::atomic::AtomicU64,
++ max_ns: std::sync::atomic::AtomicU64,
++ /// Batches by their wait: < 20 us, < 100 us, < 500 us, < 2 ms, < 8 ms, >= 8 ms.
++ buckets: [std::sync::atomic::AtomicU64; 6],
++ sizes: [std::sync::atomic::AtomicU64; 6],
++ last: std::sync::atomic::AtomicU64,
++}
++
++static HOLD_STATS: HoldStats = HoldStats {
++ groups: std::sync::atomic::AtomicU64::new(0),
++ batches: std::sync::atomic::AtomicU64::new(0),
++ held_ns: std::sync::atomic::AtomicU64::new(0),
++ max_ns: std::sync::atomic::AtomicU64::new(0),
++ buckets: [const { std::sync::atomic::AtomicU64::new(0) }; 6],
++ sizes: [const { std::sync::atomic::AtomicU64::new(0) }; 6],
++ last: std::sync::atomic::AtomicU64::new(0),
++};
++
++impl HoldStats {
++ fn group(&self, now: u64, waits: impl Iterator- ) {
++ let mut n = 0u64;
++ for wait in waits {
++ n += 1;
++ self.held_ns.fetch_add(wait, Ordering::Relaxed);
++ self.max_ns.fetch_max(wait, Ordering::Relaxed);
++ let at = [20_000, 100_000, 500_000, 2_000_000, 8_000_000].iter().take_while(|&&b| wait >= b).count();
++ self.buckets[at].fetch_add(1, Ordering::Relaxed);
++ }
++ self.groups.fetch_add(1, Ordering::Relaxed);
++ self.batches.fetch_add(n, Ordering::Relaxed);
++ let size = [2, 4, 8, 16, 32].iter().take_while(|&&b| n >= b).count();
++ self.sizes[size].fetch_add(1, Ordering::Relaxed);
++ let last = self.last.load(Ordering::Relaxed);
++ if now.saturating_sub(last) >= 10_000_000_000
++ && self.last.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_ok()
++ {
++ let take = |a: &std::sync::atomic::AtomicU64| a.swap(0, Ordering::Relaxed);
++ let (g, b, h, m) = (take(&self.groups), take(&self.batches), take(&self.held_ns), take(&self.max_ns));
++ let w: Vec
= self.buckets.iter().map(take).collect();
++ let z: Vec = self.sizes.iter().map(take).collect();
++ let line = format!(
++ "m2v groups: {g} submits of {b} batches ({:.2} a submit), wait mean {:.1} us max {:.1} us; \
++ waits <20us {} <100us {} <500us {} <2ms {} <8ms {} >=8ms {}; sizes 1 {} 2-3 {} 4-7 {} 8-15 {} 16-31 {} 32+ {}; cap {}\n",
++ b as f64 / g.max(1) as f64, h as f64 / b.max(1) as f64 / 1e3, m as f64 / 1e3,
++ w[0], w[1], w[2], w[3], w[4], w[5], z[0], z[1], z[2], z[3], z[4], z[5], group_batches(),
++ );
++ let _ = std::io::Write::write_all(&mut std::io::stderr(), line.as_bytes());
++ }
++ }
++}
++
+ /// LOCAL (Atlas, DEEP-GPU): how many host waiters outside a command buffer's own wait (Coherent's
+ /// `wait_settled`, which waits for the GPU writes of running command buffers over a surface's
+ /// pages within a bounded time) wait now. While any waits, no group is kept ([`Group::keeps`]),
+@@ -288,6 +346,8 @@ struct Member {
+ infos: Vec,
+ buffers: usize,
+ submission: Submission,
++ /// LOCAL (Atlas, DEEP-GPU): when it was held (`gpu_time::host_nanos`), for [`HoldStats`].
++ held_at: u64,
+ }
+
+ /// The batches held for one kernel submission on one `VkQueue` (the module docs), in the
+@@ -399,6 +459,7 @@ impl Group {
+ infos: held,
+ buffers,
+ submission,
++ held_at: gpu_time::host_nanos(),
+ });
+ }
+
+@@ -552,6 +613,7 @@ impl Group {
+ let outcome = match submitted {
+ Ok(()) => {
+ let now = gpu_time::host_nanos();
++ HOLD_STATS.group(now, (self.members.iter()).map(|member| now.saturating_sub(member.held_at)));
+ for member in self.members.drain(..) {
+ self.spare.push(member.infos);
+ if member.submission.schedules() && !member.submission.scheduled() {
diff --git a/patches/metal2vulkan/0038-a-shared-event-s-host-wait-sends-held-groups-HostWai.patch b/patches/metal2vulkan/0038-a-shared-event-s-host-wait-sends-held-groups-HostWai.patch
new file mode 100644
index 0000000..3c9a71b
--- /dev/null
+++ b/patches/metal2vulkan/0038-a-shared-event-s-host-wait-sends-held-groups-HostWai.patch
@@ -0,0 +1,37 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Thu, 5 Nov 2026 17:22:17 +0000
+Subject: [PATCH 38/92] a shared event's host wait sends held groups (HostWait)
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/event.rs | 9 +++++++++
+ 1 file changed, 9 insertions(+)
+
+diff --git a/crates/metal2vulkan-runtime/src/event.rs b/crates/metal2vulkan-runtime/src/event.rs
+index 0e8575be..10174929 100644
+--- a/crates/metal2vulkan-runtime/src/event.rs
++++ b/crates/metal2vulkan-runtime/src/event.rs
+@@ -302,6 +302,7 @@ impl EventShared {
+ /// counter raises it any more (`exit_guard`).
+ pub(super) fn wait_until(self: &Arc, value: u64, timeout: Duration) -> bool {
+ let deadline = Instant::now().checked_add(timeout);
++ let mut host_wait = None;
+ loop {
+ if self.value() >= value {
+ return true;
+@@ -316,6 +317,14 @@ impl EventShared {
+ if left.is_zero() || exit_guard::closed() {
+ return false;
+ }
++ // LOCAL (Atlas, DEEP-GPU): a host thread blocks on the value: no submission group
++ // is kept while it waits, so a held batch that signals it goes now
++ // (`command_buffer::HostWait`). Taken once, without the event's lock.
++ if host_wait.is_none() {
++ drop(state);
++ host_wait = Some(super::command_buffer::HostWait::begin(Some(&self.device)));
++ continue;
++ }
+ state.parked += 1;
+ let mut state = self
+ .changed
diff --git a/patches/metal2vulkan/0039-live-group_deadline_us-a-group-held-past-it-goes-at-.patch b/patches/metal2vulkan/0039-live-group_deadline_us-a-group-held-past-it-goes-at-.patch
new file mode 100644
index 0000000..7024b7d
--- /dev/null
+++ b/patches/metal2vulkan/0039-live-group_deadline_us-a-group-held-past-it-goes-at-.patch
@@ -0,0 +1,29 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Thu, 5 Nov 2026 17:23:21 +0000
+Subject: [PATCH 39/92] live group_deadline_us: a group held past it goes at
+ the next pass
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/command_buffer/group.rs | 7 +++++++
+ 1 file changed, 7 insertions(+)
+
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/group.rs b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+index 781237a2..626669dd 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/group.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+@@ -498,6 +498,13 @@ impl Group {
+ }
+ return None;
+ }
++ // LOCAL (Atlas, DEEP-GPU): live `group_deadline_us` (0 or unset: none): a group whose
++ // first batch was held longer than that goes at the scheduler's next pass, so no batch
++ // waits past the deadline for a group to fill (the guest sees its completion later).
++ let deadline_us = crate::live::get("group_deadline_us").and_then(|v| v.parse::().ok()).unwrap_or(0);
++ if deadline_us != 0 && gpu_time::host_nanos().saturating_sub(first.held_at) >= deadline_us * 1000 {
++ return None;
++ }
+ let value = device.shared().queues[self.queue].pending_beyond_one()?;
+ if !self.kept {
+ self.kept = true;
diff --git a/patches/metal2vulkan/0040-the-flat-variant-stays-SIMD16-and-counts-a-1-D-workg.patch b/patches/metal2vulkan/0040-the-flat-variant-stays-SIMD16-and-counts-a-1-D-workg.patch
new file mode 100644
index 0000000..5e1fa90
--- /dev/null
+++ b/patches/metal2vulkan/0040-the-flat-variant-stays-SIMD16-and-counts-a-1-D-workg.patch
@@ -0,0 +1,483 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Tue, 3 Nov 2026 14:36:42 +0000
+Subject: [PATCH 40/92] the flat variant stays SIMD16 and counts a 1-D
+ workgroup from its id
+
+The flat variant's index math gets three arms, each chosen by workgroup-uniform values:
+a workgroup of the first row and layer whose last index is below 2^32 counts in 32 bits
+from wx*N (no NumWorkgroups read, which ANV merges per invocation); any other workgroup of
+a dispatch of at most 2^32 invocations counts in 32 bits as before; past that the 64-bit
+index is divided by a compact 64/32 restoring loop instead of 64-bit OpUDiv/OpUMod. The
+position is derived once, for the guard and thread_position_in_grid.
+
+On Arrow Lake (Mesa 26.2) the four lowered 64-bit divisions in the unexecuted arm made
+the Simulator's masked blit compile at SIMD8 (2801 instructions); it now compiles at
+SIMD16 (346). Apple's metallib through the runtime, 10 paired rounds against 5f6f2c9f in
+both orders: p50 1.88 -> 1.54 ms, min 1.50 -> 1.40 ms, faster in 10 of 10, outputs
+byte-identical. The bare kernel in the lab shows no difference (p50 1.17 vs 1.21 ms,
+inside the spread).
+
+Tests: interpreter test of the 64/32 division over edge dividends and divisors; GPU lane
+for a dispatch past 2^32 threads in 105-thread groups, where the 32- to 64-bit switch
+lands inside a row.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/runtime_lane/indirect_dispatches.rs | 17 +-
+ crates/metal2vulkan/src/lower/dispatch.rs | 195 ++++++++++++++----
+ .../metal2vulkan/src/lower/dispatch/tests.rs | 136 ++++++++++++
+ 3 files changed, 312 insertions(+), 36 deletions(-)
+
+diff --git a/crates/metal2vulkan-validation/src/runtime_lane/indirect_dispatches.rs b/crates/metal2vulkan-validation/src/runtime_lane/indirect_dispatches.rs
+index db6faaee..9dbee7ec 100644
+--- a/crates/metal2vulkan-validation/src/runtime_lane/indirect_dispatches.rs
++++ b/crates/metal2vulkan-validation/src/runtime_lane/indirect_dispatches.rs
+@@ -817,6 +817,22 @@ done:
+ /// dispatch fits it.
+ #[test]
+ fn a_direct_dispatch_past_2_32_threads_keeps_the_flat_variant_s_64_bit_count() {
++ edges_counted_once([65_536, 65_601, 1], [32, 32, 1]);
++}
++
++/// The flat variant chooses its arm per workgroup: a workgroup whose last index `wx·N + N - 1`
++/// is below 2^32 counts in 32 bits, a later one of the same dispatch in 64 bits. With a
++/// threadgroup of 105 threads (7 x 5 x 3, not a power of two) the first 64-bit workgroup starts
++/// inside a row, so the last column and the last row are each counted once only where both arms
++/// meet exactly there.
++#[test]
++fn a_flat_dispatch_switches_to_its_64_bit_count_at_the_workgroup_that_passes_2_32() {
++ edges_counted_once([65_536, 65_601, 1], [7, 5, 3]);
++}
++
++/// Dispatch [`FLAT_EDGES`] over `grid` (more than 2^32 threads) in threadgroups of `group`: it
++/// runs on the flat variant and marks every thread of the last column and the last row once.
++fn edges_counted_once(grid: [u32; 3], group: [u32; 3]) {
+ on_device(|device, messages| {
+ let library = device
+ .new_library_with_air(&llvm_assemble_text(FLAT_EDGES).unwrap())
+@@ -830,7 +846,6 @@ fn a_direct_dispatch_past_2_32_threads_keeps_the_flat_variant_s_64_bit_count() {
+ &PipelineOptions::default(),
+ )
+ .unwrap();
+- let (grid, group) = ([65_536u32, 65_601, 1], [32u32, 32, 1]);
+ assert!(u64::from(grid[0]) * u64::from(grid[1]) > 1 << 32);
+ let [gx, gy, _] = grid;
+ let slots = u64::from(gy + gx);
+diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs
+index 6a89003d..e49b0bc2 100644
+--- a/crates/metal2vulkan/src/lower/dispatch.rs
++++ b/crates/metal2vulkan/src/lower/dispatch.rs
+@@ -598,13 +598,19 @@ pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<
+ let Some(plan) = cx.plan.dispatch.as_ref() else {
+ return Ok(());
+ };
+- // A flat grid's invocation past the grid's last thread returns before the body.
++ // A flat grid's invocation past the grid's last thread returns before the body. Its position
++ // is derived here once, with the test, and is the `thread_position_in_grid` every parameter
++ // reads: a second derivation would repeat the divisions in a construct of its own, which the
++ // driver does not merge with this one.
++ let mut flat_position = None;
+ if plan.flat_grid {
+ let decl: &crate::lower::emit::Declared = cx.decl;
+ let Some(decl) = decl.families.dispatch.kernel.as_ref() else {
+ return Err(cx.fail("a flat grid without its kernel's declarations"));
+ };
+- let (_, inside) = decl.flat(fb, &mut |fb| cx.push_field(fb, PushField::DispatchRegion))?;
++ let (pos, inside) =
++ decl.flat(fb, &mut |fb| cx.push_field(fb, PushField::DispatchRegion))?;
++ flat_position = Some(pos);
+ let past = fb.unary(UnOp::LogicalNot, inside)?;
+ let leave: ArmFn<'_, ()> = Box::new(|fb, _| {
+ fb.ret(None)?;
+@@ -635,7 +641,7 @@ pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<
+ else {
+ return Err(cx.fail(format!("dispatch parameter {} is out of range", p.param)));
+ };
+- let x = param_value(cx, fb, b)?;
++ let x = param_value(cx, fb, b, flat_position)?;
+ cx.hold(v, x);
+ }
+ Ok(())
+@@ -647,6 +653,7 @@ fn param_value(
+ cx: &mut EmitCx<'_>,
+ fb: &mut FunctionBuilder<'_>,
+ b: &ParamBinding,
++ flat_position: Option,
+ ) -> BResult {
+ let (plan, decl): (&Plan, &crate::lower::emit::Declared) = (cx.plan, cx.decl);
+ let planned = plan
+@@ -667,9 +674,12 @@ fn param_value(
+ {
+ return Err(cx.fail(format!("parameter {} is not a flat grid's", b.param)));
+ }
+- let raw = decl.value(fb, p.builtin, &mut |fb| {
+- cx.push_field(fb, PushField::DispatchRegion)
+- })?;
++ let raw = match (p.builtin, flat_position) {
++ (KernelBuiltin::ThreadPositionInGrid, Some(pos)) if decl.flat_grid => pos,
++ _ => decl.value(fb, p.builtin, &mut |fb| {
++ cx.push_field(fb, PushField::DispatchRegion)
++ })?,
++ };
+ match project(fb, raw, p.projection)? {
+ Some(x) => Ok(x),
+ None => Err(cx.fail(format!("parameter {} has no projection", b.param))),
+@@ -1270,12 +1280,21 @@ impl KernelDecl {
+ /// fastest. Inside the grid each axis's position is below its size, so it fits its `u32`;
+ /// past it the position is unused.
+ ///
+- /// The count is exact in 32 bits when the dispatch has at most 2^32 invocations
+- /// (`nx · ny · nz · N <= 2^32`, so every index is below 2^32): then the index and its
+- /// divisions are 32-bit; otherwise 64-bit. The test reads only dispatch-uniform values, so
+- /// every invocation takes the same arm. Devices without a 64-bit divider (Intel's) lower each
+- /// 64-bit division to a long software sequence: on Arrow Lake the Simulator's 1206 x 2622
+- /// masked blit ran 4.85 ms with the 64-bit form and 1.13 ms with the 32-bit one.
++ /// Three arms, each chosen by values uniform over the workgroup, so a workgroup takes one:
++ ///
++ /// - a workgroup with `wy = wz = 0` (group `wx`) whose last index `wx·N + N - 1` is below
++ /// 2^32 counts in 32 bits from `wx·N`, its test and start read from the workgroup's id and
++ /// `N` alone (every workgroup of a dispatch whose groups fit along `x`, as the Simulator's);
++ /// - any other, of a dispatch of at most 2^32 invocations (`nx · ny · nz · N <= 2^32`, so
++ /// every index is below 2^32), counts in 32 bits from `((wz · ny + wy) · nx + wx) · N`;
++ /// - past that the index is 64-bit and divided by [`Self::divmod_64_by_32`].
++ ///
++ /// Devices without a 64-bit divider (Intel's) lower each 64-bit division to a long software
++ /// sequence: on Arrow Lake the Simulator's 1206 x 2622 masked blit ran 4.85 ms with the
++ /// 64-bit form and 1.13 ms with the 32-bit one. Mesa 26.2 also compiled the whole kernel at
++ /// SIMD8 while 64-bit `OpUDiv`/`OpUMod` sat in its last arm, and per invocation tested and
++ /// counted with `NumWorkgroups`, which ANV merges from two sources per invocation: the first
++ /// arm reads neither.
+ fn flat(
+ &self,
+ fb: &mut FunctionBuilder<'_>,
+@@ -1306,24 +1325,36 @@ impl KernelDecl {
+ let [wx, wy, wz] = part(fb, wg)?;
+ let [nx, ny, nz] = part(fb, groups)?;
+ let [gx, gy, gz] = part(fb, grid)?;
+- // Whether every invocation's index fits in 32 bits: `a = nx·ny`, `b = a·nz`, `c = b·N`
+- // in 64 bits, each at most 2^32. While `a` and `b` are, the next product cannot wrap
+- // (`nz`, `N` < 2^32); a product past a failed test is not read.
+ let w = |fb: &mut FunctionBuilder<'_>, v: SValue| fb.convert(ConvOp::UConvert, v, u64_);
+ let limit = fb.module().constant(Constant::Scalar {
+ ty: u64_,
+ bits: ConstBits(1 << 32),
+ })?;
+ let limit = fb.module().const_value(limit)?;
+- let (nx64, ny64, nz64, n64) = (w(fb, nx)?, w(fb, ny)?, w(fb, nz)?, w(fb, n)?);
+- let a = fb.binary(BinOp::IMul, nx64, ny64)?;
+- let b = fb.binary(BinOp::IMul, a, nz64)?;
+- let c = fb.binary(BinOp::IMul, b, n64)?;
+- let fa = fb.binary(BinOp::ULessThanEqual, a, limit)?;
+- let fbb = fb.binary(BinOp::ULessThanEqual, b, limit)?;
+- let fc = fb.binary(BinOp::ULessThanEqual, c, limit)?;
+- let fits = fb.binary(BinOp::LogicalAnd, fa, fbb)?;
+- let fits = fb.binary(BinOp::LogicalAnd, fits, fc)?;
++ // A workgroup of the first row and layer (`wy = wz = 0`, every workgroup of a dispatch
++ // whose groups fit along `x`) is group `wx`, whatever the counts: when its last index
++ // `wx·N + N - 1` is below 2^32 its indices are counted in 32 bits from `wx·N`. The test
++ // and `wx·N` read only the workgroup's id and the threadgroup size, values the driver
++ // holds once per hardware thread, not per invocation; the counts (`NumWorkgroups`) a
++ // driver may merge per invocation are read only past it.
++ let (wx64, n64) = (w(fb, wx)?, w(fb, n)?);
++ let row = fb.binary(BinOp::BitwiseOr, wy, wz)?;
++ let zero = Self::k(fb, 0)?;
++ let first_row = fb.binary(BinOp::IEqual, row, zero)?;
++ let start = fb.binary(BinOp::IMul, wx64, n64)?;
++ let end = fb.binary(BinOp::IAdd, start, n64)?;
++ let below = fb.binary(BinOp::ULessThanEqual, end, limit)?;
++ let row_fits = fb.binary(BinOp::LogicalAnd, first_row, below)?;
++ let first: ArmFn<'_, ()> = Box::new(move |fb, _| {
++ let first = fb.convert(ConvOp::UConvert, start, u32_)?;
++ let index = fb.binary(BinOp::IAdd, first, lin)?;
++ let x = fb.binary(BinOp::UMod, index, gx)?;
++ let row = fb.binary(BinOp::UDiv, index, gx)?;
++ let y = fb.binary(BinOp::UMod, row, gy)?;
++ let z = fb.binary(BinOp::UDiv, row, gy)?;
++ let inside = fb.binary(BinOp::ULessThan, z, gz)?;
++ Ok(ArmEnd::FallThrough(vec![x, y, z, inside]))
++ });
+ let narrow: ArmFn<'_, ()> = Box::new(move |fb, _| {
+ let group = fb.binary(BinOp::IMul, wz, ny)?;
+ let group = fb.binary(BinOp::IAdd, group, wy)?;
+@@ -1342,24 +1373,43 @@ impl KernelDecl {
+ let w = |fb: &mut FunctionBuilder<'_>, v: SValue| fb.convert(ConvOp::UConvert, v, u64_);
+ let (wx, wy, wz) = (w(fb, wx)?, w(fb, wy)?, w(fb, wz)?);
+ let (nx, ny, n, lin) = (w(fb, nx)?, w(fb, ny)?, w(fb, n)?, w(fb, lin)?);
+- let (gx, gy, gz) = (w(fb, gx)?, w(fb, gy)?, w(fb, gz)?);
+ let group = fb.binary(BinOp::IMul, wz, ny)?;
+ let group = fb.binary(BinOp::IAdd, group, wy)?;
+ let group = fb.binary(BinOp::IMul, group, nx)?;
+ let group = fb.binary(BinOp::IAdd, group, wx)?;
+ let first = fb.binary(BinOp::IMul, group, n)?;
+ let index = fb.binary(BinOp::IAdd, first, lin)?;
+- let x = fb.binary(BinOp::UMod, index, gx)?;
+- let row = fb.binary(BinOp::UDiv, index, gx)?;
+- let y = fb.binary(BinOp::UMod, row, gy)?;
+- let z = fb.binary(BinOp::UDiv, row, gy)?;
+- let inside = fb.binary(BinOp::ULessThan, z, gz)?;
+- let x = fb.convert(ConvOp::UConvert, x, u32_)?;
+- let y = fb.convert(ConvOp::UConvert, y, u32_)?;
+- let z = fb.convert(ConvOp::UConvert, z, u32_)?;
+- Ok(ArmEnd::FallThrough(vec![x, y, z, inside]))
++ let lo = fb.convert(ConvOp::UConvert, index, u32_)?;
++ let thirty_two = Self::k(fb, 32)?;
++ let hi = fb.binary(BinOp::ShiftRightLogical, index, thirty_two)?;
++ let hi = fb.convert(ConvOp::UConvert, hi, u32_)?;
++ let (row_lo, row_hi, x) = Self::divmod_64_by_32(fb, [lo, hi], gx)?;
++ let (z_lo, z_hi, y) = Self::divmod_64_by_32(fb, [row_lo, row_hi], gy)?;
++ // `z < gz` in 64 bits; the position's `z` is its low word, as the conversion was.
++ let zero = Self::k(fb, 0)?;
++ let small = fb.binary(BinOp::IEqual, z_hi, zero)?;
++ let below = fb.binary(BinOp::ULessThan, z_lo, gz)?;
++ let inside = fb.binary(BinOp::LogicalAnd, small, below)?;
++ Ok(ArmEnd::FallThrough(vec![x, y, z_lo, inside]))
+ });
+- let merged = fb.if_(&mut (), fits, narrow, Some(wide))?.0;
++ // Any other workgroup: whether every invocation's index fits in 32 bits, `a = nx·ny`,
++ // `b = a·nz`, `c = b·N` in 64 bits, each at most 2^32. While `a` and `b` are, the next
++ // product cannot wrap (`nz`, `N` < 2^32); a product past a failed test is not read.
++ let rest: ArmFn<'_, ()> = Box::new(move |fb, _| {
++ let w = |fb: &mut FunctionBuilder<'_>, v: SValue| fb.convert(ConvOp::UConvert, v, u64_);
++ let (nx64, ny64, nz64) = (w(fb, nx)?, w(fb, ny)?, w(fb, nz)?);
++ let a = fb.binary(BinOp::IMul, nx64, ny64)?;
++ let b = fb.binary(BinOp::IMul, a, nz64)?;
++ let c = fb.binary(BinOp::IMul, b, n64)?;
++ let fa = fb.binary(BinOp::ULessThanEqual, a, limit)?;
++ let fbb = fb.binary(BinOp::ULessThanEqual, b, limit)?;
++ let fc = fb.binary(BinOp::ULessThanEqual, c, limit)?;
++ let fits = fb.binary(BinOp::LogicalAnd, fa, fbb)?;
++ let fits = fb.binary(BinOp::LogicalAnd, fits, fc)?;
++ let merged = fb.if_(&mut (), fits, narrow, Some(wide))?.0;
++ Ok(ArmEnd::FallThrough(merged))
++ });
++ let merged = fb.if_(&mut (), row_fits, first, Some(rest))?.0;
+ let [x, y, z, inside] = merged[..] else {
+ return Err(crate::spirv::error::BuildError::Dangling(
+ crate::spirv::error::Dangling::Value(SValue::new(u32::MAX)),
+@@ -1369,6 +1419,81 @@ impl KernelDecl {
+ Ok((pos, inside))
+ }
+
++ /// The quotient (low word, high word) and remainder of the `u64` `n` (`[low, high]`) by the
++ /// `u32` `d` (not 0), in 32-bit operations: `hi / d` and `r = hi % d` (so `r < d`), then 32
++ /// restoring steps over the low word's bits, highest first, each `r = 2r + bit` and, when
++ /// that is at least `d`, `r -= d` and the step's quotient bit set. `2r + bit < 2d < 2^33`: its
++ /// bit 32 (`r`'s top bit before the shift) is the carry, and with it set the value is past `d`
++ /// and `2r + bit - d < d` is exact modulo 2^32. The loop asks the driver not to unroll it.
++ ///
++ /// The flat variant's 64-bit arm divides by it rather than by a 64-bit `OpUDiv`/`OpUMod`:
++ /// lowered on a device without a 64-bit divider (Intel's), four of those made the arm so large
++ /// that the whole kernel compiled at a narrower SIMD width (SIMD8 for the Simulator's masked
++ /// blit on Arrow Lake, Mesa 26.2), though the arm runs only past 2^32 invocations.
++ fn divmod_64_by_32(
++ fb: &mut FunctionBuilder<'_>,
++ [lo, hi]: [SValue; 2],
++ d: SValue,
++ ) -> BResult<(SValue, SValue, SValue)> {
++ use crate::spirv::builder::constructs::{LoopFn, LoopSpec};
++ let u32_ = fb.module().ty(Type::Int {
++ width: 32,
++ signed: false,
++ })?;
++ let q_hi = fb.binary(BinOp::UDiv, hi, d)?;
++ let r0 = fb.binary(BinOp::UMod, hi, d)?;
++ let [r, q, i] = [
++ fb.local_var(u32_, None)?,
++ fb.local_var(u32_, None)?,
++ fb.local_var(u32_, None)?,
++ ];
++ let [r, q, i] = [fb.var_ptr(r)?, fb.var_ptr(q)?, fb.var_ptr(i)?];
++ let zero = Self::k(fb, 0)?;
++ let steps = Self::k(fb, 32)?;
++ fb.store(r, r0, MemAccess::default())?;
++ fb.store(q, zero, MemAccess::default())?;
++ fb.store(i, steps, MemAccess::default())?;
++ let body: LoopFn<'_, ()> = Box::new(move |fb, cx, lc| {
++ let k = fb.load(i, MemAccess::default())?;
++ let zero = Self::k(fb, 0)?;
++ let done = fb.binary(BinOp::IEqual, k, zero)?;
++ let exit: ArmFn<'_, ()> = Box::new(move |fb, _| {
++ lc.break_(fb)?;
++ Ok(ArmEnd::Exits)
++ });
++ fb.if_(cx, done, exit, None)?;
++ let one = Self::k(fb, 1)?;
++ let k = fb.binary(BinOp::ISub, k, one)?;
++ let rv = fb.load(r, MemAccess::default())?;
++ let qv = fb.load(q, MemAccess::default())?;
++ let bit = fb.binary(BinOp::ShiftRightLogical, lo, k)?;
++ let bit = fb.binary(BinOp::BitwiseAnd, bit, one)?;
++ let top = Self::k(fb, 31)?;
++ let carry = fb.binary(BinOp::ShiftRightLogical, rv, top)?;
++ let carry = fb.binary(BinOp::INotEqual, carry, zero)?;
++ let twice = fb.binary(BinOp::ShiftLeftLogical, rv, one)?;
++ let twice = fb.binary(BinOp::BitwiseOr, twice, bit)?;
++ let reaches = fb.binary(BinOp::UGreaterThanEqual, twice, d)?;
++ let take = fb.binary(BinOp::LogicalOr, carry, reaches)?;
++ let less = fb.binary(BinOp::ISub, twice, d)?;
++ let rv = fb.select(take, less, twice)?;
++ let place = fb.binary(BinOp::ShiftLeftLogical, one, k)?;
++ let place = fb.select(take, place, zero)?;
++ let qv = fb.binary(BinOp::BitwiseOr, qv, place)?;
++ fb.store(r, rv, MemAccess::default())?;
++ fb.store(q, qv, MemAccess::default())?;
++ fb.store(i, k, MemAccess::default())
++ });
++ let spec = LoopSpec {
++ exit_sel: None,
++ dont_unroll: true,
++ };
++ fb.loop_(&mut (), spec, body)?;
++ let q_lo = fb.load(q, MemAccess::default())?;
++ let rem = fb.load(r, MemAccess::default())?;
++ Ok((q_lo, q_hi, rem))
++ }
++
+ /// A folded variant's threadgroup position in the Metal grid (a `uvec3`) and whether its
+ /// workgroup is one of Metal's threadgroups: the workgroup's index `(wz · ny + wy) · nx + wx`
+ /// over the dispatch (plus `DrawIndex · nx · ny · nz` for a folded object function, whose
+diff --git a/crates/metal2vulkan/src/lower/dispatch/tests.rs b/crates/metal2vulkan/src/lower/dispatch/tests.rs
+index c5e89cf0..54c28db5 100644
+--- a/crates/metal2vulkan/src/lower/dispatch/tests.rs
++++ b/crates/metal2vulkan/src/lower/dispatch/tests.rs
+@@ -545,3 +545,139 @@ fn derivation_modules_are_valid() {
+ }
+ }
+ }
++
++/// The flat variant's 64-bit arm divides a `u64` by a `u32` in 32-bit operations
++/// ([`KernelDecl::divmod_64_by_32`]): on the CPU interpreter its quotient and remainder are Rust's
++/// for dividends at and around every power-of-two boundary of interest (2^16, 2^32, 2^58, 2^63,
++/// 2^64 - 1) and the Simulator screen's index range, and divisors 1, small, 1206 and 2622, and at
++/// both sides of 2^31 and 2^32 (where `2r + bit` carries past 32 bits).
++#[test]
++fn the_flat_variant_s_64_bit_division_is_exact() {
++ let mut cases: Vec<(u64, u32)> = Vec::new();
++ let ns = [
++ 0u64,
++ 1,
++ 1 << 16,
++ 3_162_132,
++ u64::from(u32::MAX),
++ 1 << 32,
++ (1 << 32) + 1,
++ 1 << 58,
++ 1 << 63,
++ u64::MAX,
++ ];
++ let ds = [1u32, 2, 3, 1206, 2622, 1 << 31, (1 << 31) + 1, u32::MAX - 1, u32::MAX];
++ for &n in &ns {
++ for k in [0u64, 1, 2] {
++ for &d in &ds {
++ cases.push((n.wrapping_sub(k), d));
++ cases.push((n.wrapping_add(k), d));
++ }
++ }
++ }
++ let mut mb = ModuleBuilder::new();
++ let u32_ = mb
++ .ty(Type::Int {
++ width: 32,
++ signed: false,
++ })
++ .expect("u32");
++ let rta = mb
++ .ty(Type::RuntimeArray {
++ elem: u32_,
++ stride: Some(4),
++ })
++ .expect("rta");
++ let layout = natural_layout(mb.types(), LayoutRule::Std430, true, &[rta]).expect("layout");
++ let block = mb
++ .ty(Type::Struct {
++ members: [rta].into(),
++ layout: Some(layout),
++ })
++ .expect("block");
++ let slot = ResourceSlot {
++ stage: Stage::Kernel,
++ kind: ResourceKind::Buffer,
++ index: 0,
++ };
++ let buf = mb
++ .resource(slot, StorageClass::StorageBuffer, block)
++ .expect("resource");
++ let uvec3 = mb.ty(Type::Vector { elem: u32_, len: 3 }).expect("uvec3");
++ let wg_var = mb
++ .builtin(crate::spv::BuiltIn::WorkgroupId, IoDir::Input, uvec3)
++ .expect("wg");
++ let void = mb.ty(Type::Void).expect("void");
++ let mut fb = mb.function(void).expect("function");
++ let f = &mut fb;
++ let k = |f: &mut FunctionBuilder<'_>, n: u32| {
++ let c = f.u32_const(n).expect("const");
++ f.module().const_value(c).expect("value")
++ };
++ // Case `i` (the workgroup's x) reads `[lo, hi, d]` at words `3i..` and writes
++ // `[q_lo, q_hi, r]` there.
++ let p = f.module().global_value(wg_var).expect("global");
++ let wg = f.load(p, MemAccess::default()).expect("load");
++ let i = f.composite_extract(wg, &[0]).expect("x");
++ let three = k(f, 3);
++ let at = f.binary(BinOp::IMul, i, three).expect("mul");
++ let base = f.module().global_value(buf).expect("buf");
++ let zero = k(f, 0);
++ let word = |f: &mut FunctionBuilder<'_>, j: u32| {
++ let j = k(f, j);
++ let a = f.binary(BinOp::IAdd, at, j).expect("add");
++ f.access_chain(base, &[zero, a]).expect("chain")
++ };
++ let (pl, ph, pd) = (word(f, 0), word(f, 1), word(f, 2));
++ let lo = f.load(pl, MemAccess::default()).expect("lo");
++ let hi = f.load(ph, MemAccess::default()).expect("hi");
++ let d = f.load(pd, MemAccess::default()).expect("d");
++ let (q_lo, q_hi, r) = KernelDecl::divmod_64_by_32(f, [lo, hi], d).expect("divide");
++ f.store(pl, q_lo, MemAccess::default()).expect("store");
++ f.store(ph, q_hi, MemAccess::default()).expect("store");
++ f.store(pd, r, MemAccess::default()).expect("store");
++ fb.ret(None).expect("ret");
++ let id = fb.finish().expect("finish");
++ mb.entry(
++ ExecModel::GLCompute,
++ id,
++ vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }],
++ )
++ .expect("entry");
++ let m = mb.finalize().expect("finalize");
++ let p = crate::pipeline::testing::profile("intel-arl-anv", DevicePolicy::default()).expect("profile");
++ assert_valid(m.clone(), &p);
++ let bytes: Vec = cases
++ .iter()
++ .flat_map(|&(n, d)| [n as u32, (n >> 32) as u32, d])
++ .flat_map(u32::to_le_bytes)
++ .collect();
++ let res = Resources {
++ buffers: vec![Buffer {
++ slot: Some(slot),
++ address: None,
++ bytes,
++ }],
++ push: Vec::new(),
++ spec: BTreeMap::new(),
++ };
++ let cfg = Config {
++ workgroups: [cases.len() as u32, 1, 1],
++ ..Config::default()
++ };
++ let out = run(&m, &cfg, res).expect("run");
++ let w: Vec = out.buffers[0]
++ .as_chunks::<4>()
++ .0
++ .iter()
++ .map(|c| u32::from_le_bytes(*c))
++ .collect();
++ for (j, &(n, d)) in cases.iter().enumerate() {
++ let q = u64::from(w[3 * j]) | (u64::from(w[3 * j + 1]) << 32);
++ assert_eq!(
++ (q, w[3 * j + 2]),
++ (n / u64::from(d), (n % u64::from(d)) as u32),
++ "{n} / {d}"
++ );
++ }
++}
diff --git a/patches/metal2vulkan/0041-Add-grouped-completion-and-cross-import-coherence-ch.patch b/patches/metal2vulkan/0041-Add-grouped-completion-and-cross-import-coherence-ch.patch
new file mode 100644
index 0000000..5900fac
--- /dev/null
+++ b/patches/metal2vulkan/0041-Add-grouped-completion-and-cross-import-coherence-ch.patch
@@ -0,0 +1,160 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Thu, 5 Nov 2026 19:09:18 +0000
+Subject: [PATCH 41/92] Add grouped completion and cross-import coherence
+ checks
+
+---
+ .../src/runtime_lane/grouped_submissions.rs | 37 ++++++++++-
+ .../src/runtime_lane/surface_coherent.rs | 63 +++++++++++++++++++
+ 2 files changed, 98 insertions(+), 2 deletions(-)
+
+diff --git a/crates/metal2vulkan-validation/src/runtime_lane/grouped_submissions.rs b/crates/metal2vulkan-validation/src/runtime_lane/grouped_submissions.rs
+index f9848d29..91c3c7b6 100644
+--- a/crates/metal2vulkan-validation/src/runtime_lane/grouped_submissions.rs
++++ b/crates/metal2vulkan-validation/src/runtime_lane/grouped_submissions.rs
+@@ -123,6 +123,10 @@ fn bytes_of(buffer: &Buffer) -> Vec {
+ /// `vkQueueSubmit` calls that held several batches, the batches they held, the kernel submissions
+ /// in all, the grouped-completion notices, and whether the driver merges.
+ fn run(completion: CompletionPolicy, checked: bool) -> (u64, u64, u64, usize, bool, [u64; 7]) {
++ run_batches(completion, checked, BATCHES)
++}
++
++fn run_batches(completion: CompletionPolicy, checked: bool, batch_count: usize) -> (u64, u64, u64, usize, bool, [u64; 7]) {
+ let messages = Messages::default();
+ let cache = ScratchCache::new().unwrap();
+ let (grouped, batches, submissions, merging, ends) = {
+@@ -133,15 +137,20 @@ fn run(completion: CompletionPolicy, checked: bool) -> (u64, u64, u64, usize, bo
+ let merging = merges(&device.properties().description);
+ let queue = device.new_command_queue().unwrap();
+ let event = device.new_shared_event().unwrap();
+- let buffers: Vec = (0..BATCHES)
++ let buffers: Vec = (0..batch_count)
+ .map(|_| device.new_buffer(BYTES, ResourceOptions::shared()).unwrap())
+ .collect();
+ let before = device.work_counts();
+ // The command buffers whose checks ran, in the order they ran.
+ let checks = Arc::new(Mutex::new(Vec::new()));
++ let completed = Arc::new(Mutex::new(Vec::new()));
+ let committed: Vec = (buffers.iter().enumerate())
+ .map(|(at, buffer)| {
+ let command_buffer = queue.command_buffer().unwrap();
++ let done = Arc::clone(&completed);
++ command_buffer.add_completed_handler(Box::new(move |_: &CommandBuffer| {
++ done.lock().unwrap().push(at);
++ })).unwrap();
+ if checked {
+ let checks = Arc::clone(&checks);
+ command_buffer
+@@ -179,8 +188,14 @@ fn run(completion: CompletionPolicy, checked: bool) -> (u64, u64, u64, usize, bo
+ let wrong = bytes.iter().filter(|&&byte| byte != at as u8 + 1).count();
+ assert_eq!(wrong, 0, "buffer {at}: bytes off its command buffer's fill");
+ }
++ let deadline = std::time::Instant::now() + WAIT;
++ while completed.lock().unwrap().len() != batch_count {
++ assert!(std::time::Instant::now() < deadline, "completion handlers did not finish");
++ std::thread::yield_now();
++ }
++ assert_eq!(*completed.lock().unwrap(), (0..batch_count).collect::>(), "completion handlers ran in commit order");
+ let ran = checks.lock().unwrap().clone();
+- let expected: Vec = (0..BATCHES).filter(|_| checked).collect();
++ let expected: Vec = (0..batch_count).filter(|_| checked).collect();
+ assert_eq!(ran, expected, "the checks that ran, in order");
+ let after = device.work_counts();
+ (
+@@ -210,6 +225,24 @@ fn ready_batches_go_in_one_kernel_submission_where_the_driver_merges() {
+ grouped_where_merging(false);
+ }
+
++/// A full 64-buffer group preserves each result, completion and submission check in order.
++#[test]
++fn a_group_of_64_keeps_completion_and_data_in_order() {
++ struct Reset;
++ impl Drop for Reset {
++ fn drop(&mut self) { metal2vulkan_runtime::live::set("group_batches", None); }
++ }
++ let _reset = Reset;
++ metal2vulkan_runtime::live::set("group_batches", Some("64"));
++ let (grouped, batches, submissions, heard, merging, ends) = run_batches(CompletionPolicy::Grouped, true, 64);
++ if merging {
++ assert_eq!((grouped, batches, submissions, heard), (1, 64, 1, 1));
++ assert!(ends[0] >= 1, "the full 64-buffer group was submitted: {ends:?}");
++ } else {
++ assert_eq!((grouped, batches, submissions, heard), (0, 0, 64, 0));
++ }
++}
++
+ /// The same with a submission check on each command buffer: each check runs once, in commit
+ /// order, those of the batches behind a head with the head's.
+ #[test]
+diff --git a/crates/metal2vulkan-validation/src/runtime_lane/surface_coherent.rs b/crates/metal2vulkan-validation/src/runtime_lane/surface_coherent.rs
+index 693a9fd8..4993992e 100644
+--- a/crates/metal2vulkan-validation/src/runtime_lane/surface_coherent.rs
++++ b/crates/metal2vulkan-validation/src/runtime_lane/surface_coherent.rs
+@@ -2600,3 +2600,66 @@ fn surface_coherent_a_cpu_write_after_a_standing_is_not_hidden_by_an_ordered_tak
+ assert_eq!(case.read(0, 100), [0, 0, 255, 0], "the held blend");
+ });
+ }
++
++/// Two partially planned readers overlap the same row. A writer, ordered after both readers'
++/// first passes, writes through another import. Releasing only one reader leaves the other's
++/// record potentially busy while the first takes its owed copy-in. The final guest bytes test
++/// whether the ordered write survived; the counters report whether this run reached the risk path.
++#[test]
++fn surface_coherent_two_held_readers_preserve_an_ordered_other_import_write() {
++ on_surface(true, |case| {
++ case.draw(RED, None);
++ assert_eq!(case.read(0, 0), RED_TEXEL);
++ let other_buffer = case.other_import();
++ let before = shadow_coherent::fallback_counts();
++ let first_a = case.device.new_shared_event().unwrap();
++ let first_b = case.device.new_shared_event().unwrap();
++ let gate_a = case.device.new_shared_event().unwrap();
++ let gate_b = case.device.new_shared_event().unwrap();
++ let queue_b = case.device.new_command_queue().unwrap();
++ let writer_queue = case.device.new_command_queue().unwrap();
++ let reader_a = case.queue.command_buffer().unwrap();
++ let reader_b = queue_b.command_buffer().unwrap();
++ let from = staged(case.device, &[7u8; 64]);
++ let to_a = staged(case.device, &[0u8; 64]);
++ let to_b = staged(case.device, &[0u8; 64]);
++ for (reader, first, gate, to) in [
++ (&reader_a, &first_a, &gate_a, &to_a),
++ (&reader_b, &first_b, &gate_b, &to_b),
++ ] {
++ case.pass(reader, GREEN, scissor(0, 100, 16, 1));
++ reader.encode_signal_event(first.into(), 1).unwrap();
++ reader.encode_wait_for_event(gate.into(), 1).unwrap();
++ let mut blit = reader.blit_command_encoder().unwrap();
++ blit.copy_from_buffer_to_buffer(&from, 0, to, 0, 64)
++ .unwrap();
++ blit.end_encoding().unwrap();
++ reader.commit().unwrap();
++ }
++ let writer = writer_queue.command_buffer().unwrap();
++ writer.encode_wait_for_event((&first_a).into(), 1).unwrap();
++ writer.encode_wait_for_event((&first_b).into(), 1).unwrap();
++ let bytes: Vec = (0..16).flat_map(|_| [1u8, 2, 3, 4]).collect();
++ let source = staged(case.device, &bytes);
++ let mut blit = writer.blit_command_encoder().unwrap();
++ blit.copy_from_buffer_to_buffer(&source, 0, &other_buffer, 100 * ROW, 64)
++ .unwrap();
++ blit.end_encoding().unwrap();
++ writer.commit().unwrap();
++ let written = writer.wait_until_completed_for(SOON).is_ok();
++ gate_a.set_signaled_value(1);
++ let a_done = reader_a.wait_until_completed_for(SOON).is_ok();
++ gate_b.set_signaled_value(1);
++ let b_done = reader_b.wait_until_completed_for(SOON).is_ok();
++ let after = shadow_coherent::fallback_counts();
++ assert!(
++ written && a_done && b_done,
++ "the event chain completed"
++ );
++ let actual = case.read(9, 100);
++ eprintln!("TWO-READERS owed={} busy={} actual={actual:?}",
++ after.plan_owed_copies_in - before.plan_owed_copies_in,
++ after.late_copies_in_busy - before.late_copies_in_busy);
++ assert_eq!(actual, [1, 2, 3, 4], "the later ordered write survives both readers");
++ });
++}
diff --git a/patches/metal2vulkan/0042-a-scheduled-signal-leaves-a-render-end-in-flight-on-.patch b/patches/metal2vulkan/0042-a-scheduled-signal-leaves-a-render-end-in-flight-on-.patch
new file mode 100644
index 0000000..6e62c13
--- /dev/null
+++ b/patches/metal2vulkan/0042-a-scheduled-signal-leaves-a-render-end-in-flight-on-.patch
@@ -0,0 +1,70 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Fri, 6 Nov 2026 11:01:48 +0000
+Subject: [PATCH 42/92] a scheduled signal leaves a render end in flight on the
+ lowering thread
+
+Under RenderLoweringPolicy::Worker, encode_signal_event_scheduled settled the
+command buffer's in-flight render end on the program's thread, so Reims's exec
+tail (end, completed handler, scheduled signal, commit) lowered every end and
+ran every commit at the call: the worker overlapped nothing. A scheduled
+signal is the command buffer's, set as it is scheduled, so it now reads the
+in-flight end as queue_commit does and leaves it to the thread. host_ab:
+HOST_AB_RENDER_LOWERING=worker.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../examples/host_ab/runtime.rs | 7 +++++++
+ .../src/command_buffer/mod.rs | 20 +++++++++++++++++--
+ 2 files changed, 25 insertions(+), 2 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs
+index c0bcffab..7f4da58a 100644
+--- a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs
++++ b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs
+@@ -53,6 +53,13 @@ impl Runtime {
+ options.gpu_times_from_host = true;
+ options.policy.completion = CompletionPolicy::Exact;
+ options.policy.heap_compression = HeapCompressionPolicy::Uncompressed;
++ // LOCAL (Atlas) DEEP-CPU: `HOST_AB_RENDER_LOWERING=worker` lowers render calls on the
++ // device's lowering thread (`RenderLoweringPolicy::Worker`), for the A/B of what moves
++ // off the encoding thread; the default (unset) is `AtCall`, as reims-vgpu's production.
++ if std::env::var_os("HOST_AB_RENDER_LOWERING").is_some_and(|v| v == "worker") {
++ options.policy.render_lowering = metal2vulkan::device::RenderLoweringPolicy::Worker;
++ eprintln!("host_ab: render lowering on the worker");
++ }
+ options.shader_cache = rt::ShaderCacheOptions::in_directory(cache);
+ let device = rt::Device::system_default_with(&options).expect("open the runtime's device");
+ let queue = device.new_command_queue().expect("new_command_queue");
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+index 18824b72..8f3cb31d 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+@@ -2231,9 +2231,25 @@ impl CommandBuffer {
+ if !event.device().same(&self.0.device) {
+ return Err(invalid(CALL, Problem::ForeignObject));
+ }
+- self.settle_end();
++ // LOCAL (Atlas, DEEP-CPU): a scheduled signal is the command buffer's, set as it is
++ // scheduled whatever its place among the encoders, so it does not settle a render
++ // encoder's end left to the device's lowering thread (`render/deferral.rs`): the commit
++ // after it, as Reims's exec makes one, is then left to wait for the end
++ // (`render/queued_commits.rs`) instead of the program's thread lowering it. The encoder
++ // open is then the one whose end is in flight, which ended, as `queue_commit` reads it.
++ let end_in_flight = {
++ let state = self.state();
++ state.ending.is_some() && !state.end_lowered
++ };
++ if !end_in_flight {
++ self.settle_end();
++ }
+ let mut state = self.state();
+- match state.refusal() {
++ let refusal = match state.refusal() {
++ Some(Problem::EncoderOpen) if end_in_flight => None,
++ refusal => refusal,
++ };
++ match refusal {
+ None => state.scheduled_signals.push((Arc::clone(event), value)),
+ Some(Problem::AlreadyCommitted)
+ if matches!(
diff --git a/patches/metal2vulkan/0043-lower-independent-queues-render-calls-on-a-bounded-s.patch b/patches/metal2vulkan/0043-lower-independent-queues-render-calls-on-a-bounded-s.patch
new file mode 100644
index 0000000..48d89b5
--- /dev/null
+++ b/patches/metal2vulkan/0043-lower-independent-queues-render-calls-on-a-bounded-s.patch
@@ -0,0 +1,953 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Fri, 6 Nov 2026 11:37:15 +0000
+Subject: [PATCH 43/92] lower independent queues' render calls on a bounded set
+ of lanes
+
+RenderLoweringPolicy::Worker lowered every queue's logged render calls on one
+thread per device, so busy Sims (one queue each, one VkDevice) serialized there.
+The device now lowers on up to lanes() threads (one per 4 host threads, 1..4).
+Each command queue takes a lane in turn at creation and keeps it; its slots are
+handed only to that lane, so one queue's slots are lowered one at a time in hand
+order as before. Only different lanes run at once, as AtCall's program threads
+of different queues already do. A lane's thread starts with its first slot.
+
+Unchanged: one device-wide QueuedCommits order and its single runner (binary
+semaphores and events of a later commit never pass an earlier one), slot
+ownership (queued/busy/draining), drains and settle. Per lane: the queue, its
+park/wake and the ENDS_IN_FLIGHT bound (no cross-Sim back-pressure). A panic on
+any lane, or a lane thread that fails to start, ends every lane: queued slots
+are left to their programs' drains, the lost slot refuses later drains. Teardown
+stops and joins every started lane (not one on its own thread). A kept slot
+still queued on another lane is not reused for an encoder of a different lane.
+
+Test (lavapipe, m2v_cpu_icd): two queues on different lanes, queue A's slot
+held so its lane waits inside it: queue B's batches and end are lowered while
+B's commit stays behind A's; a cross-queue event gates B's copy; pixels, word,
+per-queue handler order and status equal AtCall; a refused commit on A still
+lets A's signal and B complete; a work-counts drain with both lanes busy
+returns; teardown joins both. Negative control (all queues on lane 0) fails at
+the overlap check.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/queue.rs | 10 +
+ crates/metal2vulkan-runtime/src/render.rs | 2 +
+ .../src/render/deferral.rs | 75 ++++-
+ .../src/render/lowering_worker.rs | 260 +++++++++++++-----
+ .../src/tests/deferred_calls.rs | 257 +++++++++++++++++
+ 5 files changed, 518 insertions(+), 86 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/queue.rs b/crates/metal2vulkan-runtime/src/queue.rs
+index c88c4f3f..d2e1869d 100644
+--- a/crates/metal2vulkan-runtime/src/queue.rs
++++ b/crates/metal2vulkan-runtime/src/queue.rs
+@@ -85,6 +85,9 @@ struct QueueShared {
+ id: u64,
+ /// The index of the device's `VkQueue` the queue submits to.
+ vk_queue: usize,
++ /// LOCAL (Atlas, DEEP-CPU): the lanes' turn its encoders' calls are lowered on under
++ /// `RenderLoweringPolicy::Worker` (`render/lowering_worker.rs`).
++ lowering_lane: usize,
+ label: Mutex>,
+ /// The slots its uncompleted command buffers hold.
+ slots: Arc,
+@@ -275,6 +278,7 @@ impl Device {
+ device: self.clone(),
+ id,
+ vk_queue,
++ lowering_lane: self.shared().deferred.next_queue_lane(),
+ label: Mutex::new(None),
+ slots: Slots::new(count, Arc::clone(&self.shared().uncommitted)),
+ latest_gpu_end: Mutex::new(0),
+@@ -378,6 +382,12 @@ impl CommandQueue {
+ self.0.id
+ }
+
++ /// LOCAL (Atlas, DEEP-CPU): the lanes' turn its encoders' calls are lowered on
++ /// (`render/lowering_worker.rs`).
++ pub(crate) fn lowering_lane(&self) -> usize {
++ self.0.lowering_lane
++ }
++
+ /// The index of the device's `VkQueue` the queue submits to.
+ pub(super) fn vk_queue(&self) -> usize {
+ self.0.vk_queue
+diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs
+index 89c399b5..b933b575 100644
+--- a/crates/metal2vulkan-runtime/src/render.rs
++++ b/crates/metal2vulkan-runtime/src/render.rs
+@@ -426,6 +426,8 @@ use deferral::Logged;
+ pub(crate) use deferral::{lowering, DeferredEncoders, EndInFlight};
+ #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
+ pub(crate) use deferral::{BATCH_CALLS, HANDED_BATCHES};
++#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
++pub(crate) use lowering_worker::lanes as lowering_lanes;
+ pub(crate) use inline_splits::SpareKept;
+ use replay::{
+ DrawIndexed, DrawIndexedIndirect, DrawIndexedPatches, DrawIndexedPatchesIndirect, DrawPatches,
+diff --git a/crates/metal2vulkan-runtime/src/render/deferral.rs b/crates/metal2vulkan-runtime/src/render/deferral.rs
+index 90023fbc..27ac4980 100644
+--- a/crates/metal2vulkan-runtime/src/render/deferral.rs
++++ b/crates/metal2vulkan-runtime/src/render/deferral.rs
+@@ -78,6 +78,7 @@ use crate::replay::CallLog;
+ use metal2vulkan::device::RenderLoweringPolicy;
+ use std::collections::VecDeque;
+ use std::marker::PhantomData;
++use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
+
+ /// The calls of a batch (the module docs): few enough that the lowering thread starts on a pass's
+@@ -230,6 +231,9 @@ struct SlotState {
+ /// Batches lowered, their calls still held until the program's thread empties them as it
+ /// takes them to fill (the module docs).
+ lowered: Vec,
++ /// LOCAL (Atlas, DEEP-CPU): the lane of its encoder's queue, which alone it is
++ /// handed to, and whose ends in flight its end counts among (`render/lowering_worker.rs`).
++ lane: usize,
+ }
+
+ /// What the lowering thread takes of a slot: a batch handed, or, once none is, the encoder's end
+@@ -295,13 +299,18 @@ impl SlotState {
+ /// command buffer, which the lowering held: for the caller to let go of once it holds none of the
+ /// slot's locks, since its drop may give the slot back (an end in flight the command buffer
+ /// held, `CommandBuffer::hold_end`).
+-fn end_lowering(lowerer: &mut Lowerer, at: u32, by_thread: bool) -> Option {
++fn end_lowering(
++ lowerer: &mut Lowerer,
++ at: u32,
++ lane: usize,
++ by_thread: bool,
++) -> Option {
+ let mut lowering = lowerer.lowering.take()?;
+ let command_buffer = lowering.core.command_buffer().clone();
+ let shared = lowering.core.device().shared();
+ shared.counts.render_log_end_lowered(by_thread);
+ if let Some(worker) = shared.deferred.started() {
+- worker.end_done();
++ worker.end_done(lane);
+ }
+ // Judged as of its call, when no buffer of the device was detached.
+ lowering.core.judges_unattached(true);
+@@ -330,14 +339,14 @@ impl LoweringSlot {
+ self.left_by_thread();
+ return;
+ };
+- let turn = {
++ let (turn, lane) = {
+ let mut state = lock(&self.state);
+ let Some(turn) = state.next_turn() else {
+ state.queued = false;
+ return;
+ };
+ state.busy = true;
+- turn
++ (turn, state.lane)
+ };
+ // A program that waits for room has it (`wait_for_room`).
+ self.handed_back.notify_all();
+@@ -346,7 +355,7 @@ impl LoweringSlot {
+ if let Some(batch) = &turn.batch {
+ batch.lower(&mut lowerer, true);
+ }
+- (turn.end).and_then(|at| end_lowering(&mut lowerer, at, true))
++ (turn.end).and_then(|at| end_lowering(&mut lowerer, at, lane, true))
+ });
+ (turn, ended)
+ };
+@@ -417,7 +426,9 @@ impl LoweringSlot {
+ for batch in state.handed.iter().chain([&state.filling]) {
+ batch.lower(&mut lowerer, false);
+ }
+- let ended = (state.ending.take()).and_then(|at| end_lowering(&mut lowerer, at, false));
++ let lane = state.lane;
++ let ended =
++ (state.ending.take()).and_then(|at| end_lowering(&mut lowerer, at, lane, false));
+ let then = then(&mut lowerer, &state.filling);
+ drop(lowerer);
+ let next = state.filling.next() + past;
+@@ -461,7 +472,7 @@ impl LoweringSlot {
+ .as_ref()
+ .map(|lowering| lowering.core.device().shared());
+ if let Some(worker) = shared.and_then(|shared| shared.deferred.started()) {
+- worker.end_done();
++ worker.end_done(guard.lane);
+ }
+ }
+ let state = &mut *guard;
+@@ -491,14 +502,35 @@ impl LoweringSlot {
+ pub(crate) struct DeferredEncoders {
+ slots: Mutex>>,
+ worker: OnceLock>,
++ /// LOCAL (Atlas, DEEP-CPU): the device's command queues made, which take the lowering lanes
++ /// in turn (`render/lowering_worker.rs`).
++ queues: AtomicUsize,
+ }
+
+ impl DeferredEncoders {
++ /// LOCAL (Atlas, DEEP-CPU): the lanes' turn of a command queue made now, which its
++ /// encoders' slots are handed to for the queue's life (`render/lowering_worker.rs`).
++ pub(crate) fn next_queue_lane(&self) -> usize {
++ self.queues.fetch_add(1, Ordering::Relaxed)
++ }
++
+ /// A slot for `lowering`'s encoder, which logs its calls, with its checks at the call: one
+ /// kept, its checks' room reused, else a new one.
+ fn take(&self, lowering: Box) -> Arc {
++ let turn = lowering
++ .core
++ .command_buffer()
++ .command_queue()
++ .lowering_lane();
++ let lane = turn % super::lowering_worker::lanes();
+ let mut slots = lock(&self.slots);
+- let kept = slots.iter().find(|slot| !lock(&slot.state).taken).cloned();
++ // LOCAL (Atlas, DEEP-CPU): not one still in another lane's queue, whose thread would
++ // lower this encoder's batches out of its queue's lane (`render/lowering_worker.rs`).
++ let free = |slot: &&Arc| {
++ let state = lock(&slot.state);
++ !state.taken && (!state.queued || state.lane == lane)
++ };
++ let kept = slots.iter().find(free).cloned();
+ let slot = match kept {
+ Some(slot) => slot,
+ None => {
+@@ -515,6 +547,7 @@ impl DeferredEncoders {
+ panicked: false,
+ ending: None,
+ lowered: Vec::new(),
++ lane: 0,
+ }),
+ lowerer: Mutex::new(Lowerer {
+ lowering: None,
+@@ -529,6 +562,7 @@ impl DeferredEncoders {
+ let mut state = lock(&slot.state);
+ state.taken = true;
+ drop(slots);
++ state.lane = lane;
+ state.checking = true;
+ match &mut state.checks {
+ Some(checks) => checks.reset(&lowering),
+@@ -588,6 +622,11 @@ impl DeferredEncoders {
+ /// validation crate's GPU safety cfgs alone).
+ #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
+ impl DeferredEncoders {
++ /// LOCAL (Atlas, DEEP-CPU): the device's lowering threads, where they started.
++ pub(crate) fn started_for_test(&self) -> Option<&LoweringWorker> {
++ self.started()
++ }
++
+ /// The slots open encoders hold now.
+ pub(crate) fn taken(&self) -> Vec> {
+ let slots = lock(&self.slots);
+@@ -610,6 +649,13 @@ impl LoweringSlot {
+ pub(crate) fn handed(&self) -> usize {
+ lock(&self.state).handed.len()
+ }
++
++ /// LOCAL (Atlas, DEEP-CPU): everything handed of the slot was lowered, its end included: no
++ /// batch handed or being lowered, and no end left to lower.
++ pub(crate) fn lowered_all(&self) -> bool {
++ let state = lock(&self.state);
++ !state.busy && state.handed.is_empty() && state.ending.is_none()
++ }
+ }
+
+ /// A program's encoder's slot, with the calls it logged and their checks (the module docs),
+@@ -789,9 +835,10 @@ impl RenderCommandEncoder {
+ }
+ let unqueued = state.hand_off();
+ let full = state.handed.len() >= HANDED_BATCHES;
++ let lane = state.lane;
+ drop(state);
+ let worker = logged.device.shared().deferred.worker();
+- if unqueued && !worker.is_some_and(|worker| worker.hand(slot)) {
++ if unqueued && !worker.is_some_and(|worker| worker.hand(slot, lane)) {
+ lock(&slot.state).queued = false;
+ }
+ if full {
+@@ -855,9 +902,11 @@ impl RenderCommandEncoder {
+ let shared = command_buffer.device().shared();
+ shared.deferred.worker().filter(|worker| worker.runs())
+ });
+- let checked = {
++ let (checked, lane) = {
+ let state = lock(&slot.state);
+- state.checking && state.checks.as_ref().is_some_and(|c| !c.ends_at_call())
++ let checked =
++ state.checking && state.checks.as_ref().is_some_and(|c| !c.ends_at_call());
++ (checked, state.lane)
+ };
+ let shared = logged.device.shared();
+ let hands = checked && !shared.rebinds.any_detached_now() && !exit_guard::closed();
+@@ -865,7 +914,7 @@ impl RenderCommandEncoder {
+ if let Some((command_buffer, worker)) = handing {
+ // Room for the end among those in flight, without the slot's lock, which the thread
+ // takes to lower them (`render/lowering_worker.rs`).
+- if worker.reserve_end() {
++ if worker.reserve_end(lane) {
+ shared.counts.render_log_waited();
+ }
+ let mut state = lock(&slot.state);
+@@ -876,7 +925,7 @@ impl RenderCommandEncoder {
+ // finds it held (`CommandBuffer::end_lowered`).
+ command_buffer.hold_end(EndInFlight(logged));
+ drop(state);
+- if unqueued && !worker.hand(&slot) {
++ if unqueued && !worker.hand(&slot, lane) {
+ lock(&slot.state).queued = false;
+ }
+ return Ok(());
+diff --git a/crates/metal2vulkan-runtime/src/render/lowering_worker.rs b/crates/metal2vulkan-runtime/src/render/lowering_worker.rs
+index e39891d7..b3a91261 100644
+--- a/crates/metal2vulkan-runtime/src/render/lowering_worker.rs
++++ b/crates/metal2vulkan-runtime/src/render/lowering_worker.rs
+@@ -1,5 +1,15 @@
+-//! A device's lowering thread (`render/deferral.rs`): it lowers the batches of logged calls the
+-//! device's render encoders hand it, while the program goes on.
++//! A device's lowering threads (`render/deferral.rs`): they lower the batches of logged calls the
++//! device's render encoders hand them, while the program goes on.
++//!
++//! - **Lanes.** LOCAL (Atlas, DEEP-CPU): the device lowers on up to [`lanes`] threads, one per
++//! lane. Each command queue keeps one lane for its life, the queues taking the lanes in turn as
++//! they are made (`DeferredEncoders::next_queue_lane`), and its encoders' slots are handed to that
++//! lane alone. So one queue's slots are lowered one at a time, in the order they were handed, as
++//! on the single thread before; only slots of queues on different lanes are lowered at once, as
++//! the program's threads of different queues lower theirs at once under
++//! `RenderLoweringPolicy::AtCall`. A lane's thread starts with the first slot handed to it.
++//! The commits that wait stay in the device's one commit order (`render/queued_commits.rs`),
++//! whichever lane lowers their ends.
+ //!
+ //! - **Order.** It takes the slots it is handed in the order they were handed, and each slot's
+ //! batches in the order the program logged them, one at a time: a slot's calls are lowered in
+@@ -15,16 +25,18 @@
+ //! - **A panic** while lowering ends the thread: the slot it was lowering refuses every later
+ //! drain with that panic, on the program's thread, as the call would have panicked under
+ //! `RenderLoweringPolicy::AtCall`, and from then on the program's threads lower every slot's
+-//! calls themselves.
+-//! - **Ends bounded.** At most [`ENDS_IN_FLIGHT`] encoders' ends are handed to the thread and not
+-//! yet lowered: the next waits in `end_encoding` until the thread lowers one
++//! calls themselves: every lane leaves the slots waiting in it, takes no more, and its thread
++//! ends once the slot it lowers, if any, is done. So does a lane whose thread fails to start.
++//! - **Ends bounded.** At most [`ENDS_IN_FLIGHT`] encoders' ends are handed to a lane and not
++//! yet lowered: the next of that lane waits in `end_encoding` until its thread lowers one
+ //! (`WorkCounts::render_log_waits`). So a program that outruns the thread holds that many
+ //! encoders' logs, command buffers and the runtime's pools for them, not a queue's every command
+ //! buffer, which the thread lowers without the program, so the wait ends.
+ //! - **Commits.** The device's commits that wait for its render encoders' ends lie here too
+ //! (`render/queued_commits.rs`): the thread that lowers such an end runs them.
+-//! - **Started** with the device's first encoder that logs its calls, at the user-interactive
+-//! class (`exit_guard::spawn_user_interactive`), as the threads command buffers' work waits for;
++//! - **Started**, the first lane's thread with the device's first encoder that logs its calls and
++//! each other's with the first slot handed to it, at the user-interactive class
++//! (`exit_guard::spawn_user_interactive`), as the threads command buffers' work waits for; all
+ //! stopped and joined with the device (`DeviceShared`'s drop). No slot handed to it holds the
+ //! device by then: an encoder holds its device until it ends or goes, and its slot lets go of
+ //! its lowering then.
+@@ -36,78 +48,135 @@ use crate::exit_guard;
+ use crate::recorder::take_leaving_room;
+ use std::collections::VecDeque;
+ use std::sync::atomic::{AtomicBool, Ordering};
+-use std::sync::{Arc, Condvar, Mutex};
++use std::sync::{Arc, Condvar, Mutex, OnceLock};
+
+-/// The encoders' ends handed to the thread and not yet lowered at which the next end waits (the
+-/// module docs): a few passes' lead over the thread, enough to keep it busy while the program
+-/// encodes the next pass, each end holding at most its encoder's batches
++/// The encoders' ends handed to a lane and not yet lowered at which the lane's next end waits
++/// (the module docs): a few passes' lead over its thread, enough to keep it busy while the
++/// program encodes the next pass, each end holding at most its encoder's batches
+ /// (`render/deferral.rs`).
+ pub(crate) const ENDS_IN_FLIGHT: usize = 4;
+
+-/// The device's lowering thread (the module docs).
++/// The most lanes a device lowers on (the module docs).
++pub(crate) const MAX_LANES: usize = 4;
++
++/// LOCAL (Atlas, DEEP-CPU): the lanes a device lowers on, on a host of `threads` hardware
++/// threads: one for every four, one to [`MAX_LANES`]. Each lane's thread is busy only while its
++/// queues' programs outrun it, and the rest of the host's threads are left to those programs
++/// (Reims's task threads, a VM's virtual CPUs) and to the device's scheduler and handlers.
++pub(crate) fn lanes_for(threads: usize) -> usize {
++ (threads / 4).clamp(1, MAX_LANES)
++}
++
++/// The lanes of this process's devices: [`lanes_for`] of the host's hardware threads, read once.
++pub(crate) fn lanes() -> usize {
++ static LANES: OnceLock = OnceLock::new();
++ *LANES.get_or_init(|| {
++ let threads = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
++ lanes_for(threads)
++ })
++}
++
++/// The device's lowering threads (the module docs).
+ pub(crate) struct LoweringWorker {
+ shared: Arc,
+- thread: Mutex>>,
++ /// The lanes' threads started, to join.
++ threads: Mutex>>,
+ }
+
+-/// What the thread and the encoders that hand it their slots share.
++/// What the threads and the encoders that hand them their slots share.
+ struct WorkerShared {
+- queue: Mutex,
+- wake: Condvar,
+- /// The thread ended by a panic (the module docs).
++ lanes: Box<[Lane]>,
++ /// A thread ended by a panic, or one failed to start: no lane lowers (the module docs).
+ ended: AtomicBool,
+ /// The device's commits that wait for its render encoders' ends (the module docs).
+ commits: QueuedCommits,
+- /// The ends handed to the thread, or about to be, and not yet lowered (the module docs).
++}
++
++/// A lane: its queue of slots, its thread's wake and its ends in flight (the module docs).
++struct Lane {
++ queue: Mutex,
++ wake: Condvar,
++ /// The ends handed to the lane, or about to be, and not yet lowered.
+ ends: Mutex,
+ /// Signalled as one of them is lowered.
+ end_lowered: Condvar,
+ }
+
+ struct Queue {
+- /// The slots handed to the thread, in order.
++ /// The slots handed to the lane, in order.
+ slots: VecDeque>,
+- /// The thread waits for a slot.
++ /// Its thread waits for a slot.
+ parked: bool,
++ /// Its thread was started.
++ started: bool,
+ /// The device is torn down: the thread ends.
+ stop: bool,
+ }
+
+ impl LoweringWorker {
+- /// The device's lowering thread, started now; `None` where the host starts no thread, where
+- /// the program's threads lower every logged call at their drains.
++ /// The device's lowering threads, the first lane's started now; `None` where the host starts
++ /// no thread, where the program's threads lower every logged call at their drains.
+ pub(super) fn start() -> Option {
+- let shared = Arc::new(WorkerShared {
++ let lanes = (0..lanes()).map(|_| Lane {
+ queue: Mutex::new(Queue {
+ slots: VecDeque::new(),
+ parked: false,
++ started: false,
+ stop: false,
+ }),
+ wake: Condvar::new(),
+- ended: AtomicBool::new(false),
+- commits: QueuedCommits::new(),
+ ends: Mutex::new(0),
+ end_lowered: Condvar::new(),
+ });
+- let running = Arc::clone(&shared);
++ let worker = LoweringWorker {
++ shared: Arc::new(WorkerShared {
++ lanes: lanes.collect(),
++ ended: AtomicBool::new(false),
++ commits: QueuedCommits::new(),
++ }),
++ threads: Mutex::new(Vec::new()),
++ };
++ lock(&worker.shared.lanes[0].queue).started = true;
++ worker.spawn(0).then_some(worker)
++ }
++
++ /// Start lane `lane`'s thread: whether it started.
++ fn spawn(&self, lane: usize) -> bool {
++ let running = Arc::clone(&self.shared);
+ let builder = std::thread::Builder::new().name("metal2vulkan-lowering".to_owned());
+- let thread = exit_guard::spawn_user_interactive(builder, move || running.run()).ok()?;
+- Some(LoweringWorker {
+- shared,
+- thread: Mutex::new(Some(thread)),
+- })
++ match exit_guard::spawn_user_interactive(builder, move || running.run(lane)) {
++ Ok(thread) => {
++ lock(&self.threads).push(thread);
++ true
++ }
++ Err(_) => false,
++ }
++ }
++
++ /// The lane of the queue that took the lanes' turn `turn` (the module docs).
++ fn lane(&self, turn: usize) -> &Lane {
++ &self.shared.lanes[turn % self.shared.lanes.len()]
+ }
+
+- /// Hand `slot`, which has batches handed and is in no queue, to the thread: whether it takes
+- /// it (it has not ended).
+- pub(super) fn hand(&self, slot: &Arc) -> bool {
+- let mut queue = lock(&self.shared.queue);
++ /// Hand `slot`, which has batches handed and is in no queue, to lane `turn`'s thread (the
++ /// module docs), started now where it was not: whether the lane takes it (no thread ended).
++ pub(super) fn hand(&self, slot: &Arc, turn: usize) -> bool {
++ let lane = self.lane(turn);
++ let mut queue = lock(&lane.queue);
+ if self.shared.ended.load(Ordering::Acquire) {
+ return false;
+ }
+ queue.slots.push_back(Arc::clone(slot));
+ if queue.parked {
+- self.shared.wake.notify_one();
++ lane.wake.notify_one();
++ }
++ let starts = !queue.started;
++ queue.started = true;
++ drop(queue);
++ if starts && !self.spawn(turn % self.shared.lanes.len()) {
++ // No lane lowers from now on: the slot, and every other waiting, is the program's.
++ self.shared.abandon(None);
++ return false;
+ }
+ true
+ }
+@@ -117,15 +186,16 @@ impl LoweringWorker {
+ &self.shared.commits
+ }
+
+- /// Room for an end to hand to the thread (the module docs): wait while [`ENDS_IN_FLIGHT`]
+- /// ends are handed and not lowered, unless the thread ended or the process exits. Whether
+- /// the caller waited.
+- pub(super) fn reserve_end(&self) -> bool {
+- let mut ends = lock(&self.shared.ends);
++ /// Room for an end to hand to lane `turn` (the module docs): wait while [`ENDS_IN_FLIGHT`]
++ /// ends are handed to it and not lowered, unless a thread ended or the process exits.
++ /// Whether the caller waited.
++ pub(super) fn reserve_end(&self, turn: usize) -> bool {
++ let lane = self.lane(turn);
++ let mut ends = lock(&lane.ends);
+ let mut waited = false;
+ while *ends >= ENDS_IN_FLIGHT && self.runs() && !exit_guard::closed() {
+ waited = true;
+- ends = (self.shared.end_lowered.wait_timeout(ends, exit_guard::WAKE))
++ ends = (lane.end_lowered.wait_timeout(ends, exit_guard::WAKE))
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .0;
+ }
+@@ -133,51 +203,70 @@ impl LoweringWorker {
+ waited
+ }
+
+- /// An end [`reserve_end`](Self::reserve_end) made room for was lowered, or will never be:
+- /// room for the next.
+- pub(super) fn end_done(&self) {
+- let mut ends = lock(&self.shared.ends);
++ /// An end [`reserve_end`](Self::reserve_end) of lane `turn` made room for was lowered, or
++ /// will never be: room for the next.
++ pub(super) fn end_done(&self, turn: usize) {
++ let lane = self.lane(turn);
++ let mut ends = lock(&lane.ends);
+ debug_assert!(*ends > 0, "an end lowered that was not handed");
+- *ends -= 1;
++ *ends = ends.saturating_sub(1);
+ drop(ends);
+- self.shared.end_lowered.notify_one();
++ lane.end_lowered.notify_one();
+ }
+
+- /// Whether the thread lowers what it is handed: it has not ended.
++ /// Whether the threads lower what they are handed: none ended.
+ pub(super) fn runs(&self) -> bool {
+ !self.shared.ended.load(Ordering::Acquire)
+ }
+
+- /// End the thread and wait for it, as the device is torn down.
++ /// End the threads and wait for them, as the device is torn down. Not one on its own thread
++ /// (a device whose last handle went there), which ends as it returns.
+ pub(super) fn stop(&self) {
+- lock(&self.shared.queue).stop = true;
+- self.shared.wake.notify_one();
+- if let Some(thread) = lock(&self.thread).take() {
+- let _ = thread.join();
++ for lane in &self.shared.lanes {
++ lock(&lane.queue).stop = true;
++ lane.wake.notify_all();
+ }
++ let threads = std::mem::take(&mut *lock(&self.threads));
++ let me = std::thread::current().id();
++ for thread in threads {
++ if thread.thread().id() != me {
++ let _ = thread.join();
++ }
++ }
++ }
++}
++
++/// A device test's view of the lanes (`tests::deferred_calls`).
++#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
++impl LoweringWorker {
++ /// The lanes' threads started so far.
++ pub(crate) fn threads_started(&self) -> usize {
++ lock(&self.threads).len()
+ }
+ }
+
+ impl WorkerShared {
+- /// The thread's loop: each slot handed lowered, until [`LoweringWorker::stop`].
+- fn run(&self) {
++ /// Lane `lane`'s thread's loop: each slot handed lowered, until [`LoweringWorker::stop`], or
++ /// until a thread ended (the module docs).
++ fn run(&self, lane: usize) {
+ let mut running = Running {
+ shared: self,
+ slot: None,
+ };
++ let lane = &self.lanes[lane];
+ loop {
+ let slot = {
+- let mut queue = lock(&self.queue);
++ let mut queue = lock(&lane.queue);
+ loop {
++ if queue.stop || self.ended.load(Ordering::Acquire) {
++ return;
++ }
+ if let Some(slot) = take_leaving_room(&mut queue.slots) {
+ break slot;
+ }
+- if queue.stop {
+- return;
+- }
+ queue.parked = true;
+ queue =
+- (self.wake.wait(queue)).unwrap_or_else(std::sync::PoisonError::into_inner);
++ (lane.wake.wait(queue)).unwrap_or_else(std::sync::PoisonError::into_inner);
+ queue.parked = false;
+ }
+ };
+@@ -188,9 +277,32 @@ impl WorkerShared {
+ running.slot = None;
+ }
+ }
++
++ /// No lane lowers from now on (the module docs): each leaves the slots waiting in it, which
++ /// their programs' threads lower at their drains, `lost` (the slot a panic unwound) refusing
++ /// every later drain. A lane's thread that lowers a slot now goes on with it, then ends.
++ fn abandon(&self, lost: Option<&LoweringSlot>) {
++ // Before the lanes are swept: a hand after the sweep of its lane finds it set.
++ self.ended.store(true, Ordering::Release);
++ let mut waiting: Vec> = Vec::new();
++ for lane in &self.lanes {
++ let mut queue = lock(&lane.queue);
++ waiting.extend(queue.slots.drain(..));
++ lane.wake.notify_all();
++ drop(queue);
++ // A program that waits for room for an end has it now (`reserve_end`).
++ lane.end_lowered.notify_all();
++ }
++ if let Some(slot) = lost {
++ slot.lost_to_panic();
++ }
++ for slot in waiting {
++ slot.left_by_thread();
++ }
++ }
+ }
+
+-/// The thread's loop as it runs: a panic that unwinds it ends the thread (the module docs).
++/// A lane's loop as it runs: a panic that unwinds it ends every lane (the module docs).
+ struct Running<'a> {
+ shared: &'a WorkerShared,
+ /// The slot it lowers now.
+@@ -202,16 +314,18 @@ impl Drop for Running<'_> {
+ if !std::thread::panicking() {
+ return;
+ }
+- let waiting: Vec> = {
+- let mut queue = lock(&self.shared.queue);
+- self.shared.ended.store(true, Ordering::Release);
+- queue.slots.drain(..).collect()
+- };
+- if let Some(slot) = &self.slot {
+- slot.lost_to_panic();
+- }
+- for slot in waiting {
+- slot.left_by_thread();
+- }
++ self.shared.abandon(self.slot.as_deref());
++ }
++}
++
++#[cfg(test)]
++mod tests {
++ use super::{lanes_for, MAX_LANES};
++
++ /// One lane for every four hardware threads, at least one and at most [`MAX_LANES`].
++ #[test]
++ fn lanes_follow_the_hosts_threads_within_their_bound() {
++ let lanes: Vec = [0, 1, 4, 7, 8, 12, 16, 20, 64].map(lanes_for).into();
++ assert_eq!(lanes, [1, 1, 1, 1, 2, 3, 4, MAX_LANES, MAX_LANES]);
+ }
+ }
+diff --git a/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs b/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs
+index 6c905701..d08ccc0d 100644
+--- a/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs
++++ b/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs
+@@ -1096,3 +1096,260 @@ fn a_commit_whose_own_work_fails_completes_with_the_refusal() {
+ assert_eq!(commits, 2, "{counts:?}");
+ }
+ }
++
++/// What [`two_queues`] reads: the pass of each queue's words, the word queue B's command buffer
++/// copied after it waited for queue A's event, the completed handlers in the order they ran on
++/// each queue (queue A's first), and
++/// the passes' command buffers' statuses and errors.
++type TwoQueues = (
++ Vec,
++ Vec,
++ Vec,
++ Vec<&'static str>,
++ [(CommandBufferStatus, Option); 2],
++);
++
++/// LOCAL (Atlas, DEEP-CPU): the two queues' work of
++/// [`independent_queues_lower_at_once_and_keep_the_commit_order`] on `device`, which lowers as
++/// `policy` says; `refuse` injects an out of memory into the commit work of queue A's pass. Under
++/// Worker, with queue A's slot's lowering held so its lane's thread waits inside it: queue B's
++/// batches and end are lowered (by its own lane: nothing else lowers them), while its commit waits
++/// behind queue A's, and a read of the work counts made meanwhile on another thread returns once
++/// the hold ends.
++fn two_queues(device: &Device, policy: RenderLoweringPolicy, refuse: bool) -> TwoQueues {
++ let state = rectangle_state(device);
++ let lanes = crate::render::lowering_lanes();
++ let qa = device.new_command_queue().unwrap();
++ let mut qb = device.new_command_queue().unwrap();
++ while qb.lowering_lane() % lanes == qa.lowering_lane() % lanes {
++ qb = device.new_command_queue().unwrap();
++ }
++ let order = Arc::new(Mutex::new(Vec::new()));
++ let handler = |name: &'static str| {
++ let ran = Arc::clone(&order);
++ Box::new(move |_: &CommandBuffer| ran.lock().unwrap().push(name))
++ };
++ let (ta, tb) = (target(device), target(device));
++ let word = device.new_buffer(4, ResourceOptions::shared()).unwrap();
++ let copied = device.new_buffer(4, ResourceOptions::shared()).unwrap();
++ let event = device.new_shared_event().unwrap();
++ // Queue A: its pass, held under Worker.
++ let pass_a = qa.command_buffer().unwrap();
++ let mut ea = pass_a.render_command_encoder(&pass(&ta)).unwrap();
++ let held = match policy {
++ RenderLoweringPolicy::Worker => {
++ let slots = device.shared().deferred.taken();
++ let [slot] = &slots[..] else {
++ panic!("{} encoders' slots taken, not one", slots.len());
++ };
++ Some(Arc::clone(slot))
++ }
++ _ => None,
++ };
++ let color_b = bytes_of(&[1.0f32, 0.0, 0.0, 1.0], f32::to_le_bytes);
++ // Queue A's pass in one batch, handed at its end, which its lane takes and waits in; queue
++ // B's in several, its lane lowering each and the end.
++ let (draws_a, draws_b) = (4, BATCH_CALLS);
++ let encode = || {
++ rectangle(&state, &mut ea);
++ ea.set_fragment_bytes(&bytes_of(&COLOR, f32::to_le_bytes), 0)
++ .unwrap();
++ for _ in 0..draws_a {
++ ea.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)
++ .unwrap();
++ }
++ ea.end_encoding().unwrap();
++ pass_a.add_completed_handler(handler("a")).unwrap();
++ if refuse {
++ pass_a.fail_commit_work(2);
++ }
++ if let Some(slot) = &held {
++ // Its lane's thread took the pass's batches and waits for the held lowering.
++ until("queue A's lane takes the held slot", || slot.handed() == 0);
++ }
++ pass_a.commit().unwrap();
++ // Queue A, behind its pass: a fill, then the event queue B waits for.
++ let signal = qa.command_buffer().unwrap();
++ let mut fill = signal.blit_command_encoder().unwrap();
++ fill.fill_buffer(&word, 0..4, 0x5a).unwrap();
++ fill.end_encoding().unwrap();
++ signal
++ .encode_signal_event(EventRef::from(&event), 1)
++ .unwrap();
++ signal.add_completed_handler(handler("a-signal")).unwrap();
++ signal.commit().unwrap();
++ // Queue B: waits for queue A's event, copies the word, then its own pass.
++ let pass_b = qb.command_buffer().unwrap();
++ pass_b
++ .encode_wait_for_event(EventRef::from(&event), 1)
++ .unwrap();
++ let mut copy = pass_b.blit_command_encoder().unwrap();
++ copy.copy_from_buffer_to_buffer(&word, 0, &copied, 0, 4)
++ .unwrap();
++ copy.end_encoding().unwrap();
++ let mut eb = pass_b.render_command_encoder(&pass(&tb)).unwrap();
++ let slot_b = held.as_ref().map(|held| {
++ let slots = device.shared().deferred.taken();
++ let other = slots.iter().find(|slot| !Arc::ptr_eq(slot, held));
++ Arc::clone(other.expect("queue B's slot"))
++ });
++ rectangle(&state, &mut eb);
++ eb.set_fragment_bytes(&color_b, 0).unwrap();
++ for _ in 0..draws_b {
++ eb.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)
++ .unwrap();
++ }
++ eb.end_encoding().unwrap();
++ pass_b.add_completed_handler(handler("b")).unwrap();
++ pass_b.commit().unwrap();
++ if let Some(slot_b) = &slot_b {
++ // The overlap: queue A's lane waits inside its slot; queue B's lowers all of B's.
++ until("queue B's lane lowers its slot with queue A's held", || {
++ slot_b.lowered_all()
++ });
++ // The device's commit order: B's commit waits behind A's.
++ assert_eq!(pass_b.status(), CommandBufferStatus::Committed);
++ assert!(
++ order.lock().unwrap().is_empty(),
++ "a handler ran with A held"
++ );
++ }
++ (pass_b, signal)
++ };
++ let (pass_b, signal, drained) = match &held {
++ Some(slot) => {
++ let (done, drained) = mpsc::channel();
++ let ((pass_b, signal), reading) = slot.while_held(|| {
++ let made = encode();
++ // A device-wide drain, made while both lanes hold work: it returns after the
++ // hold, with every lane's lowering done.
++ let reading = std::thread::spawn({
++ let device = device.clone();
++ move || {
++ let _ = device.work_counts();
++ done.send(()).unwrap();
++ }
++ });
++ (made, reading)
++ });
++ let drained = drained.recv_timeout(WAIT).is_ok();
++ reading.join().unwrap();
++ (pass_b, signal, drained)
++ }
++ None => {
++ let (pass_b, signal) = encode();
++ (pass_b, signal, true)
++ }
++ };
++ assert!(drained, "{policy:?}: the work counts' drain returned");
++ for command_buffer in [&pass_a, &signal, &pass_b] {
++ command_buffer.wait_until_completed_for(WAIT).unwrap();
++ }
++ let read = |target: &Texture| {
++ let command_buffer = qb.command_buffer().unwrap();
++ let back = copy_back(device, &command_buffer, target);
++ committed(&command_buffer, &back)
++ };
++ let statuses = [&pass_a, &pass_b].map(|cb| (cb.status(), cb.error()));
++ // Each queue's handlers in its order; Metal orders no queue's completions against another's.
++ let mut order = order.lock().unwrap().clone();
++ order.sort_by_key(|name| name.starts_with('b'));
++ (read(&ta), read(&tb), words_of(&copied), order, statuses)
++}
++
++/// LOCAL (Atlas, DEEP-CPU): two command queues on different lowering lanes
++/// (`render/lowering_worker.rs`) lower at once and keep the device's one commit order: with
++/// queue A's pass's lowering held, queue B's pass is lowered whole by its lane while its commit
++/// waits behind A's, and A's queue's event (signalled behind A's pass) still gates B's copy. Every
++/// result is the same under `AtCall`: each pass's color, the word B copied after its wait, each
++/// queue's handlers in its commit order, both completed. Then with A's commit work failing: A completes with
++/// `CallRefused` of `commit`, and A's signal and B's pass still complete after it, in order. A
++/// work-counts drain made with both lanes busy returns, and the device's teardown joins both lanes.
++/// Where the host gives one lane alone there is nothing to overlap.
++#[test]
++fn independent_queues_lower_at_once_and_keep_the_commit_order() {
++ let lanes = crate::render::lowering_lanes();
++ if lanes < 2 {
++ eprintln!("one lowering lane on this host: nothing to overlap");
++ return;
++ }
++ let scratch = Scratch::new("deferred-lanes");
++ let red = u32::from_le_bytes([255, 0, 0, 255]);
++ let filled = u32::from_le_bytes([0x5a; 4]);
++ let completed = (CommandBufferStatus::Completed, None);
++ let mut results = Vec::new();
++ for policy in POLICIES {
++ let device = device(&scratch.0, policy, &[], &Heard::default());
++ let result = two_queues(&device, policy, false);
++ assert!(
++ result.0.iter().all(|&w| w == PACKED),
++ "{policy:?} A {:x?}",
++ &result.0[..4]
++ );
++ assert!(
++ result.1.iter().all(|&w| w == red),
++ "{policy:?} B {:x?}",
++ &result.1[..4]
++ );
++ assert_eq!(result.2, [filled], "{policy:?}: B's copy after A's event");
++ assert_eq!(result.3, ["a", "a-signal", "b"], "{policy:?}");
++ assert_eq!(
++ result.4,
++ [completed.clone(), completed.clone()],
++ "{policy:?}"
++ );
++ let counts = device.work_counts();
++ eprintln!(
++ "{policy:?} lanes {lanes}: batches thread/program {}/{} ends {}/{} commits {}/{} waits {}",
++ counts.render_log_batches_by_thread,
++ counts.render_log_batches_by_program,
++ counts.render_log_ends_by_thread,
++ counts.render_log_ends_by_program,
++ counts.render_log_commits_by_thread,
++ counts.render_log_commits_by_program,
++ counts.render_log_waits
++ );
++ if policy == RenderLoweringPolicy::Worker {
++ // B's end by its lane (`lowered_all` above); A's by its lane or, once the hold ended,
++ // by the work counts' drain, which takes what the lane has not. Each once.
++ let ends = counts.render_log_ends_by_thread + counts.render_log_ends_by_program;
++ let commits =
++ counts.render_log_commits_by_thread + counts.render_log_commits_by_program;
++ assert!(counts.render_log_ends_by_thread >= 1, "B's end by a lane");
++ assert_eq!(
++ (ends, commits),
++ (2, 3),
++ "each end and each queued commit ran once"
++ );
++ let worker = device.shared().deferred.started_for_test();
++ assert_eq!(worker.map(|w| w.threads_started()), Some(2));
++ }
++ results.push(result);
++ drop(device);
++ }
++ assert_eq!(results[0], results[1], "Worker against AtCall");
++ // Queue A's commit refused, under Worker: later work on both queues still runs.
++ let device = device(
++ &scratch.0,
++ RenderLoweringPolicy::Worker,
++ &[],
++ &Heard::default(),
++ );
++ let (_, b, copied, order, [a, b_status]) =
++ two_queues(&device, RenderLoweringPolicy::Worker, true);
++ let commit = EncoderCall {
++ selector: "commit",
++ index: 0,
++ };
++ assert_eq!(
++ a,
++ (
++ CommandBufferStatus::Error,
++ Some(CommandBufferError::CallRefused(commit))
++ )
++ );
++ assert_eq!(b_status, completed);
++ assert!(b.iter().all(|&w| w == red), "B {:x?}", &b[..4]);
++ assert_eq!(copied, [filled]);
++ assert_eq!(order, ["a", "a-signal", "b"]);
++}
diff --git a/patches/metal2vulkan/0044-Assign-render-lowering-lanes-on-first-use-so-idle-qu.patch b/patches/metal2vulkan/0044-Assign-render-lowering-lanes-on-first-use-so-idle-qu.patch
new file mode 100644
index 0000000..4a381a0
--- /dev/null
+++ b/patches/metal2vulkan/0044-Assign-render-lowering-lanes-on-first-use-so-idle-qu.patch
@@ -0,0 +1,127 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Fri, 6 Nov 2026 12:56:13 +0000
+Subject: [PATCH 44/92] Assign render lowering lanes on first use so idle
+ queues cannot consume them
+
+---
+ crates/metal2vulkan-runtime/src/queue.rs | 19 +++++++++++--------
+ .../src/render/deferral.rs | 8 ++++----
+ .../src/render/lowering_worker.rs | 5 +++--
+ .../src/tests/deferred_calls.rs | 12 ++++++++----
+ 4 files changed, 26 insertions(+), 18 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/queue.rs b/crates/metal2vulkan-runtime/src/queue.rs
+index d2e1869d..6ffac9fe 100644
+--- a/crates/metal2vulkan-runtime/src/queue.rs
++++ b/crates/metal2vulkan-runtime/src/queue.rs
+@@ -60,7 +60,7 @@ use super::error::{Error, Invalid, Problem};
+ use super::texture::copy_images::CopyImages;
+ use super::texture::kept_image::KeptImages;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+-use std::sync::{Arc, Condvar, Mutex, MutexGuard};
++use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
+ use std::time::Instant;
+
+ /// The uncompleted command buffers a queue holds when made with `new_command_queue`: Metal's
+@@ -85,9 +85,9 @@ struct QueueShared {
+ id: u64,
+ /// The index of the device's `VkQueue` the queue submits to.
+ vk_queue: usize,
+- /// LOCAL (Atlas, DEEP-CPU): the lanes' turn its encoders' calls are lowered on under
+- /// `RenderLoweringPolicy::Worker` (`render/lowering_worker.rs`).
+- lowering_lane: usize,
++ /// LOCAL (Atlas, DEEP-CPU): assigned when the queue first hands render work to
++ /// Worker, then stable for its life. Paging and AtCall-only queues consume no lane.
++ lowering_lane: OnceLock,
+ label: Mutex>,
+ /// The slots its uncompleted command buffers hold.
+ slots: Arc,
+@@ -278,7 +278,7 @@ impl Device {
+ device: self.clone(),
+ id,
+ vk_queue,
+- lowering_lane: self.shared().deferred.next_queue_lane(),
++ lowering_lane: OnceLock::new(),
+ label: Mutex::new(None),
+ slots: Slots::new(count, Arc::clone(&self.shared().uncommitted)),
+ latest_gpu_end: Mutex::new(0),
+@@ -382,10 +382,13 @@ impl CommandQueue {
+ self.0.id
+ }
+
+- /// LOCAL (Atlas, DEEP-CPU): the lanes' turn its encoders' calls are lowered on
+- /// (`render/lowering_worker.rs`).
++ /// LOCAL (Atlas, DEEP-CPU): the lanes' turn this queue takes on its first render
++ /// lowering, unchanged thereafter (`render/lowering_worker.rs`).
+ pub(crate) fn lowering_lane(&self) -> usize {
+- self.0.lowering_lane
++ *self
++ .0
++ .lowering_lane
++ .get_or_init(|| self.0.device.shared().deferred.next_queue_lane())
+ }
+
+ /// The index of the device's `VkQueue` the queue submits to.
+diff --git a/crates/metal2vulkan-runtime/src/render/deferral.rs b/crates/metal2vulkan-runtime/src/render/deferral.rs
+index 27ac4980..c1a7d589 100644
+--- a/crates/metal2vulkan-runtime/src/render/deferral.rs
++++ b/crates/metal2vulkan-runtime/src/render/deferral.rs
+@@ -502,14 +502,14 @@ impl LoweringSlot {
+ pub(crate) struct DeferredEncoders {
+ slots: Mutex>>,
+ worker: OnceLock>,
+- /// LOCAL (Atlas, DEEP-CPU): the device's command queues made, which take the lowering lanes
+- /// in turn (`render/lowering_worker.rs`).
++ /// LOCAL (Atlas, DEEP-CPU): the device's queues that started render lowering, which
++ /// take the lowering lanes in turn (`render/lowering_worker.rs`).
+ queues: AtomicUsize,
+ }
+
+ impl DeferredEncoders {
+- /// LOCAL (Atlas, DEEP-CPU): the lanes' turn of a command queue made now, which its
+- /// encoders' slots are handed to for the queue's life (`render/lowering_worker.rs`).
++ /// LOCAL (Atlas, DEEP-CPU): the lanes' turn of a queue starting render lowering,
++ /// kept for its life (`render/lowering_worker.rs`).
+ pub(crate) fn next_queue_lane(&self) -> usize {
+ self.queues.fetch_add(1, Ordering::Relaxed)
+ }
+diff --git a/crates/metal2vulkan-runtime/src/render/lowering_worker.rs b/crates/metal2vulkan-runtime/src/render/lowering_worker.rs
+index b3a91261..744f9717 100644
+--- a/crates/metal2vulkan-runtime/src/render/lowering_worker.rs
++++ b/crates/metal2vulkan-runtime/src/render/lowering_worker.rs
+@@ -2,8 +2,9 @@
+ //! device's render encoders hand them, while the program goes on.
+ //!
+ //! - **Lanes.** LOCAL (Atlas, DEEP-CPU): the device lowers on up to [`lanes`] threads, one per
+-//! lane. Each command queue keeps one lane for its life, the queues taking the lanes in turn as
+-//! they are made (`DeferredEncoders::next_queue_lane`), and its encoders' slots are handed to that
++//! lane. A command queue takes a lane at its first render lowering and keeps it for its
++//! life (`DeferredEncoders::next_queue_lane`); paging and AtCall-only queues take none.
++//! Its encoders' slots are handed to that
+ //! lane alone. So one queue's slots are lowered one at a time, in the order they were handed, as
+ //! on the single thread before; only slots of queues on different lanes are lowered at once, as
+ //! the program's threads of different queues lower theirs at once under
+diff --git a/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs b/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs
+index d08ccc0d..b8651f69 100644
+--- a/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs
++++ b/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs
+@@ -1120,10 +1120,14 @@ fn two_queues(device: &Device, policy: RenderLoweringPolicy, refuse: bool) -> Tw
+ let state = rectangle_state(device);
+ let lanes = crate::render::lowering_lanes();
+ let qa = device.new_command_queue().unwrap();
+- let mut qb = device.new_command_queue().unwrap();
+- while qb.lowering_lane() % lanes == qa.lowering_lane() % lanes {
+- qb = device.new_command_queue().unwrap();
+- }
++ // Paging and other non-rendering queues must not consume lowering lanes. With
++ // creation-time assignment these queues put B on A's lane, leaving the other
++ // lanes idle and preventing the overlap checked below. Keep them alive for
++ // the whole run, as Reims keeps each task's paging queue.
++ let _paging_queues: Vec<_> = (1..lanes)
++ .map(|_| device.new_command_queue().unwrap())
++ .collect();
++ let qb = device.new_command_queue().unwrap();
+ let order = Arc::new(Mutex::new(Vec::new()));
+ let handler = |name: &'static str| {
+ let ran = Arc::clone(&order);
diff --git a/patches/metal2vulkan/0045-Recycle-host-copied-textures-images-that-the-host-wr.patch b/patches/metal2vulkan/0045-Recycle-host-copied-textures-images-that-the-host-wr.patch
new file mode 100644
index 0000000..d5d877f
--- /dev/null
+++ b/patches/metal2vulkan/0045-Recycle-host-copied-textures-images-that-the-host-wr.patch
@@ -0,0 +1,298 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Fri, 6 Nov 2026 14:46:21 +0000
+Subject: [PATCH 45/92] Recycle host-copied textures' images that the host
+ writes too
+
+host_placed_image made each Shared or Managed texture's host-transfer image
+directly (placed_image_read), bypassing the image recycler the non-host
+images already use. Images the host writes too (host_reads=false) now go
+through recycled_image with the hosted plan, whose HOST_TRANSFER usage
+already separates their making from non-host images; a miss is
+placed_image's, as before. Images the host only reads (a trapping surface's,
+possibly in non-coherent memory with atom padding) keep the direct path and
+are never parked or taken: their making does not tell those placements apart.
+
+The recycler's bounds, last-holder parking, UNDEFINED hand-over and the
+host zeroing of new textures are unchanged. Tests on the CPU ICD: a
+recycled host-copied texture reads zero on the host and through a blit;
+sixty frames make images in the first frame alone; an uncommitted command
+buffer's texture is not parked until it completed and went.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/recycle.rs | 5 +-
+ .../metal2vulkan-runtime/src/tests/recycle.rs | 203 +++++++++++++++++-
+ crates/metal2vulkan-runtime/src/texture.rs | 21 +-
+ 3 files changed, 219 insertions(+), 10 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/recycle.rs b/crates/metal2vulkan-runtime/src/recycle.rs
+index fc916fdd..6493f373 100644
+--- a/crates/metal2vulkan-runtime/src/recycle.rs
++++ b/crates/metal2vulkan-runtime/src/recycle.rs
+@@ -36,7 +36,10 @@
+ //! - **When.** As the last holder goes: every command buffer that used the image or buffer
+ //! completed (they hold it), so no GPU work reaches it. Not an image of a shareable texture, one
+ //! that took its storage form, one presenting a stand-in, or one whose memory is not its
+-//! placement alone; not a heap's buffer, nor a buffer of the caller's or over host pages.
++//! placement alone, nor one with host-transfer usage the host only reads (LOCAL (Atlas): a
++//! trapping surface's, whose memory may be mapped without coherence; one the host copies into
++//! too is recycled, its usage in its making's plan); not a heap's buffer, nor a buffer of the
++//! caller's or over host pages.
+ //! - **Which.** A take hands out the latest parked object of its making, found through a map of
+ //! each making's parked objects (a hash of the making, not a search of every parked one).
+ //! - **Bounded.** At most [`IMAGES`]' and [`BUFFERS`]' count and bytes parked, and none parked
+diff --git a/crates/metal2vulkan-runtime/src/tests/recycle.rs b/crates/metal2vulkan-runtime/src/tests/recycle.rs
+index f948b651..7ce08241 100644
+--- a/crates/metal2vulkan-runtime/src/tests/recycle.rs
++++ b/crates/metal2vulkan-runtime/src/tests/recycle.rs
+@@ -23,12 +23,24 @@
+ //! the same length was filled and released: the inplace-surface probe's `fresh` mode).
+ //! - **Each frame's buffers, recycled.** Eight `Private` buffers made, filled and released each of
+ //! sixty frames take parked buffers from the second frame on.
++//! - **A recycled host-copied texture reads zero.** A `Shared` texture's image, made with
++//! host-transfer usage and zeroed on the host (`images_started_on_the_host`), cleared to a
++//! colour and released, then a texture of the same descriptor: it takes the parked image (the
++//! same `VkImage`, none made), zeroed on the host again, and every texel reads zero, on the host
++//! and through a blit, never the colour.
++//! - **Each frame's host-copied textures, recycled.** Eight such textures made, cleared and
++//! released each of sixty frames: images made in the first frame alone, every later texture's
++//! a parked one, each zeroed on the host.
++//! - **A command buffer's texture is not recycled before it completes.** A `Shared` texture an
++//! uncommitted command buffer clears, released: a texture of the same descriptor made meanwhile
++//! takes no parked image; once the command buffer completed and went, the next one takes its
++//! image, zeroed on the host, never the colour.
+
+ use super::blit_holds::{Scratch, WAIT};
+ use crate::{
+ BlitOption, Buffer, ClearColor, CommandBufferStatus, CommandQueue, Device, DeviceKind,
+- DeviceOptions, LoadAction, Origin, RenderPassDescriptor, ResourceOptions, ShaderCacheOptions,
+- Size, StoreAction, Texture, TextureDescriptor,
++ DeviceOptions, LoadAction, Origin, Region, RenderPassDescriptor, ResourceOptions,
++ ShaderCacheOptions, Size, StoreAction, Texture, TextureDescriptor,
+ };
+ use metal2vulkan::metal::{PixelFormat, TextureUsage};
+ use std::path::Path;
+@@ -356,3 +368,190 @@ fn each_frames_buffers_take_parked_buffers() {
+ "every frame after the first recycles"
+ );
+ }
++
++/// [`descriptor`]'s, `Shared`: its image takes host copies where the device has them.
++fn shared_descriptor() -> TextureDescriptor {
++ let mut descriptor = descriptor();
++ descriptor.resource_options = ResourceOptions::shared();
++ descriptor
++}
++
++/// The bytes of `texture`, copied out on the host (`get_bytes`).
++fn host_read(texture: &Texture) -> Vec {
++ let mut bytes = vec![0xcd; (SIDE * SIDE * 4) as usize];
++ texture
++ .get_bytes(
++ &mut bytes,
++ SIDE * 4,
++ 0,
++ Region::new_2d(0, 0, SIDE, SIDE),
++ 0,
++ 0,
++ )
++ .unwrap();
++ bytes
++}
++
++#[test]
++fn a_recycled_host_copied_texture_reads_zero() {
++ let scratch = Scratch::new("recycle-host-fresh");
++ let device = device(&scratch.0);
++ let queue = device.new_command_queue().unwrap();
++ let start = device.work_counts();
++ let first = device.new_texture(&shared_descriptor()).unwrap();
++ assert_eq!(
++ device.work_counts().images_started_on_the_host - start.images_started_on_the_host,
++ 1,
++ "the texture's image took host copies and was zeroed on the host"
++ );
++ let raw = first.raw_image().unwrap();
++ assert!(
++ host_read(&first).iter().all(|&b| b == 0),
++ "a new texture reads zero"
++ );
++ clear(&queue, &first);
++ assert!(
++ host_read(&first).iter().all(|&b| b != 0),
++ "the clear wrote every texel"
++ );
++ let before = device.work_counts();
++ drop(first);
++ parked_at_least(&device, before.object_churn.images_parked + 1);
++ let second = device.new_texture(&shared_descriptor()).unwrap();
++ let after = device.work_counts();
++ assert_eq!(
++ after.object_churn.images_recycled - before.object_churn.images_recycled,
++ 1,
++ "the second texture took the first one's parked image"
++ );
++ assert_eq!(second.raw_image().unwrap(), raw, "the same VkImage");
++ assert_eq!(
++ after.object_churn.vk_images_made, before.object_churn.vk_images_made,
++ "no image made"
++ );
++ assert_eq!(
++ after.images_started_on_the_host - before.images_started_on_the_host,
++ 1,
++ "the recycled image was zeroed on the host"
++ );
++ let copies = after.host_texel_copies;
++ assert!(
++ host_read(&second).iter().all(|&b| b == 0),
++ "every texel of the recycled texture reads zero on the host, not the colour"
++ );
++ assert!(
++ device.work_counts().host_texel_copies > copies,
++ "the read copied on the host"
++ );
++ assert!(
++ read(&device, &queue, &second).iter().all(|&b| b == 0),
++ "every texel of the recycled texture reads zero through a blit, not the colour"
++ );
++}
++
++#[test]
++fn each_frames_host_copied_textures_take_parked_images() {
++ let scratch = Scratch::new("recycle-host-frames");
++ let device = device(&scratch.0);
++ let queue = device.new_command_queue().unwrap();
++ const FRAMES: u64 = 60;
++ const TEXTURES: u64 = 8;
++ let start = device.work_counts();
++ let mut first_frame = None;
++ for frame in 1..=FRAMES {
++ let textures: Vec = (0..TEXTURES)
++ .map(|_| device.new_texture(&shared_descriptor()).unwrap())
++ .collect();
++ for texture in &textures {
++ clear(&queue, texture);
++ }
++ if frame == 1 {
++ first_frame = Some(device.work_counts().object_churn.vk_images_made);
++ }
++ drop(textures);
++ // The images go as their command buffers' holds do, which a completion may let go of
++ // after the wait returned.
++ parked_at_least(&device, start.object_churn.images_parked + frame * TEXTURES);
++ }
++ let end = device.work_counts();
++ let recycled = end.object_churn.images_recycled - start.object_churn.images_recycled;
++ eprintln!(
++ "RECYCLE: {FRAMES} frames of {TEXTURES} host-copied textures: {recycled} images recycled, \
++ {} made, {} started on the host, {} evicted",
++ end.object_churn.vk_images_made - start.object_churn.vk_images_made,
++ end.images_started_on_the_host - start.images_started_on_the_host,
++ end.object_churn.images_evicted - start.object_churn.images_evicted
++ );
++ assert_eq!(
++ end.images_started_on_the_host - start.images_started_on_the_host,
++ FRAMES * TEXTURES,
++ "every texture's image was zeroed on the host"
++ );
++ assert_eq!(
++ recycled,
++ (FRAMES - 1) * TEXTURES,
++ "every frame after the first recycles"
++ );
++ assert_eq!(
++ end.object_churn.vk_images_made,
++ first_frame.unwrap(),
++ "no image made after the first frame"
++ );
++}
++
++#[test]
++fn a_command_buffers_host_copied_texture_waits_for_it() {
++ let scratch = Scratch::new("recycle-host-pending");
++ let device = device(&scratch.0);
++ let queue = device.new_command_queue().unwrap();
++ let first = device.new_texture(&shared_descriptor()).unwrap();
++ let raw = first.raw_image().unwrap();
++ let command_buffer = queue.command_buffer().unwrap();
++ {
++ let mut pass = RenderPassDescriptor::new();
++ let color = &mut pass.color_attachments[0];
++ color.texture = Some(first.clone());
++ color.load_action = LoadAction::Clear;
++ color.store_action = StoreAction::Store;
++ color.clear_color = ClearColor::new(0.25, 0.5, 0.75, 1.0);
++ command_buffer
++ .render_command_encoder(&pass)
++ .unwrap()
++ .end_encoding()
++ .unwrap();
++ }
++ let before = device.work_counts().object_churn;
++ drop(first);
++ // The uncommitted command buffer holds the texture: its image is not parked.
++ let meanwhile = device.new_texture(&shared_descriptor()).unwrap();
++ let after = device.work_counts().object_churn;
++ assert_eq!(after.images_parked, before.images_parked, "nothing parked");
++ assert_eq!(
++ after.images_recycled, before.images_recycled,
++ "the texture made meanwhile took no parked image"
++ );
++ assert_ne!(meanwhile.raw_image().unwrap(), raw, "a new VkImage");
++ command_buffer.commit().unwrap();
++ assert!(command_buffer.wait_until_completed_for(WAIT).is_ok());
++ assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
++ drop(command_buffer);
++ parked_at_least(&device, before.images_parked + 1);
++ let started = device.work_counts();
++ let next = device.new_texture(&shared_descriptor()).unwrap();
++ let taken = device.work_counts();
++ assert_eq!(
++ taken.object_churn.images_recycled - started.object_churn.images_recycled,
++ 1,
++ "the next texture took the completed command buffer's image"
++ );
++ assert_eq!(next.raw_image().unwrap(), raw, "the same VkImage");
++ assert_eq!(
++ taken.images_started_on_the_host - started.images_started_on_the_host,
++ 1,
++ "zeroed on the host"
++ );
++ assert!(
++ host_read(&next).iter().all(|&b| b == 0),
++ "every texel reads zero, not the pending clear's colour"
++ );
++}
+diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs
+index f8ac72a6..53ddc844 100644
+--- a/crates/metal2vulkan-runtime/src/texture.rs
++++ b/crates/metal2vulkan-runtime/src/texture.rs
+@@ -3102,13 +3102,20 @@ impl Device {
+ }
+ let mut hosted = plan.clone();
+ hosted.usage |= ImageUsageFlags::HOST_TRANSFER;
+- let (raw, placement) = (self.placed_image_read(
+- &hosted,
+- texture_type,
+- class,
+- shared.sharing(),
+- host_reads,
+- ))
++ // An image the host writes too is a parked one of its making where one is parked
++ // (`recycle.rs`), its host-transfer usage in its plan: on a miss, `placed_image`'s, as
++ // before. One the host only reads (a trapping surface's) may lie in memory the host maps
++ // without coherence, which its making does not tell apart: never parked nor taken.
++ let (raw, placement) = match host_reads {
++ true => self.placed_image_read(
++ &hosted,
++ texture_type,
++ class,
++ shared.sharing(),
++ true,
++ ),
++ false => self.recycled_image(&hosted, texture_type, class, shared.sharing()),
++ }
+ .ok()?;
+ Some((hosted, raw, placement))
+ }
diff --git a/patches/metal2vulkan/0046-Clarify-host-copy-initialization-of-recycled-images.patch b/patches/metal2vulkan/0046-Clarify-host-copy-initialization-of-recycled-images.patch
new file mode 100644
index 0000000..9915f28
--- /dev/null
+++ b/patches/metal2vulkan/0046-Clarify-host-copy-initialization-of-recycled-images.patch
@@ -0,0 +1,97 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Fri, 6 Nov 2026 14:53:07 +0000
+Subject: [PATCH 46/92] Clarify host-copy initialization of recycled images
+
+Document completed prior uses and host visibility before reinitialization; UNDEFINED discards previous contents rather than describing the current layout. Update call-site safety notes and the placement counter contract. Documentation only. cargo fmt --all --check passed in the existing lanes image; the isolated host-image fix passed its 52 focused CPU-ICD tests, and combined compilation remains pending safe memory availability.
+---
+ crates/metal2vulkan-runtime/src/texture.rs | 7 +++++--
+ .../src/texture/host_copy.rs | 16 +++++++++-------
+ crates/metal2vulkan-runtime/src/work_counts.rs | 4 ++--
+ 3 files changed, 16 insertions(+), 11 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs
+index 53ddc844..ed552832 100644
+--- a/crates/metal2vulkan-runtime/src/texture.rs
++++ b/crates/metal2vulkan-runtime/src/texture.rs
+@@ -3292,7 +3292,9 @@ impl Device {
+ let zeros = vec![0; *length as usize];
+ let copies: Vec = copies.iter().map(buffer_image_copy).collect();
+ // SAFETY: the image is live, made with host-transfer usage and bound to memory of its
+- // own, which nothing used yet; every copy lies within it and reads within `zeros`.
++ // own. It is new or recycled after its last holder released it, with earlier device
++ // uses completed and writes made available to the host (`recycle.rs`). Every copy
++ // lies within it and reads within `zeros`.
+ unsafe {
+ host_copy::start(
+ functions,
+@@ -3312,7 +3314,8 @@ impl Device {
+ (moved, host_copies, self.shared().host_copies.as_ref())
+ {
+ // SAFETY: the image is live, made with host-transfer usage and bound to memory of its
+- // own, which nothing used yet.
++ // own. It is new or recycled after its last holder released it, with earlier device
++ // uses completed and writes made available to the host (`recycle.rs`).
+ unsafe { host_copy::transition(functions, self.shared().vk().handle(), raw, aspects) }?;
+ self.shared().counts.image_started_on_the_host();
+ return Ok(image);
+diff --git a/crates/metal2vulkan-runtime/src/texture/host_copy.rs b/crates/metal2vulkan-runtime/src/texture/host_copy.rs
+index e55672d5..d985a7cc 100644
+--- a/crates/metal2vulkan-runtime/src/texture/host_copy.rs
++++ b/crates/metal2vulkan-runtime/src/texture/host_copy.rs
+@@ -119,14 +119,16 @@ pub(crate) unsafe fn reaches_general(
+ && destinations[..written.1.min(destinations.len())].contains(&general)
+ }
+
+-/// Move the new `image` (no command or host copy used it yet) of `aspects` from `UNDEFINED` to
+-/// `GENERAL` on the host, then copy `zeros` over every texel `copies` reach (`zero_copies`, each
+-/// within `zeros` from its start).
++/// Initialize a new or recycled `image` of `aspects` on the host: discard its previous contents
++/// with a transition from `UNDEFINED` to `GENERAL`, then copy `zeros` over every texel `copies`
++/// reach (`zero_copies`, each within `zeros` from its start).
+ ///
+ /// # Safety
+ ///
+ /// `functions` are `device`'s, `image` is a live image of it with host-transfer usage, bound to
+-/// memory, which nothing else uses.
++/// its own memory range, with no outstanding use. Any earlier device use has completed and its
++/// writes have been made available to the host (`HOST` / `HOST_READ`). A recycled image meets
++/// these conditions when its last holder releases it (`recycle.rs`, `Barrier::to_host`).
+ pub(super) unsafe fn start(
+ functions: &DeviceFn,
+ device: vk::Device,
+@@ -142,8 +144,8 @@ pub(super) unsafe fn start(
+ unsafe { write(functions, device, image, zeros, copies) }
+ }
+
+-/// Move the new `image` (no command or host copy used it yet) of `aspects` from `UNDEFINED` to
+-/// `GENERAL` on the host, writing no texel (a decoded twin's, `Start::Moved`).
++/// Discard a new or recycled `image`'s previous contents by moving `aspects` from `UNDEFINED`
++/// to `GENERAL` on the host, writing no texel (a decoded twin's, `Start::Moved`).
+ ///
+ /// # Safety
+ ///
+@@ -165,7 +167,7 @@ pub(super) unsafe fn transition(
+ base_array_layer: 0,
+ layer_count: vk::REMAINING_ARRAY_LAYERS,
+ });
+- // SAFETY: the caller's contract; the image is in `UNDEFINED`, which the move leaves.
++ // SAFETY: the caller's contract; `UNDEFINED` discards contents from any previous layout.
+ if exit_guard::in_section() { exit_guard::called(Call::TransitionImageLayout); }
+ unsafe { (functions.transition_image_layout_ext)(device, 1, &transition) }
+ .result()
+diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs
+index aac9e4c2..873d951e 100644
+--- a/crates/metal2vulkan-runtime/src/work_counts.rs
++++ b/crates/metal2vulkan-runtime/src/work_counts.rs
+@@ -3816,8 +3816,8 @@ pub struct WorkCounts {
+ /// waits for: a `Shared` or `Managed` texture's first move, `replace_region` or `get_bytes`
+ /// on a device that copies none on the host from memory the host caches.
+ pub staging_submissions: u64,
+- /// New `Shared` and `Managed` textures' images with host-transfer usage placed in memory the
+- /// host does not cache, where the device has none the image may take
++ /// Host-transfer image placements in memory the host does not cache, where the device has
++ /// none the image may take; taking an existing recycled placement adds nothing here
+ /// (`texture/host_copy.rs`): their host copies read at uncached memory's speed (a 1080p
+ /// `get_bytes` 108 ms on a Radeon 780M), and none elsewhere.
+ pub uncached_host_images: u64,
diff --git a/patches/metal2vulkan/0047-diagnostic-per-draw-units-live-pass_draws-and-a-pipe.patch b/patches/metal2vulkan/0047-diagnostic-per-draw-units-live-pass_draws-and-a-pipe.patch
new file mode 100644
index 0000000..11b9a1d
--- /dev/null
+++ b/patches/metal2vulkan/0047-diagnostic-per-draw-units-live-pass_draws-and-a-pipe.patch
@@ -0,0 +1,410 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sat, 7 Nov 2026 16:47:29 +0000
+Subject: [PATCH 47/92] diagnostic: per-draw units (live pass_draws) and a
+ pipeline census in the pass timer
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/pass_times.rs | 252 +++++++++++++++++-
+ .../src/pipeline/graphics.rs | 19 ++
+ 2 files changed, 259 insertions(+), 12 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/pass_times.rs b/crates/metal2vulkan-runtime/src/pass_times.rs
+index 9cd4574c..fe63c8e5 100644
+--- a/crates/metal2vulkan-runtime/src/pass_times.rs
++++ b/crates/metal2vulkan-runtime/src/pass_times.rs
+@@ -188,6 +188,8 @@ pub(crate) enum Class {
+ Pass,
+ Compute,
+ Transfer,
++ /// One draw, where the capture times draws (`pass_draws`).
++ Draw,
+ }
+
+ /// A slot's own timestamp commands (`recorder/thunks.rs`), which the units record through: into a
+@@ -413,6 +415,11 @@ struct RawState {
+ pending_draws: u32,
+ /// The render pass instance that executed it, a secondary.
+ parent: Option,
++ /// Its draw unit open, where the capture times draws.
++ draw_open: Option,
++ /// The graphics pipeline last bound, and the first scissor last set (x, y, w, h).
++ pipeline: u64,
++ scissor: Option<[i64; 4]>,
+ }
+
+ /// A unit of work.
+@@ -427,6 +434,11 @@ struct Unit {
+ /// Its block's index in the capture's and its start query's offset in it.
+ block: usize,
+ offset: u32,
++ /// A draw unit's description, the `VkCommandBuffer` it was recorded on, and the unit open
++ /// there as it was recorded.
++ note: Option,
++ raw: u64,
++ parent: Option,
+ }
+
+ #[derive(Default)]
+@@ -447,6 +459,8 @@ pub(crate) struct Capture {
+ seq: u64,
+ key: usize,
+ queue_label: String,
++ /// Whether each draw is its own unit too (the live switch `pass_draws`, read as it began).
++ draws: bool,
+ state: Mutex,
+ }
+
+@@ -535,6 +549,7 @@ fn start(device: &Device, queue: &CommandQueue, key: usize) -> Option, scissor: Option<[i64; 4]>) {
++ if LIVE.load(Ordering::Relaxed) == 0 {
++ return;
++ }
++ let Some(capture) = capture_of(cb) else {
++ return;
++ };
++ if !capture.draws {
++ return;
++ }
++ let mut state = lock(&capture.state);
++ if let Some(raw) = state.raws.get_mut(&cb.as_raw()) {
++ if let Some(pipeline) = pipeline {
++ raw.pipeline = pipeline;
++ }
++ if scissor.is_some() {
++ raw.scissor = scissor;
++ }
++ }
++}
++
++/// Before a draw `what` of `count` vertices, indices or indirect draws and `instances` on `cb`:
++/// counted as [`draw`], and where the capture times draws, its own unit opened (the last one on
++/// `cb` closed).
++///
++/// # Safety
++///
++/// As the command's: `cb` recording inside a render pass instance (or a secondary of one), by the
++/// caller alone; `st` are its slot's.
++pub(crate) unsafe fn draw_at(st: Stamps, cb: vk::CommandBuffer, what: &'static str, count: u32, instances: u32) {
++ if LIVE.load(Ordering::Relaxed) == 0 {
++ return;
++ }
++ let Some(capture) = capture_of(cb) else {
++ return;
++ };
++ let mut guard = lock(&capture.state);
++ let state = &mut *guard;
++ let Some(raw) = state.raws.get_mut(&cb.as_raw()) else {
++ return;
++ };
++ match raw.open.or(raw.parent) {
++ Some(at) => state.units[at].count += 1,
++ None => raw.pending_draws += 1,
++ }
++ if !capture.draws {
++ return;
++ }
++ let scissor = raw.scissor.map_or_else(|| "-".to_owned(), |[x, y, w, h]| format!("{x}+{y}+{w}x{h}"));
++ let note = format!("{what}:{count}x{instances};pipe={:#x};sc={scissor}", raw.pipeline);
++ let (encoder, parent) = (raw.encoder, raw.open);
++ // SAFETY: the caller's.
++ unsafe { close_draw(st, cb, state) };
++ let unit = Unit {
++ class: Class::Draw,
++ tag: None,
++ site: None,
++ command: what,
++ encoder,
++ label: None,
++ count: 1,
++ block: 0,
++ offset: 0,
++ note: Some(note),
++ raw: cb.as_raw(),
++ parent,
++ };
++ // SAFETY: the caller's; the capture times draws only where the device resets its queries on
++ // the host, so `open` records no reset inside the render pass instance.
++ let opened = unsafe { open(st, cb, &capture, state, unit) };
++ if let Some(raw) = state.raws.get_mut(&cb.as_raw()) {
++ raw.draw_open = opened;
++ }
++}
++
+ /// Before a draw on `cb`: counted in its render pass instance, or the one that executes it.
+ pub(crate) fn draw(cb: vk::CommandBuffer) {
+ if LIVE.load(Ordering::Relaxed) == 0 {
+@@ -946,6 +1075,7 @@ macro_rules! hook {
+ };
+ (before cmd_execute_commands, $st:expr, $cb:ident, $count:ident, $buffers:ident) => {
+ if $crate::pass_times::on() {
++ unsafe { $crate::pass_times::draws_end($st, $cb) };
+ unsafe { $crate::pass_times::execute($cb, $count, $buffers) }
+ }
+ };
+@@ -956,17 +1086,38 @@ macro_rules! hook {
+ }
+ }
+ };
+- (before cmd_draw, $st:expr, $cb:ident $(, $a:ident)*) => {
+- $crate::pass_times::hook!(@draw $cb)
++ (before cmd_draw, $st:expr, $cb:ident, $v:ident, $i:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@draw_at $st, $cb, "draw", $v, $i)
+ };
+- (before cmd_draw_indexed, $st:expr, $cb:ident $(, $a:ident)*) => {
+- $crate::pass_times::hook!(@draw $cb)
++ (before cmd_draw_indexed, $st:expr, $cb:ident, $v:ident, $i:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@draw_at $st, $cb, "indexed", $v, $i)
+ };
+- (before cmd_draw_indirect, $st:expr, $cb:ident $(, $a:ident)*) => {
+- $crate::pass_times::hook!(@draw $cb)
++ (before cmd_draw_indirect, $st:expr, $cb:ident, $b:ident, $o:ident, $n:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@draw_at $st, $cb, "indirect", $n, 0)
+ };
+- (before cmd_draw_indexed_indirect, $st:expr, $cb:ident $(, $a:ident)*) => {
+- $crate::pass_times::hook!(@draw $cb)
++ (before cmd_draw_indexed_indirect, $st:expr, $cb:ident, $b:ident, $o:ident, $n:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@draw_at $st, $cb, "indexed-indirect", $n, 0)
++ };
++ (before cmd_bind_pipeline, $st:expr, $cb:ident, $point:ident, $pipeline:ident) => {
++ if $crate::pass_times::on() && $point == ash::vk::PipelineBindPoint::GRAPHICS {
++ $crate::pass_times::draw_state($cb, Some(ash::vk::Handle::as_raw($pipeline)), None)
++ }
++ };
++ (before cmd_set_scissor, $st:expr, $cb:ident, $first:ident, $count:ident, $scissors:ident) => {
++ if $crate::pass_times::on() && $first == 0 && $count > 0 && !$scissors.is_null() {
++ // SAFETY: the command's: `count` rectangles at `scissors`.
++ let r = unsafe { *$scissors };
++ $crate::pass_times::draw_state(
++ $cb,
++ None,
++ Some([r.offset.x.into(), r.offset.y.into(), r.extent.width.into(), r.extent.height.into()]),
++ )
++ }
++ };
++ (before cmd_end_render_pass, $st:expr, $cb:ident) => {
++ if $crate::pass_times::on() {
++ unsafe { $crate::pass_times::draws_end($st, $cb) }
++ }
+ };
+ (before cmd_draw_mesh_tasks, $st:expr, $cb:ident $(, $a:ident)*) => {
+ $crate::pass_times::hook!(@draw $cb)
+@@ -1021,6 +1172,11 @@ macro_rules! hook {
+ $crate::pass_times::draw($cb)
+ }
+ };
++ (@draw_at $st:expr, $cb:ident, $what:literal, $n:expr, $i:expr) => {
++ if $crate::pass_times::on() {
++ unsafe { $crate::pass_times::draw_at($st, $cb, $what, $n, $i) }
++ }
++ };
+ (@work $st:expr, $cb:ident, $class:ident, $name:literal) => {
+ if $crate::pass_times::on() {
+ unsafe { $crate::pass_times::work($st, $cb, $crate::pass_times::Class::$class, $name) }
+@@ -1122,6 +1278,7 @@ pub(crate) fn read(capture: Arc, placement: Placement<'_>) {
+ _ => "-".to_owned(),
+ };
+ let kind = match (unit.class, unit.tag) {
++ (Class::Draw, _) => "draw".to_owned(),
+ (Class::Pass, Some(Tag::Pass(PassAt::Resolve))) => "render-pass-resolve".to_owned(),
+ (Class::Pass, Some(Tag::Pass(_))) => "render-pass".to_owned(),
+ (Class::Pass, _) => {
+@@ -1150,10 +1307,13 @@ pub(crate) fn read(capture: Arc, placement: Placement<'_>) {
+ None => format!("internal:{}", unit.command),
+ },
+ };
+- let attachments = unit
+- .label
+- .as_ref()
+- .map_or_else(|| "-".to_owned(), PassLabel::format);
++ let attachments = match &unit.note {
++ Some(note) => note.replace(',', ";"),
++ None => unit
++ .label
++ .as_ref()
++ .map_or_else(|| "-".to_owned(), PassLabel::format),
++ };
+ let split = match unit.tag {
+ _ if instance(unit) => {
+ let n = totals.get(&unit.encoder).copied().unwrap_or(1);
+@@ -1180,6 +1340,12 @@ pub(crate) fn read(capture: Arc, placement: Placement<'_>) {
+ format!("{i}/{n}:{cause};{records}{not_inline}")
+ }
+ Some(Tag::Pass(PassAt::Resolve)) => "resolve".to_owned(),
++ _ if unit.class == Class::Draw => {
++ let parent = unit
++ .parent
++ .or_else(|| state.raws.get(&unit.raw).and_then(|r| r.parent));
++ parent.map_or_else(|| "in=?".to_owned(), |p| format!("in={p}"))
++ }
+ _ => "-".to_owned(),
+ };
+ let _ = writeln!(
+@@ -1195,3 +1361,65 @@ pub(crate) fn read(capture: Arc, placement: Placement<'_>) {
+ drop(state);
+ capture.times.append(&out, lines);
+ }
++
++/// LOCAL (Atlas) diagnostic: the pipeline census, while the pass timer is on: one line per
++/// graphics pipeline made, appended to `/pipes-.csv` (its handle, which the draw units
++/// name, its color blend states, its pass's shape and its stages' SPIR-V digests), and each stage's
++/// SPIR-V written once to `/spv/.spv`.
++pub(crate) fn pipeline_made(
++ raw: vk::Pipeline,
++ blends: &[vk::PipelineColorBlendAttachmentState],
++ pass: &dyn std::fmt::Debug,
++ topology: &dyn std::fmt::Debug,
++ stages: &[(&str, &str, &[u32])],
++) {
++ let Some(dir) = dir() else {
++ return;
++ };
++ static OUT: LazyLock>> = LazyLock::new(Mutex::default);
++ static WRITTEN: LazyLock>> = LazyLock::new(Mutex::default);
++ let fnv = |words: &[u32]| {
++ words.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, w| {
++ w.to_le_bytes()
++ .iter()
++ .fold(h, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
++ })
++ };
++ let mut line = format!("{:#x},{:?}", raw.as_raw(), topology);
++ line.push(',');
++ for (i, b) in blends.iter().enumerate() {
++ let _ = write!(
++ line,
++ "{}{i}:{}/m{:x}/{}-{}-{}/{}-{}-{}",
++ if i > 0 { "|" } else { "" },
++ b.blend_enable,
++ b.color_write_mask.as_raw(),
++ b.src_color_blend_factor.as_raw(),
++ b.dst_color_blend_factor.as_raw(),
++ b.color_blend_op.as_raw(),
++ b.src_alpha_blend_factor.as_raw(),
++ b.dst_alpha_blend_factor.as_raw(),
++ b.alpha_blend_op.as_raw(),
++ );
++ }
++ let _ = write!(line, ",{}", format!("{pass:?}").replace(',', ";").replace('\n', " "));
++ let spv = dir.join("spv");
++ for (stage, entry, words) in stages {
++ let digest = fnv(words);
++ let _ = write!(line, ",{stage}:{entry}:{digest:016x}");
++ if lock(&WRITTEN).insert(digest) {
++ let _ = std::fs::create_dir_all(&spv);
++ let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect();
++ let _ = std::fs::write(spv.join(format!("{digest:016x}.spv")), bytes);
++ }
++ }
++ line.push('\n');
++ let mut out = lock(&OUT);
++ if out.is_none() {
++ let path = dir.join(format!("pipes-{}.csv", std::process::id()));
++ *out = std::fs::OpenOptions::new().create(true).append(true).open(path).ok();
++ }
++ if let Some(file) = out.as_mut() {
++ let _ = file.write_all(line.as_bytes());
++ }
++}
+diff --git a/crates/metal2vulkan-runtime/src/pipeline/graphics.rs b/crates/metal2vulkan-runtime/src/pipeline/graphics.rs
+index 9e061710..ec4d5eee 100644
+--- a/crates/metal2vulkan-runtime/src/pipeline/graphics.rs
++++ b/crates/metal2vulkan-runtime/src/pipeline/graphics.rs
+@@ -1233,6 +1233,25 @@ impl VariantObjects {
+ shared.counts.driver_diagnostics_withheld(withheld);
+ let (raw, linked) = created?;
+ let created_in = started.elapsed();
++ // LOCAL (Atlas) diagnostic: the pipeline census (`pass_times.rs`).
++ if crate::pass_times::on() {
++ let stages: Vec<(&str, &str, &[u32])> = content
++ .stages
++ .iter()
++ .filter_map(|s| pipeline.stages.get(s.at))
++ .map(|m| {
++ let stage = if m.stage == metal2vulkan::vk::ShaderStage::VERTEX {
++ "vs"
++ } else if m.stage == metal2vulkan::vk::ShaderStage::FRAGMENT {
++ "fs"
++ } else {
++ "other"
++ };
++ (stage, m.entry_point.as_str(), &m.spirv[..])
++ })
++ .collect();
++ crate::pass_times::pipeline_made(raw, &content.blends, &key.pass, &key.topology, &stages);
++ }
+ let kept_at = split.then(std::time::Instant::now);
+ if content.blend_flags.contains(
+ vk::PipelineColorBlendStateCreateFlags::RASTERIZATION_ORDER_ATTACHMENT_ACCESS_EXT,
diff --git a/patches/metal2vulkan/0048-diagnostic-name-a-copy-unit-s-images-in-the-pass-tim.patch b/patches/metal2vulkan/0048-diagnostic-name-a-copy-unit-s-images-in-the-pass-tim.patch
new file mode 100644
index 0000000..c9e7963
--- /dev/null
+++ b/patches/metal2vulkan/0048-diagnostic-name-a-copy-unit-s-images-in-the-pass-tim.patch
@@ -0,0 +1,137 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sat, 7 Nov 2026 16:50:31 +0000
+Subject: [PATCH 48/92] diagnostic: name a copy unit's images in the pass timer
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/image_log.rs | 15 ++++++
+ crates/metal2vulkan-runtime/src/pass_times.rs | 52 +++++++++++++++++--
+ 2 files changed, 64 insertions(+), 3 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/image_log.rs b/crates/metal2vulkan-runtime/src/image_log.rs
+index 36639493..36459411 100644
+--- a/crates/metal2vulkan-runtime/src/image_log.rs
++++ b/crates/metal2vulkan-runtime/src/image_log.rs
+@@ -923,3 +923,18 @@ pub(crate) fn pass_label(
+ extent,
+ }
+ }
++
++/// LOCAL (Atlas) diagnostic: `image` as the pass timer names a copy's (`pass_times.rs`): its
++/// extent, usage bits and purpose, where the registry knows it.
++pub(crate) fn image_note(image: vk::Image) -> String {
++ match registry().images.get(&image.as_raw()) {
++ Some(e) => format!(
++ "{}x{}:u{:x}:{}",
++ e.extent.width,
++ e.extent.height,
++ e.usage.as_raw(),
++ e.purpose
++ ),
++ None => format!("{:#x}?", image.as_raw()),
++ }
++}
+diff --git a/crates/metal2vulkan-runtime/src/pass_times.rs b/crates/metal2vulkan-runtime/src/pass_times.rs
+index fe63c8e5..933b7d8a 100644
+--- a/crates/metal2vulkan-runtime/src/pass_times.rs
++++ b/crates/metal2vulkan-runtime/src/pass_times.rs
+@@ -150,6 +150,8 @@ pub(crate) enum PassAt {
+ }
+
+ thread_local! {
++ /// A copy's description for the unit it opens (`hook!`'s copies), taken by [`work`].
++ static COPY_NOTE: std::cell::RefCell> = const { std::cell::RefCell::new(None) };
+ static SCOPE: Cell > = const { Cell::new(None) };
+ static SITE: Cell >> = const { Cell::new(None) };
+ }
+@@ -821,6 +823,8 @@ pub(crate) unsafe fn end(st: Stamps, cb: vk::CommandBuffer) {
+ /// As the command's: `cb` recording outside a render pass instance; `st` are its slot's.
+ pub(crate) unsafe fn work(st: Stamps, cb: vk::CommandBuffer, class: Class, command: &'static str) {
+ let site = SITE.with(Cell::take);
++ // A copy's description reaches only a unit this command opens.
++ let _drop_note = DropNote;
+ if LIVE.load(Ordering::Relaxed) == 0 {
+ return;
+ }
+@@ -865,7 +869,7 @@ pub(crate) unsafe fn work(st: Stamps, cb: vk::CommandBuffer, class: Class, comma
+ count: 1,
+ block: 0,
+ offset: 0,
+- note: None,
++ note: COPY_NOTE.with(|n| n.borrow_mut().take()),
+ raw: 0,
+ parent: None,
+ };
+@@ -876,6 +880,15 @@ pub(crate) unsafe fn work(st: Stamps, cb: vk::CommandBuffer, class: Class, comma
+ }
+ }
+
++/// Clears a copy's description that no unit took.
++struct DropNote;
++
++impl Drop for DropNote {
++ fn drop(&mut self) {
++ COPY_NOTE.with(|n| n.borrow_mut().take());
++ }
++}
++
+ /// Close the draw unit open on `cb`, where one is.
+ ///
+ /// # Safety
+@@ -982,6 +995,21 @@ pub(crate) unsafe fn draw_at(st: Stamps, cb: vk::CommandBuffer, what: &'static s
+ }
+ }
+
++/// Before a copy into `dst` (from `src`, an image or null) of `count` regions, the first of
++/// `extent`: its description, for the unit it opens, where any capture is live.
++pub(crate) fn copy_note(src: vk::Image, dst: vk::Image, count: u32, extent: Option<(u32, u32)>) {
++ if LIVE.load(Ordering::Relaxed) == 0 {
++ return;
++ }
++ let (w, h) = extent.unwrap_or((0, 0));
++ let from = match src == vk::Image::null() {
++ true => "buffer".to_owned(),
++ false => image_log::image_note(src),
++ };
++ let note = format!("{count}r:{w}x{h}:{from}>{}", image_log::image_note(dst));
++ COPY_NOTE.with(|n| *n.borrow_mut() = Some(note));
++}
++
+ /// Before a draw on `cb`: counted in its render pass instance, or the one that executes it.
+ pub(crate) fn draw(cb: vk::CommandBuffer) {
+ if LIVE.load(Ordering::Relaxed) == 0 {
+@@ -1140,13 +1168,31 @@ macro_rules! hook {
+ (before cmd_copy_buffer, $st:expr, $cb:ident $(, $a:ident)*) => {
+ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdCopyBuffer")
+ };
+- (before cmd_copy_image, $st:expr, $cb:ident $(, $a:ident)*) => {
++ (before cmd_copy_image, $st:expr, $cb:ident, $src:ident, $sl:ident, $dst:ident, $dl:ident, $count:ident, $regions:ident) => {
++ if $crate::pass_times::on() {
++ $crate::pass_times::copy_note($src, $dst, $count, if $count > 0 && !$regions.is_null() {
++ // SAFETY: the command's: `count` regions.
++ let r = unsafe { *$regions };
++ Some((r.extent.width, r.extent.height))
++ } else {
++ None
++ });
++ }
+ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdCopyImage")
+ };
+ (before cmd_blit_image, $st:expr, $cb:ident $(, $a:ident)*) => {
+ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdBlitImage")
+ };
+- (before cmd_copy_buffer_to_image, $st:expr, $cb:ident $(, $a:ident)*) => {
++ (before cmd_copy_buffer_to_image, $st:expr, $cb:ident, $src:ident, $dst:ident, $dl:ident, $count:ident, $regions:ident) => {
++ if $crate::pass_times::on() {
++ $crate::pass_times::copy_note(ash::vk::Image::null(), $dst, $count, if $count > 0 && !$regions.is_null() {
++ // SAFETY: the command's: `count` regions.
++ let r = unsafe { *$regions };
++ Some((r.image_extent.width, r.image_extent.height))
++ } else {
++ None
++ });
++ }
+ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdCopyBufferToImage")
+ };
+ (before cmd_copy_image_to_buffer, $st:expr, $cb:ident $(, $a:ident)*) => {
diff --git a/patches/metal2vulkan/0049-port-strong-d2da1714-behind-live-group_keep-0-group_.patch b/patches/metal2vulkan/0049-port-strong-d2da1714-behind-live-group_keep-0-group_.patch
new file mode 100644
index 0000000..2297c54
--- /dev/null
+++ b/patches/metal2vulkan/0049-port-strong-d2da1714-behind-live-group_keep-0-group_.patch
@@ -0,0 +1,385 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sat, 7 Nov 2026 16:54:29 +0000
+Subject: [PATCH 49/92] port strong d2da1714 behind live group_keep=0 /
+ group_events=0 (default as A), and the M2V_WBS_AUDIT diagnostic
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/command_buffer/group.rs | 13 +-
+ .../src/command_buffer/rerun.rs | 2 +-
+ .../src/command_buffer/submit.rs | 5 +
+ .../metal2vulkan-runtime/src/device/prime.rs | 6 +-
+ .../metal2vulkan-runtime/src/device/relay.rs | 2 +-
+ .../src/device/staging.rs | 2 +-
+ .../metal2vulkan-runtime/src/device/submit.rs | 4 +-
+ crates/metal2vulkan-runtime/src/lib.rs | 2 +
+ .../metal2vulkan-runtime/src/scheduler/mod.rs | 2 +-
+ .../metal2vulkan-runtime/src/sparse/bind.rs | 1 +
+ crates/metal2vulkan-runtime/src/wbs_audit.rs | 166 ++++++++++++++++++
+ 11 files changed, 193 insertions(+), 12 deletions(-)
+ create mode 100644 crates/metal2vulkan-runtime/src/wbs_audit.rs
+
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/group.rs b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+index 626669dd..6d8051a6 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/group.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+@@ -481,6 +481,13 @@ impl Group {
+ /// the completion turns to wake the scheduler at. Counted once per group, and once more where
+ /// a waiter sends a group kept before.
+ pub(crate) fn keeps(&mut self) -> Option {
++ // LOCAL (Atlas, port of strong d2da1714): with the live switch `group_keep=0` a group is
++ // not kept past its pass. On Arrow Lake (one `VkQueue`) groups kept past a pass sat behind
++ // waits submitted ahead of them by paths that do not look at the group, until i915's
++ // fence timeout (strong A/B 2026-11-07). Default: kept, as build A.
++ if crate::live::get("group_keep").as_deref() == Some("0") {
++ return None;
++ }
+ let first = self.members.first()?;
+ let device = first.submission.buffer().device();
+ if self.full()
+@@ -612,7 +619,7 @@ impl Group {
+ let submitted =
+ shared.submit_logged((queue, Some(value)), fence, &relayed, |vk_queue| unsafe {
+ shared.counts.queue_submitted(submits.len(), buffers);
+- raw.queue_submit(vk_queue, submits, fence.unwrap_or(vk::Fence::null()))
++ { crate::wbs_audit::submits("group", submits); raw.queue_submit(vk_queue, submits, fence.unwrap_or(vk::Fence::null())) }
+ });
+ exit_guard::called(Call::QueueSubmit);
+ self.events.clear();
+@@ -687,7 +694,7 @@ fn submit_alone(device: &Device, after: After<'_>) -> Result<(), vk::Result> {
+ // SAFETY: the batch's submission's own (`submit.rs`).
+ let submitted = shared.submit_logged((queue, Some(value)), fence, relayed, |vk_queue| unsafe {
+ shared.counts.queue_submitted(infos.len(), buffers);
+- raw.queue_submit(vk_queue, infos, fence.unwrap_or(vk::Fence::null()))
++ { crate::wbs_audit::submits("group_one", infos); raw.queue_submit(vk_queue, infos, fence.unwrap_or(vk::Fence::null())) }
+ });
+ exit_guard::called(Call::QueueSubmit);
+ submitted
+@@ -713,7 +720,7 @@ fn signal_alone(
+ // value (no batch signalled them); the `VkQueue` is used under its lock.
+ let submitted = shared.submit_logged((queue, value), None, relayed, |vk_queue| unsafe {
+ shared.counts.queue_submitted(1, 0);
+- raw.queue_submit(vk_queue, &[info], vk::Fence::null())
++ { crate::wbs_audit::submits("group_end_signals", &[info]); raw.queue_submit(vk_queue, &[info], vk::Fence::null()) }
+ });
+ exit_guard::called(Call::QueueSubmit);
+ submitted
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs
+index f11126a1..577341cc 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs
+@@ -420,7 +420,7 @@ impl LoopCheck {
+ (queue, None),
+ Some(fence),
+ &buffer.relayed,
+- |vk_queue| unsafe { raw.queue_submit(vk_queue, &submits, fence) },
++ |vk_queue| unsafe { crate::wbs_audit::submits("rerun", &submits); raw.queue_submit(vk_queue, &submits, fence) },
+ );
+ exit_guard::called(Call::QueueSubmit);
+ if let Err(error) = submitted {
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs
+index bfed8d1c..30fed418 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs
+@@ -365,6 +365,11 @@ impl CommandBufferShared {
+ && !met
+ && sync.binary_waits.is_empty()
+ && sync.binary_signals.is_empty()
++ // LOCAL (Atlas, port of strong d2da1714): with the live switch `group_events=0` a
++ // batch that signals an event joins no group, so no group holds a signal another
++ // submission may already wait for on the one `VkQueue`. Default: joins, as build A.
++ && (crate::live::get("group_events").as_deref() != Some("0")
++ || sync.signals.is_empty())
+ && (state.recorded[state.batch_range(index)].iter())
+ .all(|recorded| recorded.sparse.is_empty())
+ };
+diff --git a/crates/metal2vulkan-runtime/src/device/prime.rs b/crates/metal2vulkan-runtime/src/device/prime.rs
+index 942dc897..8e6cb175 100644
+--- a/crates/metal2vulkan-runtime/src/device/prime.rs
++++ b/crates/metal2vulkan-runtime/src/device/prime.rs
+@@ -691,7 +691,7 @@ impl Primer<'_> {
+ // SAFETY: the caller's; the bind binds nothing, waits for nothing and signals nothing,
+ // and the queue is used under its lock.
+ queues[0]
+- .with(|queue| unsafe { device.queue_bind_sparse(queue, &info, vk::Fence::null()) })
++ .with(|queue| unsafe { crate::wbs_audit::binds("prime_bind", &info); device.queue_bind_sparse(queue, &info, vk::Fence::null()) })
+ .map_err(vulkan)?;
+ self.made(Call::QueueBindSparse);
+ Ok(())
+@@ -806,7 +806,7 @@ impl Primer<'_> {
+ // already; the signal raises the semaphore; the fence is new; the queue is used under its
+ // lock.
+ queues[0]
+- .with(|queue| unsafe { device.queue_submit(queue, &[submit], fence) })
++ .with(|queue| unsafe { crate::wbs_audit::submits("prime", &[submit]); device.queue_submit(queue, &[submit], fence) })
+ .map_err(vulkan)?;
+ self.made(Call::QueueSubmit);
+ let start = Instant::now();
+@@ -830,7 +830,7 @@ impl Primer<'_> {
+ .semaphore(signal)
+ .value(2);
+ // SAFETY: the semaphore is live, its one submitted signal landed, and 2 is above it.
+- unsafe { device.signal_semaphore(&raised) }.map_err(vulkan)?;
++ unsafe { crate::wbs_audit::host_signal("prime_host", &raised); device.signal_semaphore(&raised) }.map_err(vulkan)?;
+ self.made(Call::SignalSemaphore);
+ for queue in queues {
+ // SAFETY: the timeline is live.
+diff --git a/crates/metal2vulkan-runtime/src/device/relay.rs b/crates/metal2vulkan-runtime/src/device/relay.rs
+index 171a5108..a5b605b6 100644
+--- a/crates/metal2vulkan-runtime/src/device/relay.rs
++++ b/crates/metal2vulkan-runtime/src/device/relay.rs
+@@ -486,7 +486,7 @@ impl super::DeviceShared {
+ // value signalled there before where it has one; the queue is used under its
+ // lock.
+ let submitted =
+- unsafe { raw.queue_submit(vk_queue, submits, fence.unwrap_or_default()) };
++ unsafe { crate::wbs_audit::submits("relay", submits); raw.queue_submit(vk_queue, submits, fence.unwrap_or_default()) };
+ exit_guard::called(Call::QueueSubmit);
+ if submitted.is_err() {
+ if let Some((fence, flights)) = logged {
+diff --git a/crates/metal2vulkan-runtime/src/device/staging.rs b/crates/metal2vulkan-runtime/src/device/staging.rs
+index 71396260..1223922d 100644
+--- a/crates/metal2vulkan-runtime/src/device/staging.rs
++++ b/crates/metal2vulkan-runtime/src/device/staging.rs
+@@ -246,7 +246,7 @@ impl Device {
+ shared.counts.queue_submitted(1, buffers.len());
+ let submitted = unsafe {
+ staging.word.restore();
+- raw.queue_submit(queue, &[submit], made.fence)
++ { crate::wbs_audit::submits("staging", &[submit]); raw.queue_submit(queue, &[submit], made.fence) }
+ };
+ exit_guard::called(Call::QueueSubmit);
+ submitted.map_err(|error| self.failed(error))?;
+diff --git a/crates/metal2vulkan-runtime/src/device/submit.rs b/crates/metal2vulkan-runtime/src/device/submit.rs
+index c72b4d5e..e9ace296 100644
+--- a/crates/metal2vulkan-runtime/src/device/submit.rs
++++ b/crates/metal2vulkan-runtime/src/device/submit.rs
+@@ -249,7 +249,7 @@ impl Device {
+ .iter()
+ .map(|info| info.command_buffer_count as usize);
+ shared.counts.queue_submitted(submits.len(), buffers.sum());
+- raw.queue_submit(queue, &submits, objects.fence)
++ { crate::wbs_audit::submits("internal", &submits); raw.queue_submit(queue, &submits, objects.fence) }
+ });
+ // A `vkQueueSubmit` that fails leaves what its submissions reference as it was, or loses
+ // the device: the work goes back as `taken` drops.
+@@ -316,7 +316,7 @@ impl Device {
+ // the timeline's value (the internal lock is held).
+ shared.counts.queue_submitted(0, 0);
+ let bound = shared.use_queue(0, By::Runtime, |queue| unsafe {
+- raw.queue_bind_sparse(queue, &[info], vk::Fence::null())
++ { crate::wbs_audit::binds("internal_bind", &[info]); raw.queue_bind_sparse(queue, &[info], vk::Fence::null()) }
+ });
+ exit_guard::called(Call::QueueBindSparse);
+ bound.map_err(|error| self.failed(error))?;
+diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs
+index 546bf564..bfd49eed 100644
+--- a/crates/metal2vulkan-runtime/src/lib.rs
++++ b/crates/metal2vulkan-runtime/src/lib.rs
+@@ -128,6 +128,8 @@ mod image_barrier;
+ // LOCAL (Atlas) diagnostic: the image census and object registry (M2V_IMAGE_LOG).
+ mod image_log;
+ mod image_plan;
++// LOCAL (Atlas, diagnostic): M2V_WBS_AUDIT=1 reports timeline waits submitted before their signals.
++mod wbs_audit;
+ mod in_place;
+ mod in_place_check;
+ mod index_bounds;
+diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs
+index ff6f6367..64de47fe 100644
+--- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs
++++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs
+@@ -208,7 +208,7 @@ impl Nudge {
+ .value(value);
+ // SAFETY: the device's semaphore, live while its scheduler runs; `value` is above the
+ // semaphore's (the values rise under the scheduler's lock).
+- let signalled = unsafe { self.functions.get().signal_semaphore(&info) };
++ let signalled = unsafe { crate::wbs_audit::host_signal("scheduler_host", &info); self.functions.get().signal_semaphore(&info) };
+ exit_guard::called(exit_guard::Call::SignalSemaphore);
+ signalled.is_ok()
+ }
+diff --git a/crates/metal2vulkan-runtime/src/sparse/bind.rs b/crates/metal2vulkan-runtime/src/sparse/bind.rs
+index 8bb81c7d..177c0d75 100644
+--- a/crates/metal2vulkan-runtime/src/sparse/bind.rs
++++ b/crates/metal2vulkan-runtime/src/sparse/bind.rs
+@@ -336,6 +336,7 @@ pub(crate) fn bind_batch(
+ // lock. Where the queue's failures are relayed, one of the bind's loses the device
+ // (`device/relay.rs`).
+ shared.counts.queue_submitted(0, 0);
++ crate::wbs_audit::binds("sparse_bind", &[info]);
+ let bound = shared.use_queue(queue, By::Runtime, |vk_queue| unsafe {
+ shared
+ .vk()
+diff --git a/crates/metal2vulkan-runtime/src/wbs_audit.rs b/crates/metal2vulkan-runtime/src/wbs_audit.rs
+new file mode 100644
+index 00000000..8e42469a
+--- /dev/null
++++ b/crates/metal2vulkan-runtime/src/wbs_audit.rs
+@@ -0,0 +1,166 @@
++//! LOCAL (Atlas, diagnostic): an audit of waits submitted before their signals.
++//!
++//! With `M2V_WBS_AUDIT=1` (read once per process), every `vkQueueSubmit` and `vkQueueBindSparse`
++//! the runtime makes, and every host `vkSignalSemaphore`, passes its timeline semaphores' waits
++//! and signals here first. A wait for a value above the highest one any submission or host
++//! signal so far asked of that semaphore is a wait before its signal: on a device of one
++//! `VkQueue` (Arrow Lake's ANV) a later submission on that queue can never run before it, so it
++//! holds until i915's fence timeout. Each such wait is written to stderr (at most
++//! [`MOST_LINES`]) with the submitting site; once the signal comes, how long after the wait.
++//! Off, each call is one relaxed load. Semaphores never signalled by a submission seen here (a
++//! caller's own, or one made with a value) are not judged.
++use ash::vk;
++use std::collections::HashMap;
++use std::sync::atomic::{AtomicU64, Ordering};
++use std::sync::{LazyLock, Mutex};
++use std::time::Instant;
++
++/// The most lines written.
++const MOST_LINES: u64 = 400;
++
++static ON: LazyLock =
++ LazyLock::new(|| std::env::var_os("M2V_WBS_AUDIT").is_some_and(|v| v == "1"));
++static LINES: AtomicU64 = AtomicU64::new(0);
++
++#[derive(Default)]
++struct Seen {
++ /// The highest value asked of each semaphore so far.
++ signalled: HashMap,
++ /// Waits found early: (semaphore, value) -> (site, when).
++ early: Vec<(u64, u64, &'static str, Instant)>,
++}
++
++static SEEN: LazyLock> = LazyLock::new(|| Mutex::new(Seen::default()));
++
++fn line(text: String) {
++ if LINES.fetch_add(1, Ordering::Relaxed) < MOST_LINES {
++ eprintln!("m2v-wbs-audit: {text}");
++ }
++}
++
++fn judge(seen: &mut Seen, site: &'static str, waits: &[(vk::Semaphore, u64)]) {
++ for &(semaphore, value) in waits {
++ let key = vk::Handle::as_raw(semaphore);
++ let Some(&highest) = seen.signalled.get(&key) else {
++ continue;
++ };
++ if value > highest {
++ line(format!(
++ "{site}: waits for {key:#x} to reach {value}, asked only {highest} so far"
++ ));
++ seen.early.push((key, value, site, Instant::now()));
++ }
++ }
++}
++
++fn signal(seen: &mut Seen, site: &'static str, signals: &[(vk::Semaphore, u64)]) {
++ for &(semaphore, value) in signals {
++ let key = vk::Handle::as_raw(semaphore);
++ let highest = seen.signalled.entry(key).or_insert(0);
++ *highest = (*highest).max(value);
++ let mut i = 0;
++ while i < seen.early.len() {
++ let (s, v, at, when) = seen.early[i];
++ if s == key && v <= value {
++ line(format!(
++ "{at}: its early wait for {key:#x} to reach {v} met by {site} {:.1} ms later",
++ when.elapsed().as_secs_f64() * 1000.0
++ ));
++ seen.early.swap_remove(i);
++ } else {
++ i += 1;
++ }
++ }
++ }
++}
++
++/// # Safety
++/// `count` items at `semaphores`, and `values` either null or `count` items.
++unsafe fn pairs(
++ semaphores: *const vk::Semaphore,
++ values: *const u64,
++ count: u32,
++ values_count: u32,
++) -> Vec<(vk::Semaphore, u64)> {
++ if semaphores.is_null() || values.is_null() || count == 0 || values_count < count {
++ return Vec::new();
++ }
++ let n = count as usize;
++ // SAFETY: the caller's.
++ let (s, v) = unsafe {
++ (std::slice::from_raw_parts(semaphores, n), std::slice::from_raw_parts(values, n))
++ };
++ s.iter().copied().zip(v.iter().copied()).filter(|&(_, v)| v != 0).collect()
++}
++
++/// The timeline info in a `pNext` chain, if any.
++///
++/// # Safety
++/// `next` is a valid Vulkan `pNext` chain.
++unsafe fn timeline(mut next: *const std::ffi::c_void) -> Option<&'static vk::TimelineSemaphoreSubmitInfo<'static>> {
++ while !next.is_null() {
++ // SAFETY: every Vulkan structure starts with sType and pNext.
++ let base = unsafe { &*next.cast::>() };
++ if base.s_type == vk::StructureType::TIMELINE_SEMAPHORE_SUBMIT_INFO {
++ // SAFETY: its type says so.
++ return Some(unsafe { &*next.cast::>() });
++ }
++ next = base.p_next.cast();
++ }
++ None
++}
++
++/// A `vkQueueSubmit`'s infos, before the call.
++pub(crate) fn submits(site: &'static str, infos: &[vk::SubmitInfo<'_>]) {
++ if !*ON {
++ return;
++ }
++ let mut seen = SEEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ for info in infos {
++ // SAFETY: a submission the caller is about to make, so its pointers are valid.
++ let Some(t) = (unsafe { timeline(info.p_next) }) else {
++ continue;
++ };
++ // SAFETY: as above.
++ let (waits, signals) = unsafe {
++ (
++ pairs(info.p_wait_semaphores, t.p_wait_semaphore_values, info.wait_semaphore_count, t.wait_semaphore_value_count),
++ pairs(info.p_signal_semaphores, t.p_signal_semaphore_values, info.signal_semaphore_count, t.signal_semaphore_value_count),
++ )
++ };
++ judge(&mut seen, site, &waits);
++ signal(&mut seen, site, &signals);
++ }
++}
++
++/// A `vkQueueBindSparse`'s infos, before the call.
++pub(crate) fn binds(site: &'static str, infos: &[vk::BindSparseInfo<'_>]) {
++ if !*ON {
++ return;
++ }
++ let mut seen = SEEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ for info in infos {
++ // SAFETY: as in `submits`.
++ let Some(t) = (unsafe { timeline(info.p_next) }) else {
++ continue;
++ };
++ // SAFETY: as above.
++ let (waits, signals) = unsafe {
++ (
++ pairs(info.p_wait_semaphores, t.p_wait_semaphore_values, info.wait_semaphore_count, t.wait_semaphore_value_count),
++ pairs(info.p_signal_semaphores, t.p_signal_semaphore_values, info.signal_semaphore_count, t.signal_semaphore_value_count),
++ )
++ };
++ judge(&mut seen, site, &waits);
++ signal(&mut seen, site, &signals);
++ }
++}
++
++/// A host `vkSignalSemaphore`, before the call.
++pub(crate) fn host_signal(site: &'static str, info: &vk::SemaphoreSignalInfo<'_>) {
++ if !*ON {
++ return;
++ }
++ let mut seen = SEEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ signal(&mut seen, site, &[(info.semaphore, info.value)]);
++}
diff --git a/patches/metal2vulkan/0050-live-surface_lazy_max_texels-keeps-large-surfaces-th.patch b/patches/metal2vulkan/0050-live-surface_lazy_max_texels-keeps-large-surfaces-th.patch
new file mode 100644
index 0000000..310b286
--- /dev/null
+++ b/patches/metal2vulkan/0050-live-surface_lazy_max_texels-keeps-large-surfaces-th.patch
@@ -0,0 +1,31 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sat, 7 Nov 2026 17:53:51 +0000
+Subject: [PATCH 50/92] live surface_lazy_max_texels keeps large surfaces (the
+ desktop) out of surface_lazy
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/shadow_lazy.rs | 7 +++++++
+ 1 file changed, 7 insertions(+)
+
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index bc393926..dfe3a73c 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -282,8 +282,15 @@ pub(crate) fn takes_surface(width: u32, texels: u64) -> bool {
+ let wide = crate::live::get("surface_lazy_min_width")
+ .and_then(|v| v.parse().ok())
+ .is_none_or(|min: u32| width >= min);
++ // LOCAL (Atlas): `surface_lazy_max_texels` (default none) keeps a larger surface out, the
++ // desktop's among them: its encoders' scissors span the screen, so each copies back the whole
++ // surface, where a Simulator's display copies back what it drew (2026-11-07 loadlab).
++ let small = crate::live::get("surface_lazy_max_texels")
++ .and_then(|v| v.parse().ok())
++ .is_none_or(|max: u64| texels <= max);
+ crate::live::on(SWITCH, false)
+ && wide
++ && small
+ && texels
+ >= crate::live::get("surface_lazy_min_texels")
+ .and_then(|v| v.parse().ok())
diff --git a/patches/metal2vulkan/0051-live-surface_twin_reader_first-a-lazy-surface-s-read.patch b/patches/metal2vulkan/0051-live-surface_twin_reader_first-a-lazy-surface-s-read.patch
new file mode 100644
index 0000000..49e545f
--- /dev/null
+++ b/patches/metal2vulkan/0051-live-surface_twin_reader_first-a-lazy-surface-s-read.patch
@@ -0,0 +1,134 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sat, 7 Nov 2026 23:43:02 +0000
+Subject: [PATCH 51/92] live surface_twin_reader_first: a lazy surface's reader
+ made first is its first shadow
+
+A reader (ShaderRead only) made before its surface's writer stayed an image in place over the
+pages, and the writer's shadow beside it brought its bytes back every frame (about one copy back
+per Sim frame under Coherent). With the switch on (default off) such a reader becomes the
+surface's first lazy shadow, planned with RenderTarget | ShaderRead, so the writer made after
+it binds it through surface_twin. Counted as readers-first in the surface_lazy report.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../metal2vulkan-runtime/src/shadow_lazy.rs | 10 +++++-
+ crates/metal2vulkan-runtime/src/texture.rs | 10 +++++-
+ .../src/texture/surface_twin.rs | 34 +++++++++++++++++++
+ 3 files changed, 52 insertions(+), 2 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index dfe3a73c..6354f6d0 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -144,6 +144,8 @@ static FLUSHED_TEXELS: AtomicU64 = AtomicU64::new(0);
+ static DISCARDED: AtomicU64 = AtomicU64::new(0);
+ /// Textures that bound a surface's image (`surface_twin.rs`).
+ static TWINS: AtomicU64 = AtomicU64::new(0);
++/// Readers made first that became their surface's first shadow (`surface_twin.rs`).
++static READERS_FIRST: AtomicU64 = AtomicU64::new(0);
+ static PRESENTS: AtomicU64 = AtomicU64::new(0);
+ static PRESENTS_UNMATCHED: AtomicU64 = AtomicU64::new(0);
+ /// Milliseconds since the first report's chance at the last report.
+@@ -912,7 +914,7 @@ fn report() {
+ "surface_lazy: taken {taken} refused {refused} resyncs {resyncs} | refused: touched {} \
+ written {} epoch {} own {} uncommitted {} no-standing {} | in: first {} beyond-held {} \
+ changed {} bounded {} | ahead: deferred {} shared {} flushes {} whole {} texels {} \
+- discarded {} presents {} unmatched {} twins {}",
++ discarded {} presents {} unmatched {} twins {} readers-first {}",
+ by[Refused::Touched as usize],
+ by[Refused::Written as usize],
+ by[Refused::Epoch as usize],
+@@ -932,6 +934,7 @@ fn report() {
+ read(&PRESENTS),
+ read(&PRESENTS_UNMATCHED),
+ read(&TWINS),
++ read(&READERS_FIRST),
+ );
+ for lazy in surfaces().iter().take(16) {
+ eprintln!(
+@@ -953,6 +956,11 @@ pub(crate) fn twin_bound() {
+ TWINS.fetch_add(1, Ordering::Relaxed);
+ }
+
++/// A lazy surface's reader made first became its first shadow (`surface_twin.rs`).
++pub(crate) fn reader_first() {
++ READERS_FIRST.fetch_add(1, Ordering::Relaxed);
++}
++
+ /// The counts so far, for a lane or a stderr line: standings taken, refused, and resyncs.
+ pub fn counts() -> (u64, u64, u64) {
+ (
+diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs
+index ed552832..834ee016 100644
+--- a/crates/metal2vulkan-runtime/src/texture.rs
++++ b/crates/metal2vulkan-runtime/src/texture.rs
+@@ -2175,7 +2175,13 @@ impl Device {
+ .facts(self.compile_device().profile());
+ // The buffer's rows lay the texels out, whatever `allowGPUOptimizedContents` says: the
+ // image is planned for the texture's own usage.
+- let usage = texture_usage(descriptor.usage, descriptor.swizzle);
++ let mut usage = texture_usage(descriptor.usage, descriptor.swizzle);
++ // LOCAL (Atlas): a lazy surface's reader made before its writer is the surface's first
++ // shadow, with the writer's usage, so the writer binds it (`surface_twin.rs`).
++ let reader_first = self.surface_reader_first(&texels, layout, usage);
++ if reader_first {
++ usage |= TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
++ }
+ let plan = plan_image(layout, usage, false, &facts)
+ .map_err(|refusal| image_error(call, refusal))?;
+ // Over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their
+@@ -2206,6 +2212,8 @@ impl Device {
+ texture was made"
+ .to_owned(),
+ )
++ } else if reader_first {
++ ShadowCause::RenderTarget
+ } else {
+ // The check's own textures measure the device whatever its policy.
+ let policy = match checking {
+diff --git a/crates/metal2vulkan-runtime/src/texture/surface_twin.rs b/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
+index fb35755d..6a09fb3c 100644
+--- a/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
++++ b/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
+@@ -89,6 +89,40 @@ impl Device {
+ })
+ }
+
++ /// Whether a texture of `usage` (checked as `layout`) over `texels` is a lazy surface's reader
++ /// made before any shadow of it: with the live switch `surface_twin_reader_first` on, it is
++ /// made the surface's first shadow, planned with a writer's usage too, so the writer made
++ /// after it binds it as a later reader binds a writer's ([`surface_twin`](Self::surface_twin))
++ /// instead of making a shadow beside the reader's image in place, whose bytes the writer's
++ /// copies would bring back every frame. Off: the module's order.
++ pub(super) fn surface_reader_first(
++ &self,
++ texels: &Texels,
++ layout: &TextureLayout,
++ usage: TextureUsage,
++ ) -> bool {
++ if !crate::live::on(SWITCH, true) || !crate::live::on("surface_twin_reader_first", false) {
++ return false;
++ }
++ if usage.intersects(TextureUsage::RENDER_TARGET | TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC)
++ || !texels.lies_lazily()
++ || texels.buffer.detached()
++ || crate::in_place::checking()
++ || surface_depth_unit(layout.pixel_format).is_some()
++ {
++ return false;
++ }
++ let Some(key) = texels.surface_key() else {
++ return false;
++ };
++ let twins = lock(&self.shared().textures.twins.0);
++ let first = twins.get(&key).is_some_and(|first| first.texels.strong_count() > 0);
++ if !first {
++ crate::shadow_lazy::reader_first();
++ }
++ !first
++ }
++
+ /// Note `storage`, a new texture's, where it is the first shadow of a lazy surface.
+ pub(super) fn note_surface_first(&self, storage: &Storage) {
+ let Storage::Shadow { image, texels, copies, first: None } = storage else {
diff --git a/patches/metal2vulkan/0052-diagnostic-compute-census-in-the-pass-timer.patch b/patches/metal2vulkan/0052-diagnostic-compute-census-in-the-pass-timer.patch
new file mode 100644
index 0000000..c6c26ae
--- /dev/null
+++ b/patches/metal2vulkan/0052-diagnostic-compute-census-in-the-pass-timer.patch
@@ -0,0 +1,118 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 01:07:36 +0000
+Subject: [PATCH 52/92] diagnostic: compute census in the pass timer
+
+A dispatch's unit notes the compute pipeline last bound on the thread and its group counts;
+compute pipelines made write a census line (entry, module) and modules their SPIR-V, while the
+pass timer is on.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/pass_times.rs | 44 ++++++++++++++++++-
+ .../src/pipeline/objects.rs | 8 ++++
+ 2 files changed, 50 insertions(+), 2 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/pass_times.rs b/crates/metal2vulkan-runtime/src/pass_times.rs
+index 933b7d8a..3bc09c55 100644
+--- a/crates/metal2vulkan-runtime/src/pass_times.rs
++++ b/crates/metal2vulkan-runtime/src/pass_times.rs
+@@ -152,6 +152,8 @@ pub(crate) enum PassAt {
+ thread_local! {
+ /// A copy's description for the unit it opens (`hook!`'s copies), taken by [`work`].
+ static COPY_NOTE: std::cell::RefCell> = const { std::cell::RefCell::new(None) };
++ /// LOCAL (Atlas) diagnostic: the compute pipeline last bound on this thread, for a dispatch's note.
++ pub(crate) static LAST_COMPUTE: std::cell::Cell = const { std::cell::Cell::new(0) };
+ static SCOPE: Cell> = const { Cell::new(None) };
+ static SITE: Cell >> = const { Cell::new(None) };
+ }
+@@ -1129,6 +1131,8 @@ macro_rules! hook {
+ (before cmd_bind_pipeline, $st:expr, $cb:ident, $point:ident, $pipeline:ident) => {
+ if $crate::pass_times::on() && $point == ash::vk::PipelineBindPoint::GRAPHICS {
+ $crate::pass_times::draw_state($cb, Some(ash::vk::Handle::as_raw($pipeline)), None)
++ } else if $crate::pass_times::on() && $point == ash::vk::PipelineBindPoint::COMPUTE {
++ $crate::pass_times::LAST_COMPUTE.with(|c| c.set(ash::vk::Handle::as_raw($pipeline)))
+ }
+ };
+ (before cmd_set_scissor, $st:expr, $cb:ident, $first:ident, $count:ident, $scissors:ident) => {
+@@ -1156,9 +1160,12 @@ macro_rules! hook {
+ (before cmd_draw_mesh_tasks_indirect_count, $st:expr, $cb:ident $(, $a:ident)*) => {
+ $crate::pass_times::hook!(@draw $cb)
+ };
+- (before cmd_dispatch, $st:expr, $cb:ident $(, $a:ident)*) => {
++ (before cmd_dispatch, $st:expr, $cb:ident, $x:ident, $y:ident, $z:ident) => {{
++ if $crate::pass_times::on() {
++ $crate::pass_times::dispatch_note($x, $y, $z);
++ }
+ $crate::pass_times::hook!(@work $st, $cb, Compute, "vkCmdDispatch")
+- };
++ }};
+ (before cmd_dispatch_indirect, $st:expr, $cb:ident $(, $a:ident)*) => {
+ $crate::pass_times::hook!(@work $st, $cb, Compute, "vkCmdDispatchIndirect")
+ };
+@@ -1412,6 +1419,39 @@ pub(crate) fn read(capture: Arc, placement: Placement<'_>) {
+ /// graphics pipeline made, appended to `/pipes-.csv` (its handle, which the draw units
+ /// name, its color blend states, its pass's shape and its stages' SPIR-V digests), and each stage's
+ /// SPIR-V written once to `/spv/.spv`.
++/// LOCAL (Atlas) diagnostic: a dispatch of `x`x`y`x`z` groups of the compute pipeline last bound on
++/// this thread, as the note of the unit it opens.
++pub(crate) fn dispatch_note(x: u32, y: u32, z: u32) {
++ if LIVE.load(Ordering::Relaxed) == 0 {
++ return;
++ }
++ let pipe = LAST_COMPUTE.with(std::cell::Cell::get);
++ COPY_NOTE.with(|n| *n.borrow_mut() = Some(format!("pipe={pipe:#x};groups={x}x{y}x{z}")));
++}
++
++/// LOCAL (Atlas) diagnostic: a compute pipeline made, of `entry` in `module`: a census line.
++pub(crate) fn compute_made(raw: vk::Pipeline, entry: &str, module: vk::ShaderModule) {
++ let Some(dir) = dir() else {
++ return;
++ };
++ let line = format!("compute,{:#x},{entry},m{:x}\n", raw.as_raw(), module.as_raw());
++ let path = dir.join(format!("pipes-{}.csv", std::process::id()));
++ if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
++ let _ = file.write_all(line.as_bytes());
++ }
++}
++
++/// LOCAL (Atlas) diagnostic: a shader module made of `spirv`, kept as `spv/m.spv`.
++pub(crate) fn module_made(module: vk::ShaderModule, spirv: &[u32]) {
++ let Some(dir) = dir() else {
++ return;
++ };
++ let spv = dir.join("spv");
++ let _ = std::fs::create_dir_all(&spv);
++ let bytes: Vec = spirv.iter().flat_map(|w| w.to_le_bytes()).collect();
++ let _ = std::fs::write(spv.join(format!("m{:x}.spv", module.as_raw())), bytes);
++}
++
+ pub(crate) fn pipeline_made(
+ raw: vk::Pipeline,
+ blends: &[vk::PipelineColorBlendAttachmentState],
+diff --git a/crates/metal2vulkan-runtime/src/pipeline/objects.rs b/crates/metal2vulkan-runtime/src/pipeline/objects.rs
+index 8c62eb1c..52c35e5b 100644
+--- a/crates/metal2vulkan-runtime/src/pipeline/objects.rs
++++ b/crates/metal2vulkan-runtime/src/pipeline/objects.rs
+@@ -322,6 +322,10 @@ pub(crate) fn shader_module(
+ let info = vk::ShaderModuleCreateInfo::default().code(spirv);
+ // SAFETY: the code is live SPIR-V words for the call.
+ let raw = unsafe { shared.vk().create_shader_module(&info, None) }.map_err(vulkan)?;
++ // LOCAL (Atlas) diagnostic: the module's words for the compute census (`pass_times.rs`).
++ if crate::pass_times::on() {
++ crate::pass_times::module_made(raw, spirv);
++ }
+ Ok::<_, Error>(ShaderModule { raw })
+ });
+ let gone = modules.sweep();
+@@ -1037,6 +1041,10 @@ impl VariantObjects {
+ .copied()
+ .ok_or_else(|| internal("the driver made no pipeline"))?;
+ self.device.shared().counts.variant_pipeline_made();
++ // LOCAL (Atlas) diagnostic: the compute census (`pass_times.rs`).
++ if crate::pass_times::on() {
++ crate::pass_times::compute_made(raw, &c.object.entry.to_string_lossy(), c.object.module());
++ }
+ let pipeline = RawPipeline {
+ device: self.device.clone(),
+ raw,
diff --git a/patches/metal2vulkan/0053-diagnostic-M2V_VIEW_SHADOW_LOG-names-the-views-that-.patch b/patches/metal2vulkan/0053-diagnostic-M2V_VIEW_SHADOW_LOG-names-the-views-that-.patch
new file mode 100644
index 0000000..99312c0
--- /dev/null
+++ b/patches/metal2vulkan/0053-diagnostic-M2V_VIEW_SHADOW_LOG-names-the-views-that-.patch
@@ -0,0 +1,50 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 01:25:48 +0000
+Subject: [PATCH 53/92] diagnostic: M2V_VIEW_SHADOW_LOG names the views that
+ take shadows
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/texture/view_shadow.rs | 28 +++++++++++++++++++
+ 1 file changed, 28 insertions(+)
+
+diff --git a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs
+index 739b98de..6d940e98 100644
+--- a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs
++++ b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs
+@@ -315,6 +315,34 @@ impl Device {
+ || Error::Unsupported(self.apart_refusal(Some(base.as_ref()), view.pixel_format));
+ let image = self.image_shadow(call, base, texture, view, apart, None)?;
+ self.shared().counts.view_shadow_made();
++ // LOCAL (Atlas) diagnostic: which views take shadows, where `M2V_VIEW_SHADOW_LOG` is set.
++ if std::env::var_os("M2V_VIEW_SHADOW_LOG").is_some() {
++ static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
++ if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 60 {
++ let b = base.plan();
++ eprintln!(
++ "m2v-view-shadow: {call} view {:?} of {:?} texture (base {:?} {:?} {}x{} flags {:?} usage {:?} views {:?} purpose {}) rendered {rendered} reinterprets {} at {}",
++ view.pixel_format,
++ texture.pixel_format,
++ b.pixel_format,
++ b.format,
++ b.extent[0],
++ b.extent[1],
++ b.flags,
++ b.usage,
++ b.view_formats,
++ crate::image_log::image_note(base.own_raw()),
++ self.reinterprets(base, view.pixel_format),
++ std::backtrace::Backtrace::force_capture()
++ .to_string()
++ .lines()
++ .filter(|l| l.contains("metal2vulkan_runtime::"))
++ .take(8)
++ .collect::>()
++ .join(" | "),
++ );
++ }
++ }
+ let reinterpreting =
+ !self.shared().view_reinterpretation && self.reinterprets(base, view.pixel_format);
+ let formats = (base.plan().format, image.plan().format);
diff --git a/patches/metal2vulkan/0054-diagnostic-overwrite_risk-by-site-in-the-coherent-ce.patch b/patches/metal2vulkan/0054-diagnostic-overwrite_risk-by-site-in-the-coherent-ce.patch
new file mode 100644
index 0000000..a634a44
--- /dev/null
+++ b/patches/metal2vulkan/0054-diagnostic-overwrite_risk-by-site-in-the-coherent-ce.patch
@@ -0,0 +1,110 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 01:49:42 +0000
+Subject: [PATCH 54/92] diagnostic: overwrite_risk by site in the coherent
+ census (risk_by)
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/shadow_coherent.rs | 20 ++++++++++++++++++-
+ 1 file changed, 19 insertions(+), 1 deletion(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/shadow_coherent.rs b/crates/metal2vulkan-runtime/src/shadow_coherent.rs
+index dee6bf93..ca151e3d 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_coherent.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_coherent.rs
+@@ -595,6 +595,11 @@ struct Counts {
+ late_compare_ns_max: AtomicU64,
+ /// Rectangles held batches copied in that other imports wrote ([`Coherent::taking_beside`]).
+ late_beside: AtomicU64,
++ /// LOCAL (Atlas) diagnostic: `overwrite_risk` by site: 0 a trap's write over an unsettled copy
++ /// (`wrote`), 1 a taking over an unsettled copy or a held record (`taking`), 2 `taking_late`
++ /// with a copy back in flight or owed, 3 `taking_late` behind a record without a cut compare,
++ /// 4 `taking_late` whole after the compare, 5 `taking_beside`, 6 a sync over an unsettled copy.
++ risk_by: [AtomicU64; 8],
+ }
+
+ #[derive(Default)]
+@@ -1285,6 +1290,7 @@ impl Coherent {
+ self.sync_done(&mut state, SyncBy::Trap);
+ if !clear {
+ self.counts.overwrite_risk.fetch_add(1, Ordering::Relaxed);
++ self.counts.risk_by[0].fetch_add(1, Ordering::Relaxed);
+ }
+ state.guest = Some(self.layout.whole());
+ state.wrote_at = Some(Instant::now());
+@@ -1430,6 +1436,7 @@ impl Coherent {
+ });
+ if !clear || held_over {
+ self.counts.overwrite_risk.fetch_add(1, Ordering::Relaxed);
++ self.counts.risk_by[1].fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ // LOCAL (Atlas): if a held batch is still pending for this surface (an entry in
+@@ -1530,6 +1537,7 @@ impl Coherent {
+ };
+ let behind = ahead(&state, &[area]);
+ let mut busy = (state.flushing != 0 || !state.owed.is_empty()) && !state.snapshots.is_empty();
++ let mut why = if busy { 2 } else { 0 };
+ let mut rects = vec![area];
+ if behind && cut && !state.snapshots.is_empty() {
+ self.sync_done(&mut state, SyncBy::CopyIn);
+@@ -1545,6 +1553,9 @@ impl Coherent {
+ LATE_COMPARE_NS.fetch_add(ns, Ordering::Relaxed);
+ LATE_COMPARE_NS_MAX.fetch_max(ns, Ordering::Relaxed);
+ rects = changed;
++ if why == 0 && whole && ahead(&state, &rects) {
++ why = 4;
++ }
+ busy |= whole && ahead(&state, &rects);
+ state.guest = None;
+ // A page the guest reached as the marks moved came with no snapshot: its rectangle
+@@ -1553,11 +1564,15 @@ impl Coherent {
+ state.snapshots.clear();
+ state.opened = false;
+ } else {
++ if why == 0 && behind {
++ why = 3;
++ }
+ busy |= behind;
+ self.take_guest(&mut state);
+ }
+ if busy {
+ self.counts.overwrite_risk.fetch_add(1, Ordering::Relaxed);
++ self.counts.risk_by[why].fetch_add(1, Ordering::Relaxed);
+ self.counts.late_busy.fetch_add(1, Ordering::Relaxed);
+ count(Fallback::LateCopyInBusy);
+ }
+@@ -1624,6 +1639,7 @@ impl Coherent {
+ .any(|record| areas.iter().any(|area| meet(record.area, *area)));
+ if busy {
+ self.counts.overwrite_risk.fetch_add(1, Ordering::Relaxed);
++ self.counts.risk_by[5].fetch_add(1, Ordering::Relaxed);
+ self.counts.late_busy.fetch_add(1, Ordering::Relaxed);
+ count(Fallback::LateCopyInBusy);
+ }
+@@ -1769,6 +1785,7 @@ impl Coherent {
+ }
+ if !clear {
+ self.counts.overwrite_risk.fetch_add(1, Ordering::Relaxed);
++ self.counts.risk_by[6].fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ let held = (state.running.iter())
+@@ -2050,7 +2067,7 @@ impl Coherent {
+ \"probes\":{},\"flushes\":{},\"flushed_bytes\":{},\"copy_ins\":{},\"copy_in_bytes\":{},\
+ \"overwrite_risk\":{},\"sync_errors\":{},\"late_copies\":{},\"late_busy\":{},\
+ \"late_compares\":{},\"late_compare_ns\":{},\"late_compare_ns_max\":{},\
+- \"late_beside\":{},\"pending_done\":{},\"open_pages\":{},\
++ \"late_beside\":{},\"risk_by\":[{}],\"pending_done\":{},\"open_pages\":{},\
+ \"per_present_ns\":{{\"detect\":{detect:.0},\"sync\":{sync:.0},\"fetch\":{fetch:.0},\
+ \"total\":{total:.0},\"eager_would\":{eager:.0}}},\"pays\":{}}}\n",
+ self.layout.first_page(),
+@@ -2098,6 +2115,7 @@ impl Coherent {
+ read(&c.late_compare_ns),
+ read(&c.late_compare_ns_max),
+ read(&c.late_beside),
++ c.risk_by.iter().map(|n| read(n).to_string()).collect::>().join(","),
+ state.done.len(),
+ state.snapshots.len(),
+ read(&c.spent_ns) < read(&c.saved_ns),
diff --git a/patches/metal2vulkan/0055-diagnostic-M2V_TWIN_LOG-says-why-a-texture-over-a-la.patch b/patches/metal2vulkan/0055-diagnostic-M2V_TWIN_LOG-says-why-a-texture-over-a-la.patch
new file mode 100644
index 0000000..d6f593d
--- /dev/null
+++ b/patches/metal2vulkan/0055-diagnostic-M2V_TWIN_LOG-says-why-a-texture-over-a-la.patch
@@ -0,0 +1,81 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 02:16:09 +0000
+Subject: [PATCH 55/92] diagnostic: M2V_TWIN_LOG says why a texture over a lazy
+ surface binds no twin
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/texture/surface_twin.rs | 51 +++++++++++++++++--
+ 1 file changed, 48 insertions(+), 3 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/texture/surface_twin.rs b/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
+index 6a09fb3c..14978604 100644
+--- a/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
++++ b/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
+@@ -57,10 +57,27 @@ impl Device {
+ if surface_depth_unit(layout.pixel_format).is_some() {
+ return None;
+ }
+- let (image, first, copies) = {
++ let found = {
+ let twins = lock(&self.shared().textures.twins.0);
+- let found = twins.get(&texels.surface_key()?)?;
+- (found.image.upgrade()?, found.texels.upgrade()?, found.copies.upgrade()?)
++ twins.get(&texels.surface_key()?).and_then(|found| {
++ Some((found.image.upgrade()?, found.texels.upgrade()?, found.copies.upgrade()?))
++ })
++ };
++ let Some((image, first, copies)) = found else {
++ if std::env::var_os("M2V_TWIN_LOG").is_some() {
++ static M: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
++ if M.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 80 {
++ eprintln!(
++ "m2v-twin-first: {:?} usage {:?} {}x{} at {:?} (no first shadow yet)",
++ layout.pixel_format,
++ descriptor.usage,
++ layout.extent[0],
++ layout.extent[1],
++ texels.surface_key(),
++ );
++ }
++ }
++ return None;
+ };
+ let facts = self.shared().textures.facts(self.compile_device().profile());
+ let usage = texture_usage(descriptor.usage, descriptor.swizzle);
+@@ -78,6 +95,34 @@ impl Device {
+ && first.same_place(texels)
+ && !copies.converts()
+ && self.image_takes_view(&image, layout.pixel_format);
++ // LOCAL (Atlas) diagnostic: why a texture over a lazy surface's pages binds no image of
++ // its own surface's, where `M2V_TWIN_LOG` is set (the first 80).
++ if !takes && std::env::var_os("M2V_TWIN_LOG").is_some() {
++ static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
++ if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 80 {
++ eprintln!(
++ "m2v-twin-refused: {:?} usage {:?} (plan usage {:?} flags {:?} extent {:?} levels {} layers {} samples {:?}) vs first {:?} usage {:?} flags {:?} extent {:?} levels {} layers {} views {:?}: same {same} place {} converts {} view {}",
++ layout.pixel_format,
++ descriptor.usage,
++ plan.usage,
++ plan.flags,
++ plan.extent,
++ plan.levels,
++ plan.layers,
++ plan.samples,
++ theirs.pixel_format,
++ theirs.usage,
++ theirs.flags,
++ theirs.extent,
++ theirs.levels,
++ theirs.layers,
++ theirs.view_formats,
++ first.same_place(texels),
++ copies.converts(),
++ self.image_takes_view(&image, layout.pixel_format),
++ );
++ }
++ }
+ takes.then(|| {
+ crate::shadow_lazy::twin_bound();
+ Storage::Shadow {
diff --git a/patches/metal2vulkan/0056-diagnostic-M2V_BESIDE_LOG-names-the-commands-writing.patch b/patches/metal2vulkan/0056-diagnostic-M2V_BESIDE_LOG-names-the-commands-writing.patch
new file mode 100644
index 0000000..6cbceac
--- /dev/null
+++ b/patches/metal2vulkan/0056-diagnostic-M2V_BESIDE_LOG-names-the-commands-writing.patch
@@ -0,0 +1,44 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 02:56:23 +0000
+Subject: [PATCH 56/92] diagnostic: M2V_BESIDE_LOG names the commands writing a
+ trapping lazy surface's bytes beside its image
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../metal2vulkan-runtime/src/shadow_lazy.rs | 22 +++++++++++++++++++
+ 1 file changed, 22 insertions(+)
+
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index 6354f6d0..1ac92c0e 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -519,6 +519,28 @@ pub(super) fn note_writes(uses: &[Use], id: u64, noted: &mut Noted)
+ for lazy in all.iter().filter_map(Weak::upgrade) {
+ if lazy.meets(used) && !lazy.own_thread() {
+ let count = lazy.written.fetch_add(1, Ordering::Relaxed) + 1;
++ // LOCAL (Atlas) diagnostic: who writes a lazy surface's bytes beside its image,
++ // where `M2V_BESIDE_LOG` is set (the first 60, with the recording's frames).
++ if lazy.coherent().is_some() && std::env::var_os("M2V_BESIDE_LOG").is_some() {
++ static N: AtomicU64 = AtomicU64::new(0);
++ if N.fetch_add(1, Ordering::Relaxed) < 60 {
++ eprintln!(
++ "m2v-beside: surface {:?} {}x{} cb {id:#x} use {:?} | {}",
++ lazy.pages.as_ref().map(|p| p.start),
++ lazy.size[0],
++ lazy.size[1],
++ used,
++ std::backtrace::Backtrace::force_capture()
++ .to_string()
++ .lines()
++ .filter(|l| l.contains("metal2vulkan_runtime::"))
++ .map(str::trim)
++ .take(10)
++ .collect::>()
++ .join(" < "),
++ );
++ }
++ }
+ if lazy.note_beside(count, id, used) {
+ noted.push((Arc::downgrade(&lazy), count));
+ } else {
diff --git a/patches/metal2vulkan/0057-diagnostic-M2V_TWIN_LOG-also-names-views-apart-from-.patch b/patches/metal2vulkan/0057-diagnostic-M2V_TWIN_LOG-also-names-views-apart-from-.patch
new file mode 100644
index 0000000..b82451d
--- /dev/null
+++ b/patches/metal2vulkan/0057-diagnostic-M2V_TWIN_LOG-also-names-views-apart-from-.patch
@@ -0,0 +1,48 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 03:32:44 +0000
+Subject: [PATCH 57/92] diagnostic: M2V_TWIN_LOG also names views apart from a
+ texture over bytes
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/texture/view_shadow.rs | 26 +++++++++++++++++++
+ 1 file changed, 26 insertions(+)
+
+diff --git a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs
+index 6d940e98..d2b5ef59 100644
+--- a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs
++++ b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs
+@@ -144,6 +144,32 @@ impl Texture {
+ self.rotated_view(call, record)
+ }
+ Storage::Alias { texels, .. } | Storage::Shadow { texels, .. } => {
++ // LOCAL (Atlas) diagnostic: a view of a texture over bytes that its image takes no
++ // view of, where `M2V_TWIN_LOG` is set (the first 80).
++ if std::env::var_os("M2V_TWIN_LOG").is_some() {
++ static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
++ if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 80 {
++ let (Storage::Alias { image, .. } | Storage::Shadow { image, .. }) = &self.0.storage else {
++ unreachable!()
++ };
++ let p = image.plan();
++ eprintln!(
++ "m2v-view-apart: view {:?} usage {:?} {}x{} of {:?} texture, image {:?} {:?} flags {:?} usage {:?} views {:?} lazy {} shadow {}",
++ record.pixel_format,
++ record.usage,
++ record.image_extent[0],
++ record.image_extent[1],
++ self.0.record.pixel_format,
++ p.pixel_format,
++ p.format,
++ p.flags,
++ p.usage,
++ p.view_formats,
++ texels.lies_lazily(),
++ matches!(&self.0.storage, Storage::Shadow { .. }),
++ );
++ }
++ }
+ let mut descriptor = TextureDescriptor::texture_2d(
+ record.pixel_format,
+ u64::from(record.image_extent[0]),
diff --git a/patches/metal2vulkan/0058-live-surface_usage_shadow_image-a-lazy-surface-witho.patch b/patches/metal2vulkan/0058-live-surface_usage_shadow_image-a-lazy-surface-witho.patch
new file mode 100644
index 0000000..ef4f286
--- /dev/null
+++ b/patches/metal2vulkan/0058-live-surface_usage_shadow_image-a-lazy-surface-witho.patch
@@ -0,0 +1,35 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 04:03:59 +0000
+Subject: [PATCH 58/92] live surface_usage_shadow_image: a lazy surface without
+ storage usage takes its image's shadow
+
+A draw sampling a lazy Sim surface it renders (an attachment read) took a shadow over the bytes
+where the surface's sRGB image has no storage usage: a second lazy surface over the same pages,
+copied back after each encoder, beside the first image (coherent taking_beside risk).
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/texture/usage_shadow.rs | 9 ++++++++-
+ 1 file changed, 8 insertions(+), 1 deletion(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs b/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs
+index 1af00981..707c12aa 100644
+--- a/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs
++++ b/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs
+@@ -240,7 +240,14 @@ impl Texture {
+ // copied from the bytes it would leave that image's writes to go back for it, each frame.
+ if let Storage::Shadow { image, copies, .. } = &self.0.storage {
+ let both = ImageUsageFlags::SAMPLED | ImageUsageFlags::STORAGE;
+- if copies.lazy.is_some() && image.plan().usage.contains(both) {
++ // LOCAL (Atlas): live `surface_usage_shadow_image` (default off) takes that image for
++ // one without the storage usage too (a Sim's sRGB surface, which no storage view
++ // takes): its shadow copies image to image both ways, where the bytes' way made a
++ // second lazy surface over the same pages whose copies back after each encoder wrote
++ // beside the first image (the coherent census's `taking_beside` risk, 2026-11-08).
++ let image_way = image.plan().usage.contains(both)
++ || crate::live::on("surface_usage_shadow_image", false);
++ if copies.lazy.is_some() && image_way {
+ let root = &self.root().0.record;
+ let over = Some(Arc::clone(copies));
+ match device.image_shadow(call, image, root, &wider, refused, over) {
diff --git a/patches/metal2vulkan/0059-live-surface_coherent_own_back-a-trapping-surface-s-.patch b/patches/metal2vulkan/0059-live-surface_coherent_own_back-a-trapping-surface-s-.patch
new file mode 100644
index 0000000..cb1e0f5
--- /dev/null
+++ b/patches/metal2vulkan/0059-live-surface_coherent_own_back-a-trapping-surface-s-.patch
@@ -0,0 +1,60 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 04:54:34 +0000
+Subject: [PATCH 59/92] live surface_coherent_own_back: a trapping surface's
+ encoder-end copy back is its own
+
+Its plain copy back of its own image counted as a write beside the image, so each held batch after
+it copied those texels in again over records still running (coherent taking_beside risk, 3 Sims).
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/encoder.rs | 28 +++++++++++++++++++++-
+ 1 file changed, 27 insertions(+), 1 deletion(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs
+index e3a282da..d7cb1ae1 100644
+--- a/crates/metal2vulkan-runtime/src/encoder.rs
++++ b/crates/metal2vulkan-runtime/src/encoder.rs
+@@ -1588,6 +1588,32 @@ impl EncoderCore {
+ /// at the copy in where the device takes it (`shadow_copy_in.rs`), and the rows a copy back
+ /// moves out of a staging buffer are a copy of rows (`row_copies.rs`); the command buffer
+ /// retains each until it completes.
++ /// LOCAL (Atlas): the encoder's end's copies back, as [`shadow_copies`](Self::shadow_copies)
++ /// records them. With the live switch `surface_coherent_own_back` (default off), a trapping
++ /// lazy surface's plain copy back of its own image records as its own (`Lazy::own`): its
++ /// bytes then hold what the image holds, which no other import wrote, where before it counted
++ /// as a write beside the image (`shadow_lazy::note_writes`), and each held batch after it
++ /// copied those texels in again, over a record still running there (the coherent census's
++ /// `taking_beside` risk, 3 Sims, 2026-11-08). A merge's copy back keeps the CPU's texels and
++ /// still counts.
++ fn end_copies(&mut self, copies: &[ShadowCopy]) {
++ let own = |copy: &ShadowCopy| {
++ (matches!(copy.step, Step::Back))
++ .then(|| copy.copies.lazy.clone())
++ .flatten()
++ .filter(|lazy| lazy.coherent().is_some())
++ };
++ if !crate::live::on("surface_coherent_own_back", false) || !copies.iter().any(|c| own(c).is_some()) {
++ self.shadow_copies(copies);
++ return;
++ }
++ for copy in copies {
++ let lazy = own(copy);
++ let _own = lazy.as_ref().map(|lazy| lazy.own());
++ self.shadow_copies(std::slice::from_ref(copy));
++ }
++ }
++
+ pub(super) fn shadow_copies(&mut self, copies: &[ShadowCopy]) {
+ let device = self.device().clone();
+ let mut run = ShadowRun::default();
+@@ -2031,7 +2057,7 @@ impl EncoderCore {
+ let copies = self.shadows.finish_leaving_ahead();
+ let copies = self.sample_moves(copies);
+ self.count_shadow_copies(&copies);
+- self.shadow_copies(&copies);
++ self.end_copies(&copies);
+ // Whether it keeps its log, once its last commands, the copies back above among them,
+ // named what they name: a copy back may be the only command that names a texture's
+ // bytes over host pages (a render pass that clears a shadowed target copies nothing in).
diff --git a/patches/metal2vulkan/0060-surface_coherent_own_back-tags-own-copies-back-inste.patch b/patches/metal2vulkan/0060-surface_coherent_own_back-tags-own-copies-back-inste.patch
new file mode 100644
index 0000000..e5f38c0
--- /dev/null
+++ b/patches/metal2vulkan/0060-surface_coherent_own_back-tags-own-copies-back-inste.patch
@@ -0,0 +1,153 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 05:29:06 +0000
+Subject: [PATCH 60/92] surface_coherent_own_back tags own copies back instead
+ of hiding them
+
+Lazy::own hid the encoder-end copy back from the plans (plan_left_planned, a stalled Sim). Now it
+counts as before; its beside record is tagged own, and a held batch's copy in skips it.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/encoder.rs | 14 ++++----
+ .../metal2vulkan-runtime/src/shadow_lazy.rs | 35 +++++++++++++++++--
+ 2 files changed, 40 insertions(+), 9 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs
+index d7cb1ae1..6cacdf3b 100644
+--- a/crates/metal2vulkan-runtime/src/encoder.rs
++++ b/crates/metal2vulkan-runtime/src/encoder.rs
+@@ -1590,12 +1590,12 @@ impl EncoderCore {
+ /// retains each until it completes.
+ /// LOCAL (Atlas): the encoder's end's copies back, as [`shadow_copies`](Self::shadow_copies)
+ /// records them. With the live switch `surface_coherent_own_back` (default off), a trapping
+- /// lazy surface's plain copy back of its own image records as its own (`Lazy::own`): its
+- /// bytes then hold what the image holds, which no other import wrote, where before it counted
+- /// as a write beside the image (`shadow_lazy::note_writes`), and each held batch after it
+- /// copied those texels in again, over a record still running there (the coherent census's
+- /// `taking_beside` risk, 3 Sims, 2026-11-08). A merge's copy back keeps the CPU's texels and
+- /// still counts.
++ /// lazy surface's plain copy back of its own image is marked its own (`Lazy::own_back`): it
++ /// still counts as a write of the bytes for every plan (`shadow_lazy::note_writes`), but no
++ /// held batch after it copies those texels in again, over a record still running there (the
++ /// coherent census's `taking_beside` risk, 3 Sims, 2026-11-08). A merge's copy back keeps the
++ /// CPU's texels and is not marked. (`Lazy::own` there instead hid the write from the plans:
++ /// `plan_left_planned` and a stalled Sim.)
+ fn end_copies(&mut self, copies: &[ShadowCopy]) {
+ let own = |copy: &ShadowCopy| {
+ (matches!(copy.step, Step::Back))
+@@ -1609,7 +1609,7 @@ impl EncoderCore {
+ }
+ for copy in copies {
+ let lazy = own(copy);
+- let _own = lazy.as_ref().map(|lazy| lazy.own());
++ let _own = lazy.as_ref().map(|lazy| lazy.own_back());
+ self.shadow_copies(std::slice::from_ref(copy));
+ }
+ }
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index 1ac92c0e..5062ab66 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -136,6 +136,8 @@ static IN_BY: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
+ /// How many surfaces hold writes ahead in their images: every hook returns at once while none does.
+ static AHEAD: AtomicUsize = AtomicUsize::new(0);
+ static DEFERRED: AtomicU64 = AtomicU64::new(0);
++/// LOCAL (Atlas): own copies back a copy in skipped ([`BesideWrite::own`]).
++static OWN_BACKS_SKIPPED: AtomicU64 = AtomicU64::new(0);
+ /// The copies back not left ahead, a second texture's image lying over the same pages.
+ static SHARED: AtomicU64 = AtomicU64::new(0);
+ static FLUSHES: AtomicU64 = AtomicU64::new(0);
+@@ -155,6 +157,9 @@ thread_local! {
+ /// The surface whose own copy back this thread records: neither a write that drops its standing
+ /// nor a use that asks for a copy back.
+ static OWN: Cell<*const Lazy> = const { Cell::new(std::ptr::null()) };
++ /// LOCAL (Atlas): the surface whose plain copy back of its own image this thread records
++ /// ([`Lazy::own_back`]).
++ static OWN_BACK: Cell<*const Lazy> = const { Cell::new(std::ptr::null()) };
+ }
+
+ /// Why a take found no standing it could use.
+@@ -936,7 +941,7 @@ fn report() {
+ "surface_lazy: taken {taken} refused {refused} resyncs {resyncs} | refused: touched {} \
+ written {} epoch {} own {} uncommitted {} no-standing {} | in: first {} beyond-held {} \
+ changed {} bounded {} | ahead: deferred {} shared {} flushes {} whole {} texels {} \
+- discarded {} presents {} unmatched {} twins {} readers-first {}",
++ discarded {} presents {} unmatched {} twins {} readers-first {} own-backs-skipped {}",
+ by[Refused::Touched as usize],
+ by[Refused::Written as usize],
+ by[Refused::Epoch as usize],
+@@ -957,6 +962,7 @@ fn report() {
+ read(&PRESENTS_UNMATCHED),
+ read(&TWINS),
+ read(&READERS_FIRST),
++ read(&OWN_BACKS_SKIPPED),
+ );
+ for lazy in surfaces().iter().take(16) {
+ eprintln!(
+@@ -1110,6 +1116,9 @@ struct BesideWrite {
+ part: usize,
+ area: Option<[u32; 4]>,
+ copied: bool,
++ /// LOCAL (Atlas): every write joined in it was the surface's own plain copy back of its image
++ /// ([`Lazy::own_back`]): its bytes hold what the image holds, so no copy in needs them.
++ own: bool,
+ }
+
+ const BESIDE_KEPT: usize = 256;
+@@ -1263,6 +1272,19 @@ impl Lazy {
+ OWN.with(Cell::get) == std::ptr::from_ref(self)
+ }
+
++ /// LOCAL (Atlas): mark this thread as recording a plain copy back of this surface's own image
++ /// until the mark drops: still a write of its bytes for every count and plan, but one a later
++ /// copy in skips ([`BesideWrite::own`]).
++ pub(crate) fn own_back(&self) -> impl Drop {
++ struct OwnBack(*const Lazy);
++ impl Drop for OwnBack {
++ fn drop(&mut self) {
++ OWN_BACK.with(|own| own.set(self.0));
++ }
++ }
++ OwnBack(OWN_BACK.with(|own| own.replace(std::ptr::from_ref(self))))
++ }
++
+ /// Mark this thread as recording its own copy back until the mark drops.
+ pub(crate) fn own(&self) -> impl Drop {
+ struct Own(*const Lazy);
+@@ -1595,10 +1617,12 @@ impl Lazy {
+ }
+ _ => None,
+ };
++ let own = OWN_BACK.with(Cell::get) == std::ptr::from_ref(self);
+ let mut beside = self.beside.lock().unwrap();
+ if let Some(last) = beside.writes.back_mut() {
+ if last.id == id && last.part == usize::MAX {
+ last.count = count;
++ last.own &= own;
+ last.area = match (last.area, area) {
+ (Some(_), Some(_)) => bounding(last.area, area),
+ _ => None,
+@@ -1611,7 +1635,7 @@ impl Lazy {
+ beside.lost = beside.lost.max(gone.count);
+ }
+ }
+- beside.writes.push_back(BesideWrite { count, id, part: usize::MAX, area, copied: false });
++ beside.writes.push_back(BesideWrite { count, id, part: usize::MAX, area, copied: false, own });
+ true
+ }
+
+@@ -1665,6 +1689,13 @@ impl Lazy {
+ if write.count <= written || write.id == id || write.copied {
+ continue;
+ }
++ // LOCAL (Atlas): the image's own copy back: copying it in would put those texels, or
++ // older pages, over what the image holds (live `surface_coherent_own_back`).
++ if write.own {
++ write.copied = true;
++ OWN_BACKS_SKIPPED.fetch_add(1, Ordering::Relaxed);
++ continue;
++ }
+ match ordered(write.id, write.part) {
+ Order::Before => {}
+ Order::Held => {
diff --git a/patches/metal2vulkan/0061-live-surface_lazy_open_ids-a-standing-s-command-buff.patch b/patches/metal2vulkan/0061-live-surface_lazy_open_ids-a-standing-s-command-buff.patch
new file mode 100644
index 0000000..fade90f
--- /dev/null
+++ b/patches/metal2vulkan/0061-live-surface_lazy_open_ids-a-standing-s-command-buff.patch
@@ -0,0 +1,122 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 07:01:52 +0000
+Subject: [PATCH 61/92] live surface_lazy_open_ids: a standing's command buffer
+ committed is asked exactly
+
+The last 256 committed command buffers of every process made a standing stale within a fraction of
+a second under several Sims and the desktop, refused as uncommitted, each a whole copy in.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/command_buffer/mod.rs | 4 ++
+ .../metal2vulkan-runtime/src/shadow_lazy.rs | 53 ++++++++++++++++++-
+ 2 files changed, 55 insertions(+), 2 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+index 8f3cb31d..3a0b2881 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+@@ -1753,6 +1753,10 @@ impl Drop for CommandBufferShared {
+ // state.
+ let (pool, replays) = {
+ let mut state = lock(&self.state);
++ // LOCAL (Atlas): a command buffer gone uncommitted leaves no standing open.
++ if let Some(id) = state.shadow_carry.as_ref().map(ShadowCarry::id) {
++ crate::shadow_lazy::dropped(id);
++ }
+ (state.pool.take(), state.replays.take())
+ };
+ if let Some(pool) = pool {
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index 5062ab66..f99e10da 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -194,6 +194,53 @@ fn committed_ids() -> &'static Mutex> {
+ IDS.get_or_init(Mutex::default)
+ }
+
++/// LOCAL (Atlas): live `surface_lazy_open_ids` (default off): whether a standing's command buffer
++/// committed is asked of the command buffers that left a standing and have not committed or gone
++/// yet, exactly, instead of the last [`COMMITTED_KEPT`] committed. Those let a standing go stale
++/// after 256 commits of every process, a fraction of a second with several Sims and the desktop,
++/// so a surface idle that long (the desktop's, a triple buffer's) copied its whole bytes in again
++/// as `uncommitted` (2026-11-08 loadlab: 57564 such, 64802 whole copies in).
++const OPEN_IDS: &str = "surface_lazy_open_ids";
++/// The open command buffers kept at most: past it the exact answer is given up for good.
++const OPEN_KEPT: usize = 1 << 16;
++static OPEN_OVERFLOW: AtomicBool = AtomicBool::new(false);
++
++fn open_ids() -> &'static Mutex> {
++ static IDS: OnceLock>> = OnceLock::new();
++ IDS.get_or_init(Mutex::default)
++}
++
++fn open_exact() -> bool {
++ crate::live::on(OPEN_IDS, false) && !OPEN_OVERFLOW.load(Ordering::Relaxed)
++}
++
++/// Whether the command buffer `id`, whose encoder left a standing, has committed (or gone).
++fn was_committed(id: u64) -> bool {
++ if open_exact() {
++ !open_ids().lock().unwrap().contains(&id)
++ } else {
++ committed_ids().lock().unwrap().contains(&id)
++ }
++}
++
++/// Note an encoder of the command buffer `id` left a standing while it encodes.
++fn note_open(id: u64) {
++ if !crate::live::on(OPEN_IDS, false) || committed_ids().lock().unwrap().contains(&id) {
++ return;
++ }
++ let mut open = open_ids().lock().unwrap();
++ if open.len() >= OPEN_KEPT {
++ OPEN_OVERFLOW.store(true, Ordering::Relaxed);
++ return;
++ }
++ open.insert(id);
++}
++
++/// LOCAL (Atlas): the command buffer `id` went without a commit: it holds no standing open.
++pub(crate) fn dropped(id: u64) {
++ open_ids().lock().unwrap().remove(&id);
++}
++
+ /// LOCAL (Atlas): the command buffers committed whose last batch the scheduler has not planned
+ /// yet ([`planned`]), and the last [`PLANNED_KEPT`] that it planned.
+ #[derive(Default)]
+@@ -493,6 +540,7 @@ pub(crate) fn active() -> bool {
+
+ /// Note the command buffer of identity `id` committed.
+ pub(crate) fn committed(id: u64) {
++ open_ids().lock().unwrap().remove(&id);
+ let mut ids = committed_ids().lock().unwrap();
+ if ids.len() == COMMITTED_KEPT {
+ ids.pop_front();
+@@ -1234,7 +1282,7 @@ impl Lazy {
+ /// Whether a standing stands, from a command buffer already committed.
+ fn standing_committed(&self) -> bool {
+ let stood = *self.stood.lock().unwrap();
+- stood.is_some_and(|stood| committed_ids().lock().unwrap().contains(&stood.id))
++ stood.is_some_and(|stood| was_committed(stood.id))
+ }
+
+ /// `settled` is what ran and is not in the pages, and whether any record stays at all.
+@@ -1527,6 +1575,7 @@ impl Lazy {
+ stale: Option<[u32; 4]>,
+ ) {
+ self.register((key, alias, range));
++ note_open(id);
+ *self.stood.lock().unwrap() = Some(Stood {
+ id,
+ touched,
+@@ -1767,7 +1816,7 @@ impl Lazy {
+ Some(Refused::OwnBuffer)
+ } else if own {
+ None
+- } else if !committed_ids().lock().unwrap().contains(&stood.id) {
++ } else if !was_committed(stood.id) {
+ Some(Refused::Uncommitted)
+ } else {
+ None
diff --git a/patches/metal2vulkan/0062-live-xr_unused_bits_off-lab-ceiling-of-the-unused-bi.patch b/patches/metal2vulkan/0062-live-xr_unused_bits_off-lab-ceiling-of-the-unused-bi.patch
new file mode 100644
index 0000000..5a9da5e
--- /dev/null
+++ b/patches/metal2vulkan/0062-live-xr_unused_bits_off-lab-ceiling-of-the-unused-bi.patch
@@ -0,0 +1,30 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 09:49:39 +0000
+Subject: [PATCH 62/92] live xr_unused_bits_off, lab ceiling of the unused-bits
+ load pass's cost
+
+Measurement-only switch, default off: records no extended-range load pass.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/render/unused_bits_load.rs | 6 ++++++
+ 1 file changed, 6 insertions(+)
+
+diff --git a/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs b/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs
+index 0f9afa2c..a2c9fbcf 100644
+--- a/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs
++++ b/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs
+@@ -536,6 +536,12 @@ fn record_taken(
+ reach: TileReach<'_>,
+ frames: bool,
+ ) -> Result<(), Error> {
++ // LOCAL (Atlas, lab measurement only): live `xr_unused_bits_off` records no load pass, the
++ // attachments' unused bits kept as the device's pass keeps them (inexact: the ceiling of what
++ // skipping a canonical region's rewrite saves). Off by default; never in production.
++ if crate::live::on("xr_unused_bits_off", false) {
++ return Ok(());
++ }
+ for color in layout.colors.iter().flatten() {
+ let Some(taken) = takes(color, false) else {
+ continue;
diff --git a/patches/metal2vulkan/0063-count-why-large-shadows-copy-back-lab-diagnostics-pr.patch b/patches/metal2vulkan/0063-count-why-large-shadows-copy-back-lab-diagnostics-pr.patch
new file mode 100644
index 0000000..62d872b
--- /dev/null
+++ b/patches/metal2vulkan/0063-count-why-large-shadows-copy-back-lab-diagnostics-pr.patch
@@ -0,0 +1,140 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 11:10:19 +0000
+Subject: [PATCH 63/92] count why large shadows copy back (lab diagnostics,
+ printed with surface_lazy's report)
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/shadow.rs | 58 +++++++++++++++++--
+ .../metal2vulkan-runtime/src/shadow_lazy.rs | 13 +++++
+ 2 files changed, 67 insertions(+), 4 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs
+index ca2a7c3e..1211c06a 100644
+--- a/crates/metal2vulkan-runtime/src/shadow.rs
++++ b/crates/metal2vulkan-runtime/src/shadow.rs
+@@ -182,6 +182,20 @@ use crate::device::functions::Vk;
+ use ash::vk;
+ use metal2vulkan::error::{Feature, Unsupported};
+ use metal2vulkan::metal::PixelFormat;
++
++/// LOCAL (Atlas, lab diagnostics): why each copy back of a shadow of at least
++/// [`BACK_WHY_MIN_TEXELS`] texels was recorded, `[lazy surface or not][reason]` (reasons in
++/// [`BACK_WHY_NAMES`]); printed with `shadow_lazy`'s report. Counting only, no behaviour.
++pub(crate) static BACK_WHY: [[std::sync::atomic::AtomicU64; 12]; 2] =
++ [const { [const { std::sync::atomic::AtomicU64::new(0) }; 12] }; 2];
++/// LOCAL (Atlas): the texels those copies back moved, alike.
++pub(crate) static BACK_WHY_TEXELS: [[std::sync::atomic::AtomicU64; 12]; 2] =
++ [const { [const { std::sync::atomic::AtomicU64::new(0) }; 12] }; 2];
++pub(crate) const BACK_WHY_NAMES: [&str; 12] = [
++ "use-meets", "other-shadow", "regrows", "unkept", "two-ways", "beyond-held", "finish",
++ "ahead-not-alone", "ahead-merge", "ahead-no-lazy", "ahead-refused", "other",
++];
++const BACK_WHY_MIN_TEXELS: u64 = 2_000_000;
+ use std::ops::Range;
+ use std::sync::atomic::{AtomicU64, Ordering};
+ use std::sync::Arc;
+@@ -2592,6 +2606,25 @@ impl ShadowSync {
+ /// copy in left, which the buffer still holds (a write of its bytes another way leaves the
+ /// image stale, and copies in again before the next use).
+ fn copy_back(&mut self, i: usize, copies: &mut Vec>) {
++ self.copy_back_why(i, copies, 11);
++ }
++
++ /// LOCAL (Atlas): [`copy_back`](Self::copy_back), counted by `why` ([`BACK_WHY`]).
++ fn copy_back_why(&mut self, i: usize, copies: &mut Vec>, why: usize) {
++ {
++ let entry = &self.entries[i];
++ let texels = entry.copies.texels();
++ if texels >= BACK_WHY_MIN_TEXELS {
++ use std::sync::atomic::Ordering::Relaxed;
++ let lazy = usize::from(entry.copies.lazy.is_some());
++ let moved = match entry.area {
++ Some([x0, y0, x1, y1]) => u64::from(x1 - x0) * u64::from(y1 - y0),
++ None => texels,
++ };
++ BACK_WHY[lazy][why].fetch_add(1, Relaxed);
++ BACK_WHY_TEXELS[lazy][why].fetch_add(moved, Relaxed);
++ }
++ }
+ let entry = &mut self.entries[i];
+ let two_ways = entry.two_ways;
+ let step = match &entry.merge {
+@@ -2740,7 +2773,15 @@ impl ShadowSync {
+ let unkept = entry.merge.is_none()
+ && (merged_kept.iter()).any(|kept| kept.shadow_key == entry.copies.shadow_key);
+ if touched || regrows || unkept || (entry.merge.is_some() && entry.two_ways) {
+- self.copy_back(i, &mut copies);
++ let met = uses.iter().any(|used| entry.copies.meets(used));
++ let why = match () {
++ _ if met => 0,
++ _ if touched => 1,
++ _ if regrows => 2,
++ _ if unkept => 3,
++ _ => 4,
++ };
++ self.copy_back_why(i, &mut copies, why);
+ }
+ }
+ for shadow in shadows {
+@@ -2772,7 +2813,7 @@ impl ShadowSync {
+ // the encoder wrote through it goes back first, then the copy in below moves what
+ // this command needs.
+ if beyond_held && entry.dirty {
+- self.copy_back(i, &mut copies);
++ self.copy_back_why(i, &mut copies, 5);
+ }
+ let entry = &mut self.entries[i];
+ let cause = match entry.standing {
+@@ -2997,7 +3038,7 @@ impl ShadowSync {
+ let mut copies = Vec::new();
+ for i in 0..self.entries.len() {
+ if self.entries[i].dirty {
+- self.copy_back(i, &mut copies);
++ self.copy_back_why(i, &mut copies, 6);
+ }
+ }
+ copies
+@@ -3030,7 +3071,16 @@ impl ShadowSync {
+ entry.dirty = false;
+ entry.area = None;
+ }
+- false => self.copy_back(i, &mut copies),
++ false => {
++ let entry = &self.entries[i];
++ let why = match () {
++ _ if !alone => 7,
++ _ if entry.merge.is_some() || entry.two_ways => 8,
++ _ if entry.copies.lazy.is_none() => 9,
++ _ => 10,
++ };
++ self.copy_back_why(i, &mut copies, why);
++ }
+ }
+ }
+ copies
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index f99e10da..9061bd11 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -1012,6 +1012,19 @@ fn report() {
+ read(&READERS_FIRST),
+ read(&OWN_BACKS_SKIPPED),
+ );
++ // LOCAL (Atlas, lab diagnostics): why the large shadows' copies back were recorded.
++ for (lazy, name) in [(1usize, "lazy"), (0, "plain")] {
++ let parts: Vec = (0..12)
++ .filter_map(|w| {
++ let n = super::shadow::BACK_WHY[lazy][w].load(Ordering::Relaxed);
++ let t = super::shadow::BACK_WHY_TEXELS[lazy][w].load(Ordering::Relaxed);
++ (n > 0).then(|| format!("{} {n}/{}M", super::shadow::BACK_WHY_NAMES[w], t / 1_000_000))
++ })
++ .collect();
++ if !parts.is_empty() {
++ eprintln!("copy_back_why {name}: {}", parts.join(" "));
++ }
++ }
+ for lazy in surfaces().iter().take(16) {
+ eprintln!(
+ "surface_lazy: {:#x} {}x{} displayed {} taken {} refused {} in {} presents {}",
diff --git a/patches/metal2vulkan/0064-count-copy-back-dispatches-by-site-lab-diagnostics.patch b/patches/metal2vulkan/0064-count-copy-back-dispatches-by-site-lab-diagnostics.patch
new file mode 100644
index 0000000..e005b43
--- /dev/null
+++ b/patches/metal2vulkan/0064-count-copy-back-dispatches-by-site-lab-diagnostics.patch
@@ -0,0 +1,109 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 11:36:38 +0000
+Subject: [PATCH 64/92] count copy-back dispatches by site (lab diagnostics)
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/command_buffer/submit.rs | 3 +++
+ crates/metal2vulkan-runtime/src/encoder.rs | 3 +++
+ crates/metal2vulkan-runtime/src/shadow.rs | 14 ++++++++++++++
+ crates/metal2vulkan-runtime/src/shadow_lazy.rs | 12 ++++++++++++
+ crates/metal2vulkan-runtime/src/shadow_merge.rs | 8 +++++++-
+ 5 files changed, 39 insertions(+), 1 deletion(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs
+index 30fed418..c6fc03ce 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs
+@@ -1241,6 +1241,9 @@ impl CommandBufferShared {
+ let mut planned = Vec::new();
+ for (copy, _) in &copies {
+ let dispatched = copy.dispatched(device);
++ if dispatched.is_some() {
++ crate::shadow::count_back_site(1, copy.texels_back()); // LOCAL (Atlas): diagnostics
++ }
+ let rows = match dispatched {
+ Some(_) => None,
+ None => copy.staged_back(device),
+diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs
+index 6cacdf3b..25504a87 100644
+--- a/crates/metal2vulkan-runtime/src/encoder.rs
++++ b/crates/metal2vulkan-runtime/src/encoder.rs
+@@ -1640,6 +1640,9 @@ impl EncoderCore {
+ }
+ // A shadow takes the view a dispatch reads on a device that dispatches alone.
+ let dispatched = copy.dispatched(&device);
++ if dispatched.is_some() {
++ crate::shadow::count_back_site(0, copy.texels_back()); // LOCAL (Atlas): diagnostics
++ }
+ let rows = match dispatched {
+ Some(_) => None,
+ None => copy.staged_back(&device),
+diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs
+index 1211c06a..f00d845d 100644
+--- a/crates/metal2vulkan-runtime/src/shadow.rs
++++ b/crates/metal2vulkan-runtime/src/shadow.rs
+@@ -196,6 +196,20 @@ pub(crate) const BACK_WHY_NAMES: [&str; 12] = [
+ "ahead-not-alone", "ahead-merge", "ahead-no-lazy", "ahead-refused", "other",
+ ];
+ const BACK_WHY_MIN_TEXELS: u64 = 2_000_000;
++/// LOCAL (Atlas, lab diagnostics): copy-back dispatches recorded, by site
++/// ([`BACK_SITE_NAMES`]): `[large (at least BACK_WHY_MIN_TEXELS moved)?][site]` counts and texels.
++pub(crate) static BACK_SITE: [[std::sync::atomic::AtomicU64; 4]; 2] =
++ [const { [const { std::sync::atomic::AtomicU64::new(0) }; 4] }; 2];
++pub(crate) static BACK_SITE_TEXELS: [[std::sync::atomic::AtomicU64; 4]; 2] =
++ [const { [const { std::sync::atomic::AtomicU64::new(0) }; 4] }; 2];
++pub(crate) const BACK_SITE_NAMES: [&str; 4] = ["encoder", "late-batch", "merge-copy", "other"];
++/// LOCAL (Atlas): count one copy-back dispatch of `texels` texels at `site`.
++pub(crate) fn count_back_site(site: usize, texels: u64) {
++ use std::sync::atomic::Ordering::Relaxed;
++ let large = usize::from(texels >= 1_000_000);
++ BACK_SITE[large][site].fetch_add(1, Relaxed);
++ BACK_SITE_TEXELS[large][site].fetch_add(texels, Relaxed);
++}
+ use std::ops::Range;
+ use std::sync::atomic::{AtomicU64, Ordering};
+ use std::sync::Arc;
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index 9061bd11..8ef612fc 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -1025,6 +1025,18 @@ fn report() {
+ eprintln!("copy_back_why {name}: {}", parts.join(" "));
+ }
+ }
++ for (large, name) in [(1usize, ">=1M"), (0, "<1M")] {
++ let parts: Vec = (0..4)
++ .filter_map(|w| {
++ let n = super::shadow::BACK_SITE[large][w].load(Ordering::Relaxed);
++ let t = super::shadow::BACK_SITE_TEXELS[large][w].load(Ordering::Relaxed);
++ (n > 0).then(|| format!("{} {n}/{}M", super::shadow::BACK_SITE_NAMES[w], t / 1_000_000))
++ })
++ .collect();
++ if !parts.is_empty() {
++ eprintln!("copy_back_site {name}: {}", parts.join(" "));
++ }
++ }
+ for lazy in surfaces().iter().take(16) {
+ eprintln!(
+ "surface_lazy: {:#x} {}x{} displayed {} taken {} refused {} in {} presents {}",
+diff --git a/crates/metal2vulkan-runtime/src/shadow_merge.rs b/crates/metal2vulkan-runtime/src/shadow_merge.rs
+index 97cc4455..bce187a5 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_merge.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_merge.rs
+@@ -1168,7 +1168,13 @@ fn dispatched_out(
+ buffer_offset: part.at,
+ ..*region
+ };
+- CopyBack::new(device, *words, part.raw, ®ion)
++ let back = CopyBack::new(device, *words, part.raw, ®ion);
++ if back.is_some() {
++ // LOCAL (Atlas): diagnostics.
++ let e = region.image_extent;
++ crate::shadow::count_back_site(2, u64::from(e.width) * u64::from(e.height));
++ }
++ back
+ }
+
+ /// Where a cut rectangle's rows lie in the buffer's `VkBuffer`.
diff --git a/patches/metal2vulkan/0065-per-surface-defer-refusal-counters-and-coherent-stat.patch b/patches/metal2vulkan/0065-per-surface-defer-refusal-counters-and-coherent-stat.patch
new file mode 100644
index 0000000..eb75b5f
--- /dev/null
+++ b/patches/metal2vulkan/0065-per-surface-defer-refusal-counters-and-coherent-stat.patch
@@ -0,0 +1,94 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 12:11:16 +0000
+Subject: [PATCH 65/92] per-surface defer refusal counters and coherent state
+ in the lazy report (lab diagnostics)
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/shadow_lazy.rs | 16 +++++++++++++++-
+ 1 file changed, 15 insertions(+), 1 deletion(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index 8ef612fc..33013ce9 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -1039,7 +1039,8 @@ fn report() {
+ }
+ for lazy in surfaces().iter().take(16) {
+ eprintln!(
+- "surface_lazy: {:#x} {}x{} displayed {} taken {} refused {} in {} presents {}",
++ "surface_lazy: {:#x} {}x{} displayed {} taken {} refused {} in {} presents {} \
++ coherent {}/{} defer-no {:?}",
+ lazy.pages.as_ref().map_or(0, |pages| pages.start),
+ lazy.size[0],
+ lazy.size[1],
+@@ -1048,6 +1049,9 @@ fn report() {
+ read(&lazy.refused),
+ read(&lazy.copied_in),
+ read(&lazy.presents),
++ lazy.coherent.get().is_some(),
++ lazy.coherent().is_some(),
++ lazy.defer_no.each_ref().map(read),
+ );
+ }
+ }
+@@ -1198,6 +1202,9 @@ const BESIDE_KEPT: usize = 256;
+
+ /// One surface's standing.
+ pub(crate) struct Lazy {
++ /// LOCAL (Atlas, lab diagnostics): `defer`'s refusals by exit (not presented, beside
++ /// another, keeps gone, no queue, the traps refused).
++ defer_no: [AtomicU64; 5],
+ truth: OnceLock<(ResourceKey, Option, UseRange)>,
+ written: AtomicU64,
+ /// LOCAL (Atlas): the writes counted in [`Lazy::written`] that left no [`Beside`] entry
+@@ -1252,6 +1259,7 @@ impl Lazy {
+ ) -> Option> {
+ (surface && takes_surface(size[0], texels)).then(|| {
+ Arc::new(Lazy {
++ defer_no: Default::default(),
+ truth: OnceLock::new(),
+ written: AtomicU64::new(0),
+ plain: AtomicU64::new(0),
+@@ -1399,6 +1407,7 @@ impl Lazy {
+ || !(self.displayed.load(Ordering::Relaxed) || crate::live::on(PRESENT_ALL, false)))
+ {
+ count(Fallback::LazyDeferNotPresent);
++ self.defer_no[0].fetch_add(1, Ordering::Relaxed); // LOCAL (Atlas): diagnostics
+ return false;
+ }
+ // What it leaves ahead only hooks that find it can bring back, standing or not.
+@@ -1407,27 +1416,32 @@ impl Lazy {
+ if self.beside_another() {
+ SHARED.fetch_add(1, Ordering::Relaxed);
+ count(Fallback::LazyDeferBeside);
++ self.defer_no[1].fetch_add(1, Ordering::Relaxed);
+ return false;
+ }
+ let Some(holds) = self.keeps.get() else {
+ count(Fallback::LazyDeferKeepsGone);
++ self.defer_no[2].fetch_add(1, Ordering::Relaxed);
+ return false;
+ };
+ let holds: Option> = holds.iter().map(Weak::upgrade).collect();
+ let Some(holds) = holds else {
+ count(Fallback::LazyDeferKeepsGone);
++ self.defer_no[2].fetch_add(1, Ordering::Relaxed);
+ return false;
+ };
+ if self.queue.get().is_none() {
+ let device = self.device.downcast_ref::();
+ let Some(queue) = device.and_then(|d| d.new_command_queue().ok()) else {
+ count(Fallback::LazyDeferNoQueue);
++ self.defer_no[3].fetch_add(1, Ordering::Relaxed);
+ return false;
+ };
+ let _ = self.queue.set(Arc::new(queue));
+ }
+ // Its record is what a trap copies: no page, no deferring.
+ if coherent.is_some_and(|coherent| !coherent.defers(id, area)) {
++ self.defer_no[4].fetch_add(1, Ordering::Relaxed);
+ return false;
+ }
+ let mut pending = self.pending.lock().unwrap();
diff --git a/patches/metal2vulkan/0066-print-who-tracks-second-over-trapped-pages-lab-diagn.patch b/patches/metal2vulkan/0066-print-who-tracks-second-over-trapped-pages-lab-diagn.patch
new file mode 100644
index 0000000..60c4407
--- /dev/null
+++ b/patches/metal2vulkan/0066-print-who-tracks-second-over-trapped-pages-lab-diagn.patch
@@ -0,0 +1,53 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 12:38:24 +0000
+Subject: [PATCH 66/92] print who tracks second over trapped pages (lab
+ diagnostics)
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/shadow_coherent.rs | 14 ++++++++++++++
+ crates/metal2vulkan-runtime/src/shadow_lazy.rs | 5 +++++
+ 2 files changed, 19 insertions(+)
+
+diff --git a/crates/metal2vulkan-runtime/src/shadow_coherent.rs b/crates/metal2vulkan-runtime/src/shadow_coherent.rs
+index ca151e3d..e3edc4c9 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_coherent.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_coherent.rs
+@@ -757,6 +757,20 @@ impl Coherent {
+ {
+ let mut list = all().write().unwrap();
+ if list.iter().any(meets) {
++ // LOCAL (Atlas, lab diagnostics): who tracks second over pages another traps.
++ static SHOWN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
++ if SHOWN.fetch_add(1, Ordering::Relaxed) < 8 {
++ let other = list.iter().find(|one| meets(one)).map(|one| {
++ let lazy = one.lazy.upgrade();
++ (one.range(), lazy.map(|l| l.size_and_taken()))
++ });
++ let me = self.lazy.upgrade().map(|l| l.size_and_taken());
++ eprintln!(
++ "m2v-overlap-closed: me {:?} {:?} age {:?} other {:?}\n{}",
++ range, me, self.made.elapsed(), other,
++ std::backtrace::Backtrace::force_capture()
++ );
++ }
+ state.closed = true;
+ count(Fallback::ClosedByOverlap);
+ return false;
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index 33013ce9..95222b09 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -1302,6 +1302,11 @@ impl Lazy {
+ self.coherent.get().filter(|coherent| coherent.is_live())
+ }
+
++ /// LOCAL (Atlas, lab diagnostics): the takes of its standing so far.
++ pub(crate) fn size_and_taken(&self) -> ([u32; 2], u64) {
++ (self.size, self.taken.load(Ordering::Relaxed))
++ }
++
+ /// Whether its image must stay whole: a trapping surface's copies back are any rectangle.
+ pub(super) fn whole_image(&self) -> bool {
+ self.coherent.get().is_some_and(|coherent| coherent.is_live())
diff --git a/patches/metal2vulkan/0067-print-who-makes-a-large-lazy-surface-s-shadow-lazy-i.patch b/patches/metal2vulkan/0067-print-who-makes-a-large-lazy-surface-s-shadow-lazy-i.patch
new file mode 100644
index 0000000..0c633a5
--- /dev/null
+++ b/patches/metal2vulkan/0067-print-who-makes-a-large-lazy-surface-s-shadow-lazy-i.patch
@@ -0,0 +1,102 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 13:19:25 +0000
+Subject: [PATCH 67/92] print who makes a large lazy surface's shadow, lazy
+ identities in reports (lab diagnostics)
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/buffer_texture.rs | 40 ++++++++++++++-----
+ .../src/shadow_coherent.rs | 4 +-
+ .../metal2vulkan-runtime/src/shadow_lazy.rs | 3 +-
+ 3 files changed, 33 insertions(+), 14 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs
+index 4a8e11b7..f80893be 100644
+--- a/crates/metal2vulkan-runtime/src/buffer_texture.rs
++++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs
+@@ -1398,6 +1398,34 @@ impl Texels {
+ // A copy back dispatches, and a merge fetches, over one region copied in place alone.
+ let one_region = regions.len() == 1 && slices == 1 && staging.is_none();
+ let (bytes, tracked) = self.buffer.tracked(layout.offset..layout.end());
++ // LOCAL (Atlas): `shadow_lazy.rs`.
++ let lazy = super::shadow_lazy::Lazy::of(
++ self.buffer.device(),
++ self.backing() == super::shadow::Backing::Surface,
++ || self.buffer.host_range(),
++ [
++ (self.layout.row_bytes / self.texel_bytes) as u32,
++ self.layout.rows as u32,
++ ],
++ self.layout.row_bytes / self.texel_bytes * u64::from(self.layout.rows),
++ );
++ // LOCAL (Atlas, lab diagnostics): who makes a large lazy surface's shadow (first 24).
++ if let Some(lazy) = lazy.as_ref().filter(|_| self.layout.rows >= 1400) {
++ static SHOWN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
++ if SHOWN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 24 {
++ eprintln!(
++ "m2v-lazy-made: {:p} {:?} texel {} row_bytes {} words {} unorm {} aspects {:#x}\n{}",
++ Arc::as_ptr(lazy),
++ lazy.size_and_taken().0,
++ self.texel_bytes,
++ self.layout.row_bytes,
++ words.is_some(),
++ unorm.is_some(),
++ aspects.as_raw(),
++ std::backtrace::Backtrace::force_capture()
++ );
++ }
++ }
+ Ok(ShadowCopies {
+ source: ShadowSource::Bytes {
+ buffer: ShadowBuffer::of(&self.buffer, buffer),
+@@ -1426,17 +1454,7 @@ impl Texels {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
+- // LOCAL (Atlas): `shadow_lazy.rs`.
+- lazy: super::shadow_lazy::Lazy::of(
+- self.buffer.device(),
+- self.backing() == super::shadow::Backing::Surface,
+- || self.buffer.host_range(),
+- [
+- (self.layout.row_bytes / self.texel_bytes) as u32,
+- self.layout.rows as u32,
+- ],
+- self.layout.row_bytes / self.texel_bytes * u64::from(self.layout.rows),
+- ),
++ lazy,
+ })
+ }
+
+diff --git a/crates/metal2vulkan-runtime/src/shadow_coherent.rs b/crates/metal2vulkan-runtime/src/shadow_coherent.rs
+index e3edc4c9..d00e5e28 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_coherent.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_coherent.rs
+@@ -762,9 +762,9 @@ impl Coherent {
+ if SHOWN.fetch_add(1, Ordering::Relaxed) < 8 {
+ let other = list.iter().find(|one| meets(one)).map(|one| {
+ let lazy = one.lazy.upgrade();
+- (one.range(), lazy.map(|l| l.size_and_taken()))
++ (one.range(), lazy.map(|l| (Arc::as_ptr(&l), l.size_and_taken())))
+ });
+- let me = self.lazy.upgrade().map(|l| l.size_and_taken());
++ let me = self.lazy.upgrade().map(|l| (Arc::as_ptr(&l), l.size_and_taken()));
+ eprintln!(
+ "m2v-overlap-closed: me {:?} {:?} age {:?} other {:?}\n{}",
+ range, me, self.made.elapsed(), other,
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index 95222b09..1f9dc7da 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -1039,8 +1039,9 @@ fn report() {
+ }
+ for lazy in surfaces().iter().take(16) {
+ eprintln!(
+- "surface_lazy: {:#x} {}x{} displayed {} taken {} refused {} in {} presents {} \
++ "surface_lazy: {:p} {:#x} {}x{} displayed {} taken {} refused {} in {} presents {} \
+ coherent {}/{} defer-no {:?}",
++ Arc::as_ptr(lazy),
+ lazy.pages.as_ref().map_or(0, |pages| pages.start),
+ lazy.size[0],
+ lazy.size[1],
diff --git a/patches/metal2vulkan/0068-lab-surface_coherent_writer_wins-live-switch-default.patch b/patches/metal2vulkan/0068-lab-surface_coherent_writer_wins-live-switch-default.patch
new file mode 100644
index 0000000..0035f5c
--- /dev/null
+++ b/patches/metal2vulkan/0068-lab-surface_coherent_writer_wins-live-switch-default.patch
@@ -0,0 +1,161 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 13:29:49 +0000
+Subject: [PATCH 68/92] lab: surface_coherent_writer_wins live switch (default
+ off): a reading trap owner yields its pages to a writing image over the same
+ surface, forgetting its standing
+
+---
+ crates/metal2vulkan-runtime/src/shadow.rs | 2 +-
+ .../src/shadow_coherent.rs | 57 +++++++++++++++++++
+ .../metal2vulkan-runtime/src/shadow_lazy.rs | 14 +++++
+ 3 files changed, 72 insertions(+), 1 deletion(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs
+index f00d845d..496cab01 100644
+--- a/crates/metal2vulkan-runtime/src/shadow.rs
++++ b/crates/metal2vulkan-runtime/src/shadow.rs
+@@ -2801,7 +2801,7 @@ impl ShadowSync {
+ for shadow in shadows {
+ // Made here, or for a keep's scratch above: not copied in yet, so its copy in is the
+ // encoder's first.
+- let i = self.entry(&shadow.copies);
++ let i = crate::shadow_coherent::as_writer(shadow.writes, || self.entry(&shadow.copies));
+ let two_ways = kept
+ .iter()
+ .any(|(copies, _)| copies.shadow_key == shadow.copies.shadow_key);
+diff --git a/crates/metal2vulkan-runtime/src/shadow_coherent.rs b/crates/metal2vulkan-runtime/src/shadow_coherent.rs
+index d00e5e28..04a2fa5f 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_coherent.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_coherent.rs
+@@ -253,6 +253,24 @@ static LATE_COMPARES: AtomicU64 = AtomicU64::new(0);
+ static LATE_COMPARE_NS: AtomicU64 = AtomicU64::new(0);
+ static LATE_COMPARE_NS_MAX: AtomicU64 = AtomicU64::new(0);
+
++thread_local! {
++ /// LOCAL (Atlas): whether the shadow use being planned on this thread writes its texture
++ /// ([`as_writer`]), read by [`Coherent::tracks`] under `surface_coherent_writer_wins`.
++ static WRITER: std::cell::Cell = const { std::cell::Cell::new(false) };
++}
++
++/// LOCAL (Atlas): run `f` (a shadow entry's planning, which may track a surface) as a use that
++/// writes the texture or not.
++pub(crate) fn as_writer(writes: bool, f: impl FnOnce() -> R) -> R {
++ let before = WRITER.with(|w| w.replace(writes));
++ let out = f();
++ WRITER.with(|w| w.set(before));
++ out
++}
++
++/// LOCAL (Atlas): owners that yielded their pages to a writer (`surface_coherent_writer_wins`).
++pub(crate) static YIELDED: AtomicU64 = AtomicU64::new(0);
++
+ pub(crate) fn count(what: Fallback) {
+ FALLBACK[what as usize].fetch_add(1, Ordering::Relaxed);
+ }
+@@ -752,6 +770,22 @@ impl Coherent {
+ for one in dead {
+ one.retire();
+ }
++ // LOCAL (Atlas): live `surface_coherent_writer_wins` (default off). Two textures over one
++ // surface race to trap its pages at their first use; where the one that won never left a
++ // write ahead and has nothing running, and this use writes, it yields the pages to this
++ // one, as a dead surface's image retires above: the writer's copies back per encoder are
++ // what the trap saves. The yielding image goes on lazy alone, copying in when it is used.
++ if WRITER.with(std::cell::Cell::get) && crate::live::on("surface_coherent_writer_wins", false) {
++ let owners: Vec> = (all().read().unwrap().iter())
++ .filter(|one| meets(one) && one.lazy.strong_count() > 0)
++ .cloned()
++ .collect();
++ for one in owners {
++ if one.try_yield() {
++ YIELDED.fetch_add(1, Ordering::Relaxed);
++ }
++ }
++ }
+ // One image traps per surface: a trap reaches one, and that one would untrack the pages
+ // from under another. Any other stays lazy, its copies back keeping the pages.
+ {
+@@ -1379,6 +1413,29 @@ impl Coherent {
+ self.close(&mut state, true);
+ }
+
++ /// LOCAL (Atlas): give its pages up to another image over them that writes
++ /// (`surface_coherent_writer_wins`): only where it never left a write ahead and has nothing
++ /// running, so its image holds nothing the pages lack; what it settled lands as `retire`'s.
++ fn try_yield(&self) -> bool {
++ let mut state = self.lock();
++ if !state.tracked || state.closed {
++ return false;
++ }
++ // Anything it holds that the pages lack, or the pages hold that its image lacks, keeps it.
++ let busy = !state.running.is_empty() || !state.open.is_empty() || state.flushing != 0
++ || !state.owed.is_empty() || !state.owed_in.is_empty();
++ if self.counts.defers.load(Ordering::Relaxed) > 0 || busy || state.guest.is_some() {
++ return false;
++ }
++ self.sync_done(&mut state, SyncBy::Unmap);
++ self.close(&mut state, true);
++ drop(state);
++ if let Some(lazy) = self.lazy.upgrade() {
++ lazy.forget_standing();
++ }
++ true
++ }
++
+ /// Another image over the surface is about to read it: open pages held, so it reads all the
+ /// guest wrote and the next write traps. Whether any was open.
+ pub(crate) fn seal(&self) -> bool {
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index 1f9dc7da..9cf44341 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -1012,6 +1012,7 @@ fn report() {
+ read(&READERS_FIRST),
+ read(&OWN_BACKS_SKIPPED),
+ );
++ eprintln!("coherent_writer_wins: yielded {}", super::shadow_coherent::YIELDED.load(Ordering::Relaxed));
+ // LOCAL (Atlas, lab diagnostics): why the large shadows' copies back were recorded.
+ for (lazy, name) in [(1usize, "lazy"), (0, "plain")] {
+ let parts: Vec = (0..12)
+@@ -1206,6 +1207,10 @@ pub(crate) struct Lazy {
+ /// LOCAL (Atlas, lab diagnostics): `defer`'s refusals by exit (not presented, beside
+ /// another, keeps gone, no queue, the traps refused).
+ defer_no: [AtomicU64; 5],
++ /// LOCAL (Atlas): its surface stopped trapping for another image over it
++ /// (`surface_coherent_writer_wins`): the standing it kept while the pages trapped is not
++ /// trusted, and its next take copies the whole image in.
++ yielded: std::sync::atomic::AtomicBool,
+ truth: OnceLock<(ResourceKey, Option, UseRange)>,
+ written: AtomicU64,
+ /// LOCAL (Atlas): the writes counted in [`Lazy::written`] that left no [`Beside`] entry
+@@ -1261,6 +1266,7 @@ impl Lazy {
+ (surface && takes_surface(size[0], texels)).then(|| {
+ Arc::new(Lazy {
+ defer_no: Default::default(),
++ yielded: Default::default(),
+ truth: OnceLock::new(),
+ written: AtomicU64::new(0),
+ plain: AtomicU64::new(0),
+@@ -1303,6 +1309,11 @@ impl Lazy {
+ self.coherent.get().filter(|coherent| coherent.is_live())
+ }
+
++ /// LOCAL (Atlas): its surface gave its pages up to another image ([`Lazy::yielded`]).
++ pub(crate) fn forget_standing(&self) {
++ self.yielded.store(true, Ordering::Relaxed);
++ }
++
+ /// LOCAL (Atlas, lab diagnostics): the takes of its standing so far.
+ pub(crate) fn size_and_taken(&self) -> ([u32; 2], u64) {
+ (self.size, self.taken.load(Ordering::Relaxed))
+@@ -1845,6 +1856,9 @@ impl Lazy {
+ ordered: bool,
+ ) -> Option<(Option<[u32; 4]>, Option<[u32; 4]>, u64)> {
+ report();
++ if self.yielded.swap(false, Ordering::Relaxed) {
++ *self.stood.lock().unwrap() = None;
++ }
+ let Some(stood) = *self.stood.lock().unwrap() else {
+ REFUSED_BY[Refused::NoStanding as usize].fetch_add(1, Ordering::Relaxed);
+ return None;
diff --git a/patches/metal2vulkan/0069-lab-surface_twin_make_once-live-switch-default-off-t.patch b/patches/metal2vulkan/0069-lab-surface_twin_make_once-live-switch-default-off-t.patch
new file mode 100644
index 0000000..adabfbf
--- /dev/null
+++ b/patches/metal2vulkan/0069-lab-surface_twin_make_once-live-switch-default-off-t.patch
@@ -0,0 +1,87 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 14:00:39 +0000
+Subject: [PATCH 69/92] lab: surface_twin_make_once live switch (default off):
+ textures of a lazy surface made one at a time so a later one binds the first
+ shadow; diagnostic for a second first shadow
+
+---
+ crates/metal2vulkan-runtime/src/texture.rs | 5 +++
+ .../src/texture/surface_twin.rs | 41 +++++++++++++++++++
+ 2 files changed, 46 insertions(+)
+
+diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs
+index 834ee016..8486ee10 100644
+--- a/crates/metal2vulkan-runtime/src/texture.rs
++++ b/crates/metal2vulkan-runtime/src/texture.rs
+@@ -2149,6 +2149,11 @@ impl Device {
+ ) -> Result {
+ let record = ViewRecord::of_descriptor(layout, descriptor);
+ let texels = Arc::new(texels);
++ // LOCAL (Atlas): live `surface_twin_make_once` (default off). Two textures of one lazy
++ // surface made at once both found no first shadow and made an image each, as the first is
++ // noted only once its image is made: two standings over one surface, whose traps race
++ // (`shadow_coherent::Coherent::tracks`). Made one at a time, the later binds the first.
++ let _making = surface_twin::making_one(&texels);
+ // LOCAL (Atlas): one image for a surface's bytes (`surface_twin.rs`).
+ if let Some(storage) = self.surface_twin(&texels, descriptor, layout) {
+ return Ok(Texture::made(self, storage, record, None, id_use));
+diff --git a/crates/metal2vulkan-runtime/src/texture/surface_twin.rs b/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
+index 14978604..d5471d16 100644
+--- a/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
++++ b/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
+@@ -30,6 +30,38 @@ use super::*;
+ /// The live switch.
+ const SWITCH: &str = "surface_twin";
+
++/// LOCAL (Atlas): held while a texture of a lazy surface is made, from the look for its first
++/// shadow to its own noting as one (`surface_twin_make_once`); `None` where it is not held.
++pub(super) struct Making(Option>);
++
++impl Drop for Making {
++ fn drop(&mut self) {
++ if self.0.take().is_some() {
++ MAKING.with(|making| making.set(false));
++ }
++ }
++}
++
++thread_local! {
++ static MAKING: std::cell::Cell = const { std::cell::Cell::new(false) };
++}
++
++/// LOCAL (Atlas): make textures of lazy surfaces one at a time (`surface_twin_make_once`); a
++/// texture made while this thread makes one (an attachment's twin) goes on as before.
++pub(super) fn making_one(texels: &Texels) -> Making {
++ static ONE: Mutex<()> = Mutex::new(());
++ if !crate::live::on("surface_twin_make_once", false)
++ || !texels.lies_lazily()
++ || texels.surface_key().is_none()
++ || MAKING.with(std::cell::Cell::get)
++ {
++ return Making(None);
++ }
++ let guard = ONE.lock().unwrap_or_else(|e| e.into_inner());
++ MAKING.with(|making| making.set(true));
++ Making(Some(guard))
++}
++
+ /// A surface's first shadow, weakly: it goes with its last texture.
+ struct First {
+ image: Weak,
+@@ -178,6 +210,15 @@ impl Device {
+ };
+ let mut twins = lock(&self.shared().textures.twins.0);
+ twins.retain(|_, first| first.texels.strong_count() > 0);
++ // LOCAL (Atlas, lab diagnostics): a second first shadow of one surface, made while the
++ // first was made (`surface_twin_make_once`).
++ if twins.contains_key(&key) {
++ static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
++ let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
++ if n < 16 {
++ eprintln!("m2v-twin-second-first: {key:?} extent {:?} ({} so far)", image.plan().extent, n + 1);
++ }
++ }
+ twins.entry(key).or_insert_with(|| First {
+ image: Arc::downgrade(image),
+ texels: Arc::downgrade(texels),
diff --git a/patches/metal2vulkan/0070-lab-surface_twin_make_once-waits-per-surface-not-glo.patch b/patches/metal2vulkan/0070-lab-surface_twin_make_once-waits-per-surface-not-glo.patch
new file mode 100644
index 0000000..f61da09
--- /dev/null
+++ b/patches/metal2vulkan/0070-lab-surface_twin_make_once-waits-per-surface-not-glo.patch
@@ -0,0 +1,87 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 15:02:24 +0000
+Subject: [PATCH 70/92] lab: surface_twin_make_once waits per surface, not
+ globally; counts made/waited
+
+---
+ .../src/texture/surface_twin.rs | 47 +++++++++++++++----
+ 1 file changed, 39 insertions(+), 8 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/texture/surface_twin.rs b/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
+index d5471d16..8d1d8c60 100644
+--- a/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
++++ b/crates/metal2vulkan-runtime/src/texture/surface_twin.rs
+@@ -31,12 +31,20 @@ use super::*;
+ const SWITCH: &str = "surface_twin";
+
+ /// LOCAL (Atlas): held while a texture of a lazy surface is made, from the look for its first
+-/// shadow to its own noting as one (`surface_twin_make_once`); `None` where it is not held.
+-pub(super) struct Making(Option>);
++/// shadow to its own noting as one (`surface_twin_make_once`): textures of one surface are made one
++/// at a time, those of other surfaces meanwhile. `None` where it is not held.
++pub(super) struct Making(Option<(usize, u64)>);
++
++/// The surfaces a texture is being made of, and the wait for one to end.
++static MAKING_OF: (Mutex>, std::sync::Condvar) =
++ (Mutex::new(Vec::new()), std::sync::Condvar::new());
+
+ impl Drop for Making {
+ fn drop(&mut self) {
+- if self.0.take().is_some() {
++ if let Some(key) = self.0.take() {
++ let mut making = MAKING_OF.0.lock().unwrap_or_else(|e| e.into_inner());
++ making.retain(|one| *one != key);
++ MAKING_OF.1.notify_all();
+ MAKING.with(|making| making.set(false));
+ }
+ }
+@@ -46,20 +54,43 @@ thread_local! {
+ static MAKING: std::cell::Cell = const { std::cell::Cell::new(false) };
+ }
+
+-/// LOCAL (Atlas): make textures of lazy surfaces one at a time (`surface_twin_make_once`); a
++/// LOCAL (Atlas): make textures of one lazy surface one at a time (`surface_twin_make_once`); a
+ /// texture made while this thread makes one (an attachment's twin) goes on as before.
+ pub(super) fn making_one(texels: &Texels) -> Making {
+- static ONE: Mutex<()> = Mutex::new(());
++ let Some(key) = texels.surface_key() else {
++ return Making(None);
++ };
+ if !crate::live::on("surface_twin_make_once", false)
+ || !texels.lies_lazily()
+- || texels.surface_key().is_none()
+ || MAKING.with(std::cell::Cell::get)
+ {
+ return Making(None);
+ }
+- let guard = ONE.lock().unwrap_or_else(|e| e.into_inner());
++ // LOCAL (Atlas, lab diagnostics): textures made under the switch, and those that waited.
++ static MADE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
++ static WAITED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
++ static WAITED_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
++ let made = MADE.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
++ let start = std::time::Instant::now();
++ let mut making = MAKING_OF.0.lock().unwrap_or_else(|e| e.into_inner());
++ if making.contains(&key) {
++ while making.contains(&key) {
++ making = MAKING_OF.1.wait(making).unwrap_or_else(|e| e.into_inner());
++ }
++ WAITED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
++ WAITED_NS.fetch_add(start.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
++ }
++ if made.is_power_of_two() || made % 1024 == 0 {
++ eprintln!(
++ "m2v-make-once: made {made} waited {} for {} us",
++ WAITED.load(std::sync::atomic::Ordering::Relaxed),
++ WAITED_NS.load(std::sync::atomic::Ordering::Relaxed) / 1000
++ );
++ }
++ making.push(key);
++ drop(making);
+ MAKING.with(|making| making.set(true));
+- Making(Some(guard))
++ Making(Some(key))
+ }
+
+ /// A surface's first shadow, weakly: it goes with its last texture.
diff --git a/patches/metal2vulkan/0071-M2V_PENDING_AUDIT-diagnostic-begins-resets-of-comman.patch b/patches/metal2vulkan/0071-M2V_PENDING_AUDIT-diagnostic-begins-resets-of-comman.patch
new file mode 100644
index 0000000..350a035
--- /dev/null
+++ b/patches/metal2vulkan/0071-M2V_PENDING_AUDIT-diagnostic-begins-resets-of-comman.patch
@@ -0,0 +1,515 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 16:27:36 +0000
+Subject: [PATCH 71/92] M2V_PENDING_AUDIT diagnostic: begins/resets of command
+ buffers whose submission (or an executing primary's) is pending
+
+---
+ .../src/command_buffer/group.rs | 6 +-
+ .../src/command_buffer/rerun.rs | 2 +-
+ .../metal2vulkan-runtime/src/device/prime.rs | 2 +-
+ .../metal2vulkan-runtime/src/device/relay.rs | 2 +-
+ .../src/device/staging.rs | 2 +-
+ .../metal2vulkan-runtime/src/device/submit.rs | 2 +-
+ crates/metal2vulkan-runtime/src/lib.rs | 1 +
+ .../metal2vulkan-runtime/src/pending_audit.rs | 318 ++++++++++++++++++
+ .../metal2vulkan-runtime/src/recorder/log.rs | 14 +
+ .../src/recorder/thunks.rs | 2 +
+ crates/metal2vulkan-runtime/src/spares.rs | 6 +
+ 11 files changed, 349 insertions(+), 8 deletions(-)
+ create mode 100644 crates/metal2vulkan-runtime/src/pending_audit.rs
+
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/group.rs b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+index 6d8051a6..f592cb4f 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/group.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/group.rs
+@@ -619,7 +619,7 @@ impl Group {
+ let submitted =
+ shared.submit_logged((queue, Some(value)), fence, &relayed, |vk_queue| unsafe {
+ shared.counts.queue_submitted(submits.len(), buffers);
+- { crate::wbs_audit::submits("group", submits); raw.queue_submit(vk_queue, submits, fence.unwrap_or(vk::Fence::null())) }
++ { crate::wbs_audit::submits("group", submits); crate::pending_audit::submits(raw, "group", submits, fence.unwrap_or(vk::Fence::null())); raw.queue_submit(vk_queue, submits, fence.unwrap_or(vk::Fence::null())) }
+ });
+ exit_guard::called(Call::QueueSubmit);
+ self.events.clear();
+@@ -694,7 +694,7 @@ fn submit_alone(device: &Device, after: After<'_>) -> Result<(), vk::Result> {
+ // SAFETY: the batch's submission's own (`submit.rs`).
+ let submitted = shared.submit_logged((queue, Some(value)), fence, relayed, |vk_queue| unsafe {
+ shared.counts.queue_submitted(infos.len(), buffers);
+- { crate::wbs_audit::submits("group_one", infos); raw.queue_submit(vk_queue, infos, fence.unwrap_or(vk::Fence::null())) }
++ { crate::wbs_audit::submits("group_one", infos); crate::pending_audit::submits(raw, "group_one", infos, fence.unwrap_or(vk::Fence::null())); raw.queue_submit(vk_queue, infos, fence.unwrap_or(vk::Fence::null())) }
+ });
+ exit_guard::called(Call::QueueSubmit);
+ submitted
+@@ -720,7 +720,7 @@ fn signal_alone(
+ // value (no batch signalled them); the `VkQueue` is used under its lock.
+ let submitted = shared.submit_logged((queue, value), None, relayed, |vk_queue| unsafe {
+ shared.counts.queue_submitted(1, 0);
+- { crate::wbs_audit::submits("group_end_signals", &[info]); raw.queue_submit(vk_queue, &[info], vk::Fence::null()) }
++ { crate::wbs_audit::submits("group_end_signals", &[info]); crate::pending_audit::submits(raw, "group_end_signals", &[info], vk::Fence::null()); raw.queue_submit(vk_queue, &[info], vk::Fence::null()) }
+ });
+ exit_guard::called(Call::QueueSubmit);
+ submitted
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs
+index 577341cc..085af460 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs
+@@ -420,7 +420,7 @@ impl LoopCheck {
+ (queue, None),
+ Some(fence),
+ &buffer.relayed,
+- |vk_queue| unsafe { crate::wbs_audit::submits("rerun", &submits); raw.queue_submit(vk_queue, &submits, fence) },
++ |vk_queue| unsafe { crate::wbs_audit::submits("rerun", &submits); crate::pending_audit::submits(raw, "rerun", &submits, fence); raw.queue_submit(vk_queue, &submits, fence) },
+ );
+ exit_guard::called(Call::QueueSubmit);
+ if let Err(error) = submitted {
+diff --git a/crates/metal2vulkan-runtime/src/device/prime.rs b/crates/metal2vulkan-runtime/src/device/prime.rs
+index 8e6cb175..b0b2de77 100644
+--- a/crates/metal2vulkan-runtime/src/device/prime.rs
++++ b/crates/metal2vulkan-runtime/src/device/prime.rs
+@@ -806,7 +806,7 @@ impl Primer<'_> {
+ // already; the signal raises the semaphore; the fence is new; the queue is used under its
+ // lock.
+ queues[0]
+- .with(|queue| unsafe { crate::wbs_audit::submits("prime", &[submit]); device.queue_submit(queue, &[submit], fence) })
++ .with(|queue| unsafe { crate::wbs_audit::submits("prime", &[submit]); crate::pending_audit::submits(device, "prime", &[submit], fence); device.queue_submit(queue, &[submit], fence) })
+ .map_err(vulkan)?;
+ self.made(Call::QueueSubmit);
+ let start = Instant::now();
+diff --git a/crates/metal2vulkan-runtime/src/device/relay.rs b/crates/metal2vulkan-runtime/src/device/relay.rs
+index a5b605b6..3cb88527 100644
+--- a/crates/metal2vulkan-runtime/src/device/relay.rs
++++ b/crates/metal2vulkan-runtime/src/device/relay.rs
+@@ -486,7 +486,7 @@ impl super::DeviceShared {
+ // value signalled there before where it has one; the queue is used under its
+ // lock.
+ let submitted =
+- unsafe { crate::wbs_audit::submits("relay", submits); raw.queue_submit(vk_queue, submits, fence.unwrap_or_default()) };
++ unsafe { crate::wbs_audit::submits("relay", submits); crate::pending_audit::submits(raw, "relay", submits, fence.unwrap_or_default()); raw.queue_submit(vk_queue, submits, fence.unwrap_or_default()) };
+ exit_guard::called(Call::QueueSubmit);
+ if submitted.is_err() {
+ if let Some((fence, flights)) = logged {
+diff --git a/crates/metal2vulkan-runtime/src/device/staging.rs b/crates/metal2vulkan-runtime/src/device/staging.rs
+index 1223922d..b89a86ca 100644
+--- a/crates/metal2vulkan-runtime/src/device/staging.rs
++++ b/crates/metal2vulkan-runtime/src/device/staging.rs
+@@ -246,7 +246,7 @@ impl Device {
+ shared.counts.queue_submitted(1, buffers.len());
+ let submitted = unsafe {
+ staging.word.restore();
+- { crate::wbs_audit::submits("staging", &[submit]); raw.queue_submit(queue, &[submit], made.fence) }
++ { crate::wbs_audit::submits("staging", &[submit]); crate::pending_audit::submits(raw, "staging", &[submit], made.fence); raw.queue_submit(queue, &[submit], made.fence) }
+ };
+ exit_guard::called(Call::QueueSubmit);
+ submitted.map_err(|error| self.failed(error))?;
+diff --git a/crates/metal2vulkan-runtime/src/device/submit.rs b/crates/metal2vulkan-runtime/src/device/submit.rs
+index e9ace296..77ca99d8 100644
+--- a/crates/metal2vulkan-runtime/src/device/submit.rs
++++ b/crates/metal2vulkan-runtime/src/device/submit.rs
+@@ -249,7 +249,7 @@ impl Device {
+ .iter()
+ .map(|info| info.command_buffer_count as usize);
+ shared.counts.queue_submitted(submits.len(), buffers.sum());
+- { crate::wbs_audit::submits("internal", &submits); raw.queue_submit(queue, &submits, objects.fence) }
++ { crate::wbs_audit::submits("internal", &submits); crate::pending_audit::submits(raw, "internal", &submits, objects.fence); raw.queue_submit(queue, &submits, objects.fence) }
+ });
+ // A `vkQueueSubmit` that fails leaves what its submissions reference as it was, or loses
+ // the device: the work goes back as `taken` drops.
+diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs
+index bfd49eed..145f310a 100644
+--- a/crates/metal2vulkan-runtime/src/lib.rs
++++ b/crates/metal2vulkan-runtime/src/lib.rs
+@@ -130,6 +130,7 @@ mod image_log;
+ mod image_plan;
+ // LOCAL (Atlas, diagnostic): M2V_WBS_AUDIT=1 reports timeline waits submitted before their signals.
+ mod wbs_audit;
++mod pending_audit;
+ mod in_place;
+ mod in_place_check;
+ mod index_bounds;
+diff --git a/crates/metal2vulkan-runtime/src/pending_audit.rs b/crates/metal2vulkan-runtime/src/pending_audit.rs
+new file mode 100644
+index 00000000..6bc05d27
+--- /dev/null
++++ b/crates/metal2vulkan-runtime/src/pending_audit.rs
+@@ -0,0 +1,318 @@
++//! LOCAL (Atlas, diagnostic): command buffers begun or reset while a submission that runs them
++//! is pending, and primaries submitted with a secondary begun again since they executed it.
++//!
++//! With `M2V_PENDING_AUDIT=1` (read once per process), every `vkBeginCommandBuffer` and
++//! `vkCmdExecuteCommands` that reaches the driver (through the recorder's thunks or a replay),
++//! every `vkResetCommandPool` of a spare (with the pool's command buffers) and every
++//! `vkQueueSubmit` the runtime makes pass here first. A begin or reset of a command buffer whose
++//! last submission (its own, or that of a primary that executed it since its last begin) has not
++//! reached its timeline signal is written to stderr (at most [`MOST_LINES`]) with the sites, the
++//! time since the submission, and the semaphore's value against the signal. On ANV (Mesa 26.2.4)
++//! such a begin rewrites batch buffers the GPU has yet to run: a secondary run by
++//! `CALL_AND_RETURN` ends at its new recording's return jump, whose address the primary never
++//! patched (0), and the command streamer runs into the general state pool (the MULTI2 hang of
++//! 2026-11-08, IPEHR 0x3f800000 at 0x200024). Off, each call is one relaxed load.
++use ash::vk;
++use std::collections::HashMap;
++use std::sync::atomic::{AtomicU64, Ordering};
++use std::sync::{LazyLock, Mutex, OnceLock};
++use std::time::Instant;
++
++/// The most lines written.
++const MOST_LINES: u64 = 300;
++
++static ON: LazyLock =
++ LazyLock::new(|| std::env::var_os("M2V_PENDING_AUDIT").is_some_and(|v| v == "1"));
++static LINES: AtomicU64 = AtomicU64::new(0);
++static FOUND: AtomicU64 = AtomicU64::new(0);
++static CHECKED: AtomicU64 = AtomicU64::new(0);
++
++/// Whether the audit is on.
++pub(crate) fn on() -> bool {
++ *ON
++}
++
++/// The device whose semaphores and fences are read (the first that submits).
++static DEVICE: OnceLock = OnceLock::new();
++
++/// A primary's last submission.
++struct Sub {
++ site: &'static str,
++ at: Instant,
++ /// The timeline signals of its info or the first later info of the same call with any.
++ signals: Vec<(vk::Semaphore, u64)>,
++ fence: vk::Fence,
++}
++
++#[derive(Default)]
++struct State {
++ /// Each command buffer's begins so far.
++ generation: HashMap,
++ /// A primary's executed secondaries since its last begin, with each one's generation then.
++ executes: HashMap>,
++ /// A secondary's executing primaries since its last begin.
++ executed_by: HashMap>,
++ /// A primary's last submission since its last begin.
++ subs: HashMap,
++}
++
++static STATE: LazyLock> = LazyLock::new(|| Mutex::new(State::default()));
++
++fn key(buffer: vk::CommandBuffer) -> u64 {
++ vk::Handle::as_raw(buffer)
++}
++
++fn line(text: String) {
++ if LINES.fetch_add(1, Ordering::Relaxed) < MOST_LINES {
++ eprintln!("m2v-pending-audit: {text}");
++ }
++}
++
++/// Why `sub` is still pending, or `None` where it completed (or nothing tells).
++fn pending(sub: &Sub) -> Option {
++ let device = DEVICE.get()?;
++ for &(semaphore, value) in &sub.signals {
++ // SAFETY: a semaphore of the device a submission signalled; read only.
++ if let Ok(now) = unsafe { device.get_semaphore_counter_value(semaphore) } {
++ if now < value {
++ return Some(format!(
++ "timeline {:#x} at {now} < {value}",
++ vk::Handle::as_raw(semaphore)
++ ));
++ }
++ }
++ }
++ if sub.signals.is_empty() && sub.fence != vk::Fence::null() {
++ // SAFETY: as above (a fence the runtime may have reset or reused since: a hint).
++ if let Ok(false) = unsafe { device.get_fence_status(sub.fence) } {
++ return Some(format!("fence {:#x} unsignalled", vk::Handle::as_raw(sub.fence)));
++ }
++ }
++ None
++}
++
++/// Check `buffer` about to be begun or reset at `site`, then forget what it recorded.
++fn check_and_forget(state: &mut State, buffer: u64, site: &'static str) {
++ CHECKED.fetch_add(1, Ordering::Relaxed);
++ if let Some(sub) = state.subs.get(&buffer) {
++ if let Some(why) = pending(sub) {
++ let n = FOUND.fetch_add(1, Ordering::Relaxed) + 1;
++ line(format!(
++ "#{n} {site}: command buffer {buffer:#x} itself, submitted at {} {:.2} ms ago, is pending ({why})",
++ sub.site,
++ sub.at.elapsed().as_secs_f64() * 1000.0
++ ));
++ }
++ }
++ if let Some(primaries) = state.executed_by.get(&buffer) {
++ for primary in primaries {
++ match state.subs.get(primary) {
++ Some(sub) => {
++ if let Some(why) = pending(sub) {
++ let n = FOUND.fetch_add(1, Ordering::Relaxed) + 1;
++ line(format!(
++ "#{n} {site}: secondary {buffer:#x} executed by primary {primary:#x}, submitted at {} {:.2} ms ago, is pending ({why})",
++ sub.site,
++ sub.at.elapsed().as_secs_f64() * 1000.0
++ ));
++ }
++ }
++ // Not submitted yet: its submission finds the secondary begun again.
++ None => {}
++ }
++ }
++ }
++ *state.generation.entry(buffer).or_insert(0) += 1;
++ state.subs.remove(&buffer);
++ if let Some(secondaries) = state.executes.remove(&buffer) {
++ for (secondary, _) in secondaries {
++ if let Some(by) = state.executed_by.get_mut(&secondary) {
++ by.retain(|p| *p != buffer);
++ }
++ }
++ }
++ // A secondary begun again: the primaries that executed it keep their record, and a
++ // submission of one of them finds the generation changed.
++ if let Some(by) = state.executed_by.get_mut(&buffer) {
++ by.clear();
++ }
++}
++
++/// A `vkBeginCommandBuffer` of `buffer` at `site`, before the call.
++pub(crate) fn begin(buffer: vk::CommandBuffer, site: &'static str) {
++ if !*ON {
++ return;
++ }
++ let mut state = STATE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ check_and_forget(&mut state, key(buffer), site);
++}
++
++/// A `vkResetCommandPool` of a pool holding `buffers`, at `site`, before the call.
++pub(crate) fn reset_pool(buffers: &[vk::CommandBuffer], site: &'static str) {
++ if !*ON {
++ return;
++ }
++ let mut state = STATE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ for &buffer in buffers {
++ check_and_forget(&mut state, key(buffer), site);
++ }
++}
++
++/// A `vkCmdExecuteCommands` of `secondaries` in `primary`.
++///
++/// # Safety
++/// `count` handles at `secondaries`.
++pub(crate) unsafe fn executes(
++ primary: vk::CommandBuffer,
++ count: u32,
++ secondaries: *const vk::CommandBuffer,
++) {
++ if !*ON || secondaries.is_null() || count == 0 {
++ return;
++ }
++ // SAFETY: the caller's.
++ let list = unsafe { std::slice::from_raw_parts(secondaries, count as usize) };
++ let mut state = STATE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ let p = key(primary);
++ for &secondary in list {
++ let s = key(secondary);
++ let generation = state.generation.get(&s).copied().unwrap_or(0);
++ state.executes.entry(p).or_default().push((s, generation));
++ let by = state.executed_by.entry(s).or_default();
++ if !by.contains(&p) {
++ by.push(p);
++ }
++ }
++}
++
++/// The timeline info in a `pNext` chain, if any.
++///
++/// # Safety
++/// `next` is a valid Vulkan `pNext` chain.
++unsafe fn timeline(
++ mut next: *const std::ffi::c_void,
++) -> Option<&'static vk::TimelineSemaphoreSubmitInfo<'static>> {
++ while !next.is_null() {
++ // SAFETY: every Vulkan structure starts with sType and pNext.
++ let base = unsafe { &*next.cast::>() };
++ if base.s_type == vk::StructureType::TIMELINE_SEMAPHORE_SUBMIT_INFO {
++ // SAFETY: its type says so.
++ return Some(unsafe { &*next.cast::>() });
++ }
++ next = base.p_next.cast();
++ }
++ None
++}
++
++/// A `vkQueueSubmit` of `infos` with `fence` on `device` at `site`, before the call.
++pub(crate) fn submits(
++ device: &ash::Device,
++ site: &'static str,
++ infos: &[vk::SubmitInfo<'_>],
++ fence: vk::Fence,
++) {
++ if !*ON {
++ return;
++ }
++ let _ = DEVICE.set(device.clone());
++ // Each info's timeline signals, nonzero.
++ let signals: Vec> = infos
++ .iter()
++ .map(|info| {
++ // SAFETY: a submission the caller is about to make, so its pointers are valid.
++ let Some(t) = (unsafe { timeline(info.p_next) }) else {
++ return Vec::new();
++ };
++ let n = info.signal_semaphore_count as usize;
++ if info.p_signal_semaphores.is_null()
++ || t.p_signal_semaphore_values.is_null()
++ || (t.signal_semaphore_value_count as usize) < n
++ {
++ return Vec::new();
++ }
++ // SAFETY: as above.
++ let (s, v) = unsafe {
++ (
++ std::slice::from_raw_parts(info.p_signal_semaphores, n),
++ std::slice::from_raw_parts(t.p_signal_semaphore_values, n),
++ )
++ };
++ s.iter().copied().zip(v.iter().copied()).filter(|&(_, v)| v != 0).collect()
++ })
++ .collect();
++ let mut state = STATE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ let at = Instant::now();
++ for (index, info) in infos.iter().enumerate() {
++ if info.p_command_buffers.is_null() || info.command_buffer_count == 0 {
++ continue;
++ }
++ // SAFETY: as above.
++ let buffers = unsafe {
++ std::slice::from_raw_parts(info.p_command_buffers, info.command_buffer_count as usize)
++ };
++ let mine = signals[index..]
++ .iter()
++ .find(|s| !s.is_empty())
++ .cloned()
++ .unwrap_or_default();
++ for &buffer in buffers {
++ let p = key(buffer);
++ // A secondary begun again since this primary executed it.
++ if let Some(executed) = state.executes.get(&p) {
++ for &(s, generation) in executed {
++ let now = state.generation.get(&s).copied().unwrap_or(0);
++ if now != generation {
++ let n = FOUND.fetch_add(1, Ordering::Relaxed) + 1;
++ line(format!(
++ "#{n} {site}: primary {p:#x} submitted with secondary {s:#x} begun {} time(s) since it executed it",
++ now - generation
++ ));
++ }
++ }
++ }
++ if let Some(previous) = state.subs.get(&p) {
++ if let Some(why) = pending(previous) {
++ let n = FOUND.fetch_add(1, Ordering::Relaxed) + 1;
++ line(format!(
++ "#{n} {site}: primary {p:#x} submitted again while its submission at {} {:.2} ms ago is pending ({why})",
++ previous.site,
++ previous.at.elapsed().as_secs_f64() * 1000.0
++ ));
++ }
++ }
++ state.subs.insert(
++ p,
++ Sub {
++ site,
++ at,
++ signals: mine.clone(),
++ fence,
++ },
++ );
++ }
++ }
++ let checked = CHECKED.load(Ordering::Relaxed);
++ if checked > 0 && checked.is_power_of_two() && checked >= 1024 {
++ line(format!(
++ "summary: {checked} begins/resets checked, {} found",
++ FOUND.load(Ordering::Relaxed)
++ ));
++ }
++}
++
++/// The routed commands' hook (`recorder/thunks.rs`), for a command that reaches the driver.
++macro_rules! hook {
++ (begin_command_buffer, $cb:ident, $info:ident) => {
++ if $crate::pending_audit::on() {
++ $crate::pending_audit::begin($cb, "begin")
++ }
++ };
++ (cmd_execute_commands, $cb:ident, $count:ident, $buffers:ident) => {
++ if $crate::pending_audit::on() {
++ // SAFETY: the driver call's own arguments.
++ unsafe { $crate::pending_audit::executes($cb, $count, $buffers) }
++ }
++ };
++ ($f:ident, $cb:ident $(, $a:ident)*) => {};
++}
++pub(crate) use hook;
+diff --git a/crates/metal2vulkan-runtime/src/recorder/log.rs b/crates/metal2vulkan-runtime/src/recorder/log.rs
+index 895770d7..68fc6f1c 100644
+--- a/crates/metal2vulkan-runtime/src/recorder/log.rs
++++ b/crates/metal2vulkan-runtime/src/recorder/log.rs
+@@ -1277,6 +1277,11 @@ impl Log {
+ unsafe { f(cb, $($arg),*) }
+ }};
+ }
++ // LOCAL (Atlas) diagnostic (`pending_audit.rs`): a primary begun ahead was checked as
++ // it was begun.
++ if !begun {
++ crate::pending_audit::begin(cb, "replay begin");
++ }
+ if !begun {
+ let began = call!(BeginCommandBuffer, vk::PFN_vkBeginCommandBuffer, &begin);
+ if began != vk::Result::SUCCESS {
+@@ -1606,6 +1611,15 @@ impl Log {
+ for &secondary in self.command_buffers.get(buffers) {
+ resolved.push(resolve(secondary).ok_or(vk::Result::ERROR_UNKNOWN)?);
+ }
++ // LOCAL (Atlas) diagnostic (`pending_audit.rs`).
++ // SAFETY: `resolved` holds that many handles.
++ unsafe {
++ crate::pending_audit::executes(
++ cb,
++ resolved.len() as u32,
++ resolved.as_ptr(),
++ )
++ };
+ call!(
+ CmdExecuteCommands,
+ vk::PFN_vkCmdExecuteCommands,
+diff --git a/crates/metal2vulkan-runtime/src/recorder/thunks.rs b/crates/metal2vulkan-runtime/src/recorder/thunks.rs
+index 1c9970ba..027a3dd4 100644
+--- a/crates/metal2vulkan-runtime/src/recorder/thunks.rs
++++ b/crates/metal2vulkan-runtime/src/recorder/thunks.rs
+@@ -182,6 +182,8 @@ macro_rules! commands {
+ crate::pass_times::hook!(after $f, stamps::(), command_buffer $(, $a)*);
+ return logged;
+ }
++ // LOCAL (Atlas) diagnostic: the pending audit's hook (`pending_audit.rs`).
++ crate::pending_audit::hook!($f, command_buffer $(, $a)*);
+ let real = REAL.$f[S].load(Ordering::Acquire);
+ if real.is_null() {
+ missing($n);
+diff --git a/crates/metal2vulkan-runtime/src/spares.rs b/crates/metal2vulkan-runtime/src/spares.rs
+index 5a4ad4e2..cd4a108d 100644
+--- a/crates/metal2vulkan-runtime/src/spares.rs
++++ b/crates/metal2vulkan-runtime/src/spares.rs
+@@ -313,6 +313,12 @@ impl Spares {
+ return Ok(None);
+ };
+ if pool.recording {
++ // LOCAL (Atlas) diagnostic (`pending_audit.rs`).
++ if crate::pending_audit::on() {
++ let all: Vec =
++ pool.made.iter().flatten().copied().chain(pool.begun).collect();
++ crate::pending_audit::reset_pool(&all, "spare pool reset");
++ }
+ // SAFETY: the pool is the caller's alone now, and nothing of it is pending: the
+ // command buffer that gave it back ended its work or was never submitted.
+ let reset = unsafe {
diff --git a/patches/metal2vulkan/0072-pending-audit-reads-each-semaphore-through-the-devic.patch b/patches/metal2vulkan/0072-pending-audit-reads-each-semaphore-through-the-devic.patch
new file mode 100644
index 0000000..185c770
--- /dev/null
+++ b/patches/metal2vulkan/0072-pending-audit-reads-each-semaphore-through-the-devic.patch
@@ -0,0 +1,76 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 16:56:45 +0000
+Subject: [PATCH 72/92] pending audit reads each semaphore through the device
+ that submitted it
+
+---
+ .../metal2vulkan-runtime/src/pending_audit.rs | 24 +++++++++++++++----
+ 1 file changed, 19 insertions(+), 5 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/pending_audit.rs b/crates/metal2vulkan-runtime/src/pending_audit.rs
+index 6bc05d27..cb98b9ef 100644
+--- a/crates/metal2vulkan-runtime/src/pending_audit.rs
++++ b/crates/metal2vulkan-runtime/src/pending_audit.rs
+@@ -15,7 +15,7 @@
+ use ash::vk;
+ use std::collections::HashMap;
+ use std::sync::atomic::{AtomicU64, Ordering};
+-use std::sync::{LazyLock, Mutex, OnceLock};
++use std::sync::{LazyLock, Mutex};
+ use std::time::Instant;
+
+ /// The most lines written.
+@@ -32,11 +32,14 @@ pub(crate) fn on() -> bool {
+ *ON
+ }
+
+-/// The device whose semaphores and fences are read (the first that submits).
+-static DEVICE: OnceLock = OnceLock::new();
++/// The devices that submitted, each read through its own (a semaphore read through another
++/// device reads 0).
++static DEVICES: LazyLock>> = LazyLock::new(|| Mutex::new(Vec::new()));
+
+ /// A primary's last submission.
+ struct Sub {
++ /// The index of its device in [`DEVICES`].
++ device: usize,
+ site: &'static str,
+ at: Instant,
+ /// The timeline signals of its info or the first later info of the same call with any.
+@@ -70,7 +73,8 @@ fn line(text: String) {
+
+ /// Why `sub` is still pending, or `None` where it completed (or nothing tells).
+ fn pending(sub: &Sub) -> Option {
+- let device = DEVICE.get()?;
++ let devices = DEVICES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ let device = devices.get(sub.device)?;
+ for &(semaphore, value) in &sub.signals {
+ // SAFETY: a semaphore of the device a submission signalled; read only.
+ if let Ok(now) = unsafe { device.get_semaphore_counter_value(semaphore) } {
+@@ -214,7 +218,16 @@ pub(crate) fn submits(
+ if !*ON {
+ return;
+ }
+- let _ = DEVICE.set(device.clone());
++ let index = {
++ let mut devices = DEVICES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ match devices.iter().position(|d| d.handle() == device.handle()) {
++ Some(at) => at,
++ None => {
++ devices.push(device.clone());
++ devices.len() - 1
++ }
++ }
++ };
+ // Each info's timeline signals, nonzero.
+ let signals: Vec> = infos
+ .iter()
+@@ -283,6 +296,7 @@ pub(crate) fn submits(
+ state.subs.insert(
+ p,
+ Sub {
++ device: index,
+ site,
+ at,
+ signals: mine.clone(),
diff --git a/patches/metal2vulkan/0073-pending-audit-reads-no-fence-and-only-long-lived-tim.patch b/patches/metal2vulkan/0073-pending-audit-reads-no-fence-and-only-long-lived-tim.patch
new file mode 100644
index 0000000..a6e4bea
--- /dev/null
+++ b/patches/metal2vulkan/0073-pending-audit-reads-no-fence-and-only-long-lived-tim.patch
@@ -0,0 +1,72 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 17:10:48 +0000
+Subject: [PATCH 73/92] pending audit reads no fence and only long-lived
+ timelines (a destroyed fence's read crashed ANV)
+
+---
+ .../metal2vulkan-runtime/src/pending_audit.rs | 30 +++++++++++++++----
+ 1 file changed, 24 insertions(+), 6 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/pending_audit.rs b/crates/metal2vulkan-runtime/src/pending_audit.rs
+index cb98b9ef..8f0549fc 100644
+--- a/crates/metal2vulkan-runtime/src/pending_audit.rs
++++ b/crates/metal2vulkan-runtime/src/pending_audit.rs
+@@ -18,6 +18,9 @@ use std::sync::atomic::{AtomicU64, Ordering};
+ use std::sync::{LazyLock, Mutex};
+ use std::time::Instant;
+
++/// Submissions a semaphore must have signalled before it is read.
++const LONG_LIVED: u64 = 64;
++
+ /// The most lines written.
+ const MOST_LINES: u64 = 300;
+
+@@ -49,6 +52,9 @@ struct Sub {
+
+ #[derive(Default)]
+ struct State {
++ /// How many submissions signalled each semaphore: only one seen in [`LONG_LIVED`] is read
++ /// (a queue's timeline, which lives with its device).
++ seen: HashMap,
+ /// Each command buffer's begins so far.
+ generation: HashMap,
+ /// A primary's executed secondaries since its last begin, with each one's generation then.
+@@ -86,12 +92,9 @@ fn pending(sub: &Sub) -> Option {
+ }
+ }
+ }
+- if sub.signals.is_empty() && sub.fence != vk::Fence::null() {
+- // SAFETY: as above (a fence the runtime may have reset or reused since: a hint).
+- if let Ok(false) = unsafe { device.get_fence_status(sub.fence) } {
+- return Some(format!("fence {:#x} unsignalled", vk::Handle::as_raw(sub.fence)));
+- }
+- }
++ // No fence is read: the runtime destroys its fences, and a read of a destroyed one
++ // crashed the driver (PAUD 2026-11-08).
++ let _ = sub.fence;
+ None
+ }
+
+@@ -255,6 +258,21 @@ pub(crate) fn submits(
+ .collect();
+ let mut state = STATE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let at = Instant::now();
++ for list in &signals {
++ for &(semaphore, _) in list {
++ *state.seen.entry(vk::Handle::as_raw(semaphore)).or_insert(0) += 1;
++ }
++ }
++ let signals: Vec> = signals
++ .into_iter()
++ .map(|list| {
++ list.into_iter()
++ .filter(|&(s, _)| {
++ state.seen.get(&vk::Handle::as_raw(s)).copied().unwrap_or(0) >= LONG_LIVED
++ })
++ .collect()
++ })
++ .collect();
+ for (index, info) in infos.iter().enumerate() {
+ if info.p_command_buffers.is_null() || info.command_buffer_count == 0 {
+ continue;
diff --git a/patches/metal2vulkan/0074-pending-audit-device-index-no-longer-shadowed-by-the.patch b/patches/metal2vulkan/0074-pending-audit-device-index-no-longer-shadowed-by-the.patch
new file mode 100644
index 0000000..9fe4ef4
--- /dev/null
+++ b/patches/metal2vulkan/0074-pending-audit-device-index-no-longer-shadowed-by-the.patch
@@ -0,0 +1,189 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 17:21:20 +0000
+Subject: [PATCH 74/92] pending audit: device index no longer shadowed by the
+ info index; tracks pools' command buffers (a pool destroyed while one is
+ pending is reported) and stops reading destroyed semaphores
+
+---
+ crates/metal2vulkan-runtime/src/device/mod.rs | 3 +
+ .../metal2vulkan-runtime/src/device/prime.rs | 3 +
+ .../metal2vulkan-runtime/src/pending_audit.rs | 58 +++++++++++++++++--
+ .../src/recorder/replays.rs | 1 +
+ crates/metal2vulkan-runtime/src/release.rs | 2 +
+ 5 files changed, 61 insertions(+), 6 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs
+index 4814fae2..920f2e14 100644
+--- a/crates/metal2vulkan-runtime/src/device/mod.rs
++++ b/crates/metal2vulkan-runtime/src/device/mod.rs
+@@ -612,6 +612,9 @@ impl DeviceShared {
+ self.vk().allocate_command_buffers(info)
+ };
+ exit_guard::called(Call::AllocateCommandBuffers);
++ if let Ok(buffers) = &allocated {
++ crate::pending_audit::allocated(info.command_pool, buffers);
++ }
+ allocated.map_err(super::error::vulkan)
+ }
+
+diff --git a/crates/metal2vulkan-runtime/src/device/prime.rs b/crates/metal2vulkan-runtime/src/device/prime.rs
+index b0b2de77..a0ecd0d1 100644
+--- a/crates/metal2vulkan-runtime/src/device/prime.rs
++++ b/crates/metal2vulkan-runtime/src/device/prime.rs
+@@ -663,6 +663,9 @@ impl Primer<'_> {
+ self.loader_word.restore();
+ self.device.allocate_command_buffers(info)
+ };
++ if let Ok(made) = &buffers {
++ crate::pending_audit::allocated(info.command_pool, made);
++ }
+ Ok(buffers.map_err(vulkan)?[0])
+ }
+
+diff --git a/crates/metal2vulkan-runtime/src/pending_audit.rs b/crates/metal2vulkan-runtime/src/pending_audit.rs
+index 8f0549fc..73f11b7c 100644
+--- a/crates/metal2vulkan-runtime/src/pending_audit.rs
++++ b/crates/metal2vulkan-runtime/src/pending_audit.rs
+@@ -63,6 +63,8 @@ struct State {
+ executed_by: HashMap>,
+ /// A primary's last submission since its last begin.
+ subs: HashMap,
++ /// Each command pool's command buffers, as allocated.
++ pools: HashMap>,
+ }
+
+ static STATE: LazyLock> = LazyLock::new(|| Mutex::new(State::default()));
+@@ -78,10 +80,15 @@ fn line(text: String) {
+ }
+
+ /// Why `sub` is still pending, or `None` where it completed (or nothing tells).
+-fn pending(sub: &Sub) -> Option {
++fn pending(seen: &HashMap, sub: &Sub) -> Option {
+ let devices = DEVICES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let device = devices.get(sub.device)?;
+ for &(semaphore, value) in &sub.signals {
++ // Only a semaphore still live and long-lived: a destroyed one is out of `seen`
++ // ([`released`]), and one made again at its handle starts its count over.
++ if seen.get(&vk::Handle::as_raw(semaphore)).copied().unwrap_or(0) < LONG_LIVED {
++ continue;
++ }
+ // SAFETY: a semaphore of the device a submission signalled; read only.
+ if let Ok(now) = unsafe { device.get_semaphore_counter_value(semaphore) } {
+ if now < value {
+@@ -102,7 +109,7 @@ fn pending(sub: &Sub) -> Option {
+ fn check_and_forget(state: &mut State, buffer: u64, site: &'static str) {
+ CHECKED.fetch_add(1, Ordering::Relaxed);
+ if let Some(sub) = state.subs.get(&buffer) {
+- if let Some(why) = pending(sub) {
++ if let Some(why) = pending(&state.seen, sub) {
+ let n = FOUND.fetch_add(1, Ordering::Relaxed) + 1;
+ line(format!(
+ "#{n} {site}: command buffer {buffer:#x} itself, submitted at {} {:.2} ms ago, is pending ({why})",
+@@ -115,7 +122,7 @@ fn check_and_forget(state: &mut State, buffer: u64, site: &'static str) {
+ for primary in primaries {
+ match state.subs.get(primary) {
+ Some(sub) => {
+- if let Some(why) = pending(sub) {
++ if let Some(why) = pending(&state.seen, sub) {
+ let n = FOUND.fetch_add(1, Ordering::Relaxed) + 1;
+ line(format!(
+ "#{n} {site}: secondary {buffer:#x} executed by primary {primary:#x}, submitted at {} {:.2} ms ago, is pending ({why})",
+@@ -221,7 +228,7 @@ pub(crate) fn submits(
+ if !*ON {
+ return;
+ }
+- let index = {
++ let device_index = {
+ let mut devices = DEVICES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ match devices.iter().position(|d| d.handle() == device.handle()) {
+ Some(at) => at,
+@@ -302,7 +309,7 @@ pub(crate) fn submits(
+ }
+ }
+ if let Some(previous) = state.subs.get(&p) {
+- if let Some(why) = pending(previous) {
++ if let Some(why) = pending(&state.seen, previous) {
+ let n = FOUND.fetch_add(1, Ordering::Relaxed) + 1;
+ line(format!(
+ "#{n} {site}: primary {p:#x} submitted again while its submission at {} {:.2} ms ago is pending ({why})",
+@@ -314,7 +321,7 @@ pub(crate) fn submits(
+ state.subs.insert(
+ p,
+ Sub {
+- device: index,
++ device: device_index,
+ site,
+ at,
+ signals: mine.clone(),
+@@ -332,6 +339,45 @@ pub(crate) fn submits(
+ }
+ }
+
++/// A `vkAllocateCommandBuffers` from `pool` that made `buffers`.
++pub(crate) fn allocated(pool: vk::CommandPool, buffers: &[vk::CommandBuffer]) {
++ if !*ON {
++ return;
++ }
++ let mut state = STATE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ let list = state.pools.entry(vk::Handle::as_raw(pool)).or_default();
++ list.extend(buffers.iter().map(|&b| key(b)));
++}
++
++/// A release (`release.rs`) of the object `raw` by `call`, before it: a command pool's command
++/// buffers are checked as by a reset and forgotten (their handles may be made again); a
++/// semaphore is no longer read.
++pub(crate) fn released(call: crate::exit_guard::Call, raw: u64) {
++ if !*ON {
++ return;
++ }
++ use crate::exit_guard::Call;
++ let mut state = STATE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ match call {
++ Call::DestroyCommandPool => {
++ let Some(buffers) = state.pools.remove(&raw) else {
++ return;
++ };
++ for buffer in buffers {
++ check_and_forget(&mut state, buffer, "pool destroy");
++ state.generation.remove(&buffer);
++ state.executed_by.remove(&buffer);
++ state.executes.remove(&buffer);
++ state.subs.remove(&buffer);
++ }
++ }
++ Call::DestroySemaphore => {
++ state.seen.remove(&raw);
++ }
++ _ => {}
++ }
++}
++
+ /// The routed commands' hook (`recorder/thunks.rs`), for a command that reaches the driver.
+ macro_rules! hook {
+ (begin_command_buffer, $cb:ident, $info:ident) => {
+diff --git a/crates/metal2vulkan-runtime/src/recorder/replays.rs b/crates/metal2vulkan-runtime/src/recorder/replays.rs
+index 7e673d29..6fec2282 100644
+--- a/crates/metal2vulkan-runtime/src/recorder/replays.rs
++++ b/crates/metal2vulkan-runtime/src/recorder/replays.rs
+@@ -553,6 +553,7 @@ impl Replays {
+ raw.allocate_command_buffers(&info)
+ }?[0];
+ exit_guard::called(Call::AllocateCommandBuffers);
++ crate::pending_audit::allocated(info.command_pool, &[buffer]);
+ pool.made(level, buffer);
+ Ok((buffer, false))
+ }
+diff --git a/crates/metal2vulkan-runtime/src/release.rs b/crates/metal2vulkan-runtime/src/release.rs
+index 684d84ec..dad738c7 100644
+--- a/crates/metal2vulkan-runtime/src/release.rs
++++ b/crates/metal2vulkan-runtime/src/release.rs
+@@ -144,6 +144,8 @@ macro_rules! released {
+ unsafe fn destroy(self, device: &ash::Device, _: Door) {
+ // LOCAL (Atlas) diagnostic: the image census and registry (`image_log.rs`).
+ crate::image_log::released(Call::$call, vk::Handle::as_raw(self));
++ // LOCAL (Atlas) diagnostic: the pending audit (`pending_audit.rs`).
++ crate::pending_audit::released(Call::$call, vk::Handle::as_raw(self));
+ // SAFETY: the caller's.
+ unsafe { device.$method(self, None) }
+ }
diff --git a/patches/metal2vulkan/0075-pending-audit-forgets-destroyed-devices-and-a-hit-li.patch b/patches/metal2vulkan/0075-pending-audit-forgets-destroyed-devices-and-a-hit-li.patch
new file mode 100644
index 0000000..4ccfc35
--- /dev/null
+++ b/patches/metal2vulkan/0075-pending-audit-forgets-destroyed-devices-and-a-hit-li.patch
@@ -0,0 +1,109 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 17:58:56 +0000
+Subject: [PATCH 75/92] pending audit: forgets destroyed devices, and a hit
+ line gives each live device's read of the timeline
+
+---
+ .../metal2vulkan-runtime/src/pending_audit.rs | 52 +++++++++++++++++--
+ crates/metal2vulkan-runtime/src/release.rs | 2 +
+ 2 files changed, 51 insertions(+), 3 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/pending_audit.rs b/crates/metal2vulkan-runtime/src/pending_audit.rs
+index 73f11b7c..76361024 100644
+--- a/crates/metal2vulkan-runtime/src/pending_audit.rs
++++ b/crates/metal2vulkan-runtime/src/pending_audit.rs
+@@ -82,6 +82,10 @@ fn line(text: String) {
+ /// Why `sub` is still pending, or `None` where it completed (or nothing tells).
+ fn pending(seen: &HashMap, sub: &Sub) -> Option {
+ let devices = DEVICES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ let dead = DEAD.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
++ if dead.contains(&sub.device) {
++ return None;
++ }
+ let device = devices.get(sub.device)?;
+ for &(semaphore, value) in &sub.signals {
+ // Only a semaphore still live and long-lived: a destroyed one is out of `seen`
+@@ -92,9 +96,25 @@ fn pending(seen: &HashMap, sub: &Sub) -> Option {
+ // SAFETY: a semaphore of the device a submission signalled; read only.
+ if let Ok(now) = unsafe { device.get_semaphore_counter_value(semaphore) } {
+ if now < value {
++ // Each device's read of it, to tell a wrong device (another fd's syncobj) apart.
++ let others: Vec = devices
++ .iter()
++ .enumerate()
++ .filter(|(i, _)| !dead.contains(i))
++ .map(|(i, d)| {
++ // SAFETY: as above; a read through another device only reads.
++ match unsafe { d.get_semaphore_counter_value(semaphore) } {
++ Ok(v) => format!("{i}:{v}"),
++ Err(e) => format!("{i}:{e:?}"),
++ }
++ })
++ .collect();
+ return Some(format!(
+- "timeline {:#x} at {now} < {value}",
+- vk::Handle::as_raw(semaphore)
++ "timeline {:#x} at {now} < {value} (device {} of {}; reads {})",
++ vk::Handle::as_raw(semaphore),
++ sub.device,
++ devices.len(),
++ others.join(",")
+ ));
+ }
+ }
+@@ -230,7 +250,10 @@ pub(crate) fn submits(
+ }
+ let device_index = {
+ let mut devices = DEVICES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+- match devices.iter().position(|d| d.handle() == device.handle()) {
++ let dead = DEAD.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
++ match (devices.iter().enumerate())
++ .position(|(i, d)| !dead.contains(&i) && d.handle() == device.handle())
++ {
+ Some(at) => at,
+ None => {
+ devices.push(device.clone());
+@@ -339,6 +362,29 @@ pub(crate) fn submits(
+ }
+ }
+
++/// A `vkDestroyDevice` of `device`, before it: it is no longer read through, and what it
++/// submitted is forgotten.
++pub(crate) fn device_destroyed(device: &ash::Device) {
++ if !*ON {
++ return;
++ }
++ let mut state = STATE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ let mut devices = DEVICES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ let mut dead = DEAD.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
++ let found = (devices.iter().enumerate())
++ .position(|(i, d)| !dead.contains(&i) && d.handle() == device.handle());
++ if let Some(at) = found {
++ // Keep the indices of the others: a destroyed device's slot reads nothing.
++ state.subs.retain(|_, sub| sub.device != at);
++ dead.push(at);
++ }
++ drop(dead);
++ drop(devices);
++}
++
++/// The indices in [`DEVICES`] of devices destroyed.
++static DEAD: LazyLock>> = LazyLock::new(|| Mutex::new(Vec::new()));
++
+ /// A `vkAllocateCommandBuffers` from `pool` that made `buffers`.
+ pub(crate) fn allocated(pool: vk::CommandPool, buffers: &[vk::CommandBuffer]) {
+ if !*ON {
+diff --git a/crates/metal2vulkan-runtime/src/release.rs b/crates/metal2vulkan-runtime/src/release.rs
+index dad738c7..3dc7c08f 100644
+--- a/crates/metal2vulkan-runtime/src/release.rs
++++ b/crates/metal2vulkan-runtime/src/release.rs
+@@ -180,6 +180,8 @@ impl Released for WholeDevice {
+ const CALL: Call = Call::DestroyDevice;
+
+ unsafe fn destroy(self, device: &ash::Device, _: Door) {
++ // LOCAL (Atlas) diagnostic: the pending audit (`pending_audit.rs`).
++ crate::pending_audit::device_destroyed(device);
+ // SAFETY: the caller's: every object made from the device is released.
+ unsafe { device.destroy_device(None) }
+ }
diff --git a/patches/metal2vulkan/0076-lab-M2V_FLAT_TILE-TWxTH-a-flat-grid-s-32-bit-index-w.patch b/patches/metal2vulkan/0076-lab-M2V_FLAT_TILE-TWxTH-a-flat-grid-s-32-bit-index-w.patch
new file mode 100644
index 0000000..983c891
--- /dev/null
+++ b/patches/metal2vulkan/0076-lab-M2V_FLAT_TILE-TWxTH-a-flat-grid-s-32-bit-index-w.patch
@@ -0,0 +1,125 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 18:02:33 +0000
+Subject: [PATCH 76/92] lab: M2V_FLAT_TILE=TWxTH: a flat grid's 32-bit index
+ walks each plane in TW x TH tiles (a bijection onto the same positions), for
+ 2-D locality
+
+---
+ crates/metal2vulkan/src/lower/dispatch.rs | 85 +++++++++++++++++++----
+ 1 file changed, 73 insertions(+), 12 deletions(-)
+
+diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs
+index e49b0bc2..9a5d83e0 100644
+--- a/crates/metal2vulkan/src/lower/dispatch.rs
++++ b/crates/metal2vulkan/src/lower/dispatch.rs
+@@ -1348,12 +1348,7 @@ impl KernelDecl {
+ let first: ArmFn<'_, ()> = Box::new(move |fb, _| {
+ let first = fb.convert(ConvOp::UConvert, start, u32_)?;
+ let index = fb.binary(BinOp::IAdd, first, lin)?;
+- let x = fb.binary(BinOp::UMod, index, gx)?;
+- let row = fb.binary(BinOp::UDiv, index, gx)?;
+- let y = fb.binary(BinOp::UMod, row, gy)?;
+- let z = fb.binary(BinOp::UDiv, row, gy)?;
+- let inside = fb.binary(BinOp::ULessThan, z, gz)?;
+- Ok(ArmEnd::FallThrough(vec![x, y, z, inside]))
++ Ok(ArmEnd::FallThrough(Self::position32(fb, index, [gx, gy, gz])?))
+ });
+ let narrow: ArmFn<'_, ()> = Box::new(move |fb, _| {
+ let group = fb.binary(BinOp::IMul, wz, ny)?;
+@@ -1362,12 +1357,7 @@ impl KernelDecl {
+ let group = fb.binary(BinOp::IAdd, group, wx)?;
+ let first = fb.binary(BinOp::IMul, group, n)?;
+ let index = fb.binary(BinOp::IAdd, first, lin)?;
+- let x = fb.binary(BinOp::UMod, index, gx)?;
+- let row = fb.binary(BinOp::UDiv, index, gx)?;
+- let y = fb.binary(BinOp::UMod, row, gy)?;
+- let z = fb.binary(BinOp::UDiv, row, gy)?;
+- let inside = fb.binary(BinOp::ULessThan, z, gz)?;
+- Ok(ArmEnd::FallThrough(vec![x, y, z, inside]))
++ Ok(ArmEnd::FallThrough(Self::position32(fb, index, [gx, gy, gz])?))
+ });
+ let wide: ArmFn<'_, ()> = Box::new(move |fb, _| {
+ let w = |fb: &mut FunctionBuilder<'_>, v: SValue| fb.convert(ConvOp::UConvert, v, u64_);
+@@ -1419,6 +1409,65 @@ impl KernelDecl {
+ Ok((pos, inside))
+ }
+
++ /// A flat grid's thread position from its 32-bit `index` over the grid `[gx, gy, gz]`, and
++ /// whether it lies inside (`z < gz`): `x` fastest, then `y`, then `z` ([`emit_entry`]'s
++ /// order), or, under LOCAL (Atlas) `M2V_FLAT_TILE=TWxTH` ([`flat_tile`]), a bijection of the
++ /// same indices onto the same positions that walks each plane in bands of `TH` rows and each
++ /// band in tiles of `TW` columns (the last band and the last tile of a band narrower), so a
++ /// threadgroup's consecutive indices cover a 2-D tile rather than a run of one row: the
++ /// partition-oblivious kernel reads and writes the same texels, with 2-D locality in tiled
++ /// images. The tiled form is taken only where `gx` and `gy` are below 2^16 (so a plane and a
++ /// band count in 32 bits); elsewhere the plain one.
++ fn position32(
++ fb: &mut FunctionBuilder<'_>,
++ index: SValue,
++ [gx, gy, gz]: [SValue; 3],
++ ) -> BResult> {
++ let x = fb.binary(BinOp::UMod, index, gx)?;
++ let row = fb.binary(BinOp::UDiv, index, gx)?;
++ let y = fb.binary(BinOp::UMod, row, gy)?;
++ let z = fb.binary(BinOp::UDiv, row, gy)?;
++ let inside = fb.binary(BinOp::ULessThan, z, gz)?;
++ let Some((tw, th)) = flat_tile() else {
++ return Ok(vec![x, y, z, inside]);
++ };
++ let min = |fb: &mut FunctionBuilder<'_>, a: SValue, b: SValue| -> BResult {
++ let less = fb.binary(BinOp::ULessThan, a, b)?;
++ fb.select(less, a, b)
++ };
++ let (tw, th) = (Self::k(fb, tw)?, Self::k(fb, th)?);
++ let plane = fb.binary(BinOp::IMul, gx, gy)?;
++ let tz = fb.binary(BinOp::UDiv, index, plane)?;
++ let r = fb.binary(BinOp::UMod, index, plane)?;
++ let band = fb.binary(BinOp::IMul, th, gx)?;
++ let b = fb.binary(BinOp::UDiv, r, band)?;
++ let j = fb.binary(BinOp::UMod, r, band)?;
++ let top = fb.binary(BinOp::IMul, b, th)?;
++ let left_rows = fb.binary(BinOp::ISub, gy, top)?;
++ let rows = min(fb, th, left_rows)?;
++ let tile = fb.binary(BinOp::IMul, tw, rows)?;
++ let c = fb.binary(BinOp::UDiv, j, tile)?;
++ let k = fb.binary(BinOp::UMod, j, tile)?;
++ let left = fb.binary(BinOp::IMul, c, tw)?;
++ let left_cols = fb.binary(BinOp::ISub, gx, left)?;
++ let w = min(fb, tw, left_cols)?;
++ let kx = fb.binary(BinOp::UMod, k, w)?;
++ let ky = fb.binary(BinOp::UDiv, k, w)?;
++ let tx = fb.binary(BinOp::IAdd, left, kx)?;
++ let ty = fb.binary(BinOp::IAdd, top, ky)?;
++ let tinside = fb.binary(BinOp::ULessThan, tz, gz)?;
++ let bound = Self::k(fb, 1 << 16)?;
++ let small_x = fb.binary(BinOp::ULessThan, gx, bound)?;
++ let small_y = fb.binary(BinOp::ULessThan, gy, bound)?;
++ let small = fb.binary(BinOp::LogicalAnd, small_x, small_y)?;
++ Ok(vec![
++ fb.select(small, tx, x)?,
++ fb.select(small, ty, y)?,
++ fb.select(small, tz, z)?,
++ fb.select(small, tinside, inside)?,
++ ])
++ }
++
+ /// The quotient (low word, high word) and remainder of the `u64` `n` (`[low, high]`) by the
+ /// `u32` `d` (not 0), in 32-bit operations: `hi / d` and `r = hi % d` (so `r < d`), then 32
+ /// restoring steps over the low word's bits, highest first, each `r = 2r + bit` and, when
+@@ -1727,3 +1776,15 @@ impl KernelDecl {
+
+ #[cfg(test)]
+ mod tests;
++
++/// LOCAL (Atlas, lab): the flat grid's tile, `M2V_FLAT_TILE=TWxTH` (each 1 to 1024), read once
++/// per process; unset or malformed, none ([`KernelDecl::position32`]'s plain order).
++fn flat_tile() -> Option<(u32, u32)> {
++ static TILE: std::sync::OnceLock> = std::sync::OnceLock::new();
++ *TILE.get_or_init(|| {
++ let v = std::env::var("M2V_FLAT_TILE").ok()?;
++ let (a, b) = v.split_once('x')?;
++ let (a, b) = (a.parse::().ok()?, b.parse::().ok()?);
++ ((1..=1024).contains(&a) && (1..=1024).contains(&b)).then_some((a, b))
++ })
++}
diff --git a/patches/metal2vulkan/0077-lab-live-shared_ccs-1-a-GPU-written-Shared-Managed-t.patch b/patches/metal2vulkan/0077-lab-live-shared_ccs-1-a-GPU-written-Shared-Managed-t.patch
new file mode 100644
index 0000000..7d1f9f5
--- /dev/null
+++ b/patches/metal2vulkan/0077-lab-live-shared_ccs-1-a-GPU-written-Shared-Managed-t.patch
@@ -0,0 +1,33 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 18:03:51 +0000
+Subject: [PATCH 77/92] lab: live shared_ccs=1: a GPU-written Shared/Managed
+ texture that does not trap takes no host-transfer usage (keeps CCS on ANV);
+ its CPU copies take the staging path
+
+---
+ crates/metal2vulkan-runtime/src/texture.rs | 11 ++++++++++-
+ 1 file changed, 10 insertions(+), 1 deletion(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs
+index 8486ee10..21aca83e 100644
+--- a/crates/metal2vulkan-runtime/src/texture.rs
++++ b/crates/metal2vulkan-runtime/src/texture.rs
+@@ -3223,7 +3223,16 @@ impl Device {
+ let one_sample = layout.samples == 1;
+ let staged =
+ !traps && !held && !private && one_sample && self.stages(&plan, layout.pixel_format);
+- let refused = (held || private) && !traps;
++ // LOCAL (Atlas, lab): live `shared_ccs=1`: a `Shared` or `Managed` texture the GPU writes
++ // (storage or color attachment), whose pages do not trap, takes no host-transfer usage,
++ // which on ANV turns its compression off: its CPU copies go through the staging queue (or
++ // the device's other copies) instead, and the GPU's passes and kernels over it keep CCS.
++ let gpu_written = (plan.usage)
++ .intersects(ImageUsageFlags::STORAGE | ImageUsageFlags::COLOR_ATTACHMENT);
++ let compressed = !traps
++ && gpu_written
++ && crate::live::get("shared_ccs").as_deref() == Some("1");
++ let refused = ((held || private) && !traps) || compressed;
+ let hosted = match refused || !one_sample || is_pvrtc(descriptor.pixel_format) {
+ true => None,
+ false => self.host_placed_image(&plan, layout.texture_type, class, staged, traps),
diff --git a/patches/metal2vulkan/0078-pending-audit-skips-semaphores-that-read-0-binary-se.patch b/patches/metal2vulkan/0078-pending-audit-skips-semaphores-that-read-0-binary-se.patch
new file mode 100644
index 0000000..d887817
--- /dev/null
+++ b/patches/metal2vulkan/0078-pending-audit-skips-semaphores-that-read-0-binary-se.patch
@@ -0,0 +1,26 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sun, 8 Nov 2026 20:02:49 +0000
+Subject: [PATCH 78/92] pending audit skips semaphores that read 0 (binary
+ semaphores in a signal list)
+
+---
+ crates/metal2vulkan-runtime/src/pending_audit.rs | 5 +++++
+ 1 file changed, 5 insertions(+)
+
+diff --git a/crates/metal2vulkan-runtime/src/pending_audit.rs b/crates/metal2vulkan-runtime/src/pending_audit.rs
+index 76361024..a3899011 100644
+--- a/crates/metal2vulkan-runtime/src/pending_audit.rs
++++ b/crates/metal2vulkan-runtime/src/pending_audit.rs
+@@ -95,6 +95,11 @@ fn pending(seen: &HashMap