From 481c576f4f818a622f0ea035974ea64f5fac9ced Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 6 Nov 2026 09:02:10 -0600 Subject: [PATCH 1/7] PYTHON-6226 Keep the monitor alive when it closes its own executor --- doc/changelog.rst | 5 + pymongo/periodic_executor.py | 11 ++- .../test_discovery_and_monitoring.py | 92 +++++++++++++++++++ test/asynchronous/test_periodic_executor.py | 66 ++++++++++++- test/test_discovery_and_monitoring.py | 92 +++++++++++++++++++ test/test_periodic_executor.py | 65 ++++++++++++- 6 files changed, 328 insertions(+), 3 deletions(-) diff --git a/doc/changelog.rst b/doc/changelog.rst index dc0e697fdf..e0ea49b019 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -34,6 +34,10 @@ Bug fixes due to a CPython memory leak bug (`python/cpython#116810 `_). The bug was fixed in Python 3.12.7 and Python 3.13.1. Users of Python 3.12 and 3.13 should upgrade to at least those versions (`PYTHON-6182`_). +- Fixed a bug where ``AsyncMongoClient`` could not recover after a replica set + member removed itself from the topology with its own ``hello`` response (for + example, during a node restart): the monitor's executor cancelled its own + task, so the monitor never ran again (`PYTHON-6226`_). .. _PYTHON-5929: https://jira.mongodb.org/browse/PYTHON-5929 .. _PYTHON-6172: https://jira.mongodb.org/browse/PYTHON-6172 @@ -41,6 +45,7 @@ Bug fixes .. _PYTHON-5873: https://jira.mongodb.org/browse/PYTHON-5873 .. _PYTHON-6145: https://jira.mongodb.org/browse/PYTHON-6145 .. _PYTHON-6182: https://jira.mongodb.org/browse/PYTHON-6182 +.. _PYTHON-6226: https://jira.mongodb.org/browse/PYTHON-6226 Changes in Version 4.19.0 (2026/10/14) -------------------------------------- diff --git a/pymongo/periodic_executor.py b/pymongo/periodic_executor.py index 88149115ff..ec0a344877 100644 --- a/pymongo/periodic_executor.py +++ b/pymongo/periodic_executor.py @@ -75,7 +75,16 @@ def close(self, dummy: Any = None) -> None: callback; see monitor.py. """ self._stopped = True - if self._task is not None: + if self._task is None: + return + try: + current = asyncio.current_task() + except RuntimeError: + # close() also runs as a weakref callback, off the event loop. + current = None + # Never cancel the calling task: self-cancellation aborts close() + # mid-way and leaves the monitor dead (PYTHON-6226). + if self._task is not current: self._task.cancel() async def join(self, timeout: Optional[int] = None) -> None: diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index a3129812b1..84305458a7 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -20,11 +20,13 @@ import os import platform import socketserver +import struct import sys import threading import time from asyncio import StreamReader, StreamWriter from pathlib import Path +from typing import Any from pymongo.asynchronous.pool import AsyncConnection from pymongo.errors import ConnectionFailure @@ -38,6 +40,8 @@ from unittest.mock import patch from bson import Timestamp, json_util +from bson import decode as bson_decode +from bson import encode as bson_encode from pymongo import common, monitoring from pymongo.asynchronous.settings import TopologySettings from pymongo.asynchronous.topology import Topology @@ -679,6 +683,94 @@ async def handle_client(reader: StreamReader, writer: StreamWriter): ) +class TestMonitorRecoversAfterSelfRemoval(AsyncUnitTest): + async def test_monitor_recovers_after_self_removal(self): + # Regression test for PYTHON-6226: a monitor that closed its own + # server used to cancel itself, leaving the client stuck in + # ReplicaSetNoPrimary. The client must recover. + if _IS_SYNC: + self.skipTest("PYTHON-6226: monitor task self-cancellation is async-only") + + # Fake two-node replica set on ephemeral ports. + role: dict[int, str] = {} + hosts: list[str] = [] + + def make_handler(port_box): + async def handle(reader: StreamReader, writer: StreamWriter): + port = port_box["port"] + try: + while True: + length, req_id, _, _ = struct.unpack( + # The ignore is for the sync mirror, where + # unasync turns this read into a bare call. + " Date: Fri, 6 Nov 2026 12:50:40 -0600 Subject: [PATCH 2/7] Update topology bookkeeping before closing a removed server --- pymongo/asynchronous/topology.py | 5 +- pymongo/synchronous/topology.py | 5 +- .../test_discovery_and_monitoring.py | 47 ++++++++++++++++++- test/test_discovery_and_monitoring.py | 44 ++++++++++++++++- 4 files changed, 97 insertions(+), 4 deletions(-) diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index 8f1b4b1a21..560466387a 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -704,10 +704,13 @@ async def _update_servers(self) -> None: for address, server in list(self._servers.items()): if not self._description.has_server(address): - await server.close() + # Update our state before closing: close() can cancel the + # calling task, so the stale server must be recorded as + # removed before close() runs, not after (PYTHON-6226). if not _IS_SYNC: self._monitor_tasks.append(server._monitor) self._servers.pop(address) + await server.close() async def cleanup_monitors(self) -> None: tasks = [] diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index 9accc15dc1..8ffe447cc5 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -702,10 +702,13 @@ def _update_servers(self) -> None: for address, server in list(self._servers.items()): if not self._description.has_server(address): - server.close() + # Update our state before closing: close() can cancel the + # calling task, so the stale server must be recorded as + # removed before close() runs, not after (PYTHON-6226). if not _IS_SYNC: self._monitor_tasks.append(server._monitor) self._servers.pop(address) + server.close() def cleanup_monitors(self) -> None: tasks = [] diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index 84305458a7..428b97ae8c 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -62,7 +62,7 @@ ServerHeartbeatStartedEvent, ) from pymongo.server_description import SERVER_TYPE, ServerDescription -from pymongo.topology_description import TOPOLOGY_TYPE +from pymongo.topology_description import TOPOLOGY_TYPE, TopologyDescription from pymongo.topology_shared import _ErrorContext from test.asynchronous import ( AsyncIntegrationTest, @@ -771,6 +771,51 @@ async def handle(reader: StreamReader, writer: StreamWriter): await asyncio.gather(*[server.wait_closed() for server in servers]) +class TestServerRemovalHardening(AsyncUnitTest): + async def test_removal_bookkeeping_survives_close_cancellation(self): + # Extra hardening for PYTHON-6226: _update_servers() must record the + # monitor and pop the server before awaiting server.close(), so a + # cancellation raised during close() cannot strand a stale server in + # _servers. + if _IS_SYNC: + self.skipTest("PYTHON-6226: task cancellation is async-only") + + topology = await create_mock_topology("mongodb://a:27017,b:27017") + address_b = ("b", 27017) + victim = topology._servers[address_b] + + async def cancelling_close(): + # Simulate an executor cancelling the task that is closing it, + # as AsyncPeriodicExecutor.close() did before PYTHON-6226. + asyncio.current_task().cancel() + await asyncio.sleep(0) + + # A description that no longer contains the victim. + descriptions = topology._description.server_descriptions() + topology._description = TopologyDescription( + TOPOLOGY_TYPE.Unknown, + {addr: sd for addr, sd in descriptions.items() if addr != address_b}, + None, + None, + None, + topology._settings, + ) + + async def remove_victim(): + async with topology._lock: + with patch.object(victim, "close", cancelling_close): + await topology._update_servers() + + task = asyncio.create_task(remove_victim()) + with self.assertRaises(asyncio.CancelledError): + await task + + # The stale server must be gone despite the cancellation, and its + # monitor must be queued for cleanup. + self.assertNotIn(address_b, topology._servers) + self.assertIn(victim._monitor, topology._monitor_tasks) + + # Generate unified tests. globals().update(generate_test_classes(os.path.join(SDAM_PATH, "unified"), module=__name__)) diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index 8d676da0e4..0c6f6e35cc 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -62,7 +62,7 @@ from pymongo.synchronous.settings import TopologySettings from pymongo.synchronous.topology import Topology from pymongo.synchronous.uri_parser import parse_uri -from pymongo.topology_description import TOPOLOGY_TYPE +from pymongo.topology_description import TOPOLOGY_TYPE, TopologyDescription from pymongo.topology_shared import _ErrorContext from test import ( IntegrationTest, @@ -763,11 +763,53 @@ def handle(reader: StreamReader, writer: StreamWriter): # Both monitors self-removed; the client must recover. client.admin.command("ping") finally: + # Close the client first: on Python 3.12+ Server.wait_closed() + # waits for accepted connections to disconnect (PYTHON-6226). + client.close() for server in servers: server.close() asyncio.gather(*[server.wait_closed() for server in servers]) +class TestServerRemovalHardening(UnitTest): + def test_removal_bookkeeping_survives_close_cancellation(self): + # Hardening for PYTHON-6226: record the monitor and pop the server + # before close(), so cancellation during close() cannot strand it. + if _IS_SYNC: + self.skipTest("PYTHON-6226: task cancellation is async-only") + + topology = create_mock_topology("mongodb://a:27017,b:27017") + address_b = ("b", 27017) + victim = topology._servers[address_b] + + def cancelling_close(): + # Simulate an executor cancelling the task that closes it. + asyncio.current_task().cancel() + + # A description that no longer contains the victim. + descriptions = topology._description.server_descriptions() + topology._description = TopologyDescription( + TOPOLOGY_TYPE.Unknown, + {addr: sd for addr, sd in descriptions.items() if addr != address_b}, + None, + None, + None, + topology._settings, + ) + + def remove_victim(): + with topology._lock: + with patch.object(victim, "close", cancelling_close): + topology._update_servers() + + task = asyncio.create_task(remove_victim()) + with self.assertRaises(asyncio.CancelledError): + task + + self.assertNotIn(address_b, topology._servers) + self.assertIn(victim._monitor, topology._monitor_tasks) + + # Generate unified tests. globals().update(generate_test_classes(os.path.join(SDAM_PATH, "unified"), module=__name__)) From a2bbf05d4ec80e0d37c960008b13e31b31d0f55b Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 6 Nov 2026 12:50:55 -0600 Subject: [PATCH 3/7] Update topology bookkeeping before closing a removed server --- test/asynchronous/test_discovery_and_monitoring.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index 428b97ae8c..c7eb9c022a 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -766,6 +766,9 @@ async def handle(reader: StreamReader, writer: StreamWriter): # Both monitors self-removed; the client must recover. await client.admin.command("ping") finally: + # Close the client first: on Python 3.12+ Server.wait_closed() + # waits for accepted connections to disconnect (PYTHON-6226). + await client.close() for server in servers: server.close() await asyncio.gather(*[server.wait_closed() for server in servers]) @@ -773,10 +776,8 @@ async def handle(reader: StreamReader, writer: StreamWriter): class TestServerRemovalHardening(AsyncUnitTest): async def test_removal_bookkeeping_survives_close_cancellation(self): - # Extra hardening for PYTHON-6226: _update_servers() must record the - # monitor and pop the server before awaiting server.close(), so a - # cancellation raised during close() cannot strand a stale server in - # _servers. + # Hardening for PYTHON-6226: record the monitor and pop the server + # before close(), so cancellation during close() cannot strand it. if _IS_SYNC: self.skipTest("PYTHON-6226: task cancellation is async-only") @@ -785,8 +786,7 @@ async def test_removal_bookkeeping_survives_close_cancellation(self): victim = topology._servers[address_b] async def cancelling_close(): - # Simulate an executor cancelling the task that is closing it, - # as AsyncPeriodicExecutor.close() did before PYTHON-6226. + # Simulate an executor cancelling the task that closes it. asyncio.current_task().cancel() await asyncio.sleep(0) @@ -810,8 +810,6 @@ async def remove_victim(): with self.assertRaises(asyncio.CancelledError): await task - # The stale server must be gone despite the cancellation, and its - # monitor must be queued for cleanup. self.assertNotIn(address_b, topology._servers) self.assertIn(victim._monitor, topology._monitor_tasks) From b4f6643c62ebd2e03328694a4bbe255692660c4c Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 6 Nov 2026 14:57:54 -0600 Subject: [PATCH 4/7] Update topology bookkeeping before closing a removed server --- pymongo/asynchronous/server.py | 8 +++++-- pymongo/synchronous/server.py | 8 +++++-- .../test_discovery_and_monitoring.py | 22 +++++++++++++++++++ test/test_discovery_and_monitoring.py | 21 ++++++++++++++++++ 4 files changed, 55 insertions(+), 4 deletions(-) diff --git a/pymongo/asynchronous/server.py b/pymongo/asynchronous/server.py index 8764bfcb28..0e2656c4a6 100644 --- a/pymongo/asynchronous/server.py +++ b/pymongo/asynchronous/server.py @@ -73,8 +73,12 @@ async def close(self) -> None: """ self._sdam.server_closed(self._description.address) - await self._monitor.close() - await self._pool.close() + try: + await self._monitor.close() + finally: + # The pool must close even if cancellation or an error + # interrupts the monitor close (PYTHON-6226). + await self._pool.close() def request_check(self) -> None: """Check the server's state soon.""" diff --git a/pymongo/synchronous/server.py b/pymongo/synchronous/server.py index 0faed74f76..cb16752173 100644 --- a/pymongo/synchronous/server.py +++ b/pymongo/synchronous/server.py @@ -73,8 +73,12 @@ def close(self) -> None: """ self._sdam.server_closed(self._description.address) - self._monitor.close() - self._pool.close() + try: + self._monitor.close() + finally: + # The pool must close even if cancellation or an error + # interrupts the monitor close (PYTHON-6226). + self._pool.close() def request_check(self) -> None: """Check the server's state soon.""" diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index c7eb9c022a..8b37578f08 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -813,6 +813,28 @@ async def remove_victim(): self.assertNotIn(address_b, topology._servers) self.assertIn(victim._monitor, topology._monitor_tasks) + async def test_pool_closes_when_monitor_close_is_cancelled(self): + # A cancelled monitor close must not leave the application pool open. + if _IS_SYNC: + self.skipTest("PYTHON-6226: task cancellation is async-only") + + topology = await create_mock_topology("mongodb://a:27017,b:27017") + victim = topology._servers[("a", 27017)] + + async def cancelling_monitor_close(): + asyncio.current_task().cancel() + await asyncio.sleep(0) + + async def close_victim(): + with patch.object(victim._monitor, "close", cancelling_monitor_close): + await victim.close() + + task = asyncio.create_task(close_victim()) + with self.assertRaises(asyncio.CancelledError): + await task + + self.assertTrue(victim.pool.closed) + # Generate unified tests. globals().update(generate_test_classes(os.path.join(SDAM_PATH, "unified"), module=__name__)) diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index 0c6f6e35cc..55c2c9987f 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -809,6 +809,27 @@ def remove_victim(): self.assertNotIn(address_b, topology._servers) self.assertIn(victim._monitor, topology._monitor_tasks) + def test_pool_closes_when_monitor_close_is_cancelled(self): + # A cancelled monitor close must not leave the application pool open. + if _IS_SYNC: + self.skipTest("PYTHON-6226: task cancellation is async-only") + + topology = create_mock_topology("mongodb://a:27017,b:27017") + victim = topology._servers[("a", 27017)] + + def cancelling_monitor_close(): + asyncio.current_task().cancel() + + def close_victim(): + with patch.object(victim._monitor, "close", cancelling_monitor_close): + victim.close() + + task = asyncio.create_task(close_victim()) + with self.assertRaises(asyncio.CancelledError): + task + + self.assertTrue(victim.pool.closed) + # Generate unified tests. globals().update(generate_test_classes(os.path.join(SDAM_PATH, "unified"), module=__name__)) From 4e3003262059677f1e91db61fb227a90127bd3e7 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 6 Nov 2026 17:06:30 -0600 Subject: [PATCH 5/7] Cancel a mock task off the loop in the close test --- test/asynchronous/test_periodic_executor.py | 30 ++++++++++++++++----- test/test_periodic_executor.py | 30 ++++++++++++++++----- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index 4ebb015d77..00649046d5 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -192,7 +192,7 @@ async def target(): started.set() return True - executor = self._make_executor(target=target) + executor = self._make_executor(min_interval=0.5, target=target) executor.open() if _IS_SYNC: started.wait(timeout=2) @@ -209,15 +209,33 @@ def close_off_loop(): except BaseException as exc: close_error = exc - thread = threading.Thread(target=close_off_loop) - thread.start() - thread.join(timeout=2) + real_task: Any = None + mock_task: Any = None + if not _IS_SYNC: + # Cancel a mock off the loop: cancelling the real task from + # another thread is not thread-safe under asyncio debug mode. + assert executor._task is not None + real_task = executor._task + mock_task = mock.MagicMock() + mock_task.cancelling.return_value = 0 + executor._task = mock_task + try: + thread = threading.Thread(target=close_off_loop) + thread.start() + thread.join(timeout=2) + finally: + if not _IS_SYNC: + executor._task = real_task self.assertIsNone(close_error, "close() raised from a thread without a running event loop") + if not _IS_SYNC: + assert mock_task is not None and real_task is not None + mock_task.cancel.assert_called_once() + # Cancel the real executor on the event loop thread. + real_task.cancel() await executor.join(timeout=2) self.assertTrue(executor._stopped) if not _IS_SYNC: - assert executor._task is not None - self.assertTrue(executor._task.cancelled()) + self.assertTrue(real_task.cancelled()) async def test_target_exception_stops_executor(self): call_count = 0 diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index 2491b38a2d..d111a56d51 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -191,7 +191,7 @@ def target(): started.set() return True - executor = self._make_executor(target=target) + executor = self._make_executor(min_interval=0.5, target=target) executor.open() if _IS_SYNC: started.wait(timeout=2) @@ -208,15 +208,33 @@ def close_off_loop(): except BaseException as exc: close_error = exc - thread = threading.Thread(target=close_off_loop) - thread.start() - thread.join(timeout=2) + real_task: Any = None + mock_task: Any = None + if not _IS_SYNC: + # Cancel a mock off the loop: cancelling the real task from + # another thread is not thread-safe under asyncio debug mode. + assert executor._task is not None + real_task = executor._task + mock_task = mock.MagicMock() + mock_task.cancelling.return_value = 0 + executor._task = mock_task + try: + thread = threading.Thread(target=close_off_loop) + thread.start() + thread.join(timeout=2) + finally: + if not _IS_SYNC: + executor._task = real_task self.assertIsNone(close_error, "close() raised from a thread without a running event loop") + if not _IS_SYNC: + assert mock_task is not None and real_task is not None + mock_task.cancel.assert_called_once() + # Cancel the real executor on the event loop thread. + real_task.cancel() executor.join(timeout=2) self.assertTrue(executor._stopped) if not _IS_SYNC: - assert executor._task is not None - self.assertTrue(executor._task.cancelled()) + self.assertTrue(real_task.cancelled()) def test_target_exception_stops_executor(self): call_count = 0 From 140ba1856dcb1631a23da28ca9a4137e15b02ef9 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 6 Nov 2026 19:03:20 -0600 Subject: [PATCH 6/7] Join the off-loop close thread without blocking the loop --- test/asynchronous/test_periodic_executor.py | 6 +++++- test/test_periodic_executor.py | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index 00649046d5..bfa0c2275a 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -222,7 +222,11 @@ def close_off_loop(): try: thread = threading.Thread(target=close_off_loop) thread.start() - thread.join(timeout=2) + if _IS_SYNC: + thread.join(timeout=2) + else: + # Do not block the event loop while joining the thread. + await asyncio.to_thread(thread.join, 2) finally: if not _IS_SYNC: executor._task = real_task diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index d111a56d51..e1eaf0e9e8 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -221,7 +221,11 @@ def close_off_loop(): try: thread = threading.Thread(target=close_off_loop) thread.start() - thread.join(timeout=2) + if _IS_SYNC: + thread.join(timeout=2) + else: + # Do not block the event loop while joining the thread. + asyncio.to_thread(thread.join, 2) finally: if not _IS_SYNC: executor._task = real_task From 12b1f576fea1b0886e0b6816b02eae1ada7b3d8b Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Mon, 9 Nov 2026 13:45:46 -0600 Subject: [PATCH 7/7] address review --- test/asynchronous/test_discovery_and_monitoring.py | 10 ++++------ test/test_discovery_and_monitoring.py | 10 ++++------ 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index 8b37578f08..ca44bfbac2 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -24,6 +24,7 @@ import sys import threading import time +import unittest from asyncio import StreamReader, StreamWriter from pathlib import Path from typing import Any @@ -684,12 +685,11 @@ async def handle_client(reader: StreamReader, writer: StreamWriter): class TestMonitorRecoversAfterSelfRemoval(AsyncUnitTest): + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6226: monitor task self-cancellation is async-only") async def test_monitor_recovers_after_self_removal(self): # Regression test for PYTHON-6226: a monitor that closed its own # server used to cancel itself, leaving the client stuck in # ReplicaSetNoPrimary. The client must recover. - if _IS_SYNC: - self.skipTest("PYTHON-6226: monitor task self-cancellation is async-only") # Fake two-node replica set on ephemeral ports. role: dict[int, str] = {} @@ -775,11 +775,10 @@ async def handle(reader: StreamReader, writer: StreamWriter): class TestServerRemovalHardening(AsyncUnitTest): + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6226: task cancellation is async-only") async def test_removal_bookkeeping_survives_close_cancellation(self): # Hardening for PYTHON-6226: record the monitor and pop the server # before close(), so cancellation during close() cannot strand it. - if _IS_SYNC: - self.skipTest("PYTHON-6226: task cancellation is async-only") topology = await create_mock_topology("mongodb://a:27017,b:27017") address_b = ("b", 27017) @@ -813,10 +812,9 @@ async def remove_victim(): self.assertNotIn(address_b, topology._servers) self.assertIn(victim._monitor, topology._monitor_tasks) + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6226: task cancellation is async-only") async def test_pool_closes_when_monitor_close_is_cancelled(self): # A cancelled monitor close must not leave the application pool open. - if _IS_SYNC: - self.skipTest("PYTHON-6226: task cancellation is async-only") topology = await create_mock_topology("mongodb://a:27017,b:27017") victim = topology._servers[("a", 27017)] diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index 55c2c9987f..c310d447e1 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -24,6 +24,7 @@ import sys import threading import time +import unittest from asyncio import StreamReader, StreamWriter from pathlib import Path from typing import Any @@ -681,12 +682,11 @@ def handle_client(reader: StreamReader, writer: StreamWriter): class TestMonitorRecoversAfterSelfRemoval(UnitTest): + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6226: monitor task self-cancellation is async-only") def test_monitor_recovers_after_self_removal(self): # Regression test for PYTHON-6226: a monitor that closed its own # server used to cancel itself, leaving the client stuck in # ReplicaSetNoPrimary. The client must recover. - if _IS_SYNC: - self.skipTest("PYTHON-6226: monitor task self-cancellation is async-only") # Fake two-node replica set on ephemeral ports. role: dict[int, str] = {} @@ -772,11 +772,10 @@ def handle(reader: StreamReader, writer: StreamWriter): class TestServerRemovalHardening(UnitTest): + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6226: task cancellation is async-only") def test_removal_bookkeeping_survives_close_cancellation(self): # Hardening for PYTHON-6226: record the monitor and pop the server # before close(), so cancellation during close() cannot strand it. - if _IS_SYNC: - self.skipTest("PYTHON-6226: task cancellation is async-only") topology = create_mock_topology("mongodb://a:27017,b:27017") address_b = ("b", 27017) @@ -809,10 +808,9 @@ def remove_victim(): self.assertNotIn(address_b, topology._servers) self.assertIn(victim._monitor, topology._monitor_tasks) + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6226: task cancellation is async-only") def test_pool_closes_when_monitor_close_is_cancelled(self): # A cancelled monitor close must not leave the application pool open. - if _IS_SYNC: - self.skipTest("PYTHON-6226: task cancellation is async-only") topology = create_mock_topology("mongodb://a:27017,b:27017") victim = topology._servers[("a", 27017)]