Skip to content

Commit 71a6662

Browse files
authored
Merge pull request #305 from thisisthepy/feat/pmp-gil-release-tests
Binder: GIL release tests beyond 'does not crash' (#162)
2 parents a82e621 + c91294a commit 71a6662

3 files changed

Lines changed: 166 additions & 4 deletions

File tree

‎docs/SPEC.md‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -176,9 +176,13 @@ fail, then implement.
176176
- **C-3** Android binds through `RegisterNatives` with the calling convention chosen per function;
177177
re-entrant functions are never `@CriticalNative`. `Status: implemented`,
178178
`PM/desktopTest/.../ffi/JniCallConventionClassificationTest.kt`, `PM/androidInstrumentedTest/.../JniWiringTest.kt`.
179-
- **C-4** Every C API call holds the GIL. `Status: partial`, enforced by convention and README rules;
180-
the only direct test (`PM/commonTest/.../GilParkingTest.kt`) asserts only "does not crash". Releasing
181-
the GIL after initialisation is not enabled.
179+
- **C-4** Every C API call holds the GIL. `Status: partial`, enforced by convention and README rules.
180+
The GIL is released once `Python3.initialize` returns (it saves the main thread state with
181+
`PyEval_SaveThread`), so every entry into Python goes through `withGIL`, and `withoutGIL` gives it
182+
up while waiting in Kotlin. Tests: `PM/jvmTest/.../ffi/GilReleaseTest.kt` (desktop and Android
183+
instrumented), `PM/nativeTest/.../ffi/GilReleaseNativeTest.kt` (iOS simulator, androidNative); a
184+
second thread runs Python while the first waits in Kotlin, with bounded waits. The "every call holds
185+
the GIL" half has only `PM/commonTest/.../GilParkingTest.kt` (asserts "does not crash").
182186
- **C-5** A thread CPython creates can upcall into ART: it is attached once per thread and detached when
183187
it dies. `Status: implemented` on Android, `PM/androidInstrumentedTest/.../UpcallThreadAttachTest.kt`.
184188
- **C-6** wasm: `Py_ssize_t` boundaries and the `-1` error return are handled at the 32-bit ABI.
@@ -586,7 +590,7 @@ All in `PM/commonTest`, so they run wherever the interpreter loads.
586590
## 7. Threading and builds
587591

588592
- **T-1** GIL builds: Kotlin threads attach a thread state and serialise on the GIL. `Status: partial`
589-
(see C-4).
593+
(see C-4; the release after initialisation is tested by `GilReleaseTest` / `GilReleaseNativeTest`).
590594
- **T-1a** On desktop, entering Python from a JVM virtual thread (the outermost `withGIL`) raises
591595
`IllegalStateException` before `PyGILState_Ensure`: the GIL thread state is bound to the OS carrier
592596
thread, and a virtual thread can unmount and resume on another carrier inside the scope. Run Python on
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package python.multiplatform.ffi
2+
3+
import java.util.concurrent.CountDownLatch
4+
import java.util.concurrent.TimeUnit
5+
import java.util.concurrent.atomic.AtomicReference
6+
import kotlin.test.Test
7+
import kotlin.test.assertEquals
8+
import kotlin.test.assertNull
9+
import kotlin.test.assertTrue
10+
11+
/**
12+
* SPEC C-4 / T-1: the GIL is released once [Python3.initialize] returns (it saves the main thread
13+
* state), so a second Kotlin thread can run Python while the first waits in Kotlin.
14+
*
15+
* `jvmTest` is shared by `desktopTest` and `androidInstrumentedTest`, so one file covers both.
16+
* Modelled on `PyTypeCacheConcurrencyTest` (desktopTest) for the thread and latch shape and on
17+
* `PythonTestFixture.withInterpreter` for the interpreter set-up.
18+
*
19+
* Every wait is bounded. If the GIL were still held, the second thread would block in
20+
* `PyGILState_Ensure`, the bounded wait would time out and the assertion would fail; nothing
21+
* waits forever on the thread that is blocked.
22+
*
23+
* Negative control (deliberately not a test, it would hang on a GIL build): thread A waiting inside
24+
* `withGIL` WITHOUT `withoutGIL` keeps the GIL, so B could never get in.
25+
*/
26+
class GilReleaseTest {
27+
28+
private val timeoutSeconds = 20L
29+
30+
/** Runs `6 * 7` under the GIL on a new thread; the answer or failure lands in [result]/[error]. */
31+
private fun pythonThread(done: CountDownLatch, result: AtomicReference<String?>, error: AtomicReference<Throwable?>) =
32+
Thread {
33+
try {
34+
result.set(withGIL { PythonTestFixture.eval("6 * 7").toString() })
35+
} catch (t: Throwable) {
36+
error.set(t)
37+
} finally {
38+
done.countDown()
39+
}
40+
}.apply { isDaemon = true }
41+
42+
@Test
43+
fun secondThreadRunsPythonWhileTheInitialisingThreadWaitsInKotlin() = PythonTestFixture.withInterpreter {
44+
// The initialising thread is not inside withGIL here: it only waits in Kotlin.
45+
val done = CountDownLatch(1)
46+
val result = AtomicReference<String?>(null)
47+
val error = AtomicReference<Throwable?>(null)
48+
pythonThread(done, result, error).start()
49+
val finished = done.await(timeoutSeconds, TimeUnit.SECONDS)
50+
assertTrue(finished, "second thread could not run Python: the GIL is still held after initialisation")
51+
assertNull(error.get(), "second thread failed: ${error.get()}")
52+
assertEquals("42", result.get())
53+
}
54+
55+
@Test
56+
fun withoutGilLetsAnotherThreadRunPythonWhileThisOneWaits() = PythonTestFixture.withInterpreter {
57+
val done = CountDownLatch(1)
58+
val result = AtomicReference<String?>(null)
59+
val error = AtomicReference<Throwable?>(null)
60+
val b = pythonThread(done, result, error)
61+
var observed = false
62+
withGIL {
63+
b.start()
64+
// Wait in Kotlin with the GIL given up; no Python call inside this block.
65+
observed = withoutGIL { done.await(timeoutSeconds, TimeUnit.SECONDS) }
66+
// The GIL is held again here, so B (if it was stuck) can only proceed after we leave.
67+
}
68+
b.join(TimeUnit.SECONDS.toMillis(timeoutSeconds))
69+
assertTrue(observed, "B did not finish while A waited in withoutGIL: withoutGIL did not release the GIL")
70+
assertNull(error.get(), "B failed: ${error.get()}")
71+
assertEquals("42", result.get())
72+
}
73+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package python.multiplatform.ffi
2+
3+
import platform.posix.usleep
4+
import python.multiplatform.ffi.upcall.NativeThread
5+
import kotlin.concurrent.AtomicInt
6+
import kotlin.concurrent.AtomicReference
7+
import kotlin.test.Test
8+
import kotlin.test.assertEquals
9+
import kotlin.test.assertNull
10+
import kotlin.test.assertTrue
11+
import kotlin.time.Duration.Companion.seconds
12+
import kotlin.time.TimeSource
13+
14+
/**
15+
* SPEC C-4 / T-1 on Kotlin/Native (iOS simulator, androidNative): the GIL is released once
16+
* [Python3.initialize] returns, so a second thread can run Python while the first waits in Kotlin.
17+
* The mirror of `jvmTest`'s `GilReleaseTest`.
18+
*
19+
* Modelled on `AsyncUpcallNativeDeliveryTest` (nativeTest): same [NativeThread] (a bare
20+
* `pthread_create`) and the same `PythonTestFixture` interpreter set-up.
21+
*
22+
* Every wait is bounded by [waitFor]. If the GIL were still held the second thread would block in
23+
* `PyGILState_Ensure`; the bounded wait expires and the assertion fails. A thread that never got in
24+
* is deliberately not joined (that join would hang); the process ends the test run.
25+
*
26+
* Negative control (not a test, it would hang on a GIL build): thread A waiting inside `withGIL`
27+
* without `withoutGIL` keeps the GIL, so B could never get in.
28+
*/
29+
class GilReleaseNativeTest {
30+
31+
private val timeout = 20.seconds
32+
33+
private fun waitFor(flag: AtomicInt): Boolean {
34+
val mark = TimeSource.Monotonic.markNow()
35+
while (flag.value == 0) {
36+
if (mark.elapsedNow() > timeout) return false
37+
usleep(1000u)
38+
}
39+
return true
40+
}
41+
42+
private class Outcome {
43+
val done = AtomicInt(0)
44+
val result = AtomicReference<String?>(null)
45+
val error = AtomicReference<String?>(null)
46+
}
47+
48+
private fun pythonThread(o: Outcome) = NativeThread {
49+
try {
50+
o.result.value = withGIL { PythonTestFixture.eval("6 * 7").toString() }
51+
} catch (t: Throwable) {
52+
o.error.value = t.toString()
53+
} finally {
54+
o.done.value = 1
55+
}
56+
}
57+
58+
@Test
59+
fun secondThreadRunsPythonWhileTheInitialisingThreadWaitsInKotlin() = PythonTestFixture.withInterpreter {
60+
val o = Outcome()
61+
val b = pythonThread(o)
62+
b.start()
63+
val finished = waitFor(o.done)
64+
assertTrue(finished, "second thread could not run Python: the GIL is still held after initialisation")
65+
b.join()
66+
assertNull(o.error.value, "second thread failed: ${o.error.value}")
67+
assertEquals("42", o.result.value)
68+
}
69+
70+
@Test
71+
fun withoutGilLetsAnotherThreadRunPythonWhileThisOneWaits() = PythonTestFixture.withInterpreter {
72+
val o = Outcome()
73+
val b = pythonThread(o)
74+
var observed = false
75+
withGIL {
76+
b.start()
77+
// Wait in Kotlin with the GIL given up; no Python call inside this block.
78+
observed = withoutGIL { waitFor(o.done) }
79+
}
80+
assertTrue(observed, "B did not finish while A waited in withoutGIL: withoutGIL did not release the GIL")
81+
b.join()
82+
assertNull(o.error.value, "B failed: ${o.error.value}")
83+
assertEquals("42", o.result.value)
84+
}
85+
}

0 commit comments

Comments
 (0)