clear: a multisample attachment's guest span is not a place to write one sample

Component: crates/reims-vgpu, the clear fallback in runtime/exec.
Pathway: x86 macOS / Linux Vulkan. Rail: macos-15.

API contract. A colour attachment whose texture declares more than one sample has
no single-sample linear publication. The guest sizes and strides the allocation
for all of its samples: measured on this rail, `bytesPerRow = sampleCount * width
* bytesPerTexel` exactly, on three targets in two geometries --

  clear_dropped ... tex_ref=930  samples=4 300x300 bpr=4800   (4 * 300 * 4)
  clear_dropped ... tex_ref=1003 samples=4 300x300 bpr=4800
  clear_dropped ... tex_ref=152  samples=4 8x8     bpr=128    (4 *   8 * 4)

against `bpr=1216` on the single-sample 300x300 surfaces beside them. So a
single-sample image written into that span is not a partial answer; it is the
wrong content, in a sample layout this device has never established. This
repository already states the rule, in the sibling arm of the same function:
"treating the source as a linear image would write only one sample".

Owning invariant: `apply_clear` publishes only where a single sample is what the
destination holds.

Behavior changed. `apply_clear` refuses, fail-visibly, when the resolved target
declares more than one sample, and leaves the guest's bytes as it found them.
`clear_publish_target` above it is unchanged -- it decides from the store action,
and the store action does not name a sample count; the sample count arrives with
the resolved target, which is where the new gate sits. A resolve destination is
single-sample by construction and still publishes, so `ClearPublish::Resolved` is
untouched. Nothing changes for a target whose descriptor established no sample
count: `ResolvedRenderTarget::sample_count` is 1 there and always was.

Why. On rail macos-15 the guest runs four-sample 300x300 passes with
`storeAction=Store` and no resolve texture. The device promotes the attachment to
four samples faithfully (7540d6ec establishes the texture really declares four),
its readback then correctly refuses to linearize a multisample resident
(`read_target_multisample_image`), nothing is stored -- and then the clear
fallback wrote a flat 300x300 beige or near-black image into a span the guest had
strided for four samples, twice a boot, over whatever those pages held.

Every other rail that can write a render target's guest pages already refused
this shape through `resident_read_snapshot`: the host readback Store, the
GPU-direct copy, the deferred writeback (whose bytes come from that readback),
and the shared-backing synchronize -- which cannot even arise, because
`registry_ensure` imports guest memory only at `sample_count == 1`. `apply_clear`
was the last unguarded writer, and it is the one that ran.

What this does NOT repair, deliberately. The guest's pages now keep their prior
bytes instead of receiving a colour the contract does not put there. That is a
refusal, not a landing: the four-sample content stays in the engine resident and
this device still has no rail that can express it in guest memory. The next step
is `msaa4_color_store_no_resolve`, whose blocker is a different one --
`spirv_bind::reflected_compute_texture` refuses a reflection-declared multisample
texture as `UnstageableShape`, so the guest's own `texture2d_ms` readback never
dispatches.

Focused test. `a_multisample_linear_target_keeps_its_guest_bytes_instead_of_a_one_sample_clear`
(runtime/exec/tests.rs) drives `finish_stream` twice over the same 4x2 linear
BGRA8 texture in real guest pages, differing only in the sample count its
descriptor's trailer declares. The single-sample arm must still publish and must
actually write; the four-sample arm must leave every byte at its 0xcc fill and
say `clear_multisample_source_not_linear` on the fail channel. It fails on the
parent at the four-sample assertion.

Conformance gate: PASS. Rail macos-15, three control and three candidate
batteries interleaved against pinned binaries (control 01b1e949 = parent
7540d6ec, candidate 84452de4). 293 cases on all six, no NOT-RUN, no missing name,
no duplicate, no panic, and no timeout. Scored against both controls:

  cnd-1  preserved 263, unchanged debt 19, unchanged applicability 11, regressions 0
  cnd-2  same, regressions 0
  cnd-3  same, regressions 0

Device-reason transitions, read against the three-control envelope:

  clear_dropped               1 -> 4       this repair's own witness: three
                                           four-sample targets a boot, and exactly
                                           4 on all three candidates
  stamp_wait_timeout          3 -> 2       fewer (cnd-1, cnd-3)
  sampled_resident_reclaimed  1..2 -> 0    inside the control envelope on cnd-1 and
                                           cnd-3; fewer on cnd-2
  present_order_hold          0..1 -> 3    cnd-2 only. A timing counter, and the
                                           same one the parent's gate recorded
                                           moving inside each arm.

Reader decisions recorded rather than hidden:

- Every one of the six runs, control and candidate alike, reports
  `catastrophic=1`. `run-guest.sh` raises it on the presence of
  `stamp_wait_timeout` in the device log, and that condition is standing on this
  rail: the three prior `dc` batteries read it too, controls included (ctl 2, ctl
  2, cnd 4). It is inherited debt that both identified controls reproduce, not a
  candidate failure, and the candidate reports fewer of them than the control.

