Skip to content

The PyParallel Experiment

Trent Nelson edited this page Sep 3, 2015 · 15 revisions

This is a temporary home for what will probably eventually become the official "The PyParallel Experiment" paper. It is a work-in-progress. Blocks in italics, such as this one, indicate temporary content placeholders. Current progress: about ~13% complete.

Abstract

--

PyParallel is an experimental, proof-of-concept fork of Python 3.3.5 designed to optimally exploit contemporary hardware: multiple CPU cores, fast SSDs, NUMA architectures, and fast I/O channels (10GbE, Thunderbolt, etc). It presents a solution for removing the limitation of the Python Global Interpreter Lock (GIL) without needing to actually remove it at all. The code changes required to the interpreter are relatively unobtrusive, all existing semantics such as reference counting and garbage collection remain unchanged, the new mental model required in order to write PyParallel-safe code (both at the CPython/C extension and Python level) is very simple (don't persist parallel objects), the single-thread overhead is negligible, and performance scales linearly with cores when using the new parallel facilities.

Disclaimer

-- PyParallel is, first and foremost, an experiment. It is not currently suitable for production. It is a product of trial-and-error, intended to shape the discussions surrounding the next generation of Python. We attempt to juggle the difficult task of setting the stage for Python to flourish over the next 25 years, without discarding all the progress we made in the last 25.

PyParallel was created by an existing Python committer with the intention of eventually merging it back into the mainline. It is not a hostile fork. There are many details that still need to be ironed out. It will need to prove itself as an independent project first before it could be considered for inclusion back in the main source tree. We anticipate this being at least 5 years out, and think Python 4.x would be a more realistic target than Python 3.x.

5 years sounds like a long time, however, they will come and go, just like any other. We may as well start the ball rolling now. There's nothing wrong with slow and steady as long as you're heading in the right direction. And it's not like we're getting any less cores per year.

Expectations need to be set reasonably, and we encourage the Python community toward biasing yes versus biasing no, with a view toward the long term benefits of such a project. Early adopters and technical evaluators will need to have thick skin, a pioneering spirit and a hearty sense of adventure. You will definitely hit a __debugbreak() or two if you're doing things right. But hey, you'll be able to melt all your cores during the process, and that's kinda' fun.

We encourage existing committers to play around and experiment, to fork and to send pull requests. One of the benefits of PyParallel at the moment is the freedom to experiment without the constraints that come with normal mainline development, where much more discipline is required per commit. It provides a nice change of pace and helps get the creative juices flowing. There is also a lot of low-hanging fruit, ripe for picking by Computer Science and Software Engineering students that want to get their feet wet with open source.

Catalyst

--

PyParallel and asyncio share the same origin. They were both products of an innocuous e-mail to python-ideas in September 2012 titled asyncore: included batteries don't fit. The general discussion centered around providing better asynchronous I/O primitives in Python 3.4. PyParallel took the wildly ambitious (and at the time, somewhat ridiculous) path of trying to solve both asynchronous I/O and the parallel problem at the same time. The efforts paid off, as we consider the whole experiment to be a success (at least in terms of its original goals), but it is a much longer term project, alluded to above. There is some inevitable overlap between the asyncio interface, and the async interface we exposed for PyParallel. Additionally, async became a keyword in Python 3.5, so we will need to change the module name when we rebase against 3.5. The most likely name will be parallel. At the time of writing (August 2015), all examples and public documentation to date, including examples in this document, use the async module name.

Note: the parallel facilities provided by PyParallel are actually complementary to the single-threaded event loop facilities provided by asyncio. In fact, we envision hybrid solutions emerging that use asyncio to drive the parallel facilities behind the scenes, where the main thread dispatches requests to parallel servers behind the scenes, acting as the coordinator for parallel computation.

Overview

--

We expose a new async module to Python user code which must be used in order to leverage the new parallel execution facilities. Specifically, users implement completion-oriented protocol classes, then register them with PyParallel TCP/IP client or server objects.

import async
class Hello:
    def connection_made(self, transport, data):
        return b'Hello, World!\r\n'
    def data_received(self, transport, data):
        return b'You said: ' + data + '\r\n'
         
server = async.server('0.0.0.0', 8080)
async.register(transport=server, protocol=Hello)
async.run()

The protocol callbacks are automatically executed in parallel. This is achieved by creating parallel contexts for each client socket that connects to a server. The parallel context owns the underlying socket object, and all memory allocations required during callback execution are served from the context's heap, which is a simple block allocator. If callbacks need to send data back to the client, they must return a sendable object: bytes, bytearray or string. (That is, they do not explicitly call read() and write() methods against the transport directly.) If the contents of a file needs to be returned, transport.sendfile() can be used. Byte ranges can also be efficiently returned via transport.ranged_sendfile(). Both of these methods serve file content directly from the kernel's cache via TransmitFile.

GIL Semantics Unchanged

The semantic behavior of the "main thread" (the current thread holding the GIL) is unchanged. Instead, we introduce the notion of a parallel thread (or parallel context), and parallel objects, which are PyObjects allocated from parallel contexts. We provide an efficient way to detect if we're in a parallel thread via the Py_PXCTX() macro, as well as a way to detect if a PyObject was allocated from a parallel thread via Py_ISPX(ob). Using only these two facilities, we are able to intercept all thread-sensitive parts of the interpreter and redirect to our new parallel alternative if necessary. (The GIL entry and exit macros, Py_BEGIN_THREAD_STATE and Py_END_THREAD_STATE respectively, also get ignored in parallel contexts.)

Restriction: Don't Persist Parallel Objects

We introduce one new restriction that will affect existing Python code (and C extensions): don't persist parallel objects. More explicitly, don't cache objects that were created during parallel callback processing.

For the CPython interpreter internals (in C), this means avoiding the following: freelist manipulation, first-use static PyObject initialization, and unicode interning. On the Python side, this means avoiding mutation of global state (or, more specifically, avoiding mutation of Python objects that were allocated from the main thread; don't append to a main thread list or assign to a main thread dict from a parallel thread).

Reference Counting and Garbage Collection in Parallel Contexts

We approached the problem of referencing counting and garbage collection within parallel contexts using a rigorous engineering methodology that can be summed up as follows: let's not do it, and see what happens. Nothing happened, so we don't do it.

Instead, we manage object lifetime and memory allocation in parallel contexts by exploiting the temporal and predictable nature of the protocol callbacks, which map closely to TCP/IP states (connection_made(), data_received(), send_complete(), etc).

A snapshot is taken prior to invoking the callback and then rolled back upon completion. Object lifetime is therefore governed by the duration of the callback; all objects allocated during the processing of a HTTP request, for example, including the final bytes object we send as a response, will immediately cease to exist the moment our TCP/IP stack informs us the send completed. (Specifically, we perform the rollback activity upon receipt of the completion notification.)

This is effective for the same reason generational garbage collectors are effective: most objects are short lived. For stateless, idempotent protocols, like HTTP, all objects are short lived. For stateful protocols, scalar objects (ints, floats, strings, bytes) can be assigned to self (a special per-connection instance of the protocol class), which will trigger a copy of the object from an alternate heap (still associated with the parallel context). (This is described in more detail here.) The lifetime of these objects will last as long as the TCP/IP connection persists, or until a previous value is overwritten by a new value, which ever comes first.

Thus, PyParallel requires no changes to existing reference counting and garbage collection semantics or APIs. Py_INCREF(op) and Py_DECREF(op) get ignored in parallel contexts, and GC-specific calls like PyObject_GC_New() simply get re-routed to our custom parallel object allocator in the same fashion as PyObject_New(). This obviates the need for fine-grain, per-object locking, as well as the need for a thread-safe, concurrent garbage collector.

This is significant when you factor in how Python's scoping works at a language level: Python code executing in a parallel thread can freely access any non-local variables created by the "main thread". That is, it has the exact same scoping and variable name resolution rules as any other Python code. This facilitates loading large data structures from the main thread and then freely accessing them from parallel callbacks.

We demonstrate this with our simple Wikipedia "instant search" server, which loads a trie with 27 million entries, each one mapping a title to a 64-bit byte offset within a 60GB XML file. We then load a sorted NumPy array of all 64-bit offsets, which allows us to extract the exact byte range a given title's content appears within the XML file, allowing a client to issue a ranged request for those bytes to get the exact content via a single call to TransmitFile. This call returns immediately, but sets up the necessary structures for the kernel to send that byte range directly to the client without further interaction from us.

The working set size of the python.exe process is about 11GB when the trie and NumPy array are loaded. Thus, multiprocessing would not be feasible, as you'd have 8 separate processes of 11GB if you had 8 cores and started 8 workers, requiring 88GB just for the processes. The number of allocated objects is around 27.1 million; the datrie library can efficiently store values if they're a 32-bit integer, however, our offsets are 64-bit, so an 80-something byte PyObject needs to be allocated to represent each one.

This is significant because it demonstrates the competitive advantage PyParallel has against other languages when dealing with large heap sizes and object counts, whilst simultaneously avoiding the need for continual GC-motivated heap traversal, a product of memory allocation pressure (which is an inevitable side-effect of high-end network load, where incoming links are saturated at line rate). We ellaborate on this shortly.

For a more contained example, we present the following. We load an array with a billion elements, consuming about 9GB of memory, then expose a HTTP server that services client requests in parallel, randomly picking a slice of 10 elements within the array and summing it. The principles are the same as the Wikipedia instant search server (random access to huge data structures in parallel, where request latency and throughput scale linearly with cores and concurrency up to ncpu).

import numpy as np
import async

one_billion = 1000000000
large_array = np.random.randints(low=0, high=100, size=one_billion)
fmt = 'The sum of the items in slice [%d:%d] is %d'

class Random:
    http11 = True 
    # ^^^^ This class attribute tells PyParallel to use an SSE-accelerated
    # HTTP 1.1 parser for this protocol, automatically translating a GET
    # request for the URL '/random' to a direct call to `random()` (meaning
    # we don't have to implement `data_received()` and do HTTP parsing ourself).
    # (HTTP headers are accessible at this point via `transport.http_headers`,
    # which is a dict.)
    def random(self, transport, data):
        # This code executes within the new parallel execution environment.
        # We can access anything we'd normally be able to access according
        # to Python's scope rules.  Any new objects we create herein are
        # "parallel objects" and will only exist for the duration of the
        # callback.  (Although we could assign a scalar to self here,
        # provided we define it as a class variable above.  This would
        # allow persistence of state between callbacks, and could either
        # be used to track a higher level protocol state (like POP3), or
        # to track the results of intermediate computation.  Keep in mind
        # persisting to a scalar isn't so bad from an overhead perspective
        # when you've got other cores servicing other requests simultaneously;
        # Pickling and unpickling a complex structure (list, dict) to a string
        # each request is fast and simple, and allows us to avoid a whole
        # host of memory/object/pointer ownership issues we'd have to deal with
        # if we were persisting container objects (like lists and dicts).)
        start = np.random.randint(low=0, high=one_billion-11)
        end = start + 10
        return fmt % (start, end, large_array[start:end].sum())

server = async.server('0.0.0.0', 8080)
async.register(transport=server, protocol=Random)
print("Random server now accessible at http://localhost:8080/random")
print("Press Ctrl-C to quit.")
async.run()

This split-brain main-thread versus parallel thread approach to object allocation and ownership is a unique breakthrough. By separating the two concepts, we get the best of both worlds: reference counting and garbage collection at the global, "main thread" level, where object lifetime cannot be implicitly known any other way, and very fast GC-less allocation at the parallel level, where we can rely on the temporal nature of our protocol semantics to manage object lifetime. The incumbent "main thread" behavior doesn't need to know anything about the latter parallel behavior, and the parallel environment knows how to avoid disturbing the former.

This gives PyParallel a unique advantage over other garbage collected languages like C#, Java and Go, despite those languages being much faster in general due to being compiled versus interpreted. The absense of GC within parallel contexts means there are no GC pauses, which results in PyParallel having request latency cumulative frequency distributions on par with GC-less languages like C, C++, and Rust (in terms of the distribution, not the actual latency numbers; C/C++ will always be faster than interpreted Python, of course).

Furthermore, our experimentation shows that the new solution plays nicely with tools such as Cython (provided the Cython code uses normal Python memory allocation facilities and doesn't try to persist objects generated from parallel contexts). In fact, our Wikipedia instant search trie is powered by a Cython project named datrie, which is a wrapper around the C library libdatrie.

This is significant as it allows us to continue to leverage the stellar work done by the Python community for accelerating Python (or Python-esque) code, whilst simultaneously leveraging the benefits afforded by PyParallel. Entire request callbacks could be implemented in Cython, providing C-like performance to those domains that rely upon it. We anticipate similar compatibility with other optimizers like Numba. Converting Python code into performant, potentially-JIT-accelerated machine code will be a constantly evolving domain. PyParallel is complimentary to these techniques, providing the glue behind the scenes to minimize the latency between I/O and subsequent computation across multiple cores. We defer to the other projects to provide means for accelerating the computation from within the callback. It is a symbiotic relationship, not a competitive one.

Additionally, because code executed within parallel contexts is normal Python code, we can run it in a single-threaded fashion from the main thread during development, which allows the normal debugging and unit testing facilities needed at such a stage. (We also implement experimental support for a parallel thread to acquire the GIL and become the main thread in order to further assist debugging efforts.)

We attribute the success of the PyParallel experiment to five key things:

  • Being relatively unfamiliar with the intracacies of Python's C implementation. This was advantageous, despite how counter-intuitive it seems. Not knowing what you don't know is a great way to lower the cost of experimentation.
  • Attacking parallelization and asynchronous I/O at the same time. The two are intrinsically linked. The single-threaded, non-blocking event loop with a system multiplex call (kqueue/epoll) is simply not suitable for exploiting today's multicore 10GbE+ environments. If your I/O strategy isn't intrinsically linked to your parallel computation strategy, you're not going to be able to optimally use your underlying hardware. Minimizing the latency between completion of I/O and subsequent scheduling of computation is critical.
  • The willingness of the CPython interpreter internals to be completely subverted by our parallel shenanigans without requiring any breaking API changes or complex locking semantics. This was a delightful surprise, and all credit goes to Guido for developing the primitives the way he did 25-odd years ago.
  • The situational awareness provided by Visual Studio's debugger for facilitating such subversive changes on a code base we were ultimately unfamiliar with. Writing code was a miniscule portion of PyParallel's development time -- the vast majority of time was spent within the debugger, stepping through unfamiliar code, figuring out ways to subvert the interpreter (or determing why our attempts at subversion weren't working). All Aha! moments were had either in a) the shower, or b) whilst Visual Studio was attached to python_d.exe and we were staring at call stacks, locals, autos, memory values and source code all within the same place, stepping through individual instructions, constantly building up our situational awareness.
  • Designing around mechanical sympathy at the hardware, kernel, OS userspace, and protocol level. The reason Windows was used to develop PyParallel is because it simply has the best kernel and userspace primitives for not only solving the problem, but solving it as optimally as the underlying hardware will allow. Windows itself exhibits excellent mechanical sympathy between all levels of the stack, which we leverage extensively. The reception of a TCP/IP packet off the wire, to the I/O request completion by the NIC's device driver, to the threadpool I/O completion, to the dispatching of the most optimal thread within our process, to calling back into the C function we requested, to us immediately invoking the relevant Python object's data_received() call; mechanical sympathy is maintained at every layer of the stack, facilitating the lowest possible latency.

Interpreter Changes

-- Thread-sensitive calls are ubiquitous within the Python interpreter. Past experiments have shown that even minor changes to the overhead incurred by Py_INCREF(op) and Py_DECREF(op) impact the interpreter's performance in a non-negligible way.

Parallel Context Detection

Thus, the first problem we had to solve was coming up with a quick way to detect whether or not we were in a parallel context. The quicker it can be detected, the lower the overhead, the more viable the approach is likely to be. The key to being fast is to do less, so we wondered: what do we reliably have access to at all times that we can use to distinguish our parallel threads from normal, main threads? The convergence was quick: thread IDs.

We add the following public members to pyparallel.h:

PyAPI_DATA(volatile long) Py_MainThreadId;
PyAPI_FUNC(void) _PyParallel_JustAcquiredGIL();

And we alter take_gil() in ceval_gil.h to call into us as soon as a main thread has acquired the GIL:

@@ -236,6 +245,9 @@ static void take_gil(PyThreadState *tstate)
     MUTEX_LOCK(switch_mutex);
 #endif
     /* We now hold the GIL */
+#ifdef WITH_PARALLEL
+    _PyParallel_JustAcquiredGIL();
+#endif
     _Py_atomic_store_relaxed(&gil_locked, 1);
     _Py_ANNOTATE_RWLOCK_ACQUIRED(&gil_locked, /*is_write=*/1);

The implementation of _PyParallel_JustAcquiredGIL() in pyparallel.c simply updates Py_MainThreadId:

void
_PyParallel_JustAcquiredGIL(void)
{
    Py_MainThreadId = _Py_get_current_thread_id();
}

We now have all we need to detect if we're in a parallel context by simply comparing the value of Py_MainThreadId to _Py_get_current_thread_id(), which becomes the basis for our Py_PXCTX() macro:

#define Py_PXCTX() (Py_MainThreadId == _Py_get_current_thread_id())

However, we can improve things further. _Py_get_current_thread_id() has a direct analogue on both Windows and POSIX: GetCurrentThreadId() and pthread_self(), respectively. But our Py_PXCTX() call will be ubiquitous; is there any way we can avoid a function call? On Windows, we can interrogate the thread environment block (TEB) directly to derive the current thread ID:

#define _Py_get_current_thread_id()  (__readgsdword(0x48))

(On POSIX/amd64, we'd use __read[fg]sbase() instead. This guarantees to return a "unique" address for a thread, and we'd simply use this for the identity test instead of the actual thread ID assigned by the operating system.)

Thus, the Py_PXCTX() macro essentially expands to a simple equality test between two 32-bit variables. For example:

if (Py_PXCTX())
    return;

Expands to:

if (Py_MainThreadId == __readgsdword(0x48))
    return;

This approach has remained unchanged since inception, and has proven to be a reliable and optimal solution for parallel context detection. It has one limitation, though: it can't be used in parts of the interpreter that operate without holding the GIL. Luckily, this is mostly limited to code that deals with GIL acquisition, which is not frequently executed relative to the rest of the code base. In this situation, code can use the more reliable but slightly slower alternative _PyParallel_GetActiveContext(), which returns the TLS ctx variable we set within pyparallel.c as soon as we're invoked by the threadpool upon I/O completion. This method doesn't suffer the false-positive issue Py_PXCTX() is subject to when the GIL isn't held. The increased overhead comes from the two-level lookup required to resolve the TLS variable:

5982:     if (ctx) {
 8B 0D FF 7C 28 00          mov         ecx,dword ptr [_tls_index (1E42FD90h)]  
 BA 80 29 00 00             mov         edx,2980h  
 48 89 83 90 02 00 00       mov         qword ptr [rbx+290h],rax  
 65 48 8B 04 25 58 00 00 00 mov         rax,qword ptr gs:[58h]  
 48 8B 04 C8                mov         rax,qword ptr [rax+rcx*8]  
 48 8B 0C 02                mov         rcx,qword ptr [rdx+rax]  
 48 85 C9                   test        rcx,rcx  
 74 70                      je          new_context+253h (1E1A8123h)

This overhead is an acceptable trade-off when we need to resolve our ctx variable once within a C function body, but it makes sense to avoid it if we can for hot-path code, like reference counting interception.

--

Quality of prose goes south pretty quickly herein; work in progress, much braindump.

--

Proof-of-concept: parallel.map()

Detecting whether or not we're in a parallel context isn't much good when we don't have any concept yet of a parallel context, nor any way to get into one even if we did.

Our forth commit on the forth day of development eventually got our forth attempt at parallel.map() working, appropriately named parallel.t4().

(We're unsure about the significance of four. But hey, at least it's not six.)

def t4():
    def f(x):
        return x * x

    result = parallel.t4(f, [2, 3])
    print(result)

def t4_2():
    def f(x):
        return x * x

    data = [ i for i in range(1, 150) ]
    result = parallel.t4(f, data)
    print(result)

Granted, it was prefaced with the caveat "for lists less than 150 items, otherwise, not so much with the working", and the implementation was pretty horrendous. However, it worked well enough to serve as a proof of concept: we could intercept thread-sensitive parts of the interpreter, redirect them to an alternate thread-safe implementation, and things would basically work. The idea had demonstrable merit.

It's fun to look back on the initial commits. pyparallel.c was an adorable 50-odd lines at the time. It currently sits at 14,433 lines at the time of writing. We feel this is an appropriate time to quote Wes McKinney, mostly as a self-defense strategy: few things kill productivity in a new project like prematurely breaking things up into lots of small files.

We abandoned parallel.map() at this point and switched focus to our ideas for an async façade. (We had sketched out the ideas for our new parallel and asynchronous I/O interfaces a month earlier, in our pep-async.)

Our async façade was inspired by the new threadpool APIs introduced in Windows Vista. We sketched out the following set of interfaces:

  • Submission of arbitrary work.

    async.submit_work(func, args, kwds, callback=None, errback=None)

    Calls result = func(args, kwds) in a parallel context, then callback(result) if non-null (also in a parallel context), or errback() if an error occurred.

  • Submission of waits.

    async.submit_wait(obj, func, args, kwds, ...)

    Calls func(args, kwds) from a parallel thread when obj is signalled.

  • Submission of asynchronous file I/O.

    f = async.open(filename, 'wb')
    async.write(f, buf, callback=None, errback=None)

    Write buf to file f asynchronously. That is, immediately return from the write() call. Upon completion of the write, call callback() if provided, or errback() if an error occurred.

  • Submission of timers.

    async.submit_timer(time, func, args, kwds, ...)
    async.submit_interval(interval, func, args, kwds, ...)

    Calls func(args, kwds) from a parallel thread at time time, or every interval (e.g. every 10 milliseconds).

    XXX this next bit is out of context, fix.

    Note: we never got around to implementing these two functions, instead preferring to tackle the async client/server interface below, which we perceived as much more difficult, and we wanted to have a prototype working in under 3 months, ready for presentation at the PyCon 2013 Developer Summit. However, as part of our SSE-accelerated HTTP parser work, we implement a "shared" gmtime() timer, which uses a threadpool timer that runs every second to format the current time into the HTTP format expected in response headers (Date: Sat, 16 May 2015 15:21:34 GMT\r\n). On the request processing side, we obtain a shared reader lock and then simply memcpy the 23 bytes directly into our response header's buffer, seen here.

  • Asynchronous client/server services.

    client = async.client(host, port)
    server = async.server(host, port)
    async.register(transport=client, protocol=ClientProtocol)
    async.register(transport=server, protocol=ServerProtocol)

Threadpool Sidebar

An important design decision is worth noting at this point: PyParallel avoids creating threads manually. Specifically, it is designed to be as thread agnostic as possible, keeping in sympathy with the Windows kernel architecture, which itself is geared toward thread agnosticism.

The threadpool API manages creation and destruction of new threads as necessary. It ensures there are only ever as many threads running at any given time as there are available CPU cores. The Windows thread scheduler is NUMA cognizant, attempting to run threads on their preferred cores. However, preference does not imply affinity. Often, migrating a thread to a different core than the previous one it executed on will be more optimal than a) creating a new thread, or b) waiting for the current thread to finish executing. The end goal being optimal use of underlying hardware; just as unused memory is wasted memory, an unused core is a wasted core if there is computation waiting to take place.

Although thread migration happens relatively infrequently, it still happens. We observed approximately 5,000 migrations over the course of ten seconds at one point; a stat we can't back up because we're not even sure if we remembered it correctly.

We wrote enough code in order to successfully get Windows to call into the callback we provided from a new thread, allowing us to call back into Python's internals via PyObject_CallObject(). Not surprisingly, this crashed pretty quickly.

Playing Defense

When you don't know what you don't know: play defense. Specifically, code defensively. We implement Py_GUARD() and Px_GUARD() macros and liberally sprinkle them over the code as if they were ... something something <insert witty simily>.

The former says: crash if I hit this from a parallel thread, the latter says: crash if I hit this from the main-thread.

(Crash, in this context, refers to raising a Py_FatalError() with file and line information, or, if the environment variable PYPARALLEL_FORGOT_WHAT_ITS_CURRENTLY_CALLED_XXX_TODO is set to 1, we __debugbreak(), allowing us to attach the Visual Studio debugger.)

The primary recipient of Py_GUARD() is gcmodule.c. If a parallel thread ever manages to make its way into any function in that file, something is seriously awry. We reward the effort with a crash.

We later add additional guards for protecting not only contexts but object and memory allocations as well. It is valuable during development to be able to test (and assert, if necessary) that a given PyObject *op is a main thread object or a parallel thread object:

  • Py_GUARD_OBJ(o): if we're main thread and o is a parallel object: crash.
  • Px_GUARD_OBJ(o): if we're a parallel thread and o is a main thread object: crash.
  • PyPx_GUARD_OBJ(o): context sensitive crash: if we're a main thread and o is a parallel object: crash. If we're a parallel thread and o is a main thread object: also crash.

Likewise, for a given void *ptr memory allocation:

  • Py_GUARD_MEM(m): if we're a main thread and m is memory allocated from a parallel context: crash.
  • Px_GUARD_MEM(m): if we're a parallel thread and m is memory allocated from a main thread: crash.
  • PyPx_GUARD_MEM(m): context sensitive crash: if we're a main thread and m is memory allocated from a parallel context: crash; if we're a parallel thread and m is memory is allocated from a main thread: also crash.

In general, our rule of thumb is the venerable: crash early, crash often.

Todo: notes on implementation; PxPages and hash lookups in debug mode; where there's room for improvement on the memory side; using VADs instead of hashes, etc

Protocols

Absence of explicit send/recv. Avoid blocking calls. Avoid UNIXisms. Use protocol semantics to tightly control flow. Have one outstanding I/O request at any time. Prepare all of your data (do as much compute as you can), then send. You are running in parallel and can do as much computation in one go as you need -- you do not need to send the header first so that you can get some bytes on the wire, then yield execution so something else has a chance to run, then send some more bytes for the body, then yield, then a bit more. Just do it all up front and send. That is inherently more efficient. (It is also in complete contrast to existing paradigms that have been designed around the single-threaded non-blocking syscall multiplex UNIXisms.) Be mindful of how long your callback runs for. Prefer shorter callbacks to longer ones, and design your app accordingly. Design the client to break big requests up into smaller ones; if you have 8 cores, you can have 8 TCP/IP connections that will run simultaneously across all your cores.

... abrupt segue and... examples of trivial protocols:

import time
import async
import datetime

class Disconnect:
    pass

class Discard:
    def data_received(self, transport, data):
        pass

class Daytime:
    """
    Send a string representation of the current time, then disconnect."
    """
    def initial_bytes_to_send(self):
        return time.ctime() + r'\r\n'

class Time:
    """
    Send a 32-bit unsigned integer in binary format and network byte order,
    representing the number of seconds since 00:00 (midnight) January 1st,
    1900 GMT, then close the connection.
    """
    def initial_bytes_to_send(self):
        delta = datetime.utcnow() - datetime(1900, 1, 1)
        return bytes(socket.htonl(int(delta.total_seconds())))

class StaticQotd:
    """
    Send a static value as soon as a client connects,
    then disconnect.
    """
    initial_bytes_to_send = b'Begin. The rest is easy.\r\n'

class DynamicQotd:
    """
    Send a dynamic (value is computed just before sending)
    string to a client, then disconnect.
    """
    def initial_bytes_to_send(self):
        return b'An apple a day keeps the doctor away.\r\n'

class EchoData:
    def data_received(self, transport, data):
        return data

class Quote:
    initial_bytes_to_send = b'Begin. The rest is easy.'

class Hello:
    def connection_made(self, transport, data):
        return b'Hello, World!'
    
class HelloFastHttp:
    http11 = True
    def plaintext(self, transport, data):
        return b'Hello, World!'
    def json(self, transport, data):
        return { 'message': 'Hello, World!' }
         
server = async.server('0.0.0.0', 8080)
async.register(transport=server, protocol=Hello)
async.run()

Examples

Copy-and-paste from e-mail...

    import datrie
    import numpy as np
    import pyodbc
    import async
    from collections import defaultdict
    from async.http.server import (
        router,
        make_routes,
        HttpServer,
        RangedRequest,
    )

    # Tell PyParallel to invoke the tp_dealloc method explicitly
    # for these classes when rewinding a heap after a parallel
    # callback has finished.  (Implementation detail: this toggles
    # the Py_TPFLAGS_PX_DEALLOC flag in the TypeObject's tp_flags;
    # when PyParallel intercepts PyObject_NEW/INIT (init_object),
    # classes (PyTypeObject *tp) with this flag set will be tracked
    # in a linked-list that is local to the parallel context being
    # used to service this client.  When the context has its heaps
    # rewound back to the initial state at the time of the snapshot,
    # it will call tp_dealloc() explicitly against all objects of
    # this type that were encountered.)
    async.register_dealloc(pyodbc.Connection)
    async.register_dealloc(pyodbc.Cursor)
    async.register_dealloc(pyodbc.Row)

    # Load 29 million titles.  RSS += ~9.5GB.
    TITLES = datrie.Trie.load('titles.trie')
    # Load 15 million 64-bit offsets. RSS += ~200MB.
    OFFSETS = np.load('offsets.npy')
    XML = 'enwiki-20150205-pages-articles.xml'

    class WikiServer(HttpServer):
        # All of these methods are automatically invoked in
        # parallel.  HttpServer implements a data_received()
        # method which prepares the request object and then
        # calls the relevant method depending on the URL, e.g.
        # http://localhost/user/foo will call the user(request,
        # name='foo').  If we want to "write" to the client,
        # we return a bytes, bytearray or unicode object from
        # our callback (that is, we don't expose a socket.write()
        # to the user).
        #
        # Just before the PyParallel machinery invokes the
        # callback (via a simple PyObject_CallObject), though,
        # it takes a snapshot of its current state, such that
        # the exact state can be rolled back to (termed a socket
        # "rewind") when this callback is complete.  If we don't
        # return a sendable object back, this rewind happens
        # immediately, and then we go straight into a read call.
        # If we do return something sendable, we send it.  When
        # that send completes, *then* we do the rewind, then we
        # issue the next read/recv call.
        #
        # This approach is particularly well suited to parallel
        # callback execution because none of the objects we create
        # as part of the callback are needed when the callback
        # completes.  No garbage can accumulate because nothing
        # can live longer than that callback.  That obviates the
        # need for two things: reference counting against any object
        # in a parallel context, and garbage collection.  Those
        # things are useful for the main thread, but not parallel
        # contexts.
        #
        # What if you do want to keep something around after
        # the callback?  If it's a simple scalar type, the
        # following will work:
        #   class Server:
        #       name = None
        #       @route
        #       def set_name(self, request, name):
        #           self.name = name.upper()
        #           ^^^^^^^^^ we intercept that setattr and make
        #                     a copy of (the result of) name.upper()
        #                     using memory allocation from a different
        #                     heap that persists as long as the client
        #                     stays connnected.  (There's actually
        #                     support for alternatively persisting
        #                     the entire heap that the object was
        #                     allocated from, which we could use if
        #                     we were persisting complex, external,
        #                     or container types where simply doing
        #                     a memcpy() of a *base + size_t wouldn't
        #                     be feasible.  However, I haven't wired
        #                     up this logic to the socket context
        #                     logic yet.)
        #       @route
        #       def name(self, request):
        #           return json_serialization(request, self.name)
        #                                              ^^^^^^^^^
        #                                   This will return whatever
        #                                   was set in the call above.
        #                                   Once the client disconnects,
        #                                   the value disappears.
        #
        #       (Actually I think if you wanted to persist the object
        #        for the lifetime of the server, you could probably
        #        do `request.transport.parent.name = xyz`; or at least,
        #        if that doesn't currently work, the required mechanics
        #        definitely exist, so it would just need to be wired
        #        up.)
        #
        # If you want to keep an object around past the lifetime of
        # the connected client and the server, then send it to the main
        # thread where it can be tracked like a normal Python object:
        #
        # USERS = async.dict()
        #         ^^^^^^^^^^^^ shortcut for:
        #                           foo = {}
        #                           async.protect(foo)
        #                      or just:
        #                           foo = async.protect({})
        #         (On the backend, this instruments[3] the object such
        #          that PyParallel can intercept setattr/setitem and
        #          getattr/getitem calls and "do stuff"[4], depending
        #          on the context.)

[3]: https://bitbucket.org/tpn/pyparallel/src/8528b11ba51003a9821ceb75683ee96ed33db28a/Python/pyparallel.c?at=3.3-px#cl-1796
[4]: https://bitbucket.org/tpn/pyparallel/src/8528b11ba51003a9821ceb75683ee96ed33db28a/Python/pyparallel.c?at=3.3-px#cl-1632

        #
        # class MyServer(HttpServer):
        #   @route
        #   ^^^^^^ Ignore the mechanics of this, it's just a helper
        #          decorator I used to translate a HTTP GET for
        #          /login/foo to a function call of `login(name='foo')`.
        #          (see the bowls of async.http.server for details).
        #   def login(self, request, name):
        #       @call_from_main_thread
        #       def _save_name(n):
        #           USERS[n] = async.rdtsc()
        #           return len(USERS)
        #       count = _save_name(name)
        #       return json_serialization(request, {'count': count})
        #
        # The @call_from_main_thread decorator will enqueue a work
        # item to the main thread, and then wait on the main thread's
        # response.  The main thread executes the callback and notifies
        # the parallel thread that the call has been completed and the
        # return value (in this case the value of `len(USERS)`).  The
        # parallel thread resumes and finishes the client request.
        # Note that this will implicitly serialize execution; any number
        # of parallel requests can submit main thread work, but the
        # main thread can only call them one at a time.  So, you'd
        # usually try and avoid this, or at least remove it from your
        # application's hot code path.

        connect_string = None
        all_users_sql = 'select * from user'
        one_user_sql = 'select * from user where login = ?'

        secret_key = None

        @route
        def wiki(self, request, name):
            # http://localhost/wiki/Python: name = Python
            if name not in TITLES:
                self.error(request, 404)

            # log(n) lookup against a trie with 29 million keys.
            offset = TITLES[name][0]
            # log(n) binary search against a numpy array with 15
            # million int64s.
            ix = OFFSETS.searchsorted(offset, side='right')
            # OFFSETS[ix] = what's the offset after this?
            (start, end) = (ix-7, OFFSETS[ix]-11)
            # -7, +11 = adjust for the fact that all of the offsets
            # were calculated against the '<' of '<title>Foo</title>'.
            range_request = '%d-%d' % (start, end)
            request.range = RangedRequest(range_request)
            request.response.content_type = 'text/xml; charset=utf-8'
            return self.sendfile(request, XML)

        @route
        def users(self, request):
            # ODBC driver managers that implement connection pooling
            # behind the scenes play very nicely with our
            # pyodbc.connect() call here, returning a connection
            # from the pool (when able) without blocking.
            con = pyodbc.connect(self.connect_string)

            # The next three odbc calls would all block (in the
            # traditional sense), so this current thread would
            # not be able to serve any other requests whilst
            # waiting for completion -- however, this is far
            # less of a problem for PyParallel than single-threaded
            # land as other threads will keep servicing requests
            # in the mean time.  (ODBC 3.8/SQL Server 2012/Windows 8
            # did introduce async notification, such that we could
            # request that an event be set when the cursor/query/call
            # has completed, which we'd tie in to PyParallel by
            # submitting a threadpool wait (much like we do for async
            # DNS lookup[5], also added in Windows 8), however, it was
            # going to require a bit of modification to the pyodbc
            # module to support the async calling style, so, all the
            # calls stay synchronous for now.)

[5]: https://bitbucket.org/tpn/pyparallel/src/8528b11ba51003a9821ceb75683ee96ed33db28a/Python/pyparallel.c?at=3.3-px#cl-7616

            cur = con.cursor()
            cur.execute(self.all_users_sql)
            return json_serialization(request, cur.fetchall())

        @route
        def user(self, request, login):
            con = pyodbc.connect(self.connect_string)
            cur = con.cursor()
            cur.execute(self.one_user_sql, (login,))
            return json_serialization(request, cur.fetchall())

        @route
        def set_secret_key(self, request, key):
            # http://localhost/set_secret_key/foobar
            # An example of persisting a scalar for the lifetime
            # of the thread (that is, until it disconects or EOFs).
            try:
                self.secret_key = [ key, ]
            except ValueError:
                # This would be hit, because we've got guards in place
                # to assess the "clonability" of an object at this
                # point[6].  (Ok, after reviewing the code, we don't,
                # but at least we'd crash.)
[6]: https://bitbucket.org/tpn/pyparallel/src/8528b11ba51003a9821ceb75683ee96ed33db28a/Python/pyparallel.c?at=3.3-px#cl-4944

            # However, this would work fine, essentially memcpy'ing
            # the key object at the time of assignment using a different
            # heap to the one that automatically gets reset at the end
            # of the callback.
            self.secret_key = key

        @route
        def secret_key(self, request):
            # http://localhost/secret_key -> 'foobar'
            return json_serialization(request, {'key': self.secret_key})

        @route
        def stats(self, request):
            # Handy little json representation of various system stats;
            # active parallel contexts, I/O hogs, memory load, etc.
            stats = {
                'system': dict(sys_stats()),
                'server': dict(socket_stats(request.transport.parent)),
                'memory': dict(memory_stats()),
                'contexts': dict(context_stats()),
                'elapsed': request.transport.elapsed(),
                'thread': async.thread_seq_id(),
            }
            return json_serialization(request, stats)

        @route
        def debug(self, request):
            # Don't call print() or any of the sys.std(err|out)
            # methods in a parallel context.  If you want to do some
            # poor man's debugging with print statements in lieu of not
            # being able to attach a pdb debugger (tracing is disabled
            # in parallel threads), then use async.debug().  (On
            # Windows, this writes the message to the debug stream,
            # which you'd monitor via dbgview or VS.)
            async.debug("received request: %s" % request.data)

            # Avoid repr() at the moment in parallel threads; it uses
            # PyThreadState_SetDictItem() to control recursion depths,
            # which I haven't made safe to call from a parallel context.

            # If you want to attach Visual Studio debugger at this point
            # though, you can do so via:
            async.debugbreak()
            # (That literally just generates an INT 3.)

        @route
        def shutdown(self, request):
            # Handy helper for server shutdown (stop listening on the
            # bound IP:PORT, wait for all running client callbacks to
            # complete, then return.  Totally almost works at the
            # moment[7].)
[7]: https://bitbucket.org/tpn/pyparallel/src/8528b11ba51003a9821ceb75683ee96ed33db28a/Python/pyparallel.c?at=3.3-px#cl-11818
            request.transport.shutdown()

    def main():
        server = async.server('0.0.0.0', port)
        protocol = HttpServer
        protocol.connect_string = 'Driver={SQL Server}...'
        async.register(transport=server, protocol=protocol)
        ^^^^^^^^^^^^^^ this will create a special 'server' instance
                       of the protocol, which will issue the bind()
                       call.  It then creates a configurable number
                       (currently ncpu * 2) of parallel contexts
                       and triggers parallel AcceptEx() invocation
                       (you can prime "pre-accepted" sockets on Windows,
                       which removes the serialization limits of
                       accept() on POSIX).

        # If an exception occurs in a parallel thread, it is queued
        # to a special list the main thread has.  The main thread
        # checks this list each time async.run_once() is called, so,
        # we call it here just to propagate any exceptions that
        # may have already occurred (like attempting to bind to an
        # invalid IP, or submitting a protocol that had an error).
        async.run_once()
        return server
        # (This also facilitates interactive console usage whilst
        #  serving request in parallel.)

    if __name__ == '__main__':
        main()
        # Run forever.  Returns when there are no active contexts
        # or ctrl-c is pressed.
        async.run()

Synchronous versus Asynchronous I/O

-- Synchronous I/O has less overhead than asynchronous I/O.

XXX TODO

  • HTTP parser written in Python, then accelerated via SSE with picohttpparser's HTTP parser library.
  • Leveraging the block allocator with regards to remaining memory and upcoming memory allocations for picohttpparser.
  • How asyncio and PyParallel could work together for doing parallel compute; have the asyncio client side be able to chunk work up and spread it across HTTP connections to a PyParallel end-point, which can service concurrent connections in parallel and leverage the single memory space by pre-loading large data structures. Reference Oracle's parallel_dbms_execute and how it disassociates chunking of work from subsequent scheduling of work.