vomebook commited on
Commit ·
ffb393d
1
Parent(s): d270929
Preserve search executor ownership during shutdown
Browse files- backend/app.py +23 -1
- backend/search_execution.py +73 -3
- tests/backend/test_coverage_safety.py +157 -0
- tests/search/backend/test_search_execution.py +345 -0
backend/app.py
CHANGED
|
@@ -1333,7 +1333,27 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
|
| 1333 |
app.state.reader_index_build_task.cancel()
|
| 1334 |
await asyncio.gather(app.state.reader_index_build_task, return_exceptions=True)
|
| 1335 |
app.state.reader_index_build_task = None
|
| 1336 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1337 |
del app.state.search_executor
|
| 1338 |
if app.state.reader_assets_task is not None:
|
| 1339 |
app.state.reader_assets_task.cancel()
|
|
@@ -1350,6 +1370,8 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
|
| 1350 |
app.state.reader_range_cache.clear()
|
| 1351 |
app.state.reader_range_cache_bytes = 0
|
| 1352 |
await app.state.http_session.close()
|
|
|
|
|
|
|
| 1353 |
app = FastAPI(title="VoiceOfML Search", version="2.0", lifespan=lifespan)
|
| 1354 |
app.add_middleware(GZipMiddleware, minimum_size=500)
|
| 1355 |
app.add_middleware(
|
|
|
|
| 1333 |
app.state.reader_index_build_task.cancel()
|
| 1334 |
await asyncio.gather(app.state.reader_index_build_task, return_exceptions=True)
|
| 1335 |
app.state.reader_index_build_task = None
|
| 1336 |
+
# Defer cancellation until the real worker and join finish and resources close.
|
| 1337 |
+
close_task = asyncio.create_task(app.state.search_executor.close())
|
| 1338 |
+
cancelled = None
|
| 1339 |
+
while True:
|
| 1340 |
+
try:
|
| 1341 |
+
await asyncio.shield(close_task)
|
| 1342 |
+
break
|
| 1343 |
+
except asyncio.CancelledError as exc:
|
| 1344 |
+
if close_task.cancelled():
|
| 1345 |
+
raise
|
| 1346 |
+
if cancelled is None:
|
| 1347 |
+
cancelled = exc
|
| 1348 |
+
except Exception as exc:
|
| 1349 |
+
if cancelled is None:
|
| 1350 |
+
raise
|
| 1351 |
+
asyncio.get_running_loop().call_exception_handler({
|
| 1352 |
+
"message": "SearchExecutor close failed during lifespan cancellation",
|
| 1353 |
+
"exception": exc,
|
| 1354 |
+
"task": close_task,
|
| 1355 |
+
})
|
| 1356 |
+
raise cancelled
|
| 1357 |
del app.state.search_executor
|
| 1358 |
if app.state.reader_assets_task is not None:
|
| 1359 |
app.state.reader_assets_task.cancel()
|
|
|
|
| 1370 |
app.state.reader_range_cache.clear()
|
| 1371 |
app.state.reader_range_cache_bytes = 0
|
| 1372 |
await app.state.http_session.close()
|
| 1373 |
+
if cancelled is not None:
|
| 1374 |
+
raise cancelled
|
| 1375 |
app = FastAPI(title="VoiceOfML Search", version="2.0", lifespan=lifespan)
|
| 1376 |
app.add_middleware(GZipMiddleware, minimum_size=500)
|
| 1377 |
app.add_middleware(
|
backend/search_execution.py
CHANGED
|
@@ -2,12 +2,15 @@
|
|
| 2 |
import asyncio
|
| 3 |
from collections.abc import Callable
|
| 4 |
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
| 5 |
import time
|
| 6 |
import threading
|
| 7 |
from types import TracebackType
|
| 8 |
from typing import TypeVar
|
| 9 |
|
| 10 |
|
|
|
|
|
|
|
| 11 |
T = TypeVar("T")
|
| 12 |
|
| 13 |
|
|
@@ -28,6 +31,18 @@ def check_search_cancelled() -> None:
|
|
| 28 |
raise SearchCancelled()
|
| 29 |
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
class SearchExecutor:
|
| 32 |
def __init__(self, capacity: int = 32) -> None:
|
| 33 |
self.capacity = capacity
|
|
@@ -35,6 +50,8 @@ class SearchExecutor:
|
|
| 35 |
self._lock = asyncio.Lock()
|
| 36 |
self._tasks: set[asyncio.Task[tuple[object, float, float]]] = set()
|
| 37 |
self._closing = False
|
|
|
|
|
|
|
| 38 |
self._foreground: set[asyncio.Task[tuple[object, float, float]]] = set()
|
| 39 |
|
| 40 |
async def __aenter__(self) -> "SearchExecutor":
|
|
@@ -90,6 +107,59 @@ class SearchExecutor:
|
|
| 90 |
raise
|
| 91 |
|
| 92 |
async def close(self) -> None:
|
| 93 |
-
self.
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import asyncio
|
| 3 |
from collections.abc import Callable
|
| 4 |
from concurrent.futures import ThreadPoolExecutor
|
| 5 |
+
import logging
|
| 6 |
import time
|
| 7 |
import threading
|
| 8 |
from types import TracebackType
|
| 9 |
from typing import TypeVar
|
| 10 |
|
| 11 |
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
T = TypeVar("T")
|
| 15 |
|
| 16 |
|
|
|
|
| 31 |
raise SearchCancelled()
|
| 32 |
|
| 33 |
|
| 34 |
+
def _report_close_failure(task: asyncio.Task[None], state: dict[str, int | bool]) -> None:
|
| 35 |
+
if task.done() and not task.cancelled():
|
| 36 |
+
error = task.exception()
|
| 37 |
+
if error is not None and not state["waiters"] and not state["observed"]:
|
| 38 |
+
state["observed"] = True
|
| 39 |
+
task.get_loop().call_exception_handler({
|
| 40 |
+
"message": "SearchExecutor close failed without a waiting caller",
|
| 41 |
+
"exception": error,
|
| 42 |
+
"task": task,
|
| 43 |
+
})
|
| 44 |
+
|
| 45 |
+
|
| 46 |
class SearchExecutor:
|
| 47 |
def __init__(self, capacity: int = 32) -> None:
|
| 48 |
self.capacity = capacity
|
|
|
|
| 50 |
self._lock = asyncio.Lock()
|
| 51 |
self._tasks: set[asyncio.Task[tuple[object, float, float]]] = set()
|
| 52 |
self._closing = False
|
| 53 |
+
self._close_task: asyncio.Task[None] | None = None
|
| 54 |
+
self._close_state: dict[str, int | bool] | None = None
|
| 55 |
self._foreground: set[asyncio.Task[tuple[object, float, float]]] = set()
|
| 56 |
|
| 57 |
async def __aenter__(self) -> "SearchExecutor":
|
|
|
|
| 107 |
raise
|
| 108 |
|
| 109 |
async def close(self) -> None:
|
| 110 |
+
if (self._close_task is None or
|
| 111 |
+
(self._close_task.done() and
|
| 112 |
+
(self._close_task.cancelled() or self._close_task.exception() is not None))):
|
| 113 |
+
self._closing = True
|
| 114 |
+
|
| 115 |
+
async def drain() -> None:
|
| 116 |
+
await asyncio.gather(*self._tasks, return_exceptions=True)
|
| 117 |
+
loop = asyncio.get_running_loop()
|
| 118 |
+
joined = loop.create_future()
|
| 119 |
+
|
| 120 |
+
def notify(error: BaseException | None) -> None:
|
| 121 |
+
if not joined.done():
|
| 122 |
+
if error is None:
|
| 123 |
+
joined.set_result(None)
|
| 124 |
+
else:
|
| 125 |
+
joined.set_exception(error)
|
| 126 |
+
|
| 127 |
+
def shutdown() -> None:
|
| 128 |
+
error = None
|
| 129 |
+
try:
|
| 130 |
+
self._pool.shutdown(wait=True)
|
| 131 |
+
except BaseException as exc:
|
| 132 |
+
error = exc
|
| 133 |
+
# Log in the worker: even a successfully queued callback may
|
| 134 |
+
# never run if the loop closes, or its future is cancelled.
|
| 135 |
+
logger.exception("SearchExecutor shutdown failed")
|
| 136 |
+
try:
|
| 137 |
+
loop.call_soon_threadsafe(notify, error)
|
| 138 |
+
except RuntimeError:
|
| 139 |
+
# The host must keep the loop alive until close completes.
|
| 140 |
+
pass
|
| 141 |
+
|
| 142 |
+
threading.Thread(target=shutdown, name="search-shutdown").start()
|
| 143 |
+
await joined
|
| 144 |
+
|
| 145 |
+
self._close_task = asyncio.create_task(drain())
|
| 146 |
+
close_state: dict[str, int | bool] = {"waiters": 0, "observed": False}
|
| 147 |
+
self._close_state = close_state
|
| 148 |
+
|
| 149 |
+
self._close_task.add_done_callback(lambda task: _report_close_failure(task, close_state))
|
| 150 |
+
task = self._close_task
|
| 151 |
+
state = self._close_state
|
| 152 |
+
if state is None:
|
| 153 |
+
raise RuntimeError("SearchExecutor close state missing")
|
| 154 |
+
state["waiters"] += 1
|
| 155 |
+
try:
|
| 156 |
+
# A cancelled caller must not cancel the drain or its owned jobs.
|
| 157 |
+
await asyncio.shield(task)
|
| 158 |
+
except asyncio.CancelledError:
|
| 159 |
+
raise
|
| 160 |
+
except BaseException:
|
| 161 |
+
state["observed"] = True
|
| 162 |
+
raise
|
| 163 |
+
finally:
|
| 164 |
+
state["waiters"] -= 1
|
| 165 |
+
_report_close_failure(task, state)
|
tests/backend/test_coverage_safety.py
CHANGED
|
@@ -3,6 +3,7 @@ import asyncio
|
|
| 3 |
import gzip
|
| 4 |
import importlib
|
| 5 |
import json
|
|
|
|
| 6 |
from pathlib import Path
|
| 7 |
from tempfile import TemporaryDirectory
|
| 8 |
from types import SimpleNamespace
|
|
@@ -503,6 +504,162 @@ class LifespanAndCdnTests(unittest.IsolatedAsyncioTestCase):
|
|
| 503 |
close_flights.assert_awaited_once()
|
| 504 |
self.assertFalse(application.state.download_warm_enabled)
|
| 505 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 506 |
async def test_lifespan_tolerates_absent_warm_task_and_still_closes_resources(self):
|
| 507 |
application = FastAPI()
|
| 508 |
session = SimpleNamespace(close=AsyncMock())
|
|
|
|
| 3 |
import gzip
|
| 4 |
import importlib
|
| 5 |
import json
|
| 6 |
+
import threading
|
| 7 |
from pathlib import Path
|
| 8 |
from tempfile import TemporaryDirectory
|
| 9 |
from types import SimpleNamespace
|
|
|
|
| 504 |
close_flights.assert_awaited_once()
|
| 505 |
self.assertFalse(application.state.download_warm_enabled)
|
| 506 |
|
| 507 |
+
async def test_lifespan_cancelled_executor_close_drains_before_cleanup(self):
|
| 508 |
+
application = FastAPI()
|
| 509 |
+
worker_started, release_worker = threading.Event(), threading.Event()
|
| 510 |
+
join_started, release_join = threading.Event(), threading.Event()
|
| 511 |
+
events = []
|
| 512 |
+
session = SimpleNamespace(close=AsyncMock(side_effect=lambda: events.append('session')))
|
| 513 |
+
|
| 514 |
+
def record(name, *args):
|
| 515 |
+
events.append(name)
|
| 516 |
+
|
| 517 |
+
async def wait_for(event):
|
| 518 |
+
for _ in range(200):
|
| 519 |
+
if event.is_set():
|
| 520 |
+
return
|
| 521 |
+
await asyncio.sleep(.01)
|
| 522 |
+
self.fail('timed out waiting for thread')
|
| 523 |
+
|
| 524 |
+
with patch.object(app, 'load_data'), \
|
| 525 |
+
patch.object(app.aiohttp, 'ClientSession', return_value=session), \
|
| 526 |
+
patch.object(app.aiohttp, 'TCPConnector', return_value=object()), \
|
| 527 |
+
patch.object(app, 'initialize_reader_bucket_state'), \
|
| 528 |
+
patch.object(app, 'initialize_reader_archive_state'), \
|
| 529 |
+
patch.object(app, 'shutdown_reader_bucket_state', side_effect=lambda *a: record('bucket', *a)), \
|
| 530 |
+
patch.object(app, 'shutdown_reader_archive_state', side_effect=lambda *a: record('archive', *a)), \
|
| 531 |
+
patch.object(app, 'shutdown_reader_range_flights', side_effect=lambda: record('flights')), \
|
| 532 |
+
patch.object(app, 'warm_reader_indexes', new_callable=AsyncMock):
|
| 533 |
+
context = app.lifespan(application)
|
| 534 |
+
await context.__aenter__()
|
| 535 |
+
executor = application.state.search_executor
|
| 536 |
+
original_shutdown = executor._pool.shutdown
|
| 537 |
+
|
| 538 |
+
def worker():
|
| 539 |
+
worker_started.set()
|
| 540 |
+
release_worker.wait(3)
|
| 541 |
+
events.append('worker')
|
| 542 |
+
|
| 543 |
+
def join(*, wait):
|
| 544 |
+
join_started.set()
|
| 545 |
+
release_join.wait(3)
|
| 546 |
+
original_shutdown(wait=wait)
|
| 547 |
+
events.append('join')
|
| 548 |
+
|
| 549 |
+
with patch.object(executor._pool, 'shutdown', side_effect=join):
|
| 550 |
+
job = asyncio.create_task(executor.run(worker))
|
| 551 |
+
closing = None
|
| 552 |
+
try:
|
| 553 |
+
await wait_for(worker_started)
|
| 554 |
+
closing = asyncio.create_task(context.__aexit__(None, None, None))
|
| 555 |
+
for _ in range(200):
|
| 556 |
+
if executor._closing:
|
| 557 |
+
break
|
| 558 |
+
await asyncio.sleep(.01)
|
| 559 |
+
self.assertTrue(executor._closing)
|
| 560 |
+
closing.cancel('shutdown cancelled')
|
| 561 |
+
await asyncio.sleep(.05)
|
| 562 |
+
self.assertFalse(closing.done())
|
| 563 |
+
self.assertEqual(events, [])
|
| 564 |
+
release_worker.set()
|
| 565 |
+
await wait_for(join_started)
|
| 566 |
+
closing.cancel('again')
|
| 567 |
+
await asyncio.sleep(.05)
|
| 568 |
+
self.assertFalse(closing.done())
|
| 569 |
+
self.assertEqual(events, ['worker'])
|
| 570 |
+
release_join.set()
|
| 571 |
+
with self.assertRaises(asyncio.CancelledError) as cancelled:
|
| 572 |
+
await asyncio.wait_for(closing, 2)
|
| 573 |
+
self.assertEqual(cancelled.exception.args, ('shutdown cancelled',))
|
| 574 |
+
await asyncio.wait_for(job, 1)
|
| 575 |
+
self.assertEqual(events, ['worker', 'join', 'bucket', 'archive', 'flights', 'session'])
|
| 576 |
+
self.assertFalse(hasattr(application.state, 'search_executor'))
|
| 577 |
+
self.assertFalse(application.state.download_warm_enabled)
|
| 578 |
+
finally:
|
| 579 |
+
release_worker.set()
|
| 580 |
+
release_join.set()
|
| 581 |
+
await asyncio.gather(job, return_exceptions=True)
|
| 582 |
+
if closing is not None:
|
| 583 |
+
await asyncio.gather(closing, return_exceptions=True)
|
| 584 |
+
await executor.close()
|
| 585 |
+
|
| 586 |
+
async def test_lifespan_thread_start_failure_with_and_without_cancellation(self):
|
| 587 |
+
for cancel in (True, False):
|
| 588 |
+
with self.subTest(cancel=cancel):
|
| 589 |
+
application = FastAPI()
|
| 590 |
+
started, release = threading.Event(), threading.Event()
|
| 591 |
+
session = SimpleNamespace(close=AsyncMock())
|
| 592 |
+
failure = RuntimeError('shutdown thread start failed')
|
| 593 |
+
reports = []
|
| 594 |
+
loop = asyncio.get_running_loop()
|
| 595 |
+
previous_handler = loop.get_exception_handler()
|
| 596 |
+
original_start = threading.Thread.start
|
| 597 |
+
|
| 598 |
+
def start(thread):
|
| 599 |
+
if thread.name == 'search-shutdown':
|
| 600 |
+
raise failure
|
| 601 |
+
return original_start(thread)
|
| 602 |
+
|
| 603 |
+
def worker():
|
| 604 |
+
started.set()
|
| 605 |
+
release.wait(3)
|
| 606 |
+
|
| 607 |
+
async def wait_until(predicate):
|
| 608 |
+
async with asyncio.timeout(2):
|
| 609 |
+
while not predicate():
|
| 610 |
+
await asyncio.sleep(.01)
|
| 611 |
+
|
| 612 |
+
with patch.object(app, 'load_data'), \
|
| 613 |
+
patch.object(app.aiohttp, 'ClientSession', return_value=session), \
|
| 614 |
+
patch.object(app.aiohttp, 'TCPConnector', return_value=object()), \
|
| 615 |
+
patch.object(app, 'initialize_reader_bucket_state'), \
|
| 616 |
+
patch.object(app, 'initialize_reader_archive_state'), \
|
| 617 |
+
patch.object(app, 'shutdown_reader_bucket_state', new_callable=AsyncMock) as bucket, \
|
| 618 |
+
patch.object(app, 'shutdown_reader_archive_state', new_callable=AsyncMock) as archive, \
|
| 619 |
+
patch.object(app, 'shutdown_reader_range_flights', new_callable=AsyncMock) as flights, \
|
| 620 |
+
patch.object(app, 'warm_reader_indexes', new_callable=AsyncMock):
|
| 621 |
+
loop.set_exception_handler(lambda loop, context: reports.append(context))
|
| 622 |
+
context = app.lifespan(application)
|
| 623 |
+
await context.__aenter__()
|
| 624 |
+
executor = application.state.search_executor
|
| 625 |
+
job = asyncio.create_task(executor.run(worker))
|
| 626 |
+
closing = None
|
| 627 |
+
try:
|
| 628 |
+
await wait_until(started.is_set)
|
| 629 |
+
with patch.object(threading.Thread, 'start', new=start):
|
| 630 |
+
closing = asyncio.create_task(context.__aexit__(None, None, None))
|
| 631 |
+
await wait_until(lambda: executor._closing)
|
| 632 |
+
if cancel:
|
| 633 |
+
closing.cancel('original cancellation')
|
| 634 |
+
await asyncio.sleep(.05)
|
| 635 |
+
self.assertFalse(closing.done())
|
| 636 |
+
release.set()
|
| 637 |
+
if cancel:
|
| 638 |
+
with self.assertRaises(asyncio.CancelledError) as caught:
|
| 639 |
+
await asyncio.wait_for(closing, 2)
|
| 640 |
+
self.assertEqual(caught.exception.args, ('original cancellation',))
|
| 641 |
+
self.assertEqual(len(reports), 1)
|
| 642 |
+
self.assertIs(reports[0]['exception'], failure)
|
| 643 |
+
self.assertIn('close failed', reports[0]['message'])
|
| 644 |
+
else:
|
| 645 |
+
with self.assertRaises(RuntimeError) as caught:
|
| 646 |
+
await asyncio.wait_for(closing, 2)
|
| 647 |
+
self.assertIs(caught.exception, failure)
|
| 648 |
+
self.assertEqual(reports, [])
|
| 649 |
+
await asyncio.wait_for(job, 2)
|
| 650 |
+
self.assertIs(application.state.search_executor, executor)
|
| 651 |
+
self.assertIs(application.state.http_session, session)
|
| 652 |
+
self.assertTrue(application.state.download_warm_enabled)
|
| 653 |
+
session.close.assert_not_awaited()
|
| 654 |
+
bucket.assert_not_awaited(); archive.assert_not_awaited(); flights.assert_not_awaited()
|
| 655 |
+
finally:
|
| 656 |
+
release.set()
|
| 657 |
+
await asyncio.gather(job, return_exceptions=True)
|
| 658 |
+
if closing is not None:
|
| 659 |
+
await asyncio.gather(closing, return_exceptions=True)
|
| 660 |
+
await asyncio.wait_for(executor.close(), 2)
|
| 661 |
+
loop.set_exception_handler(previous_handler)
|
| 662 |
+
|
| 663 |
async def test_lifespan_tolerates_absent_warm_task_and_still_closes_resources(self):
|
| 664 |
application = FastAPI()
|
| 665 |
session = SimpleNamespace(close=AsyncMock())
|
tests/search/backend/test_search_execution.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import asyncio
|
|
|
|
| 2 |
import threading
|
| 3 |
import time
|
| 4 |
import unittest
|
|
@@ -156,6 +157,233 @@ class SearchExecutionTests(unittest.IsolatedAsyncioTestCase):
|
|
| 156 |
shutdown.assert_called_once_with(wait=True)
|
| 157 |
self.assertIs(executor._closing, True)
|
| 158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
async def test_background_executor_drains_before_context_exit(self):
|
| 160 |
async with SearchExecutor() as executor:
|
| 161 |
result = await asyncio.wait_for(executor.run(lambda: 'background', background=True), .5)
|
|
@@ -181,6 +409,83 @@ class SearchExecutionTests(unittest.IsolatedAsyncioTestCase):
|
|
| 181 |
self.assertEqual(executor._foreground, set())
|
| 182 |
self.assertEqual(executor._tasks, set())
|
| 183 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
async def test_close_waits_for_started_work_after_requester_cancels(self):
|
| 185 |
started, release = threading.Event(), threading.Event()
|
| 186 |
executor = SearchExecutor()
|
|
@@ -209,6 +514,46 @@ class SearchExecutionTests(unittest.IsolatedAsyncioTestCase):
|
|
| 209 |
await executor.close()
|
| 210 |
self.assertEqual(seen, ['done'])
|
| 211 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
async def test_cancelling_background_wait_keeps_foreground_ownership(self):
|
| 213 |
started, release = threading.Event(), threading.Event()
|
| 214 |
seen = []
|
|
|
|
| 1 |
import asyncio
|
| 2 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 3 |
import threading
|
| 4 |
import time
|
| 5 |
import unittest
|
|
|
|
| 157 |
shutdown.assert_called_once_with(wait=True)
|
| 158 |
self.assertIs(executor._closing, True)
|
| 159 |
|
| 160 |
+
async def test_close_after_default_executor_shutdown(self):
|
| 161 |
+
executor = SearchExecutor()
|
| 162 |
+
self.assertEqual((await executor.run(lambda: 42))[0], 42)
|
| 163 |
+
await asyncio.get_running_loop().shutdown_default_executor()
|
| 164 |
+
await asyncio.wait_for(executor.close(), 1)
|
| 165 |
+
await asyncio.wait_for(executor.close(), 1)
|
| 166 |
+
self.assertTrue(executor._pool._shutdown)
|
| 167 |
+
|
| 168 |
+
async def test_close_does_not_wait_for_busy_default_executor(self):
|
| 169 |
+
loop = asyncio.get_running_loop()
|
| 170 |
+
default = ThreadPoolExecutor(max_workers=1)
|
| 171 |
+
loop.set_default_executor(default)
|
| 172 |
+
started, release = threading.Event(), threading.Event()
|
| 173 |
+
|
| 174 |
+
def occupy():
|
| 175 |
+
started.set()
|
| 176 |
+
release.wait(1)
|
| 177 |
+
|
| 178 |
+
occupied = loop.run_in_executor(None, occupy)
|
| 179 |
+
executor = SearchExecutor()
|
| 180 |
+
try:
|
| 181 |
+
for _ in range(50):
|
| 182 |
+
if started.is_set():
|
| 183 |
+
break
|
| 184 |
+
await asyncio.sleep(.01)
|
| 185 |
+
self.assertTrue(started.is_set())
|
| 186 |
+
await asyncio.wait_for(executor.close(), .5)
|
| 187 |
+
self.assertFalse(occupied.done())
|
| 188 |
+
finally:
|
| 189 |
+
release.set()
|
| 190 |
+
await asyncio.wait_for(occupied, 2)
|
| 191 |
+
await asyncio.wait_for(executor.close(), 2)
|
| 192 |
+
|
| 193 |
+
async def test_shutdown_error_propagates_to_all_close_callers(self):
|
| 194 |
+
executor = SearchExecutor()
|
| 195 |
+
error = RuntimeError('shutdown failed')
|
| 196 |
+
with patch.object(executor._pool, 'shutdown', side_effect=error) as shutdown:
|
| 197 |
+
results = await asyncio.wait_for(asyncio.gather(
|
| 198 |
+
executor.close(), executor.close(), return_exceptions=True), 1)
|
| 199 |
+
self.assertEqual(results, [error, error])
|
| 200 |
+
shutdown.assert_called_once_with(wait=True)
|
| 201 |
+
await asyncio.wait_for(executor.close(), 1)
|
| 202 |
+
self.assertTrue(executor._pool._shutdown)
|
| 203 |
+
|
| 204 |
+
async def test_abandoned_close_failure_is_reported_once_and_retryable(self):
|
| 205 |
+
executor = SearchExecutor()
|
| 206 |
+
started, release = threading.Event(), threading.Event()
|
| 207 |
+
error = RuntimeError('abandoned shutdown failure')
|
| 208 |
+
|
| 209 |
+
def fail(*, wait):
|
| 210 |
+
started.set()
|
| 211 |
+
release.wait(1)
|
| 212 |
+
raise error
|
| 213 |
+
|
| 214 |
+
with patch.object(executor._pool, 'shutdown', side_effect=fail):
|
| 215 |
+
callers = [asyncio.create_task(executor.close()) for _ in range(2)]
|
| 216 |
+
try:
|
| 217 |
+
for _ in range(50):
|
| 218 |
+
if started.is_set():
|
| 219 |
+
break
|
| 220 |
+
await asyncio.sleep(.01)
|
| 221 |
+
self.assertTrue(started.is_set())
|
| 222 |
+
for caller in callers:
|
| 223 |
+
caller.cancel()
|
| 224 |
+
await asyncio.gather(*callers, return_exceptions=True)
|
| 225 |
+
finally:
|
| 226 |
+
release.set()
|
| 227 |
+
for _ in range(50):
|
| 228 |
+
if self._loop_errors:
|
| 229 |
+
break
|
| 230 |
+
await asyncio.sleep(.01)
|
| 231 |
+
self.assertEqual(len(self._loop_errors), 1)
|
| 232 |
+
self.assertIs(self._loop_errors.pop()['exception'], error)
|
| 233 |
+
await asyncio.wait_for(executor.close(), 1)
|
| 234 |
+
|
| 235 |
+
async def test_close_retries_after_shutdown_thread_start_failure(self):
|
| 236 |
+
executor = SearchExecutor()
|
| 237 |
+
error = RuntimeError('thread start failed')
|
| 238 |
+
with patch('backend.search_execution.threading.Thread.start', side_effect=error) as start:
|
| 239 |
+
results = await asyncio.wait_for(asyncio.gather(
|
| 240 |
+
executor.close(), executor.close(), return_exceptions=True), 1)
|
| 241 |
+
self.assertEqual(results, [error, error])
|
| 242 |
+
start.assert_called_once_with()
|
| 243 |
+
await asyncio.wait_for(executor.close(), 1)
|
| 244 |
+
self.assertTrue(executor._pool._shutdown)
|
| 245 |
+
|
| 246 |
+
async def test_shutdown_notification_ignores_cancelled_future(self):
|
| 247 |
+
executor = SearchExecutor()
|
| 248 |
+
started, release, finished = threading.Event(), threading.Event(), threading.Event()
|
| 249 |
+
original = executor._pool.shutdown
|
| 250 |
+
|
| 251 |
+
def slow_shutdown(*, wait):
|
| 252 |
+
started.set()
|
| 253 |
+
release.wait(1)
|
| 254 |
+
original(wait=wait)
|
| 255 |
+
finished.set()
|
| 256 |
+
|
| 257 |
+
with patch.object(executor._pool, 'shutdown', side_effect=slow_shutdown):
|
| 258 |
+
closing = asyncio.create_task(executor.close())
|
| 259 |
+
try:
|
| 260 |
+
for _ in range(50):
|
| 261 |
+
if started.is_set():
|
| 262 |
+
break
|
| 263 |
+
await asyncio.sleep(.01)
|
| 264 |
+
self.assertTrue(started.is_set())
|
| 265 |
+
executor._close_task.cancel()
|
| 266 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 267 |
+
await closing
|
| 268 |
+
finally:
|
| 269 |
+
release.set()
|
| 270 |
+
for _ in range(50):
|
| 271 |
+
if finished.is_set():
|
| 272 |
+
break
|
| 273 |
+
await asyncio.sleep(.01)
|
| 274 |
+
self.assertTrue(finished.is_set())
|
| 275 |
+
await asyncio.sleep(.02)
|
| 276 |
+
await asyncio.wait_for(executor.close(), 1)
|
| 277 |
+
self.assertTrue(executor._pool._shutdown)
|
| 278 |
+
|
| 279 |
+
async def test_shutdown_notification_tolerates_closed_loop(self):
|
| 280 |
+
executor = SearchExecutor()
|
| 281 |
+
started, release, notified = threading.Event(), threading.Event(), threading.Event()
|
| 282 |
+
original = executor._pool.shutdown
|
| 283 |
+
loop = asyncio.get_running_loop()
|
| 284 |
+
|
| 285 |
+
def slow_shutdown(*, wait):
|
| 286 |
+
started.set()
|
| 287 |
+
release.wait(1)
|
| 288 |
+
original(wait=wait)
|
| 289 |
+
|
| 290 |
+
def closed_loop(*args):
|
| 291 |
+
notified.set()
|
| 292 |
+
raise RuntimeError('Event loop is closed')
|
| 293 |
+
|
| 294 |
+
with patch.object(executor._pool, 'shutdown', side_effect=slow_shutdown):
|
| 295 |
+
closing = asyncio.create_task(executor.close())
|
| 296 |
+
try:
|
| 297 |
+
for _ in range(50):
|
| 298 |
+
if started.is_set():
|
| 299 |
+
break
|
| 300 |
+
await asyncio.sleep(.01)
|
| 301 |
+
self.assertTrue(started.is_set())
|
| 302 |
+
executor._close_task.cancel()
|
| 303 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 304 |
+
await closing
|
| 305 |
+
with patch.object(loop, 'call_soon_threadsafe', side_effect=closed_loop):
|
| 306 |
+
release.set()
|
| 307 |
+
for _ in range(50):
|
| 308 |
+
if notified.is_set():
|
| 309 |
+
break
|
| 310 |
+
await asyncio.sleep(.01)
|
| 311 |
+
self.assertTrue(notified.is_set())
|
| 312 |
+
finally:
|
| 313 |
+
release.set()
|
| 314 |
+
await asyncio.wait_for(executor.close(), 1)
|
| 315 |
+
|
| 316 |
+
async def test_shutdown_failure_logged_when_delivery_is_unavailable(self):
|
| 317 |
+
for closed_loop in (False, True):
|
| 318 |
+
with self.subTest(closed_loop=closed_loop):
|
| 319 |
+
executor = SearchExecutor()
|
| 320 |
+
started, release, notified = threading.Event(), threading.Event(), threading.Event()
|
| 321 |
+
error = RuntimeError('undeliverable shutdown failure')
|
| 322 |
+
loop = asyncio.get_running_loop()
|
| 323 |
+
call_soon = loop.call_soon_threadsafe
|
| 324 |
+
|
| 325 |
+
def fail(*, wait):
|
| 326 |
+
started.set()
|
| 327 |
+
release.wait(2)
|
| 328 |
+
raise error
|
| 329 |
+
|
| 330 |
+
def notify(*args):
|
| 331 |
+
try:
|
| 332 |
+
if closed_loop:
|
| 333 |
+
raise RuntimeError('Event loop is closed')
|
| 334 |
+
return call_soon(*args)
|
| 335 |
+
finally:
|
| 336 |
+
notified.set()
|
| 337 |
+
|
| 338 |
+
with patch.object(executor._pool, 'shutdown', side_effect=fail), \
|
| 339 |
+
self.assertLogs('backend.search_execution', level='ERROR') as logs:
|
| 340 |
+
closing = asyncio.create_task(executor.close())
|
| 341 |
+
try:
|
| 342 |
+
for _ in range(100):
|
| 343 |
+
if started.is_set():
|
| 344 |
+
break
|
| 345 |
+
await asyncio.sleep(.01)
|
| 346 |
+
self.assertTrue(started.is_set())
|
| 347 |
+
executor._close_task.cancel()
|
| 348 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 349 |
+
await closing
|
| 350 |
+
with patch.object(loop, 'call_soon_threadsafe', side_effect=notify):
|
| 351 |
+
release.set()
|
| 352 |
+
for _ in range(100):
|
| 353 |
+
if notified.is_set():
|
| 354 |
+
break
|
| 355 |
+
await asyncio.sleep(.01)
|
| 356 |
+
self.assertTrue(notified.is_set())
|
| 357 |
+
await asyncio.sleep(.02)
|
| 358 |
+
finally:
|
| 359 |
+
release.set()
|
| 360 |
+
self.assertEqual(len(logs.records), 1)
|
| 361 |
+
self.assertIs(logs.records[0].exc_info[1], error)
|
| 362 |
+
await asyncio.wait_for(executor.close(), 1)
|
| 363 |
+
|
| 364 |
+
async def test_shutdown_join_does_not_block_event_loop(self):
|
| 365 |
+
executor = SearchExecutor()
|
| 366 |
+
started, release = threading.Event(), threading.Event()
|
| 367 |
+
original = executor._pool.shutdown
|
| 368 |
+
|
| 369 |
+
def slow_shutdown(*, wait):
|
| 370 |
+
started.set()
|
| 371 |
+
release.wait(1)
|
| 372 |
+
original(wait=wait)
|
| 373 |
+
|
| 374 |
+
with patch.object(executor._pool, 'shutdown', side_effect=slow_shutdown):
|
| 375 |
+
closing = asyncio.create_task(executor.close())
|
| 376 |
+
try:
|
| 377 |
+
for _ in range(50):
|
| 378 |
+
if started.is_set():
|
| 379 |
+
break
|
| 380 |
+
await asyncio.sleep(.01)
|
| 381 |
+
self.assertTrue(started.is_set())
|
| 382 |
+
self.assertFalse(closing.done(), 'shutdown must not block the event loop')
|
| 383 |
+
finally:
|
| 384 |
+
release.set()
|
| 385 |
+
await asyncio.wait_for(closing, 2)
|
| 386 |
+
|
| 387 |
async def test_background_executor_drains_before_context_exit(self):
|
| 388 |
async with SearchExecutor() as executor:
|
| 389 |
result = await asyncio.wait_for(executor.run(lambda: 'background', background=True), .5)
|
|
|
|
| 409 |
self.assertEqual(executor._foreground, set())
|
| 410 |
self.assertEqual(executor._tasks, set())
|
| 411 |
|
| 412 |
+
async def test_lifespan_waits_nonblocking_for_cancelled_request_worker(self):
|
| 413 |
+
from backend import app
|
| 414 |
+
from unittest.mock import AsyncMock, MagicMock
|
| 415 |
+
|
| 416 |
+
started, release, exited = threading.Event(), threading.Event(), threading.Event()
|
| 417 |
+
close_started = asyncio.Event()
|
| 418 |
+
worker = []
|
| 419 |
+
|
| 420 |
+
def slow(**params):
|
| 421 |
+
worker.append(threading.current_thread())
|
| 422 |
+
started.set()
|
| 423 |
+
release.wait(2) # Also bounds a broken, blocking shutdown.
|
| 424 |
+
exited.set()
|
| 425 |
+
return {'results': [], 'total': 0, 'page': 1, 'page_size': 100}
|
| 426 |
+
|
| 427 |
+
session = MagicMock()
|
| 428 |
+
session.close = AsyncMock()
|
| 429 |
+
with patch.object(app, 'load_data'), \
|
| 430 |
+
patch.object(app, 'warm_reader_indexes', new_callable=AsyncMock), \
|
| 431 |
+
patch.object(app.aiohttp, 'ClientSession', return_value=session), \
|
| 432 |
+
patch.object(app.aiohttp, 'TCPConnector'), \
|
| 433 |
+
patch.object(app, 'initialize_reader_bucket_state'), \
|
| 434 |
+
patch.object(app, 'initialize_reader_archive_state'), \
|
| 435 |
+
patch.object(app, 'shutdown_reader_bucket_state', new_callable=AsyncMock), \
|
| 436 |
+
patch.object(app, 'shutdown_reader_archive_state', new_callable=AsyncMock), \
|
| 437 |
+
patch.object(app, 'shutdown_reader_range_flights', new_callable=AsyncMock), \
|
| 438 |
+
patch.object(app, 'search', slow):
|
| 439 |
+
lifespan = app.lifespan(app.app)
|
| 440 |
+
await lifespan.__aenter__()
|
| 441 |
+
executor = app.app.state.search_executor
|
| 442 |
+
request = asyncio.create_task(app.api_search(app.SearchRequest(q='query')))
|
| 443 |
+
closing = None
|
| 444 |
+
original_close = executor.close
|
| 445 |
+
|
| 446 |
+
async def observed_close():
|
| 447 |
+
close_started.set()
|
| 448 |
+
await original_close()
|
| 449 |
+
|
| 450 |
+
with patch.object(executor, 'close', wraps=observed_close) as close:
|
| 451 |
+
try:
|
| 452 |
+
self.assertTrue(await asyncio.to_thread(started.wait, 1))
|
| 453 |
+
request.cancel()
|
| 454 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 455 |
+
await request
|
| 456 |
+
closing = asyncio.create_task(lifespan.__aexit__(None, None, None))
|
| 457 |
+
await asyncio.wait_for(close_started.wait(), 1)
|
| 458 |
+
# Wait until the real drain has suspended on its owned job,
|
| 459 |
+
# not merely until the close wrapper has been scheduled.
|
| 460 |
+
async def drain_is_waiting():
|
| 461 |
+
while (executor._close_task is None or
|
| 462 |
+
executor._close_task._fut_waiter is None):
|
| 463 |
+
await asyncio.sleep(.001)
|
| 464 |
+
await asyncio.wait_for(drain_is_waiting(), 1)
|
| 465 |
+
self.assertFalse(executor._close_task.done())
|
| 466 |
+
self.assertFalse(executor._close_task._fut_waiter.done())
|
| 467 |
+
self.assertEqual(len(executor._tasks), 1)
|
| 468 |
+
self.assertFalse(next(iter(executor._tasks)).done())
|
| 469 |
+
self.assertTrue(executor._closing)
|
| 470 |
+
self.assertFalse(exited.is_set(), 'shutdown must not block the event loop')
|
| 471 |
+
self.assertTrue(worker[0].is_alive())
|
| 472 |
+
self.assertFalse(closing.done(), 'lifespan must wait for the worker')
|
| 473 |
+
self.assertIs(app.app.state.search_executor, executor)
|
| 474 |
+
self.assertFalse(session.close.called)
|
| 475 |
+
finally:
|
| 476 |
+
release.set()
|
| 477 |
+
if closing is None:
|
| 478 |
+
request.cancel()
|
| 479 |
+
await asyncio.gather(request, return_exceptions=True)
|
| 480 |
+
closing = asyncio.create_task(lifespan.__aexit__(None, None, None))
|
| 481 |
+
await asyncio.wait_for(closing, 3)
|
| 482 |
+
close.assert_awaited_once()
|
| 483 |
+
self.assertTrue(exited.is_set())
|
| 484 |
+
self.assertFalse(worker[0].is_alive(), 'lifespan must join the worker thread')
|
| 485 |
+
self.assertTrue(executor._pool._shutdown)
|
| 486 |
+
self.assertFalse(hasattr(app.app.state, 'search_executor'))
|
| 487 |
+
session.close.assert_awaited_once()
|
| 488 |
+
|
| 489 |
async def test_close_waits_for_started_work_after_requester_cancels(self):
|
| 490 |
started, release = threading.Event(), threading.Event()
|
| 491 |
executor = SearchExecutor()
|
|
|
|
| 514 |
await executor.close()
|
| 515 |
self.assertEqual(seen, ['done'])
|
| 516 |
|
| 517 |
+
async def test_cancelled_and_concurrent_close_keep_ownership_without_blocking_loop(self):
|
| 518 |
+
started, release, exited = threading.Event(), threading.Event(), threading.Event()
|
| 519 |
+
executor = SearchExecutor()
|
| 520 |
+
|
| 521 |
+
def slow():
|
| 522 |
+
started.set()
|
| 523 |
+
release.wait(1) # Bound even a broken, event-loop-blocking close.
|
| 524 |
+
exited.set()
|
| 525 |
+
return 42
|
| 526 |
+
|
| 527 |
+
active = asyncio.create_task(executor.run(slow))
|
| 528 |
+
closers = []
|
| 529 |
+
try:
|
| 530 |
+
self.assertTrue(await asyncio.to_thread(started.wait, .5))
|
| 531 |
+
owned = next(iter(executor._tasks))
|
| 532 |
+
closers = [asyncio.create_task(executor.close()) for _ in range(2)]
|
| 533 |
+
await asyncio.sleep(.01)
|
| 534 |
+
closers[0].cancel()
|
| 535 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 536 |
+
await closers[0]
|
| 537 |
+
await asyncio.sleep(.01)
|
| 538 |
+
self.assertFalse(exited.is_set(), 'close must not block the event loop')
|
| 539 |
+
self.assertIn(owned, executor._tasks)
|
| 540 |
+
self.assertFalse(owned.done())
|
| 541 |
+
self.assertFalse(closers[1].done())
|
| 542 |
+
with self.assertRaises(SearchBusy):
|
| 543 |
+
await executor.run(lambda: None)
|
| 544 |
+
closers.append(asyncio.create_task(executor.close()))
|
| 545 |
+
await asyncio.sleep(.01)
|
| 546 |
+
self.assertFalse(closers[-1].done())
|
| 547 |
+
self.assertIn(owned, executor._tasks)
|
| 548 |
+
finally:
|
| 549 |
+
release.set()
|
| 550 |
+
await asyncio.gather(active, *closers, return_exceptions=True)
|
| 551 |
+
await executor.close()
|
| 552 |
+
self.assertTrue(exited.is_set())
|
| 553 |
+
self.assertEqual(active.result()[0], 42)
|
| 554 |
+
self.assertEqual(executor._tasks, set())
|
| 555 |
+
self.assertTrue(executor._pool._shutdown)
|
| 556 |
+
|
| 557 |
async def test_cancelling_background_wait_keeps_foreground_ownership(self):
|
| 558 |
started, release = threading.Event(), threading.Event()
|
| 559 |
seen = []
|