Skip to content

Commit 646b152

Browse files
authored
Merge pull request #512 from thisisthepy/feat/164-step-coroutine
Feat: step a Python coroutine from Kotlin as one GIL-taking call; the Kotlin/Native thread rule for resuming continuations (#164 items 13, 11)
2 parents 430e546 + 59e86ce commit 646b152

10 files changed

Lines changed: 1054 additions & 22 deletions

File tree

‎docs/SPEC.md‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,8 +377,16 @@ All in `PM/commonTest`, so they run wherever the interpreter loads.
377377
it on that loop, and Kotlin's completion resolves it via `target_loop.call_soon_threadsafe(_pm_settle, ...)`.
378378
The fast path (`PendingCall.isDone` is `true` before `deliver` returns) never consults `get_running_loop()`
379379
or the configured delivery loop and builds no `Future`.
380+
**Resuming from a Kotlin/Native thread** (iOS and androidNative; #164 item 11, pythonx-concurrent S9.6;
381+
leader decision 2026-11-21, in 1.0, not owner-confirmed): any thread may resume a parked continuation,
382+
provided it holds `withGIL` while it resumes (`PendingCall`'s contract, since the resumption runs the
383+
delivery listener inline): a bare `pthread` the runtime never attached, a Kotlin/Native `Worker`, or a
384+
`kotlinx.coroutines` dispatcher thread, which is a `Worker` underneath. The thread attaches on entry to
385+
the scope and is detached when it ends (depth back to 0); the sample's iOS section 7 does it with a
386+
`Worker` (`sample/src/iosMain/.../ProxyDemo.ios.kt`).
380387
`Status: implemented` on desktop and Kotlin/Native, `PM/desktopTest/.../upcall/AsyncUpcallDeliveryTest.kt`,
381388
`AsyncUpcallCancellationTest.kt`, `AsyncUpcallEarlyCancellationTest.kt`, `PM/nativeTest/.../AsyncUpcallNative*Test.kt`,
389+
`PM/nativeTest/.../AsyncUpcallWorkerDeliveryTest.kt` (the `Worker` rule),
382390
`python-multiplatform-ksp/fixtures/app/.../GeneratedSuspendTest.kt`; `planned` on wasm (no threads).
383391
- **U-5a** (`suspend` function-typed parameters, #164 item 7):
384392
An exposed Kotlin function, method or constructor may declare a top-level parameter of a `suspend`
@@ -598,6 +606,58 @@ All in `PM/commonTest`, so they run wherever the interpreter loads.
598606
`theContinuationIsDispatchedThroughTheCallersInterceptorNotRunOnTheLoopThread`,
599607
`aKotlinxJobCancellationReachesTaskCancelThroughTheSubmitPrimitive`,
600608
`aReceiverWithoutAwaitOrNoLoopFailsBeforeAnythingIsScheduled`).
609+
- **U-5e** (stepping a Python coroutine from Kotlin, #164 item 13, pythonx-concurrent S7.9/S7.10/S7.13;
610+
fable-pmp's task 2026-11-21, agent proposal, not owner-confirmed):
611+
`fun PyObject.step(value: PyObject? = null, context: PyObject? = null): PyStep` and
612+
`fun PyObject.throwInto(exception: PyObject, context: PyObject? = null): PyStep` /
613+
`throwInto(exception: Throwable, context)` (package `python.multiplatform.ffi.pythonx`) run **one step** of
614+
the receiver, a coroutine, a generator or any object with the method used: `receiver.send(value)` (`None`
615+
when `value` is null) or `receiver.throw(exception)`, inside `context.run(...)` when a
616+
`contextvars.Context` is given, else in the calling thread's current context (a `ContextVar.set` inside
617+
the coroutine then stays in that thread's context). They need nothing but the interpreter: no binding
618+
module, no upcall table, no event loop; no loop is set running during a step (pythonx-concurrent §11
619+
item 6 is that library's decision).
620+
- **One attachment, no suspension.** The whole step is one `withGIL` scope on the calling thread,
621+
whichever thread that is (a thread CPython never saw attaches for the call and is detached on return,
622+
the nesting depth back to what it was). The library code inside the scope contains no suspension point
623+
and runs no caller-supplied Kotlin code, so the GIL (attachment on 3.15t) is never held across a Kotlin
624+
suspension and on a JVM virtual thread the step is one pinned call (#161). A Python upcall into Kotlin
625+
from inside the coroutine runs under the step's frame as any upcall does.
626+
- **The outcome is a sealed `PyStep`.** `Yielded(value)`: the object the coroutine suspended on (for an
627+
`await` of an `asyncio` future, the future itself; for U-5's proxies, the `Future` the binder handed
628+
out), a new owned reference the caller closes. `Returned(value)`: the coroutine returned; the
629+
`StopIteration` value, owned by the caller (`None` for a bare return; an exhausted generator reports
630+
`Returned(None)` again, as its `StopIteration` does). `Raised(exception)`: the step raised, with the
631+
`PyException` (type, value, traceback, `__context__`, `__cause__`) and the error indicator cleared;
632+
this includes `RuntimeError("cannot reuse already awaited coroutine")` for a finished coroutine,
633+
`ValueError("coroutine already executing")` for a step that overlaps another, and
634+
`RuntimeError("cannot enter context: ... is already entered")` when the given context is in use
635+
(the coroutine untouched in that case). A `Raised` whose `exception.isCancelledError()` is the
636+
cancellation signal; `exception.toKotlinException()` applies U-2's mapping.
637+
- **Throwing in.** `throwInto(PyObject)` throws that exception instance (or class) into the coroutine at
638+
its suspension point. `throwInto(Throwable)` builds the Python exception with U-2's mapping: a Kotlin
639+
`CancellationException` arrives as `asyncio.CancelledError` with any Kotlin cause as `__cause__`, a
640+
`PyException` as its original Python instance, any other throwable as `RuntimeError(message)` with
641+
the Kotlin cause chain on `__cause__`.
642+
- **Refusals before anything runs** (`IllegalArgumentException`, the receiver untouched): a receiver
643+
without the method used (`send` / `throw`), a `context` that is not a `contextvars.Context`.
644+
- **Threads.** Two steps of one coroutine never overlap: the driver sequences them (S7.11); each may
645+
run on a different thread, and `threading.get_ident()` inside the coroutine changes with the thread
646+
while `contextvars` stay with the `Context` the driver passes. Reference counting: the receiver and
647+
the arguments are the caller's and are not retained beyond the call; the bound method, the argument
648+
tuple and a `StopIteration` instance are released inside the scope; only the result is handed out.
649+
`Status: implemented` on desktop and Kotlin/Native (commonTest, so every target compiles and runs the
650+
thread-free part), `PM/commonTest/.../pythonx/PyCoroutineStepTest.kt`
651+
(`aCoroutineIsSteppedWithSendValuesUntilItsReturnValueArrivesAndNothingLeaks`,
652+
`eachStepRunsInsideTheGivenContextAndWritesStayInIt`,
653+
`aKotlinThrowableThrownIntoTheCoroutineArrivesMappedAndTheOutcomeIsReported`,
654+
`aFinishedCoroutineAnExhaustedGeneratorAndANonCoroutineAreReportedWithoutLeavingAnErrorIndicator`),
655+
`PM/desktopTest/.../pythonx/PyCoroutineStepThreadTest.kt`
656+
(`eachStepMayRunOnADifferentThreadCPythonNeverSawAndLeavesItDetached`,
657+
`aStepOnAVirtualThreadCompletesAndLeavesTheCarrierDetached`),
658+
`PM/nativeTest/.../pythonx/PyCoroutineStepNativeTest.kt`
659+
(`aStepFromAThreadTheRuntimeNeverAttachedCompletesTheCoroutine`); `planned` on wasm for the thread
660+
claims only (no threads there; the commonTest part runs).
601661
- **U-6** Upcalls work in a GraalVM native image (desktop). `Status: implemented` with manual
602662
verification, procedure and record in `docs/platforms/graal-native-image-verification.md`
603663
(`:sample:nativeCompile`, Liberica NIK), guarded automatically by `ReachabilityMetadataTest.kt` (C-2).

‎docs/design/upcall.md‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -920,9 +920,10 @@ The sample app on both emulators showed:
920920

921921
The last row resumes the parked continuation from a `java.lang.Thread`, as on desktop. (The original record
922922
adds that `pmp_attach` runs on that path too; a `java.lang.Thread` is already known to ART, so that is
923-
(unverified).) The iOS sample cannot yet show that row (a Kotlin/Native completion thread needs a
924-
`Worker` or memory-model decision in the sample; the library's `PythonProxyNativeDeliveryTest` does it with
925-
`pthread_create`).
923+
(unverified).) The iOS sample shows that row from a Kotlin/Native `Worker` since #164 item 11 (2026-11-21):
924+
any thread may resume the parked continuation as long as it holds `withGIL` while it does, and
925+
`AsyncUpcallWorkerDeliveryTest` proves it for a `Worker` as `PythonProxyNativeDeliveryTest` does for a bare
926+
`pthread_create` thread. A `kotlinx.coroutines` dispatcher thread is a `Worker` underneath.
926927

927928
**wasmJs**, the synchronous proxy surface runs (10 of `PythonProxyInstallTest`'s 11); `await` does not yet:
928929

@@ -999,6 +1000,40 @@ exists to avoid.
9991000
after `await()` blocks the loop while it runs. A `ContinuationInterceptor` in the context moves it off
10001001
(`suspendCoroutine` intercepts; `theContinuationIsDispatchedThroughTheCallersInterceptor...`).
10011002

1003+
### 5.10 Stepping a Python coroutine from Kotlin (SPEC U-5e)
1004+
1005+
`PyObject.step(value, context)` and `PyObject.throwInto(exception, context)` (`pythonx/PyCoroutineStep.kt`)
1006+
are the primitive pythonx-concurrent's Kotlin mode (its S7.9) drives a Python coroutine with: one
1007+
`coro.send(value)` or `coro.throw(exc)`, inside `contextvars.Context.run` when the driver names a context,
1008+
as one call that attaches, runs, and detaches. Nothing here uses the table, the binding module or a loop; it
1009+
is the object model plus one exception-mapping helper the trampoline already had.
1010+
1011+
**Why `Context.run`, and why Kotlin code sits between `Ensure` and `Release` at all.** The request reads
1012+
"no Kotlin code between Ensure and Release"; what it needs is that no *user* code and no suspension point
1013+
sit there (S7.10), so a virtual thread stays pinned for exactly one native call and the GIL is never held
1014+
across a park. `PyIter_Send` would be the single-call shape, but it cannot run under a `Context`, and
1015+
`PyContext_Enter` / `PyContext_Exit` are outside the limited API this library binds. So the scope holds a
1016+
handful of library calls: `GetAttrString(coro, "send")`, a one- or two-element tuple, `PyObject_CallObject`
1017+
on `context.run` or on the bound method, and the classification of the outcome. None of them parks.
1018+
1019+
**Outcome classification, and the references.** A non-`NULL` result is `Yielded`, a new reference the
1020+
caller owns. `NULL` with `StopIteration` on the indicator is `Returned`: the instance is taken off the
1021+
indicator (`PyErr_GetRaisedException`, new reference), its `value` attribute read (new reference, owned by
1022+
the caller), the instance released. Any other `NULL` is `Raised`, built by `PyException.fromCurrentError`,
1023+
which clears the indicator. The bound method, the `run` attribute and the argument tuple are released in
1024+
`finally`; the argument is incref'd into the tuple (`PyTuple_SetItem` steals) and the caller keeps its own.
1025+
`throwInto(Throwable)` builds the Python exception with `UpcallTrampoline.pythonExceptionObjectFor` (SPEC
1026+
U-2's mapping, the same instance restoration for a `PyException`) and releases it after the step.
1027+
1028+
**What a driver does with it.** A `Yielded` `asyncio.Future` is subscribed with `call_soon_threadsafe` on
1029+
that future's loop and the Kotlin coroutine suspends on it (S7.9 case 2, the same crossing as S4.5); a
1030+
`Yielded` object of the driver's own (a Kotlin `suspend` call, a channel operation) is awaited in Kotlin;
1031+
anything else is thrown back in with `throwInto(RuntimeError(...))`. A `Raised` whose exception
1032+
`isCancelledError()` is the cancellation signal (`toKotlinException()` gives the `CancellationException`).
1033+
Steps of one coroutine are sequenced by the driver; nothing in the primitive stops a second thread from
1034+
stepping the same coroutine, and CPython answers that with `ValueError: coroutine already executing`, which
1035+
arrives as `Raised`.
1036+
10021037
## 6. Cycle collection is part of the table's job
10031038

10041039
A Python proxy holding a Kotlin object that holds a Python object forms a cycle neither collector can break
@@ -1366,8 +1401,8 @@ Only what is really open; each with what proves the done part.
13661401
6. **Kotlin calling a Python override.** Not implemented (§4.4).
13671402
7. **Per-target gaps outside desktop.** U-3/U-4 are asserted on desktop, with smoke coverage elsewhere
13681403
(`NativeSmokeTest`, `GeneratedAndroidTableTest`); the native async tests have no recorded per-test
1369-
androidNative result (§5.7); no proxy-cost rows for Android/androidNative (§7.5); the iOS sample cannot show
1370-
the really-suspending demo (§5.8).
1404+
androidNative result (§5.7); no proxy-cost rows for Android/androidNative (§7.5). The iOS sample now shows the
1405+
really-suspending demo from a `Worker` (§5.8, #164 item 11).
13711406
8. **`BYTES` marshalling** is per item until `PyBytes_AsStringAndSize` is bound (§3.3).
13721407
9. **Incremental KSP** needs per-file fragments (§2.7). **Transitive and published-artifact discovery** are
13731408
unverified (§2.9).

‎docs/roadmap/ROADMAP.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -292,10 +292,12 @@ trampolines exist. GraalVM native image upcalls are verified by hand
292292
- **13.2 Native-image upcall verification as an automated test, open.** SPEC U-6/N-5: the procedure
293293
is manual (`:sample:nativeCompile`, Liberica NIK); only the reachability metadata is guarded
294294
automatically.
295-
- **13.3 iOS sample section 7, slow path, open (sample only).** "not wired on iOS": resuming a parked
296-
continuation needs a Kotlin/Native worker the sample does not start
297-
(`sample/src/iosMain/.../bindings/ProxyDemo.ios.kt`). The library itself does it
298-
(`PM/nativeTest/.../AsyncUpcallNative*Test.kt`).
295+
- **13.3 iOS sample section 7, slow path, closed (2026-11-21, #164 item 11).** The sample resumes the
296+
parked continuation from a Kotlin/Native `Worker` (`sample/src/iosMain/.../bindings/ProxyDemo.ios.kt`),
297+
the rule is written in SPEC U-5 ("Resuming from a Kotlin/Native thread") and `PM/iosMain/README.md`,
298+
and the library proves it for a `Worker` as well as for a bare pthread
299+
(`PM/nativeTest/.../AsyncUpcallWorkerDeliveryTest.kt`, `AsyncUpcallNative*Test.kt`). The sample's
300+
simulator run itself is still by hand (the ios job builds the ios-consumer fixture, not the sample).
299301
- **13.4 Targets compiled but never tested, open.** `iosArm64`, `iosX64`, `androidNativeX64` (SPEC
300302
P-1). For `iosX64`, `extractIosSimulatorStdlib` hardcodes `lib-arm64`
301303
(`python-multiplatform/build.gradle.kts`, the `…/ios-arm64_x86_64-simulator/lib-arm64/python$libVersion`

0 commit comments

Comments
 (0)