diff --git a/doc/changelog.rst b/doc/changelog.rst index d4e6193715..47d5b82f87 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,19 @@ Changelog ========= +Changes in Version 4.21.0 (unreleased) +-------------------------------------- + +Bug fixes +......... + +- Fixed a bug where a cancelled async command published a + ``CommandStartedEvent`` (and its "Command started" log message) without a + correlating ``CommandFailedEvent``. A cancellation now publishes the failure + before the ``CancelledError`` propagates (`PYTHON-6187`_). + +.. _PYTHON-6187: https://jira.mongodb.org/browse/PYTHON-6187 + Changes in Version 4.20.1 (2026/XX/XX) -------------------------------------- diff --git a/pymongo/asynchronous/command_runner.py b/pymongo/asynchronous/command_runner.py index b1c5421537..29150a4b55 100644 --- a/pymongo/asynchronous/command_runner.py +++ b/pymongo/asynchronous/command_runner.py @@ -216,11 +216,15 @@ async def _run_command( parse_write_concern_error=parse_write_concern_error, pool_opts=pool_opts, ) - except Exception as exc: + except BaseException as exc: if isinstance(exc, (NotPrimaryError, OperationFailure)): failure: _DocumentOut = exc.details # type: ignore[assignment] else: failure = _convert_exception(exc) + if not failure["errmsg"]: + # CancelledError, KeyboardInterrupt, and SystemExit + # stringify to "". + failure["errmsg"] = f"operation interrupted by {exc.__class__.__name__}" if telemetry is not None: telemetry.failed(failure, command_name, isinstance(exc, OperationFailure)) raise diff --git a/pymongo/message.py b/pymongo/message.py index 18c4ae162a..ead44f071a 100644 --- a/pymongo/message.py +++ b/pymongo/message.py @@ -126,8 +126,8 @@ def _maybe_add_read_preference( return spec -def _convert_exception(exception: Exception) -> dict[str, Any]: - """Convert an Exception into a failure document for publishing.""" +def _convert_exception(exception: BaseException) -> dict[str, Any]: + """Convert an exception into a failure document for publishing.""" return {"errmsg": str(exception), "errtype": exception.__class__.__name__} diff --git a/pymongo/synchronous/command_runner.py b/pymongo/synchronous/command_runner.py index 3381f117a2..1d1adfec2f 100644 --- a/pymongo/synchronous/command_runner.py +++ b/pymongo/synchronous/command_runner.py @@ -216,11 +216,15 @@ def _run_command( parse_write_concern_error=parse_write_concern_error, pool_opts=pool_opts, ) - except Exception as exc: + except BaseException as exc: if isinstance(exc, (NotPrimaryError, OperationFailure)): failure: _DocumentOut = exc.details # type: ignore[assignment] else: failure = _convert_exception(exc) + if not failure["errmsg"]: + # CancelledError, KeyboardInterrupt, and SystemExit + # stringify to "". + failure["errmsg"] = f"operation interrupted by {exc.__class__.__name__}" if telemetry is not None: telemetry.failed(failure, command_name, isinstance(exc, OperationFailure)) raise diff --git a/test/asynchronous/test_async_cancellation.py b/test/asynchronous/test_async_cancellation.py index 63688e413c..24a8fc4d9d 100644 --- a/test/asynchronous/test_async_cancellation.py +++ b/test/asynchronous/test_async_cancellation.py @@ -18,9 +18,10 @@ import asyncio import sys +import time from test.asynchronous.utils import async_get_pool -from test.utils_shared import delay, one +from test.utils_shared import OvertCommandListener, delay, one sys.path[0:0] = [""] @@ -100,6 +101,53 @@ async def task(): self.assertTrue(cursor._killed) + @async_client_context.require_failCommand_blockConnection + async def test_async_cancellation_publishes_command_failed_event(self): + # PYTHON-6187: a cancelled command must still get its + # CommandFailedEvent, per the Command Logging and Monitoring spec. + listener = OvertCommandListener() + client = await self.async_single_client(event_listeners=[listener]) + await self.client.db.coll.insert_one({"x": 1}) + self.addAsyncCleanup(self.client.db.coll.delete_many, {}) + + # Make sure the find blocks. + fail_command = { + "configureFailPoint": "failCommand", + "mode": "alwaysOn", + "data": {"failCommands": ["find"], "blockConnection": True, "blockTimeMS": 1000}, + } + + def find_started() -> bool: + return any(e.command_name == "find" for e in listener.started_events) + + async def await_find_started() -> None: + deadline = time.monotonic() + 10 + while not find_started(): + if time.monotonic() > deadline: + self.fail("the find command never started") + await asyncio.sleep(0.01) + + # Configure the failpoint before the task so the find blocks as soon + # as it starts. + async with self.fail_point(fail_command): + task = asyncio.create_task(client.db.coll.find_one({})) + try: + # A fixed sleep cannot confirm the find started, the task + # first has to connect its client. + await await_find_started() + finally: + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await task + + started = [e for e in listener.started_events if e.command_name == "find"] + failed = [e for e in listener.failed_events if e.command_name == "find"] + self.assertEqual(len(started), 1) + self.assertEqual(len(failed), 1) + self.assertEqual(failed[0].request_id, started[0].request_id) + self.assertEqual(failed[0].failure["errtype"], "CancelledError") + self.assertIn("CancelledError", failed[0].failure["errmsg"]) + @async_client_context.require_change_streams @async_client_context.require_failCommand_blockConnection async def test_async_cancellation_closes_change_stream(self):