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): onDestroy subscribers survive either teardown order (RC12 B1, revived)

esengine8a6ea5038b7c
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index a633c7eb4..5a63eca25 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -32,6 +32,7 @@ jobs:
CPP_TESTS: >-
test_ecs test_events test_particle test_tilemap test_sparse_set
test_resource_pool test_shader_variant test_log_format test_registry_safety
+ test_registry_ondestroy
test_shader_device test_draw_params test_texture_fb test_buffer_device
test_compressed_format test_batch_builder test_boundary_span test_webgpu_device
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7925e5418..ffc94fb3f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -163,6 +163,14 @@ to.
reach the engine optional-chained it away and their engine branches never ran under test. They
passed, silently testing less than they read as testing.
+- **A torn-down system no longer leaves a dangling callback in the registry — in
+ either direction.** Entity-destroy subscriptions are RAII now, end to end: the
+ subscriber's Connection removes the callback when the subscriber dies, and the
+ Connection itself is safe to outlive the registry (it holds a weak liveness flag,
+ not a bare pointer). The half-fix that existed covered only one teardown order,
+ and the order between a C++ system and the JS-owned registry is not guaranteed.
+ Held by an AddressSanitizer harness that exercises both orders.
+
- **Saves no longer live in a directory the platform may delete.** Key/value
storage went to the host's cache directory, whose stated purpose was the
regenerable bytecode cache. On iOS that is `NSCachesDirectory`, which the system
diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.ts
index 23b49e4e7..16a63da8b 100644
--- a/sdk/src/physics/PhysicsSystem.ts
+++ b/sdk/src/physics/PhysicsSystem.ts
@@ -414,6 +414,11 @@ export function applyPhysicsTransforms(
const getTransformPtr = transformPtrFn
? (e: Entity) => transformPtrFn.call(engineMod, registry!, e as number)
: null;
+ // engF32 views the ENGINE heap, srcU32/srcF32 the PHYSICS heap. Caching them
+ // across the loop is safe only because the loop allocates on neither: it
+ // reads the transform buffer and reads/writes EXISTING Transform components.
+ // ALLOW_MEMORY_GROWTH detaches a cached view on any allocation that grows
+ // the heap — add one to this loop and these must be re-read per iteration.
const engF32 = engineMod?.HEAPF32;
const addFn = (!getTransformPtr || !engF32) ? registry.addTransform.bind(registry) : null;
const t = syncTransformBuf_;
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index de9c34012..a0880aed4 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -26,7 +26,7 @@
#include "Entity.hpp"
#include "SparseSet.hpp"
#include "View.hpp"
-#include "../events/Connection.hpp"
+#include "../events/Sink.hpp"
// Standard library
#include <algorithm>
@@ -167,18 +167,10 @@ public:
// twice, later aliasing two distinct entities to the same index.
entityValid_[idx] = false;
- ++firing_destroy_;
- for (usize i = 0; i < on_destroy_entries_.size(); ++i) {
- if (on_destroy_entries_[i].dead) continue;
- on_destroy_entries_[i].callback(entity);
- }
- --firing_destroy_;
- if (firing_destroy_ == 0) {
- on_destroy_entries_.erase(
- std::remove_if(on_destroy_entries_.begin(), on_destroy_entries_.end(),
- [](const DestroyEntry& e) { return e.dead; }),
- on_destroy_entries_.end());
- }
+ // Signal handles re-entrant connect/disconnect during publish; its RAII
+ // Connection (via Sink::connect) keeps subscriber lifetimes safe in both
+ // teardown orders — Registry-first or system-first (RC12, fixes A12).
+ on_destroy_signal_.publish(entity);
component_masks_[idx].forEachSet([&](u32 bit) {
if (bit < pools_.size() && pools_[bit]) {
@@ -195,37 +187,16 @@ public:
using DestroyCallback = std::function<void(Entity)>;
- u32 onDestroy(DestroyCallback callback) {
- u32 id = next_callback_id_++;
- on_destroy_entries_.push_back({id, std::move(callback), false});
- return id;
- }
-
- void removeOnDestroy(u32 callbackId) {
- for (auto& entry : on_destroy_entries_) {
- if (entry.id == callbackId) {
- entry.dead = true;
- if (firing_destroy_ == 0) {
- on_destroy_entries_.erase(
- std::remove_if(on_destroy_entries_.begin(), on_destroy_entries_.end(),
- [](const DestroyEntry& e) { return e.dead; }),
- on_destroy_entries_.end());
- }
- return;
- }
- }
- }
-
/**
- * RAII variant of onDestroy: the returned Connection auto-unregisters the
- * callback when it is destroyed, so a subscriber that holds it as a member
- * can never leak a dangling `this` into the registry. Prefer this over the
- * raw onDestroy()/removeOnDestroy() pair.
+ * @brief Subscribe to entity destruction.
+ * @return An RAII Connection. The callback stays registered for as long as
+ * the returned Connection is alive; on its destruction the callback
+ * is removed. The Connection is also safe to outlive the Registry —
+ * it no-ops against a destroyed signal — so subscribers and the
+ * Registry can tear down in either order without a dangling callback.
*/
- [[nodiscard]] Connection onDestroyScoped(DestroyCallback callback) {
- u32 id = onDestroy(std::move(callback));
- return Connection(static_cast<CallbackId>(id),
- [this](CallbackId cid) { removeOnDestroy(static_cast<u32>(cid)); });
+ [[nodiscard]] Connection onDestroy(DestroyCallback callback) {
+ return sink(on_destroy_signal_).connect(std::move(callback));
}
/**
@@ -696,17 +667,7 @@ private:
/** @brief Type-erased component pools indexed by TypeId */
std::vector<Unique<SparseSetBase>> pools_;
- struct DestroyEntry {
- u32 id;
- DestroyCallback callback;
- bool dead;
- };
-
- std::vector<DestroyEntry> on_destroy_entries_;
- // Starts at 1: id 0 is reserved as "no connection" (Connection's
- // INVALID_CALLBACK_ID) and as the not-yet-registered sentinel.
- u32 next_callback_id_ = 1;
- u32 firing_destroy_ = 0;
+ Signal<void(Entity)> on_destroy_signal_;
};
} // namespace esengine::ecs
diff --git a/src/esengine/particle/ParticleSystem.cpp b/src/esengine/particle/ParticleSystem.cpp
index ae331def2..c6dfd3e55 100644
--- a/src/esengine/particle/ParticleSystem.cpp
+++ b/src/esengine/particle/ParticleSystem.cpp
@@ -15,7 +15,7 @@ ParticleSystem::ParticleSystem()
void ParticleSystem::update(ecs::Registry& registry, f32 dt) {
if (!destroyConn_.isConnected()) {
- destroyConn_ = registry.onDestroyScoped([this](Entity entity) {
+ destroyConn_ = registry.onDestroy([this](Entity entity) {
states_.erase(entity);
pending_play_.erase(entity);
colorLuts_.erase(entity);
diff --git a/src/esengine/trail/TrailSystem.cpp b/src/esengine/trail/TrailSystem.cpp
index ee75a767b..22149dc11 100644
--- a/src/esengine/trail/TrailSystem.cpp
+++ b/src/esengine/trail/TrailSystem.cpp
@@ -6,7 +6,7 @@ namespace esengine::trail {
void TrailSystem::update(ecs::Registry& registry, f32 dt) {
if (!destroyConn_.isConnected()) {
- destroyConn_ = registry.onDestroyScoped([this](Entity entity) {
+ destroyConn_ = registry.onDestroy([this](Entity entity) {
states_.erase(entity);
});
}
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index ab720af4c..f40a64b58 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -237,6 +237,20 @@ target_compile_options(test_registry_safety PRIVATE $<${_es_safety_asan}:-fsanit
target_link_options(test_registry_safety PRIVATE $<${_es_safety_asan}:-fsanitize=address>)
add_test(NAME test_registry_safety COMMAND test_registry_safety)
+# onDestroy RAII Connection / dual-order teardown safety (RC12 B1, fixes A12).
+# Built with AddressSanitizer so the use-after-free the old bare-`this` callback
+# caused (in either teardown order) is actually caught, not just "didn't crash".
+add_executable(test_registry_ondestroy
+ ecs/test_registry_ondestroy.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
+)
+target_include_directories(test_registry_ondestroy PRIVATE
+ ${CMAKE_SOURCE_DIR}/src
+ ${CMAKE_SOURCE_DIR}/third_party/glm)
+target_compile_options(test_registry_ondestroy PRIVATE $<${_es_safety_asan}:-fsanitize=address>)
+target_link_options(test_registry_ondestroy PRIVATE $<${_es_safety_asan}:-fsanitize=address>)
+add_test(NAME test_registry_ondestroy COMMAND test_registry_ondestroy)
+
# Physics render interpolation. The snapshot pair and the lerp live in the physics
# module, not the SDK: they touch every dynamic body every frame, which the no-JIT
# budget keeps off the JS path (docs/REARCH_NATIVE.md §3.2). The whole module is
diff --git a/tests/ecs/test_registry.cpp b/tests/ecs/test_registry.cpp
index 14f5689d7..f4d223ec4 100644
--- a/tests/ecs/test_registry.cpp
+++ b/tests/ecs/test_registry.cpp
@@ -497,18 +497,18 @@ TEST_CASE("view_each tolerates mid-iteration remove of the current entity") {
CHECK_EQ(registry.view<test::Position>().size(), 0u);
}
-TEST_CASE("onDestroy callback can safely removeOnDestroy itself") {
+TEST_CASE("onDestroy callback can safely disconnect itself mid-publish") {
esengine::ecs::Registry registry;
esengine::Entity e = registry.create();
bool other_fired = false;
- esengine::u32 self_id = 0;
esengine::u32 self_fires = 0;
- esengine::u32 other_id = registry.onDestroy([&](esengine::Entity) { other_fired = true; });
- self_id = registry.onDestroy([&](esengine::Entity) {
+ esengine::Connection self;
+ esengine::Connection other = registry.onDestroy([&](esengine::Entity) { other_fired = true; });
+ self = registry.onDestroy([&](esengine::Entity) {
++self_fires;
- registry.removeOnDestroy(self_id);
+ self.disconnect();
});
registry.destroy(e);
@@ -521,8 +521,6 @@ TEST_CASE("onDestroy callback can safely removeOnDestroy itself") {
registry.destroy(e2);
CHECK(other_fired);
CHECK_EQ(self_fires, 1u);
-
- registry.removeOnDestroy(other_id);
}
TEST_CASE("setParent is idempotent on duplicate reparent") {
diff --git a/tests/ecs/test_registry_ondestroy.cpp b/tests/ecs/test_registry_ondestroy.cpp
new file mode 100644
index 000000000..468973b08
--- /dev/null
+++ b/tests/ecs/test_registry_ondestroy.cpp
@@ -0,0 +1,98 @@
+// Native harness for RC12 B1: Registry::onDestroy via RAII Connection (fixes A12).
+//
+// Verifies the destroy callback fires, and — the point of the RC — that a
+// subscriber and the Registry can tear down in EITHER order without a dangling
+// callback. The old code registered a bare `[this]` callback with no removal on
+// the subscriber's destruction, so a destroy() after the subscriber was gone
+// called into freed memory (A12); and a subscriber outliving the Registry had no
+// way to no-op. Both directions are exercised here, under AddressSanitizer:
+//
+// clang++ -std=c++20 -fsanitize=address -I src -I third_party/glm \
+// tests/ecs/test_registry_ondestroy.cpp src/esengine/core/Log.cpp \
+// -o /tmp/test_od && /tmp/test_od
+
+#include "esengine/ecs/Registry.hpp"
+
+#include <cstdio>
+#include <set>
+
+using esengine::Entity;
+using esengine::Connection;
+using esengine::u32;
+using esengine::ecs::Registry;
+
+static int g_failures = 0;
+#define CHECK(cond, msg) \
+ do { \
+ if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; } \
+ else { std::printf("ok: %s\n", msg); } \
+ } while (0)
+
+// Mirrors ParticleSystem/SpineSystem: holds a Connection, mutates its own state
+// from the callback (so a stale `this` call is a real use-after-free).
+struct FakeSystem {
+ std::set<u32> live;
+ Connection conn;
+ void attach(Registry& r) {
+ conn = r.onDestroy([this](Entity e) { live.erase(e.index()); });
+ }
+};
+
+int main() {
+ // 1. Basic: the callback fires on destroy.
+ {
+ Registry r;
+ FakeSystem sys;
+ sys.attach(r);
+ Entity e = r.create();
+ sys.live.insert(e.index());
+ r.destroy(e);
+ CHECK(sys.live.count(e.index()) == 0, "onDestroy callback fires");
+ }
+
+ // 2. System-first teardown (A12 forward): subscriber destroyed before the
+ // Registry. A later destroy() must NOT call the freed subscriber.
+ {
+ Registry r;
+ Entity e = r.create();
+ {
+ FakeSystem sys;
+ sys.attach(r);
+ sys.live.insert(e.index());
+ } // sys destroyed here -> Connection disconnects
+ r.destroy(e); // old bug: calls sys's lambda on freed `this` -> UAF
+ CHECK(true, "destroy after subscriber gone is safe (ASAN-checked)");
+ }
+
+ // 3. Registry-first teardown (A12 reverse): Registry destroyed before the
+ // subscriber. The subscriber's Connection destructor must no-op on the
+ // dead signal (weak alive_ check).
+ {
+ FakeSystem sys;
+ {
+ Registry r;
+ sys.attach(r);
+ (void)r.create();
+ } // r destroyed here -> signal dies
+ CHECK(true, "Connection outlives Registry safely");
+ } // sys.conn destructor here -> must not touch the dead signal (ASAN-checked)
+
+ // 4. Re-entrant destroy from a callback (A7 + Signal re-entrancy) still safe.
+ {
+ Registry r;
+ Entity e = r.create();
+ int calls = 0;
+ Connection conn = r.onDestroy([&](Entity ent) {
+ if (calls++ == 0) r.destroy(ent); // re-entrant destroy of same entity
+ });
+ r.destroy(e);
+ CHECK(r.entityCount() == 0, "re-entrant destroy via signal: no underflow");
+ }
+
+ if (g_failures == 0) {
+ std::printf("\nALL RC12 B1 TESTS PASSED\n");
+ return 0;
+ }
+ std::printf("\n%d FAILURE(S)\n", g_failures);
+ return 1;
+}
diff --git a/tests/ecs/test_registry_safety.cpp b/tests/ecs/test_registry_safety.cpp
index 628948378..f38032008 100644
--- a/tests/ecs/test_registry_safety.cpp
+++ b/tests/ecs/test_registry_safety.cpp
@@ -73,7 +73,10 @@ int main() {
Registry r;
Entity e = r.create();
int calls = 0;
- r.onDestroy([&](Entity ent) {
+ // Hold the Connection: onDestroy now returns an RAII handle (RC12); a
+ // discarded return would disconnect immediately and the callback would
+ // never fire, making the re-entrancy below untested.
+ esengine::Connection conn = r.onDestroy([&](Entity ent) {
if (calls++ == 0) r.destroy(ent); // re-entrant destroy of the SAME entity
});
CHECK(r.entityCount() == 1u, "one live entity before destroy");
@@ -91,17 +94,17 @@ int main() {
CHECK(r.valid(a) && r.valid(b), "both recreated entities are valid");
}
- // --- onDestroyScoped: the RAII Connection auto-unregisters on scope exit ---
- // A system that stores the raw callback id but forgets to removeOnDestroy
- // leaves a dangling `this` in the registry (the ParticleSystem / SpineSystem
- // bug). The scoped variant makes that impossible: the callback is gone once
- // the returned Connection is destroyed. ASAN here would catch a disconnect
+ // --- onDestroy: the RAII Connection auto-unregisters on scope exit ---
+ // A system that held a raw callback id and forgot to remove it left a
+ // dangling `this` in the registry (the ParticleSystem / SpineSystem bug).
+ // The Connection makes that impossible: the callback is gone once the
+ // returned Connection is destroyed. ASAN here would catch a disconnect
// that reached into freed memory.
{
Registry r;
int hits = 0;
{
- auto conn = r.onDestroyScoped([&](Entity) { ++hits; });
+ auto conn = r.onDestroy([&](Entity) { ++hits; });
Entity e = r.create();
r.destroy(e);
CHECK(hits == 1, "scoped onDestroy fires while the Connection is alive");