#10503·wgpu

Trace drops can precede deferred Submit / FailedCommands resource references (30.0.1)

Author: macklencCreated Sep 29, 2026Updated Sep 29, 2026

Description

wgpu-core 30.0.1 can produce traces that drop resources before their deferred command records reference them. Dropping an application handle after recording a command is legal. The live execution succeeds, but the trace contains CreateBindGroup(id), DropBindGroup(id), then Submit(... SetBindGroup(id) ...). Replay no longer has that resource; pointer reuse can also alias pending generations.

This concerns trace serialization, not explicit Buffer::destroy/Texture::destroy, and is distinct from #7870's validation timing.

Reproduction

At tag v30.0.1 (40f4a34ebaf56f9a046231f54125ad046239d3f3), save this as tests/tests/trace_lifetime.rs and run cargo test --locked -p wgpu-test --test trace_lifetime. It uses the NOOP backend, memory tracing and an empty compute pass, so no physical GPU is needed. The assertion fails on the tag.

rust
use std::{any::Any, borrow::Cow, fmt::Debug, hash::Hash};
use wgc::{
    command::{Command, ComputeCommand, PointerReferences},
    device::trace::{Action, MemoryTrace},
    id::{BindGroupId, BindGroupLayoutId, CommandBufferId, DeviceId, QueueId},
};
use wgpu_core as wgc;
use wgpu_types as wgt;

struct Capture {
    global: wgc::global::Global,
    device: DeviceId,
    queue: QueueId,
    layout: BindGroupLayoutId,
}

impl Capture {
    fn new() -> Self {
        Self::with_trace(wgt::Trace::Memory)
    }

    fn with_trace(trace: wgt::Trace) -> Self {
        let global = wgc::global::Global::new(
            "trace lifetimes",
            wgt::InstanceDescriptor {
                backends: wgt::Backends::NOOP,
                backend_options: wgt::BackendOptions {
                    noop: wgt::NoopBackendOptions::enabled(),
                    ..Default::default()
                },
                ..wgt::InstanceDescriptor::new_without_display_handle()
            },
            None,
        );
        let adapter = global
            .request_adapter(&Default::default(), wgt::Backends::NOOP, None)
            .unwrap();
        let (device, queue) = global
            .adapter_request_device(
                adapter,
                &wgt::DeviceDescriptor {
                    trace,
                    required_features: wgt::Features::TIMESTAMP_QUERY
                        | wgt::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS,
                    ..Default::default()
                },
                None,
                None,
            )
            .unwrap();
        let (layout, error) = global.device_create_bind_group_layout(
            device,
            &wgc::binding_model::BindGroupLayoutDescriptor {
                label: None,
                entries: Cow::Borrowed(&[]),
            },
            None,
        );
        assert!(error.is_none(), "{error:?}");
        Self {
            global,
            device,
            queue,
            layout,
        }
    }

    fn bind_group(&self) -> BindGroupId {
        let (group, error) = self.global.device_create_bind_group(
            self.device,
            &wgc::binding_model::BindGroupDescriptor {
                label: None,
                layout: self.layout,
                entries: Cow::Borrowed(&[]),
            },
            None,
        );
        assert!(error.is_none(), "{error:?}");
        group
    }

    fn commands(&self, drop_before_finish: bool) -> CommandBufferId {
        self.commands_for(self.bind_group(), drop_before_finish)
    }

    fn commands_for(
        &self,
        group: BindGroupId,
        drop_before_finish: bool,
    ) -> CommandBufferId {
        let encoder = self.record(group);
        if drop_before_finish {
            self.global.bind_group_drop(group);
        }
        let (commands, error) =
            self.global
                .command_encoder_finish(encoder, &Default::default(), None);
        assert!(error.is_none(), "{error:?}");
        if !drop_before_finish {
            self.global.bind_group_drop(group);
        }
        commands
    }

    fn record(&self, group: BindGroupId) -> wgc::id::CommandEncoderId {
        let (encoder, error) =
            self.global
                .device_create_command_encoder(self.device, &Default::default(), None);
        assert!(error.is_none(), "{error:?}");
        let (mut pass, error) = self.global.command_encoder_begin_compute_pass(
            encoder,
            &wgc::command::ComputePassDescriptor {
                label: None,
                timestamp_writes: None,
            },
        );
        assert!(error.is_none(), "{error:?}");
        self.global
            .compute_pass_set_bind_group(&mut pass, 0, Some(group), &[])
            .unwrap();
        // No dispatch: GPU usage tracking alone must not own trace references.
        self.global.compute_pass_end(&mut pass).unwrap();
        drop(pass);
        encoder
    }

    fn inspect(&self, inspect: impl FnOnce(&[Action<PointerReferences>])) {
        let trace = self.global.device_take_trace(self.device).unwrap();
        let trace = (trace.as_ref() as &dyn Any)
            .downcast_ref::<MemoryTrace>()
            .unwrap();
        inspect(trace.actions());
    }
}


#[test]
fn trace_drops_follow_deferred_submission() {
    let capture = Capture::new();
    let commands = capture.commands(true);
    capture.global.queue_submit(capture.queue, &[commands]).unwrap();
    capture.inspect(|actions| {
        let submit = actions.iter().position(|a| matches!(a, Action::Submit(..))).unwrap();
        let drop = actions.iter().position(|a| matches!(a, Action::DropBindGroup(..)));
        assert!(drop.is_none_or(|drop| drop > submit), "DropBindGroup precedes deferred Submit");
    });
}

Expected behavior / candidate correction

Resource trace identities should outlive every serialized consumer, including deferred Submit and FailedCommands. Moving public drop events to the final resource destructor fixes one boundary, but trace-only pointer commands also need to retain their resources until serialized or abandoned. Retaining ArcCommand values only when tracing is active addresses both boundaries in local 30.0.1 tests. Failed allocation/internal buffer paths need care so they do not emit unmatched drops.

Local regression controls cover drops before/after finish, pending generations, allocator reuse, abandonment, sampler ownership, buffers, query sets, views, bundles, recording invalidation, encoding failure and failed submission. Eleven lifetime assertions fail before the correction; the corrected integration tests pass with RUSTFLAGS="--cfg wgpu_validate_locks". Lock validation also exposed pre-existing submission/init-lock ordering problems, so simply moving the destructor calls without checking those paths is insufficient.

Current trunk inspection

At 44fe9431c34e6adbcff983675c99a5cfb173f119, BindGroup::drop already emits DropBindGroup, but command-buffer trace lists still use Vec<Command<PointerReferences>> in wgpu-core/src/command/mod.rs. This is a source inspection, not a claim that this 30.0.1 reproduction has been ported and run on trunk. Is there an existing upstream fix or issue covering the retained command references?