debug_state_res.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. #! /usr/bin/env python
  2. import argparse
  3. import logging
  4. import sys
  5. from pprint import pformat
  6. from typing import Awaitable, Callable, Collection, Dict, List, Optional, Tuple, cast
  7. from unittest.mock import MagicMock, patch
  8. import dictdiffer
  9. import pydot
  10. import yaml
  11. from twisted.internet import task
  12. from synapse.config._base import RootConfig
  13. from synapse.config.cache import CacheConfig
  14. from synapse.config.database import DatabaseConfig
  15. from synapse.config.workers import WorkerConfig
  16. from synapse.events import EventBase
  17. from synapse.server import HomeServer
  18. from synapse.state import StateResolutionStore
  19. from synapse.storage.databases.main.event_federation import EventFederationWorkerStore
  20. from synapse.storage.databases.main.events_worker import EventsWorkerStore
  21. from synapse.storage.databases.main.room import RoomWorkerStore
  22. from synapse.storage.databases.main.state import StateGroupWorkerStore
  23. from synapse.storage.state import StateFilter
  24. from synapse.types import ISynapseReactor, StateMap
  25. """This monstrosity is useful for visualising and debugging state resolution problems.
  26. """
  27. logger = logging.getLogger(sys.argv[0])
  28. # Bits of the HomeServer Machinery we need to talk to the DB.
  29. class Config(RootConfig):
  30. config_classes = [DatabaseConfig, WorkerConfig, CacheConfig]
  31. def load_config(source: str) -> Config:
  32. data = yaml.safe_load(source)
  33. data["worker_name"] = "stateres-debug"
  34. config = Config()
  35. config.parse_config_dict(data, "DUMMYPATH", "DUMMYPATH")
  36. config.key = MagicMock() # Don't bother creating signing keys
  37. return config
  38. class DataStore(
  39. StateGroupWorkerStore,
  40. EventFederationWorkerStore,
  41. EventsWorkerStore,
  42. RoomWorkerStore,
  43. ):
  44. pass
  45. class MockHomeserver(HomeServer):
  46. DATASTORE_CLASS = DataStore # type: ignore [assignment]
  47. def __init__(self, config: Config):
  48. super(MockHomeserver, self).__init__(
  49. hostname="stateres-debug",
  50. config=config, # type: ignore[arg-type]
  51. )
  52. # Functions for drawing graphviz diagrams via `pydot`.
  53. def node(
  54. event: EventBase, suffix: Optional[str] = None, **kwargs: object
  55. ) -> pydot.Node:
  56. if "label" not in kwargs:
  57. label = (
  58. f"{event.event_id}\n{event.sender}: {(event.type,event.get_state_key())}"
  59. )
  60. if event.type == "m.room.member":
  61. label += f" ({event.membership.upper()})"
  62. if suffix:
  63. label += f"\n{suffix}"
  64. kwargs["label"] = label
  65. type_to_shape: Dict[str, str] = {} # {"m.room.member": "oval"}
  66. if event.type in type_to_shape:
  67. kwargs.setdefault("shape", type_to_shape[event.type])
  68. q = pydot.quote_if_necessary
  69. return pydot.Node(q(event.event_id), **kwargs)
  70. def edge(source: EventBase, target: EventBase, **kwargs: object) -> pydot.Edge:
  71. return pydot.Edge(
  72. pydot.quote_if_necessary(source.event_id),
  73. pydot.quote_if_necessary(target.event_id),
  74. **kwargs,
  75. )
  76. async def dump_mainlines(
  77. hs: MockHomeserver,
  78. resolve_point: Optional[EventBase],
  79. events: Collection[EventBase],
  80. extras: Collection[str],
  81. watch_func: Optional[Callable[[EventBase], Awaitable[str]]] = None,
  82. ) -> None:
  83. """Visualise the auth DAG above a given `starting_event`.
  84. Starting with the given event's parents and any `extras` of interest, we search in
  85. their auth events for power levels, join rules and sender membership events.
  86. We recursively repeat this process for any events found during the search
  87. until we have no more auth-ancestors of interest to find.
  88. In this way we build up a subset of the auth chain of the `starting_event`.
  89. (In particular we omit edges to m.room.create: they are everywhere and convey no
  90. information.)
  91. An optional `watch_func` allows us to annotate the events we see with a string of
  92. our choice. This can be useful if we want to track a single piece of state through
  93. the auth DAG.
  94. """
  95. graph = pydot.Dot(rankdir="BT")
  96. graph.set_node_defaults(shape="box", style="filled")
  97. async def new_node(event: EventBase, **kwargs: object) -> pydot.Node:
  98. suffix = await watch_func(event) if watch_func else None
  99. return node(event, suffix, **kwargs)
  100. seen = set()
  101. todo: List[EventBase] = []
  102. if resolve_point:
  103. graph.add_node(await new_node(resolve_point, fillcolor="#6699cc"))
  104. seen.add(resolve_point.event_id)
  105. for parent in events:
  106. graph.add_node(await new_node(parent, fillcolor="#6699cc"))
  107. seen.add(parent.event_id)
  108. todo.append(parent)
  109. if resolve_point:
  110. graph.add_edge(edge(resolve_point, parent, style="dashed"))
  111. if extras:
  112. logger.debug(extras)
  113. extra_events = await hs.get_datastores().main.get_events(extras)
  114. logger.debug(extra_events)
  115. for extra_event in extra_events.values():
  116. if extra_event.event_id in seen:
  117. continue
  118. graph.add_node(await new_node(extra_event, fillcolor="#6699ee"))
  119. todo.append(extra_event)
  120. async def fetch_auth_events(event: EventBase) -> StateMap[EventBase]:
  121. return {
  122. (e.type, e.state_key): e
  123. for e in (
  124. await hs.get_datastores().main.get_events(event.auth_event_ids())
  125. ).values()
  126. }
  127. while todo:
  128. event = todo.pop()
  129. auth_events = await fetch_auth_events(event)
  130. for key, edge_style in [
  131. (("m.room.power_levels", ""), "solid"),
  132. (("m.room.join_rules", ""), "solid"),
  133. (("m.room.member", event.sender), "dotted"),
  134. # TODO: handle that state_key might be missing
  135. # (("m.room.member", event.state_key), "solid"),
  136. ]:
  137. auth_event = auth_events.get(key)
  138. if auth_event:
  139. if auth_event.event_id not in seen:
  140. node_options = {}
  141. if key[0] == "m.room.power_levels":
  142. node_options["fillcolor"] = "#ffcccc"
  143. elif key[0] == "m.room.join_rules":
  144. node_options["fillcolor"] = "#cc9966"
  145. elif key == ("m.room.member", event.sender):
  146. auth_events_2 = await fetch_auth_events(auth_event)
  147. if ("m.room.member", event.sender) not in auth_events_2:
  148. # auth_event is the first join of that sender
  149. node_options["fillcolor"] = "#33ff33"
  150. else:
  151. node_options["fillcolor"] = "#ccffcc"
  152. graph.add_node(await new_node(auth_event, **node_options))
  153. seen.add(auth_event.event_id)
  154. todo.append(auth_event)
  155. graph.add_edge(edge(event, auth_event, style=edge_style))
  156. # TODO: make this location configurable
  157. graph.write_svg("mainlines.svg")
  158. # The main logic and the arguments we need to invoke it.
  159. parser = argparse.ArgumentParser(
  160. description="Debug the stateres calculation of a specific event."
  161. )
  162. parser.add_argument(
  163. "config_file", help="Synapse config file", type=argparse.FileType("r")
  164. )
  165. parser.add_argument("--verbose", "-v", help="Log verbosely", action="store_true")
  166. parser.add_argument("-d", "--draw", help="Render auth DAG", action="store_true")
  167. parser.add_argument(
  168. "event_ids",
  169. help="""\
  170. The event ID(s) to be resolved.\
  171. If a single event is given, resolve across all of its parents to compute the state
  172. before the given event. If multiple events are given, resolve across them directly.
  173. """,
  174. nargs="+",
  175. )
  176. parser.add_argument(
  177. "-e",
  178. "--extra",
  179. dest="extras",
  180. help=(
  181. "An extra event to include in the auth DAG when using the `--draw` flag. "
  182. "Can be provided multiple times."
  183. ),
  184. action="append",
  185. )
  186. parser.add_argument(
  187. "--watch",
  188. help="Track a piece of state in the auth DAG when using the `--draw` flag.",
  189. default=None,
  190. nargs=2,
  191. metavar=("TYPE", "STATE_KEY"),
  192. )
  193. async def debug_specific_stateres(
  194. reactor: ISynapseReactor, hs: MockHomeserver, args: argparse.Namespace
  195. ) -> None:
  196. """Recompute the state at the given event.
  197. This produces
  198. - a file called `mainline.svg` representing the auth chain of the given event,
  199. - logging from state resolution calculations, written to stdout,
  200. - the recomputed and stored state, written to stdout, and
  201. - their difference, written to stdout.
  202. """
  203. DEBUG_AT_EVENT = len(args.event_ids) == 1
  204. if DEBUG_AT_EVENT:
  205. resolve_point = await hs.get_datastores().main.get_event(args.event_ids[0])
  206. prev_event_ids = resolve_point.prev_event_ids()
  207. else:
  208. resolve_point = None
  209. prev_event_ids = args.event_ids
  210. parent_events = (await hs.get_datastores().main.get_events(prev_event_ids)).values()
  211. sample_event = next(iter(parent_events))
  212. logger.info("Resolving across %d parents, %s", len(prev_event_ids), prev_event_ids)
  213. state_after_parents = [
  214. await hs.get_storage_controllers().state.get_state_ids_for_event(prev_event_id)
  215. for prev_event_id in prev_event_ids
  216. ]
  217. if args.watch is not None:
  218. key_pair = cast(Tuple[str, str], tuple(args.watch))
  219. filter = StateFilter.from_types([key_pair])
  220. watch_func: Optional[Callable[[EventBase], Awaitable[str]]]
  221. async def watch_func(event: EventBase) -> str:
  222. try:
  223. result = (
  224. await hs.get_storage_controllers().state.get_state_ids_for_event(
  225. event.event_id, filter
  226. )
  227. )
  228. except RuntimeError:
  229. return f"\n{key_pair}: <Event unavailable :(>"
  230. else:
  231. return f"\n{key_pair}: {result.get(key_pair, '<No event in state>')}"
  232. else:
  233. watch_func = None
  234. if args.draw:
  235. await dump_mainlines(hs, resolve_point, parent_events, args.extras, watch_func)
  236. result = await hs.get_state_resolution_handler().resolve_events_with_store(
  237. sample_event.room_id,
  238. sample_event.room_version.identifier,
  239. state_after_parents,
  240. event_map=None,
  241. state_res_store=StateResolutionStore(hs.get_datastores().main),
  242. )
  243. logger.info("State resolved:")
  244. logger.info(pformat(result))
  245. if DEBUG_AT_EVENT:
  246. logger.info("Stored state at %s:", sample_event.event_id)
  247. stored_state = await hs.get_storage_controllers().state.get_state_ids_for_event(
  248. sample_event.event_id
  249. )
  250. logger.info(pformat(stored_state))
  251. # TODO make this a like-for-like comparison.
  252. logger.info("Diff from stored (after event) to resolved (before event):")
  253. for change in dictdiffer.diff(stored_state, result):
  254. logger.info(pformat(change))
  255. # Entrypoint.
  256. if __name__ == "__main__":
  257. args = parser.parse_args()
  258. logging.basicConfig(
  259. format="%(asctime)s %(name)s:%(lineno)d %(levelname)s %(message)s",
  260. level=logging.DEBUG if args.verbose else logging.INFO,
  261. stream=sys.stdout,
  262. )
  263. # Suppress logs we aren't interested in.
  264. logging.getLogger("synapse.util").setLevel(logging.ERROR)
  265. logging.getLogger("synapse.storage").setLevel(logging.ERROR)
  266. config = load_config(args.config_file)
  267. hs = MockHomeserver(config)
  268. # Patch out enough stuff so we can work with a readonly DB connection.
  269. with patch("synapse.storage.databases.prepare_database"), patch(
  270. "synapse.storage.database.BackgroundUpdater"
  271. ), patch("synapse.storage.databases.main.events_worker.MultiWriterIdGenerator"):
  272. hs.setup()
  273. task.react(debug_specific_stateres, [hs, parser.parse_args()])