Skip to content

The agent that grows with you

perf(gateway): cache pairing approved list by file mtime instead of re-reading per message

Adolaniumd644764c9d67
diff --git a/gateway/pairing.py b/gateway/pairing.py
index e5c1e49a324..9cd80007a92 100644
--- a/gateway/pairing.py
+++ b/gateway/pairing.py
@@ -333,6 +333,7 @@ class PairingStore:
_migrate_split_pairing_dirs(home=profile_home, active=self._dir)
self._lock = threading.RLock() # adapters run concurrently in threads sharing one store
self._profile = profile # for diagnostics / log lines
+ self._approved_cache: dict = {}
@property
def profile(self) -> Optional[str]:
@@ -371,9 +372,30 @@ class PairingStore:
# ----- Approved users -----
+ def _load_approved(self, platform: str) -> dict:
+ path = self._approved_path(platform)
+ try:
+ # Opening first preserves fail-closed authorization if permissions change.
+ # fstat identifies the actual opened file even during atomic replacement.
+ with path.open("rb") as stream:
+ st = os.fstat(stream.fileno())
+ key = (st.st_dev, st.st_ino, st.st_mtime_ns, st.st_ctime_ns, st.st_size)
+ cached = self._approved_cache.get(platform)
+ if cached is not None and cached[0] == key:
+ return cached[1]
+ data = json.load(stream)
+ data = data if isinstance(data, dict) else {}
+ except (OSError, json.JSONDecodeError, UnicodeDecodeError):
+ self._approved_cache.pop(platform, None)
+ # Keep the existing diagnostics for unreadable pairing files.
+ return self._load_json(path)
+ self._approved_cache[platform] = (key, data)
+ return data
+
def is_approved(self, platform: str, user_id: str) -> bool:
"""Check if a user is approved (paired) on a platform."""
- return bool(_matching_ids(platform, self._load_json(self._approved_path(platform)), user_id))
+ with self._lock:
+ return bool(_matching_ids(platform, self._load_approved(platform), user_id))
def list_approved(self, platform: str = None) -> list:
"""List approved users, optionally filtered by platform."""
diff --git a/tests/gateway/test_pairing.py b/tests/gateway/test_pairing.py
index f97bfcb3cf7..7a0f038bcc4 100644
--- a/tests/gateway/test_pairing.py
+++ b/tests/gateway/test_pairing.py
@@ -722,3 +722,52 @@ class TestProfileScopedStorage:
)
+
+
+def test_approval_cache_reuses_parse_and_observes_replacement(tmp_path, monkeypatch):
+ store = _make_store(tmp_path)
+ other = _make_store(tmp_path)
+ path = store._approved_path("telegram")
+ store._save_json(path, {"user1": {"user_name": "Alice", "approved_at": 1.0}})
+ with patch("gateway.pairing.json.load", wraps=json.load) as parse:
+ for _ in range(5):
+ assert store.is_approved("telegram", "user1")
+ assert parse.call_count == 1
+ assert other.revoke("telegram", "user1")
+ assert not store.is_approved("telegram", "user1")
+ other._save_json(path, {"user1": {"user_name": "Alice", "approved_at": 1.0}})
+ assert store.is_approved("telegram", "user1")
+ before = path.stat()
+ replacement = tmp_path / "replacement"
+ replacement.write_bytes(path.read_bytes().replace(b"user1", b"user2"))
+ os.utime(replacement, ns=(before.st_atime_ns, before.st_mtime_ns))
+ replacement.replace(path)
+ assert path.stat().st_size == before.st_size
+ assert not store.is_approved("telegram", "user1")
+ assert store.is_approved("telegram", "user2")
+ path.unlink()
+ assert not store.is_approved("telegram", "user2")
+ other._save_json(path, {"user3": {}})
+ assert store.is_approved("telegram", "user3")
+
+
+def test_approval_cache_isolated_and_unreadable_files_fail_closed(tmp_path, monkeypatch):
+ first = _make_store(tmp_path / "first")
+ second = _make_store(tmp_path / "second")
+ path = first._approved_path("telegram")
+ first._save_json(path, {"user1": {}})
+ assert first.is_approved("telegram", "user1")
+ assert not second.is_approved("telegram", "user1")
+ original = Path.open
+
+ def unreadable(self, *args, **kwargs):
+ if self == path:
+ raise PermissionError("permission revoked")
+ return original(self, *args, **kwargs)
+
+ with monkeypatch.context() as m:
+ m.setattr(Path, "open", unreadable)
+ assert not first.is_approved("telegram", "user1")
+ first._save_json(path, {"user2": {}})
+ assert not first.is_approved("telegram", "user1")
+ assert first.is_approved("telegram", "user2")