-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Remote entity reservation v4 #18380
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
ElliottjPierce
wants to merge
71
commits into
bevyengine:main
from
ElliottjPierce:remote-entity-reservation-v4
Closed
Remote entity reservation v4 #18380
ElliottjPierce
wants to merge
71
commits into
bevyengine:main
from
ElliottjPierce:remote-entity-reservation-v4
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
It's now just 2 atomic ops to refresh when we don't need to.
This will make it much easier to work with,
Reservations with &Entities now has the same potential to miss pending entities as with EntityReserver
AFAIK, not even the current implementation does this.
github-merge-queue bot
pushed a commit
that referenced
this pull request
Mar 18, 2025
# Objective The resources were converted via `clone_reflect_value` and the cloned value was mapped. But the value that is inserted is the source of the clone, which was not mapped. I ran into this issue while working on #18380. Having non consecutive entity allocations has caught a lot of bugs. ## Solution Use the cloned value for insertion if it exists.
mockersf
pushed a commit
that referenced
this pull request
Mar 18, 2025
# Objective The resources were converted via `clone_reflect_value` and the cloned value was mapped. But the value that is inserted is the source of the clone, which was not mapped. I ran into this issue while working on #18380. Having non consecutive entity allocations has caught a lot of bugs. ## Solution Use the cloned value for insertion if it exists.
This is a small but measurable improvement.
Closing in favor of v9: #18670 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Labels
A-ECS
Entities, components, systems, and events
C-Feature
A new feature, making something new possible
S-Needs-Review
Needs reviewer attention (from anyone!) to move forward
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
fixes #18003
Objective
Long story short: we need to be able to reserve entities from outside
&World
. This benefits both assets as entities and components as entities.This is an alternative to #18195 and #18266, v1 and v2 respectively. (If you're wondering where v3 went, it was some failed experimenting. I skipped the number to prevent my own confusion.)
Solution
Thanks to everyone who helped brainstorm on discord.
All entity meta is kept in a single unlocked
Vec<EntityMeta>
. We split pending entities into multiplePendingEntitiesChunk
s. One chunk is constantly pulled from while another is extended. When the pulling one is empty, we check if its worth swapping, and if so, the chunks shift, opening up more pending entities for reservation. We don't check for swapping every time; the frequency is user configurable. Checking to swap takes an additional 2 atomic operations when the swap is not needed, but can take over 10 atomic operations when it is needed (which is less than once per flush). When we don't check swapping or when we reserve directly on&Entities
(since that never needs to check for swapping) it now takes two atomic operations instead of one.When we allocate an entity directly, we pop from the new
owned: Vec<Entity>
, and if it's empty, we reserve some more entities in bulk. These entities are not flushed. The number of entities we reserve at once isideal_owned
and this is user configurable.To ensure we don't loose entities anywhere, flushing drains any
owned
entities beyond theideal_owned
amount into the pending chunk.It is possible for entity reservations to extend the
meta
vec instead of pulling from available pending entities. This happens, for example, when the pending entities are split between two chunks and we never check to swap chunks. In remote reservations, this behavior would be opt-in, and in&Entities
reservations, this is guaranteed to be fixed on the next flush after the current pending list is exhausted. If we do some thread_local magic, we could eliminate this issue for&Entities
, but that may introduce more overhead than it's worth.Small Fix
Entity::index
is a u32, but on main, the final index can never be reserved. This is becauseReserveEntitiesIterator::new_indices
was aRange<u32>
. Which doesn't include its end. So indexu32::MAX
could never be reserved. This is fixed in this PR, as it was a prerequisite fix that I discovered here. If we don't merge this, whatever solution we go with, I will make sure to follow up with a PR to fix this. (Or we can makeEntities::index
beNonMax<u32>
, freeing up another niche.)Not implemented
alloc_at
andalloc_at_without_replacement
are not supported in this PR. This was one of the pain points and limiting factors in my previous attempts, but since it is being removed anyway in 0.17 (#18148), I chose not to support it.Additionally, many of the various
len
methods were harder to implement since thePendingEntitiesChunks
can be scattered to the four winds via Arcs. As a result, they are much slower, but these are really a diagnostic tool anyway, so it's not that big of a performance problem.Practical Change
It used to be that a brand new
Entities
would yield sequential indices viaalloc
. This was never a guarantee, but many tests relied on this ordering. The ordering is still deterministic but is no longer sequential or aligned. In other words, if you allocate 5 entities. You might get back indices[0, 4, 2, 6, 7]
. Generally entities like this are opaque and this should not affect users. However, tests and benchmarks that depend on this previous, not guaranteed behavior had to be reworked.One practical effect this may have is that systems that run through
Entity
s sequentially, will have a different order. This may affect query orders, observer ordering, etc. None of these things were guarantees before, but this may expose some existing bugs in those systems.Future Work
Flushing is now completely unnecessary for many of the interactions with [
Entities
] (ex: free, alloc, etc). We still need to do it before applying command queues, etc, but we don't need to flush before allocations or freeing. If we go in this direction, we should explore relaxing those requirements for performance.Testing
Functionality hasn't changed, so no new tests were added. A few old tests were revised because of the practical changes.
However, it makes sense to add tests for remote registration, so if anyone has specific concerns, I'd be happy to write a test for it.
Showcase
Here's a tiny taste:
I would imagine, for example, the asset system hangs onto a
RemoteEntities
and passes out a&mut EntityReserver
as part of asset loading contexts. I'm no expert in that area, but hopefully that give you an idea.Costs
If we are going to keep the
meta
vec all together (which we need to), I think this is about as fast as we can get. We need the extra pointer indirection because, for this to work, we need theArc
at some point to keep things'static
. We need two atomic operations instead of the onecursor.fetch_sub(num)
because we can't do-cursor + meta.len()
withoutmeta
being in theArc
too (which would be either very slow since we'd need atomics for settingEntityLocation
, or a massive safety headache). I may be able to speed up some of the details here, but I don't think a faster design is logically possible at this point. If this is too slow, we should reconsider other designs besides remote reservation. (Maybe make everyAsset
beMapEntities
??). We're going to have to eat this performance cost somewhere.Benchmarks
These are from running:
on main vs here.
cargo bench --bench ecs -p benches -- --noplot --save-baseline remote_entities_v4_baseline
(I have other groups commented out.)I've filtered out benchmarks with less than 5% difference.
Interpretation
In general, most of these benchmarks fall somewhere between "ok-ish" to"uh-oh". But there's some good news.
The good news: This branch beats main (usually by 7-12%) on a little over a third of the benchmarks. Of course, it then looses to main by usually 10-15% on the other two thirds. That sounds about right to me. But then there are the "uh-oh" benchmarks that fall short of main by anywhere from 50% to 150%! Let's look at that.
First, I don't consider the sparse set benchmarks to be entirely correct here. The ordering of entities on main is mostly sequential, which plays to the sparse set's advantage but does not reflect realistic use. The same goes for tables but to a lesser extent. (Keep in mind that I'm not too familiar with these internals; this is my best understanding.)
But for the other "uh-oh" benchmarks, what's the problem? Let's look at the "sized_commands" and "fake_commands" benchmarks. On those benchmarks, this PR looses to main by roughly 80%. (Even though the commands do literally nothing.) So the performance problem is actually coming from
Entities::flush
. That makes sense; on this branch, there's a lot more work to do with flushing, including some atomics.That's not the only problem: 'alloc', 'free', 'reserve_entities', and 'reserve_entity' are all marginally more expensive here. That's why benchmarks like "despawn" are roughly 150% slower here (Keep in mind that a lot of that is also due to a
flush
call every despawn.) Also, 'alloc' and 'free' have to support doing so whenflush
hasn't happened, and 'alloc', 'reserve_entities', and 'reserve_entity' need to make sure they don't step on remote reservation's toes. This extra work in combination with the excessiveflush
calls is the problem.Solutions
First, we can ditch a ton of unneeded
flush
calls becausefree
andalloc
no longer need it. I only dropped one on this branch, it it caused a third of the benchmarks to beat main. It follows that by getting rid of these, we could improve performance a lot here.Second, we can create specialized
alloc
andfree
that requireflush
to have just been called. We can also add aalloc_batch
to speed things up too.Between those changes, I would guess we could get all the benchmarks within 5% of main (and many of them much faster).
But those changes will take time and reorganization. For example, hooks and observers for "despawn" will need to use the world's entities and
alloc
andfree
instead of commands. That saves another flush, but it's non-trivial and could be a breaking change. So, for now, I'd like some review and feedback on the idea before working on implementing these things.Is it worth it?
Honestly, I don't know if remote reservations are even worth it. Making every asset
MapEntities
might even end up being faster. I'd love a clear justification for why we need this specifically. Unless of course, we can cut out so manyflush
calls that this is faster thanmain
in enough places to be worth merging regardless of its impact on assets as entities and the like. I'll leave this up to SMEs to determine.