Integrate the KJ event loop into Python's asyncio event loop (#310)

* Integrate the KJ event loop into Python's asyncio event loop

Fix #256

This PR attempts to remove the slow and expensive polling behavior for asyncio
in favor of proper linking of the KJ event loop to the asyncio event loop.

* Don't memcopy buffer

* Improve promise cancellation and prepare for timer implementation

* Add attribution for asyncProvider.cpp

* Implement timeout

* Cleanup

* First round of simplifications

* Add more a_wait functions and a shutdown function

* Fix edge-cases with loop shutdown

* Clean up calculator examples

* Cleanup

* Cleanup

* Reformat

* Fix warnings

* Reformat again

* Compatibility with macos

* Inline the asyncio loop in some places where this is feasible

* Add todo

* Fix

* Remove synchronous wait

* Wrap fd listening callbacks in a class

* Remove poll_forever

* Remove the thread-local/thread-global optimization

This will not matter much soon anyway, and simplifies things

* Share promise code by using fused types

* Improve refcounting of python objects in promises

We replace many instances of PyObject* by Own<PyRefCounter> for more automatic
reference management.

* Code wrapPyFunc in a similar way to wrapPyFuncNoArg

* Refactor capabilityHelper, fix several memory bugs for promises and add __await__

* Improve promise ownership, reduce memory leaks

Promise wrappers now hold a Own<Promise<Own<PyRefCounter>>> object. This might
seem like excessive nesting of objects (which to some degree it is, but with
good reason):
- The outer Own is needed because Cython cannot allocate objects without a
  nullary constructor on the stack (Promise doesn't have a nullary constructor).
  Additionally, I believe it would be difficult or impossible to detect when a
  promise is cancelled/moved if we use a bare Promise.
- Every promise returns a Owned PyRefCounter. PyRefCounter makes sure that a
  reference to the returned object keeps existing until the promise is fulfilled
  or cancelled. Previously, this was attempted using attach, which is redundant
  and makes reasoning about PyINCREF and PyDECREF very difficult.
- Because a promise holds a Own<Promise<...>>, when we perform any kind of
  action on that promise (a_wait, then, ...), we have to explicitly move() the
  ownership around. This will leave the original promise with a NULL-pointer,
  which we can easily detect as a cancelled promise.

Promises now only hold references to their 'parents' when strictly needed. This
should reduce memory pressure.

* Simplify and test the promise joining functionality

* Attach forgotten parent

* Catch exceptions in add_reader and friends

* Further cleanup of memory leaks

* Get rid of a_wait() in examples

* Cancel all fd read operations when the python asyncio loop is closed

* Formatting

* Remove support for capnp < 7000

* Bring asyncProvider.cpp more in line with upstream async-io-unix.c++

It was originally copied from the nodejs implementation, which in turn copied
from async-io-unix.c++. But that copy is pretty old.

* Fix a bug that caused file descriptors to never be closed

* Implement AsyncIoStream based on Python transports and protocols

* Get rid of asyncProvider

All asyncio now goes through _AsyncIoStream

* Formatting

* Add __dict__ to  PyAsyncIoStreamProtocol for python 3.7

* Reintroduce strange ipv4/ipv6 selection code to make ci happy

* Extra pause_reading()

* Work around more python bugs

* Be careful to only close transport when this is still possible

* Move pause_reading() workaround
This commit is contained in:
Lasse Blaauwbroek
2023-06-06 20:08:15 +02:00
committed by GitHub
parent ed894304a3
commit d32854eb00
25 changed files with 1060 additions and 1263 deletions

View File

@@ -284,6 +284,21 @@ def test_cancel():
with pytest.raises(Exception):
remote.wait()
req = client.foo(5)
trans = req.then(lambda x: 5)
req.cancel() # Cancel a promise that was already consumed
assert trans.wait() == 5
req = client.foo(5)
req.cancel()
with pytest.raises(Exception):
trans = req.then(lambda x: 5)
req = client.foo(5)
assert req.wait().x == "26"
with pytest.raises(Exception):
req.wait()
def test_timer():
global test_timer_var
@@ -350,6 +365,33 @@ def test_then_args():
client.foo(i=5).then(lambda x, y: 1)
class PromiseJoinServer(capability.TestPipeline.Server):
def getCap(self, n, inCap, _context, **kwargs):
def _then(response):
_results = _context.results
_results.s = response.x + "_bar"
_results.outBox.cap = inCap
return (
inCap.foo(i=n)
.then(
lambda res: capnp.Promise(int(res.x))
) # Make sure that Promise is flattened
.then(
lambda x: inCap.foo(i=x + 1)
) # Make sure that RemotePromise is flattened
.then(_then)
)
def test_promise_joining():
client = capability.TestPipeline._new_client(PromiseJoinServer())
foo_client = capability.TestInterface._new_client(Server())
remote = client.getCap(n=5, inCap=foo_client)
assert remote.wait().s == "136_bar"
class ExtendsServer(Server):
def qux(self, **kwargs):
pass

View File

@@ -10,49 +10,9 @@ import pytest
import capnp
from capnp.lib.capnp import KjException
import test_capability_capnp
@pytest.mark.skipif(
platform.python_implementation() == "PyPy",
reason="pycapnp's GIL handling isn't working properly at the moment for PyPy",
)
def test_making_event_loop():
"""
Event loop test
"""
capnp.remove_event_loop(True)
capnp.create_event_loop()
capnp.remove_event_loop()
capnp.create_event_loop()
@pytest.mark.skipif(
platform.python_implementation() == "PyPy",
reason="pycapnp's GIL handling isn't working properly at the moment for PyPy",
)
def test_making_threaded_event_loop():
"""
Threaded event loop test
"""
# The following raises a KjException, and if not caught causes an SIGABRT:
# kj/async.c++:973: failed: expected head == nullptr; EventLoop destroyed with events still in the queue.
# Memory leak?; head->trace() = kj::_::ForkHub<kj::_::Void>
# kj::_::AdapterPromiseNode<kj::_::Void, kj::_::PromiseAndFulfillerAdapter<void> >
# stack: ...
# python(..) malloc: *** error for object 0x...: pointer being freed was not allocated
# python(..) malloc: *** set a breakpoint in malloc_error_break to debug
# Fatal Python error: Aborted
capnp.remove_event_loop(KjException)
capnp.create_event_loop(KjException)
capnp.remove_event_loop()
capnp.create_event_loop(KjException)
class Server(test_capability_capnp.TestInterface.Server):
"""
Server
@@ -76,9 +36,6 @@ def test_using_threads():
"""
Thread test
"""
capnp.remove_event_loop(True)
capnp.create_event_loop(True)
read, write = socket.socketpair()
def run_server():