Commit Graph
2005 Commits
Author SHA1 Message Date
Anees IqbalandClaude 6783a94576 ✨ A drain of one channel stamps one slot, so it submits one command buffer and not eleven
Pathway: x86 macOS / Linux Vulkan, drain worker. Behavior change on the child
FIFO's completion-stamp path, switched by `REIMS_VGPU_STAMP_COALESCE`.

THE MEASUREMENT THAT ASKED FOR THIS

`cb718e5f` split the drain residue's `regs` span three ways. Two driven macos-13
`blur=40` boots (`pin-split`), medians over 74 and 75 census windows:

    tailrd   0.49 / 0.48 ms/s      59 /  58 ns per op
    headwr   1.00 / 0.99 ms/s     128 / 127 ns per op
    stamp   92.29 / 98.59 ms/s   12266 / 13334 ns per op

    sum vs regs_us = 1.00 on every window

The two accesses that really are four-byte guest word accesses cost **1.5 ms a
second between them**. The stamp is **98.4 % of the span at 12.3 microseconds a
packet**, because `write_stamp` is not a word write: on the Vulkan arm it takes
the engine lock, binds the guest RAM reference, records a barrier and a
`cmd_update_buffer`, reserves a timeline value, and **submits a command buffer**.

`engine_delta` says the same thing from the other side, and this is the part that
generalizes past the stamp:

    batch_opens=6812  batch_joins=3934  batch_flushes=6812  batch_flush_draws=10746

**`batch_flushes` equals `batch_opens` exactly, at 1.58 draws a flush.** The draw
batch exists to amortize submits across draws and was never allowed to
accumulate any, because `write_stamp_after_guest_writes` appends to the open
batch and then flushes it. Every packet's stamp flushed whatever draws had
gathered.

WHAT THE CONTRACT LICENSES

Two facts, neither of them a heuristic:

1. **A stamp wait is `>=`, not `==`.** `StampWait::satisfied_by` is
   `current.wrapping_sub(self.value) as i32 >= 0`, so a wait on V is discharged
   by any value at or past V in wrapping-signed order. Intermediate values need
   never appear.
2. **A drain of one channel stamps one slot.** `stamp_index` is read once from
   the channel's register block *before* the loop, so every packet in a
   `drain_child_fifo` call writes the same slot. A run of writes to one slot is
   observable only through its greatest value unless the guest samples between
   them.

So `drain_child_fifo` now latches each packet's completion stamp into a
`PendingStamp` and writes once, after the loop. A driven boot averages **11.6
packets per drain call** (`packets` ~6400/s over `setup_calls` ~550-600/s), so
this removes roughly ten submissions in eleven.

THE TWO HAZARDS IT HAD TO DISPOSE OF, AND HOW

**A wait on the slot the drain is holding.** `note_packet_stamp_waits` reads the
word out of guest RAM, which is now stale by exactly the stamps this drain has
latched. A later packet in the same drain waiting on that slot would read the old
value, return `Hold`, and park the channel against a stamp this device is itself
sitting on — a deadlock introduced by the coalescing rather than by the guest. It
now consults the latch first, and answering from it is not a shortcut: packets
are processed in order on this thread, so a latched stamp is work that finished
before the waiting packet was decoded. Counted as `packet_stamp_wait_met_pending`
so the reliance is measurable rather than assumed.

**A latched stamp that never lands.** Every `break` in that loop falls through to
one site after it, which is why one flush is enough — a drain that stops on a
held stamp, a deferred translation, a decode fault or a host-action yield owes
what it latched exactly as one that ran the ring dry does. Leaving one unwritten
is a guest waiting on a word that never arrives, and its own deadline is a
second, so it would present as a stall rather than a hang.

`PendingStamp::latch` keeps the **maximum in wrapping-signed order**, not the
last value seen. For a well-formed guest those are the same value; taking the
maximum means this device cannot publish a slot going backwards even if a
regressing stamp arrives, which would unsatisfy a wait the guest had already been
told was met.

The main FIFO is unchanged and passes `None`: it stamps per packet and its slot
is not fixed across a drain, so neither fact above holds there. It also executed
zero times on this workload.

SWITCH

`REIMS_VGPU_STAMP_COALESCE=off` restores the per-packet arm on the same binary,
because a change to *when* a completion becomes visible fails as a stall or a
stutter rather than as a decline, and both arms have to be reachable for one A/B.
Off is a refusal and never a permission — one write per packet is strictly more
work than one per drain, and the coalesced arm needs no capability the per-packet
arm does not.

VERIFIED

- 1881 tests pass (+2), `--test-threads=1`, backend-vulkan,host-window.
- Both new tests fail without the change. `a_coalesced_stamp_keeps_the_latest_
  value_across_the_u32_wrap` was probed by stubbing `latch` to last-write-wins
  and fails on the regressing-stamp assertion; the file was restored by copying
  it back, not with git.
- Clippy `-D warnings` clean on all three arms.
- `scripts/feature-matrix`: all supported arms compile, warnings=0, lib count
  1881 (was 1879).

NOT VERIFIED

- **No boot.** Nothing here is measured on a guest yet: not the saving, not the
  frame rate, and not that the desktop still composites. That is the next step
  and it is an A/B against `=off` on one binary.
- Whether `batch_flushes` actually falls and whether the draw batch then
  accumulates. The prediction is that it does and that the win is larger than the
  92 ms/s the stamp span itself carries, but a prediction is not a reading.
- The arm64/Metal pathway. The coalescing is backend-independent but `write_stamp`'s
  GPU rail is `backend-vulkan`-gated, so the saving is expected to differ there
  and no Apple host has booted it.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 16:38:49 +03:00
Anees IqbalandClaude cb718e5f38 ✨ The residue is the stamp and the dispatch, and the two spans three sessions chased are 6% of it
Pathway: x86 macOS / Linux Vulkan, drain worker. Instrument only; no behavior
change.

WHAT THE TILING ANSWERED

`b03b2559` covered `drain_child_fifo` end to end with five spans instead of
nominating a fourth candidate. Two driven macos-13 `blur=40` boots
(`qemu-system-x86_64-pin-tile`), medians over the busy windows of each:

    outside child fifo   0.02 ms/s      <- the loop is covered; nothing hides

    residue (unnamed in drain)  270 ms/s, inside drain_us 849 at duty 0.84

    proc - draw - compute   155 ms/s   57 %    24 us/packet
    regs                     97 ms/s   36 %    5055 ns/op
    ring                     16 ms/s    6 %    1266 ns/read
    decode                  0.7 ms/s   0.3 %    117 ns/packet
    setup                  0.19 ms/s  0.07 %   0.33 us/call

The second boot reproduces every column (`regs` 88-105 ms/s, `ring` 15-16,
`proc - draw` ~165) across its 18 busy windows.

So `decode_packet` and the ring reader — the two candidates the previous two
sessions nominated from reading the code, one of which was the wrong function
entirely — are **6.3 % of the residue between them**. That is what `share of
unnamed` has been reporting at 0.06 and it is now explained rather than merely
observed. Both are retired; do not re-open either.

WHY THIS COMMIT SPLITS THEM FURTHER RATHER THAN FIXING ANYTHING

Two spans carry 93 % of the residue and neither is yet attributable to a site.

**`regs` is not register traffic.** The span was added expecting three cheap
guest word accesses a packet: the `CHILD_REG_TAIL` read, the `CHILD_REG_HEAD`
writeback, the completion stamp. It measured **5055 ns an access, 25x** what a
four-byte `address_space_read` costs, with a distribution running 65 ns at the
low end to 59 us at the high — which no word access has. `write_stamp` is the
candidate: on the Vulkan arm it tries `stamp_word_ordered_on_gpu` first, which
resolves a guest RAM reference and *submits a command buffer*, and falls through
to a blocking settle when that declines. But that is a reading of the code, and
readings of the code are 0-for-3 here, so this commit measures it instead:
`regs_ns` splits three ways by `RegsOp`, emitted beside the total so
`tailrd + headwr + stamp == regs` is checkable on the line itself.

**`proc - draw` is 24 us a packet against a decode that costs 117 ns**, over a
match with ~24 arms of which exactly one has ever been timed. Nothing says
whether that 155 ms is one arm or spread across all of them, so `proc_ns` now
splits by opcode onto its own `drain_ops` line under `drain_duty`.

THE OPCODE TABLE IS SIZED BY THE CONTRACT, NOT BY A SLOT COUNT

First draft was an associative table of 48 slots with a probe and a dropped-entry
counter. That is the bound class AGENTS.md warns about — a hand-picked capacity
that can be one short — so it was replaced with direct indexing over
`0..=CHILD_OP_MAX`, taking the width from `crate::model::CHILD_OP_MAX` rather
than from a count of the arms that happen to exist. There is no overflow left to
count: every opcode the guest can legally send has a slot, and one above the
maximum lands in `above_max`, which is a decoder result rather than a table
result since decode refuses those long before here.

`ProcOpTable` is its own type only because `#[derive(Default)]` stops at
32-element arrays and this is 65 wide. That is the entire cost of deriving the
bound instead of picking it.

`RegsOp` is a type rather than an index for the same reason the rest of the
crate's own vocabulary is: the consumer gets an exhaustiveness check, and the
integer appears once, in `label()`.

MEASUREMENT COST

Unchanged from `b03b2559` — the same four `Instant::now()` pairs a packet, now
attributed rather than aggregated. The opcode table adds one bounds-checked
index and two relaxed adds per packet.

VERIFIED

- 1879 tests pass, `--test-threads=1`, backend-vulkan,host-window.
- Clippy `-D warnings` clean on all three arms: backend-vulkan,host-window;
  `--target x86_64-unknown-linux-gnu` with the same features; and
  `--target aarch64-apple-darwin --features backend-metal`.
- `analyze.py` still reads a log captured before these fields existed — the new
  readers are their own families, so the tiling block prints unchanged on the
  two `pin-tile` logs.

NOT VERIFIED

- No boot at this commit. Which of the three accesses carries the 97 ms/s, and
  which opcodes carry the 155 ms/s, are both unmeasured — that is what the next
  boot is for.
- The arm64/Metal pathway. `write_stamp`'s GPU rail is `backend-vulkan`-gated,
  so the `Stamp` reading is expected to differ there and nothing has booted it.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 16:27:55 +03:00
Anees IqbalandClaude b03b255946 ✨ Tile the whole child-FIFO loop rather than sample it at a third point, because naming a candidate from reading the code is 0-for-2
Pathway: x86 macOS / Linux Vulkan, drain worker. Instrument only; no behavior
change.

THE PROBLEM WITH THE LAST TWO INSTRUMENTS

`drain_us` is 830-920 ms a second at duty 0.83-0.91 on a driven macos-13
`blur=40` boot, against `draw_us` 543-598. The 275-319 ms/s difference is a
third of the one thread every guest packet serializes through, and it is named
by nothing.

Two commits tried to name it by reading the code first and timing the candidate
second. `1937db0c` timed `decode_packet` and `read_ring_bytes`; the boot put
them at **0.2 % of the residue between them**, and one of the two was the wrong
function entirely — `read_ring_bytes` serves the root FIFO and executed zero
times, which `8ae8e9d5` repaired by adding the same timer to the child FIFO's
reader. Both candidates read convincingly in prose and neither was the cost.

So this stops proposing candidates. Instead of a third guess it tiles
`drain_child_fifo` end to end, so the answer is arithmetic rather than a
nomination:

    setup  +  N x ( regs + ring x2 + decode + proc )

Five spans, and they cover one iteration of the loop with nothing between them:

- `proc_us`  — the whole `process_child_packet` dispatch, all ~24 arms. It
  contains `draw_us` and `compute_us`, which name themselves on the same census
  line, so `proc - draw - compute` is the dispatch's own per-opcode cost.
- `regs_us` / `regs_ops` — the guest register traffic every packet pays around
  the dispatch: the `CHILD_REG_TAIL` read at the top of the loop, the
  `CHILD_REG_HEAD` writeback, and the completion stamp. Three accesses a packet
  that no phase has ever counted.
- `setup_us` / `setup_calls` — the per-call prologue: three register reads,
  `ensure_child_ring`, and the `page_gpas.clone()` the loop reads its ring
  through.

`ring_us` and `decode_us` already existed and complete the tiling.

WHAT THIS BUYS THAT A THIRD CANDIDATE WOULD NOT

The subtraction now closes. `analyze.py` grows an `outside child fifo` row —
`drain_us` less the tail, the boundary and all five spans — and that row is the
instrument's real output. A small one means the residue is inside this loop and
the five spans say which part. A large one means the cost is not in the child
FIFO at all and the search moves to the main FIFO, the mapper, or the pending
loop, none of which any candidate so far has even considered. Either way the
next step is read off the line rather than argued for.

COST OF THE MEASUREMENT

Four extra `Instant::now()` pairs a packet, ~40 000 a second at the observed
8 000 packets/s. A vDSO `clock_gettime` is ~20-25 ns, so ~1 ms/s against a
275-319 ms/s residue — under half a percent of the thing being measured, and it
lands identically in both arms of any A/B taken with it.

Nanoseconds, not microseconds, for the reason the existing pair documents:
`regs_ns` fires three times a packet and each sample is a handful of guest word
accesses, so `as_micros()` would truncate nearly every one to zero and report a
rail that runs 24 000 times a second as free.

VERIFIED

- 1879 tests pass, `--test-threads=1`, backend-vulkan,host-window.
- Clippy `-D warnings` clean on backend-vulkan,host-window and on
  `--target aarch64-apple-darwin --features backend-metal`.

NOT VERIFIED

- No boot at this commit. Every span added here is unmeasured; the point of the
  commit is that the next boot cannot come back ambiguous, not that it has come
  back.
- The arm64/Metal pathway. `drain_child_fifo` is backend-independent so the
  spans exist there too, but nothing has booted them.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 16:15:15 +03:00
Anees IqbalandClaude 8ae8e9d5e9 🐛 The ring reader I timed is the one that never runs, and the hot FIFO has its own
Pathway: x86 macOS / Linux Vulkan, drain worker. Instrument only.

1937db0c timed `read_ring_bytes` and `decode_packet` to find the third of the
drain worker no phase names. A driven macos-13 `blur=40` boot at that commit
answered, and the answer is that the instrument was pointed at the wrong
function:

    duty=0.91  unnamed=319.0ms  ring=0.0ms  ring_reads=0  decode=0.7ms
               packets=8663     share of unnamed = 0.002

`ring_reads` is **zero** over 35 census windows while the child FIFO decoded
6 700-8 800 packets a second. There are two readers over one wire form:
`read_ring_bytes` (2362 is the other one) serves the ROOT FIFO, which this
workload does not use, and `read_child_ring_bytes` serves the child FIFO, which
is the one every draw arrives on. Timing only the first reports a rail that
never executes, and a zero from it reads exactly like a span that is free —
which is the failure mode AGENTS.md describes for two arms consuming one wire
form, and the reason its rule is to diff them against each other rather than
read one alone.

This adds the same timer to `read_child_ring_bytes`, into the same counter pair,
with a doc on each saying why there are two and which one runs. A split by FIFO
is the next refinement if the total turns out to matter.

WHAT THE BOOT ALREADY SETTLED, AND IT IS NOT NOTHING

`decode_packet` is **not** the residue and never was: 0.7-0.9 ms/s over ~8 000
packets is ~110 ns a packet, 0.3 % of a 275-319 ms/s residue. That retires the
previous handoff's Candidate 2 outright, and it retires Candidate 1's reasoning
as well — that note asserted `read_ring_bytes` "copies the ring byte by byte",
which it does not (it chunks through `HostMemory::read_gpa` in at most two
iterations), and the function it named is not on this workload's path at all.

The residue itself is confirmed and large: 275-319 ms/s inside `drain_us` of
830-920 ms/s at duty 0.83-0.91, against `draw_us` 543-598 ms/s. Roughly a third
of the one thread every guest packet serializes through, still named by nothing.

VERIFIED

- 1879 tests pass, `--test-threads=1`, backend-vulkan,host-window.
- Clippy `-D warnings` clean on backend-vulkan,host-window.

NOT VERIFIED

- No boot at this commit. The reading above is from 1937db0c, whose binary is
  pinned at `vendor/qemu/build/qemu-system-x86_64-pin-ring`; this commit's
  binary has not been built or booted, so `ring_us` for the child reader is
  still unmeasured.
- Whether the child reader is the residue. It is now merely *counted*, which is
  the whole point — the previous two candidates both looked convincing in
  prose and were worth 0.3 % between them.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 16:09:41 +03:00
Anees IqbalandClaude 1937db0c36 ✨ The third of the drain worker named by nothing gets a per-packet split, because the residue scales with draws and every packet pays two ring reads and a decode
Pathway: x86 macOS / Linux Vulkan, drain worker. Instrument only — no behaviour
change.

`tail_us`/`boundary_us` closed the two spans after `Device::drain` returns and
found them near-empty (1.5 ms/s and 0), which localized the residue to inside
`runtime::drain::drain_pending` and no further. There is no `Instant::now`
anywhere in either FIFO function, so nothing inside it could be ranked.

Three driven macos-13 sustained-animation boots at 71462a94 put the residue at:

| boot | class | duty | unnamed in drain |
|---|---|---|---|
| v1 | ~60 Hz | 0.42 | 128 ms/s |
| v2 | ~109 Hz | 0.67 | 236 ms/s |
| v3 | ~60 Hz | 0.39 | 110 ms/s |

