vomebook commited on
Commit ·
ffb393d
1
Parent(s): d270929
Preserve search executor ownership during shutdown
Browse filesFiles changed (4)
1332 unmodified lines133313341335133613371338133910 unmodified lines1350135113521353135413551332 unmodified linesapp.state.reader_index_build_task.cancel()await asyncio.gather(app.state.reader_index_build_task, return_exceptions=True)app.state.reader_index_build_task = Noneawait app.state.search_executor.close()del app.state.search_executorif app.state.reader_assets_task is not None:app.state.reader_assets_task.cancel()10 unmodified linesapp.state.reader_range_cache.clear()app.state.reader_range_cache_bytes = 0await app.state.http_session.close()app = FastAPI(title="VoiceOfML Search", version="2.0", lifespan=lifespan)app.add_middleware(GZipMiddleware, minimum_size=500)app.add_middleware(1332 unmodified lines13331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135910 unmodified lines137013711372137313741375137613771332 unmodified linesapp.state.reader_index_build_task.cancel()await asyncio.gather(app.state.reader_index_build_task, return_exceptions=True)app.state.reader_index_build_task = None# Defer cancellation until the real worker and join finish and resources close.close_task = asyncio.create_task(app.state.search_executor.close())cancelled = Nonewhile True:try:await asyncio.shield(close_task)breakexcept asyncio.CancelledError as exc:if close_task.cancelled():raiseif cancelled is None:cancelled = excexcept Exception as exc:if cancelled is None:raiseasyncio.get_running_loop().call_exception_handler({"message": "SearchExecutor close failed during lifespan cancellation","exception": exc,"task": close_task,})raise cancelleddel app.state.search_executorif app.state.reader_assets_task is not None:app.state.reader_assets_task.cancel()10 unmodified linesapp.state.reader_range_cache.clear()app.state.reader_range_cache_bytes = 0await app.state.http_session.close()if cancelled is not None:raise cancelledapp = FastAPI(title="VoiceOfML Search", version="2.0", lifespan=lifespan)app.add_middleware(GZipMiddleware, minimum_size=500)app.add_middleware(
1 unmodified line234567891011121314 unmodified lines2829303132331 unmodified line35363738394049 unmodified lines9091929394951 unmodified lineimport asynciofrom collections.abc import Callablefrom concurrent.futures import ThreadPoolExecutorimport timeimport threadingfrom types import TracebackTypefrom typing import TypeVarT = TypeVar("T")14 unmodified linesraise SearchCancelled()class SearchExecutor:def __init__(self, capacity: int = 32) -> None:self.capacity = capacity1 unmodified lineself._lock = asyncio.Lock()self._tasks: set[asyncio.Task[tuple[object, float, float]]] = set()self._closing = Falseself._foreground: set[asyncio.Task[tuple[object, float, float]]] = set()async def __aenter__(self) -> "SearchExecutor":49 unmodified linesraiseasync def close(self) -> None:self._closing = Trueawait asyncio.gather(*self._tasks, return_exceptions=True)self._pool.shutdown(wait=True)1 unmodified line234567891011121314151614 unmodified lines3132333435363738394041424344454647481 unmodified line505152535455565749 unmodified lines1071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651 unmodified lineimport asynciofrom collections.abc import Callablefrom concurrent.futures import ThreadPoolExecutorimport loggingimport timeimport threadingfrom types import TracebackTypefrom typing import TypeVarlogger = logging.getLogger(__name__)T = TypeVar("T")14 unmodified linesraise SearchCancelled()def _report_close_failure(task: asyncio.Task[None], state: dict[str, int | bool]) -> None:if task.done() and not task.cancelled():error = task.exception()if error is not None and not state["waiters"] and not state["observed"]:state["observed"] = Truetask.get_loop().call_exception_handler({"message": "SearchExecutor close failed without a waiting caller","exception": error,"task": task,})class SearchExecutor:def __init__(self, capacity: int = 32) -> None:self.capacity = capacity1 unmodified lineself._lock = asyncio.Lock()self._tasks: set[asyncio.Task[tuple[object, float, float]]] = set()self._closing = Falseself._close_task: asyncio.Task[None] | None = Noneself._close_state: dict[str, int | bool] | None = Noneself._foreground: set[asyncio.Task[tuple[object, float, float]]] = set()async def __aenter__(self) -> "SearchExecutor":49 unmodified linesraiseasync def close(self) -> None:if (self._close_task is None or(self._close_task.done() and(self._close_task.cancelled() or self._close_task.exception() is not None))):self._closing = Trueasync def drain() -> None:await asyncio.gather(*self._tasks, return_exceptions=True)loop = asyncio.get_running_loop()joined = loop.create_future()def notify(error: BaseException | None) -> None:if not joined.done():if error is None:joined.set_result(None)else:joined.set_exception(error)def shutdown() -> None:error = Nonetry:self._pool.shutdown(wait=True)except BaseException as exc:error = exc# Log in the worker: even a successfully queued callback may# never run if the loop closes, or its future is cancelled.logger.exception("SearchExecutor shutdown failed")try:loop.call_soon_threadsafe(notify, error)except RuntimeError:# The host must keep the loop alive until close completes.passthreading.Thread(target=shutdown, name="search-shutdown").start()await joinedself._close_task = asyncio.create_task(drain())close_state: dict[str, int | bool] = {"waiters": 0, "observed": False}self._close_state = close_stateself._close_task.add_done_callback(lambda task: _report_close_failure(task, close_state))task = self._close_taskstate = self._close_stateif state is None:raise RuntimeError("SearchExecutor close state missing")state["waiters"] += 1try:# A cancelled caller must not cancel the drain or its owned jobs.await asyncio.shield(task)except asyncio.CancelledError:raiseexcept BaseException:state["observed"] = Trueraisefinally:state["waiters"] -= 1_report_close_failure(task, state)
2 unmodified lines345678494 unmodified lines5035045055065075082 unmodified linesimport gzipimport importlibimport jsonfrom pathlib import Pathfrom tempfile import TemporaryDirectoryfrom types import SimpleNamespace494 unmodified linesclose_flights.assert_awaited_once()self.assertFalse(application.state.download_warm_enabled)async def test_lifespan_tolerates_absent_warm_task_and_still_closes_resources(self):application = FastAPI()session = SimpleNamespace(close=AsyncMock())2 unmodified lines3456789494 unmodified lines5045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646652 unmodified linesimport gzipimport importlibimport jsonimport threadingfrom pathlib import Pathfrom tempfile import TemporaryDirectoryfrom types import SimpleNamespace494 unmodified linesclose_flights.assert_awaited_once()self.assertFalse(application.state.download_warm_enabled)async def test_lifespan_cancelled_executor_close_drains_before_cleanup(self):application = FastAPI()worker_started, release_worker = threading.Event(), threading.Event()join_started, release_join = threading.Event(), threading.Event()events = []session = SimpleNamespace(close=AsyncMock(side_effect=lambda: events.append('session')))def record(name, *args):events.append(name)async def wait_for(event):for _ in range(200):if event.is_set():returnawait asyncio.sleep(.01)self.fail('timed out waiting for thread')with patch.object(app, 'load_data'), \patch.object(app.aiohttp, 'ClientSession', return_value=session), \patch.object(app.aiohttp, 'TCPConnector', return_value=object()), \patch.object(app, 'initialize_reader_bucket_state'), \patch.object(app, 'initialize_reader_archive_state'), \patch.object(app, 'shutdown_reader_bucket_state', side_effect=lambda *a: record('bucket', *a)), \patch.object(app, 'shutdown_reader_archive_state', side_effect=lambda *a: record('archive', *a)), \patch.object(app, 'shutdown_reader_range_flights', side_effect=lambda: record('flights')), \patch.object(app, 'warm_reader_indexes', new_callable=AsyncMock):context = app.lifespan(application)await context.__aenter__()executor = application.state.search_executororiginal_shutdown = executor._pool.shutdowndef worker():worker_started.set()release_worker.wait(3)events.append('worker')def join(*, wait):join_started.set()release_join.wait(3)original_shutdown(wait=wait)events.append('join')with patch.object(executor._pool, 'shutdown', side_effect=join):job = asyncio.create_task(executor.run(worker))closing = Nonetry:await wait_for(worker_started)closing = asyncio.create_task(context.__aexit__(None, None, None))for _ in range(200):if executor._closing:breakawait asyncio.sleep(.01)self.assertTrue(executor._closing)closing.cancel('shutdown cancelled')await asyncio.sleep(.05)self.assertFalse(closing.done())self.assertEqual(events, [])release_worker.set()await wait_for(join_started)closing.cancel('again')await asyncio.sleep(.05)self.assertFalse(closing.done())self.assertEqual(events, ['worker'])release_join.set()with self.assertRaises(asyncio.CancelledError) as cancelled:await asyncio.wait_for(closing, 2)self.assertEqual(cancelled.exception.args, ('shutdown cancelled',))await asyncio.wait_for(job, 1)self.assertEqual(events, ['worker', 'join', 'bucket', 'archive', 'flights', 'session'])self.assertFalse(hasattr(application.state, 'search_executor'))self.assertFalse(application.state.download_warm_enabled)finally:release_worker.set()release_join.set()await asyncio.gather(job, return_exceptions=True)if closing is not None:await asyncio.gather(closing, return_exceptions=True)await executor.close()async def test_lifespan_thread_start_failure_with_and_without_cancellation(self):for cancel in (True, False):with self.subTest(cancel=cancel):application = FastAPI()started, release = threading.Event(), threading.Event()session = SimpleNamespace(close=AsyncMock())failure = RuntimeError('shutdown thread start failed')reports = []loop = asyncio.get_running_loop()previous_handler = loop.get_exception_handler()original_start = threading.Thread.startdef start(thread):if thread.name == 'search-shutdown':raise failurereturn original_start(thread)def worker():started.set()release.wait(3)async def wait_until(predicate):async with asyncio.timeout(2):while not predicate():await asyncio.sleep(.01)with patch.object(app, 'load_data'), \patch.object(app.aiohttp, 'ClientSession', return_value=session), \patch.object(app.aiohttp, 'TCPConnector', return_value=object()), \patch.object(app, 'initialize_reader_bucket_state'), \patch.object(app, 'initialize_reader_archive_state'), \patch.object(app, 'shutdown_reader_bucket_state', new_callable=AsyncMock) as bucket, \patch.object(app, 'shutdown_reader_archive_state', new_callable=AsyncMock) as archive, \patch.object(app, 'shutdown_reader_range_flights', new_callable=AsyncMock) as flights, \patch.object(app, 'warm_reader_indexes', new_callable=AsyncMock):loop.set_exception_handler(lambda loop, context: reports.append(context))context = app.lifespan(application)await context.__aenter__()executor = application.state.search_executorjob = asyncio.create_task(executor.run(worker))closing = Nonetry:await wait_until(started.is_set)with patch.object(threading.Thread, 'start', new=start):closing = asyncio.create_task(context.__aexit__(None, None, None))await wait_until(lambda: executor._closing)if cancel:closing.cancel('original cancellation')await asyncio.sleep(.05)self.assertFalse(closing.done())release.set()if cancel:with self.assertRaises(asyncio.CancelledError) as caught:await asyncio.wait_for(closing, 2)self.assertEqual(caught.exception.args, ('original cancellation',))self.assertEqual(len(reports), 1)self.assertIs(reports[0]['exception'], failure)self.assertIn('close failed', reports[0]['message'])else:with self.assertRaises(RuntimeError) as caught:await asyncio.wait_for(closing, 2)self.assertIs(caught.exception, failure)self.assertEqual(reports, [])await asyncio.wait_for(job, 2)self.assertIs(application.state.search_executor, executor)self.assertIs(application.state.http_session, session)self.assertTrue(application.state.download_warm_enabled)session.close.assert_not_awaited()bucket.assert_not_awaited(); archive.assert_not_awaited(); flights.assert_not_awaited()finally:release.set()await asyncio.gather(job, return_exceptions=True)if closing is not None:await asyncio.gather(closing, return_exceptions=True)await asyncio.wait_for(executor.close(), 2)loop.set_exception_handler(previous_handler)async def test_lifespan_tolerates_absent_warm_task_and_still_closes_resources(self):application = FastAPI()session = SimpleNamespace(close=AsyncMock())
1234151 unmodified lines15615715815916016119 unmodified lines18118218318418518622 unmodified lines209210211212213214import asyncioimport threadingimport timeimport unittest151 unmodified linesshutdown.assert_called_once_with(wait=True)self.assertIs(executor._closing, True)async def test_background_executor_drains_before_context_exit(self):async with SearchExecutor() as executor:result = await asyncio.wait_for(executor.run(lambda: 'background', background=True), .5)19 unmodified linesself.assertEqual(executor._foreground, set())self.assertEqual(executor._tasks, set())async def test_close_waits_for_started_work_after_requester_cancels(self):started, release = threading.Event(), threading.Event()executor = SearchExecutor()22 unmodified linesawait executor.close()self.assertEqual(seen, ['done'])async def test_cancelling_background_wait_keeps_foreground_ownership(self):started, release = threading.Event(), threading.Event()seen = []12345151 unmodified lines15715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838919 unmodified lines40941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049122 unmodified lines514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559import asynciofrom concurrent.futures import ThreadPoolExecutorimport threadingimport timeimport unittest151 unmodified linesshutdown.assert_called_once_with(wait=True)self.assertIs(executor._closing, True)async def test_close_after_default_executor_shutdown(self):executor = SearchExecutor()self.assertEqual((await executor.run(lambda: 42))[0], 42)await asyncio.get_running_loop().shutdown_default_executor()await asyncio.wait_for(executor.close(), 1)await asyncio.wait_for(executor.close(), 1)self.assertTrue(executor._pool._shutdown)async def test_close_does_not_wait_for_busy_default_executor(self):loop = asyncio.get_running_loop()default = ThreadPoolExecutor(max_workers=1)loop.set_default_executor(default)started, release = threading.Event(), threading.Event()def occupy():started.set()release.wait(1)occupied = loop.run_in_executor(None, occupy)executor = SearchExecutor()try:for _ in range(50):if started.is_set():breakawait asyncio.sleep(.01)self.assertTrue(started.is_set())await asyncio.wait_for(executor.close(), .5)self.assertFalse(occupied.done())finally:release.set()await asyncio.wait_for(occupied, 2)await asyncio.wait_for(executor.close(), 2)async def test_shutdown_error_propagates_to_all_close_callers(self):executor = SearchExecutor()error = RuntimeError('shutdown failed')with patch.object(executor._pool, 'shutdown', side_effect=error) as shutdown:results = await asyncio.wait_for(asyncio.gather(executor.close(), executor.close(), return_exceptions=True), 1)self.assertEqual(results, [error, error])shutdown.assert_called_once_with(wait=True)await asyncio.wait_for(executor.close(), 1)self.assertTrue(executor._pool._shutdown)async def test_abandoned_close_failure_is_reported_once_and_retryable(self):executor = SearchExecutor()started, release = threading.Event(), threading.Event()error = RuntimeError('abandoned shutdown failure')def fail(*, wait):started.set()release.wait(1)raise errorwith patch.object(executor._pool, 'shutdown', side_effect=fail):callers = [asyncio.create_task(executor.close()) for _ in range(2)]try:for _ in range(50):if started.is_set():breakawait asyncio.sleep(.01)self.assertTrue(started.is_set())for caller in callers:caller.cancel()await asyncio.gather(*callers, return_exceptions=True)finally:release.set()for _ in range(50):if self._loop_errors:breakawait asyncio.sleep(.01)self.assertEqual(len(self._loop_errors), 1)self.assertIs(self._loop_errors.pop()['exception'], error)await asyncio.wait_for(executor.close(), 1)async def test_close_retries_after_shutdown_thread_start_failure(self):executor = SearchExecutor()error = RuntimeError('thread start failed')with patch('backend.search_execution.threading.Thread.start', side_effect=error) as start:results = await asyncio.wait_for(asyncio.gather(executor.close(), executor.close(), return_exceptions=True), 1)self.assertEqual(results, [error, error])start.assert_called_once_with()await asyncio.wait_for(executor.close(), 1)self.assertTrue(executor._pool._shutdown)async def test_shutdown_notification_ignores_cancelled_future(self):executor = SearchExecutor()started, release, finished = threading.Event(), threading.Event(), threading.Event()original = executor._pool.shutdowndef slow_shutdown(*, wait):started.set()release.wait(1)original(wait=wait)finished.set()with patch.object(executor._pool, 'shutdown', side_effect=slow_shutdown):closing = asyncio.create_task(executor.close())try:for _ in range(50):if started.is_set():breakawait asyncio.sleep(.01)self.assertTrue(started.is_set())executor._close_task.cancel()with self.assertRaises(asyncio.CancelledError):await closingfinally:release.set()for _ in range(50):if finished.is_set():breakawait asyncio.sleep(.01)self.assertTrue(finished.is_set())await asyncio.sleep(.02)await asyncio.wait_for(executor.close(), 1)self.assertTrue(executor._pool._shutdown)async def test_shutdown_notification_tolerates_closed_loop(self):executor = SearchExecutor()started, release, notified = threading.Event(), threading.Event(), threading.Event()original = executor._pool.shutdownloop = asyncio.get_running_loop()def slow_shutdown(*, wait):started.set()release.wait(1)original(wait=wait)def closed_loop(*args):notified.set()raise RuntimeError('Event loop is closed')with patch.object(executor._pool, 'shutdown', side_effect=slow_shutdown):closing = asyncio.create_task(executor.close())try:for _ in range(50):if started.is_set():breakawait asyncio.sleep(.01)self.assertTrue(started.is_set())executor._close_task.cancel()with self.assertRaises(asyncio.CancelledError):await closingwith patch.object(loop, 'call_soon_threadsafe', side_effect=closed_loop):release.set()for _ in range(50):if notified.is_set():breakawait asyncio.sleep(.01)self.assertTrue(notified.is_set())finally:release.set()await asyncio.wait_for(executor.close(), 1)async def test_shutdown_failure_logged_when_delivery_is_unavailable(self):for closed_loop in (False, True):with self.subTest(closed_loop=closed_loop):executor = SearchExecutor()started, release, notified = threading.Event(), threading.Event(), threading.Event()error = RuntimeError('undeliverable shutdown failure')loop = asyncio.get_running_loop()call_soon = loop.call_soon_threadsafedef fail(*, wait):started.set()release.wait(2)raise errordef notify(*args):try:if closed_loop:raise RuntimeError('Event loop is closed')return call_soon(*args)finally:notified.set()with patch.object(executor._pool, 'shutdown', side_effect=fail), \self.assertLogs('backend.search_execution', level='ERROR') as logs:closing = asyncio.create_task(executor.close())try:for _ in range(100):if started.is_set():breakawait asyncio.sleep(.01)self.assertTrue(started.is_set())executor._close_task.cancel()with self.assertRaises(asyncio.CancelledError):await closingwith patch.object(loop, 'call_soon_threadsafe', side_effect=notify):release.set()for _ in range(100):if notified.is_set():breakawait asyncio.sleep(.01)self.assertTrue(notified.is_set())await asyncio.sleep(.02)finally:release.set()self.assertEqual(len(logs.records), 1)self.assertIs(logs.records[0].exc_info[1], error)await asyncio.wait_for(executor.close(), 1)async def test_shutdown_join_does_not_block_event_loop(self):executor = SearchExecutor()started, release = threading.Event(), threading.Event()original = executor._pool.shutdowndef slow_shutdown(*, wait):started.set()release.wait(1)original(wait=wait)with patch.object(executor._pool, 'shutdown', side_effect=slow_shutdown):closing = asyncio.create_task(executor.close())try:for _ in range(50):if started.is_set():breakawait asyncio.sleep(.01)self.assertTrue(started.is_set())self.assertFalse(closing.done(), 'shutdown must not block the event loop')finally:release.set()await asyncio.wait_for(closing, 2)async def test_background_executor_drains_before_context_exit(self):async with SearchExecutor() as executor:result = await asyncio.wait_for(executor.run(lambda: 'background', background=True), .5)19 unmodified linesself.assertEqual(executor._foreground, set())self.assertEqual(executor._tasks, set())async def test_lifespan_waits_nonblocking_for_cancelled_request_worker(self):from backend import appfrom unittest.mock import AsyncMock, MagicMockstarted, release, exited = threading.Event(), threading.Event(), threading.Event()close_started = asyncio.Event()worker = []def slow(**params):worker.append(threading.current_thread())started.set()release.wait(2) # Also bounds a broken, blocking shutdown.exited.set()return {'results': [], 'total': 0, 'page': 1, 'page_size': 100}session = MagicMock()session.close = AsyncMock()with patch.object(app, 'load_data'), \patch.object(app, 'warm_reader_indexes', new_callable=AsyncMock), \patch.object(app.aiohttp, 'ClientSession', return_value=session), \patch.object(app.aiohttp, 'TCPConnector'), \patch.object(app, 'initialize_reader_bucket_state'), \patch.object(app, 'initialize_reader_archive_state'), \patch.object(app, 'shutdown_reader_bucket_state', new_callable=AsyncMock), \patch.object(app, 'shutdown_reader_archive_state', new_callable=AsyncMock), \patch.object(app, 'shutdown_reader_range_flights', new_callable=AsyncMock), \patch.object(app, 'search', slow):lifespan = app.lifespan(app.app)await lifespan.__aenter__()executor = app.app.state.search_executorrequest = asyncio.create_task(app.api_search(app.SearchRequest(q='query')))closing = Noneoriginal_close = executor.closeasync def observed_close():close_started.set()await original_close()with patch.object(executor, 'close', wraps=observed_close) as close:try:self.assertTrue(await asyncio.to_thread(started.wait, 1))request.cancel()with self.assertRaises(asyncio.CancelledError):await requestclosing = asyncio.create_task(lifespan.__aexit__(None, None, None))await asyncio.wait_for(close_started.wait(), 1)# Wait until the real drain has suspended on its owned job,# not merely until the close wrapper has been scheduled.async def drain_is_waiting():while (executor._close_task is None orexecutor._close_task._fut_waiter is None):await asyncio.sleep(.001)await asyncio.wait_for(drain_is_waiting(), 1)self.assertFalse(executor._close_task.done())self.assertFalse(executor._close_task._fut_waiter.done())self.assertEqual(len(executor._tasks), 1)self.assertFalse(next(iter(executor._tasks)).done())self.assertTrue(executor._closing)self.assertFalse(exited.is_set(), 'shutdown must not block the event loop')self.assertTrue(worker[0].is_alive())self.assertFalse(closing.done(), 'lifespan must wait for the worker')self.assertIs(app.app.state.search_executor, executor)self.assertFalse(session.close.called)finally:release.set()if closing is None:request.cancel()await asyncio.gather(request, return_exceptions=True)closing = asyncio.create_task(lifespan.__aexit__(None, None, None))await asyncio.wait_for(closing, 3)close.assert_awaited_once()self.assertTrue(exited.is_set())self.assertFalse(worker[0].is_alive(), 'lifespan must join the worker thread')self.assertTrue(executor._pool._shutdown)self.assertFalse(hasattr(app.app.state, 'search_executor'))session.close.assert_awaited_once()async def test_close_waits_for_started_work_after_requester_cancels(self):started, release = threading.Event(), threading.Event()executor = SearchExecutor()22 unmodified linesawait executor.close()self.assertEqual(seen, ['done'])async def test_cancelled_and_concurrent_close_keep_ownership_without_blocking_loop(self):started, release, exited = threading.Event(), threading.Event(), threading.Event()executor = SearchExecutor()def slow():started.set()release.wait(1) # Bound even a broken, event-loop-blocking close.exited.set()return 42active = asyncio.create_task(executor.run(slow))closers = []try:self.assertTrue(await asyncio.to_thread(started.wait, .5))owned = next(iter(executor._tasks))closers = [asyncio.create_task(executor.close()) for _ in range(2)]await asyncio.sleep(.01)closers[0].cancel()with self.assertRaises(asyncio.CancelledError):await closers[0]await asyncio.sleep(.01)self.assertFalse(exited.is_set(), 'close must not block the event loop')self.assertIn(owned, executor._tasks)self.assertFalse(owned.done())self.assertFalse(closers[1].done())with self.assertRaises(SearchBusy):await executor.run(lambda: None)closers.append(asyncio.create_task(executor.close()))await asyncio.sleep(.01)self.assertFalse(closers[-1].done())self.assertIn(owned, executor._tasks)finally:release.set()await asyncio.gather(active, *closers, return_exceptions=True)await executor.close()self.assertTrue(exited.is_set())self.assertEqual(active.result()[0], 42)self.assertEqual(executor._tasks, set())self.assertTrue(executor._pool._shutdown)async def test_cancelling_background_wait_keeps_foreground_ownership(self):started, release = threading.Event(), threading.Event()seen = []
backend/app.py+23-1
backend/search_execution.py+73-3
tests/backend/test_coverage_safety.py+157
tests/search/backend/test_search_execution.py+345