test_event_federation.py 38 KB

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