It roughly doubles with the frame rate, which is the shape of a per-packet cost
rather than a per-opcode one — so the two spans every packet pays are where to
look first.

WHAT IS COUNTED

`ring_us`/`ring_reads` and `decode_us`/`packets` on the `drain_duty` line.
Timed at `read_ring_bytes` and `decode_packet` themselves rather than at their
call sites, so both FIFOs and both reads per packet are covered and a fifth
call site cannot be added without being measured. Each keeps its own count, so
the per-call figure is available and not inferred from a draw count.

Nanoseconds, not microseconds. These fire tens of thousands of times a second
and one costs well under a microsecond, so `as_micros()` would truncate most
samples to zero and report a rail that runs constantly as free. Divided to
microseconds at the report, so the line's units stay uniform.

The analyzer reads them as their own family rather than adding them to the
existing `tail_us` request: `rows()` drops a whole family when any requested key
is missing, so asking for these alongside `tail_us` would silently retire the
residue block on every log captured before this commit. It also prints the pair
as a share of the residue they sit inside, which is the number that decides
whether they are worth optimizing at all.

WHAT THIS DOES NOT CLAIM

Nothing about where the residue is. A previous session's handoff asserted
`read_ring_bytes` "copies the ring byte by byte"; it does not — it chunks
through `HostMemory::read_gpa` in at most two iterations. What it does do is
allocate and zero a fresh `Vec` per call and cross into QEMU's address space
per call, twice per packet, with the second read a superset of the first. That
is a hypothesis and this commit exists to test it rather than to act on it.

VERIFIED

- 1879 tests pass, `--test-threads=1`, backend-vulkan,host-window.
- Clippy `-D warnings` clean on the vulkan and metal arms.
- The three baseline boots above also confirm the two layout repairs
  (25051457, 71462a94) are a no-op on macos-13: no guest panic, exactly one
  boot per log, and zero firings of `frag_neutral_texture_substituted`,
  `compute_neutral_sampled_image_unbound` or `used_binding_absent_from_layout`.
  That is the expected result — the kb note measured that population on rails
  14, 15 and 26, not on 13.

NOT VERIFIED

- The instrument's own cost. Two `Instant::now` per ring read and two per
  decode, at tens of thousands a second, is order 1-2 ms/s against a 110-236
  ms/s residue; it has not been A/B'd and the residue figure should be read as
  including it.
- Nothing on the rails that fire the layout repairs.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 16:06:43 +03:00
Anees IqbalandClaude 71462a94c8 🐛 The draw path leaves the same layout hole, on three rails and every boot, and the guard that found it only counted
Pathway: x86 macOS / Linux Vulkan, render path. Companion to 25051457, which
repaired the compute path after a user's host was killed by it.

WHY THIS IS THE SAME BUG

`kb/frag-descriptor-unbound-is-a-real-violation.md` measured this population
already: a fragment module referencing a `set = 0` binding the descriptor set
layout does not contain, 2-3 a boot on macos-14, macos-15 and macos-26, and
fifteen of fifteen answering `Used`. That note named the repair and did not
build it, on the grounds that it "declines no draw and costs no visible guest
work".

That reading is too soft, and 25051457 is why. `engine/exec.rs` builds the
layout from provided resources alone, so an unbound-but-used texture is not an
unwritten descriptor — the binding is absent from the layout entirely. Mesa's
ANV sizes its binding array to `max_binding + 1`, zero-fills every number
nothing declared, and scores each used binding as
`(use_count << 7) / array_size`. The hole divides by zero, so pipeline creation
does not return an error: the host process dies of SIGFPE and takes the VM with
it. On an Intel host every one of those firings is a candidate host kill, on
three rails, on every boot.

WHAT CHANGED

- `draw::frag_unbound_textures_to_neutralize` narrows the guard's existing
  verdict list to the gaps this device can repair: textures, statically used.
  The guard block now yields that list instead of only counting.
- `draw/vulkan.rs` pushes a neutral 1x1 transparent `SampledImageResource` for
  each, at the relocated binding the module actually carries
  (`TEXTURE_BINDING_BASE + index` plus `FRAG_SAMPLED_RESOURCE_BINDING_OFFSET`
  when the fragment sampled band moved), reported on the fail channel as
  `frag_neutral_texture_substituted`.

The shape comes from `reflected_sampled_kind`, asked in the translator's
numbering the way the bind path asks it, so an array or volume sampler gets an
image of its own declared kind — binding a plain 2D view where the shader
samples an array would be a second violation wearing the repair's clothes.
Cube and cube-array have no single-texel neutral this engine builds and are
declined where they are bound too, so those keep the hole and say so by name
(`frag_neutral_texture_shape_unsupported`) rather than being given a shape the
shader did not declare.

Three narrowings, each load-bearing and each covered by the test: textures only
(the sampler class provisions its own default a few lines below, and a storage
buffer has no neutral to invent); `Used` only (`DeclaredUnused` is legal to omit
and must stay omitted or the census cannot separate the populations);
not `Ambiguous` (two variables on one binding is its own defect, and picking one
is a guess).

COST

Nothing on the hot path. The guard already ran per draw and already computed
each gap's `DescriptorUse`; this reuses that verdict rather than adding a second
SPIR-V walk. On a draw that binds what it samples the new vector is empty and
the loop does not execute. Deliberately NOT the compute path's backstop refusal
— that walks the module, which is affordable per dispatch and is not per draw.

VERIFIED

- 1879 tests pass, `--test-threads=1`, backend-vulkan,host-window. One new test
  covers all three narrowings, including the two classes that answer `Used`
  unconditionally from `frag_unbound_static_use` and so are exactly what a
  filter written on the verdict alone would let through.
- Clippy `-D warnings` clean on all three arms (backend-vulkan+host-window,
  the same with an explicit x86_64-unknown-linux-gnu target, and backend-metal
  under --target aarch64-apple-darwin).

NOT VERIFIED

- No live boot, and no boot on the host class that reproduces the crash: this
  dev machine has no Intel GPU. Neither the SIGFPE nor its absence can be
  observed here.
- Not measured on the rails that fire it. macos-14, macos-15 and macos-26 each
  produce 2-3 of these a boot per the kb note, so a driven boot of any of them
  should now show `frag_neutral_texture_substituted` at the same count and the
  desktop unchanged. That reading is owed and not taken.
- Vertex-stage texture gaps are not covered. The scan is fragment-only by an
  older and narrower argument (a vertex `[[buffer(n)]]` may legitimately be a
  stage-in attribute), which is about buffers and does not extend to textures.
  A vertex texture declared, used and unbound would still hole the layout.
- Whether any guest shader depended on the contents of the textures it did not
  bind. The substitute is transparent and 1x1; the fail line is what makes that
  reliance findable.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 15:56:22 +03:00
Anees IqbalandClaude 25051457a3 🐛 A compute kernel that samples a texture the guest never bound left a hole in the layout, and one driver divides by it
Pathway: x86 macOS / Linux Vulkan, compute dispatch. Reported from a user's
host: QEMU killed by SIGFPE (rc=136) on an Intel Iris Xe / Mesa 26.1.5 guest
session, the fault inside vkCreateComputePipelines on the drain thread, under
`ObjectCaches::get_or_create_compute_pipeline`.

WHAT IS WRONG

