asset stuck in `RecursiveDependencyLoadState::Loading` forever if a dependency's last handle is dropped mid-load

Open
#26,355 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
1-2 days
Newbie friendliness
48/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
rust
Domain
backend

Research direction

Start with crates/bevy_asset/src/server/info.rs, especially process_handle_drop_internal around lines 758–805 and the waiter propagation paths around lines 481–512 and 628; the report includes a reproducer and a proposed fix. Check existing asset server tests for coverage of dropped dependencies during loading. Done means the reproducer reliably reaches a terminal state instead of remaining Loading, with the outcome and any relevant error covered by a regression test.

Written by the indexing model from the issue text.

Description

A-Assets C-Bug D-Async S-Ready-For-Implementation

Bevy version and features

0.19.1 and 0.20.0, default-features = false, features std, multi_threaded, async_executor, bevy_asset, bevy_image, png, bevy_log. same code in crates/bevy_asset/src/server/info.rs on main (6fa56de).

Relevant system information

linux (cachyos, kernel 7.2), ryzen 7 7800X3D, rustc 1.98.1, release, headless app.

What you did

loader registers a dependency with LoadContext::load and drops the handle (the asset doesn't hold it either), then wait with is_loaded_with_dependencies.

use bevy::asset::{io::Reader, AssetLoader, LoadContext};
use bevy::image::{CompressedImageFormats, ImageLoader};
use bevy::prelude::*;
use std::time::{Duration, Instant};

#[derive(Asset, TypePath)]
struct Bundle;

#[derive(TypePath, Default)]
struct BundleLoader;

impl AssetLoader for BundleLoader {
    type Asset = Bundle;
    type Settings = ();
    type Error = std::io::Error;
    async fn load(&self, _: &mut dyn Reader, _: &(), cx: &mut LoadContext<'_>) -> Result<Bundle, Self::Error> {
        // a.png becomes a dependency, handle not kept
        let _ = cx.load::<Image>("a.png");
        Ok(Bundle)
    }
    fn extensions(&self) -> &[&str] {
        &["bundle"]
    }
}

// 1x1 RGBA png
const PNG: &[u8] = &[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,6,0,0,0,31,21,196,
    137,0,0,0,13,73,68,65,84,120,156,99,248,207,192,240,31,0,5,0,1,255,137,153,61,29,0,0,0,0,73,69,78,68,174,66,96,130];

fn main() {
    let dir = std::env::temp_dir().join("bevy-dropped-dependency");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.png"), PNG).unwrap();
    std::fs::write(dir.join("x.bundle"), "").unwrap();

    let mut app = App::new();
    app.add_plugins((
        MinimalPlugins,
        AssetPlugin { file_path: dir.to_string_lossy().into(), ..default() },
        bevy::image::ImagePlugin::default(),
    ))
    .register_asset_loader(ImageLoader::new(CompressedImageFormats::empty()))
    .init_asset::<Bundle>()
    .register_asset_loader(BundleLoader);
    app.finish();
    app.cleanup();

    let server = app.world().resource::<AssetServer>().clone();
    let bundle: Handle<Bundle> = server.load("x.bundle");
    let start = Instant::now();
    while !server.is_loaded_with_dependencies(&bundle) {
        if start.elapsed() > Duration::from_secs(5) {
            println!("still waiting after 5 s: {:?}", server.get_load_states(&bundle));
            std::process::exit(1);
        }
        app.update();
    }
    println!("loaded with dependencies");
}

What went wrong

most runs print still waiting after 5 s: Some((Loaded, Loading, Loading)) and it never changes.

  • default pools: 33/40 stuck on 0.19.1, 21/40 on 0.20.0
  • 1 io thread: 32-39/40 on 0.19.1, 37/40 on 0.20.0
  • rest of the runs load fine, so same input, different result
  • no warning, no error, AssetEvent::LoadedWithDependencies never sent

expected the same result every run. either it loads (dependency got dropped so nothing to wait for) or it goes RecursiveDependencyLoadState::Failed with an error naming the dropped dependency. right now a loading screen just hangs.

gltf loader hits it too with a gltf whose textures no material uses (it drops those handles): 2-8/40 stuck on 4 io threads. with a material using both textures 0/320.

Additional information

what i think happens (lines on main 6fa56de):

  1. handle_internal_asset_events handles the bundle's Loaded. a.png is still Loading so the bundle goes into a.png's dependents_waiting_on_load / dependents_waiting_on_recursive_dep_load (info.rs L481-L512)
  2. Assets::<Image>::track_assets runs after that and handles the dropped a.png handle. process_handle_drop_internal removes the pending task and the whole AssetInfo incl. the waiter sets, tells nobody (info.rs L758-L805)
  3. waiters only get released by propagate_loaded_state / propagate_failed_state (L628) which never run for a.png now. loading a.png again later makes a new AssetInfo with no waiters, so still stuck

if a.png finishes before the drop gets handled it works, hence the random results.

other path: if the drop is handled before the parent's Loaded, process_asset_load logs "Dependency ... is unknown ..." (L519-L527) and the parent sticks the same way. never saw that warning in my runs so the stall above is steps 1-3.

possible fix: in process_handle_drop_internal, if the dropped info is still NotLoaded/Loading and has waiters, release them first (remove the id from each dependent's loading sets and recheck, or fail them via propagate_failed_state). cancel-on-drop came from #14808, #21878 is related (subasset lifetimes).

found this chasing a flaky test in our game (Elderwilds). the game itself isn't affected, every texture there is used by a material.

Dominant language
Rust
Stars
49.8k
Forks
5.1k
Avg merge
3d 4h
Merged PRs (30d)
136

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.