test_event_federation.py 43 KB

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