Debian Codegraph @

pypy/doc/stackless.rst

raw
1 Application-level Stackless features
2 ====================================
3
4 Introduction
5 ------------
6
7 PyPy can expose to its user language features similar to the ones
8 present in `Stackless Python`_: the ability to write code in a
9 **massively concurrent style**. (It does not (any more) offer the
10 ability to run with no `recursion depth limit`_, but the same effect
11 can be achieved indirectly.)
12
13 This feature is based on a custom primitive called a continulet_.
14 Continulets can be directly used by application code, or it is possible
15 to write (entirely at app-level) more user-friendly interfaces.
16
17 Currently PyPy implements greenlets_ on top of continulets. It also
18 implements (an approximation of) tasklets and channels, emulating the model
19 of `Stackless Python`_.
20
21 Continulets are extremely light-weight, which means that PyPy should be
22 able to handle programs containing large amounts of them. However, due
23 to an implementation restriction, a PyPy compiled with
24 ``--gcrootfinder=shadowstack`` consumes at least one page of physical
25 memory (4KB) per live continulet, and half a megabyte of virtual memory
26 on 32-bit or a complete megabyte on 64-bit. Moreover, the feature is
27 only available (so far) on x86 and x86-64 CPUs; for other CPUs you need
28 to add a short page of custom assembler to
29 :source:`rpython/translator/c/src/stacklet/`.
30
31 .. _Stackless Python: https://www.stackless.com
32
33
34 Theory
35 ------
36
37 The fundamental idea is that, at any point in time, the program happens
38 to run one stack of frames (or one per thread, in case of
39 multi-threading). To see the stack, start at the top frame and follow
40 the chain of ``f_back`` until you reach the bottom frame. From the
41 point of view of one of these frames, it has a ``f_back`` pointing to
42 another frame (unless it is the bottom frame), and it is itself being
43 pointed to by another frame (unless it is the top frame).
44
45 The theory behind continulets is to literally take the previous sentence
46 as definition of "an O.K. situation". The trick is that there are
47 O.K. situations that are more complex than just one stack: you will
48 always have one stack, but you can also have in addition one or more
49 detached *cycles* of frames, such that by following the ``f_back`` chain
50 you run in a circle. But note that these cycles are indeed completely
51 detached: the top frame (the currently running one) is always the one
52 which is not the ``f_back`` of anybody else, and it is always the top of
53 a stack that ends with the bottom frame, never a part of these extra
54 cycles.
55
56 How do you create such cycles? The fundamental operation to do so is to
57 take two frames and *permute* their ``f_back`` --- i.e. exchange them.
58 You can permute any two ``f_back`` without breaking the rule of "an O.K.
59 situation". Say for example that ``f`` is some frame halfway down the
60 stack, and you permute its ``f_back`` with the ``f_back`` of the top
61 frame. Then you have removed from the normal stack all intermediate
62 frames, and turned them into one stand-alone cycle. By doing the same
63 permutation again you restore the original situation.
64
65 In practice, in PyPy, you cannot change the ``f_back`` of an arbitrary
66 frame, but only of frames stored in ``continulets``.
67
68 Continulets are internally implemented using stacklets_. Stacklets are a
69 bit more primitive (they are really one-shot continuations), but that
70 idea only works in C, not in Python. The basic idea of continulets is
71 to have at any point in time a complete valid stack; this is important
72 e.g. to correctly propagate exceptions (and it seems to give meaningful
73 tracebacks too).
74
75
76 Application level interface
77 ---------------------------
78
79 .. _continulet:
80
81 Continulets
82 ~~~~~~~~~~~
83
84 A translated PyPy contains by default a module called ``_continuation``
85 exporting the type ``continulet``. A ``continulet`` object from this
86 module is a container that stores a "one-shot continuation". It plays
87 the role of an extra frame you can insert in the stack, and whose
88 ``f_back`` can be changed.
89
90 To make a continulet object, call ``continulet()`` with a callable and
91 optional extra arguments.
92
93 Later, the first time you ``switch()`` to the continulet, the callable
94 is invoked with the same continulet object as the extra first argument.
95 At that point, the one-shot continuation stored in the continulet points
96 to the caller of ``switch()``. In other words you have a perfectly
97 normal-looking stack of frames. But when ``switch()`` is called again,
98 this stored one-shot continuation is exchanged with the current one; it
99 means that the caller of ``switch()`` is suspended with its continuation
100 stored in the container, and the old continuation from the continulet
101 object is resumed.
102
103 The most primitive API is actually 'permute()', which just permutes the
104 one-shot continuation stored in two (or more) continulets.
105
106 In more details:
107
108 * ``continulet(callable, *args, **kwds)``: make a new continulet.
109 Like a generator, this only creates it; the ``callable`` is only
110 actually called the first time it is switched to. It will be
111 called as follows::
112
113 callable(cont, *args, **kwds)
114
115 where ``cont`` is the same continulet object.
116
117 Note that it is actually ``cont.__init__()`` that binds
118 the continulet. It is also possible to create a not-bound-yet
119 continulet by calling explicitly ``continulet.__new__()``, and
120 only bind it later by calling explicitly ``cont.__init__()``.
121
122 * ``cont.switch(value=None, to=None)``: start the continulet if
123 it was not started yet. Otherwise, store the current continuation
124 in ``cont``, and activate the target continuation, which is the
125 one that was previously stored in ``cont``. Note that the target
126 continuation was itself previously suspended by another call to
127 ``switch()``; this older ``switch()`` will now appear to return.
128 The ``value`` argument is any object that is carried to the target
129 and returned by the target's ``switch()``.
130
131 If ``to`` is given, it must be another continulet object. In
132 that case, performs a "double switch": it switches as described
133 above to ``cont``, and then immediately switches again to ``to``.
134 This is different from switching directly to ``to``: the current
135 continuation gets stored in ``cont``, the old continuation from
136 ``cont`` gets stored in ``to``, and only then we resume the
137 execution from the old continuation out of ``to``.
138
139 * ``cont.throw(type, value=None, tb=None, to=None)``: similar to
140 ``switch()``, except that immediately after the switch is done, raise
141 the given exception in the target.
142
143 * ``cont.is_pending()``: return True if the continulet is pending.
144 This is False when it is not initialized (because we called
145 ``__new__`` and not ``__init__``) or when it is finished (because
146 the ``callable()`` returned). When it is False, the continulet
147 object is empty and cannot be ``switch()``-ed to.
148
149 * ``permute(*continulets)``: a global function that permutes the
150 continuations stored in the given continulets arguments. Mostly
151 theoretical. In practice, using ``cont.switch()`` is easier and
152 more efficient than using ``permute()``; the latter does not on
153 its own change the currently running frame.
154
155
156 Genlets
157 ~~~~~~~
158
159 The ``_continuation`` module also exposes the ``generator`` decorator::
160
161 @generator
162 def f(cont, a, b):
163 cont.switch(a + b)
164 cont.switch(a + b + 1)
165
166 for i in f(10, 20):
167 print i
168
169 This example prints 30 and 31. The only advantage over using regular
170 generators is that the generator itself is not limited to ``yield``
171 statements that must all occur syntactically in the same function.
172 Instead, we can pass around ``cont``, e.g. to nested sub-functions, and
173 call ``cont.switch(x)`` from there.
174
175 The ``generator`` decorator can also be applied to methods::
176
177 class X:
178 @generator
179 def f(self, cont, a, b):
180 ...
181
182
183 Greenlets
184 ~~~~~~~~~
185
186 Greenlets are implemented on top of continulets in :source:`lib_pypy/greenlet.py`.
187 See the official `documentation of the greenlets`_.
188
189 Note that unlike the CPython greenlets, this version does not suffer
190 from GC issues: if the program "forgets" an unfinished greenlet, it will
191 always be collected at the next garbage collection.
192
193 .. _documentation of the greenlets: https://greenlet.readthedocs.io/
194
195
196 Unimplemented features
197 ~~~~~~~~~~~~~~~~~~~~~~
198
199 The following features (present in some past Stackless version of PyPy)
200 are for the time being not supported any more:
201
202 * Coroutines (could be rewritten at app-level)
203
204 * Continuing execution of a continulet in a different thread
205 (but if it is "simple enough", you can pickle it and unpickle it
206 in the other thread).
207
208 * Automatic unlimited stack (must be emulated__ so far)
209
210 * Support for other CPUs than x86 and x86-64
211
212 .. __: `recursion depth limit`_
213
214 We also do not include any of the recent API additions to Stackless
215 Python, like ``set_atomic()``. Contributions welcome.
216
217
218 Recursion depth limit
219 ~~~~~~~~~~~~~~~~~~~~~
220
221 You can use continulets to emulate the infinite recursion depth present
222 in Stackless Python and in stackless-enabled older versions of PyPy.
223
224 The trick is to start a continulet "early", i.e. when the recursion
225 depth is very low, and switch to it "later", i.e. when the recursion
226 depth is high. Example::
227
228 from _continuation import continulet
229
230 def invoke(_, callable, arg):
231 return callable(arg)
232
233 def bootstrap(c):
234 # this loop runs forever, at a very low recursion depth
235 callable, arg = c.switch()
236 while True:
237 # start a new continulet from here, and switch to
238 # it using an "exchange", i.e. a switch with to=.
239 to = continulet(invoke, callable, arg)
240 callable, arg = c.switch(to=to)
241
242 c = continulet(bootstrap)
243 c.switch()
244
245
246 def recursive(n):
247 if n == 0:
248 return ("ok", n)
249 if n % 200 == 0:
250 prev = c.switch((recursive, n - 1))
251 else:
252 prev = recursive(n - 1)
253 return (prev[0], prev[1] + 1)
254
255 print recursive(999999) # prints ('ok', 999999)
256
257 Note that if you press Ctrl-C while running this example, the traceback
258 will be built with *all* recursive() calls so far, even if this is more
259 than the number that can possibly fit in the C stack. These frames are
260 "overlapping" each other in the sense of the C stack; more precisely,
261 they are copied out of and into the C stack as needed.
262
263 (The example above also makes use of the following general "guideline"
264 to help newcomers write continulets: in ``bootstrap(c)``, only call
265 methods on ``c``, not on another continulet object. That's why we wrote
266 ``c.switch(to=to)`` and not ``to.switch()``, which would mess up the
267 state. This is however just a guideline; in general we would recommend
268 to use other interfaces like genlets and greenlets.)
269
270
271 Stacklets
272 ~~~~~~~~~
273
274 Continulets are internally implemented using stacklets, which is the
275 generic RPython-level building block for "one-shot continuations". For
276 more information about them please see the documentation in the C source
277 at :source:`rpython/translator/c/src/stacklet/stacklet.h`.
278
279 The module ``rpython.rlib.rstacklet`` is a thin wrapper around the above
280 functions. The key point is that new() and switch() always return a
281 fresh stacklet handle (or an empty one), and switch() additionally
282 consumes one. It makes no sense to have code in which the returned
283 handle is ignored, or used more than once. Note that ``stacklet.c`` is
284 written assuming that the user knows that, and so no additional checking
285 occurs; this can easily lead to obscure crashes if you don't use a
286 wrapper like PyPy's '_continuation' module.
287
288
289 Theory of composability
290 ~~~~~~~~~~~~~~~~~~~~~~~
291
292 Although the concept of coroutines is far from new, they have not been
293 generally integrated into mainstream languages, or only in limited form
294 (like generators in Python and iterators in C#). We can argue that a
295 possible reason for that is that they do not scale well when a program's
296 complexity increases: they look attractive in small examples, but the
297 models that require explicit switching, for example by naming the target
298 coroutine, do not compose naturally. This means that a program that
299 uses coroutines for two unrelated purposes may run into conflicts caused
300 by unexpected interactions.
301
302 To illustrate the problem, consider the following example (simplified
303 code using a theoretical ``coroutine`` class). First, a simple usage of
304 coroutine::
305
306 main_coro = coroutine.getcurrent() # the main (outer) coroutine
307 data = []
308
309 def data_producer():
310 for i in range(10):
311 # add some numbers to the list 'data' ...
312 data.append(i)
313 data.append(i * 5)
314 data.append(i * 25)
315 # and then switch back to main to continue processing
316 main_coro.switch()
317
318 producer_coro = coroutine()
319 producer_coro.bind(data_producer)
320
321 def grab_next_value():
322 if not data:
323 # put some more numbers in the 'data' list if needed
324 producer_coro.switch()
325 # then grab the next value from the list
326 return data.pop(0)
327
328 Every call to grab_next_value() returns a single value, but if necessary
329 it switches into the producer function (and back) to give it a chance to
330 put some more numbers in it.
331
332 Now consider a simple reimplementation of Python's generators in term of
333 coroutines::
334
335 def generator(f):
336 """Wrap a function 'f' so that it behaves like a generator."""
337 def wrappedfunc(*args, **kwds):
338 g = generator_iterator()
339 g.bind(f, *args, **kwds)
340 return g
341 return wrappedfunc
342
343 class generator_iterator(coroutine):
344 def __iter__(self):
345 return self
346 def next(self):
347 self.caller = coroutine.getcurrent()
348 self.switch()
349 return self.answer
350
351 def Yield(value):
352 """Yield the value from the current generator."""
353 g = coroutine.getcurrent()
354 g.answer = value
355 g.caller.switch()
356
357 def squares(n):
358 """Demo generator, producing square numbers."""
359 for i in range(n):
360 Yield(i * i)
361 squares = generator(squares)
362
363 for x in squares(5):
364 print x # this prints 0, 1, 4, 9, 16
365
366 Both these examples are attractively elegant. However, they cannot be
367 composed. If we try to write the following generator::
368
369 def grab_values(n):
370 for i in range(n):
371 Yield(grab_next_value())
372 grab_values = generator(grab_values)
373
374 then the program does not behave as expected. The reason is the
375 following. The generator coroutine that executes ``grab_values()``
376 calls ``grab_next_value()``, which may switch to the ``producer_coro``
377 coroutine. This works so far, but the switching back from
378 ``data_producer()`` to ``main_coro`` lands in the wrong coroutine: it
379 resumes execution in the main coroutine, which is not the one from which
380 it comes. We expect ``data_producer()`` to switch back to the
381 ``grab_next_values()`` call, but the latter lives in the generator
382 coroutine ``g`` created in ``wrappedfunc``, which is totally unknown to
383 the ``data_producer()`` code. Instead, we really switch back to the
384 main coroutine, which confuses the ``generator_iterator.next()`` method
385 (it gets resumed, but not as a result of a call to ``Yield()``).
386
387 Thus the notion of coroutine is *not composable*. By opposition, the
388 primitive notion of continulets is composable: if you build two
389 different interfaces on top of it, or have a program that uses twice the
390 same interface in two parts, then assuming that both parts independently
391 work, the composition of the two parts still works.
392
393 A full proof of that claim would require careful definitions, but let us
394 just claim that this fact is true because of the following observation:
395 the API of continulets is such that, when doing a ``switch()``, it
396 requires the program to have some continulet to explicitly operate on.
397 It shuffles the current continuation with the continuation stored in
398 that continulet, but has no effect outside. So if a part of a program
399 has a continulet object, and does not expose it as a global, then the
400 rest of the program cannot accidentally influence the continuation
401 stored in that continulet object.
402
403 In other words, if we regard the continulet object as being essentially
404 a modifiable ``f_back``, then it is just a link between the frame of
405 ``callable()`` and the parent frame --- and it cannot be arbitrarily
406 changed by unrelated code, as long as they don't explicitly manipulate
407 the continulet object. Typically, both the frame of ``callable()``
408 (commonly a local function) and its parent frame (which is the frame
409 that switched to it) belong to the same class or module; so from that
410 point of view the continulet is a purely local link between two local
411 frames. It doesn't make sense to have a concept that allows this link
412 to be manipulated from outside.