1
0

test_cleanup_extrems.py 14 KB

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