|
| 1 | +""" |
| 2 | +Tests that verify the fix for the two-Ctrl+C shutdown hang. |
| 3 | +
|
| 4 | +Root cause: asyncio.to_thread() (used during generation for SQLite session queue operations) |
| 5 | +creates non-daemon threads via the event loop's default ThreadPoolExecutor. When the event |
| 6 | +loop is interrupted by KeyboardInterrupt without calling loop.shutdown_default_executor() and |
| 7 | +loop.close(), those non-daemon threads remain alive and cause threading._shutdown() to block. |
| 8 | +
|
| 9 | +The fix in run_app.py: |
| 10 | +1. Cancels all pending asyncio tasks (e.g. socket.io ping tasks) to avoid "Task was destroyed |
| 11 | + but it is pending!" warnings when loop.close() is called. |
| 12 | +2. Calls loop.run_until_complete(loop.shutdown_default_executor()) followed by loop.close() |
| 13 | + after ApiDependencies.shutdown(), so all executor threads are cleaned up before the process |
| 14 | + begins its Python-level teardown. |
| 15 | +""" |
| 16 | + |
| 17 | +from tests.dangerously_run_function_in_subprocess import dangerously_run_function_in_subprocess |
| 18 | + |
| 19 | + |
| 20 | +def test_asyncio_to_thread_creates_nondaemon_thread(): |
| 21 | + """Confirm that asyncio.to_thread() leaves a non-daemon thread alive after run_until_complete() |
| 22 | + is interrupted - this is the raw symptom that caused the two-Ctrl+C hang.""" |
| 23 | + |
| 24 | + def test_func(): |
| 25 | + import asyncio |
| 26 | + import threading |
| 27 | + |
| 28 | + async def use_thread(): |
| 29 | + await asyncio.to_thread(lambda: None) |
| 30 | + |
| 31 | + loop = asyncio.new_event_loop() |
| 32 | + loop.run_until_complete(use_thread()) |
| 33 | + # Deliberately do NOT call shutdown_default_executor() or loop.close() |
| 34 | + non_daemon = [t for t in threading.enumerate() if not t.daemon and t is not threading.main_thread()] |
| 35 | + # There should be at least one non-daemon executor thread still alive |
| 36 | + if not non_daemon: |
| 37 | + raise AssertionError("Expected a non-daemon thread but found none") |
| 38 | + print("ok") |
| 39 | + |
| 40 | + stdout, _stderr, returncode = dangerously_run_function_in_subprocess(test_func) |
| 41 | + assert returncode == 0, _stderr |
| 42 | + assert stdout.strip() == "ok" |
| 43 | + |
| 44 | + |
| 45 | +def test_shutdown_default_executor_cleans_up_nondaemon_threads(): |
| 46 | + """Verify that calling shutdown_default_executor() + loop.close() eliminates all non-daemon |
| 47 | + threads created by asyncio.to_thread() - this is the fix applied in run_app.py.""" |
| 48 | + |
| 49 | + def test_func(): |
| 50 | + import asyncio |
| 51 | + import threading |
| 52 | + |
| 53 | + async def use_thread(): |
| 54 | + await asyncio.to_thread(lambda: None) |
| 55 | + |
| 56 | + loop = asyncio.new_event_loop() |
| 57 | + loop.run_until_complete(use_thread()) |
| 58 | + |
| 59 | + # Apply the fix |
| 60 | + loop.run_until_complete(loop.shutdown_default_executor()) |
| 61 | + loop.close() |
| 62 | + |
| 63 | + non_daemon = [t for t in threading.enumerate() if not t.daemon and t is not threading.main_thread()] |
| 64 | + if non_daemon: |
| 65 | + raise AssertionError(f"Expected no non-daemon threads but found: {[t.name for t in non_daemon]}") |
| 66 | + print("ok") |
| 67 | + |
| 68 | + stdout, _stderr, returncode = dangerously_run_function_in_subprocess(test_func) |
| 69 | + assert returncode == 0, _stderr |
| 70 | + assert stdout.strip() == "ok" |
| 71 | + |
| 72 | + |
| 73 | +def test_shutdown_default_executor_works_after_simulated_keyboard_interrupt(): |
| 74 | + """Verify that the fix works even when run_until_complete() was previously interrupted, |
| 75 | + matching the exact flow in run_app.py's except KeyboardInterrupt block.""" |
| 76 | + |
| 77 | + def test_func(): |
| 78 | + import asyncio |
| 79 | + import threading |
| 80 | + |
| 81 | + async def use_thread_then_raise(): |
| 82 | + await asyncio.to_thread(lambda: None) |
| 83 | + raise KeyboardInterrupt |
| 84 | + |
| 85 | + loop = asyncio.new_event_loop() |
| 86 | + try: |
| 87 | + loop.run_until_complete(use_thread_then_raise()) |
| 88 | + except KeyboardInterrupt: |
| 89 | + pass |
| 90 | + |
| 91 | + # At this point a non-daemon thread exists (the bug) |
| 92 | + non_daemon_before = [t for t in threading.enumerate() if not t.daemon and t is not threading.main_thread()] |
| 93 | + if not non_daemon_before: |
| 94 | + raise AssertionError("Expected a non-daemon thread before fix") |
| 95 | + |
| 96 | + # Apply the fix (what run_app.py now does) |
| 97 | + loop.run_until_complete(loop.shutdown_default_executor()) |
| 98 | + loop.close() |
| 99 | + |
| 100 | + non_daemon_after = [t for t in threading.enumerate() if not t.daemon and t is not threading.main_thread()] |
| 101 | + if non_daemon_after: |
| 102 | + raise AssertionError(f"Non-daemon threads remain after fix: {[t.name for t in non_daemon_after]}") |
| 103 | + print("ok") |
| 104 | + |
| 105 | + stdout, _stderr, returncode = dangerously_run_function_in_subprocess(test_func) |
| 106 | + assert returncode == 0, _stderr |
| 107 | + assert stdout.strip() == "ok" |
| 108 | + |
| 109 | + |
| 110 | +def test_cancel_pending_tasks_suppresses_destroyed_task_warnings(): |
| 111 | + """Verify that cancelling pending tasks before loop.close() suppresses 'Task was destroyed |
| 112 | + but it is pending!' warnings (e.g. from socket.io ping tasks).""" |
| 113 | + |
| 114 | + def test_func(): |
| 115 | + import asyncio |
| 116 | + |
| 117 | + async def long_running(): |
| 118 | + await asyncio.sleep(1) # simulates a socket.io ping task |
| 119 | + |
| 120 | + async def start_background_task(): |
| 121 | + asyncio.create_task(long_running()) |
| 122 | + await asyncio.to_thread(lambda: None) |
| 123 | + raise KeyboardInterrupt |
| 124 | + |
| 125 | + loop = asyncio.new_event_loop() |
| 126 | + try: |
| 127 | + loop.run_until_complete(start_background_task()) |
| 128 | + except KeyboardInterrupt: |
| 129 | + pass |
| 130 | + |
| 131 | + # Apply the task-cancellation fix |
| 132 | + pending = [t for t in asyncio.all_tasks(loop) if not t.done()] |
| 133 | + for task in pending: |
| 134 | + task.cancel() |
| 135 | + if pending: |
| 136 | + loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True)) |
| 137 | + |
| 138 | + loop.run_until_complete(loop.shutdown_default_executor()) |
| 139 | + loop.close() |
| 140 | + print("ok") |
| 141 | + |
| 142 | + stdout, _stderr, returncode = dangerously_run_function_in_subprocess(test_func) |
| 143 | + assert returncode == 0, _stderr |
| 144 | + assert stdout.strip() == "ok" |
| 145 | + # The "Task was destroyed but it is pending!" message appears on stderr when tasks are NOT |
| 146 | + # cancelled before loop.close(). After the fix it must be absent. |
| 147 | + assert "Task was destroyed but it is pending" not in _stderr |
0 commit comments