siddhm11 Claude Opus 5.5 commited on
Commit
826b5f4
Β·
1 Parent(s): 3ed6773

fix(user-state): bound the in-memory user cache (audit F9)

Browse files

Every cookieless visit mints a user id and caches a UserState, and nothing
evicted them, so crawlers on public paper pages grew memory for the life of
the process (2,000 visits, 2,000 states). The cache is now an LRU capped at
5,000; an evicted reader is re-hydrated from the database on their next
request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Files changed (3) hide show
  1. app/user_state.py +16 -5
  2. tests/conftest.py +1 -1
  3. tests/test_user_state.py +25 -1
app/user_state.py CHANGED
@@ -11,7 +11,7 @@ Thread-safety: asyncio is single-threaded; no locks needed.
11
  from __future__ import annotations
12
 
13
  from dataclasses import dataclass, field
14
- from collections import deque
15
 
16
  from app import db, config
17
 
@@ -69,14 +69,25 @@ class UserState:
69
 
70
  # ── Global in-process cache ───────────────────────────────────────────────────
71
 
72
- _cache: dict[str, UserState] = {}
 
 
 
 
 
 
73
 
74
 
75
  def get_user_state(user_id: str) -> UserState:
76
  """Return the in-memory state for a user (creates if missing)."""
77
- if user_id not in _cache:
78
- _cache[user_id] = UserState()
79
- return _cache[user_id]
 
 
 
 
 
80
 
81
 
82
  async def ensure_loaded(user_id: str) -> UserState:
 
11
  from __future__ import annotations
12
 
13
  from dataclasses import dataclass, field
14
+ from collections import OrderedDict, deque
15
 
16
  from app import db, config
17
 
 
69
 
70
  # ── Global in-process cache ───────────────────────────────────────────────────
71
 
72
+ # Bounded LRU. Every cookieless visit mints a user id, so crawlers on public
73
+ # paper pages grew an unbounded dict for the life of the process (audit F9:
74
+ # 2,000 visits, 2,000 states). An evicted reader is simply re-hydrated from the
75
+ # database on their next request; nothing here is the only copy.
76
+ MAX_CACHED_USERS = 5_000
77
+
78
+ _cache: "OrderedDict[str, UserState]" = OrderedDict()
79
 
80
 
81
  def get_user_state(user_id: str) -> UserState:
82
  """Return the in-memory state for a user (creates if missing)."""
83
+ state = _cache.get(user_id)
84
+ if state is not None:
85
+ _cache.move_to_end(user_id)
86
+ return state
87
+ state = _cache[user_id] = UserState()
88
+ while len(_cache) > MAX_CACHED_USERS:
89
+ _cache.popitem(last=False)
90
+ return state
91
 
92
 
93
  async def ensure_loaded(user_id: str) -> UserState:
tests/conftest.py CHANGED
@@ -43,7 +43,7 @@ def _isolate_application_state(request, tmp_path, monkeypatch):
43
  path = str(tmp_path / "isolated-app.db")
44
  monkeypatch.setattr(config, "DB_PATH", path)
45
  monkeypatch.setattr(db, "DB_PATH", path)
46
- monkeypatch.setattr(user_state, "_cache", {})
47
  monkeypatch.setattr(recommendations, "_FEED_CACHE", OrderedDict())
48
  asyncio.run(db.init_db())
49
 
 
43
  path = str(tmp_path / "isolated-app.db")
44
  monkeypatch.setattr(config, "DB_PATH", path)
45
  monkeypatch.setattr(db, "DB_PATH", path)
46
+ monkeypatch.setattr(user_state, "_cache", OrderedDict())
47
  monkeypatch.setattr(recommendations, "_FEED_CACHE", OrderedDict())
48
  asyncio.run(db.init_db())
49
 
tests/test_user_state.py CHANGED
@@ -2,7 +2,7 @@
2
  Unit tests for user_state.py β€” pure in-memory logic, no DB/network.
3
  """
4
  import pytest
5
- from collections import deque
6
 
7
  # We test the UserState dataclass directly
8
  from app.user_state import UserState, MAX_POSITIVES, MAX_NEGATIVES
@@ -84,3 +84,27 @@ def test_all_seen_union():
84
  assert "pos1" in seen
85
  assert "neg1" in seen
86
  _cache.pop(uid, None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  Unit tests for user_state.py β€” pure in-memory logic, no DB/network.
3
  """
4
  import pytest
5
+ from collections import OrderedDict, deque
6
 
7
  # We test the UserState dataclass directly
8
  from app.user_state import UserState, MAX_POSITIVES, MAX_NEGATIVES
 
84
  assert "pos1" in seen
85
  assert "neg1" in seen
86
  _cache.pop(uid, None)
87
+
88
+
89
+ # ── Bounded cache (audit F9) ──────────────────────────────────────────────────
90
+ # Every cookieless visit mints a user id, so crawlers on public paper pages
91
+ # grew the cache for the life of the process: 2,000 visits, 2,000 states.
92
+
93
+ def test_the_user_cache_is_bounded(monkeypatch):
94
+ from app import user_state as us
95
+ monkeypatch.setattr(us, "_cache", OrderedDict())
96
+ monkeypatch.setattr(us, "MAX_CACHED_USERS", 100)
97
+ for i in range(250):
98
+ us.get_user_state(f"crawler-{i}")
99
+ assert len(us._cache) == 100
100
+
101
+
102
+ def test_a_recently_used_reader_outlives_the_crawlers(monkeypatch):
103
+ from app import user_state as us
104
+ monkeypatch.setattr(us, "_cache", OrderedDict())
105
+ monkeypatch.setattr(us, "MAX_CACHED_USERS", 100)
106
+ us.record_positive("reader", "1706.03762")
107
+ for i in range(250):
108
+ us.get_user_state(f"crawler-{i}")
109
+ us.get_user_state("reader")
110
+ assert "1706.03762" in us.get_user_state("reader").positives