test_cleanup_extrems.py 14 KB

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