state.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from ._base import SQLBaseStore
  16. from synapse.util.caches.descriptors import cached, cachedList
  17. from synapse.util.caches import intern_string
  18. from synapse.storage.engines import PostgresEngine
  19. from twisted.internet import defer
  20. import logging
  21. logger = logging.getLogger(__name__)
  22. MAX_STATE_DELTA_HOPS = 100
  23. class StateStore(SQLBaseStore):
  24. """ Keeps track of the state at a given event.
  25. This is done by the concept of `state groups`. Every event is a assigned
  26. a state group (identified by an arbitrary string), which references a
  27. collection of state events. The current state of an event is then the
  28. collection of state events referenced by the event's state group.
  29. Hence, every change in the current state causes a new state group to be
  30. generated. However, if no change happens (e.g., if we get a message event
  31. with only one parent it inherits the state group from its parent.)
  32. There are three tables:
  33. * `state_groups`: Stores group name, first event with in the group and
  34. room id.
  35. * `event_to_state_groups`: Maps events to state groups.
  36. * `state_groups_state`: Maps state group to state events.
  37. """
  38. STATE_GROUP_DEDUPLICATION_UPDATE_NAME = "state_group_state_deduplication"
  39. STATE_GROUP_INDEX_UPDATE_NAME = "state_group_state_type_index"
  40. def __init__(self, hs):
  41. super(StateStore, self).__init__(hs)
  42. self.register_background_update_handler(
  43. self.STATE_GROUP_DEDUPLICATION_UPDATE_NAME,
  44. self._background_deduplicate_state,
  45. )
  46. self.register_background_update_handler(
  47. self.STATE_GROUP_INDEX_UPDATE_NAME,
  48. self._background_index_state,
  49. )
  50. @defer.inlineCallbacks
  51. def get_state_groups_ids(self, room_id, event_ids):
  52. if not event_ids:
  53. defer.returnValue({})
  54. event_to_groups = yield self._get_state_group_for_events(
  55. event_ids,
  56. )
  57. groups = set(event_to_groups.values())
  58. group_to_state = yield self._get_state_for_groups(groups)
  59. defer.returnValue(group_to_state)
  60. @defer.inlineCallbacks
  61. def get_state_groups(self, room_id, event_ids):
  62. """ Get the state groups for the given list of event_ids
  63. The return value is a dict mapping group names to lists of events.
  64. """
  65. if not event_ids:
  66. defer.returnValue({})
  67. group_to_ids = yield self.get_state_groups_ids(room_id, event_ids)
  68. state_event_map = yield self.get_events(
  69. [
  70. ev_id for group_ids in group_to_ids.values()
  71. for ev_id in group_ids.values()
  72. ],
  73. get_prev_content=False
  74. )
  75. defer.returnValue({
  76. group: [
  77. state_event_map[v] for v in event_id_map.values() if v in state_event_map
  78. ]
  79. for group, event_id_map in group_to_ids.items()
  80. })
  81. def _have_persisted_state_group_txn(self, txn, state_group):
  82. txn.execute(
  83. "SELECT count(*) FROM state_groups WHERE id = ?",
  84. (state_group,)
  85. )
  86. row = txn.fetchone()
  87. return row and row[0]
  88. def _store_mult_state_groups_txn(self, txn, events_and_contexts):
  89. state_groups = {}
  90. for event, context in events_and_contexts:
  91. if event.internal_metadata.is_outlier():
  92. continue
  93. if context.current_state_ids is None:
  94. continue
  95. state_groups[event.event_id] = context.state_group
  96. if self._have_persisted_state_group_txn(txn, context.state_group):
  97. continue
  98. self._simple_insert_txn(
  99. txn,
  100. table="state_groups",
  101. values={
  102. "id": context.state_group,
  103. "room_id": event.room_id,
  104. "event_id": event.event_id,
  105. },
  106. )
  107. # We persist as a delta if we can, while also ensuring the chain
  108. # of deltas isn't tooo long, as otherwise read performance degrades.
  109. if context.prev_group:
  110. potential_hops = self._count_state_group_hops_txn(
  111. txn, context.prev_group
  112. )
  113. if context.prev_group and potential_hops < MAX_STATE_DELTA_HOPS:
  114. self._simple_insert_txn(
  115. txn,
  116. table="state_group_edges",
  117. values={
  118. "state_group": context.state_group,
  119. "prev_state_group": context.prev_group,
  120. },
  121. )
  122. self._simple_insert_many_txn(
  123. txn,
  124. table="state_groups_state",
  125. values=[
  126. {
  127. "state_group": context.state_group,
  128. "room_id": event.room_id,
  129. "type": key[0],
  130. "state_key": key[1],
  131. "event_id": state_id,
  132. }
  133. for key, state_id in context.delta_ids.items()
  134. ],
  135. )
  136. else:
  137. self._simple_insert_many_txn(
  138. txn,
  139. table="state_groups_state",
  140. values=[
  141. {
  142. "state_group": context.state_group,
  143. "room_id": event.room_id,
  144. "type": key[0],
  145. "state_key": key[1],
  146. "event_id": state_id,
  147. }
  148. for key, state_id in context.current_state_ids.items()
  149. ],
  150. )
  151. self._simple_insert_many_txn(
  152. txn,
  153. table="event_to_state_groups",
  154. values=[
  155. {
  156. "state_group": state_group_id,
  157. "event_id": event_id,
  158. }
  159. for event_id, state_group_id in state_groups.items()
  160. ],
  161. )
  162. def _count_state_group_hops_txn(self, txn, state_group):
  163. """Given a state group, count how many hops there are in the tree.
  164. This is used to ensure the delta chains don't get too long.
  165. """
  166. if isinstance(self.database_engine, PostgresEngine):
  167. sql = ("""
  168. WITH RECURSIVE state(state_group) AS (
  169. VALUES(?::bigint)
  170. UNION ALL
  171. SELECT prev_state_group FROM state_group_edges e, state s
  172. WHERE s.state_group = e.state_group
  173. )
  174. SELECT count(*) FROM state;
  175. """)
  176. txn.execute(sql, (state_group,))
  177. row = txn.fetchone()
  178. if row and row[0]:
  179. return row[0]
  180. else:
  181. return 0
  182. else:
  183. # We don't use WITH RECURSIVE on sqlite3 as there are distributions
  184. # that ship with an sqlite3 version that doesn't support it (e.g. wheezy)
  185. next_group = state_group
  186. count = 0
  187. while next_group:
  188. next_group = self._simple_select_one_onecol_txn(
  189. txn,
  190. table="state_group_edges",
  191. keyvalues={"state_group": next_group},
  192. retcol="prev_state_group",
  193. allow_none=True,
  194. )
  195. if next_group:
  196. count += 1
  197. return count
  198. @defer.inlineCallbacks
  199. def get_current_state(self, room_id, event_type=None, state_key=""):
  200. if event_type and state_key is not None:
  201. result = yield self.get_current_state_for_key(
  202. room_id, event_type, state_key
  203. )
  204. defer.returnValue(result)
  205. def f(txn):
  206. sql = (
  207. "SELECT event_id FROM current_state_events"
  208. " WHERE room_id = ? "
  209. )
  210. if event_type and state_key is not None:
  211. sql += " AND type = ? AND state_key = ? "
  212. args = (room_id, event_type, state_key)
  213. elif event_type:
  214. sql += " AND type = ?"
  215. args = (room_id, event_type)
  216. else:
  217. args = (room_id, )
  218. txn.execute(sql, args)
  219. results = txn.fetchall()
  220. return [r[0] for r in results]
  221. event_ids = yield self.runInteraction("get_current_state", f)
  222. events = yield self._get_events(event_ids, get_prev_content=False)
  223. defer.returnValue(events)
  224. @defer.inlineCallbacks
  225. def get_current_state_for_key(self, room_id, event_type, state_key):
  226. event_ids = yield self._get_current_state_for_key(room_id, event_type, state_key)
  227. events = yield self._get_events(event_ids, get_prev_content=False)
  228. defer.returnValue(events)
  229. @cached(num_args=3)
  230. def _get_current_state_for_key(self, room_id, event_type, state_key):
  231. def f(txn):
  232. sql = (
  233. "SELECT event_id FROM current_state_events"
  234. " WHERE room_id = ? AND type = ? AND state_key = ?"
  235. )
  236. args = (room_id, event_type, state_key)
  237. txn.execute(sql, args)
  238. results = txn.fetchall()
  239. return [r[0] for r in results]
  240. return self.runInteraction("get_current_state_for_key", f)
  241. @cached(num_args=2, max_entries=1000)
  242. def _get_state_group_from_group(self, group, types):
  243. raise NotImplementedError()
  244. @cachedList(cached_method_name="_get_state_group_from_group",
  245. list_name="groups", num_args=2, inlineCallbacks=True)
  246. def _get_state_groups_from_groups(self, groups, types):
  247. """Returns dictionary state_group -> (dict of (type, state_key) -> event id)
  248. """
  249. results = {}
  250. chunks = [groups[i:i + 100] for i in xrange(0, len(groups), 100)]
  251. for chunk in chunks:
  252. res = yield self.runInteraction(
  253. "_get_state_groups_from_groups",
  254. self._get_state_groups_from_groups_txn, chunk, types,
  255. )
  256. results.update(res)
  257. defer.returnValue(results)
  258. def _get_state_groups_from_groups_txn(self, txn, groups, types=None):
  259. results = {group: {} for group in groups}
  260. if types is not None:
  261. types = list(set(types)) # deduplicate types list
  262. if isinstance(self.database_engine, PostgresEngine):
  263. # Temporarily disable sequential scans in this transaction. This is
  264. # a temporary hack until we can add the right indices in
  265. txn.execute("SET LOCAL enable_seqscan=off")
  266. # The below query walks the state_group tree so that the "state"
  267. # table includes all state_groups in the tree. It then joins
  268. # against `state_groups_state` to fetch the latest state.
  269. # It assumes that previous state groups are always numerically
  270. # lesser.
  271. # The PARTITION is used to get the event_id in the greatest state
  272. # group for the given type, state_key.
  273. # This may return multiple rows per (type, state_key), but last_value
  274. # should be the same.
  275. sql = ("""
  276. WITH RECURSIVE state(state_group) AS (
  277. VALUES(?::bigint)
  278. UNION ALL
  279. SELECT prev_state_group FROM state_group_edges e, state s
  280. WHERE s.state_group = e.state_group
  281. )
  282. SELECT type, state_key, last_value(event_id) OVER (
  283. PARTITION BY type, state_key ORDER BY state_group ASC
  284. ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  285. ) AS event_id FROM state_groups_state
  286. WHERE state_group IN (
  287. SELECT state_group FROM state
  288. )
  289. %s
  290. """)
  291. # Turns out that postgres doesn't like doing a list of OR's and
  292. # is about 1000x slower, so we just issue a query for each specific
  293. # type seperately.
  294. if types:
  295. clause_to_args = [
  296. (
  297. "AND type = ? AND state_key = ?",
  298. (etype, state_key)
  299. )
  300. for etype, state_key in types
  301. ]
  302. else:
  303. # If types is None we fetch all the state, and so just use an
  304. # empty where clause with no extra args.
  305. clause_to_args = [("", [])]
  306. for where_clause, where_args in clause_to_args:
  307. for group in groups:
  308. args = [group]
  309. args.extend(where_args)
  310. txn.execute(sql % (where_clause,), args)
  311. rows = self.cursor_to_dict(txn)
  312. for row in rows:
  313. key = (row["type"], row["state_key"])
  314. results[group][key] = row["event_id"]
  315. else:
  316. if types is not None:
  317. where_clause = "AND (%s)" % (
  318. " OR ".join(["(type = ? AND state_key = ?)"] * len(types)),
  319. )
  320. else:
  321. where_clause = ""
  322. # We don't use WITH RECURSIVE on sqlite3 as there are distributions
  323. # that ship with an sqlite3 version that doesn't support it (e.g. wheezy)
  324. for group in groups:
  325. next_group = group
  326. while next_group:
  327. # We did this before by getting the list of group ids, and
  328. # then passing that list to sqlite to get latest event for
  329. # each (type, state_key). However, that was terribly slow
  330. # without the right indicies (which we can't add until
  331. # after we finish deduping state, which requires this func)
  332. args = [next_group]
  333. if types:
  334. args.extend(i for typ in types for i in typ)
  335. txn.execute(
  336. "SELECT type, state_key, event_id FROM state_groups_state"
  337. " WHERE state_group = ? %s" % (where_clause,),
  338. args
  339. )
  340. rows = txn.fetchall()
  341. results[group].update({
  342. (typ, state_key): event_id
  343. for typ, state_key, event_id in rows
  344. if (typ, state_key) not in results[group]
  345. })
  346. # If the lengths match then we must have all the types,
  347. # so no need to go walk further down the tree.
  348. if types is not None and len(results[group]) == len(types):
  349. break
  350. next_group = self._simple_select_one_onecol_txn(
  351. txn,
  352. table="state_group_edges",
  353. keyvalues={"state_group": next_group},
  354. retcol="prev_state_group",
  355. allow_none=True,
  356. )
  357. return results
  358. @defer.inlineCallbacks
  359. def get_state_for_events(self, event_ids, types):
  360. """Given a list of event_ids and type tuples, return a list of state
  361. dicts for each event. The state dicts will only have the type/state_keys
  362. that are in the `types` list.
  363. Args:
  364. event_ids (list)
  365. types (list): List of (type, state_key) tuples which are used to
  366. filter the state fetched. `state_key` may be None, which matches
  367. any `state_key`
  368. Returns:
  369. deferred: A list of dicts corresponding to the event_ids given.
  370. The dicts are mappings from (type, state_key) -> state_events
  371. """
  372. event_to_groups = yield self._get_state_group_for_events(
  373. event_ids,
  374. )
  375. groups = set(event_to_groups.values())
  376. group_to_state = yield self._get_state_for_groups(groups, types)
  377. state_event_map = yield self.get_events(
  378. [ev_id for sd in group_to_state.values() for ev_id in sd.values()],
  379. get_prev_content=False
  380. )
  381. event_to_state = {
  382. event_id: {
  383. k: state_event_map[v]
  384. for k, v in group_to_state[group].items()
  385. if v in state_event_map
  386. }
  387. for event_id, group in event_to_groups.items()
  388. }
  389. defer.returnValue({event: event_to_state[event] for event in event_ids})
  390. @defer.inlineCallbacks
  391. def get_state_ids_for_events(self, event_ids, types):
  392. event_to_groups = yield self._get_state_group_for_events(
  393. event_ids,
  394. )
  395. groups = set(event_to_groups.values())
  396. group_to_state = yield self._get_state_for_groups(groups, types)
  397. event_to_state = {
  398. event_id: group_to_state[group]
  399. for event_id, group in event_to_groups.items()
  400. }
  401. defer.returnValue({event: event_to_state[event] for event in event_ids})
  402. @defer.inlineCallbacks
  403. def get_state_for_event(self, event_id, types=None):
  404. """
  405. Get the state dict corresponding to a particular event
  406. Args:
  407. event_id(str): event whose state should be returned
  408. types(list[(str, str)]|None): List of (type, state_key) tuples
  409. which are used to filter the state fetched. May be None, which
  410. matches any key
  411. Returns:
  412. A deferred dict from (type, state_key) -> state_event
  413. """
  414. state_map = yield self.get_state_for_events([event_id], types)
  415. defer.returnValue(state_map[event_id])
  416. @defer.inlineCallbacks
  417. def get_state_ids_for_event(self, event_id, types=None):
  418. """
  419. Get the state dict corresponding to a particular event
  420. Args:
  421. event_id(str): event whose state should be returned
  422. types(list[(str, str)]|None): List of (type, state_key) tuples
  423. which are used to filter the state fetched. May be None, which
  424. matches any key
  425. Returns:
  426. A deferred dict from (type, state_key) -> state_event
  427. """
  428. state_map = yield self.get_state_ids_for_events([event_id], types)
  429. defer.returnValue(state_map[event_id])
  430. @cached(num_args=2, max_entries=10000)
  431. def _get_state_group_for_event(self, room_id, event_id):
  432. return self._simple_select_one_onecol(
  433. table="event_to_state_groups",
  434. keyvalues={
  435. "event_id": event_id,
  436. },
  437. retcol="state_group",
  438. allow_none=True,
  439. desc="_get_state_group_for_event",
  440. )
  441. @cachedList(cached_method_name="_get_state_group_for_event",
  442. list_name="event_ids", num_args=1, inlineCallbacks=True)
  443. def _get_state_group_for_events(self, event_ids):
  444. """Returns mapping event_id -> state_group
  445. """
  446. rows = yield self._simple_select_many_batch(
  447. table="event_to_state_groups",
  448. column="event_id",
  449. iterable=event_ids,
  450. keyvalues={},
  451. retcols=("event_id", "state_group",),
  452. desc="_get_state_group_for_events",
  453. )
  454. defer.returnValue({row["event_id"]: row["state_group"] for row in rows})
  455. def _get_some_state_from_cache(self, group, types):
  456. """Checks if group is in cache. See `_get_state_for_groups`
  457. Returns 3-tuple (`state_dict`, `missing_types`, `got_all`).
  458. `missing_types` is the list of types that aren't in the cache for that
  459. group. `got_all` is a bool indicating if we successfully retrieved all
  460. requests state from the cache, if False we need to query the DB for the
  461. missing state.
  462. Args:
  463. group: The state group to lookup
  464. types (list): List of 2-tuples of the form (`type`, `state_key`),
  465. where a `state_key` of `None` matches all state_keys for the
  466. `type`.
  467. """
  468. is_all, state_dict_ids = self._state_group_cache.get(group)
  469. type_to_key = {}
  470. missing_types = set()
  471. for typ, state_key in types:
  472. if state_key is None:
  473. type_to_key[typ] = None
  474. missing_types.add((typ, state_key))
  475. else:
  476. if type_to_key.get(typ, object()) is not None:
  477. type_to_key.setdefault(typ, set()).add(state_key)
  478. if (typ, state_key) not in state_dict_ids:
  479. missing_types.add((typ, state_key))
  480. sentinel = object()
  481. def include(typ, state_key):
  482. valid_state_keys = type_to_key.get(typ, sentinel)
  483. if valid_state_keys is sentinel:
  484. return False
  485. if valid_state_keys is None:
  486. return True
  487. if state_key in valid_state_keys:
  488. return True
  489. return False
  490. got_all = not (missing_types or types is None)
  491. return {
  492. k: v for k, v in state_dict_ids.items()
  493. if include(k[0], k[1])
  494. }, missing_types, got_all
  495. def _get_all_state_from_cache(self, group):
  496. """Checks if group is in cache. See `_get_state_for_groups`
  497. Returns 2-tuple (`state_dict`, `got_all`). `got_all` is a bool
  498. indicating if we successfully retrieved all requests state from the
  499. cache, if False we need to query the DB for the missing state.
  500. Args:
  501. group: The state group to lookup
  502. """
  503. is_all, state_dict_ids = self._state_group_cache.get(group)
  504. return state_dict_ids, is_all
  505. @defer.inlineCallbacks
  506. def _get_state_for_groups(self, groups, types=None):
  507. """Given list of groups returns dict of group -> list of state events
  508. with matching types. `types` is a list of `(type, state_key)`, where
  509. a `state_key` of None matches all state_keys. If `types` is None then
  510. all events are returned.
  511. """
  512. if types:
  513. types = frozenset(types)
  514. results = {}
  515. missing_groups = []
  516. if types is not None:
  517. for group in set(groups):
  518. state_dict_ids, missing_types, got_all = self._get_some_state_from_cache(
  519. group, types
  520. )
  521. results[group] = state_dict_ids
  522. if not got_all:
  523. missing_groups.append(group)
  524. else:
  525. for group in set(groups):
  526. state_dict_ids, got_all = self._get_all_state_from_cache(
  527. group
  528. )
  529. results[group] = state_dict_ids
  530. if not got_all:
  531. missing_groups.append(group)
  532. if missing_groups:
  533. # Okay, so we have some missing_types, lets fetch them.
  534. cache_seq_num = self._state_group_cache.sequence
  535. group_to_state_dict = yield self._get_state_groups_from_groups(
  536. missing_groups, types
  537. )
  538. # Now we want to update the cache with all the things we fetched
  539. # from the database.
  540. for group, group_state_dict in group_to_state_dict.items():
  541. if types:
  542. # We delibrately put key -> None mappings into the cache to
  543. # cache absence of the key, on the assumption that if we've
  544. # explicitly asked for some types then we will probably ask
  545. # for them again.
  546. state_dict = {
  547. (intern_string(etype), intern_string(state_key)): None
  548. for (etype, state_key) in types
  549. }
  550. state_dict.update(results[group])
  551. results[group] = state_dict
  552. else:
  553. state_dict = results[group]
  554. state_dict.update({
  555. (intern_string(k[0]), intern_string(k[1])): v
  556. for k, v in group_state_dict.items()
  557. })
  558. self._state_group_cache.update(
  559. cache_seq_num,
  560. key=group,
  561. value=state_dict,
  562. full=(types is None),
  563. )
  564. # Remove all the entries with None values. The None values were just
  565. # used for bookkeeping in the cache.
  566. for group, state_dict in results.items():
  567. results[group] = {
  568. key: event_id
  569. for key, event_id in state_dict.items()
  570. if event_id
  571. }
  572. defer.returnValue(results)
  573. def get_next_state_group(self):
  574. return self._state_groups_id_gen.get_next()
  575. @defer.inlineCallbacks
  576. def _background_deduplicate_state(self, progress, batch_size):
  577. """This background update will slowly deduplicate state by reencoding
  578. them as deltas.
  579. """
  580. last_state_group = progress.get("last_state_group", 0)
  581. rows_inserted = progress.get("rows_inserted", 0)
  582. max_group = progress.get("max_group", None)
  583. BATCH_SIZE_SCALE_FACTOR = 100
  584. batch_size = max(1, int(batch_size / BATCH_SIZE_SCALE_FACTOR))
  585. if max_group is None:
  586. rows = yield self._execute(
  587. "_background_deduplicate_state", None,
  588. "SELECT coalesce(max(id), 0) FROM state_groups",
  589. )
  590. max_group = rows[0][0]
  591. def reindex_txn(txn):
  592. new_last_state_group = last_state_group
  593. for count in xrange(batch_size):
  594. txn.execute(
  595. "SELECT id, room_id FROM state_groups"
  596. " WHERE ? < id AND id <= ?"
  597. " ORDER BY id ASC"
  598. " LIMIT 1",
  599. (new_last_state_group, max_group,)
  600. )
  601. row = txn.fetchone()
  602. if row:
  603. state_group, room_id = row
  604. if not row or not state_group:
  605. return True, count
  606. txn.execute(
  607. "SELECT state_group FROM state_group_edges"
  608. " WHERE state_group = ?",
  609. (state_group,)
  610. )
  611. # If we reach a point where we've already started inserting
  612. # edges we should stop.
  613. if txn.fetchall():
  614. return True, count
  615. txn.execute(
  616. "SELECT coalesce(max(id), 0) FROM state_groups"
  617. " WHERE id < ? AND room_id = ?",
  618. (state_group, room_id,)
  619. )
  620. prev_group, = txn.fetchone()
  621. new_last_state_group = state_group
  622. if prev_group:
  623. potential_hops = self._count_state_group_hops_txn(
  624. txn, prev_group
  625. )
  626. if potential_hops >= MAX_STATE_DELTA_HOPS:
  627. # We want to ensure chains are at most this long,#
  628. # otherwise read performance degrades.
  629. continue
  630. prev_state = self._get_state_groups_from_groups_txn(
  631. txn, [prev_group], types=None
  632. )
  633. prev_state = prev_state[prev_group]
  634. curr_state = self._get_state_groups_from_groups_txn(
  635. txn, [state_group], types=None
  636. )
  637. curr_state = curr_state[state_group]
  638. if not set(prev_state.keys()) - set(curr_state.keys()):
  639. # We can only do a delta if the current has a strict super set
  640. # of keys
  641. delta_state = {
  642. key: value for key, value in curr_state.items()
  643. if prev_state.get(key, None) != value
  644. }
  645. self._simple_delete_txn(
  646. txn,
  647. table="state_group_edges",
  648. keyvalues={
  649. "state_group": state_group,
  650. }
  651. )
  652. self._simple_insert_txn(
  653. txn,
  654. table="state_group_edges",
  655. values={
  656. "state_group": state_group,
  657. "prev_state_group": prev_group,
  658. }
  659. )
  660. self._simple_delete_txn(
  661. txn,
  662. table="state_groups_state",
  663. keyvalues={
  664. "state_group": state_group,
  665. }
  666. )
  667. self._simple_insert_many_txn(
  668. txn,
  669. table="state_groups_state",
  670. values=[
  671. {
  672. "state_group": state_group,
  673. "room_id": room_id,
  674. "type": key[0],
  675. "state_key": key[1],
  676. "event_id": state_id,
  677. }
  678. for key, state_id in delta_state.items()
  679. ],
  680. )
  681. progress = {
  682. "last_state_group": state_group,
  683. "rows_inserted": rows_inserted + batch_size,
  684. "max_group": max_group,
  685. }
  686. self._background_update_progress_txn(
  687. txn, self.STATE_GROUP_DEDUPLICATION_UPDATE_NAME, progress
  688. )
  689. return False, batch_size
  690. finished, result = yield self.runInteraction(
  691. self.STATE_GROUP_DEDUPLICATION_UPDATE_NAME, reindex_txn
  692. )
  693. if finished:
  694. yield self._end_background_update(self.STATE_GROUP_DEDUPLICATION_UPDATE_NAME)
  695. defer.returnValue(result * BATCH_SIZE_SCALE_FACTOR)
  696. @defer.inlineCallbacks
  697. def _background_index_state(self, progress, batch_size):
  698. def reindex_txn(conn):
  699. conn.rollback()
  700. if isinstance(self.database_engine, PostgresEngine):
  701. # postgres insists on autocommit for the index
  702. conn.set_session(autocommit=True)
  703. try:
  704. txn = conn.cursor()
  705. txn.execute(
  706. "CREATE INDEX CONCURRENTLY state_groups_state_type_idx"
  707. " ON state_groups_state(state_group, type, state_key)"
  708. )
  709. txn.execute(
  710. "DROP INDEX IF EXISTS state_groups_state_id"
  711. )
  712. finally:
  713. conn.set_session(autocommit=False)
  714. else:
  715. txn = conn.cursor()
  716. txn.execute(
  717. "CREATE INDEX state_groups_state_type_idx"
  718. " ON state_groups_state(state_group, type, state_key)"
  719. )
  720. txn.execute(
  721. "DROP INDEX IF EXISTS state_groups_state_id"
  722. )
  723. yield self.runWithConnection(reindex_txn)
  724. yield self._end_background_update(self.STATE_GROUP_INDEX_UPDATE_NAME)
  725. defer.returnValue(1)