Debian Codegraph @

src/test/python/jpy_cleanup_thread_test.py

raw symbols SCIP
1 """
2 jpy_cleanup_thread_test.py
3 ==========================
4 Stress tests for the PyObject cleanup daemon thread.
5
6 Background
7 ----------
8 When a Java PyObject wrapper becomes unreachable, the cleanup daemon
9 (PyObject-cleanup) drains the ReferenceQueue and calls Py_DECREF on the
10 underlying Python objects in batches via PyLib.decRefs().
11
12 The daemon calls ``ReferenceQueue.remove(passive_sleep_millis)`` to block
13 until work arrives, waking up immediately when references are enqueued.
14
15 Test strategy
16 -------------
17 * **High-throughput path** (tests 03–06): flood the ReferenceQueue with
18 FLOOD = 20 000 objects — far more than the batch buffer (default 4 096).
19 The daemon loops continuously without sleeping, exercising sustained
20 high-throughput draining.
21 * **Passive path** (test 07): release a small batch (SMALL = 100, well below
22 the buffer) and assert that cleanup completes well within the 1 000 ms
23 passive timeout, proving the daemon wakes on the event rather than waiting
24 out the full timeout.
25 * **OOM-triggered GC** (test 08): release PyObjects without calling
26 System.gc(), then trigger an OOM via ``jpy.array``. The mandatory
27 pre-OOM full GC enqueues the WeakRefs organically. The cleanup thread
28 must survive and drain correctly under OOM conditions.
29
30 All tests verify correctness (no leak, no double-free) and robustness under
31 sustained load.
32 """
33
34 import threading
35 import time
36 import unittest
37
38 import jpyutil
39
40 jpyutil.init_jvm(
41 jvm_maxmem='256M',
42 jvm_classpath=['target/classes', 'target/test-classes'],
43 )
44 import jpy
45
46 # Cache Java types at import time — jpy.get_type() may fail after an OOM
47 # because the internal lookup itself requires heap allocation.
48 _System = jpy.get_type('java.lang.System')
49 _Runtime = jpy.get_type('java.lang.Runtime')
50
51
52 # DEFAULT_BATCH_CLOSE_SIZE = 4096; flooding with FLOOD objects forces the
53 # daemon to make FLOOD/4096 consecutive passes without sleeping.
54 FLOOD = 20_000
55 TIMEOUT = 10.0 # seconds: generous upper bound for daemon to drain FLOOD objects
56
57 # ── Destruction tracking ──────────────────────────────────────────────────────
58 # Counters must be safe to update from Trackable.__del__ on both GIL and
59 # free-threaded CPython.
60 #
61 # A "safe point" is a place where the interpreter may pause a thread to run
62 # bookkeeping — signals, scheduled callbacks, GC, and (on free-threaded
63 # builds) draining queued cross-thread Py_DECREFs. Threads reach safe points
64 # at the eval-breaker check on CALL/RETURN/JUMP_BACKWARD bytecodes and
65 # whenever a primitive blocks (a contended Python-level lock, a thread-state
66 # detach for a blocking call). Guarding an incrementing counter with a lock
67 # inside __del__ can therefore drain queued decrefs while the lock is being
68 # acquired, calling more __del__s recursively and causing RecursionError.
69 #
70 # We therefore need a counter that is atomic without taking any
71 # Python-level lock. list.append(None) / len() satisfies both:
72 # * GIL Python — both are single C calls under the GIL → atomic.
73 # * Free-threaded — list.append() uses the list's per-object critical
74 # section, which is a safe point only on contention. The cleanup daemon
75 # defers Py_DECREF back to the owning thread, so each counter has a
76 # single writer and the critical section stays uncontested.
77 #
78 # When CPython gh-124366 lands a thread-safe atomic counter, this idiom can
79 # be replaced with that API.
80
81 _created = []
82 _destroyed = []
83
84
85 class Trackable:
86 """Python object that counts constructions and destructions thread-safely."""
87
88 def __init__(self):
89 _created.append(None)
90
91 def __del__(self):
92 _destroyed.append(None)
93
94
95 def _make_trackable():
96 return Trackable()
97
98
99 def _reset():
100 _created.clear()
101 _destroyed.clear()
102
103
104 def _counts():
105 return len(_created), len(_destroyed)
106
107
108 # ── Helpers ───────────────────────────────────────────────────────────────────
109
110 def gc_java(n=3):
111 """Request Java GC to enqueue WeakReferences promptly.
112
113 WeakReferences are enqueued by System.gc() alone — no finalizer involvement.
114 System.runFinalization() is deprecated for removal since Java 18 (JEP 421)
115 and is not needed here. _System is cached at import time so this function
116 is safe to call even after an OutOfMemoryError.
117 """
118 for _ in range(n):
119 _System.gc()
120
121
122 def wait_until_cleaned(expected, timeout=TIMEOUT):
123 """Poll until destroyed == expected or timeout expires."""
124 deadline = time.monotonic() + timeout
125 while time.monotonic() < deadline:
126 _, destroyed = _counts()
127 if destroyed >= expected:
128 return
129 time.sleep(0.1)
130
131
132 # ── Tests ─────────────────────────────────────────────────────────────────────
133
134 class TestCleanupThreadStress(unittest.TestCase):
135
136 def setUp(self):
137 _reset()
138 self.Fixture = jpy.get_type('org.jpy.fixtures.CleanupThreadTestFixture')
139 self.PyObjectClass = jpy.get_type('org.jpy.PyObject')
140 self.fixture = self.Fixture()
141
142 def _drain(self):
143 # Release any objects still held by the fixture and drain the cleanup
144 # queue before the next test resets the counters. Without this,
145 # objects from one test bleed into the next test's destroyed count.
146 self.fixture.releaseAll()
147 gc_java()
148 created, _ = _counts()
149 wait_until_cleaned(created)
150
151 def test_01_daemon_thread_starts_and_is_alive(self):
152 """Daemon thread must start after the first PyObject is created from JNI."""
153 self.fixture.holdPyObjects(_make_trackable, 1)
154
155 self.assertTrue(
156 self.Fixture.isCleanupThreadAlive(),
157 "PyObject-cleanup daemon thread is not alive after PyObject creation",
158 )
159 self._drain()
160
161 def test_02_held_java_refs_prevent_python_deallocation(self):
162 """While Java holds PyObject wrappers the Python objects must not be freed."""
163 self.fixture.holdPyObjects(_make_trackable, FLOOD)
164
165 created, destroyed = _counts()
166 self.assertEqual(created, FLOOD)
167 self.assertEqual(destroyed, 0,
168 f"{destroyed} objects freed while Java still held references")
169 self._drain()
170
171 def test_03_daemon_drains_single_large_flood(self):
172 """Daemon must free all objects from a single large burst.
173
174 FLOOD >> buffer size forces multiple consecutive passes without sleeping,
175 exercising the high-throughput draining path.
176 """
177 self.fixture.holdPyObjects(_make_trackable, FLOOD)
178 self.fixture.releaseAll()
179 gc_java()
180
181 wait_until_cleaned(FLOOD)
182
183 created, destroyed = _counts()
184 self.assertEqual(destroyed, FLOOD,
185 f"Single flood: expected {FLOOD} freed, got {destroyed} "
186 f"(leaked {FLOOD - destroyed})")
187
188 def test_04_daemon_handles_repeated_sequential_floods(self):
189 """No accumulation or leakage across multiple release cycles."""
190 CYCLES = 5
191
192 for cycle in range(1, CYCLES + 1):
193 self.fixture.holdPyObjects(_make_trackable, FLOOD)
194 self.fixture.releaseAll()
195 gc_java()
196
197 expected = FLOOD * cycle
198 wait_until_cleaned(expected)
199
200 _, destroyed = _counts()
201 self.assertEqual(destroyed, expected,
202 f"Cycle {cycle}: expected {expected} freed, got {destroyed}")
203
204 def test_05_daemon_keeps_up_under_concurrent_load(self):
205 """Daemon drains correctly while Python releases new batches concurrently."""
206 BURSTS = 5
207 errors = []
208
209 def release_loop():
210 try:
211 for _ in range(BURSTS):
212 self.fixture.holdPyObjects(_make_trackable, FLOOD)
213 self.fixture.releaseAll()
214 gc_java(n=1)
215 except Exception as exc:
216 errors.append(exc)
217
218 t = threading.Thread(target=release_loop, daemon=True)
219 t.start()
220 t.join()
221
222 self.assertEqual(errors, [], f"Exception in release loop: {errors}")
223
224 total = FLOOD * BURSTS
225 wait_until_cleaned(total, timeout=TIMEOUT * BURSTS)
226
227 created, destroyed = _counts()
228 self.assertEqual(created, total)
229 self.assertEqual(destroyed, total,
230 f"Concurrent load: {created} created, {destroyed} freed")
231
232
233 def test_06_explicit_cleanup_and_daemon_do_not_double_decrement(self):
234 """PyObject.cleanup() racing with the daemon must not double-decrement.
235
236 Thread-safety is guaranteed by ReferenceQueue's internal lock — each
237 reference is dequeued exactly once regardless of how many callers race.
238 """
239 self.fixture.holdPyObjects(_make_trackable, FLOOD)
240 self.fixture.releaseAll()
241 gc_java()
242
243 # Race: explicit cleanup() from Python thread while daemon also runs.
244 for _ in range(20):
245 self.PyObjectClass.cleanup()
246 time.sleep(0.02)
247
248 wait_until_cleaned(FLOOD)
249
250 created, destroyed = _counts()
251 self.assertEqual(created, FLOOD)
252 self.assertEqual(destroyed, FLOOD,
253 f"Race: {created} created, {destroyed} freed "
254 f"(expected exactly {FLOOD})")
255
256
257 def test_07_passive_path_wakes_up_promptly(self):
258 """Small batch is cleaned up promptly via the blocking ReferenceQueue.remove() path.
259
260 A batch of SMALL objects (well below the buffer size of 4096) is released
261 and we assert that cleanup completes well within the default 1 000 ms
262 passive timeout (``PROMPT_DEADLINE = 0.5 s``), proving the daemon woke
263 up on the event rather than waiting out the full timeout.
264 """
265 SMALL = 100 # << buffer size (4096)
266 PROMPT_DEADLINE = 0.5 # seconds; comfortably below passive_sleep_millis (1 000 ms)
267
268 self.fixture.holdPyObjects(_make_trackable, SMALL)
269 created, destroyed = _counts()
270 self.assertEqual(created, SMALL)
271 self.assertEqual(destroyed, 0,
272 f"{destroyed} objects freed while Java still held references")
273
274 self.fixture.releaseAll()
275 gc_java()
276
277 wait_until_cleaned(SMALL, timeout=PROMPT_DEADLINE)
278
279 _, destroyed = _counts()
280 self.assertEqual(
281 destroyed, SMALL,
282 f"Passive path: expected {SMALL} freed within {PROMPT_DEADLINE:.1f}s, "
283 f"got {destroyed} — daemon may not have woken on ReferenceQueue.remove()",
284 )
285
286 def test_08_cleanup_survives_involuntary_gc_under_oom(self):
287 """Cleanup thread must survive and drain correctly when GC is triggered by an OOM.
288
289 The JVM runs a mandatory full GC before throwing OutOfMemoryError, which enqueues
290 pending WeakReferences as a side effect. The cleanup daemon wakes up immediately
291 via ReferenceQueue.remove() and calls PyLib.decRefs() while OOM conditions persist.
292
293 A balloon of 50% of maxMemory is held so a second allocation of equal size cannot
294 succeed even after the pre-OOM full GC, guaranteeing OOM. No gc_java() is called —
295 cleanup must be driven by the OOM-triggered GC alone.
296
297 Concurrent GC activity can enqueue WeakRefs before the OOM attempt, making it
298 impossible to attribute cleanup to OOM. We retry up to MAX_ATTEMPTS times; if the
299 precondition never holds the test is skipped.
300 """
301 MAX_ATTEMPTS = 3
302 max_mem = _Runtime.getRuntime().maxMemory()
303 balloon_size = int(max_mem * 0.5)
304
305 for attempt in range(1, MAX_ATTEMPTS + 1):
306 _reset()
307 self.fixture = self.Fixture()
308
309 balloon = jpy.array('byte', balloon_size) # noqa: F841 — holds Java ref
310
311 self.fixture.holdPyObjects(_make_trackable, FLOOD)
312 self.fixture.releaseAll()
313 # no gc_java() — WeakRefs must be enqueued by the OOM GC only
314
315 _, destroyed_before = _counts()
316 if destroyed_before > 0:
317 # Concurrent GC fired before the OOM attempt; retry.
318 del balloon
319 wait_until_cleaned(FLOOD)
320 continue
321
322 try:
323 jpy.array('byte', balloon_size)
324 self.fail("Expected OutOfMemoryError not raised — balloon may be too small")
325 except MemoryError:
326 pass
327
328 wait_until_cleaned(FLOOD, timeout=TIMEOUT)
329
330 _, destroyed = _counts()
331 self.assertEqual(destroyed, FLOOD,
332 f"OOM-triggered GC: expected {FLOOD} freed, got {destroyed} "
333 f"— cleanup thread may have crashed under OOM conditions")
334 return # success
335
336 self.skipTest(
337 f"Concurrent GC fired early on all {MAX_ATTEMPTS} attempts "
338 f"— cannot prove cleanup is attributable to OOM-triggered GC"
339 )
340
341
342 if __name__ == '__main__':
343 print('\nRunning ' + __file__)
344 unittest.main()