test_greenlet_trash.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # -*- coding: utf-8 -*-
  2. """
  3. Tests for greenlets interacting with the CPython trash can API.
  4. The CPython trash can API is not designed to be re-entered from a
  5. single thread. But this can happen using greenlets, if something
  6. during the object deallocation process switches greenlets, and this second
  7. greenlet then causes the trash can to get entered again. Here, we do this
  8. very explicitly, but in other cases (like gevent) it could be arbitrarily more
  9. complicated: for example, a weakref callback might try to acquire a lock that's
  10. already held by another greenlet; that would allow a greenlet switch to occur.
  11. See https://github.com/gevent/gevent/issues/1909
  12. This test is fragile and relies on details of the CPython
  13. implementation (like most of the rest of this package):
  14. - We enter the trashcan and deferred deallocation after
  15. ``_PyTrash_UNWIND_LEVEL`` calls. This constant, defined in
  16. CPython's object.c, is generally 50. That's basically how many objects are required to
  17. get us into the deferred deallocation situation.
  18. - The test fails by hitting an ``assert()`` in object.c; if the
  19. build didn't enable assert, then we don't catch this.
  20. - If the test fails in that way, the interpreter crashes.
  21. """
  22. from __future__ import print_function, absolute_import, division
  23. import sys
  24. import unittest
  25. class TestTrashCanReEnter(unittest.TestCase):
  26. @unittest.skipUnless(
  27. sys.version_info[0] > 2,
  28. "Python 2 tracks this slightly differently, so our test doesn't catch a problem there. "
  29. )
  30. def test_it(self):
  31. # Try several times to trigger it, because it isn't 100%
  32. # reliable.
  33. for _ in range(10):
  34. self.check_it()
  35. def check_it(self): # pylint:disable=too-many-statements
  36. import greenlet
  37. from greenlet._greenlet import get_tstate_trash_delete_nesting # pylint:disable=no-name-in-module
  38. main = greenlet.getcurrent()
  39. assert get_tstate_trash_delete_nesting() == 0
  40. # We expect to be in deferred deallocation after this many
  41. # deallocations have occurred. TODO: I wish we had a better way to do
  42. # this --- that was before get_tstate_trash_delete_nesting; perhaps
  43. # we can use that API to do better?
  44. TRASH_UNWIND_LEVEL = 50
  45. # How many objects to put in a container; it's the container that
  46. # queues objects for deferred deallocation.
  47. OBJECTS_PER_CONTAINER = 500
  48. class Dealloc: # define the class here because we alter class variables each time we run.
  49. """
  50. An object with a ``__del__`` method. When it starts getting deallocated
  51. from a deferred trash can run, it switches greenlets, allocates more objects
  52. which then also go in the trash can. If we don't save state appropriately,
  53. nesting gets out of order and we can crash the interpreter.
  54. """
  55. #: Has our deallocation actually run and switched greenlets?
  56. #: When it does, this will be set to the current greenlet. This should
  57. #: be happening in the main greenlet, so we check that down below.
  58. SPAWNED = False
  59. #: Has the background greenlet run?
  60. BG_RAN = False
  61. BG_GLET = None
  62. #: How many of these things have ever been allocated.
  63. CREATED = 0
  64. #: How many of these things have ever been deallocated.
  65. DESTROYED = 0
  66. #: How many were destroyed not in the main greenlet. There should always
  67. #: be some.
  68. #: If the test is broken or things change in the trashcan implementation,
  69. #: this may not be correct.
  70. DESTROYED_BG = 0
  71. def __init__(self, sequence_number):
  72. """
  73. :param sequence_number: The ordinal of this object during
  74. one particular creation run. This is used to detect (guess, really)
  75. when we have entered the trash can's deferred deallocation.
  76. """
  77. self.i = sequence_number
  78. Dealloc.CREATED += 1
  79. def __del__(self):
  80. if self.i == TRASH_UNWIND_LEVEL and not self.SPAWNED:
  81. Dealloc.SPAWNED = greenlet.getcurrent()
  82. other = Dealloc.BG_GLET = greenlet.greenlet(background_greenlet)
  83. x = other.switch()
  84. assert x == 42
  85. # It's important that we don't switch back to the greenlet,
  86. # we leave it hanging there in an incomplete state. But we don't let it
  87. # get collected, either. If we complete it now, while we're still
  88. # in the scope of the initial trash can, things work out and we
  89. # don't see the problem. We need this greenlet to complete
  90. # at some point in the future, after we've exited this trash can invocation.
  91. del other
  92. elif self.i == 40 and greenlet.getcurrent() is not main:
  93. Dealloc.BG_RAN = True
  94. try:
  95. main.switch(42)
  96. except greenlet.GreenletExit as ex:
  97. # We expect this; all references to us go away
  98. # while we're still running, and we need to finish deleting
  99. # ourself.
  100. Dealloc.BG_RAN = type(ex)
  101. del ex
  102. # Record the fact that we're dead last of all. This ensures that
  103. # we actually get returned too.
  104. Dealloc.DESTROYED += 1
  105. if greenlet.getcurrent() is not main:
  106. Dealloc.DESTROYED_BG += 1
  107. def background_greenlet():
  108. # We direct through a second function, instead of
  109. # directly calling ``make_some()``, so that we have complete
  110. # control over when these objects are destroyed: we need them
  111. # to be destroyed in the context of the background greenlet
  112. t = make_some()
  113. del t # Triggere deletion.
  114. def make_some():
  115. t = ()
  116. i = OBJECTS_PER_CONTAINER
  117. while i:
  118. # Nest the tuples; it's the recursion that gets us
  119. # into trash.
  120. t = (Dealloc(i), t)
  121. i -= 1
  122. return t
  123. some = make_some()
  124. self.assertEqual(Dealloc.CREATED, OBJECTS_PER_CONTAINER)
  125. self.assertEqual(Dealloc.DESTROYED, 0)
  126. # If we're going to crash, it should be on the following line.
  127. # We only crash if ``assert()`` is enabled, of course.
  128. del some
  129. # For non-debug builds of CPython, we won't crash. The best we can do is check
  130. # the nesting level explicitly.
  131. self.assertEqual(0, get_tstate_trash_delete_nesting())
  132. # Discard this, raising GreenletExit into where it is waiting.
  133. Dealloc.BG_GLET = None
  134. # The same nesting level maintains.
  135. self.assertEqual(0, get_tstate_trash_delete_nesting())
  136. # We definitely cleaned some up in the background
  137. self.assertGreater(Dealloc.DESTROYED_BG, 0)
  138. # Make sure all the cleanups happened.
  139. self.assertIs(Dealloc.SPAWNED, main)
  140. self.assertTrue(Dealloc.BG_RAN)
  141. self.assertEqual(Dealloc.BG_RAN, greenlet.GreenletExit)
  142. self.assertEqual(Dealloc.CREATED, Dealloc.DESTROYED )
  143. self.assertEqual(Dealloc.CREATED, OBJECTS_PER_CONTAINER * 2)
  144. import gc
  145. gc.collect()
  146. if __name__ == '__main__':
  147. unittest.main()