fix(core): Implement render bundle debug commands (#10308)

This commit is contained in:
Jinlei Li authored and GitHub committed 2026-09-18 12:55:21 +00:00
1 parent 81e38d86f4
commit 8630a774af
10 files changed
+311 -44

No files matched your search

+11
View File
@@ -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
+1 -2
View File
@@ -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:*
+1
View File
@@ -12,5 +12,6 @@ mod immediates;
mod instance;
mod mesh_shader;
mod ray_tracing_pipeline;
mod render_bundle;
mod render_pipeline;
mod texture;
@@ -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, &params);
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, "-")));
}
+83 -39
View File
@@ -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<InvalidOrDestroyedResourceError> 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(),
-3
View File
@@ -3606,9 +3606,6 @@ fn execute_bundle(
ExecutionError::InvalidResource(e) => {
RenderPassErrorInner::RenderCommand(RenderCommandError::InvalidResource(e))
}
ExecutionError::Unimplemented(what) => {
RenderPassErrorInner::RenderCommand(RenderCommandError::Unimplemented(what))
}
})?;
unsafe {
+17
View File
@@ -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`].
+12
View File
@@ -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<u32>, instances: Range<u32>) {
self.inner
.draw_with_instance_count_and_first_vertex_and_first_instance(
+12
View File
@@ -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<u32>, instances: Range<u32>) {
self.encoder.draw(
vertices.end - vertices.start,
+4
View File
@@ -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<u32>, instances: Range<u32>);
fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>);
fn draw_indirect(