The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(supermemory): serialize capture writes and document at-least-once retry
Mahesh Sanikommuc6da9e07880f
diff --git a/plugins/memory/supermemory/README.md b/plugins/memory/supermemory/README.mdindex 4f09389cf07..5fd2317696b 100644--- a/plugins/memory/supermemory/README.md+++ b/plugins/memory/supermemory/README.md@@ -94,7 +94,7 @@ When enabled, Hermes can:- prefetch relevant memory context before each turn- write each completed user/assistant turn to **one document per session per 4-hour window** (`customId` = `<session>_<date>_b<0-5>`, so the API appends deltas), like the Codex and OpenClaw plugins-- retry failed turn writes on the next turn, session end, `/reset`, or shutdown+- retry failed turn writes on the next turn, session end, `/reset`, or shutdown (at-least-once: if the API accepted a write but the response was lost, the same turn is appended again)- route every SDK and probe request through the configured hosted or self-hosted endpoint- expose explicit tools for search, store, forget, and profile accessdiff --git a/plugins/memory/supermemory/__init__.py b/plugins/memory/supermemory/__init__.pyindex fc3c639ac5a..50e61173d0f 100644--- a/plugins/memory/supermemory/__init__.py+++ b/plugins/memory/supermemory/__init__.py@@ -316,6 +316,7 @@ class SupermemoryMemoryProvider(MemoryProvider):self._container_tag, self._turn_count, self._write_enabled, self._active = _DEFAULT_CONTAINER_TAG, 0, True, Falseself._prefetch_thread = self._sync_thread = self._write_thread = None # only _write_thread is ever startedself._pending_turns: List[Dict[str, str]] = [] # failed writes, each tagged with its session_id; retried on next write/end/switch/shutdown+ self._capture_lock = threading.Lock() # sync_turn (worker) vs on_session_switch/shutdown (caller thread) both touch _pending_turnsself._apply_config(_load_supermemory_config())self._base_url, self._allowed_containers = _DEFAULT_BASE_URL, [] # env var is only consulted in initialize()@@ -411,23 +412,29 @@ class SupermemoryMemoryProvider(MemoryProvider):profile["search_results"], self._max_recall_results)return _quietly(_recall, "Supermemory prefetch failed", default="")- def _write_turns(self, turns: List[Dict[str, str]], mode: str) -> None:- """One documents.add per session id in ``turns`` (custom_id = session + 4h bucket, so the API appends deltas).- Failed batches stay pending under their own session id, so a switch never re-homes them."""- failed: List[Dict[str, str]] = []- for sid in dict.fromkeys(t["session_id"] for t in turns):- batch = [t for t in turns if t["session_id"] == sid]- now = datetime.now(timezone.utc)- content = "\n\n".join(_format_turn(t["user"], t["assistant"]) for t in batch)- metadata = {"type": "conversation", "session_id": sid, "timestamp": now.isoformat()} # no sm_capture_mode: Hermes policy- try:- self._client.add_memory(content, metadata=metadata, entity_context=self._entity_context,- custom_id=_capture_custom_id(sid, now))- except Exception:- logger.log(logging.WARNING if mode != "turn" else logging.DEBUG, "Supermemory capture failed (%s, session=%s, %d turns pending)",- mode, sid, len(batch), exc_info=True)- failed += batch- self._pending_turns = failed+ def _write_turns(self, mode: str, new_turn: Optional[Dict[str, str]] = None) -> None:+ """Write pending turns (+ ``new_turn``) as one documents.add per session id; custom_id = session + 4h bucket, so the+ API appends deltas. Failed batches stay pending under their own session id, so a switch never re-homes them.+ Retries are at-least-once: a write the API accepted but whose response was lost is re-sent and appended again.+ The lock serializes the snapshot/write/replace sequence across the worker and caller threads."""+ with self._capture_lock:+ turns = self._pending_turns + ([new_turn] if new_turn else [])+ if not turns:+ return+ failed: List[Dict[str, str]] = []+ for sid in dict.fromkeys(t["session_id"] for t in turns):+ batch = [t for t in turns if t["session_id"] == sid]+ now = datetime.now(timezone.utc)+ content = "\n\n".join(_format_turn(t["user"], t["assistant"]) for t in batch)+ metadata = {"type": "conversation", "session_id": sid, "timestamp": now.isoformat()} # no sm_capture_mode: Hermes policy+ try:+ self._client.add_memory(content, metadata=metadata, entity_context=self._entity_context,+ custom_id=_capture_custom_id(sid, now))+ except Exception:+ logger.log(logging.WARNING if mode != "turn" else logging.DEBUG, "Supermemory capture failed (%s, session=%s, %d turns pending)",+ mode, sid, len(batch), exc_info=True)+ failed += batch+ self._pending_turns = faileddef sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:# Host runs this on a worker thread, so the blocking write is fine here.@@ -436,11 +443,11 @@ class SupermemoryMemoryProvider(MemoryProvider):turn = {"user": _clean_text_for_capture(user_content), "assistant": _clean_text_for_capture(assistant_content),"session_id": session_id or self._session_id}if turn["user"] or turn["assistant"]:- self._write_turns(self._pending_turns + [turn], "turn")+ self._write_turns("turn", turn)def _flush_pending(self, mode: str) -> None:- if self._can_write() and self._pending_turns:- self._write_turns(list(self._pending_turns), mode)+ if self._can_write():+ self._write_turns(mode)def on_session_end(self, messages: List[Dict[str, Any]]) -> None:# Turns were already written as they completed; only retry what failed.diff --git a/tests/plugins/memory/test_supermemory_provider.py b/tests/plugins/memory/test_supermemory_provider.pyindex c4d00baf0de..eb4c15b67a2 100644--- a/tests/plugins/memory/test_supermemory_provider.py+++ b/tests/plugins/memory/test_supermemory_provider.py@@ -195,6 +195,37 @@ def test_failed_switch_flush_keeps_old_session_turns_for_later_retry(provider):assert provider._pending_turns == []+def test_concurrent_sync_turn_and_session_switch_do_not_duplicate_pending(provider, monkeypatch):+ # Worker thread: sync_turn(B) with pending [A] snapshots [A, B] and blocks inside add_memory.+ # Caller thread: on_session_switch must wait for that write, not re-send A from a stale snapshot.+ provider._client.fail_add = True+ provider.sync_turn("A", "a", session_id="session-1")+ provider._client.fail_add = False+ entered, release = threading.Event(), threading.Event()+ real_add = provider._client.add_memory++ def slow_add(content, metadata=None, **kwargs):+ entered.set()+ assert release.wait(timeout=2)+ return real_add(content, metadata=metadata, **kwargs)++ monkeypatch.setattr(provider._client, "add_memory", slow_add)+ worker = threading.Thread(target=provider.sync_turn, args=("B", "b"), kwargs={"session_id": "session-1"})+ worker.start()+ assert entered.wait(timeout=2)+ switcher = threading.Thread(target=provider.on_session_switch, args=("session-2",), kwargs={"reset": True})+ switcher.start()+ switcher.join(timeout=0.2)+ assert switcher.is_alive() # blocked on the capture lock while the worker's write is in flight+ release.set()+ worker.join(timeout=2); switcher.join(timeout=2)+ assert not worker.is_alive() and not switcher.is_alive()+ assert len(provider._client.add_calls) == 1+ assert provider._client.add_calls[0]["content"].count("[role: user]") == 2 # A and B, once each+ assert provider._pending_turns == []+ assert provider._session_id == "session-2"++def test_failed_switch_flush_is_retried_at_shutdown(provider):provider._client.fail_add = Trueprovider.sync_turn("old turn", "old reply", session_id="session-1")