Skip to content

Commit fdce2cb

Browse files
authored
Merge pull request #469 from thisisthepy/feat/164-exception-mapping
Feat: map CancellationException and CancelledError across upcalls and preserve Kotlin cause (#164)
2 parents d744646 + 0363a9b commit fdce2cb

7 files changed

Lines changed: 382 additions & 19 deletions

File tree

‎docs/SPEC.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,10 @@ All in `PM/commonTest`, so they run wherever the interpreter loads.
222222
- **O-2** `PyType`: name, bases, MRO, `isSubtypeOf`, `isInstance`, construct by call, `cast` refuses an
223223
incompatible object. `Status: implemented`, `PyTypeTest.kt`.
224224
- **O-3** `PyException` is a Kotlin `Throwable` carrying the Python exception type and message.
225+
`PyException.isCancelledError()` is `true` when the underlying Python exception is an instance of
226+
`asyncio.CancelledError` (`concurrent.futures.CancelledError`), and `PyException.toKotlinException()`
227+
returns a `kotlin.coroutines.cancellation.CancellationException` with `this` as its `cause` for a
228+
cancelled error and `this` otherwise (#164).
225229
`Status: implemented`, `PyExceptionTest.kt`.
226230
- **O-4** Basic types `PyInt`, `PyFloat`, `PyBool`, `PyString`, `PyNone`, bytes round-trip with Kotlin
227231
values. `Status: implemented`, `PyBasicTypesTest.kt`, `PyValueBytesConversionTest.kt`.
@@ -265,6 +269,19 @@ All in `PM/commonTest`, so they run wherever the interpreter loads.
265269
`python-multiplatform-ksp/fixtures/app/src/desktopTest/.../GeneratedTableTest.kt`, `python-multiplatform-ksp/src/test/.../SourceRenderingTest.kt`.
266270
- **U-2** One entry point per platform marshals arguments (int, float, bool, str, bytes with NUL,
267271
objects), turns a Kotlin exception into a Python exception and a `Unit` return into `None`.
272+
Exception mapping across the upcall boundary (#164):
273+
- a `PyException` with a live Python exception value (`value != null`), or a Kotlin
274+
`CancellationException` whose `cause` is a `PyException` with `isCancelledError() == true` and a live
275+
`value`, restores that original Python exception unchanged;
276+
- a Kotlin `kotlin.coroutines.cancellation.CancellationException` maps to Python's
277+
`asyncio.CancelledError` (leaving any exception Python already raised on the indicator untouched; on a
278+
target where `asyncio` cannot be imported, it falls back to `RuntimeError`);
279+
- any other Kotlin `Throwable` maps to `RuntimeError(message)` with `__cause__` set to a `BaseException`
280+
representing the original Kotlin throwable (`"<KotlinSimpleClassName>: <message>"`, recursively chaining
281+
Kotlin `cause` onto `__cause__`, or restoring a nested `PyException` cause's live `value` as `__cause__`).
282+
When Python raises `asyncio.CancelledError` inside a callback or C API call invoked by `UpcallTrampoline`,
283+
`UpcallTrampoline` throws `kotlin.coroutines.cancellation.CancellationException` with the `PyException` as
284+
its `cause` into Kotlin.
268285
`Status: implemented`, `PM/commonTest/.../UpcallEntryTest.kt`, `UpcallTrampolineTest.kt`,
269286
`PM/nativeTest/.../UpcallRawEntryPointTest.kt`.
270287
- **U-3** Generated Python proxies let Python write ordinary Python against Kotlin: construct a class,
@@ -308,6 +325,11 @@ All in `PM/commonTest`, so they run wherever the interpreter loads.
308325
`python-multiplatform-compose/fixtures/compose/.../ProxyClassArgumentRenderTest.kt`.
309326
- **U-5** `suspend` functions are awaitable from Python (`await g.greetNow(1)`); a function that never
310327
suspends completes without a Future; cancelling the Python future cancels the Kotlin coroutine.
328+
A failure in a `suspend` function (before or after suspension) applies U-2's exception mapping (#164):
329+
a Kotlin `CancellationException` thrown by the coroutine when the Python `Future` is not already settled
330+
delivers `asyncio.CancelledError` (with any Kotlin `cause` attached as `__cause__`) to the awaiting
331+
coroutine, while any other Kotlin `Throwable` delivers `RuntimeError(message)` with the original Kotlin
332+
throwable attached as `__cause__`.
311333
`Status: implemented` on desktop and Kotlin/Native, `PM/desktopTest/.../upcall/AsyncUpcallDeliveryTest.kt`,
312334
`AsyncUpcallCancellationTest.kt`, `AsyncUpcallEarlyCancellationTest.kt`, `PM/nativeTest/.../AsyncUpcallNative*Test.kt`,
313335
`python-multiplatform-ksp/fixtures/app/.../GeneratedSuspendTest.kt`; `planned` on wasm (no threads).

‎python-multiplatform/src/commonMain/kotlin/python/multiplatform/ffi/exceptions/PyException.kt‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package python.multiplatform.ffi.exceptions
33
import python.multiplatform.ffi.PyObject
44
import python.multiplatform.ffi.PyType
55
import python.multiplatform.ffi.adoptingNewReference
6+
import kotlin.coroutines.cancellation.CancellationException
67
import python.native.ffi.NativePointer
78
import python.native.ffi.PyErr_Clear
89
import python.native.ffi.PyErr_GetRaisedException
@@ -204,4 +205,30 @@ open class PyException(
204205
// meaningful error indicator to set.
205206
}
206207
}
208+
209+
/**
210+
* `true` when this exception represents Python's `asyncio.CancelledError`
211+
* (`concurrent.futures.CancelledError`, which `asyncio.CancelledError` aliases in CPython).
212+
*
213+
* Checked along [type]'s MRO so subclasses of `CancelledError` are recognised too; when no
214+
* live [type] is attached, returns `false`.
215+
*/
216+
fun isCancelledError(): Boolean {
217+
val liveType = type ?: return false
218+
return try {
219+
liveType.name == CANCELLED_ERROR_NAME || liveType.mro.any { it.name == CANCELLED_ERROR_NAME }
220+
} catch (_: Throwable) {
221+
false
222+
}
223+
}
224+
225+
/**
226+
* Maps a Python `CancelledError` ([isCancelledError]) to a Kotlin [CancellationException]
227+
* carrying `this` as its [Throwable.cause], leaving every other [PyException] as itself
228+
* (SPEC O-3, U-2; issue #164).
229+
*/
230+
fun toKotlinException(): Exception =
231+
if (isCancelledError()) CancellationException(errMsg, this) else this
207232
}
233+
234+
private const val CANCELLED_ERROR_NAME = "CancelledError"

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

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -287,15 +287,10 @@ internal object AsyncUpcall {
287287
/**
288288
* The Python exception instance `set_exception` needs.
289289
*
290-
* A [PyException] carries the original Python exception it was built from, so a Python error
291-
* that crossed into Kotlin and back out again reaches the awaiting coroutine as *itself*,
292-
* traceback and type intact, rather than as a `RuntimeError` wrapping its message. Anything
293-
* else becomes a `RuntimeError` with the Kotlin message, which is the same mapping
294-
* [UpcallTrampoline]'s synchronous failure path uses.
290+
* Delegates to [UpcallTrampoline.pythonExceptionObjectFor] so a failure after suspension maps to
291+
* the exact same Python exception type and `__cause__` chain as a synchronous failure or a
292+
* failure before the first suspension point (SPEC U-2, U-5; issue #164).
295293
*/
296-
private fun pythonExceptionFor(failure: Throwable): PyObject {
297-
if (failure is PyException) failure.value?.let { return it }
298-
val message = failure.message ?: failure::class.simpleName ?: "the exposed suspending function failed"
299-
return UpcallTrampoline.runtimeErrorClass().invoke(PyString.from(message))
300-
}
294+
private fun pythonExceptionFor(failure: Throwable): PyObject =
295+
UpcallTrampoline.pythonExceptionObjectFor(failure)
301296
}

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

Lines changed: 167 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package python.multiplatform.ffi.upcall
22

33
import python.multiplatform.ffi.PyLong_Check
44
import python.multiplatform.ffi.PyObject
5+
import python.multiplatform.ffi.exceptions.PyException
56
import python.multiplatform.ffi.getThreadGILState
67
import python.multiplatform.ffi.types.basic.PyNone
78
import python.multiplatform.reflection.CallableHandle
@@ -10,20 +11,26 @@ import python.multiplatform.reflection.HandleTable
1011
import python.multiplatform.reflection.ObjectReference
1112
import python.multiplatform.reflection.TypeTag
1213
import python.multiplatform.reflection.UpcallTable
14+
import kotlin.coroutines.cancellation.CancellationException
1315
import python.native.ffi.NativePointer
1416
import python.native.ffi.PyBool_FromLong
1517
import python.native.ffi.PyBytes_FromObject
1618
import python.native.ffi.PyDict_GetItemString
1719
import python.native.ffi.PyErr_Clear
1820
import python.native.ffi.PyErr_Occurred
21+
import python.native.ffi.PyErr_SetRaisedException
1922
import python.native.ffi.PyErr_SetString
2023
import python.native.ffi.PyEval_GetBuiltins
24+
import python.native.ffi.PyException_SetCause
2125
import python.native.ffi.PyFloat_AsDouble
2226
import python.native.ffi.PyGILState_Ensure
2327
import python.native.ffi.PyGILState_Release
2428
import python.native.ffi.PyFloat_FromDouble
29+
import python.native.ffi.PyImport_ImportModule
2530
import python.native.ffi.PyLong_AsLongLong
2631
import python.native.ffi.PyLong_FromLongLong
32+
import python.native.ffi.PyObject_CallObject
33+
import python.native.ffi.PyObject_GetAttrString
2734
import python.native.ffi.PyObject_GetItem
2835
import python.native.ffi.PyObject_IsTrue
2936
import python.native.ffi.PyObject_Size
@@ -379,19 +386,173 @@ object UpcallTrampoline {
379386
private fun raiseInPython(t: Throwable) {
380387
try {
381388
if (PyErr_Occurred() != null) return
382-
val message = t.message ?: t::class.simpleName ?: "upcall failed"
383-
PyErr_SetString(runtimeErrorType, message)
389+
val excPtr = buildPythonExceptionPointer(t)
390+
if (excPtr != null) {
391+
PyErr_SetRaisedException(excPtr)
392+
} else {
393+
val message = t.message ?: t::class.simpleName ?: "upcall failed"
394+
PyErr_SetString(runtimeErrorType, message)
395+
}
384396
} catch (_: Throwable) {
385397
// Reporting the failure failed. Returning NULL with no indicator set is still a
386398
// Python-level error ("SystemError: returned NULL without setting an exception"),
387399
// which is strictly better than unwinding into C.
388400
}
389401
}
390402

403+
/**
404+
* Builds a **new** reference to the Python `BaseException` instance [t] maps to (SPEC U-2, U-5;
405+
* issue #164). Caller must hold the GIL.
406+
*
407+
* - A [PyException] with a live [PyException.value] returns an incremented reference to that
408+
* original Python exception instance.
409+
* - A Kotlin [CancellationException] whose [Throwable.cause] is a [PyException] with
410+
* [PyException.isCancelledError] and a live value returns an incremented reference to that
411+
* original Python `CancelledError`.
412+
* - Any other Kotlin [CancellationException] builds an `asyncio.CancelledError`
413+
* (`concurrent.futures.CancelledError`), attaching any non-null [Throwable.cause] as
414+
* `__cause__`.
415+
* - Any other Kotlin [Throwable] builds a `RuntimeError(message)` and attaches a cause chain
416+
* representing [t] (and its nested [Throwable.cause] chain) onto `__cause__`.
417+
*/
418+
internal fun buildPythonExceptionPointer(t: Throwable): NativePointer? {
419+
if (t is PyException) {
420+
val liveValue = t.value
421+
if (liveValue != null) {
422+
Py_IncRef(liveValue.pointer)
423+
return liveValue.pointer
424+
}
425+
}
426+
if (t is CancellationException) {
427+
val pyCause = t.cause as? PyException
428+
if (pyCause != null && pyCause.isCancelledError()) {
429+
val liveValue = pyCause.value
430+
if (liveValue != null) {
431+
Py_IncRef(liveValue.pointer)
432+
return liveValue.pointer
433+
}
434+
}
435+
val message = t.message ?: t::class.simpleName ?: "the Kotlin call was cancelled"
436+
val cancelledType = resolveCancelledErrorType()
437+
val excType = cancelledType ?: runtimeErrorType
438+
val excPtr = instantiateException(excType, message)
439+
if (cancelledType != null) Py_DecRef(cancelledType)
440+
if (excPtr == null) return null
441+
val kotlinCause = t.cause
442+
if (kotlinCause != null) {
443+
val causePtr = buildKotlinCausePointer(kotlinCause, depth = 0)
444+
if (causePtr != null) {
445+
PyException_SetCause(excPtr, causePtr)
446+
}
447+
}
448+
return excPtr
449+
}
450+
val message = t.message ?: t::class.simpleName ?: "upcall failed"
451+
val excPtr = instantiateException(runtimeErrorType, message) ?: return null
452+
val causePtr = buildKotlinCausePointer(t, depth = 0)
453+
if (causePtr != null) {
454+
PyException_SetCause(excPtr, causePtr)
455+
}
456+
return excPtr
457+
}
458+
459+
/**
460+
* Wraps [buildPythonExceptionPointer] as an owned [PyObject] for [AsyncUpcall]'s
461+
* `Future.set_exception`, falling back to `RuntimeError(message)` if construction fails.
462+
*/
463+
internal fun pythonExceptionObjectFor(t: Throwable): PyObject {
464+
val ptr = buildPythonExceptionPointer(t)
465+
if (ptr != null) return PyObject(ptr, borrowed = false)
466+
val message = t.message ?: t::class.simpleName ?: "the exposed suspending function failed"
467+
return runtimeErrorClass().invoke(python.multiplatform.ffi.types.basic.PyString.from(message))
468+
}
469+
470+
/**
471+
* Builds a **new** reference to the `BaseException` placed on `__cause__` for a Kotlin
472+
* [Throwable] (SPEC U-2, issue #164).
473+
*/
474+
private fun buildKotlinCausePointer(t: Throwable, depth: Int): NativePointer? {
475+
if (depth >= MAX_CAUSE_DEPTH) return null
476+
if (t is PyException) {
477+
val liveValue = t.value
478+
if (liveValue != null) {
479+
Py_IncRef(liveValue.pointer)
480+
return liveValue.pointer
481+
}
482+
}
483+
val className = t::class.simpleName ?: "Throwable"
484+
val msg = t.message
485+
val summary = if (msg.isNullOrEmpty()) className else "$className: $msg"
486+
val causePtr = instantiateException(runtimeErrorType, summary) ?: return null
487+
val nested = t.cause
488+
if (nested != null && nested !== t) {
489+
val nestedPtr = buildKotlinCausePointer(nested, depth + 1)
490+
if (nestedPtr != null) {
491+
PyException_SetCause(causePtr, nestedPtr)
492+
}
493+
}
494+
return causePtr
495+
}
496+
497+
/** Calls `excType(message)` and returns the new exception reference, clearing any error on failure. */
498+
private fun instantiateException(excType: NativePointer, message: String): NativePointer? {
499+
val msgPtr = PyUnicode_FromString(message) ?: run {
500+
PyErr_Clear()
501+
return null
502+
}
503+
val tuple = PyTuple_New(1) ?: run {
504+
Py_DecRef(msgPtr)
505+
PyErr_Clear()
506+
return null
507+
}
508+
// PyTuple_SetItem steals msgPtr.
509+
PyTuple_SetItem(tuple, 0, msgPtr)
510+
val instance = try {
511+
PyObject_CallObject(excType, tuple)
512+
} finally {
513+
Py_DecRef(tuple)
514+
}
515+
if (instance == null) {
516+
PyErr_Clear()
517+
}
518+
return instance
519+
}
520+
521+
/**
522+
* Resolves Python's `CancelledError` type as a **new** reference by importing
523+
* `concurrent.futures._base` (pure Python, does not load `selectors`, so it is safe on every
524+
* target including `wasmJs`; in CPython 3.8+, `asyncio.CancelledError` is
525+
* `concurrent.futures.CancelledError`). Caller must `Py_DecRef` the returned non-null pointer.
526+
*/
527+
private fun resolveCancelledErrorType(): NativePointer? {
528+
val mod = PyImport_ImportModule("concurrent.futures._base")
529+
?: run {
530+
PyErr_Clear()
531+
PyImport_ImportModule("asyncio.exceptions")
532+
}
533+
?: run {
534+
PyErr_Clear()
535+
return null
536+
}
537+
return try {
538+
val attr = PyObject_GetAttrString(mod, "CancelledError")
539+
if (attr == null) {
540+
PyErr_Clear()
541+
null
542+
} else {
543+
attr
544+
}
545+
} finally {
546+
Py_DecRef(mod)
547+
}
548+
}
549+
550+
private const val MAX_CAUSE_DEPTH = 16
551+
391552
/** Raises whatever Python already put on the indicator as a Kotlin exception, or a fallback. */
392553
private fun failFromPython(what: String): Nothing {
393-
val pending = python.multiplatform.ffi.exceptions.PyException.fromCurrentError()
394-
throw pending ?: IllegalArgumentException(what)
554+
val pending = PyException.fromCurrentError()
555+
throw pending?.toKotlinException() ?: IllegalArgumentException(what)
395556
}
396557

397558
/**
@@ -400,9 +561,9 @@ object UpcallTrampoline {
400561
*/
401562
private fun checkPythonError(what: String) {
402563
if (PyErr_Occurred() == null) return
403-
val pending = python.multiplatform.ffi.exceptions.PyException.fromCurrentError()
564+
val pending = PyException.fromCurrentError()
404565
PyErr_Clear()
405-
throw pending ?: IllegalArgumentException(what)
566+
throw pending?.toKotlinException() ?: IllegalArgumentException(what)
406567
}
407568

408569
// ---------------------------------------------------------------------------------------

‎python-multiplatform/src/commonTest/kotlin/python/multiplatform/ffi/exceptions/PyExceptionTest.kt‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,14 @@ import python.multiplatform.ffi.Python3
44
import python.multiplatform.ffi.PythonTestFixture
55
import python.multiplatform.ffi.exceptions.errors.PyTypeError
66
import python.multiplatform.ffi.exceptions.errors.PyValueError
7+
import kotlin.coroutines.cancellation.CancellationException
78
import kotlin.test.Test
89
import kotlin.test.assertEquals
910
import kotlin.test.assertFailsWith
11+
import kotlin.test.assertFalse
1012
import kotlin.test.assertNotNull
13+
import kotlin.test.assertSame
14+
import kotlin.test.assertTrue
1115

1216
/**
1317
* Functional tests establishing that a Python-level error surfaces as a Kotlin
@@ -68,4 +72,29 @@ class PyExceptionTest {
6872
fun valueErrorHasTheExpectedPythonTypeName() {
6973
assertEquals("ValueError", PyValueError.PYTHON_TYPE_NAME)
7074
}
75+
76+
@Test
77+
fun isCancelledErrorRecognisesConcurrentFuturesCancelledErrorAndToKotlinExceptionMapsItToCancellationException() =
78+
PythonTestFixture.withInterpreter {
79+
val thrown = assertFailsWith<PyException> {
80+
Python3.exec("import concurrent.futures; raise concurrent.futures.CancelledError('stop now')")
81+
}
82+
assertTrue(thrown.isCancelledError(), "CancelledError must be recognised by isCancelledError()")
83+
val mapped = thrown.toKotlinException()
84+
assertTrue(
85+
mapped is CancellationException,
86+
"toKotlinException() on a CancelledError must return a Kotlin CancellationException, got $mapped",
87+
)
88+
assertEquals("stop now", mapped.message)
89+
assertSame(thrown, mapped.cause, "the mapped CancellationException must keep the PyException as its cause")
90+
}
91+
92+
@Test
93+
fun nonCancelledPyExceptionToKotlinExceptionReturnsItself() = PythonTestFixture.withInterpreter {
94+
val thrown = assertFailsWith<PyException> {
95+
Python3.exec("raise ValueError('bad input')")
96+
}
97+
assertFalse(thrown.isCancelledError(), "ValueError must not be treated as a CancelledError")
98+
assertSame(thrown, thrown.toKotlinException())
99+
}
71100
}

0 commit comments

Comments
 (0)