| 1 |
.. XXX think more, some of this might be useful |
| 2 |
|
| 3 |
Designing thread pickling or "the Essence of Stackless Python" |
| 4 |
-------------------------------------------------------------- |
| 5 |
|
| 6 |
Note from 2007-07-22: This document is slightly out of date |
| 7 |
and should be turned into a description of pickling. |
| 8 |
Some research is necessary to get rid of explicit resume points, etc... |
| 9 |
|
| 10 |
Thread pickling is a unique feature in Stackless Python |
| 11 |
and should be implemented for PyPy pretty soon. |
| 12 |
|
| 13 |
What is meant by pickling? |
| 14 |
.......................... |
| 15 |
|
| 16 |
I'd like to define thread pickling as a restartable subset |
| 17 |
of a running program. The re-runnable part should be based |
| 18 |
upon Python frame chains, represented by coroutines, tasklets |
| 19 |
or any other application level switchable subcontext. |
| 20 |
It is surely possible to support pickling of arbitrary |
| 21 |
interplevel state, but this seems to be not mandatory as long |
| 22 |
as we consider Stackless as the reference implementation. |
| 23 |
Extensions of this might be considered when the basic task |
| 24 |
is fulfilled. |
| 25 |
|
| 26 |
Pickling should create a re-startable coroutine-alike thing |
| 27 |
that can run on a different machine, same Python version, |
| 28 |
but not necessarily the same PyPy translation. This belongs |
| 29 |
to the harder parts. |
| 30 |
|
| 31 |
What is not meant by pickling? |
| 32 |
.............................. |
| 33 |
|
| 34 |
Saving the whole memory state and writing a loader that |
| 35 |
reconstructs the whole binary with its state im memory |
| 36 |
is not what I consider a real solution. In some sense, |
| 37 |
this can be a fall-back if we fail in every other case, |
| 38 |
but I consider it really nasty for the C backend. |
| 39 |
|
| 40 |
If we had a dynamic backend that supports direct creation |
| 41 |
of the program and its state (example: a Forth backend), |
| 42 |
I would see it as a valid solution, since it is |
| 43 |
relocatable. It is of course a possible fall-back to write |
| 44 |
such a backend of we fail otherwise. |
| 45 |
|
| 46 |
There are some simple steps and some more difficult ones. |
| 47 |
Let's start with the simple. |
| 48 |
|
| 49 |
Basic necessities |
| 50 |
................. |
| 51 |
|
| 52 |
Pickling of a running thread involves a bit more than normal |
| 53 |
object pickling, because there exist many objects which |
| 54 |
don't have a pickling interface, and people would not care |
| 55 |
about pickling them at all. But with thread pickling, these |
| 56 |
objects simply exist as local variables and are needed |
| 57 |
to restore the current runtime environment, and the user |
| 58 |
should not have to know what goes into the pickle. |
| 59 |
|
| 60 |
Examples are |
| 61 |
|
| 62 |
- generators |
| 63 |
- frames |
| 64 |
- cells |
| 65 |
- iterators |
| 66 |
- tracebacks |
| 67 |
|
| 68 |
to name just a few. Fortunately most of these objects already have |
| 69 |
got a pickling implementation in Stackless Python, namely the |
| 70 |
prickelpit.c file. |
| 71 |
|
| 72 |
It should be simple and straightforward to redo these implementations. |
| 73 |
Nevertheless there is a complication. The most natural way to support |
| 74 |
pickling is providing a __getstate__/__setstate__ method pair. |
| 75 |
This is ok for extension types like coroutines/tasklets which we can |
| 76 |
control, but it should be avoided for existing types. |
| 77 |
|
| 78 |
Consider for instance frames. We would have to add a __getstate__ |
| 79 |
and a __setstate__ method, which is an interface change. Furthermore, |
| 80 |
we would need to support creation of frames by calling the |
| 81 |
frame type, which is not really intended. |
| 82 |
|
| 83 |
For other types with are already callable, things get more complicated |
| 84 |
because we need to make sure that creating new instances does |
| 85 |
not interfere with existing ways to call the type. |
| 86 |
|
| 87 |
Directly adding a pickling interface to existing types is quite |
| 88 |
likely to produce overlaps in the calling interface. This happened |
| 89 |
for instance, when the module type became callable, and the signature |
| 90 |
was different from what Stackless added before. |
| 91 |
|
| 92 |
For Stackless, |
| 93 |
I used the copyreg module, instead, and created special surrogate |
| 94 |
objects as placeholders, which replace the type of the object |
| 95 |
after unpickling with the right type pointer. For details, see |
| 96 |
the prickelpit.c file in the Stackless distribution. |
| 97 |
|
| 98 |
As a conclusion, pickling of tasklets is an addition to Stackless, |
| 99 |
but not meant to be an extension to Python. The need to support |
| 100 |
pickling of certain objects should not change the interface. |
| 101 |
It is better to decouple this and to use surrogate types for |
| 102 |
pickling which cannot collide with future additions to Python. |
| 103 |
|
| 104 |
The real problem |
| 105 |
................ |
| 106 |
|
| 107 |
There are currently some crucial differences between Stackless |
| 108 |
Python (SLP for now) and the PyPy Stackless support (PyPy for now) |
| 109 |
as far as it is grown. |
| 110 |
When CPython does a call to a Python function, there are several |
| 111 |
helper functions involved for adjusting parameters, unpacking |
| 112 |
methods and some more. SLP takes a hard time to remove all these |
| 113 |
C functions from the C stack before starting the Python interpreter |
| 114 |
for the function. This change of behavior is done manually for |
| 115 |
all the helper functions by figuring out, which variables are |
| 116 |
still needed after the call. It turns out that in most cases, |
| 117 |
it is possible to let all the helper functions finish their |
| 118 |
work and return form the function call before the interpreter |
| 119 |
is started at all. |
| 120 |
|
| 121 |
This is the major difference which needs to be tackled for PyPy. |
| 122 |
Whenever we run a Python function, quite a number of functions |
| 123 |
incarnate on the C stack, and they get *not* finished before |
| 124 |
running the new frame. In case of a coroutine switch, we just |
| 125 |
save the whole chain of activation records - c function |
| 126 |
entrypoints with the saved block variables. This is ok for |
| 127 |
coroutine switching, but in the sense of SLP, it is rather |
| 128 |
incomplete and not stackless at all. The stack still exists, |
| 129 |
we can unwind and rebuild it, but it is a problem. |
| 130 |
|
| 131 |
Why a problem? |
| 132 |
.............. |
| 133 |
|
| 134 |
In an ideal world, thread pickling would just be building |
| 135 |
chains of pickled frames and nothing else. For every different |
| 136 |
extra activation record like mentioned above, we have the |
| 137 |
problem of how to save this information. We need a representation |
| 138 |
which is not machine or compiler dependent. Right now, PyPy |
| 139 |
is quite unstable in terms of which blocks it will produce, |
| 140 |
what gets inlined, etc. The best solution possible is to try |
| 141 |
to get completely rid of these extra structures. |
| 142 |
|
| 143 |
Unfortunately this is not even possible with SLP, because |
| 144 |
there are different flavors of state which make it hard |
| 145 |
to go without extra information. |
| 146 |
|
| 147 |
SLP switching strategies |
| 148 |
........................ |
| 149 |
|
| 150 |
SLP has undergone several rewrites. The first implementation was aiming |
| 151 |
at complete collaboration. A new frame's execution was deferred until |
| 152 |
all the preparational C function calls had left the C stack. There |
| 153 |
was no extra state to be saved. |
| 154 |
|
| 155 |
Well, this is only partially true - there are a couple of situations |
| 156 |
where a recursive call could not be avoided, since the necessary support |
| 157 |
would require heavy rewriting of the implementation. |
| 158 |
|
| 159 |
Examples are |
| 160 |
|
| 161 |
- map is a stateful implementation of iterating over a sequence |
| 162 |
of operations. It can be made non-recursive if the map operation |
| 163 |
creates its own frame to keep state. |
| 164 |
|
| 165 |
- __init__ looks trivial, but the semantics is that the return value |
| 166 |
of __init__ is supposed to be None, and CPy has a special check for this |
| 167 |
after the call. This might simply be ignored, but it is a simple example |
| 168 |
for a case that cannot be handled automatically. |
| 169 |
|
| 170 |
- things like operator.__add__ can theoretically generate a wild pattern |
| 171 |
of recursive calls while CPy tries to figure out if it is a numeric |
| 172 |
add or a sequence add, and other callbacks may occur when methods |
| 173 |
like __coerce__ get involved. This will never be solved for SLP, but |
| 174 |
might get a solution by the strategy outlined below. |
| 175 |
|
| 176 |
The second implementation took a radically different approach. Context |
| 177 |
switches were done by hijacking parts of the C stack, storing them |
| 178 |
away and replacing them by the stack fragment that the target needs. |
| 179 |
This is very powerful and allows to switch even in the context of |
| 180 |
foreign code. With a little risk, I was even able to add concurrency |
| 181 |
to foreign Fortran code. |
| 182 |
|
| 183 |
The above concept is called Hard (switching), the collaborative Soft (switching). |
| 184 |
Note that an improved version of Hard is still the building block |
| 185 |
for greenlets, which makes them not really green - I'd name it yellow. |
| 186 |
|
| 187 |
The latest SLP rewrites combine both ideas, trying to use Soft whenever |
| 188 |
possible, but using Hard when nested interpreters are in the way. |
| 189 |
|
| 190 |
Notabene, it was never tried to pickle tasklets when Hard |
| 191 |
was involved. In SLP, pickling works with Soft. To gather more |
| 192 |
pickleable situations, you need to invent new frame types |
| 193 |
or write replacement Python code and switch it using Soft. |
| 194 |
|
| 195 |
Analogies between SLP and PyPy |
| 196 |
.............................. |
| 197 |
|
| 198 |
Right now, PyPy saves C state of functions in tiny activation records: |
| 199 |
the alive variables of a block, together with the entry point of |
| 200 |
the function that was left. |
| 201 |
This is an improvement over storing raw stack slices, but the pattern |
| 202 |
is similar: The C stack state gets restored when we switch. |
| 203 |
|
| 204 |
In this sense, it was the astonishing resume when Richard and I discussed |
| 205 |
this last week: PyPy essentially does a variant of Hard switching! At least it |
| 206 |
does a compromise that does not really help with pickling. |
| 207 |
|
| 208 |
On the other hand, this approach is half the way. It turns out to |
| 209 |
be an improvement over SLP not to have to avoid recursions in the |
| 210 |
first place. Instead, it seems to be even more elegant and efficient |
| 211 |
to get rid of unnecessary state right in the context of a switch |
| 212 |
and no earlier! |
| 213 |
|
| 214 |
Ways to handle the problem in a minimalistic way |
| 215 |
................................................ |
| 216 |
|
| 217 |
Comparing the different approaches of SLP and PyPy, it appears to be |
| 218 |
not necessary to change the interpreter in the first place. PyPy does |
| 219 |
not need to change its calling behavior in order to be cooperative. |
| 220 |
The key point is to find out which activation records need to |
| 221 |
be stored at all. This should be possible to identify as a part |
| 222 |
of the stackless transform. |
| 223 |
|
| 224 |
Consider the simple most common case of calling a normal Python function. |
| 225 |
There are several calls to functions involved, which do preparational |
| 226 |
steps. Without trying to be exact (this is part of the work to be done), |
| 227 |
involved steps are |
| 228 |
|
| 229 |
- decode the arguments of the function |
| 230 |
|
| 231 |
- prepare a new frame |
| 232 |
|
| 233 |
- store the arguments in the frame |
| 234 |
|
| 235 |
- execute the frame |
| 236 |
|
| 237 |
- return the result |
| 238 |
|
| 239 |
Now assume that we do not execute the frame, but do a context switch instead, |
| 240 |
then right now a sequence of activation records is stored on the heap. |
| 241 |
If we want to re-activate this chain of activation records, what do |
| 242 |
we really need to restore before we can do the function call? |
| 243 |
|
| 244 |
- the argument decoding is done, already, and the fact that we could have done |
| 245 |
the function call shows, that no exception occurred. We can ignore the rest |
| 246 |
of this activation record and do the housekeeping. |
| 247 |
|
| 248 |
- the frame is prepared, and arguments are stored in it. The operation |
| 249 |
succeeded, and we have the frame. We can ignore exception handling |
| 250 |
and just do housekeeping by getting rid of references. |
| 251 |
|
| 252 |
- for executing the frame, we need a special function that executes frames. It |
| 253 |
is possible that we need different flavors due to contexts. SLP does this |
| 254 |
by using different registered functions which operate on a frame, depending |
| 255 |
on the frame's state (first entry, reentry after call, returning, yielding etc) |
| 256 |
|
| 257 |
- after executing the frame, exceptions need to be handled in the usual way, |
| 258 |
and we should return to the issuer of the call. |
| 259 |
|
| 260 |
Some deeper analysis is needed to get these things correct. |
| 261 |
But it should have become quite clear, that after all the preparational |
| 262 |
steps have been done, there is no other state necessary than what we |
| 263 |
have in the Python frames: bound arguments, instruction pointer, that's it. |
| 264 |
|
| 265 |
My proposal is now to do such an analysis by hand, identify the different |
| 266 |
cases to be handled, and then trying to find an algorithm that automatically |
| 267 |
identifies the blocks in the whole program, where the restoring of the |
| 268 |
C stack can be avoided, and we can jump back to the previous caller, directly. |
| 269 |
|
| 270 |
A rough sketch of the necessary analysis: |
| 271 |
|
| 272 |
for every block in an RPython function that can reach unwind: |
| 273 |
Analyze control flow. It should be immediately leading to |
| 274 |
the return block with only one output variable. All other alive variables |
| 275 |
should have ended their liveness in this block. |
| 276 |
|
| 277 |
I think this will not work in the first place. For the bound frame |
| 278 |
arguments for instance, I think we need some notation that these are |
| 279 |
held by the frame, and we can drop their liveness before doing the call, |
| 280 |
hence we don't need to save these variables in the activation record, |
| 281 |
and hence the whole activation record can be removed. |
| 282 |
|
| 283 |
As a conclusion of this incomplete first analysis, it seems to be necessary |
| 284 |
to identify useless activation records in order to support pickling. |
| 285 |
The remaining, irreducible activation records should then be those |
| 286 |
which hold a reference to a Python frame. |
| 287 |
Such a chain is pickleable if its root points back to the context switching code |
| 288 |
of the interp-level implementation of coroutines. |
| 289 |
|
| 290 |
As an observation, this transform not only enables pickling, but |
| 291 |
also is an optimization, if we can avoid saving many activation records. |
| 292 |
|
| 293 |
Another possible observation which I hope to be able to prove is this: |
| 294 |
The remaining irreducible activation records which don't just hold |
| 295 |
a Python frame are those which should be considered special. |
| 296 |
They should be turned into something like special frames, and they would |
| 297 |
be the key to make PyPy completely stackless, a goal which is practically |
| 298 |
impossible for SLP! These activation records would need to become |
| 299 |
part of the official interface and need to get naming support for |
| 300 |
their necessary functions. |
| 301 |
|
| 302 |
I wish to stop this paper here. I believe everything else |
| 303 |
needs to be tried in an implementation, and this is so far |
| 304 |
all I can do just with imagination. |
| 305 |
|
| 306 |
best - chris |
| 307 |
|
| 308 |
Just an addition after some more thinking |
| 309 |
......................................... |
| 310 |
|
| 311 |
Actually it struck me after checking this in, that the problem of |
| 312 |
determining which blocks need to save state and which not it not |
| 313 |
really a Stackless problem. It is a system-immanent problem |
| 314 |
of a missing optimization that we still did not try to solve. |
| 315 |
|
| 316 |
Speaking in terms of GC transform, and especially the refcounting, |
| 317 |
it is probably easy to understand what I mean. Our current refcounting |
| 318 |
implementation is naive, in the sense that we do not try to do the |
| 319 |
optimizations which every extension writer does by hand: |
| 320 |
We do not try to save references. |
| 321 |
|
| 322 |
This is also why I'm always arguing that refcounting can be and |
| 323 |
effectively *is* efficient, because CPython does it very well. |
| 324 |
|
| 325 |
Our refcounting is not aware of variable lifeness, it does not |
| 326 |
track references which are known to be held by other objects. |
| 327 |
Optimizing that would do two things: The refcounting would become |
| 328 |
very efficient, since we would save some 80 % of it. |
| 329 |
The second part, which is relevant to the pickling problem is this: |
| 330 |
By doing a proper analysis, we already would have lost references to |
| 331 |
all the variables which we don't need to save any longer, because |
| 332 |
we know that they are held in, for instance, frames. |
| 333 |
|
| 334 |
I hope you understand that: If we improve the life-time analysis |
| 335 |
of variables, the sketched problem of above about which blocks |
| 336 |
need to save state and which don't, should become trivial and should |
| 337 |
just vanish. Doing this correctly will solve the pickling problem quasi |
| 338 |
automatically, leading to a more efficient implementation at the same time. |
| 339 |
|
| 340 |
I hope I told the truth and will try to prove it. |
| 341 |
|
| 342 |
ciao - chris |