sitcod3 commited on
Commit
f4a3981
·
verified ·
1 Parent(s): c4729ea

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app/utils/cache.py +70 -13
  2. tests/test_cache_circuit.py +117 -0
app/utils/cache.py CHANGED
@@ -17,6 +17,47 @@ _redis_client: Optional[object] = None
17
  _memory_cache: dict = {}
18
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  async def get_redis():
21
  """Lazily create a shared Redis client (returns None if unavailable).
22
 
@@ -66,23 +107,39 @@ def _memory_set(key: str, value: str, ttl: int):
66
 
67
 
68
  async def get_cache(key: str) -> Optional[str]:
69
- try:
70
- client = await get_redis()
71
- if client is not None:
72
- return await client.get(key)
73
- except Exception:
74
- pass
 
 
 
 
 
 
 
 
 
 
75
  return _memory_get(key)
76
 
77
 
78
  async def set_cache(key: str, value: str, ttl: int = 86400):
79
- try:
80
- client = await get_redis()
81
- if client is not None:
82
- await client.setex(key, ttl, value)
83
- return
84
- except Exception:
85
- pass
 
 
 
 
 
 
86
  _memory_set(key, value, ttl)
87
 
88
 
 
17
  _memory_cache: dict = {}
18
 
19
 
20
+ class CircuitBreaker:
21
+ """Fail fast to the in-memory cache when Redis is slow or down.
22
+
23
+ Without this, `validate_batch` pays Redis' socket timeout (~2s) on every one
24
+ of the ~8 cache calls it makes per row — measured at 10.0s per row on a
25
+ host where the Upstash link is slow, while the engine itself needs ~70ms.
26
+ After `failure_threshold` consecutive slow/failed ops the circuit opens and
27
+ calls skip Redis entirely until `cooldown_seconds` elapse, then probe once.
28
+ """
29
+
30
+ def __init__(self, failure_threshold: int = 3,
31
+ cooldown_seconds: float = 30.0, slow_threshold: float = 1.0):
32
+ self.failure_threshold = failure_threshold
33
+ self.cooldown_seconds = cooldown_seconds
34
+ self.slow_threshold = slow_threshold
35
+ self._failures = 0
36
+ self._open_until = 0.0
37
+
38
+ def allow(self) -> bool:
39
+ """True when Redis may be contacted (closed, or cooldown elapsed)."""
40
+ return time.time() >= self._open_until
41
+
42
+ def record(self, success: bool, duration: float) -> None:
43
+ """Record one op: slow ops count as failures even when they succeed."""
44
+ if success and duration < self.slow_threshold:
45
+ self._failures = 0
46
+ return
47
+ self._failures += 1
48
+ if self._failures >= self.failure_threshold:
49
+ self._open_until = time.time() + self.cooldown_seconds
50
+ self._failures = 0
51
+
52
+ def reset(self) -> None:
53
+ self._failures = 0
54
+ self._open_until = 0.0
55
+
56
+
57
+ # Trips when Redis is consistently slow/failing; see CircuitBreaker.
58
+ _circuit = CircuitBreaker()
59
+
60
+
61
  async def get_redis():
62
  """Lazily create a shared Redis client (returns None if unavailable).
63
 
 
107
 
108
 
109
  async def get_cache(key: str) -> Optional[str]:
110
+ if _circuit.allow():
111
+ t0 = time.perf_counter()
112
+ try:
113
+ client = await get_redis()
114
+ if client is not None:
115
+ value = await client.get(key)
116
+ _circuit.record(success=True, duration=time.perf_counter() - t0)
117
+ return value
118
+ # Redis is configured but get_redis() could not establish a client
119
+ # (connect/ping failed). Without this the 2s timeout is paid on
120
+ # EVERY call and the breaker never trips.
121
+ if (settings.redis_url or "").strip():
122
+ _circuit.record(success=False,
123
+ duration=time.perf_counter() - t0)
124
+ except Exception:
125
+ _circuit.record(success=False, duration=time.perf_counter() - t0)
126
  return _memory_get(key)
127
 
128
 
129
  async def set_cache(key: str, value: str, ttl: int = 86400):
130
+ if _circuit.allow():
131
+ t0 = time.perf_counter()
132
+ try:
133
+ client = await get_redis()
134
+ if client is not None:
135
+ await client.setex(key, ttl, value)
136
+ _circuit.record(success=True, duration=time.perf_counter() - t0)
137
+ return
138
+ if (settings.redis_url or "").strip():
139
+ _circuit.record(success=False,
140
+ duration=time.perf_counter() - t0)
141
+ except Exception:
142
+ _circuit.record(success=False, duration=time.perf_counter() - t0)
143
  _memory_set(key, value, ttl)
144
 
145
 
