From 61fdf2b2a0e8b7f739352d6a6486096004f5f24a Mon Sep 17 00:00:00 2001 From: Hilary Date: Fri, 13 Nov 2026 12:34:42 +0100 Subject: [PATCH 1/3] fix(bedrock): cancelling an embed call stops the rest of the batch Upstream-PR: https://github.com/genkit-ai/genkit/pull/6439 Co-authored-by: rootkiller6788 <221446036+rootkiller6788@users.noreply.github.com> --- .../src/genkit_amazon_bedrock/_embedders.py | 17 ++++++++- .../tests/embedders_test.py | 36 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py b/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py index 41dc27be2..3bcf6ebc5 100644 --- a/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py +++ b/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py @@ -553,7 +553,22 @@ async def _bounded(index: int, call: Coroutine[Any, Any, _T]) -> _T: raise tasks = [asyncio.create_task(_bounded(index, call)) for index, call in calls] - _, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) + try: + _, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) + except BaseException: + # create_task does not tie the tasks to this coroutine, and + # asyncio.wait does not cancel what it waits on, so a cancelled + # caller would leave the whole batch running and billing. + for task in tasks: + task.cancel() + # Same reason as below: retrieve the outcomes before letting the + # cancellation through. A second cancel can land on this gather, + # so swallow it and let the original exception surface. + try: + await asyncio.gather(*tasks, return_exceptions=True) + except BaseException: # noqa: S110 + pass + raise for task in pending: # Without this the rest of the batch still bills one call each. task.cancel() diff --git a/packages/genkit-amazon-bedrock/tests/embedders_test.py b/packages/genkit-amazon-bedrock/tests/embedders_test.py index 4ccb2ae19..cec6e8df6 100644 --- a/packages/genkit-amazon-bedrock/tests/embedders_test.py +++ b/packages/genkit-amazon-bedrock/tests/embedders_test.py @@ -649,6 +649,42 @@ async def test_a_failing_batch_cancels_the_calls_that_have_not_started() -> None assert len(transport.calls) < len(documents) +@pytest.mark.asyncio +async def test_cancelling_the_caller_stops_the_rest_of_the_batch() -> None: + documents = [text_doc(f'doc {i}') for i in range(50)] + + class SlowTransport: + """Completes in a moment, so lanes free and the queued calls would start.""" + + def __init__(self) -> None: + self.started = 0 + self.saturated = asyncio.Event() + + async def invoke_model(self, **kwargs: Any) -> dict[str, Any]: + self.started += 1 + if self.started >= EMBED_CONCURRENCY_LIMIT: + # Every lane is busy now, so the rest of the batch is queued. + self.saturated.set() + await asyncio.sleep(0.05) + return titan_response([1.0]) + + transport = SlowTransport() + embedder = BedrockEmbedder(model_id=TITAN_TEXT, transport=transport) + task = asyncio.create_task(embedder.embed(EmbedRequest(input=documents))) + await asyncio.wait_for(transport.saturated.wait(), timeout=5) + + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + started_when_cancelled = transport.started + # Long enough for the calls that were left alone to free their lanes and + # pull the rest of the batch through; without the cancel reaching them, all + # 50 documents end up on the wire. + await asyncio.sleep(0.3) + + assert transport.started == started_when_cancelled + + def test_the_semaphore_is_built_per_call_not_per_module() -> None: # A module-level semaphore binds to the first loop that has to wait on it, # and the Dev UI reflection server runs a second one. This needs more From 1a4a5782fc41afafceb68ab95393a2bd52b3c7f2 Mon Sep 17 00:00:00 2001 From: Jacob Cable Date: Thu, 26 Nov 2026 15:02:40 +0000 Subject: [PATCH 2/3] fix(bedrock): narrow cancellation catches in _run_bounded and document batch cancel Catch asyncio.CancelledError instead of BaseException around asyncio.wait and around the drain gather. - GeneratorExit no longer runs task.cancel() on a closed loop, which printed an extra "Event loop is closed" traceback. - KeyboardInterrupt and SystemExit raised during the drain are no longer replaced by the original CancelledError. The docstring now states that cancelling the caller cancels the whole batch, in-flight calls included. --- .../src/genkit_amazon_bedrock/_embedders.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py b/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py index 3bcf6ebc5..b3cf1ca59 100644 --- a/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py +++ b/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py @@ -523,6 +523,8 @@ async def _nova_vector(self, text: str) -> list[float]: async def _run_bounded(self, calls: list[tuple[int, Coroutine[Any, Any, _T]]]) -> list[_T]: """Runs the calls concurrently, cancelling the rest on the first failure. + Cancelling the caller cancels the whole batch, in-flight calls included. + The semaphore is built per call rather than once per module: it binds to the running loop, and the Dev UI reflection server runs a second one. """ @@ -555,7 +557,7 @@ async def _bounded(index: int, call: Coroutine[Any, Any, _T]) -> _T: tasks = [asyncio.create_task(_bounded(index, call)) for index, call in calls] try: _, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) - except BaseException: + except asyncio.CancelledError: # create_task does not tie the tasks to this coroutine, and # asyncio.wait does not cancel what it waits on, so a cancelled # caller would leave the whole batch running and billing. @@ -566,7 +568,7 @@ async def _bounded(index: int, call: Coroutine[Any, Any, _T]) -> _T: # so swallow it and let the original exception surface. try: await asyncio.gather(*tasks, return_exceptions=True) - except BaseException: # noqa: S110 + except asyncio.CancelledError: pass raise for task in pending: From 1a6b0d29ede15c23b2e260ef3d2e1b4f86f43c78 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 1 Dec 2026 10:49:04 +0100 Subject: [PATCH 3/3] fix(bedrock): report only calls that finished on their own in _run_bounded Also raise a CancelledError that came out of a call instead of returning it as a vector, and test in-flight cancel and caller timeouts. --- .../src/genkit_amazon_bedrock/_embedders.py | 17 +++- .../tests/embedders_test.py | 77 +++++++++++++++++++ 2 files changed, 90 insertions(+), 4 deletions(-) diff --git a/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py b/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py index b3cf1ca59..73b9f1343 100644 --- a/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py +++ b/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_embedders.py @@ -524,6 +524,8 @@ async def _run_bounded(self, calls: list[tuple[int, Coroutine[Any, Any, _T]]]) - """Runs the calls concurrently, cancelling the rest on the first failure. Cancelling the caller cancels the whole batch, in-flight calls included. + A ``CancelledError`` raised by a call itself does not stop the others + and is re-raised once they finish. The semaphore is built per call rather than once per module: it binds to the running loop, and the Dev UI reflection server runs a second one. @@ -556,7 +558,7 @@ async def _bounded(index: int, call: Coroutine[Any, Any, _T]) -> _T: tasks = [asyncio.create_task(_bounded(index, call)) for index, call in calls] try: - _, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) + done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) except asyncio.CancelledError: # create_task does not tie the tasks to this coroutine, and # asyncio.wait does not cancel what it waits on, so a cancelled @@ -577,10 +579,17 @@ async def _bounded(index: int, call: Coroutine[Any, Any, _T]) -> _T: # Also retrieves the cancelled outcomes, so none resurfaces later as # "Task exception was never retrieved". results = await asyncio.gather(*tasks, return_exceptions=True) - for result in results: + for task, result in zip(tasks, results, strict=True): # Index order, not completion order, so the reported failure is - # deterministic across the calls that were left to run. - if isinstance(result, BaseException) and not isinstance(result, asyncio.CancelledError): + # deterministic across the calls that were left to run. Only calls + # that finished on their own count: a call cancelled here may turn + # the cancellation into another error while cleaning up. + if task in done and isinstance(result, BaseException) and not isinstance(result, asyncio.CancelledError): + raise result + for result in results: + # Nothing failed, so nothing was cancelled here: this one came out + # of the call itself and must not be returned as a vector. + if isinstance(result, asyncio.CancelledError): raise result return cast(list[_T], results) diff --git a/packages/genkit-amazon-bedrock/tests/embedders_test.py b/packages/genkit-amazon-bedrock/tests/embedders_test.py index cec6e8df6..62c6ad781 100644 --- a/packages/genkit-amazon-bedrock/tests/embedders_test.py +++ b/packages/genkit-amazon-bedrock/tests/embedders_test.py @@ -685,6 +685,83 @@ async def invoke_model(self, **kwargs: Any) -> dict[str, Any]: assert transport.started == started_when_cancelled +class HangingTransport: + """Never answers, and counts the calls that started and were cancelled.""" + + def __init__(self) -> None: + self.started = 0 + self.cancelled = 0 + self.saturated = asyncio.Event() + + async def invoke_model(self, **kwargs: Any) -> dict[str, Any]: + self.started += 1 + if self.started >= EMBED_CONCURRENCY_LIMIT: + self.saturated.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + self.cancelled += 1 + raise + raise AssertionError('unreachable') + + +@pytest.mark.asyncio +async def test_cancelling_the_caller_cancels_the_calls_in_flight() -> None: + transport = HangingTransport() + embedder = BedrockEmbedder(model_id=TITAN_TEXT, transport=transport) + documents = [text_doc(f'doc {i}') for i in range(50)] + task = asyncio.create_task(embedder.embed(EmbedRequest(input=documents))) + await asyncio.wait_for(transport.saturated.wait(), timeout=5) + + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + assert transport.started == EMBED_CONCURRENCY_LIMIT + assert transport.cancelled == EMBED_CONCURRENCY_LIMIT + + +@pytest.mark.asyncio +async def test_a_caller_timeout_raises_timeout_and_starts_no_more_calls() -> None: + transport = HangingTransport() + documents = [text_doc(f'doc {i}') for i in range(50)] + + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(embed(TITAN_TEXT, transport, documents), timeout=0.05) + + assert transport.started == EMBED_CONCURRENCY_LIMIT + assert transport.cancelled == EMBED_CONCURRENCY_LIMIT + + +@pytest.mark.asyncio +async def test_an_error_raised_while_cancelling_does_not_hide_the_real_failure() -> None: + class CleanupFailingTransport: + async def invoke_model(self, **kwargs: Any) -> dict[str, Any]: + text = json.loads(kwargs['body'])['inputText'] + if text == 'bad': + raise ClientError({'Error': {'Code': 'ValidationException', 'Message': text}}, 'InvokeModel') + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + raise RuntimeError('cleanup failed') from None + raise AssertionError('unreachable') + + with pytest.raises(GenkitError, match='document 1'): + await embed(TITAN_TEXT, CleanupFailingTransport(), [text_doc('hangs'), text_doc('bad')]) + + +@pytest.mark.asyncio +async def test_a_call_that_raises_cancelled_error_is_not_returned_as_a_vector() -> None: + class SelfCancellingTransport: + async def invoke_model(self, **kwargs: Any) -> dict[str, Any]: + if json.loads(kwargs['body'])['inputText'] == 'cancels': + raise asyncio.CancelledError + return titan_response([1.0]) + + with pytest.raises(asyncio.CancelledError): + await embed(TITAN_TEXT, SelfCancellingTransport(), [text_doc('ok'), text_doc('cancels')]) + + def test_the_semaphore_is_built_per_call_not_per_module() -> None: # A module-level semaphore binds to the first loop that has to wait on it, # and the Dev UI reflection server runs a second one. This needs more