fix(runtime): fix data bind container re-entries (#12649) 0649b58ff5

Co-authored-by: hernan <hernan@rive.app>
diff --git a/.rive_head b/.rive_head
index 6d1d024..95ee493 100644
--- a/.rive_head
+++ b/.rive_head
@@ -1 +1 @@
-1548d0bb39cb39ca992e89167adfd97e5146946e
+0649b58ff5fe6f05d5a14ebf2a80c7fa9e0440a7
diff --git a/include/rive/data_bind/data_bind.hpp b/include/rive/data_bind/data_bind.hpp
index 2323f4c..3e3ae13 100644
--- a/include/rive/data_bind/data_bind.hpp
+++ b/include/rive/data_bind/data_bind.hpp
@@ -55,9 +55,15 @@
     void collapse(bool collapsed);
     void initialize();
     void relinkDataBind() override;
+    bool inDirtyList() const { return m_inDirtyList; }
+    void inDirtyList(bool value) { m_inDirtyList = value; }
+    bool inPersistingList() const { return m_inPersistingList; }
+    void inPersistingList(bool value) { m_inPersistingList = value; }
 
 private:
     bool m_isCollapsed = false;
+    bool m_inDirtyList = false;
+    bool m_inPersistingList = false;
 
 protected:
     ComponentDirt m_Dirt = ComponentDirt::None;
diff --git a/include/rive/data_bind/data_bind_container.hpp b/include/rive/data_bind/data_bind_container.hpp
index 382f855..3e5d3e3 100644
--- a/include/rive/data_bind/data_bind_container.hpp
+++ b/include/rive/data_bind/data_bind_container.hpp
@@ -31,6 +31,8 @@
     std::vector<DataBind*> m_persistingDataBinds;
     std::vector<DataBind*> m_dirtyDataBinds;
     std::vector<DataBind*> m_pendingDirtyDataBinds;
+    std::vector<DataBind*> m_pendingAdditions;
+    std::vector<DataBind*> m_pendingRemovals;
     DataContext* m_dataContext = nullptr;
     bool m_isProcessing = false;
 };