Vulkan requires the pipeline layout to contain a descriptor for every resource
the module *statically uses*. The descriptor set layout this device builds is
assembled from what the guest bound (`exec_compute.rs`'s `LayoutKey`), so a
texture the kernel samples and the guest left empty is absent from the layout
entirely — not an unwritten slot in it. `kb/frag-descriptor-unbound-is-a-real-
violation.md` established that population on the *draw* path and named the
repair; this is the same defect on the compute path, and it is not merely
undefined.

Mesa's ANV sizes its own binding array to `max_binding + 1`, zero-fills every
number the layout did not declare, and then scores each used binding as
`(use_count << 7) / binding->array_size` when it picks binding-table slots
(`anv_nir_apply_pipeline_layout.c`, `anv_CreateDescriptorSetLayout`). A hole
under a used binding divides by zero. `vkCreateComputePipelines` therefore does
not return an error — the host process dies inside it and takes the VM with it.
There is no validation layer in this tree and no status to inspect, so nothing
downstream could have reported this.

WHAT CHANGED

- `spirv_bind::sampled_image_bindings` — the texture analogue of the sampler
  walk that already existed. Class from the SPIR-V type, never the binding
  number: `OpTypeImage` with `Sampled` 1 and `Dim` not `SubpassData`.
- `spirv_bind::declared_binding_numbers` — the class-blind candidate sweep the
  backstop asks `descriptor_static_use` about.
- `runtime::compute_exec` provisions a neutral 1x1 transparent texture for every
  sampled-image binding the module statically uses and the guest left empty,
  mirroring the neutral-sampler pass a few lines below it. Reported on the fail
  channel as `compute_neutral_sampled_image_unbound`, because it is a repair
  that succeeded and the reliance has to stay measurable.
- `exec_compute::used_binding_absent_from_layout` refuses the dispatch if any
  used binding is still absent when the layout is built, as
  `ComputeExecutionDecline::UsedBindingAbsentFromLayout`. Expected to stay at
  zero; it is the backstop for a class the repair above does not cover, and
  losing one dispatch is the only outcome left that keeps the VM alive.

Only `Used` is provisioned. `DeclaredUnused` is legal to omit and must stay
omitted or the census that separated the two populations cannot tell them apart;
`Ambiguous` is two variables on one binding, which is its own defect and is not
repaired by picking one. `descriptor_static_use` answers `NotDeclared` for
anything that is not a `UniformConstant` descriptor, so a storage buffer — whose
root that walk cannot resolve — is never refused on a guess.

VERIFIED

- 1878 tests pass, `--test-threads=1`, backend-vulkan,host-window. Three new:
  the two walks partition set 0; the class-blind sweep vs the use test; the
  neutral pass fills the used binding and not the declared-unused one; the
  backstop refuses by number and admits the legal layout.
- Probed: stubbing the `is_violation` filter out of the neutral pass fails the
  test, so it discriminates rather than merely running.
- Clippy `-D warnings` clean on all three arms (backend-vulkan+host-window,
  the same with an explicit x86_64-unknown-linux-gnu target, and
  backend-metal under --target aarch64-apple-darwin). The three new items are
  `backend-vulkan`-gated; the Metal arm found that and it is now honest.
- The reflection was checked against the actual reporting shader by an
  independent parser, not against itself: it declares set 0 bindings 1-10
  (storage buffers), 32 (storage image), 33-38 (sampled images) and 160
  (sampler), and every one of them is statically used. The reporting host's own
  log shows the guest wrote 3 of the 6 sampled images, and the fault operand
  resolves to `binding[33].array_size` — the first used binding with no layout
  entry, which is exactly this defect.

NOT VERIFIED

- No live boot. This is a Linux/Vulkan host-side layout fix; the machine that
  reproduces it is an Intel iGPU and this dev host has no Intel GPU, so the
  SIGFPE itself cannot be re-triggered here. The repair is verified by test and
  by the driver's own published source, not by a boot.
- Whether the guest's kernel depended on the contents of the textures it did not
  bind. The neutral texture is transparent and 1x1; a kernel that queries its
  size gets 1x1. The fail line is what makes that reliance findable later.
- The draw path carries the same defect (2-3 firings a boot on rails 14, 15 and
  26 per the kb note) and is NOT fixed here.
- No throughput measurement. The neutral images are 4 bytes each and only
  materialize when the guest under-binds.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 15:48:26 +03:00
Anees Iqbal 4d4e79b2b9 📝 Spotlight does not crash on the macos-12 rail, over 32 driven rounds on two boots, and the results list renders correctly
Investigating a report of Spotlight crashing on macOS Monterey. Two driven boots
of `macos-12` (macOS 12.7.6, 21H1320), x86 macOS / Linux Vulkan, at
`ccefe3b0` — 19 rounds and 13 rounds of open, type a query, walk the results
list, close.

**It does not reproduce.**

- Spotlight's pid is **390 before and 390 after** the second boot's 13 rounds, so
  it did not die and relaunch — the check `pgrep` alone cannot make.
- No guest kernel panic in either boot's stdout, which is the verdict that
  outranks a probe's own exit.
- No new crash report in `~/Library/Logs/DiagnosticReports` or
  `/Library/Logs/DiagnosticReports`. The newest entries are `bluetoothd` and
  analytics files that predate the boot.
- Dock alive at the end of both runs.
- The typed state photographs correctly: the search field holds "safari", the
  results list is populated and categorised, the top hit is highlighted and the
  preview pane is drawn. The vibrancy surface behind it composites correctly.
- The device's own window over the rounds holds six `sampled_resident_reclaimed`,
  five `translation_deferred`, and four `type4_backing_fail` — each of the four
  paired with its own `type4_backing_recovered` 1-10 ms later, which is the
  guest finishing a mapping the device asked about early. No loss.

What that negative does *not* cover, stated so nobody reads it as broader than it
is: one rail, one snapshot, one input pattern, keyboard-only, no results opened
by Return, and nothing typed that would reach a network or index-rebuild path.
A crash that needs a particular query, a cold Spotlight index, or a mouse-driven
result would not have been found here.

Also fixes the probe flaw that boot exposed: `cmd+space` *toggles*, so a round
starting with the window already open closed it and typed into whatever had
focus — one round in three photographed a bare desktop. It now escapes first, so
every round starts from the same state whatever the last one left behind.
2026-08-11 15:23:41 +03:00
Anees Iqbal 65a61ce078 ✨ A Spotlight probe, driven from the host, because a crash inside the guest is invisible to every counter this device has
A report of Spotlight crashing on macOS Monterey needed a way to reproduce it,
and Spotlight is worth a probe of its own regardless: its window is the guest's
heaviest *vibrancy* surface — a live blur of what is behind it, re-laid-out on
every keystroke as results arrive, over a desktop that keeps compositing
underneath. Nothing else a rail reaches by default combines a live backdrop blur
with a window whose geometry changes several times a second, and three rails here
care: the sampled-image resolve, the geometry-keyed render-target registry, and
the writeback.

Host-side over QMP — `cmd+space`, typed ASCII, arrow keys — so it needs no guest
tooling and no Apple Events consent, which matters when the thing being measured
is a crash: a probe that needs ssh cannot survive its own subject.

Two things it does that a first version got wrong and are the reusable part:

- It records Spotlight's **pid before and after**. A relaunched Spotlight has the
  same name and a different pid, so `pgrep` alone reports a crash-and-restart as
  a healthy process.
- It photographs the *typed* state, not only the end. A screenshot taken after
  the last `esc` shows an empty search field, and an empty search field is what a
  closed Spotlight and a Spotlight that never received a keystroke both look
  like — the second being a probe bug that reads as a clean result.

First run on macos-12 (macOS 12.7.6), 19 open/type/close rounds, driven:
**no crash.** Spotlight alive, Dock alive, no guest kernel panic, no new crash
report in either DiagnosticReports directory, and the device's own window holds
nothing but six `sampled_resident_reclaimed`, five `translation_deferred` and
four `type4_backing_fail` that each carry their matching
`type4_backing_recovered` 1-10 ms later. The report does not reproduce on this
rail from this input.

That first run's typed state was not photographed, which is why the probe now
does — the negative above is only as strong as the evidence that the keystrokes
landed.
2026-08-11 15:19:52 +03:00
Anees Iqbal ccefe3b0ea 📝 Six sustained-animation boots at HEAD hold both compositing classes and take the slab churn from ~270 events a window to zero
x86 macOS / Linux Vulkan, macos-13, `sustained-animation-probe`, six driven
boots, host quiesced, against this session's six-boot baseline at `9b718739`
(`/tmp/cs/head`). Reported per class, because the probe's boots are bimodal and a
median over the mixture moves with how many of each were drawn.

```
                 fast class (Hz)            latched class (Hz)
HEAD          113.00 114.20 112.95        59.55 59.70 59.10
9b718739      110.85 113.20 110.90        58.60 58.65 58.95

draw_us/draw   12.57 12.82 13.09          14.80 15.43 15.65
9b718739       12.82 13.00 13.27          14.73 15.48 16.14

slab_block events per 25 s window
HEAD           0  0  1                     0  0  1
9b718739     255 306 259                 394 218 229
```

Every HEAD boot of the fast class is at or above every baseline boot of it, and
the latched class is up by about a Hz. Per-draw cost is at or below baseline in
both. Neither is a large effect and neither is claimed as one — what this boot
set is for is that nothing regressed, and it did not.

The slab churn is the change that reaches this probe: **0-1 block events a
window against 218-394**. This probe never saturates the drain worker either
(duty 0.34-0.36 latched, 0.62-0.63 fast), so it fires the idle pass constantly
and paid a 64 MiB `vkAllocateMemory` for it about ten times a second.

The 3/3 bimodal split is unchanged and is still the largest inconsistency on this
rail — `kb/the-guest-picks-a-59hz-mode-and-it-is-not-the-vblank.md`. Nothing this
session landed was aimed at it.

Also lands the instrument for what is next. `drain_us` is 933 ms a second against
`draw_us` 604 on a driven `blur=40` boot and 678 against 425 on this probe — **a
third of the drain worker's wall clock is inside `drain_us` and inside no
`DrainPhase`**, on the one thread every guest packet serializes through, and no
census names it. `drain_duty` now carries `tail_us` (the deferred-batch submit)
and `boundary_us` (the present boundary), the two spans after `Device::drain`
returns, so the residue left inside it is a subtraction rather than a guess.
`kb/harness/analyze.py` prints all three.

Not verified: what the residue is. That is the next boot.
2026-08-11 15:10:01 +03:00
Anees Iqbal 54f5de0d85 📝 The repeated-row CLEAR seed is 58% cheaper on every boot, at the same byte count, and buys no frames on the dial that measured it
x86 macOS / Linux Vulkan, macos-13, `gpu-load-probe` at `layers=12&boxes=6&blur=40`,
four interleaved driven boots of two binaries, 40 s windows, host quiesced.

```
                        solid1   abl1    solid2   abl2
clear_seed_gva_us        50296  119183    51003  120524
clear_seed_gva_kb       175598  170882   181177  174749
prep_seed_us/chain        3.71    8.47     3.70    8.55
draw_us/draw             41.13   40.92    39.08   41.00
present_hz (median)       14.5    14.8     14.9    14.8
duty (median)             0.91    0.91     0.91    0.91
```

The phase is **−56 %** and the two arms are disjoint on both readings, at byte
counts that overlap — so the saving is the conversion count and not less work.
~70 ms of host CPU returned per second on this load.

`draw_us` does not move by as much as the phase does, and frames do not move at
all. That is what `REIMS_VGPU_CLEAR_SEED=off` already predicted: ablating the
*whole* seed — 118 ms/s — moved `draw_us` by ~3.1 µs of 41 and left
`present_hz` and `duty` where they were, on both arms. **The guest paces this
workload**, at duty 0.91, and what a CPU saving buys here is host CPU rather than
guest frames.

Worth stating plainly because it retires a hope this session started with: the
`blur=40` dial runs the drain worker at the highest duty this repository has
measured and it is *still* not the limiter. No workload found so far on this rail
converts device CPU into frames.
2026-08-11 14:58:56 +03:00
Anees Iqbal 6bc18123d8 ⚡ The CLEAR seed converted the same row a thousand times, because the writer it used takes an image and every row of that image was identical
x86 macOS / Linux Vulkan, `runtime/draw`.

`clear_seed_gva_us` = **118 and 124 ms a second for 169 and 180 MB** on two
driven macos-13 boots of the load probe's `blur=40` dial. That is 0.7 GB/s to
land a solid colour, which is an order of magnitude under what the copy alone
costs, and `clear_seed_t11` is **zero** on this workload — every seed takes the
GVA branch, so the type-11 image builder shipped in the previous commit is on a
path this load never reaches.

The reason is the shape of the writer, not the copy. `write_gva_rgba8_within`
takes a full RGBA image and converts each row into the destination's native
format before copying it — correct for a rendered frame, and for a solid clear it
converts a thousand byte-identical rows into a thousand byte-identical results.

So the row source becomes a type. `SourceRows::Distinct` is one source row per
destination row, `SourceRows::Repeated` is one source row for all of them, and
`write_gva_rows_within` converts once when the rows repeat. `write_gva_solid8`
is the entry point the seed now takes: it builds a single tight row and never
materialises an image at all. `write_gva_rgba8_within` is a wrapper passing
`Distinct`, so there is one body and the two forms cannot drift.

The full-surface RGBA buffer is now built only for `i == 0`, whose copy becomes
this chain's `color0_rgba`. Neither writer takes one any more.

Tests: 1874 + 82 pass, 0 failed. New test
`a_solid_gva_landing_matches_the_full_image_landing_it_replaced` lands both
writers into two identical synthetic guests and compares the pages byte for
byte, over a destination whose row stride is wider than its tight row. Probed:
changing `SourceRows::Repeated`'s stride from 0 to 1 makes it fail, so it does
exercise the stride and not just the conversion. Clippy clean at `-D warnings`
on all three arms.

Not verified: the size of the saving on a boot. The A/B is the next one, against
`REIMS_VGPU_CLEAR_SEED=off`, whose four boots already price the whole rail at
~3.1 µs of a 41 µs chain — so this change can be worth at most that, and the
ablation bought **no frames** on that dial, both arms holding duty 0.91 and
14.2-15.2 Hz. The guest paces this workload; what a saving here buys is host CPU,
not frames.
2026-08-11 14:50:10 +03:00
Anees Iqbal 62acd7877c ✨ The CLEAR seed gets a byte count, a timer per branch and an ablation switch, because rebuilding its images cheaper moved nothing
x86 macOS / Linux Vulkan, `runtime/draw/vulkan` + `env`.

Four driven macos-13 boots of the `blur=40` dial, interleaved, two binaries:
`prep_seed_us` reads **8.69 / 8.70 µs** a chain with the one-pass image builders
and **8.62 / 8.65** without them. Nothing. The images were not the cost, so the
cost is one of the two writes the loop makes into the guest's pages, and nothing
here said which one it takes or how many bytes it lands — `swap_rb_kb`, which the
estimate that led there leaned on, belongs to the engine's swizzling writer and
not to this loop at all.

So the loop now reports itself: `clear_seed_gva` / `clear_seed_t11` with their
`_kb` and a `StoreCostSpan` each. Two branches, two counters, no inference.

And `REIMS_VGPU_CLEAR_SEED=off` prices the whole rail by removing it. That arm is
an **ablation and not a shipping arm** — the seed is what the guest sees outside
the region a draw covers, so switching it off can lose pixels and the failure
mode is content rather than a counter. The A/B harness photographs both arms,
which is the only way that damage is visible; the switch exists because no
elision of a 21 %-of-chain rail can be designed against a cost nobody has priced.

Tests: 1873 + 82 pass, 0 failed. Clippy clean at `-D warnings` on all three arms.
Not verified: anything the counters say, which is the next boot.
2026-08-11 14:35:28 +03:00
Anees Iqbal bce3a6c5c5 ⚡ A solid CLEAR seed is one repeated word, and building it cost two allocations and four passes over the surface
x86 macOS / Linux Vulkan, `runtime/draw/vulkan` + `contract/pixel_format`.

The CLEAR-seed loop at the head of a draw chain writes a solid colour into the
guest's pages for every colour attachment a record owns. It built that image by
allocating a zeroed RGBA buffer, filling it a texel at a time, allocating a
second zeroed buffer, and copying the first into it with red and blue exchanged
— four passes over the whole surface and two allocations, for a result that is
`w * h` copies of one 32-bit word.

The new `prep_seed_us` bar says what that cost: **8.62 and 8.66 µs a chain on
two driven macos-13 boots of the load probe's `blur=40` dial — 21 % of a 41 µs
chain, second only to the engine's 12.06** and larger than the sampled resolve,
the Store and the binds. The two boots agree to a hundredth of a microsecond, so
this is not a sampling artifact.

Three changes, none of which alters a byte that reaches the guest:

- `solid_image8` fills by doubling what it has already written, so the buffer is
  built by growing `memcpy`s and no byte is written twice. `vec![0u8; n]`
  followed by a fill writes every byte twice.
- `solid_bgra8` builds the type-11 seed from the *swapped pixel* instead of by
  exchanging the channels of a finished RGBA image. The exchange belongs to the
  word; doing it per texel cost an allocation and two passes.
- The RGBA copy is built only when something reads it again — `i == 0`, whose
  buffer becomes this chain's `color0_rgba`, or a GVA target, whose writer wants
  RGBA. A second or third attachment's seed now exists only in its destination's
  order.

Tests: 1873 + 82 pass, 0 failed. Two new equivalence tests in
`contract::pixel_format::solid_fill_tests`: the doubling fill against a texel
walk at ten geometries including the zero-texel and non-power-of-two tails, and
`solid_bgra8` against `solid_rgba8` with red and blue exchanged at four clear
colours — the second fails if the exchange moves the wrong pair, which a
length-only check would not catch. Clippy clean at `-D warnings` on all three
arms.

Not verified: the size of the saving. The A/B is the same dial against the
previous pin and is the next boot. `swap_rb_kb` is **not** this path's counter —
it belongs to the engine's swizzling writer — so the seed's byte volume has
never been measured and the estimate that led here was of the wrong rail.
2026-08-11 14:24:02 +03:00
Anees Iqbal 274a9c9164 ✨ The chain's prep span is split, because it is 0.16 us a chain on one load and 9.27 on the one that saturates the drain worker
x86 macOS / Linux Vulkan, `runtime/chain_phase` + `runtime/draw/vulkan`.

`prep_us` is the span from `draw_vk`'s entry to the metal2vulkan call. On the
sustained-animation load it is 0.16 µs a chain and nobody has ever had reason to
look at it. On the load probe's new `blur=40` dial — which runs the drain worker
at **duty 0.90**, the highest this repository has measured, against the
sustained probe's 0.83 — it is **9.27 µs, 22.8 % of the chain and second only to
the engine**.

A factor of 58 between two workloads is one of the two things the span holds
doing work on one of them and not the other, and one bar cannot choose:

- `prep_seed_us` — the CLEAR-seed Store loop: a full-surface solid RGBA buffer
  per colour attachment, a channel swap for a type-11 target, and the write of
  it into the guest's pages. The blur leg runs 2 635 `draw_partial_clear` and
  140 MB/s through `swap_rb` a second; the compositing leg runs neither.
- `prep_pages_us` — `sync_store_allowed_pages`, the page-table walk that bounds
  the synchronous GVA Store before any GPU work.

Both are appended after the existing ordinals, so every phase keeps its value
and `PHASES` stays derived from `Phase::LAST` — the same arrangement the five
`Pipeline*` sub-phases use and for the same reason. They are carved out of
`prep_us`, so the three together are what `prep_us` used to be alone, and the
whole line still sums to `drain_duty`'s `draw_us`.

`kb/harness/analyze.py` prints them. A log written before this commit has
neither field, so that reader drops the whole `chain_phase` family for it rather
than half-reading it — old captures must be read with the old analyzer.

Tests: 1871 + 82 pass, 0 failed. Clippy clean at `-D warnings` on all three arms.
Not verified: the split's own reading, which needs a driven boot of the blur
dial. Nothing about behaviour changes here — two `enter` calls and two fields.
2026-08-11 14:11:04 +03:00
Anees Iqbal 92ce92f1b1 📝 The slab retention removes every block allocation the WebGL dial was making, and costs the guest nothing to keep them
x86 macOS / Linux Vulkan, macos-13, `gpu-load-probe` at `layers=8&boxes=6&verts=60000`,
four interleaved driven boots of one binary (on/off/on/off), 40 s windows, host
quiesced. `REIMS_VGPU_SLAB_RETAIN`:

```
                        on1     off1     on2     off2
slab_block events         0      396       0      419
  of which ev=alloc       0      198       0      210
vk_alloc_sites delta      -    128:8192MiB:208ms   -   128:8192MiB:187ms
draw_us/draw (median)  62.6     77.5    59.5     74.1
present_hz (median)     5.8      5.8     5.8      5.8
duty (median)          0.12     0.13    0.13     0.12
```

The churn is gone rather than reduced: **zero** block events in a 40 s window
against ~400, which is 128 fewer `vkAllocateMemory` calls, 8 GiB fewer bytes
asked for and ~200 ms of driver time returned per window. Per-draw cost is
~20 % lower and the two arms are disjoint at 2v2.

`present_hz` does not move, and is not expected to: this dial's guest burns
~1.1 cores across its vCPUs to produce six frames a second while the drain
worker sits at duty 0.12, so nothing this device gives back becomes a frame
here. It is the arm that measures the churn, not the arm that measures frames.

Not verified: the effect on a saturating load. The sustained-animation probe
allocates ~4.6 blocks a second against this dial's ~8, so the same change is
worth roughly half as much there and it has not been booted.

Also lands the reading that reframes the WebGL collapse, and the instrument for
the next step. `scripts/qemu-thread-census` over these four boots puts the guest
at ~112 % of one core spread across eight vCPUs with the drain worker at ~0 and
`qemu-main` at 11 % — so the collapse is the guest computing, not this device
being slow and not a vCPU spinning on a register. Whether that computation is
Safari on the GPU or a software rasteriser the guest fell back to is the next
question, and the page now answers it directly: the WebGL context reports its
vendor, renderer, unmasked renderer and version by fetching a path the host's
server has no file for, so the answer lands in the server log. There is no other
route — the guest has no developer tools, and no counter here can see a decision
the guest made before reaching this device.
2026-08-11 14:04:46 +03:00
Anees Iqbal e33c755ed4 ⚡ The idle drain handed back the image-slab block the next frame re-allocated, on every workload that leaves a gap between frames
x86 macOS / Linux Vulkan, `backend/vulkan/engine/pools`.

The idle drain fires every `IDLE_DRAIN_INTERVAL_MS` (100 ms) whenever the poll
heartbeat ticks — which is *most passes* on any workload that does not saturate
the drain worker, because the heartbeat ticks whether or not the guest is
publishing. Every fired pass trimmed the image slab's empty blocks to zero,
overriding the hot release path's own `SLAB_KEEP_EMPTY` (2) churn budget between
two frames of a live animation.

The HOST_VISIBLE buffer pools were already protected from exactly this by
`SETTLED_PASSES_FOR_BUFFER_TRIM`, and their own comment states the reason: "a
live workload crosses a block boundary and back several times a minute and
re-crossing costs a whole block allocation". The DEVICE_LOCAL image slab was
trimmed from the caller, outside that gate, and so was not.

Measured on a driven macos-13 boot of the load probe's WebGL dial: **257 block
allocations against 162 idle trims of a 64 MiB block in a 25 s window**,
alternating one for one about eight times a second, where the compositing load
that saturates the drain worker read 39 in the same window. `vk_alloc_sites`
prices a `slab_block` allocation at ~1.2 ms on this host (352-288 allocs and
367-289 ms across two censuses 5.7 s apart), plus the `vkFreeMemory` that is not
timed. The sustained-animation probe churns too — 186 allocations and 155 trims
over one boot's log, and 284 on the boot of the same binary that latched 59 Hz.

The trim now runs from inside `trim_recycle_pools`, under the same settled state
as the buffer pools, through `idle_slab_trim_keep` — one policy, one call site,
so the two cannot drift apart again. `REIMS_VGPU_SLAB_RETAIN=off` restores the
old behaviour for the A/B; it narrows in the sense `env`'s module doc requires,
retaining strictly less memory and reaching no allocation the retaining arm
would not also reach.

Tests: 1871 + 82 pass, 0 failed (3 + 2 + 1 ignored: the wire fixtures, which are
gitignored on this checkout). New test
`idle_slab_trim_tests::an_unsettled_idle_pass_does_not_trim_the_image_slab`
fails without the gate — it would read `Some(0)` for both arms. Clippy clean at
`-D warnings` on all three arms including the cross-compiled Metal one.

Not verified: the frame-rate effect of the change. The A/B needs two driven
boots and the probe it was found with had to be fixed first (below). The `off`
arm of the switch is not reachable from the test suite, which shares one
`OnceLock` across every test in the binary.

Also: the load probe now jiggles the pointer between two corner pixels every
20 s. The guest's display sleeps, and a probe that only animates does not stop
it — a 145 s window read `display_vbl delivered=1607` frozen across two
censuses, every QEMU thread under 20 % of one core, and the page's leg
boundaries arriving exactly on schedule. A sleeping display reads as a device
that stopped.
2026-08-11 13:54:37 +03:00
Anees Iqbal a37c4f6cdc ✨ A per-thread CPU census of QEMU, because every counter this device emits measures this device
A driven boot of the WebGL dial produces six frames a second with the drain
worker's duty at 0.12. The fail log can say the device was idle seven eighths of
the time and cannot say who held the other seven eighths — a computing guest, a
vCPU spinning on a device register, and everyone asleep waiting on a round trip
all read identically there, and only one of the three is this device's bug.

QEMU names its threads, so a `/proc/<pid>/task` census separates them: a hot
`CPU n/KVM` is the guest computing, a hot `qemu-main` with a cold drain is a
guest blocked in a register write the shim handles inline, and four cold threads
against a full wall clock is a latency problem rather than a throughput one.

Costs two `/proc` reads a second. Written as its own script rather than inside a
probe because it works for any workload; `gpu-load-probe` runs it for the length
of its window.

Verified: parses and reports on a live process on the host (the field-14/15 read
counts back from the end of the line, so a thread whose name contains a space
does not shift it). Not yet run against a boot.
2026-08-11 13:46:15 +03:00
Anees Iqbal 49af089720 ✨ The load probe can raise draws, fragments and compositor blur, and walk a list of dial sets in one boot
The three dials this page had all raise *bytes*: composited surfaces, a vertex
upload, a texture upload. What a paravirtualized GPU costs is per draw — decode,
bind resolution, descriptor build, recording — so none of them could ask the
question a real 3D application asks, and the one that came closest (`verts`)
collapses the guest into its own JavaScript engine before it reaches this
device.

Three more dials, each landing somewhere the existing three do not:

- `gldraws=N` splits the WebGL frame into N `drawArrays` calls with a uniform
  write between them, so the frame's *command stream* grows while its bytes do
  not. This is the axis a paravirt device is actually priced on.
- `fragcost=K` puts K loop iterations in the fragment shader. It costs the guest
  nothing at all, so it moves ring backpressure and nothing else — which is how
  a reading says whether it was bounded by this device's CPU or by the GPU
  behind it.
- `blur=R` puts an R-pixel `backdrop-filter` on every box over a static
  patterned backdrop. The window server pays it, on the GPU, with no JavaScript
  per frame.

And `?scan=a=1,b=2;c=3&legsecs=S` walks a list of dial sets, one document each,
S seconds apart. A boot costs minutes and a leg costs seconds, so a question
about which dial moves which rail is answered by one boot instead of one boot
per dial set. It navigates rather than opening tabs or iframes, so exactly one
document is ever live; each boundary is announced by fetching a path the host's
server has no file for, and the probe cuts the fail log by byte offset when that
404 lands — which needs no mapping between the host's clock and the device's.

Verified: the page's script dry-runs under a DOM shim on the host for both a
flat dial set and both documents of a scan (the list-carrying one hands over to
leg 0, a leg document arms its own boundary timer). Not yet run against a guest;
that is the next boot.
2026-08-11 13:37:53 +03:00
Anees Iqbal 9b71873933 📝 HEAD is 41% cheaper a draw than this session's baseline on every boot, and reaches 110-113 Hz on the three of six where the guest does not latch 60
crates/reims-vgpu, x86/Vulkan. No code change; six driven macos-13
sustained-animation boots at `bab39deb` (`/tmp/cs/head`) against the session's
own three-boot baseline at `69273d22` (`/tmp/cs/base69`). No guest kernel panic
on any of the six.

Per draw, pooled, disjoint on every boot of both sets:

                 HEAD              base69
  draw_us       14.00 (12.82-16.14)  23.85 (23.62-24.16)   -41 %
  engine_us      6.48 (5.79-7.60)    10.53 (10.23-10.58)   -38 %
  store_us       1.16 (0.98-1.34)     6.72 (6.70-6.87)     -83 %
  seed_us        0.43 (0.29-0.75)     1.87 (1.74-2.29)     -77 %
  duty           0.49 (0.33-0.64)     0.81 (0.81-0.82)
  flushes/25s     781 (273-1464)     21166 (21090-21300)

The shader front index of `13f7462f` is confirmed by its own instruments:
`pl_shader_us` **2 981 us/s against 63 062** — 21x — and `shader_hash_words`
**0**, against 60 108 `shader_hits` and 0 misses in the same window. It is the
whole of the `engine_us` fall from 7.71 (lazy writeback alone) to 5.79.

**Frames are bimodal and the mode is the guest's, not this device's.**

  h1 110.8 Hz  267.4 draws/frame   28 844 draws/s
  h5 113.2     265.4               29 963
  h6 110.9     267.2               28 641
  h2  58.6     257.1               15 068
  h3  58.7     257.6               15 167
  h4  59.0     257.4               15 083

Three boots reach 110-113 Hz against the baseline's 77.2-77.9. Three latch 59
Hz — and that is not this change: the eager arm produced the same ~257
draws-per-frame band at 59.6-60.2 Hz on four of its six boots in `/tmp/cs/key`,
and `drain::claim_display_vbl`'s own doc already describes it as "the
boot-to-boot 60-vs-120 split the user reports". The device is 41 % cheaper a
draw on the latched boots too; the guest simply asks for half as much work.

So the peak moved 78 -> 111 Hz and the *floor* did not move at all, which makes
the vblank latch the largest remaining inconsistency in this device and the next
thing to measure. `display_vbl` on the two classes differs in the direction that
suggests where to look: the latched boots report a higher `not_enabled` and a
lower `delivered` than the fast ones, but those totals are latched at a
power-of-two report point rather than summed, so the series and not the last
line is what has to be read.

Not verified: `shader_digest_hits` itself, which `f7bf9d9b` only added to the
census line after this chain's binary was pinned. `shader_hash_words=0` is the
stronger reading anyway — no words walked at all.
2026-08-11 13:22:14 +03:00
Anees Iqbal f7bf9d9b0d 🐛 The shader front index's own counter was declared and never printed, so the boot that proved it could not have reported its hit rate
crates/reims-vgpu, `runtime::drain::census`. One field added to the
`engine_delta` line and one argument beside it.

`13f7462f` added `shader_digest_hits` and its doc says to read it as a fraction
of `shader_hits`, because a boot where it sits well below is a draw path handing
the walking form an allocation it does not hold — a correctness-neutral
regression nothing else reports. The `engine_counters!` macro declared the
field and `engine_delta` enumerates what it prints by hand, so the counter
existed and no boot could see it.

Caught by the boot it was written for. A driven macos-13 boot at HEAD reads
`pl_shader_us` **2 981 us/s against 63 062** — a 21x fall — and
`shader_hash_words` **0**, so the index is plainly working; but the ratio the
doc tells the next reader to check was absent from the line they would check it
on, and "the counter reads zero" and "the counter is not printed" look identical
in a grep.

This is the failure `runtime::census`'s own rule about always-on censuses exists
to prevent, arriving through the one seam the macro does not cover: declaring a
counter and emitting it are two edits, and only the first is enforced.

Verified: 1952 tests pass, 0 failed. Clippy `-D warnings` clean on the arm the
line compiles on.
2026-08-11 13:12:55 +03:00
Anees Iqbal bab39debc4 ⚡ The lazy type-11 writeback ships on, because the macos-26 panic it had to be cleared of is the one that rail already panics at without it
crates/reims-vgpu, x86/Vulkan. `REIMS_VGPU_LAZY_WRITEBACK` becomes a refusal:
unset is the lazy rail and only an explicit `off` narrows back to copying at
the Store.

**The macos-26 question, answered.** Six interleaved pairs on that rail,
`/tmp/cs/m26band`:

  on   ok ok PANIC ok PANIC ok      2/6
  off  ok ok ok    ok ok    ok      0/6

Two of six is not a rate this device introduced. Both panics are
`"hitting assertion" @AppleParavirtPageTable.cpp:201`, in
`StorageNode::clearEntry` under `AppleParavirtMemoryMap::releaseFromGPUPageTable`
on `IOAccelSharedUserClient2::stop` — the guest's own GPU page-table teardown,
which is the panic `kb/macos-26-guest-panic-orphaned-gputask.md` characterises
as **pre-existing at a pooled ~39 % over 28 boots, A/B'd against two builds, and
reproducing on boots this device is not driving at all**. 2/6 is that rate; 0/6
in the off arm is its 9 % tail, and six boots cannot separate the two at a 39 %
base.

That is not the same shape as the parked-plan rail's four-for-four on macos-13,
and the reason is structural rather than statistical: this rail holds nothing
resolved across a window, so the page-recycling hazard those panics were has no
surface here. Recorded as not-worsened, not as cleared — the macos-26 panic
stays the largest open correctness problem on that rail and the switch is how a
future session takes this rail out of a bisect.

**What ships.** Twelve interleaved driven macos-13 boots (`dff1ab52`): 90 % of
type-11 Stores superseded before anything reads their pages, `store_us` 0.89
against 9.56 us a chain, `draw_us` 14.62 against 26.52, five of six on-arm boots
at 105.8-109.2 Hz against a 77.2-78.6 Hz baseline. Five other guest rails and
both `REIMS_VGPU_GUEST_IMPORT=off` boots clean (`6b585f4f`), the latter at 90.8
and 88.4 Hz — the copying rails gain more from this than the GPU-direct one
does. `wbdebt_reach_overlap` is 0 across every boot of every rail, ~520 000
sampled payments.

The switch reader now treats unset, `on` and `Switch::Unrecognized` alike, so an
operator's typo fails toward the measured default rather than silently selecting
the arm it is 45 % slower on. Only `off` narrows.

Verified: 1952 tests pass, 0 failed. Clippy `-D warnings` clean on all three
arms.

Not verified: the arm64/Metal pathway has no arm site and no boot on this host.
No boot yet carries this default together with the shader-digest index of
`13f7462f` — the confirmation chain is next.
2026-08-11 13:09:12 +03:00
Anees Iqbal 13f7462fc2 ⚡ A repeat shader bind recognises the allocation its words live in instead of walking the module three times to rediscover a digest it already has
crates/reims-vgpu, x86/Vulkan engine caches. Adds
`ObjectCaches::get_or_create_shader_memoized` and the front index behind it.

`get_or_create_shader` keys a module by its contents, so the key costs a pass
over the contents — three of them, in fact: `required_image_capabilities`,
`Digest128::of_u32_words`, and a rebuild on the capability-patch path. The draw
path pays that for two modules on every draw, at ~30 000 draws a second, into a
cache that reports `shader_misses=0` for a whole boot.

Priced on a driven macos-13 sustained-animation boot with the lazy writeback on
(`/tmp/cs/key/on1`, `draw_phase` summed over the boot):

  pl_shader_us   63 062 us/s   the largest single item inside engine_us
  record_us      59 474
  stage_us       33 978
  slot_us        15 671        the GPU, now small
  engine_us     233 708        total

That ranking is new and is why this is worth doing now. With the writeback
eager, `slot_us` was 143-244 ms/s and every CPU saving in the device landed on a
drain worker already waiting for the GPU — which is what
`render_writeback`'s doc records as the reason three separate CPU wins here
"bought microseconds and zero frames". `wait_us` is 0 and `stalls` 0 on the boot
above; the device is CPU-bound again.

The index is `Arc<Vec<u32>>` allocation address → final digest, and the address
is sound as a key **only because the entry holds the `Arc`**: while it does, the
allocation cannot be freed, so nothing else can be given that address. Drop the
`Arc` and it is a use-after-free dressed as a cache hit. `usize` and not
`*const`, or `Caches` stops being `Send`.

Three things it deliberately does not do. It does not skip
`ObjectCaches::shaders` — a hit still asks the negative cache and then the
positive one, so the index does not depend on `ObjectCache` never evicting,
which is a property that cache happens to have and does not promise; a miss
falls through and re-walks. It does not serve the compute path, whose `spirv` is
an owned `Vec` with no stable allocation and whose dispatches are three orders
rarer than draws. And it records the digest of the **patched** module, because
the walk it memoizes ends after the capability patch — `spirv_capability added`
fires 36 times in a 25 s boot, so that path is cold but not never.

Bounded at 4 096 entries by the container's own insert, which is the only way
in. Past the bound it starts over rather than evicting: every entry is equally
cheap to rebuild and there is no recency to evict by, and `shader_digest_reset`
is the boot saying a few hundred distinct modules was the wrong assumption.

`shader_digest_hits` is the new counter, to be read as a fraction of
`shader_hits`: a boot where it sits well below is a draw path handing the
walking form an allocation it does not hold, which is correctness-neutral and
nothing else would report it.

Verified: 1952 tests pass (3 new, on the index's key being the allocation and
not the contents, on its entry keeping the words alive, and on its bound), 0
failed. Clippy `-D warnings` clean on all three arms.

Not verified: no boot has run this. `pl_shader_us` and `shader_digest_hits` are
what the next one has to read.
2026-08-11 12:54:13 +03:00
Anees Iqbal 61289c561a 📝 The writeback rail's own doc designed the deferral and then buried it, so it now points at the built one and names the three of its numbers that turned out wrong
crates/reims-vgpu, `runtime::render_writeback` module doc. No code change.

That doc is the best account in the tree of why this rail costs what it does,
and a reader arriving at it about deferral was being handed four sections of
design, one section of four guest kernel panics, and a premise the built rail
has since falsified. It now opens with a pointer to
`runtime::writeback_debt` and the twelve-boot reading, and marks the three
corrections in place rather than deleting the reasoning that produced them —
which held up, and is why the rail exists.

The three:

- **"Six reads a second against 1 556 writebacks" is the wrong denominator**,
  in exactly the way that doc already warns about for `target_reads`. Every
  `settle_*` counter it quotes counts settles that *waited*.
  `draw::vulkan::load_linear_guest_memoized` alone reaches its settle ~1 700
  times a second and reads the guest's pages on every one. The delivered saving
  is ~3 300 copies a second against ~21 000, a factor of six rather than the
  forty-three that paragraph computes — and still worth 45 % of the per-draw
  cost.
- **The seam it calls hard is not on the path.** Those readers walk raw task
  GVAs but hold a texture reference, and a debt is keyed by a mapping id, so
  `writeback_debt::pay_for_texture` resolves one to the other through the two
  tables `resource_validity::apply` already consults. `settle_guest_writes`'s
  signature never had to change and no `DeviceState` had to be threaded through
  sixteen call sites.
- **The redundancy is within one rail across frames**, not "supersession across
  rails and frames". Both of its censuses measured the spacing of Stores; what
  decides the prize is the spacing of *reads*.

The title loses "at the Store", because that is now a switch.

Verified: `cargo doc` resolves every link, on the arm the new references are
reachable from.
2026-08-11 12:48:55 +03:00
Anees Iqbal 6b585f4fbe 📝 The lazy writeback holds on all five other guest rails and on the copying rails, and it is worth more there than on the host it was measured on
crates/reims-vgpu, x86/Vulkan. No code change; the verification `dff1ab52`
said was owed. The runners live in the gitignored `kb/runners/`, so this
commit is the record.

**The copying rails.** Two boots with `REIMS_VGPU_GUEST_IMPORT=off` and the
lazy rail on, `/tmp/cs/lazyverify/import_off_lazy{1,2}`. The arm took —
`host_pointer_import=disabled_by_env`, `guest_ram_map_no_backend_import`
present — and nothing reported a bound import: `render_flush_gpu_direct` is
**0** and every payment went down `render_flush_leased`, 3 618 and 4 178 of
them, with `render_store_lost` 0.

They present at **90.8 and 88.4 Hz**, against 78 Hz for the capable host with
the rail off. That is the reading worth keeping: a host with no host-pointer
import pays a blocking whole-framebuffer readback per Store, so coalescing 86 %
of them away is worth more there than where the copy is GPU-direct. This rail
helps the memory/import cell of the support matrix that has the least, which is
the opposite of the usual direction.

**The other five rails**, one driven boot each with the rail on:

  rail       present_hz   armed    superseded   surface_flush
  macos-11      87.9      37 556     33 899        3 081
  macos-12      59.9      22 279     21 334          829
  macos-14      59.0      22 293     21 027        1 184
  macos-15      60.3      25 381     23 454        1 854
  macos-26      PANIC        440        361           76

`wbdebt_reach_overlap` is **0** on every one of them and on both import-off
boots, and no boot produced a `render_store_lost` or `wbdebt_pay_lost` line.
Coalescing runs 86-96 %. Every screenshot renders the probe's animation
correctly with no stale region.

**macos-26 panicked, and that is not yet a result.** AGENTS.md puts this rail
at roughly one driven boot in three at baseline and says to band a suspected
rate over at least six boots in both directions before believing it. One boot
is exactly the reading that means nothing. `kb/runners/run_m26band.sh` runs six
interleaved pairs; until it reports, nothing here claims the rail is safe on
macos-26 and nothing claims it is not.

Not verified: the arm64/Metal pathway, which has no arm site at all — the lazy
Store lives in `draw::vulkan` — but also no boot on this host. The unified
-memory cells of the support matrix remain unmeasurable here; this host has one
GPU and it is discrete.
2026-08-11 12:47:39 +03:00
Anees Iqbal dff1ab52bf 📝 The lazy type-11 writeback coalesces 90% of the guest's Stores and five of six driven boots present at 108 Hz against a 78 Hz baseline, so the switch is worth flipping
crates/reims-vgpu, x86/Vulkan. No code change; this records the twelve-boot
reading of `REIMS_VGPU_LAZY_WRITEBACK` on the tree at `5cad170b`, and the
regime finding that came with it.

Six interleaved pairs, driven macos-13 sustained-animation,
`AB_PROBE=anim.sh`, `/tmp/cs/key`. No guest kernel panic on any of the twelve.

  boot   present_hz   draws/frame   draws     surface_flush
  on1      109.0         270.6      739 889     3 371
  on2      109.0         271.4      742 922     2 930
  on3      105.8         274.4      711 351     3 256
  on4       58.9         257.2      379 897     1 529
  on5      108.3         271.6      712 231     3 515
  on6      109.2         271.5      713 439     3 771
  off1      59.6         256.8      383 142    14 659
  off2      59.7         258.0      383 927    14 699
  off3      78.6         340.6      646 707    20 390
  off4      60.2         257.2      387 910    14 867
  off5      77.2         342.1      671 795    21 088
  off6      59.9         257.8      383 926    14 709

Per-draw, pooled over all six of each arm and disjoint at every boot:

  draw_us/draw   on 14.62   off 26.52    -45 %
  store_us       on  0.89   off  9.56    -91 %
  engine_us      on  7.71   off 10.69    -28 %
  seed_us        on  0.69   off  0.33          (the elision costs a little)

The three-boot baseline of the same tree before any of this
(`/tmp/cs/base69`, 69273d22) was 77.2-77.9 Hz at 344 draws/frame with
draw_us 23.85 and store_us 6.72, so the off arm is the baseline and the on
arm is 40 % above the best boot either has ever produced here.

Why it works, from the on-arm counters summed over each boot: `wbdebt_armed`
~35 000 against `wbdebt_superseded` ~31 200 — **90 % of type-11 Stores are
replaced by a later one before anything reads the pages**, which is the whole
rail. `surface_flush` falls from ~21 000 to ~3 300.

Every safety counter is clean on all six: `wbdebt_reach_overlap` **0** against
`_disjoint` 8 100 — at a 1-in-64 sample that is ~520 000 payments where the
naming skipped nothing it owed — `wbdebt_generation_moved` 0, `wbdebt_evicted`
0 or 1, and zero `wbdebt_pay_lost` or `render_store_lost` lines in any log. The
screenshots are indistinguishable between arms.

**The regime is downstream of the device, which contradicts how this harness
has been reading it.** AGENTS.md treats draws-per-frame as a coin the guest
flips per boot, to be classified and never mixed. Here the arm picks it: the
off arm produced only the guest's ~257 and ~341 bands, and the on arm produced
a ~271 band the off arm never reached, five times out of six. macOS's window
server chooses its compositing strategy from observed frame timing, so a device
that finishes sooner is offered a different regime rather than more frames
within one — and on4 is the counter-example that keeps the claim narrow: it
landed in the guest's 257 band, coalesced its Stores exactly as the others did
(1 529 flushes), and presented 58.9 Hz like every off-arm boot of that band.

So the honest claim is: this rail makes the device 45 % cheaper per draw on
every boot, and on five boots of six that bought the guest a better
compositing regime and 40 % more frames. It is not 40 % unconditionally.

Not verified: `REIMS_VGPU_GUEST_IMPORT=off` with the rail on, and the other
five rails. Both are owed before the default flips, and the switch is still
off.
2026-08-11 12:33:51 +03:00
Anees Iqbal 5cad170b57 🐛 The host window keyed a frame on the guest's pages changing, so a Store that publishes pixels without writing a page was discarded as unchanged
crates/reims-vgpu, x86/Vulkan present path. Found by the first driven boot of
the lazy type-11 writeback and fixed there; the eager rail cannot reach it,
because for the eager rail the two stamps always move together.

`device::window_publish::window_frame_key` was `(frame_mapping,
frame_generation, present_epoch)`, and `frame_generation` is the captured
mapping's `content_generation` — which means "the guest's pages hold something
new". A lazy Store leaves the frame in the engine resident and owes the pages a
copy, so it moves no page and that stamp holds still while the pixels change
every frame. The window compared the key, found it equal, and dropped the frame.

Measured, one driven macos-13 sustained-animation pair, `/tmp/cs/named`:

                     lazy on    eager off
  window_publish     fresh 60   fresh 81
                  same_key 314  same_key 131
  present_hz            59.6       79.3
  display_vbl delivered 2112       4096

The presenter is not the only loss. The guest paces itself off the vblank that
follows a present, so half the publishes became half the vblanks and the guest
answered by halving its own submission rate — 381 675 draws against 672 513 in
the same 25 s. A frame dropped here costs guest work, not just a frame.

The repair is a second term rather than moving the first, because the two
stamps now mean different things and both have consumers.
`MappingEntry::content_generation` keeps meaning "the guest's pages changed" —
`draw::vulkan`'s own test asserts a deferred publish must not move it, since the
compute rail re-seeds from guest pages when it does. What the presenter wants is
"these are different pixels", which is `surface_content_epoch`, and
`PresentState::frame_content_epoch` now carries it from `capture_present_frame`
into the key. `note_surface_content_published`'s doc states the split and where
anything else that has to notice a lazy Store belongs.

Test: `device::tests::window_publish_key_moves_for_a_lazy_store_that_wrote_no_
guest_page`, ungated where its `present_epoch` sibling is macOS-only, because
that term is macOS-only and this one is not and the defect was measured on
x86/Vulkan. Verified to fail without the fix — with the epoch term stubbed to
`0` it fails on the `assert_ne!`, and passes with it restored.

Verified: 1949 tests pass, 0 failed. Clippy `-D warnings` clean on all three
arms.

Not verified: whether the fix recovers the frame rate. The A/B is next; the
eager arm's numbers above are unaffected either way, since for it the two
stamps move together and the key changes as it always did.
2026-08-11 12:10:10 +03:00
Anees Iqbal 9ba8b15526 ⚡ The three linear readers pay only what their own texture reference names, because a sampled census caught 303 payments in a row for surfaces the read never touched
crates/reims-vgpu, x86/Vulkan lazy writeback rail
(`REIMS_VGPU_LAZY_WRITEBACK`, still default off).

The census `578dffe2` added, over two driven macos-13 sustained-animation
boots with the rail on:

           reach_disjoint  reach_overlap  reach_unnamed  paid_all  paid_named
  boot 1        173              0              0          20 391      755
  boot 2        130              0              0          14 372      609

At a 1-in-64 sample that is ~2 200 payments measured out of ~35 000, and not
one of them read a page of a surface it paid for. `paid_all` against
`paid_named` says the same thing from the other side: **96 % of every payment
this rail made was for a surface the reader was not reading**, and the first
on-arm boot priced that at `sampled_us` 1.64 → 8.49 us a chain, which is the
whole reason that boot lost frames.

The fix is that the readers were never unnameable. A debt is keyed by mapping
id and this device holds two routes from a texture reference to one — the id
itself where the guest shares a namespace, and `texture_to_mapping` for the
per-task registration. `resource_validity::apply` already resolves a validity
statement through exactly that pair; `writeback_debt::pay_for_texture` asks the
same question of the same two tables. A reference resolving to neither names
no mapping this device holds, so no debt can be about it.

`texture_ref` was already in hand at two of the three sites and one parameter
away at the third (`draw::vulkan::load_linear_guest_memoized`, which its only
caller already had it for).

What the naming cannot see is raw *page* aliasing — a surface's pages re-used
as some other resource's backing with no mapping entry. So `note_unnamed_reach`
stays wired at those sites rather than being retired with the rail it
motivated: it samples the read's own page walk against every owed surface, and
`wbdebt_reach_overlap` above zero is now a payment the naming skipped and
should not have. `wbdebt_texture_owes_nothing` counts the skips.

Two other readings from the same boots, both reassuring: `wbdebt_evicted` and
`wbdebt_generation_moved` are zero, so the 32-entry bound has headroom and the
one leak the payment path admits (an orphaned resident on a remap) never
occurred. `wbdebt_unpaid_buffer_read` is 21 for a whole boot.

Verified: 1948 tests pass, 0 failed. Clippy `-D warnings` clean on all three
arms.

Not verified: no boot has run this version. The A/B is next and it is the only
thing that says whether removing 96 % of the payments turns the rail's halved
`store_us` into frames.
2026-08-11 11:59:17 +03:00
Anees Iqbal 86fea9e056 📝 The test count in the two commits above is 1948 and not 1953, because the arithmetic added the new tests to a total that already contained them
crates/reims-vgpu. No code change.

`b14e0a58` and `578dffe2` both say "1953 tests pass". The tree's actual
figure, summed across every binary of

  cargo test -p reims-vgpu --no-default-features \
    --features backend-vulkan,host-window -- --test-threads=1

is **1948 passed, 0 failed, 6 ignored**. The five ledger tests those commits
added are real and do run — `cargo test ... writeback_debt` names all five —
but they were added a second time on paper, to a `--lib` count that had
already been re-read after they landed.

Recorded rather than rewritten: the claim is wrong by five out of two
thousand and the commits it sits in are otherwise accurate, and a history
rewrite for a count is a worse trade than a line that says so. The six
`ignored` are the wire-oracle fixtures and the three observe doctests, which
this checkout has no Apple fixtures for and never runs.
2026-08-11 11:55:22 +03:00
Anees Iqbal 578dffe2d6 ✨ A sampled census of whether the readers that pay for every owed surface read any of its pages, because the first driven boot of the lazy writeback put its whole cost in one of them
crates/reims-vgpu, x86/Vulkan. Adds `writeback_debt::note_unnamed_reach` and
the shell-trap note the wiring cost.

One driven macos-13 sustained-animation pair on the shipping binary, one arm
each, `/tmp/cs/lazywb/{on1,off1}`:

              on      off
  present_hz  60.0    77.9     (different draws/frame bands, 244 vs 341)
  store_us    3.09    6.75     us/chain   -54 %   the rail working
  seed_us     0.33    2.05     us/chain   -84 %   the LOAD elision working
  sampled_us  8.49    1.64     us/chain  +418 %   the payment
  draw_us    26.95   23.87     us/draw

  surface_flush   447 / s   against 838 in the off arm
  wbdebt_armed    577  superseded 130  paid_all 447

So the rail does what it says — half the writebacks, and both columns it was
aimed at fall — and one column swamps it. Every payment but three came from
`pay_all`, and `settle_linear_memo_read_disjoint=1695` names the caller:
`draw::vulkan::load_linear_guest_memoized`, the linear sampled bind, which
reads a raw task GVA span, cannot name a mapping, and therefore pays every
owed frame about 1 700 times a second.

That also corrects the premise this rail was built on, which is the part
worth keeping. "840 writes consumed six times a second" came from the settle
census — and those counters count settles that **waited**, not settles that
were called. The call population is three orders larger. It is the same trap
`render_writeback`'s doc records for `target_reads`: the wrong denominator,
read as a redundancy.

What the census asks. Paying is only *owed* where the read and the surface
share pages; a compositor sampling a glyph atlas while three windows owe
frames pays three copies it never looks at. `note_unnamed_reach` samples one
call in 64 — the walk is ~2 000 page-table descents and the site runs 1 700
times a second, so measuring every call would measure the instrument — and
splits it three ways: `wbdebt_reach_overlap`, `_disjoint`, `_unnamed`. The
closure it walks with is the reader's own, the same one it hands the
disjointness test, so both ends stay one rule.

`_disjoint` over `_overlap` is the prize a per-debt page-extent hint would
collect. If it is small, this rail's ceiling is the ~23 % of Stores it already
coalesces and the switch stays off.

Also records `kb/zsh-does-not-split-a-bare-variable.md`: `for m in $MINE` does
not word-split under zsh, so a loop written to revert only the files a change
did not touch reverted every one of them. Same class as AGENTS.md's rule about
never reaching for git to undo a probe, and it fails the same quiet way.

Verified: 1953 tests pass, 0 failed. Clippy `-D warnings` clean on all three
arms. Not verified: the census itself has not been read from a boot — two are
running.
2026-08-11 11:54:44 +03:00
Anees Iqbal b14e0a5801 ✨ A type-11 surface Store can owe its frame to the guest's pages instead of writing it, because the device writes 840 whole surfaces a second into pages that six reads a second consume
crates/reims-vgpu, x86/Vulkan render writeback rail. Adds
`runtime::writeback_debt` and `REIMS_VGPU_LAZY_WRITEBACK`, default off.

What the census says. A driven macos-13 sustained-animation boot on this
tree (three boots, /tmp/cs/base69, 77.9 Hz median, 344 draws/frame regime):

  surface_flush              838/s   type-11 Stores, one whole frame each
  gva_flush                  854/s   the GVA twin
  settle_linear_texture_seed   5/s   colour LOAD seeds that read those pages
  settle_scanout_paint         1/s   the host console reading them
  type11_seed_elided/uploaded 802/36 LOAD seeds already served from the resident
  gvaseed_elided/not_quiet    321/5  the GVA twin

So the pages are written ~1 700 times a second and read six, and the reader
that would have consumed them is already being served from the engine
resident 96 % of the time. Every frame written between two reads is replaced
before anything looks at it. `render_writeback`'s own ablation prices the
whole rail at ~30 Hz of frame time.

What this changes. With the switch on, a type-11 surface Store records a
debt — mapping id, geometry, `map_generation`, arm order — and returns.
Nothing resolved is held: paying re-derives the identity from `DeviceState`
and re-walks the page tables at that moment, then calls the ordinary
`store_render_frame`. That is the whole difference from the parked-plan rail
whose four driven boots produced four guest page-table panics; its plan held
host pointers walked at the Store, and this holds four integers.

The pixels stay alive on `ResidentTargetSlot::gpu_only_content`, which the
reclaim already skips and which the eager Store clears at the copy. An armed
debt is exactly the case where the guest's pages do not hold the frame, so
the arm does not clear it. No pin is taken and none can leak.

Who pays. The reader set is the settle set: a host-side reader of guest bytes
this device wrote already has to call `settle_guest_writes` first, so every
site that settles now pays first. `settle_for_mapping` and `settle_unnamed`
spell the two obligations as one call so a new site cannot discharge half of
it. Three amendments, each argued at its site:

- the three completion-stamp sites do not pay (a stamp says a submission
  finished, not that the guest may read a resource);
- `SynchronizeResources` — the one host-to-guest copy the contract names —
  pays everything;
- `draw::read_buffer_bytes_resolved` holds `DeviceState` shared and cannot
  pay, so the gap is counted as `wbdebt_unpaid_buffer_read` rather than
  argued away.

The guest's own write is answered at the payment rather than at the claim:
the arm publishes through `note_surface_content_published`, and
`resource_validity::licence_of` — which already existed and already compares
the two seqs — says at pay time whether the guest superseded the frame. That
keeps one exit path, and the exit path is the only place the target identity
is in hand to hand the resident back to the reclaim.

Bound. `PendingWritebacks` is the only container and holds at most 32 entries;
an arm past that hands the caller the oldest mapping to pay. A driven boot
names about six distinct surfaces.

Verified: 1953 tests pass (5 new, on the ledger's coalescing, its geometry,
its bound and its age order), 0 failed. Clippy `-D warnings` clean on all
three arms. `cargo doc` resolves every link the new module adds.

Not verified: no boot has run with the switch on — that is the next commit,
and until it has, the only claim here is that the eager rail is unchanged
because the switch defaults off. The GVA Store rail is untouched and still
writes its 854 frames a second eagerly.
2026-08-11 11:46:46 +03:00
Anees Iqbal 69273d22b0 📝 Three quarters of the buffer gather's repeat windows have new bytes in them, so the content cache is closed and the 91% recurrence was never the size of the prize
x86 macOS / Linux Vulkan, macos-13, sustained-animation probe, two driven boots,
21 204 real comparisons. Documentation only.

    boot     audit_ok   audit_moved   seed   restart   unchanged share
    1           2 827         8 771      7       436            24.4 %
    2           2 915         6 691      8     1 100            30.3 %

A comparison is a fold of a sampled window against the previous fold of the same
window with no declared write between them. Unlike `gather_witness`'s audit —
whose comparison ran zero times across three consecutive boots, so its
`unsound=0` was never a measurement — this one ran twenty-one thousand times and
`restart` is 4-10 % rather than the dominant column.

## It closes the declaration-invalidated cache

Three quarters of the windows the guest declared nothing about had their bytes
change between two binds. One boot read `quiet_rate=1.000` with `wrote=17` in a
census second whose audit found 379 moved windows against 138 still ones. A
cache invalidated by `writeInvalidates` would have served stale vertex data on
most of its hits, which is a wrong frame that then persists.

That is the cheap route closed. The sound route — the hypervisor dirty bitmap —
remains barred by its own cost: `MAX_TRACKED_WINDOWS` is 256 because
`reims_vgpu_dirty_harvest` walks every armed page on the BQL thread at each
register write, and this rail's ~1 900 windows of ~38 pages would put ~72 000
pages into a walk the whole VM waits on.

## And it retires the number the roadmap was built on

`buffer_gather_working_set` measures 91 % of gathers as repeats of a window
already assembled, and this crate's notes have been reading that as the size of
the prize — "the largest single removable item this device has". It is not: a
repeat whose bytes moved must be re-copied by any cache, sound or not. At ~27 %
of repeats unchanged, the ceiling on a content cache with a perfect oracle is
0.91 x 0.27 = 25 % of this rail's gathers — ~5 100 a second of ~20 800, and
~105 000 of its ~427 000 transfer regions. Against ~288 MiB of device-local
memory held across submissions and a harvest cost over 1 900 windows, that is a
bad trade and it is now written down as one.

`recur` is the population a cache would be *asked* about and never the
population it would serve. All three module docs now say so — the working-set
census, `gather_phase`'s "what to do next", and the freshness split itself.

So three quarters of this rail's traffic is the guest genuinely changing its
vertex and constant data. The way to make that cheaper is to move it more
cheaply, which is what the compute gather does, and not to try not to move it.
The remaining change on that rail is the destination arena, worth ~35 % of one
of a dispatch's four cost columns — which should be weighed against the
writeback rail, whose own ablation is worth ~30 Hz.

Also fully-qualifies the intra-doc links these two new modules add, which do not
resolve from a `//!` doc as bare names.

Tests: unchanged, 1949 passed / 0 failed.

Not verified: macos-13 and one probe. The audit samples one window in 64 by a
finalised hash, so it is a spread of the population rather than all of it; and
it cannot distinguish a window whose addresses were re-resolved from one whose
bytes were rewritten — both are cases a cache may not serve, so both count as
moved, which makes 27 % an upper bound on the unchanged share rather than a
lower one.
2026-08-11 11:17:01 +03:00
Anees Iqbal 474858f14c ✨ A content audit on the buffer gather, because the guest declares 31 buffer writes a second while animating and the only way to know whether that is the whole account is to read the bytes
x86 macOS / Linux Vulkan and the shared runtime. Instrument only.

`buffer_gather_freshness` (0b129a59) put 86-89 % of repeat buffer binds on
windows the guest never declared it wrote — and the same boots showed it
declaring 31 writes a second on one and 520 on the other, against ~4 800
validity records a second naming buffer objects and ~20 800 gathers of animating
geometry. That is not credible as a complete account, and a cache built on an
incomplete one serves a stale frame. This settles it by reading the bytes.

One window in 64 is folded on every bind of it, and its fold compared against
the previous one. Four verdicts on the census line:

    audit_ok        folded under an unbroken run of quiet binds, bytes agreed
    audit_moved     folded under an unbroken run of quiet binds, BYTES MOVED
    audit_seed      first fold of this window
    audit_restart   a declared write sits between the folds, so nothing follows
    audit_kb        what the fold costs, in guest bytes read by the CPU

`audit_moved` is the number that closes the design.

Two shape decisions, both taken from what `gather_witness`'s own audit got
wrong — its comparison ran **zero** times across three consecutive boots and its
`audit_unsound=0` was read as agreement:

- **Sample windows, not binds.** A stride over binds needs a run of consecutive
  quiet ones to reach a comparison, and at an 86 % quiet rate a run of 64 is a
  coincidence this workload does not produce. Every bind of a sampled window
  folds, so the first repeat produces a verdict.
- **Re-seed on the refused bind too.** An audit that only re-seeded on agreement
  loses its baseline at the first declared write and never regains it. Here the
  bind after a refusal compares again, which a test pins.

The fold is `gather_witness::fold_runs`, made `pub(crate)` rather than copied: a
second implementation is a second place for "the bytes did not move" to mean
something slightly different, in the one direction where being wrong serves a
stale frame.

Cost, and it is real: ~66 700 binds a second averaging ~180 KiB, one in 64
folded, is ~190 MB/s of CPU reads against the rail's own ~3.5 GB/s. Reported as
`audit_kb` so it is priced rather than assumed.

The module is now `#[cfg(feature = "backend-vulkan")]` with the rail it
measures; `buffer_write_gen` stays ungated because its producer is the decoder.

## A bug the tests caught, which is the reason to write them

The sampler was a bare FNV-1a over the key, and FNV leaves the low bits of its
result a function of the low bits of its last inputs. An `offset` is
page-aligned — twelve zero low bits — so the hash returned **the same verdict
for every offset in a family**: it sampled either all of a structured slice or
none of it, which is precisely what the sampler's own doc claimed to avoid. It
surfaced as `the_sampler_picks_about_one_window_in_its_stride` failing to
terminate. Fixed with splitmix64's finaliser, which carries the high bits down
into the ones the stride tests.

Tests: 5 new beside the 8 rewritten. The alarm is pinned from both sides — bytes
that move under a quiet run report `audit_moved`, bytes that hold still report
`audit_ok` — plus a declared write refusing the comparison, the baseline
surviving that refusal, and the sampler picking about one key in its stride from
a page-aligned family. Full suite 1949 passed / 0 failed, clippy `-D warnings`
clean on all three arms, feature matrix all arms warnings=0.

Not verified: no boot has read the audit. That is the next step, and
`audit_moved` beside `audit_ok` is the whole of what to read — while
`audit_restart` dominates, the alarm is not running and its zero is not a
measurement.
2026-08-11 11:09:07 +03:00
Anees Iqbal 0b129a59ee 📝 86% of repeat buffer binds land on bytes the guest never declared it wrote, and the rate at which it declares anything at all says that number is not a hit rate
x86 macOS / Linux Vulkan, macos-13, sustained-animation probe, two driven boots.
Documentation only.

    quiet=57123  wrote=9396  first=178  dropped=0  tracked=6968  quiet_rate=0.859
    quiet=38990  wrote=4951  first=352  dropped=0  tracked=5707  quiet_rate=0.887

The wiring check passes: `buffer_write_gen_bump` is non-zero on both boots, so
the `(task, reference)` pair a bind stamps and the `(task, object)` pair a
validity record names do overlap, and `wrote` is a real population rather than a
comparison that never moves. `dropped=0`, so `tracked` is a count.

**The bump rate itself is the finding, and it points the other way.** Across the
same two boots:

             validity_no_surface/s      buffer_write_gen_bump/s
    boot 1          4 847 (median)             520 (median), 99-626
    boot 2          4 151 (median)              31 (median), 29-60

The guest issues ~4 800 validity records a second naming objects this device
holds no mapping for, and on one boot **31 of them a second** carried
`clear_host_valid`. That is the whole of its declared account of writing its own
buffers, against ~20 800 gathers a second of ~1 900 windows whose contents are
animating at 68 frames a second, and two orders of magnitude separate the two
boots.

It is not credible that the guest rewrote its vertex and constant data 31 times
in a second it drew 15 000 frames' worth of moving geometry. The likeliest
reading is that it does not have to: a Metal buffer in a shared storage mode
needs no `didModifyRange`, because the host reads the same memory. If that
holds, the declaration is not a complete account, and 86 % is an upper bound on
a rule that would serve stale bytes rather than a hit rate.

So this does not license the cache, and quoting the higher of the two boots
would have. What it does establish is that the ceiling is not the blocker —
completeness is — and that is a question with a cheap decisive test: fold a
sampled `quiet` window's bytes and check whether they moved, on the same shape
`gather_witness::AUDIT_STRIDE` already uses for the sampled rails. If they
moved, this design is closed and the cache needs the hypervisor half, which is a
harvest cost rather than a resize.

One caveat on the population, stated on the line's own doc: the split is charged
where the *bind* is taken, because the engine sees an `Arc` address and has
neither task nor reference. So it covers all ~66 700 zero-copy buffer binds a
second and not only the ~20 800 that gather. Whether the gathering subset is the
quiet one or the written one is not separated here.

Tests: unchanged, 1944 passed / 0 failed. Clippy `-D warnings` clean on all
three arms.

Not verified: macos-13 only, one probe, and the completeness question the
paragraph above exists to raise.
2026-08-11 10:47:59 +03:00
Anees Iqbal 26a4e87ac8 ✨ The guest's own account of writing a buffer, which this device decoded and threw away, because it is the one signal that says whether the gather rail's 91% of repeat windows could be served from a cache
x86 macOS / Linux Vulkan and the shared runtime. Instrument only: nothing here
changes a bind, a copy or a byte the guest sees.

## What was being dropped

`resource_validity::apply` takes the guest's validity quad for one object id and
applies it to `DeviceState::mappings`. A **buffer has no mapping**, so every
quad naming one falls out of the loop, is counted as `validity_no_surface` —
~4 700 a second on a driven macos-13 boot — and is discarded. The statement was
decoded, correct, and thrown away.

That is the one signal the draw-time buffer gather has no substitute for.
`buffer_gather_working_set` (f6420526) put 91 % of that rail's ~20 800 gathers a
second on windows it had already assembled, which is a statement about *keys*.
Whether those 91 % are copies that could be skipped or copies that were owed
depends on whether the bytes moved, and nothing had measured that.

## Two pieces

- **`runtime::buffer_write_gen`** keeps a per-`(task, object)` generation for
  exactly the ids `apply` finds no mapping for. Recorded only on that miss, so
  an object with a `content_generation` does not get a second spelling. Bounded
  at 4 096 pairs, and past it the map is **cleared** rather than partly evicted:
  forgetting one object would make its next comparison read as clean, which is
  the direction that reports a cache hit for a window whose bytes moved. A
  cleared map carries an epoch, so every stamp taken before the clear compares
  as *unknown*. A task's entries go when the task does.
- **`runtime::buffer_gather_freshness`** crosses that against the gather rail:
  for each zero-copy buffer bind it compares the owning object's stamp with the
  one this window carried the last time it was bound, and splits into
  `quiet` / `wrote` / `first` / `dropped`. `first` is a compulsory miss no cache
  size removes and is kept out of the rate for that reason. Charged from both
  the held-resolution and the fresh-walk paths, because a cache would serve a
  window whether or not the addresses had to be re-walked.

## The check that has to be read beside it

A stamp is taken on a `(task, reference)` pair at a draw-time bind and compared
against a generation recorded under a `(task, object)` pair from a validity
record. **If those are different namespaces, no comparison ever moves and the
split reports ~100 % quiet** — a false positive in exactly the direction that
would license a cache serving stale bytes. So `note_write` also emits
`buffer_write_gen_bump`, and both module docs say it: `quiet_rate=1.000` beside
`buffer_write_gen_bump=0` is a wiring fault, not a workload.

## What this is not

It is a **ceiling**, not a licence. A cache invalidated this way would be
trusting that `writeInvalidates` and the exec-table quad are a *complete*
account of guest CPU writes to a buffer's bytes. The equivalent claim for a
surface is not complete — which is why `gather_witness` carries a hypervisor
half as well — and the buffer case has not been tested either way. What the
split settles is whether it is worth testing: no declaration-invalidated cache
can beat `quiet`, so a low reading closes the design and a high one says go and
establish the soundness.

The hypervisor witness is deliberately not the instrument here.
`MAX_TRACKED_WINDOWS` of 256 is a **harvest** bound, not a memory one —
`reims_vgpu_dirty_harvest` walks every page of every armed set on the BQL thread
at each register write that hands the device work — and this rail's ~1 900
windows of ~38 pages would put ~72 000 pages into a walk the whole VM waits on.
Measuring with it would change what is measured.

Tests: 13 new, all device-free. The generation map is pinned on a declared write
moving only its own object, a stamp straddling a reset never reading quiet, and
a retired task taking its objects with it. The split is pinned on a first sight
counting as neither side, a repeat with no declared write counting as quiet, a
declared write between two gathers counting as written, the stamps surviving a
census second the counters do not, one reference at two offsets being two
windows, and a full map dropping rather than evicting. Full suite 1944 passed /
0 failed, clippy `-D warnings` clean on all three arms, feature matrix all arms
warnings=0.

Not verified: no boot has read the line. That is the next step and it is one
driven macos-13 boot; the first thing to check on it is
`buffer_write_gen_bump`, not `quiet_rate`.
2026-08-11 10:42:15 +03:00
Anees Iqbal fcd04bf4db 📝 Shaving this crate's own work off a gather dispatch moved the column it was aimed at and not the total, so the remaining cost is four driver calls and the only lever on it is issuing fewer
x86 macOS / Linux Vulkan, macos-13, sustained-animation probe. Documentation
only; the two repairs in 71102e6a stay because they are strictly less work, but
their measurement is a null and this records it as one.

Four driven boots, all in the collapsed regime (draws/frame 256.8-257.5), so one
population:

              plan   stage    dset  record   total   dispatches/s
    before   0.350   0.150   0.082   0.376   0.959      21 949
    before   0.333   0.145   0.082   0.368   0.928      20 120
    after    0.223   0.128   0.140   0.404   0.895      24 606
    after    0.225   0.142   0.146   0.419   0.932      23 085

`plan` fell **34 %** with the arms disjoint — the run table was reallocating six
times per gather and now cannot reallocate at all — and the total did not move.
The ~0.12 us reappeared in `dset` and `record`, `dset` by 74 % in a path neither
change touched. That is the split's own floor: at 80-150 ns a part, the two
`Instant::now()` calls are a large share of what is timed, and an untouched
column moving 74 % between runs is the instrument rather than a mechanism.

The staticlib is built `--release` with `opt-level = 3`, `lto = "fat"`,
`codegen-units = 1` (`vendor/qemu/hw/display/meson.build`), so 0.9 us is not a
debug artifact and there is no compiler switch left to find. What is in it is
four driver calls, and the only lever on four driver calls is issuing fewer.

So the next change is not in `gather_phase`'s subject at all. Fewer dispatches
has a floor of one per draw — the destination arena, ~35 % of `record` — and a
ceiling of none: `buffer_gather_working_set` measured **91 %** of this rail's
gathers as repeats of a window it already assembled. A content cache removes the
dispatch, the run table, the descriptor set and the GPU copy together, and makes
every column here moot rather than smaller. That is what to build, and
`runtime::gather_witness` already carries the soundness argument it needs for
the sampled rails.

Tests: unchanged, 1931 passed / 0 failed. Clippy `-D warnings` clean on all
three arms.

Not verified: the four boots were all collapsed-regime, so this says nothing
about the promoted regimes; and no arm of this comparison was run against
`REIMS_VGPU_COMPUTE_GATHER=off`, because the question was where a dispatch's own
cost sits and not whether to pay it.
2026-08-11 10:34:19 +03:00
Anees Iqbal 71102e6a6f ⚡ A gather dispatch binds its pipeline once per draw and builds its run table without reallocating, because the instrument put 76% of the cost in those two columns and 9% in the one the plan named
x86 macOS / Linux Vulkan, `backend/vulkan/engine`. Byte-identical output on
every rail: this changes only how the guest-scatter kernel's dispatches are
recorded, and both rails that use it — the render writeback and the draw-time
buffer gather — take the same two changes.

`gather_phase` (f6420526) measured a dispatch at 0.959 us and split it
`record` 39 % / `plan` 37 % / `stage` 16 % / `dset` 9 %. This is the two large
columns:

- **`vkCmdBindPipeline` is hoisted out of the dispatch loop.** It was one of
  `record`'s four driver calls and the handle never changes, so a draw's 1.4
  dispatches paid for 1.4 binds of one pipeline and the writeback's ~200-region
  windows paid one per table. `ScatterPipeline::bind` is now separate from
  `dispatch`, and its doc states the obligation the split creates: no other
  pipeline may be bound to the compute bind point between them. Both call sites
  record their dispatches in one uninterrupted loop, which is what makes that
  hold.
- **The run table's word vector is built at its exact capacity.** It grew from
  `Vec::new()` by `push`, four words at a time, to ~50 words for a ~13-run
  gather — about six reallocations and copies per table, ~21 000 tables a
  second. Every run contributes exactly `WORDS_PER_RUN` words and a window holds
  at most all of them, so `runs.len() * WORDS_PER_RUN` is the exact upper bound
  and the loop cannot reallocate at all. `tables` reserves for one window, which
  is what a boot produces on 94 % of writebacks.

Neither touches `dset`, which is the column `env::COMPUTE_GATHER` had named as
the thing to fix and which the instrument found at 9 %.

Tests: unchanged and unchanged deliberately — this is the same table, the same
bytes and the same dispatches, so the ~40 existing `guest_scatter` cases are the
regression gate and all of them pass. A test that asserted a `Vec`'s capacity
would be testing spelling. Full suite 1931 passed / 0 failed, clippy
`-D warnings` clean on all three arms.

Not verified: no boot yet. The next reading is `gather_phase` from one driven
macos-13 boot — `plan` and `record` are what should move, and by how much is
what says whether the destination arena (the remaining ~30 % of `record`, by
merging a draw's 1.4 dispatches into one) is worth building.
2026-08-11 10:27:34 +03:00
Anees Iqbal f64205262c 📝 The gather dispatch's cost is its own planning and four driver calls, not the descriptor set the fix was aimed at, and a content cache on that rail would serve 91% of it
x86 macOS / Linux Vulkan, macos-13, sustained-animation probe, two driven boots
under the compute gather. Documentation and harness only; no code behaviour
changed.

## `gather_phase`: 0.96 us a dispatch, and the plan was aimed at the 9%

Two boots, ~21 000 dispatches a census second each, agreeing to a hundredth of a
microsecond:

    record   0.376 us/dispatch   39 %   bind pipeline, bind set, push, dispatch
    plan     0.350 us/dispatch   37 %   two Vecs and the table's own, over ~13 runs
    stage    0.150 us/dispatch   16 %   the shared run-table arena, already amortised
    dset     0.082 us/dispatch    9 %   one vkUpdateDescriptorSets
             0.959

`env::COMPUTE_GATHER` named the **destination arena** as "the candidate that
survives the arithmetic without a reading". It attacks `dset`. Recycling the
sets — four lines, landed in 42ba8ce3 — had already taken
`vkAllocateDescriptorSets` and its matching free out of the steady state, and
what is left there is 9 % of the cost. Building the arena first would have been
a day spent on the smallest of the four columns, which is the outcome the split
was built to prevent and the reason it was built before anything else.

What is actually there: `plan` is entirely this crate's own code with no driver
call in it — three heap allocations and three passes over ~13 runs to produce
~200 bytes — and `record` is four driver calls whose count falls only with the
dispatch count. The destination arena does still buy ~30 % of `record` by
merging a draw's 1.4 dispatches into one; it buys it in a different column than
the one it was proposed for.

## `buffer_gather_working_set`: 91% recurrence, 288 MiB to hold it

    distinct=1897  mib=287.7  gathers=20771  mib_moved=3520.5  recur=0.909  dropped=0
    distinct=1781  mib=271.7  gathers=19452  mib_moved=3307.5  recur=0.908  dropped=0

An unbounded content cache would serve 91 % of the gathers — ~3.2 GB/s of GPU
copy and ~90 % of this rail's ~427 000 transfer regions a second, which is the
largest removable item in the device on `render_writeback`'s own established
arithmetic that region count and not bytes is the bound.

Three qualifications, all on the line: it is 91 % and not the 99.2 % this rail
is usually argued from (that was a window-drag probe and a census that no longer
exists — two workloads, both real, quote the one whose probe is named);
unbounded means 288 MiB held across submissions against a gather pool that is
transient today, so the cap will bind and the eviction policy is part of the
design; and `dropped=0` says 1 897 is a count rather than a floor.

Recurrence is about keys, not bytes. `runtime::gather_witness` already carries
the soundness argument this would need — the hypervisor dirty bitmap for guest
CPU stores and `runtime::host_writes` for this device's own — for the sampled
rails. Its `MAX_TRACKED_WINDOWS` is 256 against 1 897, so adopting it is a
resize as well as a wiring.

Also in this commit: `kb/harness/ranktest.py` (gitignored) now reports
`slot_us_per_draw`, `record_us_per_draw` and `dispatches_per_draw` beside the
frame metrics, and `kb/harness/analyze.py` prints the working-set line, so the
mechanism is visible in the same banded, ranked form as the outcome.

Tests: unchanged, 1931 passed / 0 failed. Clippy `-D warnings` clean on all
three arms. `cargo doc` adds no unresolved link.

Not verified: nothing on any rail but macos-13, and the two boots were taken on
a host that was quiesced but not exclusively so — the `_us` columns are upper
bounds, though the two boots agreeing to 1 % and the shares being ratios makes
the split itself robust to that.
2026-08-11 10:25:15 +03:00
Anees Iqbal b8279f90fa ✨ Two instruments the gather rail's next reading needs, because its remaining 0.86 microseconds a dispatch is four candidates and its frame result was a band artifact
x86 macOS / Linux Vulkan, `backend/vulkan/engine`. No behaviour change on any
rail: both additions are counters, and `REIMS_VGPU_COMPUTE_GATHER` stays
default-off.

## What the A/B said

Ten driven macos-13 sustained-animation boots, interleaved, on the tree that
gave a dispatch a shared run-table arena and a recycled descriptor set
(`42ba8ce3`). Per-draw mechanism columns, disjoint in all four regimes:

    slot_us/draw     on 1.94   off 4.06    -52 %   GPU blocking
    record_us/draw   on 3.10   off 2.01    +54 %   CPU recording
    dispatches/draw  on 1.44   off 0.00

So the arena and the recycle took the recording penalty from +85 % to +54 % and
the GPU saving held. That is progress and it is not enough.

**The frame result is unresolved, and the +9.0 % the rank test first printed is
an artifact.** The ten boots sort by draws per frame as

    257.0 257.2 | 335.9 340.4 341.4 344.0 | 361.6 362.2 363.9 367.5

which is a *fourth* compositing regime the harness's band edges did not
separate, running ~79 frames a second against the next one's ~72. The on arm
drew three boots from the fast side and the off arm one. Matched by draws per
frame the arms are level; with the edges re-derived (296/353) no band holds two
boots of both arms. The harness's edges are updated and its own doc now says to
re-derive from a pooled sort after every landed change that moves frames per
draw — this is the second time that edge has moved and the second time it moved
in the direction that flatters the arm under test.

## The instruments

- **`engine::gather_phase`** splits the 0.86 us a dispatch still costs into the
  four things that could be it — the run-table planning, the shared staging
  arena, the descriptor set, and the command-buffer calls — because guessing
  which one is the next 0.8 us is how a session spends a day on
  `vkCmdBindPipeline` and finds it was never the cost. Emitted only when a
  gather dispatched, so the line's presence is itself the statement of which arm
  a boot ran.
- **`engine::pools::buffer_gather_working_set`** counts the distinct guest
  buffer windows gathered per census second, and what holding all of them would
  cost, beside the gathers that asked. The 99.2 % recurrence figure this rail is
  argued from says the same *key* comes back; it does not say how many keys have
  to be held at once to catch them, and that is the number a cap is chosen from.
  The census the 99.2 % came from is gone, so the doc that cited it pointed at a
  dead symbol; it now points here.

Also corrects two claims in `env::COMPUTE_GATHER`: `guest_gathers` is a local of
`execute_draw_inner`, so a plan covers one draw and there is no
command-buffer-wide batch to make (merging within a draw is 1.4x on the count,
not 18x), and "the default is the one that measured faster" is now "the one that
has not been beaten", which is the claim the data supports.

Tests: 8 new, all device-free. `gather_phase` pins that a window takes what was
charged and clears itself, and that a boot with no dispatch publishes no line.
`buffer_gather_working_set` pins that gathering one window a thousand times
wants one window, that one allocation at two lengths is two windows, that the
set does not carry into the next census second, and that a set past its capacity
reports what it dropped while still counting the gathers exactly. Full suite
1931 passed / 0 failed, clippy `-D warnings` clean on all three arms, feature
matrix all arms warnings=0, `cargo doc` adds no unresolved link.

Not verified: no boot has read either line yet — that is the next step and it is
one driven boot. The harness lesson (a chain must run as a systemd user unit, or
the agent harness freezes it mid-boot; and QEMU_BIN may not point outside the
build directory or every boot dies on a missing romfile) is in gitignored `kb/`.
2026-08-11 10:18:03 +03:00
Anees Iqbal 42ba8ce33b ⚡ A submission's gather run tables share one staging slot and its descriptor sets recycle, because the compute gather was paying two driver calls and two pool acquisitions per dispatch
x86 macOS / Linux Vulkan, `backend/vulkan/engine`. Behaviour is unchanged on
every rail: this is the per-dispatch cost of the guest-scatter kernel, which the
draw-time buffer gather pays ~40 000 times a second and the writeback ~1 900.

The gather's mechanism was already measured — it takes this rail's GPU blocking
down 56 % — and it ships off because the CPU side gave more than that back, at
~1.05 us a dispatch. Three of the four things a dispatch paid for are gone:

- **The run table's staging slot.** Every dispatch took its own slot for a
  ~200-byte table, so an `acquire_staging` and a `write_staging` apiece. They
  now share one slot per submission, laid out by `engine::stage_run_tables` at
  `minStorageBufferOffsetAlignment`, and the descriptor's own `offset` field is
  what tells a dispatch which table is its own. Against ~2 200 command buffers a
  second that is one acquire and one write where there were eighteen. The kernel
  is untouched: it already indexes from zero of its bound range.
- **`vkAllocateDescriptorSets` and its matching `vkFreeDescriptorSets`.** Every
  set here is allocated against the one guest-scatter layout, so unlike a draw's
  they are interchangeable. `ResourcePools::scatter_dset_free` recycles them, fed
  only from `drain_cleanup` — after the fence of the submission that named the
  set, which is the same rule the staging and gather free lists keep and what
  makes a rewrite safe. Steady state is zero allocates and zero frees. The list
  is bounded by construction: nothing enters that was not already allocated and
  retired, so its high-water is the peak dispatches in flight.
- **A `Vec` per `write_set`.** Three writes whose count is fixed by the layout
  were being collected onto the heap 40 000 times a second; they are an array.

The writeback's scatter shares the arena for the reason it already shares
`run_table_bytes`: a second copy of the placement arithmetic is a second place
to name a descriptor offset the driver refuses.

`REIMS_VGPU_COMPUTE_GATHER` stays default-off. The switch flips when a driven
boot says it should, not because the cost model improved.

Tests: nine new, both halves device-free by the same split `take_free_gather`
uses. `pack_run_tables` is walked at the three alignments this rail meets
(16/32/256) for legal descriptor offsets, non-overlapping ranges, and each
table reading back its own words at its own place; `take_free_scatter_dset` /
`recycle_scatter_dsets` pin the no-aliasing property — two takes with no retire
between them cannot resolve to one set, which is what stops a second dispatch's
`write_set` retargeting a live one. Full suite 1917 passed / 0 failed, clippy
`-D warnings` clean on all three arms, feature matrix all arms warnings=0.

Not verified: no boot yet. The per-dispatch cost this removes is arithmetic and
driver-call count, not a measurement — the A/B that decides the switch is owed
and is the next step. The host is not quiesced at this commit, so no timing was
taken. Nothing here runs on a host that cannot import guest RAM: with
`REIMS_VGPU_GUEST_IMPORT=off` there are no gathers to plan.
2026-08-11 09:42:45 +03:00
Anees IqbalandClaude d6b9f7e384 📝 A region-count threshold for the gather dispatch buys 3% at best, because the per-dispatch cost and not the region count is what holds it back
Pathway: x86 macOS / Linux Vulkan. Doc only.

The compute gather ships off because its GPU saving is smaller than its CPU
cost. The obvious cheap interim is a threshold — dispatch only for windows with
enough runs to amortise the fixed cost — and six driven boots of
`gpu-load-probe` at `layers=24&boxes=6` put a ceiling on what that could be
worth. That load runs 23.5 gather regions per draw against the sustained
probe's 15.8. Comparing the boots that reached the same drain duty (~0.8):

            frames/s   slot_us   record_us
  on           86.96    13 007      64 357
  off          84.76    95 715      42 487
  off          83.72   107 146      42 279

The sign does flip, and the mechanism is confirmed: `slot_us` falls **86 %**
here against 56 % on the lighter load, exactly as amortising a fixed cost over
more regions predicts. It is still only ~+3 % of the frames, because the
per-dispatch cost is unchanged and the recording penalty is the same +52 %. A
threshold buys the tail of a distribution whose mean is the problem, so the
per-dispatch work stays the thing to fix.

Also recorded, because it nearly became a measurement: **`layers=24` is a poor
A/B vehicle.** The same six boots ranged over drain duty 0.25 to 0.80 and 24.7
to 87.0 frames a second, while `draws/frame` — the discriminator that separates
regimes on the sustained probe — sat at 132.7 to 133.0 on every one of them.
Nothing distinguishes a fast boot from a slow one there before the fact, so
arms have to be matched on duty after the fact, which is weaker.

One harness fix went with it (`kb/harness/ab.sh`, gitignored, so noted here):
it set the on arm by *unsetting* the variable, which is right for every
ordinary off-switch and gives two identical arms for a default-off one like
`REIMS_VGPU_COMPUTE_GATHER`. It now takes an explicit `AB_ON_VALUE` for those.
The first attempt at this A/B ran both arms off and had to be discarded.

Verification performed:
  - the six driven macos-13 boots above, quiesced host, `layers=24&boxes=6`
  - the on arm confirmed live rather than assumed: `buffer_gather_dispatches`
    is 18 811 to 20 452 a second on it and 0 on the off arm
  - clippy `-D warnings` clean, backend-vulkan/host-window

Not verified: n is 1 on-boot against 2 off-boots after matching on duty, so the
+3 % is a direction and not a number.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 09:27:00 +03:00
Anees IqbalandClaude e80ba2390c 📝 The gather region counter counts regions planned and not regions issued, so it is not the column that says which form a boot took
Pathway: x86 macOS / Linux Vulkan. Doc only.

`buffer_guest_gather_regions` is charged where a window is planned, before
either the transfer form or the dispatch form is chosen. A dispatch boot
therefore reports ~245 000 regions while issuing none — and the counter's own
doc, written one commit ago, claimed it distinguished the two. It does not.

Corrected in place, with what each column is actually for: the region count is
a property of the *workload* (how scattered the guest's buffers are), which is
what makes it comparable across both arms and across builds and worth keeping;
`buffer_gather_dispatches` and `buffer_gather_declined` are what say which form
ran, including that a decline is all-or-nothing per command buffer because the
two forms need different barriers.

Verification performed: clippy `-D warnings` clean, backend-vulkan/host-window.
No behaviour change.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 08:47:05 +03:00
Anees IqbalandClaude 726caa1f42 📝 Batching the gather dispatches would buy 1.5x and not 18x, because a gather is recorded ahead of its own draw's pass and cannot be hoisted
Pathway: x86 macOS / Linux Vulkan. Doc only — corrects the previous commit.

The commit that shipped the compute gather off-by-default named the fix as
"one arena per command buffer, an ~18x cut in dispatches". That arithmetic is
wrong and would have sent the next session at the wrong half of the problem.

~40 000 dispatches a second against ~26 500 draws is **1.5 per draw**, not 18
per command buffer. A gather is recorded ahead of its own draw's render pass
and cannot be hoisted to the front of the command buffer: a Store earlier in
that same command buffer may have landed in the pages it reads, which is
precisely why `note_guest_write_recorded` invalidates the bind map. So batching
the count buys at most 1.5x.

The cost that matters is per dispatch, ~1.05 us of the 1.6 us a draw the
dispatch path regressed by, and all three parts of it are avoidable:

  - the `acquire_staging` + `write_staging` for a ~200-byte run table, which a
    command-buffer-scoped run-table arena makes ~2 200/s instead of 40 000/s;
  - the descriptor-set allocation and update — two of the three bindings (the
    guest import, the run-table arena) are the same buffer for every dispatch
    in a command buffer, and `Dst` differs only because each gathered window
    takes its own pooled slot. Suballocate those from one arena and the whole
    command buffer needs **one** descriptor set. `BoundBuffer` already carries
    an offset, so the bind side of that costs nothing;
  - the bind, which then goes with it: a dispatch becomes a push constant
    carrying its run-table base index and `vkCmdDispatch`.

~0.05 us a dispatch against today's ~1.05, against a GPU saving already
measured at 56 %.

Verification performed: clippy `-D warnings` clean, backend-vulkan/host-window.
No behaviour change, so nothing was booted for this.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 08:45:51 +03:00
Anees IqbalandClaude d1fc7aade3 🐛 The compute gather halves this rail's GPU blocking and spends more than that on the CPU getting there, so it ships off until a command buffer's gathers share one arena
Pathway: x86 macOS / Linux Vulkan. Flips the default; no other behaviour change.

The previous commit landed the compute gather with nothing booted and said so.
Ten driven macos-13 sustained-animation boots have now run it, and the answer is
that the mechanism works and this implementation of it does not pay.

Comparing only the four boots that landed in the same compositing sub-regime
(draws/frame ~351, so like for like — see below):

                      on (n=2)          off (n=2)
  slot_us          48 838 / 62 875   124 703 / 130 423   -56 %  GPU blocking
  ring_retire_blocks          260               502      -48 %
  record_us        91 961 / 93 106    49 458 /  50 562   +85 %  CPU recording
  descriptors_us   10 387 /  9 109     6 796 /   6 757   +45 %
  frames/s          74.68 /  75.64     76.04 /   76.12    -1.4 %

Halving the blocking on a rail this device is GPU-bound on is exactly the
lever, and it gave all of it back. The reason is the count: ~40 000 dispatches
a second, one per gathered window, each paying an `acquire_staging` for its run
table, a `write_staging`, a descriptor-set allocation and an
`update_descriptor_sets`. The writeback's scatter issues ~1 900 a second and
notices none of that.

So the default becomes the transfer form, and `REIMS_VGPU_COMPUTE_GATHER=on`
reaches the dispatch. The env doc carries the table above, and names the one
change that would flip it back: give a command buffer's gather destinations one
arena buffer rather than a pooled slot each, so a single dispatch covers all of
them — ~2 200 command buffers a second against ~34 000 gathers, an ~18x cut in
dispatches, staging acquisitions and descriptor sets against a GPU saving
already measured at 56 %. That needs `BoundBuffer` to carry a suballocation
offset, which is why it is not in this change.

The switch is now a permission rather than a refusal, which bends this module's
own rule, and the doc says why knowingly: the rule is about **host capability**
— an unadvertised extension crashes and an undeclared handle is undefined
behaviour — and neither arm asks the host for anything the other does not.
Both are byte-identical copies; the default is the one that measured faster.

Two method notes, both of which nearly produced a wrong call:

  - **`draws/frame` cannot classify a regime for a change that alters frames
    per draw.** The on arm read +13.9 % disjoint at 2v2 and +5.3 % overlapping
    at 4v2, because its two fastest boots sat at draws/frame 315-326 and every
    off boot at 351. `surface_flush` per frame separates them the same way
    (10.4-10.6 against 10.85-10.94) and the device does not choose how many
    surfaces the guest composites — so those are a guest sub-regime the on arm
    happened to land in twice, not an effect. Compared inside the ~351
    sub-regime the arms are as tabled above.
  - **The collapsed band is the reproducible one.** Four boots of three
    different builds read 59.44, 59.68, 59.76, 59.80 frames/s. A regression is
    visible there at n=1; a win probably is not.

Verification performed:
  - the ten boots above, macos-13, sustained-animation probe, quiesced host
  - a `REIMS_VGPU_GUEST_IMPORT=off` boot: `host_pointer_import=disabled_by_env`
    and `buffer_gather_dispatches=0` in every census window — the dispatch is
    provably inert on the copying rails
  - `buffer_gather_declined=0` across every boot: no window's arithmetic was
    refused, so the -1.4 % is the dispatch path's cost and not a silent fallback
  - full suite green, clippy `-D warnings` clean on backend-vulkan/host-window

Not verified: the arena change is a design, not a measurement. And
`buffer_guest_gather_regions` counts regions *planned* rather than issued, so a
dispatch boot still reports ~245 000 of them; `buffer_gather_dispatches` beside
it is what says which form ran, but the counter's own doc overstates what it
distinguishes and is left for the change that fixes it.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 08:44:20 +03:00
Anees IqbalandClaude b7087842d2 ⚡ The draw-time guest buffer gather assembles its window with one compute dispatch instead of ~13 transfer regions, because that rail issues 427 000 regions a second and the writeback's identical repair was worth 48% of the frames
Pathway: x86 macOS / Linux Vulkan.

The writeback stopped issuing ~200 transfer regions per frame and started
issuing one compute dispatch, and that measured +48.3 % frames on a driven
macos-13 boot. The **gather** direction was left alone and is now the largest
region population in the device by two orders of magnitude:

  buffer_guest_gather_regions   427 122 /s   (12.6 per gathered window)
  guest_write_regions             1 629 /s   (post-scatter)

This does the same thing to it. `plan_buffer_gather_dispatches` turns each
window's `VkBufferCopy` regions into a run table and issues one dispatch per
window, in the loop that already records every gather for a draw ahead of its
render pass, and the single barrier that follows takes `COMPUTE_SHADER` /
`SHADER_WRITE` as its source scope instead of `TRANSFER` / `TRANSFER_WRITE`
when it did.

## The same kernel, exchanged

`shaders/guest_scatter.comp` carries no direction — it reads `src[run.x + i]`
and writes `dst[run.y + i]` and nothing in it knows which side is guest memory.
What differs between the two rails is only which binding has to be a *window*,
and that is forced rather than chosen: an imported RAMBlock is wider than
`maxStorageBufferRange` and a pooled slot is not, so the guest side is always
the windowed one. The writeback windows `Dst`; the gather windows `Src`.

So `build_gather_run_tables` hands `build_run_tables` the runs with the two
sides exchanged and exchanges the two index words back, rather than being a
second planner. That is not tidiness: `build_run_tables` carries the
partitioning that fixed a measured bug — 6 % of one boot's writebacks straddled
a 4 GiB boundary and fell back to ~200 regions each — and a second copy of that
sweep is a second place to get it wrong, in a direction no test on the first
one would catch. `write_set` now takes an offset for both sides; the writeback
passes 0 for the scratch it always bound whole.

Byte-identical by construction, not by measurement: the kernel copies `uint`s
and the run table is built from the very `VkBufferCopy` regions the transfer
form would have issued.

## The transfer form stays

Whole-batch, not per-gather: the two forms need different barriers and the loop
emits one for all of them. A decline is a property of the host (no import, no
pipeline) or of the arithmetic (an unaligned run), both stable across a command
buffer, so an all-or-nothing costs nothing here. `REIMS_VGPU_COMPUTE_GATHER=off`
narrows to the transfer form, which is also the only form on a host without
`VK_EXT_external_memory_host`.

`buffer_gather_dispatches` and `buffer_gather_declined` join the `engine_delta`
line beside `buffer_guest_gather_regions`, so a boot says which form it took
rather than leaving it inferred from a frame rate — the mistake the writeback's
own census made first and had to be fixed for in a follow-up.

Verification performed:
  - `cargo test -p reims-vgpu --no-default-features
    --features backend-vulkan,host-window -- --test-threads=1`:
    1908 passed, 0 failed, 6 ignored (wire fixtures + doc-tests)
  - clippy `-D warnings` clean on all three arms: backend-vulkan/host-window,
    the same with `--target x86_64-unknown-linux-gnu`, and
    `--target aarch64-apple-darwin --features backend-metal`
  - three new planner tests, all pure and running on every arm: the gather
    windows the guest side and leaves the slot index absolute; a gather table is
    the writeback table with its two index words exchanged (asserted against
    the planner it delegates to, so an edit to either is caught); and a gather
    straddling the 4 GiB storage-range wall splits into two windows

Not verified: **this has not been booted.** No guest has run it, no screenshot
compares the two arms, and the A/B against `REIMS_VGPU_COMPUTE_GATHER=off` is
the next thing to run. Nothing may be claimed for its frame effect until then —
in particular the +48 % the writeback measured is that rail's number and not a
prediction for this one, whose regions are host-to-device reads of ~13 KiB
rather than device-to-host writes of 4 KiB.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 08:16:24 +03:00
Anees IqbalandClaude 23a6e3080f 📝 The load probe's WebGL dial collapses the guest rather than the device, and the layers dial is the one that drives the gather rail hardest
Pathway: x86 macOS / Linux Vulkan. Probe only; no device code.

Four driven macos-13 boots of one binary put numbers on the three dials, and
one of them does not do what the probe was written to make it do.

  dials                                     duty   draws/s  gather regions/s
  (sustained-animation probe, for scale)    0.83    26 800           427 000
  layers=24&boxes=6                         0.68    11 525           270 807
  layers=16&boxes=6&verts=30000&tex=512     0.14     1 390            34 976
  layers=8&boxes=6&verts=60000              0.11     1 017            26 592

**Any WebGL at all collapses the guest to ~1 000 draws a second at duty 0.11.**
The device is then idle seven eighths of the time and the boot measures
Safari's WebGL path rather than this device — the exact failure the probe
exists to avoid, one layer further out. The dial is kept and documented as not
usable for ranking, because the collapse is worth being able to reproduce in
one command; it is not quietly left looking like a working axis.

Two fixes went in first, so the reading above is not measuring the page:

  - the vertex array is built once and only re-uploaded. The first version
    rewrote all `verts * 2` floats per frame, which at verts=90000 gave 1 329
    draws/s at duty 0.12 — indistinguishable from the collapse above, and
    caused by the page rather than the guest. `bufferData` re-uploads the whole
    array regardless, so eight mutated entries per frame keep the device
    traffic and stop a browser eliding the call.
  - the 2D canvas draws two fills rather than twenty-five, for the same reason:
    the upload is `tex * tex` either way and the rest was guest paint time
    bought at the device's expense.

`layers` is the axis that works, and its value is the *shape* rather than the
size: at 24 layers it drives 23.5 gather regions per draw against the sustained
probe's 15.8, so it is the heavier arm for anything about the guest buffer
gather despite the lower absolute draw rate. Nothing here beats the
sustained-animation probe for total device load, and the doc now says so.

Verification performed:
  - the four driven macos-13 boots above, quiesced host, `bash -n` on the script
  - each boot's dials are recorded in its own `load-url.txt`

Not verified: `tex` has not been measured on its own, and no rail but macos-13
has run this probe.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 08:08:59 +03:00
Anees IqbalandClaude 0ec9950464 📝 The pipeline memo removes 15% of a draw chain and buys 1.7% of the frames, because this rail is GPU-bound and the worker spends what it saves waiting
Pathway: x86 macOS / Linux Vulkan. Doc only — no behaviour change.

Ten driven macos-13 sustained-animation boots, interleaved arms of
`REIMS_VGPU_PIPELINE_MEMO`. The span the memo targets collapses exactly as
designed, disjoint across every pair of boots:

  pl_mtlb_us / pl_air_us / pl_xlate_us   34 900 / 5 300 / 33 100  ->  0 / 0 / 0
  pl_desc_us                             52 400 -> 20 000  (the identity check)
  span per chain                         4.86 us -> 0.89 us

Frames moved +1.70 % (disjoint, sep 0.9x). The reason is also disjoint, and it
is the finding rather than the memo:

  slot_us  on  129 484  132 023  121 964  121 124   (min 121 124)
          off   90 427   78 494   68 489   83 515   (max  90 427)

`slot_us` is the drain worker blocked on a ring slot, i.e. on the GPU. It rose
1.74 us of the 3.97 us a chain the memo freed, and `busy_us` is unchanged at
~840 ms/s on both arms — the worker did not go idle and did not draw more.
**This rail is GPU-bound.** A CPU saving converts at the residual rate until
the GPU work comes down, the largest piece of which is the guest buffer
gather: 5.8 GB/s over 427 000 transfer regions a second.

The memo stays, and the doc says why it is not sunk cost: it is a strict
reduction in work with no regression on any metric, the balance it was measured
against is one host's (discrete NVIDIA, fast CPU) while the unified-memory
cells of the support matrix have the opposite one, and a probe heavy enough to
make the worker the bottleneck again would convert it. What may not be said is
that it bought 15 % of anything.

Also fixes the analysis harness, which produced a wrong number first
(`kb/harness/ranktest.py`, gitignored, so recorded here):

  - the regime threshold was 350.0 and the promoted cluster has since moved to
    ~350 because the compute scatter raised frames per draw. It was clipping
    the bottom of the cluster it was meant to keep — in the direction that
    hides a win, since the arm that gains frames per draw is the arm whose
    boots get excluded.
  - there are **three** regimes, not two: ~260, ~350 and ~380 draws per
    presented frame, at ~66 to ~76 frames a second. Arms are now compared
    within a band. Across bands this same A/B read +8.4 % purely because the on
    arm drew 3 fast boots and the off arm 2 — larger than the real effect and
    in the same direction, which is the worst way for a harness to be wrong.

Verification performed:
  - clippy `-D warnings` clean, backend-vulkan/host-window
  - the ten boots above, quiesced host, macos-13, screenshots taken on every
    arm (a stale shader is a visual defect no counter here can see)
  - `pipe_memo_stale` and `pipe_memo_evict` are **zero** across ~669 000 hits
    in a boot: the guest never replaced a live pipeline object during sustained
    animation, and 1024 entries was not a binding cap

Not verified: no rail but macos-13 has booted the memo except one macos-26 boot
that panicked at its standing rate. The unified-memory claim above is a
statement about where the balance differs, not a measurement — this host has
one GPU and it is discrete.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 07:56:30 +03:00
Anees IqbalandClaude f7bd9eadd8 ✨ A probe with a dial on each of the three big rails, because the sustained-animation one has saturated and can no longer rank a device change
Pathway: x86 macOS / Linux Vulkan. New probe under `scripts/`; no device code.

`sustained-animation-probe` has stopped being able to measure this device on
macos-13. The guest produces ~26 800 draws and ~76 presented frames a second
whatever the device does underneath, and the drain worker sits at duty 0.83 —
it has idle time. A measured 3.9 us/chain saving in the pipeline span moved
`draws_s` by less than 0.1 %, and `slot_us` rose 77 -> 129 ms/s with
`ring_retire_blocks` 291 -> 496: the worker spent exactly what it saved
waiting, because there was no more guest work to do with it.

A probe the device cannot fall behind reports "no effect" for a real win and
for a real regression alike. That is the failure this replaces, and it is not
fixed by running the old probe longer or more often.

`gpu-load-probe` makes each guest frame heavier rather than asking for more
frames — which is also the only thing a page can do, since the frame rate is
the guest's own display cadence. Three dials, because they land on three
different rails and a change can help one and hurt another:

  layers=N   composited surfaces          -> the writeback / store rail
  verts=K    per-frame WebGL bufferData   -> the guest buffer gather rail
  tex=W      per-frame 2D canvas repaint  -> the sampled-image rail

The gather axis is the one nothing else here reaches. On a compositing load
`buffer_guest_gather_bytes` is 5.8 GB/s over 427 000 transfer regions a
second — the largest GPU cost left in the device now the writeback scatters in
one dispatch — and a CSS page barely exercises it. A WebGL canvas that
re-uploads its whole vertex buffer every frame does exactly that, and the
shader is deliberately trivial so the cost lands on the gather rather than on
fragments.

Determinism follows `anim.html`'s rule and for its reason: every step is per
frame, nothing in the content reads the clock, so two boots draw identical
content per frame and differ only in how many frames they get through. Layer
promotion is forced with `backface-visibility` plus a 3D transform rather than
hinted with `will-change`, which that page measured to be advisory often enough
to split boots of one binary into two clusters 24 % apart.

The URL is written to `<outdir>/load-url.txt`, so a result read later says
which load produced it. Two boots at different dials are two workloads, not two
readings.

Verification performed:
  - `bash -n` on the script; the shim `kb/harness/gpuload.sh` (gitignored)
    drops it into `ab.sh` as `AB_PROBE` the way `anim.sh` does

Not verified: **this probe has not been run against a guest yet.** It is
written to the same interface and the same serving pattern as
`sustained-animation-probe`, whose shape it copies deliberately, but no boot
has confirmed Safari renders the page, that WebGL is available on the macos-13
rail, or what the dials are worth in counters. That is the next thing to do
with it, and until then no number may be quoted from it.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 07:40:16 +03:00
Anees IqbalandClaude 630f5bcb35 ⚡ A draw resolves its pipeline and both shaders once per pipeline object instead of once per draw, because the walk that found them was 18% of a chain and never missed
Pathway: x86 macOS / Linux Vulkan. Two changes, the second measured by the
first.

## The instrument

`chain_phase`'s `pipeline_us` was its third-largest column and undivided.
Five sub-phases now carve it, appended after `Store` so every existing
ordinal keeps its value: `pl_gen`, `pl_desc`, `pl_mtlb`, `pl_air`, `pl_xlate`.
A driven macos-13 sustained-animation boot, per chain of 26.5 us:

  pl_desc_us    2.03 us   load_render_pipeline: 2 walks, 1 alloc, TLV decode
  pl_mtlb_us    1.26 us   both load_mtlb: 6 walks, 4 allocs, 2 decodes
  pl_xlate_us   1.19 us   both content hashes and the translate cache mutex
  pl_air_us     0.20 us   both wrapper-magic scans
  pl_gen_us     0.05 us   gva_alloc_generation
  pipeline_us   0.11 us   the residue

`load_render_pipeline` alone was the biggest bar — larger than both shader
loads together — which is not where the doc's standing guess pointed.

## The repair

`runtime/pipeline_resolve` memoizes the whole span on
`(task_id, pipeline_ref)`. A guest object's identity is its 12-byte
object-list entry, so an entry is served only when all three entries the
resolution depends on — the pipeline object and both function objects — read
back byte-identical. Three 12-byte walks against the 4.68 us they authorise
skipping.

What that check does not cover is stated exactly in the module doc: a guest
rewriting a descriptor, or the MTLB bytes, *in place*. Neither is a shape
Metal produces, but that is a claim about a guest rather than about the
contract, which is why `REIMS_VGPU_PIPELINE_MEMO=off` exists and narrows every
chain back down the full walk.

The bound is in the type. `BoundedByInsertion<K, V, CAP>` has `insert` as its
only mutator and returns what the cap pushed out, so a second caller cannot be
added without the bound and `pipe_memo_evict` says whether 1024 is enough on a
rail. Six `store_routes` counters name every path the memo can take.

`device_reset` calls `forget_all`: the keys are the guest's own names and mean
nothing across a reset, and unlike the translate cache underneath it this map
is not content-keyed.

Verification performed:
  - `cargo test -p reims-vgpu --no-default-features
    --features backend-vulkan,host-window -- --test-threads=1`:
    1905 passed, 0 failed, 6 ignored (the wire fixtures and three doc-tests)
  - clippy `-D warnings` clean on all three arms: backend-vulkan/host-window,
    the same with an explicit `--target x86_64-unknown-linux-gnu`, and
    `--target aarch64-apple-darwin --features backend-metal`
  - three new tests: the cap evicts the oldest insertion, a re-insert does not
    grow the order deque, and every field of every one of the three entries is
    part of the identity. The chain_phase split has one more: a sub-phase is
    carved out of the residue rather than added beside it
  - the instrumentation half booted macos-13 and macos-11/12/14/15 driven

Not verified: **the frame-rate effect of the memo itself has not been
measured.** The 4.68 us it removes is measured; what that buys in frames is
not, and the A/B against `REIMS_VGPU_PIPELINE_MEMO=off` is the next thing to
run. Nor has the memo been booted on any rail but macos-26, whose single boot
panicked at its standing ~1-in-3 rate.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 07:32:09 +03:00
Anees IqbalandClaude c5dad42d98 📝 The compute scatter is worth 48% more frames on macos-13, and the two-point model that predicted it landed within 3%
Pathway: x86 macOS / Linux Vulkan. Doc only — no behaviour change.

`runtime/render_writeback`'s module doc predicted the compute scatter as an
expected value, from a two-point fit through an ablation that *multiplied*
copy regions. It now has a measurement and says so, replacing the prediction
rather than sitting beside it.

Eight driven macos-13 sustained-animation boots, interleaved arms of
`REIMS_VGPU_COMPUTE_SCATTER`, ranked with an exact two-sided Mann-Whitney
after the standing regime exclusion (three boots collapsed, on n=3 / off n=2):

                       on        off      delta   separation
  frames/s          74.92      50.51    +48.3 %       7.1x  disjoint
  presents/s        76.08      51.74    +47.1 %      10.8x  disjoint
  draws/s        26 655.9   21 123.0    +26.2 %      15.3x  disjoint

`p` floors at 0.20 for n=3 vs n=2 and reads that way; the separations carry
it. Three independent things say it is not an artifact: the off arm reproduces
the 49.95 Hz baseline the doc already recorded from a different session and a
different probe, `present_hz` equals `offered_hz` on both arms so the presenter
did not move, and the on arm lands between the 77 Hz prediction and the 104 Hz
all-GPU-work-removed ablation ceiling.

The prediction is kept rather than deleted, because it was right: ~35 us of
frame time per region, a region-free floor of 12.94 ms, 77 Hz against 50.
Measured 74.9.

Verification performed:
  - the eight boots above, macos-13, sustained-animation probe, quiesced host
  - `REIMS_VGPU_GUEST_IMPORT=off` boot: `host_pointer_import=disabled_by_env`,
    `guest_ram_map_no_backend_import` present, `guest_write_dispatches=0` in
    every census window and `buffer_guest_imports=0` — the scatter is provably
    inert on the copying rails, which is the arm a host without the extension
    and a discrete GPU without the import both take
  - five-rail regression (macos-11/12/14/15/26), driven: 11/12/14/15 all
    `dev=1 ssh=1 dock=1 panic=0` with a composited `sd=`

Not verified: macos-26 read `sd=38 panic=1` on its single boot, which is the
boot screen and a panic. That rail panics on roughly one driven boot in three
as a standing behaviour and one red run is not a rate — it needs banding over
six boots, which this change has not done.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 07:31:39 +03:00