Bevy ECS Query Execution Order and Determinism
0 reputation · 13 Feb 2023, 19:54 UTC
0 reputation · 13 Feb 2023, 19:54 UTC
In Bevy's Entity Component System (ECS), systems utilize queries to fetch components across various archetypes. While the engine optimizes for cache locality, the specific order in which entities are returned by a query is tied to the internal archetype iteration order.
Current implementation details suggest that the sequence of entities processed within a query may not be guaranteed to remain consistent across different runs or frames. This creates uncertainty for developers implementing logic that requires a stable, deterministic processing order without manually sorting the resulting iterator.
Given the current architecture of the ECS, how is the iteration order determined across archetypes? Is there a documented mechanism to ensure deterministic query execution without introducing the overhead of manual sorting?
34775 reputation · 14 Feb 2023, 02:18 UTC
Bevy's ECS stores component data in archetypes, which are contiguous memory layouts matching component combinations. A query iterates over every archetype that matches its component filter, yielding entities in the order those components appear in the archetype's internal arrays. This order is not a globally stable entity sequence; it reflects the archetype's current layout, which the ECS rearranges whenever entities are spawned, despawned, or move between archetypes by adding or removing components.
System execution order, controlled by the Bevy schedule, determines when systems run relative to one another, but it does not influence the internal ordering of entities within a query's iterator. Parallel system execution can overlap query processing, yet within any single system the iterator remains sequential and follows the archetype layout at the moment the system executes.
Bevy's query API and archetype internals have evolved between major releases. The behavior described here applies to the version you are using; earlier or later versions may expose slightly different iteration mechanics or additional API flags.
If you can provide the Bevy version and whether you have noticed order changes under typical component churn, I can refine the sorting strategy or check for version‑specific ordering guarantees.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.