diff --git a/src/data_bind/data_bind_container.cpp b/src/data_bind/data_bind_container.cpp
index e3b70db..8513048 100644
--- a/src/data_bind/data_bind_container.cpp
+++ b/src/data_bind/data_bind_container.cpp
@@ -54,24 +54,45 @@
 
 void DataBindContainer::removeDataBind(DataBind* dataBind)
 {
-    m_dataBinds.erase(
-        std::remove(m_dataBinds.begin(), m_dataBinds.end(), dataBind),
-        m_dataBinds.end());
-    m_persistingDataBinds.erase(std::remove(m_persistingDataBinds.begin(),
-                                            m_persistingDataBinds.end(),
-                                            dataBind),
-                                m_persistingDataBinds.end());
-    m_dirtyDataBinds.erase(
-        std::remove(m_dirtyDataBinds.begin(), m_dirtyDataBinds.end(), dataBind),
-        m_dirtyDataBinds.end());
-    m_pendingDirtyDataBinds.erase(std::remove(m_pendingDirtyDataBinds.begin(),
-                                              m_pendingDirtyDataBinds.end(),
-                                              dataBind),
-                                  m_pendingDirtyDataBinds.end());
+    // Defer removal if we're mid-iteration in updateDataBinds; erasing from
+    // m_persistingDataBinds / m_dirtyDataBinds here would invalidate the
+    // active iterators.
+    if (m_isProcessing)
+    {
+        m_pendingRemovals.push_back(dataBind);
+        return;
+    }
+    auto eraseOne = [dataBind](std::vector<DataBind*>& v) {
+        v.erase(std::remove(v.begin(), v.end(), dataBind), v.end());
+    };
+    eraseOne(m_dataBinds);
+    if (dataBind->inPersistingList())
+    {
+        eraseOne(m_persistingDataBinds);
+        dataBind->inPersistingList(false);
+    }
+    if (dataBind->inDirtyList())
+    {
+        // Membership flag doesn't distinguish dirty vs pending-dirty, so check
+        // both — but only when the flag says one of them contains it.
+        eraseOne(m_dirtyDataBinds);
+        eraseOne(m_pendingDirtyDataBinds);
+        dataBind->inDirtyList(false);
+    }
+    dataBind->container(nullptr);
 }
 
 void DataBindContainer::addDataBind(DataBind* dataBind)
 {
+    // Defer if we're mid-iteration in updateDataBinds; push_back on
+    // m_persistingDataBinds during iteration could reallocate and invalidate
+    // the active range-for iterator, and the synchronous updateDataBind() call
+    // below would re-enter the update machinery.
+    if (m_isProcessing)
+    {
+        m_pendingAdditions.push_back(dataBind);
+        return;
+    }
     m_dataBinds.push_back(dataBind);
     // Any data bind that is applied to source needs to be updated regardless of
     // it having dirt or not. The reason is that they depend on changes of the
@@ -81,6 +102,7 @@
     if (dataBind->toSource())
     {
         m_persistingDataBinds.push_back(dataBind);
+        dataBind->inPersistingList(true);
     }
     dataBind->container(this);
     if (m_dataContext && dataBind->is<DataBindContext>())
@@ -121,6 +143,15 @@
 
 void DataBindContainer::updateDataBinds(bool applyTargetToSource)
 {
+    // Reject recursive entry. The defer-add / defer-remove machinery depends
+    // on m_isProcessing remaining true for the duration of the outer call.
+    // A nested call would flip m_isProcessing to false on its return, causing
+    // subsequent add/remove calls in the outer iteration to take the immediate
+    // path and invalidate the active iterators.
+    if (m_isProcessing)
+    {
+        return;
+    }
     if (m_persistingDataBinds.size() == 0 && m_dirtyDataBinds.size() == 0)
     {
         return;
@@ -138,17 +169,35 @@
         // data binds on this list don't need to apply target to source because
         // any data bind that applies to source is collected on the
         // m_persistingDataBinds list
+        dataBind->inDirtyList(false);
         updateDataBind(dataBind, false);
     }
     m_dirtyDataBinds.clear();
     if (m_pendingDirtyDataBinds.size() > 0)
     {
-
-        m_dirtyDataBinds.assign(m_pendingDirtyDataBinds.begin(),
-                                m_pendingDirtyDataBinds.end());
-        m_pendingDirtyDataBinds.clear();
+        m_dirtyDataBinds.swap(m_pendingDirtyDataBinds);
     }
     m_isProcessing = false;
+    // Flush additions before removals so a same-tick add-then-remove of the
+    // same bind resolves in chronological order (add wins, then remove).
+    if (!m_pendingAdditions.empty())
+    {
+        std::vector<DataBind*> additions;
+        additions.swap(m_pendingAdditions);
+        for (auto* dataBind : additions)
+        {
+            addDataBind(dataBind);
+        }
+    }
+    if (!m_pendingRemovals.empty())
+    {
+        std::vector<DataBind*> removals;
+        removals.swap(m_pendingRemovals);
+        for (auto* dataBind : removals)
+        {
+            removeDataBind(dataBind);
+        }
+    }
 }
 
 void DataBindContainer::sortDataBinds()
@@ -175,11 +224,12 @@
     {
         return;
     }
+    if (dataBind->inDirtyList())
+    {
+        return;
+    }
     auto& insertingList =
         m_isProcessing ? m_pendingDirtyDataBinds : m_dirtyDataBinds;
-    auto itr = std::find(insertingList.begin(), insertingList.end(), dataBind);
-    if (itr == insertingList.end())
-    {
-        insertingList.push_back(dataBind);
-    }
+    insertingList.push_back(dataBind);
+    dataBind->inDirtyList(true);
 }
