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.
 
 
 
 
 
 

1501 lines
56 KiB

  1. # Copyright 2019-2022 The Matrix.org Foundation C.I.C.
  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 logging
  15. from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, cast
  16. import attr
  17. from synapse.api.constants import EventContentFields, RelationTypes
  18. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
  19. from synapse.events import make_event_from_dict
  20. from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause
  21. from synapse.storage.database import (
  22. DatabasePool,
  23. LoggingDatabaseConnection,
  24. LoggingTransaction,
  25. make_tuple_comparison_clause,
  26. )
  27. from synapse.storage.databases.main.events import PersistEventsStore
  28. from synapse.storage.types import Cursor
  29. from synapse.types import JsonDict, StrCollection
  30. if TYPE_CHECKING:
  31. from synapse.server import HomeServer
  32. logger = logging.getLogger(__name__)
  33. _REPLACE_STREAM_ORDERING_SQL_COMMANDS = (
  34. # there should be no leftover rows without a stream_ordering2, but just in case...
  35. "UPDATE events SET stream_ordering2 = stream_ordering WHERE stream_ordering2 IS NULL",
  36. # now we can drop the rule and switch the columns
  37. "DROP RULE populate_stream_ordering2 ON events",
  38. "ALTER TABLE events DROP COLUMN stream_ordering",
  39. "ALTER TABLE events RENAME COLUMN stream_ordering2 TO stream_ordering",
  40. # ... and finally, rename the indexes into place for consistency with sqlite
  41. "ALTER INDEX event_contains_url_index2 RENAME TO event_contains_url_index",
  42. "ALTER INDEX events_order_room2 RENAME TO events_order_room",
  43. "ALTER INDEX events_room_stream2 RENAME TO events_room_stream",
  44. "ALTER INDEX events_ts2 RENAME TO events_ts",
  45. )
  46. class _BackgroundUpdates:
  47. EVENT_ORIGIN_SERVER_TS_NAME = "event_origin_server_ts"
  48. EVENT_FIELDS_SENDER_URL_UPDATE_NAME = "event_fields_sender_url"
  49. DELETE_SOFT_FAILED_EXTREMITIES = "delete_soft_failed_extremities"
  50. POPULATE_STREAM_ORDERING2 = "populate_stream_ordering2"
  51. INDEX_STREAM_ORDERING2 = "index_stream_ordering2"
  52. INDEX_STREAM_ORDERING2_CONTAINS_URL = "index_stream_ordering2_contains_url"
  53. INDEX_STREAM_ORDERING2_ROOM_ORDER = "index_stream_ordering2_room_order"
  54. INDEX_STREAM_ORDERING2_ROOM_STREAM = "index_stream_ordering2_room_stream"
  55. INDEX_STREAM_ORDERING2_TS = "index_stream_ordering2_ts"
  56. REPLACE_STREAM_ORDERING_COLUMN = "replace_stream_ordering_column"
  57. EVENT_EDGES_DROP_INVALID_ROWS = "event_edges_drop_invalid_rows"
  58. EVENT_EDGES_REPLACE_INDEX = "event_edges_replace_index"
  59. EVENTS_POPULATE_STATE_KEY_REJECTIONS = "events_populate_state_key_rejections"
  60. EVENTS_JUMP_TO_DATE_INDEX = "events_jump_to_date_index"
  61. @attr.s(slots=True, frozen=True, auto_attribs=True)
  62. class _CalculateChainCover:
  63. """Return value for _calculate_chain_cover_txn."""
  64. # The last room_id/depth/stream processed.
  65. room_id: str
  66. depth: int
  67. stream: int
  68. # Number of rows processed
  69. processed_count: int
  70. # Map from room_id to last depth/stream processed for each room that we have
  71. # processed all events for (i.e. the rooms we can flip the
  72. # `has_auth_chain_index` for)
  73. finished_room_map: Dict[str, Tuple[int, int]]
  74. class EventsBackgroundUpdatesStore(SQLBaseStore):
  75. def __init__(
  76. self,
  77. database: DatabasePool,
  78. db_conn: LoggingDatabaseConnection,
  79. hs: "HomeServer",
  80. ):
  81. super().__init__(database, db_conn, hs)
  82. self.db_pool.updates.register_background_update_handler(
  83. _BackgroundUpdates.EVENT_ORIGIN_SERVER_TS_NAME,
  84. self._background_reindex_origin_server_ts,
  85. )
  86. self.db_pool.updates.register_background_update_handler(
  87. _BackgroundUpdates.EVENT_FIELDS_SENDER_URL_UPDATE_NAME,
  88. self._background_reindex_fields_sender,
  89. )
  90. self.db_pool.updates.register_background_index_update(
  91. "event_contains_url_index",
  92. index_name="event_contains_url_index",
  93. table="events",
  94. columns=["room_id", "topological_ordering", "stream_ordering"],
  95. where_clause="contains_url = true AND outlier = false",
  96. )
  97. # an event_id index on event_search is useful for the purge_history
  98. # api. Plus it means we get to enforce some integrity with a UNIQUE
  99. # clause
  100. self.db_pool.updates.register_background_index_update(
  101. "event_search_event_id_idx",
  102. index_name="event_search_event_id_idx",
  103. table="event_search",
  104. columns=["event_id"],
  105. unique=True,
  106. psql_only=True,
  107. )
  108. self.db_pool.updates.register_background_update_handler(
  109. _BackgroundUpdates.DELETE_SOFT_FAILED_EXTREMITIES,
  110. self._cleanup_extremities_bg_update,
  111. )
  112. self.db_pool.updates.register_background_update_handler(
  113. "redactions_received_ts", self._redactions_received_ts
  114. )
  115. # This index gets deleted in `event_fix_redactions_bytes` update
  116. self.db_pool.updates.register_background_index_update(
  117. "event_fix_redactions_bytes_create_index",
  118. index_name="redactions_censored_redacts",
  119. table="redactions",
  120. columns=["redacts"],
  121. where_clause="have_censored",
  122. )
  123. self.db_pool.updates.register_background_update_handler(
  124. "event_fix_redactions_bytes", self._event_fix_redactions_bytes
  125. )
  126. self.db_pool.updates.register_background_update_handler(
  127. "event_store_labels", self._event_store_labels
  128. )
  129. self.db_pool.updates.register_background_index_update(
  130. "redactions_have_censored_ts_idx",
  131. index_name="redactions_have_censored_ts",
  132. table="redactions",
  133. columns=["received_ts"],
  134. where_clause="NOT have_censored",
  135. )
  136. self.db_pool.updates.register_background_index_update(
  137. "users_have_local_media",
  138. index_name="users_have_local_media",
  139. table="local_media_repository",
  140. columns=["user_id", "created_ts"],
  141. )
  142. self.db_pool.updates.register_background_update_handler(
  143. "rejected_events_metadata",
  144. self._rejected_events_metadata,
  145. )
  146. self.db_pool.updates.register_background_update_handler(
  147. "chain_cover",
  148. self._chain_cover_index,
  149. )
  150. self.db_pool.updates.register_background_update_handler(
  151. "purged_chain_cover",
  152. self._purged_chain_cover_index,
  153. )
  154. self.db_pool.updates.register_background_update_handler(
  155. "event_arbitrary_relations",
  156. self._event_arbitrary_relations,
  157. )
  158. ################################################################################
  159. # bg updates for replacing stream_ordering with a BIGINT
  160. # (these only run on postgres.)
  161. self.db_pool.updates.register_background_update_handler(
  162. _BackgroundUpdates.POPULATE_STREAM_ORDERING2,
  163. self._background_populate_stream_ordering2,
  164. )
  165. # CREATE UNIQUE INDEX events_stream_ordering ON events(stream_ordering2);
  166. self.db_pool.updates.register_background_index_update(
  167. _BackgroundUpdates.INDEX_STREAM_ORDERING2,
  168. index_name="events_stream_ordering",
  169. table="events",
  170. columns=["stream_ordering2"],
  171. unique=True,
  172. )
  173. # CREATE INDEX event_contains_url_index ON events(room_id, topological_ordering, stream_ordering) WHERE contains_url = true AND outlier = false;
  174. self.db_pool.updates.register_background_index_update(
  175. _BackgroundUpdates.INDEX_STREAM_ORDERING2_CONTAINS_URL,
  176. index_name="event_contains_url_index2",
  177. table="events",
  178. columns=["room_id", "topological_ordering", "stream_ordering2"],
  179. where_clause="contains_url = true AND outlier = false",
  180. )
  181. # CREATE INDEX events_order_room ON events(room_id, topological_ordering, stream_ordering);
  182. self.db_pool.updates.register_background_index_update(
  183. _BackgroundUpdates.INDEX_STREAM_ORDERING2_ROOM_ORDER,
  184. index_name="events_order_room2",
  185. table="events",
  186. columns=["room_id", "topological_ordering", "stream_ordering2"],
  187. )
  188. # CREATE INDEX events_room_stream ON events(room_id, stream_ordering);
  189. self.db_pool.updates.register_background_index_update(
  190. _BackgroundUpdates.INDEX_STREAM_ORDERING2_ROOM_STREAM,
  191. index_name="events_room_stream2",
  192. table="events",
  193. columns=["room_id", "stream_ordering2"],
  194. )
  195. # CREATE INDEX events_ts ON events(origin_server_ts, stream_ordering);
  196. self.db_pool.updates.register_background_index_update(
  197. _BackgroundUpdates.INDEX_STREAM_ORDERING2_TS,
  198. index_name="events_ts2",
  199. table="events",
  200. columns=["origin_server_ts", "stream_ordering2"],
  201. )
  202. self.db_pool.updates.register_background_update_handler(
  203. _BackgroundUpdates.REPLACE_STREAM_ORDERING_COLUMN,
  204. self._background_replace_stream_ordering_column,
  205. )
  206. ################################################################################
  207. self.db_pool.updates.register_background_update_handler(
  208. _BackgroundUpdates.EVENT_EDGES_DROP_INVALID_ROWS,
  209. self._background_drop_invalid_event_edges_rows,
  210. )
  211. self.db_pool.updates.register_background_index_update(
  212. _BackgroundUpdates.EVENT_EDGES_REPLACE_INDEX,
  213. index_name="event_edges_event_id_prev_event_id_idx",
  214. table="event_edges",
  215. columns=["event_id", "prev_event_id"],
  216. unique=True,
  217. # the old index which just covered event_id is now redundant.
  218. replaces_index="ev_edges_id",
  219. )
  220. self.db_pool.updates.register_background_update_handler(
  221. _BackgroundUpdates.EVENTS_POPULATE_STATE_KEY_REJECTIONS,
  222. self._background_events_populate_state_key_rejections,
  223. )
  224. # Add an index that would be useful for jumping to date using
  225. # get_event_id_for_timestamp.
  226. self.db_pool.updates.register_background_index_update(
  227. _BackgroundUpdates.EVENTS_JUMP_TO_DATE_INDEX,
  228. index_name="events_jump_to_date_idx",
  229. table="events",
  230. columns=["room_id", "origin_server_ts"],
  231. where_clause="NOT outlier",
  232. )
  233. async def _background_reindex_fields_sender(
  234. self, progress: JsonDict, batch_size: int
  235. ) -> int:
  236. target_min_stream_id = progress["target_min_stream_id_inclusive"]
  237. max_stream_id = progress["max_stream_id_exclusive"]
  238. rows_inserted = progress.get("rows_inserted", 0)
  239. def reindex_txn(txn: LoggingTransaction) -> int:
  240. sql = (
  241. "SELECT stream_ordering, event_id, json FROM events"
  242. " INNER JOIN event_json USING (event_id)"
  243. " WHERE ? <= stream_ordering AND stream_ordering < ?"
  244. " ORDER BY stream_ordering DESC"
  245. " LIMIT ?"
  246. )
  247. txn.execute(sql, (target_min_stream_id, max_stream_id, batch_size))
  248. rows = txn.fetchall()
  249. if not rows:
  250. return 0
  251. min_stream_id = rows[-1][0]
  252. update_rows = []
  253. for row in rows:
  254. try:
  255. event_id = row[1]
  256. event_json = db_to_json(row[2])
  257. sender = event_json["sender"]
  258. content = event_json["content"]
  259. contains_url = "url" in content
  260. if contains_url:
  261. contains_url &= isinstance(content["url"], str)
  262. except (KeyError, AttributeError):
  263. # If the event is missing a necessary field then
  264. # skip over it.
  265. continue
  266. update_rows.append((sender, contains_url, event_id))
  267. sql = "UPDATE events SET sender = ?, contains_url = ? WHERE event_id = ?"
  268. txn.execute_batch(sql, update_rows)
  269. progress = {
  270. "target_min_stream_id_inclusive": target_min_stream_id,
  271. "max_stream_id_exclusive": min_stream_id,
  272. "rows_inserted": rows_inserted + len(rows),
  273. }
  274. self.db_pool.updates._background_update_progress_txn(
  275. txn, _BackgroundUpdates.EVENT_FIELDS_SENDER_URL_UPDATE_NAME, progress
  276. )
  277. return len(rows)
  278. result = await self.db_pool.runInteraction(
  279. _BackgroundUpdates.EVENT_FIELDS_SENDER_URL_UPDATE_NAME, reindex_txn
  280. )
  281. if not result:
  282. await self.db_pool.updates._end_background_update(
  283. _BackgroundUpdates.EVENT_FIELDS_SENDER_URL_UPDATE_NAME
  284. )
  285. return result
  286. async def _background_reindex_origin_server_ts(
  287. self, progress: JsonDict, batch_size: int
  288. ) -> int:
  289. target_min_stream_id = progress["target_min_stream_id_inclusive"]
  290. max_stream_id = progress["max_stream_id_exclusive"]
  291. rows_inserted = progress.get("rows_inserted", 0)
  292. def reindex_search_txn(txn: LoggingTransaction) -> int:
  293. sql = (
  294. "SELECT stream_ordering, event_id FROM events"
  295. " WHERE ? <= stream_ordering AND stream_ordering < ?"
  296. " ORDER BY stream_ordering DESC"
  297. " LIMIT ?"
  298. )
  299. txn.execute(sql, (target_min_stream_id, max_stream_id, batch_size))
  300. rows = txn.fetchall()
  301. if not rows:
  302. return 0
  303. min_stream_id = rows[-1][0]
  304. event_ids = [row[1] for row in rows]
  305. rows_to_update = []
  306. chunks = [event_ids[i : i + 100] for i in range(0, len(event_ids), 100)]
  307. for chunk in chunks:
  308. ev_rows = self.db_pool.simple_select_many_txn(
  309. txn,
  310. table="event_json",
  311. column="event_id",
  312. iterable=chunk,
  313. retcols=["event_id", "json"],
  314. keyvalues={},
  315. )
  316. for row in ev_rows:
  317. event_id = row["event_id"]
  318. event_json = db_to_json(row["json"])
  319. try:
  320. origin_server_ts = event_json["origin_server_ts"]
  321. except (KeyError, AttributeError):
  322. # If the event is missing a necessary field then
  323. # skip over it.
  324. continue
  325. rows_to_update.append((origin_server_ts, event_id))
  326. sql = "UPDATE events SET origin_server_ts = ? WHERE event_id = ?"
  327. txn.execute_batch(sql, rows_to_update)
  328. progress = {
  329. "target_min_stream_id_inclusive": target_min_stream_id,
  330. "max_stream_id_exclusive": min_stream_id,
  331. "rows_inserted": rows_inserted + len(rows_to_update),
  332. }
  333. self.db_pool.updates._background_update_progress_txn(
  334. txn, _BackgroundUpdates.EVENT_ORIGIN_SERVER_TS_NAME, progress
  335. )
  336. return len(rows_to_update)
  337. result = await self.db_pool.runInteraction(
  338. _BackgroundUpdates.EVENT_ORIGIN_SERVER_TS_NAME, reindex_search_txn
  339. )
  340. if not result:
  341. await self.db_pool.updates._end_background_update(
  342. _BackgroundUpdates.EVENT_ORIGIN_SERVER_TS_NAME
  343. )
  344. return result
  345. async def _cleanup_extremities_bg_update(
  346. self, progress: JsonDict, batch_size: int
  347. ) -> int:
  348. """Background update to clean out extremities that should have been
  349. deleted previously.
  350. Mainly used to deal with the aftermath of #5269.
  351. """
  352. # This works by first copying all existing forward extremities into the
  353. # `_extremities_to_check` table at start up, and then checking each
  354. # event in that table whether we have any descendants that are not
  355. # soft-failed/rejected. If that is the case then we delete that event
  356. # from the forward extremities table.
  357. #
  358. # For efficiency, we do this in batches by recursively pulling out all
  359. # descendants of a batch until we find the non soft-failed/rejected
  360. # events, i.e. the set of descendants whose chain of prev events back
  361. # to the batch of extremities are all soft-failed or rejected.
  362. # Typically, we won't find any such events as extremities will rarely
  363. # have any descendants, but if they do then we should delete those
  364. # extremities.
  365. def _cleanup_extremities_bg_update_txn(txn: LoggingTransaction) -> int:
  366. # The set of extremity event IDs that we're checking this round
  367. original_set = set()
  368. # A dict[str, Set[str]] of event ID to their prev events.
  369. graph: Dict[str, Set[str]] = {}
  370. # The set of descendants of the original set that are not rejected
  371. # nor soft-failed. Ancestors of these events should be removed
  372. # from the forward extremities table.
  373. non_rejected_leaves = set()
  374. # Set of event IDs that have been soft failed, and for which we
  375. # should check if they have descendants which haven't been soft
  376. # failed.
  377. soft_failed_events_to_lookup = set()
  378. # First, we get `batch_size` events from the table, pulling out
  379. # their successor events, if any, and the successor events'
  380. # rejection status.
  381. txn.execute(
  382. """SELECT prev_event_id, event_id, internal_metadata,
  383. rejections.event_id IS NOT NULL, events.outlier
  384. FROM (
  385. SELECT event_id AS prev_event_id
  386. FROM _extremities_to_check
  387. LIMIT ?
  388. ) AS f
  389. LEFT JOIN event_edges USING (prev_event_id)
  390. LEFT JOIN events USING (event_id)
  391. LEFT JOIN event_json USING (event_id)
  392. LEFT JOIN rejections USING (event_id)
  393. """,
  394. (batch_size,),
  395. )
  396. for prev_event_id, event_id, metadata, rejected, outlier in txn:
  397. original_set.add(prev_event_id)
  398. if not event_id or outlier:
  399. # Common case where the forward extremity doesn't have any
  400. # descendants.
  401. continue
  402. graph.setdefault(event_id, set()).add(prev_event_id)
  403. soft_failed = False
  404. if metadata:
  405. soft_failed = db_to_json(metadata).get("soft_failed")
  406. if soft_failed or rejected:
  407. soft_failed_events_to_lookup.add(event_id)
  408. else:
  409. non_rejected_leaves.add(event_id)
  410. # Now we recursively check all the soft-failed descendants we
  411. # found above in the same way, until we have nothing left to
  412. # check.
  413. while soft_failed_events_to_lookup:
  414. # We only want to do 100 at a time, so we split given list
  415. # into two.
  416. batch = list(soft_failed_events_to_lookup)
  417. to_check, to_defer = batch[:100], batch[100:]
  418. soft_failed_events_to_lookup = set(to_defer)
  419. sql = """SELECT prev_event_id, event_id, internal_metadata,
  420. rejections.event_id IS NOT NULL
  421. FROM event_edges
  422. INNER JOIN events USING (event_id)
  423. INNER JOIN event_json USING (event_id)
  424. LEFT JOIN rejections USING (event_id)
  425. WHERE
  426. NOT events.outlier
  427. AND
  428. """
  429. clause, args = make_in_list_sql_clause(
  430. self.database_engine, "prev_event_id", to_check
  431. )
  432. txn.execute(sql + clause, list(args))
  433. for prev_event_id, event_id, metadata, rejected in txn:
  434. if event_id in graph:
  435. # Already handled this event previously, but we still
  436. # want to record the edge.
  437. graph[event_id].add(prev_event_id)
  438. continue
  439. graph[event_id] = {prev_event_id}
  440. soft_failed = db_to_json(metadata).get("soft_failed")
  441. if soft_failed or rejected:
  442. soft_failed_events_to_lookup.add(event_id)
  443. else:
  444. non_rejected_leaves.add(event_id)
  445. # We have a set of non-soft-failed descendants, so we recurse up
  446. # the graph to find all ancestors and add them to the set of event
  447. # IDs that we can delete from forward extremities table.
  448. to_delete = set()
  449. while non_rejected_leaves:
  450. event_id = non_rejected_leaves.pop()
  451. prev_event_ids = graph.get(event_id, set())
  452. non_rejected_leaves.update(prev_event_ids)
  453. to_delete.update(prev_event_ids)
  454. to_delete.intersection_update(original_set)
  455. deleted = self.db_pool.simple_delete_many_txn(
  456. txn=txn,
  457. table="event_forward_extremities",
  458. column="event_id",
  459. values=to_delete,
  460. keyvalues={},
  461. )
  462. logger.info(
  463. "Deleted %d forward extremities of %d checked, to clean up #5269",
  464. deleted,
  465. len(original_set),
  466. )
  467. if deleted:
  468. # We now need to invalidate the caches of these rooms
  469. rows = self.db_pool.simple_select_many_txn(
  470. txn,
  471. table="events",
  472. column="event_id",
  473. iterable=to_delete,
  474. keyvalues={},
  475. retcols=("room_id",),
  476. )
  477. room_ids = {row["room_id"] for row in rows}
  478. for room_id in room_ids:
  479. txn.call_after(
  480. self.get_latest_event_ids_in_room.invalidate, (room_id,) # type: ignore[attr-defined]
  481. )
  482. self.db_pool.simple_delete_many_txn(
  483. txn=txn,
  484. table="_extremities_to_check",
  485. column="event_id",
  486. values=original_set,
  487. keyvalues={},
  488. )
  489. return len(original_set)
  490. num_handled = await self.db_pool.runInteraction(
  491. "_cleanup_extremities_bg_update", _cleanup_extremities_bg_update_txn
  492. )
  493. if not num_handled:
  494. await self.db_pool.updates._end_background_update(
  495. _BackgroundUpdates.DELETE_SOFT_FAILED_EXTREMITIES
  496. )
  497. def _drop_table_txn(txn: LoggingTransaction) -> None:
  498. txn.execute("DROP TABLE _extremities_to_check")
  499. await self.db_pool.runInteraction(
  500. "_cleanup_extremities_bg_update_drop_table", _drop_table_txn
  501. )
  502. return num_handled
  503. async def _redactions_received_ts(self, progress: JsonDict, batch_size: int) -> int:
  504. """Handles filling out the `received_ts` column in redactions."""
  505. last_event_id = progress.get("last_event_id", "")
  506. def _redactions_received_ts_txn(txn: LoggingTransaction) -> int:
  507. # Fetch the set of event IDs that we want to update
  508. sql = """
  509. SELECT event_id FROM redactions
  510. WHERE event_id > ?
  511. ORDER BY event_id ASC
  512. LIMIT ?
  513. """
  514. txn.execute(sql, (last_event_id, batch_size))
  515. rows = txn.fetchall()
  516. if not rows:
  517. return 0
  518. (upper_event_id,) = rows[-1]
  519. # Update the redactions with the received_ts.
  520. #
  521. # Note: Not all events have an associated received_ts, so we
  522. # fallback to using origin_server_ts. If we for some reason don't
  523. # have an origin_server_ts, lets just use the current timestamp.
  524. #
  525. # We don't want to leave it null, as then we'll never try and
  526. # censor those redactions.
  527. sql = """
  528. UPDATE redactions
  529. SET received_ts = (
  530. SELECT COALESCE(received_ts, origin_server_ts, ?) FROM events
  531. WHERE events.event_id = redactions.event_id
  532. )
  533. WHERE ? <= event_id AND event_id <= ?
  534. """
  535. txn.execute(sql, (self._clock.time_msec(), last_event_id, upper_event_id))
  536. self.db_pool.updates._background_update_progress_txn(
  537. txn, "redactions_received_ts", {"last_event_id": upper_event_id}
  538. )
  539. return len(rows)
  540. count = await self.db_pool.runInteraction(
  541. "_redactions_received_ts", _redactions_received_ts_txn
  542. )
  543. if not count:
  544. await self.db_pool.updates._end_background_update("redactions_received_ts")
  545. return count
  546. async def _event_fix_redactions_bytes(
  547. self, progress: JsonDict, batch_size: int
  548. ) -> int:
  549. """Undoes hex encoded censored redacted event JSON."""
  550. def _event_fix_redactions_bytes_txn(txn: LoggingTransaction) -> None:
  551. # This update is quite fast due to new index.
  552. txn.execute(
  553. """
  554. UPDATE event_json
  555. SET
  556. json = convert_from(json::bytea, 'utf8')
  557. FROM redactions
  558. WHERE
  559. redactions.have_censored
  560. AND event_json.event_id = redactions.redacts
  561. AND json NOT LIKE '{%';
  562. """
  563. )
  564. txn.execute("DROP INDEX redactions_censored_redacts")
  565. await self.db_pool.runInteraction(
  566. "_event_fix_redactions_bytes", _event_fix_redactions_bytes_txn
  567. )
  568. await self.db_pool.updates._end_background_update("event_fix_redactions_bytes")
  569. return 1
  570. async def _event_store_labels(self, progress: JsonDict, batch_size: int) -> int:
  571. """Background update handler which will store labels for existing events."""
  572. last_event_id = progress.get("last_event_id", "")
  573. def _event_store_labels_txn(txn: LoggingTransaction) -> int:
  574. txn.execute(
  575. """
  576. SELECT event_id, json FROM event_json
  577. LEFT JOIN event_labels USING (event_id)
  578. WHERE event_id > ? AND label IS NULL
  579. ORDER BY event_id LIMIT ?
  580. """,
  581. (last_event_id, batch_size),
  582. )
  583. results = list(txn)
  584. nbrows = 0
  585. last_row_event_id = ""
  586. for event_id, event_json_raw in results:
  587. try:
  588. event_json = db_to_json(event_json_raw)
  589. self.db_pool.simple_insert_many_txn(
  590. txn=txn,
  591. table="event_labels",
  592. keys=("event_id", "label", "room_id", "topological_ordering"),
  593. values=[
  594. (
  595. event_id,
  596. label,
  597. event_json["room_id"],
  598. event_json["depth"],
  599. )
  600. for label in event_json["content"].get(
  601. EventContentFields.LABELS, []
  602. )
  603. if isinstance(label, str)
  604. ],
  605. )
  606. except Exception as e:
  607. logger.warning(
  608. "Unable to load event %s (no labels will be imported): %s",
  609. event_id,
  610. e,
  611. )
  612. nbrows += 1
  613. last_row_event_id = event_id
  614. self.db_pool.updates._background_update_progress_txn(
  615. txn, "event_store_labels", {"last_event_id": last_row_event_id}
  616. )
  617. return nbrows
  618. num_rows = await self.db_pool.runInteraction(
  619. desc="event_store_labels", func=_event_store_labels_txn
  620. )
  621. if not num_rows:
  622. await self.db_pool.updates._end_background_update("event_store_labels")
  623. return num_rows
  624. async def _rejected_events_metadata(self, progress: dict, batch_size: int) -> int:
  625. """Adds rejected events to the `state_events` and `event_auth` metadata
  626. tables.
  627. """
  628. last_event_id = progress.get("last_event_id", "")
  629. def get_rejected_events(
  630. txn: Cursor,
  631. ) -> List[Tuple[str, str, JsonDict, bool, bool]]:
  632. # Fetch rejected event json, their room version and whether we have
  633. # inserted them into the state_events or auth_events tables.
  634. #
  635. # Note we can assume that events that don't have a corresponding
  636. # room version are V1 rooms.
  637. sql = """
  638. SELECT DISTINCT
  639. event_id,
  640. COALESCE(room_version, '1'),
  641. json,
  642. state_events.event_id IS NOT NULL,
  643. event_auth.event_id IS NOT NULL
  644. FROM rejections
  645. INNER JOIN event_json USING (event_id)
  646. LEFT JOIN rooms USING (room_id)
  647. LEFT JOIN state_events USING (event_id)
  648. LEFT JOIN event_auth USING (event_id)
  649. WHERE event_id > ?
  650. ORDER BY event_id
  651. LIMIT ?
  652. """
  653. txn.execute(
  654. sql,
  655. (
  656. last_event_id,
  657. batch_size,
  658. ),
  659. )
  660. return cast(
  661. List[Tuple[str, str, JsonDict, bool, bool]],
  662. [(row[0], row[1], db_to_json(row[2]), row[3], row[4]) for row in txn],
  663. )
  664. results = await self.db_pool.runInteraction(
  665. desc="_rejected_events_metadata_get", func=get_rejected_events
  666. )
  667. if not results:
  668. await self.db_pool.updates._end_background_update(
  669. "rejected_events_metadata"
  670. )
  671. return 0
  672. state_events = []
  673. auth_events = []
  674. for event_id, room_version, event_json, has_state, has_event_auth in results:
  675. last_event_id = event_id
  676. if has_state and has_event_auth:
  677. continue
  678. room_version_obj = KNOWN_ROOM_VERSIONS.get(room_version)
  679. if not room_version_obj:
  680. # We no longer support this room version, so we just ignore the
  681. # events entirely.
  682. logger.info(
  683. "Ignoring event with unknown room version %r: %r",
  684. room_version,
  685. event_id,
  686. )
  687. continue
  688. event = make_event_from_dict(event_json, room_version_obj)
  689. if not event.is_state():
  690. continue
  691. if not has_state:
  692. state_events.append(
  693. (event.event_id, event.room_id, event.type, event.state_key)
  694. )
  695. if not has_event_auth:
  696. # Old, dodgy, events may have duplicate auth events, which we
  697. # need to deduplicate as we have a unique constraint.
  698. for auth_id in set(event.auth_event_ids()):
  699. auth_events.append((event.event_id, event.room_id, auth_id))
  700. if state_events:
  701. await self.db_pool.simple_insert_many(
  702. table="state_events",
  703. keys=("event_id", "room_id", "type", "state_key"),
  704. values=state_events,
  705. desc="_rejected_events_metadata_state_events",
  706. )
  707. if auth_events:
  708. await self.db_pool.simple_insert_many(
  709. table="event_auth",
  710. keys=("event_id", "room_id", "auth_id"),
  711. values=auth_events,
  712. desc="_rejected_events_metadata_event_auth",
  713. )
  714. await self.db_pool.updates._background_update_progress(
  715. "rejected_events_metadata", {"last_event_id": last_event_id}
  716. )
  717. if len(results) < batch_size:
  718. await self.db_pool.updates._end_background_update(
  719. "rejected_events_metadata"
  720. )
  721. return len(results)
  722. async def _chain_cover_index(self, progress: dict, batch_size: int) -> int:
  723. """A background updates that iterates over all rooms and generates the
  724. chain cover index for them.
  725. """
  726. current_room_id = progress.get("current_room_id", "")
  727. # Where we've processed up to in the room, defaults to the start of the
  728. # room.
  729. last_depth = progress.get("last_depth", -1)
  730. last_stream = progress.get("last_stream", -1)
  731. result = await self.db_pool.runInteraction(
  732. "_chain_cover_index",
  733. self._calculate_chain_cover_txn,
  734. current_room_id,
  735. last_depth,
  736. last_stream,
  737. batch_size,
  738. single_room=False,
  739. )
  740. finished = result.processed_count == 0
  741. total_rows_processed = result.processed_count
  742. current_room_id = result.room_id
  743. last_depth = result.depth
  744. last_stream = result.stream
  745. for room_id, (depth, stream) in result.finished_room_map.items():
  746. # If we've done all the events in the room we flip the
  747. # `has_auth_chain_index` in the DB. Note that its possible for
  748. # further events to be persisted between the above and setting the
  749. # flag without having the chain cover calculated for them. This is
  750. # fine as a) the code gracefully handles these cases and b) we'll
  751. # calculate them below.
  752. await self.db_pool.simple_update(
  753. table="rooms",
  754. keyvalues={"room_id": room_id},
  755. updatevalues={"has_auth_chain_index": True},
  756. desc="_chain_cover_index",
  757. )
  758. # Handle any events that might have raced with us flipping the
  759. # bit above.
  760. result = await self.db_pool.runInteraction(
  761. "_chain_cover_index",
  762. self._calculate_chain_cover_txn,
  763. room_id,
  764. depth,
  765. stream,
  766. batch_size=None,
  767. single_room=True,
  768. )
  769. total_rows_processed += result.processed_count
  770. if finished:
  771. await self.db_pool.updates._end_background_update("chain_cover")
  772. return total_rows_processed
  773. await self.db_pool.updates._background_update_progress(
  774. "chain_cover",
  775. {
  776. "current_room_id": current_room_id,
  777. "last_depth": last_depth,
  778. "last_stream": last_stream,
  779. },
  780. )
  781. return total_rows_processed
  782. def _calculate_chain_cover_txn(
  783. self,
  784. txn: LoggingTransaction,
  785. last_room_id: str,
  786. last_depth: int,
  787. last_stream: int,
  788. batch_size: Optional[int],
  789. single_room: bool,
  790. ) -> _CalculateChainCover:
  791. """Calculate the chain cover for `batch_size` events, ordered by
  792. `(room_id, depth, stream)`.
  793. Args:
  794. txn,
  795. last_room_id, last_depth, last_stream: The `(room_id, depth, stream)`
  796. tuple to fetch results after.
  797. batch_size: The maximum number of events to process. If None then
  798. no limit.
  799. single_room: Whether to calculate the index for just the given
  800. room.
  801. """
  802. # Get the next set of events in the room (that we haven't already
  803. # computed chain cover for). We do this in topological order.
  804. # We want to do a `(topological_ordering, stream_ordering) > (?,?)`
  805. # comparison, but that is not supported on older SQLite versions
  806. tuple_clause, tuple_args = make_tuple_comparison_clause(
  807. [
  808. ("events.room_id", last_room_id),
  809. ("topological_ordering", last_depth),
  810. ("stream_ordering", last_stream),
  811. ],
  812. )
  813. extra_clause = ""
  814. if single_room:
  815. extra_clause = "AND events.room_id = ?"
  816. tuple_args.append(last_room_id)
  817. sql = """
  818. SELECT
  819. event_id, state_events.type, state_events.state_key,
  820. topological_ordering, stream_ordering,
  821. events.room_id
  822. FROM events
  823. INNER JOIN state_events USING (event_id)
  824. LEFT JOIN event_auth_chains USING (event_id)
  825. LEFT JOIN event_auth_chain_to_calculate USING (event_id)
  826. WHERE event_auth_chains.event_id IS NULL
  827. AND event_auth_chain_to_calculate.event_id IS NULL
  828. AND %(tuple_cmp)s
  829. %(extra)s
  830. ORDER BY events.room_id, topological_ordering, stream_ordering
  831. %(limit)s
  832. """ % {
  833. "tuple_cmp": tuple_clause,
  834. "limit": "LIMIT ?" if batch_size is not None else "",
  835. "extra": extra_clause,
  836. }
  837. if batch_size is not None:
  838. tuple_args.append(batch_size)
  839. txn.execute(sql, tuple_args)
  840. rows = txn.fetchall()
  841. # Put the results in the necessary format for
  842. # `_add_chain_cover_index`
  843. event_to_room_id = {row[0]: row[5] for row in rows}
  844. event_to_types = {row[0]: (row[1], row[2]) for row in rows}
  845. # Calculate the new last position we've processed up to.
  846. new_last_depth: int = rows[-1][3] if rows else last_depth
  847. new_last_stream: int = rows[-1][4] if rows else last_stream
  848. new_last_room_id: str = rows[-1][5] if rows else ""
  849. # Map from room_id to last depth/stream_ordering processed for the room,
  850. # excluding the last room (which we're likely still processing). We also
  851. # need to include the room passed in if it's not included in the result
  852. # set (as we then know we've processed all events in said room).
  853. #
  854. # This is the set of rooms that we can now safely flip the
  855. # `has_auth_chain_index` bit for.
  856. finished_rooms = {
  857. row[5]: (row[3], row[4]) for row in rows if row[5] != new_last_room_id
  858. }
  859. if last_room_id not in finished_rooms and last_room_id != new_last_room_id:
  860. finished_rooms[last_room_id] = (last_depth, last_stream)
  861. count = len(rows)
  862. # We also need to fetch the auth events for them.
  863. auth_events = self.db_pool.simple_select_many_txn(
  864. txn,
  865. table="event_auth",
  866. column="event_id",
  867. iterable=event_to_room_id,
  868. keyvalues={},
  869. retcols=("event_id", "auth_id"),
  870. )
  871. event_to_auth_chain: Dict[str, List[str]] = {}
  872. for row in auth_events:
  873. event_to_auth_chain.setdefault(row["event_id"], []).append(row["auth_id"])
  874. # Calculate and persist the chain cover index for this set of events.
  875. #
  876. # Annoyingly we need to gut wrench into the persit event store so that
  877. # we can reuse the function to calculate the chain cover for rooms.
  878. PersistEventsStore._add_chain_cover_index(
  879. txn,
  880. self.db_pool,
  881. self.event_chain_id_gen, # type: ignore[attr-defined]
  882. event_to_room_id,
  883. event_to_types,
  884. cast(Dict[str, StrCollection], event_to_auth_chain),
  885. )
  886. return _CalculateChainCover(
  887. room_id=new_last_room_id,
  888. depth=new_last_depth,
  889. stream=new_last_stream,
  890. processed_count=count,
  891. finished_room_map=finished_rooms,
  892. )
  893. async def _purged_chain_cover_index(self, progress: dict, batch_size: int) -> int:
  894. """
  895. A background updates that iterates over the chain cover and deletes the
  896. chain cover for events that have been purged.
  897. This may be due to fully purging a room or via setting a retention policy.
  898. """
  899. current_event_id = progress.get("current_event_id", "")
  900. def purged_chain_cover_txn(txn: LoggingTransaction) -> int:
  901. # The event ID from events will be null if the chain ID / sequence
  902. # number points to a purged event.
  903. sql = """
  904. SELECT event_id, chain_id, sequence_number, e.event_id IS NOT NULL
  905. FROM event_auth_chains
  906. LEFT JOIN events AS e USING (event_id)
  907. WHERE event_id > ? ORDER BY event_auth_chains.event_id ASC LIMIT ?
  908. """
  909. txn.execute(sql, (current_event_id, batch_size))
  910. rows = txn.fetchall()
  911. if not rows:
  912. return 0
  913. # The event IDs and chain IDs / sequence numbers where the event has
  914. # been purged.
  915. unreferenced_event_ids = []
  916. unreferenced_chain_id_tuples = []
  917. event_id = ""
  918. for event_id, chain_id, sequence_number, has_event in rows:
  919. if not has_event:
  920. unreferenced_event_ids.append((event_id,))
  921. unreferenced_chain_id_tuples.append((chain_id, sequence_number))
  922. # Delete the unreferenced auth chains from event_auth_chain_links and
  923. # event_auth_chains.
  924. txn.executemany(
  925. """
  926. DELETE FROM event_auth_chains WHERE event_id = ?
  927. """,
  928. unreferenced_event_ids,
  929. )
  930. # We should also delete matching target_*, but there is no index on
  931. # target_chain_id. Hopefully any purged events are due to a room
  932. # being fully purged and they will be removed from the origin_*
  933. # searches.
  934. txn.executemany(
  935. """
  936. DELETE FROM event_auth_chain_links WHERE
  937. origin_chain_id = ? AND origin_sequence_number = ?
  938. """,
  939. unreferenced_chain_id_tuples,
  940. )
  941. progress = {
  942. "current_event_id": event_id,
  943. }
  944. self.db_pool.updates._background_update_progress_txn(
  945. txn, "purged_chain_cover", progress
  946. )
  947. return len(rows)
  948. result = await self.db_pool.runInteraction(
  949. "_purged_chain_cover_index",
  950. purged_chain_cover_txn,
  951. )
  952. if not result:
  953. await self.db_pool.updates._end_background_update("purged_chain_cover")
  954. return result
  955. async def _event_arbitrary_relations(
  956. self, progress: JsonDict, batch_size: int
  957. ) -> int:
  958. """Background update handler which will store previously unknown relations for existing events."""
  959. last_event_id = progress.get("last_event_id", "")
  960. def _event_arbitrary_relations_txn(txn: LoggingTransaction) -> int:
  961. # Fetch events and then filter based on whether the event has a
  962. # relation or not.
  963. txn.execute(
  964. """
  965. SELECT event_id, json FROM event_json
  966. WHERE event_id > ?
  967. ORDER BY event_id LIMIT ?
  968. """,
  969. (last_event_id, batch_size),
  970. )
  971. results = list(txn)
  972. # (event_id, parent_id, rel_type) for each relation
  973. relations_to_insert: List[Tuple[str, str, str]] = []
  974. for event_id, event_json_raw in results:
  975. try:
  976. event_json = db_to_json(event_json_raw)
  977. except Exception as e:
  978. logger.warning(
  979. "Unable to load event %s (no relations will be updated): %s",
  980. event_id,
  981. e,
  982. )
  983. continue
  984. # If there's no relation, skip!
  985. relates_to = event_json["content"].get("m.relates_to")
  986. if not relates_to or not isinstance(relates_to, dict):
  987. continue
  988. # If the relation type or parent event ID is not a string, skip it.
  989. #
  990. # Do not consider relation types that have existed for a long time,
  991. # since they will already be listed in the `event_relations` table.
  992. rel_type = relates_to.get("rel_type")
  993. if not isinstance(rel_type, str) or rel_type in (
  994. RelationTypes.ANNOTATION,
  995. RelationTypes.REFERENCE,
  996. RelationTypes.REPLACE,
  997. ):
  998. continue
  999. parent_id = relates_to.get("event_id")
  1000. if not isinstance(parent_id, str):
  1001. continue
  1002. relations_to_insert.append((event_id, parent_id, rel_type))
  1003. # Insert the missing data, note that we upsert here in case the event
  1004. # has already been processed.
  1005. if relations_to_insert:
  1006. self.db_pool.simple_upsert_many_txn(
  1007. txn=txn,
  1008. table="event_relations",
  1009. key_names=("event_id",),
  1010. key_values=[(r[0],) for r in relations_to_insert],
  1011. value_names=("relates_to_id", "relation_type"),
  1012. value_values=[r[1:] for r in relations_to_insert],
  1013. )
  1014. # Iterate the parent IDs and invalidate caches.
  1015. for parent_id in {r[1] for r in relations_to_insert}:
  1016. cache_tuple = (parent_id,)
  1017. self._invalidate_cache_and_stream( # type: ignore[attr-defined]
  1018. txn, self.get_relations_for_event, cache_tuple # type: ignore[attr-defined]
  1019. )
  1020. self._invalidate_cache_and_stream( # type: ignore[attr-defined]
  1021. txn, self.get_aggregation_groups_for_event, cache_tuple # type: ignore[attr-defined]
  1022. )
  1023. self._invalidate_cache_and_stream( # type: ignore[attr-defined]
  1024. txn, self.get_thread_summary, cache_tuple # type: ignore[attr-defined]
  1025. )
  1026. if results:
  1027. latest_event_id = results[-1][0]
  1028. self.db_pool.updates._background_update_progress_txn(
  1029. txn, "event_arbitrary_relations", {"last_event_id": latest_event_id}
  1030. )
  1031. return len(results)
  1032. num_rows = await self.db_pool.runInteraction(
  1033. desc="event_arbitrary_relations", func=_event_arbitrary_relations_txn
  1034. )
  1035. if not num_rows:
  1036. await self.db_pool.updates._end_background_update(
  1037. "event_arbitrary_relations"
  1038. )
  1039. return num_rows
  1040. async def _background_populate_stream_ordering2(
  1041. self, progress: JsonDict, batch_size: int
  1042. ) -> int:
  1043. """Populate events.stream_ordering2, then replace stream_ordering
  1044. This is to deal with the fact that stream_ordering was initially created as a
  1045. 32-bit integer field.
  1046. """
  1047. batch_size = max(batch_size, 1)
  1048. def process(txn: LoggingTransaction) -> int:
  1049. last_stream = progress.get("last_stream", -(1 << 31))
  1050. txn.execute(
  1051. """
  1052. UPDATE events SET stream_ordering2=stream_ordering
  1053. WHERE stream_ordering IN (
  1054. SELECT stream_ordering FROM events WHERE stream_ordering > ?
  1055. ORDER BY stream_ordering LIMIT ?
  1056. )
  1057. RETURNING stream_ordering;
  1058. """,
  1059. (last_stream, batch_size),
  1060. )
  1061. row_count = txn.rowcount
  1062. if row_count == 0:
  1063. return 0
  1064. last_stream = max(row[0] for row in txn)
  1065. logger.info("populated stream_ordering2 up to %i", last_stream)
  1066. self.db_pool.updates._background_update_progress_txn(
  1067. txn,
  1068. _BackgroundUpdates.POPULATE_STREAM_ORDERING2,
  1069. {"last_stream": last_stream},
  1070. )
  1071. return row_count
  1072. result = await self.db_pool.runInteraction(
  1073. "_background_populate_stream_ordering2", process
  1074. )
  1075. if result != 0:
  1076. return result
  1077. await self.db_pool.updates._end_background_update(
  1078. _BackgroundUpdates.POPULATE_STREAM_ORDERING2
  1079. )
  1080. return 0
  1081. async def _background_replace_stream_ordering_column(
  1082. self, progress: JsonDict, batch_size: int
  1083. ) -> int:
  1084. """Drop the old 'stream_ordering' column and rename 'stream_ordering2' into its place."""
  1085. def process(txn: Cursor) -> None:
  1086. for sql in _REPLACE_STREAM_ORDERING_SQL_COMMANDS:
  1087. logger.info("completing stream_ordering migration: %s", sql)
  1088. txn.execute(sql)
  1089. # ANALYZE the new column to build stats on it, to encourage PostgreSQL to use the
  1090. # indexes on it.
  1091. # We need to pass execute a dummy function to handle the txn's result otherwise
  1092. # it tries to call fetchall() on it and fails because there's no result to fetch.
  1093. await self.db_pool.execute(
  1094. "background_analyze_new_stream_ordering_column",
  1095. lambda txn: None,
  1096. "ANALYZE events(stream_ordering2)",
  1097. )
  1098. await self.db_pool.runInteraction(
  1099. "_background_replace_stream_ordering_column", process
  1100. )
  1101. await self.db_pool.updates._end_background_update(
  1102. _BackgroundUpdates.REPLACE_STREAM_ORDERING_COLUMN
  1103. )
  1104. return 0
  1105. async def _background_drop_invalid_event_edges_rows(
  1106. self, progress: JsonDict, batch_size: int
  1107. ) -> int:
  1108. """Drop invalid rows from event_edges
  1109. This only runs for postgres. For SQLite, it all happens synchronously.
  1110. Firstly, drop any rows with is_state=True. These may have been added a long time
  1111. ago, but they are no longer used.
  1112. We also drop rows that do not correspond to entries in `events`, and add a
  1113. foreign key.
  1114. """
  1115. last_event_id = progress.get("last_event_id", "")
  1116. def drop_invalid_event_edges_txn(txn: LoggingTransaction) -> bool:
  1117. """Returns True if we're done."""
  1118. # first we need to find an endpoint.
  1119. txn.execute(
  1120. """
  1121. SELECT event_id FROM event_edges
  1122. WHERE event_id > ?
  1123. ORDER BY event_id
  1124. LIMIT 1 OFFSET ?
  1125. """,
  1126. (last_event_id, batch_size),
  1127. )
  1128. endpoint = None
  1129. row = txn.fetchone()
  1130. if row:
  1131. endpoint = row[0]
  1132. where_clause = "ee.event_id > ?"
  1133. args = [last_event_id]
  1134. if endpoint:
  1135. where_clause += " AND ee.event_id <= ?"
  1136. args.append(endpoint)
  1137. # now delete any that:
  1138. # - have is_state=TRUE, or
  1139. # - do not correspond to a row in `events`
  1140. txn.execute(
  1141. f"""
  1142. DELETE FROM event_edges
  1143. WHERE event_id IN (
  1144. SELECT ee.event_id
  1145. FROM event_edges ee
  1146. LEFT JOIN events ev USING (event_id)
  1147. WHERE ({where_clause}) AND
  1148. (is_state OR ev.event_id IS NULL)
  1149. )""",
  1150. args,
  1151. )
  1152. logger.info(
  1153. "cleaned up event_edges up to %s: removed %i/%i rows",
  1154. endpoint,
  1155. txn.rowcount,
  1156. batch_size,
  1157. )
  1158. if endpoint is not None:
  1159. self.db_pool.updates._background_update_progress_txn(
  1160. txn,
  1161. _BackgroundUpdates.EVENT_EDGES_DROP_INVALID_ROWS,
  1162. {"last_event_id": endpoint},
  1163. )
  1164. return False
  1165. # if that was the final batch, we validate the foreign key.
  1166. #
  1167. # The constraint should have been in place and enforced for new rows since
  1168. # before we started deleting invalid rows, so there's no chance for any
  1169. # invalid rows to have snuck in the meantime. In other words, this really
  1170. # ought to succeed.
  1171. logger.info("cleaned up event_edges; enabling foreign key")
  1172. txn.execute(
  1173. "ALTER TABLE event_edges VALIDATE CONSTRAINT event_edges_event_id_fkey"
  1174. )
  1175. return True
  1176. done = await self.db_pool.runInteraction(
  1177. desc="drop_invalid_event_edges", func=drop_invalid_event_edges_txn
  1178. )
  1179. if done:
  1180. await self.db_pool.updates._end_background_update(
  1181. _BackgroundUpdates.EVENT_EDGES_DROP_INVALID_ROWS
  1182. )
  1183. return batch_size
  1184. async def _background_events_populate_state_key_rejections(
  1185. self, progress: JsonDict, batch_size: int
  1186. ) -> int:
  1187. """Back-populate `events.state_key` and `events.rejection_reason"""
  1188. min_stream_ordering_exclusive = progress["min_stream_ordering_exclusive"]
  1189. max_stream_ordering_inclusive = progress["max_stream_ordering_inclusive"]
  1190. def _populate_txn(txn: LoggingTransaction) -> bool:
  1191. """Returns True if we're done."""
  1192. # first we need to find an endpoint.
  1193. # we need to find the final row in the batch of batch_size, which means
  1194. # we need to skip over (batch_size-1) rows and get the next row.
  1195. txn.execute(
  1196. """
  1197. SELECT stream_ordering FROM events
  1198. WHERE stream_ordering > ? AND stream_ordering <= ?
  1199. ORDER BY stream_ordering
  1200. LIMIT 1 OFFSET ?
  1201. """,
  1202. (
  1203. min_stream_ordering_exclusive,
  1204. max_stream_ordering_inclusive,
  1205. batch_size - 1,
  1206. ),
  1207. )
  1208. row = txn.fetchone()
  1209. if row:
  1210. endpoint = row[0]
  1211. else:
  1212. # if the query didn't return a row, we must be almost done. We just
  1213. # need to go up to the recorded max_stream_ordering.
  1214. endpoint = max_stream_ordering_inclusive
  1215. where_clause = "stream_ordering > ? AND stream_ordering <= ?"
  1216. args = [min_stream_ordering_exclusive, endpoint]
  1217. # now do the updates.
  1218. txn.execute(
  1219. f"""
  1220. UPDATE events
  1221. SET state_key = (SELECT state_key FROM state_events se WHERE se.event_id = events.event_id),
  1222. rejection_reason = (SELECT reason FROM rejections rej WHERE rej.event_id = events.event_id)
  1223. WHERE ({where_clause})
  1224. """,
  1225. args,
  1226. )
  1227. logger.info(
  1228. "populated new `events` columns up to %i/%i: updated %i rows",
  1229. endpoint,
  1230. max_stream_ordering_inclusive,
  1231. txn.rowcount,
  1232. )
  1233. if endpoint >= max_stream_ordering_inclusive:
  1234. # we're done
  1235. return True
  1236. progress["min_stream_ordering_exclusive"] = endpoint
  1237. self.db_pool.updates._background_update_progress_txn(
  1238. txn,
  1239. _BackgroundUpdates.EVENTS_POPULATE_STATE_KEY_REJECTIONS,
  1240. progress,
  1241. )
  1242. return False
  1243. done = await self.db_pool.runInteraction(
  1244. desc="events_populate_state_key_rejections", func=_populate_txn
  1245. )
  1246. if done:
  1247. await self.db_pool.updates._end_background_update(
  1248. _BackgroundUpdates.EVENTS_POPULATE_STATE_KEY_REJECTIONS
  1249. )
  1250. return batch_size