test_event_federation.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  1. # Copyright 2018 New Vector 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. import datetime
  15. from typing import Dict, List, Tuple, Union
  16. import attr
  17. from parameterized import parameterized
  18. from twisted.test.proto_helpers import MemoryReactor
  19. from synapse.api.constants import EventTypes
  20. from synapse.api.room_versions import (
  21. KNOWN_ROOM_VERSIONS,
  22. EventFormatVersions,
  23. RoomVersion,
  24. )
  25. from synapse.events import _EventInternalMetadata
  26. from synapse.rest import admin
  27. from synapse.rest.client import login, room
  28. from synapse.server import HomeServer
  29. from synapse.storage.database import LoggingTransaction
  30. from synapse.types import JsonDict
  31. from synapse.util import Clock, json_encoder
  32. import tests.unittest
  33. import tests.utils
  34. @attr.s(auto_attribs=True, frozen=True, slots=True)
  35. class _BackfillSetupInfo:
  36. room_id: str
  37. depth_map: Dict[str, int]
  38. class EventFederationWorkerStoreTestCase(tests.unittest.HomeserverTestCase):
  39. servlets = [
  40. admin.register_servlets,
  41. room.register_servlets,
  42. login.register_servlets,
  43. ]
  44. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  45. self.store = hs.get_datastores().main
  46. def test_get_prev_events_for_room(self):
  47. room_id = "@ROOM:local"
  48. # add a bunch of events and hashes to act as forward extremities
  49. def insert_event(txn, i):
  50. event_id = "$event_%i:local" % i
  51. txn.execute(
  52. (
  53. "INSERT INTO events ("
  54. " room_id, event_id, type, depth, topological_ordering,"
  55. " content, processed, outlier, stream_ordering) "
  56. "VALUES (?, ?, 'm.test', ?, ?, 'test', ?, ?, ?)"
  57. ),
  58. (room_id, event_id, i, i, True, False, i),
  59. )
  60. txn.execute(
  61. (
  62. "INSERT INTO event_forward_extremities (room_id, event_id) "
  63. "VALUES (?, ?)"
  64. ),
  65. (room_id, event_id),
  66. )
  67. for i in range(0, 20):
  68. self.get_success(
  69. self.store.db_pool.runInteraction("insert", insert_event, i)
  70. )
  71. # this should get the last ten
  72. r = self.get_success(self.store.get_prev_events_for_room(room_id))
  73. self.assertEqual(10, len(r))
  74. for i in range(0, 10):
  75. self.assertEqual("$event_%i:local" % (19 - i), r[i])
  76. def test_get_rooms_with_many_extremities(self):
  77. room1 = "#room1"
  78. room2 = "#room2"
  79. room3 = "#room3"
  80. def insert_event(txn, i, room_id):
  81. event_id = "$event_%i:local" % i
  82. txn.execute(
  83. (
  84. "INSERT INTO event_forward_extremities (room_id, event_id) "
  85. "VALUES (?, ?)"
  86. ),
  87. (room_id, event_id),
  88. )
  89. for i in range(0, 20):
  90. self.get_success(
  91. self.store.db_pool.runInteraction("insert", insert_event, i, room1)
  92. )
  93. self.get_success(
  94. self.store.db_pool.runInteraction("insert", insert_event, i, room2)
  95. )
  96. self.get_success(
  97. self.store.db_pool.runInteraction("insert", insert_event, i, room3)
  98. )
  99. # Test simple case
  100. r = self.get_success(self.store.get_rooms_with_many_extremities(5, 5, []))
  101. self.assertEqual(len(r), 3)
  102. # Does filter work?
  103. r = self.get_success(self.store.get_rooms_with_many_extremities(5, 5, [room1]))
  104. self.assertTrue(room2 in r)
  105. self.assertTrue(room3 in r)
  106. self.assertEqual(len(r), 2)
  107. r = self.get_success(
  108. self.store.get_rooms_with_many_extremities(5, 5, [room1, room2])
  109. )
  110. self.assertEqual(r, [room3])
  111. # Does filter and limit work?
  112. r = self.get_success(self.store.get_rooms_with_many_extremities(5, 1, [room1]))
  113. self.assertTrue(r == [room2] or r == [room3])
  114. def _setup_auth_chain(self, use_chain_cover_index: bool) -> str:
  115. room_id = "@ROOM:local"
  116. # The silly auth graph we use to test the auth difference algorithm,
  117. # where the top are the most recent events.
  118. #
  119. # A B
  120. # \ /
  121. # D E
  122. # \ |
  123. # ` F C
  124. # | /|
  125. # G ´ |
  126. # | \ |
  127. # H I
  128. # | |
  129. # K J
  130. auth_graph = {
  131. "a": ["e"],
  132. "b": ["e"],
  133. "c": ["g", "i"],
  134. "d": ["f"],
  135. "e": ["f"],
  136. "f": ["g"],
  137. "g": ["h", "i"],
  138. "h": ["k"],
  139. "i": ["j"],
  140. "k": [],
  141. "j": [],
  142. }
  143. depth_map = {
  144. "a": 7,
  145. "b": 7,
  146. "c": 4,
  147. "d": 6,
  148. "e": 6,
  149. "f": 5,
  150. "g": 3,
  151. "h": 2,
  152. "i": 2,
  153. "k": 1,
  154. "j": 1,
  155. }
  156. # Mark the room as maybe having a cover index.
  157. def store_room(txn):
  158. self.store.db_pool.simple_insert_txn(
  159. txn,
  160. "rooms",
  161. {
  162. "room_id": room_id,
  163. "creator": "room_creator_user_id",
  164. "is_public": True,
  165. "room_version": "6",
  166. "has_auth_chain_index": use_chain_cover_index,
  167. },
  168. )
  169. self.get_success(self.store.db_pool.runInteraction("store_room", store_room))
  170. # We rudely fiddle with the appropriate tables directly, as that's much
  171. # easier than constructing events properly.
  172. def insert_event(txn):
  173. stream_ordering = 0
  174. for event_id in auth_graph:
  175. stream_ordering += 1
  176. depth = depth_map[event_id]
  177. self.store.db_pool.simple_insert_txn(
  178. txn,
  179. table="events",
  180. values={
  181. "event_id": event_id,
  182. "room_id": room_id,
  183. "depth": depth,
  184. "topological_ordering": depth,
  185. "type": "m.test",
  186. "processed": True,
  187. "outlier": False,
  188. "stream_ordering": stream_ordering,
  189. },
  190. )
  191. self.hs.datastores.persist_events._persist_event_auth_chain_txn(
  192. txn,
  193. [
  194. FakeEvent(event_id, room_id, auth_graph[event_id])
  195. for event_id in auth_graph
  196. ],
  197. )
  198. self.get_success(
  199. self.store.db_pool.runInteraction(
  200. "insert",
  201. insert_event,
  202. )
  203. )
  204. return room_id
  205. @parameterized.expand([(True,), (False,)])
  206. def test_auth_chain_ids(self, use_chain_cover_index: bool):
  207. room_id = self._setup_auth_chain(use_chain_cover_index)
  208. # a and b have the same auth chain.
  209. auth_chain_ids = self.get_success(self.store.get_auth_chain_ids(room_id, ["a"]))
  210. self.assertCountEqual(auth_chain_ids, ["e", "f", "g", "h", "i", "j", "k"])
  211. auth_chain_ids = self.get_success(self.store.get_auth_chain_ids(room_id, ["b"]))
  212. self.assertCountEqual(auth_chain_ids, ["e", "f", "g", "h", "i", "j", "k"])
  213. auth_chain_ids = self.get_success(
  214. self.store.get_auth_chain_ids(room_id, ["a", "b"])
  215. )
  216. self.assertCountEqual(auth_chain_ids, ["e", "f", "g", "h", "i", "j", "k"])
  217. auth_chain_ids = self.get_success(self.store.get_auth_chain_ids(room_id, ["c"]))
  218. self.assertCountEqual(auth_chain_ids, ["g", "h", "i", "j", "k"])
  219. # d and e have the same auth chain.
  220. auth_chain_ids = self.get_success(self.store.get_auth_chain_ids(room_id, ["d"]))
  221. self.assertCountEqual(auth_chain_ids, ["f", "g", "h", "i", "j", "k"])
  222. auth_chain_ids = self.get_success(self.store.get_auth_chain_ids(room_id, ["e"]))
  223. self.assertCountEqual(auth_chain_ids, ["f", "g", "h", "i", "j", "k"])
  224. auth_chain_ids = self.get_success(self.store.get_auth_chain_ids(room_id, ["f"]))
  225. self.assertCountEqual(auth_chain_ids, ["g", "h", "i", "j", "k"])
  226. auth_chain_ids = self.get_success(self.store.get_auth_chain_ids(room_id, ["g"]))
  227. self.assertCountEqual(auth_chain_ids, ["h", "i", "j", "k"])
  228. auth_chain_ids = self.get_success(self.store.get_auth_chain_ids(room_id, ["h"]))
  229. self.assertEqual(auth_chain_ids, {"k"})
  230. auth_chain_ids = self.get_success(self.store.get_auth_chain_ids(room_id, ["i"]))
  231. self.assertEqual(auth_chain_ids, {"j"})
  232. # j and k have no parents.
  233. auth_chain_ids = self.get_success(self.store.get_auth_chain_ids(room_id, ["j"]))
  234. self.assertEqual(auth_chain_ids, set())
  235. auth_chain_ids = self.get_success(self.store.get_auth_chain_ids(room_id, ["k"]))
  236. self.assertEqual(auth_chain_ids, set())
  237. # More complex input sequences.
  238. auth_chain_ids = self.get_success(
  239. self.store.get_auth_chain_ids(room_id, ["b", "c", "d"])
  240. )
  241. self.assertCountEqual(auth_chain_ids, ["e", "f", "g", "h", "i", "j", "k"])
  242. auth_chain_ids = self.get_success(
  243. self.store.get_auth_chain_ids(room_id, ["h", "i"])
  244. )
  245. self.assertCountEqual(auth_chain_ids, ["k", "j"])
  246. # e gets returned even though include_given is false, but it is in the
  247. # auth chain of b.
  248. auth_chain_ids = self.get_success(
  249. self.store.get_auth_chain_ids(room_id, ["b", "e"])
  250. )
  251. self.assertCountEqual(auth_chain_ids, ["e", "f", "g", "h", "i", "j", "k"])
  252. # Test include_given.
  253. auth_chain_ids = self.get_success(
  254. self.store.get_auth_chain_ids(room_id, ["i"], include_given=True)
  255. )
  256. self.assertCountEqual(auth_chain_ids, ["i", "j"])
  257. @parameterized.expand([(True,), (False,)])
  258. def test_auth_difference(self, use_chain_cover_index: bool):
  259. room_id = self._setup_auth_chain(use_chain_cover_index)
  260. # Now actually test that various combinations give the right result:
  261. difference = self.get_success(
  262. self.store.get_auth_chain_difference(room_id, [{"a"}, {"b"}])
  263. )
  264. self.assertSetEqual(difference, {"a", "b"})
  265. difference = self.get_success(
  266. self.store.get_auth_chain_difference(room_id, [{"a"}, {"b"}, {"c"}])
  267. )
  268. self.assertSetEqual(difference, {"a", "b", "c", "e", "f"})
  269. difference = self.get_success(
  270. self.store.get_auth_chain_difference(room_id, [{"a", "c"}, {"b"}])
  271. )
  272. self.assertSetEqual(difference, {"a", "b", "c"})
  273. difference = self.get_success(
  274. self.store.get_auth_chain_difference(room_id, [{"a", "c"}, {"b", "c"}])
  275. )
  276. self.assertSetEqual(difference, {"a", "b"})
  277. difference = self.get_success(
  278. self.store.get_auth_chain_difference(room_id, [{"a"}, {"b"}, {"d"}])
  279. )
  280. self.assertSetEqual(difference, {"a", "b", "d", "e"})
  281. difference = self.get_success(
  282. self.store.get_auth_chain_difference(room_id, [{"a"}, {"b"}, {"c"}, {"d"}])
  283. )
  284. self.assertSetEqual(difference, {"a", "b", "c", "d", "e", "f"})
  285. difference = self.get_success(
  286. self.store.get_auth_chain_difference(room_id, [{"a"}, {"b"}, {"e"}])
  287. )
  288. self.assertSetEqual(difference, {"a", "b"})
  289. difference = self.get_success(
  290. self.store.get_auth_chain_difference(room_id, [{"a"}])
  291. )
  292. self.assertSetEqual(difference, set())
  293. def test_auth_difference_partial_cover(self):
  294. """Test that we correctly handle rooms where not all events have a chain
  295. cover calculated. This can happen in some obscure edge cases, including
  296. during the background update that calculates the chain cover for old
  297. rooms.
  298. """
  299. room_id = "@ROOM:local"
  300. # The silly auth graph we use to test the auth difference algorithm,
  301. # where the top are the most recent events.
  302. #
  303. # A B
  304. # \ /
  305. # D E
  306. # \ |
  307. # ` F C
  308. # | /|
  309. # G ´ |
  310. # | \ |
  311. # H I
  312. # | |
  313. # K J
  314. auth_graph = {
  315. "a": ["e"],
  316. "b": ["e"],
  317. "c": ["g", "i"],
  318. "d": ["f"],
  319. "e": ["f"],
  320. "f": ["g"],
  321. "g": ["h", "i"],
  322. "h": ["k"],
  323. "i": ["j"],
  324. "k": [],
  325. "j": [],
  326. }
  327. depth_map = {
  328. "a": 7,
  329. "b": 7,
  330. "c": 4,
  331. "d": 6,
  332. "e": 6,
  333. "f": 5,
  334. "g": 3,
  335. "h": 2,
  336. "i": 2,
  337. "k": 1,
  338. "j": 1,
  339. }
  340. # We rudely fiddle with the appropriate tables directly, as that's much
  341. # easier than constructing events properly.
  342. def insert_event(txn):
  343. # First insert the room and mark it as having a chain cover.
  344. self.store.db_pool.simple_insert_txn(
  345. txn,
  346. "rooms",
  347. {
  348. "room_id": room_id,
  349. "creator": "room_creator_user_id",
  350. "is_public": True,
  351. "room_version": "6",
  352. "has_auth_chain_index": True,
  353. },
  354. )
  355. stream_ordering = 0
  356. for event_id in auth_graph:
  357. stream_ordering += 1
  358. depth = depth_map[event_id]
  359. self.store.db_pool.simple_insert_txn(
  360. txn,
  361. table="events",
  362. values={
  363. "event_id": event_id,
  364. "room_id": room_id,
  365. "depth": depth,
  366. "topological_ordering": depth,
  367. "type": "m.test",
  368. "processed": True,
  369. "outlier": False,
  370. "stream_ordering": stream_ordering,
  371. },
  372. )
  373. # Insert all events apart from 'B'
  374. self.hs.datastores.persist_events._persist_event_auth_chain_txn(
  375. txn,
  376. [
  377. FakeEvent(event_id, room_id, auth_graph[event_id])
  378. for event_id in auth_graph
  379. if event_id != "b"
  380. ],
  381. )
  382. # Now we insert the event 'B' without a chain cover, by temporarily
  383. # pretending the room doesn't have a chain cover.
  384. self.store.db_pool.simple_update_txn(
  385. txn,
  386. table="rooms",
  387. keyvalues={"room_id": room_id},
  388. updatevalues={"has_auth_chain_index": False},
  389. )
  390. self.hs.datastores.persist_events._persist_event_auth_chain_txn(
  391. txn,
  392. [FakeEvent("b", room_id, auth_graph["b"])],
  393. )
  394. self.store.db_pool.simple_update_txn(
  395. txn,
  396. table="rooms",
  397. keyvalues={"room_id": room_id},
  398. updatevalues={"has_auth_chain_index": True},
  399. )
  400. self.get_success(
  401. self.store.db_pool.runInteraction(
  402. "insert",
  403. insert_event,
  404. )
  405. )
  406. # Now actually test that various combinations give the right result:
  407. difference = self.get_success(
  408. self.store.get_auth_chain_difference(room_id, [{"a"}, {"b"}])
  409. )
  410. self.assertSetEqual(difference, {"a", "b"})
  411. difference = self.get_success(
  412. self.store.get_auth_chain_difference(room_id, [{"a"}, {"b"}, {"c"}])
  413. )
  414. self.assertSetEqual(difference, {"a", "b", "c", "e", "f"})
  415. difference = self.get_success(
  416. self.store.get_auth_chain_difference(room_id, [{"a", "c"}, {"b"}])
  417. )
  418. self.assertSetEqual(difference, {"a", "b", "c"})
  419. difference = self.get_success(
  420. self.store.get_auth_chain_difference(room_id, [{"a", "c"}, {"b", "c"}])
  421. )
  422. self.assertSetEqual(difference, {"a", "b"})
  423. difference = self.get_success(
  424. self.store.get_auth_chain_difference(room_id, [{"a"}, {"b"}, {"d"}])
  425. )
  426. self.assertSetEqual(difference, {"a", "b", "d", "e"})
  427. difference = self.get_success(
  428. self.store.get_auth_chain_difference(room_id, [{"a"}, {"b"}, {"c"}, {"d"}])
  429. )
  430. self.assertSetEqual(difference, {"a", "b", "c", "d", "e", "f"})
  431. difference = self.get_success(
  432. self.store.get_auth_chain_difference(room_id, [{"a"}, {"b"}, {"e"}])
  433. )
  434. self.assertSetEqual(difference, {"a", "b"})
  435. difference = self.get_success(
  436. self.store.get_auth_chain_difference(room_id, [{"a"}])
  437. )
  438. self.assertSetEqual(difference, set())
  439. @parameterized.expand(
  440. [(room_version,) for room_version in KNOWN_ROOM_VERSIONS.values()]
  441. )
  442. def test_prune_inbound_federation_queue(self, room_version: RoomVersion):
  443. """Test that pruning of inbound federation queues work"""
  444. room_id = "some_room_id"
  445. def prev_event_format(prev_event_id: str) -> Union[Tuple[str, dict], str]:
  446. """Account for differences in prev_events format across room versions"""
  447. if room_version.event_format == EventFormatVersions.ROOM_V1_V2:
  448. return prev_event_id, {}
  449. return prev_event_id
  450. # Insert a bunch of events that all reference the previous one.
  451. self.get_success(
  452. self.store.db_pool.simple_insert_many(
  453. table="federation_inbound_events_staging",
  454. keys=(
  455. "origin",
  456. "room_id",
  457. "received_ts",
  458. "event_id",
  459. "event_json",
  460. "internal_metadata",
  461. ),
  462. values=[
  463. (
  464. "some_origin",
  465. room_id,
  466. 0,
  467. f"$fake_event_id_{i + 1}",
  468. json_encoder.encode(
  469. {"prev_events": [prev_event_format(f"$fake_event_id_{i}")]}
  470. ),
  471. "{}",
  472. )
  473. for i in range(500)
  474. ],
  475. desc="test_prune_inbound_federation_queue",
  476. )
  477. )
  478. # Calling prune once should return True, i.e. a prune happen. The second
  479. # time it shouldn't.
  480. pruned = self.get_success(
  481. self.store.prune_staged_events_in_room(room_id, room_version)
  482. )
  483. self.assertTrue(pruned)
  484. pruned = self.get_success(
  485. self.store.prune_staged_events_in_room(room_id, room_version)
  486. )
  487. self.assertFalse(pruned)
  488. # Assert that we only have a single event left in the queue, and that it
  489. # is the last one.
  490. count = self.get_success(
  491. self.store.db_pool.simple_select_one_onecol(
  492. table="federation_inbound_events_staging",
  493. keyvalues={"room_id": room_id},
  494. retcol="COUNT(*)",
  495. desc="test_prune_inbound_federation_queue",
  496. )
  497. )
  498. self.assertEqual(count, 1)
  499. next_staged_event_info = self.get_success(
  500. self.store.get_next_staged_event_id_for_room(room_id)
  501. )
  502. assert next_staged_event_info
  503. _, event_id = next_staged_event_info
  504. self.assertEqual(event_id, "$fake_event_id_500")
  505. def _setup_room_for_backfill_tests(self) -> _BackfillSetupInfo:
  506. """
  507. Sets up a room with various events and backward extremities to test
  508. backfill functions against.
  509. Returns:
  510. _BackfillSetupInfo including the `room_id` to test against and
  511. `depth_map` of events in the room
  512. """
  513. room_id = "!backfill-room-test:some-host"
  514. # The silly graph we use to test grabbing backward extremities,
  515. # where the top is the oldest events.
  516. # 1 (oldest)
  517. # |
  518. # 2 ⹁
  519. # | \
  520. # | [b1, b2, b3]
  521. # | |
  522. # | A
  523. # | /
  524. # 3 {
  525. # | \
  526. # | [b4, b5, b6]
  527. # | |
  528. # | B
  529. # | /
  530. # 4 ´
  531. # |
  532. # 5 (newest)
  533. event_graph: Dict[str, List[str]] = {
  534. "1": [],
  535. "2": ["1"],
  536. "3": ["2", "A"],
  537. "4": ["3", "B"],
  538. "5": ["4"],
  539. "A": ["b1", "b2", "b3"],
  540. "b1": ["2"],
  541. "b2": ["2"],
  542. "b3": ["2"],
  543. "B": ["b4", "b5", "b6"],
  544. "b4": ["3"],
  545. "b5": ["3"],
  546. "b6": ["3"],
  547. }
  548. depth_map: Dict[str, int] = {
  549. "1": 1,
  550. "2": 2,
  551. "b1": 3,
  552. "b2": 3,
  553. "b3": 3,
  554. "A": 4,
  555. "3": 5,
  556. "b4": 6,
  557. "b5": 6,
  558. "b6": 6,
  559. "B": 7,
  560. "4": 8,
  561. "5": 9,
  562. }
  563. # The events we have persisted on our server.
  564. # The rest are events in the room but not backfilled tet.
  565. our_server_events = {"5", "4", "B", "3", "A"}
  566. complete_event_dict_map: Dict[str, JsonDict] = {}
  567. stream_ordering = 0
  568. for (event_id, prev_event_ids) in event_graph.items():
  569. depth = depth_map[event_id]
  570. complete_event_dict_map[event_id] = {
  571. "event_id": event_id,
  572. "type": "test_regular_type",
  573. "room_id": room_id,
  574. "sender": "@sender",
  575. "prev_event_ids": prev_event_ids,
  576. "auth_event_ids": [],
  577. "origin_server_ts": stream_ordering,
  578. "depth": depth,
  579. "stream_ordering": stream_ordering,
  580. "content": {"body": "event" + event_id},
  581. }
  582. stream_ordering += 1
  583. def populate_db(txn: LoggingTransaction):
  584. # Insert the room to satisfy the foreign key constraint of
  585. # `event_failed_pull_attempts`
  586. self.store.db_pool.simple_insert_txn(
  587. txn,
  588. "rooms",
  589. {
  590. "room_id": room_id,
  591. "creator": "room_creator_user_id",
  592. "is_public": True,
  593. "room_version": "6",
  594. },
  595. )
  596. # Insert our server events
  597. for event_id in our_server_events:
  598. event_dict = complete_event_dict_map[event_id]
  599. self.store.db_pool.simple_insert_txn(
  600. txn,
  601. table="events",
  602. values={
  603. "event_id": event_dict.get("event_id"),
  604. "type": event_dict.get("type"),
  605. "room_id": event_dict.get("room_id"),
  606. "depth": event_dict.get("depth"),
  607. "topological_ordering": event_dict.get("depth"),
  608. "stream_ordering": event_dict.get("stream_ordering"),
  609. "processed": True,
  610. "outlier": False,
  611. },
  612. )
  613. # Insert the event edges
  614. for event_id in our_server_events:
  615. for prev_event_id in event_graph[event_id]:
  616. self.store.db_pool.simple_insert_txn(
  617. txn,
  618. table="event_edges",
  619. values={
  620. "event_id": event_id,
  621. "prev_event_id": prev_event_id,
  622. "room_id": room_id,
  623. },
  624. )
  625. # Insert the backward extremities
  626. prev_events_of_our_events = {
  627. prev_event_id
  628. for our_server_event in our_server_events
  629. for prev_event_id in complete_event_dict_map[our_server_event][
  630. "prev_event_ids"
  631. ]
  632. }
  633. backward_extremities = prev_events_of_our_events - our_server_events
  634. for backward_extremity in backward_extremities:
  635. self.store.db_pool.simple_insert_txn(
  636. txn,
  637. table="event_backward_extremities",
  638. values={
  639. "event_id": backward_extremity,
  640. "room_id": room_id,
  641. },
  642. )
  643. self.get_success(
  644. self.store.db_pool.runInteraction(
  645. "_setup_room_for_backfill_tests_populate_db",
  646. populate_db,
  647. )
  648. )
  649. return _BackfillSetupInfo(room_id=room_id, depth_map=depth_map)
  650. def test_get_backfill_points_in_room(self):
  651. """
  652. Test to make sure only backfill points that are older and come before
  653. the `current_depth` are returned.
  654. """
  655. setup_info = self._setup_room_for_backfill_tests()
  656. room_id = setup_info.room_id
  657. depth_map = setup_info.depth_map
  658. # Try at "B"
  659. backfill_points = self.get_success(
  660. self.store.get_backfill_points_in_room(room_id, depth_map["B"], limit=100)
  661. )
  662. backfill_event_ids = [backfill_point[0] for backfill_point in backfill_points]
  663. self.assertEqual(backfill_event_ids, ["b6", "b5", "b4", "2", "b3", "b2", "b1"])
  664. # Try at "A"
  665. backfill_points = self.get_success(
  666. self.store.get_backfill_points_in_room(room_id, depth_map["A"], limit=100)
  667. )
  668. backfill_event_ids = [backfill_point[0] for backfill_point in backfill_points]
  669. # Event "2" has a depth of 2 but is not included here because we only
  670. # know the approximate depth of 5 from our event "3".
  671. self.assertListEqual(backfill_event_ids, ["b3", "b2", "b1"])
  672. def test_get_backfill_points_in_room_excludes_events_we_have_attempted(
  673. self,
  674. ):
  675. """
  676. Test to make sure that events we have attempted to backfill (and within
  677. backoff timeout duration) do not show up as an event to backfill again.
  678. """
  679. setup_info = self._setup_room_for_backfill_tests()
  680. room_id = setup_info.room_id
  681. depth_map = setup_info.depth_map
  682. # Record some attempts to backfill these events which will make
  683. # `get_backfill_points_in_room` exclude them because we
  684. # haven't passed the backoff interval.
  685. self.get_success(
  686. self.store.record_event_failed_pull_attempt(room_id, "b5", "fake cause")
  687. )
  688. self.get_success(
  689. self.store.record_event_failed_pull_attempt(room_id, "b4", "fake cause")
  690. )
  691. self.get_success(
  692. self.store.record_event_failed_pull_attempt(room_id, "b3", "fake cause")
  693. )
  694. self.get_success(
  695. self.store.record_event_failed_pull_attempt(room_id, "b2", "fake cause")
  696. )
  697. # No time has passed since we attempted to backfill ^
  698. # Try at "B"
  699. backfill_points = self.get_success(
  700. self.store.get_backfill_points_in_room(room_id, depth_map["B"], limit=100)
  701. )
  702. backfill_event_ids = [backfill_point[0] for backfill_point in backfill_points]
  703. # Only the backfill points that we didn't record earlier exist here.
  704. self.assertEqual(backfill_event_ids, ["b6", "2", "b1"])
  705. def test_get_backfill_points_in_room_attempted_event_retry_after_backoff_duration(
  706. self,
  707. ):
  708. """
  709. Test to make sure after we fake attempt to backfill event "b3" many times,
  710. we can see retry and see the "b3" again after the backoff timeout duration
  711. has exceeded.
  712. """
  713. setup_info = self._setup_room_for_backfill_tests()
  714. room_id = setup_info.room_id
  715. depth_map = setup_info.depth_map
  716. # Record some attempts to backfill these events which will make
  717. # `get_backfill_points_in_room` exclude them because we
  718. # haven't passed the backoff interval.
  719. self.get_success(
  720. self.store.record_event_failed_pull_attempt(room_id, "b3", "fake cause")
  721. )
  722. self.get_success(
  723. self.store.record_event_failed_pull_attempt(room_id, "b1", "fake cause")
  724. )
  725. self.get_success(
  726. self.store.record_event_failed_pull_attempt(room_id, "b1", "fake cause")
  727. )
  728. self.get_success(
  729. self.store.record_event_failed_pull_attempt(room_id, "b1", "fake cause")
  730. )
  731. self.get_success(
  732. self.store.record_event_failed_pull_attempt(room_id, "b1", "fake cause")
  733. )
  734. # Now advance time by 2 hours and we should only be able to see "b3"
  735. # because we have waited long enough for the single attempt (2^1 hours)
  736. # but we still shouldn't see "b1" because we haven't waited long enough
  737. # for this many attempts. We didn't do anything to "b2" so it should be
  738. # visible regardless.
  739. self.reactor.advance(datetime.timedelta(hours=2).total_seconds())
  740. # Try at "A" and make sure that "b1" is not in the list because we've
  741. # already attempted many times
  742. backfill_points = self.get_success(
  743. self.store.get_backfill_points_in_room(room_id, depth_map["A"], limit=100)
  744. )
  745. backfill_event_ids = [backfill_point[0] for backfill_point in backfill_points]
  746. self.assertEqual(backfill_event_ids, ["b3", "b2"])
  747. # Now advance time by 20 hours (above 2^4 because we made 4 attemps) and
  748. # see if we can now backfill it
  749. self.reactor.advance(datetime.timedelta(hours=20).total_seconds())
  750. # Try at "A" again after we advanced enough time and we should see "b3" again
  751. backfill_points = self.get_success(
  752. self.store.get_backfill_points_in_room(room_id, depth_map["A"], limit=100)
  753. )
  754. backfill_event_ids = [backfill_point[0] for backfill_point in backfill_points]
  755. self.assertEqual(backfill_event_ids, ["b3", "b2", "b1"])
  756. def test_get_backfill_points_in_room_works_after_many_failed_pull_attempts_that_could_naively_overflow(
  757. self,
  758. ) -> None:
  759. """
  760. A test that reproduces #13929 (Postgres only).
  761. Test to make sure we can still get backfill points after many failed pull
  762. attempts that cause us to backoff to the limit. Even if the backoff formula
  763. would tell us to wait for more seconds than can be expressed in a 32 bit
  764. signed int.
  765. """
  766. setup_info = self._setup_room_for_backfill_tests()
  767. room_id = setup_info.room_id
  768. depth_map = setup_info.depth_map
  769. # Pretend that we have tried and failed 10 times to backfill event b1.
  770. for _ in range(10):
  771. self.get_success(
  772. self.store.record_event_failed_pull_attempt(room_id, "b1", "fake cause")
  773. )
  774. # If the backoff periods grow without limit:
  775. # After the first failed attempt, we would have backed off for 1 << 1 = 2 hours.
  776. # After the second failed attempt we would have backed off for 1 << 2 = 4 hours,
  777. # so after the 10th failed attempt we should backoff for 1 << 10 == 1024 hours.
  778. # Wait 1100 hours just so we have a nice round number.
  779. self.reactor.advance(datetime.timedelta(hours=1100).total_seconds())
  780. # 1024 hours in milliseconds is 1024 * 3600000, which exceeds the largest 32 bit
  781. # signed integer. The bug we're reproducing is that this overflow causes an
  782. # error in postgres preventing us from fetching a set of backwards extremities
  783. # to retry fetching.
  784. backfill_points = self.get_success(
  785. self.store.get_backfill_points_in_room(room_id, depth_map["A"], limit=100)
  786. )
  787. # We should aim to fetch all backoff points: b1's latest backoff period has
  788. # expired, and we haven't tried the rest.
  789. backfill_event_ids = [backfill_point[0] for backfill_point in backfill_points]
  790. self.assertEqual(backfill_event_ids, ["b3", "b2", "b1"])
  791. def _setup_room_for_insertion_backfill_tests(self) -> _BackfillSetupInfo:
  792. """
  793. Sets up a room with various insertion event backward extremities to test
  794. backfill functions against.
  795. Returns:
  796. _BackfillSetupInfo including the `room_id` to test against and
  797. `depth_map` of events in the room
  798. """
  799. room_id = "!backfill-room-test:some-host"
  800. depth_map: Dict[str, int] = {
  801. "1": 1,
  802. "2": 2,
  803. "insertion_eventA": 3,
  804. "3": 4,
  805. "insertion_eventB": 5,
  806. "4": 6,
  807. "5": 7,
  808. }
  809. def populate_db(txn: LoggingTransaction):
  810. # Insert the room to satisfy the foreign key constraint of
  811. # `event_failed_pull_attempts`
  812. self.store.db_pool.simple_insert_txn(
  813. txn,
  814. "rooms",
  815. {
  816. "room_id": room_id,
  817. "creator": "room_creator_user_id",
  818. "is_public": True,
  819. "room_version": "6",
  820. },
  821. )
  822. # Insert our server events
  823. stream_ordering = 0
  824. for event_id, depth in depth_map.items():
  825. self.store.db_pool.simple_insert_txn(
  826. txn,
  827. table="events",
  828. values={
  829. "event_id": event_id,
  830. "type": EventTypes.MSC2716_INSERTION
  831. if event_id.startswith("insertion_event")
  832. else "test_regular_type",
  833. "room_id": room_id,
  834. "depth": depth,
  835. "topological_ordering": depth,
  836. "stream_ordering": stream_ordering,
  837. "processed": True,
  838. "outlier": False,
  839. },
  840. )
  841. if event_id.startswith("insertion_event"):
  842. self.store.db_pool.simple_insert_txn(
  843. txn,
  844. table="insertion_event_extremities",
  845. values={
  846. "event_id": event_id,
  847. "room_id": room_id,
  848. },
  849. )
  850. stream_ordering += 1
  851. self.get_success(
  852. self.store.db_pool.runInteraction(
  853. "_setup_room_for_insertion_backfill_tests_populate_db",
  854. populate_db,
  855. )
  856. )
  857. return _BackfillSetupInfo(room_id=room_id, depth_map=depth_map)
  858. def test_get_insertion_event_backward_extremities_in_room(self):
  859. """
  860. Test to make sure only insertion event backward extremities that are
  861. older and come before the `current_depth` are returned.
  862. """
  863. setup_info = self._setup_room_for_insertion_backfill_tests()
  864. room_id = setup_info.room_id
  865. depth_map = setup_info.depth_map
  866. # Try at "insertion_eventB"
  867. backfill_points = self.get_success(
  868. self.store.get_insertion_event_backward_extremities_in_room(
  869. room_id, depth_map["insertion_eventB"], limit=100
  870. )
  871. )
  872. backfill_event_ids = [backfill_point[0] for backfill_point in backfill_points]
  873. self.assertEqual(backfill_event_ids, ["insertion_eventB", "insertion_eventA"])
  874. # Try at "insertion_eventA"
  875. backfill_points = self.get_success(
  876. self.store.get_insertion_event_backward_extremities_in_room(
  877. room_id, depth_map["insertion_eventA"], limit=100
  878. )
  879. )
  880. backfill_event_ids = [backfill_point[0] for backfill_point in backfill_points]
  881. # Event "2" has a depth of 2 but is not included here because we only
  882. # know the approximate depth of 5 from our event "3".
  883. self.assertListEqual(backfill_event_ids, ["insertion_eventA"])
  884. def test_get_insertion_event_backward_extremities_in_room_excludes_events_we_have_attempted(
  885. self,
  886. ):
  887. """
  888. Test to make sure that insertion events we have attempted to backfill
  889. (and within backoff timeout duration) do not show up as an event to
  890. backfill again.
  891. """
  892. setup_info = self._setup_room_for_insertion_backfill_tests()
  893. room_id = setup_info.room_id
  894. depth_map = setup_info.depth_map
  895. # Record some attempts to backfill these events which will make
  896. # `get_insertion_event_backward_extremities_in_room` exclude them
  897. # because we haven't passed the backoff interval.
  898. self.get_success(
  899. self.store.record_event_failed_pull_attempt(
  900. room_id, "insertion_eventA", "fake cause"
  901. )
  902. )
  903. # No time has passed since we attempted to backfill ^
  904. # Try at "insertion_eventB"
  905. backfill_points = self.get_success(
  906. self.store.get_insertion_event_backward_extremities_in_room(
  907. room_id, depth_map["insertion_eventB"], limit=100
  908. )
  909. )
  910. backfill_event_ids = [backfill_point[0] for backfill_point in backfill_points]
  911. # Only the backfill points that we didn't record earlier exist here.
  912. self.assertEqual(backfill_event_ids, ["insertion_eventB"])
  913. def test_get_insertion_event_backward_extremities_in_room_attempted_event_retry_after_backoff_duration(
  914. self,
  915. ):
  916. """
  917. Test to make sure after we fake attempt to backfill event
  918. "insertion_eventA" many times, we can see retry and see the
  919. "insertion_eventA" again after the backoff timeout duration has
  920. exceeded.
  921. """
  922. setup_info = self._setup_room_for_insertion_backfill_tests()
  923. room_id = setup_info.room_id
  924. depth_map = setup_info.depth_map
  925. # Record some attempts to backfill these events which will make
  926. # `get_backfill_points_in_room` exclude them because we
  927. # haven't passed the backoff interval.
  928. self.get_success(
  929. self.store.record_event_failed_pull_attempt(
  930. room_id, "insertion_eventB", "fake cause"
  931. )
  932. )
  933. self.get_success(
  934. self.store.record_event_failed_pull_attempt(
  935. room_id, "insertion_eventA", "fake cause"
  936. )
  937. )
  938. self.get_success(
  939. self.store.record_event_failed_pull_attempt(
  940. room_id, "insertion_eventA", "fake cause"
  941. )
  942. )
  943. self.get_success(
  944. self.store.record_event_failed_pull_attempt(
  945. room_id, "insertion_eventA", "fake cause"
  946. )
  947. )
  948. self.get_success(
  949. self.store.record_event_failed_pull_attempt(
  950. room_id, "insertion_eventA", "fake cause"
  951. )
  952. )
  953. # Now advance time by 2 hours and we should only be able to see
  954. # "insertion_eventB" because we have waited long enough for the single
  955. # attempt (2^1 hours) but we still shouldn't see "insertion_eventA"
  956. # because we haven't waited long enough for this many attempts.
  957. self.reactor.advance(datetime.timedelta(hours=2).total_seconds())
  958. # Try at "insertion_eventA" and make sure that "insertion_eventA" is not
  959. # in the list because we've already attempted many times
  960. backfill_points = self.get_success(
  961. self.store.get_insertion_event_backward_extremities_in_room(
  962. room_id, depth_map["insertion_eventA"], limit=100
  963. )
  964. )
  965. backfill_event_ids = [backfill_point[0] for backfill_point in backfill_points]
  966. self.assertEqual(backfill_event_ids, [])
  967. # Now advance time by 20 hours (above 2^4 because we made 4 attemps) and
  968. # see if we can now backfill it
  969. self.reactor.advance(datetime.timedelta(hours=20).total_seconds())
  970. # Try at "insertion_eventA" again after we advanced enough time and we
  971. # should see "insertion_eventA" again
  972. backfill_points = self.get_success(
  973. self.store.get_insertion_event_backward_extremities_in_room(
  974. room_id, depth_map["insertion_eventA"], limit=100
  975. )
  976. )
  977. backfill_event_ids = [backfill_point[0] for backfill_point in backfill_points]
  978. self.assertEqual(backfill_event_ids, ["insertion_eventA"])
  979. def test_get_event_ids_to_not_pull_from_backoff(
  980. self,
  981. ):
  982. """
  983. Test to make sure only event IDs we should backoff from are returned.
  984. """
  985. # Create the room
  986. user_id = self.register_user("alice", "test")
  987. tok = self.login("alice", "test")
  988. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  989. self.get_success(
  990. self.store.record_event_failed_pull_attempt(
  991. room_id, "$failed_event_id", "fake cause"
  992. )
  993. )
  994. event_ids_to_backoff = self.get_success(
  995. self.store.get_event_ids_to_not_pull_from_backoff(
  996. room_id=room_id, event_ids=["$failed_event_id", "$normal_event_id"]
  997. )
  998. )
  999. self.assertEqual(event_ids_to_backoff, ["$failed_event_id"])
  1000. def test_get_event_ids_to_not_pull_from_backoff_retry_after_backoff_duration(
  1001. self,
  1002. ):
  1003. """
  1004. Test to make sure no event IDs are returned after the backoff duration has
  1005. elapsed.
  1006. """
  1007. # Create the room
  1008. user_id = self.register_user("alice", "test")
  1009. tok = self.login("alice", "test")
  1010. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  1011. self.get_success(
  1012. self.store.record_event_failed_pull_attempt(
  1013. room_id, "$failed_event_id", "fake cause"
  1014. )
  1015. )
  1016. # Now advance time by 2 hours so we wait long enough for the single failed
  1017. # attempt (2^1 hours).
  1018. self.reactor.advance(datetime.timedelta(hours=2).total_seconds())
  1019. event_ids_to_backoff = self.get_success(
  1020. self.store.get_event_ids_to_not_pull_from_backoff(
  1021. room_id=room_id, event_ids=["$failed_event_id", "$normal_event_id"]
  1022. )
  1023. )
  1024. # Since this function only returns events we should backoff from, time has
  1025. # elapsed past the backoff range so there is no events to backoff from.
  1026. self.assertEqual(event_ids_to_backoff, [])
  1027. @attr.s
  1028. class FakeEvent:
  1029. event_id = attr.ib()
  1030. room_id = attr.ib()
  1031. auth_events = attr.ib()
  1032. type = "foo"
  1033. state_key = "foo"
  1034. internal_metadata = _EventInternalMetadata({})
  1035. def auth_event_ids(self):
  1036. return self.auth_events
  1037. def is_state(self):
  1038. return True