1
0

test_event_chain.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. # Copyright 2020 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. from typing import Dict, List, Set, Tuple, cast
  15. from twisted.test.proto_helpers import MemoryReactor
  16. from twisted.trial import unittest
  17. from synapse.api.constants import EventTypes
  18. from synapse.api.room_versions import RoomVersions
  19. from synapse.events import EventBase
  20. from synapse.events.snapshot import EventContext
  21. from synapse.rest import admin
  22. from synapse.rest.client import login, room
  23. from synapse.server import HomeServer
  24. from synapse.storage.database import LoggingTransaction
  25. from synapse.storage.databases.main.events import _LinkMap
  26. from synapse.storage.types import Cursor
  27. from synapse.types import create_requester
  28. from synapse.util import Clock
  29. from tests.unittest import HomeserverTestCase
  30. class EventChainStoreTestCase(HomeserverTestCase):
  31. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  32. self.store = hs.get_datastores().main
  33. self._next_stream_ordering = 1
  34. def test_simple(self) -> None:
  35. """Test that the example in `docs/auth_chain_difference_algorithm.md`
  36. works.
  37. """
  38. event_factory = self.hs.get_event_builder_factory()
  39. bob = "@creator:test"
  40. alice = "@alice:test"
  41. room_id = "!room:test"
  42. # Ensure that we have a rooms entry so that we generate the chain index.
  43. self.get_success(
  44. self.store.store_room(
  45. room_id=room_id,
  46. room_creator_user_id="",
  47. is_public=True,
  48. room_version=RoomVersions.V6,
  49. )
  50. )
  51. create = self.get_success(
  52. event_factory.for_room_version(
  53. RoomVersions.V6,
  54. {
  55. "type": EventTypes.Create,
  56. "state_key": "",
  57. "sender": bob,
  58. "room_id": room_id,
  59. "content": {"tag": "create"},
  60. },
  61. ).build(prev_event_ids=[], auth_event_ids=[])
  62. )
  63. bob_join = self.get_success(
  64. event_factory.for_room_version(
  65. RoomVersions.V6,
  66. {
  67. "type": EventTypes.Member,
  68. "state_key": bob,
  69. "sender": bob,
  70. "room_id": room_id,
  71. "content": {"tag": "bob_join"},
  72. },
  73. ).build(prev_event_ids=[], auth_event_ids=[create.event_id])
  74. )
  75. power = self.get_success(
  76. event_factory.for_room_version(
  77. RoomVersions.V6,
  78. {
  79. "type": EventTypes.PowerLevels,
  80. "state_key": "",
  81. "sender": bob,
  82. "room_id": room_id,
  83. "content": {"tag": "power"},
  84. },
  85. ).build(
  86. prev_event_ids=[],
  87. auth_event_ids=[create.event_id, bob_join.event_id],
  88. )
  89. )
  90. alice_invite = self.get_success(
  91. event_factory.for_room_version(
  92. RoomVersions.V6,
  93. {
  94. "type": EventTypes.Member,
  95. "state_key": alice,
  96. "sender": bob,
  97. "room_id": room_id,
  98. "content": {"tag": "alice_invite"},
  99. },
  100. ).build(
  101. prev_event_ids=[],
  102. auth_event_ids=[create.event_id, bob_join.event_id, power.event_id],
  103. )
  104. )
  105. alice_join = self.get_success(
  106. event_factory.for_room_version(
  107. RoomVersions.V6,
  108. {
  109. "type": EventTypes.Member,
  110. "state_key": alice,
  111. "sender": alice,
  112. "room_id": room_id,
  113. "content": {"tag": "alice_join"},
  114. },
  115. ).build(
  116. prev_event_ids=[],
  117. auth_event_ids=[create.event_id, alice_invite.event_id, power.event_id],
  118. )
  119. )
  120. power_2 = self.get_success(
  121. event_factory.for_room_version(
  122. RoomVersions.V6,
  123. {
  124. "type": EventTypes.PowerLevels,
  125. "state_key": "",
  126. "sender": bob,
  127. "room_id": room_id,
  128. "content": {"tag": "power_2"},
  129. },
  130. ).build(
  131. prev_event_ids=[],
  132. auth_event_ids=[create.event_id, bob_join.event_id, power.event_id],
  133. )
  134. )
  135. bob_join_2 = self.get_success(
  136. event_factory.for_room_version(
  137. RoomVersions.V6,
  138. {
  139. "type": EventTypes.Member,
  140. "state_key": bob,
  141. "sender": bob,
  142. "room_id": room_id,
  143. "content": {"tag": "bob_join_2"},
  144. },
  145. ).build(
  146. prev_event_ids=[],
  147. auth_event_ids=[create.event_id, bob_join.event_id, power.event_id],
  148. )
  149. )
  150. alice_join2 = self.get_success(
  151. event_factory.for_room_version(
  152. RoomVersions.V6,
  153. {
  154. "type": EventTypes.Member,
  155. "state_key": alice,
  156. "sender": alice,
  157. "room_id": room_id,
  158. "content": {"tag": "alice_join2"},
  159. },
  160. ).build(
  161. prev_event_ids=[],
  162. auth_event_ids=[
  163. create.event_id,
  164. alice_join.event_id,
  165. power_2.event_id,
  166. ],
  167. )
  168. )
  169. events = [
  170. create,
  171. bob_join,
  172. power,
  173. alice_invite,
  174. alice_join,
  175. bob_join_2,
  176. power_2,
  177. alice_join2,
  178. ]
  179. expected_links = [
  180. (bob_join, create),
  181. (power, create),
  182. (power, bob_join),
  183. (alice_invite, create),
  184. (alice_invite, power),
  185. (alice_invite, bob_join),
  186. (bob_join_2, power),
  187. (alice_join2, power_2),
  188. ]
  189. self.persist(events)
  190. chain_map, link_map = self.fetch_chains(events)
  191. # Check that the expected links and only the expected links have been
  192. # added.
  193. self.assertEqual(len(expected_links), len(list(link_map.get_additions())))
  194. for start, end in expected_links:
  195. start_id, start_seq = chain_map[start.event_id]
  196. end_id, end_seq = chain_map[end.event_id]
  197. self.assertIn(
  198. (start_seq, end_seq), list(link_map.get_links_between(start_id, end_id))
  199. )
  200. # Test that everything can reach the create event, but the create event
  201. # can't reach anything.
  202. for event in events[1:]:
  203. self.assertTrue(
  204. link_map.exists_path_from(
  205. chain_map[event.event_id], chain_map[create.event_id]
  206. ),
  207. )
  208. self.assertFalse(
  209. link_map.exists_path_from(
  210. chain_map[create.event_id],
  211. chain_map[event.event_id],
  212. ),
  213. )
  214. def test_out_of_order_events(self) -> None:
  215. """Test that we handle persisting events that we don't have the full
  216. auth chain for yet (which should only happen for out of band memberships).
  217. """
  218. event_factory = self.hs.get_event_builder_factory()
  219. bob = "@creator:test"
  220. alice = "@alice:test"
  221. room_id = "!room:test"
  222. # Ensure that we have a rooms entry so that we generate the chain index.
  223. self.get_success(
  224. self.store.store_room(
  225. room_id=room_id,
  226. room_creator_user_id="",
  227. is_public=True,
  228. room_version=RoomVersions.V6,
  229. )
  230. )
  231. # First persist the base room.
  232. create = self.get_success(
  233. event_factory.for_room_version(
  234. RoomVersions.V6,
  235. {
  236. "type": EventTypes.Create,
  237. "state_key": "",
  238. "sender": bob,
  239. "room_id": room_id,
  240. "content": {"tag": "create"},
  241. },
  242. ).build(prev_event_ids=[], auth_event_ids=[])
  243. )
  244. bob_join = self.get_success(
  245. event_factory.for_room_version(
  246. RoomVersions.V6,
  247. {
  248. "type": EventTypes.Member,
  249. "state_key": bob,
  250. "sender": bob,
  251. "room_id": room_id,
  252. "content": {"tag": "bob_join"},
  253. },
  254. ).build(prev_event_ids=[], auth_event_ids=[create.event_id])
  255. )
  256. power = self.get_success(
  257. event_factory.for_room_version(
  258. RoomVersions.V6,
  259. {
  260. "type": EventTypes.PowerLevels,
  261. "state_key": "",
  262. "sender": bob,
  263. "room_id": room_id,
  264. "content": {"tag": "power"},
  265. },
  266. ).build(
  267. prev_event_ids=[],
  268. auth_event_ids=[create.event_id, bob_join.event_id],
  269. )
  270. )
  271. self.persist([create, bob_join, power])
  272. # Now persist an invite and a couple of memberships out of order.
  273. alice_invite = self.get_success(
  274. event_factory.for_room_version(
  275. RoomVersions.V6,
  276. {
  277. "type": EventTypes.Member,
  278. "state_key": alice,
  279. "sender": bob,
  280. "room_id": room_id,
  281. "content": {"tag": "alice_invite"},
  282. },
  283. ).build(
  284. prev_event_ids=[],
  285. auth_event_ids=[create.event_id, bob_join.event_id, power.event_id],
  286. )
  287. )
  288. alice_join = self.get_success(
  289. event_factory.for_room_version(
  290. RoomVersions.V6,
  291. {
  292. "type": EventTypes.Member,
  293. "state_key": alice,
  294. "sender": alice,
  295. "room_id": room_id,
  296. "content": {"tag": "alice_join"},
  297. },
  298. ).build(
  299. prev_event_ids=[],
  300. auth_event_ids=[create.event_id, alice_invite.event_id, power.event_id],
  301. )
  302. )
  303. alice_join2 = self.get_success(
  304. event_factory.for_room_version(
  305. RoomVersions.V6,
  306. {
  307. "type": EventTypes.Member,
  308. "state_key": alice,
  309. "sender": alice,
  310. "room_id": room_id,
  311. "content": {"tag": "alice_join2"},
  312. },
  313. ).build(
  314. prev_event_ids=[],
  315. auth_event_ids=[create.event_id, alice_join.event_id, power.event_id],
  316. )
  317. )
  318. self.persist([alice_join])
  319. self.persist([alice_join2])
  320. self.persist([alice_invite])
  321. # The end result should be sane.
  322. events = [create, bob_join, power, alice_invite, alice_join]
  323. chain_map, link_map = self.fetch_chains(events)
  324. expected_links = [
  325. (bob_join, create),
  326. (power, create),
  327. (power, bob_join),
  328. (alice_invite, create),
  329. (alice_invite, power),
  330. (alice_invite, bob_join),
  331. ]
  332. # Check that the expected links and only the expected links have been
  333. # added.
  334. self.assertEqual(len(expected_links), len(list(link_map.get_additions())))
  335. for start, end in expected_links:
  336. start_id, start_seq = chain_map[start.event_id]
  337. end_id, end_seq = chain_map[end.event_id]
  338. self.assertIn(
  339. (start_seq, end_seq), list(link_map.get_links_between(start_id, end_id))
  340. )
  341. def persist(
  342. self,
  343. events: List[EventBase],
  344. ) -> None:
  345. """Persist the given events and check that the links generated match
  346. those given.
  347. """
  348. persist_events_store = self.hs.get_datastores().persist_events
  349. assert persist_events_store is not None
  350. for e in events:
  351. e.internal_metadata.stream_ordering = self._next_stream_ordering
  352. self._next_stream_ordering += 1
  353. def _persist(txn: LoggingTransaction) -> None:
  354. # We need to persist the events to the events and state_events
  355. # tables.
  356. assert persist_events_store is not None
  357. persist_events_store._store_event_txn(
  358. txn,
  359. [
  360. (e, EventContext(self.hs.get_storage_controllers(), {}))
  361. for e in events
  362. ],
  363. )
  364. # Actually call the function that calculates the auth chain stuff.
  365. persist_events_store._persist_event_auth_chain_txn(txn, events)
  366. self.get_success(
  367. persist_events_store.db_pool.runInteraction(
  368. "_persist",
  369. _persist,
  370. )
  371. )
  372. def fetch_chains(
  373. self, events: List[EventBase]
  374. ) -> Tuple[Dict[str, Tuple[int, int]], _LinkMap]:
  375. # Fetch the map from event ID -> (chain ID, sequence number)
  376. rows = cast(
  377. List[Tuple[str, int, int]],
  378. self.get_success(
  379. self.store.db_pool.simple_select_many_batch(
  380. table="event_auth_chains",
  381. column="event_id",
  382. iterable=[e.event_id for e in events],
  383. retcols=("event_id", "chain_id", "sequence_number"),
  384. keyvalues={},
  385. )
  386. ),
  387. )
  388. chain_map = {
  389. event_id: (chain_id, sequence_number)
  390. for event_id, chain_id, sequence_number in rows
  391. }
  392. # Fetch all the links and pass them to the _LinkMap.
  393. auth_chain_rows = cast(
  394. List[Tuple[int, int, int, int]],
  395. self.get_success(
  396. self.store.db_pool.simple_select_many_batch(
  397. table="event_auth_chain_links",
  398. column="origin_chain_id",
  399. iterable=[chain_id for chain_id, _ in chain_map.values()],
  400. retcols=(
  401. "origin_chain_id",
  402. "origin_sequence_number",
  403. "target_chain_id",
  404. "target_sequence_number",
  405. ),
  406. keyvalues={},
  407. )
  408. ),
  409. )
  410. link_map = _LinkMap()
  411. for (
  412. origin_chain_id,
  413. origin_sequence_number,
  414. target_chain_id,
  415. target_sequence_number,
  416. ) in auth_chain_rows:
  417. added = link_map.add_link(
  418. (origin_chain_id, origin_sequence_number),
  419. (target_chain_id, target_sequence_number),
  420. )
  421. # We shouldn't have persisted any redundant links
  422. self.assertTrue(added)
  423. return chain_map, link_map
  424. class LinkMapTestCase(unittest.TestCase):
  425. def test_simple(self) -> None:
  426. """Basic tests for the LinkMap."""
  427. link_map = _LinkMap()
  428. link_map.add_link((1, 1), (2, 1), new=False)
  429. self.assertCountEqual(link_map.get_links_between(1, 2), [(1, 1)])
  430. self.assertCountEqual(link_map.get_links_from((1, 1)), [(2, 1)])
  431. self.assertCountEqual(link_map.get_additions(), [])
  432. self.assertTrue(link_map.exists_path_from((1, 5), (2, 1)))
  433. self.assertFalse(link_map.exists_path_from((1, 5), (2, 2)))
  434. self.assertTrue(link_map.exists_path_from((1, 5), (1, 1)))
  435. self.assertFalse(link_map.exists_path_from((1, 1), (1, 5)))
  436. # Attempting to add a redundant link is ignored.
  437. self.assertFalse(link_map.add_link((1, 4), (2, 1)))
  438. self.assertCountEqual(link_map.get_links_between(1, 2), [(1, 1)])
  439. # Adding new non-redundant links works
  440. self.assertTrue(link_map.add_link((1, 3), (2, 3)))
  441. self.assertCountEqual(link_map.get_links_between(1, 2), [(1, 1), (3, 3)])
  442. self.assertTrue(link_map.add_link((2, 5), (1, 3)))
  443. self.assertCountEqual(link_map.get_links_between(2, 1), [(5, 3)])
  444. self.assertCountEqual(link_map.get_links_between(1, 2), [(1, 1), (3, 3)])
  445. self.assertCountEqual(link_map.get_additions(), [(1, 3, 2, 3), (2, 5, 1, 3)])
  446. class EventChainBackgroundUpdateTestCase(HomeserverTestCase):
  447. servlets = [
  448. admin.register_servlets,
  449. room.register_servlets,
  450. login.register_servlets,
  451. ]
  452. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  453. self.store = hs.get_datastores().main
  454. self.user_id = self.register_user("foo", "pass")
  455. self.token = self.login("foo", "pass")
  456. self.requester = create_requester(self.user_id)
  457. def _generate_room(self) -> Tuple[str, List[Set[str]]]:
  458. """Insert a room without a chain cover index."""
  459. room_id = self.helper.create_room_as(self.user_id, tok=self.token)
  460. # Mark the room as not having a chain cover index
  461. self.get_success(
  462. self.store.db_pool.simple_update(
  463. table="rooms",
  464. keyvalues={"room_id": room_id},
  465. updatevalues={"has_auth_chain_index": False},
  466. desc="test",
  467. )
  468. )
  469. # Create a fork in the DAG with different events.
  470. event_handler = self.hs.get_event_creation_handler()
  471. latest_event_ids = self.get_success(
  472. self.store.get_prev_events_for_room(room_id)
  473. )
  474. event, unpersisted_context = self.get_success(
  475. event_handler.create_event(
  476. self.requester,
  477. {
  478. "type": "some_state_type",
  479. "state_key": "",
  480. "content": {},
  481. "room_id": room_id,
  482. "sender": self.user_id,
  483. },
  484. prev_event_ids=latest_event_ids,
  485. )
  486. )
  487. context = self.get_success(unpersisted_context.persist(event))
  488. self.get_success(
  489. event_handler.handle_new_client_event(
  490. self.requester, events_and_context=[(event, context)]
  491. )
  492. )
  493. state_ids1 = self.get_success(context.get_current_state_ids())
  494. assert state_ids1 is not None
  495. state1 = set(state_ids1.values())
  496. event, unpersisted_context = self.get_success(
  497. event_handler.create_event(
  498. self.requester,
  499. {
  500. "type": "some_state_type",
  501. "state_key": "",
  502. "content": {},
  503. "room_id": room_id,
  504. "sender": self.user_id,
  505. },
  506. prev_event_ids=latest_event_ids,
  507. )
  508. )
  509. context = self.get_success(unpersisted_context.persist(event))
  510. self.get_success(
  511. event_handler.handle_new_client_event(
  512. self.requester, events_and_context=[(event, context)]
  513. )
  514. )
  515. state_ids2 = self.get_success(context.get_current_state_ids())
  516. assert state_ids2 is not None
  517. state2 = set(state_ids2.values())
  518. # Delete the chain cover info.
  519. def _delete_tables(txn: Cursor) -> None:
  520. txn.execute("DELETE FROM event_auth_chains")
  521. txn.execute("DELETE FROM event_auth_chain_links")
  522. self.get_success(self.store.db_pool.runInteraction("test", _delete_tables))
  523. return room_id, [state1, state2]
  524. def test_background_update_single_room(self) -> None:
  525. """Test that the background update to calculate auth chains for historic
  526. rooms works correctly.
  527. """
  528. # Create a room
  529. room_id, states = self._generate_room()
  530. # Insert and run the background update.
  531. self.get_success(
  532. self.store.db_pool.simple_insert(
  533. "background_updates",
  534. {"update_name": "chain_cover", "progress_json": "{}"},
  535. )
  536. )
  537. # Ugh, have to reset this flag
  538. self.store.db_pool.updates._all_done = False
  539. self.wait_for_background_updates()
  540. # Test that the `has_auth_chain_index` has been set
  541. self.assertTrue(self.get_success(self.store.has_auth_chain_index(room_id)))
  542. # Test that calculating the auth chain difference using the newly
  543. # calculated chain cover works.
  544. self.get_success(
  545. self.store.db_pool.runInteraction(
  546. "test",
  547. self.store._get_auth_chain_difference_using_cover_index_txn,
  548. room_id,
  549. states,
  550. )
  551. )
  552. def test_background_update_multiple_rooms(self) -> None:
  553. """Test that the background update to calculate auth chains for historic
  554. rooms works correctly.
  555. """
  556. # Create a room
  557. room_id1, states1 = self._generate_room()
  558. room_id2, states2 = self._generate_room()
  559. room_id3, states2 = self._generate_room()
  560. # Insert and run the background update.
  561. self.get_success(
  562. self.store.db_pool.simple_insert(
  563. "background_updates",
  564. {"update_name": "chain_cover", "progress_json": "{}"},
  565. )
  566. )
  567. # Ugh, have to reset this flag
  568. self.store.db_pool.updates._all_done = False
  569. self.wait_for_background_updates()
  570. # Test that the `has_auth_chain_index` has been set
  571. self.assertTrue(self.get_success(self.store.has_auth_chain_index(room_id1)))
  572. self.assertTrue(self.get_success(self.store.has_auth_chain_index(room_id2)))
  573. self.assertTrue(self.get_success(self.store.has_auth_chain_index(room_id3)))
  574. # Test that calculating the auth chain difference using the newly
  575. # calculated chain cover works.
  576. self.get_success(
  577. self.store.db_pool.runInteraction(
  578. "test",
  579. self.store._get_auth_chain_difference_using_cover_index_txn,
  580. room_id1,
  581. states1,
  582. )
  583. )
  584. def test_background_update_single_large_room(self) -> None:
  585. """Test that the background update to calculate auth chains for historic
  586. rooms works correctly.
  587. """
  588. # Create a room
  589. room_id, states = self._generate_room()
  590. # Add a bunch of state so that it takes multiple iterations of the
  591. # background update to process the room.
  592. for i in range(150):
  593. self.helper.send_state(
  594. room_id, event_type="m.test", body={"index": i}, tok=self.token
  595. )
  596. # Insert and run the background update.
  597. self.get_success(
  598. self.store.db_pool.simple_insert(
  599. "background_updates",
  600. {"update_name": "chain_cover", "progress_json": "{}"},
  601. )
  602. )
  603. # Ugh, have to reset this flag
  604. self.store.db_pool.updates._all_done = False
  605. iterations = 0
  606. while not self.get_success(
  607. self.store.db_pool.updates.has_completed_background_updates()
  608. ):
  609. iterations += 1
  610. self.get_success(
  611. self.store.db_pool.updates.do_next_background_update(False), by=0.1
  612. )
  613. # Ensure that we did actually take multiple iterations to process the
  614. # room.
  615. self.assertGreater(iterations, 1)
  616. # Test that the `has_auth_chain_index` has been set
  617. self.assertTrue(self.get_success(self.store.has_auth_chain_index(room_id)))
  618. # Test that calculating the auth chain difference using the newly
  619. # calculated chain cover works.
  620. self.get_success(
  621. self.store.db_pool.runInteraction(
  622. "test",
  623. self.store._get_auth_chain_difference_using_cover_index_txn,
  624. room_id,
  625. states,
  626. )
  627. )
  628. def test_background_update_multiple_large_room(self) -> None:
  629. """Test that the background update to calculate auth chains for historic
  630. rooms works correctly.
  631. """
  632. # Create the rooms
  633. room_id1, _ = self._generate_room()
  634. room_id2, _ = self._generate_room()
  635. # Add a bunch of state so that it takes multiple iterations of the
  636. # background update to process the room.
  637. for i in range(150):
  638. self.helper.send_state(
  639. room_id1, event_type="m.test", body={"index": i}, tok=self.token
  640. )
  641. for i in range(150):
  642. self.helper.send_state(
  643. room_id2, event_type="m.test", body={"index": i}, tok=self.token
  644. )
  645. # Insert and run the background update.
  646. self.get_success(
  647. self.store.db_pool.simple_insert(
  648. "background_updates",
  649. {"update_name": "chain_cover", "progress_json": "{}"},
  650. )
  651. )
  652. # Ugh, have to reset this flag
  653. self.store.db_pool.updates._all_done = False
  654. iterations = 0
  655. while not self.get_success(
  656. self.store.db_pool.updates.has_completed_background_updates()
  657. ):
  658. iterations += 1
  659. self.get_success(
  660. self.store.db_pool.updates.do_next_background_update(False), by=0.1
  661. )
  662. # Ensure that we did actually take multiple iterations to process the
  663. # room.
  664. self.assertGreater(iterations, 1)
  665. # Test that the `has_auth_chain_index` has been set
  666. self.assertTrue(self.get_success(self.store.has_auth_chain_index(room_id1)))
  667. self.assertTrue(self.get_success(self.store.has_auth_chain_index(room_id2)))