tests/test_cache_circuit.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import time
3
+ import unittest
4
+ from unittest.mock import AsyncMock, patch
5
+
6
+ from app.utils import cache
7
+ from app.utils.cache import CircuitBreaker, get_cache, set_cache
8
+
9
+
10
+ class CircuitBreakerLogicTests(unittest.TestCase):
11
+ """Pure state machine, no I/O."""
12
+
13
+ def test_closed_initially_allows_traffic(self):
14
+ b = CircuitBreaker(failure_threshold=3, cooldown_seconds=30)
15
+ self.assertTrue(b.allow())
16
+
17
+ def test_opens_after_consecutive_failures(self):
18
+ b = CircuitBreaker(failure_threshold=3, cooldown_seconds=30)
19
+ for _ in range(3):
20
+ b.record(success=False, duration=2.5)
21
+ self.assertFalse(b.allow(), "circuit must open after threshold failures")
22
+
23
+ def test_success_resets_the_failure_count(self):
24
+ b = CircuitBreaker(failure_threshold=3, cooldown_seconds=30)
25
+ b.record(success=False, duration=2.5)
26
+ b.record(success=False, duration=2.5)
27
+ b.record(success=True, duration=0.05) # healthy again
28
+ b.record(success=False, duration=2.5)
29
+ self.assertTrue(b.allow(), "one success must clear prior failures")
30
+
31
+ def test_slow_op_counts_as_a_failure(self):
32
+ # A 2.5s op that eventually succeeds is still a latency failure here.
33
+ b = CircuitBreaker(failure_threshold=2, cooldown_seconds=30,
34
+ slow_threshold=1.0)
35
+ b.record(success=True, duration=2.5)
36
+ b.record(success=True, duration=2.5)
37
+ self.assertFalse(b.allow())
38
+
39
+ def test_half_open_after_cooldown(self):
40
+ b = CircuitBreaker(failure_threshold=1, cooldown_seconds=0.05)
41
+ b.record(success=False, duration=2.5)
42
+ self.assertFalse(b.allow())
43
+ time.sleep(0.06)
44
+ self.assertTrue(b.allow(), "cooldown expiry must allow a probe")
45
+
46
+
47
+ class CacheCircuitTests(unittest.IsolatedAsyncioTestCase):
48
+ """The cache must fail FAST to memory when Redis is slow, not per-call."""
49
+
50
+ async def test_slow_redis_does_not_stall_every_call(self):
51
+ cache._redis_client = None
52
+ cache._circuit.reset()
53
+
54
+ class SlowRedis:
55
+ async def get(self, key):
56
+ await asyncio.sleep(2.0)
57
+ return None
58
+
59
+ async def setex(self, key, ttl, value):
60
+ await asyncio.sleep(2.0)
61
+
62
+ with patch.object(cache, "get_redis", AsyncMock(return_value=SlowRedis())):
63
+ t0 = time.perf_counter()
64
+ for _ in range(5):
65
+ await get_cache("some:key")
66
+ first = time.perf_counter() - t0
67
+ # Circuit opens after threshold -> later calls skip Redis entirely.
68
+ for _ in range(5):
69
+ await get_cache("some:key")
70
+ later = time.perf_counter() - t0 - first
71
+
72
+ self.assertLess(
73
+ later, 1.0,
74
+ f"open circuit still paid Redis latency ({later:.2f}s for 5 calls)",
75
+ )
76
+
77
+ async def test_falls_back_to_memory_when_circuit_open(self):
78
+ cache._circuit.reset()
79
+ # Trip the breaker at the default threshold of 3.
80
+ for _ in range(3):
81
+ cache._circuit.record(success=False, duration=2.5)
82
+ self.assertFalse(cache._circuit.allow(), "circuit should be open")
83
+
84
+ with patch.object(cache, "get_redis",
85
+ AsyncMock(side_effect=AssertionError("must not be called"))):
86
+ await set_cache("mem:key", "value", 60)
87
+ got = await get_cache("mem:key")
88
+ self.assertEqual(got, "value", "memory fallback must still work")
89
+
90
+ async def test_healthy_redis_is_used_normally(self):
91
+ cache._redis_client = "sentinel"
92
+ cache._circuit.reset()
93
+
94
+ class FastRedis:
95
+ def __init__(self):
96
+ self.store = {}
97
+
98
+ async def get(self, key):
99
+ return self.store.get(key)
100
+
101
+ async def setex(self, key, ttl, value):
102
+ self.store[key] = value
103
+
104
+ fast = FastRedis()
105
+ with patch.object(cache, "get_redis", AsyncMock(return_value=fast)):
106
+ await set_cache("fast:key", "v1", 60)
107
+ got = await get_cache("fast:key")
108
+ self.assertEqual(got, "v1")
109
+ self.assertTrue(cache._circuit.allow())
110
+
111
+ async def tearDown(self):
112
+ cache._redis_client = None
113
+ cache._circuit.reset()
114
+
115
+
116
+ if __name__ == "__main__":
117
+ unittest.main()