Skip to main content

crcbl_hal/null/
mod.rs

1//! `NullBackend` — a complete, recording implementation of the seam that talks
2//! to no GPU.
3//!
4//! It exists for three jobs, in increasing order of usefulness:
5//!
6//! 1. **Prove the seam compiles and leaks nothing.** If a trait method could
7//!    not be implemented without naming a backend type, this module would not
8//!    build. The foundations stage named exactly this as its deliverable
9//!    check (`docs/notes/backends.md`).
10//! 2. **Be the substrate for the graph-compile suite.** `docs/notes/process.md`
11//!    assigns `crcbl-hal`/`crcbl-vk`/`crcbl-webgpu` a "graph-compile unit suite on
12//!    NullBackend"; the render graph that lands at P1 compiles its pass list
13//!    against this backend in CI, with no GPU and no window.
14//! 3. **Answer questions about a frame.** Every call is recorded, so a test can
15//!    assert which passes ran in which order, which barriers separated them,
16//!    and that nothing leaked. See [`Recorder`].
17//!
18//! # It can also be slow on purpose
19//!
20//! Two things the seam defers — readback and device creation — are instant
21//! here, which would leave every caller's *poll loop* untested. [`Recorder`]
22//! therefore takes a latency for each:
23//! [`set_readback_latency`](Recorder::set_readback_latency) and
24//! [`set_device_latency`](Recorder::set_device_latency) make N polls report
25//! `Pending` before completing, which is what a browser's `mapAsync` and
26//! `requestDevice` promises do and what no amount of native hardware will
27//! reproduce.
28//!
29//! # And it can fail on purpose
30//!
31//! For the same reason, one step further: this backend never fails on its own,
32//! so a caller's *error* paths would never run either.
33//! [`report_device_error`](Recorder::report_device_error) queues an out-of-band
34//! failure, [`fail_next_reconfigures`](Recorder::fail_next_reconfigures) refuses
35//! a swapchain rebuild, [`report_swapchain_out_of_date`](Recorder::report_swapchain_out_of_date)
36//! resizes the window out from under the frame loop,
37//! [`report_suboptimal_acquires`](Recorder::report_suboptimal_acquires) hands
38//! out a frame the surface has outgrown but will still take,
39//! [`report_present_wait_timeouts`](Recorder::report_present_wait_timeouts)
40//! leaves a pacing wait unanswered until its deadline passes — on a device that
41//! claims [`Features::PRESENT_FEEDBACK`], which is what
42//! [`NullInstance::with_present_feedback`] is for — and
43//! [`lose_device`](Recorder::lose_device) kills the device for good. The
44//! swapchain ones and the loss exist because the conditions they model — a
45//! resize, a stale extent, a stalled compositor and a TDR — are otherwise
46//! reachable only on a real driver at a moment nobody can schedule.
47//!
48//! # Always compiled
49//!
50//! Not behind a feature. See the crate docs for the argument — briefly: other
51//! crates' *tests* depend on it, so a feature gate would have to be turned on
52//! from their dev-dependencies, and feature unification would then make
53//! `cargo test -p x` and `cargo build -p x` disagree.
54//!
55//! # It validates
56//!
57//! The backend checks pass nesting, that commands appear in the right scope, and
58//! that every handle a command names is still alive. Violations are *recorded*,
59//! not panicked on, so a failing test reports the whole frame's problems at once.
60//! See [`ValidationError`] and [`Recorder::assert_valid`].
61//!
62//! # Two presets
63//!
64//! [`NullInstance::gpu_driven`] reports a full desktop device holding
65//! [`Features::GPU_DRIVEN`] and most of what sits beside it;
66//! [`NullInstance::portable`] reports the WebGPU-shaped floor — no bindless, no
67//! `draw_indirect_count`, no buffer device address, no push constants, no
68//! timeline semaphores, and an implicit swapchain acquire. They are two points
69//! in the capability space rather than two tiers, and running the same renderer
70//! code against both is how degradation gets tested before `crcbl-webgpu` runs
71//! in a browser.
72//!
73//! ```
74//! use crcbl_hal::null::{NullInstance, Recorder};
75//! use crcbl_hal::{BindingModel, GeometryPath, Instance};
76//!
77//! let recorder = Recorder::new();
78//! let instance: Box<dyn Instance> =
79//!     Box::new(NullInstance::portable().with_recorder(recorder.clone()));
80//!
81//! let adapter = instance.adapters()[0].clone();
82//! assert_eq!(adapter.caps.binding_model(), BindingModel::ArrayPages);
83//! assert_eq!(adapter.caps.geometry_path(), GeometryPath::IndirectPerBatch);
84//! assert_eq!(recorder.total_live_objects(), 0);
85//! ```
86
87mod record;
88
89pub use record::{
90    Command, Event, ObjectKind, PipelineRecord, Recorder, StageRecord, ValidationError,
91};
92
93use record::Detail;
94
95use core::ops::Range;
96use core::sync::atomic::{AtomicU64, Ordering};
97use core::time::Duration;
98
99use crcbl_core::{Handle, SurfaceTarget};
100
101use crate::indirect::{
102    IndirectPlan, plan_count_structures, plan_mesh_indirect, plan_structures, structure_bytes,
103};
104use crate::{
105    AcquiredFrame, AdapterId, AdapterInfo, BackendKind, Barriers, BindGroupDesc, BindGroupEntry,
106    BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry, BindGroupLayoutHandle, BindingKind,
107    BufferCopy, BufferDesc, BufferHandle, BufferImageCopy, Capability, CommandBufferHandle,
108    CommandEncoder, CommandEncoderDesc, CompositeAlpha, ComputePassDesc, ComputePipelineDesc,
109    ComputePipelineHandle, Device, DeviceCaps, DeviceDesc, DeviceRequestState, DeviceType,
110    DisplayTiming, DrawIndirect, DrawIndirectCount, Features, Format, GraphicsPipelineDesc,
111    GraphicsPipelineHandle, HalError, ImageCopy, ImageDesc, ImageHandle, ImageType, ImageUsage,
112    ImageViewDesc, ImageViewHandle, IndexFormat, Instance, Limits, MemoryLocation,
113    MeshPipelineDesc, PassTimestampWrites, PendingDevice, PipelineLayoutDesc, PipelineLayoutHandle,
114    PresentInfo, PresentMode, QueryKind, QuerySetDesc, QuerySetHandle, QueueHandle, QueueKind,
115    ReadbackDesc, ReadbackHandle, ReadbackState, Rect2d, RenderPassDesc, SamplerDesc,
116    SamplerHandle, SemaphoreDesc, SemaphoreHandle, SemaphoreKind, SemaphoreWait, ShaderModuleDesc,
117    ShaderModuleHandle, ShaderSources, ShaderStages, SubmitInfo, Support, SurfaceCaps,
118    SurfaceError, SurfaceHandle, SwapchainDesc, SwapchainHandle, Viewport,
119};
120
121/// Formats a null surface reports, and therefore the only ones a swapchain on
122/// one may be configured with. `SwapchainDesc::format` says it must be one of
123/// [`SurfaceCaps::formats`], so the two lists are one constant rather than two
124/// that drift.
125const SURFACE_FORMATS: &[Format] = &[Format::Bgra8UnormSrgb, Format::Bgra8Unorm];
126
127/// Fewest images a null swapchain ring holds — [`SurfaceCaps::min_image_count`].
128const RING_MIN_IMAGES: u32 = 2;
129/// Most images a null swapchain ring holds — [`SurfaceCaps::max_image_count`].
130const RING_MAX_IMAGES: u32 = 3;
131
132/// Low bits of a synthesised queue handle that name the queue kind. The rest
133/// carry the owning device's tag — see [`queue_handle`].
134const QUEUE_KIND_BITS: u32 = 8;
135
136/// The owning device's identity, squeezed into a queue handle's index field.
137///
138/// Queue handles are not pooled, so nothing else can record who issued one. 24
139/// bits is more device identity than a process will ever use and leaves the low
140/// byte for the kind.
141fn queue_tag(device_id: u64) -> u32 {
142    #[allow(clippy::cast_possible_truncation)]
143    {
144        (device_id % (1 << 24)) as u32
145    }
146}
147
148/// Deterministic queue handles.
149///
150/// Queues are not pooled objects — they exist for the device's lifetime and
151/// carry no state — so their handles are synthesised rather than allocated.
152/// They still carry the **issuing device's tag**, because obligation 3 applies
153/// to every handle and a queue handle from another device would otherwise be
154/// indistinguishable from this device's own.
155fn queue_handle(device_id: u64, index: u32) -> QueueHandle {
156    let raw = (queue_tag(device_id) << QUEUE_KIND_BITS) | index;
157    Handle::from_bits((1u64 << 32) | u64::from(raw)).expect("generation 1 is non-zero")
158}
159
160/// The queue-kind index behind a handle *this* device issued, or `None` if the
161/// handle came from somewhere else.
162fn queue_index_of(device_id: u64, queue: QueueHandle) -> Option<u32> {
163    let raw = queue.index();
164    (queue.generation() == 1 && (raw >> QUEUE_KIND_BITS) == queue_tag(device_id))
165        .then_some(raw & ((1 << QUEUE_KIND_BITS) - 1))
166}
167
168/// Source of owner ids for instances and devices.
169///
170/// A [`Handle`] has no room for an owner (32-bit index + 32-bit generation are
171/// fully spoken for), so ownership lives in the object side table instead. This
172/// is the mechanism `crate::device`'s rule 3 obliges every backend to provide;
173/// a real backend would key it off its `VkInstance`/`VkDevice` pointer instead
174/// of a counter.
175static NEXT_OWNER_ID: AtomicU64 = AtomicU64::new(1);
176
177fn next_owner_id() -> u64 {
178    NEXT_OWNER_ID.fetch_add(1, Ordering::Relaxed)
179}
180
181/// A no-op, recording [`Instance`].
182///
183/// Share its [`Recorder`] with [`NullInstance::with_recorder`] to inspect the
184/// stream after running a frame entirely through `dyn` traits.
185#[derive(Clone, Debug)]
186pub struct NullInstance {
187    recorder: Recorder,
188    caps: DeviceCaps,
189    name: String,
190    /// Owner id stamped into every surface this instance creates. Cloning a
191    /// `NullInstance` keeps the id, because a clone *is* the same instance;
192    /// a separately constructed one gets a fresh id and its surfaces are
193    /// therefore foreign to this one's devices.
194    id: u64,
195    /// How many adapters [`Instance::adapters`] reports. See
196    /// [`NullInstance::with_adapters`].
197    adapter_count: u32,
198    geometry_preference: Option<crate::GeometryPath>,
199}
200
201impl NullInstance {
202    /// A null instance reporting one adapter with `caps`.
203    #[must_use]
204    pub fn new(caps: DeviceCaps) -> Self {
205        Self {
206            recorder: Recorder::new(),
207            caps,
208            name: "null adapter".to_string(),
209            id: next_owner_id(),
210            adapter_count: 1,
211            geometry_preference: None,
212        }
213    }
214
215    /// Prefers a supported geometry tail while retaining the capability ceiling.
216    /// If a device request omits that tail's feature, uses its granted ceiling.
217    ///
218    /// # Panics
219    /// Panics if this instance's capabilities cannot run `path`.
220    #[must_use]
221    pub fn with_geometry_preference(mut self, path: crate::GeometryPath) -> Self {
222        assert!(supports_geometry_path(self.caps.features, path));
223        self.geometry_preference = Some(path);
224        self
225    }
226
227    /// A full desktop device: everything in [`Features::GPU_DRIVEN`] —
228    /// bindless, buffer device address, `draw_indirect_count`, multi-draw,
229    /// compute, timeline semaphores — plus push constants, timestamps, the
230    /// other query kinds and a draw index.
231    ///
232    /// [`Features::DRAW_INDEX`] is outside the default request, like
233    /// [`Features::POLYGON_MODE_LINE`]: a device opened with
234    /// [`DeviceDesc::for_adapter`](crate::DeviceDesc::for_adapter) is not
235    /// granted it, and a test that wants a renderer drawing a range of buckets
236    /// per call asks for it by name.
237    ///
238    /// Not mesh shaders and not ray tracing: those are separate selector axes,
239    /// and a preset that held every flag would leave
240    /// [`GeometryPath::MeshShader`](crate::GeometryPath::MeshShader) as the only
241    /// answer any test could get.
242    #[must_use]
243    pub fn gpu_driven() -> Self {
244        Self::new(DeviceCaps {
245            features: Features::GPU_DRIVEN
246                | Features::INDIRECT_FIRST_INSTANCE
247                | Features::TIMESTAMP_QUERY
248                | Features::PIPELINE_STATISTICS_QUERY
249                | Features::OCCLUSION_QUERY
250                | Features::ASYNC_COMPUTE_QUEUE
251                | Features::TRANSFER_QUEUE
252                | Features::PUSH_CONSTANTS
253                | Features::DEPTH_CLAMP
254                | Features::DEPTH_BIAS_CLAMP
255                | Features::POLYGON_MODE_LINE
256                | Features::TEXTURE_COMPRESSION_BC
257                | Features::SAMPLER_ANISOTROPY
258                | Features::DEBUG_MARKERS
259                | Features::DRAW_INDEX,
260            limits: Limits::desktop(),
261        })
262    }
263
264    /// The floor every backend clears, shaped like WebGPU: compute only.
265    ///
266    /// No descriptor indexing, no buffer device address, no
267    /// `draw_indirect_count`, no multi-draw, no push constants, no timeline
268    /// semaphores, and — the shape that matters most — an **implicit swapchain
269    /// acquire**, so [`AcquiredFrame`] comes back with no semaphores at all.
270    /// Every selector lands on its lowest value here. Renderer code that works
271    /// against both presets works against `crcbl-vk` and `crcbl-webgpu`.
272    #[must_use]
273    pub fn portable() -> Self {
274        let mut instance = Self::new(DeviceCaps {
275            features: Features::COMPUTE | Features::TEXTURE_COMPRESSION_BC,
276            limits: Limits::minimum(),
277        });
278        instance.name = "null adapter (portable)".to_string();
279        instance
280    }
281
282    /// This instance's adapter, plus [`Features::PRESENT_FEEDBACK`].
283    ///
284    /// Neither preset advertises it and neither should: there is no display
285    /// under this backend, so an adapter that claimed by default to observe
286    /// presents would be telling every test that opened one something untrue.
287    /// But the capability is the switch on the seam's two answers for
288    /// [`Device::wait_until_presented`] — without it the wait must return `Ok`
289    /// at once, with it the wait may lapse — so a caller's timed-out-wait path
290    /// needs a device that claims it, and until this existed such a device had
291    /// to be assembled from [`DeviceCaps`] by hand in each test that wanted
292    /// one.
293    ///
294    /// Claiming it is only half of what makes a wait lapse: nothing here is
295    /// slow, so the timeout itself comes from
296    /// [`Recorder::report_present_wait_timeouts`]. And this is the *adapter's*
297    /// capability, so a device still gets it only by asking, as it would from a
298    /// real backend.
299    #[must_use]
300    pub fn with_present_feedback(mut self) -> Self {
301        self.caps.features.insert(Features::PRESENT_FEEDBACK);
302        self
303    }
304
305    /// Reports `count` adapters instead of one, all with this instance's caps,
306    /// each named with its index once there is more than one to tell apart.
307    ///
308    /// The switch on the seam's **adapter selection** loop, which needs more
309    /// than one adapter before it is a loop at all. `crcbl/src/engine.rs`'s
310    /// `start_device` walks the list asking each adapter for
311    /// [`SurfaceCaps`] and takes the first that answers, because
312    /// `crates/crcbl/tests/windowed_e2e.rs` found a discrete RADV GPU that
313    /// enumerates first under Xvfb and cannot present to the window at all
314    /// while the software rasteriser behind it can. With one adapter that walk
315    /// has one outcome, so neither "the first refused and the second served"
316    /// nor "every one refused" could be driven from any backend here.
317    ///
318    /// Reporting more than one is only half of it: nothing here makes an
319    /// adapter *refuse*, so the refusal comes from
320    /// [`Recorder::refuse_surface_on`]. The adapters are otherwise identical —
321    /// same caps, same [`DeviceType::Cpu`] — because this backend has one set
322    /// of capabilities and an adapter here claiming to be a discrete GPU would
323    /// be telling every test that opened one something untrue.
324    ///
325    /// `count` may be `0`, which is a real state a real instance reaches — a
326    /// machine with no GPU, a browser with no WebGPU — and the one the engine
327    /// answers with "no adapter" before it walks anything.
328    #[must_use]
329    pub fn with_adapters(mut self, count: u32) -> Self {
330        self.adapter_count = count;
331        self
332    }
333
334    /// Uses `recorder` instead of this instance's own, so a caller can keep a
335    /// handle on the stream after the instance is boxed as `dyn Instance`.
336    #[must_use]
337    pub fn with_recorder(mut self, recorder: Recorder) -> Self {
338        self.recorder = recorder;
339        self
340    }
341
342    /// A clone of this instance's recorder.
343    #[must_use]
344    pub fn recorder(&self) -> Recorder {
345        self.recorder.clone()
346    }
347
348    /// Whether this backend models an implicit (WebGPU-style) swapchain
349    /// acquire, in which case [`AcquiredFrame`] carries no semaphores.
350    fn implicit_acquire(&self) -> bool {
351        !self.caps.features.contains(Features::TIMELINE_SEMAPHORE)
352    }
353
354    /// Resolves a surface handle against *this* instance.
355    fn check_surface(&self, surface: SurfaceHandle) -> Result<(), HalError> {
356        let state = self.recorder.lock();
357        if state.is_owned_by(ObjectKind::Surface, surface.to_bits(), self.id) {
358            Ok(())
359        } else if state.is_live(ObjectKind::Surface, surface.to_bits()) {
360            Err(HalError::ForeignObject {
361                kind: "surface",
362                bits: surface.to_bits(),
363            })
364        } else {
365            Err(HalError::invalid_handle("surface", surface))
366        }
367    }
368}
369
370impl Instance for NullInstance {
371    fn backend(&self) -> BackendKind {
372        BackendKind::Null
373    }
374
375    fn adapters(&self) -> Vec<AdapterInfo> {
376        (0..self.adapter_count)
377            .map(|index| AdapterInfo {
378                id: AdapterId(index),
379                // A lone adapter keeps the preset's plain name; a list suffixes
380                // the index, so a log line or an assertion can say *which* one
381                // was taken rather than only that one was.
382                name: if self.adapter_count == 1 {
383                    self.name.clone()
384                } else {
385                    format!("{} #{index}", self.name)
386                },
387                vendor_id: 0,
388                device_id: 0,
389                device_type: DeviceType::Cpu,
390                driver: format!("crcbl-hal {}", env!("CARGO_PKG_VERSION")),
391                backend: BackendKind::Null,
392                caps: self.caps,
393            })
394            .collect()
395    }
396
397    unsafe fn create_surface(&self, target: &SurfaceTarget) -> Result<SurfaceHandle, HalError> {
398        // Nothing is dereferenced, which is why this implementation is sound for
399        // any input — the `unsafe` on the trait method is a contract real
400        // backends need, not one this one uses.
401        let mut state = self.recorder.lock();
402        Ok(state.insert_owned(
403            ObjectKind::Surface,
404            self.id,
405            Some(target.platform_name().to_string()),
406            Detail::None,
407        ))
408    }
409
410    fn destroy_surface(&self, surface: SurfaceHandle) {
411        // Only this instance's surfaces; another instance's handle may collide
412        // on bits and must not be destroyed by mistake. One lock, not two: a
413        // check-then-act pair on a non-reentrant mutex is both racy and a
414        // deadlock waiting for a scoping change.
415        let mut state = self.recorder.lock();
416        if state.is_owned_by(ObjectKind::Surface, surface.to_bits(), self.id) {
417            state.remove(ObjectKind::Surface, surface.to_bits());
418        }
419    }
420
421    fn surface_caps(
422        &self,
423        surface: SurfaceHandle,
424        adapter: AdapterId,
425    ) -> Result<SurfaceCaps, HalError> {
426        if adapter.0 >= self.adapter_count {
427            return Err(HalError::NoSuchAdapter(adapter.0));
428        }
429        self.check_surface(surface)?;
430        // After the checks and outside their lock, as every other injection
431        // point in this backend is: `check_surface` takes the recorder's mutex
432        // and it is not reentrant.
433        if self.recorder.refuses_surface(adapter) {
434            return Err(HalError::Unsupported {
435                backend: BackendKind::Null,
436                what: "this adapter cannot present to this surface",
437            });
438        }
439        Ok(SurfaceCaps {
440            formats: SURFACE_FORMATS.to_vec(),
441            present_modes: if self.implicit_acquire() {
442                vec![PresentMode::Fifo]
443            } else {
444                vec![
445                    PresentMode::Fifo,
446                    PresentMode::Mailbox,
447                    PresentMode::Immediate,
448                ]
449            },
450            composite_alpha: vec![CompositeAlpha::Opaque],
451            min_image_count: RING_MIN_IMAGES,
452            max_image_count: RING_MAX_IMAGES,
453            current_extent: None,
454        })
455    }
456
457    fn request_device(&self, desc: &DeviceDesc<'_>) -> Result<Box<dyn PendingDevice>, HalError> {
458        if desc.adapter.0 >= self.adapter_count {
459            return Err(HalError::NoSuchAdapter(desc.adapter.0));
460        }
461        let missing = self.caps.missing(desc.required_features);
462        if !missing.is_empty() {
463            return Err(HalError::UnsupportedFeatures { missing });
464        }
465        if let Some(surface) = desc.compatible_surface {
466            self.check_surface(surface)?;
467        }
468        // Optional features are granted only where the adapter has them, which
469        // is the behaviour a caller must handle on a real backend. The union
470        // with `required_features` that used to be here was dead: anything
471        // required and absent left through `missing` above.
472        let caps = DeviceCaps {
473            features: self
474                .caps
475                .features
476                .intersection(desc.required_features.union(desc.optional_features)),
477            limits: self.caps.limits,
478        };
479        // Everything checkable is checked above, synchronously, which is the
480        // seam's rule: only what depends on a driver answering may be deferred.
481        // The null backend has no driver, so all that is left to defer is the
482        // simulated latency.
483        let device = NullDevice {
484            recorder: self.recorder.clone(),
485            instance_id: self.id,
486            device_id: next_owner_id(),
487            // The *device's* granted features decide the acquire shape, not the
488            // adapter's. A caller that never asked for timeline semaphores gets
489            // the implicit-acquire shape even on a fully featured adapter,
490            // which is
491            // exactly what it would get from a real backend.
492            implicit_acquire: !caps.features.contains(Features::TIMELINE_SEMAPHORE),
493            caps,
494            adapter_features: self.caps.features,
495            geometry_preference: self
496                .geometry_preference
497                .filter(|path| supports_geometry_path(caps.features, *path)),
498        };
499        let polls_remaining = self.recorder.lock().device_latency;
500        Ok(Box::new(NullPendingDevice {
501            polls_remaining,
502            device: Some(Box::new(device)),
503        }))
504    }
505}
506
507/// A null device request in flight.
508///
509/// Reached through `dyn PendingDevice` from
510/// [`Instance::request_device`]. The device is
511/// built up front — nothing about it can fail late — and handed over once the
512/// simulated latency from
513/// [`Recorder::set_device_latency`] has elapsed, which is how a caller's poll
514/// loop gets exercised with no GPU and no browser.
515#[derive(Debug)]
516struct NullPendingDevice {
517    polls_remaining: u32,
518    /// `None` once the device has been handed over, so a second poll is the
519    /// caller bug it is rather than a second device.
520    device: Option<Box<dyn Device>>,
521}
522
523impl PendingDevice for NullPendingDevice {
524    fn backend(&self) -> BackendKind {
525        BackendKind::Null
526    }
527
528    fn poll(&mut self) -> Result<DeviceRequestState, HalError> {
529        let Some(device) = self.device.take() else {
530            return Err(HalError::InvalidDescriptor(
531                "this device request already produced its device".to_string(),
532            ));
533        };
534        if self.polls_remaining > 0 {
535            self.polls_remaining -= 1;
536            self.device = Some(device);
537            return Ok(DeviceRequestState::Pending);
538        }
539        Ok(DeviceRequestState::Ready(device))
540    }
541}
542
543/// A no-op, recording [`Device`].
544///
545/// Reached through `dyn Device` from [`Instance::request_device`] — and from
546/// `Instance::create_device`, which wraps it and does not exist on `wasm32`;
547/// there is no reason for a test to name this type.
548#[derive(Debug)]
549struct NullDevice {
550    recorder: Recorder,
551    /// Id of the instance that created this device. Surfaces are checked
552    /// against this, so any device from that instance may use them.
553    instance_id: u64,
554    /// Id stamped into every object this device creates.
555    device_id: u64,
556    caps: DeviceCaps,
557    /// Everything the adapter can do, which may exceed what this device
558    /// enabled. Used to decide which queues exist.
559    adapter_features: Features,
560    implicit_acquire: bool,
561    geometry_preference: Option<crate::GeometryPath>,
562}
563
564impl NullDevice {
565    /// Resolves a handle against an expected owner.
566    ///
567    /// Three outcomes, kept distinct because their fixes differ: resolved,
568    /// resolved-but-someone-else's ([`HalError::ForeignObject`]), and gone
569    /// ([`HalError::InvalidHandle`]).
570    fn check_owner(
571        &self,
572        kind: ObjectKind,
573        bits: u64,
574        name: &'static str,
575        owner: u64,
576    ) -> Result<(), HalError> {
577        self.check_lost()?;
578        let state = self.recorder.lock();
579        if state.is_owned_by(kind, bits, owner) {
580            Ok(())
581        } else if state.is_live(kind, bits) {
582            Err(HalError::ForeignObject { kind: name, bits })
583        } else {
584            Err(HalError::InvalidHandle { kind: name, bits })
585        }
586    }
587
588    /// Resolves a device-owned handle.
589    fn check(&self, kind: ObjectKind, bits: u64, name: &'static str) -> Result<(), HalError> {
590        self.check_owner(kind, bits, name, self.device_id)
591    }
592
593    /// Fails once [`Recorder::lose_device`] has been called, and thereafter.
594    ///
595    /// One insertion point rather than one per method: [`check_owner`] and
596    /// [`check_queue`] are the two funnels every fallible call that names a
597    /// handle already passes through, so gating them is what makes a lost
598    /// device lost everywhere at once — and it lands the error in the right
599    /// vocabulary for free, since the presentation calls wrap what they return
600    /// in [`SurfaceError::Hal`], which is exactly what `crcbl-vk`'s
601    /// `surface_error` does with `VK_ERROR_DEVICE_LOST`.
602    ///
603    /// [`check_owner`]: Self::check_owner
604    /// [`check_queue`]: Self::check_queue
605    fn check_lost(&self) -> Result<(), HalError> {
606        match self.recorder.lock().lost_device.clone() {
607            Some(message) => Err(HalError::DeviceLost(message)),
608            None => Ok(()),
609        }
610    }
611
612    /// Resolves a swapchain handle for one of the three calls a frame makes on
613    /// it, and reports the out-of-date latch first.
614    ///
615    /// `acquire_next_frame`, `present` and `wait_until_presented` all have to
616    /// answer the same way while the surface has moved under the swapchain —
617    /// that is what makes a resize storm a storm rather than one bad call — so
618    /// they ask in one place instead of three.
619    ///
620    /// The handle is resolved *before* the latch is read, so a swapchain that
621    /// was destroyed still reports its own bug rather than an out-of-date one;
622    /// and a lost device beats both, through [`check_lost`](Self::check_lost)
623    /// inside the resolve.
624    fn check_current(&self, swapchain: SwapchainHandle) -> Result<(), SurfaceError> {
625        self.check(ObjectKind::Swapchain, swapchain.to_bits(), "swapchain")
626            .map_err(SurfaceError::Hal)?;
627        if self.recorder.lock().swapchain_out_of_date {
628            return Err(SurfaceError::OutOfDate);
629        }
630        Ok(())
631    }
632
633    /// Resolves an instance-owned handle — surfaces, and only surfaces.
634    fn check_instance_owned(
635        &self,
636        kind: ObjectKind,
637        bits: u64,
638        name: &'static str,
639    ) -> Result<(), HalError> {
640        self.check_owner(kind, bits, name, self.instance_id)
641    }
642
643    /// Resolves one pipeline stage: its module handle, and that the module can
644    /// actually supply the entry point the stage names.
645    ///
646    /// The second half only bites a module that offered DXIL. That is the one
647    /// artifact format with a container *per entry point*, so it is the one a
648    /// call site can under-supply — offering the vertex container and not the
649    /// fragment one leaves every other backend working and D3D12 with no
650    /// bytecode for half the pipeline. Every real backend that consumes DXIL
651    /// refuses that; saying so here means the no-GPU suite catches it on a
652    /// machine with no D3D12, which is where these call sites are written.
653    ///
654    /// A module with no DXIL at all is not held to anything: it made no claim,
655    /// and the backends that read its SPIR-V, WGSL or MSL find every entry
656    /// point inside the one artifact.
657    fn check_stage(&self, stage: crate::ShaderEntry<'_>) -> Result<(), HalError> {
658        let bits = stage.module.to_bits();
659        self.check(ObjectKind::ShaderModule, bits, "shader module")?;
660        let state = self.recorder.lock();
661        let Some(Detail::ShaderModule { dxil }) = state
662            .get(ObjectKind::ShaderModule, bits)
663            .map(|object| &object.detail)
664        else {
665            return Ok(());
666        };
667        if dxil.is_empty() || dxil.iter().any(|(name, _)| name == stage.entry_point) {
668            return Ok(());
669        }
670        Err(HalError::ShaderCompilation(format!(
671            "shader module `{label}` offers DXIL for {held}, and this stage names `{wanted}`; a \
672             DXIL container is compiled for one entry point, so a module used at two stages has \
673             to offer a container for each",
674            label = state
675                .get(ObjectKind::ShaderModule, bits)
676                .and_then(|object| object.label.as_deref())
677                .unwrap_or("<unlabelled>"),
678            held = dxil
679                .iter()
680                .map(|(name, _)| name.as_str())
681                .collect::<Vec<_>>()
682                .join(", "),
683            wanted = stage.entry_point,
684        )))
685    }
686
687    /// Files a pipeline that has passed every check in
688    /// [`Recorder::pipelines_created`], resolving its layout's sets and each
689    /// stage's DXIL container while the handles are still live.
690    fn record_pipeline(
691        &self,
692        label: Option<&str>,
693        layout: PipelineLayoutHandle,
694        stages: &[(ShaderStages, crate::ShaderEntry<'_>)],
695    ) {
696        let mut state = self.recorder.lock();
697        let (sets, push_constants) = match state
698            .get(ObjectKind::PipelineLayout, layout.to_bits())
699            .map(|object| &object.detail)
700        {
701            Some(Detail::PipelineLayout {
702                sets,
703                push_constants,
704            }) => (sets.clone(), *push_constants),
705            _ => unreachable!("every caller checked the pipeline layout handle first"),
706        };
707        let stages = stages
708            .iter()
709            .map(|(stage, entry)| StageRecord {
710                stage: *stage,
711                entry_point: entry.entry_point.to_owned(),
712                dxil: match state
713                    .get(ObjectKind::ShaderModule, entry.module.to_bits())
714                    .map(|object| &object.detail)
715                {
716                    Some(Detail::ShaderModule { dxil }) => dxil
717                        .iter()
718                        .find(|(name, _)| name == entry.entry_point)
719                        .map(|(_, bytes)| bytes.clone()),
720                    _ => None,
721                },
722            })
723            .collect();
724        state.pipelines_created.push(PipelineRecord {
725            label: label.map(ToOwned::to_owned),
726            sets,
727            push_constants,
728            stages,
729        });
730    }
731
732    fn insert<T>(&self, kind: ObjectKind, label: Option<&str>, detail: Detail) -> Handle<T> {
733        self.recorder.lock().insert_owned(
734            kind,
735            self.device_id,
736            label.map(ToOwned::to_owned),
737            detail,
738        )
739    }
740
741    /// Destroys a handle, but only if this device owns it.
742    ///
743    /// One lock for the check and the removal — see `destroy_surface`.
744    fn remove(&self, kind: ObjectKind, bits: u64) {
745        let mut state = self.recorder.lock();
746        if state.is_owned_by(kind, bits, self.device_id) {
747            state.remove(kind, bits);
748        }
749    }
750
751    fn unsupported(&self, what: &'static str) -> HalError {
752        HalError::Unsupported {
753            backend: BackendKind::Null,
754            what,
755        }
756    }
757
758    /// The checks a raster and a mesh pipeline share.
759    ///
760    /// Everything after the geometry stages is identical between the two —
761    /// same layout, same fragment stage, same attachment formats, same
762    /// rasteriser state — so the two `create_*_pipeline` methods differ only in
763    /// the stages they resolve and the capability they demand. Splitting it
764    /// this way is what keeps a fix to one of these checks from landing in one
765    /// pipeline kind and not the other.
766    fn check_raster_state(
767        &self,
768        layout: PipelineLayoutHandle,
769        fragment: Option<crate::ShaderEntry<'_>>,
770        color_targets: &[crate::ColorTargetState],
771        primitive: crate::PrimitiveState,
772        depth_stencil: Option<crate::DepthStencilState>,
773    ) -> Result<(), HalError> {
774        self.check(
775            ObjectKind::PipelineLayout,
776            layout.to_bits(),
777            "pipeline layout",
778        )?;
779        if let Some(fragment) = fragment {
780            self.check_stage(fragment)?;
781        }
782        if color_targets.len() > self.caps.limits.max_color_attachments as usize {
783            return Err(HalError::InvalidDescriptor(format!(
784                "{} colour targets exceeds max_color_attachments {}",
785                color_targets.len(),
786                self.caps.limits.max_color_attachments
787            )));
788        }
789        if primitive.polygon_mode == crate::PolygonMode::Line
790            && !self.caps.features.contains(Features::POLYGON_MODE_LINE)
791        {
792            return Err(self.unsupported("wireframe polygon mode"));
793        }
794        if primitive.depth_clamp && !self.caps.features.contains(Features::DEPTH_CLAMP) {
795            return Err(self.unsupported("depth clamping"));
796        }
797        if let Some(depth) = depth_stencil
798            && !depth.format.is_depth_stencil()
799        {
800            return Err(HalError::InvalidDescriptor(format!(
801                "{:?} is not a depth/stencil format",
802                depth.format
803            )));
804        }
805        Ok(())
806    }
807
808    /// Whether this device has a queue of `kind` at all.
809    fn has_queue(&self, kind: QueueKind) -> bool {
810        match kind {
811            QueueKind::Graphics => true,
812            QueueKind::Compute => self
813                .adapter_features
814                .contains(Features::ASYNC_COMPUTE_QUEUE),
815            QueueKind::Transfer => self.adapter_features.contains(Features::TRANSFER_QUEUE),
816        }
817    }
818
819    /// Resolves a queue handle against *this* device.
820    ///
821    /// Obligation 3 covers queues too. `submit`, `present` and
822    /// `create_command_encoder` used to ignore the argument entirely, so a
823    /// handle from another device — or a hand-made one — submitted happily.
824    fn check_queue(&self, queue: QueueHandle) -> Result<(), HalError> {
825        self.check_lost()?;
826        let bits = queue.to_bits();
827        let Some(index) = queue_index_of(self.device_id, queue) else {
828            // Another device's queue handle is well-formed but not ours; a
829            // hand-made one is neither, and there is no way to tell them apart
830            // from the bits, so the more specific error is the honest one only
831            // when the shape is right.
832            return Err(if queue.generation() == 1 {
833                HalError::ForeignObject {
834                    kind: "queue",
835                    bits,
836                }
837            } else {
838                HalError::InvalidHandle {
839                    kind: "queue",
840                    bits,
841                }
842            });
843        };
844        let kind = match index {
845            0 => QueueKind::Graphics,
846            1 => QueueKind::Compute,
847            2 => QueueKind::Transfer,
848            _ => {
849                return Err(HalError::InvalidHandle {
850                    kind: "queue",
851                    bits,
852                });
853            }
854        };
855        if self.has_queue(kind) {
856            Ok(())
857        } else {
858            Err(HalError::InvalidHandle {
859                kind: "queue",
860                bits,
861            })
862        }
863    }
864}
865
866/// The refusal both signalling paths share: a timeline only moves forwards.
867///
868/// One wording for [`Device::signal_semaphore`] and [`Device::submit`], because
869/// the rule is the semaphore's rather than either call's — a caller that learns
870/// it from the host signal meets the same rule the moment a submission carries
871/// one, and two spellings of it would read as two different rules.
872fn timeline_goes_backwards(value: u64, held: u64) -> HalError {
873    HalError::InvalidDescriptor(format!(
874        "a timeline semaphore signalled with {value} already holds {held}; a timeline only moves \
875         forwards and a waiter on the higher value would never wake"
876    ))
877}
878
879/// The index a queue kind occupies in a synthesised handle.
880const fn queue_kind_index(kind: QueueKind) -> u32 {
881    match kind {
882        QueueKind::Graphics => 0,
883        QueueKind::Compute => 1,
884        QueueKind::Transfer => 2,
885    }
886}
887
888fn supports_geometry_path(features: Features, path: crate::GeometryPath) -> bool {
889    match path {
890        crate::GeometryPath::MeshShader => features.contains(Features::MESH_SHADER),
891        crate::GeometryPath::IndirectCount => features.contains(Features::DRAW_INDIRECT_COUNT),
892        crate::GeometryPath::IndirectPerBatch => true,
893    }
894}
895
896impl Device for NullDevice {
897    fn backend(&self) -> BackendKind {
898        BackendKind::Null
899    }
900
901    fn caps(&self) -> DeviceCaps {
902        self.caps
903    }
904
905    fn preferred_geometry_path(&self) -> crate::GeometryPath {
906        self.geometry_preference
907            .unwrap_or_else(|| self.caps.geometry_path())
908    }
909
910    /// What this recorder does with each seam behaviour.
911    ///
912    /// **"Supported" here means recorded faithfully, not executed.** This
913    /// backend has no GPU, so a [`Support::Yes`] is the claim that the call is
914    /// accepted with all of its arguments and appears in the stream a test reads
915    /// back — which is exactly the property the graph's unit suite asserts
916    /// against, and all a recorder can promise.
917    ///
918    /// The refusals are the ones this backend already has, and every one of them
919    /// is a feature the preset did not grant: `NullInstance::portable` and
920    /// `NullInstance::gpu_driven` differ, so this answer differs between two
921    /// devices of the same backend, which is the shape a real backend's answer
922    /// has too.
923    ///
924    /// Exhaustive with no wildcard arm, and `deny`-ed as such: a capability
925    /// added to the enum has to be answered here as well as in the five GPU
926    /// backends, because a recorder that silently accepted a command nothing
927    /// implements would be the first place the rot could hide.
928    #[deny(clippy::wildcard_enum_match_arm)]
929    fn supports(&self, capability: Capability) -> Support {
930        let has = self.caps.features;
931        // One place the "the preset did not grant it" sentence is written, so
932        // fourteen arms cannot word it fourteen ways.
933        let gated = |feature: Features, why: &'static str| -> Support {
934            Support::granted(has, feature, why)
935        };
936
937        match capability {
938            // Recorded verbatim, arguments and all.
939            Capability::BufferFillZero
940            | Capability::ImageToImageCopy
941            | Capability::DepthImageCopy
942            | Capability::MsaaResolveAttachment
943            | Capability::StencilReference
944            | Capability::IndirectArgumentPaddedStride
945            | Capability::BinarySemaphore
946            | Capability::TimelineWaitBeforeSignal
947            | Capability::StorageImageBinding => Support::Yes,
948            // `update_bind_group` is refused per *layout*, on the UPDATE_AFTER_BIND
949            // flag it was built with, so the backend has the operation.
950            Capability::UpdateBindGroup => Support::Yes,
951            Capability::DrawIndirectCount => gated(
952                Features::DRAW_INDIRECT_COUNT,
953                "this preset did not grant DRAW_INDIRECT_COUNT",
954            ),
955            Capability::MeshShading => gated(
956                Features::MESH_SHADER,
957                "this preset did not grant MESH_SHADER",
958            ),
959            Capability::TaskShaderStage => gated(
960                Features::TASK_SHADER,
961                "this preset did not grant TASK_SHADER",
962            ),
963            Capability::PushConstants => gated(
964                Features::PUSH_CONSTANTS,
965                "this preset did not grant PUSH_CONSTANTS",
966            ),
967            Capability::BindlessDescriptorArray => gated(
968                Features::DESCRIPTOR_INDEXING,
969                "this preset did not grant DESCRIPTOR_INDEXING",
970            ),
971            Capability::PolygonModeLine => gated(
972                Features::POLYGON_MODE_LINE,
973                "this preset did not grant POLYGON_MODE_LINE",
974            ),
975            Capability::DepthClamp => gated(
976                Features::DEPTH_CLAMP,
977                "this preset did not grant DEPTH_CLAMP",
978            ),
979            Capability::SamplerAnisotropy => gated(
980                Features::SAMPLER_ANISOTROPY,
981                "this preset did not grant SAMPLER_ANISOTROPY",
982            ),
983            Capability::TimestampQuery => gated(
984                Features::TIMESTAMP_QUERY,
985                "this preset did not grant TIMESTAMP_QUERY",
986            ),
987            // Not a preset question, unlike every gate around it: this
988            // recorder refuses the kind whatever it was granted, because what
989            // is missing is a verb on `CommandEncoder` rather than a feature on
990            // a device. See `crate::NO_OCCLUSION_QUERY_VERB`, and
991            // `create_query_set` below, which refuses the same set.
992            Capability::OcclusionQuery => Support::No(crate::NO_OCCLUSION_QUERY_VERB),
993            Capability::PipelineStatisticsQuery => gated(
994                Features::PIPELINE_STATISTICS_QUERY,
995                "this preset did not grant PIPELINE_STATISTICS_QUERY",
996            ),
997            Capability::TimelineSemaphore
998            | Capability::CpuTimelineWait
999            | Capability::CpuTimelineSignal => gated(
1000                Features::TIMELINE_SEMAPHORE,
1001                "this preset did not grant TIMELINE_SEMAPHORE",
1002            ),
1003        }
1004    }
1005
1006    /// Whatever [`Recorder::report_device_error`] queued, oldest first.
1007    ///
1008    /// Nothing in this backend fails on its own — it is a recorder, not a
1009    /// driver — so every error here was put there by a test that wants to see
1010    /// what its caller does with one.
1011    fn take_error(&self) -> Option<String> {
1012        self.recorder.take_device_error()
1013    }
1014
1015    fn queue(&self, kind: QueueKind) -> Option<QueueHandle> {
1016        self.has_queue(kind)
1017            .then(|| queue_handle(self.device_id, queue_kind_index(kind)))
1018    }
1019
1020    // --- resources ---
1021
1022    fn create_buffer(&self, desc: &BufferDesc<'_>) -> Result<BufferHandle, HalError> {
1023        if desc.size == 0 {
1024            return Err(HalError::InvalidDescriptor(
1025                "buffer size must be non-zero".to_string(),
1026            ));
1027        }
1028        let bytes = if desc.memory.is_mappable() {
1029            vec![
1030                0u8;
1031                usize::try_from(desc.size).map_err(|_| {
1032                    HalError::InvalidDescriptor("mappable buffer larger than usize".to_string())
1033                })?
1034            ]
1035        } else {
1036            Vec::new()
1037        };
1038        Ok(self.insert(
1039            ObjectKind::Buffer,
1040            desc.label,
1041            Detail::Buffer {
1042                size: desc.size,
1043                memory: desc.memory,
1044                bytes,
1045            },
1046        ))
1047    }
1048
1049    fn destroy_buffer(&self, buffer: BufferHandle) {
1050        self.remove(ObjectKind::Buffer, buffer.to_bits());
1051    }
1052
1053    fn write_buffer(&self, buffer: BufferHandle, offset: u64, data: &[u8]) -> Result<(), HalError> {
1054        self.check(ObjectKind::Buffer, buffer.to_bits(), "buffer")?;
1055        let mut state = self.recorder.lock();
1056        let Some(object) = state.get_mut(ObjectKind::Buffer, buffer.to_bits()) else {
1057            return Err(HalError::invalid_handle("buffer", buffer));
1058        };
1059        let Detail::Buffer {
1060            size,
1061            memory,
1062            bytes,
1063        } = &mut object.detail
1064        else {
1065            unreachable!("a buffer handle always carries buffer detail");
1066        };
1067        if *memory != MemoryLocation::HostUpload {
1068            return Err(HalError::InvalidDescriptor(format!(
1069                "write_buffer needs HostUpload memory, buffer is {memory:?}"
1070            )));
1071        }
1072        let start = usize::try_from(offset)
1073            .map_err(|_| HalError::InvalidDescriptor("offset exceeds usize".to_string()))?;
1074        let end = start
1075            .checked_add(data.len())
1076            .ok_or_else(|| HalError::InvalidDescriptor("offset + len overflows".to_string()))?;
1077        if end as u64 > *size {
1078            return Err(HalError::InvalidDescriptor(format!(
1079                "write of {} bytes at {offset} exceeds the {size}-byte buffer",
1080                data.len(),
1081            )));
1082        }
1083        bytes[start..end].copy_from_slice(data);
1084        state.events.push(Event::BufferWritten {
1085            buffer,
1086            offset,
1087            len: data.len(),
1088        });
1089        Ok(())
1090    }
1091
1092    fn request_readback(&self, desc: &ReadbackDesc<'_>) -> Result<ReadbackHandle, HalError> {
1093        self.check(ObjectKind::Buffer, desc.buffer.to_bits(), "buffer")?;
1094        if let Some(wait) = desc.after {
1095            self.check(ObjectKind::Semaphore, wait.semaphore.to_bits(), "semaphore")?;
1096        }
1097        // Re-resolved under a fresh lock, so a concurrent `destroy_buffer` in
1098        // the gap since `check` is an `InvalidHandle` rather than a panic:
1099        // `Device` is `&self + Send + Sync`, so that gap is reachable.
1100        let (memory, buffer_size) = {
1101            let state = self.recorder.lock();
1102            let Some(object) = state.get(ObjectKind::Buffer, desc.buffer.to_bits()) else {
1103                return Err(HalError::invalid_handle("buffer", desc.buffer));
1104            };
1105            let Detail::Buffer { size, memory, .. } = &object.detail else {
1106                unreachable!("a buffer handle always carries buffer detail");
1107            };
1108            (*memory, *size)
1109        };
1110        if memory != MemoryLocation::HostReadback {
1111            return Err(HalError::InvalidDescriptor(format!(
1112                "readback needs HostReadback memory, buffer is {memory:?}"
1113            )));
1114        }
1115        let end = desc
1116            .offset
1117            .checked_add(desc.size)
1118            .ok_or_else(|| HalError::InvalidDescriptor("offset + size overflows".to_string()))?;
1119        if end > buffer_size {
1120            return Err(HalError::InvalidDescriptor(format!(
1121                "readback of {} bytes at {} exceeds the {buffer_size}-byte buffer",
1122                desc.size, desc.offset
1123            )));
1124        }
1125        let mut state = self.recorder.lock();
1126        let polls_remaining = state.readback_latency;
1127        let handle = state.insert_owned(
1128            ObjectKind::Readback,
1129            self.device_id,
1130            desc.label.map(ToOwned::to_owned),
1131            Detail::Readback {
1132                buffer: desc.buffer,
1133                offset: desc.offset,
1134                size: desc.size,
1135                polls_remaining,
1136            },
1137        );
1138        state.events.push(Event::ReadbackRequested {
1139            buffer: desc.buffer,
1140            offset: desc.offset,
1141            size: desc.size,
1142        });
1143        Ok(handle)
1144    }
1145
1146    fn poll_readback(
1147        &self,
1148        readback: ReadbackHandle,
1149        out: &mut [u8],
1150    ) -> Result<ReadbackState, HalError> {
1151        self.check(ObjectKind::Readback, readback.to_bits(), "readback")?;
1152        let (buffer, offset, ready) = {
1153            let mut state = self.recorder.lock();
1154            let Some(object) = state.get_mut(ObjectKind::Readback, readback.to_bits()) else {
1155                return Err(HalError::invalid_handle("readback", readback));
1156            };
1157            let Detail::Readback {
1158                buffer,
1159                offset,
1160                size,
1161                polls_remaining,
1162            } = &mut object.detail
1163            else {
1164                unreachable!("a readback handle always carries readback detail");
1165            };
1166            // The descriptor check happens *before* the simulated latency
1167            // advances. A rejected poll must not consume one: a caller whose
1168            // slice is the wrong length would otherwise see the configured
1169            // latency shortened by however many times it got the length wrong,
1170            // which makes the latency it is being tested against a lie.
1171            if out.len() as u64 != *size {
1172                return Err(HalError::InvalidDescriptor(format!(
1173                    "poll_readback needs a {size}-byte slice, got {}",
1174                    out.len()
1175                )));
1176            }
1177            let ready = *polls_remaining == 0;
1178            if !ready {
1179                *polls_remaining -= 1;
1180            }
1181            (*buffer, *offset, ready)
1182        };
1183        if !ready {
1184            return Ok(ReadbackState::Pending);
1185        }
1186        // The source buffer may have been destroyed between request and poll,
1187        // which is a caller bug and must be reported rather than read.
1188        self.check(ObjectKind::Buffer, buffer.to_bits(), "buffer")?;
1189        let mut state = self.recorder.lock();
1190        let Some(object) = state.get(ObjectKind::Buffer, buffer.to_bits()) else {
1191            return Err(HalError::invalid_handle("buffer", buffer));
1192        };
1193        let Detail::Buffer { bytes, .. } = &object.detail else {
1194            unreachable!("a buffer handle always carries buffer detail");
1195        };
1196        let start = usize::try_from(offset)
1197            .map_err(|_| HalError::InvalidDescriptor("offset exceeds usize".to_string()))?;
1198        out.copy_from_slice(&bytes[start..start + out.len()]);
1199        let len = out.len();
1200        state.events.push(Event::BufferRead {
1201            buffer,
1202            offset,
1203            len,
1204        });
1205        Ok(ReadbackState::Ready)
1206    }
1207
1208    fn destroy_readback(&self, readback: ReadbackHandle) {
1209        self.remove(ObjectKind::Readback, readback.to_bits());
1210    }
1211
1212    fn create_image(&self, desc: &ImageDesc<'_>) -> Result<ImageHandle, HalError> {
1213        // Every rule this used to spell out inline is now `ImageDesc::check`,
1214        // on the seam, so a backend that wants them does not copy them. The
1215        // messages are the ones that were here; this backend is the reference
1216        // the others are compared against, so they had to stay exact.
1217        desc.check(&self.caps.limits)?;
1218        // `depth_or_layers` is the *depth* of a 3D image and the array-layer
1219        // count of every other type, so a volume has one array layer however
1220        // deep it is. Filing the raw field would make every 3D image look
1221        // `depth` layers deep to `ImageViewDesc::check`, which is the one
1222        // reading of this field that turns the rule into nonsense.
1223        let layers = if desc.image_type == ImageType::D3 {
1224            1
1225        } else {
1226            desc.extent.depth_or_layers
1227        };
1228        Ok(self.insert(
1229            ObjectKind::Image,
1230            desc.label,
1231            Detail::Image {
1232                format: desc.format,
1233                mip_levels: desc.mip_levels,
1234                layers,
1235            },
1236        ))
1237    }
1238
1239    fn destroy_image(&self, image: ImageHandle) {
1240        self.remove(ObjectKind::Image, image.to_bits());
1241    }
1242
1243    fn create_image_view(&self, desc: &ImageViewDesc<'_>) -> Result<ImageViewHandle, HalError> {
1244        self.check(ObjectKind::Image, desc.image.to_bits(), "image")?;
1245        // The seam's subresource rule, which this backend could not state
1246        // before: `create_image` filed `Detail::None`, so neither count was
1247        // anywhere to be read and a view of mips the image never had was
1248        // served here while `crcbl-mtl` and `crcbl-dx12` refused it.
1249        let (image_format, mip_levels, layers) = {
1250            let state = self.recorder.lock();
1251            let Some(object) = state.get(ObjectKind::Image, desc.image.to_bits()) else {
1252                return Err(HalError::invalid_handle("image", desc.image));
1253            };
1254            let Detail::Image {
1255                format,
1256                mip_levels,
1257                layers,
1258            } = &object.detail
1259            else {
1260                unreachable!("an image handle always carries image detail");
1261            };
1262            (*format, *mip_levels, *layers)
1263        };
1264        desc.check(image_format, mip_levels, layers)?;
1265        Ok(self.insert(ObjectKind::ImageView, desc.label, Detail::None))
1266    }
1267
1268    fn destroy_image_view(&self, view: ImageViewHandle) {
1269        self.remove(ObjectKind::ImageView, view.to_bits());
1270    }
1271
1272    fn create_sampler(&self, desc: &SamplerDesc<'_>) -> Result<SamplerHandle, HalError> {
1273        // The ceiling is the rule this backend already had, now stated once on
1274        // the seam with the message that was here. The floor is the one it did
1275        // not: `crcbl-vk`, `crcbl-mtl` and `crcbl-dx12` all refused an
1276        // anisotropy below the value that disables it while this backend — the
1277        // reference the others are compared against — served it.
1278        desc.check_anisotropy_floor()?;
1279        desc.check_anisotropy_ceiling(&self.caps.limits)?;
1280        Ok(self.insert(ObjectKind::Sampler, desc.label, Detail::None))
1281    }
1282
1283    fn destroy_sampler(&self, sampler: SamplerHandle) {
1284        self.remove(ObjectKind::Sampler, sampler.to_bits());
1285    }
1286
1287    // --- shaders and pipelines ---
1288
1289    /// Accepts every format the seam defines and records which ones it was
1290    /// handed.
1291    ///
1292    /// The null backend compiles nothing, so it is the one backend with no
1293    /// reason to prefer a format — and that is what makes it the place a test
1294    /// asserts what a *caller* supplied. See
1295    /// [`Recorder::shader_modules_created`](crate::null::Recorder::shader_modules_created).
1296    fn create_shader_module(
1297        &self,
1298        desc: &ShaderModuleDesc<'_>,
1299    ) -> Result<ShaderModuleHandle, HalError> {
1300        let sources = desc.provided();
1301        if sources.is_empty() {
1302            // Every real backend rejects this too; saying so here means the
1303            // no-GPU suite catches a call site that stopped passing artifacts.
1304            return Err(desc.unusable(ShaderSources::all()));
1305        }
1306        // The SPIR-V magic number. Checking it costs nothing and catches the
1307        // classic "passed bytes where words were wanted" mistake, which
1308        // otherwise surfaces as a driver error at P1. Only when SPIR-V was
1309        // offered at all: a WGSL-only module is legal and has no magic number.
1310        const SPIRV_MAGIC: u32 = 0x0723_0203;
1311        if let Some(&word) = desc.spirv.first()
1312            && word != SPIRV_MAGIC
1313        {
1314            return Err(HalError::ShaderCompilation(format!(
1315                "not SPIR-V: first word is {word:#010x}, expected {SPIRV_MAGIC:#010x}"
1316            )));
1317        }
1318        self.recorder
1319            .lock()
1320            .shader_modules_created
1321            .push((desc.label.map(ToOwned::to_owned), sources));
1322        Ok(self.insert(
1323            ObjectKind::ShaderModule,
1324            desc.label,
1325            Detail::ShaderModule {
1326                dxil: desc
1327                    .dxil
1328                    .iter()
1329                    .map(|(entry_point, bytes)| ((*entry_point).to_owned(), bytes.to_vec()))
1330                    .collect(),
1331            },
1332        ))
1333    }
1334
1335    fn destroy_shader_module(&self, module: ShaderModuleHandle) {
1336        self.remove(ObjectKind::ShaderModule, module.to_bits());
1337    }
1338
1339    fn create_bind_group_layout(
1340        &self,
1341        desc: &BindGroupLayoutDesc<'_>,
1342    ) -> Result<BindGroupLayoutHandle, HalError> {
1343        desc.check_entries(&self.caps, BackendKind::Null)?;
1344        let update_after_bind = desc
1345            .entries
1346            .iter()
1347            .any(|entry| entry.flags.contains(crate::BindingFlags::UPDATE_AFTER_BIND));
1348        let variable_binding = desc
1349            .entries
1350            .iter()
1351            .find(|entry| entry.flags.contains(crate::BindingFlags::VARIABLE_COUNT))
1352            .map(|entry| entry.binding);
1353        self.recorder
1354            .lock()
1355            .bind_group_layouts_created
1356            .push((desc.label.map(ToOwned::to_owned), desc.entries.to_vec()));
1357        Ok(self.insert(
1358            ObjectKind::BindGroupLayout,
1359            desc.label,
1360            Detail::BindGroupLayout {
1361                entries: desc.entries.to_vec(),
1362                update_after_bind,
1363                variable_binding,
1364            },
1365        ))
1366    }
1367
1368    fn destroy_bind_group_layout(&self, layout: BindGroupLayoutHandle) {
1369        self.remove(ObjectKind::BindGroupLayout, layout.to_bits());
1370    }
1371
1372    fn create_bind_group(&self, desc: &BindGroupDesc<'_>) -> Result<BindGroupHandle, HalError> {
1373        self.check(
1374            ObjectKind::BindGroupLayout,
1375            desc.layout.to_bits(),
1376            "bind group layout",
1377        )?;
1378        let layout = self.layout_of(desc.layout)?;
1379        // `variable_count` is what the *pool* is sized with on a real backend,
1380        // so an over-large one fails `vkAllocateDescriptorSets` with a VUID
1381        // rather than the named error the rest of the seam produces.
1382        if let Some(count) = desc.variable_count {
1383            let Some(binding) = layout.variable_binding else {
1384                return Err(HalError::InvalidDescriptor(
1385                    "BindGroupDesc::variable_count on a layout with no VARIABLE_COUNT binding"
1386                        .to_string(),
1387                ));
1388            };
1389            let ceiling = layout.binding_ceiling(binding, &self.caps);
1390            if count > ceiling {
1391                return Err(HalError::InvalidDescriptor(format!(
1392                    "variable_count {count} exceeds the {ceiling} descriptors binding {binding} \
1393                     declares"
1394                )));
1395            }
1396        }
1397        self.check_entries_against(&layout, desc.entries)?;
1398        Ok(self.insert(
1399            ObjectKind::BindGroup,
1400            desc.label,
1401            Detail::BindGroup {
1402                layout: desc.layout,
1403                update_after_bind: layout.update_after_bind,
1404            },
1405        ))
1406    }
1407
1408    fn update_bind_group(
1409        &self,
1410        group: BindGroupHandle,
1411        entries: &[BindGroupEntry],
1412    ) -> Result<(), HalError> {
1413        self.check(ObjectKind::BindGroup, group.to_bits(), "bind group")?;
1414        let (layout_handle, update_after_bind) = {
1415            let state = self.recorder.lock();
1416            let Some(object) = state.get(ObjectKind::BindGroup, group.to_bits()) else {
1417                return Err(HalError::invalid_handle("bind group", group));
1418            };
1419            let Detail::BindGroup {
1420                layout,
1421                update_after_bind,
1422            } = &object.detail
1423            else {
1424                unreachable!("a bind group handle always carries bind group detail");
1425            };
1426            (*layout, *update_after_bind)
1427        };
1428        if !update_after_bind {
1429            // The error `Device::update_bind_group` promises. Without the flag,
1430            // writing a set a pending command buffer might reference is
1431            // undefined behaviour, so refusing is the only safe answer — and
1432            // the null backend accepting it made the seam's own doc untestable.
1433            return Err(self.unsupported("update_bind_group on a layout without UPDATE_AFTER_BIND"));
1434        }
1435        let layout = self.layout_of(layout_handle)?;
1436        self.check_entries_against(&layout, entries)
1437    }
1438
1439    fn destroy_bind_group(&self, group: BindGroupHandle) {
1440        self.remove(ObjectKind::BindGroup, group.to_bits());
1441    }
1442
1443    fn create_pipeline_layout(
1444        &self,
1445        desc: &PipelineLayoutDesc<'_>,
1446    ) -> Result<PipelineLayoutHandle, HalError> {
1447        for layout in desc.bind_group_layouts {
1448            self.check(
1449                ObjectKind::BindGroupLayout,
1450                layout.to_bits(),
1451                "bind group layout",
1452            )?;
1453        }
1454        if desc.bind_group_layouts.len() > self.caps.limits.max_bind_groups as usize {
1455            return Err(HalError::InvalidDescriptor(format!(
1456                "{} bind groups exceeds max_bind_groups {}",
1457                desc.bind_group_layouts.len(),
1458                self.caps.limits.max_bind_groups
1459            )));
1460        }
1461        if let Some(range) = desc.push_constants {
1462            if !self.caps.features.contains(Features::PUSH_CONSTANTS) {
1463                // Loudly, at layout creation — not by silently dropping the
1464                // writes later. This is the trap the seam exists to make
1465                // visible.
1466                return Err(self.unsupported("push constants"));
1467            }
1468            range
1469                .stages
1470                .check_supported(self.caps.features, BackendKind::Null)?;
1471            // Saturating, not wrapping: `PushConstantRange { offset: u32::MAX,
1472            // size: 1 }` panicked in debug and wrapped to 0 in release, and 0
1473            // then *passed* the check it was supposed to fail.
1474            let end = range.offset.saturating_add(range.size);
1475            if end > self.caps.limits.max_push_constant_size {
1476                return Err(HalError::InvalidDescriptor(format!(
1477                    "push constant range ends at {end} but max_push_constant_size is {}",
1478                    self.caps.limits.max_push_constant_size
1479                )));
1480            }
1481        }
1482        let sets = desc
1483            .bind_group_layouts
1484            .iter()
1485            .map(|layout| self.layout_of(*layout).map(|record| record.entries))
1486            .collect::<Result<_, _>>()?;
1487        Ok(self.insert(
1488            ObjectKind::PipelineLayout,
1489            desc.label,
1490            Detail::PipelineLayout {
1491                sets,
1492                push_constants: desc.push_constants,
1493            },
1494        ))
1495    }
1496
1497    fn destroy_pipeline_layout(&self, layout: PipelineLayoutHandle) {
1498        self.remove(ObjectKind::PipelineLayout, layout.to_bits());
1499    }
1500
1501    fn create_graphics_pipeline(
1502        &self,
1503        desc: &GraphicsPipelineDesc<'_>,
1504    ) -> Result<GraphicsPipelineHandle, HalError> {
1505        self.check_stage(desc.vertex)?;
1506        self.check_raster_state(
1507            desc.layout,
1508            desc.fragment,
1509            desc.color_targets,
1510            desc.primitive,
1511            desc.depth_stencil,
1512        )?;
1513        let mut stages = vec![(ShaderStages::VERTEX, desc.vertex)];
1514        stages.extend(desc.fragment.map(|entry| (ShaderStages::FRAGMENT, entry)));
1515        self.record_pipeline(desc.label, desc.layout, &stages);
1516        // **The vertex stage is filed rather than dropped**, which is what makes
1517        // "this pass runs that entry point" a question with a no-GPU answer —
1518        // see [`Detail::GraphicsPipeline`], which carries the argument.
1519        Ok(self.insert(
1520            ObjectKind::GraphicsPipeline,
1521            desc.label,
1522            Detail::GraphicsPipeline {
1523                vertex_entry: desc.vertex.entry_point.to_owned(),
1524            },
1525        ))
1526    }
1527
1528    fn create_mesh_pipeline(
1529        &self,
1530        desc: &MeshPipelineDesc<'_>,
1531    ) -> Result<GraphicsPipelineHandle, HalError> {
1532        // Before anything else, so a device modelling the absent capability
1533        // refuses for the reason the caller needs to hear rather than tripping
1534        // over a stale handle first.
1535        if !self.caps.features.contains(Features::MESH_SHADER) {
1536            return Err(self.unsupported("mesh shading without Features::MESH_SHADER"));
1537        }
1538        if desc.task.is_some() && !self.caps.features.contains(Features::TASK_SHADER) {
1539            return Err(self.unsupported("a task stage without Features::TASK_SHADER"));
1540        }
1541        // The half of a workgroup-size check that needs no device, which this
1542        // recorder is exactly the shape to perform; see
1543        // `MeshPipelineDesc::check_workgroup_sizes`.
1544        desc.check_workgroup_sizes()?;
1545        self.check_stage(desc.mesh)?;
1546        if let Some(task) = desc.task {
1547            self.check_stage(task)?;
1548        }
1549        self.check_raster_state(
1550            desc.layout,
1551            desc.fragment,
1552            desc.color_targets,
1553            desc.primitive,
1554            desc.depth_stencil,
1555        )?;
1556        let mut stages: Vec<_> = desc
1557            .task
1558            .map(|entry| (ShaderStages::TASK, entry))
1559            .into_iter()
1560            .collect();
1561        stages.push((ShaderStages::MESH, desc.mesh));
1562        stages.extend(desc.fragment.map(|entry| (ShaderStages::FRAGMENT, entry)));
1563        self.record_pipeline(desc.label, desc.layout, &stages);
1564        // The same pool as a raster pipeline, because the seam gives the two
1565        // one handle type — see `MeshPipelineDesc`'s decision note. `Detail::None`
1566        // beside the raster arm's `Detail::GraphicsPipeline` and it is not an
1567        // omission: this pipeline has no vertex stage to record.
1568        Ok(self.insert(ObjectKind::GraphicsPipeline, desc.label, Detail::None))
1569    }
1570
1571    fn destroy_graphics_pipeline(&self, pipeline: GraphicsPipelineHandle) {
1572        self.remove(ObjectKind::GraphicsPipeline, pipeline.to_bits());
1573    }
1574
1575    fn create_compute_pipeline(
1576        &self,
1577        desc: &ComputePipelineDesc<'_>,
1578    ) -> Result<ComputePipelineHandle, HalError> {
1579        if !self.caps.features.contains(Features::COMPUTE) {
1580            return Err(self.unsupported("compute shaders"));
1581        }
1582        self.check(
1583            ObjectKind::PipelineLayout,
1584            desc.layout.to_bits(),
1585            "pipeline layout",
1586        )?;
1587        self.check_stage(desc.compute)?;
1588        // This recorder has no module contents to compare the declared size
1589        // against, so it checks the half that needs none: a size the device's
1590        // own limits could not launch.
1591        desc.check_workgroup_size(&self.caps.limits)?;
1592        self.record_pipeline(
1593            desc.label,
1594            desc.layout,
1595            &[(ShaderStages::COMPUTE, desc.compute)],
1596        );
1597        Ok(self.insert(ObjectKind::ComputePipeline, desc.label, Detail::None))
1598    }
1599
1600    fn destroy_compute_pipeline(&self, pipeline: ComputePipelineHandle) {
1601        self.remove(ObjectKind::ComputePipeline, pipeline.to_bits());
1602    }
1603
1604    // --- queries ---
1605
1606    fn create_query_set(&self, desc: &QuerySetDesc<'_>) -> Result<QuerySetHandle, HalError> {
1607        desc.kind.check_supported(BackendKind::Null)?;
1608        let required = match desc.kind {
1609            QueryKind::Timestamp => Features::TIMESTAMP_QUERY,
1610            QueryKind::Occlusion => Features::OCCLUSION_QUERY,
1611            QueryKind::PipelineStatistics => Features::PIPELINE_STATISTICS_QUERY,
1612        };
1613        if !self.caps.features.contains(required) {
1614            return Err(self.unsupported("this query kind"));
1615        }
1616        if desc.count == 0 {
1617            return Err(HalError::InvalidDescriptor(
1618                "query set must hold at least one query".to_string(),
1619            ));
1620        }
1621        Ok(self.insert(
1622            ObjectKind::QuerySet,
1623            desc.label,
1624            Detail::QuerySet { count: desc.count },
1625        ))
1626    }
1627
1628    fn destroy_query_set(&self, set: QuerySetHandle) {
1629        self.remove(ObjectKind::QuerySet, set.to_bits());
1630    }
1631
1632    fn query_results(
1633        &self,
1634        set: QuerySetHandle,
1635        first_query: u32,
1636        out: &mut [u64],
1637    ) -> Result<(), HalError> {
1638        self.check(ObjectKind::QuerySet, set.to_bits(), "query set")?;
1639        let count = {
1640            let state = self.recorder.lock();
1641            let Some(object) = state.get(ObjectKind::QuerySet, set.to_bits()) else {
1642                return Err(HalError::invalid_handle("query set", set));
1643            };
1644            let Detail::QuerySet { count } = &object.detail else {
1645                unreachable!("a query set handle always carries query set detail");
1646            };
1647            *count
1648        };
1649        // The range check `Device::query_results` documents. It was impossible
1650        // before: `first_query` was ignored and the set's size was not even
1651        // stored, so the null backend accepted ranges `crcbl-vk` rejects.
1652        let end = u64::from(first_query) + out.len() as u64;
1653        if end > u64::from(count) {
1654            return Err(HalError::InvalidDescriptor(format!(
1655                "query range {first_query}..{end} exceeds the set's {count} queries"
1656            )));
1657        }
1658        // Zeros, as a device without timestamp support would report: the
1659        // profiler HUD degrades rather than breaking.
1660        out.fill(0);
1661        Ok(())
1662    }
1663
1664    // --- synchronisation ---
1665
1666    fn create_semaphore(&self, desc: &SemaphoreDesc<'_>) -> Result<SemaphoreHandle, HalError> {
1667        if matches!(desc.kind, SemaphoreKind::Timeline { .. })
1668            && !self.caps.features.contains(Features::TIMELINE_SEMAPHORE)
1669        {
1670            return Err(self.unsupported("timeline semaphores"));
1671        }
1672        let (timeline, value) = match desc.kind {
1673            SemaphoreKind::Timeline { initial_value } => (true, initial_value),
1674            SemaphoreKind::Binary => (false, 0),
1675        };
1676        Ok(self.insert(
1677            ObjectKind::Semaphore,
1678            desc.label,
1679            Detail::Semaphore { timeline, value },
1680        ))
1681    }
1682
1683    fn destroy_semaphore(&self, semaphore: SemaphoreHandle) {
1684        self.remove(ObjectKind::Semaphore, semaphore.to_bits());
1685    }
1686
1687    /// The value this timeline has reached, starting at the one it was created
1688    /// with.
1689    ///
1690    /// Both a host signal and a *submission's* signal move it. A submission
1691    /// moves it the instant it is recorded, because work that does not execute
1692    /// takes no time to complete — see this backend's `submit`, which is where
1693    /// that choice is argued.
1694    fn semaphore_value(&self, semaphore: SemaphoreHandle) -> Result<u64, HalError> {
1695        self.check(ObjectKind::Semaphore, semaphore.to_bits(), "semaphore")?;
1696        let state = self.recorder.lock();
1697        let Some(Detail::Semaphore { timeline, value }) = state
1698            .get(ObjectKind::Semaphore, semaphore.to_bits())
1699            .map(|object| &object.detail)
1700        else {
1701            // `check` above released the lock, so another thread could have
1702            // destroyed it in between. That is the same outcome as passing a
1703            // dead handle, and it is reported as one.
1704            return Err(HalError::invalid_handle("semaphore", semaphore));
1705        };
1706        if !*timeline {
1707            return Err(self.unsupported("a binary semaphore has no value to read"));
1708        }
1709        Ok(*value)
1710    }
1711
1712    /// Signals the timeline from the host, and refuses a value that does not
1713    /// move it forwards.
1714    ///
1715    /// The one call on this backend whose *rule* is executed rather than
1716    /// recorded, and it has to be: the seam's guarantee is that a caller which
1717    /// signals backwards is told so on every backend, and a recorder that
1718    /// accepted it would be the one place the mistake is invisible.
1719    fn signal_semaphore(&self, semaphore: SemaphoreHandle, value: u64) -> Result<(), HalError> {
1720        self.check(ObjectKind::Semaphore, semaphore.to_bits(), "semaphore")?;
1721        let mut state = self.recorder.lock();
1722        let Some(Detail::Semaphore {
1723            timeline,
1724            value: held,
1725        }) = state
1726            .get_mut(ObjectKind::Semaphore, semaphore.to_bits())
1727            .map(|object| &mut object.detail)
1728        else {
1729            return Err(HalError::invalid_handle("semaphore", semaphore));
1730        };
1731        if !*timeline {
1732            return Err(self.unsupported("a binary semaphore has no value to signal"));
1733        }
1734        if value <= *held {
1735            return Err(timeline_goes_backwards(value, *held));
1736        }
1737        *held = value;
1738        Ok(())
1739    }
1740
1741    /// Answers against the values the timelines have actually reached, and
1742    /// never blocks.
1743    ///
1744    /// `timeout_ns` is ignored because there is nothing to wait *for*: a
1745    /// submission's signals land the moment it is recorded, so every value that
1746    /// is ever going to arrive has already arrived by the time this is called.
1747    /// The answer is therefore immediate in both directions — `Ok(true)` once
1748    /// every wait's value has been reached, and `Ok(false)` — the seam's
1749    /// spelling of `vkWaitSemaphores`' `VK_TIMEOUT` — for a value nothing has
1750    /// signalled.
1751    ///
1752    /// It used to answer `Ok(true)` unconditionally, on the grounds that
1753    /// nothing is ever outstanding here. That is the one answer a caller cannot
1754    /// check its own sequencing against: a wait on a value no signal will ever
1755    /// produce — the mistake that deadlocks a real device — read as satisfied.
1756    fn wait_semaphores(&self, waits: &[SemaphoreWait], _timeout_ns: u64) -> Result<bool, HalError> {
1757        // Every `check` before the lock, never under it: `check` takes the
1758        // recorder itself, and this mutex is not reentrant. `signal_semaphore`
1759        // one method up is written in this order for the same reason.
1760        for wait in waits {
1761            self.check(ObjectKind::Semaphore, wait.semaphore.to_bits(), "semaphore")?;
1762        }
1763        let state = self.recorder.lock();
1764        let mut reached = true;
1765        for wait in waits {
1766            let Some(Detail::Semaphore { timeline, value }) = state
1767                .get(ObjectKind::Semaphore, wait.semaphore.to_bits())
1768                .map(|object| &object.detail)
1769            else {
1770                return Err(HalError::invalid_handle("semaphore", wait.semaphore));
1771            };
1772            // The refusal every real backend makes, and the one this backend
1773            // already makes in `signal_semaphore`: a binary semaphore carries no
1774            // value, so a CPU wait has nothing to compare against. Answering
1775            // `Ok(true)` said a wait no device will accept had been satisfied.
1776            if !*timeline {
1777                return Err(self.unsupported("a binary semaphore cannot be waited on from the CPU"));
1778            }
1779            // Not an early `return`: a wait list holding both an unreached
1780            // timeline and a binary semaphore has to report the refusal, and
1781            // returning the verdict here would decide the call on whichever
1782            // came first in the slice.
1783            if wait.value > *value {
1784                reached = false;
1785            }
1786        }
1787        Ok(reached)
1788    }
1789
1790    /// Records the wait and returns at once — nothing here is ever outstanding.
1791    ///
1792    /// The one method that names no handle and can still fail, which is why the
1793    /// device-loss gate is spelled out here rather than reached through
1794    /// [`NullDevice::check_lost`]'s two funnels. `vkDeviceWaitIdle` reports
1795    /// `VK_ERROR_DEVICE_LOST` for the same reason: waiting for a dead device to
1796    /// finish is not something that can succeed.
1797    fn wait_idle(&self) -> Result<(), HalError> {
1798        self.check_lost()?;
1799        self.recorder.lock().events.push(Event::WaitedIdle);
1800        Ok(())
1801    }
1802
1803    // --- commands ---
1804
1805    fn create_command_encoder(&self, desc: &CommandEncoderDesc<'_>) -> Box<dyn CommandEncoder> {
1806        Box::new(NullEncoder {
1807            recorder: self.recorder.clone(),
1808            device_id: self.device_id,
1809            limits: self.caps.limits,
1810            label: desc.label.map(ToOwned::to_owned),
1811            commands: Vec::new(),
1812            scope: Scope::Outside,
1813            // There is no error path out of `create_command_encoder`, so a
1814            // queue that is not this device's is remembered and reported by
1815            // `finish` — exactly what `crcbl-vk` does when its command pool
1816            // cannot be created.
1817            failed: self.check_queue(desc.queue).err(),
1818        })
1819    }
1820
1821    fn destroy_command_buffer(&self, buffer: CommandBufferHandle) {
1822        self.remove(ObjectKind::CommandBuffer, buffer.to_bits());
1823    }
1824
1825    /// Records the submission and applies its signals at once.
1826    ///
1827    /// **A device that runs no work completes it instantly**, so the timeline
1828    /// values `submit.signals` names are reached before this returns — the same
1829    /// place a real queue reaches them, compressed to zero. The alternative,
1830    /// recording the signal and leaving the counter behind, would make every
1831    /// value a submission produces one that never arrives, which is the
1832    /// `SilentlyIgnored` verdict
1833    /// [`Capability::TimelineSemaphore`] exists to catch and which this backend
1834    /// claims not to be.
1835    ///
1836    /// The queue-side [`SubmitInfo::waits`] are recorded and not evaluated:
1837    /// [`Capability::TimelineWaitBeforeSignal`] says a submission may wait on a
1838    /// value nothing has signalled yet, so a wait here is not a rule to check.
1839    ///
1840    /// # Errors
1841    ///
1842    /// The handle checks, and [`HalError::InvalidDescriptor`] for a signal that
1843    /// does not move a timeline forwards — the rule
1844    /// [`Device::signal_semaphore`] already enforces, applied to the other way a
1845    /// timeline can be driven so that `submit` is not the one path that can move
1846    /// one backwards. Every signal is validated before any is applied, so a
1847    /// refused submission records no event and leaves every counter where it
1848    /// was.
1849    fn submit(&self, queue: QueueHandle, submit: &SubmitInfo<'_>) -> Result<(), HalError> {
1850        self.check_queue(queue)?;
1851        for buffer in submit.command_buffers {
1852            self.check(
1853                ObjectKind::CommandBuffer,
1854                buffer.to_bits(),
1855                "command buffer",
1856            )?;
1857        }
1858        for wait in submit.waits {
1859            self.check(ObjectKind::Semaphore, wait.semaphore.to_bits(), "semaphore")?;
1860        }
1861        for signal in submit.signals {
1862            self.check(
1863                ObjectKind::Semaphore,
1864                signal.semaphore.to_bits(),
1865                "semaphore",
1866            )?;
1867        }
1868        let mut state = self.recorder.lock();
1869        // Resolved and checked first, so a refused submission records nothing
1870        // and changes nothing — the order `reconfigure_swapchain` puts its own
1871        // failure in, for the same reason.
1872        let mut advanced: Vec<(u64, u64)> = Vec::new();
1873        for signal in submit.signals {
1874            let bits = signal.semaphore.to_bits();
1875            let Some(Detail::Semaphore {
1876                timeline: true,
1877                value: held,
1878            }) = state
1879                .get(ObjectKind::Semaphore, bits)
1880                .map(|object| &object.detail)
1881            else {
1882                // A binary semaphore — the swapchain's acquire/present pair is
1883                // where they come from — carries no value, so it is signalled
1884                // by being recorded and there is nothing to advance.
1885                continue;
1886            };
1887            // A second signal on the same semaphore in one batch measures
1888            // against the first, not against the counter both started from,
1889            // or an out-of-order pair would pass and land backwards anyway.
1890            let held = advanced
1891                .iter()
1892                .rev()
1893                .find(|(seen, _)| *seen == bits)
1894                .map_or(*held, |(_, pending)| *pending);
1895            if signal.value <= held {
1896                return Err(timeline_goes_backwards(signal.value, held));
1897            }
1898            advanced.push((bits, signal.value));
1899        }
1900        for (bits, value) in advanced {
1901            let Some(Detail::Semaphore { value: held, .. }) = state
1902                .get_mut(ObjectKind::Semaphore, bits)
1903                .map(|object| &mut object.detail)
1904            else {
1905                unreachable!("the pass above resolved these bits to a timeline semaphore");
1906            };
1907            *held = value;
1908        }
1909        state.events.push(Event::Submitted {
1910            queue,
1911            command_buffers: submit.command_buffers.to_vec(),
1912            waits: submit.waits.to_vec(),
1913            signals: submit.signals.to_vec(),
1914        });
1915        Ok(())
1916    }
1917
1918    // --- presentation ---
1919
1920    fn create_swapchain(&self, desc: &SwapchainDesc<'_>) -> Result<SwapchainHandle, SurfaceError> {
1921        self.check_instance_owned(ObjectKind::Surface, desc.surface.to_bits(), "surface")
1922            .map_err(SurfaceError::Hal)?;
1923        if desc.extent.0 == 0 || desc.extent.1 == 0 {
1924            return Err(SurfaceError::Hal(HalError::InvalidDescriptor(
1925                "swapchain extent must be non-zero".to_string(),
1926            )));
1927        }
1928        let ring = self.build_ring(desc)?;
1929        Ok(self.insert(ObjectKind::Swapchain, desc.label, ring))
1930    }
1931
1932    fn reconfigure_swapchain(
1933        &self,
1934        swapchain: SwapchainHandle,
1935        desc: &SwapchainDesc<'_>,
1936    ) -> Result<(), SurfaceError> {
1937        // First, so a faulted call records nothing and changes nothing — the
1938        // property `GpuContext::set_pacing`'s rollback asserts on.
1939        if self.recorder.take_reconfigure_failure() {
1940            return Err(SurfaceError::Hal(HalError::OutOfDeviceMemory));
1941        }
1942        if desc.extent.0 == 0 || desc.extent.1 == 0 {
1943            return Err(SurfaceError::Hal(HalError::InvalidDescriptor(
1944                "swapchain extent must be non-zero".to_string(),
1945            )));
1946        }
1947        self.check(ObjectKind::Swapchain, swapchain.to_bits(), "swapchain")
1948            .map_err(SurfaceError::Hal)?;
1949
1950        // Reissue the whole ring — images, views *and* semaphores — which is
1951        // what a real backend does, since `crcbl-vk` recreates the
1952        // `VkSwapchainKHR`. A caller that wrongly held one of those handles
1953        // across a resize therefore fails here, on the backend that needs no
1954        // GPU, rather than on the one that does.
1955        //
1956        // Built **before** anything old is destroyed. The other order looks
1957        // tidier and is wrong: `build_ring` can fail (an extent past
1958        // `max_image_2d`), and a failed reconfigure that had already destroyed
1959        // the old ring would leave the swapchain naming dead handles — a call
1960        // that returned `Err` having broken the object it was given.
1961        let fresh = self.build_ring(desc)?;
1962
1963        let stale = {
1964            let mut state = self.recorder.lock();
1965            let Some(object) = state.get_mut(ObjectKind::Swapchain, swapchain.to_bits()) else {
1966                return Err(SurfaceError::Hal(HalError::invalid_handle(
1967                    "swapchain",
1968                    swapchain,
1969                )));
1970            };
1971            let previous = core::mem::replace(&mut object.detail, fresh);
1972            // The rebuild is what clears the out-of-date latch, so a caller
1973            // that handles the resize gets a working swapchain back and one
1974            // that ignores it keeps being told. Here rather than at the top of
1975            // the method: a reconfigure that failed rebuilt nothing.
1976            state.swapchain_out_of_date = false;
1977            state.events.push(Event::Reconfigured {
1978                swapchain,
1979                extent: desc.extent,
1980            });
1981            previous
1982        };
1983
1984        let Detail::Swapchain {
1985            images,
1986            views,
1987            acquire_semaphores,
1988            present_semaphores,
1989            ..
1990        } = stale
1991        else {
1992            unreachable!("a swapchain handle always carries swapchain detail");
1993        };
1994        // Views before images: a view must not outlive what it views.
1995        for view in views {
1996            self.destroy_image_view(view);
1997        }
1998        for image in images {
1999            self.destroy_image(image);
2000        }
2001        for semaphore in acquire_semaphores
2002            .into_iter()
2003            .chain(present_semaphores)
2004            .flatten()
2005        {
2006            self.destroy_semaphore(semaphore);
2007        }
2008        Ok(())
2009    }
2010
2011    fn destroy_swapchain(&self, swapchain: SwapchainHandle) {
2012        let owned = {
2013            let state = self.recorder.lock();
2014            match state
2015                .get(ObjectKind::Swapchain, swapchain.to_bits())
2016                .map(|object| &object.detail)
2017            {
2018                Some(Detail::Swapchain {
2019                    images,
2020                    views,
2021                    acquire_semaphores,
2022                    present_semaphores,
2023                    ..
2024                }) => Some((
2025                    images.clone(),
2026                    views.clone(),
2027                    acquire_semaphores.clone(),
2028                    present_semaphores.clone(),
2029                )),
2030                _ => None,
2031            }
2032        };
2033        if let Some((images, views, acquires, presents)) = owned {
2034            // Views before images: the seam says every view of an image must
2035            // already be destroyed when the image is.
2036            for view in views {
2037                self.destroy_image_view(view);
2038            }
2039            for image in images {
2040                self.destroy_image(image);
2041            }
2042            for semaphore in acquires.into_iter().chain(presents).flatten() {
2043                self.destroy_semaphore(semaphore);
2044            }
2045        }
2046        self.remove(ObjectKind::Swapchain, swapchain.to_bits());
2047    }
2048
2049    fn acquire_next_frame(
2050        &self,
2051        swapchain: SwapchainHandle,
2052    ) -> Result<AcquiredFrame, SurfaceError> {
2053        self.check_current(swapchain)?;
2054        // Before the lock, like the `check` helpers above it and for the same
2055        // reason — the recorder's mutex is not reentrant, and the borrow of the
2056        // swapchain object below holds it until the frame is built. Reading it
2057        // here also spends the injection only on an acquire that got this far,
2058        // which is what leaves a refused one recording and consuming nothing.
2059        let suboptimal = self.recorder.take_suboptimal_acquire();
2060        let mut state = self.recorder.lock();
2061        let Some(object) = state.get_mut(ObjectKind::Swapchain, swapchain.to_bits()) else {
2062            return Err(SurfaceError::Hal(HalError::invalid_handle(
2063                "swapchain",
2064                swapchain,
2065            )));
2066        };
2067        let Detail::Swapchain {
2068            extent,
2069            images,
2070            views,
2071            acquire_semaphores,
2072            present_semaphores,
2073            next,
2074            acquired,
2075        } = &mut object.detail
2076        else {
2077            unreachable!("a swapchain handle always carries swapchain detail");
2078        };
2079        let index = *next;
2080        // The seam does not make an acquire exclusive — Vulkan lets a mailbox
2081        // ring hold several at once — so a second acquire overwrites rather
2082        // than being refused, exactly as every other backend's single slot
2083        // does. What the slot is for is the *present*, which needs to have been
2084        // given a frame at all.
2085        *acquired = Some(index);
2086        let slot = index as usize;
2087        // `.max(1)`, not `unwrap_or(1)`: `u32::try_from(0usize)` is `Ok(0)`, so
2088        // the fallback never fired for the one input it looked like it guarded
2089        // against, and an empty ring divided by zero.
2090        *next = (index + 1) % u32::try_from(images.len()).unwrap_or(u32::MAX).max(1);
2091        let frame = AcquiredFrame {
2092            image: images[slot],
2093            view: views[slot],
2094            // The extent the ring was actually built at, which is the
2095            // requested one unless `Recorder::clamp_acquired_extent_to` gave
2096            // this backend a platform opinion — the thing that makes
2097            // obligation 3's branch reachable at all.
2098            extent: *extent,
2099            index,
2100            acquire_semaphore: acquire_semaphores[slot],
2101            present_semaphore: present_semaphores[slot],
2102            suboptimal,
2103        };
2104        state.events.push(Event::Acquired { swapchain, index });
2105        Ok(frame)
2106    }
2107
2108    fn present(&self, queue: QueueHandle, present: &PresentInfo<'_>) -> Result<(), SurfaceError> {
2109        self.check_queue(queue).map_err(SurfaceError::Hal)?;
2110        self.check_current(present.swapchain)?;
2111        for semaphore in present.waits {
2112            self.check(ObjectKind::Semaphore, semaphore.to_bits(), "semaphore")
2113                .map_err(SurfaceError::Hal)?;
2114        }
2115        let mut state = self.recorder.lock();
2116        // **A present needs a frame to present**, which this backend could not
2117        // say until it had somewhere to remember the acquire. The wording is
2118        // the one `crcbl-vk`, `crcbl-mtl` and `crcbl-dx12` already answer, so
2119        // one agnostic test holds every backend to the same sentence.
2120        let Some(Detail::Swapchain { acquired, .. }) = state
2121            .get_mut(ObjectKind::Swapchain, present.swapchain.to_bits())
2122            .map(|object| &mut object.detail)
2123        else {
2124            unreachable!("check_current resolved this swapchain a moment ago");
2125        };
2126        if acquired.take().is_none() {
2127            return Err(SurfaceError::Hal(HalError::InvalidDescriptor(
2128                "present without a matching acquire_next_frame".to_string(),
2129            )));
2130        }
2131        state.events.push(Event::Presented {
2132            swapchain: present.swapchain,
2133            present_id: present.present_id,
2134        });
2135        Ok(())
2136    }
2137
2138    /// Records the request and returns at once, unless a timeout was injected.
2139    ///
2140    /// There is no display under this backend, so there is nothing a wait could
2141    /// observe and nothing that could make one late. On a device that does not
2142    /// advertise [`Features::PRESENT_FEEDBACK`] the seam requires exactly that
2143    /// answer anyway — an immediate `Ok`, never a refusal — so such a device
2144    /// needs no injection to be honest and is given none: it consumes nothing
2145    /// from [`Recorder::report_present_wait_timeouts`], leaving what was asked
2146    /// for owed to a device that can honour it. A device built with
2147    /// [`NullInstance::with_present_feedback`] claims the other half of the
2148    /// contract, and that is where an injected timeout comes out.
2149    ///
2150    /// The handle is still checked, because a caller waiting on a swapchain it
2151    /// already destroyed has a bug whether or not anyone was going to block —
2152    /// and so is the out-of-date latch, because a pacing wait is one of the
2153    /// three calls a resize makes fail. See [`check_current`](Self::check_current).
2154    fn wait_until_presented(
2155        &self,
2156        swapchain: SwapchainHandle,
2157        present_id: u64,
2158        _timeout: Duration,
2159    ) -> Result<(), SurfaceError> {
2160        self.check_current(swapchain)?;
2161        // After the checks and before the lock, exactly as `acquire_next_frame`
2162        // takes its own injection and for both of that call's reasons: the
2163        // recorder's mutex is not reentrant, and a wait the checks above
2164        // refused must spend nothing.
2165        let timed_out = self.caps.features.contains(Features::PRESENT_FEEDBACK)
2166            && self.recorder.take_present_wait_timeout();
2167        let mut state = self.recorder.lock();
2168        // Recorded either way. The wait was asked for and answered; which of
2169        // the two answers it got is the part the event has to carry.
2170        state.events.push(Event::PresentWaited {
2171            swapchain,
2172            present_id,
2173            timed_out,
2174        });
2175        if timed_out {
2176            Err(SurfaceError::Timeout)
2177        } else {
2178            Ok(())
2179        }
2180    }
2181
2182    /// Always [`DisplayTiming::Unknown`], and the handle is checked first.
2183    ///
2184    /// There is no display under this backend to have a cadence, so this device
2185    /// never advertises [`Features::PRESENT_TIMING`] and the seam's answer for
2186    /// a device without it is the honest one here. The check is the same
2187    /// obligation-3 lookup every other method does: asking about a destroyed or
2188    /// foreign swapchain is a caller bug whether or not there was an answer to
2189    /// give.
2190    fn display_timing(&self, swapchain: SwapchainHandle) -> Result<DisplayTiming, SurfaceError> {
2191        self.check(ObjectKind::Swapchain, swapchain.to_bits(), "swapchain")
2192            .map_err(SurfaceError::Hal)?;
2193        Ok(DisplayTiming::Unknown)
2194    }
2195}
2196
2197impl NullDevice {
2198    /// Builds a complete swapchain ring: one image, one view and — unless this
2199    /// device models an implicit acquire — one acquire and one present
2200    /// semaphore per ring slot.
2201    ///
2202    /// Shared by create and reconfigure so the four vectors can never end up
2203    /// with different lengths. They did once: reconfigure used to replace only
2204    /// the images and views, so reconfiguring from two images to three left
2205    /// two-element semaphore vectors and the third acquire indexed past the end
2206    /// of them. The lengths are an invariant, so one constructor establishes it.
2207    fn build_ring(&self, desc: &SwapchainDesc<'_>) -> Result<Detail, SurfaceError> {
2208        // `SwapchainDesc::format` must be one of `SurfaceCaps::formats`, and
2209        // this backend used to accept anything at all — including `D32Float`,
2210        // which no surface can present.
2211        if !SURFACE_FORMATS.contains(&desc.format) {
2212            return Err(SurfaceError::Hal(HalError::InvalidDescriptor(format!(
2213                "{:?} is not one of this surface's formats {SURFACE_FORMATS:?}",
2214                desc.format
2215            ))));
2216        }
2217        // Clamped to what `surface_caps` reports, not to a pair of literals
2218        // that happened to agree with it.
2219        let image_count = desc.image_count.clamp(RING_MIN_IMAGES, RING_MAX_IMAGES);
2220        // The platform's say over the extent, if a test has given this backend
2221        // one — see `Recorder::clamp_acquired_extent_to`. Applied here rather
2222        // than at acquire so the ring's *images* are the clamped size too: a
2223        // swapchain reporting one extent and holding images of another is a
2224        // fixture no window system produces, and a render area derived from
2225        // those images would disagree with the acquired extent for a reason
2226        // that is the fixture's rather than the caller's.
2227        let extent = self.recorder.clamped_extent().unwrap_or(desc.extent);
2228        let mut images = Vec::with_capacity(image_count as usize);
2229        let mut views = Vec::with_capacity(image_count as usize);
2230        let mut acquire_semaphores = Vec::with_capacity(image_count as usize);
2231        let mut present_semaphores = Vec::with_capacity(image_count as usize);
2232        for index in 0..image_count {
2233            let image = self
2234                .create_image(&ImageDesc {
2235                    label: Some("swapchain image"),
2236                    image_type: ImageType::D2,
2237                    extent: crate::Extent3d::d2(extent.0, extent.1),
2238                    format: desc.format,
2239                    mip_levels: 1,
2240                    samples: 1,
2241                    usage: ImageUsage::COLOR_ATTACHMENT | ImageUsage::PRESENT,
2242                })
2243                .map_err(SurfaceError::Hal)?;
2244            images.push(image);
2245            // The swapchain owns its images, so it owns their views — see
2246            // `crate::swapchain`. A caller never creates or destroys one.
2247            views.push(
2248                self.create_image_view(&ImageViewDesc {
2249                    label: Some("swapchain image view"),
2250                    image,
2251                    view_type: crate::ImageViewType::D2,
2252                    format: desc.format,
2253                    range: crate::ImageSubresourceRange::all(desc.format),
2254                })
2255                .map_err(SurfaceError::Hal)?,
2256            );
2257            if self.implicit_acquire {
2258                // The WebGPU shape: no semaphores at all, so the renderer's
2259                // wait/signal splice is a no-op rather than a branch.
2260                acquire_semaphores.push(None);
2261                present_semaphores.push(None);
2262            } else {
2263                let label = format!("swapchain acquire {index}");
2264                acquire_semaphores.push(Some(self.insert::<crate::Semaphore>(
2265                    ObjectKind::Semaphore,
2266                    Some(&label),
2267                    Detail::None,
2268                )));
2269                let label = format!("swapchain present {index}");
2270                present_semaphores.push(Some(self.insert::<crate::Semaphore>(
2271                    ObjectKind::Semaphore,
2272                    Some(&label),
2273                    Detail::None,
2274                )));
2275            }
2276        }
2277        Ok(Detail::Swapchain {
2278            extent,
2279            images,
2280            views,
2281            acquire_semaphores,
2282            present_semaphores,
2283            acquired: None,
2284            next: 0,
2285        })
2286    }
2287
2288    /// Snapshots a bind-group layout, so validation can run without holding the
2289    /// recorder lock across the resource lookups it also needs.
2290    fn layout_of(&self, handle: BindGroupLayoutHandle) -> Result<LayoutRecord, HalError> {
2291        let state = self.recorder.lock();
2292        let Some(object) = state.get(ObjectKind::BindGroupLayout, handle.to_bits()) else {
2293            return Err(HalError::invalid_handle("bind group layout", handle));
2294        };
2295        let Detail::BindGroupLayout {
2296            entries,
2297            update_after_bind,
2298            variable_binding,
2299        } = &object.detail
2300        else {
2301            unreachable!("a layout handle always carries layout detail");
2302        };
2303        Ok(LayoutRecord {
2304            entries: entries.clone(),
2305            update_after_bind: *update_after_bind,
2306            variable_binding: *variable_binding,
2307        })
2308    }
2309
2310    /// Checks every assignment against the layout it claims to fill.
2311    ///
2312    /// The three things a real backend checks and this one used not to: that
2313    /// the binding exists, that the array index is inside it, and that the
2314    /// resource is the right *kind*. Without them the null backend green-lit
2315    /// bind groups `crcbl-vk` rejects outright.
2316    fn check_entries_against(
2317        &self,
2318        layout: &LayoutRecord,
2319        entries: &[BindGroupEntry],
2320    ) -> Result<(), HalError> {
2321        for entry in entries {
2322            let Some(declared) = layout
2323                .entries
2324                .iter()
2325                .find(|slot| slot.binding == entry.binding)
2326            else {
2327                return Err(HalError::InvalidDescriptor(format!(
2328                    "bind group entry names binding {}, which the layout does not declare",
2329                    entry.binding
2330                )));
2331            };
2332            let ceiling = layout.binding_ceiling(entry.binding, &self.caps);
2333            if entry.array_index >= ceiling {
2334                return Err(HalError::InvalidDescriptor(format!(
2335                    "bind group entry writes index {} of binding {}, which holds {ceiling}",
2336                    entry.array_index, entry.binding
2337                )));
2338            }
2339            check_resource_kind(declared.kind, &entry.resource, entry.binding)?;
2340            self.check_binding(&entry.resource)?;
2341            self.check_shader_writable_memory(declared.kind, &entry.resource, entry.binding)?;
2342            self.check_binding_range(declared.kind, &entry.resource, entry.binding)?;
2343            self.check_binding_offset(declared.kind, &entry.resource, entry.binding)?;
2344        }
2345        Ok(())
2346    }
2347
2348    /// Refuses a host-visible buffer filling a binding a shader can write.
2349    ///
2350    /// The seam's rule, stated on
2351    /// [`MemoryLocation`]: a buffer a shader writes is
2352    /// [`MemoryLocation::DeviceLocal`] and nothing else, because D3D12's upload
2353    /// and readback heaps admit no unordered access view. `crcbl-dx12` refuses
2354    /// it too, at the binding it builds the view for — but a violation that only
2355    /// that backend catches is one nobody sees until CI runs WARP, which has
2356    /// twice cost a device. The null backend is the reference implementation, so
2357    /// the class is refused here where every no-GPU test meets it.
2358    ///
2359    /// Read-only storage bindings are untouched: a host-visible buffer behind a
2360    /// `StructuredBuffer` is the engine's staged-table shape and legal on all
2361    /// four backends.
2362    ///
2363    /// The buffer's location is read from the record the seam already keeps,
2364    /// not inferred from whether it materialised bytes — that is a proxy, and
2365    /// the proxy is what the check would drift away from.
2366    fn check_shader_writable_memory(
2367        &self,
2368        kind: crate::BindingKind,
2369        resource: &crate::BindingResource,
2370        binding: u32,
2371    ) -> Result<(), HalError> {
2372        let (
2373            crate::BindingKind::StorageBuffer {
2374                read_only: false, ..
2375            },
2376            crate::BindingResource::Buffer { buffer, .. },
2377        ) = (kind, resource)
2378        else {
2379            return Ok(());
2380        };
2381        let state = self.recorder.lock();
2382        let Some(object) = state.get(ObjectKind::Buffer, buffer.to_bits()) else {
2383            return Err(HalError::invalid_handle("buffer", *buffer));
2384        };
2385        let Detail::Buffer { memory, .. } = &object.detail else {
2386            unreachable!("a buffer handle always carries buffer detail");
2387        };
2388        if matches!(memory, MemoryLocation::DeviceLocal) {
2389            return Ok(());
2390        }
2391        Err(HalError::InvalidDescriptor(format!(
2392            "binding {binding} is a writable storage buffer and was given a {memory:?} buffer; a \
2393             buffer a shader writes must be MemoryLocation::DeviceLocal, because D3D12's upload \
2394             and readback heaps refuse D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS at creation and \
2395             pin the resource to a state a shader cannot write from. Read-only storage bindings of \
2396             a host-visible buffer are unaffected"
2397        )))
2398    }
2399
2400    /// Refuses a buffer range longer than the limit for the slot it fills.
2401    ///
2402    /// [`Limits::max_uniform_buffer_range`](crate::Limits::max_uniform_buffer_range)
2403    /// and
2404    /// [`Limits::max_storage_buffer_range`](crate::Limits::max_storage_buffer_range)
2405    /// are the two ceilings a bind group can exceed, and the one a caller is
2406    /// likeliest to walk into by accident: a uniform ceiling of 64 KiB is small
2407    /// enough that an ordinary table outgrows it, and the buffer itself was
2408    /// created without complaint because a buffer of that size is legal — it is
2409    /// binding *all of it* to a uniform slot that is not.
2410    ///
2411    /// [`BindingResource::WHOLE_BUFFER`](crate::BindingResource::WHOLE_BUFFER)
2412    /// is resolved against the buffer's own size before comparing, because that
2413    /// is what the backend does with it: a whole-buffer binding of a buffer over
2414    /// the ceiling is the same violation spelled without a number, and checking
2415    /// only explicit sizes would let the commonest spelling through.
2416    ///
2417    /// Vulkan states both as VUIDs on `VkDescriptorBufferInfo` rather than as
2418    /// errors, so a violation there is undefined behaviour caught by validation
2419    /// layers if they happen to be on; refusing here is what makes it a named
2420    /// error every no-GPU test meets.
2421    fn check_binding_range(
2422        &self,
2423        kind: crate::BindingKind,
2424        resource: &crate::BindingResource,
2425        binding: u32,
2426    ) -> Result<(), HalError> {
2427        let limits = &self.caps.limits;
2428        let (ceiling, what) = match kind {
2429            crate::BindingKind::UniformBuffer { .. } => {
2430                (limits.max_uniform_buffer_range, "max_uniform_buffer_range")
2431            }
2432            crate::BindingKind::StorageBuffer { .. } => {
2433                (limits.max_storage_buffer_range, "max_storage_buffer_range")
2434            }
2435            _ => return Ok(()),
2436        };
2437        let crate::BindingResource::Buffer {
2438            buffer,
2439            offset,
2440            size,
2441        } = resource
2442        else {
2443            return Ok(());
2444        };
2445        let state = self.recorder.lock();
2446        let Some(object) = state.get(ObjectKind::Buffer, buffer.to_bits()) else {
2447            return Err(HalError::invalid_handle("buffer", *buffer));
2448        };
2449        let Detail::Buffer { size: length, .. } = &object.detail else {
2450            unreachable!("a buffer handle always carries buffer detail");
2451        };
2452        let bound = if *size == crate::BindingResource::WHOLE_BUFFER {
2453            length.saturating_sub(*offset)
2454        } else {
2455            *size
2456        };
2457        if bound <= ceiling {
2458            return Ok(());
2459        }
2460        Err(HalError::InvalidDescriptor(format!(
2461            "binding {binding} is given {bound} bytes of a buffer, over this device's {what} of {ceiling}"
2462        )))
2463    }
2464
2465    /// Refuses a buffer binding whose offset is not a multiple of the
2466    /// alignment its slot requires.
2467    ///
2468    /// [`crate::check_binding_offset_alignment`] is the rule; this resolves the
2469    /// offset out of the resource and hands it over. It needs no buffer record
2470    /// at all — the alignment turns on the *slot*, and the offset is in the
2471    /// descriptor — which is what makes it decidable here where every no-GPU
2472    /// test meets it. Before it existed, `crcbl-vk` and the two deferred
2473    /// backends each refused it and the reference implementation could not
2474    /// state the rule, so a misaligned offset was a bind group that this
2475    /// backend built and a driver later read from the wrong bytes.
2476    ///
2477    /// The bind-time half is [`crate::check_dynamic_offsets`], which
2478    /// `NullEncoder::bind_group` calls.
2479    fn check_binding_offset(
2480        &self,
2481        kind: crate::BindingKind,
2482        resource: &crate::BindingResource,
2483        binding: u32,
2484    ) -> Result<(), HalError> {
2485        let crate::BindingResource::Buffer { offset, .. } = resource else {
2486            return Ok(());
2487        };
2488        crate::check_binding_offset_alignment(&self.caps.limits, kind, binding, *offset)
2489    }
2490
2491    fn check_binding(&self, resource: &crate::BindingResource) -> Result<(), HalError> {
2492        match resource {
2493            crate::BindingResource::Buffer { buffer, .. } => {
2494                self.check(ObjectKind::Buffer, buffer.to_bits(), "buffer")
2495            }
2496            crate::BindingResource::ImageView(view) => {
2497                self.check(ObjectKind::ImageView, view.to_bits(), "image view")
2498            }
2499            crate::BindingResource::Sampler(sampler) => {
2500                self.check(ObjectKind::Sampler, sampler.to_bits(), "sampler")
2501            }
2502        }
2503    }
2504}
2505
2506/// A bind-group layout's declarations, copied out from under the lock.
2507#[derive(Debug)]
2508struct LayoutRecord {
2509    entries: Vec<crate::BindGroupLayoutEntry>,
2510    update_after_bind: bool,
2511    variable_binding: Option<u32>,
2512}
2513
2514impl LayoutRecord {
2515    /// How many descriptors a binding actually holds.
2516    ///
2517    /// [`BindingFlags::VARIABLE_COUNT`](crate::BindingFlags::VARIABLE_COUNT)
2518    /// makes the declared `count` an upper bound, and
2519    /// [`BindGroupLayoutEntry::resolved_count`](crate::BindGroupLayoutEntry::resolved_count)
2520    /// is where the seam's `u32::MAX` becomes a number. Only the variable
2521    /// binding is resolved: every other binding holds exactly the length it
2522    /// declared, which is the bound a caller's `array_index` has to clear.
2523    fn binding_ceiling(&self, binding: u32, caps: &DeviceCaps) -> u32 {
2524        let Some(entry) = self.entries.iter().find(|slot| slot.binding == binding) else {
2525            return 0;
2526        };
2527        if self.variable_binding == Some(binding) {
2528            entry.resolved_count(&caps.limits)
2529        } else {
2530            entry.count
2531        }
2532    }
2533}
2534
2535/// Whether a resource can fill a binding of that kind.
2536///
2537/// The same table `crcbl-vk`'s `check_resource_kind` uses, and for the same
2538/// reason: a mismatch must name the caller's binding number, not a descriptor
2539/// type in a driver message.
2540fn check_resource_kind(
2541    kind: crate::BindingKind,
2542    resource: &crate::BindingResource,
2543    binding: u32,
2544) -> Result<(), HalError> {
2545    use crate::{BindingKind as K, BindingResource as R};
2546    let ok = matches!(
2547        (kind, resource),
2548        (
2549            K::UniformBuffer { .. } | K::StorageBuffer { .. },
2550            R::Buffer { .. }
2551        ) | (
2552            K::SampledImage { .. } | K::StorageImage { .. },
2553            R::ImageView(_)
2554        ) | (K::Sampler { .. }, R::Sampler(_))
2555    );
2556    if ok {
2557        Ok(())
2558    } else {
2559        Err(HalError::InvalidDescriptor(format!(
2560            "binding {binding} is declared as {kind:?}, which cannot hold {resource:?}"
2561        )))
2562    }
2563}
2564
2565/// Which pass, if any, is currently open on an encoder.
2566#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2567enum Scope {
2568    Outside,
2569    Render,
2570    Compute,
2571}
2572
2573/// A no-op, recording [`CommandEncoder`].
2574#[derive(Debug)]
2575struct NullEncoder {
2576    recorder: Recorder,
2577    /// Owner id every handle a recorded command names must match.
2578    device_id: u64,
2579    /// This device's [`Limits`], copied at creation.
2580    ///
2581    /// The seam's two `min_*_buffer_offset_alignment` fields are the only thing
2582    /// read out of it, and they are what
2583    /// [`crate::check_dynamic_offsets`] measures a bind's offsets against — a
2584    /// rule that arrives at `bind_group` rather than at bind-group creation, so
2585    /// the device that knows the numbers is not in the room by then. Copied
2586    /// rather than reached through the recorder because [`Limits`] is `Copy`
2587    /// and an encoder outlives no device it was made by.
2588    limits: Limits,
2589    label: Option<String>,
2590    commands: Vec<Command>,
2591    scope: Scope,
2592    /// The first hard failure, reported by [`CommandEncoder::finish`]. Distinct
2593    /// from a [`ValidationError`], which is recorded and carried past.
2594    failed: Option<HalError>,
2595}
2596
2597impl NullEncoder {
2598    /// Records `command` after checking it is legal in the current scope.
2599    fn record(&mut self, command: Command) {
2600        let name = command.name();
2601        match &command {
2602            Command::BeginRenderPass { .. } | Command::BeginComputePass { .. } => {
2603                if self.scope != Scope::Outside {
2604                    self.fail(ValidationError::NestedPass { command: name });
2605                }
2606                self.scope = match command {
2607                    Command::BeginComputePass { .. } => Scope::Compute,
2608                    _ => Scope::Render,
2609                };
2610            }
2611            Command::EndRenderPass => {
2612                if self.scope != Scope::Render {
2613                    self.fail(ValidationError::UnopenedPass { command: name });
2614                }
2615                self.scope = Scope::Outside;
2616            }
2617            Command::EndComputePass => {
2618                if self.scope != Scope::Compute {
2619                    self.fail(ValidationError::UnopenedPass { command: name });
2620                }
2621                self.scope = Scope::Outside;
2622            }
2623            _ => {}
2624        }
2625        self.commands.push(command);
2626    }
2627
2628    fn fail(&self, error: ValidationError) {
2629        self.recorder.push_validation(error);
2630    }
2631
2632    /// Requires an open render pass.
2633    fn need_render(&self, command: &'static str) {
2634        if self.scope != Scope::Render {
2635            self.fail(ValidationError::OutsidePass {
2636                command,
2637                expected: "render",
2638            });
2639        }
2640    }
2641
2642    /// Requires an open compute pass.
2643    fn need_compute(&self, command: &'static str) {
2644        if self.scope != Scope::Compute {
2645            self.fail(ValidationError::OutsidePass {
2646                command,
2647                expected: "compute",
2648            });
2649        }
2650    }
2651
2652    /// Requires some pass to be open — bindings are legal in either.
2653    fn need_any_pass(&self, command: &'static str) {
2654        if self.scope == Scope::Outside {
2655            self.fail(ValidationError::OutsidePass {
2656                command,
2657                expected: "render or compute",
2658            });
2659        }
2660    }
2661
2662    /// Requires no pass to be open. Copies, barriers and query writes are
2663    /// forbidden inside dynamic rendering.
2664    fn need_outside(&self, command: &'static str) {
2665        if self.scope != Scope::Outside {
2666            self.fail(ValidationError::InsidePass { command });
2667        }
2668    }
2669
2670    /// Checks a pass's [`PassTimestampWrites`], if it has any: the set must be
2671    /// this device's and live, the two indices must differ, and both must be
2672    /// queries the set actually holds.
2673    ///
2674    /// The seam has no free-standing timestamp call left to check, so this is
2675    /// where the graph's unit suite catches a mis-aimed timestamp without a GPU.
2676    fn need_timestamps(&self, command: &'static str, writes: Option<PassTimestampWrites>) {
2677        let Some(writes) = writes else { return };
2678        self.need_live(command, ObjectKind::QuerySet, writes.set.to_bits());
2679        if writes.beginning_of_pass == writes.end_of_pass {
2680            self.fail(ValidationError::CoincidentTimestamps {
2681                command,
2682                index: writes.beginning_of_pass,
2683            });
2684        }
2685        let state = self.recorder.lock();
2686        let Some(object) = state.get(ObjectKind::QuerySet, writes.set.to_bits()) else {
2687            // A dead or foreign handle, already reported by `need_live` above.
2688            return;
2689        };
2690        let Detail::QuerySet { count } = &object.detail else {
2691            unreachable!("a query set handle always carries query set detail");
2692        };
2693        let count = *count;
2694        for index in [writes.beginning_of_pass, writes.end_of_pass] {
2695            if index >= count {
2696                drop(state);
2697                self.fail(ValidationError::TimestampOutOfRange {
2698                    command,
2699                    index,
2700                    count,
2701                });
2702                return;
2703            }
2704        }
2705    }
2706
2707    /// Requires an indirect draw's arguments to obey the seam's rules for
2708    /// stepping an array of argument structures — [`crate::indirect`].
2709    ///
2710    /// This backend resolves no driver object and can still answer all three
2711    /// rules, bounds included, because it recorded the buffer's size when it
2712    /// created it. That is the point of checking here: `crcbl-vk` needs a
2713    /// device to reach the same verdict, and this reaches it in a unit test.
2714    ///
2715    /// A refusal goes where [`report_indirect`](Self::report_indirect) sends
2716    /// it.
2717    fn need_indirect_arguments(
2718        &mut self,
2719        command: &'static str,
2720        draw: &DrawIndirect,
2721        indexed: bool,
2722    ) {
2723        let Some(length) = self.buffer_size(draw.args) else {
2724            // A dead or foreign handle, already reported by `need_live`. There
2725            // is no buffer to measure the arguments against.
2726            return;
2727        };
2728        self.report_indirect(
2729            command,
2730            plan_structures(draw, structure_bytes(indexed), length),
2731        );
2732    }
2733
2734    /// [`need_indirect_arguments`](Self::need_indirect_arguments) for a **mesh**
2735    /// dispatch, whose argument structure is three words rather than a draw's
2736    /// four or five — [`plan_mesh_indirect`].
2737    ///
2738    /// Every other rule is the same one, because they are all rules about
2739    /// stepping an array of structures in a buffer rather than about what the
2740    /// structures say.
2741    fn need_mesh_indirect_arguments(&mut self, command: &'static str, draw: &DrawIndirect) {
2742        let Some(length) = self.buffer_size(draw.args) else {
2743            // A dead or foreign handle, already reported by `need_live`.
2744            return;
2745        };
2746        self.report_indirect(command, plan_mesh_indirect(draw, length));
2747    }
2748
2749    /// [`need_indirect_arguments`](Self::need_indirect_arguments) for a
2750    /// count-limited draw, which is the same argument array plus the count word
2751    /// in a second buffer — [`plan_count_structures`].
2752    ///
2753    /// The count buffer is measured the same way and for the same reason: a
2754    /// count word hanging off the end of it is a draw count read from
2755    /// somebody else's memory, and no API reports it.
2756    fn need_indirect_count_arguments(
2757        &mut self,
2758        command: &'static str,
2759        draw: &DrawIndirectCount,
2760        indexed: bool,
2761    ) {
2762        let (Some(args_length), Some(count_length)) = (
2763            self.buffer_size(draw.args),
2764            self.buffer_size(draw.count_buffer),
2765        ) else {
2766            // A dead or foreign handle, already reported by `need_live`.
2767            return;
2768        };
2769        self.report_indirect(
2770            command,
2771            plan_count_structures(draw, structure_bytes(indexed), args_length, count_length),
2772        );
2773    }
2774
2775    /// The size a live buffer of this device's was created with, or `None` for
2776    /// a handle that no longer resolves.
2777    ///
2778    /// **`size`, not `bytes.len()`**: only a mappable buffer keeps its
2779    /// contents, and an argument buffer is device-local everywhere it matters,
2780    /// so a length taken from `bytes` would be zero and would refuse every
2781    /// legitimate draw.
2782    fn buffer_size(&self, buffer: BufferHandle) -> Option<u64> {
2783        let state = self.recorder.lock();
2784        let object = state.get(ObjectKind::Buffer, buffer.to_bits())?;
2785        let Detail::Buffer { size, .. } = &object.detail else {
2786            unreachable!("a buffer handle always carries buffer detail");
2787        };
2788        Some(*size)
2789    }
2790
2791    /// Records and remembers a refusal from [`crate::indirect`], and lets an
2792    /// accepted plan pass.
2793    ///
2794    /// A refusal goes two places. It is recorded, like every other violation,
2795    /// so a test sees the whole frame's worth; and it is remembered in
2796    /// [`failed`](Self::failed), because a recording method returns `()` and
2797    /// [`finish`](CommandEncoder::finish) is the first thing that can report
2798    /// it — the arrangement `create_command_encoder` already uses for a queue
2799    /// it cannot accept.
2800    fn report_indirect(
2801        &mut self,
2802        command: &'static str,
2803        planned: Result<Option<IndirectPlan>, HalError>,
2804    ) {
2805        let Err(error) = planned else {
2806            return;
2807        };
2808        self.report_refusal(error, |message| ValidationError::InvalidIndirectArguments {
2809            command,
2810            message,
2811        });
2812    }
2813
2814    /// Requires a bind's dynamic offsets to obey the seam's rules for filling
2815    /// the dynamic-offset slots a layout declares —
2816    /// [`crate::check_dynamic_offsets`].
2817    ///
2818    /// This backend resolves no driver object and can still answer both rules,
2819    /// because it recorded the layout a bind group was created against and the
2820    /// slots that layout declares. That is the point of checking here:
2821    /// `crcbl-vk` needs a device and a `VkDescriptorSetLayout` to reach the
2822    /// same verdict, and this reaches it in a unit test.
2823    ///
2824    /// A refusal goes where [`report_indirect`](Self::report_indirect) sends
2825    /// one, and for the same reason.
2826    fn need_dynamic_offsets(
2827        &mut self,
2828        command: &'static str,
2829        group: BindGroupHandle,
2830        offsets: &[u32],
2831    ) {
2832        let Some(dynamic) = self.dynamic_slots(group) else {
2833            // A dead or foreign bind group, already reported by `need_live` —
2834            // or a layout destroyed since the group was built, which is legal
2835            // everywhere and leaves nothing to measure the offsets against.
2836            return;
2837        };
2838        let Err(error) = crate::check_dynamic_offsets(&self.limits, &dynamic, offsets) else {
2839            return;
2840        };
2841        self.report_refusal(error, |message| ValidationError::InvalidDynamicOffsets {
2842            command,
2843            message,
2844        });
2845    }
2846
2847    /// The dynamic-offset slots of the layout a bind group was created
2848    /// against, sorted by binding number, or `None` if either handle no longer
2849    /// resolves.
2850    ///
2851    /// The sort is the seam's rule rather than tidiness:
2852    /// [`CommandEncoder::bind_group`] states that `dynamic_offsets` is
2853    /// positional and in binding order, so this order is what makes offset *i*
2854    /// the one belonging to slot *i*.
2855    fn dynamic_slots(&self, group: BindGroupHandle) -> Option<Vec<BindGroupLayoutEntry>> {
2856        let state = self.recorder.lock();
2857        let object = state.get(ObjectKind::BindGroup, group.to_bits())?;
2858        let Detail::BindGroup { layout, .. } = &object.detail else {
2859            unreachable!("a bind group handle always carries bind group detail");
2860        };
2861        let layout = state.get(ObjectKind::BindGroupLayout, layout.to_bits())?;
2862        let Detail::BindGroupLayout { entries, .. } = &layout.detail else {
2863            unreachable!("a bind group layout handle always carries layout detail");
2864        };
2865        let mut dynamic: Vec<BindGroupLayoutEntry> = entries
2866            .iter()
2867            .copied()
2868            .filter(|entry| {
2869                matches!(
2870                    entry.kind,
2871                    BindingKind::UniformBuffer { dynamic: true }
2872                        | BindingKind::StorageBuffer { dynamic: true, .. }
2873                )
2874            })
2875            .collect();
2876        dynamic.sort_by_key(|entry| entry.binding);
2877        Some(dynamic)
2878    }
2879
2880    /// Records and remembers a refusal a unit-returning recording method
2881    /// cannot return.
2882    ///
2883    /// The two places above both need it, and `wrap` is the only part that
2884    /// differs: which [`ValidationError`] the refusal is recorded as. The
2885    /// message itself is the seam's own, unchanged, so the recorded violation
2886    /// and the [`HalError`] `finish` returns say the same thing.
2887    fn report_refusal(&mut self, error: HalError, wrap: impl FnOnce(String) -> ValidationError) {
2888        let message = match error {
2889            // The seam's checks document `InvalidDescriptor` as the only
2890            // refusal they have; anything else still crosses rather than being
2891            // dropped.
2892            HalError::InvalidDescriptor(message) => message,
2893            other => other.to_string(),
2894        };
2895        self.fail(wrap(message.clone()));
2896        if self.failed.is_none() {
2897            self.failed = Some(HalError::InvalidDescriptor(message));
2898        }
2899    }
2900
2901    /// Requires a handle to still resolve *and* to belong to this device.
2902    fn need_live(&self, command: &'static str, kind: ObjectKind, bits: u64) {
2903        let state = self.recorder.lock();
2904        if state.is_owned_by(kind, bits, self.device_id) {
2905            return;
2906        }
2907        let error = if state.is_live(kind, bits) {
2908            ValidationError::ForeignHandle {
2909                command,
2910                kind,
2911                bits,
2912            }
2913        } else {
2914            ValidationError::DeadHandle {
2915                command,
2916                kind,
2917                bits,
2918            }
2919        };
2920        drop(state);
2921        self.fail(error);
2922    }
2923}
2924
2925impl CommandEncoder for NullEncoder {
2926    fn begin_debug_label(&mut self, label: &str) {
2927        self.record(Command::BeginDebugLabel(label.to_string()));
2928    }
2929
2930    fn end_debug_label(&mut self) {
2931        self.record(Command::EndDebugLabel);
2932    }
2933
2934    fn insert_debug_marker(&mut self, label: &str) {
2935        self.record(Command::DebugMarker(label.to_string()));
2936    }
2937
2938    fn pipeline_barrier(&mut self, barriers: &Barriers<'_>) {
2939        self.need_outside("Barrier");
2940        for barrier in barriers.buffers {
2941            self.need_live("Barrier", ObjectKind::Buffer, barrier.buffer.to_bits());
2942        }
2943        for barrier in barriers.images {
2944            self.need_live("Barrier", ObjectKind::Image, barrier.image.to_bits());
2945        }
2946        self.record(Command::Barrier {
2947            buffers: barriers.buffers.to_vec(),
2948            images: barriers.images.to_vec(),
2949            global: barriers.global,
2950        });
2951    }
2952
2953    fn copy_buffer_to_buffer(&mut self, copy: &BufferCopy) {
2954        self.need_outside("CopyBufferToBuffer");
2955        self.need_live("CopyBufferToBuffer", ObjectKind::Buffer, copy.src.to_bits());
2956        self.need_live("CopyBufferToBuffer", ObjectKind::Buffer, copy.dst.to_bits());
2957        self.record(Command::CopyBufferToBuffer(*copy));
2958    }
2959
2960    fn copy_buffer_to_image(&mut self, copy: &BufferImageCopy) {
2961        self.need_outside("CopyBufferToImage");
2962        self.need_live(
2963            "CopyBufferToImage",
2964            ObjectKind::Buffer,
2965            copy.buffer.to_bits(),
2966        );
2967        self.need_live("CopyBufferToImage", ObjectKind::Image, copy.image.to_bits());
2968        self.record(Command::CopyBufferToImage(*copy));
2969    }
2970
2971    fn copy_image_to_buffer(&mut self, copy: &BufferImageCopy) {
2972        self.need_outside("CopyImageToBuffer");
2973        self.need_live("CopyImageToBuffer", ObjectKind::Image, copy.image.to_bits());
2974        self.need_live(
2975            "CopyImageToBuffer",
2976            ObjectKind::Buffer,
2977            copy.buffer.to_bits(),
2978        );
2979        self.record(Command::CopyImageToBuffer(*copy));
2980    }
2981
2982    fn copy_image_to_image(&mut self, copy: &ImageCopy) {
2983        self.need_outside("CopyImageToImage");
2984        self.need_live("CopyImageToImage", ObjectKind::Image, copy.src.to_bits());
2985        self.need_live("CopyImageToImage", ObjectKind::Image, copy.dst.to_bits());
2986        self.record(Command::CopyImageToImage(*copy));
2987    }
2988
2989    fn clear_buffer(&mut self, buffer: BufferHandle, offset: u64, size: u64) {
2990        self.need_outside("ClearBuffer");
2991        self.need_live("ClearBuffer", ObjectKind::Buffer, buffer.to_bits());
2992        self.record(Command::ClearBuffer {
2993            buffer,
2994            offset,
2995            size,
2996        });
2997    }
2998
2999    fn begin_render_pass(&mut self, desc: &RenderPassDesc<'_>) {
3000        for attachment in desc.color_attachments {
3001            self.need_live(
3002                "BeginRenderPass",
3003                ObjectKind::ImageView,
3004                attachment.view.to_bits(),
3005            );
3006            if let Some(resolve) = attachment.resolve {
3007                self.need_live("BeginRenderPass", ObjectKind::ImageView, resolve.to_bits());
3008            }
3009        }
3010        if let Some(attachment) = desc.depth_stencil_attachment {
3011            self.need_live(
3012                "BeginRenderPass",
3013                ObjectKind::ImageView,
3014                attachment.view.to_bits(),
3015            );
3016        }
3017        self.need_timestamps("BeginRenderPass", desc.timestamp_writes);
3018        self.record(Command::BeginRenderPass {
3019            label: desc.label.map(ToOwned::to_owned),
3020            color_attachments: desc.color_attachments.to_vec(),
3021            depth_stencil_attachment: desc.depth_stencil_attachment,
3022            render_area: desc.render_area,
3023            timestamp_writes: desc.timestamp_writes,
3024        });
3025    }
3026
3027    fn end_render_pass(&mut self) {
3028        self.record(Command::EndRenderPass);
3029    }
3030
3031    fn set_viewport(&mut self, viewport: &Viewport) {
3032        self.need_render("SetViewport");
3033        self.record(Command::SetViewport(*viewport));
3034    }
3035
3036    fn set_scissor(&mut self, rect: &Rect2d) {
3037        self.need_render("SetScissor");
3038        self.record(Command::SetScissor(*rect));
3039    }
3040
3041    fn set_stencil_reference(&mut self, reference: u32) {
3042        self.need_render("SetStencilReference");
3043        self.record(Command::SetStencilReference(reference));
3044    }
3045
3046    fn bind_graphics_pipeline(&mut self, pipeline: GraphicsPipelineHandle) {
3047        self.need_render("BindGraphicsPipeline");
3048        self.need_live(
3049            "BindGraphicsPipeline",
3050            ObjectKind::GraphicsPipeline,
3051            pipeline.to_bits(),
3052        );
3053        self.record(Command::BindGraphicsPipeline(pipeline));
3054    }
3055
3056    fn bind_index_buffer(&mut self, buffer: BufferHandle, offset: u64, format: IndexFormat) {
3057        self.need_render("BindIndexBuffer");
3058        self.need_live("BindIndexBuffer", ObjectKind::Buffer, buffer.to_bits());
3059        self.record(Command::BindIndexBuffer {
3060            buffer,
3061            offset,
3062            format,
3063        });
3064    }
3065
3066    fn bind_group(
3067        &mut self,
3068        slot: u32,
3069        group: BindGroupHandle,
3070        dynamic_offsets: &[u32],
3071        _layout: PipelineLayoutHandle,
3072    ) {
3073        self.need_any_pass("BindGroup");
3074        self.need_live("BindGroup", ObjectKind::BindGroup, group.to_bits());
3075        self.need_dynamic_offsets("BindGroup", group, dynamic_offsets);
3076        self.record(Command::BindGroup {
3077            slot,
3078            group,
3079            dynamic_offsets: dynamic_offsets.to_vec(),
3080        });
3081    }
3082
3083    fn push_constants(
3084        &mut self,
3085        stages: ShaderStages,
3086        offset: u32,
3087        data: &[u8],
3088        _layout: PipelineLayoutHandle,
3089    ) {
3090        self.need_any_pass("PushConstants");
3091        self.record(Command::PushConstants {
3092            stages,
3093            offset,
3094            len: data.len(),
3095        });
3096    }
3097
3098    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
3099        self.need_render("Draw");
3100        self.record(Command::Draw {
3101            vertices,
3102            instances,
3103        });
3104    }
3105
3106    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
3107        self.need_render("DrawIndexed");
3108        self.record(Command::DrawIndexed {
3109            indices,
3110            base_vertex,
3111            instances,
3112        });
3113    }
3114
3115    fn draw_indirect(&mut self, draw: &DrawIndirect) {
3116        self.need_render("DrawIndirect");
3117        self.need_live("DrawIndirect", ObjectKind::Buffer, draw.args.to_bits());
3118        self.need_indirect_arguments("DrawIndirect", draw, false);
3119        self.record(Command::DrawIndirect(*draw));
3120    }
3121
3122    fn draw_indexed_indirect(&mut self, draw: &DrawIndirect) {
3123        self.need_render("DrawIndexedIndirect");
3124        self.need_live(
3125            "DrawIndexedIndirect",
3126            ObjectKind::Buffer,
3127            draw.args.to_bits(),
3128        );
3129        self.need_indirect_arguments("DrawIndexedIndirect", draw, true);
3130        self.record(Command::DrawIndexedIndirect(*draw));
3131    }
3132
3133    fn draw_indirect_count(&mut self, draw: &DrawIndirectCount) {
3134        self.need_render("DrawIndirectCount");
3135        self.need_live("DrawIndirectCount", ObjectKind::Buffer, draw.args.to_bits());
3136        self.need_live(
3137            "DrawIndirectCount",
3138            ObjectKind::Buffer,
3139            draw.count_buffer.to_bits(),
3140        );
3141        self.need_indirect_count_arguments("DrawIndirectCount", draw, false);
3142        self.record(Command::DrawIndirectCount(*draw));
3143    }
3144
3145    fn draw_indexed_indirect_count(&mut self, draw: &DrawIndirectCount) {
3146        self.need_render("DrawIndexedIndirectCount");
3147        self.need_live(
3148            "DrawIndexedIndirectCount",
3149            ObjectKind::Buffer,
3150            draw.args.to_bits(),
3151        );
3152        self.need_live(
3153            "DrawIndexedIndirectCount",
3154            ObjectKind::Buffer,
3155            draw.count_buffer.to_bits(),
3156        );
3157        self.need_indirect_count_arguments("DrawIndexedIndirectCount", draw, true);
3158        self.record(Command::DrawIndexedIndirectCount(*draw));
3159    }
3160
3161    fn draw_mesh_tasks(&mut self, x: u32, y: u32, z: u32) {
3162        // A draw, so `need_render` rather than `need_compute` — the three
3163        // counts are workgroups, but they are workgroups of a stage that emits
3164        // fragments.
3165        self.need_render("DrawMeshTasks");
3166        self.record(Command::DrawMeshTasks { x, y, z });
3167    }
3168
3169    fn draw_mesh_tasks_indirect(&mut self, draw: &DrawIndirect) {
3170        // A draw for `draw_mesh_tasks`' reason, and a live-buffer check for
3171        // `draw_indexed_indirect`'s: the argument buffer is the whole of what
3172        // this call names, so a dead handle here is a frame that reads its
3173        // group counts from nothing.
3174        self.need_render("DrawMeshTasksIndirect");
3175        self.need_live(
3176            "DrawMeshTasksIndirect",
3177            ObjectKind::Buffer,
3178            draw.args.to_bits(),
3179        );
3180        self.need_mesh_indirect_arguments("DrawMeshTasksIndirect", draw);
3181        self.record(Command::DrawMeshTasksIndirect(*draw));
3182    }
3183
3184    fn begin_compute_pass(&mut self, desc: &ComputePassDesc<'_>) {
3185        self.need_timestamps("BeginComputePass", desc.timestamp_writes);
3186        self.record(Command::BeginComputePass {
3187            label: desc.label.map(ToOwned::to_owned),
3188            timestamp_writes: desc.timestamp_writes,
3189        });
3190    }
3191
3192    fn end_compute_pass(&mut self) {
3193        self.record(Command::EndComputePass);
3194    }
3195
3196    fn bind_compute_pipeline(&mut self, pipeline: ComputePipelineHandle) {
3197        self.need_compute("BindComputePipeline");
3198        self.need_live(
3199            "BindComputePipeline",
3200            ObjectKind::ComputePipeline,
3201            pipeline.to_bits(),
3202        );
3203        self.record(Command::BindComputePipeline(pipeline));
3204    }
3205
3206    fn dispatch(&mut self, x: u32, y: u32, z: u32) {
3207        self.need_compute("Dispatch");
3208        self.record(Command::Dispatch { x, y, z });
3209    }
3210
3211    fn dispatch_indirect(&mut self, args: BufferHandle, offset: u64) {
3212        self.need_compute("DispatchIndirect");
3213        self.need_live("DispatchIndirect", ObjectKind::Buffer, args.to_bits());
3214        self.record(Command::DispatchIndirect { args, offset });
3215    }
3216
3217    fn reset_query_set(&mut self, set: QuerySetHandle, range: Range<u32>) {
3218        self.need_outside("ResetQuerySet");
3219        self.need_live("ResetQuerySet", ObjectKind::QuerySet, set.to_bits());
3220        self.record(Command::ResetQuerySet { set, range });
3221    }
3222
3223    fn resolve_query_set(
3224        &mut self,
3225        set: QuerySetHandle,
3226        range: Range<u32>,
3227        dst: BufferHandle,
3228        dst_offset: u64,
3229    ) {
3230        self.need_outside("ResolveQuerySet");
3231        self.need_live("ResolveQuerySet", ObjectKind::QuerySet, set.to_bits());
3232        self.need_live("ResolveQuerySet", ObjectKind::Buffer, dst.to_bits());
3233        self.record(Command::ResolveQuerySet {
3234            set,
3235            range,
3236            dst,
3237            dst_offset,
3238        });
3239    }
3240
3241    fn finish(self: Box<Self>) -> Result<CommandBufferHandle, HalError> {
3242        if let Some(error) = self.failed {
3243            return Err(error);
3244        }
3245        if self.scope != Scope::Outside {
3246            // Recorded *and* returned. The seam's `finish` doc names an
3247            // unclosed pass as an `Err` case and `crcbl-vk` returns one, so a
3248            // null backend that answered `Ok` let CI green-light a command
3249            // stream Vulkan refuses to end at all — `vkEndCommandBuffer` with
3250            // a `vkCmdBeginRendering` outstanding is itself illegal.
3251            self.fail(ValidationError::UnclosedPass);
3252            return Err(HalError::InvalidDescriptor(
3253                "finish with a pass still open".to_string(),
3254            ));
3255        }
3256        let mut state = self.recorder.lock();
3257        let command_buffer: CommandBufferHandle = state.insert_owned(
3258            ObjectKind::CommandBuffer,
3259            self.device_id,
3260            self.label.clone(),
3261            Detail::None,
3262        );
3263        for command in self.commands {
3264            state.events.push(Event::Command {
3265                command_buffer,
3266                command,
3267            });
3268        }
3269        state.events.push(Event::Finished {
3270            label: self.label,
3271            command_buffer,
3272        });
3273        Ok(command_buffer)
3274    }
3275}
3276
3277#[cfg(test)]
3278mod tests;