test_id_generators.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  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 synapse.storage.database import DatabasePool
  16. from synapse.storage.engines import IncorrectDatabaseSetup
  17. from synapse.storage.util.id_generators import MultiWriterIdGenerator
  18. from tests.unittest import HomeserverTestCase
  19. from tests.utils import USE_POSTGRES_FOR_TESTS
  20. class MultiWriterIdGeneratorTestCase(HomeserverTestCase):
  21. if not USE_POSTGRES_FOR_TESTS:
  22. skip = "Requires Postgres"
  23. def prepare(self, reactor, clock, hs):
  24. self.store = hs.get_datastore()
  25. self.db_pool = self.store.db_pool # type: DatabasePool
  26. self.get_success(self.db_pool.runInteraction("_setup_db", self._setup_db))
  27. def _setup_db(self, txn):
  28. txn.execute("CREATE SEQUENCE foobar_seq")
  29. txn.execute(
  30. """
  31. CREATE TABLE foobar (
  32. stream_id BIGINT NOT NULL,
  33. instance_name TEXT NOT NULL,
  34. data TEXT
  35. );
  36. """
  37. )
  38. def _create_id_generator(
  39. self, instance_name="master", writers=["master"]
  40. ) -> MultiWriterIdGenerator:
  41. def _create(conn):
  42. return MultiWriterIdGenerator(
  43. conn,
  44. self.db_pool,
  45. stream_name="test_stream",
  46. instance_name=instance_name,
  47. table="foobar",
  48. instance_column="instance_name",
  49. id_column="stream_id",
  50. sequence_name="foobar_seq",
  51. writers=writers,
  52. )
  53. return self.get_success_or_raise(self.db_pool.runWithConnection(_create))
  54. def _insert_rows(self, instance_name: str, number: int):
  55. """Insert N rows as the given instance, inserting with stream IDs pulled
  56. from the postgres sequence.
  57. """
  58. def _insert(txn):
  59. for _ in range(number):
  60. txn.execute(
  61. "INSERT INTO foobar VALUES (nextval('foobar_seq'), ?)",
  62. (instance_name,),
  63. )
  64. txn.execute(
  65. """
  66. INSERT INTO stream_positions VALUES ('test_stream', ?, lastval())
  67. ON CONFLICT (stream_name, instance_name) DO UPDATE SET stream_id = lastval()
  68. """,
  69. (instance_name,),
  70. )
  71. self.get_success(self.db_pool.runInteraction("_insert_rows", _insert))
  72. def _insert_row_with_id(self, instance_name: str, stream_id: int):
  73. """Insert one row as the given instance with given stream_id, updating
  74. the postgres sequence position to match.
  75. """
  76. def _insert(txn):
  77. txn.execute(
  78. "INSERT INTO foobar VALUES (?, ?)", (stream_id, instance_name,),
  79. )
  80. txn.execute("SELECT setval('foobar_seq', ?)", (stream_id,))
  81. txn.execute(
  82. """
  83. INSERT INTO stream_positions VALUES ('test_stream', ?, ?)
  84. ON CONFLICT (stream_name, instance_name) DO UPDATE SET stream_id = ?
  85. """,
  86. (instance_name, stream_id, stream_id),
  87. )
  88. self.get_success(self.db_pool.runInteraction("_insert_row_with_id", _insert))
  89. def test_empty(self):
  90. """Test an ID generator against an empty database gives sensible
  91. current positions.
  92. """
  93. id_gen = self._create_id_generator()
  94. # The table is empty so we expect an empty map for positions
  95. self.assertEqual(id_gen.get_positions(), {})
  96. def test_single_instance(self):
  97. """Test that reads and writes from a single process are handled
  98. correctly.
  99. """
  100. # Prefill table with 7 rows written by 'master'
  101. self._insert_rows("master", 7)
  102. id_gen = self._create_id_generator()
  103. self.assertEqual(id_gen.get_positions(), {"master": 7})
  104. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  105. # Try allocating a new ID gen and check that we only see position
  106. # advanced after we leave the context manager.
  107. async def _get_next_async():
  108. async with id_gen.get_next() as stream_id:
  109. self.assertEqual(stream_id, 8)
  110. self.assertEqual(id_gen.get_positions(), {"master": 7})
  111. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  112. self.get_success(_get_next_async())
  113. self.assertEqual(id_gen.get_positions(), {"master": 8})
  114. self.assertEqual(id_gen.get_current_token_for_writer("master"), 8)
  115. def test_out_of_order_finish(self):
  116. """Test that IDs persisted out of order are correctly handled
  117. """
  118. # Prefill table with 7 rows written by 'master'
  119. self._insert_rows("master", 7)
  120. id_gen = self._create_id_generator()
  121. self.assertEqual(id_gen.get_positions(), {"master": 7})
  122. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  123. ctx1 = self.get_success(id_gen.get_next())
  124. ctx2 = self.get_success(id_gen.get_next())
  125. ctx3 = self.get_success(id_gen.get_next())
  126. ctx4 = self.get_success(id_gen.get_next())
  127. s1 = self.get_success(ctx1.__aenter__())
  128. s2 = self.get_success(ctx2.__aenter__())
  129. s3 = self.get_success(ctx3.__aenter__())
  130. s4 = self.get_success(ctx4.__aenter__())
  131. self.assertEqual(s1, 8)
  132. self.assertEqual(s2, 9)
  133. self.assertEqual(s3, 10)
  134. self.assertEqual(s4, 11)
  135. self.assertEqual(id_gen.get_positions(), {"master": 7})
  136. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  137. self.get_success(ctx2.__aexit__(None, None, None))
  138. self.assertEqual(id_gen.get_positions(), {"master": 7})
  139. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  140. self.get_success(ctx1.__aexit__(None, None, None))
  141. self.assertEqual(id_gen.get_positions(), {"master": 9})
  142. self.assertEqual(id_gen.get_current_token_for_writer("master"), 9)
  143. self.get_success(ctx4.__aexit__(None, None, None))
  144. self.assertEqual(id_gen.get_positions(), {"master": 9})
  145. self.assertEqual(id_gen.get_current_token_for_writer("master"), 9)
  146. self.get_success(ctx3.__aexit__(None, None, None))
  147. self.assertEqual(id_gen.get_positions(), {"master": 11})
  148. self.assertEqual(id_gen.get_current_token_for_writer("master"), 11)
  149. def test_multi_instance(self):
  150. """Test that reads and writes from multiple processes are handled
  151. correctly.
  152. """
  153. self._insert_rows("first", 3)
  154. self._insert_rows("second", 4)
  155. first_id_gen = self._create_id_generator("first", writers=["first", "second"])
  156. second_id_gen = self._create_id_generator("second", writers=["first", "second"])
  157. # The first ID gen will notice that it can advance its token to 7 as it
  158. # has no in progress writes...
  159. self.assertEqual(first_id_gen.get_positions(), {"first": 7, "second": 7})
  160. self.assertEqual(first_id_gen.get_current_token_for_writer("first"), 7)
  161. self.assertEqual(first_id_gen.get_current_token_for_writer("second"), 7)
  162. # ... but the second ID gen doesn't know that.
  163. self.assertEqual(second_id_gen.get_positions(), {"first": 3, "second": 7})
  164. self.assertEqual(second_id_gen.get_current_token_for_writer("first"), 3)
  165. self.assertEqual(second_id_gen.get_current_token_for_writer("second"), 7)
  166. # Try allocating a new ID gen and check that we only see position
  167. # advanced after we leave the context manager.
  168. async def _get_next_async():
  169. async with first_id_gen.get_next() as stream_id:
  170. self.assertEqual(stream_id, 8)
  171. self.assertEqual(
  172. first_id_gen.get_positions(), {"first": 7, "second": 7}
  173. )
  174. self.get_success(_get_next_async())
  175. self.assertEqual(first_id_gen.get_positions(), {"first": 8, "second": 7})
  176. # However the ID gen on the second instance won't have seen the update
  177. self.assertEqual(second_id_gen.get_positions(), {"first": 3, "second": 7})
  178. # ... but calling `get_next` on the second instance should give a unique
  179. # stream ID
  180. async def _get_next_async():
  181. async with second_id_gen.get_next() as stream_id:
  182. self.assertEqual(stream_id, 9)
  183. self.assertEqual(
  184. second_id_gen.get_positions(), {"first": 3, "second": 7}
  185. )
  186. self.get_success(_get_next_async())
  187. self.assertEqual(second_id_gen.get_positions(), {"first": 3, "second": 9})
  188. # If the second ID gen gets told about the first, it correctly updates
  189. second_id_gen.advance("first", 8)
  190. self.assertEqual(second_id_gen.get_positions(), {"first": 8, "second": 9})
  191. def test_get_next_txn(self):
  192. """Test that the `get_next_txn` function works correctly.
  193. """
  194. # Prefill table with 7 rows written by 'master'
  195. self._insert_rows("master", 7)
  196. id_gen = self._create_id_generator()
  197. self.assertEqual(id_gen.get_positions(), {"master": 7})
  198. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  199. # Try allocating a new ID gen and check that we only see position
  200. # advanced after we leave the context manager.
  201. def _get_next_txn(txn):
  202. stream_id = id_gen.get_next_txn(txn)
  203. self.assertEqual(stream_id, 8)
  204. self.assertEqual(id_gen.get_positions(), {"master": 7})
  205. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  206. self.get_success(self.db_pool.runInteraction("test", _get_next_txn))
  207. self.assertEqual(id_gen.get_positions(), {"master": 8})
  208. self.assertEqual(id_gen.get_current_token_for_writer("master"), 8)
  209. def test_get_persisted_upto_position(self):
  210. """Test that `get_persisted_upto_position` correctly tracks updates to
  211. positions.
  212. """
  213. # The following tests are a bit cheeky in that we notify about new
  214. # positions via `advance` without *actually* advancing the postgres
  215. # sequence.
  216. self._insert_row_with_id("first", 3)
  217. self._insert_row_with_id("second", 5)
  218. id_gen = self._create_id_generator("worker", writers=["first", "second"])
  219. self.assertEqual(id_gen.get_positions(), {"first": 3, "second": 5})
  220. # Min is 3 and there is a gap between 5, so we expect it to be 3.
  221. self.assertEqual(id_gen.get_persisted_upto_position(), 3)
  222. # We advance "first" straight to 6. Min is now 5 but there is no gap so
  223. # we expect it to be 6
  224. id_gen.advance("first", 6)
  225. self.assertEqual(id_gen.get_persisted_upto_position(), 6)
  226. # No gap, so we expect 7.
  227. id_gen.advance("second", 7)
  228. self.assertEqual(id_gen.get_persisted_upto_position(), 7)
  229. # We haven't seen 8 yet, so we expect 7 still.
  230. id_gen.advance("second", 9)
  231. self.assertEqual(id_gen.get_persisted_upto_position(), 7)
  232. # Now that we've seen 7, 8 and 9 we can got straight to 9.
  233. id_gen.advance("first", 8)
  234. self.assertEqual(id_gen.get_persisted_upto_position(), 9)
  235. # Jump forward with gaps. The minimum is 11, even though we haven't seen
  236. # 10 we know that everything before 11 must be persisted.
  237. id_gen.advance("first", 11)
  238. id_gen.advance("second", 15)
  239. self.assertEqual(id_gen.get_persisted_upto_position(), 11)
  240. def test_get_persisted_upto_position_get_next(self):
  241. """Test that `get_persisted_upto_position` correctly tracks updates to
  242. positions when `get_next` is called.
  243. """
  244. self._insert_row_with_id("first", 3)
  245. self._insert_row_with_id("second", 5)
  246. id_gen = self._create_id_generator("first", writers=["first", "second"])
  247. self.assertEqual(id_gen.get_positions(), {"first": 5, "second": 5})
  248. self.assertEqual(id_gen.get_persisted_upto_position(), 5)
  249. async def _get_next_async():
  250. async with id_gen.get_next() as stream_id:
  251. self.assertEqual(stream_id, 6)
  252. self.assertEqual(id_gen.get_persisted_upto_position(), 5)
  253. self.get_success(_get_next_async())
  254. self.assertEqual(id_gen.get_persisted_upto_position(), 6)
  255. # We assume that so long as `get_next` does correctly advance the
  256. # `persisted_upto_position` in this case, then it will be correct in the
  257. # other cases that are tested above (since they'll hit the same code).
  258. def test_restart_during_out_of_order_persistence(self):
  259. """Test that restarting a process while another process is writing out
  260. of order updates are handled correctly.
  261. """
  262. # Prefill table with 7 rows written by 'master'
  263. self._insert_rows("master", 7)
  264. id_gen = self._create_id_generator()
  265. self.assertEqual(id_gen.get_positions(), {"master": 7})
  266. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  267. # Persist two rows at once
  268. ctx1 = self.get_success(id_gen.get_next())
  269. ctx2 = self.get_success(id_gen.get_next())
  270. s1 = self.get_success(ctx1.__aenter__())
  271. s2 = self.get_success(ctx2.__aenter__())
  272. self.assertEqual(s1, 8)
  273. self.assertEqual(s2, 9)
  274. self.assertEqual(id_gen.get_positions(), {"master": 7})
  275. self.assertEqual(id_gen.get_current_token_for_writer("master"), 7)
  276. # We finish persisting the second row before restart
  277. self.get_success(ctx2.__aexit__(None, None, None))
  278. # We simulate a restart of another worker by just creating a new ID gen.
  279. id_gen_worker = self._create_id_generator("worker")
  280. # Restarted worker should not see the second persisted row
  281. self.assertEqual(id_gen_worker.get_positions(), {"master": 7})
  282. self.assertEqual(id_gen_worker.get_current_token_for_writer("master"), 7)
  283. # Now if we persist the first row then both instances should jump ahead
  284. # correctly.
  285. self.get_success(ctx1.__aexit__(None, None, None))
  286. self.assertEqual(id_gen.get_positions(), {"master": 9})
  287. id_gen_worker.advance("master", 9)
  288. self.assertEqual(id_gen_worker.get_positions(), {"master": 9})
  289. def test_writer_config_change(self):
  290. """Test that changing the writer config correctly works.
  291. """
  292. self._insert_row_with_id("first", 3)
  293. self._insert_row_with_id("second", 5)
  294. # Initial config has two writers
  295. id_gen = self._create_id_generator("worker", writers=["first", "second"])
  296. self.assertEqual(id_gen.get_persisted_upto_position(), 3)
  297. self.assertEqual(id_gen.get_current_token_for_writer("first"), 3)
  298. self.assertEqual(id_gen.get_current_token_for_writer("second"), 5)
  299. # New config removes one of the configs. Note that if the writer is
  300. # removed from config we assume that it has been shut down and has
  301. # finished persisting, hence why the persisted upto position is 5.
  302. id_gen_2 = self._create_id_generator("second", writers=["second"])
  303. self.assertEqual(id_gen_2.get_persisted_upto_position(), 5)
  304. self.assertEqual(id_gen_2.get_current_token_for_writer("second"), 5)
  305. # This config points to a single, previously unused writer.
  306. id_gen_3 = self._create_id_generator("third", writers=["third"])
  307. self.assertEqual(id_gen_3.get_persisted_upto_position(), 5)
  308. # For new writers we assume their initial position to be the current
  309. # persisted up to position. This stops Synapse from doing a full table
  310. # scan when a new writer comes along.
  311. self.assertEqual(id_gen_3.get_current_token_for_writer("third"), 5)
  312. id_gen_4 = self._create_id_generator("fourth", writers=["third"])
  313. self.assertEqual(id_gen_4.get_current_token_for_writer("third"), 5)
  314. # Check that we get a sane next stream ID with this new config.
  315. async def _get_next_async():
  316. async with id_gen_3.get_next() as stream_id:
  317. self.assertEqual(stream_id, 6)
  318. self.get_success(_get_next_async())
  319. self.assertEqual(id_gen_3.get_persisted_upto_position(), 6)
  320. # If we add back the old "first" then we shouldn't see the persisted up
  321. # to position revert back to 3.
  322. id_gen_5 = self._create_id_generator("five", writers=["first", "third"])
  323. self.assertEqual(id_gen_5.get_persisted_upto_position(), 6)
  324. self.assertEqual(id_gen_5.get_current_token_for_writer("first"), 6)
  325. self.assertEqual(id_gen_5.get_current_token_for_writer("third"), 6)
  326. def test_sequence_consistency(self):
  327. """Test that we error out if the table and sequence diverges.
  328. """
  329. # Prefill with some rows
  330. self._insert_row_with_id("master", 3)
  331. # Now we add a row *without* updating the stream ID
  332. def _insert(txn):
  333. txn.execute("INSERT INTO foobar VALUES (26, 'master')")
  334. self.get_success(self.db_pool.runInteraction("_insert", _insert))
  335. # Creating the ID gen should error
  336. with self.assertRaises(IncorrectDatabaseSetup):
  337. self._create_id_generator("first")
  338. class BackwardsMultiWriterIdGeneratorTestCase(HomeserverTestCase):
  339. """Tests MultiWriterIdGenerator that produce *negative* stream IDs.
  340. """
  341. if not USE_POSTGRES_FOR_TESTS:
  342. skip = "Requires Postgres"
  343. def prepare(self, reactor, clock, hs):
  344. self.store = hs.get_datastore()
  345. self.db_pool = self.store.db_pool # type: DatabasePool
  346. self.get_success(self.db_pool.runInteraction("_setup_db", self._setup_db))
  347. def _setup_db(self, txn):
  348. txn.execute("CREATE SEQUENCE foobar_seq")
  349. txn.execute(
  350. """
  351. CREATE TABLE foobar (
  352. stream_id BIGINT NOT NULL,
  353. instance_name TEXT NOT NULL,
  354. data TEXT
  355. );
  356. """
  357. )
  358. def _create_id_generator(
  359. self, instance_name="master", writers=["master"]
  360. ) -> MultiWriterIdGenerator:
  361. def _create(conn):
  362. return MultiWriterIdGenerator(
  363. conn,
  364. self.db_pool,
  365. stream_name="test_stream",
  366. instance_name=instance_name,
  367. table="foobar",
  368. instance_column="instance_name",
  369. id_column="stream_id",
  370. sequence_name="foobar_seq",
  371. writers=writers,
  372. positive=False,
  373. )
  374. return self.get_success(self.db_pool.runWithConnection(_create))
  375. def _insert_row(self, instance_name: str, stream_id: int):
  376. """Insert one row as the given instance with given stream_id.
  377. """
  378. def _insert(txn):
  379. txn.execute(
  380. "INSERT INTO foobar VALUES (?, ?)", (stream_id, instance_name,),
  381. )
  382. txn.execute(
  383. """
  384. INSERT INTO stream_positions VALUES ('test_stream', ?, ?)
  385. ON CONFLICT (stream_name, instance_name) DO UPDATE SET stream_id = ?
  386. """,
  387. (instance_name, -stream_id, -stream_id),
  388. )
  389. self.get_success(self.db_pool.runInteraction("_insert_row", _insert))
  390. def test_single_instance(self):
  391. """Test that reads and writes from a single process are handled
  392. correctly.
  393. """
  394. id_gen = self._create_id_generator()
  395. async def _get_next_async():
  396. async with id_gen.get_next() as stream_id:
  397. self._insert_row("master", stream_id)
  398. self.get_success(_get_next_async())
  399. self.assertEqual(id_gen.get_positions(), {"master": -1})
  400. self.assertEqual(id_gen.get_current_token_for_writer("master"), -1)
  401. self.assertEqual(id_gen.get_persisted_upto_position(), -1)
  402. async def _get_next_async2():
  403. async with id_gen.get_next_mult(3) as stream_ids:
  404. for stream_id in stream_ids:
  405. self._insert_row("master", stream_id)
  406. self.get_success(_get_next_async2())
  407. self.assertEqual(id_gen.get_positions(), {"master": -4})
  408. self.assertEqual(id_gen.get_current_token_for_writer("master"), -4)
  409. self.assertEqual(id_gen.get_persisted_upto_position(), -4)
  410. # Test loading from DB by creating a second ID gen
  411. second_id_gen = self._create_id_generator()
  412. self.assertEqual(second_id_gen.get_positions(), {"master": -4})
  413. self.assertEqual(second_id_gen.get_current_token_for_writer("master"), -4)
  414. self.assertEqual(second_id_gen.get_persisted_upto_position(), -4)
  415. def test_multiple_instance(self):
  416. """Tests that having multiple instances that get advanced over
  417. federation works corretly.
  418. """
  419. id_gen_1 = self._create_id_generator("first", writers=["first", "second"])
  420. id_gen_2 = self._create_id_generator("second", writers=["first", "second"])
  421. async def _get_next_async():
  422. async with id_gen_1.get_next() as stream_id:
  423. self._insert_row("first", stream_id)
  424. id_gen_2.advance("first", stream_id)
  425. self.get_success(_get_next_async())
  426. self.assertEqual(id_gen_1.get_positions(), {"first": -1})
  427. self.assertEqual(id_gen_2.get_positions(), {"first": -1})
  428. self.assertEqual(id_gen_1.get_persisted_upto_position(), -1)
  429. self.assertEqual(id_gen_2.get_persisted_upto_position(), -1)
  430. async def _get_next_async2():
  431. async with id_gen_2.get_next() as stream_id:
  432. self._insert_row("second", stream_id)
  433. id_gen_1.advance("second", stream_id)
  434. self.get_success(_get_next_async2())
  435. self.assertEqual(id_gen_1.get_positions(), {"first": -2, "second": -2})
  436. self.assertEqual(id_gen_2.get_positions(), {"first": -1, "second": -2})
  437. self.assertEqual(id_gen_1.get_persisted_upto_position(), -2)
  438. self.assertEqual(id_gen_2.get_persisted_upto_position(), -2)