@@ -3,8 +3,10 @@ package python.multiplatform.ffi.upcall
33import python.multiplatform.ffi.PyObject
44import python.multiplatform.ffi.Python3
55import python.multiplatform.ffi.exceptions.PyException
6+ import python.multiplatform.ffi.exceptions.isNoneObject
67import python.multiplatform.ffi.types.basic.PyBool
78import python.multiplatform.ffi.types.basic.PyInt
9+ import python.multiplatform.ffi.types.basic.PyNone
810import python.multiplatform.ffi.types.basic.PyString
911import python.multiplatform.ffi.withGIL
1012import 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.
0 commit comments