You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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