Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(ecs): a slot handed back an id it had already issued

esenginef5208e645f8b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5fe63bca7..9c5c4c241 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -64,6 +64,20 @@ published separately; it ships inside the editor.
### Fixed
+- **A destroyed entity's handle could come back as a live one.** An `Entity` is a
+ 22-bit slot index plus a 10-bit generation, and recycling a slot bumped the
+ generation with a wrap: after 1023 reuses the counter returned to 1 and the slot
+ issued an id byte-for-byte identical to one it had already handed out. Anything
+ still holding the old handle then pointed at a different entity, and `valid()`
+ agreed. 1023 sounds distant and is not — an entity rebuilt every frame gets
+ there in under a second, a pool of a hundred bullets at 60fps in about a minute.
+ A slot on its last generation is now retired rather than recycled, so a handle
+ is unique for the life of the registry. The `Entity` layout is unchanged: still
+ 4 bytes, still a plain JS number, still fits box2d's 32-bit user data. What it
+ costs is index space, spent only by the churn that would otherwise alias, and
+ `Registry::retiredSlots()` reports it. Running the index space out now says so
+ in the log instead of quietly returning an invalid entity.
+
- **Exporting a project could ship files from outside it.** The IPC door already
refused a path that left the project through a link, but the asset scanner and
the cook never went through that door. A file named like content with a `.meta`
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index 300e97e2c..5bceda58d 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -181,7 +181,15 @@ public:
component_masks_[idx].reset();
--entity_count_;
- recycled_.push(idx);
+ // A slot on its last generation is RETIRED, not recycled: reusing it wraps
+ // the counter to 1 and mints an id this slot already issued, which a caller
+ // may hold and valid() would confirm. Costs index space, only where it aliases.
+ if (generations_[idx] < Entity::GEN_MASK) {
+ recycled_.push(idx);
+ } else {
+ ++retired_slots_;
+ ES_LOG_TRACE("Retired entity slot {} (generation exhausted)", idx);
+ }
ES_LOG_TRACE("Destroyed entity raw={} (index={})", entity.raw, idx);
}
@@ -216,6 +224,15 @@ public:
return entity_count_;
}
+ /**
+ * @brief Slots permanently out of circulation, their generation spent.
+ *
+ * Zero for anything but sustained create/destroy on the same indices. Rising
+ * steadily is the signal that churn is eating index space — the price paid so
+ * a destroyed entity's handle can never come back as a live one.
+ */
+ u32 retiredSlots() const { return retired_slots_; }
+
/**
* @brief Executes a function for each valid entity
* @tparam Func The callback type
@@ -450,6 +467,7 @@ public:
while (!recycled_.empty()) recycled_.pop();
next_index_ = 0;
entity_count_ = 0;
+ retired_slots_ = 0;
}
/**
@@ -637,11 +655,18 @@ private:
* @brief Activates an entity index: resizes arrays, bumps generation, returns packed Entity
*/
Entity activateIndex(u32 index) {
- // Release-safe: an index beyond the 20-bit range would silently alias an
+ // Release-safe: an index past the index field would silently alias an
// existing slot via Entity::make's mask (ES_ASSERT is stripped in
// release). Refuse before any state mutation. restore() passes a
- // deserialized index here, so this also guards scene loading.
- ES_VERIFY(index <= Entity::INDEX_MASK, return INVALID_ENTITY);
+ // deserialized index here, so this also guards scene loading. Say it out
+ // loud: running out is a state someone has to be able to see, and slot
+ // retirement below spends this space to buy handle uniqueness.
+ if (index > Entity::INDEX_MASK) {
+ ES_LOG_ERROR("Registry: entity index space exhausted ({} slots, {} retired to "
+ "generation wrap); create() returns an invalid entity from here on",
+ static_cast<u32>(Entity::INDEX_MASK) + 1u, retired_slots_);
+ return INVALID_ENTITY;
+ }
if (index >= entityValid_.size()) {
entityValid_.resize(index + 1, false);
generations_.resize(index + 1, 0);
@@ -663,6 +688,10 @@ private:
std::vector<u32> generations_;
std::vector<ComponentMask> component_masks_;
std::queue<u32> recycled_; ///< Recycled entity indices
+ /// Slots taken out of circulation because their generation ran out. Counted
+ /// rather than stored: nothing may hand them out again, so the only use for
+ /// them is telling an operator that churn is consuming index space.
+ u32 retired_slots_ = 0;
u32 next_index_ = 0; ///< Next fresh entity index
usize entity_count_ = 0;
diff --git a/tests/ecs/test_registry.cpp b/tests/ecs/test_registry.cpp
index f4d223ec4..0e6200463 100644
--- a/tests/ecs/test_registry.cpp
+++ b/tests/ecs/test_registry.cpp
@@ -3,6 +3,7 @@
#include <esengine/ESEngine.hpp>
#include <esengine/ecs/TransformSystem.hpp>
+#include <unordered_set>
#include <vector>
namespace test {
@@ -634,3 +635,78 @@ TEST_CASE("applySceneEntityOrder keeps unlisted children after the listed ones")
CHECK_EQ(registry.get<esengine::ecs::Children>(parent).entities,
std::vector<esengine::Entity>{c, a, b});
}
+
+// ─── Slot retirement ─────────────────────────────────────────────────────────
+// The generation field is 10 bits, so recycling a slot past its last one mints an
+// id it already issued. Retired instead — and 1023 reuses is not far away.
+
+TEST_CASE("a slot is never handed back with an id it already issued") {
+ esengine::ecs::Registry registry;
+ std::unordered_set<esengine::u32> seen;
+
+ // Far past one slot's generation supply, so a wrapping registry must collide.
+ for (int i = 0; i < 5000; ++i) {
+ esengine::Entity e = registry.create();
+ REQUIRE(e != esengine::INVALID_ENTITY);
+ CHECK(seen.insert(e.raw).second);
+ registry.destroy(e);
+ }
+}
+
+TEST_CASE("retirement spends an index only when a generation runs out") {
+ esengine::ecs::Registry registry;
+ CHECK_EQ(registry.retiredSlots(), 0u);
+
+ // One slot, churned to exhaustion: generations 1..GEN_MASK, then retired.
+ const esengine::u32 supply = esengine::Entity::GEN_MASK;
+ for (esengine::u32 i = 0; i < supply; ++i) {
+ registry.destroy(registry.create());
+ }
+ CHECK_EQ(registry.retiredSlots(), 1u);
+
+ // The next entity cannot be that slot.
+ esengine::Entity fresh = registry.create();
+ CHECK_EQ(fresh.index(), 1u);
+ CHECK_EQ(fresh.generation(), 1u);
+}
+
+TEST_CASE("ordinary reuse still recycles the same slot") {
+ esengine::ecs::Registry registry;
+ esengine::Entity a = registry.create();
+ registry.destroy(a);
+ esengine::Entity b = registry.create();
+
+ CHECK_EQ(b.index(), a.index()); // same slot
+ CHECK_NE(b.raw, a.raw); // different handle
+ CHECK_EQ(registry.retiredSlots(), 0u);
+}
+
+TEST_CASE("a retired slot's old handle stays invalid forever") {
+ esengine::ecs::Registry registry;
+ esengine::Entity first = registry.create();
+ const esengine::Entity stale = first;
+ registry.destroy(first);
+
+ for (esengine::u32 i = 1; i < esengine::Entity::GEN_MASK; ++i) {
+ registry.destroy(registry.create());
+ }
+ // The slot is spent. Nothing after this may make `stale` valid again.
+ for (int i = 0; i < 64; ++i) {
+ esengine::Entity e = registry.create();
+ CHECK_NE(e.raw, stale.raw);
+ }
+ CHECK_FALSE(registry.valid(stale));
+}
+
+TEST_CASE("clear returns the retirement count to zero") {
+ esengine::ecs::Registry registry;
+ for (esengine::u32 i = 0; i < esengine::Entity::GEN_MASK; ++i) {
+ registry.destroy(registry.create());
+ }
+ REQUIRE(registry.retiredSlots() == 1u);
+
+ registry.clear();
+ CHECK_EQ(registry.retiredSlots(), 0u);
+ esengine::Entity e = registry.create();
+ CHECK_EQ(e.index(), 0u);
+}