From 24a5e47b5b397be217b1b56522b166925f165749 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 3 Sep 2026 21:30:50 +0300 Subject: [PATCH 1/5] usage: the compute rail publishes too, and a wildcard stops hiding six kinds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The producer the access-mode row named as the half that was missing: "the compute rail, which publishes nothing yet". `binding_usage::compute` turns a translated kernel's reflection into a `PublishedUsage`, and the compute pre-scan publishes it. **The pre-scan and not the dispatch.** The walk asks for a pipeline's reflection once, at admission, so a transaction that leases a kernel before its usage lands carries `Unknown` for every slot for its whole life. `compute_exec::vulkan` runs after the transaction is released and is therefore too late to be the answer it was admitted on. `preflight_compute_translations` already holds the AIR and runs before admission readies the packet's leases, so it is the earliest site there is — earlier, in fact, than the render rail's. Three things had to move for that to hold: `declare_pipeline` now runs *before* the rail pre-scans. `publish_usage` refuses a pipeline the table does not hold, so publishing from the pre-scan would have been declined on exactly the packet that first builds the kernel. The step is the guest's own fact and the walk's own list; taking it earlier states the same thing at the first moment it is known. `PipelineTable::usage_published` is the memo, because the pre-scan reaches every dispatch of every packet and enumerating a binding set allocates. It is the model's record rather than a set beside the rail: `withdraw`, `refuse`, `retire`, `device_lost` and `compact` all drop the published usage, and a rail-side memo would go on claiming a pipeline was covered after its answer had been thrown away. **The wildcard was hiding six kinds.** The first driven boot came back with `binding_usage_unknown_kind=48`, and `_ => UnknownKind` could not say which kind those were. The pinned translator declares sixteen `ResourceKind` variants against the ten this module named. Reading each settled them: - `SynthesizedNullTexture` / `SynthesizedReadSampler` sit at the first binding in their band that no Metal resource claims, so their index cannot be a guest slot and skipping them is exactly true. These were the 48. - `EmbeddedArgBufferBuffer` and `BufferAddressTable` are invented indices, like `EmbeddedArgBufferTexture` — `SyntheticIndex`. - `PrimitiveAccelerationStructure`, `VisibleFunctionTable` and `IntersectionFunctionTable` occupy a buffer index whose guest-side resource class this mapping does not model — a new `AuthoredObject`. - `KernelStageInput` gets its own reason, because it is the one with a known way to close it. It is the vertex fetch's problem in compute form: Metal supplies stage-input data through buffer-table slots the *pipeline descriptor* selects, while the reflection's index for the kind is allocated as the lowest slot the kernel's own buffers leave free. Publishing would call the guest's real slot unreferenced and delete a read edge, so the stage refuses whole. The compute stage-input descriptor is what closes it, and this device decodes it already. With every variant named the `_` arm is unreachable, so it and `UnknownKind` are deleted. A translator that grows a kind now fails to compile here rather than quietly answering `Unknown` for it. Driven macos-15 x86/Vulkan boot, `reims-vgpu-pci`, three rounds to `workload done`, **185 434 draws**, zero FAIL across 39 927 lines, 25 distinct refusal reasons against the previous boot's 24: access_mode_unknown 11 632 access_mode_read 332 370 access_mode_write 10 439 access_mode_read_write 12 692 3.2 % unknown, against 3.9 % when only the render rail published. Every refusal this mapping can report reads zero — all four `binding_usage_*` — with `pipeline_usage_published=154`, `pipeline_usage_unnamed=0`, `compute_usage_translation_lost=0` and `compute_usage_already_published=190`, which is the memo firing. Zero refusals with nothing unnamed is what says the reading is the whole population rather than a sample. Co-Authored-By: Claude Opus 5 (1M context) --- crates/reims-vgpu-core/src/pipeline.rs | 70 ++++++ .../src/backend/vulkan/binding_usage.rs | 205 ++++++++++++++++-- crates/reims-vgpu/src/dead/README.md | 2 +- crates/reims-vgpu/src/model/state.rs | 18 ++ crates/reims-vgpu/src/runtime/drain/mod.rs | 20 +- crates/reims-vgpu/src/runtime/exec/vulkan.rs | 71 +++++- 6 files changed, 362 insertions(+), 24 deletions(-) diff --git a/crates/reims-vgpu-core/src/pipeline.rs b/crates/reims-vgpu-core/src/pipeline.rs index de99f47e1..461e0f7f7 100644 --- a/crates/reims-vgpu-core/src/pipeline.rs +++ b/crates/reims-vgpu-core/src/pipeline.rs @@ -580,6 +580,25 @@ impl PipelineTable { self.pipelines.get(&id) } + /// Whether an executor has already said what this pipeline's shaders do + /// with each bound slot. + /// + /// The read side of [`Self::publish_usage`] as a *question*, for a rail + /// whose pre-scan reaches the same pipeline once per packet and must build + /// its tables once per build. Enumerating a shader's binding set allocates, + /// and a rail-side "already done" set would be a second record of a fact + /// this table already holds — one that a withdrawal or a retirement could + /// leave disagreeing with it. Asking here cannot disagree. + /// + /// `false` for a pipeline this table does not hold, which is the answer + /// that makes the caller try: an executor that publishes before the + /// pipeline is declared is refused by [`Self::publish_usage`], and the next + /// pass is what lands it. + #[must_use] + pub fn usage_published(&self, id: ResourceId) -> bool { + self.usage.contains_key(&id) + } + /// Advance a pipeline. Returns whether the step was legal and taken. /// /// An illegal step is refused rather than applied, and a caller that has to @@ -1104,6 +1123,57 @@ mod tests { assert_eq!(t.census().leases_ready, 1); } + /// The memo a rail's pre-scan skips on is the same record the answer lands + /// in, so it cannot outlive the answer. + /// + /// This is why the question is the table's and not the rail's. A pre-scan + /// reaches the same pipeline once per packet and must enumerate its binding + /// set once per *build*; a set kept beside the rail would go on saying + /// "covered" after a withdrawal threw the published usage away, and the + /// rebuilt shader's usage would never be published at all. + /// + /// Also the undeclared case, which is what makes the gate safe to try + /// early: an executor holding a translation before the table holds the + /// pipeline gets `false` from both doors, so nothing is recorded and the + /// next pass publishes. + #[test] + fn the_published_usage_memo_is_dropped_by_everything_that_drops_the_usage() { + let mut t = PipelineTable::new(); + let usage = || PublishedUsage::compute(BindingUsage::new(vec![], vec![])); + + assert!( + !t.usage_published(id(1)), + "nothing is published for a pipeline this table does not hold" + ); + assert!( + !t.publish_usage(id(1), usage()), + "and publishing into one is refused rather than recorded" + ); + assert!(!t.usage_published(id(1))); + + assert!(t.declare(id(1), GEN)); + assert!(t.advance(id(1), PipelineState::Translating)); + assert!(t.advance(id(1), PipelineState::Compiling)); + assert!(t.advance(id(1), PipelineState::Ready)); + assert!(t.publish_usage(id(1), usage())); + assert!(t.usage_published(id(1)), "the pass that lands it"); + + assert!(t.withdraw(id(1))); + assert!( + !t.usage_published(id(1)), + "the rebuild's usage is not the previous build's, so the memo must let the rail publish again" + ); + + assert!(t.advance(id(1), PipelineState::Compiling)); + assert!(t.advance(id(1), PipelineState::Ready)); + assert!(t.publish_usage(id(1), usage())); + assert!(t.retire(id(1))); + assert!( + !t.usage_published(id(1)), + "a retired pipeline holds no answer, and a rail that thought it did would never publish for the name that replaces it" + ); + } + /// A pipeline the executor stopped holding a translation for goes back to /// waiting, and a transaction binding it waits again. /// diff --git a/crates/reims-vgpu/src/backend/vulkan/binding_usage.rs b/crates/reims-vgpu/src/backend/vulkan/binding_usage.rs index 7efcdb257..ca071584a 100644 --- a/crates/reims-vgpu/src/backend/vulkan/binding_usage.rs +++ b/crates/reims-vgpu/src/backend/vulkan/binding_usage.rs @@ -19,8 +19,11 @@ //! silently delete the participations it left out, and a deleted participation //! is a missing hazard edge rather than a coarser one. //! -//! That is why every unhandled case here refuses the stage rather than skipping -//! the binding. +//! That is why a binding this mapping cannot place refuses the stage rather +//! than being skipped. The only bindings left out are the ones whose index +//! cannot be a guest slot at all — sampler state, a framebuffer fetch, and the +//! translator's two band placeholders — where leaving them out says nothing +//! about a slot the guest can spell. //! //! # The vertex fetch is not in the reflection, and it still reads //! @@ -36,6 +39,15 @@ //! union. A slot in it that the reflection did not describe is a read, because //! the fetch reads it; a slot both describe keeps the shader's answer, which is //! never weaker. +//! +//! # The compute fetch has the same hole and no descriptor to fill it +//! +//! A kernel `[[stage_in]]` is the same fixed-function read, and the compute +//! pipeline's stage-input descriptor is the vertex descriptor's twin — but it +//! does not reach here, and the reflection's index for the kind is one the +//! translator invented rather than one the guest spelled. So a kernel that +//! declares one refuses instead of publishing a table missing the slot the +//! guest actually bound. See [`UnpublishableStage::KernelStageInput`]. use reims_vgpu_core::access::AccessMode; use reims_vgpu_core::pipeline::{BindingUsage, PublishedUsage}; @@ -54,9 +66,31 @@ pub(crate) enum UnpublishableStage { /// A binding whose Metal index is synthesized rather than the guest's, so /// it cannot be placed in a table the guest's slot numbers index. SyntheticIndex, - /// A binding kind this mapping has no row for. New kinds arrive with the - /// translator; the stage stays conservative until one is written. - UnknownKind, + /// A kernel `[[stage_in]]` attribute array: the fixed-function compute + /// fetch, and the compute form of the problem the vertex stage solves with + /// [`VertexBindPlan::attribute_slots`]. + /// + /// **The contract term this is missing.** Metal supplies stage-input data + /// through ordinary buffer-table slots the *pipeline descriptor* selects, + /// and the reflection cannot name those: its `metal_index` for this kind is + /// a slot allocated as the lowest index the kernel's own declared buffers + /// do not occupy, which is a translator ABI decision and not a number the + /// guest ever spelled. So the guest binds a buffer the dispatch reads and + /// the table has no row that names it. + /// + /// Publishing anyway would call that slot unreferenced and delete a read + /// edge, so the stage is refused whole. What closes it is the compute + /// pipeline's stage-input descriptor — the compute twin of the vertex + /// descriptor — which this device decodes for the dispatch and does not + /// hand to this mapping. + KernelStageInput, + /// An authored acceleration structure or function table bound as an object + /// rather than as bytes this device placed. + /// + /// It occupies a buffer index, so leaving it out of the table would read as + /// unreferenced — and this mapping has no basis for saying that about a + /// binding whose guest-side resource class it does not model. + AuthoredObject, /// A slot number that does not fit the table this builds. The guest may /// bind any slot — nothing refuses a high one — so this is a real answer /// and not an impossibility. @@ -67,7 +101,8 @@ impl UnpublishableStage { pub(crate) const fn slug(self) -> &'static str { match self { Self::SyntheticIndex => "binding_usage_synthetic_index", - Self::UnknownKind => "binding_usage_unknown_kind", + Self::KernelStageInput => "binding_usage_kernel_stage_in", + Self::AuthoredObject => "binding_usage_authored_object", Self::SlotTooHigh => "binding_usage_slot_too_high", } } @@ -182,16 +217,37 @@ fn stage_tables(reflection: &ShaderReflection) -> Result {} - ResourceKind::EmbeddedArgBufferTexture => { - return Err(UnpublishableStage::SyntheticIndex) - } - _ => return Err(UnpublishableStage::UnknownKind), + // Bind no memory the footprint is about, and none of them can + // shadow a guest slot. `Sampler` and `StaticSampler` are sampler + // state; `ColorInput` is a framebuffer fetch the pass already + // orders. The two synthesized placeholders sit at the first binding + // in their band that no Metal resource claims, which is by + // construction an index the guest did not bind — so leaving all + // five out of both tables says nothing about a slot the guest can + // spell. + ResourceKind::Sampler + | ResourceKind::StaticSampler + | ResourceKind::ColorInput + | ResourceKind::SynthesizedNullTexture + | ResourceKind::SynthesizedReadSampler => {} + // Indices the translator invented. Placing one would answer for + // whatever the guest bound at the same number, and the answer would + // be *narrower* than `Unknown`, which is the direction that loses + // edges. + ResourceKind::EmbeddedArgBufferTexture + | ResourceKind::EmbeddedArgBufferBuffer + | ResourceKind::BufferAddressTable => return Err(UnpublishableStage::SyntheticIndex), + ResourceKind::KernelStageInput => return Err(UnpublishableStage::KernelStageInput), + ResourceKind::PrimitiveAccelerationStructure + | ResourceKind::VisibleFunctionTable + | ResourceKind::IntersectionFunctionTable => { + return Err(UnpublishableStage::AuthoredObject) + } // No wildcard, on purpose. `ResourceKind` is exhaustively named + // above, so a translator that grows a kind fails to *compile* here + // rather than quietly answering `Unknown` for it — which is the + // difference between a decision this mapping made and one it never + // noticed it was making. The compiler is the only reader that can + // catch that at the moment the kind arrives. } } Ok((buffers, textures)) @@ -244,6 +300,18 @@ pub(crate) fn render( (PublishedUsage::render(v.ok(), f.ok()), refusals) } +/// What this rail can say about one compute pipeline, or why it cannot. +/// +/// One stage and no widening: a dispatch has no fixed-function fetch, so the +/// kernel's reflection is the whole of what it reads and writes and there is no +/// second table to union in. Whole or nothing for the reason the module doc +/// gives, which is why this is a `Result` rather than the render arm's pair — +/// a compute pipeline with a refused stage publishes nothing at all, and +/// nothing is what leaves the dispatch's slots `Unknown`. +pub(crate) fn compute(kernel: &ShaderReflection) -> Result { + stage_usage(kernel).map(PublishedUsage::compute) +} + #[cfg(test)] mod tests { use super::*; @@ -376,4 +444,109 @@ mod tests { ); assert_eq!(usage.buffer(1), None, "named by neither"); } + + /// A kernel publishes its own stage and neither render one. + /// + /// The distinction the `PublishedUsage` shape exists for: asking a compute + /// pipeline for its vertex stage must answer "not published" rather than + /// "published, references nothing", because the second would delete every + /// participation a mis-staged reader asked about. + #[test] + fn a_kernel_publishes_the_compute_stage_and_leaves_the_render_stages_unpublished() { + use reims_vgpu_protocol::render::ShaderStage; + + let r = reflection(vec![ + binding(ResourceKind::Buffer, 0, Some(ResourceAccess::ReadOnly)), + binding( + ResourceKind::StorageImage, + 2, + Some(ResourceAccess::WriteOnly), + ), + binding(ResourceKind::ThreadgroupBuffer, 4, None), + ]); + let published = compute(&r).expect("every kind here has a row"); + let kernel = published + .stage(None) + .expect("the compute stage is the one this publishes"); + assert_eq!(kernel.buffer(0), Some(AccessMode::Read)); + assert_eq!( + kernel.buffer(4), + Some(AccessMode::Unknown), + "threadgroup memory occupies a buffer index and binds no guest resource, so it is declared rather than left to read as unreferenced" + ); + assert_eq!(kernel.texture(2), Some(AccessMode::Write)); + assert_eq!(kernel.texture(0), None, "no binding names it"); + assert!( + published.stage(Some(ShaderStage::Vertex)).is_none() + && published.stage(Some(ShaderStage::Fragment)).is_none(), + "a dispatch has no render stages, and 'unpublished' is the true answer rather than an empty table" + ); + } + + /// A kernel this mapping cannot enumerate whole publishes nothing. + /// + /// One stage means there is no partial answer to keep: the render arm can + /// publish a vertex table while the fragment one refuses, because each is + /// exactly true on its own. A refused kernel leaves the dispatch's slots + /// `Unknown`, which is what a table stopping short would silently not do. + #[test] + fn a_kernel_with_an_unenumerable_binding_publishes_nothing_at_all() { + let r = reflection(vec![ + binding(ResourceKind::Buffer, 0, Some(ResourceAccess::ReadOnly)), + binding( + ResourceKind::EmbeddedArgBufferTexture, + 1, + Some(ResourceAccess::Sampled), + ), + ]); + assert_eq!(compute(&r), Err(UnpublishableStage::SyntheticIndex)); + } + + /// The compute fixed-function fetch refuses the stage, and is told apart + /// from every other synthetic index. + /// + /// It is the vertex fetch's problem with no vertex descriptor to solve it: + /// the guest binds the stage-input buffer at a slot its *pipeline* + /// descriptor names, while the reflection's index for the kind is the + /// lowest one the kernel's own buffers leave free. Publishing would call + /// the guest's slot unreferenced and delete a read edge, so this refuses — + /// and it carries its own reason because it is the one of these with a + /// known way to close it. + #[test] + fn a_kernel_stage_in_refuses_the_stage_under_its_own_reason() { + let r = reflection(vec![ + binding(ResourceKind::Buffer, 1, Some(ResourceAccess::ReadOnly)), + binding(ResourceKind::KernelStageInput, 0, None), + ]); + assert_eq!(compute(&r), Err(UnpublishableStage::KernelStageInput)); + assert_eq!( + UnpublishableStage::KernelStageInput.slug(), + "binding_usage_kernel_stage_in" + ); + } + + /// The translator's two placeholders are skipped, not refused. + /// + /// Each sits at the first binding in its band that no Metal resource + /// claims, so its index is by construction one the guest did not bind. + /// Leaving them out of both tables says nothing about a slot the guest can + /// spell, and refusing for them would cost every other slot of the stage + /// its answer for nothing. + #[test] + fn the_translators_placeholders_cost_the_stage_nothing() { + let r = reflection(vec![ + binding(ResourceKind::Buffer, 0, Some(ResourceAccess::ReadOnly)), + binding(ResourceKind::SynthesizedNullTexture, 7, None), + binding(ResourceKind::SynthesizedReadSampler, 7, None), + ]); + let published = compute(&r).expect("a placeholder is not a refusal"); + let kernel = published.stage(None).expect("the compute stage"); + assert_eq!(kernel.buffer(0), Some(AccessMode::Read)); + assert_eq!( + kernel.texture(7), + None, + "the placeholder binds no guest texture, and its band index is one \ + no Metal texture claims" + ); + } } diff --git a/crates/reims-vgpu/src/dead/README.md b/crates/reims-vgpu/src/dead/README.md index b47413663..e2e3cb5ab 100644 --- a/crates/reims-vgpu/src/dead/README.md +++ b/crates/reims-vgpu/src/dead/README.md @@ -162,7 +162,7 @@ the access-mode and framing censuses — or off a named off-VM gate. | Re-scans of already resolved EXEC bytes | 0 | **met** | `exec_stream_framed=18 421` against `exec_streams_loaded=18 421` — a ratio of exactly one, on the driven macos-15 boot in the last live-validation row. `walk_stream` is the crate's one framing site and it is the counted one. Every submission on that boot carried a single stream (`exec_cmdbufs_1=18 421`), so the boot cannot tell "once per stream" from "once per submission"; fn `a_submission_frames_each_stream_once_and_preflight_frames_none` is what does, on two streams, and it also holds the plan step to framing none — `preflight_submission` answers from `ExecWork` rather than from the packet's bytes. | | Repeated transfers for one range, version and direction | 0 | **met for buffers, unmeasured for images** | `buffer_bind_reuses=304 017` and `buffer_index_bind_reuses=892`: every one is a bind served from a copy the command buffer already held rather than a second transfer of the same bytes. The image side is not the same claim — `sampled_reuploads=45` at 15.3 MB are lawful, since the content version moved, but nothing here separates a lawful reupload from a repeated one. | | Pipeline compiles on a Ready pipeline draw | 0 | **met** | fn `warm_identical_dispatch_zero_creates_and_allocs` and the `creates`/`allocs` deltas the batch suite asserts at zero on a warm draw. | -| Supported operations reaching an unknown access-mode fallback | 0 | **not met, 81 % → 3.9 %** | Was `access_mode_unknown=342 987` against 81 116 known — 81 % of every access the dependency graph ordered against — because `ExecWork::footprint_into` passed `None` for the pipeline's `BindingUsage` and nothing in the tree constructed one. Since the render rail publishes its translated shaders' reflection, the driven boot reads **`unknown=10 686` against `read=246 093`, `write=6 886`, `read_write=7 492`**. Two things moved at once and they are different: 150 000 participations stopped existing at all (a slot the shader does not reference contributes nothing), and of the ones that remain 96 % now name a direction. What is left is a device buffer whose read-versus-write the translator's facade does not carry — it needs IR dataflow — plus the compute rail, which publishes nothing yet. | +| Supported operations reaching an unknown access-mode fallback | 0 | **not met, 81 % → 3.2 %** | Was `access_mode_unknown=342 987` against 81 116 known — 81 % of every access the dependency graph ordered against — because `ExecWork::footprint_into` passed `None` for the pipeline's `BindingUsage` and nothing in the tree constructed one. Both rails now publish their translated shaders' reflection, and a driven macos-15 boot reads **`unknown=11 632` against `read=332 370`, `write=10 439`, `read_write=12 692`** over 185 434 draws — **3.2 %**, against 3.9 % when only the render rail published. Two things moved when the first half landed and they are different: 150 000 participations stopped existing at all (a slot the shader does not reference contributes nothing), and of the ones that remain 97 % now name a direction. Every refusal this mapping can report reads **zero** on that boot — `binding_usage_{synthetic_index,kernel_stage_in,authored_object,slot_too_high}` — with `pipeline_usage_published=154` and `pipeline_usage_unnamed=0`, so the reading is the whole population and not a sample. What is left is a device buffer whose read-versus-write the translator's facade does not carry, which needs IR dataflow. fn `a_kernel_publishes_the_compute_stage_and_leaves_the_render_stages_unpublished`, fn `a_kernel_stage_in_refuses_the_stage_under_its_own_reason`, fn `the_translators_placeholders_cost_the_stage_nothing`, fn `the_published_usage_memo_is_dropped_by_everything_that_drops_the_usage`. | | Supported operations reaching an unknown stage fallback | 0 | **not measurable on the live path** | The instrument is `reims_vgpu_vulkan::barrier::BarrierPlan::unmapped_bits`, which reports the stage bits that had no row and were therefore widened to `ALL_COMMANDS`. The engine does not use that module — it builds its own barriers — so nothing on a live path can report it. This is a cutover item, not a missing counter. | **Do not read an unmeasured row as a zero.** The plan's own argument for this diff --git a/crates/reims-vgpu/src/model/state.rs b/crates/reims-vgpu/src/model/state.rs index a508e84b6..ffb1f9ff3 100644 --- a/crates/reims-vgpu/src/model/state.rs +++ b/crates/reims-vgpu/src/model/state.rs @@ -4402,6 +4402,24 @@ impl DeviceState { .publish_usage(pipeline, usage) } + /// Whether an executor has already published this pipeline's reflection. + /// + /// The question a rail asks before building the answer, so the binding + /// tables are enumerated once per build rather than once per packet that + /// dispatches the pipeline. See + /// [`reims_vgpu_core::pipeline::PipelineTable::usage_published`] for why + /// the memo is the model's and not the rail's. + pub fn pipeline_usage_published( + &self, + pipeline: reims_vgpu_core::identity::ResourceId, + ) -> bool { + self.session + .lock() + .expect("session") + .pipelines() + .usage_published(pipeline) + } + /// The published reflections, for the length of one packet's walk. /// /// A guard rather than a per-lookup call, because the walk asks once per diff --git a/crates/reims-vgpu/src/runtime/drain/mod.rs b/crates/reims-vgpu/src/runtime/drain/mod.rs index c4630f676..09fb2ecb1 100644 --- a/crates/reims-vgpu/src/runtime/drain/mod.rs +++ b/crates/reims-vgpu/src/runtime/drain/mod.rs @@ -2233,6 +2233,21 @@ fn admit_and_park( // against a shader that is still translating, which is the // `m2v_translation_pending_at_sync_boundary` loss measured on a driven // macos-15 desktop. + // + // **Declared before the rail pre-scans, not after.** The pre-scan is where + // a rail first holds a translated shader, and publishing what that shader + // reads is refused for a pipeline the table does not yet hold — so + // declaring afterwards would make the model's own stated order (publish, + // then ready) unreachable on the packet that first builds the kernel. The + // step is the guest's fact and the walk's own list; taking it earlier + // states the same thing at the first moment it is known. + for &lease in leases { + note_store_route(if state.declare_pipeline(lease) { + "pipeline_declared" + } else { + "pipeline_declared_already" + }); + } let translating = match (arrived.submission.as_ref(), built.payload.exec()) { (Some(submission), Some(resolved)) => { let mut measured_ns = 0u64; @@ -2247,11 +2262,6 @@ fn admit_and_park( _ => Vec::new(), }; for &lease in leases { - note_store_route(if state.declare_pipeline(lease) { - "pipeline_declared" - } else { - "pipeline_declared_already" - }); if translating.contains(&lease.slot.0) { withdraw_lease(state, lease); } else if translating.is_empty() { diff --git a/crates/reims-vgpu/src/runtime/exec/vulkan.rs b/crates/reims-vgpu/src/runtime/exec/vulkan.rs index 9e68068de..1f0177de5 100644 --- a/crates/reims-vgpu/src/runtime/exec/vulkan.rs +++ b/crates/reims-vgpu/src/runtime/exec/vulkan.rs @@ -147,9 +147,76 @@ pub(crate) fn preflight_compute_translations( PreflightPart::Cache, cache_started.elapsed().as_nanos() as u64, ); - if !cached && !pending.contains(&pipeline_ref) { - pending.push(pipeline_ref); + if !cached { + if !pending.contains(&pipeline_ref) { + pending.push(pipeline_ref); + } + continue; } + publish_kernel_usage(state, host, task_id, pipeline_ref, air, local_size); + } +} + +/// Tell the ordering plane what this kernel does with each bound slot. +/// +/// # Why here, and not where the dispatch runs +/// +/// The walk asks for a pipeline's reflection **once, at admission**, so a +/// transaction that leases a kernel before its usage lands carries +/// [`reims_vgpu_core::access::AccessMode::Unknown`] for every slot it binds for +/// the life of that transaction. The compute rail's other point of contact with +/// a reflection is `compute_exec::vulkan`, which runs after the transaction has +/// been released — too late to be the answer that transaction was admitted on. +/// This pre-scan is the earliest site that holds the AIR, and it runs before +/// admission readies the packet's leases. +/// +/// # Once per build, not once per packet +/// +/// Enumerating a binding set allocates two vectors, and this loop reaches every +/// dispatch of every packet. [`DeviceState::pipeline_usage_published`] is the +/// gate, and it is the model's own record rather than a set kept here: a +/// withdrawal or a retirement drops the published usage, and a rail-side memo +/// would go on claiming the pipeline was covered after the answer had been +/// thrown away. +/// +/// The translation is already cached — the caller has just established that — +/// so the call below is a lock and an `Arc` clone, taken only on the pass that +/// actually publishes. +fn publish_kernel_usage( + state: &DeviceState, + host: &M, + task_id: u32, + pipeline_ref: u32, + air: &[u8], + local_size: [u32; 3], +) { + let Some(name) = crate::runtime::objects::name_resource(state, host, task_id, pipeline_ref) + else { + crate::runtime::drain::note_store_route("pipeline_usage_unnamed"); + return; + }; + if state.pipeline_usage_published(name) { + crate::runtime::drain::note_store_route("compute_usage_already_published"); + return; + } + let Ok(shader) = + crate::runtime::m2v_cache::translate_cached_kernel_reflected(air, local_size, pipeline_ref) + else { + // The entry the caller found cached is gone or failed between the two + // calls. Nothing is owed: the dispatch's own path reports the + // translation failure precisely, and an unpublished kernel is a + // conservative footprint rather than a wrong one. + crate::runtime::drain::note_store_route("compute_usage_translation_lost"); + return; + }; + match crate::backend::vulkan::binding_usage::compute(&shader.reflection) { + Ok(usage) => { + crate::runtime::draw::publish_pipeline_usage(state, host, task_id, pipeline_ref, usage) + } + // A stage that cannot be published leaves the kernel at `Unknown`, + // which costs ordering and never correctness. Counted rather than + // failed, and the count is what says which reason is worth closing. + Err(refusal) => crate::runtime::drain::note_store_route(refusal.slug()), } } From 8eb3f58541b2f97e406cf6418a726da96c511e4d Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 3 Sep 2026 22:12:31 +0300 Subject: [PATCH 2/5] usage: the residue gets a census, and 81 % of it turns out to be one thing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous commit left the access-mode row at 3.2 % and a guess about what was in it. The scoreboard's own argument is that a guess and a measurement look the same from outside, so this measures. `reims_vgpu_core::exec::UsageCensus` is filled at the one place the answer is decided — `EncoderBindings::footprint_into` — and carried on the `ExecWork` beside the accesses it describes, so it cannot report a different walk than the one that ran. Four draw rows, three dispatch rows, and the first pipeline that answered nothing, so the device can ask the table what state that pipeline is in. Two hypotheses died on the first boot. `draw_usage_no_pipeline=0`: the walk always knows which pipeline a draw binds. `draw_usage_one_stage=0`: a pipeline publishes both render stages or neither. What is left is `draw_usage_no_stage=1 241` against `draw_usage_both_stages=72 447`, and the per-slot line names it: **88 of 93 first sightings read `model_pipeline=unleased`**. `unleased` is the table answering "I have never heard of this pipeline", and it is structural rather than a race. `pipeline_leases` is the walk's *own output* — the packet's bytes are what declare the pipeline — so the walk necessarily runs before the declaration it produces, and a pipeline is bound and drawn in the same packet that first names it. Closing that would mean re-walking a parked packet after its pipelines go `Ready`, which is a real option (nothing has executed while it is parked) but changes what an already-admitted ordering position depends on. Not a change to make for 1.7 % of draws without the model saying it is sound. Written down as structural at this seam. `publish_render_usage` moves the render publish into the pre-scan, where compute already publishes. **It bought nothing measurable** — 1 244 to 1 241, which is noise — and it is kept for the four `model_pipeline=ready` sightings rather than for that: a lease the model called `Ready` with no usage published is exactly the hazard `publish_pipeline_usage`'s publish-before-ready rule exists for, and the pre-scan is the only site in front of `ready_lease`, so it is where the rule holds structurally instead of by accident of which site ran first. `pipeline_usage_published` on the model is the single arbiter, so the two sites cannot both enumerate a binding set. Measured cost: preflight 10.5 to 11.4 us/call, 0.50 s over a 422 s boot, unchanged in absolute total. Driven macos-15 x86/Vulkan boots, `reims-vgpu-pci`, three rounds each, `FAIL=0` across 40 663 and 41 449 lines, 25 distinct refusal reasons: unknown=9 579 read=319 318 write=10 221 read_write=13 174 -> 2.7 % against 3.2 % the commit before and 3.9 % render-only. Of the 9 579, about 1 200 are the structural first-packet population and the other **~8 000 are one thing**: a device buffer whose read-versus-write the translator's facade does not carry. It needs IR dataflow over the SPIR-V the rail already holds, which the plan assigns to the executor that compiled the shader. That is the next move, and `dead/README.md` and the journal carry the sketch. Co-Authored-By: Claude Opus 5 (1M context) --- crates/reims-vgpu-core/src/exec.rs | 167 +++++++++++++++++- .../src/backend/vulkan/pipeline_resolve.rs | 60 +++++-- crates/reims-vgpu/src/dead/README.md | 2 +- crates/reims-vgpu/src/runtime/drain/mod.rs | 55 +++++- crates/reims-vgpu/src/runtime/exec/vulkan.rs | 101 +++++++++-- crates/reims-vgpu/src/runtime/ingress.rs | 7 +- 6 files changed, 357 insertions(+), 35 deletions(-) diff --git a/crates/reims-vgpu-core/src/exec.rs b/crates/reims-vgpu-core/src/exec.rs index d5f7725e7..58dc99c43 100644 --- a/crates/reims-vgpu-core/src/exec.rs +++ b/crates/reims-vgpu-core/src/exec.rs @@ -305,6 +305,11 @@ pub struct ExecWork { pub pipeline_leases: Vec, pub prerequisites: Vec, pub arenas: ExecArenas, + /// Why this transaction's bound slots stayed `Unknown`. See + /// [`UsageCensus`]; carried on the work rather than reported from the walk + /// so that the numbers describe exactly the walk whose accesses are beside + /// them. + pub usage_census: UsageCensus, } impl ExecWork { @@ -555,6 +560,8 @@ pub struct ExecBuilder<'u> { /// Scratch [`Self::record`] gathers each operation's participations into, /// so the walk costs no allocation after the first record. participation_scratch: Vec, + /// Why this walk's slots stayed `Unknown`. See [`UsageCensus`]. + usage_census: UsageCensus, } /// The binding state of whichever encoder is open. @@ -615,6 +622,7 @@ impl EncoderBindings { op: &ResolvedOperation, usages: &dyn crate::pipeline::UsageSource, out: &mut Vec, + census: &mut UsageCensus, ) { use reims_vgpu_protocol::render::ShaderStage; match (self, op) { @@ -625,15 +633,18 @@ impl EncoderBindings { // stays `Unknown`, which is what a draw the device cannot name // a shader for deserves. let bound = state.pipeline; - state.footprint_into( - bound.and_then(|id| usages.binding_usage(id, Some(ShaderStage::Vertex))), - bound.and_then(|id| usages.binding_usage(id, Some(ShaderStage::Fragment))), - out, - ); + let vertex = + bound.and_then(|id| usages.binding_usage(id, Some(ShaderStage::Vertex))); + let fragment = + bound.and_then(|id| usages.binding_usage(id, Some(ShaderStage::Fragment))); + census.note_draw(bound, vertex.is_some(), fragment.is_some()); + state.footprint_into(vertex, fragment, out); } (Self::Compute(state), ResolvedOperation::Compute(ComputeOp::Dispatch(_))) => { let bound = state.pipeline; - state.footprint_into(bound.and_then(|id| usages.binding_usage(id, None)), out); + let kernel = bound.and_then(|id| usages.binding_usage(id, None)); + census.note_dispatch(bound, kernel.is_some()); + state.footprint_into(kernel, out); } _ => {} } @@ -720,6 +731,7 @@ impl<'u> ExecBuilder<'u> { arenas: ExecArenas::default(), bindings: EncoderBindings::None, participation_scratch: Vec::new(), + usage_census: UsageCensus::default(), } } @@ -832,7 +844,8 @@ impl<'u> ExecBuilder<'u> { // Gathering only. Whether the encoder has *declared* what it just // answered is settled on the success path below, because everything // between here and there can still refuse the record. - self.bindings.footprint_into(&op, self.usages, &mut parts); + self.bindings + .footprint_into(&op, self.usages, &mut parts, &mut self.usage_census); // Pushed straight onto the transaction's list and rolled back on any // refusal, rather than gathered into a second vector: a record's // accesses are at most a handful and a `Vec` per record would be an @@ -966,10 +979,150 @@ impl<'u> ExecBuilder<'u> { pipeline_leases: core::mem::take(&mut self.pipeline_leases), prerequisites: core::mem::take(&mut self.prerequisites), arenas: core::mem::take(&mut self.arenas), + usage_census: self.usage_census, }) } } +/// Why a bound slot stayed [`crate::access::AccessMode::Unknown`], counted as +/// the walk decides it. +/// +/// # The reading this exists to make possible +/// +/// `Unknown` conflicts with everything, so it is the number the ordering plane +/// is judged on — and a total tells you nothing about what to fix. A draw whose +/// pipeline the walk never saw bound and a draw whose shader the executor could +/// not reflect both contribute every slot they bind, and they have nothing in +/// common: the first is a hole in the walk's own encoder state, the second is a +/// contract term the rail has not recovered. Counting them apart is what says +/// which one the next move is about. +/// +/// Counted at the one place the answer is decided, so it cannot describe a +/// different walk than the one that ran. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct UsageCensus { + /// Draws whose encoder had no pipeline bound at all. Every slot they bind + /// is `Unknown` and no executor could have helped. + pub draws_without_a_pipeline: u32, + /// Draws whose pipeline was bound and published neither stage. + pub draws_with_no_stage_published: u32, + /// Draws whose pipeline published one stage and refused the other. + pub draws_with_one_stage_published: u32, + /// Draws answered by both stages, which is the whole point. + pub draws_with_both_stages_published: u32, + /// Dispatches whose encoder had no pipeline bound. + pub dispatches_without_a_pipeline: u32, + /// Dispatches whose kernel published nothing. + pub dispatches_with_no_stage_published: u32, + /// Dispatches answered by their kernel. + pub dispatches_published: u32, + /// The first pipeline a draw or dispatch found unanswered. + /// + /// A count says how much was lost and never which pipeline lost it, and the + /// two candidate causes — a pipeline whose executor has not published yet, + /// and one whose usage a withdrawal or retirement threw away — are told + /// apart only by asking the table what state that pipeline is in. The name + /// is what lets the device ask. First rather than last, and one rather than + /// a list, because this is a diagnosis and not a population: the walk must + /// not allocate for it. + pub first_unanswered_pipeline: Option, +} + +impl UsageCensus { + fn note_draw(&mut self, bound: Option, vertex: bool, fragment: bool) { + let stages = usize::from(vertex) + usize::from(fragment); + let counter = match (bound, stages) { + (None, _) => &mut self.draws_without_a_pipeline, + (Some(_), 0) => &mut self.draws_with_no_stage_published, + (Some(_), 1) => &mut self.draws_with_one_stage_published, + (Some(_), _) => &mut self.draws_with_both_stages_published, + }; + *counter = counter.saturating_add(1); + self.note_unanswered(bound, stages == 0); + } + + fn note_dispatch(&mut self, bound: Option, kernel: bool) { + let counter = match (bound, kernel) { + (None, _) => &mut self.dispatches_without_a_pipeline, + (Some(_), false) => &mut self.dispatches_with_no_stage_published, + (Some(_), true) => &mut self.dispatches_published, + }; + *counter = counter.saturating_add(1); + self.note_unanswered(bound, !kernel); + } + + /// Keep the first pipeline that answered nothing, and only that one. + fn note_unanswered(&mut self, bound: Option, nothing_published: bool) { + if let (Some(id), true, None) = (bound, nothing_published, self.first_unanswered_pipeline) { + self.first_unanswered_pipeline = Some(id); + } + } +} + +#[cfg(test)] +mod usage_census_tests { + use super::*; + + /// The four draw outcomes are counted apart, because they name four + /// different next moves. + #[test] + fn the_reason_a_draws_slots_stayed_unknown_is_counted_and_not_summed() { + let id = ResourceId { + slot: crate::identity::ObjectListRef(9), + generation: crate::identity::SlotGeneration::default(), + }; + let mut c = UsageCensus::default(); + c.note_draw(None, false, false); + c.note_draw(Some(id), false, false); + c.note_draw(Some(id), true, false); + c.note_draw(Some(id), false, true); + c.note_draw(Some(id), true, true); + assert_eq!( + c, + UsageCensus { + draws_without_a_pipeline: 1, + draws_with_no_stage_published: 1, + draws_with_one_stage_published: 2, + draws_with_both_stages_published: 1, + first_unanswered_pipeline: Some(id), + ..UsageCensus::default() + }, + "one stage published is one row whichever stage it was: the pair \ + says how much of the draw was answered, and which half is the \ + rail's own refusal census" + ); + } + + /// A dispatch has one stage, so "published" and "no stage" are the whole + /// answer, and a kernel can never be half-answered. + #[test] + fn a_dispatch_is_answered_or_not_and_never_half() { + let id = ResourceId { + slot: crate::identity::ObjectListRef(4), + generation: crate::identity::SlotGeneration::default(), + }; + let mut c = UsageCensus::default(); + c.note_dispatch(None, false); + c.note_dispatch(Some(id), false); + c.note_dispatch(Some(id), true); + assert_eq!( + c, + UsageCensus { + dispatches_without_a_pipeline: 1, + dispatches_with_no_stage_published: 1, + dispatches_published: 1, + first_unanswered_pipeline: Some(id), + ..UsageCensus::default() + } + ); + assert_eq!( + c.draws_without_a_pipeline, 0, + "a dispatch never lands in a draw's row; the two rails are read \ + against different denominators" + ); + } +} + /// Which rail a resolved operation's records are read on, when its class /// belongs to exactly one. /// diff --git a/crates/reims-vgpu/src/backend/vulkan/pipeline_resolve.rs b/crates/reims-vgpu/src/backend/vulkan/pipeline_resolve.rs index 0979c06fd..a31013232 100644 --- a/crates/reims-vgpu/src/backend/vulkan/pipeline_resolve.rs +++ b/crates/reims-vgpu/src/backend/vulkan/pipeline_resolve.rs @@ -98,7 +98,7 @@ pub struct VertexBindPlan { } impl VertexBindPlan { - fn build(desc: &RenderPipelineDescriptor) -> Self { + pub(crate) fn build(desc: &RenderPipelineDescriptor) -> Self { let mut constant_step: Vec = desc .vertex_attributes .iter() @@ -498,6 +498,42 @@ fn resolve_uncached( }) } +/// The publish half of [`ready`], skipped when the pre-scan already answered. +/// +/// Split out so the gate and the work are one statement: a caller that checked +/// the gate and then built the tables anyway would pay for them twice, and a +/// caller that built them and let the model refuse the write would pay for them +/// on every resolve. +fn publish_usage_if_unpublished( + state: &DeviceState, + host: &M, + task_id: u32, + pipeline_ref: u32, + resolved: &ResolvedRenderPipeline, +) { + let Some(name) = crate::runtime::objects::name_resource(state, host, task_id, pipeline_ref) + else { + note_store_route("pipeline_usage_unnamed"); + return; + }; + if state.pipeline_usage_published(name) { + note_store_route("render_usage_already_published"); + return; + } + let (usage, refusals) = crate::backend::vulkan::binding_usage::render( + &resolved.vertex.reflection, + &resolved.bind_plan, + &resolved.fragment.reflection, + ); + for refusal in refusals.into_iter().flatten() { + // A stage that cannot be published is a stage left at `Unknown`, which + // costs ordering and never correctness — so it is counted rather than + // failed, and the count is what says which reason is worth closing. + note_store_route(refusal.slug()); + } + crate::runtime::draw::publish_pipeline_usage(state, host, task_id, pipeline_ref, usage); +} + /// Tell the ordering plane this pipeline is usable, which releases the exec /// transactions parked on its lease. /// @@ -508,6 +544,14 @@ fn resolve_uncached( /// transaction lease this pipeline, and the walk asks for the reflection once /// at admission and never again. So a lease taken between the two would carry /// a footprint that stays `Unknown` for the life of that transaction. +/// +/// **This is the later of the two publish sites, and the fallback.** +/// `runtime::exec::vulkan::publish_render_usage` publishes from the pre-scan, +/// which runs before admission readies the lease and is therefore in front of +/// the draw that would otherwise miss it. This site is what answers on a path +/// with no pre-scan — the memo-off ablation, and a direct resolve. The model's +/// `pipeline_usage_published` is the single arbiter, so the pipeline's binding +/// set is enumerated once whichever site reaches it first. fn ready( state: &DeviceState, host: &M, @@ -515,19 +559,7 @@ fn ready( pipeline_ref: u32, resolved: &ResolvedRenderPipeline, ) { - let (usage, refusals) = crate::backend::vulkan::binding_usage::render( - &resolved.vertex.reflection, - &resolved.bind_plan, - &resolved.fragment.reflection, - ); - for refusal in refusals.into_iter().flatten() { - // A stage that cannot be published is a stage left at `Unknown`, which - // costs ordering and never correctness — so it is counted rather than - // failed, and the count is what says which of the three reasons is - // worth closing. - note_store_route(refusal.slug()); - } - crate::runtime::draw::publish_pipeline_usage(state, host, task_id, pipeline_ref, usage); + publish_usage_if_unpublished(state, host, task_id, pipeline_ref, resolved); crate::runtime::draw::advance_pipeline( state, host, diff --git a/crates/reims-vgpu/src/dead/README.md b/crates/reims-vgpu/src/dead/README.md index e2e3cb5ab..fe013da5d 100644 --- a/crates/reims-vgpu/src/dead/README.md +++ b/crates/reims-vgpu/src/dead/README.md @@ -162,7 +162,7 @@ the access-mode and framing censuses — or off a named off-VM gate. | Re-scans of already resolved EXEC bytes | 0 | **met** | `exec_stream_framed=18 421` against `exec_streams_loaded=18 421` — a ratio of exactly one, on the driven macos-15 boot in the last live-validation row. `walk_stream` is the crate's one framing site and it is the counted one. Every submission on that boot carried a single stream (`exec_cmdbufs_1=18 421`), so the boot cannot tell "once per stream" from "once per submission"; fn `a_submission_frames_each_stream_once_and_preflight_frames_none` is what does, on two streams, and it also holds the plan step to framing none — `preflight_submission` answers from `ExecWork` rather than from the packet's bytes. | | Repeated transfers for one range, version and direction | 0 | **met for buffers, unmeasured for images** | `buffer_bind_reuses=304 017` and `buffer_index_bind_reuses=892`: every one is a bind served from a copy the command buffer already held rather than a second transfer of the same bytes. The image side is not the same claim — `sampled_reuploads=45` at 15.3 MB are lawful, since the content version moved, but nothing here separates a lawful reupload from a repeated one. | | Pipeline compiles on a Ready pipeline draw | 0 | **met** | fn `warm_identical_dispatch_zero_creates_and_allocs` and the `creates`/`allocs` deltas the batch suite asserts at zero on a warm draw. | -| Supported operations reaching an unknown access-mode fallback | 0 | **not met, 81 % → 3.2 %** | Was `access_mode_unknown=342 987` against 81 116 known — 81 % of every access the dependency graph ordered against — because `ExecWork::footprint_into` passed `None` for the pipeline's `BindingUsage` and nothing in the tree constructed one. Both rails now publish their translated shaders' reflection, and a driven macos-15 boot reads **`unknown=11 632` against `read=332 370`, `write=10 439`, `read_write=12 692`** over 185 434 draws — **3.2 %**, against 3.9 % when only the render rail published. Two things moved when the first half landed and they are different: 150 000 participations stopped existing at all (a slot the shader does not reference contributes nothing), and of the ones that remain 97 % now name a direction. Every refusal this mapping can report reads **zero** on that boot — `binding_usage_{synthetic_index,kernel_stage_in,authored_object,slot_too_high}` — with `pipeline_usage_published=154` and `pipeline_usage_unnamed=0`, so the reading is the whole population and not a sample. What is left is a device buffer whose read-versus-write the translator's facade does not carry, which needs IR dataflow. fn `a_kernel_publishes_the_compute_stage_and_leaves_the_render_stages_unpublished`, fn `a_kernel_stage_in_refuses_the_stage_under_its_own_reason`, fn `the_translators_placeholders_cost_the_stage_nothing`, fn `the_published_usage_memo_is_dropped_by_everything_that_drops_the_usage`. | +| Supported operations reaching an unknown access-mode fallback | 0 | **not met, 81 % → 2.7 %, and the residue is named** | Was `access_mode_unknown=342 987` against 81 116 known — 81 % of every access the dependency graph ordered against — because `ExecWork::footprint_into` passed `None` for the pipeline's `BindingUsage` and nothing in the tree constructed one. Both rails now publish their translated shaders' reflection, and a driven macos-15 boot reads **`unknown=9 579` against `read=319 318`, `write=10 221`, `read_write=13 174`** — **2.7 %**, against 3.9 % when only the render rail published. `UsageCensus` says what is left, and it is two things and not one. **`draw_usage_both_stages=69 407` against `draw_usage_no_pipeline=0` and `draw_usage_one_stage=0`**: the walk always knows which pipeline a draw binds, and a published pipeline is never half-published. **`draw_usage_no_stage=606`** is the first packet to *name* each pipeline — 88 of 93 first sightings read `model_pipeline=unleased`, because the packet's own bytes are what declare the pipeline and the walk that reads them runs before the declaration it produces. That is structural at this seam and not a defect: the walk asks once, at admission, and a footprint taken before the pipeline existed is coarse rather than wrong. Everything else — about 8 000 participations — is a **device buffer whose read-versus-write the translator's facade does not carry**; it needs IR dataflow over the module the rail already holds, and that is the next move on this row. Every refusal this mapping can report reads zero on that boot. fn `a_kernel_publishes_the_compute_stage_and_leaves_the_render_stages_unpublished`, fn `a_kernel_stage_in_refuses_the_stage_under_its_own_reason`, fn `the_translators_placeholders_cost_the_stage_nothing`, fn `the_published_usage_memo_is_dropped_by_everything_that_drops_the_usage`, fn `the_reason_a_draws_slots_stayed_unknown_is_counted_and_not_summed`, fn `a_dispatch_is_answered_or_not_and_never_half`. | | Supported operations reaching an unknown stage fallback | 0 | **not measurable on the live path** | The instrument is `reims_vgpu_vulkan::barrier::BarrierPlan::unmapped_bits`, which reports the stage bits that had no row and were therefore widened to `ALL_COMMANDS`. The engine does not use that module — it builds its own barriers — so nothing on a live path can report it. This is a cutover item, not a missing counter. | **Do not read an unmeasured row as a zero.** The plan's own argument for this diff --git a/crates/reims-vgpu/src/runtime/drain/mod.rs b/crates/reims-vgpu/src/runtime/drain/mod.rs index 09fb2ecb1..9c7eb989f 100644 --- a/crates/reims-vgpu/src/runtime/drain/mod.rs +++ b/crates/reims-vgpu/src/runtime/drain/mod.rs @@ -2214,7 +2214,7 @@ fn admit_and_park( } false }); - note_access_modes(&built); + note_access_modes(state, &built); // The pipelines the records bind, told to the model before it is asked // whether the packet may run: `PipelineTable::waits_for` refuses a lease it // has no entry for, and the entry is this device's to make. The list is the @@ -2331,7 +2331,7 @@ fn admit_and_park( /// a count taken at the encoder would include intents a payload never carried. /// /// See fn `an_unknown_mode_access_is_counted_apart_from_a_known_one`. -pub(crate) fn note_access_modes(built: &reims_vgpu_core::session::Packet) { +pub(crate) fn note_access_modes(state: &DeviceState, built: &reims_vgpu_core::session::Packet) { use reims_vgpu_core::access::AccessMode; for access in built.payload.accesses() { note_store_route(match access.mode { @@ -2341,6 +2341,57 @@ pub(crate) fn note_access_modes(built: &reims_vgpu_core::session::Packet) { AccessMode::Unknown => "access_mode_unknown", }); } + // Why the `Unknown`s above are `Unknown`, from the walk that decided it. + // + // The total is what the ordering plane is judged on and it says nothing + // about what to fix. A draw the walk never saw bind a pipeline and a draw + // whose shader the rail could not reflect both contribute every slot they + // bind, and the two have nothing in common: the first is a hole in the + // walk's own encoder state, the second is a contract term the rail has not + // recovered. Reported apart so the next move is aimed rather than guessed. + let Some(work) = built.payload.exec() else { + return; + }; + let census = &work.usage_census; + for (route, n) in [ + ("draw_usage_no_pipeline", census.draws_without_a_pipeline), + ("draw_usage_no_stage", census.draws_with_no_stage_published), + ( + "draw_usage_one_stage", + census.draws_with_one_stage_published, + ), + ( + "draw_usage_both_stages", + census.draws_with_both_stages_published, + ), + ( + "dispatch_usage_no_pipeline", + census.dispatches_without_a_pipeline, + ), + ( + "dispatch_usage_no_stage", + census.dispatches_with_no_stage_published, + ), + ("dispatch_usage_published", census.dispatches_published), + ] { + note_store_route_n(route, u64::from(n)); + } + // Which pipeline, and what the table thinks of it. The counts above say a + // draw found nothing published; only the pipeline's *state* tells the two + // causes apart — an executor that has not answered yet, and one whose + // answer a withdrawal or a retirement threw away. Once per slot. + if let Some(id) = census.first_unanswered_pipeline { + if crate::observe::first_sight("draw_usage_no_stage", u64::from(id.slot.0)) { + crate::observe::fail(format!( + "draw_usage_no_stage slot={} gen={} model_pipeline={} (a draw bound this \ + pipeline and the ordering plane had no reflection for it, so every slot \ + the draw binds ordered against every other access to the same resource)", + id.slot.0, + id.generation.0, + state.pipeline_state(id).unwrap_or("unleased"), + )); + } + } } /// Advance what the model is waiting on, then run everything it has released. diff --git a/crates/reims-vgpu/src/runtime/exec/vulkan.rs b/crates/reims-vgpu/src/runtime/exec/vulkan.rs index 1f0177de5..5f04a0da3 100644 --- a/crates/reims-vgpu/src/runtime/exec/vulkan.rs +++ b/crates/reims-vgpu/src/runtime/exec/vulkan.rs @@ -78,29 +78,110 @@ pub(crate) fn preflight_render_translations( continue; }; let cache_started = std::time::Instant::now(); - if !crate::runtime::m2v_cache::ensure_cached_async( + // `|` and not `||`: both stages must be *started*, so they translate in + // parallel and the packet is retried once rather than once per stage. + let translated = crate::runtime::m2v_cache::ensure_cached_async( v_air, metal2vulkan::passes::Stage::Vertex, pipeline_ref, - ) | !crate::runtime::m2v_cache::ensure_cached_async( + ) & crate::runtime::m2v_cache::ensure_cached_async( f_air, metal2vulkan::passes::Stage::Fragment, pipeline_ref, - ) { - // `|` and not `||`: both stages must be *started*, so they - // translate in parallel and the packet is retried once rather than - // once per stage. - if !pending.contains(&pipeline_ref) { - pending.push(pipeline_ref); - } - } + ); note_preflight_part( PreflightPart::Cache, cache_started.elapsed().as_nanos() as u64, ); + if !translated { + if !pending.contains(&pipeline_ref) { + pending.push(pipeline_ref); + } + continue; + } + publish_render_usage(state, host, task_id, pipeline_ref, v_air, f_air); } } +/// Tell the ordering plane what this pipeline's two stages do with each bound +/// slot, from the same pass that established they are translated. +/// +/// # Why here, when `pipeline_resolve::ready` already publishes +/// +/// `ready` runs at the pipeline's first *draw-time* resolve, which is after the +/// transaction that draws it was admitted — and the walk asks for a pipeline's +/// reflection once, at admission, and never again. So every draw of the packet +/// that first uses a pipeline gets a footprint that is `Unknown` for every slot +/// it binds. A driven macos-15 boot measured that at **1 244 draws** against +/// 69 448 answered by both stages: small, and entirely avoidable, because this +/// pass runs *before* admission readies the packet's leases. +/// +/// The compute rail has published from its own pre-scan since it had one. This +/// is the render half, so both rails answer at the same point in a packet's +/// life and the two counters are read against the same denominator. +/// +/// [`crate::model::DeviceState::pipeline_usage_published`] is what keeps the +/// two sites from being two answers: whichever reaches the pipeline first +/// publishes, the other finds the gate closed, and the gate is the model's own +/// record rather than a memo either site keeps. +fn publish_render_usage( + state: &DeviceState, + host: &M, + task_id: u32, + pipeline_ref: u32, + v_air: &[u8], + f_air: &[u8], +) { + use crate::backend::vulkan::pipeline_resolve::VertexBindPlan; + + let Some(name) = crate::runtime::objects::name_resource(state, host, task_id, pipeline_ref) + else { + crate::runtime::drain::note_store_route("pipeline_usage_unnamed"); + return; + }; + if state.pipeline_usage_published(name) { + crate::runtime::drain::note_store_route("render_usage_already_published"); + return; + } + // The descriptor, for the vertex stage's attribute slots — the buffers the + // fixed-function fetch reads, which the reflection does not name. Loaded + // only on the pass that publishes, which is once per build. + let Some(desc) = crate::runtime::draw::load_render_pipeline(state, host, task_id, pipeline_ref) + else { + crate::runtime::drain::note_store_route("render_usage_descriptor_lost"); + return; + }; + let (Ok(vertex), Ok(fragment)) = ( + crate::runtime::m2v_cache::translate_cached_reflected( + v_air, + metal2vulkan::passes::Stage::Vertex, + pipeline_ref, + ), + crate::runtime::m2v_cache::translate_cached_reflected( + f_air, + metal2vulkan::passes::Stage::Fragment, + pipeline_ref, + ), + ) else { + // Cached a moment ago and not now: the entry failed or was forgotten + // between the two calls. Nothing is owed — the draw path reports the + // translation failure precisely, and an unpublished pipeline is a + // conservative footprint rather than a wrong one. + crate::runtime::drain::note_store_route("render_usage_translation_lost"); + return; + }; + let plan = VertexBindPlan::build(&desc); + let (usage, refusals) = crate::backend::vulkan::binding_usage::render( + &vertex.reflection, + &plan, + &fragment.reflection, + ); + for refusal in refusals.into_iter().flatten() { + crate::runtime::drain::note_store_route(refusal.slug()); + } + crate::runtime::draw::publish_pipeline_usage(state, host, task_id, pipeline_ref, usage); +} + /// `dispatches` is the **model's own record of what this packet dispatches**, /// not a second scan of its bytes. /// diff --git a/crates/reims-vgpu/src/runtime/ingress.rs b/crates/reims-vgpu/src/runtime/ingress.rs index 596337b82..18ef92e40 100644 --- a/crates/reims-vgpu/src/runtime/ingress.rs +++ b/crates/reims-vgpu/src/runtime/ingress.rs @@ -2031,6 +2031,11 @@ mod tests { .find(|row| LifecycleKind::of(row.channel, row.opcode) == Some(want)) .expect("the ledger has a row for every settled lifetime kind") }; + // A device only so the census can ask what the model thinks of a + // pipeline a draw left unanswered. This fixture's packets are lifetime + // packets and bind none, so the answer is never reached — the argument + // is what the counting door takes, not what this test is about. + let device = crate::model::DeviceState::new(crate::model::DeviceId(1), 12); let counted = |want: LifecycleKind| { let row = row_of(want); let fifo = fifo_for(row.channel); @@ -2047,7 +2052,7 @@ mod tests { store_route_count("access_mode_read_write"), store_route_count("access_mode_unknown"), ]; - note_access_modes(&built); + note_access_modes(&device, &built); [ store_route_count("access_mode_read") - before[0], store_route_count("access_mode_write") - before[1], From a96c8d6fe3492f18ef95aba695597e014b349772 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 3 Sep 2026 22:45:17 +0300 Subject: [PATCH 3/5] usage: the row was pointing at a gap that does not exist, and the census says so MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `8eb3f585` named IR dataflow over the SPIR-V as the next move, for "a device buffer whose read-versus-write the translator's facade does not carry". That was built — a ~400-line analyser in `reims-vgpu-vulkan`, nine tests, wired through both publish sites — and it is **not** in this commit, because the boot that was supposed to confirm it refuted it instead. `buffer_direction_from_module=0`, and so are the other three outcomes of the lookup, on a boot where the analyser demonstrably ran. No `ResourceKind::Buffer` binding this guest declares has `access: None`. The scoreboard's claim was read off an **older revision** of the translator's own doc; the pinned revision populates buffer access "from Metal's declared access and tightened by specialized-entry parameter attributes", which is the narrowing the pass was written to add. A pass that answers a question nothing asks is a linear scan per pipeline build that can only ever delete edges, so it is reverted rather than kept against a future guest that might need it — that is Hypothesis-grade, and the plan says a hypothesis may not control implementation. What is kept is the instrument, because it is what found this. Two new participation-weighted rows finish `UsageCensus`, and they are weighted the way the ordering plane weighs them rather than by draws: one conceded slot in a pipeline that draws ten thousand times is ten thousand conflicting participations, and one unpublished pipeline that draws twice is four. Driven macos-15 x86/Vulkan boot, `reims-vgpu-pci`, three rounds, `FAIL=0` across 40 777 lines, `unknown=9 375 read=331 995 write=10 383 read_write=12 800` (2.6 %), and the split is decisive: - **`unknown_from_a_table=0`.** Not one `Unknown` comes from a published `BindingUsage`. Every table this device publishes is already as narrow as the reflection can make it, so no publisher-side work can move this row further. - **`unknown_with_no_table=3 589`** is the structural population: the packet that first names a pipeline draws against it, and `pipeline_leases` is that same packet's walk output, so the walk precedes the declaration it produces. - **The remaining 5 786 are neither.** They are participations the records themselves declare, not slots an encoder bound; they never pass through a `BindingUsage` and no reflection can reach them. That is a different subsystem, and `dead/README.md` now says so instead of pointing at buffers. Co-Authored-By: Claude Opus 5 (1M context) --- crates/reims-vgpu-core/src/exec.rs | 76 ++++++++++++++++++++++ crates/reims-vgpu/src/dead/README.md | 2 +- crates/reims-vgpu/src/runtime/drain/mod.rs | 8 +++ 3 files changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/reims-vgpu-core/src/exec.rs b/crates/reims-vgpu-core/src/exec.rs index 58dc99c43..7709eb8ae 100644 --- a/crates/reims-vgpu-core/src/exec.rs +++ b/crates/reims-vgpu-core/src/exec.rs @@ -638,13 +638,19 @@ impl EncoderBindings { let fragment = bound.and_then(|id| usages.binding_usage(id, Some(ShaderStage::Fragment))); census.note_draw(bound, vertex.is_some(), fragment.is_some()); + let before = out.len(); + let had_a_table = vertex.is_some() || fragment.is_some(); state.footprint_into(vertex, fragment, out); + census.note_unknowns(&out[before..], had_a_table); } (Self::Compute(state), ResolvedOperation::Compute(ComputeOp::Dispatch(_))) => { let bound = state.pipeline; let kernel = bound.and_then(|id| usages.binding_usage(id, None)); census.note_dispatch(bound, kernel.is_some()); + let before = out.len(); + let had_a_table = kernel.is_some(); state.footprint_into(kernel, out); + census.note_unknowns(&out[before..], had_a_table); } _ => {} } @@ -1016,6 +1022,17 @@ pub struct UsageCensus { pub dispatches_with_no_stage_published: u32, /// Dispatches answered by their kernel. pub dispatches_published: u32, + /// `Unknown` participations a *published* table produced. + /// + /// The other half of the row, and the one a count of draws cannot give: + /// one conceded slot in a pipeline that draws ten thousand times is ten + /// thousand conflicting participations, and one wholly unpublished pipeline + /// that draws twice is four. Which of those the residue is decides whether + /// the next move is about the publisher or about the reflection it + /// publishes, so they are weighted the way the ordering plane weighs them. + pub unknown_participations_from_a_table: u32, + /// `Unknown` participations emitted because there was no table to ask. + pub unknown_participations_with_no_table: u32, /// The first pipeline a draw or dispatch found unanswered. /// /// A count says how much was lost and never which pipeline lost it, and the @@ -1051,6 +1068,24 @@ impl UsageCensus { self.note_unanswered(bound, !kernel); } + /// Split the `Unknown`s a footprint just produced by whether a table + /// answered them. + fn note_unknowns(&mut self, produced: &[Participation], had_a_table: bool) { + let unknown = produced + .iter() + .filter(|p| p.mode == crate::access::AccessMode::Unknown) + .count(); + let Ok(unknown) = u32::try_from(unknown) else { + return; + }; + let counter = if had_a_table { + &mut self.unknown_participations_from_a_table + } else { + &mut self.unknown_participations_with_no_table + }; + *counter = counter.saturating_add(unknown); + } + /// Keep the first pipeline that answered nothing, and only that one. fn note_unanswered(&mut self, bound: Option, nothing_published: bool) { if let (Some(id), true, None) = (bound, nothing_published, self.first_unanswered_pipeline) { @@ -1093,6 +1128,47 @@ mod usage_census_tests { ); } + /// The `Unknown`s are split by whether a table produced them, and they are + /// weighted the way the ordering plane weighs them. + /// + /// A count of *draws* cannot answer this row. One conceded slot in a + /// pipeline that draws ten thousand times is ten thousand conflicting + /// participations; one wholly unpublished pipeline that draws twice is + /// four. Which of those the residue is decides whether the next move is + /// about the publisher or about the reflection it publishes. + #[test] + fn an_unknown_is_charged_to_the_table_that_conceded_it_or_to_the_absence_of_one() { + use crate::access::AccessMode; + use crate::identity::{ObjectListRef, SlotGeneration}; + + let part = |mode| Participation { + resource: ResourceId { + slot: ObjectListRef(1), + generation: SlotGeneration::default(), + }, + extent: crate::access::ParticipationExtent::Whole, + mode, + api_stages: 0, + }; + let mut c = UsageCensus::default(); + c.note_unknowns( + &[ + part(AccessMode::Unknown), + part(AccessMode::Read), + part(AccessMode::Unknown), + ], + true, + ); + c.note_unknowns(&[part(AccessMode::Unknown)], false); + assert_eq!(c.unknown_participations_from_a_table, 2); + assert_eq!(c.unknown_participations_with_no_table, 1); + assert_eq!( + c.draws_without_a_pipeline, 0, + "counting the participations is not counting the draws, which is \ + the whole reason both rows exist" + ); + } + /// A dispatch has one stage, so "published" and "no stage" are the whole /// answer, and a kernel can never be half-answered. #[test] diff --git a/crates/reims-vgpu/src/dead/README.md b/crates/reims-vgpu/src/dead/README.md index fe013da5d..ac21c0bad 100644 --- a/crates/reims-vgpu/src/dead/README.md +++ b/crates/reims-vgpu/src/dead/README.md @@ -162,7 +162,7 @@ the access-mode and framing censuses — or off a named off-VM gate. | Re-scans of already resolved EXEC bytes | 0 | **met** | `exec_stream_framed=18 421` against `exec_streams_loaded=18 421` — a ratio of exactly one, on the driven macos-15 boot in the last live-validation row. `walk_stream` is the crate's one framing site and it is the counted one. Every submission on that boot carried a single stream (`exec_cmdbufs_1=18 421`), so the boot cannot tell "once per stream" from "once per submission"; fn `a_submission_frames_each_stream_once_and_preflight_frames_none` is what does, on two streams, and it also holds the plan step to framing none — `preflight_submission` answers from `ExecWork` rather than from the packet's bytes. | | Repeated transfers for one range, version and direction | 0 | **met for buffers, unmeasured for images** | `buffer_bind_reuses=304 017` and `buffer_index_bind_reuses=892`: every one is a bind served from a copy the command buffer already held rather than a second transfer of the same bytes. The image side is not the same claim — `sampled_reuploads=45` at 15.3 MB are lawful, since the content version moved, but nothing here separates a lawful reupload from a repeated one. | | Pipeline compiles on a Ready pipeline draw | 0 | **met** | fn `warm_identical_dispatch_zero_creates_and_allocs` and the `creates`/`allocs` deltas the batch suite asserts at zero on a warm draw. | -| Supported operations reaching an unknown access-mode fallback | 0 | **not met, 81 % → 2.7 %, and the residue is named** | Was `access_mode_unknown=342 987` against 81 116 known — 81 % of every access the dependency graph ordered against — because `ExecWork::footprint_into` passed `None` for the pipeline's `BindingUsage` and nothing in the tree constructed one. Both rails now publish their translated shaders' reflection, and a driven macos-15 boot reads **`unknown=9 579` against `read=319 318`, `write=10 221`, `read_write=13 174`** — **2.7 %**, against 3.9 % when only the render rail published. `UsageCensus` says what is left, and it is two things and not one. **`draw_usage_both_stages=69 407` against `draw_usage_no_pipeline=0` and `draw_usage_one_stage=0`**: the walk always knows which pipeline a draw binds, and a published pipeline is never half-published. **`draw_usage_no_stage=606`** is the first packet to *name* each pipeline — 88 of 93 first sightings read `model_pipeline=unleased`, because the packet's own bytes are what declare the pipeline and the walk that reads them runs before the declaration it produces. That is structural at this seam and not a defect: the walk asks once, at admission, and a footprint taken before the pipeline existed is coarse rather than wrong. Everything else — about 8 000 participations — is a **device buffer whose read-versus-write the translator's facade does not carry**; it needs IR dataflow over the module the rail already holds, and that is the next move on this row. Every refusal this mapping can report reads zero on that boot. fn `a_kernel_publishes_the_compute_stage_and_leaves_the_render_stages_unpublished`, fn `a_kernel_stage_in_refuses_the_stage_under_its_own_reason`, fn `the_translators_placeholders_cost_the_stage_nothing`, fn `the_published_usage_memo_is_dropped_by_everything_that_drops_the_usage`, fn `the_reason_a_draws_slots_stayed_unknown_is_counted_and_not_summed`, fn `a_dispatch_is_answered_or_not_and_never_half`. | +| Supported operations reaching an unknown access-mode fallback | 0 | **not met, 81 % → 2.6 %, and the residue is not where this table said it was** | Was `access_mode_unknown=342 987` against 81 116 known — 81 % of every access the dependency graph ordered against — because `ExecWork::footprint_into` passed `None` for the pipeline's `BindingUsage` and nothing in the tree constructed one. Both rails now publish, and a driven macos-15 boot reads **`unknown=9 375` against `read=331 995`, `write=10 383`, `read_write=12 800`** — **2.6 %**. **`UsageCensus` moved this row from inference to measurement, and corrected it twice.** `unknown_from_a_table=0`: **not one** `Unknown` participation comes from a published table, so the tables are already as narrow as the reflection can make them. This row previously said the residue was "a device buffer whose read-versus-write the translator's facade does not carry"; that was read off an **older translator revision's** doc. The pinned one populates buffer access "from Metal's declared access and tightened by specialized-entry parameter attributes", and a lookup wired to catch the gap measured **zero hits on every buffer this guest declares**, so the gap does not exist here and the SPIR-V dataflow pass written for it was reverted rather than landed. `unknown_with_no_table=3 589` is the structural population: the packet that *first names* a pipeline draws against it, and `pipeline_leases` is that same packet's walk output, so the walk necessarily precedes the declaration it produces (88 of 93 first sightings read `model_pipeline=unleased`). Coarse rather than wrong, and closing it means re-walking a parked packet after its pipelines go `Ready` — sound only if the model says an admitted ordering position may restate what it depends on. **The remaining 5 786 are neither**: they are participations the *records themselves* declare, not slots an encoder bound, so they are outside `BindingUsage` entirely and no publisher can narrow them. That is where this row goes next, and it is a different subsystem than the one this table has been pointing at. fn `a_kernel_publishes_the_compute_stage_and_leaves_the_render_stages_unpublished`, fn `a_kernel_stage_in_refuses_the_stage_under_its_own_reason`, fn `the_translators_placeholders_cost_the_stage_nothing`, fn `the_published_usage_memo_is_dropped_by_everything_that_drops_the_usage`, fn `the_reason_a_draws_slots_stayed_unknown_is_counted_and_not_summed`, fn `a_dispatch_is_answered_or_not_and_never_half`, fn `an_unknown_is_charged_to_the_table_that_conceded_it_or_to_the_absence_of_one`. | | Supported operations reaching an unknown stage fallback | 0 | **not measurable on the live path** | The instrument is `reims_vgpu_vulkan::barrier::BarrierPlan::unmapped_bits`, which reports the stage bits that had no row and were therefore widened to `ALL_COMMANDS`. The engine does not use that module — it builds its own barriers — so nothing on a live path can report it. This is a cutover item, not a missing counter. | **Do not read an unmeasured row as a zero.** The plan's own argument for this diff --git a/crates/reims-vgpu/src/runtime/drain/mod.rs b/crates/reims-vgpu/src/runtime/drain/mod.rs index 9c7eb989f..93ee45a1d 100644 --- a/crates/reims-vgpu/src/runtime/drain/mod.rs +++ b/crates/reims-vgpu/src/runtime/drain/mod.rs @@ -2373,6 +2373,14 @@ pub(crate) fn note_access_modes(state: &DeviceState, built: &reims_vgpu_core::se census.dispatches_with_no_stage_published, ), ("dispatch_usage_published", census.dispatches_published), + ( + "unknown_from_a_table", + census.unknown_participations_from_a_table, + ), + ( + "unknown_with_no_table", + census.unknown_participations_with_no_table, + ), ] { note_store_route_n(route, u64::from(n)); } From a925b13f9250bfca62b441764eff6034a01fa608 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 3 Sep 2026 23:12:14 +0300 Subject: [PATCH 4/5] dead: the directory the cutover was reading from, deleted wholesale MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 2026-09-02 amendment replaced Seam 6's "delete the legacy counterpart" with "disconnect it", and it always ended in this commit: `dead/` is deleted whole, in one commit, once the groups have moved. The packet-class groups have moved — `Namespace` and `RefResolver` are the sole name authority, the ingress switch is cut, `ingress::Gap` is down to two variants and `packet_class_unclassified` is zero on both driven rails — and the one item left on the disconnect list is not a packet class at all. It is the process-global mutable engine behind `static ENGINE: Lazy>`, and its legacy files leave the tree with it when it wires, not through a staging directory. Removed, all of it unreachable by construction already: - `crates/reims-vgpu/src/dead/` — eight files, ~344 KB of legacy Rust (`blit_decoder`, `compute_decoder`, `render_decoder` and its tests, `stream_framer`, `event_decoder`, `child_deprecated_ops`, `pending_stamp`), and the 159 KB register that recorded what moved, the structural-zero scoreboard, and the live-validation table. - `crates/reims-vgpu/tests/dead_is_unreachable_by_construction.rs`. Its own `every_dead_directory_carries_its_register` says the suite goes when the last `dead/` does, and there is nothing left for its six doors to guard. What goes with it is the check that the register's 63 named functions still exist; every one of them was verified present in live source before the delete, so the claims it was standing behind are true at the moment it stops asking. The coverage the gate held is now held by the rule instead: a group's legacy tests die with its legacy source, so the commit that wires a group names the owner-level tests replacing them in its message. `AGENTS.md` and the plan's Seam 6 say that rather than the disconnect procedure, and neither offers `dead/` as a place to stage a deletion through. Three call sites pointed at the register for a number rather than for code — `vm/README.md` and `vm/drive-desktop.sh` for the workload every rate was taken behind, and `runtime::drain` for the stamp counter read at zero when the publication point moved — and each now carries the fact instead of the pointer. Verified: `cargo check --workspace --all-targets --no-default-features --features reims-vgpu/backend-vulkan` clean (three pre-existing warnings in `queue_owner.rs`, which are `host-window`-gated consumers, not dead code); `dispatch_agrees_with_the_packet_ledger` passes, being the one test that reads `runtime/drain/mod.rs` as text; `cargo fmt --check` clean. No guest-visible behavior changes — nothing deleted was compiled. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_017RrJpWZWCYaxKdLk4oQk3h --- AGENTS.md | 34 +- crates/reims-vgpu/src/dead/README.md | 259 -- crates/reims-vgpu/src/dead/blit_decoder.rs | 1327 ---------- .../src/dead/child_deprecated_ops.rs | 84 - crates/reims-vgpu/src/dead/compute_decoder.rs | 1293 --------- crates/reims-vgpu/src/dead/event_decoder.rs | 377 --- crates/reims-vgpu/src/dead/pending_stamp.rs | 345 --- crates/reims-vgpu/src/dead/render_decoder.rs | 1509 ----------- .../src/dead/render_decoder_tests.rs | 2352 ----------------- crates/reims-vgpu/src/dead/stream_framer.rs | 795 ------ crates/reims-vgpu/src/runtime/drain/mod.rs | 8 +- .../dead_is_unreachable_by_construction.rs | 477 ---- vm/README.md | 7 +- vm/drive-desktop.sh | 13 +- 14 files changed, 30 insertions(+), 8850 deletions(-) delete mode 100644 crates/reims-vgpu/src/dead/README.md delete mode 100644 crates/reims-vgpu/src/dead/blit_decoder.rs delete mode 100644 crates/reims-vgpu/src/dead/child_deprecated_ops.rs delete mode 100644 crates/reims-vgpu/src/dead/compute_decoder.rs delete mode 100644 crates/reims-vgpu/src/dead/event_decoder.rs delete mode 100644 crates/reims-vgpu/src/dead/pending_stamp.rs delete mode 100644 crates/reims-vgpu/src/dead/render_decoder.rs delete mode 100644 crates/reims-vgpu/src/dead/render_decoder_tests.rs delete mode 100644 crates/reims-vgpu/src/dead/stream_framer.rs delete mode 100644 crates/reims-vgpu/tests/dead_is_unreachable_by_construction.rs diff --git a/AGENTS.md b/AGENTS.md index 5c5dd03e7..39530e544 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -128,28 +128,26 @@ disjoint class back buys no safety while costing the bisect it could have provid State the disjointness before moving a group and make it hold structurally — named owners, not an argument that the current call sites happen not to overlap. If it cannot be made to hold, the group is larger than it looked: enlarge it rather than move anyway. Within a group the switch is atomic -and the legacy counterpart is disconnected in the same commit. Order the groups by how little state +and the legacy counterpart is deleted in the same commit. Order the groups by how little state they move; the ordering and publication core is last, and carries the scheduler's deletion. -**Disconnect, do not delete — amending "the legacy counterpart is deleted in the same commit" -above, and the plan's Seam 6.** In the commit that wires a group, move its legacy files to -`crates//src/dead/` and remove every `mod` declaration that reaches them. `dead/` does not -compile, is not feature-gated, and is not linkable; it is source to read. Unreachability by -construction is what the prohibition on two semantic models needs, and it is what a removed `mod` -gives — a flag or a `cfg` would give the prohibition's opposite. +**The 2026-09-02 "disconnect, do not delete" amendment is spent, and `dead/` is gone as of +2026-09-03.** It bought attribution while packet classes were moving under outstanding macOS cells: +a group's legacy files went to `crates//src/dead/`, unreachable because no `mod` declared +them, so a live regression on a class that had just moved could be read rather than reconstructed +from `git log`. Every packet-class group has since moved, the classes it was protecting are settled, +and the directory was deleted wholesale in one commit along with the gate that held it unreachable. -Each move appends a row to `crates//src/dead/README.md` naming what moved, which commit -replaced it, and which new owner-level tests replaced the legacy tests that moved with it. Those -tests stop running the moment they move, so a group that ships without that replacement coverage -has silently lost it and the row is where that is caught. Name each replacing test as ``fn `name` ``: -the `fn` is what `dead_is_unreachable_by_construction` reads to tell a promise about a function from -the prose beside it, and a name written without it is a claim nothing checks. +So the rule above is the rule again: **the group's legacy counterpart is deleted in the commit that +wires it.** Do not recreate `dead/`, and do not stage a deletion through it — what an old arm did is +now read out of `git log`, and the deleted-in-the-same-commit form is what the prohibition on two +semantic models asks for directly. The one group still to move is the process-global mutable engine +behind `backend::vulkan::engine`; when it wires, its legacy files leave the tree with it. -Nothing is resurrected from `dead/`, and no build-time or run-time switch may reach it. When a live -boot regresses, `dead/` is read to learn what the old code did and the fix lands in the new owner. -`dead/` is deleted wholesale, in one commit, once every group has moved and the plan's gates are -green — never pruned incrementally, because a half-emptied `dead/` reads as "these were the ones -worth keeping". +A group's legacy tests die with its legacy source, so the commit that wires it must name — in the +commit message, since there is no register any more — the owner-level tests that replace them. A +group shipping without that replacement coverage has silently lost it, and nothing in the build +relates the two. ## Working and verification diff --git a/crates/reims-vgpu/src/dead/README.md b/crates/reims-vgpu/src/dead/README.md deleted file mode 100644 index ac21c0bad..000000000 --- a/crates/reims-vgpu/src/dead/README.md +++ /dev/null @@ -1,259 +0,0 @@ -# `dead/` — disconnected legacy source - -This directory is **not a module.** No `mod` declaration reaches it, nothing here -compiles, nothing here is feature-gated, and nothing here is linkable. It is -source to read. - -## Why it exists - -`AGENTS.md` and the replacement plan's Seam 6 say a group's legacy counterpart is -*deleted* in the commit that wires the group. The project owner amended that to -**disconnect instead of delete**, for one reason: when a live boot regresses on a -packet class that has just moved, the question is "what did the old arm do", and -`git log` over a 400k-line tree is a poor way to ask it. Unreachability is what -the prohibition on two semantic models actually needs, and removing the `mod` -declaration gives that by construction rather than by a flag. - -## The rules, and they are not negotiable - -- **Nothing is resurrected from here.** Not by a `mod`, not by a feature, not by - a copy-paste. A regression is read here and *fixed in the new owner*. -- **No build-time or run-time switch may reach `dead/`.** A `#[cfg]` that turns a - file here back on is the second semantic model the plan forbids, wearing a - different hat. -- **Every move appends a row below**, naming what moved, the commit that - replaced it, and the owner-level tests that replaced the legacy tests moving - with it. Those tests stop running the moment they move; a group that ships - without replacement coverage has silently lost it, and the row is where that - is checked. -- **A coverage name is written ``fn `name` ``.** The `fn` is not decoration: it - is what separates a promise about a function from the prose around it, so a - row can go on naming a directory, a route family or a slug that no longer - exists in the same sentence. The gate below reads exactly those names and - requires each to be a function that still exists — before this marker existed - it read nine coverage claims and could verify two, while its own doc and the - rule above both said it verified all nine. -- **The four rules above are a test, not a convention.** - `crates/reims-vgpu/tests/dead_is_unreachable_by_construction.rs` refuses a - `mod dead` declaration, a `#[path]` attribute pointing into a `dead/` - directory, an `include!` splicing a `dead/` file, a Cargo target whose `path` - points into one, any path naming `dead` from live source, and a `dead/` with - no register — and it checks that every function a register row *declares* as - replacement coverage is still a function, because that row is the only record - that a moved group's coverage survived and nothing in the build relates the - two. It reads both tables: seven of the nine coverage claims in this file are - in the three-column live-validation table, and reading only the five-column - register was reading the smaller half. Six doors, because the module tree is not the only one: a - `[[test]]` with `path = "src/dead/…"` compiles and links the file as its own - crate root while a walk of `src/` reports the tree clean. A convention with no gate is what the amendment was written - against: `mod dead;` compiles, and the second semantic model it re-links - shows up as a behaviour difference on a live boot weeks later, attributed to - whatever else changed that week. -- **`dead/` is deleted wholesale, in one commit,** once every group has moved and - the Seam 6 gates are green. It is not pruned incrementally — a half-emptied - `dead/` reads as "these were the ones worth keeping", which is the opposite of - what it means. - -## What is still live, read off the tree rather than off the plan - -The plan's "final group" section (2026-09-02) names that group as `Namespace` + -`RefResolver` + the four `ingress::Gap` classes + the ingress switch. **Three of -those four have since moved, and the section has not been rewritten**, so a -reader taking it as current would go looking for work that is done. As of -`02bd23cd`: - -- **`Namespace` and `RefResolver` are the production authority.** - `DeviceState::object_name` asks `reims_vgpu_core::resolve::TaskNamespaces` on - the owner it holds, and `declare_object`, `retire_object_name`, - `define_task_namespace`, `delete_task_namespace`, `apply_lifetime` and the - access source all route through `reims_vgpu_core::lifecycle::Lifecycle`, which - is where `Namespace` lives. There is no second name table. -- **The ingress switch is cut.** Every accepted packet reaches - `runtime::ingress::device_packet` through `admit_and_park`, which is what - advances the head. -- **`ingress::Gap` is down from four variants to two** — `Unresolved` and - `ExecStreamsUnread` — and `packet_class_unclassified` is zero on macos-15 and - macos-26 both, so the first of those refuses nothing a driven guest sends. - -What blocks the wholesale delete is the third item on Seam 6's own disconnect -list, and it is one thing rather than a list: **the process-global mutable -engine.** `backend/vulkan/engine` is 62 000 lines behind -`static ENGINE: Lazy>` plus nine more process-global statics -beside it. The second item this paragraph used to name, `BLIT_FAIL_REASON` — a -thread-local carrying a reason the observation channel should carry — is gone: -`BlitFailure` and `BlitStatus::Failed { failure, reason }` replaced it in -`13f9aa49`, and `br` is the only constructor, so a refusal without a reason is -now unspellable. - -Two of Seam 6's structural zeros that were *not* about the engine have since -closed, and neither was where a reader would have looked for them. "No host -thread is created per EXEC, command buffer, draw, **save**, or watchdog -operation" was violated twice over: arming the compute stall proxy spawned a -thread per dispatch that slept the whole threshold holding a copy of the -kernel's SPIR-V (`5c1be382` — one registry, one thread, sixteen slots), and -persisting the pipeline cache spawned a thread per pipeline creation -(`b0bb5b8a` — the owner the plan's own pipeline section asks for). Both are now -gated behind `/proc/self/task` counts taken *after* the single owner is up, so -the gate reads per-operation rather than per-process. What is left of the thread -survey is one long-lived worker each for m2v translation, completion stamping -and queue ownership, and the plan says a dedicated owner thread is not itself a -defect. - -That is also what holds the rest of `reims-vgpu-vulkan` out. Twelve of its -thirty-six modules are wired — `raster`, `swapchain`, `vertex`, `blend`, -`depth_stencil`, `topology`, `sampler`, `pixel`, `view`, `memory`, `queues`, -`buffer` — and every one of them is a pure translation whose caller kept its -ownership. The next tier is not: `resident` and `placement` own native handles -and retirement points, `transfer`, `record`, `pass`, `renderpass` and `barrier` -are written against them, and the plan's own ordering rule says a module owning -handles, caches or submission lifetimes wires once the model owning those -lifetimes is in place. The engine is that model, and it has not moved. - -## Register - -Rows are ordered as they landed. A row's **step** is either a *wiring step* -(`W`n) — a pure translation or plan module whose legacy caller keeps its -ownership and loses only its duplicate arithmetic, per the plan's 2026-09-01 -amendment — or a *group* (`G`n), a set of packet classes moving to -`DeviceTransaction` together under the 2026-09-02 decomposition amendment. The -two are not the same claim and are not recorded as if they were: a wiring step -moves a decision, a group moves a lifetime. - -| Step | Moved | From | Replaced by | Owner-level tests that replaced the moved ones | -|---|---|---|---|---| -| W1 | `child_deprecated_ops.rs` — `CHILD_DEPRECATED_OPS`, `is_deprecated_child_opcode`, and the ledger test that walked them | `model/regs.rs`, `runtime/decode/ledger.rs` | `reims_vgpu_core::control::ControlKind::of` ⇒ `RetiredSlot`, read through `runtime::drain::is_retired_control_slot`. **What moved is the classification, not the envelope**: the drain still owns the stamp waits, the ordering position and the completion word for these packets, so this is a wiring step and not the inert class's cutover. | `runtime::decode::ledger::packets::the_ledger_judges_a_retired_set_at_all` (new — asserts the set's size against the reference host rather than against a transcription of the ledger); `runtime::decode::ledger::packets::no_live_command_is_also_a_retired_slot` and `no_ledger_row_names_a_command_this_device_cannot_receive` (re-sourced off the ledger, replacing the `const` assertion in `model::regs` that went with the table); `runtime::drain::tests::a_retired_slot_is_reported_as_retired_and_not_as_undecodable` (re-sourced off the ledger, so it now covers every judged slot rather than every transcribed one) | -| W2 | *(nothing moved)* | `runtime/drain/mod.rs` — the inline `if opcode == TAHOE { WithKeyLimit } else { WithoutKeyLimit }`, and the two arms that each named their own request decoder | `reims_vgpu_core::query::QueryKind::of` + `query::request_words`, joined by `runtime::drain::query_request` | No row content moves: the legacy counterpart was an expression inside a live match arm, not a file, so there is nothing `dead/` can hold. Recorded anyway so the register is the list of wiring steps and not only the list of files. New coverage: `runtime::decode::ledger::packets::the_query_arms_and_the_models_questions_are_the_same_four` — the check the drain cannot make for itself, since it sees one opcode at a time. | -| W3 | *(nothing moved)* | `runtime/drain/mod.rs` — the inline `packet.opcode == ROOT_OP_DEFINE_FIFO` that decided which end of a channel lifetime a packet was, and the silent `Ok(_) => {}` beside the range gate | `reims_vgpu_core::control::resolve` ⇒ `ControlOp::Channel { transition, domain }` | Again an expression rather than a file. New coverage: `runtime::drain::tests::a_channel_lifetime_outside_the_channel_range_is_reported` — the drop the old arm made in silence. | -| W4 | `event_decoder.rs` — all of `runtime/decode/event.rs` (the decoder, its `Command`/`Kind`/`DecodeStatus`, the refused-opcode list and its five tests), plus `runtime::fence_exec::tests::event_wait_timeout_unsupported` and the ledger test that drove it | `runtime/decode/event.rs` (whole file), `runtime/decode/mod.rs` (`pub mod event;`), `runtime/fence_exec.rs`, `runtime/decode/ledger.rs`, `runtime/plan/event_sync.rs` | `reims_vgpu_protocol::decode::sync::decode` for the lift, called from `runtime::exec::handle_event_record`; `reims_vgpu_protocol::sync::EventKind` for the two kinds the wire has. `plan_event` lost its `has_timeout` parameter and `Decision`/`Reason` lost their `WaitTimeoutUnsupported` variants — the settled row is refused where the ledger settled it, not a second time in the planner. Still a wiring step and not a group: `execute_event` keeps the fence-generation store and `core::resolve::event` is **not** wired, because it resolves an event ref through a namespace this device does not hold events in. | `runtime::exec::tests::a_bounded_event_wait_is_refused_by_contract_and_leaves_the_generation_alone` (new — the bounded wait's refusal reaches the failure channel from the segment walk, under the row's own name, and the signal ahead of it still lands); `runtime::decode::ledger::the_event_rail_lifts_its_records_and_refuses_its_one_settled_row` (replaces the per-rail decoder cross-check, and adds the claim the old one could not make: exactly one event row is `RefusedByContract` rather than `Unjudged`); `golden_vectors::event_signal_golden` (same bytes, re-pointed at the decoder in production) | -| W5 | `stream_framer.rs` — all of `runtime/decode/stream.rs` (segment and record framing, `Segment`, `Record`, `DecodeStatus`'s twenty-odd checks, `segment_disposition`, `segment_index_for_offset`, `SEGMENT_CHAIN_ROUTES`), plus the two `runtime::exec::tests` cases whose subjects it constructed | `runtime/decode/stream.rs` (whole file), `runtime/decode/mod.rs` (`pub mod stream;`), `runtime/exec/mod.rs`, `runtime/exec/vulkan.rs`, `runtime/exec/tests.rs`, `tests/golden_vectors.rs` | `reims_vgpu_protocol::segment::SegmentStream` for segments and `reims_vgpu_wire::op::OpStream` for the records inside one. `FramedSegment` carries the command window as a slice, so the sixteen `stream_reval_*` checks are gone with the state they guarded rather than moved; the per-segment index is counted instead of found by a quadratic re-walk; `segment_chain_route` moved to `runtime::exec` and now takes a `SegmentLifetime`, which also fixed a census that counted every segment three times on the Vulkan rail. **Carries one guest-visible behaviour change** — an unknown segment type ends the walk instead of being stepped over; see the header of `stream_framer.rs`. | `runtime::exec::tests::a_record_overrunning_its_segment_names_the_check_rather_than_ending_quietly` (new — the record-length half of the old defect, which is the half still expressible, and it asserts the well-formed record ahead of it still ran); `runtime::exec::tests::an_unknown_segment_family_ends_the_walk_and_the_envelope_does_not` (new — pins the behaviour change end to end: segments before the unknown family execute, the ones after do not, the line names the type and the count, and the protection envelope is still skipped in silence); `walking_a_well_formed_segment_to_its_end_logs_nothing` and `a_stream_that_will_not_frame_says_so_instead_of_executing_nothing` (kept, re-pointed at the new framing and its refusal names); `golden_vectors::stream_segment_record_roundtrip_shape` (same bytes, re-pointed) | -| W6 | *(nothing moved yet — the legacy blit decoder shrank rather than left)* | `runtime/exec/mod.rs` (`handle_blit_record`'s fence, ICB-optimize and content-representation arms), `runtime/blit_exec/mod.rs` (`execute_blit_fence`'s two refusals) | `reims_vgpu_core::operation::classify` decides the record's class from the ledger row; `reims_vgpu_protocol::decode::{sync, icb, resource_state}` lift the three settled classes. `execute_blit_fence` takes a `FenceRecord`, so `fence_wrong_kind` and `fence_bad_opcode` are unrepresentable. **The rows the ledger has not settled deliberately keep this device's own decoder**, because their decline census is the evidence that will settle them — see `handle_blit_device_decoded_record`. `runtime/decode/blit.rs` cannot move to `dead/` until the transfers move, which is the next step on this rail. | `runtime::exec::tests::each_icb_blit_record_reaches_a_counter_that_names_which_one_it_is` and `each_blit_spi_record_reaches_a_counter_that_names_which_one_it_is` (kept, and now also prove the settled/unsettled split routes correctly); `runtime::blit_exec::tests::blit_fence_{update_then_wait,wait_pending_without_update,zero_ref_fails}` (re-pointed at `FenceRecord`) | -| W7 | `blit_decoder.rs` — all of `runtime/decode/blit.rs`: the flat `Command` with fifty-odd fields, `Kind`, `CopyKind`, `RefKind`, `FillSource`, `parse_blit_options`/`BlitOptionError`, and its seventeen tests | `runtime/decode/blit.rs` (whole file), `runtime/decode/mod.rs` (`pub mod blit;`), `runtime/blit_exec/{mod,vulkan,tests}.rs`, `runtime/exec/mod.rs`, `runtime/decode/ledger.rs`, `backend/{mod,vulkan/mod}.rs`, `tests/{golden_vectors,wire_fixtures_reach_the_decoders}.rs` | `reims_vgpu_protocol::decode::blit::BlitRecord` for the nine transfers, whose variants now carry **named payloads** so each executor arm takes the one record it handles by reference — `execute_blit` matches the enum and the seven `exec_*` arms are functions of `BufferToBuffer`, `BufferToTexture`, `TextureToBuffer`, `TextureRegion`, `TextureSlices` and `FillBuffer`. A record charged to one family and executed by another is no longer expressible: the census route and the arm both come from `BlitRecord::kind()`, where they used to be two reads of a `kind` tag and a `copy_kind` tag a decoder set separately. `has_options` is gone with `parse_blit_options` — a record with no `options:` word selects the whole texel, which is what `protocol::blit::select_aspect(0)` answers, so "no options word" and "options word is zero" stopped being two states. `generateMipmapsForTexture:` is answered by the caller, since `runtime::mipmap` owns the chain. **The four rows the ledger has not settled did not move**: `runtime/decode/blit_spi.rs` is new and decodes exactly them — the indirect-command reset and copy and the two texture fills — because their decline census is the evidence that will settle them, and it refuses every settled opcode by name so no record has two readings. | `reims_vgpu_protocol::decode::blit::{a_texture_to_buffer_copy_reads_no_byte_past_its_options, a_region_copy_with_options_is_refused_at_the_plain_forms_length, a_slice_and_level_copy_lifts_its_six_counts_in_the_records_order}` (new — the three field-order and length claims that moved with `decode_b2b`, `decode_copy_slice_level_0x13e` and `texture_to_texture_options_len`); `reims_vgpu_protocol::blit::an_option_word_selects_one_plane_or_names_why_it_cannot` (new — replaces `parse_blit_options_aspects` at the owner, and adds the claim the old one could not make: the three refusals do not share a slug); `runtime::decode::blit_spi::{both_texture_fills_read_their_extent_from_the_size_and_not_the_origin, the_two_icb_mutations_are_told_apart_by_whether_they_name_a_destination, the_two_texture_fills_keep_their_sources_apart, the_settled_optimize_hint_is_not_a_record_this_decoder_owns, no_transfer_opcode_is_a_record_this_decoder_owns, a_record_short_of_its_body_is_refused}` (new — replace `both_texture_fills_decode_their_region_size_before_origin`, `an_icb_blit_record_is_read_rather_than_refused_whole` and `each_spi_record_refuses_a_length_one_byte_short`, and the last three are the claim that keeps `dead/`'s prohibition structural: no settled row is decodable twice); `runtime::decode::ledger::every_blit_row_reaches_exactly_one_decoder_and_the_ledger_picks_it` (new — replaces `the_blit_decoder_recognises_every_blit_operation_the_ledger_records` and `the_blit_opcode_table_is_exactly_apples_blit_manifest`, and is strictly stronger: the rail has five decoders now, so "no row is dropped by all of them" and "no row is claimed by two" are both asserted where one decoder could only assert the first); `golden_vectors::stream_segment_record_roundtrip_shape` and `corpus_property_random_decode_no_panic` (same bytes, re-pointed at the lift in production); the ~40 `runtime::blit_exec::tests` executor cases (kept, re-pointed at the payload structs — `copy_cmd(CopyKind::…)` became one builder per record, so a test can no longer construct a copy whose `kind` and `copy_kind` disagree) | -| W8 | *(nothing moved yet — the legacy compute decoder shrank rather than left)* | `runtime/exec/mod.rs` (`handle_compute_record`'s entry), `runtime/compute_exec/mod.rs` (`apply_record_inner`'s five no-op arms, `note_residency_declaration` and `ComputeResidencyDeclared`) | `reims_vgpu_core::operation::classify` decides the record's class from the ledger row, and the three classes that own no segment state are answered from it: `reims_vgpu_protocol::decode::sync` lifts the two barriers, `decode::resource_state` lifts the compressed-reinterpretation flush, and `decode::residency::lift` lifts the two unqualified residency declarations — the first device call into that module at all, which until now was reachable from nothing. **The disjointness is the reason this group is separable and it is structural**: none of the five records touches `seg.acc`, `seg.session` or `seg.block`, and the test asserts that rather than arguing it. A heap declaration carrying no usage is now the record's own shape (`ResidencyRecord::usage: Option<_>`) instead of a zero the decoder filled in, so "declared nothing" and "declared no usage" stopped being one word. **The rail's other eleven unsettled rows did not move**: the fence pair (`0xd4`/`0xd5`), the seven control-flow records and the two indirect-command executions are all `Unresolved`, so `classify` returns `None` for them and the protocol crate will not lift a row it has not settled — and unlike the blit rail's unsettled four, these feed live executors (`fence_exec::execute_fence`, `MetalSession::{encode_control,encode_icb}`) rather than declines, so they keep this device's decoder until the record types their executors take can change with them. `runtime/decode/compute.rs` cannot move to `dead/` until that happens. | `runtime::exec::tests::each_ledger_routed_compute_class_reaches_a_counter_that_names_which_one_it_is` (new — the five records, each reaching exactly one of five counters and none of the other four, plus the claim that makes the group a group: no segment state moved); `runtime::exec::tests::a_ledger_routed_compute_record_short_of_its_body_is_declined_and_not_counted` (new — a declaration whose refs are not there is declined under its own name rather than priced as one that was, which is why the three no-op classes are still decoded instead of answered on the opcode) | -| W9 | `compute_decoder.rs` — all of `runtime/decode/compute.rs`: the flat `Command` with forty fields, `Kind`'s thirty-four variants, `OpcodeConfidence`, `opcode_supported`/`opcode_apple_rejected`, the `BufferBinding`/`RefBinding`/`SamplerBinding`/`Size3`/`Region3` entry structs, `var_len`, and its thirteen tests | `runtime/decode/compute.rs` (whole file), `runtime/decode/mod.rs` (`pub mod compute;`), `runtime/compute_exec/{mod,vulkan,metal,tests}.rs`, `runtime/compute_session/{mod,metal}.rs`, `runtime/exec/{mod,vulkan,report}.rs`, `runtime/icb/tests.rs`, `backend/{mod,compute_session,vulkan/mod,metal/device}.rs`, `runtime/decode/ledger.rs`, `tests/{golden_vectors,wire_fixtures_reach_the_decoders}.rs` | `reims_vgpu_protocol::decode::compute::ComputeRecord` for the seventeen settled records, whose variants carry **named payloads** so `apply_record` matches thirteen of them and each arm takes the one record it handles; `decode::sync` for the two barriers, `decode::resource_state` for the compressed-reinterpretation flush, and `decode::residency::lift` for the unqualified residency pair. The four dispatches reach `Backend::execute_dispatch` as a `DispatchRecord`, which removed `resolve_dims_unknown_kind` — there is no not-a-dispatch left to refuse — and stopped the indirect forms reporting a grid of three zeroes they never carried. `ComputeAccum`'s three bind setters take an entry *contract* (`BufferBindEntry`, `ObjectBindEntry`) rather than the decoder's structs, so `has_attribute_stride`/`has_lod_clamp` stopped being flags beside a zero: the record with no stride field cannot produce a `Some`. `ComputeAccum::dispatch_type` is a `DispatchType` end to end. **Carries one guest-visible change** — a `writeDescriptor` ordinal outside `MTLDispatchType` is refused at the lift instead of being substituted with `Serial`, so the pass keeps the type the guest last stated; the `compute_dispatch_type_unknown` census survives at the refusal. **The eleven rows the ledger has not settled did not move**: `runtime/decode/compute_spi.rs` is new and decodes exactly them — the fence pair, the seven control-flow records and the two indirect-command executions — and refuses every settled opcode by name. Unlike the blit rail's unsettled four, these **drive real work**, and that difference is stated in its header rather than papered over. | `runtime::decode::compute_spi::{no_settled_compute_row_is_a_record_this_decoder_owns, every_unsettled_compute_row_reaches_this_decoder, a_control_marker_and_a_control_predicate_are_told_apart_by_their_length, the_two_command_buffer_executions_name_different_second_operands, the_fence_pair_keeps_its_two_directions_apart, an_opcode_no_compute_row_names_is_unknown_rather_than_settled}` (new — replace `control_do_while_start_empty_end_condition`, `control_if_while_and_icb_lengths` and `the_control_flow_condition_is_apples_own_layout`, and add the claim that keeps `dead/`'s prohibition structural: no settled row is decodable twice); `runtime::decode::ledger::every_compute_row_reaches_exactly_one_decoder_and_the_ledger_picks_it` (new — replaces `the_compute_decoder_recognises_every_compute_operation_the_ledger_records` and `the_compute_opcode_table_is_apples_compute_manifest_plus_four_named_exceptions`, and is strictly stronger: the rail has five decoders now, so "no row is dropped by all of them" and "no row is claimed by two" are both asserted where one decoder could only assert the first); `reims_vgpu_protocol::decode::compute::{the_two_direct_dispatches_share_a_record_and_not_a_meaning, the_two_indirect_records_have_opposite_field_orders_and_one_meaning, the_stage_in_region_writes_its_size_before_its_origin, a_bind_borrows_its_entries_and_keeps_the_slot_it_starts_at, the_offset_rebind_carries_a_stride_only_when_its_record_does, a_bind_count_that_overruns_is_told_apart_from_a_short_head}` (already at the owner — they replace `set_buffers`, `pipeline_and_dispatch`, `a_bind_larger_than_the_deleted_cap_decodes_every_entry` and `every_compute_decode_failure_names_its_own_check`); `runtime::compute_exec::tests::{a_bind_with_no_stride_field_and_one_with_a_zero_stride_are_not_the_same_slot, a_sampler_bound_without_a_clamp_and_one_clamped_to_zero_are_not_the_same_slot, a_nil_entry_clears_the_slot_on_the_wire_path_too}` (new — the entry contract at its owner); `runtime::exec::tests::an_undeclared_dispatch_type_refuses_its_record_and_leaves_the_pass_type_alone` (new — replaces `an_undeclared_dispatch_type_is_named_and_counted_before_it_becomes_serial`, and adds the claim the substitution got wrong in the other direction: a refused descriptor must not reset a pass the guest set to Concurrent); the ~59 `runtime::compute_exec::tests` executor cases (kept, re-pointed at `DispatchRecord` and the wire entry types). `rejected_and_matrix` and `property_fuzz_opcodes` have **no replacement**: `REJECTED_85`/`REJECTED_88`/`REJECTED_C7` and the `ErrUnsupportedOpcode` they distinguished have no closure-ledger rows, so the question they asked no longer exists — `no_settled_compute_row_is_a_record_this_decoder_owns` asks the ledger's version of it instead. | -| W10 | *(nothing moved yet — the legacy render decoder shrank rather than left)* | `runtime/exec/mod.rs` (`handle_render_record`'s `Fence`, `Barrier`, `UseResource` and `UseHeap` arms), `runtime/exec/report.rs` (`note_residency_declaration`, `ResidencyWriteDeclared`) | `reims_vgpu_core::operation::classify` decides the record's class from the ledger row, and the three classes that own no stream state are answered from it: `reims_vgpu_protocol::decode::sync` lifts the fence pair and all three barrier shapes, and `decode::residency::lift` lifts all four residency declarations. **The disjointness is the reason this group is separable and it is structural**: none of the three touches `StreamAccum`, and the test asserts that rather than arguing it — the indirect-command executions look equally self-contained and are not, because they push onto `acc.execute_icb`, which is why they stayed behind. A render fence's *direction* now comes from the same answer that says it is a fence, so `render_fence_opcode_unknown` — a third case for a fence that was neither an update nor a wait — is unrepresentable. `note_residency_declaration` takes `Option`s: the heap forms carry no usage and the unqualified pair carries no stages, where the flat command had both fields on every record and filled them with zeros, so "the guest declared nothing" and "the selector has no such argument" stopped being one word on the counters whose whole job is telling them apart. **Carries one behaviour change**: a barrier record shorter than its wire head is now declined as short instead of counted as a no-op. Both answers execute nothing; the difference is which line a reading gets, and the wire crate's fixture-derived length is what says an eight-byte `memoryBarrierWithResources:` is not that record. | `runtime::exec::tests::each_ledger_routed_render_class_reaches_a_counter_that_names_which_one_it_is` (new — replaces `a_residency_or_barrier_record_is_counted_rather_than_dropped_in_silence`, whose fixtures were header-only records the wire layout says are short, and is stronger in three ways: all three barrier shapes rather than two, the read/write/empty residency split rather than empty alone, and the claim that makes the group a group — no stream state moved); `runtime::exec::tests::a_render_fence_orders_in_the_direction_its_own_opcode_names` (new — an update reaches the render domain and satisfies the wait that follows it, which is the only way to tell the two directions apart from outside the fence store) | -| W11a | *(nothing moved yet — the legacy render decoder shrank rather than left)* | `runtime/exec/mod.rs` (the eleven `RenderKind::{SetPipeline,SetViewport,SetScissor,SetBlendColor,SetCullMode,SetFrontFacing,SetDepthBias,SetDepthStencil,SetStencilReference,SetRasterState,SetVisibilityResultMode}` arms, and the `setLineWidth:` half of `SetFloatState`) | `reims_vgpu_protocol::decode::render::decode` lifts all fifteen rows, applied by `runtime::exec::handle_render_stream_state`. **The disjointness claim is different in kind from W8's and W10's and the code says which**: those classes touched no stream state at all, which is a test that separates nothing on this rail because every encoder record lands in `StreamAccum`. These fifteen are separable because each is the *sole writer* of the field it sets, so no other record class can disagree with the new decoder about a value — `is_render_stream_state` is where that claim lives and is exhaustive over `RenderKind`, so a row added to the contract must be classified rather than silently joining the legacy path. Routing is on the kind and not on `classify`: every encoder record is one `OperationClass::Render`, and `RenderKind::of_opcode` answering at all is the ledger's settlement. That is why `setLineWidth:` moved and `setTessellationFactorScale:` — the same wire form with no settled row — did not, leaving half of the legacy `SetFloatState` arm live and half a misroute. **The store actions did not move and are not in this group**: `SetStoreAction` mutates `color_slots`, `depth_attach` and `stencil_attach`, which the pass descriptor writes, so those three are one later group; the binds write the six bind tables and `unrepresentable`, and the draws read the whole accumulator. **Carries one named reading change** — a plural viewport or scissor record of count zero was `ErrBadLength`, a line saying a render record failed to decode without saying which; it is now a census with the previous state standing, which is what the refusal already did and could not say. | `runtime::exec::tests::each_render_state_record_writes_the_one_field_it_names_and_no_other` (new — replaces the per-arm value assertions that the legacy state arms carried, and is strictly stronger: it destructures the whole of `StreamAccum` so a field added to the struct fails to compile until it is named, and asserts that exactly one entry differs per record, which is the sole-writer claim itself rather than an argument for it — none of the old per-arm checks could see whether a record had also moved a field belonging to another class); `runtime::exec::tests::a_plural_viewport_or_scissor_of_count_zero_keeps_what_the_stream_already_bound` (new — pins the reading change: both counters fire and both bound states stand) | -| W11b | *(nothing moved yet — the legacy render decoder shrank rather than left)* | `runtime/exec/mod.rs` (the four `RenderKind::{SetBuffer,SetBufferOffset,SetTexture,SetSampler}` arms and `apply_binds`'s stage vocabulary), `runtime/draw/mod.rs` and `runtime/draw/metal/mod.rs` (`PastTableBind::stage`) | `reims_vgpu_protocol::decode::render::decode` lifts all twelve bind and offset rows, applied by `runtime::exec::handle_render_binds`. **The disjointness claim is weaker than W11a's and the code says which**: these twelve write the six bind tables — sole writers, as W11a's fifteen were — and also the `unrepresentable` latch, which the pass descriptor writes too. That is still a group boundary because the latch is **first-wins and its insert order is the stream's own record order**, which no change of decoder can alter, where two writers of a *value* could disagree. **`Stage::Unknown` is gone from the live vocabulary**: `RenderKind::bind_stage` is total over the bind rows, so the state the flat command reached as "the record named no stage" — and which `apply_binds` answered by counting a clear against a table it could not name, and `PastTableBind::stage_name` by answering `"unknown"` — is not one a lifted bind can be in. `apply_binds` takes its entries by reference and `make` takes `&T`, so each of the five wire entry shapes reaches its own arm: a record with no stride field cannot produce `Some(0)` and one with no LOD clamp cannot produce a clamp of zero, which is what `has_attribute_stride`/`has_lod_clamp` beside a zero used to allow. The LOD clamp travels *inside* its entry, so a slot can no longer be paired with another slot's clamp — the flat command carried two parallel lists and zipped them. | `runtime::exec::tests::each_render_bind_row_writes_the_one_argument_table_its_opcode_names` (new — twelve rows against six tables, asserting the one its opcode names moved and the other five did not, and that no row refused the stream's draws; no legacy test could make this claim, because the stage came from a field the decoder had already filled in); `runtime::exec::tests::{a_strided_vertex_bind_keeps_its_stride_and_a_plain_one_reports_none, a_sampler_bind_carries_its_own_lod_clamps_per_slot}` and the ~30 other `runtime::exec::tests` bind cases (kept, re-pointed at the lift in production — they drive `handle_render_record`, so the `None`-is-not-`Some(0)` claims they already pinned now pin them at the new owner); `reims_vgpu_protocol::decode::render::{a_bind_borrows_its_entries_and_keeps_the_slot_it_starts_at, the_offset_rebind_carries_a_stride_only_when_its_record_does}` (already at the owner) | -| W11c | *(nothing moved yet — the legacy render decoder shrank rather than left)* | `runtime/exec/mod.rs` (the `RenderKind::{RenderPass,SetStoreAction}` arms), `runtime/exec/report.rs` (`note_pass_extent_for_slot`'s `&Command` parameter) | `reims_vgpu_protocol::decode::render::decode` lifts the pass descriptor and the three store-action rows, applied by `runtime::exec::handle_render_pass_state`. **The three overrides are *in* this group and not beside it**: they mutate `color_slots`, `depth_attach` and `stencil_attach`, which the descriptor writes, so splitting them would put two decoders on one attachment's `store_action` — the disagreement the plan forbids. The descriptor is one wire view: `decode_{depth,stencil,color}_attachment` each re-derived their section's base from `size_of` sums this module also wrote down, and the eight colour slots are now an iteration over `RenderPassBody::color` rather than eight offset computations. `StoreActionTarget` is total over the three rows, so the legacy arm's fourth case — a store action for none of the three, reported as `render_store_action_opcode_unknown` — is unrepresentable. The `color0` convenience block is gone with the second reading it needed: it re-pushed slot 0 onto `clears` from a separately lifted field, guarded by "it is not already there", and the loop pushes exactly that attachment under exactly that condition, so the guard could never pass. **Carries one behaviour change** — a pass record shorter than `RenderPassBody` is refused instead of read at the offsets that fit. The legacy decoder accepted anything from `PASS_MIN_PAYLOAD` (depth, stencil, one colour slot) and answered the other seven slots as unattached, which is indistinguishable from a guest that attached one; Apple's serializer writes all 592 bytes, and the short form was a tolerance for this repo's own fixtures. | `runtime::exec::tests::a_pass_descriptor_short_of_its_record_is_refused_rather_than_read_at_the_offsets_that_fit` (new — pins the behaviour change in both directions: one byte short moves no pass state at all, and the full-length record with the same first attachment is still honoured, which is what says the refusal is about the length and not the bytes); `runtime::exec::tests::each_store_action_override_reaches_the_attachment_its_target_names` (new — one pass declaring colour slots 0 and 3, a depth and a stencil attachment, all four `DontCare`, then all three overrides; the claim the two kept tests cannot make is that slot 0 stays `DontCare` while slot 3 moves, so a cross-target landing is visible rather than merely absent); `runtime::exec::tests::{a_store_action_override_reaches_the_slot_it_names, a_depth_or_stencil_store_action_override_reaches_its_own_attachment, an_unsupported_depth_attachment_is_named_not_just_dropped, a_colour_attachment_naming_a_subresource_this_device_cannot_bind_refuses_the_draws, the_pass_extent_census_scores_either_resolve_arm}` and the other `runtime::exec::tests` pass cases (kept, re-pointed — the last three had their fixtures lengthened to the record's real 592 bytes, which is itself the change being recorded) | -| W11d | *(nothing moved yet — the legacy render decoder shrank rather than left)* | `runtime/exec/mod.rs` (the `RenderKind::{Draw,DrawIndirect}` arms and `execute_indirect_draw`'s `&Command`), `runtime/exec/report.rs` (`is_indexed_draw_opcode`, deleted; `note_indirect_draw_refused`'s `&Command`), `runtime/decode/render/mod.rs` (`wire_instance_count`, now unreached) | `reims_vgpu_protocol::decode::render::decode` lifts all fourteen draw rows, applied by `runtime::exec::handle_render_draw`. **This group moves last because it is the only *reader***: it takes `bind_snapshot`, which is everything W11a, W11b and W11c wrote, and a reader can only be trusted once every writer it reads is settled. Which indirect form a record is comes from its own variant — an `IndexedIndirect` carries an `IndexRef` and a `PrimitivesIndirect` does not — so the opcode is not read a second time, and the `1 => 4, _ => 2` index-stride restatement is `IndexType::bytes` (with `IndexType::ordinal`, new, as the inverse of `parse` for the consumers that still carry `MTLIndexType` as a raw `u32`). `is_indexed_draw_opcode` is **deleted rather than moved**: it existed only because the decoder collapsed every draw form to one `Kind`, so the opcode was the only thing that could say which class a record was — and it listed **three** of the six indexed forms, which `DrawRecord::Indexed` is now total over. **Carries one behaviour change** — `wire_instance_count`'s `.max(1)` is gone, so a selector carrying no `instanceCount:` argument draws one instance (Metal's own default for it) and a guest that wrote `instanceCount:0` gets the zero it wrote. Those were one number in the decoder, and three arms of this device disagreed about the zero: `backend::metal::render` refuses it by name — a refusal the clamp made unreachable — and `runtime::icb` already handed the same argument to Metal unclamped. The clamp read zero on every driven boot, so this is inert on measured workloads and stops the disagreement on unmeasured ones; the `draw_instance_count_zero` census survives at the lift. A count above `u32::MAX` is refused as `render_draw_count_out_of_range` rather than truncated, which is `narrow_count`'s rule at its new site. | `runtime::exec::tests::a_draw_with_no_instance_count_and_one_asking_for_zero_are_not_the_same_draw` (new — pins the behaviour change end to end: the plain form records one instance, the written zero records zero *and* raises the census, which no test could assert while the clamp made the two one number); `runtime::exec::tests::a_compact_draw_and_its_wide_encoding_record_the_same_draw` (new — the compact and wide encodings of one shape have different field orders and different widths, and must produce the same `PendingDraw`, or a guest whose count crossed 65535 would draw different geometry than the same guest below it); `runtime::exec::tests::{wide_indexed_draw_reaches_pending_draw, a_base_vertex_and_base_instance_reach_the_pending_draw, every_decoded_draw_in_a_stream_reaches_the_draw_list, an_indexed_draw_with_no_index_buffer_is_named, a_bind_after_a_draw_does_not_rewrite_that_draws_snapshot, a_dropped_draw_names_which_check_refused_not_just_its_class}` and the other `runtime::exec::tests` draw cases (kept, re-pointed at the lift in production); `reims_vgpu_protocol::decode::render`'s draw-layout tests (already at the owner — they are what makes the per-form offsets one declaration rather than six) | -| W11e | *(nothing moved yet — and this row is where the reason stops being "the decoder shrank")* | `runtime/exec/mod.rs` (`render::decode` and the eleven remaining `RenderKind` arms, including the `OtherAccepted` catch-all), `runtime/exec/vulkan.rs` (`render_pipeline_refs`), `runtime/exec/report.rs` (`note_unnamed_icb_execute`'s `&Command`) | `runtime/decode/render_spi.rs` is new and decodes exactly the thirty-one rows the ledger has not settled: the five patch draws, the two `executeCommandsInBuffer:` forms, the six pass-property records, the three store-action-options records, the two tessellation records and the twelve amplification and tile-shader records. It refuses every settled opcode by name, so no record on this rail has two readings. **After this commit no production path reaches `runtime::decode::render::decode` at all** — the Vulkan preflight's pipeline pre-scan was the last one, and it now uses the same lift the walk does, so a pre-scan can no longer disagree with the walk about which records set a pipeline. The module's three refusals answer three different questions where the legacy decoder had a catch-all: `ErrUnknownOpcode` keeps the deduped fail-visible line **and the wire capture**, because for an opcode no row names the bytes are the whole diagnostic; `ErrSettledElsewhere` is a routing bug; `ErrShort` is a record. **The legacy file does not move yet and the reason is not the usual one**: `runtime/decode/render/mod.rs` also holds the live render-pass attachment model — `ColorAttachment`, `DepthAttachment`, `StencilAttachment`, `ScissorRect`, the attachment offsets, the three `*_from_wire` lifts and `attachment_subresource_is_bindable` — which production still uses and which is not a decoder. Splitting the file is W11f, and it is what disconnects the decoder. | `runtime::decode::render_spi::tests::{no_row_a_render_kind_names_is_a_record_this_decoder_owns, every_row_this_decoder_owns_is_an_unsettled_render_row, an_opcode_no_render_row_names_is_unknown_rather_than_settled, the_wide_patch_draw_opcode_is_resolved_by_length_and_refused_without_one, the_store_action_options_are_not_wider_store_actions, an_amplification_count_reports_whether_any_mapping_moves_a_view, the_two_command_buffer_executions_name_different_second_operands, every_pass_property_record_reaches_an_arm_of_its_own, a_tile_dispatch_grid_is_not_the_threadgroup_memory_length, a_record_short_of_its_body_is_refused}` (new — they replace the legacy decoder's `the_wide_patch_draw_opcode_is_resolved_by_length_and_refused_without_one`, `the_store_action_options_are_not_wider_store_actions`, `vertex_amplification_decodes_at_the_widths_the_serializer_wrote`, `a_single_view_mapping_that_offsets_a_view_is_not_the_default`, `execute_commands_range_and_indirect`, `every_pass_property_record_reaches_an_arm_of_its_own` and `a_tile_record_is_decoded_rather_than_accepted_without_a_claim`, and add the two claims that keep `dead/`'s prohibition structural: no settled row is decodable twice, and no row is claimed here that the ledger does not carry); `runtime::decode::ledger::every_render_row_reaches_exactly_one_decoder_and_the_ledger_picks_it` (new — replaces `the_render_opcode_table_is_exactly_apples_render_manifest` and `the_accepted_window_ends_where_apples_render_manifest_does`, and is strictly stronger: the rail has four decoders now, so "no row is dropped by all of them" and "no row is claimed by two" are both asserted where one decoder could only assert the first. It is also the first of the three rail cross-checks to meet a `Closure::Refused` row, and it settles what a contract refusal claims: nothing) | -| W11f | `render_decoder.rs` — the decoder half of `runtime/decode/render/mod.rs`: `DecodeStatus`, `Kind`'s thirty-four variants, `Stage`, the flat `Command`, `DecodedBufferBind`, `wire_view`/`narrow_count`/`wire_instance_count`, `opcode_supported`/`opcode_above_the_encoder_window`/`unclaimed_accepted_opcode` and the eighty-arm `decode`; and `render_decoder_tests.rs` — thirty-nine of its forty-four tests, plus the three `runtime::decode::ledger` cross-checks that named it | `runtime/decode/render/{mod,tests}.rs` (both deleted), `runtime/decode/mod.rs` (`pub mod render;`), `runtime/exec/{mod,tests,report}.rs`, `runtime/draw/{mod,tests}.rs`, `runtime/draw/metal/mod.rs`, `runtime/decode/ledger.rs`, `crates/reims-vgpu-wire/src/ops/render_pass.rs`, `tests/{golden_vectors,wire_fixtures_reach_the_decoders}.rs` | Nothing — the decoder's replacements all landed in W11a–W11e. **What this row does is the disconnect**, and it needed a split first: the file held a decoder *and* the live render-pass attachment model, and only the decoder had been replaced. The model — `ColorAttachment`, `DepthAttachment`, `StencilAttachment`, `ScissorRect`, `AttachSubresource`, `LevelSupport`, the attachment offsets, the three `*_from_wire` lifts, `attachment_subresource_is_bindable` — is now `runtime::render_pass`, out from under `decode/` because it answers "what can this device bind" and not "what did the guest write". Five of the forty-four tests covered the model rather than the decoder and moved with it. **One defect fell out of the move and is fixed at its owner**: `wire_fixtures_reach_the_decoders::no_decoder_reads_a_bit_apples_serializer_never_wrote` began failing on `0x1a`, because `RenderRecord::WriteDescriptor` borrows the whole `RenderPassBody` and the derived `Debug` rendered the three `unwritten_above_*` fields — bytes the wire crate's own doc calls "the guest's stale ring". The three bodies have hand-written `Debug` impls now that omit them; `PartialEq` is untouched, because byte equality over a descriptor is a legitimate and different question. | The thirty-nine moved tests' replacements are the ones W11a–W11e's rows already name, and the register is where that is checked rather than assumed: the fifteen state rows by `each_render_state_record_writes_the_one_field_it_names_and_no_other`, the twelve binds by `each_render_bind_row_writes_the_one_argument_table_its_opcode_names`, the pass descriptor and store actions by `a_pass_descriptor_short_of_its_record_is_refused_rather_than_read_at_the_offsets_that_fit` and `each_store_action_override_reaches_the_attachment_its_target_names`, the draws by `a_draw_with_no_instance_count_and_one_asking_for_zero_are_not_the_same_draw` and `a_compact_draw_and_its_wide_encoding_record_the_same_draw`, the thirty-one unsettled rows by `runtime::decode::render_spi::tests`' ten, and the three ledger cross-checks by `every_render_row_reaches_exactly_one_decoder_and_the_ledger_picks_it`. Kept and re-homed: `runtime::render_pass::tests::{depth_and_stencil_pass_slots, depth_and_stencil_records_end_where_the_next_section_begins, a_scissor_covers_its_target_only_when_every_term_says_so, every_field_of_the_attachment_prefix_decides_bindability, a_colour_attachments_level_does_not_swallow_its_slice}` — the five that were about the model all along. Re-pointed: `tests::wire_fixtures_reach_the_decoders::render_verdict` (now the union of the rail's four decoders, and it lost the `Kind::OtherAccepted` arm — an `Ok` meaning "no arm claimed this", which is what once hid the LOD-bearing sampler binds behind a passing run) and `golden_vectors::corpus_property_random_decode_no_panic` | - -## Seam 6's structural zeros, as a scoreboard - -The plan states these as required steady-state values. It does not say which are -met, and a table of aspirations reads exactly like a table of results — so this -is where the current answer lives, with the number it was read from. Every row -below is off a driven macos-15 x86/Vulkan boot behind a live-validation row — -the 172 862-draw one, except where a row names the 164 129-draw boot that added -the access-mode and framing censuses — or off a named off-VM gate. - -| Metric | Required | Now | Read from | -|---|---:|---|---| -| Threads created per EXEC, command buffer, draw, save, or watchdog | 0 | **met** | fn `a_watched_dispatch_that_returns_creates_no_thread_of_its_own`, fn `sixty_four_saves_create_no_thread_beyond_the_one_owner`; both count `/proc/self/task` after the single owner is up. The two violations were a watchdog thread per compute dispatch (`5c1be382`) and a persistence thread per pipeline-cache save (`b0bb5b8a`). | -| Heap allocations per steady-state draw | 0 | **met, for the draw** | fn `a_warm_repeat_draw_that_binds_descriptors_and_vertex_buffers_does_not_allocate`: 0 trips, 0 bytes, on a draw binding one storage buffer and three vertex attributes. Compute dispatch is not measured this way and is not claimed. | -| Full binding-table rebuilds on an unchanged draw | 0 | **met** | `descriptor_push_held=9 680` draws sent nothing, and since `191b06c9` they also *build* nothing: the write structures are derived only by the consumer that sends them. | -| Standalone stamp submissions | 0 | **met** | `gpu_stamps=24 852` against `queue_async_submits=2 404`, which equals `batch_flushes` exactly. Stamps ride a batch that was being submitted anyway; none adds a submission. | -| Native submissions per draw | 0 | **met in the sense the plan means** | `queue_async_submits=2 404` for `draws=172 862` — one submission per 72 draws, and every one of them is a batch flush, never a draw. | -| Cache misses for a live unchanged contract object after first resolution | 0 | **met to within first use** | `layout_hits=48 880`/`layout_misses=59`, `pipeline 48 610`/`329`, `pass 61 828`/`20`, `shader 97 637`/`142`. The misses are first sights: `attr_sets` settles at **14** for the boot, which is the plateau these unbounded caches are justified by. | -| Shared/global mutex acquisitions per draw | 0 | **not met** | `static ENGINE: Lazy>`. Every draw takes it. This is the process-global engine named above, and nothing else on this list is blocked on anything else. | -| Global atomic census updates per draw | 0 | **not met** | `EngineCounters` is a bag of process-global atomics and a draw bumps a dozen. Uncontended today *because* the engine mutex already serialises draws, so it is the same blocker wearing a different hat: sharding the counters before the lock goes buys nothing measurable. | -| Host GPU waits for ordinary commands | 0 | **met** | `ring_retire_blocks=0` and `fence_timeouts=0` over 172 862 draws, with `readbacks=0` — no draw ever waited for a ring slot's fence, which is the only wait a steady-state draw could take. The two warm-draw gates assert both deltas at zero, so it is a standing check and not one boot's reading. `render_post_wait_skips=49 550` is the positive half: the skip path ran. | -| Wakeups whose scheduling unit is a draw | 0 | **met at the queue owner** | `queue_async_submits=2 404` for 172 862 draws, equal to `batch_flushes` — the queue owner wakes once per batch, never per draw. Only that thread is measured; a wakeup elsewhere would not appear here. | -| Re-scans of already resolved EXEC bytes | 0 | **met** | `exec_stream_framed=18 421` against `exec_streams_loaded=18 421` — a ratio of exactly one, on the driven macos-15 boot in the last live-validation row. `walk_stream` is the crate's one framing site and it is the counted one. Every submission on that boot carried a single stream (`exec_cmdbufs_1=18 421`), so the boot cannot tell "once per stream" from "once per submission"; fn `a_submission_frames_each_stream_once_and_preflight_frames_none` is what does, on two streams, and it also holds the plan step to framing none — `preflight_submission` answers from `ExecWork` rather than from the packet's bytes. | -| Repeated transfers for one range, version and direction | 0 | **met for buffers, unmeasured for images** | `buffer_bind_reuses=304 017` and `buffer_index_bind_reuses=892`: every one is a bind served from a copy the command buffer already held rather than a second transfer of the same bytes. The image side is not the same claim — `sampled_reuploads=45` at 15.3 MB are lawful, since the content version moved, but nothing here separates a lawful reupload from a repeated one. | -| Pipeline compiles on a Ready pipeline draw | 0 | **met** | fn `warm_identical_dispatch_zero_creates_and_allocs` and the `creates`/`allocs` deltas the batch suite asserts at zero on a warm draw. | -| Supported operations reaching an unknown access-mode fallback | 0 | **not met, 81 % → 2.6 %, and the residue is not where this table said it was** | Was `access_mode_unknown=342 987` against 81 116 known — 81 % of every access the dependency graph ordered against — because `ExecWork::footprint_into` passed `None` for the pipeline's `BindingUsage` and nothing in the tree constructed one. Both rails now publish, and a driven macos-15 boot reads **`unknown=9 375` against `read=331 995`, `write=10 383`, `read_write=12 800`** — **2.6 %**. **`UsageCensus` moved this row from inference to measurement, and corrected it twice.** `unknown_from_a_table=0`: **not one** `Unknown` participation comes from a published table, so the tables are already as narrow as the reflection can make them. This row previously said the residue was "a device buffer whose read-versus-write the translator's facade does not carry"; that was read off an **older translator revision's** doc. The pinned one populates buffer access "from Metal's declared access and tightened by specialized-entry parameter attributes", and a lookup wired to catch the gap measured **zero hits on every buffer this guest declares**, so the gap does not exist here and the SPIR-V dataflow pass written for it was reverted rather than landed. `unknown_with_no_table=3 589` is the structural population: the packet that *first names* a pipeline draws against it, and `pipeline_leases` is that same packet's walk output, so the walk necessarily precedes the declaration it produces (88 of 93 first sightings read `model_pipeline=unleased`). Coarse rather than wrong, and closing it means re-walking a parked packet after its pipelines go `Ready` — sound only if the model says an admitted ordering position may restate what it depends on. **The remaining 5 786 are neither**: they are participations the *records themselves* declare, not slots an encoder bound, so they are outside `BindingUsage` entirely and no publisher can narrow them. That is where this row goes next, and it is a different subsystem than the one this table has been pointing at. fn `a_kernel_publishes_the_compute_stage_and_leaves_the_render_stages_unpublished`, fn `a_kernel_stage_in_refuses_the_stage_under_its_own_reason`, fn `the_translators_placeholders_cost_the_stage_nothing`, fn `the_published_usage_memo_is_dropped_by_everything_that_drops_the_usage`, fn `the_reason_a_draws_slots_stayed_unknown_is_counted_and_not_summed`, fn `a_dispatch_is_answered_or_not_and_never_half`, fn `an_unknown_is_charged_to_the_table_that_conceded_it_or_to_the_absence_of_one`. | -| Supported operations reaching an unknown stage fallback | 0 | **not measurable on the live path** | The instrument is `reims_vgpu_vulkan::barrier::BarrierPlan::unmapped_bits`, which reports the stage bits that had no row and were therefore widened to `ALL_COMMANDS`. The engine does not use that module — it builds its own barriers — so nothing on a live path can report it. This is a cutover item, not a missing counter. | - -**Do not read an unmeasured row as a zero.** The plan's own argument for this -table is that an unmeasured zero and a violated one are indistinguishable from -the outside, and the access-mode row is what that argument was for: it read as -a plausible zero for as long as nobody counted, and the first count came back -at 81 %. One row is unmeasured now — the stage fallback — and it is unmeasured -for a structural reason rather than a missing counter. - -## Live validation - -A cutover is verified against a guest, not only against a suite, and this is -where that is recorded — a row whose gates are green and whose rail has never -run under an unmodified guest has not been checked where it matters. - -**How to read the absolute counts.** Route counters are per-second windows and -a boot's total is their sum. Rows landed before `37f6f953` were summed by -selecting census lines on one of the keys being summed, which silently skips -every window in which *that* key did not fire — measured at a 3.3x undercount -on `pipe_memo_hit` in one boot. Select census lines on `store_routes`, the dump -line's own marker, instead. Two keys summed over the same window set still compare -exactly, so every **equality** below stands and every magnitude is a lower -bound. A **zero** does not follow from that sum at all: a counter is only -printed in a window where it fired, so one that fires only in skipped windows -reads zero when it is not. Establish a zero by asking whether the key appears -in the log *at all* — `grep -c 'key=' /tmp/reims-vgpu-fail.log` — which needs no -window arithmetic and is exact. Every zero this file claims has been -re-established that way. - -| Rows | Pathway | Result | -|---|---|---| -| W1–W7 | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-13` (x86 macOS guest, Linux/KVM host, Vulkan rail) | Guest reached the desktop; `blit_kind_b2t_us` / `blit_kind_t2b_us` / `blitrec_copy_n` non-zero, so real guest transfers ran through the lifted records; zero lines on `blit_fail`, `blit_decode`, `blit_record_wrong_class`, `blit_transfer_not_a_transfer` and `*_misrouted` across 2306 log lines. | -| W8–W9 | same | Guest reached first frame through the resident zero-copy path; the compute rail executed real work (`compute_n` up to 16 dispatches in a packet, `compute_pipeline_hits`, `compute_buffer_extent_narrowed`, guest-page writeback) and the blit and draw rails were unaffected (`blit_kind_b2t_us`, `draws`); **zero** lines on `compute_record_misrouted`, `compute_barrier_not_a_barrier`, `compute_residency_without_usage`, `compute_record_unframed`, `compute_decode_settled_elsewhere` and `compute_decode_unknown_opcode` across 4203 log lines. | -| W10 | same | Guest reached the desktop through the resident zero-copy path and the render rail did real work — `draws` up to 893 in one packet, `render_noop_barrier` up to 76, `fence` up to 14 with real wait times, and the bind reach bands (`render_bind_reach_{buffer,texture,sampler}_le`) populated. **Zero** lines on `render_record_misrouted`, `render_fence_not_a_fence`, `render_barrier_not_a_barrier`, `render_record_unframed`, `render_residency_resource_without_usage` and `render_record` declines across 7823 log lines. The four residency counters read zero, which is a reading and not a gap: this guest's compositor declares no residency on the render encoder, so the class is routed and unexercised — the barriers and the fence pair are what this boot actually validated. | -| W11a | same | Guest reached the desktop; the render rail ran 768 draws through the lifted state records, and the rail's own dynamic-state census is the positive evidence rather than the absence of failures: `dynstate_{pipeline,depth_bias,line_width,blend_constants,depth_stencil}_held=185`, `dynstate_raster_held=718`, `dynstate_viewport_held=153`, `dynstate_scissor_held=120`, `pipeline_hits=764` — every one of those is a value that reached `PendingDraw` from a record `handle_render_stream_state` lifted. **Zero** lines on `render_record_misrouted`, `render_state_record_not_state`, `render_record_unframed`, `render_record` declines and `render_decode` across 8019 log lines. The two count-zero counters this step added read zero, which is the reading their comment predicted: Metal requires at least one viewport, so a guest emitting the empty array is the case worth a line and not the case worth expecting. | -| W11b | same | Guest reached the desktop; 763 draws, and all three bind classes ran through the lifted entries — `render_bind_reach_buffer_le16` 20 records, `render_bind_reach_texture_le16` 19, `render_bind_reach_sampler_le16` 19, `vertex_buffer_bind_slots=2878` reaching the encoder. **Zero** lines on `render_record_misrouted`, `render_bind_record_not_a_bind`, `render_record_unframed`, `render_record` declines and `render_decode` across 7944 log lines, and zero on `render_*_bind_slot_past_table` and `render_buffer_offset_slot_{unbound,past_table}` — the three losses `apply_binds` can report. Every record this guest issued ended at slot 16 or below, which is the same band the pre-cutover reading found, so the stage now coming from the opcode did not move any bind. | -| W11c–W11d | same | The whole render encoder now runs through the lifted records, and this is the boot that says the pixels are the same ones. Guest reached the desktop; 788 draws, `pass_hits=788` and `layout_hits` matching them one for one, `render_pass_continuations=499`, and the scissor-coverage bands populated (`draw_cover_loaded_full_scissor=209`, `draw_cover_loaded_partial_scissor=453`) — every one of those is a value a draw read out of a `PendingDraw` the new lift assembled from a descriptor the new lift read. **Zero** lines on `render_record_misrouted`, `render_pass_record_not_pass_state`, `render_draw_record_not_a_draw`, `render_record_unframed`, `render_record` declines, `render_draw_count_out_of_range`, `render_store_action_slot_undeclared` and `render_store_action_out_of_range` across 7932 log lines. The two censuses W11c and W11d added or moved — `draw_instance_count_zero` and the short-pass refusal — read zero, which is what the clamp's own measurement predicted for the first and what a serializer that writes all 592 bytes predicts for the second. | -| W11e–W11f | same | The rail with no legacy decoder left behind it, and the boot it is recorded from did not reach the desktop — the guest kernel panicked, and the panic is not this cutover's. Two boots on this tree panicked (Dock, `CR2: 0x1e8`; NotificationCenter, `CR2: 0x0`) and a **control build of `9f58d047`, the commit before W11e**, built and pinned in an isolated worktree, panicked the same way and sooner (fontworker, `rw lock count underflow`, 618 log lines against 1579 and 2391). All three carry the three markers `journal/2026-09-01-x86-guest-panic-not-the-backport.md` established as separating a panicking boot from a clean one — `row_pitch_mismatch`, `spirv_capability added` and the `guest_bpp=16 shader_bpp=4` storage specialization — which are compute/storage-path work no render decode touches. What the render rail did do before each panic is the positive evidence: 222 draws with `pass_hits=222` and `layout_hits` tracking them, `render_pass_continuations` up to 138, `render_noop_barrier` up to 47, `pipeline_hits` up to 195, and all three bind reach bands populated (`render_bind_reach_{buffer,texture,sampler}_le16`) — every one of those read out of a record `render_spi` lifted, since no other decoder is in the tree. **Zero** lines on `render_record_misrouted`, `render_decode_settled_elsewhere`, `render_decode_unknown_opcode`, `render_record_unframed`, `render_state_record_not_state`, `render_bind_record_not_a_bind`, `render_pass_record_not_pass_state`, `render_draw_record_not_a_draw` and `render_record` declines, across both boots. A desktop-reaching boot on this rail remains owed and is recorded here as owed, not as done. | -| W11e–W11f | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail) | The desktop-reaching boot the row above records as owed. A second rail was tried because macos-13 panicked three times running, and macos-15 ran the full 420 s without one — which is also what says the panic is the rail's and not the tree's. The render rail did an order of magnitude more work than any earlier row: **6947 draws** in one packet, `pass_hits=12354`, `layout_hits=6940` and `pipeline_hits=6897` tracking them, `render_pass_continuations=6384`, `render_noop_barrier=198`, `vertex_buffer_bind_slots=18509` reaching the encoder, the dynamic-state census populated across the board (`dynstate_raster_held=6598`, `dynstate_viewport_held=5393`, `dynstate_scissor_held=5227`, `dynstate_pipeline_held=5407`), the scissor-coverage bands split 5958 full / 767 partial, and all three bind reach bands populated. Every one of those is a value that reached the encoder from a record `render_spi` lifted, because no other render decoder is in the tree. **Zero** lines on `render_record_misrouted`, `render_decode_settled_elsewhere`, `render_decode_unknown_opcode`, `render_record_unframed`, `render_state_record_not_state`, `render_bind_record_not_a_bind`, `render_pass_record_not_pass_state`, `render_draw_record_not_a_draw`, `render_record` declines, `render_draw_count_out_of_range` and `render_store_action_out_of_range`, across 8712 log lines. `draw_instance_count_zero` and the short-pass refusal read zero here too, on a workload seven times the size of the one that first predicted it. | -| *(no register row — `898f1603`, the naming authority)* | same | Recorded here because it changed live resolve and delete behaviour without moving a file: `DeviceState` owns one `reims_vgpu_core::namespace::Namespace` per task, `objects::resolve_resource` is the single declaration site, and `TaskResources` is keyed by the issued `ResourceId` rather than by the guest's reference. One model and not two, because a retired name cannot be spelled. Guest reached the desktop through the resident zero-copy path. **Zero** on all three refusals the change could produce — `object_declared_over_a_live_name`, `task_resource_slot_repointed`, `storage_extent_unrecovered` — across a denominator of **137 041** `task_resource_reexamined` comparisons, twice the largest earlier reading. The declaration census summed exactly for the third time (`declared_storage_dedicated=1566` + `declared_storage_no_bytes=72` = `backing_identity_asked=1638`), so every object this guest constructed was both nameable and declarable by the authority that now names it. | -| *(no register row — `1d52c36f`, on-demand naming)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15` | Recorded here for `898f1603`'s reason: it changed what the device does at run time without moving a file. Naming a guest reference is split from constructing it, because a namespace populated only by construction cannot answer a resource-lifetime list — the boot before this one measured **49 unanswerable refs of 1339**, and the model's list join refuses a whole packet for one unresolved ref. Guest reached the desktop. `lifetime_ref_already_named=1213` + `lifetime_ref_named_on_demand=19` = `lifetime_ref_asked=1232` exactly, with `lifetime_ref_unnameable=0` and `lifetime_ref_list_would_refuse=0` — **the residue closed completely**. Naming ahead of construction displaced nothing (`object_declared_over_a_live_name=0`), and the declaration census summed exactly for the fifth boot running (`declared_storage_dedicated=1510` + `declared_storage_no_bytes=54` = `backing_identity_asked=1564`, `storage_extent_unrecovered=0`). The same boot carries `4edca0aa`, which routes all twelve lifetime commands through `reims_vgpu_core::lifecycle::operation`; that path has no production caller yet, so this boot validates the naming door and not the bridge. | -| G1 | Nothing — no file moved. `DeviceState::active_child_mask` and `DeviceState::channels_defined_by_packet` are **gone as fields**, and the two arms that wrote the first are gone with them. | `model/state.rs`, `runtime/drain/mod.rs`, `runtime/mmio.rs` | `reims_vgpu_core::session::SessionModel`, held by `DeviceState::session` and reached through `child_domain_open` / `open_child_mask` / `drainable_child_mask`. **The first group, and it moves a lifetime rather than a decision.** `active_child_mask` answered two unrelated questions with one bit — "is this a publication domain the guest defined" and "is there work waiting here" — written by a channel definition, a locked doorbell register write, and a lock-free ring. Openness is now the model's `open_channels`, with `apply_control` as its one writer; "there is work here" stays `pending.child_mask`, which the two doorbell events write and which no longer claims a definition; the union is derived. **The envelope did not move**: stamps, ordering position and completion word stay with the drain for every class, and move when the ordering core does. What this buys immediately is the model's two guards, which this device did not have — a redefinition of a live domain and a free of an undefined one are now refusals rather than silent bit arithmetic, reported through `note_channel_transition_verdict`. | `runtime::drain::tests::a_definition_opens_the_domain_in_the_model_and_a_doorbell_does_not` (new — drives all three events that used to write the field and asserts only the definition moves openness); `runtime::drain::tests::the_channel_transitions_the_model_would_refuse_are_counted_apart` (now reads the model's verdict rather than a shadow mask); `runtime::drain::tests::a_packet_on_a_doorbell_only_domain_is_told_apart_from_one_on_a_defined_domain` (re-sourced onto `child_domain_open`). Re-pointed rather than replaced: every test that opened a channel by assigning the mask now goes through `DeviceState::open_child_domains_for_test`, which is the owner's own door — a fixture that could write openness directly would be exercising the second record this group removed. | -| G2 | Nothing — no file moved. `DeviceState::namespaces: Mutex>` is **gone as a field**, replaced by `lifecycle: Mutex`; `declare_object` returns the owner's refusal instead of always succeeding, and the twelve lifetime commands each reach `Lifecycle::apply`. | `model/state.rs` (the four namespace doors, `define_task`, `delete_task`), `runtime/objects/mod.rs` (`declare_object_name`'s task census, now the owner's refusal), `runtime/drain/mod.rs` (the nine wire-borne lifetime arms) | `reims_vgpu_core::lifecycle::Lifecycle` — namespaces, per-task heaps and session content authority in one owner, reached only through `DeviceState`'s lifetime doors. `LadderRung::NoTaskSpace` is the rung below `no_list_entry` the refusal needed. | `a_declaration_into_an_undefined_task_is_told_apart_from_one_into_a_live_task` now asserts the **refusal** rather than counting the difference; `a_task_redefinition_reads_its_root_move_from_the_model` holds `define_task`'s two routes to `Redefinition::root_moved` instead of a second copy of the previous directory; `a_deleted_name_stops_resolving_and_its_teardown_is_the_models` holds the teardown the device routes on and the name's resolution to one owner; `a_lifetime_command_on_an_undefined_task_is_told_apart_from_one_on_a_defined_task` (from `d2a90d93`) now also drives `apply_lifetime`'s refusal path. | -| G3 | `pending_stamp.rs` — `PendingStamp` (the per-drain coalescing latch, `latch` / `owed` / `discharges`), `StampVerdict` and its `and`, the latch-answering branch of `note_packet_stamp_waits`, and the three tests that walked them. The three `break`s the verdict drove, `stamp_deferred_mask` and `retry_stamp_held_timelines` went with `f0d7c6cc` itself. | `runtime/drain/mod.rs`, `runtime/drain/tests.rs` | The **ordering and publication group**, wired by `f0d7c6cc` and cleared of its last dropped-work regression by `dff03408`. Both drains put every arrived packet into `reims_vgpu_core::session::SessionModel` through `runtime::drain::admit_and_park` and take work back out through `settle_model_work`; the ring head advances unconditionally, and a packet that cannot run yet holds an ordering *position* rather than a consumer pointer. There is no latch because there is no window in which a completed packet's word is unpublished — completing a position publishes it — and no verdict because nothing chooses. `Unevaluable` is the one arm that moved rather than vanished: `admit_and_park` drops a wait naming a slot outside the stamp page before admission and counts `packet_stamp_wait_unresolvable`, which is the same asymmetry stated where a packet is admitted instead of where a ring head is moved. | `a_packet_whose_stamp_wait_is_unmet_is_parked_until_the_slot_reaches_it` drives the whole cycle end to end — admitted, parked, slot advanced, released, completed — which is what the latch and the verdict existed to approximate one packet at a time; `a_stamp_wait_naming_a_slot_that_cannot_exist_runs_rather_than_parking` keeps `StampVerdict::Unevaluable`'s claim against `admit_and_park`'s filter and asserts nothing is parked on such a wait. For the latch's own two properties the owner's tests replace the drain's: `a_wrapped_stamp_still_advances_its_slot` and `a_stamp_that_does_not_advance_its_slot_publishes_nothing` hold the wrapping-signed monotonicity `PendingStamp::latch` was taking a maximum for, and `a_stamp_wait_participates_and_a_wrapped_value_still_discharges_it` with `a_completion_stamp_answers_a_stamp_wait_from_another_packet` hold what `PendingStamp::discharges` answered — including the case it could not, a wait on a slot some *other* channel writes, which its own doc measured at 2 836 avoidable holds a boot. | -| G1 | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload (three rounds of launching and quitting five applications over ssh) | The first group's own boot, and the one the row above records as owed. Guest reached the desktop and presented frames; **11 095 draws** in one packet, the largest workload any row here has measured. The group's own claim is the three counters and all three are the safe answer: `channel_transition_model_agrees=5` with `channel_open_of_open_domain=0` and `channel_free_of_undefined_domain=0` — the model's two guards, which this device did not have before the group, refused nothing the guest asked for. `child_packet_domain_defined=2180` with `child_packet_domain_undefined=0`, which is what says the other behaviour delta costs nothing: a domain that was rung and never defined is no longer re-published by the stranded-FIFO rescue, and this guest puts no packets on such a domain. Five channel transitions is the population and not a sample — it does not move under the workload, because this guest establishes its FIFO set once at accelerator start and per-application contexts share those channels. Zero lines on all three routes across 20 722 log lines, and nothing on stranded FIFOs, channel lifetime or a wedge. The device-info reply census agreed for the fourth boot running (`device_info_reply_before_any_identity=1`, `after=0`). | -| *(no register row — `0806b19e`, the declaration door)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload | Recorded here because it changed a production path — every object this device names goes through it — without moving a file. `DeviceState::declare_object` takes a `reims_vgpu_core::lifecycle::Storage` instead of an `Option`, so the two call sites lose a duplicated flattening and the door speaks the vocabulary `Lifecycle::create_resource` takes. The half that matters is the distinction the old signature could not carry: "this object owns no memory" and "this device could not describe storage that exists" were both a `None` backing, and under the new owner the first is a claim to the content authority that the second must not make. Guest reached the desktop and presented frames; **15 937 draws**, the largest workload the register has measured. `object_declared_with_undescribable_storage=0` read **directly** — the floor `storage_extent_unrecovered` had predicted by proxy on six boots — with `object_declared_into_an_undefined_task=0` of 1095, `object_declared_over_a_live_name=0`, and `declared_storage_dedicated=1089` + `declared_storage_no_bytes=25` still summing. The same boot carries `fe2e1f94`'s two `&self` doors on `Lifecycle`, which have no production caller and are not validated by it. | -| *(no register row — `d2a90d93`, the lifetime-task census)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload (three rounds of launching and quitting five applications over ssh) | The resource-lifecycle group's **last identified refusal**, counted before the group moves — the same gate G1's channel definition got. `Lifecycle::apply` answers `NoSuchTask` for eleven of the twelve lifetime commands and the refusal loses the whole packet, so the question is whether this guest ever sends one. Guest reached the desktop and was driven through three rounds of five applications: **`lifetime_command_in_a_defined_task=14 644`, `lifetime_command_in_an_undefined_task=0`**, with `object_declared_into_an_undefined_task=0` of 3902 re-confirmed on the same boot and no line on the failure channel. Every lifetime command this guest sends names a task a `CmdDefineTask2` opened. The namespace refusals are *not* in this reading and the drain's module doc says why: after the move the same `Lifecycle` answers the resolution and the apply, so `Refusal::Namespace` is unreachable by construction rather than unobserved. | -| G2 | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload (three rounds of launching and quitting five applications over ssh) | The group's own boot, and the first on which the semantic model — not this device — owns every object name. Guest reached the desktop and drove real work: `draw_scissor_full=42 769` + `draw_scissor_partial=38 270`, `walk_records_render=34 624`, and **no line at all on the failure channel**. Every route the cutover added read zero: `lifetime_command_refused`, `lifetime_operation_unresolved`, `lifetime_effect_unacted`, `lifecycle_transfers`, `lifecycle_storage_freed`, `object_declared_into_an_undefined_task` and `no_task_space` are all absent. The positive evidence is that the model did the work rather than that nothing broke: **`lifetime_command_in_a_defined_task=15 177`** and **`object_declared_into_a_defined_task=4085`** all through `Lifecycle::apply`; the teardowns the device routes on are the model's (`object_teardown_now=2268`, `object_teardown_no_storage=428`, `object_teardown_held_by_peer=2`); and `map_audit_consistent=8822` with no finding, which is the audit run off `Remap::established` rather than off a second reading of the opcode. One known floor, now counted rather than inferred: of 204 re-points, **170** reached the model as a `ReplacePhysical` and **34** did not — `replace_physical_storage_undescribable`, a reference whose new storage this device cannot describe, whose content authority therefore stays on the old pages. | -| *(no register row — `12da7555`, the class census)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload | The **ordering and publication group's** denominator, taken before that group moves, and it found the group's one blocker rather than confirming a zero. `SessionModel::admit` refuses `UnknownCommand` and `UnestablishedContract`, both of which are `transaction::classify` answering `None`. This boot: **`packet_class_exec=20 802`, `packet_class_lifecycle=13 505`, `packet_class_present=2140`, `packet_class_query=13`, `packet_class_control=11`** — 36 471 classified — and **`packet_class_unclassified=2166`, every one of them child `0x28` `CmdDeleteObject`**, whose ledger row is `Closure::Unresolved`. Five and a half per cent of the stream, one opcode. The kind census then says the open question is **10 packets wide**: 2148 of the 2166 delete a sampler state, 4 a depth-stencil state and 4 a render pipeline state — the three kinds this device tracks and retires (`sampler_state_deleted=2143`, `ds_state_deleted=4`, `pipeline_state_deleted=4`) — and the eight untracked kinds are 5 functions, 3 compute pipeline states and 2 fences, exactly `cmd_delete_object_unimplemented=10`. The row holds back 2156 packets whose ref space is already resolved in order to be honest about 10 whose is not. The traffic is also over half exec, which puts the group's risk in the class whose payload the bridge cannot build at all — see `ingress::Gap::ExecResolution`'s third input. | -| *(no register row — `c2d7ac4d` then `ca38c412`, the fence delete)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload | Recorded here because it changed live behaviour without moving a file, and because it is the census method applied to a *bug* rather than to a cutover. The question was whether the serializer's fence ref space and the ref a command stream's fence record carries are the same numbers — the same question `apply_delete_object` records answering **no** for the object table. `c2d7ac4d` counted it and did nothing: **`delete_fence_ref_live=2`, `delete_fence_ref_absent=0`**, both in the render domain. So they coincide, and `ca38c412` retires the generations. The hazard removed is a wrong answer, not a leak: a wait is satisfied when the stored generation is at or past its target, so a generation outliving its fence made the next fence to get that ref pass its first wait with nothing behind it. Validation boot: desktop reached, `draw_scissor_full=40 378`, **no line on the failure channel**, `delete_fence_ref_live=2` / `_absent=0` again, and `cmd_delete_object_unimplemented` down from **10 to 8** exactly as the kind census predicted — the two fences left it, and the 5 functions and 3 compute pipeline states did not. | -| *(no register row — `ac180b8d`, the destroy ref space)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload | The third and last of this session's ref-space questions, and the one that closes the `CmdDeleteObject` investigation down to a residue. For the eight destroys this device retires nothing for — 5 functions, 3 compute pipeline states — the census reports the **pair**: the type the destroy opcode names against the type the guest's own object-list entry carries, because a resolving integer is a collision (the object table's boot found 22 such) and an agreeing type is an identity. Reading: **`delete_object_ref_no_list_entry=8`**, with `delete_object_ref_type_agrees` and `delete_object_ref_type_differs` both silent. Not one of them names anything in the object list, so there is nothing for a ref-keyed retirement to find and nothing this device is failing to do. Desktop reached, `draw_scissor_full=39 879`, no line on the failure channel, `cmd_delete_object_unimplemented=8` and `delete_fence_ref_live=2` unchanged from the previous boot. What remains unresolved on the row is now enumerable: the five kinds a driven guest has never sent. | -| *(no register row — `5b7e46fb`, `e0b3cc11`, `b4327ac7` then `85b7a63c`, the backing re-point)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload | G2's own coverage hole, opened by the previous session's `replace_physical_storage_undescribable=34` and closed over four boots by the same census method. The one counter was split into a refusal enum (`RepointStorageRefusal`) with a route per reason; boot one said **all 32 were `NoBytes`**, so nothing was leaving the model's content authority stale — but the 32 coincided exactly with `_via_mapping` and `_dropped`. Boot two asked whether the same integer named a live mapping surface: **31 of 31, yes**. Boot three asked the **type pair** — what the guest's own list holds at that integer — because a resolving integer is a collision and an agreeing type is an identity: **`_no_bytes_backing=36` of 36**, every other kind silent. So a re-point the model never heard about was always a surface-backing object, and its slot *is* the mapping id by construction (`backing_claimant_tasks` finds a surface's owner by probing exactly that slot for exactly that type). `85b7a63c` routes `OBJECT_TYPE_BACKING` through `mapping_backing_id` at its own slot and takes the extent from the backing's own record. Validation boot: **every `replace_physical_storage_*` refusal route silent**, `replace_physical_teardowns=189` = `unknown_object=158` + `via_mapping=31` — the 31 that were unheard now reach the model — desktop reached, host-driven workload completed, **0 FAIL lines**. | -| *(no register row — `e7708079`, `0254c64a` then `de73a9c2`, the destroy's name)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload | The ordering group's last blocker, measured to its cause and fixed. `CmdDeleteObject`'s ledger row is unresolved, so `classify` gives it no class and 5.5% of the stream would refuse at admission — affordable for the channel now that a refused packet's completion word is the caller's (`d818a425`), but not for the work, since this device retires a sampler, depth-stencil, render-pipeline or fence registry entry on every one of them. Boot one asked the type pair of the kinds it *does* retire: **2123 of 2203 named no object-list entry**, which reads like two ref spaces and is not — `objects::resolve_sampler_state` looks that same ref up in the guest's list and requires a `SERIALIZER_OBJECT` there, so the spaces are one and the reading is about *time*: the guest clears its slot before it sends the destroy. Boot two asked the question that actually decides it — can the **model** name the reference, which `name_resource` answers from `object_name` before consulting the list: **zero of 1984**, because a sampler is built out of the list once and answered from `task_sampler_states` forever, and no path on it ever declared a name. `de73a9c2` takes the name at construction, through the same door the production `RefResolver` answers with. Validation boot: **`delete_object_retained_ref_model_named=2006`, `_unnamed=15`**, against `sampler_state_deleted=2006` — every sampler this device retires is now one the model can name. Desktop reached, `draw_scissor_full=39 279`, `slot_recheck` reporting no recycled-slot disagreement, **0 FAIL lines**. The residual 15 are the depth-stencil, render-pipeline and fence kinds, whose construction paths are rail-local or hold no list entry at all. | -| *(no register row — `b00224e8` then `9d81936e`, the destroy's class)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload | The ordering group's blocker, closed. `CmdDeleteObject` was the one unresolved row a driven guest sends, and `classify` giving it no class kept 5.5% of the stream out of the semantic model. `b00224e8` gave the protocol crate the record's meaning — which of eleven kinds, and whether that kind's serializer row is settled — and `9d81936e` made the packet an operation: `LifecycleKind::DeleteObject` resolving through `object_destroy`, `LifecycleOp::DeleteObject` carrying the kind because the executor's half of the work differs by it, and `ResolveRefusal::UnsettledDestroy` refusing **one packet** for the five kinds no boot has ever sent instead of the whole class. Validation boot: **`packet_class_unclassified = 0`** — exec 20 758, lifecycle 15 483 (up from 13 505, which is the destroys arriving), present 2117, query 13, control 12 — against `sampler_state_deleted = 2120` and `delete_object_retained_ref_model_named = 2120`. Desktop reached, `draw_scissor_full = 39 945`, **0 FAIL lines**. What is left under `ingress::Gap::Unresolved` is four rows a driven guest does not send: `CmdDebug`, two display commands and `CmdDelay`. | -| *(no register row — `02beb035`, `cb417cb7` then `4c557186`, the ordering plane's next two blockers)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload | Two things `SessionModel::admit` would have refused a real guest for, found by reading the refusal list against what production actually holds rather than by running it. **The root domain**: `open_channels` started empty and only `CmdDefineFifo` added to it, and `CmdDefineFifo` arrives on the root FIFO — so the cutover would have refused `ChannelNotOpen` on the command that opens every other domain. `ChannelId::ROOT` is now opened by `SessionModel::new` and cannot be freed. **The pipeline table**: `admit` refuses an exec whose stream binds a pipeline the table does not hold, and nothing had ever declared into it — every exec packet a real guest sends, over half the stream. `4c557186` declares at `runtime::draw::load_render_pipeline`, the one door both rails reach before either starts host work, and retires on `CmdDeleteObject`'s render-pipeline kind. Validation boot: **`pipeline_declared=134`, `pipeline_declared_already=2657`, `pipeline_declared_unnamed=0`** — every pipeline a driven guest binds has a name the model can hold — and `pipeline_retired=4` against `pipeline_state_deleted=4`. Desktop reached, `draw_scissor_full=39 223`, `packet_class_exec=21 182`, `packet_class_unclassified=0`, **0 FAIL lines**. What is still missing is the rails advancing a declared pipeline to `Ready`: until they do, an admitted exec would park on a compilation nothing finishes. | -| *(no register row — `806faadd`, the pipeline build)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload (three rounds of launching and quitting five apps) | The other half of the previous row: the table filled, so `admit` stopped answering `Absent` to every exec and would have started answering `Pending` to every exec forever. Both rails now walk a declared pipeline `Declared → Translating → Compiling → Ready` through one rail-neutral pair, `draw::advance_pipeline` and `draw::refuse_pipeline`, and refuse with a reason where they cannot build it. Validation boot: **`pipeline_declared=135` = `pipeline_translating=135` = `pipeline_compiling=135` = `pipeline_ready=135`** — every pipeline this guest declares becomes usable, none is stranded mid-build — with `pipeline_refused=0` and `pipeline_advance_unnamed=0`. The declines account exactly: `pipe_memo_miss=142` against 135 first declarations leaves 7 re-resolutions, each of which declines all three steps, and `pipeline_advance_declined=21` is 3 × 7. `pipeline_retired=4`, `pipeline_retire_released=0` (nothing is admitted into this model yet, so nothing was parked). Desktop reached, `pipe_memo_hit=32 400`, **0 FAIL lines**. | -| *(no register row — `4fc4e814` then `14a1371a`, the completion word)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload (three rounds of launching and quitting five apps) | The scheduler's other wait kind. `admit` parks a packet whose header names a point another packet must publish, and nothing in production called `Scheduler::publish` — so the cutover would have parked every packet the guest orders behind a fence, exactly as the empty pipeline table would have parked every exec. `4fc4e814` published at `write_stamp`, and its boot read healthy about the wrong set: **13 702 publications over four slots, 0 behind, 0 repeat** — while `stamp_write_forward` ran **14 245**, and a device publishing fewer words than it writes is missing a writer. It was the root FIFO, which writes slot 0 inline rather than through `write_stamp`; about 160 words a boot, on the timeline the measured root stamp waits are on. `14a1371a` put both records — the device's owed-word ledger and the ordering plane's timeline — behind one function called at both sites, so the next writer cannot record one and not the other. Validation boot: **`stamp_publish_first=5`** (four child timelines and the root, where it was four), `stamp_publish_advanced=12 753`, **`stamp_publish_behind=0`** — this device never writes a word behind what the model holds — against `stamp_write_forward=12 748` and `root_stamp_ordered_gpu=159`. Desktop reached, `pipeline_declared=127` = `pipeline_ready=127`, **0 FAIL lines**. | -| *(no register row — `9ab40542` then `fb76145e`, the publication point)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload (three rounds of launching and quitting five apps) | The census asking whether the ordering plane would answer a stamp wait the way this drain does, and the defect it found on its first boot — which was in the commit two rows above. **`stamp_wait_model_ahead = 12 824` against `stamp_unmet_queued = 12 824`**, the same number twice: `write_stamp` hands the word to the GPU-ordered rail and returns, `Queued` is the device ledger's own name for exactly that state, and the plane's timeline was being published at that line. Twelve thousand times a boot the plane called a wait satisfied while the guest could still read the old value — a cutover publishing there releases work ordered behind GPU work that has not finished. Submission is not completion. `fb76145e` splits the records along the line they were always about: the ledger stays at `write_stamp`, and `note_stamp_visible` tells the plane at the three places a word is observed to have *landed* — the two inline page writes and the drain's own read of the slot. Validation boot: **`stamp_wait_model_ahead = 0`** and **`stamp_wait_model_agrees_unmet = 17 674 = packet_stamp_wait_unmet`** — the plane now releases nothing this device holds. `stamp_visible_observed = 30 584` against `inline = 178` and `root = 12`, `stamp_publish_behind = 0`, `pipeline_declared = 134` = `pipeline_ready = 134`, **0 FAIL lines**. `stamp_wait_model_behind = 5207` of 12 910 met waits is the *expected* remainder and not a hang: it is the first wait after a queued word lands, before the read teaches the plane — and because the publication runs in the same call as the read, a cutover that decides after publishing pays no round trip for it. **That ordering is the constraint the switch inherits from this row.** | -| *(no register row — `7edac094` then `39da38fa`, the destroys the model could not name)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload (three rounds of launching and quitting five apps) | Nineteen destroys a boot, of about 2160, arriving with no name the model can hold — every one a packet `SessionModel::admit` refuses with `UnknownRef`. `7edac094` added the per-kind census first, because two counters that say *how many* cannot aim a fix, and the composition it measured was **not** the one an older reading recorded: depth stencil 4, sampler state 5, **function 5**, **compute pipeline 3**, fence 2. The old list named render pipeline (now zero — its declaration door names it) and missed function and compute pipeline entirely, so two rail edits would have gone to four packets. `39da38fa` names the three closeable kinds at their own construction sites — `mtlb::load_mtlb`, `compute_exec::load_compute_pipeline`, and one `draw::name_depth_stencil` shared by the two rail loaders, because a route pair written twice is how the second rail spells it differently. Validation boot: **`delete_unnamed_depth_stencil_state`, `delete_unnamed_function` and `delete_unnamed_compute_pipeline_state` all 0**, from 4, 5 and 3; the total falls **19 → 7**, and the seven are `delete_unnamed_sampler_state = 5` and `delete_unnamed_fence = 2` — the two kinds with no moment where the list entry and the model's namespace are both available. Naming took `function_model_named = 6051`, `compute_pipeline_model_named = 393`, `ds_state_model_named = 33`, each with **zero** unnamed. `draw_scissor_full = 40 308` against 39 621 the boot before, so the added lookups cost no frames. `pipeline_ready = 131`, **0 FAIL lines**. | -| *(no register row — `407112da`, `36186308` then this commit, the stamp wait's owner)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload (three rounds of launching and quitting five apps) | The first wiring step on the stamp side, in the plan's sense: the drain keeps its ownership — the retry, the hold bit, the head pointer — and loses only its duplicate arithmetic. Whether a published point discharges a wait is one wrapping rule and it was written twice, in `drain::StampWait::satisfied_by` and in `reims_vgpu_core::identity::StampValue::reached`, character for character; two implementations of a wrapping comparison are two silent chances to disagree about which of two numbers is later, and the two failures are opposite — one parks a timeline forever on a value already written, the other releases work early. `407112da` took the *verdict* from `DeviceState::published_completion_stamp` and kept the drain's own answer beside it as a witness; `36186308` made the device's remaining callers — `PendingStamp::discharges` and `StampLedger::classify` — defer to the owning type rather than restate it. Validation boot: **`stamp_wait_owner_differs = 0` against `stamp_wait_owner_agrees = 29 852`** — the two answers never parted — with `packet_stamp_wait_met = 12 540` + `unmet = 17 312` summing to the same 29 852, `stamp_publish_behind = 0` and `stamp_wait_model_ahead = 0`. Desktop reached, `draw_scissor_full = 39 820`, `pipeline_ready = 135`, the unnamed destroys holding at sampler 5 + fence 2, **0 FAIL lines**. The witness is removed in this commit: it fires only where `stamp_publish_behind` does, which makes it a second name for one event. | -| *(second rail — `806faadd` .. `dc70dd61`, everything above)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-26` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload | A different guest driver, chosen because this rail clears its object-list slot while the packet that named it is still undrained — which is exactly where naming at construction could behave differently, and where the rows above were all established on `macos-15`. It does not: **`function_model_unnamed`, `compute_pipeline_model_unnamed` and `ds_state_model_unnamed` are all 0** over 6851, 469 and 33 namings, and the unnamed destroys are `sampler_state = 5` alone — this rail's guest never sends the two fence deletes `macos-15` does. It is also the first rail to exercise the *refusal* arm on a real guest: **`pipeline_refused = 1`, `pipeline_compilation_failed = 1`**, one pipeline this device cannot build, refused terminally with a reason instead of leaving every exec that binds it parked on a compilation nothing finishes. The table balances — `declared 210`, `translating 208` = `compiling 207` + the one refusal, `ready 207`, `retired 13` — with two pipelines resting at `Declared`, which are pipelines nothing ever drew with and so nothing ever binds. `pipe_memo_hit = 67 969` against `miss = 367`, `stamp_publish_behind = 0`, `stamp_wait_model_ahead = 0`, `packet_class_unclassified = 0`, desktop reached, **0 FAIL lines**. | -| *(no register row — `8aeb713a` then `37f6f953`, what the table is holding)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-26`, host-driven workload | The counters said what *happened* to a pipeline and nothing said what the table was *holding*, which is the difference between a healthy boot and one accumulating builds nobody is running — the same argument `backing_outstanding_census` is emitted beside `store_routes` for, and it matters more here because `Declared`/`Translating`/`Compiling` are the three states a transaction waits on. `8aeb713a` added the occupancy line; its first boot showed **170 retirements against a table holding 116**, and `37f6f953` split the two facts the ending doors had been returning one empty list for. Validation boot: **`pipeline_declared` = `translating` = `compiling` = `ready` = 260**, and `pipeline_retired = 160` matching the occupancy line's `retired = 160` exactly, against `pipeline_retire_absent = 102` — render pipelines the guest deletes that this device never drew with, so never declared. Final occupancy `pending=0 ready=100 retired=160 total=260`: **nothing parked on a build.** `stamp_visible_observed = 136 709` equals `packet_stamp_wait_met + unmet` exactly, so every wait evaluation publishes once; `stamp_wait_model_ahead = 0`, `stamp_publish_behind = 0`, `packet_class_unclassified = 0`, `pipe_memo_hit = 227 427` against `miss = 427`, **0 FAIL lines**. This is also the boot that found the summing error the preamble above now warns about. | -| *(no register row — re-verification of `806faadd` .. `134f5263` on the rail every row above was established on)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload | The rows above were measured with the summing error the preamble names, and their **zeros** were the claims that error could actually falsify — a counter is printed only in a window where it fired, so one firing only in skipped windows reads zero when it is not. Every zero re-established here by presence rather than by sum: `stamp_wait_model_ahead`, `stamp_publish_behind`, `pipeline_refuse_already_ended`, `delete_unnamed_{depth_stencil_state,function,compute_pipeline_state,buffer,texture}`, `{function,compute_pipeline,ds_state}_model_unnamed`, `pipeline_{declared,advance,refuse,retire}_unnamed`, `pipeline_refuse_not_a_build_decline`, `delete_unnamed_not_a_destroy` and `packet_class_unclassified` **do not appear in the log at all**, while `stamp_publish_repeat` appears 152 times — which is what says the method can tell the two apart. Magnitudes, summed correctly this time: `pipeline_declared` = `translating` = `compiling` = `ready` = **131**, occupancy `ready 127 + retired 4 = total 131` with `pending = 0`, `pipeline_retired = 4` against `retire_absent = 0` (this rail's guest deletes only pipelines it drew with, unlike `macos-26`'s 102), `stamp_visible_observed = 30 125` = `met 12 435 + unmet 17 690` exactly, `stamp_publish_first = 5` for four child timelines and the root, `function_model_named = 5876`, `compute_pipeline_model_named = 422`, `ds_state_model_named = 34`, the unnamed destroys holding at sampler 5 + fence 2, `pipe_memo_hit = 101 799` against `miss = 140`, `draw_scissor_full = 39 558`, **0 FAIL lines**. The one zero that cannot be re-established is `stamp_wait_owner_differs`, whose counter `9fbe427b` removed — but `36186308` had already made both sides of that comparison call one implementation, so it could differ only on a rewind, and the rewind population is `stamp_publish_behind`, which is zero by presence on both rails. | -| *(no register row — `be21e4ab` then `b1259eb4`, the destroy's reference)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload (three rounds of launching and quitting five apps) | The last of the ten `session::Refusal` variants that a real guest could still have hit, and the boot that says it cannot. `object_destroy` refused a `DeleteObject` whose reference the namespace could not resolve, and two of the eleven kinds have no construction moment where a name could be taken: a **fence exists only when an exec stream first signals it** — `set_fence_generation` is the sole writer, there is no creation command — so no namespace can ever name one, and refusing its destroy is not a safe failure but a *wrong answer*, since the stored generation outlives the fence and the next fence to reuse that reference starts life already signalled. `be21e4ab` first split the two questions the census had been asking as one, because they are not the same packets: whether *the model* has a name yet (`object_name`) is not whether *the production bridge* would refuse (`name_resource`, which falls through to the guest's own object list). `b1259eb4` then made `LifecycleOp::DeleteObject` carry `object_ref: u32` beside `resource: Option` — the effect is keyed by the reference, and `resources()` answers an empty slice when unnamed, which is safe because a resource this model cannot name is one nothing else in it names. Validation boot: **`delete_unnamed_but_list_still_has_it` does not appear in the log at all** — no destroy is refused for a reference the guest's list still holds — against `delete_unnamed_and_unresolvable = 7`, which is `delete_unnamed_sampler_state = 5` + `delete_unnamed_fence = 2`, the two structurally unnameable kinds, and matches `delete_object_retained_ref_model_unnamed = 7` of `_named = 2050`. The five kinds no driven boot has ever sent are still zero by presence (`delete_unnamed_{buffer,texture,heap,rasterization_rate_map,indirect_command_buffer}`), so `UnsettledDestroy` remains a one-packet refusal for work no guest here does. This boot is a regression check and not evidence for the change — nothing in production calls `object_destroy` yet — and it regresses nothing: `pipeline_declared` = `translating` = `compiling` = `ready` = **133** with `retired = 4` and `retire_absent = 0`, `stamp_visible_observed = 29 500` = `met 12 660` + `unmet 16 840` exactly, `packet_class_unclassified`, `stamp_publish_behind`, `stamp_wait_model_ahead` and the four `pipeline_*_unnamed` all absent from the log while `stamp_publish_repeat` appears 141 times as the control, `pipe_memo_hit = 93 877` against `miss = 141`, `draw_scissor_full = 38 201`, **0 FAIL lines** across 21 886. It also reads the plan's second open contract question, which was instrumented and unread: **`query_reply_scanned = 12` = `query_reply_outside_every_allocation = 12`, and `query_reply_inside_an_allocation` is absent entirely** — on this rail no query's reply destination lands inside an allocation this device already identifies, so a reply given a backing of its own orders against nothing else. `backing_id_heap_placed` is still zero here, so a heap's extent stays unrecovered and refused by name; rails 11, 12, 14 and 26 are untried for it. | -| *(no register row — `dc99ef8c`, the per-record sink)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload (three rounds of launching and quitting five apps) | A behaviour-preserving split of `walk_stream` into a framing loop and a `StreamSink`, so the walker over an exec stream can be replaced rather than duplicated — and the boot that says the split did not move a record. Desktop reached, workload completed, **0 FAIL lines across 23 223**. `walk_records_render = 530 623`, `walk_records_compute = 1085`, `walk_records_blit = 750` all still reach their handlers through the sink, `seg_chain_none = 19 921` with the other three chain routes at zero (this guest continues no encoder across a segment), `draw_scissor_full = 39 995`, `pipeline_declared = ready = 125`, `retired = 4`, `stamp_visible_observed = 30 242` = `met 12 439` + `unmet 17 803` exactly, `pipe_memo_hit = 89 818` / `miss = 134`, `packet_class_exec = 20 873`. The two losses the sink can newly name are **absent from the log entirely** — `exec_compute_record_unopened` and `exec_segment_unended` — which is what says the framing loop pairs its `begin_segment`/`end_segment` calls correctly on a real guest, and `compute_session_finish`, `stream_frame_fail` and `stream_record_fail` are absent too. | -| *(no register row — `dc99ef8c` + `5a6dea05` on two further guests)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-26` and `--rail macos-14` (x86 macOS guests, Linux/KVM host, Vulkan rail), host-driven workload | The sink and the read/execute split on guests neither was written against. **macos-26** (Darwin 25.6.0): desktop reached, **0 FAIL lines across 56 903**, `walk_records_render = 1 060 053` / `compute 1422` / `blit 754` all still reaching their handlers through `StreamSink`, `seg_chain_none = 40 190` with the other three chain routes at zero, `pipeline_declared = 138` / `ready = 137` / `retired = 26` against `retire_absent = 20`, `stamp_visible_observed = 110 751` = `met 38 958` + `unmet 71 793` exactly, `pipe_memo_hit = 174 923` / `miss = 183`, `packet_class_exec = 41 150`, `lifecycle = 57 410`, `present = 7115`, `control = 14 956`. **macos-14** (Darwin 23.6.0): desktop reached, **0 FAIL lines across 58 442**, `walk_records_render = 1 096 063`, `draw_scissor_full = 52 431`, `stamp_visible_observed = 112 464` = `met 39 522` + `unmet 72 942` exactly, `packet_class_exec = 42 542`. On both rails the two losses the sink can newly name — `exec_compute_record_unopened` and `exec_segment_unended` — are **absent from the log entirely**, as are `compute_session_finish`, `stream_frame_fail`, `stream_record_fail`, `packet_class_unclassified`, `stamp_publish_behind`, `stamp_wait_model_ahead` and `delete_unnamed_but_list_still_has_it`. The query-reply reading replicates: `query_reply_scanned = 15` = `query_reply_outside_every_allocation = 15` on each, with `query_reply_inside_an_allocation` absent — three rails now say a reply destination never lands inside an allocation this device identifies. `backing_id_heap_placed` is absent on both, so a heap's extent stays unrecovered on macos-14 and macos-26 as well. **The two guests are distinct and that was checked rather than assumed**: they report identical `packet_class_control = 14 956` and `pipeline_declared = 138`, which reads like one log summed twice, but each fail log holds exactly one `rail_selected`, the disk images differ (30.8 GB against 41.1 GB), the serial logs say Darwin 25.6.0 and Darwin 23.6.0, and `packet_class_exec` and `draw_scissor_full` do differ — the two that match are deterministic sets, the cursor-glyph upload `op0x04` carries (14 949 of that rail's 14 956 control packets, against 11 on macos-15) and the compositor's pipeline set. | -| *(no register row — the drain loops' ring read as one named step)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (three rounds of launching and quitting five apps) | Both drain loops' bound-header-snapshot-decode replaced by `Ring` + `arrival`, which is the hottest read this device performs and the one place a mistake stops every packet. Desktop reached, workload completed, **0 FAIL lines across 23 577**. Every ring fault this step can report is **absent from the log entirely** — `packet_bad_size = 0`, and no `MalformedRootPacket` or `MalformedChildPacket` of any fault, so no read regressed into one. The traffic is the same shape the earlier macos-15 rows measured: `walk_records_render = 585 095` / `compute 1097` / `blit 763`, `packet_class_exec = 22 147` / `lifecycle = 16 778` / `present = 2393` / `control = 11`, `draw_scissor_full = 40 083`, `pipeline_declared = ready = 131` with `retired = 4`, `stamp_visible_observed = 32 124` = `met 13 031` + `unmet 19 093` exactly, `pipe_memo_hit = 101 289` / `miss = 141`. `packet_stamp_wait_held = 18 885`, which is the counter the present-backpressure and stamp-hold `break`s still drive — the gate now reads `packet.opcode` instead of peeking the raw header, and it holds the same packets. The one `TRANSPORT sync_exec_lock_hold` is the first-draw pipeline compile the 2026-09-01 and 2026-09-02 journals already record at 2.9 s and 2.06 s; this boot's is 1.37 s. | - -The macOS/arm64 rows of the pathway table in `AGENTS.md` cannot be run on this -host and are outstanding qualification for every row above, as the plan's -2026-09-02 amendment records. Compilation on those arms is covered by the -cross-compiled `aarch64-apple-darwin` feature-matrix arms and is not the same -claim. -| G3 | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, host-driven workload (three rounds of launching and quitting five applications over ssh) | The ordering group's own boot, and the first on which **this device drops no guest work at all**: `packet_unadmitted` does not appear in the log, and neither does any `FAIL` line. Every packet the guest sent went into `SessionModel` and came back out of it — `parked_taken_ready = 26 224`, `walk_records_render = 276 698`, `pipeline_declared = 143` all ready. The stamp plane carried 9366 waits (`packet_stamp_wait_met = 4000`, `unmet = 5366`) with `stamp_visible_observed = 46 255`, and the two counters that would say the plane and this device disagree — `stamp_wait_model_ahead`, `stamp_wait_model_behind` — appear nowhere in the log, nor does `packet_stamp_wait_unresolvable`. `f0d7c6cc`'s two named regressions were closed by `74f00590` (741 refused deletes), `2d4ec9e3` (the refused backing retirement) and `dff03408` (the seven refused exec windows); the first of those three shipped a deadlock that `416f9d6c` fixed after a boot measured it at `walk_records_render = 42`. The reading that made the group's own switch worth trusting is `packet_stamp_wait_met_pending`, which the moved latch's doc predicted at zero and which is absent here for the reason that doc gives — the waits this guest sends are on slots *other* channels write, and a per-drain latch could never have answered one. | -| G3 (rail sweep) | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail ` for **all six** provisioned x86 rails, Vulkan | The ordering group proven on more than the rail it was written against, and it found a defect on the one rail nobody had booted it on. **macos-13, macos-14, macos-15**, host-driven workload: `packet_unadmitted` and `FAIL` absent from every log, `walk_records_render` 160 519 / 153 002 / 286 140. **macos-11 and macos-12** reached a first frame through the model and are boot-only — macos-11's sshd did not answer inside the 7-minute testing window and macos-12 refused the key — with `packet_unadmitted` and `FAIL` absent from both. **macos-26** refused 918 exec packets on the first boot and 9375 on the second: `pipeline_absent_retired`, the guest deleting render pipelines and continuing to bind them, which `6587f618` took to **17** (an unresolvable exec ref, and one fragment shader this device cannot translate) while taking `walk_records_render` from 133 630 to 218 466. The sweep is the row: five rails agreeing says nothing about the sixth, and the sixth is where the group's remaining defect was. | -| *(no register row — this commit, the compute half of the pre-scan)* | `vm/boot-x86.sh --device reims-vgpu-pci --interactive --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (three rounds of launching and quitting five apps) | The correction `94838490` made to the render arm, applied to the compute arm — and the boot that first said which arm the measured loss was on. `94838490`'s own driven boot is the row's baseline (`/tmp/fail15-c0b667b8.log`, not committed): it is clean — `packet_unadmitted` 0, `FAIL` 0, `rail_selected` 1 — and it **did not** move `m2v_translation_pending_at_sync_boundary`, which stood at 2 before and after. Both of those two lines read `compute_linux_m2v … stage=kernel`. **They are compute kernels, and the render arm could not have fixed them.** Meanwhile `preflight_compute_translations` still byte-scanned each stream while admission readied the walk's *class-blind* `pipeline_leases` — which holds compute binds — on that scan's verdict, so the compute half had exactly the defect the render half had just lost, with three ways to miss a kernel: a selector carrying no threadgroup size (`DispatchThreadsIndirect`, where the flat command offered a zeroed field the scan then rejected as an out-of-range extent — the same word it uses for "the guest asked for a grid of nothing"), a dispatch after an encoder continuation (the scan reset its bound ref at every framed segment; a stream is one encoder however many segments carry it), and a framing refusal it swallowed. `reims_vgpu_core::exec::ExecWork::compute_dispatch_translations` answers all three from records the walk already resolved, and says the first structurally: `DispatchOp::ThreadsIndirect` has no such field to read. `preflight_translations` now takes `(render_pipelines, compute_dispatches)` and **reads no stream at all**. Validation boot: desktop reached, workload completed, **`packet_unadmitted` = 0, `FAIL` = 0** across 5.85 MB, `rail_selected` = 1, `pipeline_declared = 144`, `parked_taken_ready = 26 642`, `walk_records_render = 270 724` / `compute 1085` / `blit 1582`, `pipe_memo_hit = 45 551` / `miss = 142`, `preflight_mtlb_unloadable` and `preflight_air_unextractable` both **0**. The pre-scan reaches *more* work, not less: `preflight_memo_ready` 47 577 → **54 142** on comparable `_absent` (46 540 → 46 568), which is the continuations and indirect dispatches the byte scan was not reaching. And the cost the plan's census called "the part most obviously redundant" is **gone rather than smaller**: every `preflight_split` line reads `refs_us=0 refs_n=0`, against `refs_us=7 refs_n=47` per second on the baseline — nothing charges that part any more, because there is no second decode of the stream to charge. That reading is what licenses removing `PreflightPart::Refs` in this commit rather than leaving an always-zero column that reads as "this part is free". **What this boot does not establish**: the compute loss fell 2 → 1, not to 0, and one boot cannot separate a real halving from the boot-to-boot variance the journal already records at about one boot in three. The same boot also shows one *render*-side `linux_m2v_draw … stage=fragment pipeline_ref=5` with `model_pipeline=ready` — a draw refused against a fragment shader still translating while the ordering plane held the pipeline ready — which is the same defect shape on the arm `94838490` was supposed to have closed, and is owed a diagnosis. The log also carries one `observe_slug_collision` for this very slug, claimed by both `runtime::m2v_cache::M2vCacheDecline` and `backend::vulkan::engine::draw_prepare`, so a bare `grep -c` of it conflates two holders; the counts above are by `stage=`. | -| *(no register row — `f696867d`, `77f5bd88` then `e2d11cb1`, the pipeline that stopped being ready)* | `vm/boot-x86.sh --device reims-vgpu-pci --interactive --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (three rounds of launching and quitting five apps) | The last of the lost draws this device could explain, and the model was wrong about its own state rather than the pre-scan being wrong about the packet. Four boots put every remaining `m2v_translation_pending_at_sync_boundary` in one shape: `linux_m2v_async queued pipe=5 stage=Fragment air=4332` → `done` → `pipeline_lease_ready site=…_pump slot=5`, then twenty seconds later `queued pipe=5 … air=4328` with the refused draw four milliseconds inside that window, and the compute one identical at `pipe=14 air=11764 → 11760`. **The guest rewrites the shader behind a live pipeline ref in place** — `pipeline_retired = 4` against 143 declared, `pipe_memo_miss = 138`, no delete, so no generation and the same `ResourceId`. `f696867d` measured the population at the one place both identities are in one hand: **five `m2v_pipe_content_changed` a desktop**, which is what says the name-keyed pre-scan memo is worth keeping (`pipe_memo_hit = 44 832`) and only its key is wrong. The pre-scan was never the defect: it read the new AIR, queued the translation and answered pending — and `PipelineState::Ready` had no step back except `Retired`, so it meant "was translated once", `waits_for` returned nothing, and the ordering plane released the transaction anyway. `77f5bd88` gave the table the step and `PipelineTable::withdraw` as its own door; `e2d11cb1` made `preflight_translations` return the refs it could not serve instead of a bool, because a bool cannot tell the lease that must stop being ready from the lease that must become it. **The door is separate because an existing test said so**: `a_rail_walks_a_declared_pipeline_to_ready_and_a_second_walk_is_declined` failed the moment `advance` allowed the step, since the Metal rail retains no pipeline state and re-walks `Translating → Compiling → Ready` on every draw — through `advance`, every draw would un-ready its own pipeline. Validation boot: **every translation-pending loss is gone** — no `m2v_translation_pending_at_sync_boundary` and no `draw_prepare_{vertex,fragment}_translate` anywhere in the log, against one to four on each of the four boots before it — with **0 `FAIL` lines**, `packet_unadmitted = 0`, `rail_selected = 1` and `observe_slug_collision = 0`. **Nothing is stranded**: the table's final occupancy is `pending=0 declared=0 translating=0 compiling=0 ready=139 refused=0 retired=4 total=143`, and `pipeline_lease_withdrawn = 7` against `pipeline_ready = 150` = `declared 143` + those same 7 — every withdrawal came back. The withdrawal is not a loop: 7 against 150 readies and 257 611 render records. The two draws still lost are `engine_drew_store_lost_it`, the unimplemented MSAA writeback (300×300 `samples=4`), which is unrelated and unchanged. **The cost, stated:** a withdrawn lease stops the pump's `parked_translations_already_ready` short-circuit for its position, so `preflight_memo_absent` roughly doubles (46 568 → 97 923) — about 420 ms of guest AIR resolves across a 220-second boot, or 1.9 ms/s. `stamp_publish_behind = 14 534` here and 14 141 on the pre-change baseline: **pre-existing on this tree and not this change**, but it contradicts the zero an earlier row above records, and that row's claim is the one to re-establish rather than this number to explain. | -| *(second rail — `f696867d` .. `e2d11cb1`, the withdrawal on the rail that deletes pipelines)* | `vm/boot-x86.sh --device reims-vgpu-pci --interactive --rail macos-26` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload | The withdrawal on the guest that provokes it five times harder, chosen because it is the rail every earlier row's defect was found on and because the new step is a *scheduling* change whose failure mode is a hang. It does not hang and it strands nothing: **0 `FAIL` lines** across 11 MB, `rail_selected = 1`, and the table rests at `pending=0 declared=0 translating=0 compiling=0 ready=108 refused=0 retired=120 total=228`. `m2v_pipe_content_changed = 26` here against macos-15's 5 — this guest rewrites shaders far more often — and `pipeline_lease_withdrawn = 14` over twelve distinct slots, with `pipeline_ready = 242` = `declared 228` + those 14 exactly, the same identity the macos-15 row records. Fourteen withdrawals against 535 026 render records is not the Metal-rail cycle. **The defect the change was for is closed on this rail too, and the residue is a different one, which the `model_pipeline=` field added by `d1637062` is what says.** Five losses remain — two render, three compute — and **not one of them reads `model_pipeline=ready`**. Both render ones read **`model_pipeline=retired`** (`pipe=72`, `pipe=29`): the guest deleted the pipeline and a packet recorded before the delete still binds it, which is exactly the loss `6587f618` chose to take when it stopped refusing the whole packet for a deleted pipeline — *"one draw is what the guest loses, which is what it lost before this table existed"* — and this rail retires **120** pipelines a boot against macos-15's 4. The three compute ones carry no `model_pipeline` field and are **owed a diagnosis**; the render arm's field is what made its two legible, and the compute refusal has no equivalent. `packet_unadmitted = 9` over two latched reasons, `lifecycle_unknown_ref` and `resolve_ref_names_no_object` — the guest defect an earlier row records at 1 on a differently-shaped run; **no macos-26 boot was taken at the pre-change commit, so that number is unattributed rather than clean.** Nothing in this change touches admission's refusal path: a withdrawn lease is `Translating`, which `waits_for` answers `Pending` for, and a refusal is only ever `Lease::Refused` or absent. | -| *(no register row — this commit, the two counters a boot was needed to read)* | `vm/boot-x86.sh --device reims-vgpu-pci --interactive --rail macos-26` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (three rounds of launching and quitting five applications over ssh) | **Two open questions closed by one boot, and neither had a code change in it.** First, the ordering group's classification denominator. The `9ab40542`/`fb76145e` row's macos-15 reading was `packet_class_unclassified = 2166`, every one of them child `0x28` `CmdDeleteObject`, whose ledger row was then `Closure::Unresolved`. That row is `Closure::Implemented` now, and this rail sent nothing else `reims_vgpu_core::transaction::classify` refuses: **`packet_class_exec=946`, `packet_class_lifecycle=1096`, `packet_class_present=172`, `packet_class_query=3`, `packet_class_control=10` — 2227 classified — and `packet_class_unclassified=0`**, with no `packet_class_unclassified` line on the failure channel. The four rows still unresolved (`CmdDebug`, `CmdDisplaySleepState`, `CmdDisplaySetProperties`, `CmdDelay`) are a contract question this guest does not exercise. Second, `stamp_publish_behind`, which `48f6252e` instrumented precisely because a bare count could not say whether the meaning had drifted or the invariant had broken — this row's own predecessor recorded it at **zero** and every boot since `2099769c` reads about fourteen thousand. **The meaning drifted.** Three slots answered it, all inside the boot's first 24 seconds and none after, by one to seven: `slot=1 page=1 held=3`, `slot=2 page=19 held=26`, `slot=4 page=0 held=1`. The zero was taken when the drain's page read was the plane's only publisher; `SessionModel::complete` publishes the channel's released stamp straight into the scheduler now, and the word itself is queued on the GPU-ordered rail — `stamp_visible_observed = 1 700 804` against `stamp_visible_inline = 25`. The page is behind because the write has not landed, not because it went back: `stamp_write_forward = 2203` against `stamp_write_backward = 1`. **And nothing is decided inside the window**: `stamp_wait_model_ahead = 0` and `stamp_wait_model_behind = 0` against 767 waits decided (`stamp_wait_model_agrees_met = 405`, `stamp_wait_model_agrees_unmet = 362`), which is the whole difference between this and the `stamp_wait_model_ahead = 12 824` the publication point was moved to escape. The rest of the boot holds: `m2v_translation_pending_at_sync_boundary` absent, `observe_slug_collision = 0`, `packet_unadmitted = 2`, `pipeline_lease_withdrawn = 77`, `pipeline_refused = 0`. What it also names, and this row is where it is written down rather than acted on: `preflight_mtlb_unloadable = 4` and **two** draws refused `draw_prepare_pipeline_missing` with `model_pipeline=ready` beside them. The pre-scan cannot load an absent pipeline's shader containers, so it answers "no translation is pending" — which is true — and admission readies the lease on that answer. `Ready` is nonetheless the right lease: a refused lease refuses the *whole* exec packet at admission, so ending it would trade one lost draw for every other draw in every packet binding the ref, and a `PipelineMissing` at this rate is transient. No test moved with this row; nothing moved. | -| *(no register row — this commit, the frame half of the reply destination)* | `vm/boot-x86.sh --device reims-vgpu-pci --interactive --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (three rounds of launching and quitting five applications over ssh) | The macos-15 half of the row above, and two of the plan's named-unsettled terms read on both rails. **The classification denominator, retaken on the rail it was written against**: `packet_class_exec=9571`, `packet_class_lifecycle=15033`, `packet_class_present=1066`, `packet_class_query=13`, `packet_class_control=11` — 25 694 classified — and `packet_class_unclassified=0` against the 2166 the `9ab40542`/`fb76145e` row recorded, with `packet_unadmitted=0` and no `FAIL` line. Both rails now refuse nothing for want of a payload class. **The reply-destination term, task-GVA half**: `query_reply_scanned=24` and `query_reply_outside_every_allocation=24` here, 4 and 4 on macos-26 — twenty-eight replies, none inside an allocation this device identifies, no `query_reply_inside_an_allocation` line on either rail. So a task-GVA reply destination given a backing of its own is the construction these guests support. **The frame half was unreadable and now is not.** Both rails read `device_info_reply_scanned=1` and `device_info_reply_after_an_identity=1` — the guest asks after this device has minted, every time, so the mint-count arm never closes on a real rail. It was also answering the wrong question: a monotone never-reused counter feeds all three key spaces, so a fresh number cannot equal one already handed out by construction, while the danger the plan names is *aliasing* — the reply page being storage some other identity already covers. This commit asks that of geometry, in the one key space a page frame can collide with: whether the reply frame is one of a live mapping's `page_entries`. New routes `device_info_reply_frame_in_no_mapping` (closing) and `device_info_reply_frame_in_a_mapping` (open), reachable on a rail that has already minted. **Also read, and still unrecovered**: `backing_id_heap_placed=0` on macos-15 and macos-26 both, so no driven boot has placed a heap texture and the heap-extent term stays refused by name — macos-26 was one of the four rails the plan lists as untried and is now tried. Replacement coverage for the new arm: fn `runtime::objects::tests::a_device_info_reply_frame_is_measured_against_the_mappings_this_device_holds`, which pins the live-mapping hit, the unmapped-mapping miss and the never-named-page miss. No test moved with this row; nothing moved. | -| *(no register row — the six-rail sweep for `7ddd6f72`/`02bd23cd`, no code change)* | `vm/rail-sweep.sh` over **all six** provisioned x86 rails — macos-11, macos-12, macos-13, macos-14, macos-15, macos-26 — each `vm/boot-x86.sh --device reims-vgpu-pci --testing --rail ` (x86 macOS guest, Linux/KVM host, Vulkan rail) driven by the committed workload, one binary shared by all six (13:26–14:02) | **The reply-destination term closed on every rail this project can boot, and nothing else moved.** Every rail reached first frame and completed the workload; `FAIL` appears in **none** of the six logs (11: 15 952 lines, 12: 9 817, 13: 14 421, 14: 20 399, 15: 20 839, 26: 10 511). **`device_info_reply_frame_in_a_mapping = 0` on all six** and `device_info_reply_frame_in_no_mapping` fires on all six, so the frame the guest is told to write its device-info reply into is never one of a live mapping's pages — the aliasing arm the geometry question was asked to find does not exist on any supported guest, and the term is settled rather than merely untried. `device_info_reply_after_an_identity = 1` and `device_info_reply_before_any_identity = 0` everywhere, which is why the earlier mint-count arm could never close. **`packet_class_unclassified = 0` on all six**, against the 2166 the plan's superseded section recorded — the ingress classification has no residue on any rail. `stamp_wait_model_ahead = 0` and `delete_unnamed_but_list_still_has_it = 0` on all six. `exec_segment_unended`, `stream_frame_fail`, `stream_record_fail`, `exec_compute_record_unopened` and `query_reply_inside_an_allocation`: **zero on all six**, established by key absence and not by summing per-interval dumps. Query replies: 24 / 28 / 38 / 42 / 24 / 4 scanned across the six, **156 in total and every one outside every allocation this device identifies**, which is the task-GVA half of the same term on six rails instead of two. Render traffic spans two orders of magnitude across the rails (`walk_records_render` 13 041 on macos-12 to 230 110 on macos-15) and `packet_class_exec` 574 to 7 635, so the zeros above are not one workload's accident. **Still unrecovered, on all six**: `backing_id_heap_placed = 0` — no driven guest on any provisioned rail places a heap texture, so the heap-extent term stays refused by name and the four rails the plan listed as untried are now tried. No test moved with this row; nothing moved. Replacement coverage is unchanged from the two rows above, which this sweep re-runs on four more rails. | -| *(no register row — this commit, the object caches leave the process-global engine)* | `vm/boot-x86.sh --device reims-vgpu-pci --testing --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (three rounds of launching and quitting five applications over ssh) | **The first handle-owning subsystem out of the process-global engine, on a live guest.** `EngineState::caches` is gone; `ObjectCaches` now lives in the device's own `RailDeviceState` slot as `VulkanDeviceState::caches`, and `execute_draw_request`, `execute_compute_request`, `flush_batched_draws` and `object_cache_levels` take the `&DeviceState` they reach it through. Guest reached the desktop and completed the full workload; **`FAIL` absent from all 23 172 log lines**, `vk_device_recreate` absent, and `device_lost=0` on every one of the 212 `engine_delta` lines. `object_cache_levels` — the line that reads the moved caches, now through the device — climbs and settles exactly as before (`shaders=4 layouts=2 passes=1 pipelines=2 samplers=1` at t=29 s to `shaders=140 layouts=62 passes=21 pipelines=318 samplers=19 compute_pipelines=10` at t=242 s), so the caches are populated, read and warm on the device's slot. **`vk_engine_device_caches_unreachable` never fires**, which is the refusal the new arm names for a slot another rail holds — unreachable under `backend::select`'s one-rail-per-process latch, and now measured to be. Replacement coverage: fn `vk_engine_parity::a_second_devices_caches_are_its_own_and_ending_one_spares_the_other`, the assertion the process-global shape could not express — a second `DeviceState` on the *same* `VkDevice` draws the identical request cold (`creates > 0`, inheriting none of the first device's warm pipelines), goes warm on its own second draw (`creates == 0`), and its ending leaves the first device's levels unchanged and its next draw still warm. No test moved with this row; nothing moved to `dead/`. | -| *(no register row — `b37b6740`, the window's second registry dependency)* | `vm/boot-x86.sh --device reims-vgpu-pci --testing --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (three rounds of launching and quitting five applications over ssh) | Recorded here because it corrects the *size* of a cutover step rather than taking one, and because the correction was found by reading production and confirmed by a boot. Removing `begin_present`'s registry re-resolve — the read that holds the resident registry in the process-global engine — was sized as "publish carries what the window reads off the slot". It is not: the window reads `slot.access` as the **current Vulkan layout and source masks**, feeds it to its blit barrier's `oldLayout`/`srcStageMask`/`srcAccessMask`, and writes back `registry_note_access(TransferRead)` afterwards. That is a read-modify-write, and a barrier from an access the image has left is an invalid transition rather than a stale picture. `WINDOW_SOURCE_EPOCH` answers only the first of the two questions. So `b37b6740` carries `ResolvedResident` beside the stamp and *compares* it against the re-resolve — five named classes, first difference wins, both resolutions in the line — while the blit still uses the re-resolve, so no frame changes. **The boot: all five classes absent, zero `FAIL` lines, 136 cadence windows all `busy=0` and 89 at `direct_frac=1.00`, `slate_source_stale` absent, `walk_records_render` 278 859 and 169 515 draws.** The publish-time resolution and the window's own re-resolve agreed on every presented frame — the reading the removal needs, on the presenting half. **What it does not say:** `evicts=0` and `gen_mismatch=0` again, so no published resident *left* the registry during the boot and the removal half of the epoch's cover is still unmeasured. That is the same gap the previous three boots left and it is the one thing still owed before the re-resolve goes. Replacement coverage: seven owner-level tests on `divergence_class` as the total function it is — one per class, one that the coarsest difference wins when every field moved at once, one that no two classes share a slug, one that every rendered field is a whitespace-free `k=v` pair, one that a vanished source names only what was promised. No test moved with this row; nothing moved to `dead/`. | -| *(no register row — `d6155cf1`, the window's licence moves to the type that owns the registry)* | `vm/boot-x86.sh --device reims-vgpu-pci --testing --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (three rounds of launching and quitting five applications over ssh), then a clean SIGTERM teardown | Recorded here because it moved a rule rather than a file, and because the comment it replaced said the rule could not be moved. `invalidate_all_resident_holders` bumped two counters and its own doc conceded that "a *new* wholesale-invalidation site that bumps only one counter is exactly the defect, and no test relates a future site to this function". `pools::WINDOW_SOURCE_EPOCH` now moves inside `ResourcePools` at the three points a published resident's promise can end — `unregister_resident` (the sole `registry.remove`), `destroy_all` (the sole `registry.drain`, bumped on the line *above* the loop that frees the images), and `Drop for ResourcePools` (the `*pools = ResourcePools::new()` path that has no `ctx` to destroy anything through). `invalidate_all_resident_holders` keeps only `RESIDENT_RESOURCE_EPOCH`, which has no such owner. A wholesale site that forgets to call it can no longer strand a window stamp. **The boot:** zero `FAIL` lines, all five `window_source_*` divergence classes still absent, 122 cadence windows all `busy=0` with 97 at `direct_frac=1.00`, `walk_records_render` 264 964 and 155 742 draws — indistinguishable from `b37b6740`'s boot on the presenting path, which is the claim, since this changes only what happens when a registry goes away. The teardown the SIGTERM drives is the `destroy_all` this commit added a bump to: QEMU exited on signal 15, the harness reverted its clone, and the fail channel stayed at zero across all 24 005 lines. Replacement coverage: fn `the_resident_registry_has_exactly_one_removal_and_one_drain` (a source-level count over all of `pools/`, since `registry` is a private field and a third exit added later is a use-after-free nothing in the build would relate to this rule), fn `the_wholesale_bump_precedes_the_destruction_it_answers_for`, and two `Drop` tests — one that a pools carrying a window source moves the stamp when it goes, one that a pools carrying none moves nothing, because every test in this crate builds one. No test moved with this row; nothing moved to `dead/`. | -| *(no register row — `1fd17c08`, the promised access)* | `vm/boot-x86.sh --device reims-vgpu-pci --testing --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (three rounds of launching and quitting five applications over ssh), then a clean SIGTERM teardown | The window's *second* registry dependency, closed, and the boot that says the closing is free. `ResidentAccess` is the `oldLayout`, `srcStageMask` and `srcAccessMask` of the barrier the present blit builds, so a resolution whose image is right and whose access is stale is an invalid transition rather than a torn frame — and `WINDOW_SOURCE_EPOCH` vouched only for the image. `ResourcePools::set_registry_access` is now the sole writer of a resident's access and moves the epoch when the value **changes** under a published identity. On a change and not on a write, because a colour target rendered again ends in the access it was already in and a per-write bump would send every present through host memory. **The cost, which the earlier census could not bound** — it compares publish-time against present-time and cannot see a change that reverts in between, and the window's own blit write-back is exactly such a change, once per direct present. **The boot: 123 cadence windows all `busy=0`, 95 at `direct_frac=1.00`** against 97 and 89 on the two boots before it, `slate_source_stale` absent, all five `window_source_*` classes still absent, zero `FAIL` across 23 822 lines, `walk_records_render` 275 915 and 171 675 draws. The rule fires and never reaches the window: the publish that follows a bump takes its stamp after it, and the only source that can go stale is one being re-presented without a new frame. Replacement coverage: fn `moving_a_published_residents_access_moves_the_window_stamp`, fn `rewriting_the_access_a_published_resident_already_holds_moves_nothing` (eight times over — the frame-cost rule), fn `moving_an_unpublished_residents_access_moves_nothing`, and fn `the_registry_writes_a_residents_access_in_exactly_one_place`, a source-level count over all of `pools/` taking any receiver rather than a binding named `slot`. No test moved with this row; nothing moved to `dead/`. | -| *(no register row — `a9a7d515`, the window reads no registry)* | `vm/boot-x86.sh --device reims-vgpu-pci --testing --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (three rounds of launching and quitting five applications over ssh), then a clean SIGTERM teardown | **The host window's present path no longer touches the resident registry.** `begin_present`'s two `registry_get` calls are gone and with them the presenter's whole judgement of a resident: it takes the `WindowPresentResolution` the publish produced under the engine lock and checks one atomic stamp. This is what four commits of this session were for — the window thread can never hold a `&DeviceState` (the lock one comes behind is the drain's, held for a whole render tranche at 935-979 ms per exec packet), so the registry's move to the device needed the window to stop reading it rather than to read it more cheaply. Six `SlateReason` variants become two: `no_resident`, `content_not_ready`, `not_bgra` and `geom_mismatch` were the presenter judging what it had re-resolved, and are now decided by `resident_present_decision` a frame earlier and named there as `winpub_*` on the drain's route channel. **The boot: zero `FAIL` across 21 806 lines, 99 cadence windows all `busy=0`, 73 at `direct_frac=1.00` — every window past the 25 firmware ones and the one crossover, which is the same shape as the 97/123 and 97/122 the two boots before it read** — `slate_source_stale` absent, no `winpub_*` route fired at all, first guest frame presented via rail resident (same-device zero-copy), `walk_records_render` 275 577 and 176 642 draws, clean SIGTERM teardown. Replacement coverage for the four presenter-side classification tests that moved out from under: fn `the_publish_names_the_first_blocker_a_resident_carries` (the same ladder at its owner, plus the every-rung-failing case saying the coarsest wins), fn `each_publish_blocker_has_its_own_route_name` (each rung's `winpub_*` name, and that the accepting arm returns exactly `slot_window_resolution` of the slot it accepted at the epoch it read) and fn `a_declined_publish_vouches_for_nothing`. The seven divergence-census tests went with the census, which after this has nothing to compare. Nothing moved to `dead/`. | -| *(no register row — `13f9aa49`, the blit refusal carries its own reason)* | `vm/boot-x86.sh --device reims-vgpu-pci --testing --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (`vm/drive-desktop.sh`, three rounds of launching and quitting five applications over ssh), then a clean SIGTERM teardown | Seam 6's disconnect list names `BLIT_FAIL_REASON` — "a thread-local carrying a reason the observation channel should carry" — and this is that item, closed. The rail's 177 checks collapse into six classes, so the specific cause had to travel somewhere; it travelled in a thread-local that `br` set, every command entry cleared, and `Refusal::refusal` read back on three unchecked assumptions (same thread, before any other write, at all). It also said nothing about the nineteen sites that never called `br` — `.ok_or(BlitStatus::Capacity)?` and `return Err(BlitStatus::GuestIo)` in the buffer↔texture aspect helpers — which reached the dispatch line as `blit_unattributed`. `BlitStatus` splits into `BlitFailure` (the six classes a caller branches on) and `BlitStatus::Failed { failure, reason }`, `br` is its only constructor, and a refusal with no reason is now unspellable; the nineteen did not compile until each named the check it had been discarding. **The boot: zero `FAIL` across 27 263 lines, 167 cadence windows all `busy=0` with 139 at `direct_frac=1.00`** — the 26 firmware windows with no guest frame plus two crossover windows (0.83, 0.90) account for the rest, the same shape as the 73-of-99 and 97-of-123 the boots before it read — `walk_records_render` 301 624 over 166 windows, 129 678 draws, first guest frame presented via rail resident, clean SIGTERM teardown and revert. **No blit refusal fired at all**, which is the honest reading of this boot: it says the change introduced none, not that the nineteen new slugs were exercised — a driven desktop does not refuse blits, and the nineteen are covered at their owner instead. One `slate_source_stale` episode, one frame, at `display_enable_mask 0xd -> 0xc`: the documented lawful case (the epoch moved between the publish's stamp and the present), reported here because the three rows above record it as absent and this boot is 167 windows against their 99. Replacement coverage: fn `a_refusal_cannot_be_spelled_without_the_check_that_fired` (which asserts the construction rather than the old `blit_unattributed` name, because there is no site left that can produce it), fn `a_refusal_names_which_of_the_collapsed_checks_fired`, and eleven copy/fill-executor tests that read the channel after the status now assert both in one `BlitStatus::Failed { .. }` literal — a stronger statement than the pair was, since it says the class and the check came from the same refusal, which is exactly what the thread-local could not promise. Nothing moved to `dead/`. | -| *(no register row — `e1a4af18` and `9b2470e0`, the publish submits what it vouches for)* | `vm/boot-x86.sh --device reims-vgpu-pci --testing --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (`vm/drive-desktop.sh`, three rounds of launching and quitting five applications over ssh), then a clean SIGTERM teardown | The presenter's `pools.batch_flush` moves to `prepare_window_resident_present`. The flush had to be somewhere — `content_ready` is set when a draw *records* into a resident, so a resolution can name pixels that exist only in a command buffer nobody has ended — and the presenter was the wrong somewhere twice over: the batch is the drain's and the publish *is* the drain, so the window thread was submitting a whole tranche of guest work on the display's latency path; and a flush at present time also submits every draw recorded *after* the publish, so the frame reaching the screen was not the frame the publish vouched for. A flush failure declines by name (`winpub_batch_flush_failed`) and latches `note_device_lost_seen`, because this transaction holds the engine guard and no `ObjectCaches` and that order is fixed. **The boot: zero `FAIL` across 22 868 lines, 112 cadence windows all `busy=0` with 86 at `direct_frac=1.00`** — 24 firmware windows and two crossovers (0.83, 0.88) are the rest, so 86 of the 88 windows past the firmware phase, the same shape as the 139-of-167 the row above read — `walk_records_render` 291 960 over 111 windows, 127 344 draws, first guest frame presented via rail resident, clean SIGTERM teardown and revert. One `slate_source_stale` episode again. **The window thread's engine lock, which is the reading this change is actually about: median 4 acquisitions per second, median 155 µs held per second, median longest single hold 68 µs.** One outlier window at 902 ms total with a single 554 ms hold, which is the swapchain creation at startup and is named here so a later reader does not take it for a steady-state number. That is the floor the remaining work has to beat, and it is small — what is left in that hold is the blit recording and one registry write. `9b2470e0` is the doc that closes `00a52e81`'s open question about that write: it cannot move to the publish (which would promise a transition a `Busy` present never makes, and the lie is the *access*, not the layout, since a primary target and `transfer_read(false)` share `TRANSFER_SRC_OPTIMAL`) and it cannot be replaced by a restore after the blit (the layout comes back, the dependency does not — a guest colour write barriering from the restored `ColorWrite` names `COLOR_ATTACHMENT_OUTPUT` and does not wait for this blit's `TRANSFER` read). The barrier and the record of it are one action; the write leaves when the present becomes a transaction against the device that owns the registry. Replacement coverage: fn `the_window_publish_flushes_the_open_batch_before_it_vouches`, a device test whose assertion is ahead of the publish's own accept/decline, so a refactor that moved the flush behind the decision cannot pass on the accepting arm alone. Nothing moved to `dead/`. | -| *(no register row — `3e4276c5` and `8aa30037`, the live warm draw stops allocating)* | `vm/boot-x86.sh --device reims-vgpu-pci --testing --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail), host-driven workload (`vm/drive-desktop.sh`, three rounds of launching and quitting five applications over ssh), then a clean SIGTERM teardown | "Heap allocations per steady-state draw" is a required value in the plan's structural-zero table. `reims-vgpu-core` had met it for the semantic model; nothing measured the live executor. Measured, a warm repeat draw took **1 trip, 16 bytes**, every run — all of it `exec::clear_values` returning a `Vec` whose first `push` allocated, on the overwhelmingly common draw of one colour target with no secondaries and no depth. It is a `ClearValues` array now and the answer is zero. Capacity is the wire's own bound (`1 + MAX_SECONDARY_ATTACH` is `PASS_MAX_COLOR_ATTACHMENTS`) plus depth, and overflow refuses under the same `SecondaryAttachmentCap` reason the pass-key path uses rather than truncating, because Vulkan indexes the array positionally and a short one gives a later attachment an earlier one's colour. **The boot, which is what a change on the render-pass begin path owes: zero `FAIL` across 25 213 lines, 146 cadence windows all `busy=0` with 119 at `direct_frac=1.00`** — 25 firmware windows and two crossovers (0.83, 0.91) are the rest, so 119 of the 121 past the firmware phase, the same shape as the 86-of-88 and 139-of-141 the two rows above read — `walk_records_render` 285 753 over 146 windows, 123 510 draws, first guest frame presented via rail resident, clean SIGTERM teardown and revert. `slate_source_stale` absent this time. **What the gate does not yet cover, said here rather than left for a reader to assume:** the measured shape binds no descriptors, and `Vec::with_capacity(0)` allocates nothing, so the zero is a statement about descriptor-free draws. A draw that binds anything still builds a `Vec` and clones it into the pipeline key — at least two trips — and that is the next piece of the same gate. Replacement coverage: fn `a_warm_repeat_draw_does_not_enter_the_allocator` (which brackets a counter snapshot, asserting one `batch_joins` and no `batch_flushes` inside the measured region, because an early return allocates nothing too and would pass for the wrong reason) and fn `a_clear_array_past_the_attachment_bound_refuses_rather_than_truncating`. Nothing moved to `dead/`. | -| *(no register row — `191b06c9`, the binding-table split)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail) | The boot the descriptor change owed, because it moves what a draw hands `vkCmdPushDescriptorSetKHR`. Guest reached the desktop through the resident zero-copy path (`first guest frame presented via rail resident`), host-driven workload (three rounds of launching and quitting five applications over ssh), clean SIGTERM teardown, **zero `FAIL` across 19 776 log lines**. The positive evidence is the split's own census: **153 187 draws**, `descriptor_pushes=34 423` against `descriptor_push_held=9 018` — so 9 018 draws found the command buffer already carrying their bindings and, since this commit, build no Vulkan write structures at all, where before they built and dropped a `Vec` and a `Vec` each. `descriptor_set_updates=3` and `descriptor_set_binds=3` in the whole boot, which is the reading that says the allocated-set arm is the exception and the push rail is the one worth measuring. `pass_hits=55 141`, `pipeline_hits=43 089`, `layout_hits=43 380`, `vertex_buffer_bind_slots=144 943`, `batch_joins=41 432` — every one of them a value that reached the encoder through the rewritten path. | -| *(no register row — `5471721f`, the three per-draw lists)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail) | Owed because it moves where a draw's vertex and storage binds live and replaces the gather-role table with a scan. Guest reached the desktop, host-driven workload, clean SIGTERM teardown, **zero `FAIL` across 25 173 log lines**. **172 885 draws**, `vertex_buffer_bind_slots=162 246` reaching the encoder and `vertex_buffer_bind_emitted` equal to it — the bind list now lives in the command buffer's scratch, and those two being equal is what says nothing was dropped moving it — resolved into `vertex_buffer_bind_calls=47 576` consecutive runs. `buffer_bind_reuses=303 021`, `descriptor_pushes=38 795` against `descriptor_push_held=10 374`, `pipeline_hits=48 745`, `pass_hits=61 948`. The gather-role scan replaced a table whose three call sites `expect()` a classification: `buffer_guest_imports=158 028` binds went through them without one returning `None`, which is the whole of what the table was consulted for. **What this boot does not cover:** `buffer_guest_gathers=0` and `buffer_gather_declined=0` — this host imports every guest buffer window directly, so the role's *byte columns* (`buffer_guest_gather_{vertex,storage,shared,index}_bytes`) were never written on it and the scan's split is asserted only by `buffer_gather_roles_partition_physical_content_allocations`. A host without pointer import is what would exercise them. | -| *(no register row — `155fe27b` and `158888b3`, layout and attribute-set interning)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15` (x86 macOS guest, Linux/KVM host, Vulkan rail) | Owed because both change what a draw's pipeline key *is*. Guest reached the desktop, host-driven workload, clean SIGTERM teardown, **zero `FAIL` across 23 735 log lines**, **172 862 draws**. The reading that is about this change is `attr_sets=14`: fourteen distinct vertex-attribute sets for a whole boot, flat across every window. That is the plateau the unbounded object caches are justified by, measured on the newest of them, and it is why the level was added to `object_cache_levels` rather than left uncounted. Beside it the interned layouts answered `layout_hits=48 880` against `layout_misses=59`, `pipeline_hits=48 610`/`pipeline_misses=329`, `pass_hits=61 828`/`pass_misses=20`, `shader_hits=97 637`/`shader_misses=142` — the "no cache miss for a live unchanged contract object after first resolution" zero, as close to met as a boot that compiles new shaders can show. `descriptor_pushes=39 254` against `descriptor_push_held=9 680`, `vertex_buffer_bind_slots=161 833` equal to `vertex_buffer_bind_emitted`. | -| *(no register row — `40748306`, the two scoreboard instruments)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, then `vm/drive-desktop.sh` (x86 macOS guest, Linux/KVM host, Vulkan rail) | The boot the two new censuses were read off, at `40748306`. Guest reached the desktop and the drive script ran its three open/quit rounds to completion (`workload done`, exit 0) with **zero `FAIL` lines** across 39 215 log lines; 164 129 draws, `queue_async_submits=4149` equal to `batch_flushes`, `ring_retire_blocks=0`, `fence_timeouts=0`, `packet_class_unclassified=0`. The readings: `exec_stream_framed=18 421` against `exec_streams_loaded=18 421`, and `access_mode_unknown=342 987` against `read=59 641` / `write=9 866` / `read_write=11 609`. The refusal histogram is 24 distinct `reason=` values, all small and all previously classified — the largest are `gva_zero_pfn`(11), `load_action_dont_care_cleared`(8) and `m2v_pipe_content_changed`(7). **The run ended on `boot-x86.sh`'s own 420 s cap and the script printed its "wedge verdict" banner; that is the harness's timeout and not a hang** — the drive had finished 3 min 19 s earlier and the census kept flowing to the end. A row wanting a clean SIGTERM should send it before the cap. | -| *(no register row — `89be2cbf` and the publisher above it)* | `vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15`, then `vm/drive-desktop.sh` (x86 macOS guest, Linux/KVM host, Vulkan rail) | The boot that says publishing the reflection changed the ordering and nothing else. Guest reached the desktop, three open/quit rounds to `workload done` exit 0, **zero `FAIL` lines** across 24 130, 145 819 draws, `queue_async_submits=2650` equal to `batch_flushes`, `ring_retire_blocks=0`, `fence_timeouts=0`. `pipeline_usage_published=137` with `pipeline_usage_declined`, `pipeline_usage_unnamed` and all three `binding_usage_*` refusals at **zero** — every render pipeline this guest built published both its stages, so the reading is not a small sample of them. The access-mode split moved 81 % → 3.9 % unknown. The refusal histogram is the same shape as the boot before it: 24 distinct `reason=` values against 24, the same top four at the same counts, one gone (`slate_source_stale`) and one arrived (`rt_backing_base_format`), both at one line. No new refusal, no lost draw, no dropped frame — which is what a change that only *removes* ordering edges has to be checked for, because a missing edge shows as a wrong frame and not as a line in this log. | diff --git a/crates/reims-vgpu/src/dead/blit_decoder.rs b/crates/reims-vgpu/src/dead/blit_decoder.rs deleted file mode 100644 index 9d913ce0f..000000000 --- a/crates/reims-vgpu/src/dead/blit_decoder.rs +++ /dev/null @@ -1,1327 +0,0 @@ -// DISCONNECTED SOURCE — this file does not compile, is not feature-gated, and -// is not linkable. No `mod` declaration reaches `dead/`. It is here to be read. -// -// What this was: this device's own blit-rail decoder, `runtime::decode::blit`. -// One `decode` over every opcode the rail carries, returning one flat `Command` -// with roughly fifty fields — the union of nine transfers, three -// indirect-command records, four content directives, two fences and four -// `BlitEncoderSPI` rows — plus a `kind` tag and a `copy_kind` tag saying which -// of them were live. -// -// Why it went, three reasons: -// -// * A record's *class* and its *field offsets* were one verdict. The match -// arm that decided "this is a texture-to-texture copy" was the same arm -// that read the fields, so a misclassification read a real layout at the -// wrong offsets and produced a plausible copy of the wrong bytes. The class -// now comes from the closure ledger through -// `reims_vgpu_core::operation::classify`, and each class is lifted by the -// layer that owns its layout. -// * The flat record made two independent reads of the same question. `kind` -// and `copy_kind` were set separately and read separately — once to charge -// the census clock and once to pick the executor — so a record could be -// timed as one family and executed as another with nothing comparing the -// two. `BlitRecord`'s variants carry named payloads and `kind()` is derived -// from the variant, so both reads are one. -// * `has_options` existed only because this decoder knew which records carry -// an `options:` word and the record did not. A record with no options field -// selects the whole texel, which is exactly what -// `protocol::blit::select_aspect(0)` answers, so the flag was a second -// spelling of a zero. -// -// What did NOT move for a shape reason: the four rows the closure ledger has -// not settled — `resetCommandsInBuffer:withRange:`, -// `copyIndirectCommandBuffer:…`, and the two `fillTexture:…` forms. An -// unresolved row has no established contract, so no layer above the wire may -// give it a shape; this device decodes them in order to *decline* them by name -// and with their extents, and that decline's count is the measurement that -// settles the row. `runtime::decode::blit_spi` is that decoder, and it is -// deliberately narrow: it refuses every settled opcode, so no record on this -// rail has two readings. -// -// Replaced by commit "cutover: the blit rail's nine transfers were a flat -// record with a tag saying which fields were live". Do not resurrect: read it, -// then fix the new owner. - -//! Blit command decoder (port of `host/utils/reims-vgpu-blit-decode`). -//! -//! # The three indirect-command-buffer records, which this decoder reads and no -//! executor applies -//! -//! **Apple's serializer emits all three**, so calling them "rejected" -- which -//! this module did -- was a claim about Apple that the serializer contradicts: -//! `copyIndirectCommandBuffer:sourceRange:destination:destinationIndex:` writes -//! `0x131`, `optimizeIndirectCommandBuffer:withRange:` writes `0x138` and -//! `resetCommandsInBuffer:withRange:` writes `0x139`, each pinned by a fixture -//! in `reims_vgpu_wire::ops::blit` (`CopyIcb`, `IcbRange`). -//! -//! They sit inside this encoder's opcode space, between `0x12c` and `0x13e`, so -//! they are not a foreign encoder's numbers arriving in a blit segment either. -//! -//! They used to be refused whole, under one shared reason. Refusing them said -//! three different things with one word, and the three are not equivalent: -//! `0x138` is Metal's *optimization hint*, so skipping it is semantically -//! correct and costs only speed, while `0x139` leaves commands live that the -//! guest asked to be reset and `0x131` leaves a destination buffer holding -//! whatever it held before. Two of the three are lost work and one is not. -//! Decoding them lets `runtime::exec` say which; see the arms there. -//! -//! # The five records `-setSupportsBlitEncoderSPI:` gates -//! -//! This encoder's opcode run does not stop at `0x13e`. It was read that way for -//! as long as the wire capture drove the class with every capability at its -//! default, and all sixteen of those default off -- so five real records looked -//! like selectors Apple never emits, and this decoder answered every one of -//! them with `ErrUnknownOpcode`. -//! -//! Each is pinned by a fixture in [`reims_vgpu_wire::ops::blit`], and the three -//! fills are writes to guest-visible memory: dropping one leaves the -//! destination holding whatever it held before, which the guest then reads back -//! as content it believes it just wrote. -//! -//! `0x142` and `0x143` are the [`wire::Ref`] and [`wire::RefSliceLevel`] shapes -//! exactly, and this module deliberately does **not** fold them into the arms -//! that already decode those shapes: those arms end in the executor's -//! unconditional no-op, and a compressed-texture invalidate that silently -//! joined them would be indistinguishable from a `synchronizeTexture:` that -//! genuinely needs nothing done. - -use reims_vgpu_wire::ops::blit as wire; - -// `MTLBlitOption`, owned by `reims-vgpu-protocol` — the layer that assigns -// meaning to a wire tag — and named here because this is where it is read. -pub use reims_vgpu_protocol::blit::{ - MTL_BLIT_OPTION_DEPTH_FROM_DEPTH_STENCIL, MTL_BLIT_OPTION_KNOWN_MASK, MTL_BLIT_OPTION_NONE, - MTL_BLIT_OPTION_ROW_LINEAR_PVRTC, MTL_BLIT_OPTION_STENCIL_FROM_DEPTH_STENCIL, -}; - -/// Selected texture aspect for a buffer↔texture / options-bearing copy. -/// -/// Defined in [`crate::protocol::pixel_format`], which is where every consumer -/// of the choice lives, and re-exported here because this is where it is -/// produced. One type, so the decoder's refusal of depth+stencil is the only -/// place that state is ever considered. -pub(crate) use crate::protocol::pixel_format::BlitAspect; - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum BlitOptionError { - UnknownBits, - RowLinearPvrtc, - ConflictingAspects, -} - -impl crate::observe::Decline for BlitOptionError { - fn slug(&self) -> &'static str { - match self { - Self::UnknownBits => "blit_options_unknown_bits", - Self::RowLinearPvrtc => "blit_options_row_linear_pvrtc", - Self::ConflictingAspects => "blit_options_conflicting_aspects", - } - } -} - -/// Parse wire `MTLBlitOption` bits into a product-path aspect selection. -/// -/// - Zero / absent options → [`BlitAspect::Full`] -/// - Depth and stencil bits are mutually exclusive -/// - `RowLinearPVRTC` and unknown bits fail (no PVRTC rail; unknown stays unknown) -pub fn parse_blit_options(has_options: bool, options: u32) -> Result { - if !has_options { - return Ok(BlitAspect::Full); - } - // The rule itself belongs to the layer that owns the tag, and both rails - // ask it there. What stays here is the "no options word at all" case, - // which is a fact about the *record shape* this decoder read and not about - // the word. - reims_vgpu_protocol::blit::select_aspect(options).map_err(|refusal| match refusal { - reims_vgpu_protocol::blit::OptionRefusal::UnknownBits { .. } => { - BlitOptionError::UnknownBits - } - reims_vgpu_protocol::blit::OptionRefusal::RowLinearPvrtc => BlitOptionError::RowLinearPvrtc, - reims_vgpu_protocol::blit::OptionRefusal::ConflictingAspects => { - BlitOptionError::ConflictingAspects - } - }) -} - -/// Why the blit decoder refused a command. -/// -/// There is deliberately no `Ok`: `decode` returns `Result`, so -/// success is the `Ok` arm of the result and not a variant here. `ErrArgs` went -/// with it — every argument this decoder rejects is a payload too short for the -/// field it was about to read, which is `ErrShort`. Both were constructed only -/// by the test that listed them. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum DecodeStatus { - ErrShort, - ErrUnknownOpcode, -} - -impl crate::observe::Refusal for DecodeStatus { - /// Slugs carry a `blit_decode_` prefix. - /// - /// `DecodeStatus` is **seven separate enums** in `runtime/decode/`, one per - /// module, and five of them have an `ErrShort`. Without the prefix they - /// would all answer with the same name for five different reads, which is - /// the collapse the crate-wide uniqueness gate exists to refuse. - fn refusal(&self) -> Option<&'static str> { - Some(match self { - Self::ErrShort => "blit_decode_short", - Self::ErrUnknownOpcode => "blit_decode_unknown_opcode", - }) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum Kind { - #[default] - Unknown = 0, - Copy, - FillBuffer, - Resource, - Image, - Fence, - /// `optimizeIndirectCommandBuffer:withRange:` and - /// `resetCommandsInBuffer:withRange:`, which name one ICB and a command - /// range. Which of the two is [`Command::opcode`]; the buffer is - /// [`Command::resource`] and the range is [`Command::range_location`] and - /// [`Command::range_length`]. - IcbRange, - /// `copyIndirectCommandBuffer:sourceRange:destination:destinationIndex:`. - /// Source and destination are [`Command::source`] and - /// [`Command::destination`], the source range is the shared range pair, and - /// the destination command index is [`Command::destination_index`]. - IcbCopy, - /// `fillBuffer:range:pattern4:` — [`Kind::FillBuffer`] with a repeating - /// 32-bit unit in [`Command::fill_pattern`] instead of the single byte in - /// [`Command::fill_value`]. Separate kinds rather than one kind with two - /// value fields, because an executor that read the wrong one would write - /// plausible bytes rather than fail. - FillBufferPattern4, - /// `fillTexture:level:slice:region:color:[pixelFormat:]` and - /// `fillTexture:level:slice:region:bytes:length:`, told apart by - /// [`Command::fill_source`]. - FillTexture, - /// `invalidateCompressedTexture:` and its `slice:level:` form. The texture - /// is [`Command::texture`]; the whole-texture form leaves - /// [`Command::slice`] and [`Command::level`] at zero, and - /// [`Command::opcode`] is what distinguishes "slice 0, level 0" from "every - /// slice and every level". - InvalidateCompressedTexture, -} - -/// Where a [`Kind::FillTexture`] takes the value it writes. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum FillSource { - #[default] - None = 0, - /// A clear colour, in [`Command::fill_color_raw`], interpreted in - /// [`Command::fill_pixel_format`]. - Color, - /// A pixel pattern the serializer staged into a buffer rather than putting - /// it on the wire: [`Command::fill_bytes_ref`], - /// [`Command::fill_bytes_offset`] and [`Command::fill_bytes_length`]. The - /// record carries no pixel data. - Bytes, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum CopyKind { - #[default] - None = 0, - BufferToTexture, - BufferToBuffer, - TextureToBuffer, - TextureToTexture, - TextureToTextureSliceLevel, -} - -/// What a blit command's source/destination/resource ref names. -/// -/// There is deliberately no `Fence`: the two fence opcodes carry their ref in -/// [`Command::fence`] under [`Kind::Fence`] and leave every `RefKind` field at -/// `None`, so a `RefKind::Fence` was a second name for a ref this decoder puts -/// somewhere else. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum RefKind { - #[default] - None = 0, - Buffer, - Texture, - Resource, - /// An `MTLIndirectCommandBuffer`. Not folded into [`Self::Resource`]: the - /// three ICB records reach it through `indirectCommandBufferRef`, which is - /// a different accessor from every other resource in this encoder, and a - /// consumer that resolved one as a generic resource would look it up in the - /// wrong table. - IndirectCommandBuffer, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct Point { - pub x: u64, - pub y: u64, - pub z: u64, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct Size { - pub width: u64, - pub height: u64, - pub depth: u64, -} - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct Command { - pub opcode: u32, - pub command_length: u32, - pub kind: Kind, - pub copy_kind: CopyKind, - pub source_kind: RefKind, - pub destination_kind: RefKind, - pub source: u32, - pub destination: u32, - pub source_offset: u64, - pub source_bytes_per_row: u64, - pub source_bytes_per_image: u64, - pub source_origin: Point, - pub source_size: Size, - pub destination_offset: u64, - pub destination_bytes_per_row: u64, - pub destination_bytes_per_image: u64, - pub destination_origin: Point, - pub size: u64, - pub source_slice: u16, - pub source_level: u16, - pub destination_slice: u16, - pub destination_level: u16, - pub slice_count: u16, - pub level_count: u16, - pub has_options: bool, - pub options: u32, - pub resource: u32, - pub resource_kind: RefKind, - pub buffer: u32, - pub range_location: u64, - pub range_length: u64, - /// Destination command index of a [`Kind::IcbCopy`]. - /// - /// A `u64` of its own rather than one of the `u16` subresource indices - /// beside it: this counts *commands* in the destination buffer, and the - /// record keeps the two kinds of index apart. - pub destination_index: u64, - pub fill_value: u8, - /// The repeating 32-bit unit of a [`Kind::FillBufferPattern4`]. - pub fill_pattern: u32, - pub texture: u32, - pub slice: u16, - pub level: u16, - pub fence: u32, - - // --- Kind::FillTexture --------------------------------------------------- - pub fill_source: FillSource, - /// The filled region. Named apart from the copy records' origin and size - /// because a fill has one texture and no direction: reusing - /// `source_origin`/`destination_origin` here would make a reader ask which - /// end of a copy this was. - /// - /// The wire stores the region **size before its origin**, reversing - /// `MTLRegion` and the selector's own type encoding. That is the wire - /// crate's business and this decoder reads it through the pinned view, but - /// it is the reason not to hand-roll the offsets here. - pub fill_origin: Point, - pub fill_size: Size, - /// The clear colour's four components as the serializer wrote them. - /// - /// IEEE-754 `double` bit patterns rather than `f64`, for two reasons: - /// [`Command`] is `Eq`, which `f64` cannot be, and nothing in this device - /// converts them yet — so storing the bits keeps the record exact instead of - /// committing to a conversion no consumer has asked for. - pub fill_color_raw: [u64; 4], - /// The format the colour is interpreted in. Comes from the guest's argument - /// on the `pixelFormat:` form and from the *texture* on the other, and the - /// wire record cannot tell you which — [`Command::opcode`] is the same for - /// both. - pub fill_pixel_format: u16, - /// The staging buffer a [`FillSource::Bytes`] fill named, its offset, and - /// the number of pattern bytes there. An executor must fetch them; the - /// record carries no pixel data and the length is the guest's rather than - /// anything derivable from the region. - pub fill_bytes_ref: u32, - pub fill_bytes_offset: u64, - pub fill_bytes_length: u64, -} - -/// Transactional decode of one blit command record. -/// -/// Framing and field layout come from [`reims_vgpu_wire`]: [`reims_vgpu_wire::op`] -/// for the shared header, and the parsers in [`reims_vgpu_wire::ops::blit`] for -/// each covered payload. This module maps those views into the product -/// [`Command`] / [`Kind`] model and names refusals; it does not restate offsets. -pub fn decode(command: &[u8]) -> Result { - let op = reims_vgpu_wire::op(command, 0).map_err(|_| DecodeStatus::ErrShort)?; - let mut out = Command { - opcode: op.opcode(), - command_length: op.length(), - ..Default::default() - }; - let command_length = op.length() as usize; - - match op.opcode() { - wire::OPCODE_COPY_BUFFER_TO_TEXTURE => { - if command_length != wire::COPY_BUFFER_TO_TEXTURE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let c = wire::copy_buffer_to_texture(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Copy; - out.copy_kind = CopyKind::BufferToTexture; - out.source_kind = RefKind::Buffer; - out.destination_kind = RefKind::Texture; - out.source = c.source_ref.get(); - out.destination = c.dest_ref.get(); - out.source_offset = c.source_offset.get(); - out.source_bytes_per_row = c.source_bytes_per_row.get(); - out.source_bytes_per_image = c.source_bytes_per_image.get(); - out.source_size = Size { - width: c.size_width.get(), - height: c.size_height.get(), - depth: c.size_depth.get(), - }; - out.destination_origin = Point { - x: c.dest_origin_x.get(), - y: c.dest_origin_y.get(), - z: c.dest_origin_z.get(), - }; - out.destination_slice = c.dest_slice.get(); - out.destination_level = c.dest_level.get(); - out.has_options = true; - out.options = c.options.get(); - Ok(out) - } - wire::OPCODE_COPY_BUFFER_TO_BUFFER => { - if command_length != wire::COPY_BUFFER_TO_BUFFER_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let c = wire::copy_buffer_to_buffer(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Copy; - out.copy_kind = CopyKind::BufferToBuffer; - out.source_kind = RefKind::Buffer; - out.destination_kind = RefKind::Buffer; - out.source = c.source_ref.get(); - out.destination = c.dest_ref.get(); - out.source_offset = c.source_offset.get(); - out.destination_offset = c.dest_offset.get(); - out.size = c.size.get(); - Ok(out) - } - wire::OPCODE_COPY_TEXTURE_TO_BUFFER => { - if command_length != wire::COPY_TEXTURE_TO_BUFFER_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let c = wire::copy_texture_to_buffer(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Copy; - out.copy_kind = CopyKind::TextureToBuffer; - out.source_kind = RefKind::Texture; - out.destination_kind = RefKind::Buffer; - out.source = c.source_ref.get(); - out.destination = c.dest_ref.get(); - out.source_origin = Point { - x: c.source_origin_x.get(), - y: c.source_origin_y.get(), - z: c.source_origin_z.get(), - }; - out.source_size = Size { - width: c.size_width.get(), - height: c.size_height.get(), - depth: c.size_depth.get(), - }; - out.destination_offset = c.dest_offset.get(); - out.destination_bytes_per_row = c.dest_bytes_per_row.get(); - out.destination_bytes_per_image = c.dest_bytes_per_image.get(); - out.source_slice = c.source_slice.get(); - out.source_level = c.source_level.get(); - out.has_options = true; - // Wire stores options as u16 on this record (see CopyTextureToBuffer). - out.options = c.options.get() as u32; - Ok(out) - } - wire::OPCODE_COPY_TEXTURE_REGION => { - if command_length != wire::COPY_TEXTURE_REGION_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let c = wire::copy_texture_region(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Copy; - out.copy_kind = CopyKind::TextureToTexture; - out.source_kind = RefKind::Texture; - out.destination_kind = RefKind::Texture; - out.source = c.source_ref.get(); - out.destination = c.dest_ref.get(); - out.source_origin = Point { - x: c.source_origin_x.get(), - y: c.source_origin_y.get(), - z: c.source_origin_z.get(), - }; - out.source_size = Size { - width: c.size_width.get(), - height: c.size_height.get(), - depth: c.size_depth.get(), - }; - out.destination_origin = Point { - x: c.dest_origin_x.get(), - y: c.dest_origin_y.get(), - z: c.dest_origin_z.get(), - }; - out.source_slice = c.source_slice.get(); - out.source_level = c.source_level.get(); - out.destination_slice = c.dest_slice.get(); - out.destination_level = c.dest_level.get(); - Ok(out) - } - wire::OPCODE_COPY_TEXTURE_REGION_OPTIONS => { - if command_length != wire::COPY_TEXTURE_REGION_OPTIONS_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let c = wire::copy_texture_region_options(&op).map_err(|_| DecodeStatus::ErrShort)?; - let r = &c.region; - out.kind = Kind::Copy; - out.copy_kind = CopyKind::TextureToTexture; - out.source_kind = RefKind::Texture; - out.destination_kind = RefKind::Texture; - out.source = r.source_ref.get(); - out.destination = r.dest_ref.get(); - out.source_origin = Point { - x: r.source_origin_x.get(), - y: r.source_origin_y.get(), - z: r.source_origin_z.get(), - }; - out.source_size = Size { - width: r.size_width.get(), - height: r.size_height.get(), - depth: r.size_depth.get(), - }; - out.destination_origin = Point { - x: r.dest_origin_x.get(), - y: r.dest_origin_y.get(), - z: r.dest_origin_z.get(), - }; - out.source_slice = r.source_slice.get(); - out.source_level = r.source_level.get(); - out.destination_slice = r.dest_slice.get(); - out.destination_level = r.dest_level.get(); - out.has_options = true; - out.options = c.options.get(); - Ok(out) - } - wire::OPCODE_COPY_TEXTURE_SLICES => { - if command_length != wire::COPY_TEXTURE_SLICES_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let c = wire::copy_texture_slices(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Copy; - out.copy_kind = CopyKind::TextureToTextureSliceLevel; - out.source_kind = RefKind::Texture; - out.destination_kind = RefKind::Texture; - out.source = c.source_ref.get(); - out.destination = c.dest_ref.get(); - out.source_slice = c.source_slice.get(); - out.source_level = c.source_level.get(); - out.destination_slice = c.dest_slice.get(); - out.destination_level = c.dest_level.get(); - out.slice_count = c.slice_count.get(); - out.level_count = c.level_count.get(); - Ok(out) - } - wire::OPCODE_FILL_BUFFER => { - if command_length != wire::FILL_BUFFER_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let f = wire::fill_buffer(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::FillBuffer; - out.buffer = f.buffer_ref.get(); - out.range_location = f.range_location.get(); - out.range_length = f.range_length.get(); - out.fill_value = f.value; - Ok(out) - } - wire::OPCODE_GENERATE_MIPMAPS - | wire::OPCODE_OPTIMIZE_FOR_CPU - | wire::OPCODE_OPTIMIZE_FOR_GPU => { - if command_length != wire::REF_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let r = wire::object_ref(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Resource; - out.resource_kind = RefKind::Texture; - out.resource = r.object_ref.get(); - Ok(out) - } - wire::OPCODE_OPTIMIZE_FOR_CPU_SLICE_LEVEL - | wire::OPCODE_OPTIMIZE_FOR_GPU_SLICE_LEVEL - | wire::OPCODE_SYNCHRONIZE_TEXTURE => { - if command_length != wire::REF_SLICE_LEVEL_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let r = wire::ref_slice_level(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Image; - out.texture = r.texture_ref.get(); - out.slice = r.slice.get(); - out.level = r.level.get(); - Ok(out) - } - wire::OPCODE_SYNCHRONIZE_RESOURCE => { - if command_length != wire::REF_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let r = wire::object_ref(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Resource; - out.resource_kind = RefKind::Resource; - out.resource = r.object_ref.get(); - Ok(out) - } - wire::OPCODE_UPDATE_FENCE | wire::OPCODE_WAIT_FOR_FENCE => { - if command_length != wire::REF_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let r = wire::object_ref(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Fence; - out.fence = r.object_ref.get(); - Ok(out) - } - wire::OPCODE_OPTIMIZE_ICB | wire::OPCODE_RESET_ICB => { - if command_length != wire::ICB_RANGE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let r = wire::icb_range(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::IcbRange; - out.resource_kind = RefKind::IndirectCommandBuffer; - out.resource = r.icb_ref.get(); - out.range_location = r.range_location.get(); - out.range_length = r.range_length.get(); - Ok(out) - } - wire::OPCODE_COPY_ICB => { - if command_length != wire::COPY_ICB_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let c = wire::copy_icb(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::IcbCopy; - out.source_kind = RefKind::IndirectCommandBuffer; - out.destination_kind = RefKind::IndirectCommandBuffer; - out.source = c.source_ref.get(); - out.destination = c.dest_ref.get(); - out.range_location = c.range_location.get(); - out.range_length = c.range_length.get(); - out.destination_index = c.dest_index.get(); - Ok(out) - } - wire::OPCODE_FILL_BUFFER_PATTERN4 => { - if command_length != wire::FILL_BUFFER_PATTERN4_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let f = wire::fill_buffer_pattern4(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::FillBufferPattern4; - out.buffer = f.buffer_ref.get(); - out.range_location = f.range_location.get(); - out.range_length = f.range_length.get(); - out.fill_pattern = f.pattern.get(); - Ok(out) - } - wire::OPCODE_FILL_TEXTURE_COLOR => { - if command_length != wire::FILL_TEXTURE_COLOR_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let f = wire::fill_texture_color(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::FillTexture; - out.fill_source = FillSource::Color; - out.texture = f.texture_ref.get(); - out.level = f.level.get(); - out.slice = f.slice.get(); - out.fill_origin = Point { - x: f.origin_x.get(), - y: f.origin_y.get(), - z: f.origin_z.get(), - }; - out.fill_size = Size { - width: f.size_width.get(), - height: f.size_height.get(), - depth: f.size_depth.get(), - }; - out.fill_color_raw = [ - f.color_red.get().to_bits(), - f.color_green.get().to_bits(), - f.color_blue.get().to_bits(), - f.color_alpha.get().to_bits(), - ]; - out.fill_pixel_format = f.pixel_format.get(); - Ok(out) - } - wire::OPCODE_FILL_TEXTURE_BYTES => { - if command_length != wire::FILL_TEXTURE_BYTES_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let f = wire::fill_texture_bytes(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::FillTexture; - out.fill_source = FillSource::Bytes; - out.texture = f.texture_ref.get(); - out.level = f.level.get(); - out.slice = f.slice.get(); - out.fill_origin = Point { - x: f.origin_x.get(), - y: f.origin_y.get(), - z: f.origin_z.get(), - }; - out.fill_size = Size { - width: f.size_width.get(), - height: f.size_height.get(), - depth: f.size_depth.get(), - }; - out.fill_bytes_ref = f.bytes_ref.get(); - out.fill_bytes_offset = f.bytes_offset.get(); - out.fill_bytes_length = f.length.get(); - Ok(out) - } - wire::OPCODE_INVALIDATE_COMPRESSED_TEXTURE => { - if command_length != wire::REF_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let r = wire::object_ref(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::InvalidateCompressedTexture; - out.texture = r.object_ref.get(); - Ok(out) - } - wire::OPCODE_INVALIDATE_COMPRESSED_TEXTURE_SLICE_LEVEL => { - if command_length != wire::REF_SLICE_LEVEL_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let r = wire::ref_slice_level(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::InvalidateCompressedTexture; - out.texture = r.texture_ref.get(); - out.slice = r.slice.get(); - out.level = r.level.get(); - Ok(out) - } - _ => Err(DecodeStatus::ErrUnknownOpcode), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::protocol::endian::{st16, st32, st64}; - use core::mem::offset_of; - use reims_vgpu_wire::OP_HEADER_LEN; - - // format offsets (payload-relative) - - const CBT_OPTIONS: usize = offset_of!(wire::CopyBufferToTexture, options); - const CBT_LEN: usize = wire::COPY_BUFFER_TO_TEXTURE_TOTAL_LEN as usize; - - const CBB_SRC_OFF: usize = offset_of!(wire::BufferToBuffer, source_offset); - const CBB_DST_OFF: usize = offset_of!(wire::BufferToBuffer, dest_offset); - const CBB_SIZE: usize = offset_of!(wire::BufferToBuffer, size); - const CBB_LEN: usize = wire::COPY_BUFFER_TO_BUFFER_TOTAL_LEN as usize; - - const CTB_OPTIONS: usize = offset_of!(wire::CopyTextureToBuffer, options); - const CTB_LEN: usize = wire::COPY_TEXTURE_TO_BUFFER_TOTAL_LEN as usize; - - const CTT_LEN: usize = wire::COPY_TEXTURE_REGION_TOTAL_LEN as usize; - const CTT_OPTIONS_LEN: usize = wire::COPY_TEXTURE_REGION_OPTIONS_TOTAL_LEN as usize; - - const FILL_REF: usize = offset_of!(wire::FillBuffer, buffer_ref); - const FILL_RANGE_LOC: usize = offset_of!(wire::FillBuffer, range_location); - const FILL_RANGE_LEN: usize = offset_of!(wire::FillBuffer, range_length); - const FILL_VALUE: usize = offset_of!(wire::FillBuffer, value); - const FILL_LEN: usize = wire::FILL_BUFFER_TOTAL_LEN as usize; - - const RESOURCE_LEN: usize = wire::REF_TOTAL_LEN as usize; - const FENCE_LEN: usize = wire::REF_TOTAL_LEN as usize; - - fn hdr(opcode: u32, len: u32) -> Vec { - let mut v = vec![0u8; len as usize]; - st32(&mut v[0..4], opcode); - st32(&mut v[4..8], len); - v - } - - /// A blit record that fails to decode used to be `Err(_) => return` at the - /// dispatch site — a dropped guest command indistinguishable from a segment - /// carrying no blit work. Each of the four checks now names itself, and `Ok` - /// still produces no line. - #[test] - fn every_blit_decode_failure_names_its_own_check() { - use crate::observe::{Decline, Refusal}; - const ALL: &[DecodeStatus] = &[DecodeStatus::ErrShort, DecodeStatus::ErrUnknownOpcode]; - let mut slugs: Vec<&str> = ALL.iter().filter_map(|s| s.refusal()).collect(); - assert_eq!(slugs.len(), ALL.len(), "every variant refuses"); - slugs.sort_unstable(); - slugs.dedup(); - assert_eq!( - slugs.len(), - ALL.len(), - "two blit decode checks share a slug" - ); - // The prefix is load-bearing: seven modules define a `DecodeStatus` and - // five of them have an `ErrShort` meaning a different read. - assert!(slugs.iter().all(|s| s.starts_with("blit_decode_"))); - - // The three option checks used to be discarded by `map_err(|_| ..)`. - let mut opts: Vec<&str> = [ - BlitOptionError::UnknownBits, - BlitOptionError::RowLinearPvrtc, - BlitOptionError::ConflictingAspects, - ] - .iter() - .map(|e| e.slug()) - .collect(); - opts.sort_unstable(); - opts.dedup(); - assert_eq!(opts.len(), 3, "two blit option checks share a slug"); - } - - #[test] - fn buffer_to_buffer() { - let mut v = hdr(wire::OPCODE_COPY_BUFFER_TO_BUFFER, CBB_LEN as u32); - st32(&mut v[8..], 1); - st32(&mut v[12..], 2); - st64(&mut v[8 + CBB_SRC_OFF..], 0x10); - st64(&mut v[8 + CBB_DST_OFF..], 0x20); - st64(&mut v[8 + CBB_SIZE..], 0x30); - let c = decode(&v).unwrap(); - assert_eq!(c.copy_kind, CopyKind::BufferToBuffer); - assert_eq!(c.source, 1); - assert_eq!(c.destination, 2); - assert_eq!(c.size, 0x30); - } - - #[test] - fn fill_buffer() { - let mut v = hdr(wire::OPCODE_FILL_BUFFER, FILL_LEN as u32); - st32(&mut v[8 + FILL_REF..], 9); - st64(&mut v[8 + FILL_RANGE_LOC..], 4); - st64(&mut v[8 + FILL_RANGE_LEN..], 8); - v[8 + FILL_VALUE] = 0xAB; - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::FillBuffer); - assert_eq!(c.fill_value, 0xAB); - assert_eq!(c.range_length, 8); - } - - /// The pattern fill is the byte fill with a wider last field, and this - /// reads it as one. - /// - /// The pattern is asymmetric so a decoder that read it big-endian, or read - /// only its low byte into `fill_value`, fails rather than producing a - /// plausible number. - #[test] - fn fill_buffer_pattern4() { - let total = wire::FILL_BUFFER_PATTERN4_TOTAL_LEN; - let mut v = hdr(wire::OPCODE_FILL_BUFFER_PATTERN4, total); - st32(&mut v[OP_HEADER_LEN..], 9); - st64(&mut v[OP_HEADER_LEN + 4..], 0x3300); - st64(&mut v[OP_HEADER_LEN + 12..], 0x4400); - st32(&mut v[OP_HEADER_LEN + 20..], 0x89ab_cdef); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::FillBufferPattern4); - assert_eq!(c.buffer, 9); - assert_eq!(c.range_location, 0x3300); - assert_eq!(c.range_length, 0x4400); - assert_eq!(c.fill_pattern, 0x89ab_cdef); - // The two fills are distinct kinds precisely so this cannot happen: an - // executor reading `fill_value` off a pattern record would write one - // plausible byte instead of failing. - assert_eq!(c.fill_value, 0); - } - - /// The two texture fills share every field up to their tail, and the tail - /// is what `fill_source` names. - /// - /// The region is checked component by component with no two values equal, - /// because the wire stores the size **before** the origin — reversing - /// `MTLRegion` — and a decoder that took them the other way round would - /// read back a region that is the right shape and in the wrong place. - #[test] - fn both_texture_fills_decode_their_region_size_before_origin() { - let region = |v: &mut [u8]| { - let p = OP_HEADER_LEN; - st32(&mut v[p..], 4242); - st16(&mut v[p + 4..], 3); - st16(&mut v[p + 6..], 5); - st64(&mut v[p + 8..], 0x44); - st64(&mut v[p + 16..], 0x55); - st64(&mut v[p + 24..], 0x66); - st64(&mut v[p + 32..], 0x11); - st64(&mut v[p + 40..], 0x22); - st64(&mut v[p + 48..], 0x33); - }; - let expect_shared = |c: &Command| { - assert_eq!(c.kind, Kind::FillTexture); - assert_eq!(c.texture, 4242); - assert_eq!(c.level, 3); - assert_eq!(c.slice, 5); - assert_eq!( - c.fill_size, - Size { - width: 0x44, - height: 0x55, - depth: 0x66 - } - ); - assert_eq!( - c.fill_origin, - Point { - x: 0x11, - y: 0x22, - z: 0x33 - } - ); - }; - - let mut v = hdr( - wire::OPCODE_FILL_TEXTURE_COLOR, - wire::FILL_TEXTURE_COLOR_TOTAL_LEN, - ); - region(&mut v); - for (i, bits) in [0.25f64, 0.5, 0.75, 1.0].iter().enumerate() { - st64(&mut v[OP_HEADER_LEN + 56 + i * 8..], bits.to_bits()); - } - st16(&mut v[OP_HEADER_LEN + 88..], 80); - let c = decode(&v).unwrap(); - expect_shared(&c); - assert_eq!(c.fill_source, FillSource::Color); - assert_eq!( - c.fill_color_raw, - [ - 0.25f64.to_bits(), - 0.5f64.to_bits(), - 0.75f64.to_bits(), - 1.0f64.to_bits() - ], - "the four colour components must keep their order" - ); - assert_eq!(c.fill_pixel_format, 80); - assert_eq!(c.fill_bytes_ref, 0); - - let mut v = hdr( - wire::OPCODE_FILL_TEXTURE_BYTES, - wire::FILL_TEXTURE_BYTES_TOTAL_LEN, - ); - region(&mut v); - st32(&mut v[OP_HEADER_LEN + 56..], 8181); - st64(&mut v[OP_HEADER_LEN + 60..], 0x9999); - st64(&mut v[OP_HEADER_LEN + 68..], 8); - let c = decode(&v).unwrap(); - expect_shared(&c); - assert_eq!(c.fill_source, FillSource::Bytes); - // The pattern is staged, not inline: the record names a buffer and an - // offset and carries no pixel data. - assert_eq!(c.fill_bytes_ref, 8181); - assert_eq!(c.fill_bytes_offset, 0x9999); - assert_eq!(c.fill_bytes_length, 8); - assert_eq!(c.fill_color_raw, [0; 4]); - } - - /// Both compressed-texture invalidates reach one kind, and the `slice:level:` - /// form is the only one that carries a subresource. - /// - /// These share their wire shapes with `generateMipmapsForTexture:` and - /// `synchronizeTexture:slice:level:`, whose arms end in the executor's - /// unconditional no-op. Landing there would be correct behaviour and an - /// unusable measurement — "this workload issues no compressed-texture - /// invalidates" would be unprovable — so the kind is separate. - #[test] - fn both_compressed_texture_invalidates_are_their_own_kind() { - let mut v = hdr( - wire::OPCODE_INVALIDATE_COMPRESSED_TEXTURE, - wire::REF_TOTAL_LEN, - ); - st32(&mut v[OP_HEADER_LEN..], 4242); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::InvalidateCompressedTexture); - assert_eq!(c.texture, 4242); - assert_eq!((c.slice, c.level), (0, 0)); - - let mut v = hdr( - wire::OPCODE_INVALIDATE_COMPRESSED_TEXTURE_SLICE_LEVEL, - wire::REF_SLICE_LEVEL_TOTAL_LEN, - ); - st32(&mut v[OP_HEADER_LEN..], 4242); - st16(&mut v[OP_HEADER_LEN + 4..], 3); - st16(&mut v[OP_HEADER_LEN + 6..], 5); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::InvalidateCompressedTexture); - assert_eq!(c.texture, 4242); - assert_eq!(c.slice, 3); - assert_eq!(c.level, 5); - // Not folded into `Kind::Image`, which the same wire shape reaches for - // three other opcodes. `opcode` is what tells the two forms apart, - // because "slice 0, level 0" and "every slice, every level" read alike. - assert_eq!( - c.opcode, - wire::OPCODE_INVALIDATE_COMPRESSED_TEXTURE_SLICE_LEVEL - ); - } - - /// Every one of the five refuses a record one byte short of its length. - /// - /// The length check is what stops a truncated record being read as a whole - /// one, and each of these lengths is a constant from the wire crate rather - /// than a number restated here — so a serializer that changed one fails - /// this rather than decoding into the wrong fields. - #[test] - fn each_spi_record_refuses_a_length_one_byte_short() { - for (op, total) in [ - ( - wire::OPCODE_FILL_BUFFER_PATTERN4, - wire::FILL_BUFFER_PATTERN4_TOTAL_LEN, - ), - ( - wire::OPCODE_FILL_TEXTURE_BYTES, - wire::FILL_TEXTURE_BYTES_TOTAL_LEN, - ), - ( - wire::OPCODE_FILL_TEXTURE_COLOR, - wire::FILL_TEXTURE_COLOR_TOTAL_LEN, - ), - ( - wire::OPCODE_INVALIDATE_COMPRESSED_TEXTURE, - wire::REF_TOTAL_LEN, - ), - ( - wire::OPCODE_INVALIDATE_COMPRESSED_TEXTURE_SLICE_LEVEL, - wire::REF_SLICE_LEVEL_TOTAL_LEN, - ), - ] { - let v = hdr(op, total - 1); - assert_eq!( - decode(&v), - Err(DecodeStatus::ErrShort), - "op {op:#x} accepted a record one byte short of {total}" - ); - } - } - - #[test] - fn parse_blit_options_aspects() { - assert_eq!(parse_blit_options(false, 0), Ok(BlitAspect::Full)); - assert_eq!(parse_blit_options(true, 0), Ok(BlitAspect::Full)); - assert_eq!( - parse_blit_options(true, MTL_BLIT_OPTION_DEPTH_FROM_DEPTH_STENCIL), - Ok(BlitAspect::Depth) - ); - assert_eq!( - parse_blit_options(true, MTL_BLIT_OPTION_STENCIL_FROM_DEPTH_STENCIL), - Ok(BlitAspect::Stencil) - ); - // Both depth+stencil forbidden. - assert!(parse_blit_options( - true, - MTL_BLIT_OPTION_DEPTH_FROM_DEPTH_STENCIL | MTL_BLIT_OPTION_STENCIL_FROM_DEPTH_STENCIL - ) - .is_err()); - // PVRTC not on product path. - assert!(parse_blit_options(true, MTL_BLIT_OPTION_ROW_LINEAR_PVRTC).is_err()); - // Unknown bits fail. - assert!(parse_blit_options(true, 1 << 8).is_err()); - } - - /// `copyFromTexture:toBuffer:` reads two bytes of `options`, not four. - /// - /// It is the one copy record that narrows the field: the serializer wrote - /// `04 00 AA AA` there against the oracle's poison, where the - /// buffer-to-texture and region forms fill all four. The two bytes past it - /// belong to no field, so on a guest's wire they hold whatever the ring - /// last contained — which is what the poison stands in for here. - /// - /// Both halves matter. A plain copy writes zero into the two live bytes and - /// must still parse as `Full`; a depth-aspect copy must reach `Depth` - /// rather than being refused for bits that were never written. - #[test] - fn a_texture_to_buffer_copy_reads_no_byte_past_its_options() { - for (written, want) in [ - (0u16, BlitAspect::Full), - ( - MTL_BLIT_OPTION_DEPTH_FROM_DEPTH_STENCIL as u16, - BlitAspect::Depth, - ), - ] { - let mut v = hdr(wire::OPCODE_COPY_TEXTURE_TO_BUFFER, CTB_LEN as u32); - // Everything past the options field is ring content, not record. - for b in v.iter_mut().skip(OP_HEADER_LEN + CTB_OPTIONS + 2) { - *b = 0xAA; - } - st16(&mut v[OP_HEADER_LEN + CTB_OPTIONS..], written); - - let c = decode(&v).expect("a well-formed copy must decode"); - assert_eq!( - c.options, written as u32, - "options picked up a byte the serializer never wrote" - ); - assert_eq!(parse_blit_options(c.has_options, c.options), Ok(want)); - } - - // The sibling that really is four bytes wide keeps reading four, so - // this is a per-record narrowing rather than a family rule. - let mut v = hdr(wire::OPCODE_COPY_BUFFER_TO_TEXTURE, CBT_LEN as u32); - st32(&mut v[OP_HEADER_LEN + CBT_OPTIONS..], 0x0001_0000); - assert_eq!(decode(&v).unwrap().options, 0x0001_0000); - } - - /// A record we decline and a number we do not recognise are different - /// refusals, and the three ICB opcodes are the first kind. - /// - /// The opcodes come from `reims-vgpu-wire`, where fixtures pin them against - /// bytes the serializer produced. Asserting them against that crate rather - /// than against literals is what keeps this from drifting back into a claim - /// that Apple never emits them. - #[test] - fn an_icb_blit_record_is_read_rather_than_refused_whole() { - use crate::protocol::endian::st64; - use reims_vgpu_wire::ops::blit as wire; - - for (op, wire_op) in [ - (wire::OPCODE_COPY_ICB, wire::OPCODE_COPY_ICB), - (wire::OPCODE_OPTIMIZE_ICB, wire::OPCODE_OPTIMIZE_ICB), - (wire::OPCODE_RESET_ICB, wire::OPCODE_RESET_ICB), - ] { - assert_eq!(op, wire_op, "the serializer writes a different opcode"); - } - // Still inside this encoder's opcode space, which is why "a foreign - // encoder's number arrived here" was never the explanation. - for op in [ - wire::OPCODE_COPY_ICB, - wire::OPCODE_OPTIMIZE_ICB, - wire::OPCODE_RESET_ICB, - ] { - assert!( - (wire::OPCODE_COPY_BUFFER_TO_TEXTURE..=wire::OPCODE_COPY_TEXTURE_SLICES) - .contains(&op), - "op {op:#x} is outside the blit opcode space" - ); - } - - // The two range forms: a ref then two `u64` in declaration order. The - // range values differ from each other so a record that carried the same - // number twice could not read back correct. - for op in [wire::OPCODE_OPTIMIZE_ICB, wire::OPCODE_RESET_ICB] { - let total = wire::ICB_RANGE_TOTAL_LEN; - let mut v = hdr(op, total); - st32(&mut v[OP_HEADER_LEN..], 6161); - st64(&mut v[OP_HEADER_LEN + 4..], 0x3300); - st64(&mut v[OP_HEADER_LEN + 12..], 0x4400); - let c = decode(&v).unwrap_or_else(|e| panic!("op {op:#x}: {e:?}")); - assert_eq!(c.kind, Kind::IcbRange, "op {op:#x}"); - assert_eq!( - c.resource_kind, - RefKind::IndirectCommandBuffer, - "op {op:#x}" - ); - assert_eq!(c.resource, 6161, "op {op:#x}"); - assert_eq!( - (c.range_location, c.range_length), - (0x3300, 0x4400), - "op {op:#x}: the range is crossed" - ); - assert_eq!( - decode(&hdr(op, total - 4)).unwrap_err(), - DecodeStatus::ErrShort, - "op {op:#x} accepted a record four bytes short" - ); - } - - // The copy: both refs lead, and the destination index is a `u64` beside - // the source range rather than a `u16` at the tail — it counts commands, - // not subresources. Four distinct values, so no pair can be swapped - // without the assertion seeing it. - let total = wire::COPY_ICB_TOTAL_LEN; - let mut v = hdr(wire::OPCODE_COPY_ICB, total); - st32(&mut v[OP_HEADER_LEN..], 7171); - st32(&mut v[OP_HEADER_LEN + 4..], 7272); - st64(&mut v[OP_HEADER_LEN + 8..], 0x1100); - st64(&mut v[OP_HEADER_LEN + 16..], 0x2200); - st64(&mut v[OP_HEADER_LEN + 24..], 0x3300); - let c = decode(&v).expect("copy icb"); - assert_eq!(c.kind, Kind::IcbCopy); - assert_eq!((c.source, c.destination), (7171, 7272)); - assert_eq!(c.source_kind, RefKind::IndirectCommandBuffer); - assert_eq!(c.destination_kind, RefKind::IndirectCommandBuffer); - assert_eq!((c.range_location, c.range_length), (0x1100, 0x2200)); - assert_eq!( - c.destination_index, 0x3300, - "the destination index read one of the range words" - ); - assert_eq!( - decode(&hdr(wire::OPCODE_COPY_ICB, total - 4)).unwrap_err(), - DecodeStatus::ErrShort - ); - - assert_eq!( - decode(&hdr(0x999, 16)).unwrap_err(), - DecodeStatus::ErrUnknownOpcode - ); - } - - #[test] - fn fence_and_resource() { - let mut v = hdr(wire::OPCODE_UPDATE_FENCE, FENCE_LEN as u32); - st32(&mut v[8..], 3); - assert_eq!(decode(&v).unwrap().fence, 3); - let mut v = hdr(wire::OPCODE_GENERATE_MIPMAPS, RESOURCE_LEN as u32); - st32(&mut v[8..], 5); - let c = decode(&v).unwrap(); - assert_eq!(c.resource, 5); - assert_eq!(c.resource_kind, RefKind::Texture); - } - - #[test] - fn texture_to_texture_options_len() { - let v = hdr( - wire::OPCODE_COPY_TEXTURE_REGION_OPTIONS, - CTT_OPTIONS_LEN as u32, - ); - // zeros decode fine - let c = decode(&v).unwrap(); - assert!(c.has_options); - let bad = hdr(wire::OPCODE_COPY_TEXTURE_REGION_OPTIONS, CTT_LEN as u32); - assert_eq!(decode(&bad).unwrap_err(), DecodeStatus::ErrShort); - } - - /// Every blit opcode Apple's serializer emits has a constant here, and this - /// module names no opcode Apple does not emit. - /// - /// The blit arm is the one where both directions of this have already cost - /// guest work. Three records the serializer emits were called records it - /// refuses, and `0x13f`–`0x143` — the six `BlitEncoderSPI` selectors — all - /// reached `blit_decode_unknown_opcode` until the capability was forced, - /// because `ops::blit`'s own doc said the run stopped at `0x13e` and no - /// capture had contradicted it. A run's upper end is a statement about what - /// has been driven, so nothing here may take one on faith. - /// - /// Unlike the compute sibling this is plain set equality: the blit encoder - /// has no inherited numbers and no refused-but-decoded arms, so a mismatch - /// in either direction is a defect rather than an exception to record. - #[test] - fn the_blit_opcode_table_is_exactly_apples_blit_manifest() { - let device: &[(u32, &str)] = &[ - ( - wire::OPCODE_COPY_BUFFER_TO_TEXTURE, - "wire::OPCODE_COPY_BUFFER_TO_TEXTURE", - ), - ( - wire::OPCODE_COPY_BUFFER_TO_BUFFER, - "wire::OPCODE_COPY_BUFFER_TO_BUFFER", - ), - ( - wire::OPCODE_COPY_TEXTURE_TO_BUFFER, - "wire::OPCODE_COPY_TEXTURE_TO_BUFFER", - ), - ( - wire::OPCODE_COPY_TEXTURE_REGION, - "wire::OPCODE_COPY_TEXTURE_REGION", - ), - ( - wire::OPCODE_COPY_TEXTURE_REGION_OPTIONS, - "wire::OPCODE_COPY_TEXTURE_REGION_OPTIONS", - ), - (wire::OPCODE_COPY_ICB, "wire::OPCODE_COPY_ICB"), - (wire::OPCODE_FILL_BUFFER, "wire::OPCODE_FILL_BUFFER"), - ( - wire::OPCODE_GENERATE_MIPMAPS, - "wire::OPCODE_GENERATE_MIPMAPS", - ), - ( - wire::OPCODE_OPTIMIZE_FOR_CPU, - "wire::OPCODE_OPTIMIZE_FOR_CPU", - ), - ( - wire::OPCODE_OPTIMIZE_FOR_GPU, - "wire::OPCODE_OPTIMIZE_FOR_GPU", - ), - ( - wire::OPCODE_OPTIMIZE_FOR_CPU_SLICE_LEVEL, - "wire::OPCODE_OPTIMIZE_FOR_CPU_SLICE_LEVEL", - ), - ( - wire::OPCODE_OPTIMIZE_FOR_GPU_SLICE_LEVEL, - "wire::OPCODE_OPTIMIZE_FOR_GPU_SLICE_LEVEL", - ), - (wire::OPCODE_OPTIMIZE_ICB, "wire::OPCODE_OPTIMIZE_ICB"), - (wire::OPCODE_RESET_ICB, "wire::OPCODE_RESET_ICB"), - ( - wire::OPCODE_SYNCHRONIZE_RESOURCE, - "wire::OPCODE_SYNCHRONIZE_RESOURCE", - ), - ( - wire::OPCODE_SYNCHRONIZE_TEXTURE, - "wire::OPCODE_SYNCHRONIZE_TEXTURE", - ), - (wire::OPCODE_UPDATE_FENCE, "wire::OPCODE_UPDATE_FENCE"), - (wire::OPCODE_WAIT_FOR_FENCE, "wire::OPCODE_WAIT_FOR_FENCE"), - ( - wire::OPCODE_COPY_TEXTURE_SLICES, - "wire::OPCODE_COPY_TEXTURE_SLICES", - ), - ( - wire::OPCODE_FILL_BUFFER_PATTERN4, - "wire::OPCODE_FILL_BUFFER_PATTERN4", - ), - ( - wire::OPCODE_FILL_TEXTURE_BYTES, - "wire::OPCODE_FILL_TEXTURE_BYTES", - ), - ( - wire::OPCODE_FILL_TEXTURE_COLOR, - "wire::OPCODE_FILL_TEXTURE_COLOR", - ), - ( - wire::OPCODE_INVALIDATE_COMPRESSED_TEXTURE, - "wire::OPCODE_INVALIDATE_COMPRESSED_TEXTURE", - ), - ( - wire::OPCODE_INVALIDATE_COMPRESSED_TEXTURE_SLICE_LEVEL, - "wire::OPCODE_INVALIDATE_COMPRESSED_TEXTURE_SLICE_LEVEL", - ), - ]; - - let mut apple: Vec = reims_vgpu_wire::manifest::MANIFEST - .iter() - .filter(|e| e.class == "PGSerializerBlitCommandEncoder") - .flat_map(|e| e.opcodes.iter().copied()) - .collect(); - apple.sort_unstable(); - apple.dedup(); - - for (op, name) in device { - assert!( - apple.contains(op), - "{name} = {op:#x} is not an opcode Apple's blit manifest lists, \ - so no capture supports it" - ); - } - for op in &apple { - assert!( - device.iter().any(|(d, _)| d == op), - "Apple's serializer emits blit opcode {op:#x} and this module \ - names no constant for it, so every copy or fill carrying it is \ - declined as an opcode Apple does not write" - ); - } - assert_eq!( - device.len(), - apple.len(), - "the roster has a duplicate entry" - ); - } - - #[test] - fn property_fuzz_opcodes() { - for op in 0x120u32..0x150 { - let mut v = hdr(op, 0x80); - let _ = decode(&v); - // also exact common lengths - for len in [0x0c, 0x10, 0x1c, 0x20, 0x28, 0x60, 0x64] { - v = hdr(op, len); - let _ = decode(&v); - } - } - } -} diff --git a/crates/reims-vgpu/src/dead/child_deprecated_ops.rs b/crates/reims-vgpu/src/dead/child_deprecated_ops.rs deleted file mode 100644 index f758d07f2..000000000 --- a/crates/reims-vgpu/src/dead/child_deprecated_ops.rs +++ /dev/null @@ -1,84 +0,0 @@ -// DISCONNECTED SOURCE — this file does not compile, is not feature-gated, and -// is not linkable. No `mod` declaration reaches `dead/`. It is here to be read. -// -// What this was: the drain's own transcription of the fifteen child opcodes the -// reference host routes to its shared deprecated handler, and the predicate the -// dispatcher matched them with. It lived in `crate::model::regs` beside this -// device's live command constants. -// -// Why it went: `reims_vgpu_protocol::packets::LEDGER` judges those same fifteen -// rows `Closure::ProvenNoOp`, and `reims_vgpu_core::control::ControlKind::of` -// turns that judgement into `ControlKind::RetiredSlot`. Two lists of one set is -// two places a slot that goes live has to be remembered, and the cost of -// forgetting one is a live command swallowed by a handler that does nothing. -// -// Do not resurrect any of this. When a boot regresses on a retired slot, read -// it to learn what the old arm did and fix `reims_vgpu_core::control` or the -// ledger row. - -/// The opcodes the reference host routes to its one shared deprecated handler. -/// -/// These are real slots with a real handler, not holes: the host accepts the -/// packet, does nothing with the payload and retires the stamps. They are -/// listed rather than folded into the unknown arm so a guest that still emits -/// one is reported as "sent a retired command" and not as "sent something this -/// device cannot decode" — the first is expected of an older guest and the -/// second is a gap in this device. -/// -/// `0x2d` is in this set on the reference host, and is also -/// [`ROOT_OP_DEVICE_INFO_MONTEREY`]. Both are true: the Monterey-era device-info -/// command was retired in favour of [`ROOT_OP_DEVICE_INFO_TAHOE`] (`0x3a`), and -/// this device still answers it for a guest old enough to ask. The root arm runs -/// first, so the deprecated arm never sees it on the root channel. -pub const CHILD_DEPRECATED_OPS: [u16; 15] = [ - 0x03, 0x1f, 0x21, 0x23, 0x24, 0x26, 0x27, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x32, -]; - -/// True for the opcodes in [`CHILD_DEPRECATED_OPS`]. -/// -/// A function rather than a match arm because a `match` cannot pattern on an -/// array's contents, and spelling the fifteen numbers a second time in a pattern -/// is exactly the duplicated-constant mistake `no_two_child_opcodes_share_a_number` -/// exists to catch. -#[must_use] -pub const fn is_deprecated_child_opcode(opcode: u16) -> bool { - let mut i = 0; - while i < CHILD_DEPRECATED_OPS.len() { - if CHILD_DEPRECATED_OPS[i] == opcode { - return true; - } - i += 1; - } - false -} - -// ---- The legacy test that moved with it, from `runtime::decode::ledger` ---- -// -// Circular the moment the table above went: it asked the ledger whether it -// agreed with a transcription of itself. Replaced by -// `the_ledger_judges_a_retired_set_at_all` in the same module — which asserts -// the set's size against the reference host rather than against a copy — and by -// `a_retired_slot_is_reported_as_retired_and_not_as_undecodable` in -// `runtime::drain::tests`, now driven off the ledger and so covering every -// judged slot rather than every transcribed one. - /// The retired slots are commands too — the reference host has one handler - /// for all fifteen — so each is a row, and a row that says the shared - /// handler's behavior *is* the contract rather than a gap. - #[test] - fn every_retired_slot_has_a_ledger_row() { - for op in CHILD_DEPRECATED_OPS { - let row = find(Channel::Child, op) - .unwrap_or_else(|| panic!("retired slot {op:#04x} is unjudged")); - assert!( - matches!( - row.closure, - reims_vgpu_protocol::closure::Closure::ProvenNoOp { .. } - ), - "retired slot {op:#04x} reads as {} — the reference host's shared handler is the \ - whole contract, so anything else claims this device owes more or less than the \ - host it is imitating", - row.closure.name() - ); - } - } - diff --git a/crates/reims-vgpu/src/dead/compute_decoder.rs b/crates/reims-vgpu/src/dead/compute_decoder.rs deleted file mode 100644 index 70b7731e5..000000000 --- a/crates/reims-vgpu/src/dead/compute_decoder.rs +++ /dev/null @@ -1,1293 +0,0 @@ -// DISCONNECTED — this file is not a module. Nothing here compiles or links. -// -// It was `crates/reims-vgpu/src/runtime/decode/compute.rs`: the compute rail's -// single decoder, which assigned a `Kind` in the same pass that read the fields -// and so gave a record's class and its layout as one verdict. The seventeen -// rows the closure ledger has settled are lifted by -// `reims_vgpu_protocol::decode::compute` and routed by -// `reims_vgpu_core::operation::classify`; the barriers, the compressed- -// reinterpretation flush and the unqualified residency pair are answered from -// their own protocol decoders in `runtime::exec`; the eleven rows the ledger -// has not settled are decoded by `runtime::decode::compute_spi`. -// -// Read it to learn what the old arms did. Nothing is resurrected from here, and -// no build-time or run-time switch may reach it — see `dead/README.md`. -// -// What is *not* here, because it never had a successor: `OpcodeConfidence`, -// `opcode_apple_rejected` and `REJECTED_85`/`REJECTED_88`/`REJECTED_C7`. Those -// three opcodes are rows Apple's serializer was shown not to emit, and the -// closure ledger has no entry for any of them, so `ErrUnsupportedOpcode` — -// "this is a real compute opcode this decoder does not handle" — has no -// question left to answer. A record carrying one of them is -// `compute_decode_unknown_opcode` now, which is what the ledger says it is. - -//! Compute command decoder (port of `host/utils/reims-vgpu-compute-decode`). - -use crate::protocol::endian::ld32; -use reims_vgpu_wire::ops::compute as wire; - -/// Shared serializer op-header length from `reims-vgpu-wire`. -use reims_vgpu_wire::OP_HEADER_LEN; - -/// Residency on the compute rail. -/// -/// # These are inherited, not unsupported -/// -/// This doc used to say the pair had **no selector behind it at all**: the -/// compute encoder's own selector list carries no `useHeaps:`/`useResources:`, -/// so — the argument went — nothing in the serializer can produce these two -/// numbers, and `compute_noop_residency_hint` reading zero on a driven boot was -/// that conclusion confirmed. -/// -/// The premise is true and the conclusion does not follow. Residency is declared -/// on the encoder base class, which every encoder derives from, in an -/// unqualified `useHeaps:count:` / `useResources:count:usage:` pair; only the -/// `stages:`-qualified overrides are declared on the render encoder, which is -/// why those are the only ones that appear in -/// [`reims_vgpu_wire::manifest`]. That manifest is built from each class's *own* -/// method list and has no row for the base class, so a base-class selector is -/// absent from it while being callable on every encoder — see the caveat in that -/// module, which this is the worked example of. -/// -/// So a compute encoder does answer `useHeaps:count:`, and these are the numbers -/// it emits. The zero counter says this workload never issued one, which is the -/// ordinary reading of a healthy zero, not evidence that the arm is unreachable. -/// -/// The layouts agree independently: the emitted record for `useHeaps:count:` is -/// a four-byte head and `count` four-byte refs, and for -/// `useResources:count:usage:` an eight-byte head and the same refs — which is -/// exactly [`COUNT_BASE`] and [`BIND_BASE`] below. -/// -/// # The render rail had the same gap, and it is closed -/// -/// `runtime::decode::render` carried `0x86`/`0x87` as its residency pair until a -/// capture replaced them with `0x1b`/`0x89`. That replacement was right for the -/// records it measured — those are the `stages:`-qualified forms — but it left -/// the render rail knowing only half the family, because a render encoder -/// inherits the unqualified pair too, and an unqualified -/// `useResources:count:usage:` on a render encoder reached no render arm at all. -/// -/// It now carries all four: `wire::OPCODE_USE_RESOURCES_NO_STAGES` and -/// `wire::OPCODE_USE_HEAPS_NO_STAGES` decode beside the qualified pair, with the -/// usage read at the wider width the unqualified form writes it and the stages -/// left at zero because that selector has none, and `runtime::exec` routes all -/// four through `note_residency_declaration`. Recorded here rather than deleted -/// because this module is where the inheritance argument is written down, and a -/// reader who follows it needs to know which rail it has already been applied -/// to. -/// -/// Whether guest work is lost depends on the declaration, on either rail: this -/// device answers a *read* residency declaration by doing nothing, for the -/// reason `runtime::exec` states, and a *write* one is content it never produces -/// — which is why the classification, not the count, is what the routes carry. -pub const OP_USE_HEAPS: u32 = 0x86; -pub const OP_USE_RESOURCES: u32 = 0x87; - -pub const REJECTED_85: u32 = 0x85; -pub const REJECTED_88: u32 = 0x88; -pub const REJECTED_C7: u32 = 0xc7; - -const COUNT_BASE: usize = OP_HEADER_LEN + 4; -const BIND_BASE: usize = OP_HEADER_LEN + 8; -const REF_SIZE: usize = 4; -const BUF_ENTRY: usize = 12; -const BUF_STRIDE_ENTRY: usize = 20; -const SAMPLER_LOD_ENTRY: usize = 12; -/// A control-flow marker is the header alone; the crate that derived the -/// predicate form derived this one beside it. -/// -/// `insertCompressedTextureReinterpretationFlush` shares this arm and is a -/// different family with its own derivation, so its length is asserted equal -/// rather than assumed: two records being the header alone is a fact about each -/// one, not a fact they share. -const EMPTY_LEN: usize = wire::CONTROL_FLOW_MARKER_TOTAL_LEN as usize; -const _: () = assert!(EMPTY_LEN == wire::INSERT_COMPRESSED_TEXTURE_FLUSH_TOTAL_LEN as usize); - -/// Why the compute decoder refused a command. -/// -/// No `Ok` and no `ErrArgs`, for the reason recorded on `blit::DecodeStatus`: -/// success is the result's own `Ok`, and a bad argument here is a payload -/// shorter than the field, which `ErrShort` already names. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum DecodeStatus { - ErrShort, - ErrUnknownOpcode, - ErrUnsupportedOpcode, -} - -impl crate::observe::Refusal for DecodeStatus { - /// Slugs carry a `compute_decode_` prefix: seven modules under - /// `runtime/decode/` define a type called `DecodeStatus`, and five of them - /// have an `ErrShort` that means a different read. Without the prefix the - /// crate-wide uniqueness gate could not tell the compute decoder's refusals - /// from any other's. - fn refusal(&self) -> Option<&'static str> { - Some(match self { - Self::ErrShort => "compute_decode_short", - Self::ErrUnknownOpcode => "compute_decode_unknown_opcode", - Self::ErrUnsupportedOpcode => "compute_decode_unsupported_opcode", - }) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum OpcodeConfidence { - #[default] - Unknown = 0, - AppleEmittedConfirmed, - AppleRejected, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum Kind { - #[default] - Unknown = 0, - UseHeaps, - UseResources, - Pipeline, - BufferBind, - BufferOffset, - TextureBind, - SamplerBind, - SamplerLod, - DispatchThreadgroups, - DispatchThreadgroupsIndirect, - DispatchThreads, - StageInRegion, - StageInRegionIndirect, - ThreadgroupMemory, - UpdateFence, - WaitFence, - BarrierResources, - BarrierScope, - ImageblockDimensions, - BufferBindAttributeStride, - BufferOffsetAttributeStride, - DispatchType, - DispatchThreadsIndirect, - ControlStartDoWhile, - ControlEndDoWhile, - ControlStartWhile, - ControlEndWhile, - ControlStartIf, - ControlStartElse, - ControlEndIf, - CompressedTextureFlush, - ExecuteCommandsInBuffer, - ExecuteCommandsInBufferIndirect, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct Size3 { - pub x: u64, - pub y: u64, - pub z: u64, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct BufferBinding { - pub ref_: u32, - pub offset: u64, - pub attribute_stride: u64, - pub has_attribute_stride: bool, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct RefBinding { - pub ref_: u32, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct SamplerBinding { - pub ref_: u32, - pub lod_min_bits: u32, - pub lod_max_bits: u32, - pub has_lod_clamp: bool, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct Region3 { - pub origin: Size3, - pub size: Size3, -} - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct Command { - pub opcode: u32, - pub command_length: u32, - pub kind: Kind, - pub confidence: OpcodeConfidence, - pub pipeline_ref: u32, - pub first: u32, - pub count: u32, - pub buffers: Vec, - pub textures: Vec, - pub samplers: Vec, - pub resources: Vec, - pub heaps: Vec, - pub grid: Size3, - pub threads_per_threadgroup: Size3, - pub indirect_buffer_ref: u32, - pub indirect_buffer_offset: u64, - pub buffer_offset: u64, - pub attribute_stride: u64, - pub imageblock_width: u32, - pub imageblock_height: u32, - pub dispatch_type: u32, - pub stage_in_region: Region3, - pub stage_in_indirect_buffer_ref: u32, - pub stage_in_indirect_buffer_offset: u64, - pub threadgroup_memory_length: u64, - pub threadgroup_memory_index: u32, - /// `MTLResourceUsage` from `useResources:count:usage:`. Zero on the heap - /// form, which carries no usage argument — that zero is a property of the - /// selector and not a guest declaring no access. - pub resource_usage: reims_vgpu_protocol::residency::ResourceUsage, - pub fence_ref: u32, - pub barrier_scope: u16, - pub condition_buffer_ref: u32, - pub condition_buffer_offset: u64, - pub condition_comparison: u32, - pub condition_reference_value: u32, - pub indirect_command_buffer_ref: u32, - pub indirect_command_range_location: u64, - pub indirect_command_range_length: u64, - pub indirect_command_arguments_buffer_ref: u32, - pub indirect_command_arguments_buffer_offset: u64, -} - -pub fn opcode_supported(opcode: u32) -> bool { - matches!( - opcode, - OP_USE_HEAPS - | OP_USE_RESOURCES - | wire::OPCODE_DISPATCH_THREADGROUPS - | wire::OPCODE_DISPATCH_THREADGROUPS_INDIRECT - | wire::OPCODE_DISPATCH_THREADS - | wire::OPCODE_SET_BUFFER - | wire::OPCODE_SET_SAMPLER - | wire::OPCODE_SET_SAMPLER_LOD - | wire::OPCODE_SET_TEXTURE - | wire::OPCODE_SET_BUFFER_OFFSET - | wire::OPCODE_SET_PIPELINE_STATE - | wire::OPCODE_SET_STAGE_IN_REGION - | wire::OPCODE_SET_STAGE_IN_REGION_INDIRECT - | wire::OPCODE_SET_THREADGROUP_MEMORY_LENGTH - | wire::OPCODE_UPDATE_FENCE - | wire::OPCODE_WAIT_FOR_FENCE - | wire::OPCODE_MEMORY_BARRIER_RESOURCES - | wire::OPCODE_MEMORY_BARRIER_SCOPE - | wire::OPCODE_SET_IMAGEBLOCK_SIZE - | wire::OPCODE_SET_BUFFER_STRIDE - | wire::OPCODE_SET_BUFFER_OFFSET_STRIDE - | wire::OPCODE_WRITE_DESCRIPTOR - | wire::OPCODE_START_DO_WHILE - | wire::OPCODE_END_DO_WHILE - | wire::OPCODE_START_WHILE - | wire::OPCODE_END_WHILE - | wire::OPCODE_START_IF - | wire::OPCODE_START_ELSE - | wire::OPCODE_END_IF - | wire::OPCODE_INSERT_COMPRESSED_TEXTURE_FLUSH - | wire::OPCODE_EXECUTE_COMMANDS_RANGE - | wire::OPCODE_EXECUTE_COMMANDS_INDIRECT - | wire::OPCODE_DISPATCH_THREADS_INDIRECT - ) -} - -pub fn opcode_apple_rejected(opcode: u32) -> bool { - matches!(opcode, REJECTED_85 | REJECTED_88 | REJECTED_C7) -} - -pub fn opcode_confidence(opcode: u32) -> OpcodeConfidence { - if opcode_supported(opcode) { - OpcodeConfidence::AppleEmittedConfirmed - } else if opcode_apple_rejected(opcode) { - OpcodeConfidence::AppleRejected - } else { - OpcodeConfidence::Unknown - } -} - -/// Whether a variable-length record's declared length is exactly what `count` -/// entries of `stride` need. -/// -/// **A bind record is bounded by its own length and by nothing else.** Seven -/// call sites used to test `count > MAX_BIND_ENTRIES` first and refuse the whole -/// record with `ErrTooManyBindings`; the constant was 128 and carried no -/// citation. `runtime::decode::render` removed the identical check for the -/// identical reason — its cap was 32 and refused a 40-slot texture bind Apple's -/// serializer really produces, dropping all forty rather than the eight that -/// would not fit — and `bind_record_len` there states the rule this doc now -/// states here. -/// -/// The cap was also redundant, which is why removing it costs no safety. The -/// count is never trusted before this check, `command_length <= command.len()` -/// is established at the top of [`decode`], and the arithmetic below is done in -/// `u64` and bounded at `u32::MAX`, so nothing is read or pushed until the -/// entries are known to be inside the record the guest itself sized. What the -/// cap added was a second, lower bound with no derivation behind it. -/// -/// Which index a backend can actually bind is a *backend* question and is -/// already answered there — `REIMS_VGPU_METAL_MAX_BUFFERS` and -/// `valid_buffer_binding` on the Metal arm, the descriptor-set limits on the -/// Vulkan one. A decoder that pre-empts them refuses guest work neither of them -/// would have. -/// -/// **The limit those caps were reaching for has since been measured, and it is -/// three numbers rather than one** — see [`reims_vgpu_wire::ops::bind_limit`], -/// where fixtures pin them. Apple's serializer truncates a plural bind's range -/// at the stage's argument table: 128 textures, **31** buffers, 16 samplers, -/// with the bound falling on `first + count` rather than on `count`. -/// -/// That is the sharper reason a single `MAX_BIND_ENTRIES` could not have been -/// right at these seven sites. The compute rail's 128 was correct for the two -/// texture sites and four times too permissive for the buffer ones; the render -/// rail's 32 was above the buffer limit and a quarter of the texture one, which -/// is the half that fired. A cap that is too permissive never refuses anything -/// and so never looks wrong. -/// -/// It does **not** license reinstating them as three constants. These describe -/// what Apple's serializer *emits*; they are not a validity check on bytes -/// arriving from a guest, and refusing a record for declaring more entries than -/// Apple currently writes loses every bind in it the first time a limit moves. -/// The record's own declared length is the bound, and it always was. -fn var_len(cmd_len: usize, base: usize, count: u32, stride: usize) -> bool { - let expected = base as u64 + (count as u64) * (stride as u64); - expected <= u32::MAX as u64 && cmd_len == expected as usize -} - -/// Transactional compute command decode. -/// -/// Framing and covered layouts come from [`reims_vgpu_wire`]: [`reims_vgpu_wire::op`] -/// for the shared header and the parsers in [`reims_vgpu_wire::ops::compute`] for -/// each payload this encoder owns. Local residency opcodes (`OP_USE_HEAPS` / -/// `OP_USE_RESOURCES`) have no wire export and stay hand-read. -pub fn decode(command: &[u8]) -> Result { - let op = reims_vgpu_wire::op(command, 0).map_err(|_| DecodeStatus::ErrShort)?; - let opcode = op.opcode(); - let command_length = op.length() as usize; - let confidence = opcode_confidence(opcode); - if confidence == OpcodeConfidence::Unknown { - return Err(DecodeStatus::ErrUnknownOpcode); - } - if !opcode_supported(opcode) { - return Err(DecodeStatus::ErrUnsupportedOpcode); - } - let payload = op.payload; - let mut out = Command { - opcode, - command_length: op.length(), - confidence, - ..Default::default() - }; - - match opcode { - OP_USE_HEAPS => { - // No wire export: Apple's compute serializer has no useHeaps: selector. - if command_length < COUNT_BASE { - return Err(DecodeStatus::ErrShort); - } - let count = ld32(&payload[0..]); - if !var_len(command_length, COUNT_BASE, count, REF_SIZE) { - return Err(DecodeStatus::ErrShort); - } - out.kind = Kind::UseHeaps; - out.count = count; - for i in 0..count as usize { - out.heaps.push(RefBinding { - ref_: ld32(&payload[4 + i * REF_SIZE..]), - }); - } - Ok(out) - } - OP_USE_RESOURCES => { - // No wire export: same gap as OP_USE_HEAPS. - if command_length < BIND_BASE { - return Err(DecodeStatus::ErrShort); - } - let count = ld32(&payload[0..]); - if !var_len(command_length, BIND_BASE, count, REF_SIZE) { - return Err(DecodeStatus::ErrShort); - } - out.kind = Kind::UseResources; - out.count = count; - out.resource_usage = reims_vgpu_protocol::residency::ResourceUsage(ld32(&payload[4..])); - for i in 0..count as usize { - out.resources.push(RefBinding { - ref_: ld32(&payload[8 + i * REF_SIZE..]), - }); - } - Ok(out) - } - wire::OPCODE_SET_PIPELINE_STATE => { - if command_length != wire::SET_PIPELINE_STATE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let r = wire::set_pipeline_state(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Pipeline; - out.pipeline_ref = r.object_ref.get(); - Ok(out) - } - wire::OPCODE_SET_BUFFER => { - let (head, entries) = wire::buffer_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - if !var_len(command_length, BIND_BASE, head.count.get(), BUF_ENTRY) { - return Err(DecodeStatus::ErrShort); - } - out.kind = Kind::BufferBind; - out.first = head.first.get(); - out.count = head.count.get(); - for e in entries { - out.buffers.push(BufferBinding { - ref_: e.buffer_ref.get(), - offset: e.offset.get(), - ..Default::default() - }); - } - Ok(out) - } - wire::OPCODE_SET_BUFFER_STRIDE => { - let (head, entries) = - wire::buffer_stride_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - if !var_len( - command_length, - BIND_BASE, - head.count.get(), - BUF_STRIDE_ENTRY, - ) { - return Err(DecodeStatus::ErrShort); - } - out.kind = Kind::BufferBindAttributeStride; - out.first = head.first.get(); - out.count = head.count.get(); - for e in entries { - out.buffers.push(BufferBinding { - ref_: e.buffer_ref.get(), - offset: e.offset.get(), - attribute_stride: e.attribute_stride.get(), - has_attribute_stride: true, - }); - } - Ok(out) - } - wire::OPCODE_SET_SAMPLER | wire::OPCODE_SET_TEXTURE => { - let (head, entries) = wire::ref_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - if !var_len(command_length, BIND_BASE, head.count.get(), REF_SIZE) { - return Err(DecodeStatus::ErrShort); - } - let samplers = opcode == wire::OPCODE_SET_SAMPLER; - out.kind = if samplers { - Kind::SamplerBind - } else { - Kind::TextureBind - }; - out.first = head.first.get(); - out.count = head.count.get(); - for e in entries { - let ref_ = e.object_ref.get(); - if samplers { - out.samplers.push(SamplerBinding { - ref_, - ..Default::default() - }); - } else { - out.textures.push(RefBinding { ref_ }); - } - } - Ok(out) - } - wire::OPCODE_SET_SAMPLER_LOD => { - let (head, entries) = - wire::sampler_lod_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - if !var_len( - command_length, - BIND_BASE, - head.count.get(), - SAMPLER_LOD_ENTRY, - ) { - return Err(DecodeStatus::ErrShort); - } - out.kind = Kind::SamplerLod; - out.first = head.first.get(); - out.count = head.count.get(); - for e in entries { - out.samplers.push(SamplerBinding { - ref_: e.sampler_ref.get(), - lod_min_bits: e.lod_min_clamp.get().to_bits(), - lod_max_bits: e.lod_max_clamp.get().to_bits(), - has_lod_clamp: true, - }); - } - Ok(out) - } - wire::OPCODE_SET_BUFFER_OFFSET => { - if command_length != wire::SET_BUFFER_OFFSET_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let b = wire::set_buffer_offset(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::BufferOffset; - out.first = b.index.get(); - out.buffer_offset = b.offset.get(); - Ok(out) - } - wire::OPCODE_SET_BUFFER_OFFSET_STRIDE => { - if command_length != wire::SET_BUFFER_OFFSET_STRIDE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let b = wire::buffer_offset_stride(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::BufferOffsetAttributeStride; - out.first = b.index.get(); - out.buffer_offset = b.offset.get(); - out.attribute_stride = b.attribute_stride.get(); - Ok(out) - } - wire::OPCODE_DISPATCH_THREADGROUPS | wire::OPCODE_DISPATCH_THREADS => { - if command_length != wire::DISPATCH_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let d = wire::dispatch(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = if opcode == wire::OPCODE_DISPATCH_THREADGROUPS { - Kind::DispatchThreadgroups - } else { - Kind::DispatchThreads - }; - out.grid = Size3 { - x: d.groups_width.get(), - y: d.groups_height.get(), - z: d.groups_depth.get(), - }; - out.threads_per_threadgroup = Size3 { - x: d.threads_width.get(), - y: d.threads_height.get(), - z: d.threads_depth.get(), - }; - Ok(out) - } - wire::OPCODE_DISPATCH_THREADGROUPS_INDIRECT => { - if command_length != wire::DISPATCH_THREADGROUPS_INDIRECT_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let d = wire::dispatch_indirect(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::DispatchThreadgroupsIndirect; - out.threads_per_threadgroup = Size3 { - x: d.threads_width.get(), - y: d.threads_height.get(), - z: d.threads_depth.get(), - }; - out.indirect_buffer_offset = d.indirect_buffer_offset.get(); - out.indirect_buffer_ref = d.indirect_buffer_ref.get(); - Ok(out) - } - wire::OPCODE_DISPATCH_THREADS_INDIRECT => { - if command_length != wire::DISPATCH_THREADS_INDIRECT_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let d = wire::dispatch_threads_indirect(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::DispatchThreadsIndirect; - out.indirect_buffer_offset = d.indirect_buffer_offset.get(); - out.indirect_buffer_ref = d.indirect_buffer_ref.get(); - Ok(out) - } - wire::OPCODE_SET_STAGE_IN_REGION => { - if command_length != wire::SET_STAGE_IN_REGION_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let r = wire::set_stage_in_region(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::StageInRegion; - out.stage_in_region.size = Size3 { - x: r.size_width.get(), - y: r.size_height.get(), - z: r.size_depth.get(), - }; - out.stage_in_region.origin = Size3 { - x: r.origin_x.get(), - y: r.origin_y.get(), - z: r.origin_z.get(), - }; - Ok(out) - } - wire::OPCODE_SET_STAGE_IN_REGION_INDIRECT => { - if command_length != wire::SET_STAGE_IN_REGION_INDIRECT_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let r = wire::set_stage_in_region_indirect(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::StageInRegionIndirect; - out.stage_in_indirect_buffer_ref = r.indirect_buffer_ref.get(); - out.stage_in_indirect_buffer_offset = r.indirect_buffer_offset.get(); - Ok(out) - } - wire::OPCODE_SET_THREADGROUP_MEMORY_LENGTH => { - if command_length != wire::SET_THREADGROUP_MEMORY_LENGTH_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let t = wire::set_threadgroup_memory_length(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::ThreadgroupMemory; - out.threadgroup_memory_length = t.length.get(); - out.threadgroup_memory_index = t.index.get(); - Ok(out) - } - wire::OPCODE_UPDATE_FENCE | wire::OPCODE_WAIT_FOR_FENCE => { - if command_length != wire::FENCE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let r = wire::fence(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = if opcode == wire::OPCODE_UPDATE_FENCE { - Kind::UpdateFence - } else { - Kind::WaitFence - }; - out.fence_ref = r.object_ref.get(); - Ok(out) - } - wire::OPCODE_MEMORY_BARRIER_RESOURCES => { - let (head, refs) = - wire::memory_barrier_resources(&op).map_err(|_| DecodeStatus::ErrShort)?; - if !var_len(command_length, COUNT_BASE, head.count.get(), REF_SIZE) { - return Err(DecodeStatus::ErrShort); - } - out.kind = Kind::BarrierResources; - out.count = head.count.get(); - for r in refs { - out.resources.push(RefBinding { - ref_: r.object_ref.get(), - }); - } - Ok(out) - } - wire::OPCODE_MEMORY_BARRIER_SCOPE => { - if command_length != wire::MEMORY_BARRIER_SCOPE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let s = wire::memory_barrier_scope(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::BarrierScope; - out.barrier_scope = s.scope.get(); - Ok(out) - } - wire::OPCODE_SET_IMAGEBLOCK_SIZE => { - if command_length != wire::SET_IMAGEBLOCK_SIZE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let s = wire::set_imageblock_size(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::ImageblockDimensions; - out.imageblock_width = s.width.get(); - out.imageblock_height = s.height.get(); - Ok(out) - } - wire::OPCODE_WRITE_DESCRIPTOR => { - if command_length != wire::WRITE_DESCRIPTOR_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let d = wire::write_descriptor(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::DispatchType; - out.dispatch_type = d.dispatch_type.get(); - Ok(out) - } - wire::OPCODE_START_WHILE | wire::OPCODE_START_IF | wire::OPCODE_END_DO_WHILE => { - if command_length != wire::CONTROL_FLOW_PREDICATE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let p = wire::control_flow_predicate(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = match opcode { - wire::OPCODE_START_WHILE => Kind::ControlStartWhile, - wire::OPCODE_START_IF => Kind::ControlStartIf, - _ => Kind::ControlEndDoWhile, - }; - out.condition_buffer_ref = p.buffer_ref.get(); - out.condition_buffer_offset = p.offset.get(); - out.condition_comparison = p.comparison.get(); - out.condition_reference_value = p.reference_value.get(); - Ok(out) - } - wire::OPCODE_START_DO_WHILE - | wire::OPCODE_END_WHILE - | wire::OPCODE_START_ELSE - | wire::OPCODE_END_IF - | wire::OPCODE_INSERT_COMPRESSED_TEXTURE_FLUSH => { - if command_length != EMPTY_LEN { - return Err(DecodeStatus::ErrShort); - } - out.kind = match opcode { - wire::OPCODE_START_DO_WHILE => Kind::ControlStartDoWhile, - wire::OPCODE_END_WHILE => Kind::ControlEndWhile, - wire::OPCODE_START_ELSE => Kind::ControlStartElse, - wire::OPCODE_END_IF => Kind::ControlEndIf, - _ => Kind::CompressedTextureFlush, - }; - Ok(out) - } - wire::OPCODE_EXECUTE_COMMANDS_RANGE => { - if command_length != wire::EXECUTE_COMMANDS_RANGE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let e = wire::execute_commands_range(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::ExecuteCommandsInBuffer; - out.indirect_command_buffer_ref = e.icb_ref.get(); - out.indirect_command_range_location = e.range_location.get(); - out.indirect_command_range_length = e.range_length.get(); - Ok(out) - } - wire::OPCODE_EXECUTE_COMMANDS_INDIRECT => { - if command_length != wire::EXECUTE_COMMANDS_INDIRECT_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrShort); - } - let e = wire::execute_commands_indirect(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::ExecuteCommandsInBufferIndirect; - out.indirect_command_buffer_ref = e.icb_ref.get(); - out.indirect_command_arguments_buffer_ref = e.indirect_buffer_ref.get(); - out.indirect_command_arguments_buffer_offset = e.indirect_buffer_offset.get(); - Ok(out) - } - _ => Err(DecodeStatus::ErrUnknownOpcode), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::protocol::endian::st32; - - /// Header plus two `Size3`, and taken from the crate that pins it. - const DISPATCH_DIRECT_LEN: usize = wire::DISPATCH_TOTAL_LEN as usize; - /// Header plus two `Size3` — the region's size and its origin. - const BARRIER_SCOPE_LEN: usize = wire::MEMORY_BARRIER_SCOPE_TOTAL_LEN as usize; - /// The condition record's length, from the crate that derived it. - /// - /// Was `0x1c` written here. It is the same number, and that is the point: - /// the two agreed by luck for as long as nobody could check, because - /// `-setSupportsCommandBufferJump:` defaults off and the capture recorded - /// all seven control-flow selectors as emitting nothing at all. - const CONDITION_LEN: usize = wire::CONTROL_FLOW_PREDICATE_TOTAL_LEN as usize; - const EXECUTE_LEN: usize = wire::EXECUTE_COMMANDS_RANGE_TOTAL_LEN as usize; - const PIPELINE_LEN: usize = wire::SET_PIPELINE_STATE_TOTAL_LEN as usize; - - /// A malformed compute command used to be dropped at the dispatch site with no - /// log line at all — indistinguishable from a segment carrying no compute - /// work. Each check names itself now, `Ok` still produces nothing, and the - /// prefix keeps them apart from the six sibling `DecodeStatus` enums. - #[test] - fn every_compute_decode_failure_names_its_own_check() { - use crate::observe::Refusal; - const ERRS: &[DecodeStatus] = &[ - DecodeStatus::ErrShort, - DecodeStatus::ErrUnknownOpcode, - DecodeStatus::ErrUnsupportedOpcode, - ]; - let mut slugs: Vec<&str> = ERRS.iter().filter_map(|s| s.refusal()).collect(); - assert_eq!(slugs.len(), ERRS.len(), "every error variant refuses"); - assert!(slugs.iter().all(|s| s.starts_with("compute_decode_"))); - slugs.sort_unstable(); - let n = slugs.len(); - slugs.dedup(); - assert_eq!(slugs.len(), n, "two compute decode checks share a slug"); - } - fn hdr(op: u32, len: usize) -> Vec { - let mut v = vec![0u8; len]; - st32(&mut v[0..4], op); - st32(&mut v[4..8], len as u32); - v - } - - /// A bind record above the old `MAX_BIND_ENTRIES = 128` cap decodes, and - /// every entry of it survives. - /// - /// This is the compute half of the bug `runtime::decode::render` fixed by - /// deleting its own cap: a well-formed record was refused whole, so a guest - /// binding 200 textures lost all 200 rather than the 72 that would not have - /// fit. Metal's own per-stage texture limit is 128, but that is the - /// *backend's* bound to enforce and it is enforced there — a decoder that - /// pre-empts it turns a bind the backend would have clamped into a decode - /// failure with a shape slug, which the divergence instrument reads as this - /// project having the layout wrong. - /// - /// 200 rather than 129 so the assertion cannot pass by an off-by-one in a - /// bound that is supposed to be gone entirely. - #[test] - fn a_bind_larger_than_the_deleted_cap_decodes_every_entry() { - const COUNT: u32 = 200; - let len = BIND_BASE + COUNT as usize * REF_SIZE; - let mut v = hdr(wire::OPCODE_SET_TEXTURE, len); - st32(&mut v[8..], 0); // first - st32(&mut v[12..], COUNT); - for i in 0..COUNT as usize { - st32(&mut v[BIND_BASE + i * REF_SIZE..], 1000 + i as u32); - } - let c = decode(&v).expect("a record the guest sized correctly must decode"); - assert_eq!(c.kind, Kind::TextureBind); - assert_eq!(c.count, COUNT); - assert_eq!(c.textures.len(), COUNT as usize); - assert_eq!(c.textures[0].ref_, 1000); - assert_eq!(c.textures[COUNT as usize - 1].ref_, 1000 + COUNT - 1); - - // The record's own length is still the bound, and it is exact: one - // entry's worth of slack either way is `ErrShort`, not a silent - // truncation. Deleting the cap must not have loosened this. - let mut short = v.clone(); - st32(&mut short[12..], COUNT + 1); - assert_eq!(decode(&short).unwrap_err(), DecodeStatus::ErrShort); - st32(&mut short[12..], COUNT - 1); - assert_eq!(decode(&short).unwrap_err(), DecodeStatus::ErrShort); - // A count whose entries would overflow the length arithmetic is refused - // by the same check rather than by a cap. - st32(&mut short[12..], u32::MAX); - assert_eq!(decode(&short).unwrap_err(), DecodeStatus::ErrShort); - } - - #[test] - fn pipeline_and_dispatch() { - let mut v = hdr(wire::OPCODE_SET_PIPELINE_STATE, PIPELINE_LEN); - st32(&mut v[8..], 42); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::Pipeline); - assert_eq!(c.pipeline_ref, 42); - - let v = hdr(wire::OPCODE_DISPATCH_THREADGROUPS, DISPATCH_DIRECT_LEN); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::DispatchThreadgroups); - } - - #[test] - fn rejected_and_matrix() { - assert!(opcode_supported(wire::OPCODE_SET_PIPELINE_STATE)); - assert!(opcode_apple_rejected(REJECTED_85)); - assert_eq!( - decode(&hdr(REJECTED_85, 16)).unwrap_err(), - DecodeStatus::ErrUnsupportedOpcode - ); - assert_eq!( - decode(&hdr(0x999, 16)).unwrap_err(), - DecodeStatus::ErrUnknownOpcode - ); - } - - #[test] - fn set_buffers() { - let count = 2u32; - let len = BIND_BASE + (count as usize) * BUF_ENTRY; - let mut v = hdr(wire::OPCODE_SET_BUFFER, len); - st32(&mut v[8..], 1); // first - st32(&mut v[12..], count); - st32(&mut v[16..], 10); - st32(&mut v[28..], 11); - let c = decode(&v).unwrap(); - assert_eq!(c.count, 2); - assert_eq!(c.buffers[0].ref_, 10); - assert_eq!(c.buffers[1].ref_, 11); - } - - #[test] - fn property_fuzz_opcodes() { - for op in 0x80u32..0xf0 { - for len in [8, 12, 16, 20, 28, 0x14, 0x1c, 0x38, 0x40] { - let _ = decode(&hdr(op, len)); - } - } - } - - #[test] - fn control_do_while_start_empty_end_condition() { - // Wire contract: start-do-while is empty; end-do-while carries condition. - let v = hdr(wire::OPCODE_START_DO_WHILE, EMPTY_LEN); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::ControlStartDoWhile); - - let mut v = hdr(wire::OPCODE_END_DO_WHILE, CONDITION_LEN); - st32(&mut v[8..], 1201); // buffer ref - // offset u64 @ +4 payload = absolute +12 - v[12..20].copy_from_slice(&0x640u64.to_le_bytes()); - st32(&mut v[20..], 2); // comparison Equal - st32(&mut v[24..], 0x1234_5678); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::ControlEndDoWhile); - assert_eq!(c.condition_buffer_ref, 1201); - assert_eq!(c.condition_buffer_offset, 0x640); - assert_eq!(c.condition_comparison, 2); - assert_eq!(c.condition_reference_value, 0x1234_5678); - - // Swapped lengths must fail closed. - assert!(decode(&hdr(wire::OPCODE_START_DO_WHILE, CONDITION_LEN)).is_err()); - assert!(decode(&hdr(wire::OPCODE_END_DO_WHILE, EMPTY_LEN)).is_err()); - } - - /// The control-flow layout this device uses is Apple's, field for field. - /// - /// It arrived here as a port with no derivation recorded, and - /// `compute_ctrl_seen` has never fired on a driven boot — so nothing said - /// whether it was right, and the wire capture could not say either while - /// `-setSupportsCommandBufferJump:` was at its default and all seven - /// selectors looked like records Apple never writes. Driving them showed - /// this arm had every offset and every width correct. - /// - /// This asserts the offsets against `offset_of!` on the derived struct - /// rather than against the numbers that were here, so the check is against - /// Apple's layout rather than against this module's memory of it. The - /// interesting one is `comparison`: it is `Q` on all three selectors and - /// four bytes on the wire, and widening it to match the API would push - /// `reference_value` off the end. - #[test] - fn the_control_flow_condition_is_apples_own_layout() { - use core::mem::offset_of; - - assert_eq!( - CONDITION_LEN, - OP_HEADER_LEN + core::mem::size_of::(), - "the condition record is its header plus the derived body" - ); - assert_eq!(offset_of!(wire::ControlFlowPredicate, buffer_ref), 0); - assert_eq!(offset_of!(wire::ControlFlowPredicate, offset), 4); - assert_eq!(offset_of!(wire::ControlFlowPredicate, comparison), 12); - assert_eq!(offset_of!(wire::ControlFlowPredicate, reference_value), 16); - - // All three condition-bearing opcodes read the same body. Driven per - // opcode rather than generalized from one, because the three are - // separate arms and only the `Kind` is supposed to differ. - for (op, kind) in [ - (wire::OPCODE_START_IF, Kind::ControlStartIf), - (wire::OPCODE_START_WHILE, Kind::ControlStartWhile), - (wire::OPCODE_END_DO_WHILE, Kind::ControlEndDoWhile), - ] { - let mut v = hdr(op, CONDITION_LEN); - st32(&mut v[OP_HEADER_LEN..], 5151); - v[OP_HEADER_LEN + 4..OP_HEADER_LEN + 12].copy_from_slice(&0x1111u64.to_le_bytes()); - st32(&mut v[OP_HEADER_LEN + 12..], 0x22); - st32(&mut v[OP_HEADER_LEN + 16..], 0x89ab_cdef); - let c = decode(&v).unwrap_or_else(|e| panic!("op {op:#x}: {e:?}")); - assert_eq!(c.kind, kind); - assert_eq!(c.condition_buffer_ref, 5151); - assert_eq!(c.condition_buffer_offset, 0x1111); - // Outside `MTLCompareFunction`'s 0–7 on purpose: the serializer - // carries the guest's ordinal verbatim rather than validating or - // remapping it, so a reader must treat an out-of-range value as - // guest data rather than as impossible. - assert_eq!(c.condition_comparison, 0x22); - assert_eq!(c.condition_reference_value, 0x89ab_cdef); - } - } - - #[test] - fn control_if_while_and_icb_lengths() { - let mut v = hdr(wire::OPCODE_START_IF, CONDITION_LEN); - st32(&mut v[8..], 7); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::ControlStartIf); - assert_eq!(c.condition_buffer_ref, 7); - - assert_eq!( - decode(&hdr(wire::OPCODE_START_ELSE, EMPTY_LEN)) - .unwrap() - .kind, - Kind::ControlStartElse - ); - assert_eq!( - decode(&hdr(wire::OPCODE_END_IF, EMPTY_LEN)).unwrap().kind, - Kind::ControlEndIf - ); - - let mut v = hdr(wire::OPCODE_EXECUTE_COMMANDS_RANGE, EXECUTE_LEN); - st32(&mut v[8..], 1301); - v[12..20].copy_from_slice(&3u64.to_le_bytes()); - v[20..28].copy_from_slice(&7u64.to_le_bytes()); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::ExecuteCommandsInBuffer); - assert_eq!(c.indirect_command_buffer_ref, 1301); - assert_eq!(c.indirect_command_range_location, 3); - assert_eq!(c.indirect_command_range_length, 7); - } - - /// A compute resource barrier is the length the serializer writes. - /// - /// It is `12 + 4 * count`: eight bytes of header, the count, then the refs. - /// This arm demanded `16 + 4 * count`, four bytes further on, so every - /// barrier a guest issued was refused with `ErrShort` and every resource it - /// named was lost — and the four bytes it skipped were the first ref, so a - /// record long enough to pass would have read the list shifted by one. - /// - /// The lengths come from `reims_vgpu_wire::ops::compute`, which pins them - /// against bytes Apple's serializer produced. Both directions are asserted: - /// the length Apple writes is accepted, and the one this arm used to demand - /// is refused. - #[test] - fn a_resource_barrier_is_the_length_the_serializer_writes() { - use crate::protocol::endian::st32; - - const COUNT: u32 = 2; - let apple_len = COUNT_BASE + (COUNT as usize) * REF_SIZE; - assert_eq!(apple_len, 20, "the serializer's own record is 20 bytes"); - - let mut v = vec![0u8; apple_len]; - st32(&mut v[0..], wire::OPCODE_MEMORY_BARRIER_RESOURCES); - st32(&mut v[4..], apple_len as u32); - st32(&mut v[OP_HEADER_LEN..], COUNT); - st32(&mut v[OP_HEADER_LEN + 4..], 5151); - st32(&mut v[OP_HEADER_LEN + 8..], 4343); - - let c = decode(&v).expect("the serializer's own record must decode"); - assert_eq!(c.kind, Kind::BarrierResources); - assert_eq!(c.count, COUNT); - let refs: Vec = c.resources.iter().map(|r| r.ref_).collect(); - assert_eq!( - refs, - vec![5151, 4343], - "the refs start at the count, not four bytes past it" - ); - - // The length this arm used to require. Nothing writes it, so it must - // not be the one that decodes. - let old_len = BIND_BASE + (COUNT as usize) * REF_SIZE; - let mut v = vec![0u8; old_len]; - st32(&mut v[0..], wire::OPCODE_MEMORY_BARRIER_RESOURCES); - st32(&mut v[4..], old_len as u32); - st32(&mut v[OP_HEADER_LEN..], COUNT); - assert_eq!(decode(&v).unwrap_err(), DecodeStatus::ErrShort); - } - - /// The scope barrier lifts only the bytes the serializer wrote. - /// - /// `compute_memory_barrier_scope` is `04 00 AA AA` against the oracle's - /// poison: two bytes written, two never touched. On a guest's wire those - /// two hold whatever the ring last contained, so a field reading them - /// reports noise. Poison here stands in for that ring content — if a future - /// change grew a field into those bytes, this decodes `0xAAAA` into it. - #[test] - fn the_scope_barrier_reads_no_byte_the_serializer_left_alone() { - use crate::protocol::endian::st32; - - let mut v = vec![0xAAu8; BARRIER_SCOPE_LEN]; - st32(&mut v[0..], wire::OPCODE_MEMORY_BARRIER_SCOPE); - st32(&mut v[4..], BARRIER_SCOPE_LEN as u32); - v[OP_HEADER_LEN] = 4; - v[OP_HEADER_LEN + 1] = 0; - - let c = decode(&v).expect("the serializer's own record must decode"); - assert_eq!(c.kind, Kind::BarrierScope); - assert_eq!(c.barrier_scope, 4); - // Everything else the record could carry stays at its default, so no - // field picked up the two unwritten bytes. - assert_eq!(c.count, 0); - assert_eq!(c.resource_usage, Default::default()); - assert_eq!(c.fence_ref, 0); - } - - /// The compute encoder does not *declare* residency — it inherits it. - /// - /// This asserts exactly one thing: no residency selector appears among the - /// compute encoder's own methods. That is all the manifest can say, because - /// it is built from each class's own method list and has no row for the - /// encoder base class where residency is declared. - /// - /// It used to be read as the stronger claim that these two opcodes have no - /// producer at all, and [`OP_USE_HEAPS`] records why that does not follow. - /// The assertion is unchanged and still worth keeping: if a future build - /// *overrides* residency on this class, the override may carry a different - /// record shape from the inherited one, and this fires before the arm below - /// decodes the new shape with the old layout. - #[test] - fn the_compute_encoder_declares_no_residency_selector() { - let residency: Vec<&str> = reims_vgpu_wire::manifest::MANIFEST - .iter() - .filter(|e| e.class == "PGSerializerComputeCommandEncoder") - .map(|e| e.selector) - .filter(|s| s.starts_with("useHeap") || s.starts_with("useResource")) - .collect(); - assert!( - residency.is_empty(), - "the compute encoder now declares {residency:?} of its own; an \ - override may not share the inherited record shape, so the \ - OP_USE_HEAPS/OP_USE_RESOURCES layouts need a fresh capture" - ); - // The render encoder does ship them, and its opcodes are not these. - use reims_vgpu_wire::ops::render as wire; - assert_ne!(OP_USE_HEAPS, wire::OPCODE_USE_HEAP); - assert_ne!(OP_USE_RESOURCES, wire::OPCODE_USE_RESOURCE); - } - - /// Every compute opcode Apple's serializer emits has a constant here, and - /// the two this module names beyond them are named as exceptions. - /// - /// The render sibling of this test can assert plain set equality; this one - /// cannot, and the difference is the point. `0x86`/`0x87` are declared on - /// the encoder base class rather than on this one, which is what - /// `the_compute_encoder_declares_no_residency_selector` states and all it - /// states — the manifest is built per class from each class's own methods - /// and has no row for the base, so an inherited selector cannot appear in - /// the set this test compares against. See [`OP_USE_HEAPS`]. - /// - /// # This list used to hold four, and the other two were a wrong claim - /// - /// `0xe3`/`0xe6` sat here as "a selector Apple's serializer **refuses**, - /// failing an assertion instead of emitting". That was measured, and it was - /// measured in one capability state. Both selectors are gated — - /// `insertCompressedTextureReinterpretationFlush` on - /// `-setSupportsInsertCompressedTextureReinterpretationFlush:`, - /// `dispatchThreadsWithIndirectBuffer:indirectBufferOffset:` on - /// `-setSupportsDispatchThreadsIndirect:` — and with the flag forced on the - /// serializer emits both. They are ordinary derived opcodes now, and the - /// layouts this module already read for them turned out to be right. - /// - /// The lesson is about the *shape* of the old claim rather than its - /// content: an assertion is a refusal by this harness's inputs, not by - /// Apple, and neither is a claim any single capability state can support. - /// - /// Keeping the remaining exception explicit is what stops a third from being - /// added silently. - /// - /// The gap direction is the one that costs guest work. An opcode Apple - /// emits and this module does not name reaches no arm, and a compute record - /// that reaches no arm is a dispatch or a bind that never happened. - #[test] - fn the_compute_opcode_table_is_apples_compute_manifest_plus_four_named_exceptions() { - let derived: &[(u32, &str)] = &[ - ( - wire::OPCODE_DISPATCH_THREADGROUPS, - "wire::OPCODE_DISPATCH_THREADGROUPS", - ), - ( - wire::OPCODE_DISPATCH_THREADGROUPS_INDIRECT, - "wire::OPCODE_DISPATCH_THREADGROUPS_INDIRECT", - ), - ( - wire::OPCODE_DISPATCH_THREADS, - "wire::OPCODE_DISPATCH_THREADS", - ), - (wire::OPCODE_SET_BUFFER, "wire::OPCODE_SET_BUFFER"), - (wire::OPCODE_SET_SAMPLER, "wire::OPCODE_SET_SAMPLER"), - (wire::OPCODE_SET_SAMPLER_LOD, "wire::OPCODE_SET_SAMPLER_LOD"), - (wire::OPCODE_SET_TEXTURE, "wire::OPCODE_SET_TEXTURE"), - ( - wire::OPCODE_SET_BUFFER_OFFSET, - "wire::OPCODE_SET_BUFFER_OFFSET", - ), - ( - wire::OPCODE_SET_PIPELINE_STATE, - "wire::OPCODE_SET_PIPELINE_STATE", - ), - ( - wire::OPCODE_SET_STAGE_IN_REGION, - "wire::OPCODE_SET_STAGE_IN_REGION", - ), - ( - wire::OPCODE_SET_STAGE_IN_REGION_INDIRECT, - "wire::OPCODE_SET_STAGE_IN_REGION_INDIRECT", - ), - ( - wire::OPCODE_SET_THREADGROUP_MEMORY_LENGTH, - "wire::OPCODE_SET_THREADGROUP_MEMORY_LENGTH", - ), - (wire::OPCODE_UPDATE_FENCE, "wire::OPCODE_UPDATE_FENCE"), - (wire::OPCODE_WAIT_FOR_FENCE, "wire::OPCODE_WAIT_FOR_FENCE"), - ( - wire::OPCODE_MEMORY_BARRIER_RESOURCES, - "wire::OPCODE_MEMORY_BARRIER_RESOURCES", - ), - ( - wire::OPCODE_MEMORY_BARRIER_SCOPE, - "wire::OPCODE_MEMORY_BARRIER_SCOPE", - ), - ( - wire::OPCODE_SET_IMAGEBLOCK_SIZE, - "wire::OPCODE_SET_IMAGEBLOCK_SIZE", - ), - ( - wire::OPCODE_SET_BUFFER_STRIDE, - "wire::OPCODE_SET_BUFFER_STRIDE", - ), - ( - wire::OPCODE_SET_BUFFER_OFFSET_STRIDE, - "wire::OPCODE_SET_BUFFER_OFFSET_STRIDE", - ), - ( - wire::OPCODE_WRITE_DESCRIPTOR, - "wire::OPCODE_WRITE_DESCRIPTOR", - ), - (wire::OPCODE_START_DO_WHILE, "wire::OPCODE_START_DO_WHILE"), - (wire::OPCODE_END_DO_WHILE, "wire::OPCODE_END_DO_WHILE"), - (wire::OPCODE_START_WHILE, "wire::OPCODE_START_WHILE"), - (wire::OPCODE_END_WHILE, "wire::OPCODE_END_WHILE"), - (wire::OPCODE_START_IF, "wire::OPCODE_START_IF"), - (wire::OPCODE_START_ELSE, "wire::OPCODE_START_ELSE"), - (wire::OPCODE_END_IF, "wire::OPCODE_END_IF"), - ( - wire::OPCODE_EXECUTE_COMMANDS_RANGE, - "wire::OPCODE_EXECUTE_COMMANDS_RANGE", - ), - ( - wire::OPCODE_EXECUTE_COMMANDS_INDIRECT, - "wire::OPCODE_EXECUTE_COMMANDS_INDIRECT", - ), - ( - wire::OPCODE_INSERT_COMPRESSED_TEXTURE_FLUSH, - "wire::OPCODE_INSERT_COMPRESSED_TEXTURE_FLUSH", - ), - ( - wire::OPCODE_DISPATCH_THREADS_INDIRECT, - "wire::OPCODE_DISPATCH_THREADS_INDIRECT", - ), - ]; - - // Each exception names the selector that explains it, or `None` when - // the class ships no selector for it at all. - let unsupported: &[(u32, &str, Option<&str>)] = &[ - (OP_USE_HEAPS, "OP_USE_HEAPS", None), - (OP_USE_RESOURCES, "OP_USE_RESOURCES", None), - ]; - - let rows = || { - reims_vgpu_wire::manifest::MANIFEST - .iter() - .filter(|e| e.class == "PGSerializerComputeCommandEncoder") - }; - let mut apple: Vec = rows().flat_map(|e| e.opcodes.iter().copied()).collect(); - apple.sort_unstable(); - apple.dedup(); - - for (op, name) in derived { - assert!( - apple.contains(op), - "{name} = {op:#x} is not an opcode Apple's compute manifest \ - lists, so no capture supports it" - ); - } - for op in &apple { - assert!( - derived.iter().any(|(d, _)| d == op), - "Apple's serializer emits compute opcode {op:#x} and this module \ - names no constant for it, so every dispatch or bind carrying it \ - reaches no arm" - ); - } - for (op, name, selector) in unsupported { - assert!( - !apple.contains(op), - "{name} = {op:#x} now has a producer in Apple's manifest and must \ - move to the derived roster, taking its decoder arm with it" - ); - match selector { - // A refused selector is a measured outcome, so the row must - // still be there saying Apple declined to emit it. - Some(sel) => { - let row = rows().find(|e| e.selector == *sel).unwrap_or_else(|| { - panic!("{name}: the compute class no longer ships {sel}") - }); - assert!( - matches!( - row.coverage, - reims_vgpu_wire::manifest::Coverage::Excluded { .. } - ), - "{name}: {sel} is no longer excluded, so {op:#x} needs a \ - capture rather than an inherited number" - ); - } - // No selector at all is the weaker state, and the one the - // residency test above pins by name. - None => assert!( - !rows().any(|e| e.opcodes.contains(op)), - "{name}: a selector now claims {op:#x}" - ), - } - } - assert_eq!( - derived.len(), - apple.len(), - "the derived roster has a duplicate entry" - ); - } -} diff --git a/crates/reims-vgpu/src/dead/event_decoder.rs b/crates/reims-vgpu/src/dead/event_decoder.rs deleted file mode 100644 index e25d3c494..000000000 --- a/crates/reims-vgpu/src/dead/event_decoder.rs +++ /dev/null @@ -1,377 +0,0 @@ -// DISCONNECTED SOURCE — this file does not compile, is not feature-gated, and -// is not linkable. No `mod` declaration reaches `dead/`. It is here to be read. -// -// What this was: this device's own event/sync record decoder, `runtime::decode::event`. -// It framed the three event opcodes, carried the blit encoder's fence numbers in -// order to refuse them, derived two boundary probes from its own accepted -// window, and returned a `Command` with an `Unknown` kind a well-formed record -// could reach. -// -// Why it went: `reims_vgpu_protocol::decode::sync` lifts fence, event and -// barrier records for every rail at once, from inside the crate that owns the -// closure ledger — so the cross-encoder refusals and the accepted window stop -// being this crate's to keep true, and `EventKind` has the two kinds the wire -// has rather than three. `waitForEvent:value:timeoutMS:` is refused there, at -// the row that settled it, instead of here-then-again in the planner. -// -// The tests below moved with it and stopped running. See the row in README.md -// for what replaced each of them. -// -// Do not resurrect any of this. When a boot regresses on an event record, read -// it to learn what the old decoder did and fix `reims_vgpu_protocol::decode::sync` -// or the ledger row. - -//! Event/sync command decoder (port of `host/utils/reims-vgpu-event-decode`). - -use crate::protocol::endian::{ld32, ld64}; -use reims_vgpu_wire::ops::blit as wire_blit; - -pub const U32_SIZE: usize = 4; -pub const U64_SIZE: usize = 8; -/// The serializer op header's own two fields. This decoder frames records no -/// capture has driven — the event encoder is the one segment family -/// `reims-vgpu-wire` deliberately does not name — but the *header* around them -/// is the one every other record carries, so it comes from the same place. -pub const OPCODE_OFFSET: usize = core::mem::offset_of!(reims_vgpu_wire::OpHeader, opcode); -pub const LENGTH_OFFSET: usize = core::mem::offset_of!(reims_vgpu_wire::OpHeader, length); -/// Shared serializer op-header length from `reims-vgpu-wire`. -use reims_vgpu_wire::OP_HEADER_LEN; - -pub const VALUE_REF: usize = 0; -pub const VALUE_VALUE: usize = 4; -pub const TIMEOUT: usize = 12; -pub const SIGNAL_WAIT_PAYLOAD_LEN: usize = VALUE_VALUE + U64_SIZE; -pub const WAIT_TIMEOUT_PAYLOAD_LEN: usize = TIMEOUT + U32_SIZE; -pub const SIGNAL_WAIT_LEN: usize = OP_HEADER_LEN + SIGNAL_WAIT_PAYLOAD_LEN; -pub const WAIT_TIMEOUT_LEN: usize = OP_HEADER_LEN + WAIT_TIMEOUT_PAYLOAD_LEN; - -pub const OP_WAIT_EVENT: u32 = 0x190; -pub const OP_SIGNAL_EVENT: u32 = 0x191; -pub const OP_WAIT_EVENT_TIMEOUT: u32 = 0x192; - -/// Opcodes the event deserializer refuses, and why each is here. -/// -/// The first two are the **blit encoder's** fence records, and naming them is -/// this list's whole point: `0x13c`/`0x13d` are real opcodes in another space, -/// so an event decoder that accepted them would be reading a blit fence as an -/// event. They are taken from the crate that derived them rather than written -/// again — a number whose only job is to be another encoder's opcode should be -/// that opcode, or the two can part company and this list starts refusing -/// something Apple never writes while letting a renumbered fence through. -/// -/// The last two are the boundary probes, one below and one above the event -/// window `OP_WAIT_EVENT`..=`OP_WAIT_EVENT_TIMEOUT`. They are derived from the -/// window rather than transcribed beside it, so extending the window moves the -/// probes with it instead of leaving one of them *inside* the accepted range — -/// which would make this predicate refuse a command the decoder implements. -pub const REJECTED_BLIT_UPDATE_FENCE: u32 = wire_blit::OPCODE_UPDATE_FENCE; -pub const REJECTED_BLIT_WAIT_FENCE: u32 = wire_blit::OPCODE_WAIT_FOR_FENCE; -pub const REJECTED_BEFORE_WINDOW: u32 = OP_WAIT_EVENT - 1; -pub const REJECTED_AFTER_WINDOW: u32 = OP_WAIT_EVENT_TIMEOUT + 1; - -/// Why the event decoder refused a command. -/// -/// No `Ok` and no `ErrArgs`, for the reason recorded on `blit::DecodeStatus`: -/// success is the result's own `Ok`, and a bad argument here is a payload -/// shorter than the field, which `ErrShort` already names. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum DecodeStatus { - ErrShort, - ErrBadLength, - ErrUnknownOpcode, - ErrRejectedOpcode, -} - -impl crate::observe::Refusal for DecodeStatus { - /// Slugs carry a `event_decode_` prefix: seven modules under - /// `runtime/decode/` define a type called `DecodeStatus`, and five of them - /// have an `ErrShort` that means a different read. Without the prefix the - /// crate-wide uniqueness gate could not tell the event decoder's refusals - /// from any other's. - fn refusal(&self) -> Option<&'static str> { - Some(match self { - Self::ErrShort => "event_decode_short", - Self::ErrBadLength => "event_decode_bad_length", - Self::ErrUnknownOpcode => "event_decode_unknown_opcode", - Self::ErrRejectedOpcode => "event_decode_rejected_opcode", - }) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Kind { - Unknown = 0, - SignalEvent, - WaitEvent, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Command { - pub opcode: u32, - pub command_length: u32, - pub kind: Kind, - pub event_ref: u32, - pub value: u64, - pub has_timeout: bool, - pub timeout: u32, - pub raw_payload_offset: usize, - pub raw_payload_length: usize, -} - -pub fn opcode_rejected_by_deserializer(opcode: u32) -> bool { - matches!( - opcode, - REJECTED_BLIT_UPDATE_FENCE - | REJECTED_BLIT_WAIT_FENCE - | REJECTED_BEFORE_WINDOW - | REJECTED_AFTER_WINDOW - ) -} - -/// Decode one event command. Transactional: returns Ok only with a full snapshot. -pub fn decode(command: &[u8]) -> Result { - if command.len() < OP_HEADER_LEN { - return Err(DecodeStatus::ErrShort); - } - let opcode = ld32(&command[OPCODE_OFFSET..]); - let command_length = ld32(&command[LENGTH_OFFSET..]) as usize; - if command_length < OP_HEADER_LEN || command_length > command.len() { - return Err(DecodeStatus::ErrShort); - } - let payload = &command[OP_HEADER_LEN..command_length]; - let mut decoded = Command { - opcode, - command_length: command_length as u32, - kind: Kind::Unknown, - event_ref: 0, - value: 0, - has_timeout: false, - timeout: 0, - raw_payload_offset: OP_HEADER_LEN, - raw_payload_length: command_length - OP_HEADER_LEN, - }; - - match opcode { - OP_WAIT_EVENT => { - if command_length < SIGNAL_WAIT_LEN { - return Err(DecodeStatus::ErrBadLength); - } - decoded.kind = Kind::WaitEvent; - decoded.event_ref = ld32(&payload[VALUE_REF..]); - decoded.value = ld64(&payload[VALUE_VALUE..]); - Ok(decoded) - } - OP_SIGNAL_EVENT => { - if command_length < SIGNAL_WAIT_LEN { - return Err(DecodeStatus::ErrBadLength); - } - decoded.kind = Kind::SignalEvent; - decoded.event_ref = ld32(&payload[VALUE_REF..]); - decoded.value = ld64(&payload[VALUE_VALUE..]); - Ok(decoded) - } - OP_WAIT_EVENT_TIMEOUT => { - if command_length < WAIT_TIMEOUT_LEN { - return Err(DecodeStatus::ErrBadLength); - } - decoded.kind = Kind::WaitEvent; - decoded.event_ref = ld32(&payload[VALUE_REF..]); - decoded.value = ld64(&payload[VALUE_VALUE..]); - decoded.has_timeout = true; - decoded.timeout = ld32(&payload[TIMEOUT..]); - Ok(decoded) - } - _ => { - if opcode_rejected_by_deserializer(opcode) { - Err(DecodeStatus::ErrRejectedOpcode) - } else { - Err(DecodeStatus::ErrUnknownOpcode) - } - } - } -} - -#[cfg(test)] -mod tests { - - /// A malformed event command used to be dropped at the dispatch site with no - /// log line at all — indistinguishable from a segment carrying no event - /// work. Each check names itself now, `Ok` still produces nothing, and the - /// prefix keeps them apart from the six sibling `DecodeStatus` enums. - #[test] - fn every_event_decode_failure_names_its_own_check() { - use crate::observe::Refusal; - const ERRS: &[DecodeStatus] = &[ - DecodeStatus::ErrShort, - DecodeStatus::ErrBadLength, - DecodeStatus::ErrUnknownOpcode, - DecodeStatus::ErrRejectedOpcode, - ]; - let mut slugs: Vec<&str> = ERRS.iter().filter_map(|s| s.refusal()).collect(); - assert_eq!(slugs.len(), ERRS.len(), "every error variant refuses"); - assert!(slugs.iter().all(|s| s.starts_with("event_decode_"))); - slugs.sort_unstable(); - let n = slugs.len(); - slugs.dedup(); - assert_eq!(slugs.len(), n, "two event decode checks share a slug"); - } - use super::*; - use crate::protocol::endian::{st32, st64}; - - fn build(opcode: u32, payload: &[u8]) -> Vec { - let len = (OP_HEADER_LEN + payload.len()) as u32; - let mut v = vec![0u8; OP_HEADER_LEN + payload.len()]; - st32(&mut v[0..4], opcode); - st32(&mut v[4..8], len); - v[OP_HEADER_LEN..].copy_from_slice(payload); - v - } - - #[test] - fn signal_and_wait() { - let mut payload = [0u8; SIGNAL_WAIT_PAYLOAD_LEN]; - st32(&mut payload[0..4], 7); - st64(&mut payload[4..12], 0x100); - let cmd = decode(&build(OP_SIGNAL_EVENT, &payload)).unwrap(); - assert_eq!(cmd.kind, Kind::SignalEvent); - assert_eq!(cmd.event_ref, 7); - assert_eq!(cmd.value, 0x100); - - let cmd = decode(&build(OP_WAIT_EVENT, &payload)).unwrap(); - assert_eq!(cmd.kind, Kind::WaitEvent); - - let mut p2 = [0u8; WAIT_TIMEOUT_PAYLOAD_LEN]; - p2[..SIGNAL_WAIT_PAYLOAD_LEN].copy_from_slice(&payload); - st32(&mut p2[TIMEOUT..TIMEOUT + 4], 42); - let cmd = decode(&build(OP_WAIT_EVENT_TIMEOUT, &p2)).unwrap(); - assert!(cmd.has_timeout); - assert_eq!(cmd.timeout, 42); - } - - #[test] - fn rejected_and_unknown() { - assert_eq!( - decode(&build(REJECTED_BLIT_UPDATE_FENCE, &[])).unwrap_err(), - DecodeStatus::ErrRejectedOpcode - ); - assert_eq!( - decode(&build(0x999, &[])).unwrap_err(), - DecodeStatus::ErrUnknownOpcode - ); - } - - #[test] - fn short_header() { - assert_eq!(decode(&[0; 4]).unwrap_err(), DecodeStatus::ErrShort); - } - - /// No refused opcode is one this decoder implements. - /// - /// The two boundary probes are now `OP_WAIT_EVENT - 1` and - /// `OP_WAIT_EVENT_TIMEOUT + 1` rather than `0x18f`/`0x193` written beside - /// them, and this is the property that derivation buys: a window that grows - /// downward or upward carries its probes with it. Transcribed, one of them - /// would end up *inside* the accepted range and - /// [`opcode_rejected_by_deserializer`] would refuse a command the match - /// below decodes — a guest's event silently declined by a constant that was - /// only ever meant to sit outside. - /// - /// The blit pair is checked the same way and for the sharper reason: those - /// two are real opcodes in another encoder's space, so this list is only - /// correct while it names *that* space's fences and not this one's events. - #[test] - fn no_refused_opcode_is_one_this_decoder_implements() { - for (op, name) in [ - (OP_WAIT_EVENT, "OP_WAIT_EVENT"), - (OP_SIGNAL_EVENT, "OP_SIGNAL_EVENT"), - (OP_WAIT_EVENT_TIMEOUT, "OP_WAIT_EVENT_TIMEOUT"), - ] { - assert!( - !opcode_rejected_by_deserializer(op), - "{name} = {op:#x} is both implemented and refused" - ); - } - // And every refused opcode really is refused, so the list is not - // quietly empty of the case it exists for. - for (op, name) in [ - (REJECTED_BLIT_UPDATE_FENCE, "REJECTED_BLIT_UPDATE_FENCE"), - (REJECTED_BLIT_WAIT_FENCE, "REJECTED_BLIT_WAIT_FENCE"), - (REJECTED_BEFORE_WINDOW, "REJECTED_BEFORE_WINDOW"), - (REJECTED_AFTER_WINDOW, "REJECTED_AFTER_WINDOW"), - ] { - assert!(opcode_rejected_by_deserializer(op), "{name} is not refused"); - assert_eq!( - decode(&build(op, &[0u8; 32])).unwrap_err(), - DecodeStatus::ErrRejectedOpcode, - "{name} = {op:#x} must refuse by name rather than as an unknown" - ); - } - } - - #[test] - fn property_fuzz_opcodes() { - for op in 0u32..0x200 { - let mut v = build(op, &[0u8; 32]); - // Force length large enough - let len = v.len() as u32; - st32(&mut v[4..8], len); - let _ = decode(&v); - } - } -} - -// ---- The legacy tests that moved with it, from `runtime::fence_exec` ---- -// -// The bounded wait can no longer be constructed as an `EventRecord`, so this -// test's subject does not exist. Replaced by -// `runtime::exec::tests::a_bounded_event_wait_is_refused_by_contract_and_leaves_the_generation_alone`, -// which drives the bytes through the segment walk and asserts the refusal -// reaches the failure channel under the row's own name. - #[test] - fn event_wait_timeout_unsupported() { - let mut state = DeviceState::new(DeviceId(1), PAGE_SHIFT_ARM64E); - let wait = event_cmd(OP_WAIT_EVENT_TIMEOUT, 1, 1, Some(42)); - // Asserting the reason, not just the coarse status: this path shares - // `Unsupported` with six other checks. - assert_eq!( - execute_event(&mut state, 1, &wait), - FenceStatus::Unsupported("event_wait_timeout_unsupported") - ); - // Satisfied path even with timeout flag is still WaitSatisfied if value present. - assert_eq!( - execute_event(&mut state, 1, &event_cmd(OP_SIGNAL_EVENT, 1, 5, None)), - FenceStatus::Ok - ); - let wait_ok = event_cmd(OP_WAIT_EVENT_TIMEOUT, 1, 5, Some(42)); - assert_eq!(execute_event(&mut state, 1, &wait_ok), FenceStatus::Ok); - } - - -// ---- And from `runtime::decode::ledger` ---- -// -// Drove this crate's event decoder across the ledger's event rows. Replaced by -// `the_event_rail_lifts_its_records_and_refuses_its_one_settled_row`, which -// drives the protocol decoder on the rail this device names and additionally -// asserts that exactly one row is refused by contract rather than unjudged. -#[test] -fn the_event_decoder_recognises_every_event_operation_the_ledger_records() { - use super::event::{decode, DecodeStatus}; - for op in LEDGER - .iter() - .filter(|o| o.rail == Rail::Event) - .filter_map(|o| o.opcode) - { - let refused_the_opcode = probe_records(op).all(|r| { - matches!( - decode(&r), - Err(DecodeStatus::ErrUnknownOpcode) | Err(DecodeStatus::ErrRejectedOpcode) - ) - }); - assert!( - !refused_the_opcode, - "the closure ledger records event {op:#x} and this rail's decoder refuses the opcode \ - itself under every payload length" - ); - } -} - diff --git a/crates/reims-vgpu/src/dead/pending_stamp.rs b/crates/reims-vgpu/src/dead/pending_stamp.rs deleted file mode 100644 index f9c94fdb1..000000000 --- a/crates/reims-vgpu/src/dead/pending_stamp.rs +++ /dev/null @@ -1,345 +0,0 @@ -// DISCONNECTED — not a module, not compiled, not linkable. Source to read. -// -// Moved here by the commit that wired the ordering and publication group (G3). -// See `crates/reims-vgpu/src/dead/README.md` for the register row, and -// `AGENTS.md` for why nothing is resurrected from this directory. -// -// WHAT THIS WAS -// -// The drain's own stamp machinery: the per-drain coalescing latch, the verdict -// it produced, and the three `break`s that verdict drove. A packet whose stamp -// wait was unmet stopped its whole timeline at the ring's consumer pointer, and -// the latch existed because the word that would clear it was sitting unwritten -// in the same drain's stack frame. -// -// WHAT REPLACED IT -// -// `reims_vgpu_core::session::SessionModel::admit` takes a packet's stamp waits -// as an *ordering position*, and `runtime::drain::settle_model_work` releases -// the position when the slot reaches it. There is no latch because there is no -// window in which a completed packet's word is unpublished: completing a -// position publishes it. There is no verdict because nothing chooses — a -// position either has been released or has not. -// -// The one arm that survived the move is `Unevaluable`, and it moved rather than -// disappeared: `admit_and_park` drops a wait naming a slot outside the stamp -// page before admission and counts `packet_stamp_wait_unresolvable`. The -// asymmetry the variant's doc argues is the same one, stated where the packet -// is admitted instead of where a ring head is moved. - -/// The completion stamp one drain of one channel owes, coalesced. -/// -/// Every packet in a `drain_child_fifo` call stamps **the same slot** — the -/// index is read once from the channel's register block before the loop — and a -/// stamp wait is satisfied by any value at or past the one awaited -/// ([`StampWait::satisfied_by`]). So a run of stamps to one slot is observable -/// only through its greatest value unless the guest samples between the writes, -/// and writing only that value discharges every wait the run would have. -/// -/// That matters because a stamp is a FIFO completion, not merely a word write. -/// Coalescing avoids one completion record per packet while preserving the -/// greatest value the guest can observe from the drain. -/// -/// # What it bought, six driven macos-13 boots, one binary, both arms -/// -/// All six in one compositing regime (995-999 draws a frame), no panics, same -/// desktop. `gpu_stamps` fell to **1.9 %** of the per-packet arm and the span -/// with it: -/// -/// ```text -/// coalesced per packet -/// stamp ms/s 5.9-6.8 77.1-97.2 -/// unnamed in drain 224-231 314-317 -/// duty 0.80-0.81 0.89-0.90 -/// slot_us 29 049 37 874 -/// ``` -/// -/// **The arithmetic closes**: the stamp span fell 90.3 ms/s and the whole drain -/// residue fell 88.6 ms/s, so the time was removed rather than relocated — and -/// `proc - draw - compute` is 197 against 201 ms/s, unchanged, which says the -/// same from the other side. -/// -/// It buys **headroom, not frames**. `present_hz`/`offered_hz` are 15.05 against -/// 14.90; the guest paces this rail and four CPU wins in a row have moved it by -/// nothing. -/// -/// # It holds on all six guest drivers -/// -/// The measurement above is macos-13 alone, and *when a completion becomes -/// visible* is exactly the class that can be fine on one guest driver and stall -/// another — failing as a frozen desktop rather than as a decline, which no -/// counter reports. So all six x86 rails were swept: -/// -/// ```text -/// macos-11 dev=1 ssh=1 dock=1 sd=184 panic=0 -/// macos-12 dev=1 ssh=1 dock=1 sd=147 panic=0 -/// macos-13 dev=1 ssh=1 dock=1 sd=131 panic=0 -/// macos-14 dev=1 ssh=1 dock=1 sd=215 panic=0 -/// macos-15 dev=1 ssh=1 dock=1 sd=281 panic=0 -/// macos-26 dev=1 ssh=1 dock=1 sd=126 panic=0 -/// ``` -/// -/// `sd` is the field that answers the question — host-window standard deviation, -/// ~38 for the boot screen and >100 for a composited desktop. Every rail cleared -/// 126, so every one of them put a picture up rather than sitting on a stamp it -/// was still waiting for. `stamp_write_forward` runs 345-1815 a boot across the -/// six, so the coalesced write is landing everywhere and not only where it was -/// tuned. -/// -/// These are undriven boots: they prove the desktop composites on each driver, -/// not that the saving reproduces there. Only macos-13 has been driven. -/// -/// Completion publication does not close an open draw batch. It registers the -/// stamp in the bounded pending queue and the batch's eventual successful -/// submission assigns its completion point. The pending-stamp capacity remains -/// the pressure bound: filling it submits the batch rather than sleeping while -/// holding the only command buffer that can make room. -/// -/// [`Self::latch`] takes the **maximum in wrapping-signed order** rather than -/// the last value seen. For a well-formed guest those are the same, and taking -/// the maximum means this device cannot introduce a regressing stamp even if a -/// regressing one arrives — a slot going backwards would unsatisfy a wait the -/// guest had already been told was met. -#[derive(Clone, Copy, Default)] -pub struct PendingStamp { - /// `None` until a packet in this drain has completed. A drain that stamps - /// nothing owes nothing and must submit nothing. - value: Option, -} - -impl PendingStamp { - /// Fold one packet's completion stamp in, keeping the later of the two in - /// the same wrapping-signed order [`StampWait::satisfied_by`] compares in. - pub fn latch(&mut self, stamp: u32) { - self.value = Some(match self.value { - Some(held) if stamp.wrapping_sub(held) as i32 <= 0 => held, - _ => stamp, - }); - } - - /// The value owed, or `None` when this drain stamped nothing. - pub fn owed(self) -> Option { - self.value - } - - /// Whether `wait` is already discharged by what this drain has latched but - /// not yet written. - /// - /// Without this a packet waiting on the slot an earlier packet in the same - /// drain stamped would read the stale word out of guest RAM, return - /// [`StampVerdict::Hold`], and park the channel against a stamp this device - /// is itself holding. `slot` is the drain's own stamp index; a wait naming - /// any other slot is not ours to answer. - /// - /// # It fires zero times, and the hazard it guards is real - /// - /// The A/B above is the same six boots. `packet_stamp_wait_met_pending` is - /// **0** on the coalesced arm while `packet_stamp_wait_held` **more than - /// doubled**, 5 073 against 2 237, taking `setup_calls` up 47 % with it in - /// re-drains. Those two readings together say this comparison never matches: - /// the packets that should have been answered here fall through to the stale - /// word instead. - /// - /// It is not a correctness failure — every `break` flushes the pending - /// stamp, so a held packet's retry finds the word — but it is ~2 800 - /// avoidable round trips a boot behind a guard that reads as working. - /// - /// # Why, measured rather than guessed - /// - /// It is **not** an encoding mismatch, which was the first suspicion. The - /// boot's own `packet_stamp_wait_unmet` lines name both sides, and they - /// disagree about the *channel*, not the spelling: - /// - /// ```text - /// packet_stamp_wait_unmet opcode=0x37 ch1 index=2 awaited=0xe current=0xa - /// packet_stamp_wait_unmet opcode=0x6 ch5 index=1 awaited=0x5 current=0x3 - /// packet_stamp_wait_unmet opcode=0x22 ch2 index=4 awaited=0x1 current=0x0 - /// ``` - /// - /// Channel 1 waits on slot 2, channel 5 on slot 1, channel 2 on slot 4. - /// **Every one of them is waiting on a slot some other channel writes**, and - /// this guard answers only the drain's own slot — by construction, as its - /// last line above says. So it is not broken; it covers a case this workload - /// does not produce, while the case the workload does produce is the one it - /// declines. - /// - /// The mechanism is nesting: `process_child_packet` can reach `drain_other`, - /// so channel B's drain runs inside channel A's, and A's latched stamps are - /// sitting in A's stack frame where B cannot see them. Answering from them - /// would be correct for the same reason it is correct here — the drain - /// thread is single-threaded, so a latched stamp is work that finished - /// before the waiting packet was decoded — but it needs the latch to live in - /// `DeviceState` keyed by channel rather than in a local. - /// - /// **That is worth ~0.2 ms/s and no more**: 2 836 extra holds over a 45 s - /// boot, each costing a re-drain, against a change that bought 88 ms/s. It - /// is recorded because a guard that fires zero times should say why, not - /// because it is the next thing to fix. - fn discharges(self, slot: u32, wait: StampWait) -> bool { - stamp_slot_index(wait.index) == slot && self.value.is_some_and(|v| wait.satisfied_by(v)) - } -} - -/// What a packet's stamp waits say the drain should do with it. -/// -/// The three answers are not degrees of the same thing. [`Self::Ready`] and -/// [`Self::Hold`] are the wait working; [`Self::Unevaluable`] is the device -/// unable to decide, and collapsing it into `Hold` is how a report becomes a -/// hang — see the variant's own note. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum StampVerdict { - /// Every wait is satisfied, or there were none. Run the packet. - Ready, - /// At least one wait is genuinely behind. Hold the packet: a stamp this - /// device will publish is what clears it. - Hold, - /// A wait this device cannot decide, and **no future event changes that**. - /// - /// Holding on one would park the timeline forever, which is strictly worse - /// than the ordering slip it was meant to prevent: an ordering slip loses - /// one packet's ordering, a parked root FIFO loses the guest. So this runs - /// the packet, loudly. Every case here is a refusal with a named reason, and - /// none of them fired on a driven boot. - Unevaluable, -} - -impl StampVerdict { - /// Fold one wait's answer into the packet's, most restrictive winning. - /// - /// `Unevaluable` outranks `Hold`, which outranks `Ready`. That order is the - /// whole point: a packet with one wait genuinely behind and one that can - /// never be decided must **run**, because holding for the first would still - /// park the timeline forever on the second. - fn and(self, other: Self) -> Self { - match (self, other) { - (Self::Unevaluable, _) | (_, Self::Unevaluable) => Self::Unevaluable, - (Self::Hold, _) | (_, Self::Hold) => Self::Hold, - _ => Self::Ready, - } - } -} - -// --- the tests that moved with it --- - - // A packet carrying both an ordinary unmet wait and an undecidable one still - // runs: holding for the first would park the timeline forever on the second. - let mut both = vec![0u8; (PACKET_HEADER_LEN + 2 * PACKET_STAMP_LEN) as usize]; - st16(&mut both[PACKET_OPCODE..], 0); - st16(&mut both[PACKET_STAMP_COUNT..], 2); - st32( - &mut both[PACKET_TOTAL_SIZE..], - PACKET_HEADER_LEN + 2 * PACKET_STAMP_LEN, - ); - st32(&mut both[PACKET_HEADER_LEN as usize..], 6); - st32(&mut both[PACKET_HEADER_LEN as usize + 4..], 0x99); - st32( - &mut both[(PACKET_HEADER_LEN + PACKET_STAMP_LEN) as usize..], - bad_slot, - ); - st32( - &mut both[(PACKET_HEADER_LEN + PACKET_STAMP_LEN) as usize + 4..], - 1, - ); - let decoded = decode_packet(&both, 0, both.len() as u32, RING).expect("two records decode"); - assert_eq!( - note_packet_stamp_waits(&state, &host, None, &decoded, None), - StampVerdict::Unevaluable, - "Unevaluable outranks Hold, or the packet parks forever on the wait that \ - cannot clear while waiting for the one that could" - ); - - -/// The coalesced stamp keeps the **greatest** value a drain latched, in the same -/// wrapping-signed order a wait is compared in. -/// -/// Not "the last one seen". For a well-formed guest the two agree, and the whole -/// point of taking the maximum is that a regressing stamp arriving from the -/// guest cannot make this device publish a slot going backwards — which would -/// unsatisfy a wait the guest had already been told was met. -#[test] -fn a_coalesced_stamp_keeps_the_latest_value_across_the_u32_wrap() { - let mut pending = PendingStamp::default(); - assert_eq!( - pending.owed(), - None, - "a drain that stamped nothing owes nothing" - ); - - pending.latch(7); - pending.latch(9); - assert_eq!(pending.owed(), Some(9), "the later of two ascending stamps"); - - pending.latch(8); - assert_eq!( - pending.owed(), - Some(9), - "a stamp behind the one held must not pull the slot backwards" - ); - - // Across the wrap: 0xffff_fff0 then 4. The signed difference is +20, so 4 is - // *later*, and a plain `>=` would keep 0xffff_fff0 and stall every wait on - // the far side of the wrap. - let mut wrapped = PendingStamp::default(); - wrapped.latch(0xffff_fff0); - wrapped.latch(4); - assert_eq!( - wrapped.owed(), - Some(4), - "the wrap is a signed difference, not a magnitude comparison" - ); -} - -/// A wait on the slot the drain is holding is answered from the latch. -/// -/// Without this the packet reads the stale word out of guest RAM, returns -/// `Hold`, and parks the channel against a stamp this device is itself sitting -/// on — a deadlock introduced by the coalescing rather than by the guest. -#[test] -fn a_pending_stamp_discharges_a_wait_on_its_own_slot_and_no_other() { - const SLOT: u32 = 3; - let mut pending = PendingStamp::default(); - pending.latch(20); - - let met = StampWait { - index: SLOT, - value: 20, - }; - assert!( - pending.discharges(SLOT, met), - "a wait at exactly the latched value is discharged" - ); - assert!( - pending.discharges( - SLOT, - StampWait { - index: SLOT, - value: 12 - } - ), - "and so is one behind it" - ); - assert!( - !pending.discharges( - SLOT, - StampWait { - index: SLOT, - value: 21 - } - ), - "a wait past the latched value is not discharged by it" - ); - assert!( - !pending.discharges( - SLOT, - StampWait { - index: SLOT + 1, - value: 1 - } - ), - "a wait on another slot is not this drain's to answer" - ); - assert!( - !PendingStamp::default().discharges(SLOT, met), - "a drain that has latched nothing discharges nothing" - ); -} diff --git a/crates/reims-vgpu/src/dead/render_decoder.rs b/crates/reims-vgpu/src/dead/render_decoder.rs deleted file mode 100644 index d92993c6f..000000000 --- a/crates/reims-vgpu/src/dead/render_decoder.rs +++ /dev/null @@ -1,1509 +0,0 @@ -//! DISCONNECTED — this file is not a module. See `dead/README.md`. -//! -//! The render rail's own record decoder: the flat `Command` with a hundred-odd -//! fields, `Kind`'s thirty-four variants, `Stage`, `DecodeStatus`, the accepted -//! opcode window and the eighty-arm `decode` that read them. -//! -//! Replaced across W11a–W11e by `reims_vgpu_protocol::decode::render` for the -//! forty-five rows the closure ledger has settled and -//! `runtime::decode::render_spi` for the thirty-one it has not. What did *not* -//! move with it is the render-pass attachment model — `ColorAttachment`, -//! `DepthAttachment`, `StencilAttachment`, `ScissorRect`, the attachment -//! offsets, the three `*_from_wire` lifts and -//! `attachment_subresource_is_bindable` — which is live in -//! `runtime::render_pass`. That split is what this file's removal from the -//! module tree needed: the file held a decoder and a capability model, and only -//! the decoder had been replaced. -//! -//! # What to read this for -//! -//! The `Kind` variants and their opcode arms are the record-by-record reading -//! this device had before the ledger settled anything, including the four -//! Apple-rejected opcodes and the `OtherAccepted` catch-all. If a live boot -//! regresses on a render record, the arm that used to answer it is here — and -//! the fix lands in `protocol::decode::render` or `render_spi`, never here. -//! -//! # Two guest-visible readings changed on the way out, and they are recorded -//! -//! `wire_instance_count`'s `.max(1)` below is the clamp W11d removed: a -//! selector with no `instanceCount:` argument now draws one instance because -//! that is Metal's default for it, and a guest that wrote `instanceCount:0` -//! gets the zero it wrote. `PASS_MIN_PAYLOAD`'s tolerance is the one W11c -//! removed: a pass descriptor shorter than `RenderPassBody` is refused rather -//! than read at whichever offsets fit. - -/// Map a `reims-vgpu-wire` view onto a payload, translating its refusal. -/// -/// The draw layouts live in that crate, derived from Apple's own serializer and -/// pinned by fixtures, so this module reads them rather than restating them — -/// one declaration, and drift is impossible rather than merely detectable. What -/// stays here is everything the crate cannot know: which `Kind` a record is, -/// what the runtime's `Command` calls each field, and how a refusal is named. -#[inline] -fn wire_view(payload: &[u8]) -> Result<&T, DecodeStatus> { - reims_vgpu_wire::view::(payload).map_err(|_| DecodeStatus::ErrShort) -} - -/// Narrow a wide draw's 64-bit count to the 32 bits `Command` carries. -/// -/// The wide forms exist because the guest had a value above 16 bits, not above -/// 32: a vertex or index count of four billion is not a draw any GPU completes. -/// Truncating one would draw the wrong geometry in silence, so it is refused by -/// name instead. -#[inline] -fn narrow_count(value: u64) -> Result { - u32::try_from(value).map_err(|_| DecodeStatus::ErrCountOutOfRange) -} - -/// The instance count a selector that carries one on the wire asked for. -/// -/// Eight decode arms wrote `(…get() as u32).max(1)` and none of them said why. -/// The clamp only does anything when the guest serialized `instanceCount:0`, and -/// there it draws one instance against whatever the instance buffers happen to -/// hold — the selector's own argument, overruled. -/// -/// Three arms of this device disagree about that value and were never diffed -/// against each other. This one clamps it. `backend::metal::render` refuses it -/// by name as `metal_render_instance_count_zero` — a refusal this clamp makes -/// unreachable, so the two cannot both be describing the contract. And -/// `runtime::icb` decodes the same argument out of an ICB slot and hands it -/// straight to `drawPrimitives:…:instanceCount:` with no clamp at all, so the -/// device already ships a zero instance count to Metal on the path that happens -/// not to come through here. -/// -/// A zero is counted here and nowhere else, as `draw_instance_count_zero` — a -/// census rather than a failure, because a guest that culled every instance -/// would be expected control flow rather than lost work. -/// -/// **It reads zero.** Driven x86/Vulkan boot, Ventura desktop, Safari window -/// drag: never fired against `mrt_draw_single` in the thousands. So no guest -/// command on this workload reaches the clamp, and it is inert rather than -/// load-bearing — which is also why it has not been replaced. Both candidate -/// replacements (pass the zero through as the ICB path does, or refuse it as -/// `backend::metal::render` does) would be unobservable here, so the reading -/// cannot choose between them, and Metal's own validation rejects -/// `instanceCount:0` outright — which is the reason to doubt any guest emits it. -/// -/// A firing is the signal. It would mean a real selector carries zero, and the -/// arm that receives it decides the pixels: this one draws one instance, the -/// Metal backend refuses the draw, the ICB path draws nothing. -/// -/// Because this is the single site, the count it guarantees is what let the -/// four further `.max(1)`s downstream of it go: two in `runtime::exec`, one in -/// `runtime::draw` and one in `runtime::draw::vulkan`, each re-applying a rule -/// already applied here. The last of those outlived the sweep that claimed all -/// of them, which is the failure mode a restatement has: it changes nothing -/// until the rule it copies changes, and then it changes one arm. -#[inline] -fn wire_instance_count(value: u64) -> Result { - let count = narrow_count(value)?; - if count == 0 { - crate::runtime::drain::note_store_route("draw_instance_count_zero"); - return Ok(1); - } - Ok(count) -} - -/// Why the render decoder refused a command. -/// -/// No `Ok` and no `ErrArgs`, for the reason recorded on `blit::DecodeStatus`: -/// success is the result's own `Ok`, and a bad argument here is a payload -/// shorter than the field, which `ErrShort` already names. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum DecodeStatus { - ErrShort, - ErrUnknownOpcode, - ErrUnsupportedOpcode, - ErrBadLength, - /// A wide draw's 64-bit count does not fit the 32 bits `Command` carries. - /// See [`narrow_count`] for why that is refused rather than truncated. - ErrCountOutOfRange, -} - -impl crate::observe::Refusal for DecodeStatus { - /// Slugs carry a `render_decode_` prefix: seven modules under - /// `runtime/decode/` define a type called `DecodeStatus`, and five of them - /// have an `ErrShort` that means a different read. Without the prefix the - /// crate-wide uniqueness gate could not tell the render decoder's refusals - /// from any other's. - fn refusal(&self) -> Option<&'static str> { - Some(match self { - Self::ErrShort => "render_decode_short", - Self::ErrUnknownOpcode => "render_decode_unknown_opcode", - Self::ErrUnsupportedOpcode => "render_decode_unsupported_opcode", - Self::ErrBadLength => "render_decode_bad_length", - Self::ErrCountOutOfRange => "render_decode_count_out_of_range", - }) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum Kind { - #[default] - Unknown, - SetPipeline, - SetBuffer, - /// setVertexBufferOffset / setFragmentBufferOffset (0x7e / 0x6f). - SetBufferOffset, - SetTexture, - SetSampler, - Draw, - SetViewport, - SetScissor, - SetDepthStencil, - SetBlendColor, - SetCullMode, - SetFrontFacing, - SetDepthBias, - SetStencilReference, - Fence, - Barrier, - /// `setTriangleFillMode:` / `setDepthClipMode:`. The value is in - /// [`Command::mode`]; which state it sets is [`Command::opcode`], as on the - /// wire. - SetRasterState, - /// `setLineWidth:` / `setTessellationFactorScale:`, value in - /// [`Command::float_value`]. - SetFloatState, - /// `setColorStoreAction:atIndex:` and the depth and stencil forms. The - /// colour form carries an index; the other two have one attachment each and - /// carry none. - SetStoreAction, - UseResource, - UseHeap, - ExecuteCommands, - RenderPass, - /// `drawPrimitives:indirectBuffer:` and its indexed sibling. Which of the - /// two is [`Command::opcode`], as on the wire. The buffer holding the - /// counts is [`Command::indirect_buffer_ref`] at - /// [`Command::indirect_buffer_offset`]; the indexed form also fills - /// [`Command::index_type`], [`Command::index_buffer_ref`] and - /// [`Command::index_buffer_offset`]. - DrawIndirect, - /// `setVisibilityResultMode:offset:`. Mode in [`Command::mode`], offset in - /// [`Command::visibility_result_offset`]. - SetVisibilityResultMode, - /// `setVertexAmplificationMode:value:` fills [`Command::mode`] and - /// [`Command::amplification_value`]; `setVertexAmplificationCount:viewMappings:` - /// fills [`Command::count`]. Which of the two is [`Command::opcode`], as on - /// the wire. The view mappings are not lifted — see - /// [`wire::OPCODE_SET_VERTEX_AMPLIFICATION_MODE`]. - SetVertexAmplification, - /// A bind against the **tile** argument tables: `0x9d`/`0x9e` (buffer and - /// offset), `0x9f`/`0xa0` (sampler, plain and LOD-bearing), `0xa1` - /// (texture). Which of the five is [`Command::opcode`], as on the wire; - /// the slots are [`Command::first`] and [`Command::count`]. - /// - /// **Deliberately not `SetBuffer`/`SetTexture`/`SetSampler` with a third - /// [`Stage`].** The records are those records byte for byte, so folding - /// them in is the tempting shape — but every existing executor arm reads - /// `Stage` as vertex-or-fragment, and a tile texture routed through one - /// would bind into the *fragment* table. That is worse than dropping it: - /// the guest's fragment shader would sample a texture it never bound. A - /// kind nothing else matches cannot be mis-applied by an arm that has not - /// been taught about tiles. - TileBind, - /// A tile-shader dispatch: `0x9b`, or `0xa2`/`0xa3` bounded to a region. - /// Threads per tile in [`Command::tile_threads`]. - TileDispatch, - /// `getTileDimensions:` (`0xa4`), the guest asking the host to report tile - /// geometry into [`Command::buffer_ref`] at [`Command::buffer_offset`]. - TileDimensionsQuery, - /// `set{Color,Depth,Stencil}StoreActionOptions:` (`0x67`/`0x6a`/`0x79`). - /// Options in [`Command::mode`]; the colour form also fills - /// [`Command::first`] with the attachment index. Distinct from - /// [`Kind::SetStoreAction`], which is the action rather than its options - /// and is a different record at a different width. - SetStoreActionOptions, - /// `setTessellationFactorBuffer:offset:instanceStride:` (`0x7a`), in - /// [`Command::buffer_ref`] and [`Command::buffer_offset`]. - SetTessellationFactorBuffer, - /// A tessellated draw: [`wire::OPCODE_DRAW_PATCHES`] and its four siblings. Which - /// form is [`Command::opcode`], as on the wire — except that `0x0c` is two - /// records and [`Command::command_length`] is what separates them. - /// - /// No field is lifted, because nothing here tessellates and a `patch_count` - /// with no consumer is worse than its absence. The record is still fully - /// bounds-checked, so a truncated one is refused rather than reported as a - /// smaller draw. - DrawPatches, - /// One pass property `writeDescriptor` emits as a record of its own rather - /// than as a field of the pass descriptor: `0x1e` the default raster sample - /// count, `0x20` the programmable sample positions, `0x21` the - /// rasterization rate map, `0x22`/`0x23` the imageblock and threadgroup - /// memory lengths, `0x24` the tile size. Which one is [`Command::opcode`], - /// as on the wire; the scalar is [`Command::mode`] and the rate map's ref is - /// [`Command::object_ref`]. - /// - /// Decoded and counted rather than applied. Each of the six is behind a - /// capability that defaults off, so a non-zero count is the first evidence - /// this project would have that any guest negotiates one — which is a thing - /// nothing in this device currently observes. - RenderPassProperty, - OtherAccepted, -} - -/// One entry of a multi-slot buffer bind record. -/// -/// A struct rather than the `(u32, u64)` tuple this used to be, because the -/// stride is a third value travelling with the same two. The pair had already -/// outgrown the tuple: the -/// twenty-byte `setVertexBuffers:offsets:attributeStrides:withRange:` entry -/// carries all three, and the decoder was reading the first two and stepping -/// over the third. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct DecodedBufferBind { - pub buffer_ref: u32, - pub offset: u64, - /// The vertex fetch stride this bind declares, overriding whatever the - /// pipeline's `MTLVertexBufferLayoutDescriptor` said for the same index. - /// - /// `None` is "this record carried no stride table", which is the plain - /// `setVertexBuffers:offsets:withRange:` and every non-vertex stage. It is - /// not the same as `Some(0)`: a zero stride is a legal Metal request that - /// fetches every vertex from the same address. - pub attribute_stride: Option, -} - -/// Which encoder table a render bind record names. -/// -/// Derived from the opcode, not from a wire field: -/// `wire::OPCODE_SET_VERTEX_*` versus `wire::OPCODE_SET_FRAGMENT_*`. The render -/// opcode set expresses no other stage, so there are no other variants — an -/// object/mesh/tile bind reaches the device through the indirect-command-buffer -/// path and carries [`crate::runtime::icb::IcbRenderBindStage`], which is a -/// different vocabulary with a different wire encoding. -/// -/// Keeping this exhaustive is the point. With unreachable variants present, -/// every `match` over it needed a catch-all, and a catch-all is what would -/// swallow a genuinely new stage in silence. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum Stage { - /// The record named no stage, or the opcode was not a stage-bearing one. - #[default] - Unknown, - Vertex, - Fragment, -} - -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Command { - pub opcode: u32, - pub command_length: u32, - pub kind: Kind, - pub stage: Stage, - pub pipeline_ref: u32, - pub first: u32, - pub count: u32, - /// What a residency record declared, for [`Kind::UseResource`] and - /// [`Kind::UseHeap`] and nothing else. - /// - /// The three shapes disagree about which halves exist — the `stages:`-qualified - /// `useResource` carries both in 16 bits each, `useHeap` carries stages - /// alone, and the two inherited unqualified forms carry usage alone or - /// neither — so a missing half is [`ResourceUsage`]/[`RenderStages`] zero - /// and means "the selector had no such argument". The executor must not - /// read a zero here as the guest asking for nothing. - pub residency_usage: reims_vgpu_protocol::residency::ResourceUsage, - pub residency_stages: reims_vgpu_protocol::residency::RenderStages, - pub buffer_ref: u32, - pub buffer_offset: u64, - /// Multi-entry buffer binds for slots `first..first+count`. - pub buffer_binds: Vec, - pub texture_ref: u32, - /// Multi-entry texture/sampler refs for slots first..first+count. - pub ref_binds: Vec, - /// `(lodMinClamp, lodMaxClamp)` as raw `f32` bits, one per entry of - /// [`Self::ref_binds`], for the two sampler-bind opcodes that carry them. - /// Empty for every other record, including the plain sampler bind — an - /// empty list is "the record declared no clamps", which is not the same as - /// a pair that happens to be `(0.0, 0.0)`. - pub sampler_lod_binds: Vec<(u32, u32)>, - pub sampler_ref: u32, - pub primitive_type: u32, - pub vertex_start: u32, - pub vertex_count: u32, - pub instance_count: u32, - pub index_count: u32, - pub index_type: u32, - pub index_buffer_ref: u32, - pub index_buffer_offset: u64, - /// Metal `baseInstance` / Vulkan `firstInstance`. Zero on the draw forms - /// whose selector has no such argument, which is what Metal defaults to. - pub base_instance: u32, - /// Metal `baseVertex` / Vulkan `vertexOffset`, on the indexed forms that - /// carry one. Signed: Metal declares it `NSInteger`, Apple's serializer - /// declares it `q` where every count beside it is `Q`, and a negative - /// offset read as unsigned becomes a large index rather than an error. - pub base_vertex: i64, - /// Every viewport a [`Kind::SetViewport`] record carried, in the guest's - /// order — the singular opcode's one, or all of `setViewports:count:`. - /// - /// A `Vec` rather than one entry plus a count, because the two forms are the - /// same record with a different length and the count used to be kept only to - /// say how many entries were being thrown away. Empty for every other kind. - pub viewports: Vec<[f64; 6]>, - /// Every scissor rect a [`Kind::SetScissor`] record carried, in the guest's - /// order. See [`Self::viewports`]. - pub scissors: Vec, - pub fence_ref: u32, - /// Value of a [`Kind::SetRasterState`], [`Kind::SetStoreAction`] or - /// [`Kind::SetVisibilityResultMode`] record. - pub mode: u64, - /// Buffer a [`Kind::DrawIndirect`] record reads its counts from, and the - /// byte offset of the arguments structure within it. Distinct from - /// [`Command::index_buffer_ref`], which the indexed form fills as well — - /// an indexed indirect draw names two buffers and two offsets, and a - /// decoder that crossed them would replay the wrong one. - pub indirect_buffer_ref: u32, - pub indirect_buffer_offset: u64, - /// Byte offset a [`Kind::SetVisibilityResultMode`] record writes its - /// occlusion counter to, within the pass's visibility result buffer. - pub visibility_result_offset: u64, - /// `value` of a [`Kind::SetVertexAmplification`] mode record. Thirty-two - /// bits: the selector declares it `Q` and the serializer narrows it, which - /// only the capture shows. - pub amplification_value: u32, - /// A `setVertexAmplificationCount:viewMappings:` record carried at least - /// one `MTLVertexAmplificationViewMapping` that is not the identity. - /// - /// Only ever true on [`Kind::SetVertexAmplification`], and only on the - /// count form — the mode record carries no mappings. - /// - /// It exists because the count alone does not say whether the record asks - /// for anything. A mapping offsets the viewport and render-target *array - /// indices* the view rasterises into, so a count of one with a non-zero - /// offset is a draw aimed at a different array slice than slice zero, while - /// a count of one with the identity is the API default and asks for nothing. - /// Reading only the count reports those two as the same record, and the - /// first of them then renders into the wrong slice with nothing said. - /// - /// A flag rather than the offsets themselves, for the reason - /// [`Command::has_attribute_stride`] is one: nothing downstream amplifies, - /// so what a reader needs is whether the record asked for something this - /// rail did not do, and carrying the pairs would suggest somebody applies - /// them. - pub amplification_offsets_views: bool, - /// Threads per tile of a [`Kind::TileDispatch`], as width/height/depth. - /// - /// Unnarrowed `u64` — the serializer writes all three at full width, unlike - /// almost every other count in this protocol. Read by `runtime::exec` both - /// to tell an empty dispatch from a real one and to say in the fail line - /// how much work was dropped. - pub tile_threads: [u64; 3], - /// Value of a [`Kind::SetFloatState`] record. - pub float_value: f32, - /// The vertex buffer bind carried a per-entry attribute stride this decoder - /// did not lift. True on [`Kind::SetBuffer`] and [`Kind::SetBufferOffset`]; - /// see [`wire::OPCODE_SET_VERTEX_BUFFER_STRIDE`]. The buffer still binds — what is - /// missing is the stride the guest wanted the vertex fetch to use. - pub has_attribute_stride: bool, - /// The stride of a single-slot [`Kind::SetBufferOffset`] record that - /// carried one (`setVertexBufferOffset:attributeStride:atIndex:`). The - /// multi-slot forms carry theirs per entry in - /// [`DecodedBufferBind::attribute_stride`], because the record does. - pub attribute_stride: Option, - pub raw_payload_len: usize, - /// Color attachment[0] when kind is RenderPass (boot clear path). - pub color0: ColorAttachment, - pub depth: DepthAttachment, - pub stencil: StencilAttachment, - /// The pass's own tail, on [`Kind::RenderPass`]. Decoded, not applied. - /// - /// `visibility_result_buffer_ref` is the buffer - /// `setVisibilityResultMode:offset:` indexes — that record carries the mode - /// and the offset and *only* the pass record names the buffer, so the two - /// halves of an occlusion query arrive on different records. The three - /// geometry fields are the guest's explicit statement about the pass extent - /// and layer count, which cannot be recovered from the attachments: a guest - /// may bind a 4096-wide texture and ask for a 640-wide pass. - pub pass_visibility_result_buffer_ref: u32, - pub pass_render_target_array_length: u64, - pub pass_render_target_width: u64, - pub pass_render_target_height: u64, - /// setBlendColor RGBA floats (when kind is SetBlendColor). - pub blend_color: [f32; 4], - /// setCullMode - pub cull_mode: u32, - /// setFrontFacingWinding - pub front_facing: u32, - /// setDepthBias (depthBias, slopeScale, clamp) as f32. - pub depth_bias: [f32; 3], - /// setDepthStencilState object ref - pub depth_stencil_ref: u32, - /// setStencilReference front/back - pub stencil_ref_front: u32, - pub stencil_ref_back: u32, - /// `0x14`/`0x15` executeCommandsInBuffer. - pub indirect_command_buffer_ref: u32, - /// `0x15` range form (unaligned after ICB ref). - pub icb_range_location: u64, - pub icb_range_length: u64, - /// `0x14` indirect range buffer form. - pub icb_args_buffer_ref: u32, - pub icb_args_buffer_offset: u64, - /// True when kind is ExecuteCommands with the range layout (`0x15`). - pub icb_is_range: bool, -} - -/// Whether an opcode is above every one Apple's serializer writes here. -/// -/// Named for what it measures. Its predecessor was `opcode_is_apple_rejected`, -/// which asserted the serializer would never emit anything above the window -- -/// and it emitted `0xa5` and `0xa6`, so this device refused four vertex binds as -/// records Apple does not produce. That is the same correction -/// `decode::blit::opcode_unimplemented_here` needed, and the same lesson: the -/// highest opcode *this project has driven* is not the highest Apple writes. -/// -/// The bound comes from [`wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE`], which is now derived from -/// `reims_vgpu_wire`'s manifest rather than from observation. -/// An opcode inside the accepted window that no decode arm claims. -/// -/// Two tests need one -- this module's catch-all test and `runtime::exec`'s fail-visible test -- -/// and both used to hardcode it. Both went stale, twice: -/// `wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE` stopped working when that bound was corrected to -/// `0xa6`, and its replacement `0x99` lasted one commit until `setVertexAmplificationMode:value:` -/// turned out to be exactly that number. Searching keeps them honest as arms are added, because -/// what they test is that the catch-all exists and reports, not that any number is in it. -#[cfg(test)] -pub(crate) fn unclaimed_accepted_opcode() -> u32 { - (0..=wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE) - .find(|&op| { - let mut v = vec![0u8; OP_HEADER_LEN]; - crate::protocol::endian::st32(&mut v[0..4], op); - crate::protocol::endian::st32(&mut v[4..8], OP_HEADER_LEN as u32); - matches!(decode(&v), Ok(c) if c.kind == Kind::OtherAccepted) - }) - .expect("every opcode in the window is decoded; the catch-all is unreachable") -} - -pub fn opcode_above_the_encoder_window(opcode: u32) -> bool { - opcode > wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE -} - -/// The full accepted window, from `reims_vgpu_render_decode.h`'s enum range. -/// -/// One comparison, in [`opcode_above_the_encoder_window`]. This used to end with -/// `opcode <= wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE` after the early -/// return above it — the exact negation of the test just made, so it could not -/// be false, while reading like a second admission rule that a later edit would -/// have to keep in step. -pub fn opcode_supported(opcode: u32) -> bool { - !opcode_above_the_encoder_window(opcode) -} - -/// Transactional render command decode. -pub fn decode(command: &[u8]) -> Result { - let op = reims_vgpu_wire::op(command, 0).map_err(|_| DecodeStatus::ErrShort)?; - let opcode = op.opcode(); - let command_length = op.length() as usize; - if opcode_above_the_encoder_window(opcode) { - return Err(DecodeStatus::ErrUnsupportedOpcode); - } - if !opcode_supported(opcode) { - return Err(DecodeStatus::ErrUnknownOpcode); - } - let payload = op.payload; - let mut out = Command { - opcode, - command_length: command_length as u32, - raw_payload_len: payload.len(), - ..Default::default() - }; - - match opcode { - wire::OPCODE_SET_RENDER_PIPELINE_STATE => { - let r = wire::state_ref(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetPipeline; - out.pipeline_ref = r.object_ref.get(); - Ok(out) - } - wire::OPCODE_SET_VERTEX_BUFFER | wire::OPCODE_SET_FRAGMENT_BUFFER => { - let (head, entries) = wire::buffer_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetBuffer; - out.stage = if opcode == wire::OPCODE_SET_FRAGMENT_BUFFER { - Stage::Fragment - } else { - Stage::Vertex - }; - out.first = head.first.get(); - out.count = head.count.get(); - if out.count == 0 { - return Err(DecodeStatus::ErrBadLength); - } - // Exact length: product refuses slack the guest did not size for. - match bind_record_len(out.count, BUFFER_BIND_ENTRY_SIZE) { - Some(need) if payload.len() >= need => {} - _ => return Err(DecodeStatus::ErrShort), - } - out.buffer_binds.clear(); - for e in entries { - out.buffer_binds.push(DecodedBufferBind { - buffer_ref: e.buffer_ref.get(), - offset: e.offset.get(), - attribute_stride: None, - }); - } - if let Some(b) = out.buffer_binds.first() { - out.buffer_ref = b.buffer_ref; - out.buffer_offset = b.offset; - } - Ok(out) - } - wire::OPCODE_SET_VERTEX_BUFFER_STRIDE => { - // Attribute-stride form: twenty-byte entries, all three fields of - // each lifted. - let (head, entries) = - wire::buffer_stride_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetBuffer; - out.stage = Stage::Vertex; - out.has_attribute_stride = true; - out.first = head.first.get(); - out.count = head.count.get(); - if out.count == 0 { - return Err(DecodeStatus::ErrBadLength); - } - match bind_record_len(out.count, BUFFER_STRIDE_BIND_ENTRY_SIZE) { - Some(need) if payload.len() >= need => {} - _ => return Err(DecodeStatus::ErrShort), - } - out.buffer_binds.clear(); - for e in entries { - out.buffer_binds.push(DecodedBufferBind { - buffer_ref: e.buffer_ref.get(), - offset: e.offset.get(), - attribute_stride: Some(e.attribute_stride.get()), - }); - } - if let Some(b) = out.buffer_binds.first() { - out.buffer_ref = b.buffer_ref; - out.buffer_offset = b.offset; - } - Ok(out) - } - wire::OPCODE_SET_VERTEX_TEXTURE - | wire::OPCODE_SET_FRAGMENT_TEXTURE - | wire::OPCODE_SET_VERTEX_SAMPLER - | wire::OPCODE_SET_FRAGMENT_SAMPLER => { - let (head, entries) = wire::ref_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - let textures = opcode == wire::OPCODE_SET_VERTEX_TEXTURE - || opcode == wire::OPCODE_SET_FRAGMENT_TEXTURE; - out.kind = if textures { - Kind::SetTexture - } else { - Kind::SetSampler - }; - out.stage = if opcode == wire::OPCODE_SET_VERTEX_TEXTURE - || opcode == wire::OPCODE_SET_VERTEX_SAMPLER - { - Stage::Vertex - } else { - Stage::Fragment - }; - out.first = head.first.get(); - out.count = head.count.get(); - if out.count == 0 { - return Err(DecodeStatus::ErrBadLength); - } - match bind_record_len(out.count, REF_BIND_ENTRY_SIZE) { - Some(need) if payload.len() >= need => {} - _ => return Err(DecodeStatus::ErrShort), - } - out.ref_binds.clear(); - for e in entries { - out.ref_binds.push(e.object_ref.get()); - } - if let Some(&r) = out.ref_binds.first() { - if textures { - out.texture_ref = r; - } else { - out.sampler_ref = r; - } - } - Ok(out) - } - wire::OPCODE_SET_VERTEX_SAMPLER_LOD | wire::OPCODE_SET_FRAGMENT_SAMPLER_LOD => { - // Both halves are lifted: the refs into `ref_binds` and the - // per-entry clamps into `sampler_lod_binds` beside them. - let (head, entries) = - wire::sampler_lod_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetSampler; - out.stage = if opcode == wire::OPCODE_SET_VERTEX_SAMPLER_LOD { - Stage::Vertex - } else { - Stage::Fragment - }; - out.first = head.first.get(); - out.count = head.count.get(); - if out.count == 0 { - return Err(DecodeStatus::ErrBadLength); - } - match bind_record_len(out.count, SAMPLER_LOD_BIND_ENTRY_SIZE) { - Some(need) if payload.len() >= need => {} - _ => return Err(DecodeStatus::ErrShort), - } - out.ref_binds.clear(); - out.sampler_lod_binds.clear(); - for e in entries { - out.ref_binds.push(e.sampler_ref.get()); - // Carried as bits. The clamps are per *entry* — the wire doc - // says so and `render_set_vertex_samplers_lod_range` binds two - // slots with four distinct values — so they are pushed beside - // the refs rather than lifted to a per-record pair. - out.sampler_lod_binds.push(( - e.lod_min_clamp.get().to_bits(), - e.lod_max_clamp.get().to_bits(), - )); - } - if let Some(&r) = out.ref_binds.first() { - out.sampler_ref = r; - } - Ok(out) - } - wire::OPCODE_DRAW => { - // Compact `drawPrimitives:vertexStart:vertexCount:`: an 8-byte - // payload of `u32 primitiveType · u16 vertexStart · u16 vertexCount`. - // - // This used to read four u32s behind `payload.len() < 16`, which is - // neither of the selector's two forms. The only test for it was a - // synthetic 24-byte fixture built to match the code, so nothing - // caught it — and every live compact draw was rejected `ErrShort` - // and dropped. Silently, until the decode refusal was named: one - // fired on the first arm64 boot that could report it. The layout is - // now `reims_vgpu_wire::ops::render::Draw`, pinned by fixtures - // `render_draw_primitives` and `render_draw_primitives_strip`. - if command_length != DRAW_COMPACT_CMD_LEN { - return Err(DecodeStatus::ErrBadLength); - } - let d = wire::draw(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Draw; - out.primitive_type = d.primitive_type.get(); - out.vertex_start = d.vertex_start.get() as u32; - out.vertex_count = d.vertex_count.get() as u32; - // Not on the wire: this selector is the non-instanced one, and - // Metal draws it once. - out.instance_count = 1; - Ok(out) - } - // Wide `drawPrimitives:vertexStart:vertexCount:`, which the guest emits - // instead of `0x01` when either count exceeds 16 bits. - // - // This arm used to decline by name, and it was right to: the layout it - // would have guessed — `u64 · u64 · u32 primitiveType@0x10`, by analogy - // with the wide instanced siblings — is wrong. `primitiveType` leads and - // is 32-bit, exactly as in the compact form. Fixtures - // `render_draw_primitives_wide`, `..._count_over_16bit` and - // `..._start_over_16bit` settle it. - wire::OPCODE_DRAW_WIDE => { - if command_length != wire::DRAW_WIDE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = wire::draw_wide(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Draw; - out.primitive_type = d.primitive_type.get(); - out.vertex_start = narrow_count(d.vertex_start.get())?; - out.vertex_count = narrow_count(d.vertex_count.get())?; - out.instance_count = 1; - Ok(out) - } - // Compact `drawPrimitives:vertexStart:vertexCount:instanceCount:`. - // - // The layout is DISTINCT from the `0x01` form — the counts lead and - // `primitiveType` is last and 16-bit. Derived here from live x86 WebKit - // bytes (`00000400 0d000400` = vs0 vc4 inst13 primTriStrip) before the - // oracle existed, and `render_draw_primitives_instanced` later agreed - // field for field. This is WebKit's instanced glyph/rect batch; the - // non-instanced `0x01` and indexed `0x07` forms render chrome text, - // which is why chrome rendered while page content stayed blank. - wire::OPCODE_DRAW_INSTANCED => { - let d = wire::draw_instanced(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Draw; - out.vertex_start = d.vertex_start.get() as u32; - out.vertex_count = d.vertex_count.get() as u32; - out.instance_count = wire_instance_count(d.instance_count.get() as u64)?; - out.primitive_type = d.primitive_type.get() as u32; - Ok(out) - } - // Wide `drawPrimitives:…:instanceCount:` — the counts widen together - // when any one of them passes 16 bits, so the whole record is 64-bit - // even where two of the three would have fitted. - wire::OPCODE_DRAW_INSTANCED_WIDE => { - if command_length != wire::DRAW_INSTANCED_WIDE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = wire::draw_instanced_wide(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Draw; - out.vertex_start = narrow_count(d.vertex_start.get())?; - out.vertex_count = narrow_count(d.vertex_count.get())?; - out.instance_count = wire_instance_count(d.instance_count.get())?; - out.primitive_type = d.primitive_type.get() as u32; - Ok(out) - } - // `drawPrimitives:…:instanceCount:baseInstance:`, both encodings. - // - // Neither was decoded at all until now: both fall inside the accepted - // window, so they reached `Kind::OtherAccepted` and executed nothing — - // an entire Metal draw selector dropped, wearing the shape of an - // accepted state-set. - wire::OPCODE_DRAW_INSTANCED_BASE => { - if command_length != wire::DRAW_INSTANCED_BASE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = wire::draw_instanced_base(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Draw; - out.vertex_start = d.vertex_start.get() as u32; - out.vertex_count = d.vertex_count.get() as u32; - out.instance_count = wire_instance_count(d.instance_count.get() as u64)?; - out.base_instance = d.base_instance.get() as u32; - out.primitive_type = d.primitive_type.get() as u32; - Ok(out) - } - wire::OPCODE_DRAW_INSTANCED_BASE_WIDE => { - if command_length != wire::DRAW_INSTANCED_BASE_WIDE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = wire::draw_instanced_base_wide(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Draw; - out.vertex_start = narrow_count(d.vertex_start.get())?; - out.vertex_count = narrow_count(d.vertex_count.get())?; - out.instance_count = wire_instance_count(d.instance_count.get())?; - out.base_instance = narrow_count(d.base_instance.get())?; - out.primitive_type = d.primitive_type.get() as u32; - Ok(out) - } - wire::OPCODE_DRAW_INDEXED_WIDE => { - // The wide indexed form. This arm's head was already right; what it - // called `u32 indexCount@8, u32 pad@0xc` and `u32 - // indexBufferOffset@0x10, u32 pad@0x14` are the two halves of two - // 64-bit fields, which reads the same below 2³² and differently - // above it. Fixtures `render_draw_indexed_count_over_16bit` and - // `..._offset_over_16bit`. - if command_length != wire::DRAW_INDEXED_WIDE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = wire::draw_indexed_wide(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Draw; - out.primitive_type = d.primitive_type.get() as u32; - out.index_type = d.index_type.get() as u32; - out.index_buffer_ref = d.index_buffer_ref.get(); - out.index_count = narrow_count(d.index_count.get())?; - out.index_buffer_offset = d.index_buffer_offset.get(); - out.instance_count = 1; - Ok(out) - } - // Compact indexed draws: `0x07` is 20 bytes on the wire and `0x09` is - // 24, the second appending a 16-bit instance count. - // - // Two things here were wrong and could not be seen from a boot. The - // first four bytes were read as one `u32 primitiveType`, which absorbs - // `indexType` at `+2`; and `index_type` was then hardcoded to - // `MTLIndexTypeUInt16`. Both are right exactly while the guest uses - // 16-bit indices, because that ordinal is 0. Fixture - // `render_draw_indexed_uint32` is the case that separates them: with - // `MTLIndexTypeUInt32` the word reads `04 00 01 00`, so the old arm - // produced `primitiveType = 0x10004` — no such Metal primitive — - // alongside a 32-bit index buffer drawn as 16-bit. - // - // The `payload.len() >= 28` branch that used to sit in front of this is - // gone. These two records are 12 and 16 bytes of payload and never - // anything else; the wide forms are separate opcodes (`0x06`, `0x08`). - // It was unreachable, and the layout it carried was an invention. - wire::OPCODE_DRAW_INDEXED | wire::OPCODE_DRAW_INDEXED_INSTANCED => { - out.kind = Kind::Draw; - // Shared compact body; the instanced form only adds instance_count. - // Use the layout view (not draw_indexed's opcode assert) so both arms share it. - let d = wire_view::(payload)?; - out.primitive_type = d.primitive_type.get() as u32; - out.index_type = d.index_type.get() as u32; - out.index_buffer_ref = d.index_buffer_ref.get(); - out.index_count = d.index_count.get() as u32; - out.index_buffer_offset = d.index_buffer_offset.get() as u64; - out.instance_count = if opcode == wire::OPCODE_DRAW_INDEXED_INSTANCED { - let i = wire::draw_indexed_instanced(&op).map_err(|_| DecodeStatus::ErrShort)?; - wire_instance_count(i.instance_count.get() as u64)? - } else { - 1 - }; - Ok(out) - } - wire::OPCODE_DRAW_INDEXED_INSTANCED_WIDE => { - if command_length != wire::DRAW_INDEXED_INSTANCED_WIDE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = wire::draw_indexed_instanced_wide(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Draw; - out.primitive_type = d.primitive_type.get() as u32; - out.index_type = d.index_type.get() as u32; - out.index_buffer_ref = d.index_buffer_ref.get(); - out.index_count = narrow_count(d.index_count.get())?; - out.index_buffer_offset = d.index_buffer_offset.get(); - out.instance_count = wire_instance_count(d.instance_count.get())?; - Ok(out) - } - // The full indexed draw, with a base vertex and a base instance. - // - // These two are the *only* records in the family that put the buffer - // offset before the index count. Reading them with the siblings' order - // swaps a guest's index count and its buffer offset, which draws from - // the wrong place in the wrong amount — so the field order here is not - // a copy of the arm above and must not be made one. - wire::OPCODE_DRAW_INDEXED_INSTANCED_BASE => { - if command_length != wire::DRAW_INDEXED_INSTANCED_BASE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = wire::draw_indexed_instanced_base(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Draw; - out.primitive_type = d.primitive_type.get() as u32; - out.index_type = d.index_type.get() as u32; - out.index_buffer_ref = d.index_buffer_ref.get(); - out.index_count = d.index_count.get() as u32; - out.index_buffer_offset = d.index_buffer_offset.get() as u64; - out.instance_count = wire_instance_count(d.instance_count.get() as u64)?; - out.base_instance = d.base_instance.get() as u32; - out.base_vertex = d.base_vertex.get() as i64; - Ok(out) - } - wire::OPCODE_DRAW_INDEXED_INSTANCED_BASE_WIDE => { - if command_length != wire::DRAW_INDEXED_INSTANCED_BASE_WIDE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = - wire::draw_indexed_instanced_base_wide(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Draw; - out.primitive_type = d.primitive_type.get() as u32; - out.index_type = d.index_type.get() as u32; - out.index_buffer_ref = d.index_buffer_ref.get(); - out.index_count = narrow_count(d.index_count.get())?; - out.index_buffer_offset = d.index_buffer_offset.get(); - out.instance_count = wire_instance_count(d.instance_count.get())?; - out.base_instance = narrow_count(d.base_instance.get())?; - out.base_vertex = d.base_vertex.get(); - Ok(out) - } - wire::OPCODE_SET_VERTEX_BUFFER_OFFSET | wire::OPCODE_SET_FRAGMENT_BUFFER_OFFSET => { - let b = wire::buffer_offset(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetBufferOffset; - out.stage = if opcode == wire::OPCODE_SET_FRAGMENT_BUFFER_OFFSET { - Stage::Fragment - } else { - Stage::Vertex - }; - out.first = b.index.get(); - out.buffer_offset = b.offset.get(); - Ok(out) - } - wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE => { - let b = wire::buffer_offset_stride(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetBufferOffset; - out.stage = Stage::Vertex; - out.has_attribute_stride = true; - out.first = b.index.get(); - out.buffer_offset = b.offset.get(); - out.attribute_stride = Some(b.attribute_stride.get()); - Ok(out) - } - wire::OPCODE_SET_VIEWPORT => { - let v = wire::set_viewport(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetViewport; - out.count = 1; - out.viewports = vec![viewport_from_wire(v)]; - Ok(out) - } - wire::OPCODE_SET_VIEWPORTS => { - // The whole array is lifted. `count` is the record's own, and the - // slice the wire view returns is already that long, so the two - // cannot disagree about how many the guest set. - let (head, ports) = wire::set_viewports(&op).map_err(|_| DecodeStatus::ErrShort)?; - let count = head.count.get(); - if count == 0 { - return Err(DecodeStatus::ErrBadLength); - } - out.kind = Kind::SetViewport; - out.count = count; - out.viewports = ports.iter().map(viewport_from_wire).collect(); - Ok(out) - } - wire::OPCODE_SET_SCISSOR => { - let r = wire::set_scissor(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetScissor; - out.count = 1; - out.scissors = vec![scissor_from_wire(r)]; - Ok(out) - } - wire::OPCODE_SET_SCISSOR_RECTS => { - let (head, rects) = wire::set_scissor_rects(&op).map_err(|_| DecodeStatus::ErrShort)?; - let count = head.count.get(); - if count == 0 { - return Err(DecodeStatus::ErrBadLength); - } - let Ok(count) = u32::try_from(count) else { - return Err(DecodeStatus::ErrCountOutOfRange); - }; - out.kind = Kind::SetScissor; - out.count = count; - out.scissors = rects.iter().map(scissor_from_wire).collect(); - Ok(out) - } - wire::OPCODE_SET_BLEND_COLOR => { - let b = wire::set_blend_color(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetBlendColor; - out.blend_color = [b.red.get(), b.green.get(), b.blue.get(), b.alpha.get()]; - Ok(out) - } - wire::OPCODE_SET_CULL_MODE => { - let m = wire::set_cull_mode(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetCullMode; - out.cull_mode = m.mode.get() as u32; - Ok(out) - } - wire::OPCODE_SET_FRONT_FACING => { - let m = wire::set_front_facing(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetFrontFacing; - out.front_facing = m.mode.get() as u32; - Ok(out) - } - wire::OPCODE_SET_DEPTH_BIAS => { - let d = wire::set_depth_bias(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetDepthBias; - out.depth_bias = [d.bias.get(), d.slope_scale.get(), d.clamp.get()]; - Ok(out) - } - wire::OPCODE_SET_DEPTH_STENCIL_STATE => { - let r = wire::state_ref(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetDepthStencil; - out.depth_stencil_ref = r.object_ref.get(); - Ok(out) - } - wire::OPCODE_SET_STENCIL_REFERENCE => { - let s = wire::set_stencil_reference(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetStencilReference; - out.stencil_ref_front = s.front.get(); - out.stencil_ref_back = s.back.get(); - Ok(out) - } - wire::OPCODE_UPDATE_FENCE | wire::OPCODE_WAIT_FOR_FENCE => { - let f = wire::fence(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::Fence; - out.fence_ref = f.fence_ref.get(); - Ok(out) - } - wire::OPCODE_USE_RESOURCE => { - // Refs are not lifted: the rail resolves every binding it draws - // with, so a ref list here would be allocated per record and read - // by nobody. `usage` and `stages` are, because they are what says - // whether that reasoning holds — see - // `reims_vgpu_protocol::residency`. Count bounds the record via the - // wire layout (usage+stages pack to 4 bytes, refs at +8). - let (head, refs) = wire::use_resource(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::UseResource; - out.count = head.count.get(); - out.residency_usage = ResourceUsage(u32::from(head.usage.get())); - out.residency_stages = RenderStages(u32::from(head.stages.get())); - if out.count as usize != refs.len() { - return Err(DecodeStatus::ErrShort); - } - Ok(out) - } - wire::OPCODE_USE_HEAP => { - // Heap form: no usage word, so `residency_usage` stays zero and - // means "this selector has no usage argument" rather than "the - // guest declared none". Stages u16, refs at +6 (align-1). - let (head, refs) = wire::use_heap(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::UseHeap; - out.count = head.count.get(); - out.residency_stages = RenderStages(u32::from(head.stages.get())); - if out.count as usize != refs.len() { - return Err(DecodeStatus::ErrShort); - } - Ok(out) - } - // The two residency forms that take no `stages:`. A render encoder - // inherits them from the encoder base class, so they arrive on this rail - // as readily as the two above; without these arms they reached the - // `OtherAccepted` catch-all and were reported as unimplemented opcodes, - // which is a wrong answer twice over — they are implemented, by doing - // nothing, and the residency routes were counting half their family. - // - // Separate arms rather than a shared one because the heads differ: four - // bytes here against the qualified pair's six and eight. Reading either - // with another's layout starts the refs in the wrong place, which is what - // the `count == refs.len()` check catches. - wire::OPCODE_USE_RESOURCES_NO_STAGES => { - let (head, refs) = - wire::use_resources_no_stages(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::UseResource; - out.count = head.count.get(); - out.residency_usage = ResourceUsage(head.usage.get()); - if out.count as usize != refs.len() { - return Err(DecodeStatus::ErrShort); - } - Ok(out) - } - wire::OPCODE_USE_HEAPS_NO_STAGES => { - let (head, refs) = - wire::use_heaps_no_stages(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::UseHeap; - out.count = head.count.get(); - if out.count as usize != refs.len() { - return Err(DecodeStatus::ErrShort); - } - Ok(out) - } - wire::OPCODE_MEMORY_BARRIER_RESOURCES - | wire::OPCODE_MEMORY_BARRIER_SCOPE - | wire::OPCODE_TEXTURE_BARRIER => { - out.kind = Kind::Barrier; - Ok(out) - } - wire::OPCODE_SET_DEPTH_CLIP_MODE | wire::OPCODE_SET_TRIANGLE_FILL_MODE => { - let m = wire::mode_state(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetRasterState; - out.mode = m.mode.get(); - Ok(out) - } - wire::OPCODE_DRAW_INDIRECT => { - if command_length != wire::DRAW_INDIRECT_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = wire::draw_indirect(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::DrawIndirect; - // 16 bits here, where the direct draws give the same field 32. The - // two bytes above it are never written by the serializer, so a - // wider read takes the guest's stale ring. - out.primitive_type = d.primitive_type.get() as u32; - out.indirect_buffer_ref = d.indirect_buffer_ref.get(); - out.indirect_buffer_offset = d.indirect_buffer_offset.get(); - Ok(out) - } - wire::OPCODE_DRAW_INDEXED_INDIRECT => { - if command_length != wire::DRAW_INDEXED_INDIRECT_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = wire::draw_indexed_indirect(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::DrawIndirect; - out.primitive_type = d.primitive_type.get() as u32; - // Its own 16-bit field beside `primitive_type`, not the upper half - // of a 32-bit one — reading a `u32` at `+0` would absorb it, which - // is the bug the compact indexed draw had. - out.index_type = d.index_type.get() as u32; - out.index_buffer_ref = d.index_buffer_ref.get(); - out.index_buffer_offset = d.index_buffer_offset.get(); - out.indirect_buffer_ref = d.indirect_buffer_ref.get(); - out.indirect_buffer_offset = d.indirect_buffer_offset.get(); - Ok(out) - } - wire_tile::OPCODE_SET_TILE_THREADGROUP_MEMORY => { - if command_length != wire_tile::SET_TILE_THREADGROUP_MEMORY_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let m = wire_tile::tile_threadgroup_memory(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::TileBind; - out.first = m.index.get(); - out.count = 1; - // The length and the offset are read by the view and then not - // lifted, exactly as the other tile binds' entries are not: nothing - // downstream allocates imageblock memory, so a field carrying the - // size would have no consumer. `tile_threads` in particular is a - // dispatch's grid and must not be borrowed for it. - Ok(out) - } - wire_tile::OPCODE_SET_TILE_BUFFER => { - // Entries are not lifted (no tile table consumer); first/count and - // length come from the wire bind walk. - let (head, _entries) = - wire_tile::tile_buffer_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::TileBind; - out.first = head.first.get(); - out.count = head.count.get(); - if out.count == 0 { - return Err(DecodeStatus::ErrBadLength); - } - match bind_record_len(out.count, BUFFER_BIND_ENTRY_SIZE) { - Some(need) if payload.len() >= need => Ok(out), - _ => Err(DecodeStatus::ErrShort), - } - } - wire_tile::OPCODE_SET_TILE_TEXTURE => { - let (head, _entries) = - wire_tile::tile_texture_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::TileBind; - out.first = head.first.get(); - out.count = head.count.get(); - if out.count == 0 { - return Err(DecodeStatus::ErrBadLength); - } - match bind_record_len(out.count, REF_BIND_ENTRY_SIZE) { - Some(need) if payload.len() >= need => Ok(out), - _ => Err(DecodeStatus::ErrShort), - } - } - wire_tile::OPCODE_SET_TILE_SAMPLER => { - let (head, _entries) = - wire_tile::tile_sampler_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::TileBind; - out.first = head.first.get(); - out.count = head.count.get(); - if out.count == 0 { - return Err(DecodeStatus::ErrBadLength); - } - match bind_record_len(out.count, REF_BIND_ENTRY_SIZE) { - Some(need) if payload.len() >= need => Ok(out), - _ => Err(DecodeStatus::ErrShort), - } - } - wire_tile::OPCODE_SET_TILE_SAMPLER_LOD => { - let (head, _entries) = - wire_tile::tile_sampler_lod_binds(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::TileBind; - out.first = head.first.get(); - out.count = head.count.get(); - if out.count == 0 { - return Err(DecodeStatus::ErrBadLength); - } - match bind_record_len(out.count, SAMPLER_LOD_BIND_ENTRY_SIZE) { - Some(need) if payload.len() >= need => Ok(out), - _ => Err(DecodeStatus::ErrShort), - } - } - wire_tile::OPCODE_SET_TILE_BUFFER_OFFSET => { - if command_length != wire_tile::SET_TILE_BUFFER_OFFSET_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let b = wire_tile::tile_buffer_offset(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::TileBind; - out.first = b.index.get(); - out.count = 1; - out.buffer_offset = b.offset.get(); - Ok(out) - } - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE => { - if command_length != wire_tile::DISPATCH_THREADS_PER_TILE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = - wire_tile::dispatch_threads_per_tile(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::TileDispatch; - out.tile_threads = [d.width.get(), d.height.get(), d.depth.get()]; - Ok(out) - } - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION - | wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION_RT_INDEX => { - if command_length != wire_tile::DISPATCH_THREADS_PER_TILE_IN_REGION_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let d = wire_tile::dispatch_threads_per_tile_in_region(&op) - .map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::TileDispatch; - out.tile_threads = [d.width.get(), d.height.get(), d.depth.get()]; - // Region / RT index not lifted — see wire tile module. - Ok(out) - } - wire_tile::OPCODE_GET_TILE_DIMENSIONS => { - if command_length != wire_tile::GET_TILE_DIMENSIONS_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let g = wire_tile::get_tile_dimensions(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::TileDimensionsQuery; - out.buffer_ref = g.buffer_ref.get(); - out.buffer_offset = g.offset.get(); - Ok(out) - } - wire::OPCODE_SET_VERTEX_AMPLIFICATION_MODE => { - if command_length != wire::SET_VERTEX_AMPLIFICATION_MODE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let m = wire::vertex_amplification_mode(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetVertexAmplification; - out.mode = m.mode.get() as u64; - out.amplification_value = m.value.get(); - Ok(out) - } - wire::OPCODE_SET_VERTEX_AMPLIFICATION_COUNT => { - // Four-byte count head (not BindHeader); mappings follow and are - // not lifted — nothing downstream amplifies. Wire parser bounds - // entries to the record length. - let (head, mappings) = - wire::vertex_amplification_count(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetVertexAmplification; - out.count = head.count.get(); - if out.count as usize != mappings.len() { - return Err(DecodeStatus::ErrShort); - } - // The pairs stay unlifted — nothing downstream amplifies — but - // whether any of them is the identity is not the same question as - // the count, and it is the one that says whether the record asked - // for anything. See [`Command::amplification_offsets_views`]. - out.amplification_offsets_views = mappings.iter().any(|m| { - m.viewport_array_index_offset.get() != 0 - || m.render_target_array_index_offset.get() != 0 - }); - Ok(out) - } - wire::OPCODE_SET_VISIBILITY_RESULT_MODE => { - if command_length != wire::SET_VISIBILITY_RESULT_MODE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let v = wire::set_visibility_result_mode(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetVisibilityResultMode; - // Offset first, mode second. See `wire::OPCODE_SET_VISIBILITY_RESULT_MODE`. - out.visibility_result_offset = v.offset.get(); - out.mode = v.mode.get(); - Ok(out) - } - wire::OPCODE_SET_LINE_WIDTH | wire::OPCODE_SET_TESSELLATION_FACTOR_SCALE => { - let f = wire::float_state(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetFloatState; - out.float_value = f.value.get(); - Ok(out) - } - wire::OPCODE_SET_COLOR_STORE_ACTION => { - let a = wire::set_color_store_action(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetStoreAction; - out.mode = u64::from(a.store_action.get()); - out.first = a.index.get(); - Ok(out) - } - wire::OPCODE_SET_DEPTH_STORE_ACTION | wire::OPCODE_SET_STENCIL_STORE_ACTION => { - // Depth/stencil store actions share the one-NSUInteger mode shape. - let m = wire::mode_state(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetStoreAction; - out.mode = m.mode.get(); - Ok(out) - } - wire::OPCODE_SET_COLOR_STORE_ACTION_OPTIONS - | wire::OPCODE_SET_DEPTH_STORE_ACTION_OPTIONS - | wire::OPCODE_SET_STENCIL_STORE_ACTION_OPTIONS => { - // The same three-attachment split one opcode higher, and the widths - // do *not* carry over: the options are a `u64` where the store - // action is a `u32`, so the colour form's index sits at `+8` rather - // than `+4` and the record is 20 bytes rather than 16. - if opcode == wire::OPCODE_SET_COLOR_STORE_ACTION_OPTIONS { - if command_length != wire::SET_COLOR_STORE_ACTION_OPTIONS_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let a = wire::set_color_store_action_options(&op) - .map_err(|_| DecodeStatus::ErrShort)?; - out.mode = a.options.get(); - out.first = a.index.get(); - } else { - if command_length != wire::SET_STORE_ACTION_OPTIONS_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let a = wire::set_store_action_options(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.mode = a.options.get(); - } - out.kind = Kind::SetStoreActionOptions; - Ok(out) - } - wire::OPCODE_DRAW_PATCHES - | wire::OPCODE_DRAW_PATCHES_WIDE - | wire::OPCODE_DRAW_INDEXED_PATCHES - | wire::OPCODE_DRAW_PATCHES_INDIRECT - | wire::OPCODE_DRAW_INDEXED_PATCHES_INDIRECT => { - // Six records across five opcodes, because `0x0c` is two: the plain - // wide draw at 56 bytes and the indexed wide draw at 68. Dispatched - // on the length rather than guessed, and a `0x0c` at any other - // length is refused rather than read as whichever is closer -- the - // two bodies disagree from their tenth byte on. - // - // Every form is length-checked exactly, so a truncated patch draw - // is an `ErrBadLength` rather than a draw with invented counts. - // - // None of the fields is lifted. Nothing here tessellates, so a - // `patch_count` in `Command` would be a producer with no consumer; - // what `runtime::exec` needs is that a patch draw happened and - // which form, and the opcode carries both. - let want = match opcode { - wire::OPCODE_DRAW_PATCHES => wire::DRAW_PATCHES_TOTAL_LEN as usize, - wire::OPCODE_DRAW_INDEXED_PATCHES => wire::DRAW_INDEXED_PATCHES_TOTAL_LEN as usize, - wire::OPCODE_DRAW_PATCHES_INDIRECT => { - wire::DRAW_PATCHES_INDIRECT_TOTAL_LEN as usize - } - wire::OPCODE_DRAW_INDEXED_PATCHES_INDIRECT => { - wire::DRAW_INDEXED_PATCHES_INDIRECT_TOTAL_LEN as usize - } - // `0x0c`: the two wide forms, and nothing else. - _ => match command_length { - n if n == wire::DRAW_PATCHES_WIDE_TOTAL_LEN as usize => n, - n if n == wire::DRAW_INDEXED_PATCHES_WIDE_TOTAL_LEN as usize => n, - _ => return Err(DecodeStatus::ErrBadLength), - }, - }; - if command_length != want { - return Err(DecodeStatus::ErrBadLength); - } - // Viewed, so a record whose declared length outran its bytes is - // refused here rather than by whoever reads it next. - match opcode { - wire::OPCODE_DRAW_PATCHES => { - wire::draw_patches(&op).map_err(|_| DecodeStatus::ErrShort)?; - } - wire::OPCODE_DRAW_INDEXED_PATCHES => { - wire::draw_indexed_patches(&op).map_err(|_| DecodeStatus::ErrShort)?; - } - wire::OPCODE_DRAW_PATCHES_INDIRECT => { - wire::draw_patches_indirect(&op).map_err(|_| DecodeStatus::ErrShort)?; - } - wire::OPCODE_DRAW_INDEXED_PATCHES_INDIRECT => { - wire::draw_indexed_patches_indirect(&op).map_err(|_| DecodeStatus::ErrShort)?; - } - _ if command_length == wire::DRAW_PATCHES_WIDE_TOTAL_LEN as usize => { - wire::draw_patches_wide(&op).map_err(|_| DecodeStatus::ErrShort)?; - } - _ => { - wire::draw_indexed_patches_wide(&op).map_err(|_| DecodeStatus::ErrShort)?; - } - } - out.kind = Kind::DrawPatches; - Ok(out) - } - wire::OPCODE_SET_TESSELLATION_FACTOR_BUFFER => { - // Not a bind: one buffer per encoder, so there is no slot and no - // count -- the ref and its two `u64` sit directly in the payload. - if command_length != wire::SET_TESSELLATION_FACTOR_BUFFER_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let t = - wire::set_tessellation_factor_buffer(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::SetTessellationFactorBuffer; - out.buffer_ref = t.buffer_ref.get(); - out.buffer_offset = t.offset.get(); - Ok(out) - } - wire::OPCODE_EXECUTE_COMMANDS_INDIRECT => { - if command_length != wire::EXECUTE_COMMANDS_INDIRECT_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let e = wire::execute_commands_indirect(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::ExecuteCommands; - out.icb_is_range = false; - out.indirect_command_buffer_ref = e.icb_ref.get(); - out.icb_args_buffer_ref = e.indirect_buffer_ref.get(); - out.icb_args_buffer_offset = e.indirect_buffer_offset.get(); - Ok(out) - } - wire::OPCODE_EXECUTE_COMMANDS_RANGE => { - if command_length != wire::EXECUTE_COMMANDS_RANGE_TOTAL_LEN as usize { - return Err(DecodeStatus::ErrBadLength); - } - let e = wire::execute_commands_range(&op).map_err(|_| DecodeStatus::ErrShort)?; - out.kind = Kind::ExecuteCommands; - out.icb_is_range = true; - out.indirect_command_buffer_ref = e.icb_ref.get(); - out.icb_range_location = e.range_location.get(); - out.icb_range_length = e.range_length.get(); - Ok(out) - } - wire_pass::OPCODE_RENDER_PASS => { - if payload.len() < PASS_MIN_PAYLOAD { - return Err(DecodeStatus::ErrShort); - } - out.kind = Kind::RenderPass; - // Full Apple record: one wire body. Shorter product fixtures still - // decode through the attachment views (same wire layouts at offsets). - if let Ok(body) = wire_pass::render_pass(&op) { - out.depth = depth_from_wire(&body.depth); - out.stencil = stencil_from_wire(&body.stencil); - out.color0 = color_from_wire(&body.color[0]); - out.pass_visibility_result_buffer_ref = body.visibility_result_buffer_ref.get(); - out.pass_render_target_array_length = body.render_target_array_length.get(); - out.pass_render_target_width = body.render_target_width.get(); - out.pass_render_target_height = body.render_target_height.get(); - } else { - out.depth = decode_depth_attachment(payload); - out.stencil = decode_stencil_attachment(payload); - out.color0 = decode_color_attachment(payload, 0); - } - if out.color0.texture_ref != 0 { - out.texture_ref = out.color0.texture_ref; - } - Ok(out) - } - wire_pass::OPCODE_RASTERIZATION_RATE_MAP => { - let r = wire_pass::pass_rate_map(&op).map_err(|_| DecodeStatus::ErrBadLength)?; - out.kind = Kind::RenderPassProperty; - out.texture_ref = r.rate_map_ref.get(); - Ok(out) - } - wire_pass::OPCODE_DEFAULT_RASTER_SAMPLE_COUNT => { - let c = wire_pass::default_raster_sample_count(&op) - .map_err(|_| DecodeStatus::ErrBadLength)?; - out.kind = Kind::RenderPassProperty; - out.mode = u64::from(c.count.get()); - Ok(out) - } - wire_pass::OPCODE_IMAGEBLOCK_SAMPLE_LENGTH - | wire_pass::OPCODE_THREADGROUP_MEMORY_LENGTH => { - let m = wire_pass::tile_memory(&op).map_err(|_| DecodeStatus::ErrBadLength)?; - out.kind = Kind::RenderPassProperty; - out.mode = u64::from(m.length.get()); - Ok(out) - } - wire_pass::OPCODE_TILE_SIZE => { - let s = wire_pass::tile_size(&op).map_err(|_| DecodeStatus::ErrBadLength)?; - out.kind = Kind::RenderPassProperty; - // width | height << 16 — product packing, not a second layout. - out.mode = u64::from(s.width.get()) | (u64::from(s.height.get()) << 16); - Ok(out) - } - wire_pass::OPCODE_SAMPLE_POSITIONS => { - let (head, positions) = - wire_pass::sample_positions(&op).map_err(|_| DecodeStatus::ErrBadLength)?; - out.kind = Kind::RenderPassProperty; - out.count = head.count.get(); - if out.count as usize != positions.len() { - return Err(DecodeStatus::ErrBadLength); - } - Ok(out) - } - _ => { - out.kind = Kind::OtherAccepted; - Ok(out) - } - } -} - - -// --- Test-only layout constants whose only readers were the decoder tests -// --- in `render_decoder_tests.rs`. They moved with them: every offset here -// --- is an `offset_of!` on a `reims-vgpu-wire` struct, so the layout they -// --- pinned is pinned by that crate's own fixtures too. - -/// Fixed total lengths and field offsets for the two ICB execute records. -/// -/// From the wire views, like the draw layouts above them and for the same -/// reason. These were eight literals with a note beside them saying to prefer -/// `wire::EXECUTE_COMMANDS_*_TOTAL_LEN` at new call sites — which leaves the old -/// sites reading a second transcription, and a note is not a mechanism. -#[cfg(test)] -pub(crate) const EXECUTE_INDIRECT_CMD_LEN: usize = - wire::EXECUTE_COMMANDS_INDIRECT_TOTAL_LEN as usize; - -#[cfg(test)] -pub(crate) const EXECUTE_RANGE_CMD_LEN: usize = wire::EXECUTE_COMMANDS_RANGE_TOTAL_LEN as usize; - -#[cfg(test)] -pub(crate) const PASS_TAIL_ARRAY_LENGTH: usize = 0x04; - -/// Offset of the pass-level tail, past the last colour slot. -/// -/// Four fields this device decodes and does not apply. They are the guest's -/// explicit statement about the pass's extent and its occlusion query buffer, -/// and none of them can be recovered from the attachments: a guest may bind a -/// 4096-wide texture and ask for a 640-wide pass. -#[cfg(test)] -pub(crate) const PASS_TAIL_OFF: usize = - PASS_COLOR_ATTACH_OFF + PASS_MAX_COLOR_ATTACHMENTS * PASS_COLOR_ATTACH_STRIDE; - -#[cfg(test)] -pub(crate) const PASS_TAIL_TARGET_HEIGHT: usize = 0x14; - -#[cfg(test)] -pub(crate) const PASS_TAIL_TARGET_WIDTH: usize = 0x0c; - -#[cfg(test)] -pub(crate) const PASS_TAIL_VISIBILITY_BUFFER_REF: usize = 0x00; - -/// Count width of `setViewports:count:` — four bytes (see [`SCISSOR_RECTS_COUNT_LEN`]). -#[cfg(test)] -pub(crate) const VIEWPORTS_COUNT_LEN: usize = core::mem::size_of::(); diff --git a/crates/reims-vgpu/src/dead/render_decoder_tests.rs b/crates/reims-vgpu/src/dead/render_decoder_tests.rs deleted file mode 100644 index f8baab947..000000000 --- a/crates/reims-vgpu/src/dead/render_decoder_tests.rs +++ /dev/null @@ -1,2352 +0,0 @@ -//! DISCONNECTED — the tests of `render_decoder.rs`. See `dead/README.md`. -//! -//! The five that covered the *attachment model* rather than the decoder did -//! not move: they are `runtime::render_pass`'s own test module now. - -/// A malformed render command used to be dropped at the dispatch site with no -/// log line at all — indistinguishable from a segment carrying no render -/// work. Each check names itself now, `Ok` still produces nothing, and the -/// prefix keeps them apart from the six sibling `DecodeStatus` enums. -#[test] -fn every_render_decode_failure_names_its_own_check() { - use crate::observe::Refusal; - const ERRS: &[DecodeStatus] = &[ - DecodeStatus::ErrShort, - DecodeStatus::ErrUnknownOpcode, - DecodeStatus::ErrUnsupportedOpcode, - DecodeStatus::ErrBadLength, - ]; - let mut slugs: Vec<&str> = ERRS.iter().filter_map(|s| s.refusal()).collect(); - assert_eq!(slugs.len(), ERRS.len(), "every error variant refuses"); - assert!(slugs.iter().all(|s| s.starts_with("render_decode_"))); - slugs.sort_unstable(); - let n = slugs.len(); - slugs.dedup(); - assert_eq!(slugs.len(), n, "two render decode checks share a slug"); -} -use super::*; -use crate::protocol::endian::st32; - -fn hdr(op: u32, len: usize) -> Vec { - let mut v = vec![0u8; len]; - st32(&mut v[0..4], op); - st32(&mut v[4..8], len as u32); - v -} - -#[test] -fn pipeline_and_draw() { - let mut v = hdr(wire::OPCODE_SET_RENDER_PIPELINE_STATE, 12); - st32(&mut v[8..], 9); - let c = decode(&v).unwrap(); - assert_eq!(c.pipeline_ref, 9); - - // The compact draw form gets its own test below, against captured - // bytes rather than a fixture shaped like the code. -} - -/// Opcode `0x1` is the COMPACT `drawPrimitives:vertexStart:vertexCount:` — -/// `alloc(1, 8)`, so wire sz `0x10` and an 8-byte payload of -/// `u32 primitiveType · u16 vertexStart · u16 vertexCount`. -/// -/// These payload bytes are the contract's, from the encoder's field order -/// plus the checked-in corpus record: `03 00 00 00 00 00 06 00` = triangle list, -/// vertexStart 0, vertexCount 6. -/// -/// This is the test that fails without the fix. The old fixture was a -/// synthetic 24-byte record with four u32s, which is neither the compact nor -/// the wide form — so the decoder rejected every real compact draw as -/// `ErrShort` and the test agreed with it. -#[test] -fn compact_draw_layout_is_the_contracts_eight_byte_payload() { - let v: [u8; 16] = [ - 0x01, 0x00, 0x00, 0x00, // opcode 0x1 - 0x10, 0x00, 0x00, 0x00, // sz 0x10 - 0x03, 0x00, 0x00, 0x00, // primitiveType 3 (triangle list) - 0x00, 0x00, // vertexStart 0 - 0x06, 0x00, // vertexCount 6 - ]; - let c = decode(&v).expect("the contract's compact draw must decode"); - assert_eq!(c.kind, Kind::Draw); - assert_eq!(c.primitive_type, 3); - assert_eq!(c.vertex_start, 0); - assert_eq!(c.vertex_count, 6); - assert_eq!(c.instance_count, 1, "the non-instanced selector draws once"); - - // A nonzero start must survive: the device offsets both the stage-in - // fetch and `[[vertex_id]]` from it, so reading it from the wrong offset - // renders the wrong vertices rather than nothing. - let mut v2 = v; - v2[12] = 0x02; - v2[14] = 0x04; - let c2 = decode(&v2).expect("nonzero start decodes"); - assert_eq!((c2.vertex_start, c2.vertex_count), (2, 4)); -} - -/// Any other length for opcode `0x1` is not a form this contract knows, so -/// it is refused by name rather than read at a guessed offset. -#[test] -fn a_compact_draw_of_the_wrong_length_is_refused_not_guessed() { - let mut wide = hdr(wire::OPCODE_DRAW, 24); - st32(&mut wide[8..], 3); - assert_eq!(decode(&wide), Err(DecodeStatus::ErrBadLength)); - let short = hdr(wire::OPCODE_DRAW, 12); - assert_eq!(decode(&short), Err(DecodeStatus::ErrBadLength)); -} - -/// The wide form is a *different opcode*, emitted when either count does -/// not fit 16 bits, and it keeps the compact form's field order rather than -/// the instanced forms': `primitiveType` leads and is 32-bit. -/// -/// This arm used to decline by name, which lost the draw but said so. The -/// layout its comment proposed by analogy — two `u64`s then a trailing -/// `primitiveType` — was the wrong one of the two candidates, so decoding on -/// that reasoning would have drawn a wrong primitive from a wrong offset. -/// The bytes below are `reims-vgpu-wire`'s `render_draw_primitives_wide` -/// fixture shape: Apple's serializer emits exactly this for -/// `(Triangle, start 0x11111, count 0x22222)`. -#[test] -fn the_wide_draw_form_decodes_with_the_compact_forms_field_order() { - use crate::protocol::endian::st64; - - let mut v = hdr(wire::OPCODE_DRAW_WIDE, wire::DRAW_WIDE_TOTAL_LEN as usize); - st32(&mut v[8..], 3); // primitiveType, 32-bit and FIRST - st64(&mut v[12..], 0x11111); // vertexStart - st64(&mut v[20..], 0x22222); // vertexCount - let c = decode(&v).expect("the wide draw decodes"); - assert_eq!(c.kind, Kind::Draw); - assert_eq!(c.primitive_type, 3); - assert_eq!(c.vertex_start, 0x11111); - assert_eq!(c.vertex_count, 0x22222); - assert_eq!(c.instance_count, 1, "the non-instanced selector draws once"); - - // Reading it with the instanced forms' order would have taken - // `primitiveType` from the last four bytes, which are a count's high - // half and read zero. A regression to that guess shows up here. - assert_ne!(c.primitive_type, 0); - - let short = hdr( - wire::OPCODE_DRAW_WIDE, - wire::DRAW_WIDE_TOTAL_LEN as usize - 4, - ); - assert_eq!(decode(&short), Err(DecodeStatus::ErrBadLength)); -} - -/// A wide count above 32 bits is refused rather than truncated. -/// -/// `Command` carries 32-bit counts, and the wide encoding exists because a -/// value passed 16 bits, not 32 — so this cannot arise from a real draw. -/// Truncating would silently draw different geometry, which is the class -/// this decoder's named refusals exist to prevent. -#[test] -fn a_wide_count_that_cannot_fit_the_commands_field_is_refused_not_truncated() { - use crate::protocol::endian::st64; - - let mut v = hdr(wire::OPCODE_DRAW_WIDE, wire::DRAW_WIDE_TOTAL_LEN as usize); - st32(&mut v[8..], 3); - st64(&mut v[12..], 0); - st64(&mut v[20..], 0x1_0000_0000); - assert_eq!(decode(&v), Err(DecodeStatus::ErrCountOutOfRange)); -} - -/// The compact indexed draw carries its index type on the wire, in the two -/// bytes that used to be read as the upper half of `primitiveType`. -/// -/// Both readings agree while the guest uses 16-bit indices, because -/// `MTLIndexTypeUInt16` is ordinal 0. With `MTLIndexTypeUInt32` the head -/// reads `04 00 01 00`, and the old arm produced `primitiveType = 0x10004` -/// — no such Metal primitive — while separately reporting UInt16 for a -/// 32-bit index buffer. Apple's serializer emits exactly these bytes for -/// `(TriangleStrip, count 0x1111, UInt32, ref, offset 0x2222)`; the wire -/// Every selector that carries an instance count leaves it non-zero, which -/// is the guarantee three `.max(1)`s downstream of here used to re-apply — -/// two in `runtime::exec`, one in `runtime::draw`. They are gone, so -/// this is now the only thing holding that property up. A decode arm added -/// without [`wire_instance_count`] fails here rather than in a boot. -#[test] -fn no_decoded_draw_leaves_a_zero_instance_count() { - use crate::protocol::endian::st16; - - // The two compact instanced forms, each with the wire carrying zero. - let mut inst = hdr( - wire::OPCODE_DRAW_INSTANCED, - wire::DRAW_INSTANCED_TOTAL_LEN as usize, - ); - st16(&mut inst[8..], 0); // vertexStart - st16(&mut inst[10..], 3); // vertexCount - st16(&mut inst[12..], 0); // instanceCount — the case under test - st16(&mut inst[14..], 3); // primitiveType - assert_eq!( - decode(&inst).expect("instanced draw").instance_count, - 1, - "a wire zero is clamped here or nowhere" - ); - - let mut ix = hdr( - wire::OPCODE_DRAW_INDEXED_INSTANCED, - wire::DRAW_INDEXED_INSTANCED_TOTAL_LEN as usize, - ); - st16(&mut ix[8..], 3); // primitiveType - st16(&mut ix[10..], 0); // indexType - st32(&mut ix[12..], 1); // index buffer ref - st16(&mut ix[16..], 3); // index count - st16(&mut ix[18..], 0); // index buffer offset - st16(&mut ix[20..], 0); // instanceCount — the case under test - assert_eq!( - decode(&ix).expect("indexed instanced draw").instance_count, - 1 - ); - - // And the non-instanced selectors, which carry no count at all: the - // API's own default is one instance, not zero. - let mut compact = hdr(wire::OPCODE_DRAW, DRAW_COMPACT_CMD_LEN); - st32(&mut compact[8..], 3); - st16(&mut compact[12..], 0); - st16(&mut compact[14..], 3); - assert_eq!(decode(&compact).expect("compact draw").instance_count, 1); -} - -/// crate's `render_draw_indexed_uint32` fixture is the same capture. -#[test] -fn a_compact_indexed_draw_reads_its_index_type_from_the_wire() { - use crate::protocol::endian::st16; - - let mut v = hdr( - wire::OPCODE_DRAW_INDEXED, - wire::DRAW_INDEXED_TOTAL_LEN as usize, - ); - st16(&mut v[8..], 4); // primitiveType, 16-bit - st16(&mut v[10..], 1); // indexType UInt32 - st32(&mut v[12..], 0x141f); // index buffer ref - st16(&mut v[16..], 0x1111); // index count - st16(&mut v[18..], 0x2222); // index buffer offset - - let c = decode(&v).expect("compact indexed draw"); - assert_eq!(c.kind, Kind::Draw); - assert_eq!( - c.primitive_type, 4, - "primitiveType must not absorb indexType" - ); - assert_eq!(c.index_type, 1, "UInt32 must survive rather than reading 0"); - assert_eq!(c.index_buffer_ref, 0x141f); - assert_eq!(c.index_count, 0x1111); - assert_eq!(c.index_buffer_offset, 0x2222); - assert_eq!(c.instance_count, 1); - - // The instanced sibling appends a 16-bit instance count and changes - // nothing before it. - let mut w = hdr( - wire::OPCODE_DRAW_INDEXED_INSTANCED, - wire::DRAW_INDEXED_INSTANCED_TOTAL_LEN as usize, - ); - w[8..20].copy_from_slice(&v[8..20]); - st16(&mut w[20..], 0x3333); - let ci = decode(&w).expect("compact instanced indexed draw"); - assert_eq!(ci.primitive_type, 4); - assert_eq!(ci.index_type, 1); - assert_eq!(ci.index_count, 0x1111); - assert_eq!(ci.instance_count, 0x3333); -} - -#[test] -fn compact_instanced_draw_layout_live_webkit_bytes() { - // Live x86 WebKit content record (aneesiqbal.ai), boot serial-20260717-161608: - // 03000000 10000000 | 00000400 0d000400 - // op 0x3, sz 0x10, payload = vs0 vc4 inst13 primTriStrip(4). - let v: [u8; 16] = [ - 0x03, 0x00, 0x00, 0x00, // opcode 0x3 - 0x10, 0x00, 0x00, 0x00, // sz 0x10 - 0x00, 0x00, // vertexStart 0 - 0x04, 0x00, // vertexCount 4 - 0x0d, 0x00, // instanceCount 13 - 0x04, 0x00, // primitiveType 4 (triangle strip) - ]; - let c = decode(&v).expect("compact instanced draw"); - assert_eq!(c.kind, Kind::Draw); - assert_eq!(c.vertex_start, 0); - assert_eq!(c.vertex_count, 4); - assert_eq!(c.instance_count, 13); - assert_eq!(c.primitive_type, 4); - // Not misread as an indexed draw. - assert_eq!(c.index_count, 0); - assert_eq!(c.index_buffer_ref, 0); -} - -/// The six draw forms that carry a base instance used to reach -/// `Kind::OtherAccepted` and execute nothing — two whole Metal selectors -/// dropped, plus the wide encodings of two more, each wearing the shape of -/// an accepted state-set. -/// -/// This walks all twelve draw opcodes and asserts none of them lands in the -/// catch-all. A new opcode in `0x00..=0x0b` that nobody decodes fails here -/// rather than going quiet. -#[test] -fn no_draw_opcode_falls_through_to_the_accepted_catch_all() { - for (opcode, total) in [ - (wire::OPCODE_DRAW_WIDE, wire::DRAW_WIDE_TOTAL_LEN), - (wire::OPCODE_DRAW, wire::DRAW_TOTAL_LEN), - ( - wire::OPCODE_DRAW_INSTANCED_WIDE, - wire::DRAW_INSTANCED_WIDE_TOTAL_LEN, - ), - (wire::OPCODE_DRAW_INSTANCED, wire::DRAW_INSTANCED_TOTAL_LEN), - ( - wire::OPCODE_DRAW_INSTANCED_BASE_WIDE, - wire::DRAW_INSTANCED_BASE_WIDE_TOTAL_LEN, - ), - ( - wire::OPCODE_DRAW_INSTANCED_BASE, - wire::DRAW_INSTANCED_BASE_TOTAL_LEN, - ), - ( - wire::OPCODE_DRAW_INDEXED_WIDE, - wire::DRAW_INDEXED_WIDE_TOTAL_LEN, - ), - (wire::OPCODE_DRAW_INDEXED, wire::DRAW_INDEXED_TOTAL_LEN), - ( - wire::OPCODE_DRAW_INDEXED_INSTANCED_WIDE, - wire::DRAW_INDEXED_INSTANCED_WIDE_TOTAL_LEN, - ), - ( - wire::OPCODE_DRAW_INDEXED_INSTANCED, - wire::DRAW_INDEXED_INSTANCED_TOTAL_LEN, - ), - ( - wire::OPCODE_DRAW_INDEXED_INSTANCED_BASE_WIDE, - wire::DRAW_INDEXED_INSTANCED_BASE_WIDE_TOTAL_LEN, - ), - ( - wire::OPCODE_DRAW_INDEXED_INSTANCED_BASE, - wire::DRAW_INDEXED_INSTANCED_BASE_TOTAL_LEN, - ), - ] { - let v = hdr(opcode, total as usize); - let c = decode(&v).unwrap_or_else(|e| panic!("opcode {opcode:#x} refused: {e:?}")); - assert_eq!( - c.kind, - Kind::Draw, - "opcode {opcode:#x} is a draw and must not decode as {:?}", - c.kind - ); - } -} - -/// `drawPrimitives:…:instanceCount:baseInstance:`, the compact form. -/// -/// Metal offsets `[[instance_id]]` and every per-instance vertex fetch from -/// `baseInstance`, so dropping it draws the same instance repeatedly rather -/// than drawing nothing — which is why this was invisible until the -/// selector was decoded at all. -#[test] -fn a_base_instance_draw_carries_its_base_instance() { - use crate::protocol::endian::st16; - - let mut v = hdr( - wire::OPCODE_DRAW_INSTANCED_BASE, - wire::DRAW_INSTANCED_BASE_TOTAL_LEN as usize, - ); - st16(&mut v[8..], 1); // vertexStart - st16(&mut v[10..], 2); // vertexCount - st16(&mut v[12..], 3); // instanceCount - st16(&mut v[14..], 4); // baseInstance - st16(&mut v[16..], 3); // primitiveType, last and 16-bit - let c = decode(&v).expect("base-instance draw"); - assert_eq!(c.kind, Kind::Draw); - assert_eq!(c.vertex_start, 1); - assert_eq!(c.vertex_count, 2); - assert_eq!(c.instance_count, 3); - assert_eq!(c.base_instance, 4); - assert_eq!(c.primitive_type, 3); -} - -/// The two indexed forms with a base vertex put the buffer offset BEFORE -/// the index count, which their four siblings do not. -/// -/// Reading them with the siblings' order swaps the two, drawing the wrong -/// number of indices from the wrong place — and both are plausible values, -/// so nothing downstream would refuse it. The base vertex is signed, so a -/// small negative offset must not read as an index near 65535. -#[test] -fn the_full_indexed_draw_puts_its_offset_before_its_count_and_signs_its_base_vertex() { - use crate::protocol::endian::st16; - - let mut v = hdr( - wire::OPCODE_DRAW_INDEXED_INSTANCED_BASE, - wire::DRAW_INDEXED_INSTANCED_BASE_TOTAL_LEN as usize, - ); - st16(&mut v[8..], 3); // primitiveType - st16(&mut v[10..], 1); // indexType UInt32 - st32(&mut v[12..], 0x141f); // index buffer ref - st16(&mut v[16..], 0x2222); // index buffer OFFSET first - st16(&mut v[18..], 0x1111); // index count second - st16(&mut v[20..], 0x3333); // instanceCount - st16(&mut v[22..], 0xfffe); // baseVertex = -2, two's complement - st16(&mut v[24..], 0x55); // baseInstance - - let c = decode(&v).expect("full indexed draw"); - assert_eq!(c.kind, Kind::Draw); - assert_eq!(c.index_buffer_offset, 0x2222, "offset comes first here"); - assert_eq!(c.index_count, 0x1111, "count comes second here"); - assert_eq!(c.index_type, 1); - assert_eq!(c.index_buffer_ref, 0x141f); - assert_eq!(c.instance_count, 0x3333); - assert_eq!(c.base_instance, 0x55); - assert_eq!( - c.base_vertex, -2, - "a negative base vertex must stay negative" - ); -} - -/// The wide form of the same record, whose base vertex is sign-extended to -/// 64 bits rather than truncated to 16. -#[test] -fn the_wide_full_indexed_draw_sign_extends_its_base_vertex() { - use crate::protocol::endian::{st16, st64}; - - let mut v = hdr( - wire::OPCODE_DRAW_INDEXED_INSTANCED_BASE_WIDE, - wire::DRAW_INDEXED_INSTANCED_BASE_WIDE_TOTAL_LEN as usize, - ); - st16(&mut v[8..], 3); - st16(&mut v[10..], 0); - st32(&mut v[12..], 0x141f); - st64(&mut v[16..], 0x2222); // offset first - st64(&mut v[24..], 0x1111); // count second - st64(&mut v[32..], 0x10000); // instanceCount, the argument that widened it - st64(&mut v[40..], (-70000i64) as u64); // baseVertex - st64(&mut v[48..], 0x55); // baseInstance - - let c = decode(&v).expect("wide full indexed draw"); - assert_eq!(c.index_buffer_offset, 0x2222); - assert_eq!(c.index_count, 0x1111); - assert_eq!(c.instance_count, 0x10000); - assert_eq!(c.base_vertex, -70000); - assert_eq!(c.base_instance, 0x55); -} - -#[test] -fn wide_indexed_draw_layout() { - use crate::protocol::endian::st16; - - let mut v = hdr(wire::OPCODE_DRAW_INDEXED_WIDE, 0x20); - st16(&mut v[8..], 3); // triangle - st16(&mut v[10..], 0); // UInt16 - st32(&mut v[12..], 0x3e); // index buffer ref - st32(&mut v[16..], 6); // index count - st32(&mut v[24..], 0x10100); // byte offset - - let c = decode(&v).expect("wide indexed draw"); - assert_eq!(c.kind, Kind::Draw); - assert_eq!(c.primitive_type, 3); - assert_eq!(c.index_type, 0); - assert_eq!(c.index_buffer_ref, 0x3e); - assert_eq!(c.index_count, 6); - assert_eq!(c.index_buffer_offset, 0x10100); - assert_eq!(c.instance_count, 1); -} - -#[test] -fn execute_commands_range_and_indirect() { - use crate::protocol::endian::st64; - // 0x15 withRange: ref + unaligned location/length - let mut v = hdr(wire::OPCODE_EXECUTE_COMMANDS_RANGE, EXECUTE_RANGE_CMD_LEN); - st32(&mut v[8..], 0x3333); - st64(&mut v[12..], 5); - st64(&mut v[20..], 7); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::ExecuteCommands); - assert!(c.icb_is_range); - assert_eq!(c.indirect_command_buffer_ref, 0x3333); - assert_eq!(c.icb_range_location, 5); - assert_eq!(c.icb_range_length, 7); - // 0x14 indirect buffer form - let mut v = hdr( - wire::OPCODE_EXECUTE_COMMANDS_INDIRECT, - EXECUTE_INDIRECT_CMD_LEN, - ); - st32(&mut v[8..], 0x1111); - st32(&mut v[12..], 0x2222); - st64(&mut v[16..], 0x40); - let c = decode(&v).unwrap(); - assert!(!c.icb_is_range); - assert_eq!(c.indirect_command_buffer_ref, 0x1111); - assert_eq!(c.icb_args_buffer_ref, 0x2222); - assert_eq!(c.icb_args_buffer_offset, 0x40); -} - - - - - -#[test] -fn blend_color_and_cull() { - let mut v = hdr(wire::OPCODE_SET_BLEND_COLOR, 24); - // RGBA as f32 bits - st32(&mut v[8..], 1.0f32.to_bits()); - st32(&mut v[12..], 0.0f32.to_bits()); - st32(&mut v[16..], 0.0f32.to_bits()); - st32(&mut v[20..], 1.0f32.to_bits()); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::SetBlendColor); - assert!((c.blend_color[0] - 1.0).abs() < 1e-6); - - // Mode state is one NSUInteger on the wire (SET_MODE_TOTAL_LEN = 16). - let mut v = hdr( - wire::OPCODE_SET_CULL_MODE, - wire::SET_MODE_TOTAL_LEN as usize, - ); - st32(&mut v[8..], 2); - let c = decode(&v).unwrap(); - assert_eq!(c.kind, Kind::SetCullMode); - assert_eq!(c.cull_mode, 2); -} - -/// Above the window is refused; inside it but unclaimed is not. -/// -/// These are different answers and the difference is the whole reason the -/// bound moved. `0x99` used to be refused here because it was one past -/// `0x98`, the highest opcode this project had *seen* -- and `0xa5`/`0xa6` -/// were refused with it, which lost four real vertex binds. `0x99` is now -/// inside the encoder's range and unclaimed, so it reaches the catch-all -/// and is reported as a gap rather than denied. -#[test] -fn an_opcode_above_the_window_is_refused_and_one_inside_it_is_not() { - assert!(opcode_above_the_encoder_window(0xff)); - assert_eq!( - decode(&hdr(0xff, 16)).unwrap_err(), - DecodeStatus::ErrUnsupportedOpcode - ); - // One past the highest opcode Apple's serializer writes here. - assert!(opcode_above_the_encoder_window( - wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE + 1 - )); - assert_eq!( - decode(&hdr(wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE + 1, 16)).unwrap_err(), - DecodeStatus::ErrUnsupportedOpcode - ); - // Inside the range, claimed by no arm. `OtherAccepted` is what says so. - // - // Found rather than named. A literal here goes stale the moment that - // opcode is decoded, which already happened once: `0x99` was the - // unclaimed probe until `setVertexAmplificationMode:value:` turned out - // to be exactly that number. - let unclaimed = super::unclaimed_accepted_opcode(); - assert_eq!( - decode(&hdr(unclaimed, 16)) - .unwrap_or_else(|e| panic!("op {unclaimed:#x}: {e:?}")) - .kind, - Kind::OtherAccepted - ); -} - -/// Every bind opcode refuses `count == 0` and refuses more entries than the -/// slot table holds, so a decoded bind record ALWAYS carries at least one -/// entry. -/// -/// `exec::apply_record` relies on this: it walks `buffer_binds` / `ref_binds` -/// directly, with no single-entry wire form to fall back to. If a zero-count -/// record ever decoded successfully, those loops would silently bind nothing. -#[test] -fn a_bind_record_never_decodes_to_zero_entries() { - for (op, entry_size) in [ - (wire::OPCODE_SET_VERTEX_BUFFER, BUFFER_BIND_ENTRY_SIZE), - (wire::OPCODE_SET_FRAGMENT_BUFFER, BUFFER_BIND_ENTRY_SIZE), - (wire::OPCODE_SET_VERTEX_TEXTURE, REF_BIND_ENTRY_SIZE), - (wire::OPCODE_SET_FRAGMENT_TEXTURE, REF_BIND_ENTRY_SIZE), - (wire::OPCODE_SET_VERTEX_SAMPLER, REF_BIND_ENTRY_SIZE), - (wire::OPCODE_SET_FRAGMENT_SAMPLER, REF_BIND_ENTRY_SIZE), - ] { - let hdr_len = 8; - let body = |count: u32, entries: usize| { - let mut v = hdr(op, hdr_len + BIND_ENTRIES + entries * entry_size); - st32(&mut v[hdr_len + BIND_FIRST..], 0); - st32(&mut v[hdr_len + BIND_COUNT..], count); - v - }; - assert_eq!( - decode(&body(0, 0)).unwrap_err(), - DecodeStatus::ErrBadLength, - "op {op:#x} accepted count=0" - ); - // A count with no entries behind it. The record is the guest's own - // length claim, so this is the bound — and it must not wrap. - assert_eq!( - decode(&body(4, 3)).unwrap_err(), - DecodeStatus::ErrShort, - "op {op:#x} accepted a record one entry shorter than its count" - ); - assert_eq!( - decode(&body(u32::MAX, 1)).unwrap_err(), - DecodeStatus::ErrShort, - "op {op:#x} accepted a count whose entries cannot exist" - ); - let c = decode(&body(1, 1)).unwrap_or_else(|e| panic!("op {op:#x}: {e:?}")); - assert_eq!( - c.buffer_binds.len() + c.ref_binds.len(), - 1, - "op {op:#x} decoded one entry into neither list" - ); - // Forty slots, which Apple produces (`setVertexTextures:withRange:` - // over a range of 40) and a 32-entry cap used to refuse whole. - let c = decode(&body(40, 40)).unwrap_or_else(|e| panic!("op {op:#x} refused 40: {e:?}")); - assert_eq!( - c.buffer_binds.len() + c.ref_binds.len(), - 40, - "op {op:#x} did not decode all forty entries" - ); - } -} - -/// The six unapplied states decode to their own kinds, at their own widths. -/// -/// Two are sixteen-byte records with a `u64`, two are twelve-byte records -/// with an `f32`, and the colour store action is the only one of the three -/// store forms that carries an index -- depth and stencil have one -/// attachment each. Reading a float record as a `f64` would take four bytes -/// of whatever followed it, which is why the length is asserted here rather -/// than assumed from the family. -#[test] -fn each_unapplied_state_decodes_at_its_own_width() { - use crate::protocol::endian::{st32, st64}; - use reims_vgpu_wire::ops::render as wire; - - for (op, wire_op) in [ - ( - wire::OPCODE_SET_DEPTH_CLIP_MODE, - wire::OPCODE_SET_DEPTH_CLIP_MODE, - ), - ( - wire::OPCODE_SET_TRIANGLE_FILL_MODE, - wire::OPCODE_SET_TRIANGLE_FILL_MODE, - ), - (wire::OPCODE_SET_LINE_WIDTH, wire::OPCODE_SET_LINE_WIDTH), - ( - wire::OPCODE_SET_TESSELLATION_FACTOR_SCALE, - wire::OPCODE_SET_TESSELLATION_FACTOR_SCALE, - ), - ( - wire::OPCODE_SET_COLOR_STORE_ACTION, - wire::OPCODE_SET_COLOR_STORE_ACTION, - ), - ( - wire::OPCODE_SET_DEPTH_STORE_ACTION, - wire::OPCODE_SET_DEPTH_STORE_ACTION, - ), - ( - wire::OPCODE_SET_STENCIL_STORE_ACTION, - wire::OPCODE_SET_STENCIL_STORE_ACTION, - ), - (wire::OPCODE_TEXTURE_BARRIER, wire::OPCODE_TEXTURE_BARRIER), - ] { - assert_eq!(op, wire_op, "the serializer writes a different opcode"); - } - - // The `u64` mode records. - for op in [ - wire::OPCODE_SET_DEPTH_CLIP_MODE, - wire::OPCODE_SET_TRIANGLE_FILL_MODE, - ] { - let mut v = hdr(op, wire::SET_MODE_TOTAL_LEN as usize); - st64(&mut v[OP_HEADER_LEN..], 1); - let c = decode(&v).unwrap_or_else(|e| panic!("op {op:#x}: {e:?}")); - assert_eq!(c.kind, Kind::SetRasterState, "op {op:#x}"); - assert_eq!(c.mode, 1, "op {op:#x}"); - assert_eq!( - decode(&hdr(op, OP_HEADER_LEN + 4)).unwrap_err(), - DecodeStatus::ErrShort, - "op {op:#x} read a mode out of four bytes" - ); - } - - // The `f32` records: twelve bytes, and the payload is four. - for op in [ - wire::OPCODE_SET_LINE_WIDTH, - wire::OPCODE_SET_TESSELLATION_FACTOR_SCALE, - ] { - let total = wire::SET_FLOAT_TOTAL_LEN as usize; - assert_eq!(total, OP_HEADER_LEN + 4, "op {op:#x}"); - let mut v = hdr(op, total); - st32(&mut v[OP_HEADER_LEN..], 2.5f32.to_bits()); - let c = decode(&v).unwrap_or_else(|e| panic!("op {op:#x}: {e:?}")); - assert_eq!(c.kind, Kind::SetFloatState, "op {op:#x}"); - assert_eq!(c.float_value, 2.5, "op {op:#x}"); - } - - // The colour store action carries an index; the other two do not, and - // the values are deliberately unequal so a swap is visible. - let mut v = hdr(wire::OPCODE_SET_COLOR_STORE_ACTION, 16); - st32(&mut v[OP_HEADER_LEN..], 2); - st32(&mut v[OP_HEADER_LEN + 4..], 3); - let c = decode(&v).expect("colour store action"); - assert_eq!(c.kind, Kind::SetStoreAction); - assert_eq!((c.mode, c.first), (2, 3), "action and index are swapped"); - - for op in [ - wire::OPCODE_SET_DEPTH_STORE_ACTION, - wire::OPCODE_SET_STENCIL_STORE_ACTION, - ] { - let mut v = hdr(op, 16); - st64(&mut v[OP_HEADER_LEN..], 1); - let c = decode(&v).unwrap_or_else(|e| panic!("op {op:#x}: {e:?}")); - assert_eq!(c.kind, Kind::SetStoreAction, "op {op:#x}"); - assert_eq!(c.mode, 1, "op {op:#x}"); - assert_eq!(c.first, 0, "op {op:#x} invented an attachment index"); - } - - // `textureBarrier` is the header alone and joins the barrier kind. - let c = decode(&hdr(wire::OPCODE_TEXTURE_BARRIER, OP_HEADER_LEN)).expect("texture barrier"); - assert_eq!(c.kind, Kind::Barrier); -} - -/// A vertex bind carrying an attribute stride binds the buffer. -/// -/// It used to be refused outright: `0xa5`/`0xa6` are above the old -/// `wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE` of `0x98`, so `opcode_is_apple_rejected` called them -/// records Apple does not emit -- and Apple emits them whenever the guest -/// negotiates `supportsDynamicAttributeStride`. Every strided vertex bind -/// was dropped and the buffer never bound, which is the sampler-LOD bug -/// again with a worse consequence. -/// -/// The plural case is the load-bearing one. Its two entries are twenty -/// bytes apart, and a decoder using the plain twelve would read the second -/// entry out of the middle of the first -- so both offsets are distinct and -/// both are asserted. -#[test] -fn a_vertex_bind_with_an_attribute_stride_binds_the_buffer_rather_than_being_refused() { - use crate::protocol::endian::{st32, st64}; - use reims_vgpu_wire::ops::render as wire; - - for (op, wire_op) in [ - ( - wire::OPCODE_SET_VERTEX_BUFFER_STRIDE, - wire::OPCODE_SET_VERTEX_BUFFER_STRIDE, - ), - ( - wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE, - wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE, - ), - ] { - assert_eq!(op, wire_op, "the serializer writes a different opcode"); - assert!( - !opcode_above_the_encoder_window(op), - "op {op:#x} is still called a record Apple does not emit, and Apple emits it" - ); - } - - // Two slots, twenty bytes apart: {ref u32, offset u64, stride u64}. - let entries = 2usize; - let total = OP_HEADER_LEN + BIND_ENTRIES + entries * BUFFER_STRIDE_BIND_ENTRY_SIZE; - assert_eq!(total, 56, "the plural fixture is 56 bytes"); - let mut v = hdr(wire::OPCODE_SET_VERTEX_BUFFER_STRIDE, total); - st32(&mut v[OP_HEADER_LEN + BIND_FIRST..], 9); - st32(&mut v[OP_HEADER_LEN + BIND_COUNT..], entries as u32); - for (i, (r, off, stride)) in [(5151u32, 0x3333u64, 0x5555u64), (5252, 0x4444, 0x6666)] - .into_iter() - .enumerate() - { - let e = OP_HEADER_LEN + BIND_ENTRIES + i * BUFFER_STRIDE_BIND_ENTRY_SIZE; - st32(&mut v[e..], r); - st64(&mut v[e + 4..], off); - st64(&mut v[e + 12..], stride); - } - let c = decode(&v).expect("a strided vertex bind must decode"); - assert_eq!(c.kind, Kind::SetBuffer); - assert_eq!(c.stage, Stage::Vertex, "there is no fragment stride form"); - assert!(c.has_attribute_stride); - assert_eq!(c.first, 9); - assert_eq!( - c.buffer_binds, - vec![ - DecodedBufferBind { - buffer_ref: 5151, - offset: 0x3333, - attribute_stride: Some(0x5555), - }, - DecodedBufferBind { - buffer_ref: 5252, - offset: 0x4444, - attribute_stride: Some(0x6666), - } - ], - "the entry stride is 20, not the plain bind's 12, and the third field of \ - each entry is the stride rather than padding stepped over" - ); - - // The plain bind must not be told it carries one, or every ordinary - // vertex bind would report a loss it did not have. - let plain_total = OP_HEADER_LEN + BIND_ENTRIES + BUFFER_BIND_ENTRY_SIZE; - let mut p = hdr(wire::OPCODE_SET_VERTEX_BUFFER, plain_total); - st32(&mut p[OP_HEADER_LEN + BIND_COUNT..], 1); - st32(&mut p[OP_HEADER_LEN + BIND_ENTRIES..], 5151); - let c = decode(&p).expect("plain vertex bind"); - assert!(!c.has_attribute_stride); - - // `0xa6` is the offset re-point with the stride appended: 28 bytes. - let total = wire::SET_BUFFER_OFFSET_STRIDE_TOTAL_LEN as usize; - let mut v = hdr(wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE, total); - st32(&mut v[OP_HEADER_LEN..], 8); - st64(&mut v[OP_HEADER_LEN + 4..], 0x4567); - st64(&mut v[OP_HEADER_LEN + 12..], 0x5678); - let c = decode(&v).expect("a strided offset re-point must decode"); - assert_eq!(c.kind, Kind::SetBufferOffset); - assert_eq!(c.stage, Stage::Vertex); - assert!(c.has_attribute_stride); - assert_eq!((c.first, c.buffer_offset), (8, 0x4567)); - // Short of its own stride word it is refused, rather than read as the - // twenty-byte record it is not. - assert_eq!( - decode(&hdr( - wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE, - total - 8 - )) - .unwrap_err(), - DecodeStatus::ErrShort - ); -} - -/// Vertex amplification decodes at two widths the type encoding hides. -/// -/// The mode record declares both arguments `Q` and puts both on the wire at -/// 32 bits, so a decoder written from the encoding reads a 24-byte record -/// that is 16. The count record's head is four bytes rather than the -/// eight-byte bind header every other counted record here uses, so reading -/// a `BindHeader` takes the first mapping's viewport offset as the count -- -/// which is why the fixture's count and first offset are deliberately -/// unequal and this test asserts on both. -#[test] -fn vertex_amplification_decodes_at_the_widths_the_serializer_wrote() { - use crate::protocol::endian::st32; - use reims_vgpu_wire::ops::render as wire; - - for (op, wire_op) in [ - ( - wire::OPCODE_SET_VERTEX_AMPLIFICATION_MODE, - wire::OPCODE_SET_VERTEX_AMPLIFICATION_MODE, - ), - ( - wire::OPCODE_SET_VERTEX_AMPLIFICATION_COUNT, - wire::OPCODE_SET_VERTEX_AMPLIFICATION_COUNT, - ), - ] { - assert_eq!(op, wire_op, "the serializer writes a different opcode"); - } - - let total = wire::SET_VERTEX_AMPLIFICATION_MODE_TOTAL_LEN as usize; - assert_eq!(total, OP_HEADER_LEN + 8, "two u32, not two u64"); - let mut v = hdr(wire::OPCODE_SET_VERTEX_AMPLIFICATION_MODE, total); - st32(&mut v[OP_HEADER_LEN..], 0x5555); - st32(&mut v[OP_HEADER_LEN + 4..], 0x6666); - let c = decode(&v).expect("amplification mode"); - assert_eq!(c.kind, Kind::SetVertexAmplification); - assert_eq!( - (c.mode, c.amplification_value), - (0x5555, 0x6666), - "mode and value are crossed" - ); - - // Two mappings, four distinct offsets. The count is 2 and the first - // viewport offset is 0x1111, so a four-byte head cannot be confused - // with an eight-byte one. - let mappings = 2usize; - let total = OP_HEADER_LEN + AMPLIFICATION_COUNT_LEN + mappings * AMPLIFICATION_MAPPING_SIZE; - assert_eq!(total, 28, "the fixture is 28 bytes"); - let mut v = hdr(wire::OPCODE_SET_VERTEX_AMPLIFICATION_COUNT, total); - st32(&mut v[OP_HEADER_LEN..], mappings as u32); - for (i, (vp, rt)) in [(0x1111u32, 0x2222u32), (0x3333, 0x4444)] - .into_iter() - .enumerate() - { - let e = OP_HEADER_LEN + AMPLIFICATION_COUNT_LEN + i * AMPLIFICATION_MAPPING_SIZE; - st32(&mut v[e..], vp); - st32(&mut v[e + 4..], rt); - } - let c = decode(&v).expect("amplification count"); - assert_eq!(c.kind, Kind::SetVertexAmplification); - assert_eq!(c.count, 2, "the head was read as eight bytes"); - assert!( - c.amplification_offsets_views, - "four non-zero offsets and the record claims to ask for nothing" - ); - - // A count with no mappings behind it. The record is the guest's own - // length claim, so this is the bound, and it must not wrap. - let mut short = hdr(wire::OPCODE_SET_VERTEX_AMPLIFICATION_COUNT, total); - st32(&mut short[OP_HEADER_LEN..], 3); - assert_eq!(decode(&short).unwrap_err(), DecodeStatus::ErrShort); - let mut huge = hdr(wire::OPCODE_SET_VERTEX_AMPLIFICATION_COUNT, total); - st32(&mut huge[OP_HEADER_LEN..], u32::MAX); - assert_eq!(decode(&huge).unwrap_err(), DecodeStatus::ErrShort); -} - -/// A count of one is the API default; a *mapping* of one is not. -/// -/// `setVertexAmplificationCount:viewMappings:` carries one -/// `MTLVertexAmplificationViewMapping` per view, and each offsets the viewport -/// and render-target *array indices* that view rasterises into. So a record -/// with count 1 and a zero mapping asks for exactly what this rail already -/// does, while one with count 1 and a non-zero offset asks for a draw aimed at -/// a different array slice — and until this landed the decoder discarded the -/// mappings unread, so `count > 1` reported the two as the same record and the -/// second rendered into slice zero with nothing said. -/// -/// Both offsets are driven separately, because they are two different indices -/// and an `any` over the wrong field would still pass with only one of them. -#[test] -fn a_single_view_mapping_that_offsets_a_view_is_not_the_default() { - use crate::protocol::endian::st32; - use reims_vgpu_wire::ops::render as wire; - - let record = |viewport: u32, render_target: u32| { - let total = OP_HEADER_LEN + AMPLIFICATION_COUNT_LEN + AMPLIFICATION_MAPPING_SIZE; - let mut v = hdr(wire::OPCODE_SET_VERTEX_AMPLIFICATION_COUNT, total); - st32(&mut v[OP_HEADER_LEN..], 1); - let e = OP_HEADER_LEN + AMPLIFICATION_COUNT_LEN; - st32(&mut v[e..], viewport); - st32(&mut v[e + 4..], render_target); - decode(&v).expect("amplification count") - }; - - let identity = record(0, 0); - assert_eq!(identity.count, 1); - assert!( - !identity.amplification_offsets_views, - "the identity mapping asks for what this rail already does" - ); - - for (viewport, render_target) in [(2u32, 0u32), (0, 3), (2, 3)] { - let c = record(viewport, render_target); - assert_eq!(c.count, 1, "still one view"); - assert!( - c.amplification_offsets_views, - "viewport={viewport} render_target={render_target}" - ); - } - - // The mode record carries no mappings at all, so it never claims one. - let total = wire::SET_VERTEX_AMPLIFICATION_MODE_TOTAL_LEN as usize; - let mut v = hdr(wire::OPCODE_SET_VERTEX_AMPLIFICATION_MODE, total); - st32(&mut v[OP_HEADER_LEN..], 1); - st32(&mut v[OP_HEADER_LEN + 4..], 1); - let c = decode(&v).expect("amplification mode"); - assert!(!c.amplification_offsets_views); -} - -/// `0x0c` is two records, and only the length says which. -/// -/// The plain wide patch draw is 56 bytes and the indexed one is 68, under -/// the same opcode — the one place in this family where a wide form does -/// not get its own number. The two bodies agree for nine bytes and diverge -/// at the tenth, so a decoder that dispatched on the opcode and read either -/// body unconditionally would misread the other half the time rather than -/// refuse it. -/// -/// The third arm is the one that matters most: a `0x0c` at any *other* -/// length has no reading at all, and picking the nearer of the two would -/// take one record's buffer ref as the other's offset. It must be refused. -#[test] -fn the_wide_patch_draw_opcode_is_resolved_by_length_and_refused_without_one() { - use reims_vgpu_wire::ops::render as wire; - - for (op, wire_op) in [ - (wire::OPCODE_DRAW_PATCHES, wire::OPCODE_DRAW_PATCHES), - ( - wire::OPCODE_DRAW_PATCHES_WIDE, - wire::OPCODE_DRAW_PATCHES_WIDE, - ), - ( - wire::OPCODE_DRAW_INDEXED_PATCHES, - wire::OPCODE_DRAW_INDEXED_PATCHES, - ), - ( - wire::OPCODE_DRAW_PATCHES_INDIRECT, - wire::OPCODE_DRAW_PATCHES_INDIRECT, - ), - ( - wire::OPCODE_DRAW_INDEXED_PATCHES_INDIRECT, - wire::OPCODE_DRAW_INDEXED_PATCHES_INDIRECT, - ), - ] { - assert_eq!(op, wire_op, "the serializer writes a different opcode"); - } - - // The two wide lengths really are different, which is what makes the - // length usable as a discriminator at all. - assert_ne!( - wire::DRAW_PATCHES_WIDE_TOTAL_LEN, - wire::DRAW_INDEXED_PATCHES_WIDE_TOTAL_LEN - ); - - for total in [ - wire::DRAW_PATCHES_WIDE_TOTAL_LEN as usize, - wire::DRAW_INDEXED_PATCHES_WIDE_TOTAL_LEN as usize, - ] { - let c = decode(&hdr(wire::OPCODE_DRAW_PATCHES_WIDE, total)) - .unwrap_or_else(|e| panic!("0x0c at {total} bytes: {e:?}")); - assert_eq!(c.kind, Kind::DrawPatches); - assert_eq!(c.command_length as usize, total); - } - - // Between the two, above both, and below both: none has a reading. - for total in [ - wire::DRAW_PATCHES_WIDE_TOTAL_LEN as usize + 4, - wire::DRAW_INDEXED_PATCHES_WIDE_TOTAL_LEN as usize + 4, - wire::DRAW_PATCHES_WIDE_TOTAL_LEN as usize - 4, - ] { - assert_eq!( - decode(&hdr(wire::OPCODE_DRAW_PATCHES_WIDE, total)).unwrap_err(), - DecodeStatus::ErrBadLength, - "0x0c at {total} bytes was given a reading; it has none" - ); - } - - // The four single-length forms, each accepted at its own length and - // refused four bytes short. A patch draw read short is invented - // geometry, not a smaller draw. - for (op, total) in [ - ( - wire::OPCODE_DRAW_PATCHES, - wire::DRAW_PATCHES_TOTAL_LEN as usize, - ), - ( - wire::OPCODE_DRAW_INDEXED_PATCHES, - wire::DRAW_INDEXED_PATCHES_TOTAL_LEN as usize, - ), - ( - wire::OPCODE_DRAW_PATCHES_INDIRECT, - wire::DRAW_PATCHES_INDIRECT_TOTAL_LEN as usize, - ), - ( - wire::OPCODE_DRAW_INDEXED_PATCHES_INDIRECT, - wire::DRAW_INDEXED_PATCHES_INDIRECT_TOTAL_LEN as usize, - ), - ] { - let c = decode(&hdr(op, total)).unwrap_or_else(|e| panic!("op {op:#x}: {e:?}")); - assert_eq!(c.kind, Kind::DrawPatches, "op {op:#x}"); - assert_eq!( - decode(&hdr(op, total - 4)).unwrap_err(), - DecodeStatus::ErrBadLength, - "op {op:#x} accepted a record four bytes short" - ); - } - - // A record whose header promises more bytes than are present is - // refused by the framing, before any of the above runs. - let mut truncated = hdr( - wire::OPCODE_DRAW_PATCHES, - wire::DRAW_PATCHES_TOTAL_LEN as usize, - ); - truncated.truncate(truncated.len() - 4); - assert!(decode(&truncated).is_err(), "a short buffer was accepted"); -} - - -/// The pass's tail is four fields this device decodes and does not apply. -/// -/// A record short of the tail must leave all four at zero rather than -/// reading past its own payload — the decoder accepts a payload as small as -/// one colour slot, and Apple's own record is 584 bytes. -#[test] -fn the_render_pass_tail_is_read_only_when_the_record_carries_one() { - use crate::protocol::endian::st64; - let full = OP_HEADER_LEN + PASS_TAIL_OFF + 0x1c; - let mut cmd = vec![0u8; full]; - st32(&mut cmd[0..], wire_pass::OPCODE_RENDER_PASS); - st32(&mut cmd[4..], full as u32); - let t = OP_HEADER_LEN + PASS_TAIL_OFF; - st32(&mut cmd[t + PASS_TAIL_VISIBILITY_BUFFER_REF..], 5151); - st64(&mut cmd[t + PASS_TAIL_ARRAY_LENGTH..], 0x11); - st64(&mut cmd[t + PASS_TAIL_TARGET_WIDTH..], 0x1234); - st64(&mut cmd[t + PASS_TAIL_TARGET_HEIGHT..], 0x5678); - let c = decode(&cmd).expect("well formed"); - assert_eq!(c.kind, Kind::RenderPass); - assert_eq!(c.pass_visibility_result_buffer_ref, 5151); - assert_eq!(c.pass_render_target_array_length, 0x11); - assert_eq!(c.pass_render_target_width, 0x1234); - assert_eq!(c.pass_render_target_height, 0x5678); - - let short = OP_HEADER_LEN + PASS_MIN_PAYLOAD; - let mut cmd = vec![0u8; short]; - st32(&mut cmd[0..], wire_pass::OPCODE_RENDER_PASS); - st32(&mut cmd[4..], short as u32); - let c = decode(&cmd).expect("well formed"); - assert_eq!(c.kind, Kind::RenderPass); - assert_eq!(c.pass_render_target_width, 0, "read past the payload"); -} - -/// The six pass-property records decode rather than reaching the catch-all. -/// -/// Every one sits inside the accepted opcode window, so before they were -/// named they were accepted, dropped and silent — which is exactly the -/// shape that hid the sampler-LOD binds. -#[test] -fn every_pass_property_record_reaches_an_arm_of_its_own() { - for (op, payload_len) in [ - (wire_pass::OPCODE_DEFAULT_RASTER_SAMPLE_COUNT, 4usize), - (wire_pass::OPCODE_RASTERIZATION_RATE_MAP, 4), - (wire_pass::OPCODE_IMAGEBLOCK_SAMPLE_LENGTH, 4), - (wire_pass::OPCODE_THREADGROUP_MEMORY_LENGTH, 4), - (wire_pass::OPCODE_TILE_SIZE, 4), - ] { - let total = OP_HEADER_LEN + payload_len; - let mut cmd = vec![0u8; total]; - st32(&mut cmd[0..], op); - st32(&mut cmd[4..], total as u32); - st32(&mut cmd[OP_HEADER_LEN..], 4); - let c = decode(&cmd).expect("well formed"); - assert_eq!(c.kind, Kind::RenderPassProperty, "opcode {op:#x}"); - if op == wire_pass::OPCODE_RASTERIZATION_RATE_MAP { - assert_eq!(c.texture_ref, 4, "opcode {op:#x}: ref"); - } else { - assert_eq!(c.mode, 4, "opcode {op:#x}: scalar"); - } - // A header that claims to be the whole record carries no scalar, - // and that is a refusal rather than a zero. - let mut bare = vec![0u8; OP_HEADER_LEN]; - st32(&mut bare[0..], op); - st32(&mut bare[4..], OP_HEADER_LEN as u32); - assert!( - matches!(decode(&bare), Err(DecodeStatus::ErrBadLength)), - "opcode {op:#x}" - ); - } - - // Sample positions are head plus `count` pairs, and the count is guest - // data: one claiming more pairs than the record holds is refused. - let total = OP_HEADER_LEN + 4 + 2 * 8; - let mut cmd = vec![0u8; total]; - st32(&mut cmd[0..], wire_pass::OPCODE_SAMPLE_POSITIONS); - st32(&mut cmd[4..], total as u32); - st32(&mut cmd[OP_HEADER_LEN..], 2); - let c = decode(&cmd).expect("well formed"); - assert_eq!(c.kind, Kind::RenderPassProperty); - assert_eq!(c.count, 2); - st32(&mut cmd[OP_HEADER_LEN..], 0xffff_ffff); - assert!(matches!(decode(&cmd), Err(DecodeStatus::ErrBadLength))); -} - -#[test] -fn the_store_action_options_are_not_wider_store_actions() { - use crate::protocol::endian::{st32, st64}; - use reims_vgpu_wire::ops::render as wire; - - for (op, wire_op) in [ - ( - wire::OPCODE_SET_COLOR_STORE_ACTION_OPTIONS, - wire::OPCODE_SET_COLOR_STORE_ACTION_OPTIONS, - ), - ( - wire::OPCODE_SET_DEPTH_STORE_ACTION_OPTIONS, - wire::OPCODE_SET_DEPTH_STORE_ACTION_OPTIONS, - ), - ( - wire::OPCODE_SET_STENCIL_STORE_ACTION_OPTIONS, - wire::OPCODE_SET_STENCIL_STORE_ACTION_OPTIONS, - ), - ( - wire::OPCODE_SET_TESSELLATION_FACTOR_BUFFER, - wire::OPCODE_SET_TESSELLATION_FACTOR_BUFFER, - ), - ] { - assert_eq!(op, wire_op, "the serializer writes a different opcode"); - } - - // Each options opcode is exactly one above its store action, and the - // two are different records at different lengths. Asserting the - // adjacency keeps a future edit from collapsing them into one arm. - for (action, options) in [ - ( - wire::OPCODE_SET_COLOR_STORE_ACTION, - wire::OPCODE_SET_COLOR_STORE_ACTION_OPTIONS, - ), - ( - wire::OPCODE_SET_DEPTH_STORE_ACTION, - wire::OPCODE_SET_DEPTH_STORE_ACTION_OPTIONS, - ), - ( - wire::OPCODE_SET_STENCIL_STORE_ACTION, - wire::OPCODE_SET_STENCIL_STORE_ACTION_OPTIONS, - ), - ] { - assert_eq!(options, action + 1); - } - - // The colour form. The index is at +8; a `u32` read of the options - // would leave it at +4 and find the options' own high half. - let total = wire::SET_COLOR_STORE_ACTION_OPTIONS_TOTAL_LEN as usize; - let mut v = hdr(wire::OPCODE_SET_COLOR_STORE_ACTION_OPTIONS, total); - st64(&mut v[OP_HEADER_LEN..], 0x1111); - st32(&mut v[OP_HEADER_LEN + 8..], 3); - let c = decode(&v).expect("colour store action options"); - assert_eq!(c.kind, Kind::SetStoreActionOptions); - assert_eq!( - (c.mode, c.first), - (0x1111, 3), - "the options and the attachment index are crossed" - ); - - // Depth and stencil have one attachment each and carry no index, so - // their record is four bytes shorter than the colour form's. - let total = wire::SET_STORE_ACTION_OPTIONS_TOTAL_LEN as usize; - assert_eq!( - total + 4, - wire::SET_COLOR_STORE_ACTION_OPTIONS_TOTAL_LEN as usize - ); - for (op, options) in [ - (wire::OPCODE_SET_DEPTH_STORE_ACTION_OPTIONS, 0x2222u64), - (wire::OPCODE_SET_STENCIL_STORE_ACTION_OPTIONS, 0x3333), - ] { - let mut v = hdr(op, total); - st64(&mut v[OP_HEADER_LEN..], options); - let c = decode(&v).unwrap_or_else(|e| panic!("op {op:#x}: {e:?}")); - assert_eq!(c.kind, Kind::SetStoreActionOptions); - assert_eq!(c.mode, options, "op {op:#x}"); - assert_eq!(c.first, 0, "op {op:#x} invented an attachment index"); - } - - // `0x7a`: ref, then two `u64` that differ, so a crossed pair shows. - let total = wire::SET_TESSELLATION_FACTOR_BUFFER_TOTAL_LEN as usize; - let mut v = hdr(wire::OPCODE_SET_TESSELLATION_FACTOR_BUFFER, total); - st32(&mut v[OP_HEADER_LEN..], 5151); - st64(&mut v[OP_HEADER_LEN + 4..], 0x3456); - st64(&mut v[OP_HEADER_LEN + 12..], 0x4567); - let c = decode(&v).expect("tessellation factor buffer"); - assert_eq!(c.kind, Kind::SetTessellationFactorBuffer); - assert_eq!( - (c.buffer_ref, c.buffer_offset), - (5151, 0x3456), - "read as a bind header rather than as a ref and an offset" - ); - - for (op, total) in [ - ( - wire::OPCODE_SET_COLOR_STORE_ACTION_OPTIONS, - wire::SET_COLOR_STORE_ACTION_OPTIONS_TOTAL_LEN as usize, - ), - ( - wire::OPCODE_SET_DEPTH_STORE_ACTION_OPTIONS, - wire::SET_STORE_ACTION_OPTIONS_TOTAL_LEN as usize, - ), - ( - wire::OPCODE_SET_STENCIL_STORE_ACTION_OPTIONS, - wire::SET_STORE_ACTION_OPTIONS_TOTAL_LEN as usize, - ), - ( - wire::OPCODE_SET_TESSELLATION_FACTOR_BUFFER, - wire::SET_TESSELLATION_FACTOR_BUFFER_TOTAL_LEN as usize, - ), - ] { - assert_eq!( - decode(&hdr(op, total - 4)).unwrap_err(), - DecodeStatus::ErrBadLength, - "op {op:#x} accepted a record four bytes short" - ); - } -} - -/// The nine tile-shader opcodes leave the catch-all. -/// -/// All nine were `Kind::OtherAccepted` together, so a guest running a tile -/// shader produced one deduped line naming a number and nothing that said a -/// dispatch or a bind had been lost. They are checked here against -/// `reims_vgpu_wire::ops::tile`'s constants, which fixtures pin against -/// bytes Apple's serializer produced. -/// -/// Every value is distinct, because four of the five bind opcodes share a -/// record shape and differ only in entry stride: a decoder that took -/// `0xa0`'s twelve-byte entry for `0x9f`'s four would accept a record it -/// should refuse, and one that read `0x9e` as a bind header would take the -/// low half of its 64-bit offset as a count. -#[test] -fn a_tile_record_is_decoded_rather_than_accepted_without_a_claim() { - use crate::protocol::endian::{st32, st64}; - use reims_vgpu_wire::ops::tile as wire_tile; - - // The local constants and the serializer's, held together so neither - // can drift. This is the check that would have caught `0x86`/`0x87`. - for (op, wire_op) in [ - ( - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE, - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE, - ), - ( - wire_tile::OPCODE_SET_TILE_BUFFER, - wire_tile::OPCODE_SET_TILE_BUFFER, - ), - ( - wire_tile::OPCODE_SET_TILE_BUFFER_OFFSET, - wire_tile::OPCODE_SET_TILE_BUFFER_OFFSET, - ), - ( - wire_tile::OPCODE_SET_TILE_SAMPLER, - wire_tile::OPCODE_SET_TILE_SAMPLER, - ), - ( - wire_tile::OPCODE_SET_TILE_SAMPLER_LOD, - wire_tile::OPCODE_SET_TILE_SAMPLER_LOD, - ), - ( - wire_tile::OPCODE_SET_TILE_TEXTURE, - wire_tile::OPCODE_SET_TILE_TEXTURE, - ), - ( - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION, - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION, - ), - ( - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION_RT_INDEX, - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION_RT_INDEX, - ), - ( - wire_tile::OPCODE_GET_TILE_DIMENSIONS, - wire_tile::OPCODE_GET_TILE_DIMENSIONS, - ), - ( - wire_tile::OPCODE_SET_TILE_THREADGROUP_MEMORY, - wire_tile::OPCODE_SET_TILE_THREADGROUP_MEMORY, - ), - ] { - assert_eq!(op, wire_op, "the serializer writes a different opcode"); - } - - // `0x9c`: length, offset, index. Three distinct values, because a - // decoder that took the compute encoder's two-field namesake would read - // the offset's low half as the index. - let total = wire_tile::SET_TILE_THREADGROUP_MEMORY_TOTAL_LEN as usize; - let mut v = hdr(wire_tile::OPCODE_SET_TILE_THREADGROUP_MEMORY, total); - st64(&mut v[OP_HEADER_LEN..], 0x1234); - st64(&mut v[OP_HEADER_LEN + 8..], 0x2345); - st32(&mut v[OP_HEADER_LEN + 16..], 5); - let c = decode(&v).expect("tile threadgroup memory"); - assert_eq!(c.kind, Kind::TileBind); - assert_eq!((c.first, c.count), (5, 1)); - - // `0x9b`: three unnarrowed `u64`, none of them equal. - let total = wire_tile::DISPATCH_THREADS_PER_TILE_TOTAL_LEN as usize; - let mut v = hdr(wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE, total); - st64(&mut v[OP_HEADER_LEN..], 0x11); - st64(&mut v[OP_HEADER_LEN + 8..], 0x22); - st64(&mut v[OP_HEADER_LEN + 16..], 0x33); - let c = decode(&v).expect("tile dispatch"); - assert_eq!(c.kind, Kind::TileDispatch); - assert_eq!(c.tile_threads, [0x11, 0x22, 0x33]); - - // `0xa2`/`0xa3`: the same nine `u64`, the grid first and the region - // origin-before-size. Only `0xa3` writes the trailing `u32`, so the - // decoder must read neither -- set those four bytes and require the - // answer not to move on either opcode. - let total = wire_tile::DISPATCH_THREADS_PER_TILE_IN_REGION_TOTAL_LEN as usize; - for op in [ - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION, - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION_RT_INDEX, - ] { - let mut v = hdr(op, total); - for (i, value) in [0x11u64, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99] - .into_iter() - .enumerate() - { - st64(&mut v[OP_HEADER_LEN + i * 8..], value); - } - let c = decode(&v).expect("tile region dispatch"); - assert_eq!(c.kind, Kind::TileDispatch); - assert_eq!( - c.tile_threads, - [0x11, 0x22, 0x33], - "op {op:#x} took the region's origin for the grid" - ); - - let mut noisy = v.clone(); - noisy[OP_HEADER_LEN + wire_tile::REGION_RT_INDEX_OFFSET..][..4].fill(0xff); - assert_eq!( - decode(&noisy).expect("tile region dispatch"), - c, - "op {op:#x} let the trailing render-target index reach a field; on \ - 0xa2 those four bytes are the guest's ring" - ); - } - - // `0xa4`: a ref then a 64-bit offset, and it is a readback rather than - // a bind -- the buffer is where the *host* writes. - let total = wire_tile::GET_TILE_DIMENSIONS_TOTAL_LEN as usize; - let mut v = hdr(wire_tile::OPCODE_GET_TILE_DIMENSIONS, total); - st32(&mut v[OP_HEADER_LEN..], 5151); - st64(&mut v[OP_HEADER_LEN + 4..], 0x9999); - let c = decode(&v).expect("tile dimensions query"); - assert_eq!(c.kind, Kind::TileDimensionsQuery); - assert_eq!((c.buffer_ref, c.buffer_offset), (5151, 0x9999)); - - // `0x9e`: index then a 64-bit offset. Not a bind header -- a decoder - // that read one would take the offset's low half as a count. - let total = wire_tile::SET_TILE_BUFFER_OFFSET_TOTAL_LEN as usize; - let mut v = hdr(wire_tile::OPCODE_SET_TILE_BUFFER_OFFSET, total); - st32(&mut v[OP_HEADER_LEN..], 4); - st64(&mut v[OP_HEADER_LEN + 4..], 0x2345); - let c = decode(&v).expect("tile buffer offset"); - assert_eq!(c.kind, Kind::TileBind); - assert_eq!((c.first, c.count, c.buffer_offset), (4, 1, 0x2345)); - - // The four bind opcodes, each at its own entry stride. A two-slot - // record is built at the right size and accepted, and the same record - // one entry short is refused -- which is what separates "knows the - // stride" from "accepts anything with a plausible head". - for (op, entry_size) in [ - (wire_tile::OPCODE_SET_TILE_BUFFER, BUFFER_BIND_ENTRY_SIZE), - (wire_tile::OPCODE_SET_TILE_TEXTURE, REF_BIND_ENTRY_SIZE), - (wire_tile::OPCODE_SET_TILE_SAMPLER, REF_BIND_ENTRY_SIZE), - ( - wire_tile::OPCODE_SET_TILE_SAMPLER_LOD, - SAMPLER_LOD_BIND_ENTRY_SIZE, - ), - ] { - let total = OP_HEADER_LEN + BIND_ENTRIES + 2 * entry_size; - let mut v = hdr(op, total); - st32(&mut v[OP_HEADER_LEN + BIND_FIRST..], 7); - st32(&mut v[OP_HEADER_LEN + BIND_COUNT..], 2); - let c = decode(&v).unwrap_or_else(|e| panic!("op {op:#x}: {e:?}")); - assert_eq!(c.kind, Kind::TileBind, "op {op:#x}"); - assert_eq!((c.first, c.count), (7, 2), "op {op:#x}"); - - let mut short = hdr(op, total - entry_size); - st32(&mut short[OP_HEADER_LEN + BIND_FIRST..], 7); - st32(&mut short[OP_HEADER_LEN + BIND_COUNT..], 2); - assert_eq!( - decode(&short).unwrap_err(), - DecodeStatus::ErrShort, - "op {op:#x} accepted a two-slot bind holding one entry" - ); - - // A zero count is not a bind; it is a record whose head does not - // describe itself, the same refusal the other stages give. - let mut empty = hdr(op, OP_HEADER_LEN + BIND_ENTRIES); - st32(&mut empty[OP_HEADER_LEN + BIND_COUNT..], 0); - assert_eq!( - decode(&empty).unwrap_err(), - DecodeStatus::ErrBadLength, - "op {op:#x} accepted a bind of no slots" - ); - } - - // The fixed-length forms are refused at any other length rather than - // read short. - for (op, total) in [ - ( - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE, - wire_tile::DISPATCH_THREADS_PER_TILE_TOTAL_LEN as usize, - ), - ( - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION, - wire_tile::DISPATCH_THREADS_PER_TILE_IN_REGION_TOTAL_LEN as usize, - ), - ( - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION_RT_INDEX, - wire_tile::DISPATCH_THREADS_PER_TILE_IN_REGION_TOTAL_LEN as usize, - ), - ( - wire_tile::OPCODE_SET_TILE_BUFFER_OFFSET, - wire_tile::SET_TILE_BUFFER_OFFSET_TOTAL_LEN as usize, - ), - ( - wire_tile::OPCODE_GET_TILE_DIMENSIONS, - wire_tile::GET_TILE_DIMENSIONS_TOTAL_LEN as usize, - ), - ( - wire_tile::OPCODE_SET_TILE_THREADGROUP_MEMORY, - wire_tile::SET_TILE_THREADGROUP_MEMORY_TOTAL_LEN as usize, - ), - ] { - assert_eq!( - decode(&hdr(op, total - 4)).unwrap_err(), - DecodeStatus::ErrBadLength, - "op {op:#x} accepted a record four bytes short" - ); - } -} - -/// The two indirect draws and the visibility mode leave the catch-all. -/// -/// All three were `Kind::OtherAccepted`, which is an `Ok` that means "no arm -/// claimed this" -- so a guest's indirect draw produced one deduped line -/// naming a raw opcode and nothing that said a draw had been lost. -/// -/// Every field here is a distinct value on purpose. Two of these three -/// records put an argument on the wire in the reverse of its selector -/// order, and `0x11` names two buffers and two offsets that are all the -/// same widths, so a decoder that crossed any pair would read back -/// plausible numbers and draw the wrong thing. Only distinct values catch -/// that, and the layouts they are checked against are -/// `reims_vgpu_wire::ops::render`'s, pinned by fixtures. -#[test] -fn an_indirect_draw_is_decoded_rather_than_accepted_without_a_claim() { - use crate::protocol::endian::{st16, st32, st64}; - use reims_vgpu_wire::ops::render as wire; - - for (op, wire_op) in [ - (wire::OPCODE_DRAW_INDIRECT, wire::OPCODE_DRAW_INDIRECT), - ( - wire::OPCODE_DRAW_INDEXED_INDIRECT, - wire::OPCODE_DRAW_INDEXED_INDIRECT, - ), - ( - wire::OPCODE_SET_VISIBILITY_RESULT_MODE, - wire::OPCODE_SET_VISIBILITY_RESULT_MODE, - ), - ] { - assert_eq!(op, wire_op, "the serializer writes a different opcode"); - } - - // `0x10`: offset first, then the buffer, then a 16-bit primitive type. - let total = wire::DRAW_INDIRECT_TOTAL_LEN as usize; - let mut v = hdr(wire::OPCODE_DRAW_INDIRECT, total); - st64(&mut v[OP_HEADER_LEN..], 0x1111); - st32(&mut v[OP_HEADER_LEN + 8..], 5151); - st16(&mut v[OP_HEADER_LEN + 12..], 3); - let c = decode(&v).expect("indirect draw"); - assert_eq!(c.kind, Kind::DrawIndirect); - assert_eq!(c.indirect_buffer_offset, 0x1111); - assert_eq!(c.indirect_buffer_ref, 5151); - assert_eq!(c.primitive_type, 3); - // The two bytes above `primitive_type` are never written by the - // serializer, so a wider read would take them. Set them and require the - // answer not to move; `no_decoder_reads_a_bit_apples_serializer_never_wrote` - // makes the same check against Apple's own measured mask. - let mut noisy = v.clone(); - noisy[OP_HEADER_LEN + 14] = 0xff; - noisy[OP_HEADER_LEN + 15] = 0xff; - assert_eq!( - decode(&noisy).expect("indirect draw"), - c, - "the record's unwritten tail reached a field" - ); - - // `0x11`: both types lead as `u16`, both refs follow as `u32`, both - // offsets trail as `u64` -- the blit family's shape, not `0x10`'s. - let total = wire::DRAW_INDEXED_INDIRECT_TOTAL_LEN as usize; - let mut v = hdr(wire::OPCODE_DRAW_INDEXED_INDIRECT, total); - st16(&mut v[OP_HEADER_LEN..], 4); - st16(&mut v[OP_HEADER_LEN + 2..], 1); - st32(&mut v[OP_HEADER_LEN + 4..], 5151); - st32(&mut v[OP_HEADER_LEN + 8..], 5252); - st64(&mut v[OP_HEADER_LEN + 12..], 0x1111); - st64(&mut v[OP_HEADER_LEN + 20..], 0x2222); - let c = decode(&v).expect("indexed indirect draw"); - assert_eq!(c.kind, Kind::DrawIndirect); - assert_eq!(c.primitive_type, 4); - assert_eq!(c.index_type, 1, "index type read out of the primitive type"); - assert_eq!((c.index_buffer_ref, c.indirect_buffer_ref), (5151, 5252)); - assert_eq!( - (c.index_buffer_offset, c.indirect_buffer_offset), - (0x1111, 0x2222), - "the two offsets are crossed" - ); - - // `0x84`: offset first, mode second, reversing the selector. - let total = wire::SET_VISIBILITY_RESULT_MODE_TOTAL_LEN as usize; - let mut v = hdr(wire::OPCODE_SET_VISIBILITY_RESULT_MODE, total); - st64(&mut v[OP_HEADER_LEN..], 0x1234); - st64(&mut v[OP_HEADER_LEN + 8..], 2); - let c = decode(&v).expect("visibility result mode"); - assert_eq!(c.kind, Kind::SetVisibilityResultMode); - assert_eq!( - (c.visibility_result_offset, c.mode), - (0x1234, 2), - "mode and offset are swapped" - ); - - // Each is a fixed length the serializer always writes, so a record that - // is not that length is refused rather than read short. - for (op, total) in [ - ( - wire::OPCODE_DRAW_INDIRECT, - wire::DRAW_INDIRECT_TOTAL_LEN as usize, - ), - ( - wire::OPCODE_DRAW_INDEXED_INDIRECT, - wire::DRAW_INDEXED_INDIRECT_TOTAL_LEN as usize, - ), - ( - wire::OPCODE_SET_VISIBILITY_RESULT_MODE, - wire::SET_VISIBILITY_RESULT_MODE_TOTAL_LEN as usize, - ), - ] { - assert_eq!( - decode(&hdr(op, total - 4)).unwrap_err(), - DecodeStatus::ErrBadLength, - "op {op:#x} accepted a record four bytes short" - ); - } -} - -/// The plural viewport and scissor records are the singular ones behind a -/// count, and the two counts are not the same width. -/// -/// Eight bytes for scissor, four for viewport -- from selectors that both -/// declare `Q`, so only the capture settles it. Borrowing either constant -/// for the other reads the first entry four bytes off, which for a scissor -/// is `x` taken from the high half of the count. -#[test] -fn a_plural_viewport_or_scissor_is_the_singular_record_behind_its_own_count() { - use crate::protocol::endian::{st32, st64}; - use reims_vgpu_wire::ops::render as wire; - - assert_eq!( - wire::OPCODE_SET_SCISSOR_RECTS, - wire::OPCODE_SET_SCISSOR_RECTS - ); - assert_eq!(wire::OPCODE_SET_VIEWPORTS, wire::OPCODE_SET_VIEWPORTS); - assert_ne!( - SCISSOR_RECTS_COUNT_LEN, VIEWPORTS_COUNT_LEN, - "the two counts are different widths; that is the whole hazard" - ); - - // Two rects, and the *first* is the one this rail keeps. - let total = OP_HEADER_LEN + SCISSOR_RECTS_COUNT_LEN + 2 * SCISSOR_PAYLOAD_LEN; - let mut v = hdr(wire::OPCODE_SET_SCISSOR_RECTS, total); - st64(&mut v[OP_HEADER_LEN..], 2); - let e0 = OP_HEADER_LEN + SCISSOR_RECTS_COUNT_LEN; - for (i, val) in [0x11u64, 0x22, 0x33, 0x44].into_iter().enumerate() { - st64(&mut v[e0 + i * 8..], val); - } - let e1 = e0 + SCISSOR_PAYLOAD_LEN; - for (i, val) in [0x55u64, 0x66, 0x77, 0x88].into_iter().enumerate() { - st64(&mut v[e1 + i * 8..], val); - } - let c = decode(&v).expect("two scissor rects"); - assert_eq!(c.kind, Kind::SetScissor); - assert_eq!(c.count, 2); - assert_eq!( - c.scissors, - vec![ - ScissorRect { - x: 0x11, - y: 0x22, - width: 0x33, - height: 0x44 - }, - ScissorRect { - x: 0x55, - y: 0x66, - width: 0x77, - height: 0x88 - } - ], - "both rects, in the guest's order, at the record's own count width" - ); - - // Two viewports, four-byte count. - let total = OP_HEADER_LEN + VIEWPORTS_COUNT_LEN + 2 * 48; - let mut v = hdr(wire::OPCODE_SET_VIEWPORTS, total); - st32(&mut v[OP_HEADER_LEN..], 2); - let e0 = OP_HEADER_LEN + VIEWPORTS_COUNT_LEN; - for i in 0..6 { - st64(&mut v[e0 + i * 8..], (1.0f64 + i as f64).to_bits()); - } - for i in 0..6 { - st64(&mut v[e0 + 48 + i * 8..], (100.0f64 + i as f64).to_bits()); - } - let c = decode(&v).expect("two viewports"); - assert_eq!(c.kind, Kind::SetViewport); - assert_eq!(c.count, 2); - assert_eq!( - c.viewports, - vec![ - [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], - [100.0, 101.0, 102.0, 103.0, 104.0, 105.0] - ], - "the second viewport is the guest's second, not a copy of the first" - ); - - // A count of zero names no rect, and a record that cannot hold the - // count it claims is refused rather than read short. - let mut v = hdr( - wire::OPCODE_SET_SCISSOR_RECTS, - OP_HEADER_LEN + SCISSOR_RECTS_COUNT_LEN, - ); - st64(&mut v[OP_HEADER_LEN..], 0); - assert_eq!(decode(&v).unwrap_err(), DecodeStatus::ErrBadLength); - let mut v = hdr( - wire::OPCODE_SET_VIEWPORTS, - OP_HEADER_LEN + VIEWPORTS_COUNT_LEN + 48, - ); - st32(&mut v[OP_HEADER_LEN..], 2); - assert_eq!(decode(&v).unwrap_err(), DecodeStatus::ErrShort); - - // The singular opcodes keep reading from offset zero and report one. - let mut v = hdr( - wire::OPCODE_SET_SCISSOR, - OP_HEADER_LEN + SCISSOR_PAYLOAD_LEN, - ); - st64(&mut v[OP_HEADER_LEN..], 0x99); - let c = decode(&v).expect("singular scissor"); - assert_eq!(c.scissors.len(), 1); - assert_eq!(c.scissors[0].x, 0x99); - assert_eq!(c.count, 1); -} - -/// A sampler bind carrying LOD clamps is a bind, at a wider entry stride. -/// -/// `0x80` and `0x71` are not longer forms of `0x7f` and `0x70` — they are -/// separate opcodes, so this decoder knowing only the plain pair did not -/// lose the clamps, it lost the whole bind and left the slot empty. The -/// entry is twelve bytes here against four there, which is the assertion -/// that matters: reading a LOD record at the plain stride would take a -/// clamp for the next slot's sampler. -#[test] -fn a_sampler_bind_with_lod_clamps_is_still_a_sampler_bind() { - use crate::protocol::endian::st32; - use reims_vgpu_wire::ops::render as wire; - - assert_eq!( - wire::OPCODE_SET_VERTEX_SAMPLER_LOD, - wire::OPCODE_SET_VERTEX_SAMPLER_LOD - ); - assert_eq!( - wire::OPCODE_SET_FRAGMENT_SAMPLER_LOD, - wire::OPCODE_SET_FRAGMENT_SAMPLER_LOD - ); - - for (op, stage) in [ - (wire::OPCODE_SET_VERTEX_SAMPLER_LOD, Stage::Vertex), - (wire::OPCODE_SET_FRAGMENT_SAMPLER_LOD, Stage::Fragment), - ] { - const COUNT: u32 = 2; - let total = OP_HEADER_LEN + BIND_ENTRIES + (COUNT as usize) * SAMPLER_LOD_BIND_ENTRY_SIZE; - let mut v = hdr(op, total); - st32(&mut v[OP_HEADER_LEN + BIND_FIRST..], 3); - st32(&mut v[OP_HEADER_LEN + BIND_COUNT..], COUNT); - for i in 0..COUNT as usize { - let e = OP_HEADER_LEN + BIND_ENTRIES + i * SAMPLER_LOD_BIND_ENTRY_SIZE; - st32(&mut v[e..], 0x6363 + i as u32); - // A distinct clamp pair per entry. Both halves are lifted, and - // `runtime::exec` zips them against the refs by position — so a - // decoder that read one entry's clamps for another's slot, or read - // at the plain four-byte stride and took a clamp for a ref, has to - // fail here rather than downstream where the pairing is invisible. - st32(&mut v[e + 4..], 0x3e80_0000 + i as u32); // ~0.25 - st32(&mut v[e + 8..], 0x3f40_0000 + i as u32); // ~0.75 - } - - let c = decode(&v).unwrap_or_else(|e| panic!("op {op:#x}: {e:?}")); - assert_eq!(c.kind, Kind::SetSampler, "op {op:#x}"); - assert_eq!(c.stage, stage, "op {op:#x}"); - assert_eq!(c.first, 3, "op {op:#x}"); - assert_eq!( - c.ref_binds, - vec![0x6363, 0x6364], - "op {op:#x} read the entries at the wrong stride" - ); - assert_eq!( - c.sampler_lod_binds, - vec![(0x3e80_0000, 0x3f40_0000), (0x3e80_0001, 0x3f40_0001)], - "op {op:#x} lost the clamps or paired them with the wrong slot" - ); - assert_eq!(c.sampler_ref, 0x6363, "op {op:#x}"); - } - - // The plain forms keep the four-byte stride and carry no clamps at all, - // so the clamp list is empty rather than defaulted — and `exec`'s zip - // gives those slots `None` rather than a clamp the record never carried. - let total = OP_HEADER_LEN + BIND_ENTRIES + REF_BIND_ENTRY_SIZE; - let mut v = hdr(wire::OPCODE_SET_VERTEX_SAMPLER, total); - st32(&mut v[OP_HEADER_LEN + BIND_COUNT..], 1); - st32(&mut v[OP_HEADER_LEN + BIND_ENTRIES..], 0x6363); - let c = decode(&v).expect("plain sampler bind"); - assert_eq!(c.ref_binds, vec![0x6363]); - assert!( - c.sampler_lod_binds.is_empty(), - "a plain bind must not invent a clamp" - ); -} - -/// The accepted-opcode window ends exactly where Apple's render manifest -/// does, computed rather than transcribed. -/// -/// The accepted window ends at the highest opcode in the wire render -/// manifest (`OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE`). A capture that -/// adds a higher opcode fails here and names itself, rather than leaving -/// a stale bound that refuses real records as "Apple does not write". -#[test] -fn the_accepted_window_ends_where_apples_render_manifest_does() { - let highest = reims_vgpu_wire::manifest::MANIFEST - .iter() - .filter(|e| e.class == "PGSerializerRenderCommandEncoder") - .flat_map(|e| e.opcodes.iter().copied()) - .max() - .expect("the render encoder has opcodes in the manifest"); - assert_eq!( - wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE, - highest, - "a render opcode above the accepted window would be refused as one \ - Apple does not write" - ); -} - -/// Every render opcode Apple's serializer emits has a constant here, and -/// this module names no opcode Apple does not emit. -/// -/// [`wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE`] bounds the window and this fills it. The two catch -/// different failures, and the one this catches is the quieter: an opcode -/// *inside* the accepted window that no arm claims does not get refused, it -/// gets [`Kind::OtherAccepted`] — the catch-all whose `Ok` is not a decode, -/// and which is what hid the sampler-LOD binds `0x80`/`0x71` behind a -/// passing run. So a capture that adds `0x9b`..`0xa4` the way `TileShaders` -/// did lands below the window's end, breaks nothing, and loses every record -/// it names. -/// -/// The roster below is references rather than numbers, so no entry can -/// carry a wrong *value*; what this test adds is that no entry can go -/// *missing*. The reverse direction matters as much and is the shape of the -/// `0x86`/`0x87` residency bug: an opcode named here and absent from the -/// manifest is a number no capture supports. -/// -/// **`0x1a` used to be excluded from it, on a claim that was wrong.** This -/// doc said the render-pass descriptor was "the live descriptor this -/// device's own framing carries, not a record -/// `PGSerializerRenderCommandEncoder` writes, and the manifest agrees by -/// omitting it" — and the manifest omitted it only because no case had -/// driven `writeDescriptor`, which emits it. Six more opcodes arrived with -/// it, all of them pass properties behind a capability, and every one was -/// reaching the catch-all. -/// -/// The general form is worth keeping: **"the manifest agrees" is not -/// evidence when the manifest's silence is what is being explained.** An -/// opcode absent from a capture-derived roster can be an opcode nobody -/// captured. -/// -/// # Two decoded opcodes are deliberately outside this bijection -/// -/// `OPCODE_USE_HEAPS_NO_STAGES` (`0x86`) and `OPCODE_USE_RESOURCES_NO_STAGES` -/// (`0x87`) are decoded by this module and named in no manifest row, which the -/// reverse direction above would ordinarily call a number no capture supports. -/// They are the exception the manifest cannot express: the selectors behind them -/// are declared on the encoder base class, and the manifest is built per class -/// from each class's own method list, so no `PGSerializerRenderCommandEncoder` -/// row can ever carry them however many captures run. See the inheritance caveat -/// in [`reims_vgpu_wire::manifest`]. Adding them to the roster would fail this -/// test for a reason that is about the instrument rather than about the device, -/// so they stay out of it and are covered by -/// `the_inherited_residency_opcodes_reach_the_residency_arm` instead. -#[test] -fn the_render_opcode_table_is_exactly_apples_render_manifest() { - let device: &[(u32, &str)] = &[ - (wire::OPCODE_DRAW_WIDE, "wire::OPCODE_DRAW_WIDE"), - (wire::OPCODE_DRAW, "wire::OPCODE_DRAW"), - ( - wire::OPCODE_DRAW_INSTANCED_WIDE, - "wire::OPCODE_DRAW_INSTANCED_WIDE", - ), - (wire::OPCODE_DRAW_INSTANCED, "wire::OPCODE_DRAW_INSTANCED"), - ( - wire::OPCODE_DRAW_INSTANCED_BASE_WIDE, - "wire::OPCODE_DRAW_INSTANCED_BASE_WIDE", - ), - ( - wire::OPCODE_DRAW_INSTANCED_BASE, - "wire::OPCODE_DRAW_INSTANCED_BASE", - ), - ( - wire::OPCODE_DRAW_INDEXED_WIDE, - "wire::OPCODE_DRAW_INDEXED_WIDE", - ), - (wire::OPCODE_DRAW_INDEXED, "wire::OPCODE_DRAW_INDEXED"), - ( - wire::OPCODE_DRAW_INDEXED_INSTANCED_WIDE, - "wire::OPCODE_DRAW_INDEXED_INSTANCED_WIDE", - ), - ( - wire::OPCODE_DRAW_INDEXED_INSTANCED, - "wire::OPCODE_DRAW_INDEXED_INSTANCED", - ), - ( - wire::OPCODE_DRAW_INDEXED_INSTANCED_BASE_WIDE, - "wire::OPCODE_DRAW_INDEXED_INSTANCED_BASE_WIDE", - ), - ( - wire::OPCODE_DRAW_INDEXED_INSTANCED_BASE, - "wire::OPCODE_DRAW_INDEXED_INSTANCED_BASE", - ), - ( - wire::OPCODE_DRAW_PATCHES_WIDE, - "wire::OPCODE_DRAW_PATCHES_WIDE", - ), - (wire::OPCODE_DRAW_PATCHES, "wire::OPCODE_DRAW_PATCHES"), - ( - wire::OPCODE_DRAW_INDEXED_PATCHES, - "wire::OPCODE_DRAW_INDEXED_PATCHES", - ), - (wire::OPCODE_DRAW_INDIRECT, "wire::OPCODE_DRAW_INDIRECT"), - ( - wire::OPCODE_DRAW_INDEXED_INDIRECT, - "wire::OPCODE_DRAW_INDEXED_INDIRECT", - ), - ( - wire::OPCODE_DRAW_PATCHES_INDIRECT, - "wire::OPCODE_DRAW_PATCHES_INDIRECT", - ), - ( - wire::OPCODE_DRAW_INDEXED_PATCHES_INDIRECT, - "wire::OPCODE_DRAW_INDEXED_PATCHES_INDIRECT", - ), - ( - wire::OPCODE_EXECUTE_COMMANDS_INDIRECT, - "wire::OPCODE_EXECUTE_COMMANDS_INDIRECT", - ), - ( - wire::OPCODE_EXECUTE_COMMANDS_RANGE, - "wire::OPCODE_EXECUTE_COMMANDS_RANGE", - ), - ( - wire::OPCODE_MEMORY_BARRIER_RESOURCES, - "wire::OPCODE_MEMORY_BARRIER_RESOURCES", - ), - ( - wire::OPCODE_MEMORY_BARRIER_SCOPE, - "wire::OPCODE_MEMORY_BARRIER_SCOPE", - ), - (wire::OPCODE_UPDATE_FENCE, "wire::OPCODE_UPDATE_FENCE"), - (wire::OPCODE_WAIT_FOR_FENCE, "wire::OPCODE_WAIT_FOR_FENCE"), - (wire::OPCODE_USE_HEAP, "wire::OPCODE_USE_HEAP"), - (wire::OPCODE_SET_BLEND_COLOR, "wire::OPCODE_SET_BLEND_COLOR"), - ( - wire::OPCODE_SET_COLOR_STORE_ACTION, - "wire::OPCODE_SET_COLOR_STORE_ACTION", - ), - ( - wire::OPCODE_SET_COLOR_STORE_ACTION_OPTIONS, - "wire::OPCODE_SET_COLOR_STORE_ACTION_OPTIONS", - ), - ( - wire::OPCODE_SET_DEPTH_STENCIL_STATE, - "wire::OPCODE_SET_DEPTH_STENCIL_STATE", - ), - ( - wire::OPCODE_SET_DEPTH_STORE_ACTION, - "wire::OPCODE_SET_DEPTH_STORE_ACTION", - ), - ( - wire::OPCODE_SET_DEPTH_STORE_ACTION_OPTIONS, - "wire::OPCODE_SET_DEPTH_STORE_ACTION_OPTIONS", - ), - (wire::OPCODE_SET_CULL_MODE, "wire::OPCODE_SET_CULL_MODE"), - (wire::OPCODE_SET_DEPTH_BIAS, "wire::OPCODE_SET_DEPTH_BIAS"), - ( - wire::OPCODE_SET_DEPTH_CLIP_MODE, - "wire::OPCODE_SET_DEPTH_CLIP_MODE", - ), - ( - wire::OPCODE_SET_FRAGMENT_BUFFER, - "wire::OPCODE_SET_FRAGMENT_BUFFER", - ), - ( - wire::OPCODE_SET_FRAGMENT_BUFFER_OFFSET, - "wire::OPCODE_SET_FRAGMENT_BUFFER_OFFSET", - ), - ( - wire::OPCODE_SET_FRAGMENT_SAMPLER, - "wire::OPCODE_SET_FRAGMENT_SAMPLER", - ), - ( - wire::OPCODE_SET_FRAGMENT_SAMPLER_LOD, - "wire::OPCODE_SET_FRAGMENT_SAMPLER_LOD", - ), - ( - wire::OPCODE_SET_FRAGMENT_TEXTURE, - "wire::OPCODE_SET_FRAGMENT_TEXTURE", - ), - ( - wire::OPCODE_SET_FRONT_FACING, - "wire::OPCODE_SET_FRONT_FACING", - ), - ( - wire::OPCODE_SET_RENDER_PIPELINE_STATE, - "wire::OPCODE_SET_RENDER_PIPELINE_STATE", - ), - (wire::OPCODE_SET_SCISSOR, "wire::OPCODE_SET_SCISSOR"), - ( - wire::OPCODE_SET_SCISSOR_RECTS, - "wire::OPCODE_SET_SCISSOR_RECTS", - ), - ( - wire::OPCODE_SET_STENCIL_REFERENCE, - "wire::OPCODE_SET_STENCIL_REFERENCE", - ), - ( - wire::OPCODE_SET_STENCIL_STORE_ACTION, - "wire::OPCODE_SET_STENCIL_STORE_ACTION", - ), - ( - wire::OPCODE_SET_STENCIL_STORE_ACTION_OPTIONS, - "wire::OPCODE_SET_STENCIL_STORE_ACTION_OPTIONS", - ), - ( - wire::OPCODE_SET_TESSELLATION_FACTOR_BUFFER, - "wire::OPCODE_SET_TESSELLATION_FACTOR_BUFFER", - ), - ( - wire::OPCODE_SET_TESSELLATION_FACTOR_SCALE, - "wire::OPCODE_SET_TESSELLATION_FACTOR_SCALE", - ), - ( - wire::OPCODE_SET_TRIANGLE_FILL_MODE, - "wire::OPCODE_SET_TRIANGLE_FILL_MODE", - ), - ( - wire::OPCODE_SET_VERTEX_BUFFER, - "wire::OPCODE_SET_VERTEX_BUFFER", - ), - ( - wire::OPCODE_SET_VERTEX_BUFFER_OFFSET, - "wire::OPCODE_SET_VERTEX_BUFFER_OFFSET", - ), - ( - wire::OPCODE_SET_VERTEX_SAMPLER, - "wire::OPCODE_SET_VERTEX_SAMPLER", - ), - ( - wire::OPCODE_SET_VERTEX_SAMPLER_LOD, - "wire::OPCODE_SET_VERTEX_SAMPLER_LOD", - ), - ( - wire::OPCODE_SET_VERTEX_TEXTURE, - "wire::OPCODE_SET_VERTEX_TEXTURE", - ), - (wire::OPCODE_SET_VIEWPORT, "wire::OPCODE_SET_VIEWPORT"), - (wire::OPCODE_SET_VIEWPORTS, "wire::OPCODE_SET_VIEWPORTS"), - ( - wire::OPCODE_SET_VISIBILITY_RESULT_MODE, - "wire::OPCODE_SET_VISIBILITY_RESULT_MODE", - ), - (wire::OPCODE_TEXTURE_BARRIER, "wire::OPCODE_TEXTURE_BARRIER"), - (wire::OPCODE_SET_LINE_WIDTH, "wire::OPCODE_SET_LINE_WIDTH"), - (wire::OPCODE_USE_RESOURCE, "wire::OPCODE_USE_RESOURCE"), - ( - wire::OPCODE_SET_VERTEX_AMPLIFICATION_MODE, - "wire::OPCODE_SET_VERTEX_AMPLIFICATION_MODE", - ), - ( - wire::OPCODE_SET_VERTEX_AMPLIFICATION_COUNT, - "wire::OPCODE_SET_VERTEX_AMPLIFICATION_COUNT", - ), - ( - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE, - "wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE", - ), - ( - wire_tile::OPCODE_SET_TILE_THREADGROUP_MEMORY, - "wire_tile::OPCODE_SET_TILE_THREADGROUP_MEMORY", - ), - ( - wire_tile::OPCODE_SET_TILE_BUFFER, - "wire_tile::OPCODE_SET_TILE_BUFFER", - ), - ( - wire_tile::OPCODE_SET_TILE_BUFFER_OFFSET, - "wire_tile::OPCODE_SET_TILE_BUFFER_OFFSET", - ), - ( - wire_tile::OPCODE_SET_TILE_SAMPLER, - "wire_tile::OPCODE_SET_TILE_SAMPLER", - ), - ( - wire_tile::OPCODE_SET_TILE_SAMPLER_LOD, - "wire_tile::OPCODE_SET_TILE_SAMPLER_LOD", - ), - ( - wire_tile::OPCODE_SET_TILE_TEXTURE, - "wire_tile::OPCODE_SET_TILE_TEXTURE", - ), - ( - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION, - "wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION", - ), - ( - wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION_RT_INDEX, - "wire_tile::OPCODE_DISPATCH_THREADS_PER_TILE_IN_REGION_RT_INDEX", - ), - ( - wire_tile::OPCODE_GET_TILE_DIMENSIONS, - "wire_tile::OPCODE_GET_TILE_DIMENSIONS", - ), - ( - wire::OPCODE_SET_VERTEX_BUFFER_STRIDE, - "wire::OPCODE_SET_VERTEX_BUFFER_STRIDE", - ), - ( - wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE, - "wire::OPCODE_SET_VERTEX_BUFFER_OFFSET_STRIDE", - ), - ( - wire_pass::OPCODE_RENDER_PASS, - "wire_pass::OPCODE_RENDER_PASS", - ), - ( - wire_pass::OPCODE_DEFAULT_RASTER_SAMPLE_COUNT, - "wire_pass::OPCODE_DEFAULT_RASTER_SAMPLE_COUNT", - ), - ( - wire_pass::OPCODE_SAMPLE_POSITIONS, - "wire_pass::OPCODE_SAMPLE_POSITIONS", - ), - ( - wire_pass::OPCODE_RASTERIZATION_RATE_MAP, - "wire_pass::OPCODE_RASTERIZATION_RATE_MAP", - ), - ( - wire_pass::OPCODE_IMAGEBLOCK_SAMPLE_LENGTH, - "wire_pass::OPCODE_IMAGEBLOCK_SAMPLE_LENGTH", - ), - ( - wire_pass::OPCODE_THREADGROUP_MEMORY_LENGTH, - "wire_pass::OPCODE_THREADGROUP_MEMORY_LENGTH", - ), - (wire_pass::OPCODE_TILE_SIZE, "wire_pass::OPCODE_TILE_SIZE"), - ]; - - let mut apple: Vec = reims_vgpu_wire::manifest::MANIFEST - .iter() - .filter(|e| e.class == "PGSerializerRenderCommandEncoder") - .flat_map(|e| e.opcodes.iter().copied()) - .collect(); - apple.sort_unstable(); - apple.dedup(); - - for (op, name) in device { - assert!( - apple.contains(op), - "{name} = {op:#x} is an opcode Apple's render manifest does not \ - list, so no capture supports it" - ); - } - for op in &apple { - assert!( - device.iter().any(|(d, _)| d == op), - "Apple's serializer emits render opcode {op:#x} and this module \ - names no constant for it, so it reaches Kind::OtherAccepted and \ - every record carrying it is lost without a refusal" - ); - } - assert_eq!( - device.len(), - apple.len(), - "the roster has a duplicate entry" - ); -} - -/// Residency is four opcodes in two pairs, and the pairs are not interchangeable. -/// -/// `0x1b`/`0x89` are the `stages:`-qualified forms the render encoder declares -/// itself; `0x86`/`0x87` are the unqualified ones it inherits. The four numbers -/// must stay distinct, because their heads are three different sizes and reading -/// one record with another's layout starts the refs in the wrong place — -/// `a_residency_record_is_bounded_by_its_own_count` is what catches that, and it -/// can only catch it while the opcodes disagree. -#[test] -fn the_residency_opcodes_are_the_ones_apples_serializer_writes() { - use reims_vgpu_wire::ops::render as wire; - assert_eq!(wire::OPCODE_USE_HEAP, 0x1b); - assert_eq!(wire::OPCODE_USE_RESOURCE, 0x89); - assert_eq!(wire::OPCODE_USE_HEAPS_NO_STAGES, 0x86); - assert_eq!(wire::OPCODE_USE_RESOURCES_NO_STAGES, 0x87); - let all = [ - wire::OPCODE_USE_HEAP, - wire::OPCODE_USE_RESOURCE, - wire::OPCODE_USE_HEAPS_NO_STAGES, - wire::OPCODE_USE_RESOURCES_NO_STAGES, - ]; - for (i, a) in all.iter().enumerate() { - for b in &all[i + 1..] { - assert_ne!(a, b, "two residency forms share one opcode"); - } - } -} - -/// The refs of a residency record start at a different offset on each form, -/// and the count-led extent is checked rather than assumed. -/// -/// `useHeap:` puts its array at `+6`, which is not a multiple of four: a -/// record read with `useResource:`'s `+8` accepts two bytes fewer than it -/// needs, so the length check is what separates the two layouts. -#[test] -fn a_residency_record_is_bounded_by_its_own_count() { - for (op, refs_at, kind) in [ - ( - wire::OPCODE_USE_RESOURCE, - USE_RESOURCE_REFS, - Kind::UseResource, - ), - (wire::OPCODE_USE_HEAP, USE_HEAP_REFS, Kind::UseHeap), - ( - wire::OPCODE_USE_RESOURCES_NO_STAGES, - USE_RESOURCES_NO_STAGES_REFS, - Kind::UseResource, - ), - ( - wire::OPCODE_USE_HEAPS_NO_STAGES, - USE_HEAPS_NO_STAGES_REFS, - Kind::UseHeap, - ), - ] { - let body = |count: u32, entries: usize| { - let mut v = hdr(op, OP_HEADER_LEN + refs_at + entries * REF_BIND_ENTRY_SIZE); - st32(&mut v[OP_HEADER_LEN + RESIDENCY_COUNT..], count); - v - }; - - let c = decode(&body(2, 2)).unwrap_or_else(|e| panic!("op {op:#x}: {e:?}")); - assert_eq!(c.kind, kind, "op {op:#x}"); - assert_eq!(c.count, 2, "op {op:#x}"); - - // One entry short of what the count claims. - assert_eq!( - decode(&body(2, 1)).unwrap_err(), - DecodeStatus::ErrShort, - "op {op:#x} accepted a record one ref shorter than its count" - ); - // Past the bind cap and still well-formed. This record names no - // table slot, so a bind-table cap is not its bound; refusing here - // would drop a residency declaration a guest may legitimately make. - let big = 40u32; - let c = decode(&body(big, big as usize)) - .unwrap_or_else(|e| panic!("op {op:#x} refused {big} resources: {e:?}")); - assert_eq!(c.count, big, "op {op:#x}"); - // A count whose byte length overflows `usize` must not wrap into a - // bound the record satisfies. - assert_eq!( - decode(&body(u32::MAX, 1)).unwrap_err(), - DecodeStatus::ErrShort, - "op {op:#x} accepted a count whose array cannot exist" - ); - // Shorter than the form's own head. Written against `refs_at` rather - // than a literal, because the four forms have three different head - // sizes and the smallest of them is four bytes — a literal 4 here is a - // *valid* empty `useHeaps:count:` record, not a truncated one. - assert_eq!( - decode(&hdr(op, OP_HEADER_LEN + refs_at - 1)).unwrap_err(), - DecodeStatus::ErrShort, - "op {op:#x} accepted a record shorter than its own head" - ); - } -} - -/// `0x86` and `0x87` reach the residency arm, not the catch-all. -/// -/// This test used to assert the opposite, and the reason it gave was sound at -/// the time: the residency kinds had no executor arm, so reading these two as -/// residency removed them from `Kind::OtherAccepted` — the one net that would -/// have named them on the failure channel. Both halves of that have since -/// changed. `runtime::exec` answers `UseResource`/`UseHeap` with -/// a residency route, so the kind is a counter rather than a hole; -/// and the numbers are not a guess but the two forms of residency a render -/// encoder inherits from the encoder base class, which -/// [`reims_vgpu_wire::ops::render::UseHeapsNoStages`] records. -/// -/// So the net they belong in is the counter, and leaving them in the catch-all -/// reported an implemented command as unimplemented while -/// the residency routes counted half their family. -#[test] -fn the_inherited_residency_opcodes_reach_the_residency_arm() { - for (op, kind) in [ - (wire::OPCODE_USE_HEAPS_NO_STAGES, Kind::UseHeap), - (wire::OPCODE_USE_RESOURCES_NO_STAGES, Kind::UseResource), - ] { - let c = decode(&hdr(op, OP_HEADER_LEN + 16)).unwrap_or_else(|e| panic!("{op:#x}: {e:?}")); - assert_eq!(c.kind, kind, "{op:#x} did not reach the residency arm"); - } -} - -#[test] -fn property_fuzz() { - for op in 0u32..0x120 { - for len in [8usize, 12, 16, 24, 32, 48, 64] { - let _ = decode(&hdr(op, len)); - } - } -} - - - -// --- The three `runtime::decode::ledger` cross-checks that named this -// --- decoder. All three are superseded by -// --- `every_render_row_reaches_exactly_one_decoder_and_the_ledger_picks_it`, -// --- which asks both directions where these asked one each. - -#[test] -fn the_render_decoder_recognises_every_render_operation_the_ledger_records() { - use super::render::{decode, DecodeStatus}; - for op in LEDGER - .iter() - .filter(|o| o.rail == Rail::Render) - .filter_map(|o| o.opcode) - { - let refused_the_opcode = matches!( - decode(&zero_record(op, GENEROUS_PAYLOAD)), - Err(DecodeStatus::ErrUnknownOpcode) | Err(DecodeStatus::ErrUnsupportedOpcode) - ); - assert!( - !refused_the_opcode, - "the closure ledger records render {op:#x} and this rail's decoder \ - refuses the opcode itself: one of the two is describing an \ - operation the other says does not exist" - ); - } -} - -/// Recognising an opcode is not claiming it. -/// -/// The render decoder accepts a contiguous range and falls through to -/// `Kind::OtherAccepted` inside it, which is how an opcode can be accepted with -/// no arm decoding it — and the rail then reports the record as -/// `accepted_without_executor` and drops it. That is precisely the state the -/// opcode-recognition test above cannot see, because a fall-through is not a -/// refusal. So this is the sharper claim: an operation the ledger judges must -/// reach an arm that names what it is. -/// -/// A record that decodes under none of [`probe_records`]' spellings is -/// inconclusive rather than a failure: this test is about which arm claims an -/// opcode, not about whether this file can synthesise a legal record for every -/// family. The reached count is printed rather than asserted, because it is a -/// property of the probe. -#[test] -fn no_render_operation_the_ledger_judges_decodes_as_unclaimed() { - use super::render::{decode, Kind}; - let mut conclusive = 0usize; - for op in LEDGER - .iter() - .filter(|o| o.rail == Rail::Render) - .filter_map(|o| o.opcode) - { - let Some(cmd) = probe_records(op).find_map(|r| decode(&r).ok()) else { - continue; - }; - conclusive += 1; - assert_ne!( - cmd.kind, - Kind::OtherAccepted, - "the closure ledger judges render {op:#x} and the decoder has no arm for it, so the \ - rail reports it as accepted-without-executor and drops it whatever the ledger says" - ); - } - println!("{conclusive} of the ledger's render operations reached a decode arm"); -} - -/// The other direction on the one rail that can state its own window. -/// -/// The render decoder accepts a contiguous opcode range and falls through to -/// `Kind::OtherAccepted` inside it, so an opcode can be *accepted* without any -/// arm claiming it — which is a decodable operation the device drops. Those are -/// numbers rather than known selectors, so the ledger does not carry rows for -/// them; what it must not do is disagree about the window's edge, because an -/// operation the ledger judges must be inside it. -#[test] -fn no_ledger_operation_sits_outside_the_render_encoder_window() { - use super::render::opcode_above_the_encoder_window; - for op in LEDGER - .iter() - .filter(|o| o.rail == Rail::Render) - .filter_map(|o| o.opcode) - { - assert!( - !opcode_above_the_encoder_window(op), - "render {op:#x} is judged by the ledger and above the window this \ - rail accepts, so the judgement can never be acted on" - ); - } -} diff --git a/crates/reims-vgpu/src/dead/stream_framer.rs b/crates/reims-vgpu/src/dead/stream_framer.rs deleted file mode 100644 index 85f80e888..000000000 --- a/crates/reims-vgpu/src/dead/stream_framer.rs +++ /dev/null @@ -1,795 +0,0 @@ -// DISCONNECTED SOURCE — this file does not compile, is not feature-gated, and -// is not linkable. No `mod` declaration reaches `dead/`. It is here to be read. -// -// What this was: this device's own command-stream framer, -// `runtime::decode::stream`. It located segments, located the records inside -// one, and re-validated an already-parsed `Segment` against the buffer on every -// record — sixteen `stream_reval_*` refusals guarding a state a caller should -// not have been able to construct. -// -// Why it went, three reasons: -// -// * `reims_vgpu_protocol::segment::SegmentStream` frames segments and -// `reims_vgpu_wire::op::OpStream` frames the records inside one. Both live -// in the layers that own those layouts. -// * `FramedSegment` carries its command window as a *slice*, so a segment -// cannot claim bytes the buffer does not hold. The whole `validate_segment` -// family is gone with the state it guarded, not merely moved. -// * `decode_next_segment` found each segment's index with -// `segment_index_for_offset`, which re-walks the stream from zero. That is -// quadratic in the segment count, and a driven boot puts ninety-five -// thousand segments in a stream. `SegmentStream` counts the index it -// already knows. -// -// THE ONE BEHAVIOUR CHANGE, recorded here because this is where a reader will -// come looking for it: an unknown segment type. This framer reported it and -// walked on to the next segment. `SegmentStream` stops. The reason is on -// `FramingRefusal::UnknownType` — a family whose record framing is unknown can -// only be skipped on its declared length, and skipping on that hands the -// following segment an encoder state derived from bytes nothing here -// understands. `segment_disposition`'s own doc, below, records that the -// reference host "rejects new non-continuation types >= 4" rather than stepping -// over them, so stopping is the closer reading of the host being imitated. -// -// Do not resurrect any of this. If a boot regresses on a stream this framer -// walked and `SegmentStream` refuses, read it here and fix -// `reims_vgpu_protocol::segment`. - -//! Command-stream framing decoder (port of `host/utils/reims-vgpu-stream-decode`). - -use crate::protocol::checked::size_fits_u32; -use crate::protocol::endian::ld32; - -// Segment types and header length from `reims-vgpu-wire` (observed serializer -// surface). Re-exported so stream walkers share one path with the wire crate. -// -// `SEGMENT_TYPE_INFO` is 4, not the next integer in sequence — a guess would -// write 3, which is `SEGMENT_TYPE_EVENT` and comes from `reims-vgpu-protocol` -// below. Protection options joined once the capture drove that envelope. -use reims_vgpu_wire::ops::segment as wire_segment; -pub use reims_vgpu_wire::ops::segment::{ - SEGMENT_HEADER_LEN, SEGMENT_TYPE_BLIT, SEGMENT_TYPE_COMPUTE, SEGMENT_TYPE_INFO, - SEGMENT_TYPE_PROTECTION_OPTIONS, SEGMENT_TYPE_RENDER, -}; - -// The one type the wire crate deliberately does not name, because its capture -// has never driven the encoder that writes it. It is not this module's either: -// naming a value no fixture wrote is assigning a meaning, and -// `reims-vgpu-protocol` is the layer that does that. It re-derives it there -// from the deserializer's contiguous `0..=3` decoder set, and this is the -// re-export so the two readings cannot drift. -pub use reims_vgpu_protocol::segment::SEGMENT_TYPE_EVENT; - -/// Segment-header field offsets, from the view that derived them. -/// -/// `SEGMENT_UNWRITTEN_OFFSET` is `size_of` rather than `offset_of` because the -/// wire struct deliberately stops at seven bytes: the eighth is the one the -/// serializer never writes, so it is the byte *after* the header rather than a -/// field in it, and saying so here is the whole difference between reading it -/// as ring contents and reading it as padding. -pub const SEGMENT_LENGTH_OFFSET: usize = core::mem::offset_of!(wire_segment::SegmentHeader, length); -pub const SEGMENT_TYPE_OFFSET: usize = - core::mem::offset_of!(wire_segment::SegmentHeader, segment_type); -pub const SEGMENT_BEGIN_FLAG_OFFSET: usize = - core::mem::offset_of!(wire_segment::SegmentHeader, begin_flag); -pub const SEGMENT_UNIDENTIFIED_OFFSET: usize = - core::mem::offset_of!(wire_segment::SegmentHeader, unidentified_u8); -pub const SEGMENT_UNWRITTEN_OFFSET: usize = core::mem::size_of::(); - -/// Record-header field offsets. This is the serializer's op header, a different -/// protocol level from the segment header above — see [`SEGMENT_HEADER_LEN`]. -pub const RECORD_OPCODE_OFFSET: usize = core::mem::offset_of!(reims_vgpu_wire::OpHeader, opcode); -pub const RECORD_LENGTH_OFFSET: usize = core::mem::offset_of!(reims_vgpu_wire::OpHeader, length); -/// Serializer op-header length ([`reims_vgpu_wire::OP_HEADER_LEN`]). Distinct -/// from [`SEGMENT_HEADER_LEN`]: both are 8, but they frame different protocol -/// levels — do not treat them as interchangeable. -use reims_vgpu_wire::OP_HEADER_LEN; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum DecodeStatus { - Ok, - /// End of stream, or end of a segment's records. Control flow — the walkers - /// terminate on it, so it is never a refusal and never reaches the log. - Done, - /// Refused; the payload is the registered slug naming which check refused. - /// - /// The payload is not decoration. This decoder frames *every* guest command, - /// and a single coarse `ErrBadLength` covers seventeen checks here — a - /// segment header disagreeing with the buffer, a record header disagreeing - /// with its segment, and the re-validation of an already-parsed segment are - /// three very different bugs that would otherwise arrive at the sink - /// wearing one name. - ErrArgs(&'static str), - ErrShort(&'static str), - ErrBadLength(&'static str), -} - -impl crate::observe::Refusal for DecodeStatus { - /// Slugs carry a `stream_` prefix: seven modules under `runtime/decode/` - /// define a type called `DecodeStatus`, and five of them have an `ErrShort` - /// meaning a different read. Without the prefix the crate-wide uniqueness - /// gate could not tell this decoder's refusals from any other's. - fn refusal(&self) -> Option<&'static str> { - match self { - Self::Ok | Self::Done => None, - Self::ErrArgs(slug) | Self::ErrShort(slug) | Self::ErrBadLength(slug) => Some(slug), - } - } -} - -/// One segment of the command stream, as decoded from its header. -/// -/// The three bytes after `type_` are carried but never acted on: the device -/// reads the length and the type and nothing else, and their only reader is -/// `validate_segment`, which re-reads the header and refuses a stream whose -/// bytes moved under it. They are named for what the oracle measured, because -/// the names they had were three claims it has since settled — `cont` for the -/// `BOOL` argument of `-beginSegment:protectionOptions:`, `chain` for a byte -/// that has never been made to move, and `pad` for one the serializer does not -/// write at all. See [`reims_vgpu_wire::ops::segment::SegmentHeader`], which -/// records what each was perturbed with. -/// -/// # The two the reader's contract does act on -/// -/// A conforming consumer of this stream treats `begin_flag` and -/// `unidentified_u8` as **encoder-lifetime control**, and it is the only thing -/// it treats them as. `begin_flag` set means this segment's records continue -/// the encoder the previous segment left open, and are a protocol error if that -/// encoder is absent or of a different type — the reader is required to refuse -/// rather than quietly open a fresh one. `unidentified_u8` set means the -/// encoder survives this segment and the next one may continue it; clear means -/// the encoder ends here. A render segment that does *not* continue a previous -/// one begins by decoding a render-pass descriptor out of its own records. -/// -/// So one Metal render command encoder — one Vulkan render pass — may span an -/// unbounded number of records across an unbounded number of segments, and this -/// device instead opens and ends a render pass per draw. -/// -/// **Whether that costs anything here is a question about this guest**, and -/// [`SEGMENT_CHAIN_ROUTES`] answered it. Driven x86 Safari-drag boot: -/// -/// ```text -/// seg_chain_none 94 860 -/// seg_chain_next 0 -/// seg_chain_prev 0 -/// seg_chain_both 0 -/// ``` -/// -/// **Every segment of the boot.** This guest never asks for an encoder to -/// outlive a segment, so there is nothing here to honour and no pass to hold -/// open across one. Keep the routes: this is a property of a workload, not of -/// the protocol, and a guest that did chain would arrive as a non-zero here -/// rather than as a rendering defect. -/// -/// The narrower question — whether a *single* segment carries more draws than -/// the one render pass this device opens per draw — has the same answer, from -/// the same boot: **94 860 segments against 96 351 draws**, so a render segment -/// carries about one. A render pass per draw is what this guest asks for, not a -/// translation artifact, and the contract permitting an unbounded number of -/// draws per encoder does not mean this workload presents one. -/// -/// So the submission and render-pass granularity are both already the guest's. -/// Neither is where this device's remaining cost is. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub struct Segment { - pub offset: u32, - pub length: u32, - pub type_: u8, - /// `-beginSegment:`'s unnamed `BOOL` first argument, verbatim. The reader's - /// contract makes this "continue the open encoder"; see the type doc. - pub begin_flag: u8, - /// Written, always `0` in every fixture. The reader's contract makes this - /// "the encoder outlives this segment"; see the type doc. - pub unidentified_u8: u8, - /// The eighth header byte, which neither `-beginSegment:` call writes. On a - /// real wire it is whatever the ring last contained, so it is not padding - /// and nothing may read it as a value. - pub unwritten_u8: u8, - pub command_offset: u32, - pub command_length: u32, - pub index: u32, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Record { - pub segment_index: u32, - pub segment_type: u32, - pub offset: u32, - pub length: u32, - pub opcode: u32, - /// Absolute offset of the record header in the stream bytes. - pub bytes_offset: u32, -} - -pub fn segment_type_name(type_: u32) -> &'static str { - match type_ { - 0 => "render", - 1 => "compute", - 2 => "blit", - 3 => "event", - 4 => "info", - 5 => "protection-options", - _ => "unknown", - } -} - -/// What the stream walker should do with a segment family. -/// -/// This exists so the walker's "everything else" arm is a decision rather than a -/// fallthrough. It used to be `_ => {}`, which gave the same silence to a ref-texture -/// envelope the contract says to skip and to a segment family the host has never -/// seen — and the second of those is unknown wire format. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SegmentDisposition { - /// A family with a record walker: render, compute, blit, event, info. - Walk, - /// Type 5. `-beginSegment:protectionOptions:` emits a segment-level envelope - /// *before* the real segment. Skipping it is contract-correct, so it is - /// control flow and stays silent — logging it would put a line in the sink - /// on every healthy frame that carries one. - /// - /// # Its command window is the protection value, and this doc used to deny - /// that - /// - /// The wording here was "raw envelope bytes carrying no decodable protection - /// value", which was a guess written where a measurement now sits. Driven - /// under `-setSupportsProtectionOptionsEnvelope:` the burst is exactly three - /// records: this ref-texture header, then **eight fully-written bytes that are the - /// `protectionOptions:` argument verbatim**, then the ordinary segment - /// header. `reims_vgpu_wire::ops::segment::ProtectionOptionsEnvelope` is the - /// view; `blit_begin_segment_protected` sends `0x44` and `..._alt` sends - /// `0x33`, so it is the guest's value and not a constant. - /// - /// Skipping stays right — this device implements no protection domains, so - /// there is nothing to do with the value — but "we cannot read it" and "we - /// choose not to act on it" are different claims and only the second is - /// true. - /// - /// The envelope needs **both** conditions: the `BOOL` argument clear *and* - /// non-zero options. Either alone emits the ordinary single header, which is - /// measured by `blit_begin_segment_protected_flag_set` and - /// `blit_begin_segment_protection_zero` respectively. - Envelope, - /// A family this host has no contract for. MetalSerializer's deserializer - /// constructs decoders for `0..3` and rejects new non-continuation types - /// `>= 4`, so a type past the known set is not something to guess at: - /// refuse it visibly instead of walking its bytes as records. - Unknown, -} - -impl crate::observe::Refusal for SegmentDisposition { - fn refusal(&self) -> Option<&'static str> { - match self { - Self::Walk | Self::Envelope => None, - Self::Unknown => Some("stream_segment_type_unknown"), - } - } -} - -/// The disposition of a segment type, derived from the one parse that owns it. -/// -/// `reims_vgpu_protocol::segment::segment_role` decides which byte is which -/// family; this only says what *this* walker does with each answer. Listing the -/// five record-bearing types again here would be a second copy of the segment -/// map, and the failure mode of a second copy is a family admitted by one and -/// refused by the other. -pub fn segment_disposition(type_: u8) -> SegmentDisposition { - use reims_vgpu_protocol::segment::SegmentRole; - match reims_vgpu_protocol::segment::segment_role(type_) { - Some(SegmentRole::Encoder(_)) => SegmentDisposition::Walk, - Some(SegmentRole::ProtectionEnvelope) => SegmentDisposition::Envelope, - None => SegmentDisposition::Unknown, - } -} - -fn validate_bytes(bytes: &[u8]) -> DecodeStatus { - if !size_fits_u32(bytes.len()) { - return DecodeStatus::ErrBadLength("stream_bytes_len_overflow"); - } - DecodeStatus::Ok -} - -fn segment_index_for_offset(bytes: &[u8], target_offset: u32) -> Result { - let mut cursor = 0usize; - let mut index = 0u32; - while cursor < bytes.len() { - if bytes.len() - cursor < SEGMENT_HEADER_LEN { - return Err(DecodeStatus::ErrShort("stream_index_walk_short_header")); - } - if !size_fits_u32(cursor) { - return Err(DecodeStatus::ErrBadLength( - "stream_index_walk_cursor_overflow", - )); - } - if cursor as u32 == target_offset { - return Ok(index); - } - let segment_len = ld32(&bytes[cursor + SEGMENT_LENGTH_OFFSET..]) as usize; - if segment_len < SEGMENT_HEADER_LEN || segment_len > bytes.len() - cursor { - return Err(DecodeStatus::ErrBadLength("stream_index_walk_seg_len")); - } - cursor += segment_len; - index += 1; - } - Err(DecodeStatus::ErrBadLength( - "stream_index_target_offset_not_found", - )) -} - -/// Decode the next segment at `cursor`. On Ok advances cursor. Transactional: no partial out. -pub fn decode_next_segment(bytes: &[u8], cursor: &mut usize) -> Result { - let status = validate_bytes(bytes); - if status != DecodeStatus::Ok { - return Err(status); - } - if *cursor > bytes.len() { - return Err(DecodeStatus::ErrArgs("stream_seg_cursor_past_end")); - } - if *cursor == bytes.len() { - return Err(DecodeStatus::Done); - } - if bytes.len() - *cursor < SEGMENT_HEADER_LEN { - return Err(DecodeStatus::ErrShort("stream_seg_short_header")); - } - let header = &bytes[*cursor..]; - let segment_len = ld32(&header[SEGMENT_LENGTH_OFFSET..]) as usize; - if segment_len < SEGMENT_HEADER_LEN { - return Err(DecodeStatus::ErrBadLength("stream_seg_len_below_header")); - } - if segment_len > bytes.len() - *cursor { - return Err(DecodeStatus::ErrBadLength("stream_seg_len_past_buffer_end")); - } - if !size_fits_u32(*cursor) { - return Err(DecodeStatus::ErrBadLength("stream_seg_cursor_overflow")); - } - let segment_index = segment_index_for_offset(bytes, *cursor as u32)?; - crate::runtime::drain::note_store_route(segment_chain_route( - header[SEGMENT_BEGIN_FLAG_OFFSET], - header[SEGMENT_UNIDENTIFIED_OFFSET], - )); - let out = Segment { - offset: *cursor as u32, - length: segment_len as u32, - type_: header[SEGMENT_TYPE_OFFSET], - begin_flag: header[SEGMENT_BEGIN_FLAG_OFFSET], - unidentified_u8: header[SEGMENT_UNIDENTIFIED_OFFSET], - unwritten_u8: header[SEGMENT_UNWRITTEN_OFFSET], - command_offset: (*cursor + SEGMENT_HEADER_LEN) as u32, - command_length: (segment_len - SEGMENT_HEADER_LEN) as u32, - index: segment_index, - }; - *cursor += segment_len; - Ok(out) -} - -/// Every census route [`segment_chain_route`] can answer, in the order -/// `(continues_previous, continues_into_next)` counts up. -/// -/// Exported so a reading is over a named set rather than over whichever names a -/// grep of the log happened to find, and so the four cannot be spelled twice. -pub const SEGMENT_CHAIN_ROUTES: [&str; 4] = [ - "seg_chain_none", - "seg_chain_next", - "seg_chain_prev", - "seg_chain_both", -]; - -/// Which of [`SEGMENT_CHAIN_ROUTES`] a segment header's two encoder-lifetime -/// bytes select. -/// -/// Any non-zero is a set flag: the bytes carry a `BOOL` and the stream is -/// guest-controlled, so `!= 0` is the test rather than `== 1`. A guest that -/// wrote `2` would otherwise be counted as "not chaining" and the whole reading -/// would be wrong in the direction that reads as a settled question. -pub fn segment_chain_route(continues_previous: u8, continues_into_next: u8) -> &'static str { - let index = usize::from(continues_previous != 0) << 1 | usize::from(continues_into_next != 0); - SEGMENT_CHAIN_ROUTES[index] -} - -fn validate_segment(bytes: &[u8], segment: &Segment) -> Result { - let status = validate_bytes(bytes); - if status != DecodeStatus::Ok { - return Err(status); - } - if (segment.length as usize) < SEGMENT_HEADER_LEN { - return Err(DecodeStatus::ErrBadLength("stream_reval_len_below_header")); - } - if (segment.offset as usize) > bytes.len() - || (segment.length as usize) > bytes.len() - segment.offset as usize - { - return Err(DecodeStatus::ErrBadLength("stream_reval_span_oob")); - } - let header = &bytes[segment.offset as usize..]; - if ld32(&header[SEGMENT_LENGTH_OFFSET..]) != segment.length - || header[SEGMENT_TYPE_OFFSET] != segment.type_ - || header[SEGMENT_BEGIN_FLAG_OFFSET] != segment.begin_flag - || header[SEGMENT_UNIDENTIFIED_OFFSET] != segment.unidentified_u8 - || header[SEGMENT_UNWRITTEN_OFFSET] != segment.unwritten_u8 - { - return Err(DecodeStatus::ErrBadLength("stream_reval_header_mismatch")); - } - if segment.command_offset != segment.offset + SEGMENT_HEADER_LEN as u32 - || segment.command_length != segment.length - SEGMENT_HEADER_LEN as u32 - { - return Err(DecodeStatus::ErrBadLength( - "stream_reval_command_span_mismatch", - )); - } - if segment.command_offset < segment.offset - || segment.command_length > u32::MAX - segment.command_offset - { - return Err(DecodeStatus::ErrBadLength( - "stream_reval_command_offset_overflow", - )); - } - let command_end = segment.command_offset as usize + segment.command_length as usize; - if (segment.command_offset as usize) > command_end - || command_end > segment.offset as usize + segment.length as usize - || command_end > bytes.len() - { - return Err(DecodeStatus::ErrBadLength("stream_reval_command_end_oob")); - } - Ok(command_end) -} - -pub fn decode_next_record( - bytes: &[u8], - segment: &Segment, - cursor: &mut usize, -) -> Result { - let command_end = validate_segment(bytes, segment)?; - if *cursor < segment.command_offset as usize || *cursor > command_end { - return Err(DecodeStatus::ErrArgs("stream_rec_cursor_out_of_segment")); - } - if segment.type_ == SEGMENT_TYPE_PROTECTION_OPTIONS { - if *cursor != segment.command_offset as usize && *cursor != command_end { - return Err(DecodeStatus::ErrArgs( - "stream_rec_protection_cursor_misaligned", - )); - } - *cursor = command_end; - return Err(DecodeStatus::Done); - } - if *cursor == command_end { - return Err(DecodeStatus::Done); - } - if command_end - *cursor < OP_HEADER_LEN { - return Err(DecodeStatus::ErrShort("stream_rec_short_header")); - } - let header = &bytes[*cursor..]; - let opcode = ld32(&header[RECORD_OPCODE_OFFSET..]); - let record_len = ld32(&header[RECORD_LENGTH_OFFSET..]) as usize; - if record_len < OP_HEADER_LEN { - return Err(DecodeStatus::ErrBadLength("stream_rec_len_below_header")); - } - if record_len > command_end - *cursor { - return Err(DecodeStatus::ErrBadLength( - "stream_rec_len_past_segment_end", - )); - } - if !size_fits_u32(*cursor) { - return Err(DecodeStatus::ErrBadLength("stream_rec_cursor_overflow")); - } - let out = Record { - segment_index: segment.index, - segment_type: segment.type_ as u32, - offset: *cursor as u32, - length: record_len as u32, - opcode, - bytes_offset: *cursor as u32, - }; - *cursor += record_len; - Ok(out) -} - -pub fn decode_first_record( - bytes: &[u8], - segment: &Segment, - cursor: &mut usize, -) -> Result { - *cursor = segment.command_offset as usize; - decode_next_record(bytes, segment, cursor) -} - -/// Iterate all segments. -pub fn iter_segments(bytes: &[u8]) -> Result, DecodeStatus> { - let mut cursor = 0usize; - let mut out = Vec::new(); - loop { - match decode_next_segment(bytes, &mut cursor) { - Ok(s) => out.push(s), - Err(DecodeStatus::Done) => return Ok(out), - Err(e) => return Err(e), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::protocol::endian::st32; - - /// The four chain routes are distinct, and each pair of flags selects its - /// own. A collision would fold two populations into one bucket, which is - /// the failure that reads as an answer: `seg_chain_none` carrying the whole - /// census is the reading that says this guest never chains encoders, and it - /// must not also be what a mis-indexed table says. - #[test] - fn each_pair_of_chain_flags_selects_its_own_route() { - let mut seen = std::collections::HashSet::new(); - for route in SEGMENT_CHAIN_ROUTES { - assert!( - seen.insert(route), - "two chain routes share the name {route}" - ); - } - assert_eq!(segment_chain_route(0, 0), "seg_chain_none"); - assert_eq!(segment_chain_route(0, 1), "seg_chain_next"); - assert_eq!(segment_chain_route(1, 0), "seg_chain_prev"); - assert_eq!(segment_chain_route(1, 1), "seg_chain_both"); - } - - /// The bytes are guest-controlled, so the flag test is `!= 0` and not - /// `== 1`. A guest writing any other truthy value must not be counted as - /// "did not chain" — that would put a segment the reader's contract says - /// continues an open encoder into the bucket whose emptiness is the whole - /// question. - #[test] - fn any_non_zero_chain_byte_is_a_set_flag() { - for v in [1u8, 2, 0x7f, 0x80, 0xff] { - assert_eq!(segment_chain_route(v, 0), "seg_chain_prev", "prev={v:#x}"); - assert_eq!(segment_chain_route(0, v), "seg_chain_next", "next={v:#x}"); - assert_eq!(segment_chain_route(v, v), "seg_chain_both", "both={v:#x}"); - } - } - - fn push_segment(buf: &mut Vec, type_: u8, payload: &[u8]) { - let len = (SEGMENT_HEADER_LEN + payload.len()) as u32; - let mut hdr = [0u8; 8]; - st32(&mut hdr[0..4], len); - hdr[4] = type_; - buf.extend_from_slice(&hdr); - buf.extend_from_slice(payload); - } - - fn push_record(buf: &mut Vec, opcode: u32, payload: &[u8]) { - let len = (OP_HEADER_LEN + payload.len()) as u32; - let mut hdr = [0u8; 8]; - st32(&mut hdr[0..4], opcode); - st32(&mut hdr[4..8], len); - buf.extend_from_slice(&hdr); - buf.extend_from_slice(payload); - } - - #[test] - fn empty_stream_done() { - let mut c = 0; - assert_eq!( - decode_next_segment(&[], &mut c).unwrap_err(), - DecodeStatus::Done - ); - assert_eq!(c, 0); - } - - #[test] - fn single_blit_segment_with_record() { - let mut payload = Vec::new(); - push_record(&mut payload, 0x12d, &[0u8; 0x18]); // buffer-to-buffer shape - let mut stream = Vec::new(); - push_segment(&mut stream, SEGMENT_TYPE_BLIT, &payload); - - let segs = iter_segments(&stream).unwrap(); - assert_eq!(segs.len(), 1); - assert_eq!(segs[0].type_, SEGMENT_TYPE_BLIT); - assert_eq!(segs[0].index, 0); - - let mut rc = 0; - let rec = decode_first_record(&stream, &segs[0], &mut rc).unwrap(); - assert_eq!(rec.opcode, 0x12d); - assert_eq!( - decode_next_record(&stream, &segs[0], &mut rc).unwrap_err(), - DecodeStatus::Done - ); - } - - #[test] - fn short_and_bad_length_name_the_check_that_refused() { - use crate::observe::Refusal; - // Asserting the slug rather than the variant is the point: both of these - // used to be one `ErrBadLength`/`ErrShort` shared with sixteen other - // checks, so a passing test said nothing about *which* read disagreed. - assert_eq!( - decode_next_segment(&[1, 2, 3], &mut 0) - .unwrap_err() - .refusal(), - Some("stream_seg_short_header") - ); - let mut bad = [0u8; 8]; - st32(&mut bad[0..4], 4); // length < header - assert_eq!( - decode_next_segment(&bad, &mut 0).unwrap_err().refusal(), - Some("stream_seg_len_below_header") - ); - // A segment header that outruns the buffer is a different bug from one - // that undershoots its own header, and now says so. - let mut past = [0u8; 8]; - st32(&mut past[0..4], 64); - assert_eq!( - decode_next_segment(&past, &mut 0).unwrap_err().refusal(), - Some("stream_seg_len_past_buffer_end") - ); - } - - #[test] - fn end_of_stream_and_end_of_segment_are_never_refusals() { - use crate::observe::Refusal; - // `Done` is how both walkers terminate. If it ever reported a reason the - // sink would carry one line per segment per frame — the flood that the - // speculative-return carve-out exists to prevent. - assert_eq!(DecodeStatus::Done.refusal(), None); - assert_eq!(DecodeStatus::Ok.refusal(), None); - - let mut stream = Vec::new(); - push_segment(&mut stream, SEGMENT_TYPE_RENDER, &[]); - let segs = iter_segments(&stream).unwrap(); - let mut c = 0; - assert_eq!( - decode_first_record(&stream, &segs[0], &mut c) - .unwrap_err() - .refusal(), - None - ); - let mut sc = stream.len(); - assert_eq!( - decode_next_segment(&stream, &mut sc).unwrap_err().refusal(), - None - ); - } - - #[test] - fn every_refusal_in_this_decoder_carries_a_registered_slug() { - use crate::observe::Refusal; - // What this pins is that no site returns a refusal whose payload is - // empty or absent, which would render `reason=` bare. - for status in [ - DecodeStatus::ErrArgs("stream_seg_cursor_past_end"), - DecodeStatus::ErrShort("stream_seg_short_header"), - DecodeStatus::ErrBadLength("stream_bytes_len_overflow"), - ] { - let slug = status.refusal().expect("a refusal names its check"); - assert!( - slug.starts_with("stream_"), - "{slug} lacks the module prefix" - ); - } - } - - #[test] - fn multi_segment_indices() { - let mut stream = Vec::new(); - push_segment(&mut stream, SEGMENT_TYPE_RENDER, &[]); - push_segment(&mut stream, SEGMENT_TYPE_COMPUTE, &[]); - let segs = iter_segments(&stream).unwrap(); - assert_eq!(segs[0].index, 0); - assert_eq!(segs[1].index, 1); - assert_eq!(segment_type_name(0), "render"); - } - - #[test] - fn property_fuzz_random_headers() { - // Smoke: random-ish short buffers must not panic. - for n in 0..32usize { - let bytes = vec![0xAAu8; n]; - let mut c = 0; - let _ = decode_next_segment(&bytes, &mut c); - } - } -} - -// ---- The legacy tests that moved with it, from `runtime::exec::tests` ---- -// -// Both of these had subjects that no longer exist. The first constructed a -// `Segment` naming bytes the buffer did not hold — unrepresentable now — and -// the second asked `segment_disposition` for a verdict the framer makes -// itself. See README.md for what replaced each. -#[test] -fn a_truncated_segment_names_the_check_rather_than_looking_like_end_of_records() { - use reims_vgpu_protocol::segment::{ - segment_type_name, Segment, SEGMENT_HEADER_LEN, SEGMENT_TYPE_INFO, - }; - // `Err(_) => break` treated a self-inconsistent segment exactly like - // `Done`: the remaining records went unexecuted with nothing logged. - let stream = vec![0u8; SEGMENT_HEADER_LEN + 4]; - // A segment claiming a longer body than the buffer holds, handed straight - // to the record walker — the shape `iter_segments` would have rejected but - // that an already-parsed `Segment` can still carry. - let seg = Segment { - offset: 0, - length: (SEGMENT_HEADER_LEN + 64) as u32, - type_: SEGMENT_TYPE_INFO, - command_offset: SEGMENT_HEADER_LEN as u32, - command_length: 64, - ..Segment::default() - }; - let before = sink_body().len(); - let mut handled = 0usize; - walk_segment_records(&stream, &seg, |_, _| handled += 1); - let added = sink_body()[before..].to_string(); - assert_eq!(handled, 0, "the malformed segment yields no records"); - assert!( - added.contains("stream_record_fail"), - "dropping a segment's records must reach the sink, got:\n{added}" - ); - assert!( - added.contains("reason=stream_reval_span_oob"), - "the line must name the failing re-validation check, got:\n{added}" - ); - assert!( - added.contains(&format!( - "seg={}", - segment_type_name(u32::from(SEGMENT_TYPE_INFO)) - )), - "the line must say which segment family lost its records, got:\n{added}" - ); -} - -#[test] -fn walking_a_well_formed_segment_to_its_end_logs_nothing() { - use reims_vgpu_protocol::segment::{iter_segments, SEGMENT_HEADER_LEN, SEGMENT_TYPE_EVENT}; - // The other half of the obligation: `Done` is how every segment ends, so - // if it produced a line the sink would carry one per segment per frame. - let mut records = [0u8; 8]; - st32(&mut records[0..4], 0x190); - st32(&mut records[4..8], 8); - let mut stream = vec![0u8; SEGMENT_HEADER_LEN]; - st32( - &mut stream[0..4], - (SEGMENT_HEADER_LEN + records.len()) as u32, - ); - stream[4] = SEGMENT_TYPE_EVENT; - stream.extend_from_slice(&records); - - let segs = iter_segments(&stream).expect("a well-formed stream frames"); - let before = sink_body().len(); - let mut handled = 0usize; - walk_segment_records(&stream, &segs[0], |_, _| handled += 1); - let added = sink_body()[before..].to_string(); - assert_eq!(handled, 1, "the one record is handed over"); - assert!( - !added.contains("stream_record_fail"), - "end-of-segment is control flow and must stay out of the log, got:\n{added}" - ); -} - -#[test] -fn an_unknown_segment_family_is_refused_and_the_type_5_envelope_is_not() { - use crate::observe::Refusal; - use reims_vgpu_protocol::segment::{ - segment_disposition, SegmentDisposition, SEGMENT_TYPE_BLIT, SEGMENT_TYPE_PROTECTION_OPTIONS, - }; - // `walk_stream` ended in `_ => {}`, which gave one silence to two very - // different things. Ref-texture is a contract-correct skip; function is wire - // format the host has never seen. - assert_eq!( - segment_disposition(SEGMENT_TYPE_PROTECTION_OPTIONS), - SegmentDisposition::Envelope - ); - assert_eq!( - segment_disposition(SEGMENT_TYPE_PROTECTION_OPTIONS).refusal(), - None, - "the envelope arrives on healthy frames; a line here is a flood" - ); - assert_eq!( - segment_disposition(SEGMENT_TYPE_BLIT), - SegmentDisposition::Walk - ); - assert_eq!( - segment_disposition(6).refusal(), - Some("stream_segment_type_unknown") - ); - assert_eq!( - segment_disposition(0xff).refusal(), - Some("stream_segment_type_unknown") - ); -} - diff --git a/crates/reims-vgpu/src/runtime/drain/mod.rs b/crates/reims-vgpu/src/runtime/drain/mod.rs index 93ee45a1d..0f1c451b9 100644 --- a/crates/reims-vgpu/src/runtime/drain/mod.rs +++ b/crates/reims-vgpu/src/runtime/drain/mod.rs @@ -3071,10 +3071,10 @@ fn note_stamp_visible(state: &DeviceState, index: u32, value: u32, site: &'stati // the guest can read from. // // **Named, once per slot, because the count is two different - // facts.** A boot measures about 14 000 of these, and - // `dead/README.md` records the same counter at zero when the - // publication point was moved to this site — so either the meaning - // drifted or the invariant broke, and a bare count cannot say + // facts.** A boot measures about 14 000 of these, and the driven + // boot taken when the publication point was moved to this site read + // the same counter at zero — so either the meaning drifted or the + // invariant broke, and a bare count cannot say // which. What separates them is *which slot* and *by how much*: one // slot whose page rewound under a timeline that will not follow it // is a slot to explain, and a timeline running ahead of every word diff --git a/crates/reims-vgpu/tests/dead_is_unreachable_by_construction.rs b/crates/reims-vgpu/tests/dead_is_unreachable_by_construction.rs deleted file mode 100644 index 585fb5954..000000000 --- a/crates/reims-vgpu/tests/dead_is_unreachable_by_construction.rs +++ /dev/null @@ -1,477 +0,0 @@ -//! `dead/` is source to read, and this is what makes that claim checkable. -//! -//! # Why a test and not a convention -//! -//! The project owner's 2026-09-02 amendment replaced the plan's *delete the -//! legacy counterpart* with *disconnect it*: the commit that wires a group -//! moves that group's files to `crates//src/dead/` and removes every -//! `mod` declaration that reaches them. The strength being bought is that the -//! prohibition on two semantic models holds **by construction** — a removed -//! `mod` is not a flag anyone can flip, and a file no module tree reaches is -//! not compiled, not feature-gated and not linkable. -//! -//! That strength lasts exactly as long as nobody adds the `mod` back. Nothing -//! in the build would complain: `mod dead;` compiles, and the second semantic -//! model it re-links would show up as a behaviour difference on a live boot -//! weeks later, attributed to whatever else changed that week. A convention -//! with no gate is the thing the amendment was written against. -//! -//! # What it checks, and why each one -//! -//! * **No `mod` declaration names `dead`.** The direct form. -//! * **No `#[path]` attribute points into a `dead/` directory.** The indirect -//! form, which a reader scanning for `mod dead;` would not find — a module -//! declared under any name at all can be given a `dead/` file to compile. -//! * **Nothing outside `dead/` names it as a path.** A `crate::dead::…` or -//! `use …dead::…` cannot compile without one of the two above, so a hit here -//! is a leftover from a reversal in progress and is worth naming separately -//! from the mechanism that would carry it. -//! * **No `include!` names a `dead/` file.** A third way to compile one: the -//! macro splices the file into whatever module the call sits in, with no -//! `mod` and no `#[path]` for either of the checks above to see. -//! * **No `Cargo.toml` target points into `dead/`.** The module tree is not the -//! only door. A `[[test]]` or `[[bin]]` with `path = "src/dead/…"` compiles -//! and links the file as its own crate root, which is a second semantic model -//! that the whole `src/` walk would report as clean. -//! * **Every function the register names still exists.** A row's last column -//! names the owner-level tests that replaced the legacy tests moving with -//! the group, and those legacy tests stopped running the moment they moved. -//! A row naming a test that has since been renamed or deleted is the silent -//! coverage loss the rule exists to catch, and prose cannot notice it. -//! * **Every `dead/` has a `README.md`.** The register is where a move records -//! what it replaced and which owner-level tests replaced the legacy tests -//! that moved with it. Those tests stop running the moment they move, so a -//! `dead/` with no register is a group that has silently lost its coverage. -//! -//! The walk is over sources on disk rather than over anything the compiler -//! knows, because the whole point is to catch a file the compiler *has* been -//! told about. - -use std::path::{Path, PathBuf}; - -/// The workspace root, from this crate's manifest directory. -fn workspace_root() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .parent() - .and_then(Path::parent) - .expect("crates/ sits two levels under the workspace root") - .to_path_buf() -} - -/// Every `.rs` file under `crates/*/src`, with the ones inside a `dead/` -/// directory left out — `dead/` is not compiled, so what it says about itself -/// is not evidence about the live tree. -fn live_rust_sources() -> Vec { - let mut out = Vec::new(); - let crates = workspace_root().join("crates"); - let entries = std::fs::read_dir(&crates).expect("crates/ is readable"); - for entry in entries.flatten() { - walk(&entry.path().join("src"), &mut out); - } - assert!( - out.len() > 100, - "the walk found {} sources, which is too few to have visited the tree — \ - a test that silently inspects nothing passes for the wrong reason", - out.len() - ); - out -} - -fn walk(dir: &Path, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - if path.file_name().is_some_and(|n| n == "dead") { - continue; - } - walk(&path, out); - } else if path.extension().is_some_and(|e| e == "rs") { - out.push(path); - } - } -} - -/// A line with its `//` and `//!` comment tail removed, so the prose in this -/// file — and in `dead/README.md`'s neighbours — cannot fail the test it -/// describes. -/// -/// Deliberately not a parser. A `mod dead;` inside a string literal or a block -/// comment would be flagged; that is the safe direction for a check whose -/// failure mode is a re-linked semantic model, and no such literal exists. -fn code_of(line: &str) -> &str { - match line.find("//") { - Some(i) => &line[..i], - None => line, - } -} - -#[test] -fn no_module_declaration_reaches_dead() { - let mut offenders = Vec::new(); - for path in live_rust_sources() { - let text = std::fs::read_to_string(&path).expect("a source file is readable"); - for (n, line) in text.lines().enumerate() { - let code = code_of(line); - let declares_dead = code - .split_whitespace() - .collect::>() - .windows(2) - .any(|w| w[0] == "mod" && w[1].trim_end_matches(';') == "dead"); - if declares_dead { - offenders.push(format!("{}:{}", path.display(), n + 1)); - } - } - } - assert!( - offenders.is_empty(), - "a `mod dead` declaration re-links the disconnected legacy source, which \ - is the second semantic model the plan forbids wearing a different hat. \ - `dead/` is read and the fix lands in the new owner; nothing is \ - resurrected from it. Found at: {offenders:?}" - ); -} - -#[test] -fn no_path_attribute_points_into_dead() { - let mut offenders = Vec::new(); - for path in live_rust_sources() { - let text = std::fs::read_to_string(&path).expect("a source file is readable"); - for (n, line) in text.lines().enumerate() { - let code = code_of(line); - if code.contains("path") && code.contains("dead/") && code.contains('#') { - offenders.push(format!("{}:{}", path.display(), n + 1)); - } - } - } - assert!( - offenders.is_empty(), - "a `#[path = \"…dead/…\"]` compiles a disconnected file under some other \ - module's name, which a reader scanning for `mod dead;` would not find. \ - Found at: {offenders:?}" - ); -} - -#[test] -fn nothing_outside_dead_names_it_as_a_path() { - let mut offenders = Vec::new(); - for path in live_rust_sources() { - let text = std::fs::read_to_string(&path).expect("a source file is readable"); - for (n, line) in text.lines().enumerate() { - if code_of(line).contains("dead::") { - offenders.push(format!("{}:{}", path.display(), n + 1)); - } - } - } - assert!( - offenders.is_empty(), - "a path into `dead` cannot compile without a module declaration this \ - suite already refuses, so a hit here is a reversal in progress rather \ - than a finished one. Found at: {offenders:?}" - ); -} - -#[test] -fn every_dead_directory_carries_its_register() { - let crates = workspace_root().join("crates"); - let mut seen = 0usize; - for entry in std::fs::read_dir(&crates) - .expect("crates/ is readable") - .flatten() - { - let dead = entry.path().join("src").join("dead"); - if !dead.is_dir() { - continue; - } - seen += 1; - assert!( - dead.join("README.md").is_file(), - "{} has no register. Every move appends a row naming what moved, \ - which commit replaced it, and which owner-level tests replaced the \ - legacy tests that moved with it — those tests stop running the \ - moment they move, and the row is where that is caught", - dead.display() - ); - } - assert!( - seen > 0, - "no `dead/` directory found at all. If the last one has been deleted \ - wholesale — which happens once, after every group has moved and the \ - gates are green — this suite has done its job and goes with it" - ); -} - -#[test] -fn no_include_macro_splices_a_dead_file() { - let mut offenders = Vec::new(); - for path in live_rust_sources() { - let text = std::fs::read_to_string(&path).expect("a source file is readable"); - for (n, line) in text.lines().enumerate() { - let code = code_of(line); - if code.contains("dead/") - && (code.contains("include!") || code.contains("include_str!")) - { - offenders.push(format!("{}:{}", path.display(), n + 1)); - } - } - } - assert!( - offenders.is_empty(), - "an `include!` splices a disconnected file into whatever module the call \ - sits in, with no `mod` and no `#[path]` for the other checks to see. \ - Found at: {offenders:?}" - ); -} - -#[test] -fn no_cargo_target_points_into_dead() { - let crates = workspace_root().join("crates"); - let mut offenders = Vec::new(); - let mut seen = 0usize; - for entry in std::fs::read_dir(&crates) - .expect("crates/ is readable") - .flatten() - { - let manifest = entry.path().join("Cargo.toml"); - let Ok(text) = std::fs::read_to_string(&manifest) else { - continue; - }; - seen += 1; - for (n, line) in text.lines().enumerate() { - let code = match line.find('#') { - Some(i) => &line[..i], - None => line, - }; - if code.contains("dead/") { - offenders.push(format!("{}:{}", manifest.display(), n + 1)); - } - } - } - assert!( - seen > 1, - "only {seen} manifests were read; the walk missed the tree" - ); - assert!( - offenders.is_empty(), - "a Cargo target with `path = \"src/dead/…\"` compiles and links the file \ - as its own crate root — a second semantic model the `src/` walk would \ - report as clean, because the module tree is not the only door. \ - Found at: {offenders:?}" - ); -} - -/// Every function the register's replacement-coverage column names is still a -/// function. -/// -/// # The row is the only record that the coverage survived -/// -/// A group's legacy tests move to `dead/` with its source and stop running -/// there. What replaced them is written in the register and nowhere else — no -/// build step relates the two — so a row naming -/// `runtime::exec::tests::a_bounded_event_wait_is_refused_by_contract…` is the -/// whole evidence that the case is still covered. Rename or delete that test -/// and the row keeps reading as if it were, which is the exact failure the -/// rule was written against, arriving in the record that was supposed to -/// prevent it. -/// -/// # What counts as a name, and why the rule is that shape -/// -/// Two forms, because one of them was not enough. -/// -/// The first is a backticked path with at least one `::` whose last segment is -/// snake_case with an underscore in it. Type and variant names end in CamelCase -/// and are skipped. -/// -/// The second exists because almost no coverage claim is written that way. A -/// test named in a row is named the way a reader would say it — bare, as -/// `a_declined_publish_vouches_for_nothing` — and a bare backticked word cannot -/// be told from a census route, a counter or an observation slug, of which the -/// rows are full. So this check read nine coverage claims and verified two of -/// them, while its own doc and the register's rules both said it verified all -/// nine. A gate that reports on what it did not inspect is worse than no gate: -/// the rule it was standing in for was being trusted. -/// -/// The fix is to make the claim say it is one. A coverage name is written -/// ``fn `name` `` after the `Replacement coverage` marker, and that `fn` is what -/// separates the claim from the prose around it — which is how a row can go on -/// naming `pools/`, `winpub_*` or a slug that no longer exists in the same -/// sentence without either being mistaken for a promise. -/// -/// The marker is required because the register's other columns name functions -/// while describing what *moved*, and a moved function is allowed to be gone. -/// -/// Existence, not location: a name in the register is prose written by a -/// human, and pinning the module as well would make the check fail on a -/// correct row whose module was reorganised — a gate that fails on correct -/// work is a gate that gets weakened. -#[test] -fn every_function_the_register_names_still_exists() { - let register = workspace_root() - .join("crates") - .join("reims-vgpu") - .join("src") - .join("dead") - .join("README.md"); - let text = std::fs::read_to_string(®ister).expect("the register is readable"); - - let mut named: Vec = Vec::new(); - let mut rows = 0usize; - let mut claims = 0usize; - for line in text.lines() { - if !line.starts_with('|') || line.starts_with("|---") { - continue; - } - // The register proper has five columns and its fifth is the - // replacement-coverage column. The live-validation table below it has - // three, and its rows carry coverage claims in prose — seven of the - // nine in this file, which is why reading only the five-column table - // was reading the smaller half. - if line.matches('|').count() >= 6 { - if let Some(column) = line.split('|').nth(5) { - rows += 1; - named.extend(backticked_function_paths(column)); - } - } - // Every ``fn `name` `` on the line, wherever it sits. The rule this - // gate enforces is stated about the marker and not about a column, and - // the file has since grown a fourth place that uses it — the - // structural-zero scoreboard, whose "read from" cells name the gates - // that establish each zero. Those are promises about functions by - // exactly the rule's own definition, and keying the parser to the - // "replacement coverage" phrase silently exempted them: the scoreboard - // named four gates and this test verified none of them, which is the - // shape of the defect the marker was introduced to end. - let claimed = declared_coverage_names(line); - claims += claimed.len(); - named.extend(claimed); - } - assert!( - rows > 5, - "only {rows} register rows were parsed, which is too few to have read \ - the table — a check that inspects nothing passes for the wrong reason" - ); - assert!( - claims > 10, - "only {claims} `fn `name`` coverage claims were found. Either the rows \ - stopped declaring them in the form this gate reads, or this parser \ - stopped reading it — and both leave the register's coverage column \ - unchecked while it still reads as checked" - ); - assert!( - named.len() > 10, - "only {} names were extracted from {rows} rows", - named.len() - ); - - let defined = defined_function_names(); - let missing: Vec<&String> = named.iter().filter(|n| !defined.contains(*n)).collect(); - assert!( - missing.is_empty(), - "the register names {missing:?}, and no `fn` by that name exists. A row \ - claiming coverage that has been renamed or deleted is the silent loss \ - the rule exists to catch: either restore the function, or amend the row \ - to name what covers the case now" - ); -} - -/// The names a line *declares* as a promise about a function, which is the -/// subset of its backticks written as ``fn `name` ``. -/// -/// Everything else in the sentence is prose and stays prose: `pools/` is a -/// directory, `winpub_*` is a route family, and a row is allowed to name a slug -/// that no longer exists in order to say that it no longer exists. Only what -/// carries the `fn` is a promise about a function. -fn declared_coverage_names(tail: &str) -> Vec { - let mut out = Vec::new(); - let mut rest = tail; - while let Some(at) = rest.find("fn `") { - rest = &rest[at + 4..]; - let Some(end) = rest.find('`') else { break }; - let token = &rest[..end]; - rest = &rest[end + 1..]; - if token.is_empty() - || token - .chars() - .any(|c| !(c.is_ascii_alphanumeric() || c == '_' || c == ':')) - { - continue; - } - let last = token.rsplit("::").next().unwrap_or_default(); - if !last.is_empty() { - out.push(last.to_string()); - } - } - out -} - -/// The snake_case tails of backticked `a::b::c` paths in one register cell. -fn backticked_function_paths(cell: &str) -> Vec { - let mut out = Vec::new(); - for token in cell.split('`').skip(1).step_by(2) { - if !token.contains("::") { - continue; - } - if token - .chars() - .any(|c| !(c.is_ascii_alphanumeric() || c == '_' || c == ':')) - { - // A type parameter, a field with its type, a lifetime — not a plain - // path, and guessing at one is how this check starts failing on - // prose. - continue; - } - let last = token.rsplit("::").next().unwrap_or_default(); - if last.contains('_') && last.chars().all(|c| !c.is_ascii_uppercase()) { - out.push(last.to_string()); - } - } - out -} - -/// Every `fn` name defined anywhere in the workspace's crates, `dead/` -/// included — a row may legitimately name a function that moved, as long as it -/// still exists somewhere to be read. -fn defined_function_names() -> std::collections::HashSet { - let mut out = std::collections::HashSet::new(); - let mut files = Vec::new(); - let crates = workspace_root().join("crates"); - for entry in std::fs::read_dir(&crates) - .expect("crates/ is readable") - .flatten() - { - walk_all(&entry.path(), &mut files); - } - for path in files { - let Ok(text) = std::fs::read_to_string(&path) else { - continue; - }; - for line in text.lines() { - let Some(at) = line.find("fn ") else { continue }; - let rest = &line[at + 3..]; - let name: String = rest - .chars() - .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') - .collect(); - if !name.is_empty() { - out.insert(name); - } - } - } - out -} - -fn walk_all(dir: &Path, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - walk_all(&path, out); - } else if path.extension().is_some_and(|e| e == "rs") { - out.push(path); - } - } -} diff --git a/vm/README.md b/vm/README.md index 69effac74..a306c2a3a 100644 --- a/vm/README.md +++ b/vm/README.md @@ -36,10 +36,9 @@ vm/rail-sweep.sh macos-15 macos-26 # or just these ``` `drive-desktop.sh` is the "three rounds of launching and quitting five -applications over ssh" that every validation row in -`crates/reims-vgpu/src/dead/README.md` names. It is committed rather than -described because a rate is only comparable across boots if the workload is. -`ROUNDS` and `APPS` override it. +applications over ssh" that every validation reading this project quotes was +taken behind. It is committed rather than described because a rate is only +comparable across boots if the workload is. `ROUNDS` and `APPS` override it. `rail-sweep.sh` boots each rail with `--testing`, drives it, snapshots `/tmp/reims-vgpu-fail.log` to `/tmp/sweep--fail.log`, and prints the same diff --git a/vm/drive-desktop.sh b/vm/drive-desktop.sh index d288f528b..47f342ffc 100755 --- a/vm/drive-desktop.sh +++ b/vm/drive-desktop.sh @@ -4,12 +4,13 @@ # # WHY THIS EXISTS. Almost every reading this project takes is a *rate* — draws # a second, packets a boot, refusals per desktop — and a guest sitting at an -# idle Finder produces none of them. The numbers in `crates/reims-vgpu/src/ -# dead/README.md` are all "host-driven workload (three rounds of launching and -# quitting five applications over ssh)", and that sentence was a shell script -# in `/tmp` that each session re-derived from the row it was reading. Two -# sessions re-derived it slightly differently, which is the thing a committed -# harness stops: a rate is only comparable across boots if the workload is. +# idle Finder produces none of them. Every such number this project has ever +# quoted was taken behind "host-driven workload (three rounds of launching and +# quitting five applications over ssh)", and that sentence used to be a shell +# script in `/tmp` that each session re-derived from the reading it was +# chasing. Two sessions re-derived it slightly differently, which is the thing +# a committed harness stops: a rate is only comparable across boots if the +# workload is. # # It is host-driven on purpose. Input synthesised inside the guest would be the # guest exercising itself; `AGENTS.md` asks for host-driven input so that what From aa07715a6cf801d7f78a257d1fd90110bb1b349e Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 3 Sep 2026 23:25:01 +0300 Subject: [PATCH 5/5] :fire: Remove outdated bits in AGENTS.md --- AGENTS.md | 49 ------------------------------------------------- 1 file changed, 49 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 39530e544..9b0af930f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,55 +100,6 @@ classes, or guest rails. Vulkan 1.2 is the baseline; newer functionality require capability-gated fallback. Host-pointer import is optional, and guest-visible semantics must be the same on imported and copying paths. -## Wire a finished subsystem immediately - -The replacement architecture is landing subsystem by subsystem, and each one **joins production in -the commit that finishes it**. A subsystem that exists but is reachable only from its own tests has -not been verified against a guest; a release that switches thirty of them at once has no bisect -that can attribute a regression to one. So a subsystem is done when its legacy counterpart is gone -or delegates to it — not when it compiles. - -What this does *not* license is two semantic models running at once. No per-packet feature switch -choosing between executors, no shadow execution that mutates state twice, no adapter translating -between an old model and a new one. A call site that *replaces* its own logic with a call into the -owning crate creates no second model, and is the shape to reach for. - -Wire in order of how little state moves. A pure translation or plan module — a function of its -inputs returning a value — wires first: the caller keeps its ownership and loses only its duplicate -arithmetic, so a regression points at one table. Modules owning handles, caches, or submission -lifetimes wire once the model that owns those lifetimes is in place, because they cannot be split. - -The same rule decides how the final ingress switch is cut. **A packet class moves to the new model -alone exactly when nothing it owns is ordered against, or shares mutable state with, anything still -on the legacy path. Classes that do share such state move together, and that group — not -"everything" — is the atomic unit.** Two models are dangerous because they can disagree about one -piece of state; where there is no shared state there is nothing to disagree about, and holding a -disjoint class back buys no safety while costing the bisect it could have provided. - -State the disjointness before moving a group and make it hold structurally — named owners, not an -argument that the current call sites happen not to overlap. If it cannot be made to hold, the group -is larger than it looked: enlarge it rather than move anyway. Within a group the switch is atomic -and the legacy counterpart is deleted in the same commit. Order the groups by how little state -they move; the ordering and publication core is last, and carries the scheduler's deletion. - -**The 2026-09-02 "disconnect, do not delete" amendment is spent, and `dead/` is gone as of -2026-09-03.** It bought attribution while packet classes were moving under outstanding macOS cells: -a group's legacy files went to `crates//src/dead/`, unreachable because no `mod` declared -them, so a live regression on a class that had just moved could be read rather than reconstructed -from `git log`. Every packet-class group has since moved, the classes it was protecting are settled, -and the directory was deleted wholesale in one commit along with the gate that held it unreachable. - -So the rule above is the rule again: **the group's legacy counterpart is deleted in the commit that -wires it.** Do not recreate `dead/`, and do not stage a deletion through it — what an old arm did is -now read out of `git log`, and the deleted-in-the-same-commit form is what the prohibition on two -semantic models asks for directly. The one group still to move is the process-global mutable engine -behind `backend::vulkan::engine`; when it wires, its legacy files leave the tree with it. - -A group's legacy tests die with its legacy source, so the commit that wires it must name — in the -commit message, since there is no register any more — the owner-level tests that replace them. A -group shipping without that replacement coverage has silently lost it, and nothing in the build -relates the two. - ## Working and verification Use a workflow proportionate to the change: