Return SubmissionIndex only if submissions succeed (#10218)

This commit is contained in:
Teodor Tanasoaia authored and GitHub committed 2026-10-27 13:16:23 +00:00
1 parent 5dfcef2ade
commit a979c33dcd
11 files changed
+83 -45

No files matched your search

+2
View File
@@ -190,6 +190,8 @@ By @sagudev in [#10307](https://github.com/gfx-rs/wgpu/pull/10307).
- `request_adapter` will return error on `InstanceFlags::STRICT_WEBGPU_COMPLIANCE` if the adapter has already been consumed by a previous `request_device`. By @sagudev in [#10444](https://github.com/gfx-rs/wgpu/pull/10444).
- The variants of `wgpu_core::validation::StageError` related to entry point selection have been reorganized. By @jimblandy in [#10544](https://github.com/gfx-rs/wgpu/pull/10544).
- `clear_texture` now rejects a request to clear only some aspects of a texture. Previously such a request would clear all aspects of the texture. By @andyleiserson in [#10684](https://github.com/gfx-rs/wgpu/pull/10684).
- `Queue::submit` now returns `Option<SubmissionIndex>`, and returns `None` if the submission failed. A `None` result means the submission never reached the driver, so fences/events/semaphores attached to HAL queues will never be signalled. By @teoxoy in [#10218](https://github.com/gfx-rs/wgpu/pull/10218).
- `Device::poll` now always returns `PollError::CantWait` if called with `PollType::Wait` on the WebGPU backend. By @teoxoy in [#10218](https://github.com/gfx-rs/wgpu/pull/10218).
#### naga
@@ -355,7 +355,7 @@ impl QueueInterface for CustomQueue {
fn submit(
&self,
_command_buffers: &mut dyn Iterator<Item = wgpu::custom::DispatchCommandBuffer>,
) -> u64 {
) -> Option<u64> {
unimplemented!()
}
+37 -14
View File
@@ -251,7 +251,7 @@ static WAIT_ON_SUBMISSION: GpuTestConfiguration = GpuTestConfiguration::new()
let index = ctx.queue.submit(Some(cmd_buf));
ctx.async_poll(PollType::Wait {
submission_index: Some(index),
submission_index: index,
timeout: None,
})
.await
@@ -266,7 +266,7 @@ static WAIT_ON_SUBMISSION_WITH_TIMEOUT: GpuTestConfiguration = GpuTestConfigurat
let index = ctx.queue.submit(Some(cmd_buf));
ctx.async_poll(PollType::Wait {
submission_index: Some(index),
submission_index: index,
timeout: Some(Duration::from_secs(1)),
})
.await
@@ -281,7 +281,7 @@ static WAIT_ON_SUBMISSION_WITH_TIMEOUT_MAX: GpuTestConfiguration = GpuTestConfig
let index = ctx.queue.submit(Some(cmd_buf));
ctx.async_poll(PollType::Wait {
submission_index: Some(index),
submission_index: index,
timeout: Some(Duration::MAX),
})
.await
@@ -296,13 +296,13 @@ static DOUBLE_WAIT_ON_SUBMISSION: GpuTestConfiguration = GpuTestConfiguration::n
let index = ctx.queue.submit(Some(cmd_buf));
ctx.async_poll(PollType::Wait {
submission_index: Some(index.clone()),
submission_index: index.clone(),
timeout: None,
})
.await
.unwrap();
ctx.async_poll(PollType::Wait {
submission_index: Some(index),
submission_index: index,
timeout: None,
})
.await
@@ -319,13 +319,13 @@ static WAIT_OUT_OF_ORDER: GpuTestConfiguration = GpuTestConfiguration::new()
let index1 = ctx.queue.submit(Some(cmd_buf1));
let index2 = ctx.queue.submit(Some(cmd_buf2));
ctx.async_poll(PollType::Wait {
submission_index: Some(index2),
submission_index: index2,
timeout: None,
})
.await
.unwrap();
ctx.async_poll(PollType::Wait {
submission_index: Some(index1),
submission_index: index1,
timeout: None,
})
.await
@@ -383,10 +383,18 @@ async fn wait_after_bad_submission(ctx: TestingContext) {
/// > operation you have already presented to the device is going to store in
/// > `fence`.
///
/// `wgpu::Queue::submit` returns `None` for a failed submission, and
/// `wgpu::Device::poll` only accepts indices returned by successful
/// submissions, so the hole index cannot be used through the `wgpu` API. This
/// test therefore submits and polls through the underlying wgpu-core queue and
/// device, where a submission index is a plain `u64` we can construct
/// ourselves.
///
/// Regression test for <https://github.com/gfx-rs/wgpu/issues/9498>.
#[apply(gpu_test!)]
static WAIT_ON_FAILED_SUBMISSION: GpuTestConfiguration = GpuTestConfiguration::new()
.parameters(wgpu_test::TestParameters::default())
// Needs the wgpu-core backend.
.parameters(TestParameters::default().skip(FailureCase::backend(Backends::BROWSER_WEBGPU)))
.run_async(wait_on_failed_submission);
async fn wait_on_failed_submission(ctx: TestingContext) {
@@ -397,17 +405,21 @@ async fn wait_on_failed_submission(ctx: TestingContext) {
.await;
// 1. Successful empty submit. Advances `last_successful_submission_index`.
let _idx_before = queue2.submit([]);
let idx_before = queue2
.as_core()
.unwrap()
.submit(&[])
.expect("empty submission should succeed");
// 2. Failed submit (cross-device cmd buffer). Burns an index but does not
// advance `last_successful_submission_index`. Capture the returned
// index using an error scope so the validation error is not fatal.
// advance `last_successful_submission_index`. Use an error scope so the
// validation error is not fatal.
let command_buffer_wrong_device = ctx
.device
.create_command_encoder(&CommandEncoderDescriptor::default())
.finish();
let scope = device2.push_error_scope(wgpu::ErrorFilter::Validation);
let bad_index = queue2.submit([command_buffer_wrong_device]);
queue2.submit([command_buffer_wrong_device]);
let scope_error = scope.pop().await;
assert!(
scope_error.is_some(),
@@ -442,14 +454,25 @@ async fn wait_on_failed_submission(ctx: TestingContext) {
for _ in 0..16 {
encoder.copy_buffer_to_buffer(&src, 0, &dst, 0, Some(big_size));
}
let _idx_after = queue2.submit([encoder.finish()]);
// `wgpu` returns no index for the failed submission, so submit through
// wgpu-core to get the index right after it.
let idx_after = queue2
.as_core()
.unwrap()
.submit(&[encoder.finish().as_core().unwrap()])
.expect("submission should succeed");
// Each submission attempt consumes exactly one index, so the failed one
// sits between the two successful ones.
let bad_index = idx_after - 1;
assert!(idx_before < bad_index);
// 4. The interesting wait: pass the hole index to `poll(Wait)`. The
// wgpu-core guard sees `bad_index <= last_successful_submission_index`
// and lets it through to the HAL `wait`, which is being asked to wait
// on a fence value no operation actually presented. Must not panic or
// hang.
let result = device2.poll(wgpu::PollType::Wait {
let result = device2.as_core().unwrap().poll(wgpu_types::PollType::Wait {
submission_index: Some(bad_index),
timeout: Some(Duration::from_secs(5)),
});
+1 -1
View File
@@ -44,7 +44,7 @@ impl Global {
&self,
queue_id: QueueId,
command_buffer_ids: &[CommandBufferId],
) -> SubmissionIndex {
) -> Option<SubmissionIndex> {
let hub = self.hub.borrow();
let queue = hub.queues.get(queue_id);
let command_buffers = command_buffer_ids
+17 -19
View File
@@ -128,9 +128,7 @@ impl Queue {
texture: &Arc<Texture>,
) -> Result<(), DeviceError> {
let snatch_guard = self.device.snatchable_lock.read();
let submission = self
.allocate_submission(snatch_guard)
.map_err(|(_index, e)| e)?;
let submission = self.allocate_submission(snatch_guard)?;
let device = &self.device;
// If the texture is uninitialized it needs to be cleared before presenting
@@ -1565,9 +1563,7 @@ impl Queue {
buffer: &Arc<Buffer>,
snatch_guard: SnatchGuard,
) -> Result<(), BufferAccessError> {
let submission = self
.allocate_submission(snatch_guard)
.map_err(|(_index, e)| e)?;
let submission = self.allocate_submission(snatch_guard)?;
let pending_writes = self.pending_writes.lock();
if !pending_writes.contains_buffer(buffer) {
@@ -1581,9 +1577,7 @@ impl Queue {
fn flush_pending_writes(&self) -> Result<Option<SubmissionIndex>, DeviceError> {
let snatch_guard = self.device.snatchable_lock.read();
let submission = self
.allocate_submission(snatch_guard)
.map_err(|(_index, e)| e)?;
let submission = self.allocate_submission(snatch_guard)?;
let submit_index = submission.index;
let pending_writes = self.pending_writes.lock();
if pending_writes.is_recording {
@@ -1624,20 +1618,21 @@ impl Queue {
fn submit_inner(
&self,
command_buffers: &[Arc<CommandBuffer>],
) -> Result<SubmissionIndex, (SubmissionIndex, QueueSubmitError)> {
) -> Result<SubmissionIndex, Box<(Option<SubmissionIndex>, QueueSubmitError)>> {
profiling::scope!("Queue::submit");
api_log!("Queue::submit");
let snatch_guard = self.device.snatchable_lock.read();
let mut submission = self
.allocate_submission(snatch_guard)
.map_err(|(index, e)| (index, e.into()))?;
.map_err(|e| (None, e.into()))?;
let submit_index = submission.index;
// If we encounter an error after we have started updating global state and before
// successful submission, we must lose the device to avoid continuing with
// potentially inaccurate resource state.
let mut lose_device_on_error = false;
let mut successfully_submitted = false;
let res = 'error: {
let mut used_surface_textures = track::TextureUsageScope::default();
@@ -1844,6 +1839,7 @@ impl Queue {
Ok(result) => result,
Err(e) => break 'error Err(e.into()),
};
successfully_submitted = true;
profiling::scope!("cleanup");
@@ -1879,7 +1875,10 @@ impl Queue {
if lose_device_on_error {
self.device.lose("submission failed");
}
return Err((submit_index, e));
return Err(Box::new((
successfully_submitted.then_some(submit_index),
e,
)));
}
};
@@ -1893,10 +1892,11 @@ impl Queue {
Ok(submit_index)
}
pub fn submit(&self, command_buffers: &[Arc<CommandBuffer>]) -> SubmissionIndex {
pub fn submit(&self, command_buffers: &[Arc<CommandBuffer>]) -> Option<SubmissionIndex> {
match self.submit_inner(command_buffers) {
Ok(submit_index) => submit_index,
Err((submit_index, e)) => {
Ok(submit_index) => Some(submit_index),
Err(e) => {
let (submit_index, e) = *e;
self.device
.handle_error(e, Some(self.label()), "Queue::submit");
submit_index
@@ -1929,14 +1929,12 @@ impl Queue {
fn allocate_submission<'a>(
&'a self,
snatch_guard: SnatchGuard<'a>,
) -> Result<PendingSubmission<'a>, (SubmissionIndex, DeviceError)> {
) -> Result<PendingSubmission<'a>, DeviceError> {
let mut command_index_guard = self.device.command_indices.write();
command_index_guard.active_submission_index += 1;
let index = command_index_guard.active_submission_index;
if let Err(e) = self.device.check_is_valid() {
return Err((index, e));
}
self.device.check_is_valid()?;
let submission = PendingSubmission {
queue: self,
+5
View File
@@ -353,6 +353,8 @@ pub enum PollError {
Timeout,
/// The requested Wait was given a wrong submission index.
WrongSubmissionIndex(u64, u64),
/// The backend doesn't support synchronously waiting.
CantWait,
}
// This impl could be derived by `thiserror`, but by not doing so, we can reduce the number of
@@ -369,6 +371,9 @@ impl fmt::Display for PollError {
that has not been returned by a successful submission \
(last successful submission: {successful}"
),
PollError::CantWait => {
f.write_str("The backend doesn't support synchronously waiting.")
}
}
}
}
+1 -1
View File
@@ -105,7 +105,7 @@ impl Device {
/// receives it. `Queue`s can be shared between threads, so other threads
/// could submit new work at any time.)
///
/// When running on WebGPU, this is a no-op. `Device`s are automatically polled.
/// On the WebGPU backend, a call with [`PollType::Poll`] is a no-op since `Device`s are automatically polled. A call with [`PollType::Wait`] is not supported (always returns [`crate::PollError::CantWait`]).
pub fn poll(&self, poll_type: PollType) -> Result<crate::PollStatus, crate::PollError> {
self.inner.poll(poll_type.map_index(|s| s.index))
}
+4 -2
View File
@@ -277,10 +277,12 @@ impl Queue {
}
/// Submits a series of finished command buffers for execution.
///
/// Returns `Some` if the submission started and can be waited on via a `poll`, or `None` otherwise. On the WebGPU backend, it always returns `None` (even for successful submissions), because the WebGPU backend does not support waiting for a particular submission.
pub fn submit<I: IntoIterator<Item = CommandBuffer>>(
&self,
command_buffers: I,
) -> SubmissionIndex {
) -> Option<SubmissionIndex> {
// As submit drains the iterator (even on error), collect deferred actions
// from each CommandBuffer along the way.
let mut actions = DeferredCommandBufferActions::default();
@@ -294,7 +296,7 @@ impl Queue {
// Execute all deferred actions after submit.
actions.execute(&self.inner);
SubmissionIndex { index }
index.map(|index| SubmissionIndex { index })
}
/// Gets the amount of nanoseconds each tick of a timestamp query represents.
+10 -5
View File
@@ -2876,9 +2876,14 @@ impl dispatch::DeviceInterface for WebDevice {
// No capturing api in webgpu
}
fn poll(&self, _poll_type: wgt::PollType<u64>) -> Result<crate::PollStatus, crate::PollError> {
// Device is polled automatically
Ok(crate::PollStatus::QueueEmpty)
fn poll(&self, poll_type: wgt::PollType<u64>) -> Result<crate::PollStatus, crate::PollError> {
match poll_type {
wgt::PollType::Wait { .. } => Err(crate::PollError::CantWait),
wgt::PollType::Poll => {
// Device is polled automatically
Ok(crate::PollStatus::Poll)
}
}
}
fn get_internal_counters(&self) -> crate::InternalCounters {
@@ -3022,7 +3027,7 @@ impl dispatch::QueueInterface for WebQueue {
fn submit(
&self,
command_buffers: &mut dyn Iterator<Item = dispatch::DispatchCommandBuffer>,
) -> u64 {
) -> Option<u64> {
let temp_command_buffers = command_buffers.collect::<Vec<_>>();
let array = temp_command_buffers
@@ -3032,7 +3037,7 @@ impl dispatch::QueueInterface for WebQueue {
self.inner.submit(&array);
0
None
}
fn get_timestamp_period(&self) -> f32 {
+1 -1
View File
@@ -1748,7 +1748,7 @@ impl dispatch::QueueInterface for CoreQueue {
fn submit(
&self,
command_buffers: &mut dyn Iterator<Item = dispatch::DispatchCommandBuffer>,
) -> u64 {
) -> Option<u64> {
let temp_command_buffers = command_buffers.collect::<SmallVec<[_; 4]>>();
let command_buffers = temp_command_buffers
.iter()
+4 -1
View File
@@ -255,7 +255,10 @@ pub trait QueueInterface: CommonTraits {
);
/// Submit must always drain the iterator, even in the case of error.
fn submit(&self, command_buffers: &mut dyn Iterator<Item = DispatchCommandBuffer>) -> u64;
fn submit(
&self,
command_buffers: &mut dyn Iterator<Item = DispatchCommandBuffer>,
) -> Option<u64>;
fn get_timestamp_period(&self) -> f32;
fn on_submitted_work_done(&self, callback: BoxSubmittedWorkDoneCallback);