godot: [Regression] ResourceLoader.LoadThreadedRequest(scenePath) stuck at 0.5, infinite loop.

Tested versions

NOTReproducible in: v4.3 stable for Windows

Reprodcible in: v4.3 stable for MacOs v4.4.dev4.mono.official [36e6207bb] (Windows and MacOS)

For MacOS and Windows

System information

Godot v4.4.dev4.mono - Windows 10.0.19045 - Multi-window, 1 monitor - Vulkan (Forward+) - dedicated NVIDIA GeForce RTX 3060 Ti (NVIDIA; 32.0.15.6094) - AMD Ryzen 7 3700X 8-Core Processor (16 threads)

Issue description

When using

ResourceLoader.LoadThreadedRequest(scenePath);

This happened before and looks like its still happening: https://github.com/godotengine/godot/issues/92844#issuecomment-2167849384

NOTE: I’m calling the render server when loading TileSets, but I’m doing a RenderingServer.ForceSync();

I’m getting stuck at 0.5 progress and the progress never changes, maybe a recursive load? Or a race condition, I don’t know, my debugger points here:

image

Steps to reproduce

I’m loading the instance like this:

In MacOS it doesnt work at all it is always stuck (thats why we did the load in the same thread), on windows there is a race condition, so sometimes it works, sometime it doesnt.

public partial class Main2 : Node2D
{
    public override void _Ready()
    {
        // Construct the path to the scene file
        var scenePath = $"res://main.tscn";

        var error = ResourceLoader.LoadThreadedRequest(scenePath);
        GD.PrintErr($"Loading scene: {scenePath} {error}");
        var percentageReport = new Godot.Collections.Array();

        double percentage;
        ResourceLoader.ThreadLoadStatus loadingStatus;
        do
        {
            loadingStatus = ResourceLoader.LoadThreadedGetStatus(scenePath, percentageReport);
            if (loadingStatus == ResourceLoader.ThreadLoadStatus.Failed)
            {
                GD.PrintErr($"Failed to load scene at path: {scenePath}");
                return;
            }

            percentage = percentageReport[0].As<double>();
            GD.PrintErr($"Loading scene: loading: {loadingStatus} scene: {scenePath} percentage: {percentage} {percentageReport}");
            RenderingServer.ForceSync();
        } while (loadingStatus == ResourceLoader.ThreadLoadStatus.InProgress);

        GD.PrintErr($"Finished loading scene: {scenePath} {loadingStatus} {percentage}");
    }
}

Minimal reproduction project (MRP)

bug-thread.zip

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 16
  • Comments: 37 (15 by maintainers)

Most upvoted comments

I have given this issue some more thought and I have a theory on how to fix it, but unfortunately I’m not equipped to compile and test godot

From what I understand, as described on #99798, the source of this issue is the fact that, while loading a script and while the lock is acquired, dependencies might have to be loaded as well. If the loading is made from a worker thread, a new thread will be created and go through the same lock, and therefore the deadlock will happen as the previous thread already had locked it. Debugging on VS, this is exactly what I saw, it tries to load a class while loading a resource through ResourceLoader.LoadThreadedRequest, and then tries to load it’s base class, which it fails to due to the lock

The fix proposal above was to remove the godot_sharp_internal_script_load from the lock, which might have fixed the issue, but instead it was preferred to go with #99539, which keeps that call in the lock, but instead used an actual ReadWrite lock so that, in theory, the deadlock couldn’t happen anymore

The issue, however, is that the actual behavior of the lock remained exactly the same! All lock calls were replaced by ReaderWriterLockSlim.EnterUpgradeableReadLock and additional ReaderWriterLockSlim.EnterWriteLock calls were added. An UpgradeableReadLock can run in parallel with other ReadLocks, but not with other UpgradeableReadLocks, so despite all the apparent Read locking, there is never more than one thread reading at the same time. When godot_sharp_internal_script_load is called the thread is not under a write lock, but it is under an upgradeable lock, and so the new thread to load any dependencies gets stuck

