|
| 1 | +""" |
| 2 | +Tests for run_async_in_new_loop — specifically the concurrent-greenlet scenario |
| 3 | +that caused "Future attached to a different loop" errors under load. |
| 4 | +
|
| 5 | +Regression test for: multiple concurrent callers sharing the same OS thread |
| 6 | +(as dramatiq-gevent greenlets do) must not share an event loop. |
| 7 | +""" |
| 8 | + |
| 9 | +import asyncio |
| 10 | +import threading |
| 11 | +from concurrent.futures import ThreadPoolExecutor, as_completed |
| 12 | + |
| 13 | +import pytest |
| 14 | + |
| 15 | +from dembrane.async_helpers import run_async_in_new_loop |
| 16 | + |
| 17 | + |
| 18 | +async def _simple_coro(value: int) -> int: |
| 19 | + """Minimal async coroutine that does a thread-pool round-trip (like run_in_thread_pool).""" |
| 20 | + loop = asyncio.get_running_loop() |
| 21 | + # Simulate run_in_thread_pool: submit blocking work to the executor |
| 22 | + result = await loop.run_in_executor(None, lambda: value * 2) |
| 23 | + return result |
| 24 | + |
| 25 | + |
| 26 | +async def _gather_coro(value: int) -> int: |
| 27 | + """Uses asyncio.gather internally — matches what summarize_conversation does.""" |
| 28 | + loop = asyncio.get_running_loop() |
| 29 | + a, b = await asyncio.gather( |
| 30 | + loop.run_in_executor(None, lambda: value + 1), |
| 31 | + loop.run_in_executor(None, lambda: value + 2), |
| 32 | + ) |
| 33 | + return a + b |
| 34 | + |
| 35 | + |
| 36 | +def test_run_async_in_new_loop_basic(): |
| 37 | + """Single call works correctly.""" |
| 38 | + result = run_async_in_new_loop(_simple_coro(5)) |
| 39 | + assert result == 10 |
| 40 | + |
| 41 | + |
| 42 | +def test_run_async_in_new_loop_with_gather(): |
| 43 | + """Gather inside coroutine works correctly.""" |
| 44 | + result = run_async_in_new_loop(_gather_coro(3)) |
| 45 | + assert result == 9 # (3+1) + (3+2) = 9 |
| 46 | + |
| 47 | + |
| 48 | +def test_run_async_in_new_loop_concurrent_threads(): |
| 49 | + """ |
| 50 | + Simulates the dramatiq-gevent scenario: N threads all calling |
| 51 | + run_async_in_new_loop concurrently. Before the fix, they shared |
| 52 | + a cached loop by thread ID, causing "Future attached to a different |
| 53 | + loop" errors under concurrent load. |
| 54 | + """ |
| 55 | + errors = [] |
| 56 | + results = [] |
| 57 | + |
| 58 | + def worker(value: int): |
| 59 | + try: |
| 60 | + r = run_async_in_new_loop(_gather_coro(value)) |
| 61 | + results.append(r) |
| 62 | + except Exception as e: |
| 63 | + errors.append(str(e)) |
| 64 | + |
| 65 | + # Simulate 10 concurrent callers (matches or exceeds Stage 3 load test concurrency) |
| 66 | + with ThreadPoolExecutor(max_workers=10) as pool: |
| 67 | + futures = [pool.submit(worker, i) for i in range(10)] |
| 68 | + for f in as_completed(futures): |
| 69 | + f.result() # re-raises if the thread itself crashed |
| 70 | + |
| 71 | + assert errors == [], f"Concurrent run_async_in_new_loop raised errors: {errors}" |
| 72 | + assert len(results) == 10 |
| 73 | + |
| 74 | + |
| 75 | +def test_run_async_in_new_loop_same_thread_sequential(): |
| 76 | + """ |
| 77 | + Calls from the same thread are safe when sequential. |
| 78 | + Verifies loop is properly closed between calls (no 'loop is closed' error). |
| 79 | + """ |
| 80 | + for i in range(5): |
| 81 | + result = run_async_in_new_loop(_simple_coro(i)) |
| 82 | + assert result == i * 2 |
| 83 | + |
| 84 | + |
| 85 | +def test_run_async_in_new_loop_same_thread_id_concurrent(): |
| 86 | + """ |
| 87 | + Reproduces the exact bug: multiple coroutines submitted from threads |
| 88 | + that all share the same thread ID (simulated by patching get_ident). |
| 89 | +
|
| 90 | + Before the fix (persistent loop per thread ID), all concurrent callers |
| 91 | + shared one loop → "Future attached to a different loop". |
| 92 | + After the fix (fresh loop per call), each call is isolated. |
| 93 | + """ |
| 94 | + original_get_ident = threading.get_ident |
| 95 | + # Make all threads report the same thread ID — exactly what gevent does |
| 96 | + threading.get_ident = lambda: 99999 |
| 97 | + |
| 98 | + errors = [] |
| 99 | + results = [] |
| 100 | + |
| 101 | + def worker(value: int): |
| 102 | + try: |
| 103 | + r = run_async_in_new_loop(_gather_coro(value)) |
| 104 | + results.append(r) |
| 105 | + except Exception as e: |
| 106 | + errors.append(str(e)) |
| 107 | + |
| 108 | + try: |
| 109 | + with ThreadPoolExecutor(max_workers=5) as pool: |
| 110 | + futures = [pool.submit(worker, i) for i in range(5)] |
| 111 | + for f in as_completed(futures): |
| 112 | + f.result() |
| 113 | + finally: |
| 114 | + threading.get_ident = original_get_ident |
| 115 | + |
| 116 | + assert errors == [], f"Same-thread-ID concurrent calls raised errors: {errors}" |
| 117 | + assert len(results) == 5 |
| 118 | + |
| 119 | + |
| 120 | +def test_run_async_in_new_loop_rejects_non_coroutine(): |
| 121 | + """Type guard still works.""" |
| 122 | + with pytest.raises(TypeError, match="expects a coroutine or Future"): |
| 123 | + run_async_in_new_loop(42) # type: ignore |
0 commit comments