test_lrucache.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import List
  15. from unittest.mock import Mock, patch
  16. from synapse.metrics.jemalloc import JemallocStats
  17. from synapse.util.caches.lrucache import LruCache, setup_expire_lru_cache_entries
  18. from synapse.util.caches.treecache import TreeCache
  19. from tests import unittest
  20. from tests.unittest import override_config
  21. class LruCacheTestCase(unittest.HomeserverTestCase):
  22. def test_get_set(self):
  23. cache = LruCache(1)
  24. cache["key"] = "value"
  25. self.assertEqual(cache.get("key"), "value")
  26. self.assertEqual(cache["key"], "value")
  27. def test_eviction(self):
  28. cache = LruCache(2)
  29. cache[1] = 1
  30. cache[2] = 2
  31. self.assertEqual(cache.get(1), 1)
  32. self.assertEqual(cache.get(2), 2)
  33. cache[3] = 3
  34. self.assertEqual(cache.get(1), None)
  35. self.assertEqual(cache.get(2), 2)
  36. self.assertEqual(cache.get(3), 3)
  37. def test_setdefault(self):
  38. cache = LruCache(1)
  39. self.assertEqual(cache.setdefault("key", 1), 1)
  40. self.assertEqual(cache.get("key"), 1)
  41. self.assertEqual(cache.setdefault("key", 2), 1)
  42. self.assertEqual(cache.get("key"), 1)
  43. cache["key"] = 2 # Make sure overriding works.
  44. self.assertEqual(cache.get("key"), 2)
  45. def test_pop(self):
  46. cache = LruCache(1)
  47. cache["key"] = 1
  48. self.assertEqual(cache.pop("key"), 1)
  49. self.assertEqual(cache.pop("key"), None)
  50. def test_del_multi(self):
  51. cache = LruCache(4, cache_type=TreeCache)
  52. cache[("animal", "cat")] = "mew"
  53. cache[("animal", "dog")] = "woof"
  54. cache[("vehicles", "car")] = "vroom"
  55. cache[("vehicles", "train")] = "chuff"
  56. self.assertEqual(len(cache), 4)
  57. self.assertEqual(cache.get(("animal", "cat")), "mew")
  58. self.assertEqual(cache.get(("vehicles", "car")), "vroom")
  59. cache.del_multi(("animal",))
  60. self.assertEqual(len(cache), 2)
  61. self.assertEqual(cache.get(("animal", "cat")), None)
  62. self.assertEqual(cache.get(("animal", "dog")), None)
  63. self.assertEqual(cache.get(("vehicles", "car")), "vroom")
  64. self.assertEqual(cache.get(("vehicles", "train")), "chuff")
  65. # Man from del_multi say "Yes".
  66. def test_clear(self):
  67. cache = LruCache(1)
  68. cache["key"] = 1
  69. cache.clear()
  70. self.assertEqual(len(cache), 0)
  71. @override_config({"caches": {"per_cache_factors": {"mycache": 10}}})
  72. def test_special_size(self):
  73. cache = LruCache(10, "mycache")
  74. self.assertEqual(cache.max_size, 100)
  75. class LruCacheCallbacksTestCase(unittest.HomeserverTestCase):
  76. def test_get(self):
  77. m = Mock()
  78. cache = LruCache(1)
  79. cache.set("key", "value")
  80. self.assertFalse(m.called)
  81. cache.get("key", callbacks=[m])
  82. self.assertFalse(m.called)
  83. cache.get("key", "value")
  84. self.assertFalse(m.called)
  85. cache.set("key", "value2")
  86. self.assertEqual(m.call_count, 1)
  87. cache.set("key", "value")
  88. self.assertEqual(m.call_count, 1)
  89. def test_multi_get(self):
  90. m = Mock()
  91. cache = LruCache(1)
  92. cache.set("key", "value")
  93. self.assertFalse(m.called)
  94. cache.get("key", callbacks=[m])
  95. self.assertFalse(m.called)
  96. cache.get("key", callbacks=[m])
  97. self.assertFalse(m.called)
  98. cache.set("key", "value2")
  99. self.assertEqual(m.call_count, 1)
  100. cache.set("key", "value")
  101. self.assertEqual(m.call_count, 1)
  102. def test_set(self):
  103. m = Mock()
  104. cache = LruCache(1)
  105. cache.set("key", "value", callbacks=[m])
  106. self.assertFalse(m.called)
  107. cache.set("key", "value")
  108. self.assertFalse(m.called)
  109. cache.set("key", "value2")
  110. self.assertEqual(m.call_count, 1)
  111. cache.set("key", "value")
  112. self.assertEqual(m.call_count, 1)
  113. def test_pop(self):
  114. m = Mock()
  115. cache = LruCache(1)
  116. cache.set("key", "value", callbacks=[m])
  117. self.assertFalse(m.called)
  118. cache.pop("key")
  119. self.assertEqual(m.call_count, 1)
  120. cache.set("key", "value")
  121. self.assertEqual(m.call_count, 1)
  122. cache.pop("key")
  123. self.assertEqual(m.call_count, 1)
  124. def test_del_multi(self):
  125. m1 = Mock()
  126. m2 = Mock()
  127. m3 = Mock()
  128. m4 = Mock()
  129. cache = LruCache(4, cache_type=TreeCache)
  130. cache.set(("a", "1"), "value", callbacks=[m1])
  131. cache.set(("a", "2"), "value", callbacks=[m2])
  132. cache.set(("b", "1"), "value", callbacks=[m3])
  133. cache.set(("b", "2"), "value", callbacks=[m4])
  134. self.assertEqual(m1.call_count, 0)
  135. self.assertEqual(m2.call_count, 0)
  136. self.assertEqual(m3.call_count, 0)
  137. self.assertEqual(m4.call_count, 0)
  138. cache.del_multi(("a",))
  139. self.assertEqual(m1.call_count, 1)
  140. self.assertEqual(m2.call_count, 1)
  141. self.assertEqual(m3.call_count, 0)
  142. self.assertEqual(m4.call_count, 0)
  143. def test_clear(self):
  144. m1 = Mock()
  145. m2 = Mock()
  146. cache = LruCache(5)
  147. cache.set("key1", "value", callbacks=[m1])
  148. cache.set("key2", "value", callbacks=[m2])
  149. self.assertEqual(m1.call_count, 0)
  150. self.assertEqual(m2.call_count, 0)
  151. cache.clear()
  152. self.assertEqual(m1.call_count, 1)
  153. self.assertEqual(m2.call_count, 1)
  154. def test_eviction(self):
  155. m1 = Mock(name="m1")
  156. m2 = Mock(name="m2")
  157. m3 = Mock(name="m3")
  158. cache = LruCache(2)
  159. cache.set("key1", "value", callbacks=[m1])
  160. cache.set("key2", "value", callbacks=[m2])
  161. self.assertEqual(m1.call_count, 0)
  162. self.assertEqual(m2.call_count, 0)
  163. self.assertEqual(m3.call_count, 0)
  164. cache.set("key3", "value", callbacks=[m3])
  165. self.assertEqual(m1.call_count, 1)
  166. self.assertEqual(m2.call_count, 0)
  167. self.assertEqual(m3.call_count, 0)
  168. cache.set("key3", "value")
  169. self.assertEqual(m1.call_count, 1)
  170. self.assertEqual(m2.call_count, 0)
  171. self.assertEqual(m3.call_count, 0)
  172. cache.get("key2")
  173. self.assertEqual(m1.call_count, 1)
  174. self.assertEqual(m2.call_count, 0)
  175. self.assertEqual(m3.call_count, 0)
  176. cache.set("key1", "value", callbacks=[m1])
  177. self.assertEqual(m1.call_count, 1)
  178. self.assertEqual(m2.call_count, 0)
  179. self.assertEqual(m3.call_count, 1)
  180. class LruCacheSizedTestCase(unittest.HomeserverTestCase):
  181. def test_evict(self):
  182. cache = LruCache(5, size_callback=len)
  183. cache["key1"] = [0]
  184. cache["key2"] = [1, 2]
  185. cache["key3"] = [3]
  186. cache["key4"] = [4]
  187. self.assertEqual(cache["key1"], [0])
  188. self.assertEqual(cache["key2"], [1, 2])
  189. self.assertEqual(cache["key3"], [3])
  190. self.assertEqual(cache["key4"], [4])
  191. self.assertEqual(len(cache), 5)
  192. cache["key5"] = [5, 6]
  193. self.assertEqual(len(cache), 4)
  194. self.assertEqual(cache.get("key1"), None)
  195. self.assertEqual(cache.get("key2"), None)
  196. self.assertEqual(cache["key3"], [3])
  197. self.assertEqual(cache["key4"], [4])
  198. self.assertEqual(cache["key5"], [5, 6])
  199. def test_zero_size_drop_from_cache(self) -> None:
  200. """Test that `drop_from_cache` works correctly with 0-sized entries."""
  201. cache: LruCache[str, List[int]] = LruCache(5, size_callback=lambda x: 0)
  202. cache["key1"] = []
  203. self.assertEqual(len(cache), 0)
  204. cache.cache["key1"].drop_from_cache()
  205. self.assertIsNone(
  206. cache.pop("key1"), "Cache entry should have been evicted but wasn't"
  207. )
  208. class TimeEvictionTestCase(unittest.HomeserverTestCase):
  209. """Test that time based eviction works correctly."""
  210. def default_config(self):
  211. config = super().default_config()
  212. config.setdefault("caches", {})["expiry_time"] = "30m"
  213. return config
  214. def test_evict(self):
  215. setup_expire_lru_cache_entries(self.hs)
  216. cache = LruCache(5, clock=self.hs.get_clock())
  217. # Check that we evict entries we haven't accessed for 30 minutes.
  218. cache["key1"] = 1
  219. cache["key2"] = 2
  220. self.reactor.advance(20 * 60)
  221. self.assertEqual(cache.get("key1"), 1)
  222. self.reactor.advance(20 * 60)
  223. # We have only touched `key1` in the last 30m, so we expect that to
  224. # still be in the cache while `key2` should have been evicted.
  225. self.assertEqual(cache.get("key1"), 1)
  226. self.assertEqual(cache.get("key2"), None)
  227. # Check that re-adding an expired key works correctly.
  228. cache["key2"] = 3
  229. self.assertEqual(cache.get("key2"), 3)
  230. self.reactor.advance(20 * 60)
  231. self.assertEqual(cache.get("key2"), 3)
  232. self.reactor.advance(20 * 60)
  233. self.assertEqual(cache.get("key1"), None)
  234. self.assertEqual(cache.get("key2"), 3)
  235. class MemoryEvictionTestCase(unittest.HomeserverTestCase):
  236. @override_config(
  237. {
  238. "caches": {
  239. "cache_autotuning": {
  240. "max_cache_memory_usage": "700M",
  241. "target_cache_memory_usage": "500M",
  242. "min_cache_ttl": "5m",
  243. }
  244. }
  245. }
  246. )
  247. @patch("synapse.util.caches.lrucache.get_jemalloc_stats")
  248. def test_evict_memory(self, jemalloc_interface) -> None:
  249. mock_jemalloc_class = Mock(spec=JemallocStats)
  250. jemalloc_interface.return_value = mock_jemalloc_class
  251. # set the return value of get_stat() to be greater than max_cache_memory_usage
  252. mock_jemalloc_class.get_stat.return_value = 924288000
  253. setup_expire_lru_cache_entries(self.hs)
  254. cache = LruCache(4, clock=self.hs.get_clock())
  255. cache["key1"] = 1
  256. cache["key2"] = 2
  257. # advance the reactor less than the min_cache_ttl
  258. self.reactor.advance(60 * 2)
  259. # our items should still be in the cache
  260. self.assertEqual(cache.get("key1"), 1)
  261. self.assertEqual(cache.get("key2"), 2)
  262. # advance the reactor past the min_cache_ttl
  263. self.reactor.advance(60 * 6)
  264. # the items should be cleared from cache
  265. self.assertEqual(cache.get("key1"), None)
  266. self.assertEqual(cache.get("key2"), None)
  267. # add more stuff to caches
  268. cache["key1"] = 1
  269. cache["key2"] = 2
  270. # set the return value of get_stat() to be lower than target_cache_memory_usage
  271. mock_jemalloc_class.get_stat.return_value = 10000
  272. # advance the reactor past the min_cache_ttl
  273. self.reactor.advance(60 * 6)
  274. # the items should still be in the cache
  275. self.assertEqual(cache.get("key1"), 1)
  276. self.assertEqual(cache.get("key2"), 2)