diff --git a/aws_lambda_powertools/event_handler/middlewares/async_utils.py b/aws_lambda_powertools/event_handler/middlewares/async_utils.py index 0e215589820..88e8d7c6f3f 100644 --- a/aws_lambda_powertools/event_handler/middlewares/async_utils.py +++ b/aws_lambda_powertools/event_handler/middlewares/async_utils.py @@ -145,6 +145,12 @@ def __init__( self.current_middleware: Callable[..., Any] = current_middleware self.next_middleware: Callable[..., Any] = next_middleware self._next_middleware_name = next_middleware.__name__ + # Class-based middlewares expose their logic through `handler`, which may be a coroutine + # function even though the instance itself is not + middleware_handler = getattr(current_middleware, "handler", None) + self._is_async_middleware = inspect.iscoroutinefunction(current_middleware) or inspect.iscoroutinefunction( + middleware_handler, + ) @property def __name__(self) -> str: # noqa: A003 @@ -162,26 +168,43 @@ async def __call__(self, app: ApiGatewayResolver) -> dict | tuple | Response: extra_kwargs = _resolve_extra_middleware_kwargs(app, self.current_middleware) - # Class-based middlewares expose their logic through `handler`, which may be a coroutine - # function even though the instance itself is not - middleware_handler = getattr(self.current_middleware, "handler", None) - is_async_middleware = inspect.iscoroutinefunction( - self.current_middleware, - ) or inspect.iscoroutinefunction(middleware_handler) - - if is_async_middleware: + if self._is_async_middleware: result = self.current_middleware(app, self.next_middleware, **extra_kwargs) if inspect.iscoroutine(result): result = await result return result loop = asyncio.get_running_loop() + return await asyncio.to_thread(self._run_sync_middleware, app, loop, extra_kwargs) + + def _run_sync_middleware(self, app: ApiGatewayResolver, loop: asyncio.AbstractEventLoop, extra_kwargs: dict) -> Any: + """Run this sync middleware in the current worker thread. + + Consecutive sync middlewares stay in this thread. Hopping back to the event loop only to borrow a + second executor thread for the next sync middleware is what deadlocked under load: with every + executor thread blocked inside the first middleware, the second one could never start (#8866). + Only an async next step is scheduled on the event loop. + """ def sync_next(app: ApiGatewayResolver) -> Any: - future = asyncio.run_coroutine_threadsafe(self.next_middleware(app), loop) + next_middleware = self.next_middleware + if isinstance(next_middleware, AsyncMiddlewareFrame) and not next_middleware._is_async_middleware: + return next_middleware._run_sync_middleware_inline(app, loop) + + future = asyncio.run_coroutine_threadsafe(next_middleware(app), loop) return future.result() - return await asyncio.to_thread(self.current_middleware, app, sync_next, **extra_kwargs) + return self.current_middleware(app, sync_next, **extra_kwargs) + + def _run_sync_middleware_inline(self, app: ApiGatewayResolver, loop: asyncio.AbstractEventLoop) -> Any: + """Entry point used by the previous sync frame to run this frame in the same worker thread.""" + logger.debug("AsyncMiddlewareFrame: %s", self) + app._push_processed_stack_frame(str(self)) + + from aws_lambda_powertools.event_handler.api_gateway import _resolve_extra_middleware_kwargs + + extra_kwargs = _resolve_extra_middleware_kwargs(app, self.current_middleware) + return self._run_sync_middleware(app, loop, extra_kwargs) async def _registered_api_adapter_async( diff --git a/tests/functional/event_handler/_pydantic/test_http_resolver_pydantic.py b/tests/functional/event_handler/_pydantic/test_http_resolver_pydantic.py index 9f66784d579..b691f2801bb 100644 --- a/tests/functional/event_handler/_pydantic/test_http_resolver_pydantic.py +++ b/tests/functional/event_handler/_pydantic/test_http_resolver_pydantic.py @@ -540,3 +540,68 @@ async def start(name): await asyncio.gather(*pending, return_exceptions=True) asyncio.run(scenario()) + + +# ============================================================================= +# Concurrency Tests (#8866) +# ============================================================================= + + +async def _asgi_call(app: HttpResolverLocal, path: str) -> dict[str, Any]: + scope = {"type": "http", "method": "GET", "path": path, "query_string": b"", "headers": []} + send, captured = make_asgi_send() + await app(scope, make_asgi_receive(), send) + return captured + + +async def _gather_with_small_executor(coroutines, max_workers: int = 2): + # A tiny executor makes the thread starvation deterministic: with more in-flight requests + # than worker threads, a sync middleware that needs a second thread to run the next one never gets it + from concurrent.futures import ThreadPoolExecutor + + executor = ThreadPoolExecutor(max_workers=max_workers) + asyncio.get_running_loop().set_default_executor(executor) + try: + return await asyncio.wait_for(asyncio.gather(*coroutines), timeout=5) + finally: + executor.shutdown(wait=False, cancel_futures=True) + + +@pytest.mark.asyncio +async def test_asgi_concurrent_requests_with_validation_do_not_deadlock(): + # GIVEN an app with validation enabled, which adds two sync middlewares around every route + app = HttpResolverLocal(enable_validation=True) + + @app.get("/ping") + def ping() -> dict[str, str]: + return {"ok": "yes"} + + # WHEN more requests arrive at once than there are executor threads + results = await _gather_with_small_executor([_asgi_call(app, "/ping") for _ in range(6)]) + + # THEN every request is answered + assert [captured["status_code"] for captured in results] == [200] * 6 + + +@pytest.mark.asyncio +async def test_asgi_concurrent_requests_keep_request_state_isolated(): + # GIVEN validation enabled plus a sync middleware that stores request data in the context + app = HttpResolverLocal(enable_validation=True) + + def remember_path(app: HttpResolverLocal, next_middleware): + app.append_context(seen=app.current_event.path) + return next_middleware(app) + + app.use([remember_path]) + + @app.get("/echo/") + def echo(value: str) -> dict[str, str]: + return {"value": value, "seen": app.context["seen"]} + + # WHEN many distinct requests run concurrently through the sync middleware chain + results = await _gather_with_small_executor([_asgi_call(app, f"/echo/v{i}") for i in range(12)]) + + # THEN each caller gets its own value and its own context back + for i, captured in enumerate(results): + assert captured["status_code"] == 200 + assert json.loads(captured["body"]) == {"value": f"v{i}", "seen": f"/echo/v{i}"} diff --git a/tests/functional/event_handler/required_dependencies/test_http_resolver.py b/tests/functional/event_handler/required_dependencies/test_http_resolver.py index ffcc6135339..ee535875425 100644 --- a/tests/functional/event_handler/required_dependencies/test_http_resolver.py +++ b/tests/functional/event_handler/required_dependencies/test_http_resolver.py @@ -1577,3 +1577,58 @@ def handler(): assert result["statusCode"] == 200 assert "cookies" in result assert "multiValueHeaders" not in result + + +# ============================================================================= +# Concurrency Tests (#8866) +# ============================================================================= + + +def _asgi_scope(path: str) -> dict[str, Any]: + return {"type": "http", "method": "GET", "path": path, "query_string": b"", "headers": []} + + +async def _asgi_call(app: HttpResolverLocal, path: str) -> dict[str, Any]: + send, captured = make_asgi_send() + await app(_asgi_scope(path), make_asgi_receive(), send) + return captured + + +async def _gather_with_small_executor(coroutines, max_workers: int = 2): + # A tiny executor makes the thread starvation deterministic: with more in-flight requests + # than worker threads, a sync middleware that needs a second thread to run the next one never gets it + from concurrent.futures import ThreadPoolExecutor + + executor = ThreadPoolExecutor(max_workers=max_workers) + asyncio.get_running_loop().set_default_executor(executor) + try: + return await asyncio.wait_for(asyncio.gather(*coroutines), timeout=5) + finally: + executor.shutdown(wait=False, cancel_futures=True) + + +@pytest.mark.asyncio +async def test_asgi_concurrent_requests_with_chained_sync_middlewares_do_not_deadlock(): + # GIVEN two consecutive sync middlewares and no validation + app = HttpResolverLocal() + + def first(app: HttpResolverLocal, next_middleware): + app.append_context(first="seen") + return next_middleware(app) + + def second(app: HttpResolverLocal, next_middleware): + app.append_context(second="seen") + return next_middleware(app) + + app.use([first, second]) + + @app.get("/ping") + def ping(): + return {"first": app.context["first"], "second": app.context["second"]} + + # WHEN more requests arrive at once than there are executor threads + results = await _gather_with_small_executor([_asgi_call(app, "/ping") for _ in range(6)]) + + # THEN every request goes through both middlewares and is answered + assert [captured["status_code"] for captured in results] == [200] * 6 + assert all(json.loads(captured["body"]) == {"first": "seen", "second": "seen"} for captured in results)