You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

219 lines
11 KiB

  1. Intro
  2. =====
  3. The basic rule for dealing with weakref callbacks (and __del__ methods too,
  4. for that matter) during cyclic gc:
  5. Once gc has computed the set of unreachable objects, no Python-level
  6. code can be allowed to access an unreachable object.
  7. If that can happen, then the Python code can resurrect unreachable objects
  8. too, and gc can't detect that without starting over. Since gc eventually
  9. runs tp_clear on all unreachable objects, if an unreachable object is
  10. resurrected then tp_clear will eventually be called on it (or may already
  11. have been called before resurrection). At best (and this has been an
  12. historically common bug), tp_clear empties an instance's __dict__, and
  13. "impossible" AttributeErrors result. At worst, tp_clear leaves behind an
  14. insane object at the C level, and segfaults result (historically, most
  15. often by setting a new-style class's mro pointer to NULL, after which
  16. attribute lookups performed by the class can segfault).
  17. OTOH, it's OK to run Python-level code that can't access unreachable
  18. objects, and sometimes that's necessary. The chief example is the callback
  19. attached to a reachable weakref W to an unreachable object O. Since O is
  20. going away, and W is still alive, the callback must be invoked. Because W
  21. is still alive, everything reachable from its callback is also reachable,
  22. so it's also safe to invoke the callback (although that's trickier than it
  23. sounds, since other reachable weakrefs to other unreachable objects may
  24. still exist, and be accessible to the callback -- there are lots of painful
  25. details like this covered in the rest of this file).
  26. Python 2.4/2.3.5
  27. ================
  28. The "Before 2.3.3" section below turned out to be wrong in some ways, but
  29. I'm leaving it as-is because it's more right than wrong, and serves as a
  30. wonderful example of how painful analysis can miss not only the forest for
  31. the trees, but also miss the trees for the aphids sucking the trees
  32. dry <wink>.
  33. The primary thing it missed is that when a weakref to a piece of cyclic
  34. trash (CT) exists, then any call to any Python code whatsoever can end up
  35. materializing a strong reference to that weakref's CT referent, and so
  36. possibly resurrect an insane object (one for which cyclic gc has called-- or
  37. will call before it's done --tp_clear()). It's not even necessarily that a
  38. weakref callback or __del__ method does something nasty on purpose: as
  39. soon as we execute Python code, threads other than the gc thread can run
  40. too, and they can do ordinary things with weakrefs that end up resurrecting
  41. CT while gc is running.
  42. http://www.python.org/sf/1055820
  43. shows how innocent it can be, and also how nasty. Variants of the three
  44. focussed test cases attached to that bug report are now part of Python's
  45. standard Lib/test/test_gc.py.
  46. Jim Fulton gave the best nutshell summary of the new (in 2.4 and 2.3.5)
  47. approach:
  48. Clearing cyclic trash can call Python code. If there are weakrefs to
  49. any of the cyclic trash, then those weakrefs can be used to resurrect
  50. the objects. Therefore, *before* clearing cyclic trash, we need to
  51. remove any weakrefs. If any of the weakrefs being removed have
  52. callbacks, then we need to save the callbacks and call them *after* all
  53. of the weakrefs have been cleared.
  54. Alas, doing just that much doesn't work, because it overlooks what turned
  55. out to be the much subtler problems that were fixed earlier, and described
  56. below. We do clear all weakrefs to CT now before breaking cycles, but not
  57. all callbacks encountered can be run later. That's explained in horrid
  58. detail below.
  59. Older text follows, with a some later comments in [] brackets:
  60. Before 2.3.3
  61. ============
  62. Before 2.3.3, Python's cyclic gc didn't pay any attention to weakrefs.
  63. Segfaults in Zope3 resulted.
  64. weakrefs in Python are designed to, at worst, let *other* objects learn
  65. that a given object has died, via a callback function. The weakly
  66. referenced object itself is not passed to the callback, and the presumption
  67. is that the weakly referenced object is unreachable trash at the time the
  68. callback is invoked.
  69. That's usually true, but not always. Suppose a weakly referenced object
  70. becomes part of a clump of cyclic trash. When enough cycles are broken by
  71. cyclic gc that the object is reclaimed, the callback is invoked. If it's
  72. possible for the callback to get at objects in the cycle(s), then it may be
  73. possible for those objects to access (via strong references in the cycle)
  74. the weakly referenced object being torn down, or other objects in the cycle
  75. that have already suffered a tp_clear() call. There's no guarantee that an
  76. object is in a sane state after tp_clear(). Bad things (including
  77. segfaults) can happen right then, during the callback's execution, or can
  78. happen at any later time if the callback manages to resurrect an insane
  79. object.
  80. [That missed that, in addition, a weakref to CT can exist outside CT, and
  81. any callback into Python can use such a non-CT weakref to resurrect its CT
  82. referent. The same bad kinds of things can happen then.]
  83. Note that if it's possible for the callback to get at objects in the trash
  84. cycles, it must also be the case that the callback itself is part of the
  85. trash cycles. Else the callback would have acted as an external root to
  86. the current collection, and nothing reachable from it would be in cyclic
  87. trash either.
  88. [Except that a non-CT callback can also use a non-CT weakref to get at
  89. CT objects.]
  90. More, if the callback itself is in cyclic trash, then the weakref to which
  91. the callback is attached must also be trash, and for the same kind of
  92. reason: if the weakref acted as an external root, then the callback could
  93. not have been cyclic trash.
  94. So a problem here requires that a weakref, that weakref's callback, and the
  95. weakly referenced object, all be in cyclic trash at the same time. This
  96. isn't easy to stumble into by accident while Python is running, and, indeed,
  97. it took quite a while to dream up failing test cases. Zope3 saw segfaults
  98. during shutdown, during the second call of gc in Py_Finalize, after most
  99. modules had been torn down. That creates many trash cycles (esp. those
  100. involving new-style classes), making the problem much more likely. Once you
  101. know what's required to provoke the problem, though, it's easy to create
  102. tests that segfault before shutdown.
  103. In 2.3.3, before breaking cycles, we first clear all the weakrefs with
  104. callbacks in cyclic trash. Since the weakrefs *are* trash, and there's no
  105. defined-- or even predictable --order in which tp_clear() gets called on
  106. cyclic trash, it's defensible to first clear weakrefs with callbacks. It's
  107. a feature of Python's weakrefs too that when a weakref goes away, the
  108. callback (if any) associated with it is thrown away too, unexecuted.
  109. [In 2.4/2.3.5, we first clear all weakrefs to CT objects, whether or not
  110. those weakrefs are themselves CT, and whether or not they have callbacks.
  111. The callbacks (if any) on non-CT weakrefs (if any) are invoked later,
  112. after all weakrefs-to-CT have been cleared. The callbacks (if any) on CT
  113. weakrefs (if any) are never invoked, for the excruciating reasons
  114. explained here.]
  115. Just that much is almost enough to prevent problems, by throwing away
  116. *almost* all the weakref callbacks that could get triggered by gc. The
  117. problem remaining is that clearing a weakref with a callback decrefs the
  118. callback object, and the callback object may *itself* be weakly referenced,
  119. via another weakref with another callback. So the process of clearing
  120. weakrefs can trigger callbacks attached to other weakrefs, and those
  121. latter weakrefs may or may not be part of cyclic trash.
  122. So, to prevent any Python code from running while gc is invoking tp_clear()
  123. on all the objects in cyclic trash,
  124. [That was always wrong: we can't stop Python code from running when gc
  125. is breaking cycles. If an object with a __del__ method is not itself in
  126. a cycle, but is reachable only from CT, then breaking cycles will, as a
  127. matter of course, drop the refcount on that object to 0, and its __del__
  128. will run right then. What we can and must stop is running any Python
  129. code that could access CT.]
  130. it's not quite enough just to invoke
  131. tp_clear() on weakrefs with callbacks first. Instead the weakref module
  132. grew a new private function (_PyWeakref_ClearRef) that does only part of
  133. tp_clear(): it removes the weakref from the weakly-referenced object's list
  134. of weakrefs, but does not decref the callback object. So calling
  135. _PyWeakref_ClearRef(wr) ensures that wr's callback object will never
  136. trigger, and (unlike weakref's tp_clear()) also prevents any callback
  137. associated *with* wr's callback object from triggering.
  138. [Although we may trigger such callbacks later, as explained below.]
  139. Then we can call tp_clear on all the cyclic objects and never trigger
  140. Python code.
  141. [As above, not so: it means never trigger Python code that can access CT.]
  142. After we do that, the callback objects still need to be decref'ed. Callbacks
  143. (if any) *on* the callback objects that were also part of cyclic trash won't
  144. get invoked, because we cleared all trash weakrefs with callbacks at the
  145. start. Callbacks on the callback objects that were not part of cyclic trash
  146. acted as external roots to everything reachable from them, so nothing
  147. reachable from them was part of cyclic trash, so gc didn't do any damage to
  148. objects reachable from them, and it's safe to call them at the end of gc.
  149. [That's so. In addition, now we also invoke (if any) the callbacks on
  150. non-CT weakrefs to CT objects, during the same pass that decrefs the
  151. callback objects.]
  152. An alternative would have been to treat objects with callbacks like objects
  153. with __del__ methods, refusing to collect them, appending them to gc.garbage
  154. instead. That would have been much easier. Jim Fulton gave a strong
  155. argument against that (on Python-Dev):
  156. There's a big difference between __del__ and weakref callbacks.
  157. The __del__ method is "internal" to a design. When you design a
  158. class with a del method, you know you have to avoid including the
  159. class in cycles.
  160. Now, suppose you have a design that makes has no __del__ methods but
  161. that does use cyclic data structures. You reason about the design,
  162. run tests, and convince yourself you don't have a leak.
  163. Now, suppose some external code creates a weakref to one of your
  164. objects. All of a sudden, you start leaking. You can look at your
  165. code all you want and you won't find a reason for the leak.
  166. IOW, a class designer can out-think __del__ problems, but has no control
  167. over who creates weakrefs to his classes or class instances. The class
  168. user has little chance either of predicting when the weakrefs he creates
  169. may end up in cycles.
  170. Callbacks on weakref callbacks are executed in an arbitrary order, and
  171. that's not good (a primary reason not to collect cycles with objects with
  172. __del__ methods is to avoid running finalizers in an arbitrary order).
  173. However, a weakref callback on a weakref callback has got to be rare.
  174. It's possible to do such a thing, so gc has to be robust against it, but
  175. I doubt anyone has done it outside the test case I wrote for it.
  176. [The callbacks (if any) on non-CT weakrefs to CT objects are also executed
  177. in an arbitrary order now. But they were before too, depending on the
  178. vagaries of when tp_clear() happened to break enough cycles to trigger
  179. them. People simply shouldn't try to use __del__ or weakref callbacks to
  180. do fancy stuff.]