Mass entities initializing fragments on the incorrect archetypes due to shared CreationContext

I’m unsure if this was introduced in 5.6, as looks as if it could have happened back in 5.5, but we’re seeing a failure in FMassEntityManager::BatchSetEntityFragmentValues->FMassArchetypeData::SetFragmentData->FragmentIndexMap.FindChecked(FragmentType) when starting some levels. This is because in UMassSpawnerSubsystem::DoSpawning, the CreationContext grabbed from BatchCreateEntities->…->ObserverManager.GetOrMakeCreationContext gets a ActiveCreationContext that is shared across all PendingAgentEntities in UMassAgentSubsystem::HandlePendingInitialization. So the entity collections passed into BatchSetEntityFragmentValues from CreationContext->GetEntityCollections(*EntityManager.Get()) contains all of the entities created so far in the pending creation loop, even if those entities have very different archetypes. There is nothing seemingly gating the set of initial fragment data on entities that actually share the template/archetype of the entities being actively spawned and so it just tries to set it on all of the entities that have been spawned so far and fails the FindChecked call when it can’t find a fragment on one of those earlier spawned entities.

This seemingly should have been an issue in 5.5 because GetOrMakeCreationContext existed in FMassEntityManager back then and similarly used a shared CreationContext, so I haven’t quite found what saved it or if this was just a timing case we had not hit. Generally entities of the same archetype are spawned together and rarely do we have multiple in the same frame so perhaps that is why this has flown under the radar.

It does appear to also rerun RunProcessorsView for each entity accumulating on each spawn. I’m surprised this isn’t running BatchSetEntityFragmentValues/RunProcessorsView just over the SpawnedEntities here.

[mention removed]​ for vis

This change to HandlePendingInitialization was added in 5.6 to address an issue brought forward by another user. We had not seen this internally, and I believe this is the first post/report for the issue.

Do you have the callstack(s) for when this happens? Is it always coming from the same code path? The goal is to check that any and all code paths are corrected as needed. How often do you see this happening? Is it a 25% crash or higher? Not asking to downplay the issue but to get a better understanding for reproducing this.

-James

We also encountered the same problem. If two da objects are created in the same frame, it will be triggered, especially when not in the editor. Is there any solution?

We made a change that should work for this. It is part of 5.7. It is in CL 45139186 in the UE5 Main branch. If you are a GitHub user rather than p4, I can find the GitHub commit link if needed.

-James