Considering all that, my proposal would be to mix both solutions, keeping godot_sharp_internal_script_load inside a read lock but not in a upgradeable lock. According to the ReaderWriterLockSlim documentation, it is possible to downgrade a lock back to a normal ReadLock simply by calling ReaderWriterLockSlim.EnterReadLock. Releasing the lock is still be done with ReaderWriterLockSlim.ExitUpgradeableReadLock so ReaderWriterLockSlim.ExitReadLock is not required

I do not have enough knowledge of the ScriptManagerBridge class to know just where Read locks actually need to be upgradeable or not, but I am under the impression that godot_sharp_internal_script_load could be done in a Read only lock by downgrading it. Right after it, the code my either call GetOrCreateScriptBridgeForType or AddScriptBridgeCore, but each of these start by already acquiring a lock, so I’m led to believe that there won’t be a problem if another Upgradeable lock is acquired before those methods are actually executed. If this is a problem, then we might need to rethink if loading dependencies should actually create a new thread or not

I hope these findings help shed some light on how to fix this issue 😃

Godot v4.4.beta2.mono - the problem still occurs…

30% of times ResourceLoader.LoadThreadedRequest gets stuck at 50%

This should be a high priority issue, you literally cannot load the game in 30% of the times

On Linux everything works fine for me. On Android however, I start to run into some interesting things.

  1. When loading via ResourceLoader.LoadThreadedRequest(scenePath), it loads to 50% and then instantly switches to the other scene which is fascinating.
  2. When loading via ResourceLoader.LoadThreadedRequest(scenePath, useSubThreads: true); it loads to 75% before switching on 2 of our 3 scenes. On the 3rd scene, it hangs forever at 0%.

I have no idea if this is related, but I found the 50% thing interesting when loading linearly and the freeze with subthreads. I will have to put together a separate mrp so you guys can test. In summary:

ResourceLoader.LoadThreadedRequest(scenePath)

10% -> 23% -> 35% -> 50% -> switch scene

ResourceLoader.LoadThreadedRequest(scenePath, useSubThreads: true);

0% -> 75% -> switch scene

on all except 1 which hangs.

Tbh, the first one likely isn’t an issue. Its hard to know which assets will take longer to load than others, so a clean 0% -> 100% is hard to achieve. But the hang is definitely a bug.

Is there currently any consensus or anyone investigating the appropriate way to correctly fix this bug? I saw that 4.5 beta 1 was just released so I was wondering if there are any hopes of including this in the final 4.5 release

It’s just my personal opinion but I find this a pretty severe bug, it’s preventing me from doing any asynchronous resource loading which means freezing my game for a few frames every time I have to load something heavy. Were my project in a more advanced state, this bug would be enough to stop me from updating Godot until it was fixed

I see it’s in the 4.x Release Blockers project but it’s status is simply Bad, and there is an actual status for Release Blockers so it isn’t clear to me if I should expect a fix or not

I wish I could do more to help fix this. Thanks to everyone who is putting effort into this bug ^^

Issue still happens at random, with no clear reproduction steps. I’m trying to load a Node3D PackedScene using ResourceLoader.LoadThreadedRequest(scenePath). Progress is stuck at 0.5 while polling in a _Process method.

Godot v4.4.beta1.mono - Windows 10 (build 19045) - Single-window, 1 monitor - Vulkan (Forward+) - dedicated NVIDIA GeForce RTX 4070 (NVIDIA; 32.0.15.6094) - Intel® Core™ i7-14700K (28 threads)

@raulsntos After attempting it several times, I could no longer reproduce the bug with your build. I could reproduce it quite easily on 4.4.1 so I think #99798 solves it for me 😃

@RandomShaper, @akien-mga I still can reproduce it in 4.4dev7 even after #99539

Godot version: v4.4.dev7.mono.official [46c8f8c5c]

Godot v4.4.dev7.mono - Windows 10 (build 19045) - Multi-window, 1 monitor - Vulkan (Forward+) - dedicated NVIDIA GeForce RTX 3060 Ti (NVIDIA; 32.0.15.6094) - AMD Ryzen 7 3700X 8-Core Processor (16 threads)

I can also confirm that the fix from #99798 solved the problems for me.

