diff --git a/Cargo.lock b/Cargo.lock index ac0aa8b8e..176f5b411 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4942,8 +4942,10 @@ dependencies = [ "wasm-bindgen-test", "web-sys", "wgpu", + "wgpu-core", "wgpu-hal", "wgpu-macros", + "wgpu-types", ] [[package]] diff --git a/docs/testing.md b/docs/testing.md index 2140e355f..5a1387d7d 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -40,6 +40,7 @@ This is a table of contents, in the form of the repository's directory structure - [compile](#wgpu-compile-tests) - [dependency](#wgpu-dependency-tests) - [gpu](#wgpu-gpu-tests) + - [trace](#wgpu-trace-tests) - [validation](#wgpu-validation-tests) And where applicable [unit-tests](#unit-tests) @@ -102,7 +103,7 @@ There are inputs in `wgsl`, `spirv`, and `glsl`. There are outputs for `hlsl`, `spirv`, `wgsl`, `msl`, `glsl`, and naga's internal IR. The tests can be configured by a sidecar toml file of the same name as the input file. -This is the goto tool for testing all kinds of codegen and parsing features. +This is the goto tool for testing all kinds of codegen and parsing features. To avoid clutter we generally use the following pattern: @@ -143,7 +144,7 @@ the [wgsl errors](#naga-wgsl-error-tests) tests. These are tests for the error messages that the `wgsl` frontend produces. Additionally you can check that a given validation error -is produced by the validator from a given `wgsl` snippet. +is produced by the validator from a given `wgsl` snippet. ## `player` Tests @@ -208,6 +209,15 @@ Normal `#[test]`s will not be found in this test crate, as we use a custom harne See also the [example tests](#example-tests) for additional GPU tests. +## `wgpu` Trace Tests + +- Located in: `tests/tests/wgpu_trace.rs` +- Run with `cargo nextest run --test wgpu_trace` +- Use the standard `#[test]` harness. + +These tests are focused on testing the tracing functionality in `wgpu`. They +use the a special `noop` backend which does not connect to a real GPU. + ## `wgpu` Validation Tests - Located in: `tests/tests/wgpu-validation` @@ -215,7 +225,7 @@ See also the [example tests](#example-tests) for additional GPU tests. - Use the standard `#[test]` harness. - `wgpu` integration tests, with access to `wgpu_test` helpers. -These tests are focused on testing the validation inside of `wgpu-core`. +These tests are focused on testing the validation inside of `wgpu-core`. They are written against the `wgpu` API, but are targeting a special `noop` backend which does not connect to a real GPU. diff --git a/tests/Cargo.toml b/tests/Cargo.toml index 0ae9e19b2..aeec237e3 100644 --- a/tests/Cargo.toml +++ b/tests/Cargo.toml @@ -23,6 +23,10 @@ harness = true name = "wgpu-gpu" harness = false +[[test]] +name = "wgpu_trace" +harness = true + [[test]] name = "wgpu-validation" harness = true @@ -39,8 +43,10 @@ test-build-with-profiling = ["profiling/type-check"] # `cargo clippy -- -Wunused-crate-dependencies` give fewer false positives. [dependencies] wgpu = { workspace = true, features = ["noop"] } +wgpu-core = { workspace = true, features = ["trace"] } wgpu-hal = { workspace = true, features = ["validation_canary"] } wgpu-macros.workspace = true +wgpu-types.workspace = true anyhow.workspace = true arrayvec.workspace = true diff --git a/tests/tests/wgpu_trace.rs b/tests/tests/wgpu_trace.rs new file mode 100644 index 000000000..0de163ab7 --- /dev/null +++ b/tests/tests/wgpu_trace.rs @@ -0,0 +1,189 @@ +//! Tests of [`wgpu::Buffer`] and related. + +use std::any::Any; + +use wgpu_core as wgc; +use wgpu_types as wgt; + +use wgc::{command::Command, device::trace::Action}; + +#[derive(Eq, PartialEq)] +enum TestType { + Normal, + FailedCommands, + FailedSubmit, +} + +fn trace_test(test_type: TestType) { + let global = wgc::global::Global::new( + "test", + wgt::instance::InstanceDescriptor { + backends: wgt::Backends::NOOP, + backend_options: wgt::BackendOptions { + noop: wgt::NoopBackendOptions { enable: true }, + ..Default::default() + }, + ..Default::default() + }, + None, + ); + let adapter_id = global + .request_adapter( + &wgt::RequestAdapterOptions::default(), + wgt::Backends::NOOP, + None, + ) + .unwrap(); + let (device_id, queue_id) = global + .adapter_request_device( + adapter_id, + &wgt::DeviceDescriptor { + trace: wgt::Trace::Memory, + ..Default::default() + }, + None, + None, + ) + .unwrap(); + + let (buffer_id, error) = global.device_create_buffer( + device_id, + &wgt::BufferDescriptor { + label: None, + size: 1024, + usage: wgt::BufferUsages::COPY_DST, + mapped_at_creation: false, + }, + None, + ); + assert!(error.is_none()); + + let (encoder_id, error) = global.device_create_command_encoder( + device_id, + &wgt::CommandEncoderDescriptor::default(), + None, + ); + assert!(error.is_none()); + + match test_type { + TestType::Normal => { + global + .command_encoder_clear_buffer(encoder_id, buffer_id, 0, None) + .unwrap(); + let (cmdbuf_id, error) = global.command_encoder_finish( + encoder_id, + &wgt::CommandBufferDescriptor::default(), + None, + ); + assert!(error.is_none()); + global.queue_submit(queue_id, &[cmdbuf_id]).unwrap(); + } + TestType::FailedCommands => { + // Try to clear past the end of the buffer. + global + .command_encoder_clear_buffer(encoder_id, buffer_id, 0, Some(2048)) + .unwrap(); + let (_cmdbuf_id, error) = global.command_encoder_finish( + encoder_id, + &wgt::CommandBufferDescriptor::default(), + None, + ); + assert!(error.is_some()); + } + TestType::FailedSubmit => { + // Destroy the buffer after encoding the clear command, before submitting it. + global + .command_encoder_clear_buffer(encoder_id, buffer_id, 0, None) + .unwrap(); + let (cmdbuf_id, error) = global.command_encoder_finish( + encoder_id, + &wgt::CommandBufferDescriptor::default(), + None, + ); + assert!(error.is_none()); + global.buffer_destroy(buffer_id); + global.queue_submit(queue_id, &[cmdbuf_id]).unwrap_err(); + } + } + + let trace = global.device_take_trace(device_id).unwrap(); + let trace = (trace.as_ref() as &dyn Any) + .downcast_ref::() + .unwrap(); + let actions = trace.actions(); + + match test_type { + TestType::Normal => { + let Some(Action::Submit(_, commands)) = actions.last() else { + panic!("expected last action to be Submit"); + }; + assert_eq!(commands.len(), 1); + assert!(matches!( + commands[0], + Command::ClearBuffer { + dst: _, + offset: 0, + size: None, + }, + )); + } + TestType::FailedCommands => { + let Some(Action::FailedCommands { + commands: Some(commands), + failed_at_submit: None, + error, + }) = actions.last() + else { + panic!("expected last action to be FailedCommands"); + }; + assert_eq!( + error, + "Clear of 0..2048 would end up overrunning the bounds of the buffer of size 1024" + ); + assert_eq!(commands.len(), 1); + assert!(matches!( + commands[0], + Command::ClearBuffer { + dst: _, + offset: 0, + size: Some(2048), + }, + )); + } + TestType::FailedSubmit => { + let Some(Action::FailedCommands { + commands: Some(commands), + failed_at_submit: Some(_), + error, + }) = actions.last() + else { + panic!("expected last action to be FailedCommands"); + }; + assert_eq!(error, "Buffer with '' label has been destroyed"); + assert_eq!(commands.len(), 1); + assert!(matches!( + commands[0], + Command::ClearBuffer { + dst: _, + offset: 0, + size: None, + }, + )); + } + } +} + +#[test] +fn trace_clear_buffer() { + trace_test(TestType::Normal); +} + +#[test] +fn trace_failed_commands() { + trace_test(TestType::FailedCommands); +} + +#[test] +fn trace_failed_submit() { + trace_test(TestType::FailedSubmit); +} diff --git a/wgpu-core/src/device/global.rs b/wgpu-core/src/device/global.rs index 0897778a9..fa8140c64 100644 --- a/wgpu-core/src/device/global.rs +++ b/wgpu-core/src/device/global.rs @@ -1993,6 +1993,15 @@ impl Global { device.generate_allocator_report() } + #[cfg(feature = "trace")] + pub fn device_take_trace( + &self, + device_id: DeviceId, + ) -> Option> { + let device = self.hub.devices.get(device_id); + device.take_trace() + } + pub fn queue_drop(&self, queue_id: QueueId) { profiling::scope!("Queue::drop"); api_log!("Queue::drop {queue_id:?}"); diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index e7bb2c2dc..9103a326c 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -642,6 +642,14 @@ impl Device { } } + /// Stop tracing and return the trace object. + /// + /// This is mostly useful for in-memory traces. + #[cfg(feature = "trace")] + pub fn take_trace(&self) -> Option> { + self.trace.lock().take() + } + /// Checks that we are operating within the memory budget reported by the native APIs. /// /// If we are not, the device gets invalidated. diff --git a/wgpu-core/src/device/trace/record.rs b/wgpu-core/src/device/trace/record.rs index a745cd7e0..923dfca83 100644 --- a/wgpu-core/src/device/trace/record.rs +++ b/wgpu-core/src/device/trace/record.rs @@ -1,5 +1,5 @@ use alloc::{borrow::Cow, string::ToString, sync::Arc, vec::Vec}; -use core::convert::Infallible; +use core::{any::Any, convert::Infallible}; use std::io::Write as _; use crate::{ @@ -39,7 +39,7 @@ pub(crate) fn new_render_bundle_encoder_descriptor( } } -pub trait Trace: Send + Sync { +pub trait Trace: Any + Send + Sync { fn make_binary(&mut self, kind: DataKind, data: &[u8]) -> Data; fn make_string(&mut self, kind: DataKind, data: &str) -> Data; @@ -831,6 +831,17 @@ impl IntoTrace for Option { fn action_to_owned(action: Action<'_, PointerReferences>) -> Action<'static, PointerReferences> { use Action as A; match action { + A::Init { desc, backend } => A::Init { + desc: wgt::DeviceDescriptor { + label: desc.label.map(|l| Cow::Owned(l.into_owned())), + required_features: desc.required_features, + required_limits: desc.required_limits, + experimental_features: desc.experimental_features, + memory_hints: desc.memory_hints, + trace: desc.trace, + }, + backend, + }, A::ConfigureSurface(surface, config) => A::ConfigureSurface(surface, config), A::CreateBuffer(buffer, desc) => A::CreateBuffer( buffer, @@ -896,8 +907,7 @@ fn action_to_owned(action: Action<'_, PointerReferences>) -> Action<'static, Poi A::DestroyBlas(blas) => A::DestroyBlas(blas), A::DestroyTlas(tlas) => A::DestroyTlas(tlas), - A::Init { .. } - | A::CreateTexture(..) + A::CreateTexture(..) | A::CreateTextureView { .. } | A::CreateExternalTexture { .. } | A::CreateSampler(..)