__init__.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector 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. import heapq
  16. import logging
  17. from collections import ChainMap, defaultdict
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. Awaitable,
  22. Callable,
  23. Collection,
  24. DefaultDict,
  25. Dict,
  26. FrozenSet,
  27. List,
  28. Mapping,
  29. Optional,
  30. Sequence,
  31. Set,
  32. Tuple,
  33. )
  34. import attr
  35. from frozendict import frozendict
  36. from prometheus_client import Counter, Histogram
  37. from synapse.api.constants import EventTypes
  38. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, StateResolutionVersions
  39. from synapse.events import EventBase
  40. from synapse.events.snapshot import EventContext
  41. from synapse.logging.context import ContextResourceUsage
  42. from synapse.replication.http.state import ReplicationUpdateCurrentStateRestServlet
  43. from synapse.state import v1, v2
  44. from synapse.storage.databases.main.events_worker import EventRedactBehaviour
  45. from synapse.storage.state import StateFilter
  46. from synapse.types import StateMap
  47. from synapse.util.async_helpers import Linearizer
  48. from synapse.util.caches.expiringcache import ExpiringCache
  49. from synapse.util.metrics import Measure, measure_func
  50. if TYPE_CHECKING:
  51. from synapse.server import HomeServer
  52. from synapse.storage.controllers import StateStorageController
  53. from synapse.storage.databases.main import DataStore
  54. logger = logging.getLogger(__name__)
  55. metrics_logger = logging.getLogger("synapse.state.metrics")
  56. # Metrics for number of state groups involved in a resolution.
  57. state_groups_histogram = Histogram(
  58. "synapse_state_number_state_groups_in_resolution",
  59. "Number of state groups used when performing a state resolution",
  60. buckets=(1, 2, 3, 5, 7, 10, 15, 20, 50, 100, 200, 500, "+Inf"),
  61. )
  62. EVICTION_TIMEOUT_SECONDS = 60 * 60
  63. _NEXT_STATE_ID = 1
  64. POWER_KEY = (EventTypes.PowerLevels, "")
  65. def _gen_state_id() -> str:
  66. global _NEXT_STATE_ID
  67. s = "X%d" % (_NEXT_STATE_ID,)
  68. _NEXT_STATE_ID += 1
  69. return s
  70. class _StateCacheEntry:
  71. __slots__ = ["_state", "state_group", "prev_group", "delta_ids"]
  72. def __init__(
  73. self,
  74. state: Optional[StateMap[str]],
  75. state_group: Optional[int],
  76. prev_group: Optional[int] = None,
  77. delta_ids: Optional[StateMap[str]] = None,
  78. ):
  79. if state is None and state_group is None and prev_group is None:
  80. raise Exception("One of state, state_group or prev_group must be not None")
  81. if prev_group is not None and delta_ids is None:
  82. raise Exception("If prev_group is set so must delta_ids")
  83. # A map from (type, state_key) to event_id.
  84. #
  85. # This can be None if we have a `state_group` (as then we can fetch the
  86. # state from the DB.)
  87. self._state = frozendict(state) if state is not None else None
  88. # the ID of a state group if one and only one is involved.
  89. # otherwise, None otherwise?
  90. self.state_group = state_group
  91. self.prev_group = prev_group
  92. self.delta_ids = frozendict(delta_ids) if delta_ids is not None else None
  93. async def get_state(
  94. self,
  95. state_storage: "StateStorageController",
  96. state_filter: Optional["StateFilter"] = None,
  97. ) -> StateMap[str]:
  98. """Get the state map for this entry, either from the in-memory state or
  99. looking up the state group in the DB.
  100. """
  101. if self._state is not None:
  102. return self._state
  103. if self.state_group is not None:
  104. return await state_storage.get_state_ids_for_group(
  105. self.state_group, state_filter
  106. )
  107. assert self.prev_group is not None and self.delta_ids is not None
  108. prev_state = await state_storage.get_state_ids_for_group(
  109. self.prev_group, state_filter
  110. )
  111. # ChainMap expects MutableMapping, but since we're using it immutably
  112. # its safe to give it immutable maps.
  113. return ChainMap(self.delta_ids, prev_state) # type: ignore[arg-type]
  114. def set_state_group(self, state_group: int) -> None:
  115. """Update the state group assigned to this state (e.g. after we've
  116. persisted it).
  117. Note: this will cause the cache entry to drop any stored state.
  118. """
  119. self.state_group = state_group
  120. # We clear out the state as we know longer need to explicitly keep it in
  121. # the `state_cache` (as the store state group cache will do that).
  122. self._state = None
  123. def __len__(self) -> int:
  124. # The len should be used to estimate how large this cache entry is, for
  125. # cache eviction purposes. This is why it's fine to return 1 if we're
  126. # not storing any state.
  127. length = 0
  128. if self._state:
  129. length += len(self._state)
  130. if self.delta_ids:
  131. length += len(self.delta_ids)
  132. return length or 1 # Make sure its not 0.
  133. class StateHandler:
  134. """Fetches bits of state from the stores, and does state resolution
  135. where necessary
  136. """
  137. def __init__(self, hs: "HomeServer"):
  138. self.clock = hs.get_clock()
  139. self.store = hs.get_datastores().main
  140. self._state_storage_controller = hs.get_storage_controllers().state
  141. self.hs = hs
  142. self._state_resolution_handler = hs.get_state_resolution_handler()
  143. self._storage_controllers = hs.get_storage_controllers()
  144. self._events_shard_config = hs.config.worker.events_shard_config
  145. self._instance_name = hs.get_instance_name()
  146. self._update_current_state_client = (
  147. ReplicationUpdateCurrentStateRestServlet.make_client(hs)
  148. )
  149. async def compute_state_after_events(
  150. self,
  151. room_id: str,
  152. event_ids: Collection[str],
  153. state_filter: Optional[StateFilter] = None,
  154. ) -> StateMap[str]:
  155. """Fetch the state after each of the given event IDs. Resolve them and return.
  156. This is typically used where `event_ids` is a collection of forward extremities
  157. in a room, intended to become the `prev_events` of a new event E. If so, the
  158. return value of this function represents the state before E.
  159. Args:
  160. room_id: the room_id containing the given events.
  161. event_ids: the events whose state should be fetched and resolved.
  162. Returns:
  163. the state dict (a mapping from (event_type, state_key) -> event_id) which
  164. holds the resolution of the states after the given event IDs.
  165. """
  166. logger.debug("calling resolve_state_groups from compute_state_after_events")
  167. ret = await self.resolve_state_groups_for_events(room_id, event_ids)
  168. return await ret.get_state(self._state_storage_controller, state_filter)
  169. async def get_current_user_ids_in_room(
  170. self, room_id: str, latest_event_ids: List[str]
  171. ) -> Set[str]:
  172. """
  173. Get the users IDs who are currently in a room.
  174. Note: This is much slower than using the equivalent method
  175. `DataStore.get_users_in_room` or `DataStore.get_users_in_room_with_profiles`,
  176. so this should only be used when wanting the users at a particular point
  177. in the room.
  178. Args:
  179. room_id: The ID of the room.
  180. latest_event_ids: Precomputed list of latest event IDs. Will be computed if None.
  181. Returns:
  182. Set of user IDs in the room.
  183. """
  184. assert latest_event_ids is not None
  185. logger.debug("calling resolve_state_groups from get_current_user_ids_in_room")
  186. entry = await self.resolve_state_groups_for_events(room_id, latest_event_ids)
  187. state = await entry.get_state(self._state_storage_controller, StateFilter.all())
  188. return await self.store.get_joined_user_ids_from_state(room_id, state)
  189. async def get_hosts_in_room_at_events(
  190. self, room_id: str, event_ids: Collection[str]
  191. ) -> FrozenSet[str]:
  192. """Get the hosts that were in a room at the given event ids
  193. Args:
  194. room_id:
  195. event_ids:
  196. Returns:
  197. The hosts in the room at the given events
  198. """
  199. entry = await self.resolve_state_groups_for_events(room_id, event_ids)
  200. state = await entry.get_state(self._state_storage_controller, StateFilter.all())
  201. return await self.store.get_joined_hosts(room_id, state, entry)
  202. async def compute_event_context(
  203. self,
  204. event: EventBase,
  205. state_ids_before_event: Optional[StateMap[str]] = None,
  206. partial_state: Optional[bool] = None,
  207. ) -> EventContext:
  208. """Build an EventContext structure for a non-outlier event.
  209. (for an outlier, call EventContext.for_outlier directly)
  210. This works out what the current state should be for the event, and
  211. generates a new state group if necessary.
  212. Args:
  213. event:
  214. state_ids_before_event: The event ids of the state before the event if
  215. it can't be calculated from existing events. This is normally
  216. only specified when receiving an event from federation where we
  217. don't have the prev events, e.g. when backfilling.
  218. partial_state:
  219. `True` if `state_ids_before_event` is partial and omits non-critical
  220. membership events.
  221. `False` if `state_ids_before_event` is the full state.
  222. `None` when `state_ids_before_event` is not provided. In this case, the
  223. flag will be calculated based on `event`'s prev events.
  224. Returns:
  225. The event context.
  226. Raises:
  227. RuntimeError if `state_ids_before_event` is not provided and one or more
  228. prev events are missing or outliers.
  229. """
  230. assert not event.internal_metadata.is_outlier()
  231. #
  232. # first of all, figure out the state before the event, unless we
  233. # already have it.
  234. #
  235. if state_ids_before_event:
  236. # if we're given the state before the event, then we use that
  237. state_group_before_event_prev_group = None
  238. deltas_to_state_group_before_event = None
  239. # .. though we need to get a state group for it.
  240. state_group_before_event = (
  241. await self._state_storage_controller.store_state_group(
  242. event.event_id,
  243. event.room_id,
  244. prev_group=None,
  245. delta_ids=None,
  246. current_state_ids=state_ids_before_event,
  247. )
  248. )
  249. # the partial_state flag must be provided
  250. assert partial_state is not None
  251. else:
  252. # otherwise, we'll need to resolve the state across the prev_events.
  253. # partial_state should not be set explicitly in this case:
  254. # we work it out dynamically
  255. assert partial_state is None
  256. # if any of the prev-events have partial state, so do we.
  257. # (This is slightly racy - the prev-events might get fixed up before we use
  258. # their states - but I don't think that really matters; it just means we
  259. # might redundantly recalculate the state for this event later.)
  260. prev_event_ids = event.prev_event_ids()
  261. incomplete_prev_events = await self.store.get_partial_state_events(
  262. prev_event_ids
  263. )
  264. partial_state = any(incomplete_prev_events.values())
  265. if partial_state:
  266. logger.debug(
  267. "New/incoming event %s refers to prev_events %s with partial state",
  268. event.event_id,
  269. [k for (k, v) in incomplete_prev_events.items() if v],
  270. )
  271. logger.debug("calling resolve_state_groups from compute_event_context")
  272. # we've already taken into account partial state, so no need to wait for
  273. # complete state here.
  274. entry = await self.resolve_state_groups_for_events(
  275. event.room_id,
  276. event.prev_event_ids(),
  277. await_full_state=False,
  278. )
  279. state_group_before_event_prev_group = entry.prev_group
  280. deltas_to_state_group_before_event = entry.delta_ids
  281. state_ids_before_event = None
  282. # We make sure that we have a state group assigned to the state.
  283. if entry.state_group is None:
  284. # store_state_group requires us to have either a previous state group
  285. # (with deltas) or the complete state map. So, if we don't have a
  286. # previous state group, load the complete state map now.
  287. if state_group_before_event_prev_group is None:
  288. state_ids_before_event = await entry.get_state(
  289. self._state_storage_controller, StateFilter.all()
  290. )
  291. state_group_before_event = (
  292. await self._state_storage_controller.store_state_group(
  293. event.event_id,
  294. event.room_id,
  295. prev_group=state_group_before_event_prev_group,
  296. delta_ids=deltas_to_state_group_before_event,
  297. current_state_ids=state_ids_before_event,
  298. )
  299. )
  300. entry.set_state_group(state_group_before_event)
  301. else:
  302. state_group_before_event = entry.state_group
  303. #
  304. # now if it's not a state event, we're done
  305. #
  306. if not event.is_state():
  307. return EventContext.with_state(
  308. storage=self._storage_controllers,
  309. state_group_before_event=state_group_before_event,
  310. state_group=state_group_before_event,
  311. state_delta_due_to_event={},
  312. prev_group=state_group_before_event_prev_group,
  313. delta_ids=deltas_to_state_group_before_event,
  314. partial_state=partial_state,
  315. )
  316. #
  317. # otherwise, we'll need to create a new state group for after the event
  318. #
  319. key = (event.type, event.state_key)
  320. if state_ids_before_event is not None:
  321. replaces = state_ids_before_event.get(key)
  322. else:
  323. replaces_state_map = await entry.get_state(
  324. self._state_storage_controller, StateFilter.from_types([key])
  325. )
  326. replaces = replaces_state_map.get(key)
  327. if replaces and replaces != event.event_id:
  328. event.unsigned["replaces_state"] = replaces
  329. delta_ids = {key: event.event_id}
  330. state_group_after_event = (
  331. await self._state_storage_controller.store_state_group(
  332. event.event_id,
  333. event.room_id,
  334. prev_group=state_group_before_event,
  335. delta_ids=delta_ids,
  336. current_state_ids=None,
  337. )
  338. )
  339. return EventContext.with_state(
  340. storage=self._storage_controllers,
  341. state_group=state_group_after_event,
  342. state_group_before_event=state_group_before_event,
  343. state_delta_due_to_event=delta_ids,
  344. prev_group=state_group_before_event,
  345. delta_ids=delta_ids,
  346. partial_state=partial_state,
  347. )
  348. async def compute_event_context_for_batched(
  349. self,
  350. event: EventBase,
  351. state_ids_before_event: StateMap[str],
  352. current_state_group: int,
  353. ) -> EventContext:
  354. """
  355. Generate an event context for an event that has not yet been persisted to the
  356. database. Intended for use with events that are created to be persisted in a batch.
  357. Args:
  358. event: the event the context is being computed for
  359. state_ids_before_event: a state map consisting of the state ids of the events
  360. created prior to this event.
  361. current_state_group: the current state group before the event.
  362. """
  363. state_group_before_event_prev_group = None
  364. deltas_to_state_group_before_event = None
  365. state_group_before_event = current_state_group
  366. # if the event is not state, we are set
  367. if not event.is_state():
  368. return EventContext.with_state(
  369. storage=self._storage_controllers,
  370. state_group_before_event=state_group_before_event,
  371. state_group=state_group_before_event,
  372. state_delta_due_to_event={},
  373. prev_group=state_group_before_event_prev_group,
  374. delta_ids=deltas_to_state_group_before_event,
  375. partial_state=False,
  376. )
  377. # otherwise, we'll need to create a new state group for after the event
  378. key = (event.type, event.state_key)
  379. if state_ids_before_event is not None:
  380. replaces = state_ids_before_event.get(key)
  381. if replaces and replaces != event.event_id:
  382. event.unsigned["replaces_state"] = replaces
  383. delta_ids = {key: event.event_id}
  384. state_group_after_event = (
  385. await self._state_storage_controller.store_state_group(
  386. event.event_id,
  387. event.room_id,
  388. prev_group=state_group_before_event,
  389. delta_ids=delta_ids,
  390. current_state_ids=None,
  391. )
  392. )
  393. return EventContext.with_state(
  394. storage=self._storage_controllers,
  395. state_group=state_group_after_event,
  396. state_group_before_event=state_group_before_event,
  397. state_delta_due_to_event=delta_ids,
  398. prev_group=state_group_before_event,
  399. delta_ids=delta_ids,
  400. partial_state=False,
  401. )
  402. @measure_func()
  403. async def resolve_state_groups_for_events(
  404. self, room_id: str, event_ids: Collection[str], await_full_state: bool = True
  405. ) -> _StateCacheEntry:
  406. """Given a list of event_ids this method fetches the state at each
  407. event, resolves conflicts between them and returns them.
  408. Args:
  409. room_id
  410. event_ids
  411. await_full_state: if true, will block if we do not yet have complete
  412. state at these events.
  413. Returns:
  414. The resolved state
  415. Raises:
  416. RuntimeError if we don't have a state group for one or more of the events
  417. (ie. they are outliers or unknown)
  418. """
  419. logger.debug("resolve_state_groups event_ids %s", event_ids)
  420. state_groups = await self._state_storage_controller.get_state_group_for_events(
  421. event_ids, await_full_state=await_full_state
  422. )
  423. state_group_ids = state_groups.values()
  424. # check if each event has same state group id, if so there's no state to resolve
  425. state_group_ids_set = set(state_group_ids)
  426. if len(state_group_ids_set) == 1:
  427. (state_group_id,) = state_group_ids_set
  428. (
  429. prev_group,
  430. delta_ids,
  431. ) = await self._state_storage_controller.get_state_group_delta(
  432. state_group_id
  433. )
  434. return _StateCacheEntry(
  435. state=None,
  436. state_group=state_group_id,
  437. prev_group=prev_group,
  438. delta_ids=delta_ids,
  439. )
  440. elif len(state_group_ids_set) == 0:
  441. return _StateCacheEntry(state={}, state_group=None)
  442. room_version = await self.store.get_room_version_id(room_id)
  443. state_to_resolve = await self._state_storage_controller.get_state_for_groups(
  444. state_group_ids_set
  445. )
  446. result = await self._state_resolution_handler.resolve_state_groups(
  447. room_id,
  448. room_version,
  449. state_to_resolve,
  450. None,
  451. state_res_store=StateResolutionStore(self.store),
  452. )
  453. return result
  454. async def update_current_state(self, room_id: str) -> None:
  455. """Recalculates the current state for a room, and persists it.
  456. Raises:
  457. SynapseError(502): if all attempts to connect to the event persister worker
  458. fail
  459. """
  460. writer_instance = self._events_shard_config.get_instance(room_id)
  461. if writer_instance != self._instance_name:
  462. await self._update_current_state_client(
  463. instance_name=writer_instance,
  464. room_id=room_id,
  465. )
  466. return
  467. assert self._storage_controllers.persistence is not None
  468. await self._storage_controllers.persistence.update_current_state(room_id)
  469. @attr.s(slots=True, auto_attribs=True)
  470. class _StateResMetrics:
  471. """Keeps track of some usage metrics about state res."""
  472. # System and User CPU time, in seconds
  473. cpu_time: float = 0.0
  474. # time spent on database transactions (excluding scheduling time). This roughly
  475. # corresponds to the amount of work done on the db server, excluding event fetches.
  476. db_time: float = 0.0
  477. # number of events fetched from the db.
  478. db_events: int = 0
  479. _biggest_room_by_cpu_counter = Counter(
  480. "synapse_state_res_cpu_for_biggest_room_seconds",
  481. "CPU time spent performing state resolution for the single most expensive "
  482. "room for state resolution",
  483. )
  484. _biggest_room_by_db_counter = Counter(
  485. "synapse_state_res_db_for_biggest_room_seconds",
  486. "Database time spent performing state resolution for the single most "
  487. "expensive room for state resolution",
  488. )
  489. _cpu_times = Histogram(
  490. "synapse_state_res_cpu_for_all_rooms_seconds",
  491. "CPU time (utime+stime) spent computing a single state resolution",
  492. )
  493. _db_times = Histogram(
  494. "synapse_state_res_db_for_all_rooms_seconds",
  495. "Database time spent computing a single state resolution",
  496. )
  497. class StateResolutionHandler:
  498. """Responsible for doing state conflict resolution.
  499. Note that the storage layer depends on this handler, so all functions must
  500. be storage-independent.
  501. """
  502. def __init__(self, hs: "HomeServer"):
  503. self.clock = hs.get_clock()
  504. self.resolve_linearizer = Linearizer(name="state_resolve_lock")
  505. # dict of set of event_ids -> _StateCacheEntry.
  506. self._state_cache: ExpiringCache[
  507. FrozenSet[int], _StateCacheEntry
  508. ] = ExpiringCache(
  509. cache_name="state_cache",
  510. clock=self.clock,
  511. max_len=100000,
  512. expiry_ms=EVICTION_TIMEOUT_SECONDS * 1000,
  513. iterable=True,
  514. reset_expiry_on_get=True,
  515. )
  516. #
  517. # stuff for tracking time spent on state-res by room
  518. #
  519. # tracks the amount of work done on state res per room
  520. self._state_res_metrics: DefaultDict[str, _StateResMetrics] = defaultdict(
  521. _StateResMetrics
  522. )
  523. self.clock.looping_call(self._report_metrics, 120 * 1000)
  524. async def resolve_state_groups(
  525. self,
  526. room_id: str,
  527. room_version: str,
  528. state_groups_ids: Mapping[int, StateMap[str]],
  529. event_map: Optional[Dict[str, EventBase]],
  530. state_res_store: "StateResolutionStore",
  531. ) -> _StateCacheEntry:
  532. """Resolves conflicts between a set of state groups
  533. Always generates a new state group (unless we hit the cache), so should
  534. not be called for a single state group
  535. Args:
  536. room_id: room we are resolving for (used for logging and sanity checks)
  537. room_version: version of the room
  538. state_groups_ids:
  539. A map from state group id to the state in that state group
  540. (where 'state' is a map from state key to event id)
  541. event_map:
  542. a dict from event_id to event, for any events that we happen to
  543. have in flight (eg, those currently being persisted). This will be
  544. used as a starting point for finding the state we need; any missing
  545. events will be requested via state_res_store.
  546. If None, all events will be fetched via state_res_store.
  547. state_res_store
  548. Returns:
  549. The resolved state
  550. """
  551. group_names = frozenset(state_groups_ids.keys())
  552. async with self.resolve_linearizer.queue(group_names):
  553. cache = self._state_cache.get(group_names, None)
  554. if cache:
  555. return cache
  556. logger.info(
  557. "Resolving state for %s with groups %s",
  558. room_id,
  559. list(group_names),
  560. )
  561. state_groups_histogram.observe(len(state_groups_ids))
  562. new_state = await self.resolve_events_with_store(
  563. room_id,
  564. room_version,
  565. list(state_groups_ids.values()),
  566. event_map=event_map,
  567. state_res_store=state_res_store,
  568. )
  569. # if the new state matches any of the input state groups, we can
  570. # use that state group again. Otherwise we will generate a state_id
  571. # which will be used as a cache key for future resolutions, but
  572. # not get persisted.
  573. with Measure(self.clock, "state.create_group_ids"):
  574. cache = _make_state_cache_entry(new_state, state_groups_ids)
  575. self._state_cache[group_names] = cache
  576. return cache
  577. async def resolve_events_with_store(
  578. self,
  579. room_id: str,
  580. room_version: str,
  581. state_sets: Sequence[StateMap[str]],
  582. event_map: Optional[Dict[str, EventBase]],
  583. state_res_store: "StateResolutionStore",
  584. ) -> StateMap[str]:
  585. """
  586. Args:
  587. room_id: the room we are working in
  588. room_version: Version of the room
  589. state_sets: List of dicts of (type, state_key) -> event_id,
  590. which are the different state groups to resolve.
  591. event_map:
  592. a dict from event_id to event, for any events that we happen to
  593. have in flight (eg, those currently being persisted). This will be
  594. used as a starting point for finding the state we need; any missing
  595. events will be requested via state_map_factory.
  596. If None, all events will be fetched via state_res_store.
  597. state_res_store: a place to fetch events from
  598. Returns:
  599. a map from (type, state_key) to event_id.
  600. """
  601. try:
  602. with Measure(self.clock, "state._resolve_events") as m:
  603. room_version_obj = KNOWN_ROOM_VERSIONS[room_version]
  604. if room_version_obj.state_res == StateResolutionVersions.V1:
  605. return await v1.resolve_events_with_store(
  606. room_id,
  607. room_version_obj,
  608. state_sets,
  609. event_map,
  610. state_res_store.get_events,
  611. )
  612. else:
  613. return await v2.resolve_events_with_store(
  614. self.clock,
  615. room_id,
  616. room_version_obj,
  617. state_sets,
  618. event_map,
  619. state_res_store,
  620. )
  621. finally:
  622. self._record_state_res_metrics(room_id, m.get_resource_usage())
  623. def _record_state_res_metrics(
  624. self, room_id: str, rusage: ContextResourceUsage
  625. ) -> None:
  626. room_metrics = self._state_res_metrics[room_id]
  627. room_metrics.cpu_time += rusage.ru_utime + rusage.ru_stime
  628. room_metrics.db_time += rusage.db_txn_duration_sec
  629. room_metrics.db_events += rusage.evt_db_fetch_count
  630. _cpu_times.observe(rusage.ru_utime + rusage.ru_stime)
  631. _db_times.observe(rusage.db_txn_duration_sec)
  632. def _report_metrics(self) -> None:
  633. if not self._state_res_metrics:
  634. # no state res has happened since the last iteration: don't bother logging.
  635. return
  636. self._report_biggest(
  637. lambda i: i.cpu_time,
  638. "CPU time",
  639. _biggest_room_by_cpu_counter,
  640. )
  641. self._report_biggest(
  642. lambda i: i.db_time,
  643. "DB time",
  644. _biggest_room_by_db_counter,
  645. )
  646. self._state_res_metrics.clear()
  647. def _report_biggest(
  648. self,
  649. extract_key: Callable[[_StateResMetrics], Any],
  650. metric_name: str,
  651. prometheus_counter_metric: Counter,
  652. ) -> None:
  653. """Report metrics on the biggest rooms for state res
  654. Args:
  655. extract_key: a callable which, given a _StateResMetrics, extracts a single
  656. metric to sort by.
  657. metric_name: the name of the metric we have extracted, for the log line
  658. prometheus_counter_metric: a prometheus metric recording the sum of the
  659. the extracted metric
  660. """
  661. n_to_log = 10
  662. if not metrics_logger.isEnabledFor(logging.DEBUG):
  663. # only need the most expensive if we don't have debug logging, which
  664. # allows nlargest() to degrade to max()
  665. n_to_log = 1
  666. items = self._state_res_metrics.items()
  667. # log the N biggest rooms
  668. biggest: List[Tuple[str, _StateResMetrics]] = heapq.nlargest(
  669. n_to_log, items, key=lambda i: extract_key(i[1])
  670. )
  671. metrics_logger.debug(
  672. "%i biggest rooms for state-res by %s: %s",
  673. len(biggest),
  674. metric_name,
  675. ["%s (%gs)" % (r, extract_key(m)) for (r, m) in biggest],
  676. )
  677. # report info on the single biggest to prometheus
  678. _, biggest_metrics = biggest[0]
  679. prometheus_counter_metric.inc(extract_key(biggest_metrics))
  680. def _make_state_cache_entry(
  681. new_state: StateMap[str], state_groups_ids: Mapping[int, StateMap[str]]
  682. ) -> _StateCacheEntry:
  683. """Given a resolved state, and a set of input state groups, pick one to base
  684. a new state group on (if any), and return an appropriately-constructed
  685. _StateCacheEntry.
  686. Args:
  687. new_state: resolved state map (mapping from (type, state_key) to event_id)
  688. state_groups_ids:
  689. map from state group id to the state in that state group (where
  690. 'state' is a map from state key to event id)
  691. Returns:
  692. The cache entry.
  693. """
  694. # if the new state matches any of the input state groups, we can
  695. # use that state group again. Otherwise we will generate a state_id
  696. # which will be used as a cache key for future resolutions, but
  697. # not get persisted.
  698. # first look for exact matches
  699. new_state_event_ids = set(new_state.values())
  700. for sg, state in state_groups_ids.items():
  701. if len(new_state_event_ids) != len(state):
  702. continue
  703. old_state_event_ids = set(state.values())
  704. if new_state_event_ids == old_state_event_ids:
  705. # got an exact match.
  706. return _StateCacheEntry(state=None, state_group=sg)
  707. # TODO: We want to create a state group for this set of events, to
  708. # increase cache hits, but we need to make sure that it doesn't
  709. # end up as a prev_group without being added to the database
  710. # failing that, look for the closest match.
  711. prev_group = None
  712. delta_ids: Optional[StateMap[str]] = None
  713. for old_group, old_state in state_groups_ids.items():
  714. if old_state.keys() - new_state.keys():
  715. # Currently we don't support deltas that remove keys from the state
  716. # map, so we have to ignore this group as a candidate to base the
  717. # new group on.
  718. continue
  719. n_delta_ids = {k: v for k, v in new_state.items() if old_state.get(k) != v}
  720. if not delta_ids or len(n_delta_ids) < len(delta_ids):
  721. prev_group = old_group
  722. delta_ids = n_delta_ids
  723. if prev_group is not None:
  724. # If we have a prev group and deltas then we can drop the new state from
  725. # the cache (to reduce memory usage).
  726. return _StateCacheEntry(
  727. state=None, state_group=None, prev_group=prev_group, delta_ids=delta_ids
  728. )
  729. else:
  730. return _StateCacheEntry(state=new_state, state_group=None)
  731. @attr.s(slots=True, auto_attribs=True)
  732. class StateResolutionStore:
  733. """Interface that allows state resolution algorithms to access the database
  734. in well defined way.
  735. """
  736. store: "DataStore"
  737. def get_events(
  738. self, event_ids: Collection[str], allow_rejected: bool = False
  739. ) -> Awaitable[Dict[str, EventBase]]:
  740. """Get events from the database
  741. Args:
  742. event_ids: The event_ids of the events to fetch
  743. allow_rejected: If True return rejected events.
  744. Returns:
  745. An awaitable which resolves to a dict from event_id to event.
  746. """
  747. return self.store.get_events(
  748. event_ids,
  749. redact_behaviour=EventRedactBehaviour.as_is,
  750. get_prev_content=False,
  751. allow_rejected=allow_rejected,
  752. )
  753. def get_auth_chain_difference(
  754. self, room_id: str, state_sets: List[Set[str]]
  755. ) -> Awaitable[Set[str]]:
  756. """Given sets of state events figure out the auth chain difference (as
  757. per state res v2 algorithm).
  758. This equivalent to fetching the full auth chain for each set of state
  759. and returning the events that don't appear in each and every auth
  760. chain.
  761. Returns:
  762. An awaitable that resolves to a set of event IDs.
  763. """
  764. return self.store.get_auth_chain_difference(room_id, state_sets)