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