Skip to content

Commit 486943d

Browse files
authored
Merge pull request #478 from thisisthepy/feat/164-suspend-fn-type
Feat: support suspend function-typed parameters in PythonCallables and PythonxAdapter (#164)
2 parents 06a334e + 0eb3d4a commit 486943d

5 files changed

Lines changed: 783 additions & 0 deletions

File tree

‎docs/SPEC.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,40 @@ All in `PM/commonTest`, so they run wherever the interpreter loads.
361361
`Status: implemented` on desktop and Kotlin/Native, `PM/desktopTest/.../upcall/AsyncUpcallDeliveryTest.kt`,
362362
`AsyncUpcallCancellationTest.kt`, `AsyncUpcallEarlyCancellationTest.kt`, `PM/nativeTest/.../AsyncUpcallNative*Test.kt`,
363363
`python-multiplatform-ksp/fixtures/app/.../GeneratedSuspendTest.kt`; `planned` on wasm (no threads).
364+
- **U-5a** (`suspend` function-typed parameters, #164 item 7):
365+
An exposed Kotlin function, method or constructor may declare a top-level parameter of a `suspend`
366+
function type (`suspend () -> R`, `suspend (A1, ..., AN) -> R`, nullable forms and `typealias`es thereof,
367+
for arities `0..5`, matching `PythonCallables.newFunction`). Return types, properties, and `suspend`
368+
function types nested inside generic type arguments (`List<suspend () -> Unit>`) remain unexposed with a
369+
KSP warning.
370+
- **Table metadata:** KSP and the artifact walker record the parameter's declared type name as
371+
`kotlin.coroutines.SuspendFunctionN(Arg1,...)->Ret` (with `TypeTag.OBJECT`), and the generated Kotlin
372+
thunk casts `args[i]` to the declared `suspend` function type.
373+
- **Python surface and lifetime:** Inside an active `PythonCallableScope` (the same scope requirement as
374+
ordinary function slots), passing a Python callable (`async def` or a callable returning an awaitable or
375+
plain value) into a `SuspendFunctionN` slot wraps it through `PythonCallables.newSuspendFunction` into a
376+
Kotlin `suspend` lambda of matching arity, owned and interned by that scope. An invocation that has
377+
already started acquires its own extra `PyObject` reference to the callable (and releases it when the
378+
invocation finishes), so closing the `PythonCallableScope` while an `await` is still in flight is safe.
379+
- **Invocation, return unmarshalling, and GIL discipline:** When Kotlin invokes the wrapped `suspend`
380+
lambda:
381+
1. Under `withGIL`, arguments are marshalled to Python and the Python callable is called.
382+
2. If the return value is not awaitable (`!hasattr(r, '__await__')`), it is unmarshalled according to
383+
`Ret` (`kotlin.Unit`, `kotlin.Boolean`, `kotlin.Int`, `kotlin.Long`, `kotlin.Float`, `kotlin.Double`,
384+
`kotlin.String`, or `PyObject`/handle for `OBJECT`) and returned immediately without suspending (fast
385+
path).
386+
3. If the return value is awaitable, it is submitted to the target `asyncio` loop resolved by U-5's
387+
delivery-loop order (`get_running_loop` → `use_delivery_loop` → `set_delivery_loop`, failing with
388+
`IllegalStateException` if no open loop is available), a done callback is attached, and the `withGIL`
389+
scope exits **before** the Kotlin coroutine suspends (`kotlin.coroutines.suspendCoroutine`) so the
390+
GIL is never held across suspension.
391+
4. When the Python task/future finishes, the callback unmarshals the result (or converts a Python
392+
exception via `PyException.toKotlinException()`, mapping `asyncio.CancelledError` to
393+
`CancellationException`) and resumes the Kotlin `Continuation`.
394+
- **Out of scope here:** `python-multiplatform` keeps no `kotlinx.coroutines` dependency (uses stdlib
395+
`suspendCoroutine` only). Propagating Kotlin `Job` cancellation back to `Task.cancel()` belongs to the
396+
`kotlinx.coroutines`-aware await wrapper (#164 item 2).
397+
`Status: implemented` on desktop, `PM/desktopTest/.../pythonx/SuspendFunctionParameterTest.kt`.
364398
- **U-6** Upcalls work in a GraalVM native image (desktop). `Status: implemented` with manual
365399
verification, procedure and record in `docs/platforms/graal-native-image-verification.md`
366400
(`:sample:nativeCompile`, Liberica NIK), guarded automatically by `ReachabilityMetadataTest.kt` (C-2).

‎python-multiplatform/build.gradle.kts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2853,4 +2853,5 @@ tasks.named<Test>("desktopTest") {
28532853

28542854
val pythonHome = File(extractedDir, "$platform$desktopFlavourSuffix/python").absolutePath
28552855
environment("PYTHONHOME", pythonHome)
2856+
testLogging.exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
28562857
}

0 commit comments

Comments
 (0)