Skip to content

Commit 06a334e

Browse files
authored
Merge pull request #475 from thisisthepy/feat/164-delivery-loop
Feat: add delivery loop configuration for suspend upcalls without a running loop (#164)
2 parents 24f28b0 + bd77896 commit 06a334e

5 files changed

Lines changed: 445 additions & 23 deletions

File tree

‎docs/SPEC.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,34 @@ All in `PM/commonTest`, so they run wherever the interpreter loads.
330330
delivers `asyncio.CancelledError` (with any Kotlin `cause` attached as `__cause__`) to the awaiting
331331
coroutine, while any other Kotlin `Throwable` delivers `RuntimeError(message)` with the original Kotlin
332332
throwable attached as `__cause__`.
333+
**Named delivery loop when the calling thread has no running loop** (#164, item 10):
334+
When an exposed `suspend` function suspends (`PendingCall.isDone` is `false`), `AsyncUpcall` resolves the
335+
target `asyncio` event loop in priority order:
336+
1. `asyncio.get_running_loop()` on the calling thread, when a loop is currently running there (a running
337+
loop on the calling thread always wins so an `await` inside that loop never receives a `Future` bound
338+
to another loop);
339+
2. the task-scoped loop set by `with python_multiplatform.use_delivery_loop(loop):`, stored in a
340+
`contextvars.ContextVar` so a coroutine stepped across threads inside `contextvars.Context.run` keeps
341+
its target loop;
342+
3. the process-wide fallback loop set by `python_multiplatform.set_delivery_loop(loop)` (`None` clears it
343+
and returns the previous value; `python_multiplatform.get_delivery_loop()` returns the configured loop
344+
from (2) or (3), or `None`).
345+
A non-`None` argument to `use_delivery_loop` or `set_delivery_loop` must expose callable `create_future`,
346+
`call_soon_threadsafe` and `is_closed` attributes, or `TypeError` is raised when configuring it. If no
347+
loop is running on the calling thread and no loop is configured (or the configured loop's `is_closed()` is
348+
`True`), `AsyncUpcall.deliver` cancels the already-started `PendingCall` (`call.cancel()`) before raising
349+
`RuntimeError` (`"no running event loop"` / `"delivery event loop is closed"`), so a cooperating Kotlin
350+
body stops at its next `ensureActive()` checkpoint.
351+
When the call resolves its loop from (2) or (3) on a thread where that loop is not running, the `Future`
352+
and its `_pm_watch` cancellation callback are created on the target loop via
353+
`target_loop.call_soon_threadsafe` and waited for while releasing the GIL (`withoutGIL`), so
354+
`loop.create_future()` and `Future.add_done_callback` run only on the target loop's own thread. In Python
355+
`coro.send(None)` (as in `pythonx-concurrent` S7.9's Kotlin-mode driver), `await _pm_r` inside the
356+
generated `async def` proxy calls `_pm_r.__await__()`, which yields that `asyncio.Future` bound to the
357+
target loop out of `coro.send()`; the driver (or a task scheduled on the target loop) subscribes or awaits
358+
it on that loop, and Kotlin's completion resolves it via `target_loop.call_soon_threadsafe(_pm_settle, ...)`.
359+
The fast path (`PendingCall.isDone` is `true` before `deliver` returns) never consults `get_running_loop()`
360+
or the configured delivery loop and builds no `Future`.
333361
`Status: implemented` on desktop and Kotlin/Native, `PM/desktopTest/.../upcall/AsyncUpcallDeliveryTest.kt`,
334362
`AsyncUpcallCancellationTest.kt`, `AsyncUpcallEarlyCancellationTest.kt`, `PM/nativeTest/.../AsyncUpcallNative*Test.kt`,
335363
`python-multiplatform-ksp/fixtures/app/.../GeneratedSuspendTest.kt`; `planned` on wasm (no threads).

‎python-multiplatform/src/commonMain/kotlin/python/multiplatform/ffi/upcall/AsyncUpcall.kt‎

Lines changed: 73 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ package python.multiplatform.ffi.upcall
33
import python.multiplatform.ffi.PyObject
44
import python.multiplatform.ffi.Python3
55
import python.multiplatform.ffi.exceptions.PyException
6+
import python.multiplatform.ffi.exceptions.isNoneObject
67
import python.multiplatform.ffi.types.basic.PyBool
78
import python.multiplatform.ffi.types.basic.PyInt
9+
import python.multiplatform.ffi.types.basic.PyNone
810
import python.multiplatform.ffi.types.basic.PyString
911
import python.multiplatform.ffi.withGIL
1012
import python.multiplatform.reflection.ExposedCallable
@@ -113,35 +115,83 @@ internal object AsyncUpcall {
113115
return UpcallTrampoline.marshalResult(entry.returnType, call.value)
114116
}
115117

116-
val loop = runningLoop()
117-
val future = loop.getAttr("create_future").invoke()
118-
val tag = entry.returnType
119-
// Resolved here, on the upcall thread, rather than inside the completion: the completing
120-
// thread may be one CPython has never seen, and this keeps its GIL scope down to the calls
121-
// that have to be there. `PythonProxySource` installs it if nothing else has.
122-
val settle = PythonProxySource.settleFunction()
123-
val handle = armCancellationNotice(call, future)
124-
// Registering after the future exists: a completion that lands between the isDone check
125-
// above and this line fires the listener inline, on this thread, with the GIL already held
126-
// -- which is exactly what the listener is written to tolerate.
127-
call.onCompleted { completed -> resolve(loop, future, settle, tag, completed, handle) }
118+
return try {
119+
// Resolved first, on the upcall thread, so `python_multiplatform` and `__main__`'s
120+
// support functions exist before we consult `get_delivery_loop()`.
121+
val settle = PythonProxySource.settleFunction()
122+
val (loop, isRunningOnCallingThread) = resolveDeliveryLoop()
123+
val tag = entry.returnType
124+
val (future, handle) = if (isRunningOnCallingThread) {
125+
val created = loop.getAttr("create_future").invoke()
126+
val armed = armCancellationNotice(call, created)
127+
created to armed
128+
} else {
129+
createFutureOnConfiguredLoop(call, loop)
130+
}
131+
// Registering after the future exists: a completion that lands between the isDone check
132+
// above and this line fires the listener inline, on this thread, with the GIL already
133+
// held -- which is exactly what the listener is written to tolerate.
134+
call.onCompleted { completed -> resolve(loop, future, settle, tag, completed, handle) }
128135

129-
// The trampoline's contract: the result is a new reference. The wrapper keeps its own,
130-
// because the completion still needs it.
131-
Py_IncRef(future.pointer)
132-
return future.pointer.toRawValue()
136+
// The trampoline's contract: the result is a new reference. The wrapper keeps its own,
137+
// because the completion still needs it.
138+
Py_IncRef(future.pointer)
139+
future.pointer.toRawValue()
140+
} catch (t: Throwable) {
141+
// SPEC U-5 (#164, item 10): if resolving or creating the Future on the target loop
142+
// fails (for example, no running loop and no configured delivery loop, or a closed
143+
// delivery loop), cancel the already-started PendingCall so a cooperating Kotlin body
144+
// stops at its next ensureActive() checkpoint rather than running on as an orphan.
145+
call.cancel()
146+
throw t
147+
}
133148
}
134149

135150
/**
136-
* `asyncio.get_running_loop()` -- the loop belonging to the coroutine this upcall came out of.
151+
* Resolves the target `asyncio` loop for a suspended call in SPEC U-5 priority order (#164,
152+
* item 10):
153+
* 1. `asyncio.get_running_loop()` on the calling thread, when a loop is currently running
154+
* there (`second == true`);
155+
* 2. `python_multiplatform.get_delivery_loop()` (`use_delivery_loop` `ContextVar` first, then
156+
* `set_delivery_loop` fallback; `second == false`).
137157
*
138-
* Not `get_event_loop()`: that one will happily create or return a loop nobody is running,
139-
* which would queue the completion somewhere no one ever drains. Not cached either, because the
140-
* module object would outlive an interpreter that gets finalized and this is the slow path by
141-
* construction -- a call that genuinely suspended is not counting attribute lookups.
158+
* When neither is present, rethrows the `RuntimeError("no running event loop")` from
159+
* `get_running_loop()`.
160+
*/
161+
private fun resolveDeliveryLoop(): Pair<PyObject, Boolean> {
162+
val runningError: Throwable = try {
163+
return Python3.import("asyncio").getAttr("get_running_loop").invoke() to true
164+
} catch (t: Throwable) {
165+
t
166+
}
167+
val configured = Python3.import(KotlinSurface.MODULE_NAME).getAttr("get_delivery_loop").invoke()
168+
if (!configured.pointer.isNoneObject()) {
169+
if (configured.getAttr("is_closed").invoke().toString() == "True") {
170+
throw IllegalStateException("delivery event loop is closed")
171+
}
172+
return configured to false
173+
}
174+
throw runningError
175+
}
176+
177+
/**
178+
* Creates an `asyncio.Future` (and arms `_pm_watch` when available) on [loop]'s own thread via
179+
* `_pm_create_remote_future`, so neither `loop.create_future()` nor `Future.add_done_callback`
180+
* runs off-thread when the calling thread has no running loop.
142181
*/
143-
private fun runningLoop(): PyObject =
144-
Python3.import("asyncio").getAttr("get_running_loop").invoke()
182+
private fun createFutureOnConfiguredLoop(call: PendingCall, loop: PyObject): Pair<PyObject, ObjectReference?> {
183+
val createRemote = PythonProxySource.createRemoteFutureFunction()
184+
val hasWatch = PythonProxySource.watchFunctionOrNull() != null
185+
val handle = if (hasWatch) HandleTable.register(call) else null
186+
return try {
187+
val handleArg: PyObject = if (handle != null) PyInt.from(handle.raw) else PyNone.get()
188+
val future = createRemote.invoke(loop, handleArg)
189+
future to handle
190+
} catch (t: Throwable) {
191+
if (handle != null) HandleTable.release(handle)
192+
throw t
193+
}
194+
}
145195

146196
/**
147197
* Gives Python a way to tell [call] it has been abandoned, and returns the handle that costs.

‎python-multiplatform/src/commonMain/kotlin/python/multiplatform/ffi/upcall/KotlinSurface.kt‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ object KotlinSurface {
193193
# `python_multiplatform` -- the binder's root module. Kotlin-named modules carry Kotlin's own
194194
# surface; this module describes it, so that a Pythonic package can be built on top by rule.
195195
196+
import contextvars as _contextvars
196197
import inspect as _inspect
197198
import keyword as _keyword
198199
import re as _re
@@ -208,6 +209,66 @@ object KotlinSurface {
208209
# for how the two decide which layer answers a call.
209210
_proxy_epoch = -1
210211
212+
# Delivery event loop configuration when the calling thread has no running asyncio loop
213+
# (SPEC U-5; issue #164, item 10).
214+
_delivery_loop_var = _contextvars.ContextVar('python_multiplatform.delivery_loop', default=None)
215+
_default_delivery_loop = None
216+
_REQUIRED_LOOP_ATTRS = ('create_future', 'call_soon_threadsafe', 'is_closed')
217+
218+
219+
def _validate_delivery_loop(loop):
220+
if loop is None:
221+
return
222+
for attr in _REQUIRED_LOOP_ATTRS:
223+
if not callable(getattr(loop, attr, None)):
224+
raise TypeError(
225+
'delivery loop must provide callable ' + ', '.join(_REQUIRED_LOOP_ATTRS) +
226+
'; missing or non-callable ' + repr(attr)
227+
)
228+
229+
230+
def set_delivery_loop(loop):
231+
'''Sets the process-wide fallback asyncio loop for `suspend` upcalls on threads with no
232+
running event loop, and returns the previous fallback loop (`None` clears it).
233+
'''
234+
global _default_delivery_loop
235+
_validate_delivery_loop(loop)
236+
previous = _default_delivery_loop
237+
_default_delivery_loop = loop
238+
return previous
239+
240+
241+
def get_delivery_loop():
242+
'''Returns the task-scoped delivery loop (`use_delivery_loop`) if set in the current
243+
`contextvars.Context`, otherwise the process-wide fallback (`set_delivery_loop`), or `None`.
244+
'''
245+
loop = _delivery_loop_var.get()
246+
return loop if loop is not None else _default_delivery_loop
247+
248+
249+
class _DeliveryLoopScope:
250+
__slots__ = ('_loop', '_token')
251+
252+
def __init__(self, loop):
253+
_validate_delivery_loop(loop)
254+
self._loop = loop
255+
self._token = None
256+
257+
def __enter__(self):
258+
self._token = _delivery_loop_var.set(self._loop)
259+
return self._loop
260+
261+
def __exit__(self, _exc_type, _exc_val, _exc_tb):
262+
if self._token is not None:
263+
_delivery_loop_var.reset(self._token)
264+
self._token = None
265+
return False
266+
267+
268+
def use_delivery_loop(loop):
269+
'''Context manager that binds [loop] as the delivery loop in the current `contextvars.Context`.'''
270+
return _DeliveryLoopScope(loop)
271+
211272
212273
class _KotlinDefault:
213274
'''The `default` of a parameter whose Kotlin declaration has one.

‎python-multiplatform/src/commonMain/kotlin/python/multiplatform/ffi/upcall/PythonProxySource.kt‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,9 @@ object PythonProxySource {
266266
/** The name [AsyncUpcall] resolves out of `__main__` to arm a `Future`'s cancellation notice. */
267267
internal const val WATCH_FUNCTION = "_pm_watch"
268268

269+
/** The name [AsyncUpcall] resolves out of `__main__` to create a `Future` on a non-running configured delivery loop. */
270+
internal const val CREATE_REMOTE_FUTURE_FUNCTION = "_pm_create_remote_future"
271+
269272
/** The `(long) -> int` entry point `_pm_watch` routes a cancellation to; per-platform. */
270273
internal const val CANCEL_ENTRY_POINT = "_pm_cancel"
271274

@@ -347,6 +350,27 @@ object PythonProxySource {
347350
_fut.add_done_callback(_pm_done)
348351
349352
353+
def _pm_create_remote_future(_loop, _handle):
354+
# Creates an `asyncio.Future` (and, when [_handle] is non-None, arms `_pm_watch`) on
355+
# [_loop]'s own thread via `call_soon_threadsafe`, waiting on a `concurrent.futures.Future`
356+
# carrier so CPython releases the GIL while waiting and `create_future()` /
357+
# `add_done_callback` never run off-thread (SPEC U-5; issue #164, item 10).
358+
import concurrent.futures as _pm_cf
359+
if _loop.is_closed():
360+
raise RuntimeError('delivery event loop is closed')
361+
_carrier = _pm_cf.Future()
362+
def _make():
363+
try:
364+
_f = _loop.create_future()
365+
if _handle is not None:
366+
_pm_watch(_f, _handle)
367+
_carrier.set_result(_f)
368+
except BaseException as _e:
369+
_carrier.set_exception(_e)
370+
_loop.call_soon_threadsafe(_make)
371+
return _carrier.result()
372+
373+
350374
def _pm_module(_name):
351375
# Exposed names are Kotlin fully-qualified names, so `fixture.library.greet` should be
352376
# reachable as `from fixture.library import greet`. Injecting into sys.modules is what
@@ -715,6 +739,14 @@ object PythonProxySource {
715739
return main.getAttrOrNull(WATCH_FUNCTION)
716740
}
717741

742+
/** Makes sure `_pm_create_remote_future` exists in `__main__` and hands it back. */
743+
internal fun createRemoteFutureFunction(): PyObject {
744+
val main = Python3.import("__main__")
745+
main.getAttrOrNull(CREATE_REMOTE_FUTURE_FUNCTION)?.let { return it }
746+
Python3.exec(support)
747+
return main.getAttr(CREATE_REMOTE_FUTURE_FUNCTION)
748+
}
749+
718750
// ------------------------------------------------------------------------------- rendering
719751

720752
private val ENTRY_POINT_GUARD = """

0 commit comments

Comments
 (0)