From 8630a774af7c386457d596eabb5e25c43e3018bf Mon Sep 17 00:00:00 2001 From: Jinlei Li Date: Fri, 18 Sep 2026 20:55:21 +0800 Subject: [PATCH] fix(core): Implement render bundle debug commands (#10308) --- CHANGELOG.md | 11 ++ cts_runner/test.lst | 3 +- tests/tests/wgpu-validation/api/mod.rs | 1 + .../wgpu-validation/api/render_bundle.rs | 170 ++++++++++++++++++ wgpu-core/src/command/bundle.rs | 122 +++++++++---- wgpu-core/src/command/render.rs | 3 - wgpu/src/api/render_bundle_encoder.rs | 17 ++ wgpu/src/backend/webgpu.rs | 12 ++ wgpu/src/backend/wgpu_core.rs | 12 ++ wgpu/src/dispatch.rs | 4 + 10 files changed, 311 insertions(+), 44 deletions(-) create mode 100644 tests/tests/wgpu-validation/api/render_bundle.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index a44f7f457..e4219a856 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -106,6 +106,17 @@ By @sagudev in [#10109](https://github.com/gfx-rs/wgpu/pull/10109). - Zero-size vertex and index buffer bindings are now accepted by `set_vertex_buffer` and `set_index_buffer`. By @andyleiserson in [#9848](https://github.com/gfx-rs/wgpu/pull/9848). - Added the `snorm10-10-10-2` vertex format on Metal and Vulkan. Not yet supported on DX12. By @andyleiserson in [#10226](https://github.com/gfx-rs/wgpu/pull/10226). +- Added the following methods to `RenderBundleEncoder` for recording debug markers and groups: + + - `insert_debug_marker(&mut self, label: &str)` + - `push_debug_group(&mut self, label: &str)` + - `pop_debug_group(&mut self)` + + `wgpu-core` now validates debug group balance at `finish()` and replays debug annotations when executing render bundles. `InstanceFlags::DISCARD_HAL_LABELS` suppresses native debug annotations without disabling validation. + + **Breaking for custom backends:** Implementations of `RenderBundleEncoderInterface` must implement these three new methods. + + By @jinleili in [#10308](https://github.com/gfx-rs/wgpu/pull/10308). #### Naga diff --git a/cts_runner/test.lst b/cts_runner/test.lst index 20522f8e0..0a80f8ae8 100644 --- a/cts_runner/test.lst +++ b/cts_runner/test.lst @@ -170,8 +170,7 @@ webgpu:api,validation,encoding,cmds,copyBufferToBuffer:* webgpu:api,validation,encoding,cmds,copyTextureToTexture:* webgpu:api,validation,encoding,cmds,debug:debug_group_balanced:encoderType="compute%20pass" webgpu:api,validation,encoding,cmds,debug:debug_group_balanced:encoderType="non-pass" -//FAIL: webgpu:api,validation,encoding,cmds,debug:debug_group_balanced:encoderType="render%20bundle" -// https://github.com/gfx-rs/wgpu/issues/8039 +webgpu:api,validation,encoding,cmds,debug:debug_group_balanced:encoderType="render%20bundle" webgpu:api,validation,encoding,cmds,debug:debug_group_balanced:encoderType="render%20pass" webgpu:api,validation,encoding,cmds,debug:debug_group:* webgpu:api,validation,encoding,cmds,debug:debug_marker:* diff --git a/tests/tests/wgpu-validation/api/mod.rs b/tests/tests/wgpu-validation/api/mod.rs index a7ef7c84d..05b9510db 100644 --- a/tests/tests/wgpu-validation/api/mod.rs +++ b/tests/tests/wgpu-validation/api/mod.rs @@ -12,5 +12,6 @@ mod immediates; mod instance; mod mesh_shader; mod ray_tracing_pipeline; +mod render_bundle; mod render_pipeline; mod texture; diff --git a/tests/tests/wgpu-validation/api/render_bundle.rs b/tests/tests/wgpu-validation/api/render_bundle.rs new file mode 100644 index 000000000..1c7aa11b3 --- /dev/null +++ b/tests/tests/wgpu-validation/api/render_bundle.rs @@ -0,0 +1,170 @@ +use wgpu::*; +use wgpu_test::{fail, fail_if, valid}; + +/// Encodes `+` (push), `-` (pop), and `m` (marker), asserting no encoding-time error. +fn encode<'a>(device: &'a Device, ops: &str) -> RenderBundleEncoder<'a> { + let mut encoder = device.create_render_bundle_encoder(&RenderBundleEncoderDescriptor { + color_formats: &[Some(TextureFormat::Rgba8Unorm)], + sample_count: 1, + ..Default::default() + }); + valid(device, || { + for op in ops.chars() { + match op { + '+' => encoder.push_debug_group("group\0\u{1f31e}"), + '-' => encoder.pop_debug_group(), + 'm' => encoder.insert_debug_marker(""), + _ => unreachable!(), + } + } + }); + encoder +} + +/// Group errors are reported at finish, even when HAL labels are discarded. +#[test] +fn debug_group_balance() { + for discard_labels in [false, true] { + let params = wgpu_test::TestParameters::default(); + let params = if discard_labels { + params.instance_flags(InstanceFlags::DISCARD_HAL_LABELS) + } else { + params.remove_instance_flags(InstanceFlags::DISCARD_HAL_LABELS) + }; + let instance = wgpu_test::initialize_instance(Backends::NOOP, ¶ms); + let adapter = pollster::block_on(instance.request_adapter(&Default::default())).unwrap(); + let (device, _queue) = + pollster::block_on(adapter.request_device(&Default::default())).unwrap(); + for (ops, expected) in [ + ("", None), + ("m", None), + ("+-", None), + ("++m--", None), + ("+-+-", None), + ("-", Some("Cannot pop debug group")), + ("+", Some("A debug group was not popped")), + // Equal push/pop counts must not hide an earlier underflow. + ("-+", Some("Cannot pop debug group")), + ("+--+", Some("Cannot pop debug group")), + ("+--", Some("Cannot pop debug group")), + ] { + eprintln!("ops={ops:?}, discard_labels={discard_labels}"); + let encoder = encode(&device, ops); + fail_if( + &device, + expected.is_some(), + || encoder.finish(&Default::default()), + expected, + ); + } + } +} + +/// Both successful and failed finish calls permanently end the encoder. +/// Uses core directly because the public Rust API consumes the encoder at finish. +#[test] +fn finish_ends_encoder() { + use wgpu_core::{command as c, instance::Instance}; + + let mut desc = InstanceDescriptor::new_without_display_handle(); + desc.backends = Backends::NOOP; + desc.backend_options.noop.enable = true; + let (device, _queue) = Instance::new("bundle debug validation", desc, None) + .request_adapter(&Default::default(), Backends::NOOP) + .unwrap() + .request_device(&Default::default()) + .unwrap(); + for op in [None, Some('-'), Some('+')] { + let mut encoder = device.create_render_bundle_encoder(&c::RenderBundleEncoderDescriptor { + color_formats: std::borrow::Cow::Borrowed(&[Some(TextureFormat::Rgba8Unorm)]), + ..Default::default() + }); + match op { + Some('-') => encoder.pop_debug_group(), + Some('+') => encoder.push_debug_group("unclosed"), + _ => {} + } + device.push_error_scope(ErrorFilter::Validation); + encoder.finish(&Default::default()); + assert_eq!(device.pop_error_scope().unwrap().is_some(), op.is_some()); + for operation in ["push", "pop", "marker", "finish"] { + device.push_error_scope(ErrorFilter::Validation); + match operation { + "push" => encoder.push_debug_group("ended"), + "pop" => encoder.pop_debug_group(), + "marker" => encoder.insert_debug_marker("ended"), + "finish" => { + encoder.finish(&Default::default()); + } + _ => unreachable!(), + } + let error = device.pop_error_scope().unwrap().unwrap(); + let expected = if operation == "finish" { + "Render bundle encoder has already ended" + } else { + "Encoding must not have ended" + }; + assert!( + error.to_string().contains(expected), + "{operation} after {op:?}: {error}" + ); + } + } +} + +/// Using an invalid bundle reports an error at command encoder finish, not pass end. +#[test] +fn invalid_bundle_rejected_by_pass() { + let (device, _queue) = Device::noop(&Default::default()); + let texture = device.create_texture(&TextureDescriptor { + label: None, + size: Extent3d { + width: 1, + height: 1, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: TextureDimension::D2, + format: TextureFormat::Rgba8Unorm, + usage: TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + for (ops, expected) in [ + ("-", "Cannot pop debug group"), + ("+", "A debug group was not popped"), + ] { + let bundle = fail( + &device, + || encode(&device, ops).finish(&Default::default()), + Some(expected), + ); + let mut commands = device.create_command_encoder(&Default::default()); + valid(&device, || { + let mut pass = commands.begin_render_pass(&RenderPassDescriptor { + color_attachments: &[Some(RenderPassColorAttachment { + view: &view, + depth_slice: None, + resolve_target: None, + ops: Operations::default(), + })], + ..Default::default() + }); + pass.push_debug_group("independent pass group"); + pass.execute_bundles([&bundle]); + pass.pop_debug_group(); + }); + fail( + &device, + || commands.finish(), + Some("RenderBundle with '' label is invalid"), + ); + } +} + +#[test] +fn dropping_invalid_encoder_does_not_report_error() { + let (device, _queue) = Device::noop(&Default::default()); + valid(&device, || drop(encode(&device, "-"))); +} diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index f63635633..aa7243203 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -84,7 +84,7 @@ use alloc::{ sync::Arc, vec::Vec, }; -use core::{convert::Infallible, mem, num::NonZeroU32, ops::Range}; +use core::{convert::Infallible, mem, num::NonZeroU32, ops::Range, str}; use arrayvec::ArrayVec; use thiserror::Error; @@ -97,9 +97,9 @@ use crate::{ command::{ bind::Binder, pass::{validate_immediates_alignment, ImmediateState}, - pass_base, ArcReferences, BasePass, BindGroupStateChange, ColorAttachmentError, DrawError, - EncoderStateError, MapPassErr, PassErrorScope, PassStateError, RenderCommand, - RenderCommandError, StateChange, + pass_base, ArcReferences, BasePass, BindGroupStateChange, ColorAttachmentError, + DebugGroupError, DrawError, EncoderStateError, MapPassErr, PassErrorScope, PassStateError, + RenderCommand, RenderCommandError, StateChange, }, device::{ AttachmentData, Device, DeviceError, MissingDownlevelFlags, MissingFeatures, @@ -386,6 +386,8 @@ impl RenderBundleEncoder { state.trackers.buffers.set_size(indices.buffers.size()); state.trackers.textures.set_size(indices.textures.size()); + let mut debug_scope_depth = 0usize; + let mut debug_string_bytes = 0usize; for command in self.base.commands.drain(..) { match command { RenderCommand::SetBindGroup { @@ -512,10 +514,28 @@ impl RenderBundleEncoder { } => { unreachable!("unexpected (multi-)draw indirect with count {count}, vertex_or_index_limits {vertex_or_index_limit:?}, instance_limit {instance_limit:?} found in a render bundle"); } - RenderCommand::MultiDrawIndirectCount { .. } - | RenderCommand::PushDebugGroup { color: _, len: _ } - | RenderCommand::InsertDebugMarker { color: _, len: _ } - | RenderCommand::PopDebugGroup => { + RenderCommand::PushDebugGroup { color, len } => { + debug_scope_depth += 1; + debug_string_bytes += len; + state + .commands + .push(ArcRenderCommand::PushDebugGroup { color, len }); + } + RenderCommand::InsertDebugMarker { color, len } => { + debug_string_bytes += len; + state + .commands + .push(ArcRenderCommand::InsertDebugMarker { color, len }); + } + RenderCommand::PopDebugGroup => { + if debug_scope_depth == 0 { + return Err(DebugGroupError::InvalidPop) + .map_pass_err(PassErrorScope::PopDebugGroup); + } + debug_scope_depth -= 1; + state.commands.push(ArcRenderCommand::PopDebugGroup); + } + RenderCommand::MultiDrawIndirectCount { .. } => { unimplemented!("not supported by a render bundle") } // Must check the TIMESTAMP_QUERY_INSIDE_PASSES feature @@ -534,6 +554,11 @@ impl RenderBundleEncoder { } } + if debug_scope_depth != 0 { + return Err(DebugGroupError::MissingPop).map_pass_err(PassErrorScope::Bundle); + } + debug_assert_eq!(debug_string_bytes, self.base.string_data.len()); + let State { trackers, flat_dynamic_offsets, @@ -864,9 +889,13 @@ impl RenderBundleEncoder { } } - fn push_debug_group_inner(&mut self, _label: &str) -> Result<(), PassStateError> { + fn push_debug_group_inner(&mut self, label: &str) -> Result<(), PassStateError> { pass_base!(self, PassErrorScope::PushDebugGroup); - //TODO + self.base.string_data.extend_from_slice(label.as_bytes()); + self.base.commands.push(RenderCommand::PushDebugGroup { + color: 0, + len: label.len(), + }); Ok(()) } @@ -879,7 +908,7 @@ impl RenderBundleEncoder { fn pop_debug_group_inner(&mut self) -> Result<(), PassStateError> { pass_base!(self, PassErrorScope::PopDebugGroup); - //TODO + self.base.commands.push(RenderCommand::PopDebugGroup); Ok(()) } @@ -890,9 +919,13 @@ impl RenderBundleEncoder { } } - fn insert_debug_marker_inner(&mut self, _label: &str) -> Result<(), PassStateError> { + fn insert_debug_marker_inner(&mut self, label: &str) -> Result<(), PassStateError> { pass_base!(self, PassErrorScope::InsertDebugMarker); - //TODO + self.base.string_data.extend_from_slice(label.as_bytes()); + self.base.commands.push(RenderCommand::InsertDebugMarker { + color: 0, + len: label.len(), + }); Ok(()) } @@ -1349,7 +1382,7 @@ impl WebGpuError for CreateRenderBundleError { } } -/// Error type returned from `RenderBundleEncoder::new` if the sample count is invalid. +/// Error encountered while executing a finished render bundle. #[derive(Clone, Debug, Error)] #[non_exhaustive] pub enum ExecutionError { @@ -1359,8 +1392,6 @@ pub enum ExecutionError { DestroyedResource(#[from] DestroyedResourceError), #[error(transparent)] InvalidResource(#[from] InvalidResourceError), - #[error("Using {0} in a render bundle is not implemented")] - Unimplemented(&'static str), } impl From for ExecutionError { @@ -1467,7 +1498,8 @@ impl RenderBundle { /// /// Note that the function isn't expected to fail, generally. /// All the validation has already been done by this point. - /// The only failure condition is if some of the used buffers are destroyed. + /// Execution can still fail if a resource was destroyed or indirect draw validation + /// cannot allocate a buffer. pub(super) unsafe fn execute( &self, raw: &mut dyn hal::DynCommandEncoder, @@ -1483,6 +1515,7 @@ impl RenderBundle { } } + let mut strings = self.base.string_data.as_slice(); use ArcRenderCommand as Cmd; for command in self.base.commands.iter() { match command { @@ -1529,15 +1562,12 @@ impl RenderBundle { size, } => { let buffer = buffer.try_raw(snatch_guard)?; + let size = size.expect( + "Index buffer binding size should already be resolved when executing bundle", + ); // SAFETY: The binding size was checked against the buffer size // in `set_index_buffer` and again in `IndexState::flush`. - let bb = hal::BufferBinding::new_unchecked( - buffer, - *offset, - size.expect( - "Index buffer binding size should already be resolved when executing bundle", - ), - ); + let bb = hal::BufferBinding::new_unchecked(buffer, *offset, size); unsafe { raw.set_index_buffer(bb, *index_format) }; } Cmd::SetVertexBuffer { @@ -1547,15 +1577,12 @@ impl RenderBundle { size, } => { let buffer = buffer.as_ref().unwrap().try_raw(snatch_guard)?; + let size = size.expect( + "Vertex buffer binding size should already be resolved when executing bundle", + ); // SAFETY: The binding size was checked against the buffer size // in `set_vertex_buffer` and again in `VertexState::flush`. - let bb = hal::BufferBinding::new_unchecked( - buffer, - *offset, - size.expect( - "Vertex buffer binding size should already be resolved when executing bundle", - ), - ); + let bb = hal::BufferBinding::new_unchecked(buffer, *offset, size); unsafe { raw.set_vertex_buffer(*slot, bb) }; } Cmd::SetImmediate { offset, data } => { @@ -1643,17 +1670,31 @@ impl RenderBundle { } } Cmd::DrawIndirect { .. } | Cmd::MultiDrawIndirectCount { .. } => { - return Err(ExecutionError::Unimplemented("multi-draw-indirect")) + unreachable!("multi-draw commands are not supported in render bundles") } - Cmd::PushDebugGroup { .. } | Cmd::InsertDebugMarker { .. } | Cmd::PopDebugGroup => { - return Err(ExecutionError::Unimplemented("debug-markers")) + Cmd::PushDebugGroup { len, .. } | Cmd::InsertDebugMarker { len, .. } => { + let (label, rest) = strings.split_at(*len); + strings = rest; + if !self.discard_hal_labels { + let label = str::from_utf8(label).unwrap(); + if matches!(command, Cmd::PushDebugGroup { .. }) { + unsafe { raw.begin_debug_marker(label) }; + } else { + unsafe { raw.insert_debug_marker(label) }; + } + } + } + Cmd::PopDebugGroup => { + if !self.discard_hal_labels { + unsafe { raw.end_debug_marker() }; + } } Cmd::WriteTimestamp { .. } | Cmd::BeginOcclusionQuery { .. } | Cmd::EndOcclusionQuery | Cmd::BeginPipelineStatisticsQuery { .. } | Cmd::EndPipelineStatisticsQuery => { - return Err(ExecutionError::Unimplemented("queries")) + unreachable!("query commands are not supported in render bundles") } Cmd::ExecuteBundle(_) | Cmd::SetBlendConstant(_) @@ -1663,10 +1704,10 @@ impl RenderBundle { } } - if !self.discard_hal_labels { - if let Some(_) = self.base.label { - unsafe { raw.end_debug_marker() }; - } + debug_assert!(strings.is_empty()); + + if !self.discard_hal_labels && self.base.label.is_some() { + unsafe { raw.end_debug_marker() }; } Ok(()) @@ -1913,6 +1954,8 @@ impl State { /// Error encountered when finishing recording a render bundle. #[derive(Clone, Debug, Error)] pub enum RenderBundleErrorInner { + #[error(transparent)] + DebugGroup(#[from] DebugGroupError), #[error(transparent)] Create(#[from] CreateRenderBundleError), #[error(transparent)] @@ -1950,6 +1993,7 @@ pub struct RenderBundleError { impl WebGpuError for RenderBundleError { fn webgpu_error_type(&self) -> ErrorType { match self.inner.as_ref() { + RenderBundleErrorInner::DebugGroup(e) => e.webgpu_error_type(), RenderBundleErrorInner::Create(e) => e.webgpu_error_type(), RenderBundleErrorInner::Device(e) => e.webgpu_error_type(), RenderBundleErrorInner::RenderCommand(e) => e.webgpu_error_type(), diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index df8d24a88..223cd396c 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -3606,9 +3606,6 @@ fn execute_bundle( ExecutionError::InvalidResource(e) => { RenderPassErrorInner::RenderCommand(RenderCommandError::InvalidResource(e)) } - ExecutionError::Unimplemented(what) => { - RenderPassErrorInner::RenderCommand(RenderCommandError::Unimplemented(what)) - } })?; unsafe { diff --git a/wgpu/src/api/render_bundle_encoder.rs b/wgpu/src/api/render_bundle_encoder.rs index 6b95af931..df3e5e4e1 100644 --- a/wgpu/src/api/render_bundle_encoder.rs +++ b/wgpu/src/api/render_bundle_encoder.rs @@ -132,6 +132,23 @@ impl<'a> RenderBundleEncoder<'a> { } } + /// Inserts a debug marker into the recorded commands. + pub fn insert_debug_marker(&mut self, label: &str) { + self.inner.insert_debug_marker(label); + } + + /// Begins a debug group for the recorded commands. + /// + /// All debug groups must be popped before calling [`Self::finish`]. + pub fn push_debug_group(&mut self, label: &str) { + self.inner.push_debug_group(label); + } + + /// Ends the most recently pushed debug group. + pub fn pop_debug_group(&mut self) { + self.inner.pop_debug_group(); + } + /// Draws primitives from the active vertex buffer(s). /// /// The active vertex buffers can be set with [`RenderBundleEncoder::set_vertex_buffer`]. diff --git a/wgpu/src/backend/webgpu.rs b/wgpu/src/backend/webgpu.rs index 7140c3871..cc21806c6 100644 --- a/wgpu/src/backend/webgpu.rs +++ b/wgpu/src/backend/webgpu.rs @@ -4153,6 +4153,18 @@ impl dispatch::RenderBundleEncoderInterface for WebRenderBundleEncoder { panic!("IMMEDIATES feature must be enabled to call set_immediates") } + fn insert_debug_marker(&mut self, label: &str) { + self.inner.insert_debug_marker(label); + } + + fn push_debug_group(&mut self, group_label: &str) { + self.inner.push_debug_group(group_label); + } + + fn pop_debug_group(&mut self) { + self.inner.pop_debug_group(); + } + fn draw(&mut self, vertices: Range, instances: Range) { self.inner .draw_with_instance_count_and_first_vertex_and_first_instance( diff --git a/wgpu/src/backend/wgpu_core.rs b/wgpu/src/backend/wgpu_core.rs index deeb54ce9..8cbc9bfcd 100644 --- a/wgpu/src/backend/wgpu_core.rs +++ b/wgpu/src/backend/wgpu_core.rs @@ -2571,6 +2571,18 @@ impl dispatch::RenderBundleEncoderInterface for CoreRenderBundleEncoder { self.encoder.set_immediates(offset, data); } + fn insert_debug_marker(&mut self, label: &str) { + self.encoder.insert_debug_marker(label); + } + + fn push_debug_group(&mut self, group_label: &str) { + self.encoder.push_debug_group(group_label); + } + + fn pop_debug_group(&mut self) { + self.encoder.pop_debug_group(); + } + fn draw(&mut self, vertices: Range, instances: Range) { self.encoder.draw( vertices.end - vertices.start, diff --git a/wgpu/src/dispatch.rs b/wgpu/src/dispatch.rs index 4df30ec0e..17d1975ae 100644 --- a/wgpu/src/dispatch.rs +++ b/wgpu/src/dispatch.rs @@ -588,6 +588,10 @@ pub trait RenderBundleEncoderInterface: CommonTraits { ); fn set_immediates(&mut self, offset: u32, data: &[u8]); + fn insert_debug_marker(&mut self, label: &str); + fn push_debug_group(&mut self, group_label: &str); + fn pop_debug_group(&mut self); + fn draw(&mut self, vertices: Range, instances: Range); fn draw_indexed(&mut self, indices: Range, base_vertex: i32, instances: Range); fn draw_indirect(