I’m able to reproduce the issue in 4.4 stable (but less frequently than I expected). Update: Also able to reproduce in 4.4.1.stable.mono

I was having difficulty with the two links to the MRP above (and it was hard for me to tell what was going on - it would freeze or even crash the editor). I modified/improved it a bit to remove those distractions and now I can see the regression clearly when it happens.

bug-thread-improved.zip

Details (Including screenshots and MRP Change List)

Screenshot from when it is stuck: Image

Screenshot from when it completes loading normally: Image

Change List:

  • Main2.cs
    • Rewrote the script to use _Process (as recommended in the documentation).
    • Changed logging so that GD.PrintErr is only used for problems (GD.Print is used for normal debug info).
    • Changed logging so that messages only print once (as it was causing a message overflow issue in the original).
  • SomeComponent.tscn
    • Clicked “Access as Unique Name” on TextureProgressBar and Timer since the C# script was using GetNode<T>("%NodeName")

Godot v4.4.stable.mono - Windows 11 (build 22631) - Multi-window, 2 monitors - Vulkan (Forward+) - dedicated NVIDIA GeForce RTX 4060 (NVIDIA; 32.0.15.6094) - 13th Gen Intel® Core™ i5-13600K (20 threads)

I think all the packages you need should be in the Editor compressed archive, under the GodotSharp/Tools/nupkgs directory. Put them in a custom NuGet source feed or extract them to your NuGet packages directory (%userprofile%\.nuget\packages. in Windows).

@dougVanny Here you go:

Editor Templates
Windows x86_64 Windows x86_64

It’s a build from master at commit 4e6ac9bccc7868432b9d8a009d34860a2e6f3393 with https://github.com/godotengine/godot/pull/99798 rebased and included.

@TCROC These changes from #99798 fixed the issue for me

99798_changes.txt

Moving NativeFuncs.godotsharp_internal_reload_registered_script out of the lock in GetOrCreateScriptBridgeForType was enough to fix it for me. Moving NativeFuncs.godotsharp_internal_reload_registered_script out of the lock in GetOrLoadOrCreateScriptForType.GetPathOtherwiseGetOrCreateScript didn’t change anything on my end.

Godot v4.4.stable.mono - still happening in my project (Update: also Reproducible with the MRP - bug-thread-improved.zip). I agree that this should be a high priority issue.

Godot v4.4.stable.mono - Windows 11 (build 22631) - Multi-window, 2 monitors - Vulkan (Forward+) - dedicated NVIDIA GeForce RTX 4090 (NVIDIA; 32.0.15.6636) - Intel® Core™ i9-14900KF (32 threads)

Details and Code Example:

On my actual (proprietary) project (where I need to load a large scene via a button), I’m seeing the problem more of the time when not calling RenderingServer.ForceSync() at all: 60% of the time ResourceLoader.LoadThreadedRequest is getting stuck at 50% (Stuck: 30 times, Completed Normally: 20 times).

When calling RenderingServer.ForceSync() immediately after each call to ResourceLoader.LoadThreadedGetStatus(), it appears that my odds improve significantly: 12% of the time ResourceLoader.LoadThreadedRequest is getting stuck at 50% (Stuck: 6 times, Completed Normally: 44 times).

Edit: I think the difference in odds of getting stuck was just a fluke. If I run tests in one time frame, I might have more or less luck than another time frame. I’m not confident that RenderingServer.ForceSync() is actually helping lower the frequency of the issue.

using Godot;

public partial class Main : Node3D
{
    private const string resourcePath = "res://MyLargeScene.tscn";
    private bool isLoading;
    private bool isLoadingStuckMessageLogged;
    private float maxProgress;
    private DateTime startTime;
    private ResourceLoader.ThreadLoadStatus threadLoadStatus = ResourceLoader.ThreadLoadStatus.Failed;

    [Export] Button LoadButton { get; set; }
    [Export] Node3D TargetParent  { get; set; }

    private override void _Ready()
    {
        LoadButton.Pressed += HandleLoadButtonPressed;
    }

    private override void _ExitTree()
    {
        LoadButton.Pressed -= HandleLoadButtonPressed;
    }
    
