| 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 |
OM |
| 47 |
|
| 48 |
_System = jpy.get_type('java.lang.System') |
| 49 |
_Runtime = jpy.get_type('java.lang.Runtime') |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
FLOOD = 20_000 |
| 55 |
TIMEOUT = 10.0 |
| 56 |
|
| 57 |
────────────────────────────────────── |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
ed |
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
mic. |
| 73 |
al |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 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 |
────────────────────────────────────────────── |
| 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 |
──────────────────────────────────────────────── |
| 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 |
|
| 144 |
|
| 145 |
|
| 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 |
|
| 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 |
| 266 |
PROMPT_DEADLINE = 0.5 |
| 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) ef |
| 310 |
|
| 311 |
self.fixture.holdPyObjects(_make_trackable, FLOOD) |
| 312 |
self.fixture.releaseAll() |
| 313 |
ly |
| 314 |
|
| 315 |
_, destroyed_before = _counts() |
| 316 |
if destroyed_before > 0: |
| 317 |
|
| 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 |
| 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() |