25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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