From d01aa31d69c412d73c3732f5f4ce2d2a81be9f7b Mon Sep 17 00:00:00 2001 From: Sam <16504129+sagudev@users.noreply.github.com> Date: Tue, 30 Jun 2026 12:11:10 +0200 Subject: [PATCH] [core] Move validity into `Arc` (#9762) Signed-off-by: sagudev <16504129+sagudev@users.noreply.github.com> --- player/src/lib.rs | 33 +---------- player/tests/player/data/bind-group.ron | 2 +- .../player/data/pipeline-statistics-query.ron | 2 +- player/tests/player/data/zero-init-buffer.ron | 2 +- .../player/data/zero-init-texture-binding.ron | 2 +- wgpu-core/src/command/compute.rs | 23 +++++--- wgpu-core/src/device/global.rs | 47 +++++---------- wgpu-core/src/device/resource.rs | 40 +++++++++++-- wgpu-core/src/device/trace.rs | 2 +- wgpu-core/src/hub.rs | 2 +- wgpu-core/src/pipeline.rs | 57 +++++++++++++++++-- 11 files changed, 121 insertions(+), 91 deletions(-) diff --git a/player/src/lib.rs b/player/src/lib.rs index e2c5db231..d8ec134ca 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -14,7 +14,7 @@ use wgc::{ binding_model::BindingResource, command::{ArcCommand, ArcReferences, BasePass, Command, PointerReferences}, device::trace::{self, DataKind, DataLoader}, - id::{Marker, PointerId}, + id::PointerId, }; #[derive(Debug)] @@ -89,28 +89,6 @@ impl Default for Player { } } -fn process_result( - op: &str, - map: &mut HashMap, U>, - id: Option>, - value: Result, -) { - match (id, value) { - (Some(id), Ok(value)) => { - map.insert(id, value); - } - (Some(_), Err(err)) => { - panic!("{op} succeeded when recording, but failed on playback: {err}"); - } - (None, Ok(_)) => { - panic!("{op} failed when recording, but succeeded on playback"); - } - (None, Err(err)) => { - panic!("{op} failed when recording, and failed on playback: {err}"); - } - } -} - impl Player { pub fn process( &mut self, @@ -353,13 +331,8 @@ impl Player { } Action::CreateComputePipeline { id, desc } => { let resolved_desc = self.resolve_compute_pipeline_descriptor(desc); - let pipeline = device.create_compute_pipeline(resolved_desc); - process_result( - "create_compute_pipeline", - &mut self.compute_pipelines, - id, - pipeline, - ); + let (pipeline, _error) = device.create_compute_pipeline(resolved_desc); + self.compute_pipelines.insert(id, pipeline); } Action::DropComputePipeline(id) => { self.compute_pipelines diff --git a/player/tests/player/data/bind-group.ron b/player/tests/player/data/bind-group.ron index e887b3720..c434b1d11 100644 --- a/player/tests/player/data/bind-group.ron +++ b/player/tests/player/data/bind-group.ron @@ -50,7 +50,7 @@ data: File("empty.wgsl"), ), CreateComputePipeline( - id: Some(PointerId(0x10)), + id: PointerId(0x10), desc: ( label: None, layout: Some(PointerId(0x10)), diff --git a/player/tests/player/data/pipeline-statistics-query.ron b/player/tests/player/data/pipeline-statistics-query.ron index 083663ac7..3bde19bb6 100644 --- a/player/tests/player/data/pipeline-statistics-query.ron +++ b/player/tests/player/data/pipeline-statistics-query.ron @@ -23,7 +23,7 @@ data: File("empty.wgsl"), ), CreateComputePipeline( - id: Some(PointerId(0x10)), + id: PointerId(0x10), desc: ( label: None, layout: Some(PointerId(0x10)), diff --git a/player/tests/player/data/zero-init-buffer.ron b/player/tests/player/data/zero-init-buffer.ron index 03939e8a7..1d159e18c 100644 --- a/player/tests/player/data/zero-init-buffer.ron +++ b/player/tests/player/data/zero-init-buffer.ron @@ -125,7 +125,7 @@ immediate_size: 0, )), CreateComputePipeline( - id: Some(PointerId(0x10)), + id: PointerId(0x10), desc: ( label: None, layout: Some(PointerId(0x10)), diff --git a/player/tests/player/data/zero-init-texture-binding.ron b/player/tests/player/data/zero-init-texture-binding.ron index 204ef2e8a..9f4265c57 100644 --- a/player/tests/player/data/zero-init-texture-binding.ron +++ b/player/tests/player/data/zero-init-texture-binding.ron @@ -128,7 +128,7 @@ data: File("zero-init-texture-binding.wgsl"), ), CreateComputePipeline( - id: Some(PointerId(0x10)), + id: PointerId(0x10), desc: ( label: None, layout: Some(PointerId(0x10)), diff --git a/wgpu-core/src/command/compute.rs b/wgpu-core/src/command/compute.rs index 0ba412c31..d4099debf 100644 --- a/wgpu-core/src/command/compute.rs +++ b/wgpu-core/src/command/compute.rs @@ -915,22 +915,23 @@ fn set_pipeline( .pass .base .raw_encoder - .set_compute_pipeline(pipeline.raw()); + .set_compute_pipeline(pipeline.raw()?); } // Rebind resources + let pipeline_layout = pipeline.layout()?; pass::change_pipeline_layout::( &mut state.pass, - &pipeline.layout, + pipeline_layout, &pipeline.late_sized_buffer_groups, || { // This only needs to be here for compute pipelines because they use immediates for // validating indirect draws. state.immediates.clear(); // Note that can only be one range for each stage. See the `MoreThanOneImmediateRangePerStage` error. - if pipeline.layout.immediate_size != 0 { + if pipeline_layout.immediate_size != 0 { // Note that non-0 range start doesn't work anyway https://github.com/gfx-rs/wgpu/issues/4502 - let len = pipeline.layout.immediate_size as usize + let len = pipeline_layout.immediate_size as usize / wgt::IMMEDIATE_DATA_ALIGNMENT as usize; state.immediates.extend(core::iter::repeat_n(0, len)); } @@ -1097,13 +1098,15 @@ fn dispatch_workgroups_indirect( .pass .base .raw_encoder - .set_compute_pipeline(pipeline.raw()); + .set_compute_pipeline(pipeline.raw()?); } + let pipeline_layout = pipeline.layout()?; + if !state.immediates.is_empty() { unsafe { state.pass.base.raw_encoder.set_immediates( - pipeline.layout.raw(), + pipeline_layout.raw(), 0, &state.immediates, ); @@ -1114,7 +1117,7 @@ fn dispatch_workgroups_indirect( let raw_bg = group.try_raw(state.pass.base.snatch_guard)?; unsafe { state.pass.base.raw_encoder.set_bind_group( - pipeline.layout.raw(), + pipeline_layout.raw(), i as u32, raw_bg, dynamic_offsets, @@ -1234,9 +1237,11 @@ impl Global { } let hub = &self.hub; - let pipeline = pass_try!(base, scope, hub.compute_pipelines.get(pipeline_id).get()); + let compute_pipeline = hub.compute_pipelines.get(pipeline_id); + pass_try!(base, scope, compute_pipeline.check_valid()); - base.commands.push(ArcComputeCommand::SetPipeline(pipeline)); + base.commands + .push(ArcComputeCommand::SetPipeline(compute_pipeline)); Ok(()) } diff --git a/wgpu-core/src/device/global.rs b/wgpu-core/src/device/global.rs index ac828e138..e86af17e6 100644 --- a/wgpu-core/src/device/global.rs +++ b/wgpu-core/src/device/global.rs @@ -1648,9 +1648,11 @@ impl Global { let fid = hub.compute_pipelines.prepare(id_in); - let error = 'error: { - let device = self.hub.devices.get(device_id); + let device = self.hub.devices.get(device_id); + // eventually there will be no error handling here only id to object mapping + let error = 'error: { + // until then we also need this if let Err(e) = device.check_is_valid() { break 'error e.into(); } @@ -1697,31 +1699,18 @@ impl Global { cache, }; - #[cfg(feature = "trace")] - let trace_desc = desc.clone().into_trace(); + let (pipeline, error) = device.create_compute_pipeline(desc); - let res = device.create_compute_pipeline(desc); - - #[cfg(feature = "trace")] - if let Some(ref mut trace) = *device.trace.lock() { - trace.add(trace::Action::CreateComputePipeline { - id: res.as_ref().ok().map(IntoTrace::to_trace), - desc: trace_desc, - }); - } - - let pipeline = match res { - Ok(pair) => pair, - Err(e) => break 'error e, - }; - - let id = fid.assign(Fallible::Valid(pipeline)); + let id = fid.assign(pipeline); api_log!("Device::create_compute_pipeline -> {id:?}"); - return (id, None); + return (id, error); }; - let id = fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string()))); + let id = fid.assign(pipeline::ComputePipeline::invalid( + device, + desc.label.to_string(), + )); (id, Some(error)) } @@ -1741,12 +1730,9 @@ impl Global { let fid = hub.bind_group_layouts.prepare(id_in); - let error = 'error: { - let pipeline = match hub.compute_pipelines.get(pipeline_id).get() { - Ok(pipeline) => pipeline, - Err(e) => break 'error e.into(), - }; + let pipeline = hub.compute_pipelines.get(pipeline_id); + let error = 'error: { match pipeline.get_bind_group_layout(index) { Ok(bgl) => { #[cfg(feature = "trace")] @@ -1776,13 +1762,6 @@ impl Global { let hub = &self.hub; let _pipeline = hub.compute_pipelines.remove(compute_pipeline_id); - - #[cfg(feature = "trace")] - if let Ok(pipeline) = _pipeline.get() { - if let Some(t) = pipeline.device.trace.lock().as_mut() { - t.add(trace::Action::DropComputePipeline(pipeline.to_trace())); - } - } } /// # Safety diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index e3728beb3..3de47ed93 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -47,7 +47,7 @@ use crate::{ present, resource::{ self, Buffer, ExternalTexture, Fallible, Labeled, ParentDevice, QuerySet, - RawResourceAccess, Sampler, StagingBuffer, Texture, TextureView, + RawResourceAccess, ResourceState, Sampler, StagingBuffer, Texture, TextureView, TextureViewNotRenderableReason, Tlas, TrackingData, }, resource_log, @@ -3957,6 +3957,32 @@ impl Device { pub fn create_compute_pipeline( self: &Arc, desc: pipeline::ResolvedComputePipelineDescriptor, + ) -> ( + Arc, + Option, + ) { + let (compute_pipeline, error) = match self.create_compute_pipeline_inner(desc.clone()) { + Ok(compute_pipeline) => (compute_pipeline, None), + Err(error) => ( + pipeline::ComputePipeline::invalid(self.clone(), desc.label.to_string()), + Some(error), + ), + }; + #[cfg(feature = "trace")] + if let Some(ref mut trace) = *self.trace.lock() { + use crate::device::trace; + use crate::device::trace::IntoTrace; + trace.add(trace::Action::CreateComputePipeline { + id: compute_pipeline.to_trace(), + desc: desc.to_trace(), + }); + } + (compute_pipeline, error) + } + + pub fn create_compute_pipeline_inner( + self: &Arc, + desc: pipeline::ResolvedComputePipelineDescriptor, ) -> Result, pipeline::CreateComputePipelineError> { self.check_is_valid()?; @@ -4072,10 +4098,12 @@ impl Device { }); let pipeline = pipeline::ComputePipeline { - raw: ManuallyDrop::new(raw), - layout: pipeline_layout, + state: ResourceState::Valid(pipeline::ComputePipelineState { + raw: ManuallyDrop::new(raw), + layout: pipeline_layout.clone(), + _shader_module: shader_module, + }), device: self.clone(), - _shader_module: shader_module, late_sized_buffer_groups, immediate_slots_required, label: desc.label.to_string(), @@ -4085,7 +4113,7 @@ impl Device { let pipeline = Arc::new(pipeline); if is_auto_layout { - for bgl in pipeline.layout.bind_group_layouts.iter() { + for bgl in pipeline_layout.bind_group_layouts.iter() { let Some(bgl) = bgl else { continue; }; @@ -4953,7 +4981,7 @@ impl Device { }; let pipeline = pipeline::RenderPipeline { - state: resource::ResourceState::Valid(pipeline::RenderPipelineState { + state: ResourceState::Valid(pipeline::RenderPipelineState { raw: ManuallyDrop::new(raw), layout: pipeline_layout.clone(), }), diff --git a/wgpu-core/src/device/trace.rs b/wgpu-core/src/device/trace.rs index 5dd66080f..b3c4a38c3 100644 --- a/wgpu-core/src/device/trace.rs +++ b/wgpu-core/src/device/trace.rs @@ -195,7 +195,7 @@ pub enum Action<'a, R: ReferenceType> { }, DropShaderModule(PointerId), CreateComputePipeline { - id: Option>, + id: PointerId, desc: TraceComputePipelineDescriptor<'a>, }, DropComputePipeline(PointerId), diff --git a/wgpu-core/src/hub.rs b/wgpu-core/src/hub.rs index 2daf85a9a..d498d6e80 100644 --- a/wgpu-core/src/hub.rs +++ b/wgpu-core/src/hub.rs @@ -195,7 +195,7 @@ pub struct Hub { pub(crate) command_buffers: Registry>, pub(crate) render_bundles: Registry>, pub(crate) render_pipelines: Registry>, - pub(crate) compute_pipelines: Registry>, + pub(crate) compute_pipelines: Registry>, pub(crate) pipeline_caches: Registry>, pub(crate) query_sets: Registry>, pub(crate) buffers: Registry>, diff --git a/wgpu-core/src/pipeline.rs b/wgpu-core/src/pipeline.rs index 21eb2d77e..fd32c36f3 100644 --- a/wgpu-core/src/pipeline.rs +++ b/wgpu-core/src/pipeline.rs @@ -301,11 +301,16 @@ impl WebGpuError for CreateComputePipelineError { } #[derive(Debug)] -pub struct ComputePipeline { +pub struct ComputePipelineState { pub(crate) raw: ManuallyDrop>, pub(crate) layout: Arc, - pub(crate) device: Arc, pub(crate) _shader_module: Arc, +} + +#[derive(Debug)] +pub struct ComputePipeline { + pub(crate) state: ResourceState, + pub(crate) device: Arc, pub(crate) late_sized_buffer_groups: ArrayVec, pub(crate) immediate_slots_required: naga::valid::ImmediateSlots, /// The `label` from the descriptor used to create the resource. @@ -316,8 +321,20 @@ pub struct ComputePipeline { impl Drop for ComputePipeline { fn drop(&mut self) { resource_log!("Destroy raw {}", self.error_ident()); + #[cfg(feature = "trace")] + { + use crate::device::trace; + if let Some(t) = self.device.trace.lock().as_mut() { + t.add(trace::Action::DropComputePipeline(unsafe { + trace::to_trace(self) + })); + } + } + let ResourceState::Valid(state) = &mut self.state else { + return; + }; // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point. - let raw = unsafe { ManuallyDrop::take(&mut self.raw) }; + let raw = unsafe { ManuallyDrop::take(&mut state.raw) }; unsafe { self.device.raw().destroy_compute_pipeline(raw); } @@ -331,15 +348,43 @@ crate::impl_storage_item!(ComputePipeline); crate::impl_trackable!(ComputePipeline); impl ComputePipeline { - pub(crate) fn raw(&self) -> &dyn hal::DynComputePipeline { - self.raw.as_ref() + pub(crate) fn raw(&self) -> Result<&dyn hal::DynComputePipeline, InvalidResourceError> { + let ResourceState::Valid(state) = &self.state else { + return Err(InvalidResourceError(self.error_ident())); + }; + Ok(state.raw.as_ref()) + } + + pub(crate) fn layout(&self) -> Result<&Arc, InvalidResourceError> { + let ResourceState::Valid(state) = &self.state else { + return Err(InvalidResourceError(self.error_ident())); + }; + Ok(&state.layout) + } + + pub(crate) fn check_valid(&self) -> Result<(), InvalidResourceError> { + let ResourceState::Valid(_) = &self.state else { + return Err(InvalidResourceError(self.error_ident())); + }; + Ok(()) + } + + pub(crate) fn invalid(device: Arc, label: String) -> Arc { + Arc::new(Self { + tracking_data: TrackingData::new(device.tracker_indices.compute_pipelines.clone()), + state: ResourceState::Invalid, + device, + late_sized_buffer_groups: ArrayVec::new(), + immediate_slots_required: naga::valid::ImmediateSlots::default(), + label, + }) } pub fn get_bind_group_layout( self: &Arc, index: u32, ) -> Result, GetBindGroupLayoutError> { - self.layout.get_bind_group_layout(index, self.into()) + self.layout()?.get_bind_group_layout(index, self.into()) } }