\ No newline at end of file
diff --git a/tests/unit_tests/runtime/data_bind_container_test.cpp b/tests/unit_tests/runtime/data_bind_container_test.cpp
new file mode 100644
index 0000000..23680c2
--- /dev/null
+++ b/tests/unit_tests/runtime/data_bind_container_test.cpp
@@ -0,0 +1,282 @@
+#include <catch.hpp>
+#include <functional>
+#include "rive/component_dirt.hpp"
+#include "rive/data_bind/data_bind.hpp"
+#include "rive/data_bind/data_bind_container.hpp"
+#include "rive/data_bind_flags.hpp"
+
+using namespace rive;
+
+namespace
+{
+
+class TestContainer : public DataBindContainer
+{
+public:
+    using DataBindContainer::deleteDataBinds;
+};
+
+class TestDataBind : public DataBind
+{
+public:
+    int updateCalls = 0;
+    int updateSourceBindingCalls = 0;
+    std::function<void()> onUpdate;
+
+    void update(ComponentDirt value) override
+    {
+        updateCalls++;
+        if (onUpdate)
+        {
+            onUpdate();
+        }
+    }
+    void updateSourceBinding(bool invalidate = false) override
+    {
+        updateSourceBindingCalls++;
+    }
+};
+
+TestDataBind* makeBind(DataBindFlags f = DataBindFlags::ToTarget)
+{
+    auto* b = new TestDataBind();
+    b->flags(static_cast<uint32_t>(f));
+    return b;
+}
+
+} // namespace
+
+TEST_CASE("addDataBind registers backpointer and persisting flag",
+          "[data_bind_container]")
+{
+    TestContainer c;
+    auto* toTarget = makeBind(DataBindFlags::ToTarget);
+    auto* toSource = makeBind(DataBindFlags::ToSource);
+
+    c.addDataBind(toTarget);
+    c.addDataBind(toSource);
+
+    REQUIRE(toTarget->m_container == &c);
+    REQUIRE(toSource->m_container == &c);
+    REQUIRE(toTarget->inPersistingList() == false);
+    REQUIRE(toSource->inPersistingList() == true);
+
+    c.deleteDataBinds();
+}
+
+TEST_CASE("removeDataBind clears backpointer and membership flags",
+          "[data_bind_container]")
+{
+    TestContainer c;
+    auto* b = makeBind(DataBindFlags::ToSource);
+    c.addDataBind(b);
+    c.addDirtyDataBind(b); // no-op for toSource, but exercises the path
+
+    REQUIRE(b->m_container == &c);
+    REQUIRE(b->inPersistingList() == true);
+
+    c.removeDataBind(b);
+
+    REQUIRE(b->m_container == nullptr);
+    REQUIRE(b->inPersistingList() == false);
+    REQUIRE(b->inDirtyList() == false);
+
+    delete b;
+}
+
+TEST_CASE("addDirtyDataBind dedupes via inDirtyList flag",
+          "[data_bind_container]")
+{
+    TestContainer c;
+    auto* b = makeBind(DataBindFlags::ToTarget);
+    c.addDataBind(b);
+    b->dirt(ComponentDirt::Bindings);
+
+    REQUIRE(b->inDirtyList() == false);
+    c.addDirtyDataBind(b);
+    REQUIRE(b->inDirtyList() == true);
+
+    // Spam-add — should all early-return on the flag.
+    for (int i = 0; i < 25; i++)
+    {
+        c.addDirtyDataBind(b);
+    }
+
+    c.updateDataBinds();
+
+    // If dedupe were broken, update() would have been called once per entry.
+    REQUIRE(b->updateCalls == 1);
+    REQUIRE(b->inDirtyList() == false);
+
+    c.deleteDataBinds();
+}
+
+TEST_CASE("recursive updateDataBinds is rejected", "[data_bind_container]")
+{
+    TestContainer c;
+    auto* b = makeBind(DataBindFlags::ToSource);
+    c.addDataBind(b);
+    b->dirt(ComponentDirt::Bindings);
+
+    // External flag — must NOT self-clear b->onUpdate inside the lambda;
+    // doing so destroys the std::function storage holding the running
+    // lambda and leaves `this` dangling for the rest of the call.
+    bool fired = false;
+    b->onUpdate = [&]() {
+        if (fired)
+        {
+            return;
+        }
+        fired = true;
+        c.updateDataBinds();
+    };
+
+    c.updateDataBinds();
+
+    // Outer call ran update() once; the inner recursive call must have
+    // early-returned without touching the loops.
+    REQUIRE(b->updateCalls == 1);
+
+    c.deleteDataBinds();
+}
+
+TEST_CASE("addDataBind during update is deferred and flushed after",
+          "[data_bind_container]")
+{
+    TestContainer c;
+    auto* b = makeBind(DataBindFlags::ToSource);
+    auto* added = makeBind(DataBindFlags::ToSource);
+    c.addDataBind(b);
+    b->dirt(ComponentDirt::Bindings);
+
+    bool fired = false;
+    b->onUpdate = [&]() {
+        if (fired)
+        {
+            return;
+        }
+        fired = true;
+        c.addDataBind(added);
+        // Defer means the new bind is NOT live yet during outer iteration.
+        REQUIRE(added->m_container == nullptr);
+        REQUIRE(added->inPersistingList() == false);
+    };
+
+    c.updateDataBinds();
+
+    // Flush completed after the loops ran — the deferred add lands now.
+    REQUIRE(added->m_container == &c);
+    REQUIRE(added->inPersistingList() == true);
+    // It was added post-iteration, so its update() should not run this tick.
+    REQUIRE(added->updateCalls == 0);
+    REQUIRE(b->updateCalls == 1);
+
+    c.deleteDataBinds();
+}
+
+TEST_CASE("removeDataBind during update is deferred and flushed after",
+          "[data_bind_container]")
+{
+    TestContainer c;
+    auto* b = makeBind(DataBindFlags::ToSource);
+    auto* toRemove = makeBind(DataBindFlags::ToSource);
+    c.addDataBind(b);
+    c.addDataBind(toRemove);
+    b->dirt(ComponentDirt::Bindings);
+
+    bool fired = false;
+    b->onUpdate = [&]() {
+        if (fired)
+        {
+            return;
+        }
+        fired = true;
+        c.removeDataBind(toRemove);
+        // Defer means toRemove stays in the lists until the flush; if the
+        // removal happened inline, m_persistingDataBinds erase would
+        // invalidate the active range-for iterator (crash) and the
+        // backpointer would already be null here.
+        REQUIRE(toRemove->m_container == &c);
+        REQUIRE(toRemove->inPersistingList() == true);
+    };
+
+    c.updateDataBinds();
+
+    REQUIRE(toRemove->m_container == nullptr);
+    REQUIRE(toRemove->inPersistingList() == false);
+
+    c.deleteDataBinds();
+    delete toRemove;
+}
+
+TEST_CASE("same-tick add then remove of the same bind resolves to removed",
+          "[data_bind_container]")
+{
+    TestContainer c;
+    auto* b = makeBind(DataBindFlags::ToSource);
+    auto* transient = makeBind(DataBindFlags::ToSource);
+    c.addDataBind(b);
+    b->dirt(ComponentDirt::Bindings);
+
+    bool fired = false;
+    b->onUpdate = [&]() {
+        if (fired)
+        {
+            return;
+        }
+        fired = true;
+        c.addDataBind(transient);    // queued in pendingAdditions
+        c.removeDataBind(transient); // queued in pendingRemovals
+    };
+
+    c.updateDataBinds();
+
+    // Additions flush before removals, so the chronological add-then-remove
+    // resolves to: bind ends up removed.
+    REQUIRE(transient->m_container == nullptr);
+    REQUIRE(transient->inPersistingList() == false);
+
+    c.deleteDataBinds();
+    delete transient;
+}
+
+TEST_CASE("pending-dirty binds swap into dirty on next tick",
+          "[data_bind_container]")
+{
+    TestContainer c;
+    auto* driver = makeBind(DataBindFlags::ToSource);
+    auto* dependent = makeBind(DataBindFlags::ToTarget);
+    c.addDataBind(driver);
+    c.addDataBind(dependent);
+    driver->dirt(ComponentDirt::Bindings);
+
+    bool fired = false;
+    driver->onUpdate = [&]() {
+        if (fired)
+        {
+            return;
+        }
+        fired = true;
+        // Marking another bind dirty while processing — should land in
+        // m_pendingDirtyDataBinds, not m_dirtyDataBinds.
+        dependent->dirt(ComponentDirt::Bindings);
+        c.addDirtyDataBind(dependent);
+        REQUIRE(dependent->inDirtyList() == true);
+    };
+
+    c.updateDataBinds();
+
+    // Dependent was queued mid-processing — should not have been updated yet.
+    REQUIRE(dependent->updateCalls == 0);
+    // But should still be flagged for next tick (lives in dirty list now).
+    REQUIRE(dependent->inDirtyList() == true);
+
+    c.updateDataBinds();
+
+    // Second tick — dependent is in the dirty list, gets processed once,
+    // flag cleared.
+    REQUIRE(dependent->updateCalls == 1);
+    REQUIRE(dependent->inDirtyList() == false);
+
+    c.deleteDataBinds();
+}