Skip to content

The agent that grows with you

fix(gateway): serialize rich_sent_store._update across worker threads

kshitijk4poorc6ed9d5734bf
diff --git a/gateway/rich_sent_store.py b/gateway/rich_sent_store.py
index 73327626a29..00ae6e471a1 100644
--- a/gateway/rich_sent_store.py
+++ b/gateway/rich_sent_store.py
@@ -14,12 +14,19 @@ from __future__ import annotations
import asyncio
import json
import os
+import threading
import time
from typing import Optional
from utils import atomic_json_write
_MAX_ENTRIES = 1000
_MAX_TEXT_CHARS = 2000
+# ``atomic_json_write`` makes each WRITE atomic, not the load/merge/save triple.
+# ``record_async`` runs ``_update`` on worker threads, so two concurrent callers
+# (two inbound WhatsApp-Cloud messages, a Telegram send racing an edit) would
+# otherwise each load the same pre-state and the later ``os.replace`` drops the
+# other key.
+_LOCK = threading.Lock()
def _store_path() -> str:
@@ -39,19 +46,20 @@ def _load(path: str) -> dict:
def _update(chat_id, message_id, fields: dict) -> None:
"""Merge ``fields`` into the ``(chat_id, message_id)`` entry. No-op on any failure."""
path = _store_path()
- try:
- os.makedirs(os.path.dirname(path), exist_ok=True)
- data = _load(path)
- key = f"{chat_id}:{message_id}"
- entry = data.get(key)
- entry = entry if isinstance(entry, dict) else {}
- data[key] = {**entry, **fields, "ts": int(time.time())}
- if len(data) > _MAX_ENTRIES: # trim oldest by timestamp
- for k, _ in sorted(data.items(), key=lambda kv: kv[1].get("ts", 0))[: len(data) - _MAX_ENTRIES]:
- data.pop(k, None)
- atomic_json_write(path, data, indent=None) # atomic; tolerates concurrent writers racing
- except Exception:
- return
+ with _LOCK:
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ data = _load(path)
+ key = f"{chat_id}:{message_id}"
+ entry = data.get(key)
+ entry = entry if isinstance(entry, dict) else {}
+ data[key] = {**entry, **fields, "ts": int(time.time())}
+ if len(data) > _MAX_ENTRIES: # trim oldest by timestamp
+ for k, _ in sorted(data.items(), key=lambda kv: kv[1].get("ts", 0))[: len(data) - _MAX_ENTRIES]:
+ data.pop(k, None)
+ atomic_json_write(path, data, indent=None) # atomic write; the lock makes the triple atomic
+ except Exception:
+ return
def record(chat_id, message_id, text: Optional[str]) -> None:
diff --git a/tests/gateway/test_rich_sent_store_off_loop.py b/tests/gateway/test_rich_sent_store_off_loop.py
index 1595b21362e..16b5a0a5ad1 100644
--- a/tests/gateway/test_rich_sent_store_off_loop.py
+++ b/tests/gateway/test_rich_sent_store_off_loop.py
@@ -2,6 +2,7 @@
import asyncio
import threading
+import time
import pytest
@@ -30,3 +31,29 @@ def test_record_async_runs_off_the_loop_thread(isolated_store, monkeypatch):
loop_thread = asyncio.run(go())
assert writer_thread and writer_thread[0] != loop_thread
assert rich_sent_store.lookup("chat", "42") == "hello"
+
+
+def test_concurrent_record_async_calls_lose_no_entry(isolated_store, monkeypatch):
+ """Two off-loop RMWs for different keys must both land in the durable file.
+
+ ``atomic_json_write`` makes each write atomic, not load/merge/save. Slowing the
+ write forces the second caller to load the same pre-state unless ``_update`` is
+ serialized, in which case the later ``os.replace`` drops the other key.
+ """
+ real_write = rich_sent_store.atomic_json_write
+
+ def slow_write(path, data, *a, **kw):
+ time.sleep(0.2)
+ return real_write(path, data, *a, **kw)
+
+ monkeypatch.setattr(rich_sent_store, "atomic_json_write", slow_write)
+
+ async def go():
+ await asyncio.gather(
+ rich_sent_store.record_async("chat", "1", "one"),
+ rich_sent_store.record_async("chat", "2", "two"),
+ )
+
+ asyncio.run(go())
+ assert rich_sent_store.lookup("chat", "1") == "one"
+ assert rich_sent_store.lookup("chat", "2") == "two"