Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

1932 lignes
73 KiB

  1. # Copyright 2014-2016 OpenMarket 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. import itertools
  16. import logging
  17. from queue import Empty, PriorityQueue
  18. from typing import (
  19. TYPE_CHECKING,
  20. Collection,
  21. Dict,
  22. Iterable,
  23. List,
  24. Optional,
  25. Set,
  26. Tuple,
  27. cast,
  28. )
  29. import attr
  30. from prometheus_client import Counter, Gauge
  31. from synapse.api.constants import MAX_DEPTH, EventTypes
  32. from synapse.api.errors import StoreError
  33. from synapse.api.room_versions import EventFormatVersions, RoomVersion
  34. from synapse.events import EventBase, make_event_from_dict
  35. from synapse.logging.opentracing import tag_args, trace
  36. from synapse.metrics.background_process_metrics import wrap_as_background_process
  37. from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause
  38. from synapse.storage.database import (
  39. DatabasePool,
  40. LoggingDatabaseConnection,
  41. LoggingTransaction,
  42. )
  43. from synapse.storage.databases.main.events_worker import EventsWorkerStore
  44. from synapse.storage.databases.main.signatures import SignatureWorkerStore
  45. from synapse.storage.engines import PostgresEngine, Sqlite3Engine
  46. from synapse.types import JsonDict
  47. from synapse.util import json_encoder
  48. from synapse.util.caches.descriptors import cached
  49. from synapse.util.caches.lrucache import LruCache
  50. from synapse.util.cancellation import cancellable
  51. from synapse.util.iterutils import batch_iter
  52. if TYPE_CHECKING:
  53. from synapse.server import HomeServer
  54. oldest_pdu_in_federation_staging = Gauge(
  55. "synapse_federation_server_oldest_inbound_pdu_in_staging",
  56. "The age in seconds since we received the oldest pdu in the federation staging area",
  57. )
  58. number_pdus_in_federation_queue = Gauge(
  59. "synapse_federation_server_number_inbound_pdu_in_staging",
  60. "The total number of events in the inbound federation staging",
  61. )
  62. pdus_pruned_from_federation_queue = Counter(
  63. "synapse_federation_server_number_inbound_pdu_pruned",
  64. "The number of events in the inbound federation staging that have been "
  65. "pruned due to the queue getting too long",
  66. )
  67. logger = logging.getLogger(__name__)
  68. BACKFILL_EVENT_BACKOFF_UPPER_BOUND_SECONDS: int = int(
  69. datetime.timedelta(days=7).total_seconds()
  70. )
  71. BACKFILL_EVENT_EXPONENTIAL_BACKOFF_STEP_SECONDS: int = int(
  72. datetime.timedelta(hours=1).total_seconds()
  73. )
  74. # All the info we need while iterating the DAG while backfilling
  75. @attr.s(frozen=True, slots=True, auto_attribs=True)
  76. class BackfillQueueNavigationItem:
  77. depth: int
  78. stream_ordering: int
  79. event_id: str
  80. type: str
  81. class _NoChainCoverIndex(Exception):
  82. def __init__(self, room_id: str):
  83. super().__init__("Unexpectedly no chain cover for events in %s" % (room_id,))
  84. class EventFederationWorkerStore(SignatureWorkerStore, EventsWorkerStore, SQLBaseStore):
  85. def __init__(
  86. self,
  87. database: DatabasePool,
  88. db_conn: LoggingDatabaseConnection,
  89. hs: "HomeServer",
  90. ):
  91. super().__init__(database, db_conn, hs)
  92. self.hs = hs
  93. if hs.config.worker.run_background_tasks:
  94. hs.get_clock().looping_call(
  95. self._delete_old_forward_extrem_cache, 60 * 60 * 1000
  96. )
  97. # Cache of event ID to list of auth event IDs and their depths.
  98. self._event_auth_cache: LruCache[str, List[Tuple[str, int]]] = LruCache(
  99. 500000, "_event_auth_cache", size_callback=len
  100. )
  101. self._clock.looping_call(self._get_stats_for_federation_staging, 30 * 1000)
  102. async def get_auth_chain(
  103. self, room_id: str, event_ids: Collection[str], include_given: bool = False
  104. ) -> List[EventBase]:
  105. """Get auth events for given event_ids. The events *must* be state events.
  106. Args:
  107. room_id: The room the event is in.
  108. event_ids: state events
  109. include_given: include the given events in result
  110. Returns:
  111. list of events
  112. """
  113. event_ids = await self.get_auth_chain_ids(
  114. room_id, event_ids, include_given=include_given
  115. )
  116. return await self.get_events_as_list(event_ids)
  117. @trace
  118. @tag_args
  119. async def get_auth_chain_ids(
  120. self,
  121. room_id: str,
  122. event_ids: Collection[str],
  123. include_given: bool = False,
  124. ) -> Set[str]:
  125. """Get auth events for given event_ids. The events *must* be state events.
  126. Args:
  127. room_id: The room the event is in.
  128. event_ids: state events
  129. include_given: include the given events in result
  130. Returns:
  131. set of event_ids
  132. """
  133. # Check if we have indexed the room so we can use the chain cover
  134. # algorithm.
  135. room = await self.get_room(room_id) # type: ignore[attr-defined]
  136. if room["has_auth_chain_index"]:
  137. try:
  138. return await self.db_pool.runInteraction(
  139. "get_auth_chain_ids_chains",
  140. self._get_auth_chain_ids_using_cover_index_txn,
  141. room_id,
  142. event_ids,
  143. include_given,
  144. )
  145. except _NoChainCoverIndex:
  146. # For whatever reason we don't actually have a chain cover index
  147. # for the events in question, so we fall back to the old method.
  148. pass
  149. return await self.db_pool.runInteraction(
  150. "get_auth_chain_ids",
  151. self._get_auth_chain_ids_txn,
  152. event_ids,
  153. include_given,
  154. )
  155. def _get_auth_chain_ids_using_cover_index_txn(
  156. self,
  157. txn: LoggingTransaction,
  158. room_id: str,
  159. event_ids: Collection[str],
  160. include_given: bool,
  161. ) -> Set[str]:
  162. """Calculates the auth chain IDs using the chain index."""
  163. # First we look up the chain ID/sequence numbers for the given events.
  164. initial_events = set(event_ids)
  165. # All the events that we've found that are reachable from the events.
  166. seen_events: Set[str] = set()
  167. # A map from chain ID to max sequence number of the given events.
  168. event_chains: Dict[int, int] = {}
  169. sql = """
  170. SELECT event_id, chain_id, sequence_number
  171. FROM event_auth_chains
  172. WHERE %s
  173. """
  174. for batch in batch_iter(initial_events, 1000):
  175. clause, args = make_in_list_sql_clause(
  176. txn.database_engine, "event_id", batch
  177. )
  178. txn.execute(sql % (clause,), args)
  179. for event_id, chain_id, sequence_number in txn:
  180. seen_events.add(event_id)
  181. event_chains[chain_id] = max(
  182. sequence_number, event_chains.get(chain_id, 0)
  183. )
  184. # Check that we actually have a chain ID for all the events.
  185. events_missing_chain_info = initial_events.difference(seen_events)
  186. if events_missing_chain_info:
  187. # This can happen due to e.g. downgrade/upgrade of the server. We
  188. # raise an exception and fall back to the previous algorithm.
  189. logger.info(
  190. "Unexpectedly found that events don't have chain IDs in room %s: %s",
  191. room_id,
  192. events_missing_chain_info,
  193. )
  194. raise _NoChainCoverIndex(room_id)
  195. # Now we look up all links for the chains we have, adding chains that
  196. # are reachable from any event.
  197. sql = """
  198. SELECT
  199. origin_chain_id, origin_sequence_number,
  200. target_chain_id, target_sequence_number
  201. FROM event_auth_chain_links
  202. WHERE %s
  203. """
  204. # A map from chain ID to max sequence number *reachable* from any event ID.
  205. chains: Dict[int, int] = {}
  206. # Add all linked chains reachable from initial set of chains.
  207. for batch2 in batch_iter(event_chains, 1000):
  208. clause, args = make_in_list_sql_clause(
  209. txn.database_engine, "origin_chain_id", batch2
  210. )
  211. txn.execute(sql % (clause,), args)
  212. for (
  213. origin_chain_id,
  214. origin_sequence_number,
  215. target_chain_id,
  216. target_sequence_number,
  217. ) in txn:
  218. # chains are only reachable if the origin sequence number of
  219. # the link is less than the max sequence number in the
  220. # origin chain.
  221. if origin_sequence_number <= event_chains.get(origin_chain_id, 0):
  222. chains[target_chain_id] = max(
  223. target_sequence_number,
  224. chains.get(target_chain_id, 0),
  225. )
  226. # Add the initial set of chains, excluding the sequence corresponding to
  227. # initial event.
  228. for chain_id, seq_no in event_chains.items():
  229. chains[chain_id] = max(seq_no - 1, chains.get(chain_id, 0))
  230. # Now for each chain we figure out the maximum sequence number reachable
  231. # from *any* event ID. Events with a sequence less than that are in the
  232. # auth chain.
  233. if include_given:
  234. results = initial_events
  235. else:
  236. results = set()
  237. if isinstance(self.database_engine, PostgresEngine):
  238. # We can use `execute_values` to efficiently fetch the gaps when
  239. # using postgres.
  240. sql = """
  241. SELECT event_id
  242. FROM event_auth_chains AS c, (VALUES ?) AS l(chain_id, max_seq)
  243. WHERE
  244. c.chain_id = l.chain_id
  245. AND sequence_number <= max_seq
  246. """
  247. rows = txn.execute_values(sql, chains.items())
  248. results.update(r for r, in rows)
  249. else:
  250. # For SQLite we just fall back to doing a noddy for loop.
  251. sql = """
  252. SELECT event_id FROM event_auth_chains
  253. WHERE chain_id = ? AND sequence_number <= ?
  254. """
  255. for chain_id, max_no in chains.items():
  256. txn.execute(sql, (chain_id, max_no))
  257. results.update(r for r, in txn)
  258. return results
  259. def _get_auth_chain_ids_txn(
  260. self, txn: LoggingTransaction, event_ids: Collection[str], include_given: bool
  261. ) -> Set[str]:
  262. """Calculates the auth chain IDs.
  263. This is used when we don't have a cover index for the room.
  264. """
  265. if include_given:
  266. results = set(event_ids)
  267. else:
  268. results = set()
  269. # We pull out the depth simply so that we can populate the
  270. # `_event_auth_cache` cache.
  271. base_sql = """
  272. SELECT a.event_id, auth_id, depth
  273. FROM event_auth AS a
  274. INNER JOIN events AS e ON (e.event_id = a.auth_id)
  275. WHERE
  276. """
  277. front = set(event_ids)
  278. while front:
  279. new_front: Set[str] = set()
  280. for chunk in batch_iter(front, 100):
  281. # Pull the auth events either from the cache or DB.
  282. to_fetch: List[str] = [] # Event IDs to fetch from DB
  283. for event_id in chunk:
  284. res = self._event_auth_cache.get(event_id)
  285. if res is None:
  286. to_fetch.append(event_id)
  287. else:
  288. new_front.update(auth_id for auth_id, depth in res)
  289. if to_fetch:
  290. clause, args = make_in_list_sql_clause(
  291. txn.database_engine, "a.event_id", to_fetch
  292. )
  293. txn.execute(base_sql + clause, args)
  294. # Note we need to batch up the results by event ID before
  295. # adding to the cache.
  296. to_cache: Dict[str, List[Tuple[str, int]]] = {}
  297. for event_id, auth_event_id, auth_event_depth in txn:
  298. to_cache.setdefault(event_id, []).append(
  299. (auth_event_id, auth_event_depth)
  300. )
  301. new_front.add(auth_event_id)
  302. for event_id, auth_events in to_cache.items():
  303. self._event_auth_cache.set(event_id, auth_events)
  304. new_front -= results
  305. front = new_front
  306. results.update(front)
  307. return results
  308. async def get_auth_chain_difference(
  309. self, room_id: str, state_sets: List[Set[str]]
  310. ) -> Set[str]:
  311. """Given sets of state events figure out the auth chain difference (as
  312. per state res v2 algorithm).
  313. This equivalent to fetching the full auth chain for each set of state
  314. and returning the events that don't appear in each and every auth
  315. chain.
  316. Returns:
  317. The set of the difference in auth chains.
  318. """
  319. # Check if we have indexed the room so we can use the chain cover
  320. # algorithm.
  321. room = await self.get_room(room_id) # type: ignore[attr-defined]
  322. if room["has_auth_chain_index"]:
  323. try:
  324. return await self.db_pool.runInteraction(
  325. "get_auth_chain_difference_chains",
  326. self._get_auth_chain_difference_using_cover_index_txn,
  327. room_id,
  328. state_sets,
  329. )
  330. except _NoChainCoverIndex:
  331. # For whatever reason we don't actually have a chain cover index
  332. # for the events in question, so we fall back to the old method.
  333. pass
  334. return await self.db_pool.runInteraction(
  335. "get_auth_chain_difference",
  336. self._get_auth_chain_difference_txn,
  337. state_sets,
  338. )
  339. def _get_auth_chain_difference_using_cover_index_txn(
  340. self, txn: LoggingTransaction, room_id: str, state_sets: List[Set[str]]
  341. ) -> Set[str]:
  342. """Calculates the auth chain difference using the chain index.
  343. See docs/auth_chain_difference_algorithm.md for details
  344. """
  345. # First we look up the chain ID/sequence numbers for all the events, and
  346. # work out the chain/sequence numbers reachable from each state set.
  347. initial_events = set(state_sets[0]).union(*state_sets[1:])
  348. # Map from event_id -> (chain ID, seq no)
  349. chain_info: Dict[str, Tuple[int, int]] = {}
  350. # Map from chain ID -> seq no -> event Id
  351. chain_to_event: Dict[int, Dict[int, str]] = {}
  352. # All the chains that we've found that are reachable from the state
  353. # sets.
  354. seen_chains: Set[int] = set()
  355. sql = """
  356. SELECT event_id, chain_id, sequence_number
  357. FROM event_auth_chains
  358. WHERE %s
  359. """
  360. for batch in batch_iter(initial_events, 1000):
  361. clause, args = make_in_list_sql_clause(
  362. txn.database_engine, "event_id", batch
  363. )
  364. txn.execute(sql % (clause,), args)
  365. for event_id, chain_id, sequence_number in txn:
  366. chain_info[event_id] = (chain_id, sequence_number)
  367. seen_chains.add(chain_id)
  368. chain_to_event.setdefault(chain_id, {})[sequence_number] = event_id
  369. # Check that we actually have a chain ID for all the events.
  370. events_missing_chain_info = initial_events.difference(chain_info)
  371. if events_missing_chain_info:
  372. # This can happen due to e.g. downgrade/upgrade of the server. We
  373. # raise an exception and fall back to the previous algorithm.
  374. logger.info(
  375. "Unexpectedly found that events don't have chain IDs in room %s: %s",
  376. room_id,
  377. events_missing_chain_info,
  378. )
  379. raise _NoChainCoverIndex(room_id)
  380. # Corresponds to `state_sets`, except as a map from chain ID to max
  381. # sequence number reachable from the state set.
  382. set_to_chain: List[Dict[int, int]] = []
  383. for state_set in state_sets:
  384. chains: Dict[int, int] = {}
  385. set_to_chain.append(chains)
  386. for event_id in state_set:
  387. chain_id, seq_no = chain_info[event_id]
  388. chains[chain_id] = max(seq_no, chains.get(chain_id, 0))
  389. # Now we look up all links for the chains we have, adding chains to
  390. # set_to_chain that are reachable from each set.
  391. sql = """
  392. SELECT
  393. origin_chain_id, origin_sequence_number,
  394. target_chain_id, target_sequence_number
  395. FROM event_auth_chain_links
  396. WHERE %s
  397. """
  398. # (We need to take a copy of `seen_chains` as we want to mutate it in
  399. # the loop)
  400. for batch2 in batch_iter(set(seen_chains), 1000):
  401. clause, args = make_in_list_sql_clause(
  402. txn.database_engine, "origin_chain_id", batch2
  403. )
  404. txn.execute(sql % (clause,), args)
  405. for (
  406. origin_chain_id,
  407. origin_sequence_number,
  408. target_chain_id,
  409. target_sequence_number,
  410. ) in txn:
  411. for chains in set_to_chain:
  412. # chains are only reachable if the origin sequence number of
  413. # the link is less than the max sequence number in the
  414. # origin chain.
  415. if origin_sequence_number <= chains.get(origin_chain_id, 0):
  416. chains[target_chain_id] = max(
  417. target_sequence_number,
  418. chains.get(target_chain_id, 0),
  419. )
  420. seen_chains.add(target_chain_id)
  421. # Now for each chain we figure out the maximum sequence number reachable
  422. # from *any* state set and the minimum sequence number reachable from
  423. # *all* state sets. Events in that range are in the auth chain
  424. # difference.
  425. result = set()
  426. # Mapping from chain ID to the range of sequence numbers that should be
  427. # pulled from the database.
  428. chain_to_gap: Dict[int, Tuple[int, int]] = {}
  429. for chain_id in seen_chains:
  430. min_seq_no = min(chains.get(chain_id, 0) for chains in set_to_chain)
  431. max_seq_no = max(chains.get(chain_id, 0) for chains in set_to_chain)
  432. if min_seq_no < max_seq_no:
  433. # We have a non empty gap, try and fill it from the events that
  434. # we have, otherwise add them to the list of gaps to pull out
  435. # from the DB.
  436. for seq_no in range(min_seq_no + 1, max_seq_no + 1):
  437. event_id = chain_to_event.get(chain_id, {}).get(seq_no)
  438. if event_id:
  439. result.add(event_id)
  440. else:
  441. chain_to_gap[chain_id] = (min_seq_no, max_seq_no)
  442. break
  443. if not chain_to_gap:
  444. # If there are no gaps to fetch, we're done!
  445. return result
  446. if isinstance(self.database_engine, PostgresEngine):
  447. # We can use `execute_values` to efficiently fetch the gaps when
  448. # using postgres.
  449. sql = """
  450. SELECT event_id
  451. FROM event_auth_chains AS c, (VALUES ?) AS l(chain_id, min_seq, max_seq)
  452. WHERE
  453. c.chain_id = l.chain_id
  454. AND min_seq < sequence_number AND sequence_number <= max_seq
  455. """
  456. args = [
  457. (chain_id, min_no, max_no)
  458. for chain_id, (min_no, max_no) in chain_to_gap.items()
  459. ]
  460. rows = txn.execute_values(sql, args)
  461. result.update(r for r, in rows)
  462. else:
  463. # For SQLite we just fall back to doing a noddy for loop.
  464. sql = """
  465. SELECT event_id FROM event_auth_chains
  466. WHERE chain_id = ? AND ? < sequence_number AND sequence_number <= ?
  467. """
  468. for chain_id, (min_no, max_no) in chain_to_gap.items():
  469. txn.execute(sql, (chain_id, min_no, max_no))
  470. result.update(r for r, in txn)
  471. return result
  472. def _get_auth_chain_difference_txn(
  473. self, txn: LoggingTransaction, state_sets: List[Set[str]]
  474. ) -> Set[str]:
  475. """Calculates the auth chain difference using a breadth first search.
  476. This is used when we don't have a cover index for the room.
  477. """
  478. # Algorithm Description
  479. # ~~~~~~~~~~~~~~~~~~~~~
  480. #
  481. # The idea here is to basically walk the auth graph of each state set in
  482. # tandem, keeping track of which auth events are reachable by each state
  483. # set. If we reach an auth event we've already visited (via a different
  484. # state set) then we mark that auth event and all ancestors as reachable
  485. # by the state set. This requires that we keep track of the auth chains
  486. # in memory.
  487. #
  488. # Doing it in a such a way means that we can stop early if all auth
  489. # events we're currently walking are reachable by all state sets.
  490. #
  491. # *Note*: We can't stop walking an event's auth chain if it is reachable
  492. # by all state sets. This is because other auth chains we're walking
  493. # might be reachable only via the original auth chain. For example,
  494. # given the following auth chain:
  495. #
  496. # A -> C -> D -> E
  497. # / /
  498. # B -´---------´
  499. #
  500. # and state sets {A} and {B} then walking the auth chains of A and B
  501. # would immediately show that C is reachable by both. However, if we
  502. # stopped at C then we'd only reach E via the auth chain of B and so E
  503. # would erroneously get included in the returned difference.
  504. #
  505. # The other thing that we do is limit the number of auth chains we walk
  506. # at once, due to practical limits (i.e. we can only query the database
  507. # with a limited set of parameters). We pick the auth chains we walk
  508. # each iteration based on their depth, in the hope that events with a
  509. # lower depth are likely reachable by those with higher depths.
  510. #
  511. # We could use any ordering that we believe would give a rough
  512. # topological ordering, e.g. origin server timestamp. If the ordering
  513. # chosen is not topological then the algorithm still produces the right
  514. # result, but perhaps a bit more inefficiently. This is why it is safe
  515. # to use "depth" here.
  516. initial_events = set(state_sets[0]).union(*state_sets[1:])
  517. # Dict from events in auth chains to which sets *cannot* reach them.
  518. # I.e. if the set is empty then all sets can reach the event.
  519. event_to_missing_sets = {
  520. event_id: {i for i, a in enumerate(state_sets) if event_id not in a}
  521. for event_id in initial_events
  522. }
  523. # The sorted list of events whose auth chains we should walk.
  524. search: List[Tuple[int, str]] = []
  525. # We need to get the depth of the initial events for sorting purposes.
  526. sql = """
  527. SELECT depth, event_id FROM events
  528. WHERE %s
  529. """
  530. # the list can be huge, so let's avoid looking them all up in one massive
  531. # query.
  532. for batch in batch_iter(initial_events, 1000):
  533. clause, args = make_in_list_sql_clause(
  534. txn.database_engine, "event_id", batch
  535. )
  536. txn.execute(sql % (clause,), args)
  537. # I think building a temporary list with fetchall is more efficient than
  538. # just `search.extend(txn)`, but this is unconfirmed
  539. search.extend(cast(List[Tuple[int, str]], txn.fetchall()))
  540. # sort by depth
  541. search.sort()
  542. # Map from event to its auth events
  543. event_to_auth_events: Dict[str, Set[str]] = {}
  544. base_sql = """
  545. SELECT a.event_id, auth_id, depth
  546. FROM event_auth AS a
  547. INNER JOIN events AS e ON (e.event_id = a.auth_id)
  548. WHERE
  549. """
  550. while search:
  551. # Check whether all our current walks are reachable by all state
  552. # sets. If so we can bail.
  553. if all(not event_to_missing_sets[eid] for _, eid in search):
  554. break
  555. # Fetch the auth events and their depths of the N last events we're
  556. # currently walking, either from cache or DB.
  557. search, chunk = search[:-100], search[-100:]
  558. found: List[Tuple[str, str, int]] = [] # Results found
  559. to_fetch: List[str] = [] # Event IDs to fetch from DB
  560. for _, event_id in chunk:
  561. res = self._event_auth_cache.get(event_id)
  562. if res is None:
  563. to_fetch.append(event_id)
  564. else:
  565. found.extend((event_id, auth_id, depth) for auth_id, depth in res)
  566. if to_fetch:
  567. clause, args = make_in_list_sql_clause(
  568. txn.database_engine, "a.event_id", to_fetch
  569. )
  570. txn.execute(base_sql + clause, args)
  571. # We parse the results and add the to the `found` set and the
  572. # cache (note we need to batch up the results by event ID before
  573. # adding to the cache).
  574. to_cache: Dict[str, List[Tuple[str, int]]] = {}
  575. for event_id, auth_event_id, auth_event_depth in txn:
  576. to_cache.setdefault(event_id, []).append(
  577. (auth_event_id, auth_event_depth)
  578. )
  579. found.append((event_id, auth_event_id, auth_event_depth))
  580. for event_id, auth_events in to_cache.items():
  581. self._event_auth_cache.set(event_id, auth_events)
  582. for event_id, auth_event_id, auth_event_depth in found:
  583. event_to_auth_events.setdefault(event_id, set()).add(auth_event_id)
  584. sets = event_to_missing_sets.get(auth_event_id)
  585. if sets is None:
  586. # First time we're seeing this event, so we add it to the
  587. # queue of things to fetch.
  588. search.append((auth_event_depth, auth_event_id))
  589. # Assume that this event is unreachable from any of the
  590. # state sets until proven otherwise
  591. sets = event_to_missing_sets[auth_event_id] = set(
  592. range(len(state_sets))
  593. )
  594. else:
  595. # We've previously seen this event, so look up its auth
  596. # events and recursively mark all ancestors as reachable
  597. # by the current event's state set.
  598. a_ids = event_to_auth_events.get(auth_event_id)
  599. while a_ids:
  600. new_aids = set()
  601. for a_id in a_ids:
  602. event_to_missing_sets[a_id].intersection_update(
  603. event_to_missing_sets[event_id]
  604. )
  605. b = event_to_auth_events.get(a_id)
  606. if b:
  607. new_aids.update(b)
  608. a_ids = new_aids
  609. # Mark that the auth event is reachable by the appropriate sets.
  610. sets.intersection_update(event_to_missing_sets[event_id])
  611. search.sort()
  612. # Return all events where not all sets can reach them.
  613. return {eid for eid, n in event_to_missing_sets.items() if n}
  614. @trace
  615. @tag_args
  616. async def get_backfill_points_in_room(
  617. self,
  618. room_id: str,
  619. ) -> List[Tuple[str, int]]:
  620. """
  621. Gets the oldest events(backwards extremities) in the room along with the
  622. approximate depth. Sorted by depth, highest to lowest (descending).
  623. Args:
  624. room_id: Room where we want to find the oldest events
  625. Returns:
  626. List of (event_id, depth) tuples. Sorted by depth, highest to lowest
  627. (descending)
  628. """
  629. def get_backfill_points_in_room_txn(
  630. txn: LoggingTransaction, room_id: str
  631. ) -> List[Tuple[str, int]]:
  632. # Assemble a tuple lookup of event_id -> depth for the oldest events
  633. # we know of in the room. Backwards extremeties are the oldest
  634. # events we know of in the room but we only know of them because
  635. # some other event referenced them by prev_event and aren't
  636. # persisted in our database yet (meaning we don't know their depth
  637. # specifically). So we need to look for the approximate depth from
  638. # the events connected to the current backwards extremeties.
  639. sql = """
  640. SELECT backward_extrem.event_id, event.depth FROM events AS event
  641. /**
  642. * Get the edge connections from the event_edges table
  643. * so we can see whether this event's prev_events points
  644. * to a backward extremity in the next join.
  645. */
  646. INNER JOIN event_edges AS edge
  647. ON edge.event_id = event.event_id
  648. /**
  649. * We find the "oldest" events in the room by looking for
  650. * events connected to backwards extremeties (oldest events
  651. * in the room that we know of so far).
  652. */
  653. INNER JOIN event_backward_extremities AS backward_extrem
  654. ON edge.prev_event_id = backward_extrem.event_id
  655. /**
  656. * We use this info to make sure we don't retry to use a backfill point
  657. * if we've already attempted to backfill from it recently.
  658. */
  659. LEFT JOIN event_failed_pull_attempts AS failed_backfill_attempt_info
  660. ON
  661. failed_backfill_attempt_info.room_id = backward_extrem.room_id
  662. AND failed_backfill_attempt_info.event_id = backward_extrem.event_id
  663. WHERE
  664. backward_extrem.room_id = ?
  665. /* We only care about non-state edges because we used to use
  666. * `event_edges` for two different sorts of "edges" (the current
  667. * event DAG, but also a link to the previous state, for state
  668. * events). These legacy state event edges can be distinguished by
  669. * `is_state` and are removed from the codebase and schema but
  670. * because the schema change is in a background update, it's not
  671. * necessarily safe to assume that it will have been completed.
  672. */
  673. AND edge.is_state is ? /* False */
  674. /**
  675. * Exponential back-off (up to the upper bound) so we don't retry the
  676. * same backfill point over and over. ex. 2hr, 4hr, 8hr, 16hr, etc.
  677. *
  678. * We use `1 << n` as a power of 2 equivalent for compatibility
  679. * with older SQLites. The left shift equivalent only works with
  680. * powers of 2 because left shift is a binary operation (base-2).
  681. * Otherwise, we would use `power(2, n)` or the power operator, `2^n`.
  682. */
  683. AND (
  684. failed_backfill_attempt_info.event_id IS NULL
  685. OR ? /* current_time */ >= failed_backfill_attempt_info.last_attempt_ts + /*least*/%s((1 << failed_backfill_attempt_info.num_attempts) * ? /* step */, ? /* upper bound */)
  686. )
  687. /**
  688. * Sort from highest to the lowest depth. Then tie-break on
  689. * alphabetical order of the event_ids so we get a consistent
  690. * ordering which is nice when asserting things in tests.
  691. */
  692. ORDER BY event.depth DESC, backward_extrem.event_id DESC
  693. """
  694. if isinstance(self.database_engine, PostgresEngine):
  695. least_function = "least"
  696. elif isinstance(self.database_engine, Sqlite3Engine):
  697. least_function = "min"
  698. else:
  699. raise RuntimeError("Unknown database engine")
  700. txn.execute(
  701. sql % (least_function,),
  702. (
  703. room_id,
  704. False,
  705. self._clock.time_msec(),
  706. 1000 * BACKFILL_EVENT_EXPONENTIAL_BACKOFF_STEP_SECONDS,
  707. 1000 * BACKFILL_EVENT_BACKOFF_UPPER_BOUND_SECONDS,
  708. ),
  709. )
  710. return cast(List[Tuple[str, int]], txn.fetchall())
  711. return await self.db_pool.runInteraction(
  712. "get_backfill_points_in_room",
  713. get_backfill_points_in_room_txn,
  714. room_id,
  715. )
  716. @trace
  717. async def get_insertion_event_backward_extremities_in_room(
  718. self,
  719. room_id: str,
  720. ) -> List[Tuple[str, int]]:
  721. """
  722. Get the insertion events we know about that we haven't backfilled yet
  723. along with the approximate depth. Sorted by depth, highest to lowest
  724. (descending).
  725. Args:
  726. room_id: Room where we want to find the oldest events
  727. Returns:
  728. List of (event_id, depth) tuples. Sorted by depth, highest to lowest
  729. (descending)
  730. """
  731. def get_insertion_event_backward_extremities_in_room_txn(
  732. txn: LoggingTransaction, room_id: str
  733. ) -> List[Tuple[str, int]]:
  734. sql = """
  735. SELECT
  736. insertion_event_extremity.event_id, event.depth
  737. /* We only want insertion events that are also marked as backwards extremities */
  738. FROM insertion_event_extremities AS insertion_event_extremity
  739. /* Get the depth of the insertion event from the events table */
  740. INNER JOIN events AS event USING (event_id)
  741. /**
  742. * We use this info to make sure we don't retry to use a backfill point
  743. * if we've already attempted to backfill from it recently.
  744. */
  745. LEFT JOIN event_failed_pull_attempts AS failed_backfill_attempt_info
  746. ON
  747. failed_backfill_attempt_info.room_id = insertion_event_extremity.room_id
  748. AND failed_backfill_attempt_info.event_id = insertion_event_extremity.event_id
  749. WHERE
  750. insertion_event_extremity.room_id = ?
  751. /**
  752. * Exponential back-off (up to the upper bound) so we don't retry the
  753. * same backfill point over and over. ex. 2hr, 4hr, 8hr, 16hr, etc
  754. *
  755. * We use `1 << n` as a power of 2 equivalent for compatibility
  756. * with older SQLites. The left shift equivalent only works with
  757. * powers of 2 because left shift is a binary operation (base-2).
  758. * Otherwise, we would use `power(2, n)` or the power operator, `2^n`.
  759. */
  760. AND (
  761. failed_backfill_attempt_info.event_id IS NULL
  762. OR ? /* current_time */ >= failed_backfill_attempt_info.last_attempt_ts + /*least*/%s((1 << failed_backfill_attempt_info.num_attempts) * ? /* step */, ? /* upper bound */)
  763. )
  764. /**
  765. * Sort from highest to the lowest depth. Then tie-break on
  766. * alphabetical order of the event_ids so we get a consistent
  767. * ordering which is nice when asserting things in tests.
  768. */
  769. ORDER BY event.depth DESC, insertion_event_extremity.event_id DESC
  770. """
  771. if isinstance(self.database_engine, PostgresEngine):
  772. least_function = "least"
  773. elif isinstance(self.database_engine, Sqlite3Engine):
  774. least_function = "min"
  775. else:
  776. raise RuntimeError("Unknown database engine")
  777. txn.execute(
  778. sql % (least_function,),
  779. (
  780. room_id,
  781. self._clock.time_msec(),
  782. 1000 * BACKFILL_EVENT_EXPONENTIAL_BACKOFF_STEP_SECONDS,
  783. 1000 * BACKFILL_EVENT_BACKOFF_UPPER_BOUND_SECONDS,
  784. ),
  785. )
  786. return cast(List[Tuple[str, int]], txn.fetchall())
  787. return await self.db_pool.runInteraction(
  788. "get_insertion_event_backward_extremities_in_room",
  789. get_insertion_event_backward_extremities_in_room_txn,
  790. room_id,
  791. )
  792. async def get_max_depth_of(self, event_ids: List[str]) -> Tuple[Optional[str], int]:
  793. """Returns the event ID and depth for the event that has the max depth from a set of event IDs
  794. Args:
  795. event_ids: The event IDs to calculate the max depth of.
  796. """
  797. rows = await self.db_pool.simple_select_many_batch(
  798. table="events",
  799. column="event_id",
  800. iterable=event_ids,
  801. retcols=(
  802. "event_id",
  803. "depth",
  804. ),
  805. desc="get_max_depth_of",
  806. )
  807. if not rows:
  808. return None, 0
  809. else:
  810. max_depth_event_id = ""
  811. current_max_depth = 0
  812. for row in rows:
  813. if row["depth"] > current_max_depth:
  814. max_depth_event_id = row["event_id"]
  815. current_max_depth = row["depth"]
  816. return max_depth_event_id, current_max_depth
  817. async def get_min_depth_of(self, event_ids: List[str]) -> Tuple[Optional[str], int]:
  818. """Returns the event ID and depth for the event that has the min depth from a set of event IDs
  819. Args:
  820. event_ids: The event IDs to calculate the max depth of.
  821. """
  822. rows = await self.db_pool.simple_select_many_batch(
  823. table="events",
  824. column="event_id",
  825. iterable=event_ids,
  826. retcols=(
  827. "event_id",
  828. "depth",
  829. ),
  830. desc="get_min_depth_of",
  831. )
  832. if not rows:
  833. return None, 0
  834. else:
  835. min_depth_event_id = ""
  836. current_min_depth = MAX_DEPTH
  837. for row in rows:
  838. if row["depth"] < current_min_depth:
  839. min_depth_event_id = row["event_id"]
  840. current_min_depth = row["depth"]
  841. return min_depth_event_id, current_min_depth
  842. async def get_prev_events_for_room(self, room_id: str) -> List[str]:
  843. """
  844. Gets a subset of the current forward extremities in the given room.
  845. Limits the result to 10 extremities, so that we can avoid creating
  846. events which refer to hundreds of prev_events.
  847. Args:
  848. room_id: room_id
  849. Returns:
  850. The event ids of the forward extremities.
  851. """
  852. return await self.db_pool.runInteraction(
  853. "get_prev_events_for_room", self._get_prev_events_for_room_txn, room_id
  854. )
  855. def _get_prev_events_for_room_txn(
  856. self, txn: LoggingTransaction, room_id: str
  857. ) -> List[str]:
  858. # we just use the 10 newest events. Older events will become
  859. # prev_events of future events.
  860. sql = """
  861. SELECT e.event_id FROM event_forward_extremities AS f
  862. INNER JOIN events AS e USING (event_id)
  863. WHERE f.room_id = ?
  864. ORDER BY e.depth DESC
  865. LIMIT 10
  866. """
  867. txn.execute(sql, (room_id,))
  868. return [row[0] for row in txn]
  869. async def get_rooms_with_many_extremities(
  870. self, min_count: int, limit: int, room_id_filter: Iterable[str]
  871. ) -> List[str]:
  872. """Get the top rooms with at least N extremities.
  873. Args:
  874. min_count: The minimum number of extremities
  875. limit: The maximum number of rooms to return.
  876. room_id_filter: room_ids to exclude from the results
  877. Returns:
  878. At most `limit` room IDs that have at least `min_count` extremities,
  879. sorted by extremity count.
  880. """
  881. def _get_rooms_with_many_extremities_txn(txn: LoggingTransaction) -> List[str]:
  882. where_clause = "1=1"
  883. if room_id_filter:
  884. where_clause = "room_id NOT IN (%s)" % (
  885. ",".join("?" for _ in room_id_filter),
  886. )
  887. sql = """
  888. SELECT room_id FROM event_forward_extremities
  889. WHERE %s
  890. GROUP BY room_id
  891. HAVING count(*) > ?
  892. ORDER BY count(*) DESC
  893. LIMIT ?
  894. """ % (
  895. where_clause,
  896. )
  897. query_args = list(itertools.chain(room_id_filter, [min_count, limit]))
  898. txn.execute(sql, query_args)
  899. return [room_id for room_id, in txn]
  900. return await self.db_pool.runInteraction(
  901. "get_rooms_with_many_extremities", _get_rooms_with_many_extremities_txn
  902. )
  903. @cached(max_entries=5000, iterable=True)
  904. async def get_latest_event_ids_in_room(self, room_id: str) -> List[str]:
  905. return await self.db_pool.simple_select_onecol(
  906. table="event_forward_extremities",
  907. keyvalues={"room_id": room_id},
  908. retcol="event_id",
  909. desc="get_latest_event_ids_in_room",
  910. )
  911. async def get_min_depth(self, room_id: str) -> Optional[int]:
  912. """For the given room, get the minimum depth we have seen for it."""
  913. return await self.db_pool.runInteraction(
  914. "get_min_depth", self._get_min_depth_interaction, room_id
  915. )
  916. def _get_min_depth_interaction(
  917. self, txn: LoggingTransaction, room_id: str
  918. ) -> Optional[int]:
  919. min_depth = self.db_pool.simple_select_one_onecol_txn(
  920. txn,
  921. table="room_depth",
  922. keyvalues={"room_id": room_id},
  923. retcol="min_depth",
  924. allow_none=True,
  925. )
  926. return int(min_depth) if min_depth is not None else None
  927. @cancellable
  928. async def get_forward_extremities_for_room_at_stream_ordering(
  929. self, room_id: str, stream_ordering: int
  930. ) -> List[str]:
  931. """For a given room_id and stream_ordering, return the forward
  932. extremeties of the room at that point in "time".
  933. Throws a StoreError if we have since purged the index for
  934. stream_orderings from that point.
  935. Args:
  936. room_id:
  937. stream_ordering:
  938. Returns:
  939. A list of event_ids
  940. """
  941. # We want to make the cache more effective, so we clamp to the last
  942. # change before the given ordering.
  943. last_change = self._events_stream_cache.get_max_pos_of_last_change(room_id) # type: ignore[attr-defined]
  944. # We don't always have a full stream_to_exterm_id table, e.g. after
  945. # the upgrade that introduced it, so we make sure we never ask for a
  946. # stream_ordering from before a restart
  947. last_change = max(self._stream_order_on_start, last_change) # type: ignore[attr-defined]
  948. # provided the last_change is recent enough, we now clamp the requested
  949. # stream_ordering to it.
  950. if last_change > self.stream_ordering_month_ago: # type: ignore[attr-defined]
  951. stream_ordering = min(last_change, stream_ordering)
  952. return await self._get_forward_extremeties_for_room(room_id, stream_ordering)
  953. @cached(max_entries=5000, num_args=2)
  954. async def _get_forward_extremeties_for_room(
  955. self, room_id: str, stream_ordering: int
  956. ) -> List[str]:
  957. """For a given room_id and stream_ordering, return the forward
  958. extremeties of the room at that point in "time".
  959. Throws a StoreError if we have since purged the index for
  960. stream_orderings from that point.
  961. """
  962. if stream_ordering <= self.stream_ordering_month_ago: # type: ignore[attr-defined]
  963. raise StoreError(400, "stream_ordering too old %s" % (stream_ordering,))
  964. sql = """
  965. SELECT event_id FROM stream_ordering_to_exterm
  966. INNER JOIN (
  967. SELECT room_id, MAX(stream_ordering) AS stream_ordering
  968. FROM stream_ordering_to_exterm
  969. WHERE stream_ordering <= ? GROUP BY room_id
  970. ) AS rms USING (room_id, stream_ordering)
  971. WHERE room_id = ?
  972. """
  973. def get_forward_extremeties_for_room_txn(txn: LoggingTransaction) -> List[str]:
  974. txn.execute(sql, (stream_ordering, room_id))
  975. return [event_id for event_id, in txn]
  976. return await self.db_pool.runInteraction(
  977. "get_forward_extremeties_for_room", get_forward_extremeties_for_room_txn
  978. )
  979. def _get_connected_batch_event_backfill_results_txn(
  980. self, txn: LoggingTransaction, insertion_event_id: str, limit: int
  981. ) -> List[BackfillQueueNavigationItem]:
  982. """
  983. Find any batch connections of a given insertion event.
  984. A batch event points at a insertion event via:
  985. batch_event.content[MSC2716_BATCH_ID] -> insertion_event.content[MSC2716_NEXT_BATCH_ID]
  986. Args:
  987. txn: The database transaction to use
  988. insertion_event_id: The event ID to navigate from. We will find
  989. batch events that point back at this insertion event.
  990. limit: Max number of event ID's to query for and return
  991. Returns:
  992. List of batch events that the backfill queue can process
  993. """
  994. batch_connection_query = """
  995. SELECT e.depth, e.stream_ordering, c.event_id, e.type FROM insertion_events AS i
  996. /* Find the batch that connects to the given insertion event */
  997. INNER JOIN batch_events AS c
  998. ON i.next_batch_id = c.batch_id
  999. /* Get the depth of the batch start event from the events table */
  1000. INNER JOIN events AS e ON c.event_id = e.event_id
  1001. /* Find an insertion event which matches the given event_id */
  1002. WHERE i.event_id = ?
  1003. LIMIT ?
  1004. """
  1005. # Find any batch connections for the given insertion event
  1006. txn.execute(
  1007. batch_connection_query,
  1008. (insertion_event_id, limit),
  1009. )
  1010. return [
  1011. BackfillQueueNavigationItem(
  1012. depth=row[0],
  1013. stream_ordering=row[1],
  1014. event_id=row[2],
  1015. type=row[3],
  1016. )
  1017. for row in txn
  1018. ]
  1019. def _get_connected_prev_event_backfill_results_txn(
  1020. self, txn: LoggingTransaction, event_id: str, limit: int
  1021. ) -> List[BackfillQueueNavigationItem]:
  1022. """
  1023. Find any events connected by prev_event the specified event_id.
  1024. Args:
  1025. txn: The database transaction to use
  1026. event_id: The event ID to navigate from
  1027. limit: Max number of event ID's to query for and return
  1028. Returns:
  1029. List of prev events that the backfill queue can process
  1030. """
  1031. # Look for the prev_event_id connected to the given event_id
  1032. connected_prev_event_query = """
  1033. SELECT depth, stream_ordering, prev_event_id, events.type FROM event_edges
  1034. /* Get the depth and stream_ordering of the prev_event_id from the events table */
  1035. INNER JOIN events
  1036. ON prev_event_id = events.event_id
  1037. /* exclude outliers from the results (we don't have the state, so cannot
  1038. * verify if the requesting server can see them).
  1039. */
  1040. WHERE NOT events.outlier
  1041. /* Look for an edge which matches the given event_id */
  1042. AND event_edges.event_id = ? AND NOT event_edges.is_state
  1043. /* Because we can have many events at the same depth,
  1044. * we want to also tie-break and sort on stream_ordering */
  1045. ORDER BY depth DESC, stream_ordering DESC
  1046. LIMIT ?
  1047. """
  1048. txn.execute(
  1049. connected_prev_event_query,
  1050. (event_id, limit),
  1051. )
  1052. return [
  1053. BackfillQueueNavigationItem(
  1054. depth=row[0],
  1055. stream_ordering=row[1],
  1056. event_id=row[2],
  1057. type=row[3],
  1058. )
  1059. for row in txn
  1060. ]
  1061. async def get_backfill_events(
  1062. self, room_id: str, seed_event_id_list: List[str], limit: int
  1063. ) -> List[EventBase]:
  1064. """Get a list of Events for a given topic that occurred before (and
  1065. including) the events in seed_event_id_list. Return a list of max size `limit`
  1066. Args:
  1067. room_id
  1068. seed_event_id_list
  1069. limit
  1070. """
  1071. event_ids = await self.db_pool.runInteraction(
  1072. "get_backfill_events",
  1073. self._get_backfill_events,
  1074. room_id,
  1075. seed_event_id_list,
  1076. limit,
  1077. )
  1078. events = await self.get_events_as_list(event_ids)
  1079. return sorted(
  1080. # type-ignore: mypy doesn't like negating the Optional[int] stream_ordering.
  1081. # But it's never None, because these events were previously persisted to the DB.
  1082. events,
  1083. key=lambda e: (-e.depth, -e.internal_metadata.stream_ordering), # type: ignore[operator]
  1084. )
  1085. def _get_backfill_events(
  1086. self,
  1087. txn: LoggingTransaction,
  1088. room_id: str,
  1089. seed_event_id_list: List[str],
  1090. limit: int,
  1091. ) -> Set[str]:
  1092. """
  1093. We want to make sure that we do a breadth-first, "depth" ordered search.
  1094. We also handle navigating historical branches of history connected by
  1095. insertion and batch events.
  1096. """
  1097. logger.debug(
  1098. "_get_backfill_events(room_id=%s): seeding backfill with seed_event_id_list=%s limit=%s",
  1099. room_id,
  1100. seed_event_id_list,
  1101. limit,
  1102. )
  1103. event_id_results: Set[str] = set()
  1104. # In a PriorityQueue, the lowest valued entries are retrieved first.
  1105. # We're using depth as the priority in the queue and tie-break based on
  1106. # stream_ordering. Depth is lowest at the oldest-in-time message and
  1107. # highest and newest-in-time message. We add events to the queue with a
  1108. # negative depth so that we process the newest-in-time messages first
  1109. # going backwards in time. stream_ordering follows the same pattern.
  1110. queue: "PriorityQueue[Tuple[int, int, str, str]]" = PriorityQueue()
  1111. for seed_event_id in seed_event_id_list:
  1112. event_lookup_result = self.db_pool.simple_select_one_txn(
  1113. txn,
  1114. table="events",
  1115. keyvalues={"event_id": seed_event_id, "room_id": room_id},
  1116. retcols=(
  1117. "type",
  1118. "depth",
  1119. "stream_ordering",
  1120. ),
  1121. allow_none=True,
  1122. )
  1123. if event_lookup_result is not None:
  1124. logger.debug(
  1125. "_get_backfill_events(room_id=%s): seed_event_id=%s depth=%s stream_ordering=%s type=%s",
  1126. room_id,
  1127. seed_event_id,
  1128. event_lookup_result["depth"],
  1129. event_lookup_result["stream_ordering"],
  1130. event_lookup_result["type"],
  1131. )
  1132. if event_lookup_result["depth"]:
  1133. queue.put(
  1134. (
  1135. -event_lookup_result["depth"],
  1136. -event_lookup_result["stream_ordering"],
  1137. seed_event_id,
  1138. event_lookup_result["type"],
  1139. )
  1140. )
  1141. while not queue.empty() and len(event_id_results) < limit:
  1142. try:
  1143. _, _, event_id, event_type = queue.get_nowait()
  1144. except Empty:
  1145. break
  1146. if event_id in event_id_results:
  1147. continue
  1148. event_id_results.add(event_id)
  1149. # Try and find any potential historical batches of message history.
  1150. if self.hs.config.experimental.msc2716_enabled:
  1151. # We need to go and try to find any batch events connected
  1152. # to a given insertion event (by batch_id). If we find any, we'll
  1153. # add them to the queue and navigate up the DAG like normal in the
  1154. # next iteration of the loop.
  1155. if event_type == EventTypes.MSC2716_INSERTION:
  1156. # Find any batch connections for the given insertion event
  1157. connected_batch_event_backfill_results = (
  1158. self._get_connected_batch_event_backfill_results_txn(
  1159. txn, event_id, limit - len(event_id_results)
  1160. )
  1161. )
  1162. logger.debug(
  1163. "_get_backfill_events(room_id=%s): connected_batch_event_backfill_results=%s",
  1164. room_id,
  1165. connected_batch_event_backfill_results,
  1166. )
  1167. for (
  1168. connected_batch_event_backfill_item
  1169. ) in connected_batch_event_backfill_results:
  1170. if (
  1171. connected_batch_event_backfill_item.event_id
  1172. not in event_id_results
  1173. ):
  1174. queue.put(
  1175. (
  1176. -connected_batch_event_backfill_item.depth,
  1177. -connected_batch_event_backfill_item.stream_ordering,
  1178. connected_batch_event_backfill_item.event_id,
  1179. connected_batch_event_backfill_item.type,
  1180. )
  1181. )
  1182. # Now we just look up the DAG by prev_events as normal
  1183. connected_prev_event_backfill_results = (
  1184. self._get_connected_prev_event_backfill_results_txn(
  1185. txn, event_id, limit - len(event_id_results)
  1186. )
  1187. )
  1188. logger.debug(
  1189. "_get_backfill_events(room_id=%s): connected_prev_event_backfill_results=%s",
  1190. room_id,
  1191. connected_prev_event_backfill_results,
  1192. )
  1193. for (
  1194. connected_prev_event_backfill_item
  1195. ) in connected_prev_event_backfill_results:
  1196. if connected_prev_event_backfill_item.event_id not in event_id_results:
  1197. queue.put(
  1198. (
  1199. -connected_prev_event_backfill_item.depth,
  1200. -connected_prev_event_backfill_item.stream_ordering,
  1201. connected_prev_event_backfill_item.event_id,
  1202. connected_prev_event_backfill_item.type,
  1203. )
  1204. )
  1205. return event_id_results
  1206. @trace
  1207. async def record_event_failed_pull_attempt(
  1208. self, room_id: str, event_id: str, cause: str
  1209. ) -> None:
  1210. """
  1211. Record when we fail to pull an event over federation.
  1212. This information allows us to be more intelligent when we decide to
  1213. retry (we don't need to fail over and over) and we can process that
  1214. event in the background so we don't block on it each time.
  1215. Args:
  1216. room_id: The room where the event failed to pull from
  1217. event_id: The event that failed to be fetched or processed
  1218. cause: The error message or reason that we failed to pull the event
  1219. """
  1220. await self.db_pool.runInteraction(
  1221. "record_event_failed_pull_attempt",
  1222. self._record_event_failed_pull_attempt_upsert_txn,
  1223. room_id,
  1224. event_id,
  1225. cause,
  1226. db_autocommit=True, # Safe as it's a single upsert
  1227. )
  1228. def _record_event_failed_pull_attempt_upsert_txn(
  1229. self,
  1230. txn: LoggingTransaction,
  1231. room_id: str,
  1232. event_id: str,
  1233. cause: str,
  1234. ) -> None:
  1235. sql = """
  1236. INSERT INTO event_failed_pull_attempts (
  1237. room_id, event_id, num_attempts, last_attempt_ts, last_cause
  1238. )
  1239. VALUES (?, ?, ?, ?, ?)
  1240. ON CONFLICT (room_id, event_id) DO UPDATE SET
  1241. num_attempts=event_failed_pull_attempts.num_attempts + 1,
  1242. last_attempt_ts=EXCLUDED.last_attempt_ts,
  1243. last_cause=EXCLUDED.last_cause;
  1244. """
  1245. txn.execute(sql, (room_id, event_id, 1, self._clock.time_msec(), cause))
  1246. async def get_missing_events(
  1247. self,
  1248. room_id: str,
  1249. earliest_events: List[str],
  1250. latest_events: List[str],
  1251. limit: int,
  1252. ) -> List[EventBase]:
  1253. ids = await self.db_pool.runInteraction(
  1254. "get_missing_events",
  1255. self._get_missing_events,
  1256. room_id,
  1257. earliest_events,
  1258. latest_events,
  1259. limit,
  1260. )
  1261. return await self.get_events_as_list(ids)
  1262. def _get_missing_events(
  1263. self,
  1264. txn: LoggingTransaction,
  1265. room_id: str,
  1266. earliest_events: List[str],
  1267. latest_events: List[str],
  1268. limit: int,
  1269. ) -> List[str]:
  1270. seen_events = set(earliest_events)
  1271. front = set(latest_events) - seen_events
  1272. event_results: List[str] = []
  1273. query = (
  1274. "SELECT prev_event_id FROM event_edges "
  1275. "WHERE event_id = ? AND NOT is_state "
  1276. "LIMIT ?"
  1277. )
  1278. while front and len(event_results) < limit:
  1279. new_front = set()
  1280. for event_id in front:
  1281. txn.execute(query, (event_id, limit - len(event_results)))
  1282. new_results = {t[0] for t in txn} - seen_events
  1283. new_front |= new_results
  1284. seen_events |= new_results
  1285. event_results.extend(new_results)
  1286. front = new_front
  1287. # we built the list working backwards from latest_events; we now need to
  1288. # reverse it so that the events are approximately chronological.
  1289. event_results.reverse()
  1290. return event_results
  1291. @trace
  1292. @tag_args
  1293. async def get_successor_events(self, event_id: str) -> List[str]:
  1294. """Fetch all events that have the given event as a prev event
  1295. Args:
  1296. event_id: The event to search for as a prev_event.
  1297. """
  1298. return await self.db_pool.simple_select_onecol(
  1299. table="event_edges",
  1300. keyvalues={"prev_event_id": event_id},
  1301. retcol="event_id",
  1302. desc="get_successor_events",
  1303. )
  1304. @wrap_as_background_process("delete_old_forward_extrem_cache")
  1305. async def _delete_old_forward_extrem_cache(self) -> None:
  1306. def _delete_old_forward_extrem_cache_txn(txn: LoggingTransaction) -> None:
  1307. # Delete entries older than a month, while making sure we don't delete
  1308. # the only entries for a room.
  1309. sql = """
  1310. DELETE FROM stream_ordering_to_exterm
  1311. WHERE
  1312. room_id IN (
  1313. SELECT room_id
  1314. FROM stream_ordering_to_exterm
  1315. WHERE stream_ordering > ?
  1316. ) AND stream_ordering < ?
  1317. """
  1318. txn.execute(
  1319. sql, (self.stream_ordering_month_ago, self.stream_ordering_month_ago) # type: ignore[attr-defined]
  1320. )
  1321. await self.db_pool.runInteraction(
  1322. "_delete_old_forward_extrem_cache",
  1323. _delete_old_forward_extrem_cache_txn,
  1324. )
  1325. @trace
  1326. async def insert_insertion_extremity(self, event_id: str, room_id: str) -> None:
  1327. await self.db_pool.simple_upsert(
  1328. table="insertion_event_extremities",
  1329. keyvalues={"event_id": event_id},
  1330. values={
  1331. "event_id": event_id,
  1332. "room_id": room_id,
  1333. },
  1334. insertion_values={},
  1335. desc="insert_insertion_extremity",
  1336. lock=False,
  1337. )
  1338. async def insert_received_event_to_staging(
  1339. self, origin: str, event: EventBase
  1340. ) -> None:
  1341. """Insert a newly received event from federation into the staging area."""
  1342. # We use an upsert here to handle the case where we see the same event
  1343. # from the same server multiple times.
  1344. await self.db_pool.simple_upsert(
  1345. table="federation_inbound_events_staging",
  1346. keyvalues={
  1347. "origin": origin,
  1348. "event_id": event.event_id,
  1349. },
  1350. values={},
  1351. insertion_values={
  1352. "room_id": event.room_id,
  1353. "received_ts": self._clock.time_msec(),
  1354. "event_json": json_encoder.encode(event.get_dict()),
  1355. "internal_metadata": json_encoder.encode(
  1356. event.internal_metadata.get_dict()
  1357. ),
  1358. },
  1359. desc="insert_received_event_to_staging",
  1360. )
  1361. async def remove_received_event_from_staging(
  1362. self,
  1363. origin: str,
  1364. event_id: str,
  1365. ) -> Optional[int]:
  1366. """Remove the given event from the staging area.
  1367. Returns:
  1368. The received_ts of the row that was deleted, if any.
  1369. """
  1370. if self.db_pool.engine.supports_returning:
  1371. def _remove_received_event_from_staging_txn(
  1372. txn: LoggingTransaction,
  1373. ) -> Optional[int]:
  1374. sql = """
  1375. DELETE FROM federation_inbound_events_staging
  1376. WHERE origin = ? AND event_id = ?
  1377. RETURNING received_ts
  1378. """
  1379. txn.execute(sql, (origin, event_id))
  1380. row = cast(Optional[Tuple[int]], txn.fetchone())
  1381. if row is None:
  1382. return None
  1383. return row[0]
  1384. return await self.db_pool.runInteraction(
  1385. "remove_received_event_from_staging",
  1386. _remove_received_event_from_staging_txn,
  1387. db_autocommit=True,
  1388. )
  1389. else:
  1390. def _remove_received_event_from_staging_txn(
  1391. txn: LoggingTransaction,
  1392. ) -> Optional[int]:
  1393. received_ts = self.db_pool.simple_select_one_onecol_txn(
  1394. txn,
  1395. table="federation_inbound_events_staging",
  1396. keyvalues={
  1397. "origin": origin,
  1398. "event_id": event_id,
  1399. },
  1400. retcol="received_ts",
  1401. allow_none=True,
  1402. )
  1403. self.db_pool.simple_delete_txn(
  1404. txn,
  1405. table="federation_inbound_events_staging",
  1406. keyvalues={
  1407. "origin": origin,
  1408. "event_id": event_id,
  1409. },
  1410. )
  1411. return received_ts
  1412. return await self.db_pool.runInteraction(
  1413. "remove_received_event_from_staging",
  1414. _remove_received_event_from_staging_txn,
  1415. )
  1416. async def get_next_staged_event_id_for_room(
  1417. self,
  1418. room_id: str,
  1419. ) -> Optional[Tuple[str, str]]:
  1420. """
  1421. Get the next event ID in the staging area for the given room.
  1422. Returns:
  1423. Tuple of the `origin` and `event_id`
  1424. """
  1425. def _get_next_staged_event_id_for_room_txn(
  1426. txn: LoggingTransaction,
  1427. ) -> Optional[Tuple[str, str]]:
  1428. sql = """
  1429. SELECT origin, event_id
  1430. FROM federation_inbound_events_staging
  1431. WHERE room_id = ?
  1432. ORDER BY received_ts ASC
  1433. LIMIT 1
  1434. """
  1435. txn.execute(sql, (room_id,))
  1436. return cast(Optional[Tuple[str, str]], txn.fetchone())
  1437. return await self.db_pool.runInteraction(
  1438. "get_next_staged_event_id_for_room", _get_next_staged_event_id_for_room_txn
  1439. )
  1440. async def get_next_staged_event_for_room(
  1441. self,
  1442. room_id: str,
  1443. room_version: RoomVersion,
  1444. ) -> Optional[Tuple[str, EventBase]]:
  1445. """Get the next event in the staging area for the given room."""
  1446. def _get_next_staged_event_for_room_txn(
  1447. txn: LoggingTransaction,
  1448. ) -> Optional[Tuple[str, str, str]]:
  1449. sql = """
  1450. SELECT event_json, internal_metadata, origin
  1451. FROM federation_inbound_events_staging
  1452. WHERE room_id = ?
  1453. ORDER BY received_ts ASC
  1454. LIMIT 1
  1455. """
  1456. txn.execute(sql, (room_id,))
  1457. return cast(Optional[Tuple[str, str, str]], txn.fetchone())
  1458. row = await self.db_pool.runInteraction(
  1459. "get_next_staged_event_for_room", _get_next_staged_event_for_room_txn
  1460. )
  1461. if not row:
  1462. return None
  1463. event_d = db_to_json(row[0])
  1464. internal_metadata_d = db_to_json(row[1])
  1465. origin = row[2]
  1466. event = make_event_from_dict(
  1467. event_dict=event_d,
  1468. room_version=room_version,
  1469. internal_metadata_dict=internal_metadata_d,
  1470. )
  1471. return origin, event
  1472. async def prune_staged_events_in_room(
  1473. self,
  1474. room_id: str,
  1475. room_version: RoomVersion,
  1476. ) -> bool:
  1477. """Checks if there are lots of staged events for the room, and if so
  1478. prune them down.
  1479. Returns:
  1480. Whether any events were pruned
  1481. """
  1482. # First check the size of the queue.
  1483. count = await self.db_pool.simple_select_one_onecol(
  1484. table="federation_inbound_events_staging",
  1485. keyvalues={"room_id": room_id},
  1486. retcol="COUNT(*)",
  1487. desc="prune_staged_events_in_room_count",
  1488. )
  1489. if count < 100:
  1490. return False
  1491. # If the queue is too large, then we want clear the entire queue,
  1492. # keeping only the forward extremities (i.e. the events not referenced
  1493. # by other events in the queue). We do this so that we can always
  1494. # backpaginate in all the events we have dropped.
  1495. rows = await self.db_pool.simple_select_list(
  1496. table="federation_inbound_events_staging",
  1497. keyvalues={"room_id": room_id},
  1498. retcols=("event_id", "event_json"),
  1499. desc="prune_staged_events_in_room_fetch",
  1500. )
  1501. # Find the set of events referenced by those in the queue, as well as
  1502. # collecting all the event IDs in the queue.
  1503. referenced_events: Set[str] = set()
  1504. seen_events: Set[str] = set()
  1505. for row in rows:
  1506. event_id = row["event_id"]
  1507. seen_events.add(event_id)
  1508. event_d = db_to_json(row["event_json"])
  1509. # We don't bother parsing the dicts into full blown event objects,
  1510. # as that is needlessly expensive.
  1511. # We haven't checked that the `prev_events` have the right format
  1512. # yet, so we check as we go.
  1513. prev_events = event_d.get("prev_events", [])
  1514. if not isinstance(prev_events, list):
  1515. logger.info("Invalid prev_events for %s", event_id)
  1516. continue
  1517. if room_version.event_format == EventFormatVersions.ROOM_V1_V2:
  1518. for prev_event_tuple in prev_events:
  1519. if (
  1520. not isinstance(prev_event_tuple, list)
  1521. or len(prev_event_tuple) != 2
  1522. ):
  1523. logger.info("Invalid prev_events for %s", event_id)
  1524. break
  1525. prev_event_id = prev_event_tuple[0]
  1526. if not isinstance(prev_event_id, str):
  1527. logger.info("Invalid prev_events for %s", event_id)
  1528. break
  1529. referenced_events.add(prev_event_id)
  1530. else:
  1531. for prev_event_id in prev_events:
  1532. if not isinstance(prev_event_id, str):
  1533. logger.info("Invalid prev_events for %s", event_id)
  1534. break
  1535. referenced_events.add(prev_event_id)
  1536. to_delete = referenced_events & seen_events
  1537. if not to_delete:
  1538. return False
  1539. pdus_pruned_from_federation_queue.inc(len(to_delete))
  1540. logger.info(
  1541. "Pruning %d events in room %s from federation queue",
  1542. len(to_delete),
  1543. room_id,
  1544. )
  1545. await self.db_pool.simple_delete_many(
  1546. table="federation_inbound_events_staging",
  1547. keyvalues={"room_id": room_id},
  1548. iterable=to_delete,
  1549. column="event_id",
  1550. desc="prune_staged_events_in_room_delete",
  1551. )
  1552. return True
  1553. async def get_all_rooms_with_staged_incoming_events(self) -> List[str]:
  1554. """Get the room IDs of all events currently staged."""
  1555. return await self.db_pool.simple_select_onecol(
  1556. table="federation_inbound_events_staging",
  1557. keyvalues={},
  1558. retcol="DISTINCT room_id",
  1559. desc="get_all_rooms_with_staged_incoming_events",
  1560. )
  1561. @wrap_as_background_process("_get_stats_for_federation_staging")
  1562. async def _get_stats_for_federation_staging(self) -> None:
  1563. """Update the prometheus metrics for the inbound federation staging area."""
  1564. def _get_stats_for_federation_staging_txn(
  1565. txn: LoggingTransaction,
  1566. ) -> Tuple[int, int]:
  1567. txn.execute("SELECT count(*) FROM federation_inbound_events_staging")
  1568. (count,) = cast(Tuple[int], txn.fetchone())
  1569. txn.execute(
  1570. "SELECT min(received_ts) FROM federation_inbound_events_staging"
  1571. )
  1572. (received_ts,) = cast(Tuple[Optional[int]], txn.fetchone())
  1573. # If there is nothing in the staging area default it to 0.
  1574. age = 0
  1575. if received_ts is not None:
  1576. age = self._clock.time_msec() - received_ts
  1577. return count, age
  1578. count, age = await self.db_pool.runInteraction(
  1579. "_get_stats_for_federation_staging", _get_stats_for_federation_staging_txn
  1580. )
  1581. number_pdus_in_federation_queue.set(count)
  1582. oldest_pdu_in_federation_staging.set(age)
  1583. class EventFederationStore(EventFederationWorkerStore):
  1584. """Responsible for storing and serving up the various graphs associated
  1585. with an event. Including the main event graph and the auth chains for an
  1586. event.
  1587. Also has methods for getting the front (latest) and back (oldest) edges
  1588. of the event graphs. These are used to generate the parents for new events
  1589. and backfilling from another server respectively.
  1590. """
  1591. EVENT_AUTH_STATE_ONLY = "event_auth_state_only"
  1592. def __init__(
  1593. self,
  1594. database: DatabasePool,
  1595. db_conn: LoggingDatabaseConnection,
  1596. hs: "HomeServer",
  1597. ):
  1598. super().__init__(database, db_conn, hs)
  1599. self.db_pool.updates.register_background_update_handler(
  1600. self.EVENT_AUTH_STATE_ONLY, self._background_delete_non_state_event_auth
  1601. )
  1602. async def clean_room_for_join(self, room_id: str) -> None:
  1603. await self.db_pool.runInteraction(
  1604. "clean_room_for_join", self._clean_room_for_join_txn, room_id
  1605. )
  1606. def _clean_room_for_join_txn(self, txn: LoggingTransaction, room_id: str) -> None:
  1607. query = "DELETE FROM event_forward_extremities WHERE room_id = ?"
  1608. txn.execute(query, (room_id,))
  1609. txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,))
  1610. async def _background_delete_non_state_event_auth(
  1611. self, progress: JsonDict, batch_size: int
  1612. ) -> int:
  1613. def delete_event_auth(txn: LoggingTransaction) -> bool:
  1614. target_min_stream_id = progress.get("target_min_stream_id_inclusive")
  1615. max_stream_id = progress.get("max_stream_id_exclusive")
  1616. if not target_min_stream_id or not max_stream_id:
  1617. txn.execute("SELECT COALESCE(MIN(stream_ordering), 0) FROM events")
  1618. rows = txn.fetchall()
  1619. target_min_stream_id = rows[0][0]
  1620. txn.execute("SELECT COALESCE(MAX(stream_ordering), 0) FROM events")
  1621. rows = txn.fetchall()
  1622. max_stream_id = rows[0][0]
  1623. min_stream_id = max_stream_id - batch_size
  1624. sql = """
  1625. DELETE FROM event_auth
  1626. WHERE event_id IN (
  1627. SELECT event_id FROM events
  1628. LEFT JOIN state_events AS se USING (room_id, event_id)
  1629. WHERE ? <= stream_ordering AND stream_ordering < ?
  1630. AND se.state_key IS null
  1631. )
  1632. """
  1633. txn.execute(sql, (min_stream_id, max_stream_id))
  1634. new_progress = {
  1635. "target_min_stream_id_inclusive": target_min_stream_id,
  1636. "max_stream_id_exclusive": min_stream_id,
  1637. }
  1638. self.db_pool.updates._background_update_progress_txn(
  1639. txn, self.EVENT_AUTH_STATE_ONLY, new_progress
  1640. )
  1641. return min_stream_id >= target_min_stream_id
  1642. result = await self.db_pool.runInteraction(
  1643. self.EVENT_AUTH_STATE_ONLY, delete_event_auth
  1644. )
  1645. if not result:
  1646. await self.db_pool.updates._end_background_update(
  1647. self.EVENT_AUTH_STATE_ONLY
  1648. )
  1649. return batch_size