test_cleanup_extrems.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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. import os.path
  15. from unittest.mock import Mock, patch
  16. import synapse.rest.admin
  17. from synapse.api.constants import EventTypes
  18. from synapse.rest.client.v1 import login, room
  19. from synapse.storage import prepare_database
  20. from synapse.types import UserID, create_requester
  21. from tests.unittest import HomeserverTestCase
  22. class CleanupExtremBackgroundUpdateStoreTestCase(HomeserverTestCase):
  23. """
  24. Test the background update to clean forward extremities table.
  25. """
  26. def prepare(self, reactor, clock, homeserver):
  27. self.store = homeserver.get_datastore()
  28. self.room_creator = homeserver.get_room_creation_handler()
  29. # Create a test user and room
  30. self.user = UserID("alice", "test")
  31. self.requester = create_requester(self.user)
  32. info, _ = self.get_success(self.room_creator.create_room(self.requester, {}))
  33. self.room_id = info["room_id"]
  34. def run_background_update(self):
  35. """Re run the background update to clean up the extremities."""
  36. # Make sure we don't clash with in progress updates.
  37. self.assertTrue(
  38. self.store.db_pool.updates._all_done, "Background updates are still ongoing"
  39. )
  40. schema_path = os.path.join(
  41. prepare_database.schema_path,
  42. "main",
  43. "delta",
  44. "54",
  45. "delete_forward_extremities.sql",
  46. )
  47. def run_delta_file(txn):
  48. prepare_database.executescript(txn, schema_path)
  49. self.get_success(
  50. self.store.db_pool.runInteraction(
  51. "test_delete_forward_extremities", run_delta_file
  52. )
  53. )
  54. # Ugh, have to reset this flag
  55. self.store.db_pool.updates._all_done = False
  56. while not self.get_success(
  57. self.store.db_pool.updates.has_completed_background_updates()
  58. ):
  59. self.get_success(
  60. self.store.db_pool.updates.do_next_background_update(100), by=0.1
  61. )
  62. def test_soft_failed_extremities_handled_correctly(self):
  63. """Test that extremities are correctly calculated in the presence of
  64. soft failed events.
  65. Tests a graph like:
  66. A <- SF1 <- SF2 <- B
  67. Where SF* are soft failed.
  68. """
  69. # Create the room graph
  70. event_id_1 = self.create_and_send_event(self.room_id, self.user)
  71. event_id_2 = self.create_and_send_event(
  72. self.room_id, self.user, True, [event_id_1]
  73. )
  74. event_id_3 = self.create_and_send_event(
  75. self.room_id, self.user, True, [event_id_2]
  76. )
  77. event_id_4 = self.create_and_send_event(
  78. self.room_id, self.user, False, [event_id_3]
  79. )
  80. # Check the latest events are as expected
  81. latest_event_ids = self.get_success(
  82. self.store.get_latest_event_ids_in_room(self.room_id)
  83. )
  84. self.assertEqual(latest_event_ids, [event_id_4])
  85. def test_basic_cleanup(self):
  86. """Test that extremities are correctly calculated in the presence of
  87. soft failed events.
  88. Tests a graph like:
  89. A <- SF1 <- B
  90. Where SF* are soft failed, and with extremities of A and B
  91. """
  92. # Create the room graph
  93. event_id_a = self.create_and_send_event(self.room_id, self.user)
  94. event_id_sf1 = self.create_and_send_event(
  95. self.room_id, self.user, True, [event_id_a]
  96. )
  97. event_id_b = self.create_and_send_event(
  98. self.room_id, self.user, False, [event_id_sf1]
  99. )
  100. # Add the new extremity and check the latest events are as expected
  101. self.add_extremity(self.room_id, event_id_a)
  102. latest_event_ids = self.get_success(
  103. self.store.get_latest_event_ids_in_room(self.room_id)
  104. )
  105. self.assertEqual(set(latest_event_ids), {event_id_a, event_id_b})
  106. # Run the background update and check it did the right thing
  107. self.run_background_update()
  108. latest_event_ids = self.get_success(
  109. self.store.get_latest_event_ids_in_room(self.room_id)
  110. )
  111. self.assertEqual(latest_event_ids, [event_id_b])
  112. def test_chain_of_fail_cleanup(self):
  113. """Test that extremities are correctly calculated in the presence of
  114. soft failed events.
  115. Tests a graph like:
  116. A <- SF1 <- SF2 <- B
  117. Where SF* are soft failed, and with extremities of A and B
  118. """
  119. # Create the room graph
  120. event_id_a = self.create_and_send_event(self.room_id, self.user)
  121. event_id_sf1 = self.create_and_send_event(
  122. self.room_id, self.user, True, [event_id_a]
  123. )
  124. event_id_sf2 = self.create_and_send_event(
  125. self.room_id, self.user, True, [event_id_sf1]
  126. )
  127. event_id_b = self.create_and_send_event(
  128. self.room_id, self.user, False, [event_id_sf2]
  129. )
  130. # Add the new extremity and check the latest events are as expected
  131. self.add_extremity(self.room_id, event_id_a)
  132. latest_event_ids = self.get_success(
  133. self.store.get_latest_event_ids_in_room(self.room_id)
  134. )
  135. self.assertEqual(set(latest_event_ids), {event_id_a, event_id_b})
  136. # Run the background update and check it did the right thing
  137. self.run_background_update()
  138. latest_event_ids = self.get_success(
  139. self.store.get_latest_event_ids_in_room(self.room_id)
  140. )
  141. self.assertEqual(latest_event_ids, [event_id_b])
  142. def test_forked_graph_cleanup(self):
  143. r"""Test that extremities are correctly calculated in the presence of
  144. soft failed events.
  145. Tests a graph like, where time flows down the page:
  146. A B
  147. / \ /
  148. / \ /
  149. SF1 SF2
  150. | |
  151. SF3 |
  152. / \ |
  153. | \ |
  154. C SF4
  155. Where SF* are soft failed, and with them A, B and C marked as
  156. extremities. This should resolve to B and C being marked as extremity.
  157. """
  158. # Create the room graph
  159. event_id_a = self.create_and_send_event(self.room_id, self.user)
  160. event_id_b = self.create_and_send_event(self.room_id, self.user)
  161. event_id_sf1 = self.create_and_send_event(
  162. self.room_id, self.user, True, [event_id_a]
  163. )
  164. event_id_sf2 = self.create_and_send_event(
  165. self.room_id, self.user, True, [event_id_a, event_id_b]
  166. )
  167. event_id_sf3 = self.create_and_send_event(
  168. self.room_id, self.user, True, [event_id_sf1]
  169. )
  170. self.create_and_send_event(
  171. self.room_id, self.user, True, [event_id_sf2, event_id_sf3]
  172. ) # SF4
  173. event_id_c = self.create_and_send_event(
  174. self.room_id, self.user, False, [event_id_sf3]
  175. )
  176. # Add the new extremity and check the latest events are as expected
  177. self.add_extremity(self.room_id, event_id_a)
  178. latest_event_ids = self.get_success(
  179. self.store.get_latest_event_ids_in_room(self.room_id)
  180. )
  181. self.assertEqual(set(latest_event_ids), {event_id_a, event_id_b, event_id_c})
  182. # Run the background update and check it did the right thing
  183. self.run_background_update()
  184. latest_event_ids = self.get_success(
  185. self.store.get_latest_event_ids_in_room(self.room_id)
  186. )
  187. self.assertEqual(set(latest_event_ids), {event_id_b, event_id_c})
  188. class CleanupExtremDummyEventsTestCase(HomeserverTestCase):
  189. CONSENT_VERSION = "1"
  190. EXTREMITIES_COUNT = 50
  191. servlets = [
  192. synapse.rest.admin.register_servlets_for_client_rest_resource,
  193. login.register_servlets,
  194. room.register_servlets,
  195. ]
  196. def make_homeserver(self, reactor, clock):
  197. config = self.default_config()
  198. config["cleanup_extremities_with_dummy_events"] = True
  199. return self.setup_test_homeserver(config=config)
  200. def prepare(self, reactor, clock, homeserver):
  201. self.store = homeserver.get_datastore()
  202. self.room_creator = homeserver.get_room_creation_handler()
  203. self.event_creator_handler = homeserver.get_event_creation_handler()
  204. # Create a test user and room
  205. self.user = UserID.from_string(self.register_user("user1", "password"))
  206. self.token1 = self.login("user1", "password")
  207. self.requester = create_requester(self.user)
  208. info, _ = self.get_success(self.room_creator.create_room(self.requester, {}))
  209. self.room_id = info["room_id"]
  210. self.event_creator = homeserver.get_event_creation_handler()
  211. homeserver.config.user_consent_version = self.CONSENT_VERSION
  212. def test_send_dummy_event(self):
  213. self._create_extremity_rich_graph()
  214. # Pump the reactor repeatedly so that the background updates have a
  215. # chance to run.
  216. self.pump(20)
  217. latest_event_ids = self.get_success(
  218. self.store.get_latest_event_ids_in_room(self.room_id)
  219. )
  220. self.assertTrue(len(latest_event_ids) < 10, len(latest_event_ids))
  221. @patch("synapse.handlers.message._DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY", new=0)
  222. def test_send_dummy_events_when_insufficient_power(self):
  223. self._create_extremity_rich_graph()
  224. # Criple power levels
  225. self.helper.send_state(
  226. self.room_id,
  227. EventTypes.PowerLevels,
  228. body={"users": {str(self.user): -1}},
  229. tok=self.token1,
  230. )
  231. # Pump the reactor repeatedly so that the background updates have a
  232. # chance to run.
  233. self.pump(10 * 60)
  234. latest_event_ids = self.get_success(
  235. self.store.get_latest_event_ids_in_room(self.room_id)
  236. )
  237. # Check that the room has not been pruned
  238. self.assertTrue(len(latest_event_ids) > 10)
  239. # New user with regular levels
  240. user2 = self.register_user("user2", "password")
  241. token2 = self.login("user2", "password")
  242. self.helper.join(self.room_id, user2, tok=token2)
  243. self.pump(10 * 60)
  244. latest_event_ids = self.get_success(
  245. self.store.get_latest_event_ids_in_room(self.room_id)
  246. )
  247. self.assertTrue(len(latest_event_ids) < 10, len(latest_event_ids))
  248. @patch("synapse.handlers.message._DUMMY_EVENT_ROOM_EXCLUSION_EXPIRY", new=250)
  249. def test_expiry_logic(self):
  250. """Simple test to ensure that _expire_rooms_to_exclude_from_dummy_event_insertion()
  251. expires old entries correctly.
  252. """
  253. self.event_creator_handler._rooms_to_exclude_from_dummy_event_insertion[
  254. "1"
  255. ] = 100000
  256. self.event_creator_handler._rooms_to_exclude_from_dummy_event_insertion[
  257. "2"
  258. ] = 200000
  259. self.event_creator_handler._rooms_to_exclude_from_dummy_event_insertion[
  260. "3"
  261. ] = 300000
  262. self.event_creator_handler._expire_rooms_to_exclude_from_dummy_event_insertion()
  263. # All entries within time frame
  264. self.assertEqual(
  265. len(
  266. self.event_creator_handler._rooms_to_exclude_from_dummy_event_insertion
  267. ),
  268. 3,
  269. )
  270. # Oldest room to expire
  271. self.pump(1.01)
  272. self.event_creator_handler._expire_rooms_to_exclude_from_dummy_event_insertion()
  273. self.assertEqual(
  274. len(
  275. self.event_creator_handler._rooms_to_exclude_from_dummy_event_insertion
  276. ),
  277. 2,
  278. )
  279. # All rooms to expire
  280. self.pump(2)
  281. self.assertEqual(
  282. len(
  283. self.event_creator_handler._rooms_to_exclude_from_dummy_event_insertion
  284. ),
  285. 0,
  286. )
  287. def _create_extremity_rich_graph(self):
  288. """Helper method to create bushy graph on demand"""
  289. event_id_start = self.create_and_send_event(self.room_id, self.user)
  290. for _ in range(self.EXTREMITIES_COUNT):
  291. self.create_and_send_event(
  292. self.room_id, self.user, prev_event_ids=[event_id_start]
  293. )
  294. latest_event_ids = self.get_success(
  295. self.store.get_latest_event_ids_in_room(self.room_id)
  296. )
  297. self.assertEqual(len(latest_event_ids), 50)
  298. def _enable_consent_checking(self):
  299. """Helper method to enable consent checking"""
  300. self.event_creator._block_events_without_consent_error = "No consent from user"
  301. consent_uri_builder = Mock()
  302. consent_uri_builder.build_user_consent_uri.return_value = "http://example.com"
  303. self.event_creator._consent_uri_builder = consent_uri_builder