Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions doc/changelog.rst
Original file line number Diff line number Diff line change
@@ -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)
--------------------------------------

Expand Down
6 changes: 5 additions & 1 deletion pymongo/asynchronous/command_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pymongo/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__}


Expand Down
6 changes: 5 additions & 1 deletion pymongo/synchronous/command_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
50 changes: 49 additions & 1 deletion test/asynchronous/test_async_cancellation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] = [""]

Expand Down Expand Up @@ -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):
Expand Down
Loading