Verification actually run: cargo fmt --all and --check; clippy -D warnings on all
three main arms (aarch64-apple-darwin backend-metal, host
backend-vulkan,host-window, x86_64-unknown-linux-gnu backend-vulkan,host-window);
the full reims-vgpu suite serially, 2305 passed / 0 failed / 1 ignored.

Not verified:
- No live desktop boot ran this candidate and no visual interaction was
  re-photographed. The 300x300 tiles it stops overwriting were never isolated as
  a photographed symptom; the evidence is the device log and the guest's own
  stride.
- What the guest's four-sample span is supposed to contain is still unknown, and
  is deliberately not guessed here. This commit stops writing the one thing that
  is certainly not it.
- Metal arm cross-compiles only; its tests did not run. No other pathway or rail.
This commit is contained in:
Anees Iqbal committed 2026-08-30 18:52:02 +03:00
1 parent 7540d6ecf9
commit a65348ed34
2 files changed
+185

No files matched your search

+42
View File
@@ -4250,6 +4250,48 @@ fn apply_clear<M: HostMemory + HostOps>(
return false;
};
let c0 = req.colors.first().unwrap_or_else(|| unreachable!());
// A multisample attachment has no single-sample linear publication, and
// this is the first point at which that is knowable: `clear_publish_target`
// above decides from the store action alone, and the sample count arrives
// with the resolved target.
//
// The rule is the one the `StoredAndResolved` arm already states —
// "treating the source as a linear image would write only one sample" — and
// it applies just as much to a plain `MTLStoreActionStore` on a texture
// whose descriptor declares four samples. That arm could not reach this
// case because the store action does not name it.
//
// The guest sizes and strides these allocations for their samples. On rail
// macos-15 the 300x300 four-sample tiles carry `bpr = 4800`, exactly four
// times a 300-wide BGRA8 tight row, against `bpr = 1216` on the
// single-sample surfaces beside them. So writing a single-sample image here
// is not a partial answer: it fills 1200 bytes of every 4800-byte row with
// a solid colour and leaves the rest, in a sample layout this device has
// never established. Refusing leaves the guest the bytes it already had,
// which is what every other refusal on this rail promises.
//
// This narrows the clear rail; it does not close it. A resolve destination
// is single-sample by construction and still publishes, through
// `ClearPublish::Resolved` above.
if c0.sample_count > 1 {
note_clear_dropped(
"clear_multisample_source_not_linear",
att.texture_ref,
&format!(
"samples={} {}x{} bpr={} gva={:#x} mid={} store={} (the guest \
strided this span for its samples; a one-sample image is the \
wrong content for it, not a partial one)",
c0.sample_count,
c0.width,
c0.height,
c0.row_stride,
c0.target_gva,
c0.mapping_id,
att.store_action
),
);
return false;
}
// Format and clear representation are one contract decision. Continuous
// colour keeps the semantic RGBA8 carrier the existing converters consume;
// integer targets carry their own texels, where `1` remains the integer 1.
+143
View File
@@ -5350,3 +5350,146 @@ fn clear_fallback_draw_accounting_is_scoped_to_one_render_stream() {
"a draw that lands in this stream suppresses its destructive fallback"
);
}
/// A multisample colour attachment has no single-sample linear publication.
///
/// # The contract
///
/// On rail macos-15 the guest renders 300x300 tiles into type-2/3 linear
/// textures whose descriptors declare `sampleCount = 4`, and it sizes those
/// allocations to match: the boot's `gva_view_fragmented ... pages=352` at two
/// separate targets fixes `height * bpr` inside `(351, 352] * 4096`, which for
/// `height = 300` admits one plausible stride — `4800`, exactly four times the
/// single-sample tight row of a 300-wide BGRA8 texture. Ordinary single-sample
/// 300x300 surfaces in the same boot report `bpr=1216`.
///
/// So the guest strided that span for four samples per pixel, and this device
/// has never established what the samples' layout inside it is. A single-sample
/// image written there is not a partial answer, it is the wrong content: it
/// fills 1200 of every 4800 bytes and leaves the rest.
///
/// `apply_clear`'s sibling arm already states the rule for
/// `StoreAndMultisampleResolve` — "treating the source as a linear image would
/// write only one sample" — and could not apply it to a plain `Store`, because
/// `clear_publish_target` decides from the store action alone and never sees a
/// sample count.
///
/// # What this guards
///
/// The clear fallback is reached exactly when the draw's Store was refused, and
/// on this rail that refusal is `read_target_multisample_image`, which is
/// itself correct. What followed it was a solid beige or near-black 300x300
/// clear written over the guest's four-sample pages, twice a boot.
#[test]
fn a_multisample_linear_target_keeps_its_guest_bytes_instead_of_a_one_sample_clear() {
use crate::contract::pixel_format::MTL_FORMAT_BGRA8_UNORM;
use crate::runtime::decode::resource::{
list_object_entry_offset, LINEAR_DESC_HANDLE, LINEAR_DESC_SIZE, OBJECT_LIST_ENTRY_LEN,
OBJECT_TYPE_TEXTURE, TEXTURE_DESC_BASE_LEN, TEXTURE_DESC_HEIGHT, TEXTURE_DESC_PIXEL_FORMAT,
TEXTURE_DESC_ROW_STRIDE, TEXTURE_DESC_SAMPLE_COUNT, TEXTURE_DESC_TRAILER_HEIGHT,
TEXTURE_DESC_TRAILER_WIDTH, TEXTURE_DESC_WIDTH,
};
use crate::runtime::gva_mem::{
define_task_pages_arm64e, read_task_gva_by_id, write_task_gva_arm64e,
};
// Both arms of one comparison: the same texture, the same clear, differing
// only in the sample count its descriptor declares. Single-sample must keep
// publishing — this narrows the clear rail, it does not close it.
let published = |sample_count: u16| -> (bool, Vec<u8>) {
let mut state = DeviceState::new(DeviceId(1), PAGE_SHIFT_ARM64E);
let mut host = FakeHost::new();
define_task_pages_arm64e(&mut host, &mut state, 4, 16);
assert!(state.set_object_list(1, 0, 256));
// Four samples per pixel in the stride, as the rail's own span
// arithmetic gives it: `bpr = samples * width * 4`.
let (texture_ref, handle, width, height) = (200u32, 8u32, 2u32, 2u32);
let row_stride = u32::from(sample_count) * width * 4;
let target_gva = (handle as u64) << PAGE_SHIFT_ARM64E;
let mut pages = vec![0xcc; (row_stride * height) as usize];
write_task_gva_arm64e(&mut host, &state.tasks[1], target_gva, &pages);
let mut desc = vec![0u8; TEXTURE_DESC_BASE_LEN];
st64(
&mut desc[LINEAR_DESC_SIZE..],
u64::from(row_stride) * u64::from(height),
);
st32(&mut desc[LINEAR_DESC_HANDLE..], handle);
st32(&mut desc[TEXTURE_DESC_ROW_STRIDE..], row_stride);
st32(&mut desc[TEXTURE_DESC_WIDTH..], width);
st32(&mut desc[TEXTURE_DESC_HEIGHT..], height);
st16(
&mut desc[TEXTURE_DESC_PIXEL_FORMAT..],
MTL_FORMAT_BGRA8_UNORM,
);
// The trailer states the extent a second time, and the decode returns
// the sample count only when the two statements agree.
st32(&mut desc[TEXTURE_DESC_TRAILER_WIDTH..], width);
st32(&mut desc[TEXTURE_DESC_TRAILER_HEIGHT..], height);
st16(&mut desc[TEXTURE_DESC_SAMPLE_COUNT..], sample_count);
let desc_gva = 0x280u64;
write_task_gva_arm64e(&mut host, &state.tasks[1], desc_gva, &desc);
let entry_off = list_object_entry_offset(texture_ref, 256).expect("object-list ref");
let mut entry = [0u8; OBJECT_LIST_ENTRY_LEN];
st32(
&mut entry,
(OBJECT_TYPE_TEXTURE as u32) | ((desc.len() as u32) << 8),
);
entry[4..12].copy_from_slice(&desc_gva.to_le_bytes());
write_task_gva_arm64e(&mut host, &state.tasks[1], entry_off, &entry);
let mut acc = StreamAccum::default();
acc.clears.push(ColorAttachment {
texture_ref,
load_action: MTL_LOAD_ACTION_CLEAR,
store_action: MTL_STORE_ACTION_STORE,
clear_color: [1.0, 1.0, 1.0, 1.0],
..Default::default()
});
let mut out = ExecResult::default();
finish_stream(&mut state, &mut host, 1, &mut out, &acc);
read_task_gva_by_id(
&host,
&state.tasks,
1,
target_gva,
&mut pages,
PAGE_SHIFT_ARM64E,
)
.expect("read the target's guest pages");
(out.clears_applied == 1, pages)
};
let (one_published, one_pages) = published(1);
assert!(
one_published,
"a single-sample linear Store still publishes its clear"
);
assert!(
one_pages.contains(&0xff),
"the single-sample arm must actually have written the clear, or the \
multisample arm below proves nothing"
);
let (four_published, four_pages) = published(4);
assert!(
!four_published,
"a four-sample attachment has no single-sample linear publication"
);
assert!(
four_pages.iter().all(|&byte| byte == 0xcc),
"the guest's four-sample span must be left exactly as it was found, not \
overwritten with one sample's worth of clear colour"
);
let log = std::fs::read_to_string(crate::observe::fail_log_path()).expect("fail log");
assert!(
log.lines().any(|line| {
line.contains("reason=clear_multisample_source_not_linear")
&& line.contains("samples=4")
}),
"the refused publication must be fail-visible: a clear this device drops \
silently is the one outcome the ground rules forbid"
);
}