Shutdown crash during GPU pipeline compilation

Open
#26,632 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 2 days

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
22/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
rust

Research direction

The race is in crates/bevy_render/src/render_resource/pipeline_cache.rs, where PipelineCache can be dropped while a pipeline compilation task is still running. Start by reading how CachedPipelineState::Creating tasks are created and dropped, and run the reproduction several times to confirm the SIGSEGV. Done means shutdown after AppExit::Success no longer crashes across repeated runs, without leaving tasks running or hanging on exit.

Written by the indexing model from the issue text.

Description

C-Bug S-Needs-Triage

On stock Bevy 0.20.1, shutdown can segfault after it sends AppExit::Success. Tracing with GDB caught the fault on an async compute worker inside Vulkan pipeline creation. Not a huge issue for end users, but really messes with our test suite and can make some shutdowns extremely slow (due to coredump).

This is on Linux with Bevy 0.20.1, wgpu 30.0.1, an RTX 3080 Ti, and NVIDIA driver 620.73.04.

The smallest reproduction I could come up with. Since it's a race, you may have to run it several times to reproduce. On my system it occurs roughly 2 out of every 3 runs.

use bevy::{core_pipeline::tonemapping::Tonemapping, prelude::*};

fn main() -> AppExit {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, close)
        .run()
}

fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    commands.spawn((
        Mesh3d(meshes.add(Cuboid::default())),
        MeshMaterial3d(materials.add(Color::WHITE)),
    ));
    commands.spawn((PointLight::default(), Transform::from_xyz(2., 3., 2.)));
    commands.spawn((
        Camera3d::default(),
        Tonemapping::None,
        Transform::from_xyz(2., 2., 3.).looking_at(Vec3::ZERO, Vec3::Y),
    ));
}

fn close(mut frames: Local<u32>, mut exit: MessageWriter<AppExit>) {
    *frames += 1;
    if *frames == 8 {
        eprintln!("Requesting AppExit");
        exit.write(AppExit::Success);
    }
}

Which segfaults:

Thread 8 "Async Compute T" received signal SIGSEGV, Segmentation fault.
#0  ... from /usr/lib/libnvidia-glcore.so.620.73.04
#7  ... in <ash::device::Device>::create_compute_pipelines ()

Looking into it, it appears PipelineCache can finish dropping while a compilation task is still running. As a quick-fix I tried tracking the in-flight pipeline compilation tasks, including those superseded by shader reloads, and waiting for them to stop before dropping the pipeline cache, which worked. I'm not familiar enough with Bevy's internals to judge the side-effects.

diff --git a/crates/bevy_render/src/render_resource/pipeline_cache.rs b/crates/bevy_render/src/render_resource/pipeline_cache.rs
index b6614fa..1f46568 100644
--- a/crates/bevy_render/src/render_resource/pipeline_cache.rs
+++ b/crates/bevy_render/src/render_resource/pipeline_cache.rs
@@ -59,2 +59,8 @@ pub enum CachedPipelineState {
 impl CachedPipelineState {
+    fn requeue(&mut self, pending: &mut Vec<Task<Result<Pipeline, ShaderCacheError>>>) {
+        if let Self::Creating(task) = mem::replace(self, Self::Queued) {
+            pending.push(task);
+        }
+    }
+
     /// Convenience method to "unwrap" a pipeline state into its underlying GPU object.
@@ -224,2 +230,3 @@ pub struct PipelineCache {
     pipelines: Vec<CachedPipeline>,
+    superseded_tasks: Vec<Task<Result<Pipeline, ShaderCacheError>>>,
     waiting_pipelines: HashSet<CachedPipelineId>,
@@ -234,2 +241,13 @@ pub struct PipelineCache {
 
+impl Drop for PipelineCache {
+    fn drop(&mut self) {
+        for pipeline in &mut self.pipelines {
+            pipeline.state.requeue(&mut self.superseded_tasks);
+        }
+        for task in self.superseded_tasks.drain(..) {
+            let _ = bevy_tasks::block_on(task.cancel());
+        }
+    }
+}
+
 impl PipelineCache {
@@ -283,2 +301,3 @@ impl PipelineCache {
             pipelines: default(),
+            superseded_tasks: default(),
             global_shader_defs,
@@ -520,3 +539,5 @@ impl PipelineCache {
         for cached_pipeline in pipelines_to_queue {
-            self.pipelines[cached_pipeline].state = CachedPipelineState::Queued;
+            self.pipelines[cached_pipeline]
+                .state
+                .requeue(&mut self.superseded_tasks);
             self.waiting_pipelines.insert(cached_pipeline);
@@ -530,3 +551,5 @@ impl PipelineCache {
         for cached_pipeline in pipelines_to_queue {
-            self.pipelines[cached_pipeline].state = CachedPipelineState::Queued;
+            self.pipelines[cached_pipeline]
+                .state
+                .requeue(&mut self.superseded_tasks);
             self.waiting_pipelines.insert(cached_pipeline);
@@ -863,2 +886,3 @@ impl PipelineCache {
     pub fn process_queue(&mut self) {
+        self.superseded_tasks.retain(|task| !task.is_finished());
         let mut waiting_pipelines = mem::take(&mut self.waiting_pipelines);
Dominant language
Rust
Stars
50k
Forks
5.1k
Avg merge
2d 20h
Merged PRs (30d)
129

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from bevyengine/bevy

All issues in bevyengine/bevy

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.