Skip to content

Build and run agents you can see, understand and trust.

fix(memory): start the ReMe app once for concurrent callers (#3687)

Kiko0301997e2e288db0
diff --git a/src/agentscope/middleware/_longterm_memory/_reme/_middleware.py b/src/agentscope/middleware/_longterm_memory/_reme/_middleware.py
index 818734b96..8470eac37 100644
--- a/src/agentscope/middleware/_longterm_memory/_reme/_middleware.py
+++ b/src/agentscope/middleware/_longterm_memory/_reme/_middleware.py
@@ -212,6 +212,9 @@ class ReMeMiddleware(MiddlewareBase):
# it builds, so :meth:`close` tears it down.
self._app: Any | None = None
self._started = False
+ # Serializes the lazy start so hooks running concurrently on a fresh
+ # middleware start the embedded app exactly once.
+ self._start_lock = asyncio.Lock()
self._workspace_dir = workspace_dir
self._parameters = parameters or self.Parameters()
# In-flight background retrieval per session (started in ``on_reply``,
@@ -265,9 +268,15 @@ class ReMeMiddleware(MiddlewareBase):
The AgentScope minimal config only creates an embedding component when
``embedding_model`` is provided.
"""
- if self._app is None:
- self._app = self._build_app()
- if not self._started:
+ if self._started:
+ return
+ async with self._start_lock:
+ # Checked again under the lock: a concurrent caller may have
+ # finished starting the app while this one waited for it.
+ if self._started:
+ return
+ if self._app is None:
+ self._app = self._build_app()
if self._parameters.chat_model is not None:
await self._app.update_component(
_AS_LLM_COMPONENT,
diff --git a/tests/reme_middleware_test.py b/tests/reme_middleware_test.py
index 96c4be843..c83f40fbb 100644
--- a/tests/reme_middleware_test.py
+++ b/tests/reme_middleware_test.py
@@ -619,6 +619,31 @@ class TestConstructorValidation(IsolatedAsyncioTestCase):
self.assertIn("embedding_store", components)
+class TestAppLifecycle(IsolatedAsyncioTestCase):
+ """Tests for the lazily built embedded app's one-time start."""
+
+ async def test_concurrent_callers_start_the_app_once(self) -> None:
+ """Hooks that run before the app is started must start it once."""
+
+ class _SlowStartApp(_FakeReMeApp):
+ """A fake app whose start yields, so callers interleave."""
+
+ async def start(self) -> None:
+ await asyncio.sleep(0)
+ await super().start()
+
+ mw = ReMeMiddleware()
+ app = _SlowStartApp()
+ with mock.patch.object(mw, "_build_app", return_value=app):
+ await asyncio.gather(
+ *(mw._ensure_started() for _ in range(5)),
+ )
+
+ self.assertEqual(app.start_count, 1)
+ self.assertTrue(mw._started)
+ self.assertIs(mw._app, app)
+
+
# ----------------------------------------------------------------------
# Static-control mode (default)
# ----------------------------------------------------------------------