Skip to content

PYTHON-4993 - Reevaluate handling of asyncio.CancelledError #2132

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 3 additions & 0 deletions pymongo/_client_bulk_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"""Constants, types, and classes shared across Client Bulk Write API implementations."""
from __future__ import annotations

import asyncio
from typing import TYPE_CHECKING, Any, Mapping, MutableMapping, NoReturn

from pymongo.errors import ClientBulkWriteException, OperationFailure
Expand Down Expand Up @@ -75,5 +76,7 @@ def _throw_client_bulk_write_exception(
)
raise OperationFailure(errmsg, code, full_result)
if isinstance(full_result["error"], BaseException):
if isinstance(full_result["error"], asyncio.CancelledError):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this actually needed? Like do we catch BaseException where _throw_client_bulk_write_exception is called? Or is this added just to be safe?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. We don't catch BaseException when _throw_client_bulk_write_exception is called, so this can be removed.

raise
raise ClientBulkWriteException(full_result, verbose_results) from full_result["error"]
raise ClientBulkWriteException(full_result, verbose_results)
4 changes: 0 additions & 4 deletions pymongo/asynchronous/encryption.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,6 @@ def _wrap_encryption_errors() -> Iterator[None]:
# BSON encoding/decoding errors are unrelated to encryption so
# we should propagate them unchanged.
raise
except asyncio.CancelledError:
raise
except Exception as exc:
raise EncryptionError(exc) from exc

Expand Down Expand Up @@ -766,8 +764,6 @@ async def create_encrypted_collection(
await database.create_collection(name=name, **kwargs),
encrypted_fields,
)
except asyncio.CancelledError:
raise
except Exception as exc:
raise EncryptedCollectionError(exc, encrypted_fields) from exc

Expand Down
7 changes: 0 additions & 7 deletions pymongo/asynchronous/mongo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
"""
from __future__ import annotations

import asyncio
import contextlib
import os
import warnings
Expand Down Expand Up @@ -2038,8 +2037,6 @@ async def _process_kill_cursors(self) -> None:
for address, cursor_id, conn_mgr in pinned_cursors:
try:
await self._cleanup_cursor_lock(cursor_id, address, conn_mgr, None, False)
except asyncio.CancelledError:
raise
except Exception as exc:
if isinstance(exc, InvalidOperation) and self._topology._closed:
# Raise the exception when client is closed so that it
Expand All @@ -2054,8 +2051,6 @@ async def _process_kill_cursors(self) -> None:
for address, cursor_ids in address_to_cursor_ids.items():
try:
await self._kill_cursors(cursor_ids, address, topology, session=None)
except asyncio.CancelledError:
raise
except Exception as exc:
if isinstance(exc, InvalidOperation) and self._topology._closed:
raise
Expand All @@ -2070,8 +2065,6 @@ async def _process_periodic_tasks(self) -> None:
try:
await self._process_kill_cursors()
await self._topology.update_pool()
except asyncio.CancelledError:
raise
except Exception as exc:
if isinstance(exc, InvalidOperation) and self._topology._closed:
return
Expand Down
7 changes: 0 additions & 7 deletions pymongo/asynchronous/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

from __future__ import annotations

import asyncio
import atexit
import logging
import time
Expand Down Expand Up @@ -257,8 +256,6 @@ async def _check_server(self) -> ServerDescription:
details = cast(Mapping[str, Any], exc.details)
await self._topology.receive_cluster_time(details.get("$clusterTime"))
raise
except asyncio.CancelledError:
raise
except ReferenceError:
raise
except Exception as error:
Expand Down Expand Up @@ -424,8 +421,6 @@ def _get_seedlist(self) -> Optional[list[tuple[str, Any]]]:
if len(seedlist) == 0:
# As per the spec: this should be treated as a failure.
raise Exception
except asyncio.CancelledError:
raise
except Exception:
# As per the spec, upon encountering an error:
# - An error must not be raised
Expand Down Expand Up @@ -489,8 +484,6 @@ async def _run(self) -> None:
except ReferenceError:
# Topology was garbage-collected.
await self.close()
except asyncio.CancelledError:
raise
except Exception:
await self._pool.reset()

Expand Down
2 changes: 0 additions & 2 deletions pymongo/asynchronous/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -704,8 +704,6 @@ def _close_conn(self) -> None:
# shutdown.
try:
self.conn.close()
except asyncio.CancelledError:
raise
except Exception: # noqa: S110
pass

Expand Down
5 changes: 0 additions & 5 deletions pymongo/synchronous/encryption.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"""Support for explicit client-side field level encryption."""
from __future__ import annotations

import asyncio
import contextlib
import enum
import socket
Expand Down Expand Up @@ -127,8 +126,6 @@ def _wrap_encryption_errors() -> Iterator[None]:
# BSON encoding/decoding errors are unrelated to encryption so
# we should propagate them unchanged.
raise
except asyncio.CancelledError:
raise
except Exception as exc:
raise EncryptionError(exc) from exc

Expand Down Expand Up @@ -760,8 +757,6 @@ def create_encrypted_collection(
database.create_collection(name=name, **kwargs),
encrypted_fields,
)
except asyncio.CancelledError:
raise
except Exception as exc:
raise EncryptedCollectionError(exc, encrypted_fields) from exc

Expand Down
7 changes: 0 additions & 7 deletions pymongo/synchronous/mongo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
"""
from __future__ import annotations

