Debian Codegraph @

pypy/doc/discussion/finalizer-order.rst

raw
1 Ordering finalizers in the MiniMark GC
2 ======================================
3
4
5 RPython interface
6 -----------------
7
8 In RPython programs like PyPy, we need a fine-grained method of
9 controlling the RPython- as well as the app-level ``__del__()``. To
10 make it possible, the RPython interface is now the following one (from
11 May 2016):
12
13 * RPython objects can have ``__del__()``. These are called
14 immediately by the GC when the last reference to the object goes
15 away, like in CPython. However, the long-term goal is that all
16 ``__del__()`` methods should only contain simple enough code. If
17 they do, we call them "destructors". They can't use operations that
18 would resurrect the object, for example. Use the decorator
19 ``@rgc.must_be_light_finalizer`` to ensure they are destructors.
20
21 * RPython-level ``__del__()`` that are not passing the destructor test
22 are supported for backward compatibility, but deprecated. The rest
23 of this document assumes that ``__del__()`` are all destructors.
24
25 * For any more advanced usage --- in particular for any app-level
26 object with a __del__ --- we don't use the RPython-level
27 ``__del__()`` method. Instead we use
28 ``rgc.FinalizerController.register_finalizer()``. This allows us to
29 attach a finalizer method to the object, giving more control over
30 the ordering than just an RPython ``__del__()``.
31
32 We try to consistently call ``__del__()`` a destructor, to distinguish
33 it from a finalizer. A finalizer runs earlier, and in topological
34 order; care must be taken that the object might still be reachable at
35 this point if we're clever enough. A destructor on the other hand runs
36 last; nothing can be done with the object any more, and the GC frees it
37 immediately.
38
39
40 Destructors
41 -----------
42
43 A destructor is an RPython ``__del__()`` method that is called directly
44 by the GC when it is about to free the memory. Intended for objects
45 that just need to free an extra block of raw memory.
46
47 There are restrictions on the kind of code you can put in ``__del__()``,
48 including all other functions called by it. These restrictions are
49 checked. In particular you cannot access fields containing GC objects.
50 Right now you can't call any external C function either.
51
52 Destructors are called precisely when the GC frees the memory of the
53 object. As long as the object exists (even in some finalizer queue or
54 anywhere), its destructor is not called.
55
56
57 Register_finalizer
58 ------------------
59
60 The interface for full finalizers is made with PyPy in mind, but should
61 be generally useful.
62
63 The idea is that you subclass the ``rgc.FinalizerQueue`` class:
64
65 * You must give a class-level attribute ``base_class``, which is the
66 base class of all instances with a finalizer. (If you need
67 finalizers on several unrelated classes, you need several unrelated
68 ``FinalizerQueue`` subclasses.)
69
70 * You override the ``finalizer_trigger()`` method; see below.
71
72 Then you create one global (or space-specific) instance of this
73 subclass; call it ``fin``. At runtime, you call
74 ``fin.register_finalizer(obj)`` for every instance ``obj`` that needs
75 a finalizer. Each ``obj`` must be an instance of ``fin.base_class``,
76 but not every such instance needs to have a finalizer registered;
77 typically we try to register a finalizer on as few objects as possible
78 (e.g. only if it is an object which has an app-level ``__del__()``
79 method).
80
81 After a major collection, the GC finds all objects ``obj`` on which a
82 finalizer was registered and which are unreachable, and mark them as
83 reachable again, as well as all objects they depend on. It then picks
84 a topological ordering (breaking cycles randomly, if any) and enqueues
85 the objects and their registered finalizer functions in that order, in
86 a queue specific to the prebuilt ``fin`` instance. Finally, when the
87 major collection is done, it calls ``fin.finalizer_trigger()``.
88
89 This method ``finalizer_trigger()`` can either do some work directly,
90 or delay it to be done later (e.g. between two bytecodes). If it does
91 work directly, note that it cannot (directly or indirectly) cause the
92 GIL to be released.
93
94 To find the queued items, call ``fin.next_dead()`` repeatedly. It
95 returns the next queued item, or ``None`` when the queue is empty.
96
97 In theory, it would kind of work if you cumulate several different
98 ``FinalizerQueue`` instances for objects of the same class, and
99 (always in theory) the same ``obj`` could be registered several times
100 in the same queue, or in several queues. This is not tested though.
101 For now the untranslated emulation does not support registering the
102 same object several times.
103
104 Note that the Boehm garbage collector, used in ``rpython -O0``,
105 completely ignores ``register_finalizer()``.
106
107
108 Ordering of finalizers
109 ----------------------
110
111 After a collection, the MiniMark GC should call the finalizers on
112 *some* of the objects that have one and that have become unreachable.
113 Basically, if there is a reference chain from an object a to an object b
114 then it should not call the finalizer for b immediately, but just keep b
115 alive and try again to call its finalizer after the next collection.
116
117 (Note that this creates rare but annoying issues as soon as the program
118 creates chains of objects with finalizers more quickly than the rate at
119 which major collections go (which is very slow). In August 2013 we tried
120 instead to call all finalizers of all objects found unreachable at a major
121 collection. That branch, ``gc-del``, was never merged. It is still
122 unclear what the real consequences would be on programs in the wild.)
123
124 The basic idea fails in the presence of cycles. It's not a good idea to
125 keep the objects alive forever or to never call any of the finalizers.
126 The model we came up with is that in this case, we could just call the
127 finalizer of one of the objects in the cycle -- but only, of course, if
128 there are no other objects outside the cycle that has a finalizer and a
129 reference to the cycle.
130
131 More precisely, given the graph of references between objects::
132
133 for each strongly connected component C of the graph:
134 if C has at least one object with a finalizer:
135 if there is no object outside C which has a finalizer and
136 indirectly references the objects in C:
137 mark one of the objects of C that has a finalizer
138 copy C and all objects it references to the new space
139
140 for each marked object:
141 detach the finalizer (so that it's not called more than once)
142 call the finalizer
143
144
145 Algorithm
146 ---------
147
148 During deal_with_objects_with_finalizers(), each object x can be in 4
149 possible states::
150
151 state[x] == 0: unreachable
152 state[x] == 1: (temporary state, see below)
153 state[x] == 2: reachable from any finalizer
154 state[x] == 3: alive
155
156 Initially, objects are in state 0 or 3 depending on whether they have
157 been copied or not by the regular sweep done just before. The invariant
158 is that if there is a reference from x to y, then state[y] >= state[x].
159
160 The state 2 is used for objects that are reachable from a finalizer but
161 that may be in the same strongly connected component than the finalizer.
162 The state of these objects goes to 3 when we prove that they can be
163 reached from a finalizer which is definitely not in the same strongly
164 connected component. Finalizers on objects with state 3 must not be
165 called.
166
167 Let closure(x) be the list of objects reachable from x, including x
168 itself. Pseudo-code (high-level) to get the list of marked objects::
169
170 marked = []
171 for x in objects_with_finalizers:
172 if state[x] != 0:
173 continue
174 marked.append(x)
175 for y in closure(x):
176 if state[y] == 0:
177 state[y] = 2
178 elif state[y] == 2:
179 state[y] = 3
180 for x in marked:
181 assert state[x] >= 2
182 if state[x] != 2:
183 marked.remove(x)
184
185 This does the right thing independently on the order in which the
186 objects_with_finalizers are enumerated. First assume that [x1, .., xn]
187 are all in the same unreachable strongly connected component; no object
188 with finalizer references this strongly connected component from
189 outside. Then:
190
191 * when x1 is processed, state[x1] == .. == state[xn] == 0 independently
192 of whatever else we did before. So x1 gets marked and we set
193 state[x1] = .. = state[xn] = 2.
194
195 * when x2, ... xn are processed, their state is != 0 so we do nothing.
196
197 * in the final loop, only x1 is marked and state[x1] == 2 so it stays
198 marked.
199
200 Now, let's assume that x1 and x2 are not in the same strongly connected
201 component and there is a reference path from x1 to x2. Then:
202
203 * if x1 is enumerated before x2, then x2 is in closure(x1) and so its
204 state gets at least >= 2 when we process x1. When we process x2 later
205 we just skip it ("continue" line) and so it doesn't get marked.
206
207 * if x2 is enumerated before x1, then when we process x2 we mark it and
208 set its state to >= 2 (before x2 is in closure(x2)), and then when we
209 process x1 we set state[x2] == 3. So in the final loop x2 gets
210 removed from the "marked" list.
211
212 I think that it proves that the algorithm is doing what we want.
213
214 The next step is to remove the use of closure() in the algorithm in such
215 a way that the new algorithm has a reasonable performance -- linear in
216 the number of objects whose state it manipulates::
217
218 marked = []
219 for x in objects_with_finalizers:
220 if state[x] != 0:
221 continue
222 marked.append(x)
223 recursing on the objects y starting from x:
224 if state[y] == 0:
225 state[y] = 1
226 follow y's children recursively
227 elif state[y] == 2:
228 state[y] = 3
229 follow y's children recursively
230 else:
231 don't need to recurse inside y
232 recursing on the objects y starting from x:
233 if state[y] == 1:
234 state[y] = 2
235 follow y's children recursively
236 else:
237 don't need to recurse inside y
238 for x in marked:
239 assert state[x] >= 2
240 if state[x] != 2:
241 marked.remove(x)
242
243 In this algorithm we follow the children of each object at most 3 times,
244 when the state of the object changes from 0 to 1 to 2 to 3. In a visit
245 that doesn't change the state of an object, we don't follow its children
246 recursively.
247
248 In practice, in the MiniMark GCs, we can encode
249 the 4 states with a combination of two bits in the header:
250
251 ===== ============== ============================
252 state GCFLAG_VISITED GCFLAG_FINALIZATION_ORDERING
253 ===== ============== ============================
254 0 no no
255 1 no yes
256 2 yes yes
257 3 yes no
258 ===== ============== ============================
259
260 So the loop above that does the transition from state 1 to state 2 is
261 really just a recursive visit. We must also clear the
262 FINALIZATION_ORDERING bit at the end (state 2 to state 3) to clean up
263 before the next collection.