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 41dc27be..73b9f134 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,10 @@ 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. + 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. """ @@ -553,17 +557,39 @@ 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: + 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 + # 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 asyncio.CancelledError: + pass + raise for task in pending: # Without this the rest of the batch still bills one call each. task.cancel() # 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 4ccb2ae1..62c6ad78 100644 --- a/packages/genkit-amazon-bedrock/tests/embedders_test.py +++ b/packages/genkit-amazon-bedrock/tests/embedders_test.py @@ -649,6 +649,119 @@ 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 + + +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