import asyncio
import contextlib
import os
import warnings
Expand Down Expand Up @@ -2032,8 +2031,6 @@ def _process_kill_cursors(self) -> None:
for address, cursor_id, conn_mgr in pinned_cursors:
try:
self._cleanup_cursor_lock(cursor_id, address, conn_mgr, None, False)
except asyncio.CancelledError:
raise
except Exception as exc:
if isinstance(exc, InvalidOperation) and self._topology._closed:
# Raise the exception when client is closed so that it
Expand All @@ -2048,8 +2045,6 @@ def _process_kill_cursors(self) -> None:
for address, cursor_ids in address_to_cursor_ids.items():
try:
self._kill_cursors(cursor_ids, address, topology, session=None)
except asyncio.CancelledError:
raise
except Exception as exc:
if isinstance(exc, InvalidOperation) and self._topology._closed:
raise
Expand All @@ -2064,8 +2059,6 @@ def _process_periodic_tasks(self) -> None:
try:
self._process_kill_cursors()
self._topology.update_pool()
except asyncio.CancelledError:
raise
except Exception as exc:
if isinstance(exc, InvalidOperation) and self._topology._closed:
return
Expand Down
7 changes: 0 additions & 7 deletions pymongo/synchronous/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

from __future__ import annotations

import asyncio
import atexit
import logging
import time
Expand Down Expand Up @@ -257,8 +256,6 @@ def _check_server(self) -> ServerDescription:
details = cast(Mapping[str, Any], exc.details)
self._topology.receive_cluster_time(details.get("$clusterTime"))
raise
except asyncio.CancelledError:
raise
except ReferenceError:
raise
except Exception as error:
Expand Down Expand Up @@ -424,8 +421,6 @@ def _get_seedlist(self) -> Optional[list[tuple[str, Any]]]:
if len(seedlist) == 0:
# As per the spec: this should be treated as a failure.
raise Exception
except asyncio.CancelledError:
raise
except Exception:
# As per the spec, upon encountering an error:
# - An error must not be raised
Expand Down Expand Up @@ -489,8 +484,6 @@ def _run(self) -> None:
except ReferenceError:
# Topology was garbage-collected.
self.close()
except asyncio.CancelledError:
raise
except Exception:
self._pool.reset()

Expand Down
2 changes: 0 additions & 2 deletions pymongo/synchronous/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -702,8 +702,6 @@ def _close_conn(self) -> None:
# shutdown.
try:
self.conn.close()
except asyncio.CancelledError:
raise
except Exception: # noqa: S110
pass

Expand Down
Loading