Debian Codegraph @

docs/source/design.rst

raw
1 Design and internals
2 ====================
3
4 .. currentmodule:: trio
5
6 Here we'll discuss Trio's overall design and architecture: how it fits
7 together and why we made the decisions we did. If all you want to do
8 is use Trio, then you don't need to read this – though you might find
9 it interesting. The main target audience here is (a) folks who want to
10 read the code and potentially contribute, (b) anyone working on
11 similar libraries who want to understand what we're up to, (c) anyone
12 interested in I/O library design generally.
13
14 There are many valid approaches to writing an async I/O library. This
15 is ours.
16
17
18 High-level design principles
19 ----------------------------
20
21 Trio's two overriding goals are **usability** and **correctness**: we
22 want to make it *easy* to get things *right*.
23
24 Of course there are lots of other things that matter too, like speed,
25 maintainability, etc. We want those too, as much as we can get. But
26 sometimes these things come in conflict, and when that happens, these
27 are our priorities.
28
29 In some sense the entire rest of this document is a description of how
30 these play out, but to give a simple example: Trio's
31 ``KeyboardInterrupt`` handling machinery is a bit tricky and hard to
32 test, so it scores poorly on simplicity and maintainability. But we
33 think the usability+correctness gains outweigh this.
34
35 There are some subtleties here. Notice that it's specifically "easy to
36 get things right". There are situations (e.g. writing one-off scripts)
37 where the most "usable" tool is the one that will happily ignore
38 errors and keep going no matter what, or that doesn't bother with
39 resource cleanup. (Cf. the success of PHP.) This is a totally valid
40 use case and valid definition of usability, but it's not the one we
41 use: we think it's easier to build reliable and correct systems if
42 exceptions propagate until handled and if the system `catches you when
43 you make potentially dangerous resource handling errors
44 <https://github.com/python-trio/trio/issues/265>`__, so that's what we
45 optimize for.
46
47 It's also worth saying something about speed, since it often looms
48 large in comparisons between I/O libraries. This is a rather subtle
49 and complex topic.
50
51 In general, speed is certainly important – but the fact that people
52 sometimes use Python instead of C is a pretty good indicator that
53 usability often trumps speed in practice. We want to make Trio fast,
54 but it's not an accident that it's left off our list of overriding
55 goals at the top: if necessary we are willing to accept some slowdowns
56 in the service of usability and reliability.
57
58 To break things down in more detail:
59
60 First of all, there are the cases where speed directly impacts
61 correctness, like when you hit an accidental ``O(N**2)`` algorithm and
62 your program effectively locks up. Trio is very careful to use
63 algorithms and data structures that have good worst-case behavior
64 (even if this might mean sacrificing a few percentage points of speed
65 in the average case).
66
67 Similarly, when there's a conflict, we care more about 99th percentile
68 latencies than we do about raw throughput, because insufficient
69 throughput – if it's consistent! – can often be budgeted for and
70 handled with horizontal scaling, but once you lose latency it's gone
71 forever, and latency spikes can easily cross over to become a
72 correctness issue (e.g., an RPC server that responds slowly enough to
73 trigger timeouts is effectively non-functional). Again, of course,
74 this doesn't mean we don't care about throughput – but sometimes
75 engineering requires making trade-offs, especially for early-stage
76 projects that haven't had time to optimize for all use cases yet.
77
78 And finally: we care about speed on real-world applications quite a
79 bit, but speed on microbenchmarks is just about our lowest
80 priority. We aren't interested in competing to build "the fastest echo
81 server in the West". I mean, it's nice if it happens or whatever, and
82 microbenchmarks are an invaluable tool for understanding a system's
83 behavior. But if you play that game to win then it's very easy to get
84 yourself into a situation with seriously misaligned incentives, where
85 you have to start compromising on features and correctness in order to
86 get a speedup that's totally irrelevant to real-world applications. In
87 most cases (we suspect) it's the application code that's the
88 bottleneck, and you'll get more of a win out of running the whole app
89 under PyPy than out of any heroic optimizations to the I/O
90 layer. (And this is why Trio *does* place a priority on PyPy
91 compatibility.)
92
93 As a matter of tactics, we also note that at this stage in Trio's
94 lifecycle, it'd probably be a mistake to worry about speed too
95 much. It doesn't make sense to spend lots of effort optimizing an API
96 whose semantics are still in flux.
97
98
99 User-level API principles
100 -------------------------
101
102 Basic principles
103 ~~~~~~~~~~~~~~~~
104
105 Trio is very much a continuation of the ideas explored in `this blog
106 post
107 <https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/>`__,
108 and in particular the `principles identified there
109 <https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/#review-and-summing-up-what-is-async-await-native-anyway>`__
110 that make curio easier to use correctly than asyncio. So Trio also
111 adopts these rules, in particular:
112
113 * The only form of concurrency is the task.
114
115 * Tasks are guaranteed to run to completion.
116
117 * Task spawning is always explicit. No callbacks, no implicit
118 concurrency, no futures/deferreds/promises/other APIs that involve
119 callbacks. All APIs are `"causal"
120 <https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/#review-and-summing-up-what-is-async-await-native-anyway>`__
121 except for those that are explicitly used for task spawning.
122
123 * Exceptions are used for error handling; ``try``/``finally``
124 and ``with`` blocks for handling cleanup.
125
126
127 Cancel points and schedule points
128 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
129
130 The first major place that Trio departs from curio is in its decision
131 to make a much larger fraction of the API use sync functions rather
132 than async functions, and to provide strong conventions about cancel
133 points and schedule points. (At this point, there are a lot of ways
134 that Trio and curio have diverged. But this was really the origin –
135 the tipping point where I realized that exploring these ideas would
136 require a new library, and couldn't be done inside curio.) The full
137 reasoning here takes some unpacking.
138
139 First, some definitions: a *cancel point* is a point where your code
140 checks if it has been cancelled – e.g., due to a timeout having
141 expired – and potentially raises a :exc:`Cancelled` error. A *schedule
142 point* is a point where the current task can potentially be suspended,
143 and another task allowed to run.
144
145 In curio, the convention is that all operations that interact with the
146 run loop in any way are syntactically async, and it's undefined which
147 of these operations are cancel/schedule points; users are instructed
148 to assume that any of them *might* be cancel/schedule points, but with
149 a few exceptions there's no guarantee that any of them are unless they
150 actually block. (I.e., whether a given call acts as a cancel/schedule
151 point is allowed to vary across curio versions and also depending on
152 runtime factors like network load.)
153
154 But when using an async library, there are good reasons why you need
155 to be aware of cancel and schedule points. They introduce a set of
156 complex and partially conflicting constraints on your code:
157
158 You need to make sure that every task passes through a cancel
159 point regularly, because otherwise timeouts become ineffective
160 and your code becomes subject to DoS attacks and other
161 problems. So for correctness, it's important to make sure you
162 have enough cancel points.
163
164 But... every cancel point also increases the chance of subtle
165 bugs in your program, because it's a place where you have to be
166 prepared to handle a :exc:`Cancelled` exception and clean up
167 properly. And while we try to make this as easy as possible,
168 these kinds of clean-up paths are notorious for getting missed
169 in testing and harboring subtle bugs. So the more cancel points
170 you have, the harder it is to make sure your code is correct.
171
172 Similarly, you need to make sure that every task passes through
173 a schedule point regularly, because otherwise this task could
174 end up hogging the event loop and preventing other code from
175 running, causing a latency spike. So for correctness, it's
176 important to make sure you have enough schedule points.
177
178 But... you have to be careful here too, because every schedule
179 point is a point where arbitrary other code could run, and
180 alter your program's state out from under you, introducing
181 classic concurrency bugs. So as you add more schedule points,
182 it `becomes exponentially harder to reason about how your code
183 is interleaved and be sure that it's correct
184 <https://glyph.twistedmatrix.com/2014/02/unyielding.html>`__.
185
186 So an important question for an async I/O library is: how do we help
187 the user manage these trade-offs?
188
189 Trio's answer is informed by two further observations:
190
191 First, any time a task blocks (e.g., because it does an ``await
192 sock.recv()`` but there's no data available to receive), that
193 has to be a cancel point (because if the I/O never arrives, we
194 need to be able to time out), and it has to be a schedule point
195 (because the whole idea of asynchronous programming is that
196 when one task is waiting we can switch to another task to get
197 something useful done).
198
199 And second, a function which sometimes counts as a cancel/schedule
200 point, and sometimes doesn't, is the worst of both worlds: you have
201 put in the effort to make sure your code handles cancellation or
202 interleaving correctly, but you can't count on it to help meet latency
203 requirements.
204
205 With all that in mind, Trio takes the following approach:
206
207 Rule 1: to reduce the number of concepts to keep track of, we collapse
208 cancel points and schedule points together. Every point that is a
209 cancel point is also a schedule point and vice versa. These are
210 distinct concepts both theoretically and in the actual implementation,
211 but we hide that distinction from the user so that there's only one
212 concept they need to keep track of.
213
214 Rule 2: Cancel+schedule points are determined *statically*. A Trio
215 primitive is either *always* a cancel+schedule point, or *never* a
216 cancel+schedule point, regardless of runtime conditions. This is
217 because we want it to be possible to determine whether some code has
218 "enough" cancel/schedule points by reading the source code.
219
220 In fact, to make this even simpler, we make it so you don't even have
221 to look at the function arguments: each *function* is either a
222 cancel+schedule point on *every* call or on *no* calls.
223
224 (Pragmatic exception: a Trio primitive is not required to act as a
225 cancel+schedule point when it raises an exception, even if it would
226 act as one in the case of a successful return. See `issue 474
227 <https://github.com/python-trio/trio/issues/474>`__ for more details;
228 basically, requiring checkpoints on all exception paths added a lot of
229 implementation complexity with negligible user-facing benefit.)
230
231 Observation: since blocking is always a cancel+schedule point, rule 2
232 implies that any function that *sometimes* blocks is *always* a
233 cancel+schedule point.
234
235 So that gives us a number of cancel+schedule points: all the functions
236 that can block. Are there any others? Trio's answer is: no. It's easy
237 to add new points explicitly (throw in a ``sleep(0)`` or whatever) but
238 hard to get rid of them when you don't want them. (And this is a real
239 issue – "too many potential cancel points" is definitely a tension
240 `I've felt
241 <https://github.com/dabeaz/curio/issues/149#issuecomment-269745283>`__
242 while trying to build things like task supervisors in curio.) And we
243 expect that most Trio programs will execute potentially-blocking
244 operations "often enough" to produce reasonable behavior. So, rule 3:
245 the *only* cancel+schedule points are the potentially-blocking
246 operations.
247
248 And now that we know where our cancel+schedule points are, there's the
249 question of how to effectively communicate this information to the
250 user. We want some way to mark out a category of functions that might
251 block or trigger a task switch, so that they're clearly distinguished
252 from functions that don't do this. Wouldn't it be nice if there were
253 some Python feature, that naturally divided functions into two
254 categories, and maybe put some sort of special syntactic marking on
255 with the functions that can do weird things like block and task
256 switch...? What a coincidence, that's exactly how async functions
257 work! Rule 4: in Trio, only the potentially blocking functions are
258 async. So e.g. :meth:`Event.wait` is async, but :meth:`Event.set` is
259 sync.
260
261 Summing up: out of what's actually a pretty vast space of design
262 possibilities, we declare by fiat that when it comes to Trio
263 primitives, all of these categories are identical:
264
265 * async functions
266 * functions that can, under at least some circumstances, block
267 * functions where the caller needs to be prepared to handle
268 potential :exc:`Cancelled` exceptions
269 * functions that are guaranteed to notice any pending cancellation
270 * functions where you need to be prepared for a potential task switch
271 * functions that are guaranteed to take care of switching tasks if
272 appropriate
273
274 This requires some non-trivial work internally – it actually takes a
275 fair amount of care to make those 4 cancel/schedule categories line
276 up, and there are some shenanigans required to let sync and async APIs
277 both interact with the run loop on an equal footing. But this is all
278 invisible to the user, we feel that it pays off in terms of usability
279 and correctness.
280
281 There is one exception to these rules, for async context
282 managers. Context managers are composed of two operations – enter and
283 exit – and sometimes only one of these is potentially
284 blocking. (Examples: ``async with lock:`` can block when entering but
285 never when exiting; ``async with open_nursery() as ...:`` can block
286 when exiting but never when entering.) But, Python doesn't have
287 "half-asynchronous" context managers: either both operations are
288 async-flavored, or neither is. In Trio we take a pragmatic approach:
289 for this kind of async context manager, we enforce the above rules
290 only on the potentially blocking operation, and the other operation is
291 allowed to be syntactically ``async`` but semantically
292 synchronous. And async context managers should always document which
293 of their operations are schedule+cancel points.
294
295
296 Exceptions always propagate
297 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
298
299 Another rule that Trio follows is that *exceptions must always
300 propagate*. This is like the `zen
301 <https://www.python.org/dev/peps/pep-0020/>`__ line about "Errors
302 should never pass silently", except that in every other concurrency
303 library for Python (threads, asyncio, curio, ...), it's fairly common
304 to end up with an undeliverable exception, which just gets printed to
305 stderr and then discarded. While we understand the pragmatic
306 constraints that motivated these libraries to adopt this approach, we
307 feel that there are far too many situations where no human will ever
308 look at stderr and notice the problem, and insist that Trio APIs find
309 a way to propagate exceptions "up the stack" – whatever that might
310 mean.
311
312 This is often a challenging rule to follow – for example, the call
313 soon code has to jump through some hoops to make it happen – but its
314 most dramatic influence can seen in Trio's task-spawning interface,
315 where it motivates the use of "nurseries":
316
317 .. code-block:: python
318
319 async def parent():
320 async with trio.open_nursery() as nursery:
321 nursery.start_soon(child)
322
323 (See :ref:`tasks` for full details.)
324
325 If you squint you can see the conceptual influence of Erlang's "task
326 linking" and "task tree" ideas here, though the details are different.
327
328 This design also turns out to enforce a remarkable, unexpected
329 invariant.
330
331 In `the blog post
332 <https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/#c-c-c-c-causality-breaker>`__
333 I called out a nice feature of curio's spawning API, which is that
334 since spawning is the only way to break causality, and in curio
335 ``spawn`` is async, which means that in curio sync functions are
336 guaranteed to be causal. One limitation though is that this invariant
337 is actually not very predictive: in curio there are lots of async
338 functions that could spawn off children and violate causality, but
339 most of them don't, but there's no clear marker for the ones that do.
340
341 Our API doesn't quite give that guarantee, but actually a better
342 one. In Trio:
343
344 * Sync functions can't create nurseries, because nurseries require an
345 ``async with``
346
347 * Any async function can create a nursery and start new tasks... but
348 creating a nursery *allows task starting but does not permit
349 causality breaking*, because the children have to exit before the
350 function is allowed to return. So we can preserve causality without
351 having to give up concurrency!
352
353 * The only way to violate causality (which is an important feature,
354 just one that needs to be handled carefully) is to explicitly create
355 a nursery object in one task and then pass it into another task. And
356 this provides a very clear and precise signal about where the funny
357 stuff is happening – just watch for the nursery object getting
358 passed around.
359
360
361 Introspection, debugging, testing
362 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
363
364 Tools for introspection and debugging are critical to achieving
365 usability and correctness in practice, so they should be first-class
366 considerations in Trio.
367
368 Similarly, the availability of powerful testing tools has a huge
369 impact on usability and correctness; we consider testing helpers to be
370 very much in scope for the Trio project.
371
372
373 Specific style guidelines
374 -------------------------
375
376 * As noted above, functions that don't block should be sync-colored,
377 and functions that might block should be async-colored and
378 unconditionally act as cancel+schedule points.
379
380 * Any function that takes a callable to run should have a signature
381 like:
382
383 .. code-block:: python
384
385 def call_the_thing(fn, *args, kwonly1, kwonly2):
386 ...
387
388 where ``fn(*args)`` is the thing to be called, and ``kwonly1``,
389 ``kwonly2``, are keyword-only arguments that belong to
390 ``call_the_thing``. This applies even if ``call_the_thing`` doesn't
391 take any arguments of its own, i.e. in this case its signature looks
392 like:
393
394 .. code-block:: python
395
396 def call_the_thing(fn, *args):
397 ...
398
399 This allows users to skip faffing about with
400 :func:`functools.partial` in most cases, while still providing an
401 unambiguous and extensible way to pass arguments to the caller.
402 (Hat-tip to asyncio, who we stole this convention from.)
403
404 * Whenever it makes sense, Trio classes should have a method called
405 ``statistics()`` which returns an immutable object with named fields
406 containing internal statistics about the object that are useful for
407 debugging or introspection (:ref:`examples <synchronization>`).
408
409 * Functions or methods whose purpose is to wait for a condition to
410 become true should be called ``wait_<condition>``. This avoids
411 ambiguities like "does ``await readable()`` *check* readability
412 (returning a bool) or *wait for* readability?".
413
414 Sometimes this leads to the slightly funny looking ``await
415 wait_...``. Sorry. As far as I can tell all the alternatives are
416 worse, and you get used to the convention pretty quick.
417
418 * If it's desirable to have both blocking and non-blocking versions of
419 a function, then they look like:
420
421 .. code-block:: python
422
423 async def OPERATION(arg1, arg2):
424 ...
425
426 def OPERATION_nowait(arg1, arg2):
427 ...
428
429 and the ``nowait`` version raises :exc:`trio.WouldBlock` if it would block.
430
431 * ...we should, but currently don't, have a solid convention to
432 distinguish between functions that take an async callable and those
433 that take a sync callable. See `issue #68
434 <https://github.com/python-trio/trio/issues/68>`__.
435
436
437 A brief tour of Trio's internals
438 --------------------------------
439
440 If you want to understand how Trio is put together internally, then
441 the first thing to know is that there's a very strict internal
442 layering: the ``trio._core`` package is a fully self-contained
443 implementation of the core scheduling/cancellation/IO handling logic,
444 and then the other ``trio.*`` modules are implemented in terms of the
445 API it exposes. (If you want to see what this API looks like, then
446 ``import trio; print(trio._core.__all__)``). Everything exported from
447 ``trio._core`` is *also* exported as part of the ``trio``,
448 ``trio.lowlevel``, or ``trio.testing`` namespaces. (See their
449 respective ``__init__.py`` files for details; there's a test to
450 enforce this.)
451
452 Rationale: currently, Trio is a new project in a novel part of the
453 design space, so we don't make any stability guarantees. But the goal
454 is to reach the point where we *can* declare the API stable. It's
455 unlikely that we'll be able to quickly explore all possible corners of
456 the design space and cover all possible types of I/O. So instead, our
457 strategy is to make sure that it's possible for independent packages
458 to add new features on top of Trio. Enforcing the ``trio`` vs
459 ``trio._core`` split is a way of `eating our own dogfood
460 <https://en.wikipedia.org/wiki/Eating_your_own_dog_food>`__: basic
461 functionality like :class:`trio.Lock` and :mod:`trio.socket` is
462 actually implemented solely in terms of public APIs. And the hope is
463 that by doing this, we increase the chances that someone who comes up
464 with a better kind of queue or wants to add some new functionality
465 like, say, file system change watching, will be able to do that on top
466 of our public APIs without having to modify Trio internals.
467
468
469 Inside ``trio._core``
470 ~~~~~~~~~~~~~~~~~~~~~
471
472 The ``_ki.py`` module implements the core infrastructure for safe handling
473 of :class:`KeyboardInterrupt`. It's largely independent of the rest of Trio,
474 and could (possibly should?) be extracted into its own independent package.
475
476 The most important submodule, where everything is integrated, is
477 ``_run.py``. (This is also by far the largest submodule; it'd be nice
478 to factor bits of it out where possible, but it's tricky because the
479 core functionality genuinely is pretty intertwined.) Notably, this is
480 where cancel scopes, nurseries, and :class:`~trio.lowlevel.Task` are
481 defined; it's also where the scheduler state and :func:`trio.run`
482 live.
483
484 The one thing that *isn't* in ``_run.py`` is I/O handling. This is
485 delegated to an ``IOManager`` class, of which there are currently
486 three implementations:
487
488 * ``EpollIOManager`` in ``_io_epoll.py`` (used on Linux, illumos)
489
490 * ``KqueueIOManager`` in ``_io_kqueue.py`` (used on macOS, \*BSD)
491
492 * ``WindowsIOManager`` in ``_io_windows.py`` (used on Windows)
493
494 The epoll and kqueue backends take advantage of the epoll and kqueue
495 wrappers in the stdlib :mod:`select` module. The windows backend uses
496 CFFI to access to the Win32 API directly (see
497 ``trio/_core/_windows_cffi.py``). In general, we prefer to go directly
498 to the raw OS functionality rather than use :mod:`selectors`, for
499 several reasons:
500
501 * Controlling our own fate: I/O handling is pretty core to what Trio
502 is about, and :mod:`selectors` is (as of 2017-03-01) somewhat buggy
503 (e.g. `issue 29256 <https://bugs.python.org/issue29256>`__, `issue
504 29255 <https://bugs.python.org/issue29255>`__). Which isn't a big
505 deal on its own, but since :mod:`selectors` is part of the standard
506 library we can't fix it and ship an updated version; we're stuck
507 with whatever we get. We want more control over our users'
508 experience than that.
509
510 * Impedance mismatch: the :mod:`selectors` API isn't particularly
511 well-fitted to how we want to use it. For example, kqueue natively
512 treats an interest in readability of some fd as a separate thing
513 from an interest in that same fd's writability, which neatly matches
514 Trio's model. :class:`selectors.KqueueSelector` goes to some effort
515 internally to lump together all interests in a single fd, and to use
516 it we'd then we'd have to jump through more hoops to reverse
517 this. Of course, the native epoll API is fd-centric in the same way
518 as the :mod:`selectors` API so we do still have to write code to
519 jump through these hoops, but the point is that the :mod:`selectors`
520 abstractions aren't providing a lot of extra value.
521
522 * (Most important) Access to raw platform capabilities:
523 :mod:`selectors` is highly inadequate on Windows, and even on
524 Unix-like systems it hides a lot of power (e.g. kqueue can do a lot
525 more than just check fd readability/writability!).
526
527 The ``IOManager`` layer provides a fairly raw exposure of the capabilities
528 of each system, with public API functions that vary between different
529 backends. (This is somewhat inspired by how :mod:`os` works.) These
530 public APIs are then exported as part of :mod:`trio.lowlevel`, and
531 higher-level APIs like :mod:`trio.socket` abstract over these
532 system-specific APIs to provide a uniform experience.
533
534 Currently the choice of backend is made statically at import time, and
535 there is no provision for "pluggable" backends. The intuition here is
536 that we'd rather focus our energy on making one set of solid, official
537 backends that provide a high-quality experience out-of-the-box on all
538 supported systems.