    private void HandleLoadButtonPressed()
    {
        if (isLoading)
        {
            return;
        }

        startTime = DateTime.UtcNow;

        isLoading = true;
        GD.Print("Loading: Started");
        
        var godotError = ResourceLoader.LoadThreadedRequest(resourcePath);
        if (godotError != Error.Ok)
        {
            // I have only seen Godot.Error.Ok during testing.
            isLoading = false;
            GD.Print($"ResourceLoader.LoadThreadedRequest returned Godot Error: {godotError}");
        }
    }
    
    public override void _Process(double delta)
    {
        if (!isLoading)
        {
            return;
        }
    
        Godot.Collections.Array currentProgressArray = [];
        var currentThreadLoadStatus = ResourceLoader.LoadThreadedGetStatus(resourcePath, currentProgressArray);
        RenderingServer.ForceSync(); // Decreases the odds of ResourceLoader getting stuck in my testing.
        var currentProgress = currentProgressArray[0].AsSingle();
    
        if (currentProgress > maxProgress)
        {
            maxProgress = currentProgress;
            GD.Print($"Loading: {currentProgress * 100}%");
        }
    
        if (currentThreadLoadStatus != threadLoadStatus)
        {
            threadLoadStatus = currentThreadLoadStatus;
            GD.Print($"Loading: ResourceLoader.ThreadLoadStatus {threadLoadStatus}");
    
            if (threadLoadStatus == ResourceLoader.ThreadLoadStatus.Loaded)
            {
                Complete();
            }
        }

        var realTimeElapsed = DateTime.UtcNow - startTime;
        if (realTimeElapsed.TotalSeconds > 3.0f && !isLoadingStuckMessageLogged)
        {
            GD.Print("Loading: Incomplete after 3s, ResourceLoader may have gotten stuck. Please restart. See https://github.com/godotengine/godot/issues/99128 for details on the issue.");
            isLoadingStuckMessageLogged = true;
        }
    }
    
    private void Complete()
    {
        var resource = ResourceLoader.LoadThreadedGet(resourcePath);
        var packedScene = resource as PackedScene;
        var node = packedScene?.Instantiate() ?? null;
        isLoading = false;
    
        if (node is null)
        {
            GD.Print("Loading: Failed");
        }
        else
        {
            GD.Print("Loading: Completed");
            TargetParent.AddChild(node);
        }
    }
}

@raulsntos, I can confirm that using your custom Windows build for #99798 fixes the issue for me in my (very easy to test) MRP bug-thread-improved.zip. I tried running it hundreds of times and it never got stuck! In contrast, it only took ~20 times or less for me to reproduce it again today on 4.4.0 and 4.4.1.

Hey folks, just caught up with the discussion here. @raulsntos reached out to me to reopen that PR 👍.

Thanks for testing!

@raulstnos I have not tested it yet. We’ve recently started testing game with our users so we’ve been prioritizing the bugs introduced by us in our game logic itself. But we are due for an engine update so I’ll include that PR in our next built here soon for a test

If the closed PR (https://github.com/godotengine/godot/pull/99798) fixes the issue you all are getting and doesn’t introduce other issues, then we can reopen it and merge it. It was closed because we didn’t have enough confidence it wouldn’t introduce other bugs, and it initially seemed the alternative PR would fix this bug too.

@TCROC Did you end up testing https://github.com/godotengine/godot/pull/99798? If so, did that PR fix the issue for you?

@dougVanny You said you are unable to compile Godot, would you be willing to test a custom build that includes https://github.com/godotengine/godot/pull/99798? If so, what platform does the editor need to target? And if you need to test this in an exported game, what platforms do the templates need to target?

In general, the more people test and confirm that https://github.com/godotengine/godot/pull/99798 fixes the issue without introducing other issues, the more confident we’ll be to merge the PR. I’m currently unable to reproduce this issue, so testing and reviews from other users and contributors is much appreciated.

Thank you for the clarification! I’ll be curious to test out these PRs. I have this issue as well and as a result, just don’t use LoadThreadedRequest with multiple threads. Just a single background thread.