From c30acd522e39f4550439eeb3e4cfba7e27958c3a Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 17 Nov 2026 07:36:10 -0600 Subject: [PATCH 01/26] PYTHON-1634 Join monitor threads on MongoClient close --- doc/changelog.rst | 8 ++++++ pymongo/asynchronous/monitor.py | 29 ++++++++++++++----- pymongo/asynchronous/topology.py | 32 +++++++++++++-------- pymongo/synchronous/monitor.py | 27 ++++++++++++++---- pymongo/synchronous/topology.py | 32 +++++++++++++-------- test/asynchronous/test_monitor.py | 46 +++++++++++++++++++++++++++++++ test/test_monitor.py | 46 +++++++++++++++++++++++++++++++ 7 files changed, 184 insertions(+), 36 deletions(-) diff --git a/doc/changelog.rst b/doc/changelog.rst index d4e6193715..7a6b032381 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -12,9 +12,17 @@ Bug fixes - Fixed a bug where ``getMore`` commands in load-balanced mode were not retried when the server returned a retryable overload error (`PYTHON-6262`_). +- Fixed a race between a server monitor's background thread and connection + pool teardown during + :meth:`~pymongo.synchronous.mongo_client.MongoClient.close`. Closing a + client now waits (with a bounded timeout) for its monitor threads to stop + before returning, adding up to a couple hundred milliseconds to + ``close()`` (`PYTHON-1634`_). .. _PYTHON-6262: https://jira.mongodb.org/browse/PYTHON-6262 +.. _PYTHON-1634: https://jira.mongodb.org/browse/PYTHON-1634 + Changes in Version 4.20.0 (2026/11/12) -------------------------------------- diff --git a/pymongo/asynchronous/monitor.py b/pymongo/asynchronous/monitor.py index a3aebb80b0..ebc292379f 100644 --- a/pymongo/asynchronous/monitor.py +++ b/pymongo/asynchronous/monitor.py @@ -16,7 +16,6 @@ from __future__ import annotations -import asyncio import atexit import threading import time @@ -107,9 +106,9 @@ async def close(self) -> None: """ self.gc_safe_close() - async def join(self) -> None: + async def join(self, timeout: int | None = None) -> None: """Wait for the monitor to stop.""" - await self._executor.join() + await self._executor.join(timeout) def request_check(self) -> None: """If the monitor is sleeping, wake it soon.""" @@ -185,14 +184,24 @@ def gc_safe_close(self) -> None: self._rtt_monitor.gc_safe_close() self.cancel_check() - async def join(self) -> None: - await asyncio.gather( - self._executor.join(), self._rtt_monitor.join(), return_exceptions=True - ) # type: ignore[func-returns-value] + async def join(self, timeout: int | None = None) -> None: + # The timeout budgets BOTH executors: the RTT join gets whatever + # remains after the heartbeat executor stops. + start = time.monotonic() + await self._executor.join(timeout) + if timeout is not None: + timeout = max(0, round(timeout - (time.monotonic() - start))) + await self._rtt_monitor.join(timeout) async def close(self) -> None: self.gc_safe_close() await self._rtt_monitor.close() + # Wake the executor and wait briefly for the task to stop before + # resetting the pool, so we don't race with a connection it has + # checked out. The join is a bounded backstop: if the task is still + # running, the reset below closes the socket once it's checked in. + self._executor.wake() + await self._executor.join(1) # Increment the generation and maybe close the socket. If the executor # thread has the socket checked out, it will be closed when checked in. await self._reset_connection() @@ -409,6 +418,12 @@ def __init__(self, topology: Topology, topology_settings: TopologySettings, pool async def close(self) -> None: self.gc_safe_close() + # Wake the executor and wait briefly for the task to stop before + # resetting the pool, so we don't race with a connection it has + # checked out. The join is a bounded backstop: if the task is still + # running, the reset below closes the socket once it's checked in. + self._executor.wake() + await self._executor.join(1) # Increment the generation and maybe close the socket. If the executor # thread has the socket checked out, it will be closed when checked in. await self._pool.reset() diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index 1471830ddf..f871adc1e5 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -16,7 +16,6 @@ from __future__ import annotations -import asyncio import os import random import sys @@ -188,8 +187,8 @@ async def select_servers( else: server_timeout = server_selection_timeout - # Cleanup any completed monitor tasks safely - if not _IS_SYNC and self._monitor_tasks: + # Join any monitors closed under the topology lock. + if self._monitor_tasks: await self.cleanup_monitors() async with self._lock: @@ -401,8 +400,7 @@ async def _process_change( and self._description.topology_type not in SRV_POLLING_TOPOLOGIES ): await self._srv_monitor.close() - if not _IS_SYNC: - self._monitor_tasks.append(self._srv_monitor) + self._monitor_tasks.append(self._srv_monitor) # Wake anything waiting in select_servers(). self._condition.notify_all() @@ -520,8 +518,7 @@ async def close(self) -> None: old_td = self._description for server in self._servers.values(): await server.close() - if not _IS_SYNC: - self._monitor_tasks.append(server._monitor) + self._monitor_tasks.append(server._monitor) # Mark all servers Unknown. self._description = self._description.reset() @@ -532,12 +529,14 @@ async def close(self) -> None: # Stop SRV polling thread. if self._srv_monitor: await self._srv_monitor.close() - if not _IS_SYNC: - self._monitor_tasks.append(self._srv_monitor) + self._monitor_tasks.append(self._srv_monitor) self._opened = False self._closed = True + # Join the monitors we just closed, now that the lock is released. + await self.cleanup_monitors() + # Publish only after releasing the lock. if self._sdam._publish_tp: self._description = TopologyDescription( @@ -708,16 +707,25 @@ async def _update_servers(self) -> None: # 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._monitor_tasks.append(server._monitor) self._servers.pop(address) await server.close() async def cleanup_monitors(self) -> None: + """Join monitors closed earlier while the topology lock was held. + + Always call this with the lock released: a monitor being joined may + itself be blocked acquiring the lock. + """ tasks = [] try: while self._monitor_tasks: tasks.append(self._monitor_tasks.pop()) except IndexError: pass - await asyncio.gather(*[t.join() for t in tasks], return_exceptions=True) # type: ignore[func-returns-value] + for t in tasks: + try: + await t.join(1) + except Exception: # noqa: S110 + # One monitor failing to stop must not block the rest. + pass diff --git a/pymongo/synchronous/monitor.py b/pymongo/synchronous/monitor.py index 436e9eed8b..e94c134016 100644 --- a/pymongo/synchronous/monitor.py +++ b/pymongo/synchronous/monitor.py @@ -16,7 +16,6 @@ from __future__ import annotations -import asyncio import atexit import threading import time @@ -107,9 +106,9 @@ def close(self) -> None: """ self.gc_safe_close() - def join(self) -> None: + def join(self, timeout: int | None = None) -> None: """Wait for the monitor to stop.""" - self._executor.join() + self._executor.join(timeout) def request_check(self) -> None: """If the monitor is sleeping, wake it soon.""" @@ -185,12 +184,24 @@ def gc_safe_close(self) -> None: self._rtt_monitor.gc_safe_close() self.cancel_check() - def join(self) -> None: - asyncio.gather(self._executor.join(), self._rtt_monitor.join(), return_exceptions=True) # type: ignore[func-returns-value] + def join(self, timeout: int | None = None) -> None: + # The timeout budgets BOTH executors: the RTT join gets whatever + # remains after the heartbeat executor stops. + start = time.monotonic() + self._executor.join(timeout) + if timeout is not None: + timeout = max(0, round(timeout - (time.monotonic() - start))) + self._rtt_monitor.join(timeout) def close(self) -> None: self.gc_safe_close() self._rtt_monitor.close() + # Wake the executor and wait briefly for the task to stop before + # resetting the pool, so we don't race with a connection it has + # checked out. The join is a bounded backstop: if the task is still + # running, the reset below closes the socket once it's checked in. + self._executor.wake() + self._executor.join(1) # Increment the generation and maybe close the socket. If the executor # thread has the socket checked out, it will be closed when checked in. self._reset_connection() @@ -407,6 +418,12 @@ def __init__(self, topology: Topology, topology_settings: TopologySettings, pool def close(self) -> None: self.gc_safe_close() + # Wake the executor and wait briefly for the task to stop before + # resetting the pool, so we don't race with a connection it has + # checked out. The join is a bounded backstop: if the task is still + # running, the reset below closes the socket once it's checked in. + self._executor.wake() + self._executor.join(1) # Increment the generation and maybe close the socket. If the executor # thread has the socket checked out, it will be closed when checked in. self._pool.reset() diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index b7a9bd366c..e0942253c6 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -16,7 +16,6 @@ from __future__ import annotations -import asyncio import os import random import sys @@ -188,8 +187,8 @@ def select_servers( else: server_timeout = server_selection_timeout - # Cleanup any completed monitor tasks safely - if not _IS_SYNC and self._monitor_tasks: + # Join any monitors closed under the topology lock. + if self._monitor_tasks: self.cleanup_monitors() with self._lock: @@ -401,8 +400,7 @@ def _process_change( and self._description.topology_type not in SRV_POLLING_TOPOLOGIES ): self._srv_monitor.close() - if not _IS_SYNC: - self._monitor_tasks.append(self._srv_monitor) + self._monitor_tasks.append(self._srv_monitor) # Wake anything waiting in select_servers(). self._condition.notify_all() @@ -518,8 +516,7 @@ def close(self) -> None: old_td = self._description for server in self._servers.values(): server.close() - if not _IS_SYNC: - self._monitor_tasks.append(server._monitor) + self._monitor_tasks.append(server._monitor) # Mark all servers Unknown. self._description = self._description.reset() @@ -530,12 +527,14 @@ def close(self) -> None: # Stop SRV polling thread. if self._srv_monitor: self._srv_monitor.close() - if not _IS_SYNC: - self._monitor_tasks.append(self._srv_monitor) + self._monitor_tasks.append(self._srv_monitor) self._opened = False self._closed = True + # Join the monitors we just closed, now that the lock is released. + self.cleanup_monitors() + # Publish only after releasing the lock. if self._sdam._publish_tp: self._description = TopologyDescription( @@ -706,16 +705,25 @@ def _update_servers(self) -> None: # 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._monitor_tasks.append(server._monitor) self._servers.pop(address) server.close() def cleanup_monitors(self) -> None: + """Join monitors closed earlier while the topology lock was held. + + Always call this with the lock released: a monitor being joined may + itself be blocked acquiring the lock. + """ tasks = [] try: while self._monitor_tasks: tasks.append(self._monitor_tasks.pop()) except IndexError: pass - asyncio.gather(*[t.join() for t in tasks], return_exceptions=True) # type: ignore[func-returns-value] + for t in tasks: + try: + t.join(1) + except Exception: # noqa: S110 + # One monitor failing to stop must not block the rest. + pass diff --git a/test/asynchronous/test_monitor.py b/test/asynchronous/test_monitor.py index 9ad8f00ea3..354993d120 100644 --- a/test/asynchronous/test_monitor.py +++ b/test/asynchronous/test_monitor.py @@ -20,6 +20,7 @@ import gc import subprocess import sys +import time import warnings from functools import partial @@ -107,6 +108,51 @@ async def test_cleanup_executors_on_client_close(self): lambda: executor._stopped, f"closed executor: {executor._name}", timeout=5 ) + @async_client_context.require_sync + def test_close_stops_monitor_thread(self): + """PYTHON-1634: close() joins the monitor thread before returning, + so callers don't race it while it reads the socket. + """ + client = self.create_client() + server = next(iter(client._topology._servers.values())) + monitor = server._monitor + + def thread_alive(executor): + try: + return executor._thread is not None and executor._thread.is_alive() + except ReferenceError: + return False + + deadline = time.monotonic() + 10 + while not thread_alive(monitor._executor) and time.monotonic() < deadline: + time.sleep(0.1) + self.assertTrue(thread_alive(monitor._executor), "monitor thread never started") + + client.close() + + # close() drains the deferred-join queue after releasing the lock. + self.assertEqual(client._topology._monitor_tasks, []) + self.assertFalse(thread_alive(monitor._executor)) + self.assertFalse(thread_alive(monitor._rtt_monitor._executor)) + + @async_client_context.require_async + async def test_close_stops_monitor_task(self): + """PYTHON-1634: the async counterpart of + test_close_stops_monitor_thread. + """ + client = await self.create_client() + server = next(iter(client._topology._servers.values())) + monitor = server._monitor + + self.assertIsNotNone(monitor._executor._task) + self.assertFalse(monitor._executor._task.done()) + + await client.close() + + self.assertEqual(client._topology._monitor_tasks, []) + self.assertTrue(monitor._executor._task.done()) + self.assertTrue(monitor._rtt_monitor._executor._task.done()) + @async_client_context.require_sync def test_no_thread_start_runtime_err_on_shutdown(self): """Test we silence noisy runtime errors fired when the AsyncMongoClient spawns a new thread diff --git a/test/test_monitor.py b/test/test_monitor.py index b19b64715c..fdbfb0f2be 100644 --- a/test/test_monitor.py +++ b/test/test_monitor.py @@ -20,6 +20,7 @@ import gc import subprocess import sys +import time import warnings from functools import partial @@ -103,6 +104,51 @@ def test_cleanup_executors_on_client_close(self): for executor in executors: wait_until(lambda: executor._stopped, f"closed executor: {executor._name}", timeout=5) + @client_context.require_sync + def test_close_stops_monitor_thread(self): + """PYTHON-1634: close() joins the monitor thread before returning, + so callers don't race it while it reads the socket. + """ + client = self.create_client() + server = next(iter(client._topology._servers.values())) + monitor = server._monitor + + def thread_alive(executor): + try: + return executor._thread is not None and executor._thread.is_alive() + except ReferenceError: + return False + + deadline = time.monotonic() + 10 + while not thread_alive(monitor._executor) and time.monotonic() < deadline: + time.sleep(0.1) + self.assertTrue(thread_alive(monitor._executor), "monitor thread never started") + + client.close() + + # close() drains the deferred-join queue after releasing the lock. + self.assertEqual(client._topology._monitor_tasks, []) + self.assertFalse(thread_alive(monitor._executor)) + self.assertFalse(thread_alive(monitor._rtt_monitor._executor)) + + @client_context.require_async + def test_close_stops_monitor_task(self): + """PYTHON-1634: the async counterpart of + test_close_stops_monitor_thread. + """ + client = self.create_client() + server = next(iter(client._topology._servers.values())) + monitor = server._monitor + + self.assertIsNotNone(monitor._executor._task) + self.assertFalse(monitor._executor._task.done()) + + client.close() + + self.assertEqual(client._topology._monitor_tasks, []) + self.assertTrue(monitor._executor._task.done()) + self.assertTrue(monitor._rtt_monitor._executor._task.done()) + @client_context.require_sync def test_no_thread_start_runtime_err_on_shutdown(self): """Test we silence noisy runtime errors fired when the MongoClient spawns a new thread From b593991f61118e2cc2a65db4332100790a1c1557 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 17 Nov 2026 07:36:25 -0600 Subject: [PATCH 02/26] PYTHON-6168 Add a thread sanitizer test --- .evergreen/generated_configs/tasks.yml | 18 ++- .evergreen/scripts/generate_config.py | 22 ++- .evergreen/scripts/setup_tests.py | 53 ++++--- .evergreen/scripts/test_generate_config.py | 42 +++--- .evergreen/scripts/utils.py | 5 + .evergreen/tsan-suppressions.txt | 18 +++ CONTRIBUTING.md | 12 ++ test/test_bson.py | 167 ++++++++++++++++++++- test/test_message.py | 88 ++++++++++- test/test_raw_bson_shared.py | 151 +++++++++++++++++++ 10 files changed, 527 insertions(+), 49 deletions(-) create mode 100644 .evergreen/tsan-suppressions.txt diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index 2bcc195224..b8b9524252 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -2845,7 +2845,7 @@ tasks: tags: [perf] # Sanitizer tests - - name: test-sanitizer + - name: test-sanitizer-asan commands: - func: run server vars: @@ -2858,6 +2858,22 @@ tasks: SSL: nossl TOPOLOGY: standalone TEST_NAME: sanitizer + SUB_TEST_NAME: asan + tags: [sanitizer, pr] + - name: test-sanitizer-tsan + commands: + - func: run server + vars: + AUTH: noauth + SSL: nossl + TOPOLOGY: standalone + - func: run tests + vars: + AUTH: noauth + SSL: nossl + TOPOLOGY: standalone + TEST_NAME: sanitizer + SUB_TEST_NAME: tsan tags: [sanitizer, pr] # Search index tests diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index 58299f7f33..1adb5245ca 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -531,8 +531,9 @@ def create_fuzz_variants(): def create_sanitizer_variants() -> list[BuildVariant]: - # ASan/UBSan checks on every PR (PYTHON-6048). The rhel8 toolchain - # provides the instrumented CPython (utils.SANITIZER_PYTHON), and the + # Sanitizer checks on every PR (PYTHON-6048, PYTHON-6168): ASan/UBSan + # and TSan tasks. The rhel8 toolchain provides the instrumented + # CPythons (utils.SANITIZER_PYTHON, utils.TSAN_PYTHON), and the # large distro gives ASan's shadow memory and redzones room for the # ~6GiB test_encode_size_limit allocation, so no test is skipped. host = DEFAULT_HOST @@ -966,15 +967,20 @@ def create_fuzz_tasks(): def create_sanitizer_tasks(): # VERSION comes from the variant: a task-level VERSION would trip the - # pr-tasks-run-coverage rule, and coverage under ASan is not useful. + # pr-tasks-run-coverage rule, and coverage under sanitizers is not + # useful. tags = ["sanitizer", "pr"] expansions = dict(AUTH="noauth", SSL="nossl", TOPOLOGY="standalone") server_func = FunctionCall(func="run server", vars=expansions) - test_vars = expansions.copy() - test_vars["TEST_NAME"] = "sanitizer" - test_func = FunctionCall(func="run tests", vars=test_vars) - name = get_task_name("test-sanitizer") - return [EvgTask(name=name, tags=tags, commands=[server_func, test_func])] + tasks = [] + for sub_test_name in ("asan", "tsan"): + test_vars = expansions.copy() + test_vars["TEST_NAME"] = "sanitizer" + test_vars["SUB_TEST_NAME"] = sub_test_name + test_func = FunctionCall(func="run tests", vars=test_vars) + name = get_task_name(f"test-sanitizer-{sub_test_name}") + tasks.append(EvgTask(name=name, tags=tags, commands=[server_func, test_func])) + return tasks def create_kms_tasks(): diff --git a/.evergreen/scripts/setup_tests.py b/.evergreen/scripts/setup_tests.py index c12599cbc0..225ce42f89 100644 --- a/.evergreen/scripts/setup_tests.py +++ b/.evergreen/scripts/setup_tests.py @@ -20,6 +20,7 @@ ROOT, SANITIZER_PYTHON, TEST_SUITE_MAP, + TSAN_PYTHON, Distro, check_drivers_tools, get_test_options, @@ -57,13 +58,16 @@ # Map the test name to test group. GROUP_MAP = dict(fuzz="fuzz", mockupdb="mockupdb", perf="perf") -# The test files run under ASan/UBSan (PYTHON-6048). They exercise the -# buffer-protocol acquisition path in bson/_cbsonmodule.c -# (_get_buffer/_prepare_input_buffer) and the wire-message builders in -# pymongo/_cmessagemodule.c (_op_msg, _batched_op_msg, -# _encode_batched_write_command). +# The test files run under the sanitizer tasks (PYTHON-6048, PYTHON-6168). +# They exercise the buffer-protocol acquisition path in +# bson/_cbsonmodule.c (_get_buffer/_prepare_input_buffer), the wire-message +# builders in pymongo/_cmessagemodule.c (_op_msg, _batched_op_msg, +# _encode_batched_write_command), and — via the concurrency classes added +# in PYTHON-6168 — concurrent zero-copy RawBSONDocument reads and batched +# message building on free-threaded CPython. SANITIZER_FILES = [ "test/test_bson.py", + "test/test_message.py", "test/test_raw_bson.py", "test/test_raw_bson_shared.py", "test/test_client.py", @@ -550,12 +554,14 @@ def handle_test_env() -> None: write_env("FUZZ_CORPUS_DIR", str(corpus_dir)) if test_name == "sanitizer": + tsan = sub_test_name == "tsan" + python = TSAN_PYTHON if tsan else SANITIZER_PYTHON if PLATFORM != "linux": raise RuntimeError("The sanitizer tests require the Linux Python toolchain.") - if not Path(SANITIZER_PYTHON).is_file(): + if not Path(python).is_file(): raise RuntimeError( - f"Sanitizer interpreter not found at {SANITIZER_PYTHON}; " - "the task must run on a host with the ASan/UBSan toolchain Python." + f"Sanitizer interpreter not found at {python}; the task must run " + "on a host with the sanitizer toolchain Python." ) # Clear stale C artifacts: build_ext reuses them by mtime, and a # plain same-version CPython build shares the ABI tag. @@ -563,20 +569,29 @@ def handle_test_env() -> None: for pkg in ["bson", "pymongo"]: for ext in (ROOT / pkg).glob("*.so"): ext.unlink() - # Build and run against the ASan/UBSan-instrumented toolchain CPython, + # Build and run against the sanitizer-instrumented toolchain CPython, # and fail loudly rather than silently skip the C extension build. - write_env("UV_PYTHON", SANITIZER_PYTHON) + write_env("UV_PYTHON", python) write_env("PYMONGO_C_EXT_MUST_BUILD") - write_env("CFLAGS", "-fsanitize=address,undefined -fno-omit-frame-pointer -g -O1") - write_env("LDFLAGS", "-fsanitize=address,undefined") - # CPython's pymalloc trips LeakSanitizer with false positives. - write_env("ASAN_OPTIONS", "detect_leaks=0") - # UBSan only warns by default; make undefined behavior fail the task. - write_env("UBSAN_OPTIONS", "halt_on_error=1:print_stacktrace=1") + if tsan: + write_env("CFLAGS", "-fsanitize=thread -fno-omit-frame-pointer -g -O1") + write_env("LDFLAGS", "-fsanitize=thread") + suppressions = ROOT / ".evergreen" / "tsan-suppressions.txt" + write_env( + "TSAN_OPTIONS", + f"halt_on_error=1:handle_segv=0:suppressions={suppressions}", + ) + else: + write_env("CFLAGS", "-fsanitize=address,undefined -fno-omit-frame-pointer -g -O1") + write_env("LDFLAGS", "-fsanitize=address,undefined") + # CPython's pymalloc trips LeakSanitizer with false positives. + write_env("ASAN_OPTIONS", "detect_leaks=0") + # UBSan only warns by default; make undefined behavior fail the task. + write_env("UBSAN_OPTIONS", "halt_on_error=1:print_stacktrace=1") # The toolchain interpreter self-initializes the sanitizer runtimes, - # so no LD_PRELOAD: gcc's libasan.so is a linker script that ld.so - # cannot preload, and preloading a mismatched runtime would mix two - # sanitizers in one process. + # so no LD_PRELOAD: preloading a mismatched runtime would mix two + # sanitizers in one process, and for TSan report false races inside + # CPython's own free-threading internals. # -s: with halt_on_error=1, a sanitizer failure exits the interpreter # before pytest replays captured stderr, losing the report and trace. TEST_ARGS = "-s " + " ".join(SANITIZER_FILES) + " " + TEST_ARGS diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 67f9e8a639..dd241d5387 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -311,24 +311,28 @@ def test_load_balancer_marker_selection(monkeypatch): def test_sanitizer_task_wiring(): - """PYTHON-6048: one pr-tagged sanitizer task, selected by exactly one - variant that pins MAX_VERSION and runs on a large host for ASan's memory - headroom. VERSION stays off the task so it is exempt - from the pr COVERAGE rule (coverage under ASan is not useful). + """PYTHON-6048/PYTHON-6168: pr-tagged sanitizer tasks, selected by + exactly one variant that pins MAX_VERSION and runs on a large host for + ASan's memory headroom. VERSION stays off the tasks so they are exempt + from the pr COVERAGE rule (coverage under sanitizers is not useful). """ tasks = [task for task in all_tasks() if "sanitizer" in (task.tags or [])] - assert len(tasks) == 1 - task = tasks[0] - assert "pr" in task.tags - funcs = [getattr(cmd, "func", None) for cmd in task.commands] - assert funcs == ["run server", "run tests"] - vars_ = task_vars(task) - assert vars_["TEST_NAME"] == "sanitizer" - assert vars_["TOPOLOGY"] == "standalone" - assert vars_["AUTH"] == "noauth" - assert vars_["SSL"] == "nossl" - assert "VERSION" not in vars_ - variants = [v for v in all_variants() if variant_selects(v, task)] - assert len(variants) == 1 - assert variants[0].run_on == ["rhel8.10-large"] - assert (variants[0].expansions or {}).get("VERSION") == generate_config_utils.MAX_VERSION + assert {task.name for task in tasks} == { + "test-sanitizer-asan", + "test-sanitizer-tsan", + } + for task in tasks: + assert "pr" in task.tags + funcs = [getattr(cmd, "func", None) for cmd in task.commands] + assert funcs == ["run server", "run tests"] + vars_ = task_vars(task) + assert vars_["TEST_NAME"] == "sanitizer" + assert vars_["SUB_TEST_NAME"] in ("asan", "tsan") + assert vars_["TOPOLOGY"] == "standalone" + assert vars_["AUTH"] == "noauth" + assert vars_["SSL"] == "nossl" + assert "VERSION" not in vars_ + variants = [v for v in all_variants() if variant_selects(v, task)] + assert len(variants) == 1 + assert variants[0].run_on == ["rhel8.10-large"] + assert (variants[0].expansions or {}).get("VERSION") == generate_config_utils.MAX_VERSION diff --git a/.evergreen/scripts/utils.py b/.evergreen/scripts/utils.py index 4126b86998..115f109b8d 100644 --- a/.evergreen/scripts/utils.py +++ b/.evergreen/scripts/utils.py @@ -94,6 +94,11 @@ class Distro: # (PYTHON-6048), built by mongo-python-toolchain (PYTHON-6067). Linux only. SANITIZER_PYTHON = "/opt/python/3.14-asan-ubsan/bin/python3" +# The TSan-instrumented, free-threaded toolchain CPython used by the TSan +# sanitizer task (PYTHON-6168), built by mongo-python-toolchain +# (PYTHON-6067). Linux only. +TSAN_PYTHON = "/opt/python/3.14t-tsan/bin/python3" + # Tests that do not use run-mongodb directly. NO_RUN_ORCHESTRATION = [ "auth_oidc", diff --git a/.evergreen/tsan-suppressions.txt b/.evergreen/tsan-suppressions.txt new file mode 100644 index 0000000000..66feeca453 --- /dev/null +++ b/.evergreen/tsan-suppressions.txt @@ -0,0 +1,18 @@ +# PyMongo-specific ThreadSanitizer suppressions. +# +# The TSan task (PYTHON-6168) passes this file as TSan's single +# suppressions= path via TSAN_OPTIONS in .evergreen/scripts/setup_tests.py. +# +# Add an entry below only for a race that has been investigated and judged +# benign, with a comment saying why: either a race in PyMongo's own C +# extensions, or a CPython-internal race (both stacks within CPython) that +# the toolchain interpreter's own suppression set does not yet cover. +# +# Reference: https://github.com/google/sanitizers/wiki/ThreadSanitizerSuppressions + +# CPython-internal: under free-threading the GC's delete_garbage path +# (memory_clear) and a worker thread's deferred refcount merge +# (memory_dealloc) can both enter _memory_release for the same +# memoryview. Both stacks are entirely within CPython; pymongo only +# creates and releases the memoryviews concurrently. +race_top:_memory_release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9e0e058c94..5e803253f0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -514,6 +514,18 @@ toolchain: just setup-tests sanitizer just run-tests +The `sanitizer tsan` suite (PYTHON-6168) builds the C extensions with +`-fsanitize=thread` against the toolchain's TSan-instrumented, +free-threaded CPython (`TSAN_PYTHON` in `.evergreen/scripts/utils.py`) and +runs the same files as the ASan suite with ThreadSanitizer set to halt on +error (suppressions in `.evergreen/tsan-suppressions.txt`). It runs on PRs +via the same "Sanitizer RHEL8" variant. To run it on a Linux host with the +toolchain: + + just run-server + just setup-tests sanitizer tsan + just run-tests + ## Handling flaky tests We have a custom `flaky` decorator in [test/asynchronous/utils.py](test/asynchronous/utils.py) that can be used for diff --git a/test/test_bson.py b/test/test_bson.py index 0380d1f22e..c933af267d 100644 --- a/test/test_bson.py +++ b/test/test_bson.py @@ -31,6 +31,7 @@ import uuid from collections import OrderedDict, abc from io import BytesIO +from typing import Any sys.path[0:0] = [""] @@ -63,7 +64,8 @@ from bson.codec_options import CodecOptions, DatetimeConversion from bson.datetime_ms import _DATETIME_ERROR_SUGGESTION from bson.dbref import DBRef -from bson.errors import InvalidBSON, InvalidDocument +from bson.decimal128 import Decimal128 +from bson.errors import BSONError, InvalidBSON, InvalidDocument from bson.int64 import Int64 from bson.max_key import MaxKey from bson.min_key import MinKey @@ -2081,5 +2083,168 @@ def test_long_long_to_string(self): print("_cbson was not imported. Check compilation logs.") +def _nested_document(depth: int) -> dict[str, Any]: + doc: dict[str, Any] = {"leaf": 1} + for _ in range(depth): + doc = {"d": doc} + return doc + + +def _typed_documents() -> list[dict[str, Any]]: + """One document per BSON type, at value extremes where applicable.""" + return [ + {}, + {"int32": 1}, + {"int64 max": Int64(2**63 - 1), "int64 min": Int64(-(2**63))}, + {"double": 1.5, "double min": sys.float_info.min, "double max": sys.float_info.max}, + {"string": "hello é", "string empty": ""}, + {"string big": "x" * 70000}, + { + "binary": Binary(b"\x00\xffbin", 0), + "binary old": Binary(b"old", 2), + "binary empty": Binary(b"", 0), + }, + { + "datetime zero": DatetimeMS(0), + "datetime min": DatetimeMS(-(2**63)), + "datetime max": DatetimeMS(2**63 - 1), + }, + {"timestamp": Timestamp(0, 1), "timestamp max": Timestamp(0xFFFFFFFF, 0xFFFFFFFF)}, + { + "decimal128": Decimal128("1.25"), + "decimal128 nan": Decimal128("NaN"), + "decimal128 inf": Decimal128("Infinity"), + "decimal128 neg0": Decimal128("-0"), + }, + {"regex": Regex("a*b", "im"), "regex empty": Regex("", "")}, + {"code": Code("function() { return 1; }"), "code scope": Code("f", {"x": [1, 2]})}, + { + "dbref": DBRef("coll", "id"), + "objectid": ObjectId(b"0123456789ab"), + "minkey": MinKey(), + "maxkey": MaxKey(), + "null": None, + "bool": True, + }, + {"array": [1, "two", None, {"nested": True}], "subdoc": {"b": {"c": 1}}}, + {"bytes": b"raw bytes"}, + {"key" * 63 + "e": 1}, + {"deep": _nested_document(50)}, + ] + + +_DATETIME_MS_CODEC = CodecOptions(datetime_conversion=DatetimeConversion.DATETIME_MS) + + +class TestBSONEncodeDecodeBoundaries(unittest.TestCase): + """Encode every BSON type at value extremes and re-encode byte-stably. + + Drives buffer growth transitions and every _downcast_and_check path + under sanitizer builds. + """ + + def _round_trip(self, doc): + encoded = bson.encode(doc, codec_options=_DATETIME_MS_CODEC) + decoded = bson.decode(encoded, codec_options=_DATETIME_MS_CODEC) + # Compare byte-level stability rather than decoded == doc so that + # NaN payloads (which are not equal to themselves) round-trip too. + self.assertEqual(bson.encode(decoded, codec_options=_DATETIME_MS_CODEC), encoded) + + def test_round_trip_value_extremes(self): + for doc in _typed_documents(): + self._round_trip(doc) + + def test_round_trip_size_boundaries(self): + # String sizes that cross buffer doubling boundaries. + for size in (127, 128, 255, 256, 2**16, 2**16 + 1): + self._round_trip({"a": "x" * size}) + + +class TestBSONHostileLengths(unittest.TestCase): + """Decode must reject malformed length fields with a BSONError. + + Exercises the C decoder's int-boundary validation without allocating + multi-GiB buffers. + """ + + def _assert_bson_error(self, data, msg=None): + with self.assertRaises(BSONError, msg=msg): + bson.decode(data) + + def test_declared_document_lengths(self): + base = bson.encode({"a": "b" * 20, "c": [1, 2]}) + for length in (0, -1, 0x7F7F7F7F, 0x7FFFFFFF, len(base) + 1): + data = bytearray(base) + data[0:4] = struct.pack(" bytes: + return encode( + { + "small": {"n": 1}, + "big": {"payload": BIG_PAYLOAD, "n": 42}, + "arr": [{"payload": BIG_PAYLOAD, "idx": i} for i in range(3)], + } + ) + class _TaggedRawBSONDocument(RawBSONDocument): """RawBSONDocument subclass with a different __init__ signature and @@ -322,5 +337,141 @@ def test_contains_dbref(self): self.assertEqual(doc["value"].raw, raw_encoded) +class TestRawBSONDocumentConcurrency(unittest.TestCase): + """Concurrency and buffer-lifetime regression tests for zero-copy + RawBSONDocument; also run under the sanitizer CI tasks (see + SANITIZER_FILES in .evergreen/scripts/setup_tests.py). + """ + + def test_concurrent_reads_on_shared_document(self): + doc_bytes = _make_shared_doc_bytes() + shared_doc = RawBSONDocument(doc_bytes) + + # Confirm we're actually exercising the zero-copy memoryview path, + # not accidentally testing a byte-copy fallback. + big_check = shared_doc["big"] + self.assertIsInstance(big_check.raw, memoryview) + self.assertTrue(big_check.raw.readonly) + + errors: list[BaseException] = [] + errors_lock = threading.Lock() + + def worker() -> None: + try: + for _ in range(N_ITERS): + big = shared_doc["big"] + assert big["payload"] == BIG_PAYLOAD + assert big["n"] == 42 + assert isinstance(big.raw, memoryview) + + arr = shared_doc["arr"] + for j, item in enumerate(arr): + assert item["idx"] == j + assert item["payload"] == BIG_PAYLOAD + + small = shared_doc["small"] + assert small["n"] == 1 + + # Re-encodes a view-backed subdocument while other + # threads may be reading the same underlying buffer. + reencoded = encode({"again": big}) + assert isinstance(reencoded, bytes) + + multi = decode_all(doc_bytes * 2, DEFAULT_RAW_BSON_OPTIONS) + assert len(multi) == 2 + for d in multi: + assert isinstance(d["big"].raw, memoryview) + except BaseException as exc: + with errors_lock: + errors.append(exc) + raise + + threads = [threading.Thread(target=worker) for _ in range(N_THREADS)] + for t in threads: + t.start() + for t in threads: + t.join() + + self.assertEqual(errors, []) + + def test_buffer_survives_after_source_bytes_are_dropped(self): + # Slice a bytearray, wrap it in a RawBSONDocument, then mutate and + # drop the original buffer to check for a dangling view. + encoded = _make_shared_doc_bytes() + for _ in range(50): + buf = bytearray(encoded) + b"\x00" * 10 + view = memoryview(buf)[: len(encoded)] + raw = RawBSONDocument(view) + _ = raw["big"] + _ = dict(raw["small"]) + _ = list(raw["arr"]) + copied = dict(raw) + del raw + del view + buf[:] = b"\xff" * len(buf) + del buf + gc.collect() + self.assertEqual(copied["small"]["n"], 1) + + +class _FakeBulkWriteContext: + """Stand-in for pymongo.message._BulkWriteContext. + + The C batched-message builders only read a few numeric size attributes + off the context object. + """ + + max_bson_size = 16 * 1024 * 1024 + max_write_batch_size = 100000 + max_message_size = 48 * 1024 * 1024 + max_split_size = 16 * 1024 * 1024 + + +class TestBatchedMessageBuilderConcurrency(unittest.TestCase): + def test_concurrent_batched_message_building(self): + try: + from pymongo import _cmessage + except ImportError: + self.skipTest("pymongo._cmessage C extension is not built") + + has_op_msg = hasattr(_cmessage, "_encode_batched_op_msg") + has_write_cmd = hasattr(_cmessage, "_encode_batched_write_command") + if not (has_op_msg or has_write_cmd): + self.skipTest("no batched message builder found on pymongo._cmessage") + + ns = "db.coll" + docs = [{"_id": i, "payload": "y" * 100} for i in range(50)] + command = {"insert": "coll", "ordered": True} + ctx = _FakeBulkWriteContext() + insert_op = 0 # pymongo.message._INSERT + + errors: list[BaseException] = [] + errors_lock = threading.Lock() + + def worker() -> None: + try: + for _ in range(N_ITERS): + if has_op_msg: + _cmessage._encode_batched_op_msg( + insert_op, command, docs, True, DEFAULT_RAW_BSON_OPTIONS, ctx + ) + if has_write_cmd: + _cmessage._encode_batched_write_command( + ns, insert_op, command, docs, DEFAULT_RAW_BSON_OPTIONS, ctx + ) + except BaseException as exc: + with errors_lock: + errors.append(exc) + raise + + threads = [threading.Thread(target=worker) for _ in range(N_THREADS)] + for t in threads: + t.start() + for t in threads: + t.join() + + self.assertEqual(errors, []) + + if __name__ == "__main__": unittest.main() From 3bd1f1fae36a01246e8e1352d27bb5d32f1ec98b Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 18 Nov 2026 10:09:15 -0600 Subject: [PATCH 03/26] code cleanup --- doc/changelog.rst | 3 +- pymongo/asynchronous/monitor.py | 47 ++++++++++++++---------- pymongo/periodic_executor.py | 4 +-- pymongo/synchronous/monitor.py | 47 ++++++++++++++---------- test/asynchronous/test_monitor.py | 59 ++++++++++++++++++++++++++++--- test/test_monitor.py | 59 ++++++++++++++++++++++++++++--- test/test_raw_bson_shared.py | 18 +++++----- 7 files changed, 180 insertions(+), 57 deletions(-) diff --git a/doc/changelog.rst b/doc/changelog.rst index 7a6b032381..278507e616 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -16,8 +16,7 @@ Bug fixes pool teardown during :meth:`~pymongo.synchronous.mongo_client.MongoClient.close`. Closing a client now waits (with a bounded timeout) for its monitor threads to stop - before returning, adding up to a couple hundred milliseconds to - ``close()`` (`PYTHON-1634`_). + before returning (`PYTHON-1634`_). .. _PYTHON-6262: https://jira.mongodb.org/browse/PYTHON-6262 diff --git a/pymongo/asynchronous/monitor.py b/pymongo/asynchronous/monitor.py index ebc292379f..88b812fd96 100644 --- a/pymongo/asynchronous/monitor.py +++ b/pymongo/asynchronous/monitor.py @@ -45,6 +45,9 @@ _IS_SYNC = False +# Seconds to wait for an executor to stop before resetting the pool. +_EXECUTOR_JOIN_TIMEOUT = 1 + def _sanitize(error: Exception) -> None: """PYTHON-2433 Clear error traceback info.""" @@ -106,10 +109,22 @@ async def close(self) -> None: """ self.gc_safe_close() - async def join(self, timeout: int | None = None) -> None: - """Wait for the monitor to stop.""" + async def join(self, timeout: float | None = None) -> None: + """Wait for the monitor to stop. + + :param timeout: Maximum time in seconds to wait; ``None`` waits + indefinitely. + """ await self._executor.join(timeout) + async def _wake_and_join_executor(self) -> None: + # Wait briefly for the executor to stop before resetting the pool, so + # we don't race with a connection it has checked out. The timeout is a + # backstop: if the executor is still running, the reset closes its + # socket once the connection is checked in. + self._executor.wake() + await self._executor.join(_EXECUTOR_JOIN_TIMEOUT) + def request_check(self) -> None: """If the monitor is sleeping, wake it soon.""" self._executor.wake() @@ -184,24 +199,25 @@ def gc_safe_close(self) -> None: self._rtt_monitor.gc_safe_close() self.cancel_check() - async def join(self, timeout: int | None = None) -> None: - # The timeout budgets BOTH executors: the RTT join gets whatever - # remains after the heartbeat executor stops. + async def join(self, timeout: float | None = None) -> None: + """Wait for the monitor to stop. + + The timeout budgets both executors: the RTT monitor gets whatever + remains after the heartbeat executor stops. + + :param timeout: Maximum time in seconds to wait; ``None`` waits + indefinitely. + """ start = time.monotonic() await self._executor.join(timeout) if timeout is not None: - timeout = max(0, round(timeout - (time.monotonic() - start))) + timeout = max(0.0, timeout - (time.monotonic() - start)) await self._rtt_monitor.join(timeout) async def close(self) -> None: self.gc_safe_close() await self._rtt_monitor.close() - # Wake the executor and wait briefly for the task to stop before - # resetting the pool, so we don't race with a connection it has - # checked out. The join is a bounded backstop: if the task is still - # running, the reset below closes the socket once it's checked in. - self._executor.wake() - await self._executor.join(1) + await self._wake_and_join_executor() # Increment the generation and maybe close the socket. If the executor # thread has the socket checked out, it will be closed when checked in. await self._reset_connection() @@ -418,12 +434,7 @@ def __init__(self, topology: Topology, topology_settings: TopologySettings, pool async def close(self) -> None: self.gc_safe_close() - # Wake the executor and wait briefly for the task to stop before - # resetting the pool, so we don't race with a connection it has - # checked out. The join is a bounded backstop: if the task is still - # running, the reset below closes the socket once it's checked in. - self._executor.wake() - await self._executor.join(1) + await self._wake_and_join_executor() # Increment the generation and maybe close the socket. If the executor # thread has the socket checked out, it will be closed when checked in. await self._pool.reset() diff --git a/pymongo/periodic_executor.py b/pymongo/periodic_executor.py index c20dfdfec8..67918a603f 100644 --- a/pymongo/periodic_executor.py +++ b/pymongo/periodic_executor.py @@ -87,7 +87,7 @@ def close(self, dummy: Any = None) -> None: if self._task is not current: self._task.cancel() - async def join(self, timeout: int | None = None) -> None: + async def join(self, timeout: float | None = None) -> None: if self._task is not None: await asyncio.wait([self._task], timeout=timeout) # type-ignore: [arg-type] @@ -245,7 +245,7 @@ def close(self, dummy: Any = None) -> None: """ self._stopped = True - def join(self, timeout: int | None = None) -> None: + def join(self, timeout: float | None = None) -> None: if self._thread is not None: try: self._thread.join(timeout) diff --git a/pymongo/synchronous/monitor.py b/pymongo/synchronous/monitor.py index e94c134016..d4ecc54154 100644 --- a/pymongo/synchronous/monitor.py +++ b/pymongo/synchronous/monitor.py @@ -45,6 +45,9 @@ _IS_SYNC = True +# Seconds to wait for an executor to stop before resetting the pool. +_EXECUTOR_JOIN_TIMEOUT = 1 + def _sanitize(error: Exception) -> None: """PYTHON-2433 Clear error traceback info.""" @@ -106,10 +109,22 @@ def close(self) -> None: """ self.gc_safe_close() - def join(self, timeout: int | None = None) -> None: - """Wait for the monitor to stop.""" + def join(self, timeout: float | None = None) -> None: + """Wait for the monitor to stop. + + :param timeout: Maximum time in seconds to wait; ``None`` waits + indefinitely. + """ self._executor.join(timeout) + def _wake_and_join_executor(self) -> None: + # Wait briefly for the executor to stop before resetting the pool, so + # we don't race with a connection it has checked out. The timeout is a + # backstop: if the executor is still running, the reset closes its + # socket once the connection is checked in. + self._executor.wake() + self._executor.join(_EXECUTOR_JOIN_TIMEOUT) + def request_check(self) -> None: """If the monitor is sleeping, wake it soon.""" self._executor.wake() @@ -184,24 +199,25 @@ def gc_safe_close(self) -> None: self._rtt_monitor.gc_safe_close() self.cancel_check() - def join(self, timeout: int | None = None) -> None: - # The timeout budgets BOTH executors: the RTT join gets whatever - # remains after the heartbeat executor stops. + def join(self, timeout: float | None = None) -> None: + """Wait for the monitor to stop. + + The timeout budgets both executors: the RTT monitor gets whatever + remains after the heartbeat executor stops. + + :param timeout: Maximum time in seconds to wait; ``None`` waits + indefinitely. + """ start = time.monotonic() self._executor.join(timeout) if timeout is not None: - timeout = max(0, round(timeout - (time.monotonic() - start))) + timeout = max(0.0, timeout - (time.monotonic() - start)) self._rtt_monitor.join(timeout) def close(self) -> None: self.gc_safe_close() self._rtt_monitor.close() - # Wake the executor and wait briefly for the task to stop before - # resetting the pool, so we don't race with a connection it has - # checked out. The join is a bounded backstop: if the task is still - # running, the reset below closes the socket once it's checked in. - self._executor.wake() - self._executor.join(1) + self._wake_and_join_executor() # Increment the generation and maybe close the socket. If the executor # thread has the socket checked out, it will be closed when checked in. self._reset_connection() @@ -418,12 +434,7 @@ def __init__(self, topology: Topology, topology_settings: TopologySettings, pool def close(self) -> None: self.gc_safe_close() - # Wake the executor and wait briefly for the task to stop before - # resetting the pool, so we don't race with a connection it has - # checked out. The join is a bounded backstop: if the task is still - # running, the reset below closes the socket once it's checked in. - self._executor.wake() - self._executor.join(1) + self._wake_and_join_executor() # Increment the generation and maybe close the socket. If the executor # thread has the socket checked out, it will be closed when checked in. self._pool.reset() diff --git a/test/asynchronous/test_monitor.py b/test/asynchronous/test_monitor.py index 354993d120..a4c5164e5b 100644 --- a/test/asynchronous/test_monitor.py +++ b/test/asynchronous/test_monitor.py @@ -26,11 +26,13 @@ sys.path[0:0] = [""] +from pymongo.asynchronous.monitor import Monitor from pymongo.periodic_executor import _EXECUTORS from test.asynchronous import AsyncIntegrationTest, async_client_context, connected, unittest from test.asynchronous.utils import ( async_wait_until, ) +from test.utils import wait_until as sync_wait_until from test.utils_shared import ( ServerAndTopologyEventListener, gevent_monkey_patched, @@ -123,10 +125,7 @@ def thread_alive(executor): except ReferenceError: return False - deadline = time.monotonic() + 10 - while not thread_alive(monitor._executor) and time.monotonic() < deadline: - time.sleep(0.1) - self.assertTrue(thread_alive(monitor._executor), "monitor thread never started") + sync_wait_until(lambda: thread_alive(monitor._executor), "monitor thread never started") client.close() @@ -172,5 +171,57 @@ def test_no_thread_start_runtime_err_on_shutdown(self): self.assertFalse(completed_process.stdout) +class _SlowExecutor: + """Executor stand-in whose join takes a fixed time.""" + + def __init__(self, delay: float) -> None: + self._delay = delay + + async def join(self, timeout: float | None = None) -> None: + # Blocks with time.sleep on purpose: the sync mirror of this test + # needs the same delay, and unasync does not translate asyncio.sleep. + self._sleep() + + def _sleep(self) -> None: + time.sleep(self._delay) + + +class _RecordingExecutor: + """Executor stand-in that records the timeouts it is joined with.""" + + def __init__(self) -> None: + self.timeouts: list[float | None] = [] + + async def join(self, timeout: float | None = None) -> None: + self.timeouts.append(timeout) + + +class TestMonitorJoin(unittest.IsolatedAsyncioTestCase): + """Unit tests for the timeout budget in Monitor.join.""" + + async def test_rtt_join_gets_unspent_budget(self): + # PYTHON-1634: after the heartbeat executor stops, the RTT monitor + # gets whatever budget remains, never more. + monitor = Monitor.__new__(Monitor) + monitor._executor = _SlowExecutor(0.45) # type: ignore[assignment] + rtt = _RecordingExecutor() + monitor._rtt_monitor = rtt # type: ignore[assignment] + + await monitor.join(1) + rtt_timeout = rtt.timeouts[0] + # Narrowing only; the verified assertion is assertLess below. + assert isinstance(rtt_timeout, float) + self.assertLess(rtt_timeout, 0.95) + + async def test_join_without_timeout_waits_indefinitely(self): + monitor = Monitor.__new__(Monitor) + monitor._executor = _SlowExecutor(0) # type: ignore[assignment] + rtt = _RecordingExecutor() + monitor._rtt_monitor = rtt # type: ignore[assignment] + + await monitor.join(None) + self.assertEqual(rtt.timeouts, [None]) + + if __name__ == "__main__": unittest.main() diff --git a/test/test_monitor.py b/test/test_monitor.py index fdbfb0f2be..74c5a20857 100644 --- a/test/test_monitor.py +++ b/test/test_monitor.py @@ -27,10 +27,12 @@ sys.path[0:0] = [""] from pymongo.periodic_executor import _EXECUTORS +from pymongo.synchronous.monitor import Monitor from test import IntegrationTest, client_context, connected, unittest from test.utils import ( wait_until, ) +from test.utils import wait_until as sync_wait_until from test.utils_shared import ( ServerAndTopologyEventListener, gevent_monkey_patched, @@ -119,10 +121,7 @@ def thread_alive(executor): except ReferenceError: return False - deadline = time.monotonic() + 10 - while not thread_alive(monitor._executor) and time.monotonic() < deadline: - time.sleep(0.1) - self.assertTrue(thread_alive(monitor._executor), "monitor thread never started") + sync_wait_until(lambda: thread_alive(monitor._executor), "monitor thread never started") client.close() @@ -168,5 +167,57 @@ def test_no_thread_start_runtime_err_on_shutdown(self): self.assertFalse(completed_process.stdout) +class _SlowExecutor: + """Executor stand-in whose join takes a fixed time.""" + + def __init__(self, delay: float) -> None: + self._delay = delay + + def join(self, timeout: float | None = None) -> None: + # Blocks with time.sleep on purpose: the sync mirror of this test + # needs the same delay, and unasync does not translate asyncio.sleep. + self._sleep() + + def _sleep(self) -> None: + time.sleep(self._delay) + + +class _RecordingExecutor: + """Executor stand-in that records the timeouts it is joined with.""" + + def __init__(self) -> None: + self.timeouts: list[float | None] = [] + + def join(self, timeout: float | None = None) -> None: + self.timeouts.append(timeout) + + +class TestMonitorJoin(unittest.TestCase): + """Unit tests for the timeout budget in Monitor.join.""" + + def test_rtt_join_gets_unspent_budget(self): + # PYTHON-1634: after the heartbeat executor stops, the RTT monitor + # gets whatever budget remains, never more. + monitor = Monitor.__new__(Monitor) + monitor._executor = _SlowExecutor(0.45) # type: ignore[assignment] + rtt = _RecordingExecutor() + monitor._rtt_monitor = rtt # type: ignore[assignment] + + monitor.join(1) + rtt_timeout = rtt.timeouts[0] + # Narrowing only; the verified assertion is assertLess below. + assert isinstance(rtt_timeout, float) + self.assertLess(rtt_timeout, 0.95) + + def test_join_without_timeout_waits_indefinitely(self): + monitor = Monitor.__new__(Monitor) + monitor._executor = _SlowExecutor(0) # type: ignore[assignment] + rtt = _RecordingExecutor() + monitor._rtt_monitor = rtt # type: ignore[assignment] + + monitor.join(None) + self.assertEqual(rtt.timeouts, [None]) + + if __name__ == "__main__": unittest.main() diff --git a/test/test_raw_bson_shared.py b/test/test_raw_bson_shared.py index 3c43462c0b..4615371292 100644 --- a/test/test_raw_bson_shared.py +++ b/test/test_raw_bson_shared.py @@ -360,27 +360,27 @@ def worker() -> None: try: for _ in range(N_ITERS): big = shared_doc["big"] - assert big["payload"] == BIG_PAYLOAD - assert big["n"] == 42 - assert isinstance(big.raw, memoryview) + self.assertEqual(big["payload"], BIG_PAYLOAD) + self.assertEqual(big["n"], 42) + self.assertIsInstance(big.raw, memoryview) arr = shared_doc["arr"] for j, item in enumerate(arr): - assert item["idx"] == j - assert item["payload"] == BIG_PAYLOAD + self.assertEqual(item["idx"], j) + self.assertEqual(item["payload"], BIG_PAYLOAD) small = shared_doc["small"] - assert small["n"] == 1 + self.assertEqual(small["n"], 1) # Re-encodes a view-backed subdocument while other # threads may be reading the same underlying buffer. reencoded = encode({"again": big}) - assert isinstance(reencoded, bytes) + self.assertIsInstance(reencoded, bytes) multi = decode_all(doc_bytes * 2, DEFAULT_RAW_BSON_OPTIONS) - assert len(multi) == 2 + self.assertEqual(len(multi), 2) for d in multi: - assert isinstance(d["big"].raw, memoryview) + self.assertIsInstance(d["big"].raw, memoryview) except BaseException as exc: with errors_lock: errors.append(exc) From 70cf9f09d81ed4d3f4efe378a0a6ed45908dfcb6 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 18 Nov 2026 13:35:17 -0600 Subject: [PATCH 04/26] Refactor sanitizer setup into setup_sanitizer.py --- .evergreen/scripts/setup_sanitizer.py | 110 +++++++++++++++ .evergreen/scripts/setup_tests.py | 62 +-------- .evergreen/scripts/test_setup_sanitizer.py | 148 +++++++++++++++++++++ CONTRIBUTING.md | 2 +- test/test_raw_bson_shared.py | 2 +- 5 files changed, 263 insertions(+), 61 deletions(-) create mode 100644 .evergreen/scripts/setup_sanitizer.py create mode 100644 .evergreen/scripts/test_setup_sanitizer.py diff --git a/.evergreen/scripts/setup_sanitizer.py b/.evergreen/scripts/setup_sanitizer.py new file mode 100644 index 0000000000..508f9f4ff3 --- /dev/null +++ b/.evergreen/scripts/setup_sanitizer.py @@ -0,0 +1,110 @@ +"""Sanitizer test task configuration (PYTHON-6048, PYTHON-6168). + +The sanitizer tasks build the C extensions with -fsanitize=... flags against +the toolchain's instrumented interpreters and run the files in +SANITIZER_FILES. +""" + +from __future__ import annotations + +import shutil +import subprocess +from pathlib import Path + +from utils import PLATFORM, ROOT, SANITIZER_PYTHON, TSAN_PYTHON, write_env + +# The test files run under the sanitizer tasks (PYTHON-6048, PYTHON-6168, +# PYTHON-6285). They exercise the buffer-protocol acquisition path in +# bson/_cbsonmodule.c (_get_buffer/_prepare_input_buffer), the wire-message +# builders in pymongo/_cmessagemodule.c (_op_msg, _batched_op_msg, +# _encode_batched_write_command), the hostile-input and boundary tests +# driving the decoder and builders directly, and — via the concurrency +# classes added in PYTHON-6168 — concurrent zero-copy RawBSONDocument reads +# and batched message building on free-threaded CPython. +SANITIZER_FILES = [ + "test/test_bson.py", + "test/test_message.py", + "test/test_raw_bson.py", + "test/test_raw_bson_shared.py", + "test/test_client.py", +] + + +def tsan_interface_exported(python_binary: str) -> bool: + """Check the interpreter's dynamic symbols for the TSan interface. + + Instrumented extensions resolve __tsan_func_entry and friends against + the interpreter's dynamic exports; an interpreter built without the + sanitizer exports none of them. + """ + nm = shutil.which("nm") + if nm is None: + # No binutils: skip the check rather than fail the setup. + return True + out = subprocess.run( # noqa: S603 + [nm, "-D", python_binary], + capture_output=True, + text=True, + check=True, + ).stdout + return "__tsan_func_entry" in out + + +def configure_env(sub_test_name: str, test_args: str) -> str: + """Write the environment for a sanitizer test run. + + Returns the TEST_ARGS value to run the tests with. + """ + tsan = sub_test_name == "tsan" + python = TSAN_PYTHON if tsan else SANITIZER_PYTHON + if PLATFORM != "linux": + raise RuntimeError("The sanitizer tests require the Linux Python toolchain.") + if not Path(python).is_file(): + raise RuntimeError( + f"Sanitizer interpreter not found at {python}; the task must run " + "on a host with the sanitizer toolchain Python." + ) + # Clear stale C artifacts: build_ext reuses them by mtime, and a + # plain same-version CPython build shares the ABI tag. + shutil.rmtree(ROOT / "build", ignore_errors=True) + for pkg in ["bson", "pymongo"]: + for ext in (ROOT / pkg).glob("*.so"): + ext.unlink() + # Build and run against the sanitizer-instrumented toolchain CPython, + # and fail loudly rather than silently skip the C extension build. + write_env("UV_PYTHON", python) + write_env("PYMONGO_C_EXT_MUST_BUILD") + # The sanitizer flags live in environment variables, which are not + # part of uv's wheel cache key: a cached wheel built without them + # would load uninstrumented extensions and silently void the run. + write_env("UV_NO_CACHE", "1") + if tsan: + write_env("CFLAGS", "-fsanitize=thread -fno-omit-frame-pointer -g -O1") + write_env("LDFLAGS", "-fsanitize=thread") + # The instrumented interpreter must also export the runtime + # interface the extensions resolve against. + if not tsan_interface_exported(python): + raise RuntimeError( + "The TSan interpreter does not export the TSan interface " + "its extensions resolve against (no __tsan_func_entry in " + "its dynamic symbols). Rebuild the toolchain (PYTHON-6067)." + ) + suppressions = ROOT / ".evergreen" / "tsan-suppressions.txt" + write_env( + "TSAN_OPTIONS", + f"halt_on_error=1:handle_segv=0:suppressions={suppressions}", + ) + else: + write_env("CFLAGS", "-fsanitize=address,undefined -fno-omit-frame-pointer -g -O1") + write_env("LDFLAGS", "-fsanitize=address,undefined") + # CPython's pymalloc trips LeakSanitizer with false positives. + write_env("ASAN_OPTIONS", "detect_leaks=0") + # UBSan only warns by default; make undefined behavior fail the task. + write_env("UBSAN_OPTIONS", "halt_on_error=1:print_stacktrace=1") + # The toolchain interpreter self-initializes the sanitizer runtimes, + # so no LD_PRELOAD: preloading a mismatched runtime would mix two + # sanitizers in one process, and for TSan report false races inside + # CPython's own free-threading internals. + # -s: with halt_on_error=1, a sanitizer failure exits the interpreter + # before pytest replays captured stderr, losing the report and trace. + return "-s " + " ".join(SANITIZER_FILES) + " " + test_args diff --git a/.evergreen/scripts/setup_tests.py b/.evergreen/scripts/setup_tests.py index c5a924d869..6582786e05 100644 --- a/.evergreen/scripts/setup_tests.py +++ b/.evergreen/scripts/setup_tests.py @@ -11,6 +11,7 @@ from pathlib import Path from urllib import request +import setup_sanitizer from utils import ( DRIVERS_TOOLS, ENV_FILE, @@ -19,9 +20,7 @@ PERF_PYTHON_VERSION, PLATFORM, ROOT, - SANITIZER_PYTHON, TEST_SUITE_MAP, - TSAN_PYTHON, Distro, check_drivers_tools, get_test_options, @@ -59,22 +58,7 @@ # Map the test name to test group. GROUP_MAP = dict(fuzz="fuzz", mockupdb="mockupdb", perf="perf") -# The test files run under the sanitizer tasks (PYTHON-6048, PYTHON-6168, -# PYTHON-6285). They exercise the buffer-protocol acquisition path in -# bson/_cbsonmodule.c (_get_buffer/_prepare_input_buffer), the wire-message -# builders in pymongo/_cmessagemodule.c (_op_msg, _batched_op_msg, -# _encode_batched_write_command), the hostile-input and boundary tests -# driving the decoder and builders directly, and — via the concurrency -# classes added in PYTHON-6168 — concurrent zero-copy RawBSONDocument reads -# and batched message building on free-threaded CPython. -SANITIZER_FILES = [ - "test/test_bson.py", - "test/test_message.py", - "test/test_raw_bson.py", - "test/test_raw_bson_shared.py", - "test/test_client.py", -] - +# The test files run under the sanitizer tasks; see sanitizer.py. # The libmongocrypt release used when LIBMONGOCRYPT_URL is not set. Must be at # least 1.21.0; the beta preview string query types were removed in 1.21.0 # (MONGOCRYPT-938). @@ -574,47 +558,7 @@ def handle_test_env() -> None: write_env("FUZZ_CORPUS_DIR", str(corpus_dir)) if test_name == "sanitizer": - tsan = sub_test_name == "tsan" - python = TSAN_PYTHON if tsan else SANITIZER_PYTHON - if PLATFORM != "linux": - raise RuntimeError("The sanitizer tests require the Linux Python toolchain.") - if not Path(python).is_file(): - raise RuntimeError( - f"Sanitizer interpreter not found at {python}; the task must run " - "on a host with the sanitizer toolchain Python." - ) - # Clear stale C artifacts: build_ext reuses them by mtime, and a - # plain same-version CPython build shares the ABI tag. - shutil.rmtree(ROOT / "build", ignore_errors=True) - for pkg in ["bson", "pymongo"]: - for ext in (ROOT / pkg).glob("*.so"): - ext.unlink() - # Build and run against the sanitizer-instrumented toolchain CPython, - # and fail loudly rather than silently skip the C extension build. - write_env("UV_PYTHON", python) - write_env("PYMONGO_C_EXT_MUST_BUILD") - if tsan: - write_env("CFLAGS", "-fsanitize=thread -fno-omit-frame-pointer -g -O1") - write_env("LDFLAGS", "-fsanitize=thread") - suppressions = ROOT / ".evergreen" / "tsan-suppressions.txt" - write_env( - "TSAN_OPTIONS", - f"halt_on_error=1:handle_segv=0:suppressions={suppressions}", - ) - else: - write_env("CFLAGS", "-fsanitize=address,undefined -fno-omit-frame-pointer -g -O1") - write_env("LDFLAGS", "-fsanitize=address,undefined") - # CPython's pymalloc trips LeakSanitizer with false positives. - write_env("ASAN_OPTIONS", "detect_leaks=0") - # UBSan only warns by default; make undefined behavior fail the task. - write_env("UBSAN_OPTIONS", "halt_on_error=1:print_stacktrace=1") - # The toolchain interpreter self-initializes the sanitizer runtimes, - # so no LD_PRELOAD: preloading a mismatched runtime would mix two - # sanitizers in one process, and for TSan report false races inside - # CPython's own free-threading internals. - # -s: with halt_on_error=1, a sanitizer failure exits the interpreter - # before pytest replays captured stderr, losing the report and trace. - TEST_ARGS = "-s " + " ".join(SANITIZER_FILES) + " " + TEST_ARGS + TEST_ARGS = setup_sanitizer.configure_env(sub_test_name, TEST_ARGS) # Add coverage if requested. if opts.cov: diff --git a/.evergreen/scripts/test_setup_sanitizer.py b/.evergreen/scripts/test_setup_sanitizer.py new file mode 100644 index 0000000000..fcefe532b3 --- /dev/null +++ b/.evergreen/scripts/test_setup_sanitizer.py @@ -0,0 +1,148 @@ +"""Tests for .evergreen/scripts/setup_setup_sanitizer.py. + +Run with: python -m pytest .evergreen/scripts/test_setup_sanitizer.py +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).parent)) + +import setup_sanitizer +import utils + +pytestmark = [pytest.mark.default] + + +@pytest.fixture +def repo(tmp_path, monkeypatch): + """A fake repo root with a fake env file and stale build artifacts.""" + root = tmp_path / "repo" + (root / ".evergreen").mkdir(parents=True) + (root / "build").mkdir() + for pkg in ("bson", "pymongo"): + (root / pkg).mkdir() + (root / "bson" / "_cbson.so").write_bytes(b"") + (root / "pymongo" / "_cmessage.so").write_bytes(b"") + (root / ".evergreen" / "tsan-suppressions.txt").write_text("") + interpreter = root / "interpreter" / "python3" + interpreter.parent.mkdir(parents=True) + interpreter.write_bytes(b"") + monkeypatch.setattr(setup_sanitizer, "ROOT", root) + monkeypatch.setattr(setup_sanitizer, "TSAN_PYTHON", str(interpreter)) + monkeypatch.setattr(setup_sanitizer, "SANITIZER_PYTHON", str(interpreter)) + monkeypatch.setattr(utils, "ENV_FILE", tmp_path / "env.sh") + return root + + +def env_lines(): + lines = {} + for line in utils.ENV_FILE.read_text().splitlines(): + name, _, value = line.removeprefix("export ").partition("=") + lines[name] = value.strip('"') + return lines + + +@pytest.mark.usefixtures("repo") +def test_tsan_env_writes_expected_variables(monkeypatch): + monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") + monkeypatch.setattr(setup_sanitizer, "tsan_interface_exported", lambda *_: True) + + test_args = setup_sanitizer.configure_env("tsan", "--existing args") + + lines = env_lines() + assert lines["UV_PYTHON"] == setup_sanitizer.TSAN_PYTHON + assert lines["CFLAGS"] == "-fsanitize=thread -fno-omit-frame-pointer -g -O1" + assert lines["LDFLAGS"] == "-fsanitize=thread" + assert lines["UV_NO_CACHE"] == "1" + assert "tsan-suppressions.txt" in lines["TSAN_OPTIONS"] + assert "halt_on_error=1" in lines["TSAN_OPTIONS"] + assert lines["PYMONGO_C_EXT_MUST_BUILD"] == "1" + assert test_args.startswith("-s test/test_bson.py test/test_message.py") + assert test_args.endswith("--existing args") + + +def test_tsan_env_clears_stale_c_artifacts(repo, monkeypatch): + monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") + monkeypatch.setattr(setup_sanitizer, "tsan_interface_exported", lambda *_: True) + + setup_sanitizer.configure_env("tsan", "") + + assert not (repo / "build").exists() + assert not list(repo.glob("*/*.so")) + + +@pytest.mark.usefixtures("repo") +def test_asan_env_writes_expected_variables(monkeypatch): + monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") + + test_args = setup_sanitizer.configure_env("asan", "") + + lines = env_lines() + assert lines["UV_PYTHON"] == setup_sanitizer.SANITIZER_PYTHON + assert lines["CFLAGS"] == "-fsanitize=address,undefined -fno-omit-frame-pointer -g -O1" + assert lines["LDFLAGS"] == "-fsanitize=address,undefined" + assert lines["ASAN_OPTIONS"] == "detect_leaks=0" + assert lines["UBSAN_OPTIONS"] == "halt_on_error=1:print_stacktrace=1" + assert lines["UV_NO_CACHE"] == "1" + assert "TSAN_OPTIONS" not in lines + assert test_args.startswith("-s ") + + +@pytest.mark.usefixtures("repo") +def test_tsan_env_fails_without_the_exported_interface(monkeypatch): + monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") + monkeypatch.setattr(setup_sanitizer, "tsan_interface_exported", lambda *_: False) + + with pytest.raises(RuntimeError, match="__tsan_func_entry"): + setup_sanitizer.configure_env("tsan", "") + + +@pytest.mark.usefixtures("repo") +def test_env_fails_off_linux(monkeypatch): + monkeypatch.setattr(setup_sanitizer, "PLATFORM", "darwin") + + with pytest.raises(RuntimeError, match="Linux Python toolchain"): + setup_sanitizer.configure_env("tsan", "") + + +def test_env_fails_without_the_interpreter(monkeypatch, tmp_path): + monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") + monkeypatch.setattr(setup_sanitizer, "TSAN_PYTHON", str(tmp_path / "missing" / "python3")) + + with pytest.raises(RuntimeError, match="Sanitizer interpreter not found"): + setup_sanitizer.configure_env("tsan", "") + + +def test_tsan_interface_exported_skips_without_nm(monkeypatch): + monkeypatch.setattr(setup_sanitizer.shutil, "which", lambda *_: None) + + assert setup_sanitizer.tsan_interface_exported("python3") is True + + +def test_tsan_interface_exported_true(monkeypatch, tmp_path): + binary = tmp_path / "python3" + binary.write_bytes(b"") + monkeypatch.setattr( + setup_sanitizer.subprocess, + "run", + lambda *args, **kwargs: type("R", (), {"stdout": "T __tsan_func_entry\n"})(), + ) + + assert setup_sanitizer.tsan_interface_exported(str(binary)) is True + + +def test_tsan_interface_exported_false(monkeypatch, tmp_path): + binary = tmp_path / "python3" + binary.write_bytes(b"") + monkeypatch.setattr( + setup_sanitizer.subprocess, + "run", + lambda *args, **kwargs: type("R", (), {"stdout": ""})(), + ) + + assert setup_sanitizer.tsan_interface_exported(str(binary)) is False diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3d2ba4ddaa..2210f30906 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -509,7 +509,7 @@ CPython version whose toolchain dir exists, `UV_PYTHON_SEARCH_PATH` points uv at The `sanitizer` test suite (PYTHON-6048) builds the C extensions with `-fsanitize=address,undefined` against the toolchain's ASan/UBSan-instrumented CPython (`SANITIZER_PYTHON` in `.evergreen/scripts/utils.py`) and runs the -files listed in `SANITIZER_FILES` in `.evergreen/scripts/setup_tests.py`. The +files listed in `SANITIZER_FILES` in `.evergreen/scripts/setup_sanitizer.py`. The toolchain interpreter initializes the sanitizer runtimes itself. It runs on PRs via the "Sanitizer RHEL8" variant. To run it on a Linux host with the toolchain: diff --git a/test/test_raw_bson_shared.py b/test/test_raw_bson_shared.py index 4615371292..90e35f2bf1 100644 --- a/test/test_raw_bson_shared.py +++ b/test/test_raw_bson_shared.py @@ -340,7 +340,7 @@ def test_contains_dbref(self): class TestRawBSONDocumentConcurrency(unittest.TestCase): """Concurrency and buffer-lifetime regression tests for zero-copy RawBSONDocument; also run under the sanitizer CI tasks (see - SANITIZER_FILES in .evergreen/scripts/setup_tests.py). + SANITIZER_FILES in .evergreen/scripts/setup_sanitizer.py). """ def test_concurrent_reads_on_shared_document(self): From da0d6f9baad00ac11cdf0478d648c185ebd1659c Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 08:25:53 -0600 Subject: [PATCH 05/26] Fix the sanitizer extension builds --- .evergreen/scripts/setup_sanitizer.py | 149 ++++++++++++++++++++- .evergreen/scripts/test_setup_sanitizer.py | 126 ++++++++++++++++- 2 files changed, 270 insertions(+), 5 deletions(-) diff --git a/.evergreen/scripts/setup_sanitizer.py b/.evergreen/scripts/setup_sanitizer.py index 508f9f4ff3..366beb0c92 100644 --- a/.evergreen/scripts/setup_sanitizer.py +++ b/.evergreen/scripts/setup_sanitizer.py @@ -7,6 +7,7 @@ from __future__ import annotations +import re import shutil import subprocess from pathlib import Path @@ -50,6 +51,103 @@ def tsan_interface_exported(python_binary: str) -> bool: return "__tsan_func_entry" in out +def _first_line(args: list[str]) -> str | None: + """Return the first stdout line of a command, or None if it cannot run.""" + try: + out = subprocess.run( # noqa: S603 + args, + capture_output=True, + text=True, + check=True, + ).stdout + except (OSError, subprocess.SubprocessError): + return None + return out.strip().splitlines()[0] if out.strip() else None + + +def interpreter_clang_version(python_binary: str) -> str | None: + """Return the clang version that built the interpreter, if discoverable. + + platform.python_compiler() reports e.g. "Clang 14.0.6 (Red Hat + 14.0.6-1.module+el8.7.0+15816+ec020e8f)" for the toolchain interpreters. + """ + out = _first_line([python_binary, "-c", "import platform; print(platform.python_compiler())"]) + match = re.search(r"Clang (\d+(?:\.\d+)+)", out or "") + return match.group(1) if match else None + + +def compiler_clang_version(compiler: str) -> str | None: + """Return the clang version of the compiler, if discoverable.""" + match = re.search(r"clang version (\d+(?:\.\d+)+)", _first_line([compiler, "--version"]) or "") + return match.group(1) if match else None + + +def clang_candidates() -> list[str]: + """Return the clang compilers the image may carry. + + The hosts carry several: the mongodbtoolchain's versioned installs and + the system clang, whose /usr/bin one (clang 22.1.8) is far newer than + the module clang 14.0.6 that built the instrumented interpreters. + """ + root = Path("/") + return sorted( + [ + str(path) + for pattern in ( + "opt/mongodbtoolchain/*/bin/clang", + "usr/lib64/llvm*/bin/clang", + "usr/bin/clang-*", + ) + for path in root.glob(pattern) + ] + + ["/usr/bin/clang", "/usr/local/bin/clang"] + ) + + +def find_matching_clang(version: str) -> tuple[str, str, bool]: + """Return a clang compatible with the interpreter's build compiler. + + Instrumented extensions resolve the sanitizer's interface symbols + against the interpreter's runtime; a NEWER compiler emits references + the runtime does not export (undefined symbol at import: __tsan_memcpy + under TSan with a newer clang's memcall lowering, + __ubsan_handle_function_type_mismatch under UBSan's function check). + The reverse direction is the supported one: the runtime's + compiled-code interface is forward-compatible, so when the exact + compiler is absent the newest clang OLDER than the interpreter's is a + usable stopgap. Returns (path, clang version, exact match). + """ + probed = [] + fallback: tuple[str, str] | None = None + required = _version_key(version) + for candidate in clang_candidates(): + candidate_version = compiler_clang_version(candidate) + if candidate_version is None: + continue + probed.append(f"{candidate} (clang {candidate_version})") + if candidate_version == version: + return candidate, candidate_version, True + candidate_key = _version_key(candidate_version) + if candidate_key < required and ( + fallback is None or candidate_key > _version_key(fallback[1]) + ): + fallback = (candidate, candidate_version) + if fallback is not None: + return *fallback, False + raise RuntimeError( + f"No clang compatible with the interpreter's build compiler " + f"(clang {version}) was found on this host. Probed: " + + ("; ".join(probed) if probed else "none") + + ". The toolchain image must provide the clang that built its " + "instrumented interpreters (PYTHON-6067)." + ) + + +def _version_key(version: str) -> tuple[int, ...]: + """Return a numeric sort key for a dotted version string.""" + return tuple(int(part) for part in version.split(".")) + + def configure_env(sub_test_name: str, test_args: str) -> str: """Write the environment for a sanitizer test run. @@ -70,8 +168,45 @@ def configure_env(sub_test_name: str, test_args: str) -> str: for pkg in ["bson", "pymongo"]: for ext in (ROOT / pkg).glob("*.so"): ext.unlink() - # Build and run against the sanitizer-instrumented toolchain CPython, - # and fail loudly rather than silently skip the C extension build. + # The extensions must be compiled by a clang whose version matches the + # one that built the interpreter (see find_matching_clang), so resolve + # the compiler by version match and fail setup — with the probed + # inventory in the message — when the host has no match, rather than + # failing deep in the run with a confusing ImportError. + interpreter_version = interpreter_clang_version(python) + if interpreter_version is None: + # Cannot probe the interpreter: fall back to the system clang and + # say so; a mismatch would surface at import time as before. + compiler = "/usr/bin/clang" + compiler_version = compiler_clang_version(compiler) + print( + "sanitizer setup: the interpreter's clang version is not " + f"discoverable; falling back to the extension compiler {compiler} " + f"(clang {compiler_version}); the compiler/interpreter match is " + "unchecked." + ) + else: + compiler, compiler_version, exact = find_matching_clang(interpreter_version) + if exact: + print( + f"sanitizer setup: extensions compile with {compiler} (clang " + f"{compiler_version}); the interpreter was built with clang " + f"{interpreter_version}." + ) + else: + print( + f"sanitizer setup: no clang {interpreter_version} on this host; " + f"extensions compile with {compiler} (clang {compiler_version}), " + "the newest clang older than the interpreter's build compiler " + "— a newer compiler emits references the interpreter's runtime " + "does not export. Upgrade the toolchain image to ship the " + "interpreter's compiler (PYTHON-6067)." + ) + compiler_path = Path(compiler) + write_env("CC", compiler) + write_env( + "CXX", str(compiler_path.with_name(compiler_path.name.replace("clang", "clang++", 1))) + ) write_env("UV_PYTHON", python) write_env("PYMONGO_C_EXT_MUST_BUILD") # The sanitizer flags live in environment variables, which are not @@ -95,7 +230,15 @@ def configure_env(sub_test_name: str, test_args: str) -> str: f"halt_on_error=1:handle_segv=0:suppressions={suppressions}", ) else: - write_env("CFLAGS", "-fsanitize=address,undefined -fno-omit-frame-pointer -g -O1") + # -fno-sanitize=function: the toolchain interpreter's UBSan runtime + # predates the image's clang, whose function check references a + # handler the runtime does not export — the extensions fail to + # import with undefined symbol: __ubsan_handle_function_type_mismatch + # (PYTHON-6167). + write_env( + "CFLAGS", + "-fsanitize=address,undefined -fno-sanitize=function -fno-omit-frame-pointer -g -O1", + ) write_env("LDFLAGS", "-fsanitize=address,undefined") # CPython's pymalloc trips LeakSanitizer with false positives. write_env("ASAN_OPTIONS", "detect_leaks=0") diff --git a/.evergreen/scripts/test_setup_sanitizer.py b/.evergreen/scripts/test_setup_sanitizer.py index fcefe532b3..ff399c84c0 100644 --- a/.evergreen/scripts/test_setup_sanitizer.py +++ b/.evergreen/scripts/test_setup_sanitizer.py @@ -31,10 +31,20 @@ def repo(tmp_path, monkeypatch): (root / ".evergreen" / "tsan-suppressions.txt").write_text("") interpreter = root / "interpreter" / "python3" interpreter.parent.mkdir(parents=True) - interpreter.write_bytes(b"") + interpreter.write_text( + "#!/bin/sh\n" + 'if [ "$1" = "-c" ]; then\n' + " echo 'Clang 14.0.6 (Red Hat 14.0.6-1.module+el8.7.0+15816+ec020e8f)'\n" + "else\n" + " echo 'clang -pthread'\n" + "fi\n" + ) + interpreter.chmod(0o755) monkeypatch.setattr(setup_sanitizer, "ROOT", root) monkeypatch.setattr(setup_sanitizer, "TSAN_PYTHON", str(interpreter)) monkeypatch.setattr(setup_sanitizer, "SANITIZER_PYTHON", str(interpreter)) + monkeypatch.setattr(setup_sanitizer, "clang_candidates", lambda: ["/usr/bin/clang"]) + monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda *_: "14.0.6") monkeypatch.setattr(utils, "ENV_FILE", tmp_path / "env.sh") return root @@ -56,6 +66,8 @@ def test_tsan_env_writes_expected_variables(monkeypatch): lines = env_lines() assert lines["UV_PYTHON"] == setup_sanitizer.TSAN_PYTHON + assert lines["CC"] == "/usr/bin/clang" + assert lines["CXX"] == "/usr/bin/clang++" assert lines["CFLAGS"] == "-fsanitize=thread -fno-omit-frame-pointer -g -O1" assert lines["LDFLAGS"] == "-fsanitize=thread" assert lines["UV_NO_CACHE"] == "1" @@ -84,7 +96,12 @@ def test_asan_env_writes_expected_variables(monkeypatch): lines = env_lines() assert lines["UV_PYTHON"] == setup_sanitizer.SANITIZER_PYTHON - assert lines["CFLAGS"] == "-fsanitize=address,undefined -fno-omit-frame-pointer -g -O1" + assert lines["CC"] == "/usr/bin/clang" + assert lines["CXX"] == "/usr/bin/clang++" + assert ( + lines["CFLAGS"] + == "-fsanitize=address,undefined -fno-sanitize=function -fno-omit-frame-pointer -g -O1" + ) assert lines["LDFLAGS"] == "-fsanitize=address,undefined" assert lines["ASAN_OPTIONS"] == "detect_leaks=0" assert lines["UBSAN_OPTIONS"] == "halt_on_error=1:print_stacktrace=1" @@ -93,6 +110,111 @@ def test_asan_env_writes_expected_variables(monkeypatch): assert test_args.startswith("-s ") +@pytest.mark.usefixtures("repo") +def test_tsan_env_fails_on_compiler_mismatch(monkeypatch): + monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") + monkeypatch.setattr(setup_sanitizer, "tsan_interface_exported", lambda *_: True) + monkeypatch.setattr( + setup_sanitizer, + "clang_candidates", + lambda: ["/opt/mongodbtoolchain/v5/bin/clang", "/usr/bin/clang"], + ) + versions = { + "/opt/mongodbtoolchain/v5/bin/clang": "19.1.7", + "/usr/bin/clang": "22.1.8", + } + monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda cc: versions[cc]) + + with pytest.raises(RuntimeError, match=r"14\.0\.6.*19\.1\.7.*22\.1\.8"): + setup_sanitizer.configure_env("tsan", "") + + +def test_find_matching_clang_picks_the_interpreters_version(monkeypatch): + candidates = [ + "/opt/mongodbtoolchain/v5/bin/clang", + "/opt/rh/llvm-toolset-14/root/usr/bin/clang", + ] + monkeypatch.setattr(setup_sanitizer, "clang_candidates", lambda: candidates) + versions = dict(zip(candidates, ["19.1.7", "14.0.6"], strict=False)) + monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda cc: versions[cc]) + + assert setup_sanitizer.find_matching_clang("14.0.6") == ( + "/opt/rh/llvm-toolset-14/root/usr/bin/clang", + "14.0.6", + True, + ) + + +def test_find_matching_clang_falls_back_to_the_newest_older_clang(monkeypatch): + """No exact match: the newest clang OLDER than the interpreter's is the + stopgap — a newer clang emits references the runtime does not export + (the v5 clang 19.1.7 and the system clang 22.1.8 both fail on hosts + whose interpreters were built with clang 14.0.6). + """ + candidates = [ + "/opt/mongodbtoolchain/v4/bin/clang", + "/opt/mongodbtoolchain/v5/bin/clang", + "/usr/bin/clang", + ] + monkeypatch.setattr(setup_sanitizer, "clang_candidates", lambda: candidates) + versions = dict(zip(candidates, ["12.0.1", "19.1.7", "22.1.8"], strict=False)) + monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda cc: versions[cc]) + + assert setup_sanitizer.find_matching_clang("14.0.6") == ( + "/opt/mongodbtoolchain/v4/bin/clang", + "12.0.1", + False, + ) + + +def test_find_matching_clang_lists_the_probed_candidates_on_failure(monkeypatch): + candidates = ["/opt/mongodbtoolchain/v5/bin/clang", "/usr/bin/clang"] + monkeypatch.setattr(setup_sanitizer, "clang_candidates", lambda: candidates) + versions = dict(zip(candidates, ["19.1.7", "22.1.8"], strict=False)) + monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda cc: versions[cc]) + + with pytest.raises(RuntimeError, match=r"14\.0\.6.*19\.1\.7.*22\.1\.8"): + setup_sanitizer.find_matching_clang("14.0.6") + + +@pytest.mark.usefixtures("repo") +def test_tsan_env_proceeds_without_a_discoverable_compiler_version(monkeypatch, capsys): + monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") + monkeypatch.setattr(setup_sanitizer, "tsan_interface_exported", lambda *_: True) + monkeypatch.setattr(setup_sanitizer, "interpreter_clang_version", lambda *_: None) + monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda *_: None) + + setup_sanitizer.configure_env("tsan", "") + + assert "not discoverable" in capsys.readouterr().out + + +def test_interpreter_clang_version_parses_the_compiler_banner(tmp_path, monkeypatch): + binary = tmp_path / "python3" + binary.write_bytes(b"") + monkeypatch.setattr( + setup_sanitizer.subprocess, + "run", + lambda *args, **kwargs: type( + "R", (), {"stdout": "Clang 14.0.6 (Red Hat 14.0.6-1.module+el8.7.0+15816+ec020e8f)\n"} + )(), + ) + + assert setup_sanitizer.interpreter_clang_version(str(binary)) == "14.0.6" + + +def test_interpreter_clang_version_skips_a_non_clang_interpreter(tmp_path, monkeypatch): + binary = tmp_path / "python3" + binary.write_bytes(b"") + monkeypatch.setattr( + setup_sanitizer.subprocess, + "run", + lambda *args, **kwargs: type("R", (), {"stdout": "GCC 12.1.1\n"})(), + ) + + assert setup_sanitizer.interpreter_clang_version(str(binary)) is None + + @pytest.mark.usefixtures("repo") def test_tsan_env_fails_without_the_exported_interface(monkeypatch): monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") From 3cbb36c1fe2bf6c09bc4b6511c9714989738a038 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 08:45:22 -0600 Subject: [PATCH 06/26] Remove sanitizer setup tests and apply coding-standards audit fixes --- .evergreen/scripts/setup_sanitizer.py | 2 +- .evergreen/scripts/setup_tests.py | 1 - .evergreen/scripts/test_setup_sanitizer.py | 271 --------------------- .evergreen/tsan-suppressions.txt | 2 +- pymongo/asynchronous/monitor.py | 6 +- pymongo/asynchronous/topology.py | 4 +- pymongo/synchronous/monitor.py | 6 +- pymongo/synchronous/topology.py | 4 +- 8 files changed, 12 insertions(+), 284 deletions(-) delete mode 100644 .evergreen/scripts/test_setup_sanitizer.py diff --git a/.evergreen/scripts/setup_sanitizer.py b/.evergreen/scripts/setup_sanitizer.py index 366beb0c92..32db84bf8b 100644 --- a/.evergreen/scripts/setup_sanitizer.py +++ b/.evergreen/scripts/setup_sanitizer.py @@ -115,7 +115,7 @@ def find_matching_clang(version: str) -> tuple[str, str, bool]: The reverse direction is the supported one: the runtime's compiled-code interface is forward-compatible, so when the exact compiler is absent the newest clang OLDER than the interpreter's is a - usable stopgap. Returns (path, clang version, exact match). + usable fallback. Returns (path, clang version, exact match). """ probed = [] fallback: tuple[str, str] | None = None diff --git a/.evergreen/scripts/setup_tests.py b/.evergreen/scripts/setup_tests.py index 2e2cf31ee4..a8bc490106 100644 --- a/.evergreen/scripts/setup_tests.py +++ b/.evergreen/scripts/setup_tests.py @@ -60,7 +60,6 @@ # Map the test name to test group. GROUP_MAP = dict(fuzz="fuzz", mockupdb="mockupdb", perf="perf") -# The test files run under the sanitizer tasks; see sanitizer.py. # The libmongocrypt release used when LIBMONGOCRYPT_URL is not set. Must be at # least 1.21.0; the beta preview string query types were removed in 1.21.0 # (MONGOCRYPT-938). diff --git a/.evergreen/scripts/test_setup_sanitizer.py b/.evergreen/scripts/test_setup_sanitizer.py deleted file mode 100644 index 98dbc44971..0000000000 --- a/.evergreen/scripts/test_setup_sanitizer.py +++ /dev/null @@ -1,271 +0,0 @@ -"""Tests for .evergreen/scripts/setup_setup_sanitizer.py. - -Run with: python -m pytest .evergreen/scripts/test_setup_sanitizer.py -""" - -from __future__ import annotations - -import sys -from pathlib import Path - -import pytest - -sys.path.insert(0, str(Path(__file__).parent)) - -import setup_sanitizer -import utils - -pytestmark = [pytest.mark.default] - - -@pytest.fixture -def repo(tmp_path, monkeypatch): - """Create a fake repo root with a fake env file and stale build artifacts.""" - root = tmp_path / "repo" - (root / ".evergreen").mkdir(parents=True) - (root / "build").mkdir() - for pkg in ("bson", "pymongo"): - (root / pkg).mkdir() - (root / "bson" / "_cbson.so").write_bytes(b"") - (root / "pymongo" / "_cmessage.so").write_bytes(b"") - (root / ".evergreen" / "tsan-suppressions.txt").write_text("") - interpreter = root / "interpreter" / "python3" - interpreter.parent.mkdir(parents=True) - interpreter.write_text( - "#!/bin/sh\n" - 'if [ "$1" = "-c" ]; then\n' - " echo 'Clang 14.0.6 (Red Hat 14.0.6-1.module+el8.7.0+15816+ec020e8f)'\n" - "else\n" - " echo 'clang -pthread'\n" - "fi\n" - ) - interpreter.chmod(0o755) - monkeypatch.setattr(setup_sanitizer, "ROOT", root) - monkeypatch.setattr(setup_sanitizer, "TSAN_PYTHON", str(interpreter)) - monkeypatch.setattr(setup_sanitizer, "SANITIZER_PYTHON", str(interpreter)) - monkeypatch.setattr(setup_sanitizer, "clang_candidates", lambda: ["/usr/bin/clang"]) - monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda *_: "14.0.6") - monkeypatch.setattr(utils, "ENV_FILE", tmp_path / "env.sh") - return root - - -def env_lines(): - lines = {} - for line in utils.ENV_FILE.read_text().splitlines(): - name, _, value = line.removeprefix("export ").partition("=") - lines[name] = value.strip('"') - return lines - - -@pytest.mark.usefixtures("repo") -def test_tsan_env_writes_expected_variables(monkeypatch): - monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") - monkeypatch.setattr(setup_sanitizer, "tsan_interface_exported", lambda *_: True) - - test_args = setup_sanitizer.configure_env("tsan", "--existing args") - - lines = env_lines() - assert lines["UV_PYTHON"] == setup_sanitizer.TSAN_PYTHON - assert lines["CC"] == "/usr/bin/clang" - assert lines["CXX"] == "/usr/bin/clang++" - assert lines["CFLAGS"] == "-fsanitize=thread -fno-omit-frame-pointer -g -O1" - assert lines["LDFLAGS"] == "-fsanitize=thread" - assert lines["UV_NO_CACHE"] == "1" - assert "tsan-suppressions.txt" in lines["TSAN_OPTIONS"] - assert "halt_on_error=1" in lines["TSAN_OPTIONS"] - assert lines["PYMONGO_C_EXT_MUST_BUILD"] == "1" - assert test_args.startswith("-s test/test_bson.py test/test_message.py") - assert test_args.endswith("--existing args") - - -def test_tsan_env_clears_stale_c_artifacts(repo, monkeypatch): - monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") - monkeypatch.setattr(setup_sanitizer, "tsan_interface_exported", lambda *_: True) - - setup_sanitizer.configure_env("tsan", "") - - assert not (repo / "build").exists() - assert not list(repo.glob("*/*.so")) - - -@pytest.mark.usefixtures("repo") -def test_asan_env_writes_expected_variables(monkeypatch): - monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") - - test_args = setup_sanitizer.configure_env("asan", "") - - lines = env_lines() - assert lines["UV_PYTHON"] == setup_sanitizer.SANITIZER_PYTHON - assert lines["CC"] == "/usr/bin/clang" - assert lines["CXX"] == "/usr/bin/clang++" - assert ( - lines["CFLAGS"] - == "-fsanitize=address,undefined -fno-sanitize=function -fno-omit-frame-pointer -g -O1" - ) - assert lines["LDFLAGS"] == "-fsanitize=address,undefined" - assert lines["ASAN_OPTIONS"] == "detect_leaks=0" - assert lines["UBSAN_OPTIONS"] == "halt_on_error=1:print_stacktrace=1" - assert lines["UV_NO_CACHE"] == "1" - assert "TSAN_OPTIONS" not in lines - assert test_args.startswith("-s ") - - -@pytest.mark.usefixtures("repo") -def test_tsan_env_fails_on_compiler_mismatch(monkeypatch): - monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") - monkeypatch.setattr(setup_sanitizer, "tsan_interface_exported", lambda *_: True) - monkeypatch.setattr( - setup_sanitizer, - "clang_candidates", - lambda: ["/opt/mongodbtoolchain/v5/bin/clang", "/usr/bin/clang"], - ) - versions = { - "/opt/mongodbtoolchain/v5/bin/clang": "19.1.7", - "/usr/bin/clang": "22.1.8", - } - monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda cc: versions[cc]) - - with pytest.raises(RuntimeError, match=r"14\.0\.6.*19\.1\.7.*22\.1\.8"): - setup_sanitizer.configure_env("tsan", "") - - -def test_find_matching_clang_picks_the_interpreters_version(monkeypatch): - candidates = [ - "/opt/mongodbtoolchain/v5/bin/clang", - "/opt/rh/llvm-toolset-14/root/usr/bin/clang", - ] - monkeypatch.setattr(setup_sanitizer, "clang_candidates", lambda: candidates) - versions = dict(zip(candidates, ["19.1.7", "14.0.6"], strict=False)) - monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda cc: versions[cc]) - - assert setup_sanitizer.find_matching_clang("14.0.6") == ( - "/opt/rh/llvm-toolset-14/root/usr/bin/clang", - "14.0.6", - True, - ) - - -def test_find_matching_clang_falls_back_to_the_newest_older_clang(monkeypatch): - """No exact match: the newest clang OLDER than the interpreter's is the stopgap. - - A newer clang emits references the runtime does not export (the v5 clang - 19.1.7 and the system clang 22.1.8 both fail on hosts whose interpreters - were built with clang 14.0.6). - """ - candidates = [ - "/opt/mongodbtoolchain/v4/bin/clang", - "/opt/mongodbtoolchain/v5/bin/clang", - "/usr/bin/clang", - ] - monkeypatch.setattr(setup_sanitizer, "clang_candidates", lambda: candidates) - versions = dict(zip(candidates, ["12.0.1", "19.1.7", "22.1.8"], strict=False)) - monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda cc: versions[cc]) - - assert setup_sanitizer.find_matching_clang("14.0.6") == ( - "/opt/mongodbtoolchain/v4/bin/clang", - "12.0.1", - False, - ) - - -def test_find_matching_clang_lists_the_probed_candidates_on_failure(monkeypatch): - candidates = ["/opt/mongodbtoolchain/v5/bin/clang", "/usr/bin/clang"] - monkeypatch.setattr(setup_sanitizer, "clang_candidates", lambda: candidates) - versions = dict(zip(candidates, ["19.1.7", "22.1.8"], strict=False)) - monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda cc: versions[cc]) - - with pytest.raises(RuntimeError, match=r"14\.0\.6.*19\.1\.7.*22\.1\.8"): - setup_sanitizer.find_matching_clang("14.0.6") - - -@pytest.mark.usefixtures("repo") -def test_tsan_env_proceeds_without_a_discoverable_compiler_version(monkeypatch, capsys): - monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") - monkeypatch.setattr(setup_sanitizer, "tsan_interface_exported", lambda *_: True) - monkeypatch.setattr(setup_sanitizer, "interpreter_clang_version", lambda *_: None) - monkeypatch.setattr(setup_sanitizer, "compiler_clang_version", lambda *_: None) - - setup_sanitizer.configure_env("tsan", "") - - assert "not discoverable" in capsys.readouterr().out - - -def test_interpreter_clang_version_parses_the_compiler_banner(tmp_path, monkeypatch): - binary = tmp_path / "python3" - binary.write_bytes(b"") - monkeypatch.setattr( - setup_sanitizer.subprocess, - "run", - lambda *args, **kwargs: type( - "R", (), {"stdout": "Clang 14.0.6 (Red Hat 14.0.6-1.module+el8.7.0+15816+ec020e8f)\n"} - )(), - ) - - assert setup_sanitizer.interpreter_clang_version(str(binary)) == "14.0.6" - - -def test_interpreter_clang_version_skips_a_non_clang_interpreter(tmp_path, monkeypatch): - binary = tmp_path / "python3" - binary.write_bytes(b"") - monkeypatch.setattr( - setup_sanitizer.subprocess, - "run", - lambda *args, **kwargs: type("R", (), {"stdout": "GCC 12.1.1\n"})(), - ) - - assert setup_sanitizer.interpreter_clang_version(str(binary)) is None - - -@pytest.mark.usefixtures("repo") -def test_tsan_env_fails_without_the_exported_interface(monkeypatch): - monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") - monkeypatch.setattr(setup_sanitizer, "tsan_interface_exported", lambda *_: False) - - with pytest.raises(RuntimeError, match="__tsan_func_entry"): - setup_sanitizer.configure_env("tsan", "") - - -@pytest.mark.usefixtures("repo") -def test_env_fails_off_linux(monkeypatch): - monkeypatch.setattr(setup_sanitizer, "PLATFORM", "darwin") - - with pytest.raises(RuntimeError, match="Linux Python toolchain"): - setup_sanitizer.configure_env("tsan", "") - - -def test_env_fails_without_the_interpreter(monkeypatch, tmp_path): - monkeypatch.setattr(setup_sanitizer, "PLATFORM", "linux") - monkeypatch.setattr(setup_sanitizer, "TSAN_PYTHON", str(tmp_path / "missing" / "python3")) - - with pytest.raises(RuntimeError, match="Sanitizer interpreter not found"): - setup_sanitizer.configure_env("tsan", "") - - -def test_tsan_interface_exported_skips_without_nm(monkeypatch): - monkeypatch.setattr(setup_sanitizer.shutil, "which", lambda *_: None) - - assert setup_sanitizer.tsan_interface_exported("python3") is True - - -def test_tsan_interface_exported_true(monkeypatch, tmp_path): - binary = tmp_path / "python3" - binary.write_bytes(b"") - monkeypatch.setattr( - setup_sanitizer.subprocess, - "run", - lambda *args, **kwargs: type("R", (), {"stdout": "T __tsan_func_entry\n"})(), - ) - - assert setup_sanitizer.tsan_interface_exported(str(binary)) is True - - -def test_tsan_interface_exported_false(monkeypatch, tmp_path): - binary = tmp_path / "python3" - binary.write_bytes(b"") - monkeypatch.setattr( - setup_sanitizer.subprocess, - "run", - lambda *args, **kwargs: type("R", (), {"stdout": ""})(), - ) - - assert setup_sanitizer.tsan_interface_exported(str(binary)) is False diff --git a/.evergreen/tsan-suppressions.txt b/.evergreen/tsan-suppressions.txt index 66feeca453..e5afc1949e 100644 --- a/.evergreen/tsan-suppressions.txt +++ b/.evergreen/tsan-suppressions.txt @@ -1,7 +1,7 @@ # PyMongo-specific ThreadSanitizer suppressions. # # The TSan task (PYTHON-6168) passes this file as TSan's single -# suppressions= path via TSAN_OPTIONS in .evergreen/scripts/setup_tests.py. +# suppressions= path via TSAN_OPTIONS in .evergreen/scripts/setup_sanitizer.py. # # Add an entry below only for a race that has been investigated and judged # benign, with a comment saying why: either a race in PyMongo's own C diff --git a/pymongo/asynchronous/monitor.py b/pymongo/asynchronous/monitor.py index b7b1e01ff9..ae24680f8e 100644 --- a/pymongo/asynchronous/monitor.py +++ b/pymongo/asynchronous/monitor.py @@ -119,9 +119,9 @@ async def join(self, timeout: float | None = None) -> None: async def _wake_and_join_executor(self) -> None: # Wait briefly for the executor to stop before resetting the pool, so - # we don't race with a connection it has checked out. The timeout is a - # backstop: if the executor is still running, the reset closes its - # socket once the connection is checked in. + # we don't race with a connection it has checked out. The timeout only + # bounds the wait: if the executor is still running, the reset closes + # its socket once the connection is checked in. self._executor.wake() await self._executor.join(_EXECUTOR_JOIN_TIMEOUT) diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index 8d1b53600c..034e3bc430 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -30,7 +30,7 @@ _ServerSelectionTelemetry, log_server_selection_succeeded, ) -from pymongo.asynchronous.monitor import MonitorBase, SrvMonitor +from pymongo.asynchronous.monitor import _EXECUTOR_JOIN_TIMEOUT, MonitorBase, SrvMonitor from pymongo.asynchronous.pool import Pool from pymongo.asynchronous.server import Server from pymongo.errors import ( @@ -728,7 +728,7 @@ async def cleanup_monitors(self) -> None: pass for t in tasks: try: - await t.join(1) + await t.join(_EXECUTOR_JOIN_TIMEOUT) except Exception: # noqa: S110 # One monitor failing to stop must not block the rest. pass diff --git a/pymongo/synchronous/monitor.py b/pymongo/synchronous/monitor.py index cc7c7afecd..d886131685 100644 --- a/pymongo/synchronous/monitor.py +++ b/pymongo/synchronous/monitor.py @@ -119,9 +119,9 @@ def join(self, timeout: float | None = None) -> None: def _wake_and_join_executor(self) -> None: # Wait briefly for the executor to stop before resetting the pool, so - # we don't race with a connection it has checked out. The timeout is a - # backstop: if the executor is still running, the reset closes its - # socket once the connection is checked in. + # we don't race with a connection it has checked out. The timeout only + # bounds the wait: if the executor is still running, the reset closes + # its socket once the connection is checked in. self._executor.wake() self._executor.join(_EXECUTOR_JOIN_TIMEOUT) diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index 470312a1e1..94310af0cb 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -52,7 +52,7 @@ secondary_server_selector, writable_server_selector, ) -from pymongo.synchronous.monitor import MonitorBase, SrvMonitor +from pymongo.synchronous.monitor import _EXECUTOR_JOIN_TIMEOUT, MonitorBase, SrvMonitor from pymongo.synchronous.pool import Pool from pymongo.synchronous.server import Server from pymongo.topology_description import ( @@ -726,7 +726,7 @@ def cleanup_monitors(self) -> None: pass for t in tasks: try: - t.join(1) + t.join(_EXECUTOR_JOIN_TIMEOUT) except Exception: # noqa: S110 # One monitor failing to stop must not block the rest. pass From 9e1e6041e3ce0f31de95b1d24b786c2f2872485c Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 08:53:28 -0600 Subject: [PATCH 07/26] Clean up dash separators and via in PR prose --- .evergreen/scripts/setup_sanitizer.py | 18 +++++++++--------- .evergreen/tsan-suppressions.txt | 2 +- CONTRIBUTING.md | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.evergreen/scripts/setup_sanitizer.py b/.evergreen/scripts/setup_sanitizer.py index 32db84bf8b..524d89bcf4 100644 --- a/.evergreen/scripts/setup_sanitizer.py +++ b/.evergreen/scripts/setup_sanitizer.py @@ -19,9 +19,9 @@ # bson/_cbsonmodule.c (_get_buffer/_prepare_input_buffer), the wire-message # builders in pymongo/_cmessagemodule.c (_op_msg, _batched_op_msg, # _encode_batched_write_command), the hostile-input and boundary tests -# driving the decoder and builders directly, and — via the concurrency -# classes added in PYTHON-6168 — concurrent zero-copy RawBSONDocument reads -# and batched message building on free-threaded CPython. +# driving the decoder and builders directly, and the PYTHON-6168 +# concurrency classes: concurrent zero-copy RawBSONDocument reads and +# batched message building on free-threaded CPython. SANITIZER_FILES = [ "test/test_bson.py", "test/test_message.py", @@ -170,9 +170,9 @@ def configure_env(sub_test_name: str, test_args: str) -> str: ext.unlink() # The extensions must be compiled by a clang whose version matches the # one that built the interpreter (see find_matching_clang), so resolve - # the compiler by version match and fail setup — with the probed - # inventory in the message — when the host has no match, rather than - # failing deep in the run with a confusing ImportError. + # the compiler by version match and, when the host has no match, fail + # setup with the probed inventory in the message rather than failing + # deep in the run with a confusing ImportError. interpreter_version = interpreter_clang_version(python) if interpreter_version is None: # Cannot probe the interpreter: fall back to the system clang and @@ -197,8 +197,8 @@ def configure_env(sub_test_name: str, test_args: str) -> str: print( f"sanitizer setup: no clang {interpreter_version} on this host; " f"extensions compile with {compiler} (clang {compiler_version}), " - "the newest clang older than the interpreter's build compiler " - "— a newer compiler emits references the interpreter's runtime " + "the newest clang older than the interpreter's build compiler. " + "A newer compiler emits references the interpreter's runtime " "does not export. Upgrade the toolchain image to ship the " "interpreter's compiler (PYTHON-6067)." ) @@ -232,7 +232,7 @@ def configure_env(sub_test_name: str, test_args: str) -> str: else: # -fno-sanitize=function: the toolchain interpreter's UBSan runtime # predates the image's clang, whose function check references a - # handler the runtime does not export — the extensions fail to + # handler the runtime does not export, so the extensions fail to # import with undefined symbol: __ubsan_handle_function_type_mismatch # (PYTHON-6167). write_env( diff --git a/.evergreen/tsan-suppressions.txt b/.evergreen/tsan-suppressions.txt index e5afc1949e..ba838d3ef6 100644 --- a/.evergreen/tsan-suppressions.txt +++ b/.evergreen/tsan-suppressions.txt @@ -1,7 +1,7 @@ # PyMongo-specific ThreadSanitizer suppressions. # # The TSan task (PYTHON-6168) passes this file as TSan's single -# suppressions= path via TSAN_OPTIONS in .evergreen/scripts/setup_sanitizer.py. +# suppressions= path through TSAN_OPTIONS in .evergreen/scripts/setup_sanitizer.py. # # Add an entry below only for a race that has been investigated and judged # benign, with a comment saying why: either a race in PyMongo's own C diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index be924c01a8..a55cb1dd15 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -523,7 +523,7 @@ The `sanitizer tsan` suite (PYTHON-6168) builds the C extensions with free-threaded CPython (`TSAN_PYTHON` in `.evergreen/scripts/utils.py`) and runs the same files as the ASan suite with ThreadSanitizer set to halt on error (suppressions in `.evergreen/tsan-suppressions.txt`). It runs on PRs -via the same "Sanitizer RHEL8" variant. To run it on a Linux host with the +with the same "Sanitizer RHEL8" variant. To run it on a Linux host with the toolchain: just run-server From 335e28f48472ea84b12f5037ad2b4f601bb17b4c Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 09:37:53 -0600 Subject: [PATCH 08/26] Pin the sanitizer compiler and run on rhel87-large --- .evergreen/generated_configs/variants.yml | 2 +- .evergreen/scripts/generate_config.py | 10 +- .evergreen/scripts/setup_sanitizer.py | 165 +++------------------ .evergreen/scripts/test_generate_config.py | 9 +- 4 files changed, 35 insertions(+), 151 deletions(-) diff --git a/.evergreen/generated_configs/variants.yml b/.evergreen/generated_configs/variants.yml index 5e1094ac9e..defb5a8023 100644 --- a/.evergreen/generated_configs/variants.yml +++ b/.evergreen/generated_configs/variants.yml @@ -386,7 +386,7 @@ buildvariants: - name: .sanitizer display_name: Sanitizer RHEL8 run_on: - - rhel8.10-large + - rhel87-large expansions: VERSION: "9.0" tags: [pr] diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index 98923179bf..57dd2a4aca 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -409,16 +409,18 @@ def create_fuzz_variants(): def create_sanitizer_variants() -> list[BuildVariant]: # Sanitizer checks on every PR (PYTHON-6048, PYTHON-6168): ASan/UBSan # and TSan tasks. The rhel8 toolchain provides the instrumented - # CPythons (utils.SANITIZER_PYTHON, utils.TSAN_PYTHON), and the - # large distro gives ASan's shadow memory and redzones room for the - # ~6GiB test_encode_size_limit allocation, so no test is skipped. + # CPythons (utils.SANITIZER_PYTHON, utils.TSAN_PYTHON). The host must + # carry the llvm-toolset-14 module clang that built those interpreters + # (setup_sanitizer.CLANG): the rhel8.7 pool has it. It is also a large + # distro, giving ASan's shadow memory and redzones room for the ~6GiB + # test_encode_size_limit allocation, so no test is skipped. host = DEFAULT_HOST return [ create_variant( [".sanitizer"], get_variant_name("Sanitizer", host), host=host, - run_on="rhel8.10-large", + run_on="rhel87-large", version=MAX_VERSION, tags=["pr"], ) diff --git a/.evergreen/scripts/setup_sanitizer.py b/.evergreen/scripts/setup_sanitizer.py index 524d89bcf4..2c7ca958a1 100644 --- a/.evergreen/scripts/setup_sanitizer.py +++ b/.evergreen/scripts/setup_sanitizer.py @@ -7,7 +7,6 @@ from __future__ import annotations -import re import shutil import subprocess from pathlib import Path @@ -30,6 +29,17 @@ "test/test_client.py", ] +# The compiler that built the toolchain's sanitizer interpreters. +# build-cpython-linux.sh exports CC=clang on the toolchain's rhel87-large +# build host, where PATH clang is the RHEL 8 AppStream llvm-toolset module +# (clang 14.0.6, as the interpreters report in platform.python_compiler()). +# The rhel87-large runtime image ships the same clang-14.0.6 rpm, installed +# into the normal filesystem. Instrumented extensions must be compiled by +# the same version: a newer clang emits references the interpreter's +# runtime does not export (undefined symbol at import). +CLANG = "/usr/bin/clang" +CLANGXX = "/usr/bin/clang++" + def tsan_interface_exported(python_binary: str) -> bool: """Check the interpreter's dynamic symbols for the TSan interface. @@ -51,103 +61,6 @@ def tsan_interface_exported(python_binary: str) -> bool: return "__tsan_func_entry" in out -def _first_line(args: list[str]) -> str | None: - """Return the first stdout line of a command, or None if it cannot run.""" - try: - out = subprocess.run( # noqa: S603 - args, - capture_output=True, - text=True, - check=True, - ).stdout - except (OSError, subprocess.SubprocessError): - return None - return out.strip().splitlines()[0] if out.strip() else None - - -def interpreter_clang_version(python_binary: str) -> str | None: - """Return the clang version that built the interpreter, if discoverable. - - platform.python_compiler() reports e.g. "Clang 14.0.6 (Red Hat - 14.0.6-1.module+el8.7.0+15816+ec020e8f)" for the toolchain interpreters. - """ - out = _first_line([python_binary, "-c", "import platform; print(platform.python_compiler())"]) - match = re.search(r"Clang (\d+(?:\.\d+)+)", out or "") - return match.group(1) if match else None - - -def compiler_clang_version(compiler: str) -> str | None: - """Return the clang version of the compiler, if discoverable.""" - match = re.search(r"clang version (\d+(?:\.\d+)+)", _first_line([compiler, "--version"]) or "") - return match.group(1) if match else None - - -def clang_candidates() -> list[str]: - """Return the clang compilers the image may carry. - - The hosts carry several: the mongodbtoolchain's versioned installs and - the system clang, whose /usr/bin one (clang 22.1.8) is far newer than - the module clang 14.0.6 that built the instrumented interpreters. - """ - root = Path("/") - return sorted( - [ - str(path) - for pattern in ( - "opt/mongodbtoolchain/*/bin/clang", - "usr/lib64/llvm*/bin/clang", - "usr/bin/clang-*", - ) - for path in root.glob(pattern) - ] - + ["/usr/bin/clang", "/usr/local/bin/clang"] - ) - - -def find_matching_clang(version: str) -> tuple[str, str, bool]: - """Return a clang compatible with the interpreter's build compiler. - - Instrumented extensions resolve the sanitizer's interface symbols - against the interpreter's runtime; a NEWER compiler emits references - the runtime does not export (undefined symbol at import: __tsan_memcpy - under TSan with a newer clang's memcall lowering, - __ubsan_handle_function_type_mismatch under UBSan's function check). - The reverse direction is the supported one: the runtime's - compiled-code interface is forward-compatible, so when the exact - compiler is absent the newest clang OLDER than the interpreter's is a - usable fallback. Returns (path, clang version, exact match). - """ - probed = [] - fallback: tuple[str, str] | None = None - required = _version_key(version) - for candidate in clang_candidates(): - candidate_version = compiler_clang_version(candidate) - if candidate_version is None: - continue - probed.append(f"{candidate} (clang {candidate_version})") - if candidate_version == version: - return candidate, candidate_version, True - candidate_key = _version_key(candidate_version) - if candidate_key < required and ( - fallback is None or candidate_key > _version_key(fallback[1]) - ): - fallback = (candidate, candidate_version) - if fallback is not None: - return *fallback, False - raise RuntimeError( - f"No clang compatible with the interpreter's build compiler " - f"(clang {version}) was found on this host. Probed: " - + ("; ".join(probed) if probed else "none") - + ". The toolchain image must provide the clang that built its " - "instrumented interpreters (PYTHON-6067)." - ) - - -def _version_key(version: str) -> tuple[int, ...]: - """Return a numeric sort key for a dotted version string.""" - return tuple(int(part) for part in version.split(".")) - - def configure_env(sub_test_name: str, test_args: str) -> str: """Write the environment for a sanitizer test run. @@ -162,51 +75,20 @@ def configure_env(sub_test_name: str, test_args: str) -> str: f"Sanitizer interpreter not found at {python}; the task must run " "on a host with the sanitizer toolchain Python." ) + if not Path(CLANG).is_file(): + raise RuntimeError( + f"Compiler not found at {CLANG}: the llvm-toolset module clang " + "that built the toolchain's sanitizer interpreters. The task " + "image must provide it (PYTHON-6067)." + ) # Clear stale C artifacts: build_ext reuses them by mtime, and a # plain same-version CPython build shares the ABI tag. shutil.rmtree(ROOT / "build", ignore_errors=True) for pkg in ["bson", "pymongo"]: for ext in (ROOT / pkg).glob("*.so"): ext.unlink() - # The extensions must be compiled by a clang whose version matches the - # one that built the interpreter (see find_matching_clang), so resolve - # the compiler by version match and, when the host has no match, fail - # setup with the probed inventory in the message rather than failing - # deep in the run with a confusing ImportError. - interpreter_version = interpreter_clang_version(python) - if interpreter_version is None: - # Cannot probe the interpreter: fall back to the system clang and - # say so; a mismatch would surface at import time as before. - compiler = "/usr/bin/clang" - compiler_version = compiler_clang_version(compiler) - print( - "sanitizer setup: the interpreter's clang version is not " - f"discoverable; falling back to the extension compiler {compiler} " - f"(clang {compiler_version}); the compiler/interpreter match is " - "unchecked." - ) - else: - compiler, compiler_version, exact = find_matching_clang(interpreter_version) - if exact: - print( - f"sanitizer setup: extensions compile with {compiler} (clang " - f"{compiler_version}); the interpreter was built with clang " - f"{interpreter_version}." - ) - else: - print( - f"sanitizer setup: no clang {interpreter_version} on this host; " - f"extensions compile with {compiler} (clang {compiler_version}), " - "the newest clang older than the interpreter's build compiler. " - "A newer compiler emits references the interpreter's runtime " - "does not export. Upgrade the toolchain image to ship the " - "interpreter's compiler (PYTHON-6067)." - ) - compiler_path = Path(compiler) - write_env("CC", compiler) - write_env( - "CXX", str(compiler_path.with_name(compiler_path.name.replace("clang", "clang++", 1))) - ) + write_env("CC", CLANG) + write_env("CXX", CLANGXX) write_env("UV_PYTHON", python) write_env("PYMONGO_C_EXT_MUST_BUILD") # The sanitizer flags live in environment variables, which are not @@ -230,11 +112,10 @@ def configure_env(sub_test_name: str, test_args: str) -> str: f"halt_on_error=1:handle_segv=0:suppressions={suppressions}", ) else: - # -fno-sanitize=function: the toolchain interpreter's UBSan runtime - # predates the image's clang, whose function check references a - # handler the runtime does not export, so the extensions fail to - # import with undefined symbol: __ubsan_handle_function_type_mismatch - # (PYTHON-6167). + # -fno-sanitize=function: parity with main (PYTHON-6167). With the + # compiler pinned to the interpreter's build compiler the function + # check resolves fine, and the flag costs nothing; it only matters + # if the pinned compiler and the interpreter ever drift. write_env( "CFLAGS", "-fsanitize=address,undefined -fno-sanitize=function -fno-omit-frame-pointer -g -O1", diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 163cab11ec..348a8fc02f 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -759,9 +759,10 @@ def test_sanitizer_task_wiring(): """PYTHON-6048/PYTHON-6168: pr-tagged sanitizer tasks, selected by one variant. Each task is selected by exactly one variant that pins MAX_VERSION and - runs on a large host for ASan's memory headroom. VERSION stays off the - tasks so they are exempt from the pr COVERAGE rule (coverage under - sanitizers is not useful). + runs on a rhel8.7 large host, which carries the llvm-toolset-14 module + clang that built the interpreters and has the memory headroom ASan + needs. VERSION stays off the tasks so they are exempt from the pr + COVERAGE rule (coverage under sanitizers is not useful). """ tasks = [task for task in all_tasks() if "sanitizer" in (task.tags or [])] assert {task.name for task in tasks} == { @@ -781,5 +782,5 @@ def test_sanitizer_task_wiring(): assert "VERSION" not in vars_ variants = [v for v in all_variants() if variant_selects(v, task)] assert len(variants) == 1 - assert variants[0].run_on == ["rhel8.10-large"] + assert variants[0].run_on == ["rhel87-large"] assert (variants[0].expansions or {}).get("VERSION") == generate_config_utils.MAX_VERSION From daf8f913e83e3288079e014671ad6a612a6fcb9d Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 09:41:50 -0600 Subject: [PATCH 09/26] Trim comment prose --- .evergreen/scripts/generate_config.py | 15 +++------ .evergreen/scripts/setup_sanitizer.py | 45 +++++++-------------------- .evergreen/scripts/utils.py | 5 ++- .evergreen/tsan-suppressions.txt | 18 ++++------- pymongo/asynchronous/monitor.py | 6 ++-- pymongo/asynchronous/topology.py | 2 -- pymongo/synchronous/monitor.py | 6 ++-- pymongo/synchronous/topology.py | 2 -- test/asynchronous/test_monitor.py | 4 +-- test/test_monitor.py | 4 +-- test/test_raw_bson_shared.py | 7 +---- 11 files changed, 32 insertions(+), 82 deletions(-) diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index 57dd2a4aca..207dd53056 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -407,13 +407,9 @@ def create_fuzz_variants(): def create_sanitizer_variants() -> list[BuildVariant]: - # Sanitizer checks on every PR (PYTHON-6048, PYTHON-6168): ASan/UBSan - # and TSan tasks. The rhel8 toolchain provides the instrumented - # CPythons (utils.SANITIZER_PYTHON, utils.TSAN_PYTHON). The host must - # carry the llvm-toolset-14 module clang that built those interpreters - # (setup_sanitizer.CLANG): the rhel8.7 pool has it. It is also a large - # distro, giving ASan's shadow memory and redzones room for the ~6GiB - # test_encode_size_limit allocation, so no test is skipped. + # Sanitizer checks on every PR (PYTHON-6048, PYTHON-6168). The host needs + # the instrumented interpreters, the clang that built them + # (setup_sanitizer.CLANG), and memory for ASan's ~6GiB worst case. host = DEFAULT_HOST return [ create_variant( @@ -751,9 +747,8 @@ def create_fuzz_tasks(): def create_sanitizer_tasks(): - # VERSION comes from the variant: a task-level VERSION would trip the - # pr-tasks-run-coverage rule, and coverage under sanitizers is not - # useful. + # VERSION comes from the variant: a task-level VERSION trips the pr + # coverage rule. tags = ["sanitizer", "pr"] expansions = dict(AUTH="noauth", SSL="nossl", TOPOLOGY="standalone") server_func = FunctionCall(func="run server", vars=expansions) diff --git a/.evergreen/scripts/setup_sanitizer.py b/.evergreen/scripts/setup_sanitizer.py index 2c7ca958a1..8b3f43ba9d 100644 --- a/.evergreen/scripts/setup_sanitizer.py +++ b/.evergreen/scripts/setup_sanitizer.py @@ -13,14 +13,8 @@ from utils import PLATFORM, ROOT, SANITIZER_PYTHON, TSAN_PYTHON, write_env -# The test files run under the sanitizer tasks (PYTHON-6048, PYTHON-6168, -# PYTHON-6285). They exercise the buffer-protocol acquisition path in -# bson/_cbsonmodule.c (_get_buffer/_prepare_input_buffer), the wire-message -# builders in pymongo/_cmessagemodule.c (_op_msg, _batched_op_msg, -# _encode_batched_write_command), the hostile-input and boundary tests -# driving the decoder and builders directly, and the PYTHON-6168 -# concurrency classes: concurrent zero-copy RawBSONDocument reads and -# batched message building on free-threaded CPython. +# Run under the sanitizer tasks (PYTHON-6048, PYTHON-6168): exercise the C +# extensions' buffer, message-building, and concurrency entry points. SANITIZER_FILES = [ "test/test_bson.py", "test/test_message.py", @@ -29,14 +23,9 @@ "test/test_client.py", ] -# The compiler that built the toolchain's sanitizer interpreters. -# build-cpython-linux.sh exports CC=clang on the toolchain's rhel87-large -# build host, where PATH clang is the RHEL 8 AppStream llvm-toolset module -# (clang 14.0.6, as the interpreters report in platform.python_compiler()). -# The rhel87-large runtime image ships the same clang-14.0.6 rpm, installed -# into the normal filesystem. Instrumented extensions must be compiled by -# the same version: a newer clang emits references the interpreter's -# runtime does not export (undefined symbol at import). +# The clang (14.0.6) that built the toolchain's sanitizer interpreters on the +# rhel87 build host. Extensions must use the same version: a newer clang +# emits references the interpreter's runtime does not export. CLANG = "/usr/bin/clang" CLANGXX = "/usr/bin/clang++" @@ -81,8 +70,7 @@ def configure_env(sub_test_name: str, test_args: str) -> str: "that built the toolchain's sanitizer interpreters. The task " "image must provide it (PYTHON-6067)." ) - # Clear stale C artifacts: build_ext reuses them by mtime, and a - # plain same-version CPython build shares the ABI tag. + # Clear stale artifacts: build_ext reuses them by mtime (same ABI tag). shutil.rmtree(ROOT / "build", ignore_errors=True) for pkg in ["bson", "pymongo"]: for ext in (ROOT / pkg).glob("*.so"): @@ -91,15 +79,12 @@ def configure_env(sub_test_name: str, test_args: str) -> str: write_env("CXX", CLANGXX) write_env("UV_PYTHON", python) write_env("PYMONGO_C_EXT_MUST_BUILD") - # The sanitizer flags live in environment variables, which are not - # part of uv's wheel cache key: a cached wheel built without them - # would load uninstrumented extensions and silently void the run. + # Env-var flags sit outside uv's cache key; skip the cache so wheels + # rebuild instrumented. write_env("UV_NO_CACHE", "1") if tsan: write_env("CFLAGS", "-fsanitize=thread -fno-omit-frame-pointer -g -O1") write_env("LDFLAGS", "-fsanitize=thread") - # The instrumented interpreter must also export the runtime - # interface the extensions resolve against. if not tsan_interface_exported(python): raise RuntimeError( "The TSan interpreter does not export the TSan interface " @@ -112,10 +97,7 @@ def configure_env(sub_test_name: str, test_args: str) -> str: f"halt_on_error=1:handle_segv=0:suppressions={suppressions}", ) else: - # -fno-sanitize=function: parity with main (PYTHON-6167). With the - # compiler pinned to the interpreter's build compiler the function - # check resolves fine, and the flag costs nothing; it only matters - # if the pinned compiler and the interpreter ever drift. + # -fno-sanitize=function: guard against compiler drift (PYTHON-6167). write_env( "CFLAGS", "-fsanitize=address,undefined -fno-sanitize=function -fno-omit-frame-pointer -g -O1", @@ -125,10 +107,7 @@ def configure_env(sub_test_name: str, test_args: str) -> str: write_env("ASAN_OPTIONS", "detect_leaks=0") # UBSan only warns by default; make undefined behavior fail the task. write_env("UBSAN_OPTIONS", "halt_on_error=1:print_stacktrace=1") - # The toolchain interpreter self-initializes the sanitizer runtimes, - # so no LD_PRELOAD: preloading a mismatched runtime would mix two - # sanitizers in one process, and for TSan report false races inside - # CPython's own free-threading internals. - # -s: with halt_on_error=1, a sanitizer failure exits the interpreter - # before pytest replays captured stderr, losing the report and trace. + # No LD_PRELOAD: the interpreter self-initializes its runtimes, and a + # mismatched preloaded runtime mixes sanitizers in one process. + # -s: with halt_on_error=1, a sanitizer failure exits before pytest replays captured stderr. return "-s " + " ".join(SANITIZER_FILES) + " " + test_args diff --git a/.evergreen/scripts/utils.py b/.evergreen/scripts/utils.py index 6b1ce4e305..8561bfde5a 100644 --- a/.evergreen/scripts/utils.py +++ b/.evergreen/scripts/utils.py @@ -96,9 +96,8 @@ class Distro: # (PYTHON-6048), built by mongo-python-toolchain (PYTHON-6067). Linux only. SANITIZER_PYTHON = "/opt/python/3.14-asan-ubsan/bin/python3" -# The TSan-instrumented, free-threaded toolchain CPython used by the TSan -# sanitizer task (PYTHON-6168), built by mongo-python-toolchain -# (PYTHON-6067). Linux only. +# The TSan-instrumented, free-threaded CPython for the TSan task +# (PYTHON-6168). Linux only. TSAN_PYTHON = "/opt/python/3.14t-tsan/bin/python3" # Tests that do not use run-mongodb directly. diff --git a/.evergreen/tsan-suppressions.txt b/.evergreen/tsan-suppressions.txt index ba838d3ef6..632df008de 100644 --- a/.evergreen/tsan-suppressions.txt +++ b/.evergreen/tsan-suppressions.txt @@ -1,18 +1,12 @@ # PyMongo-specific ThreadSanitizer suppressions. # -# The TSan task (PYTHON-6168) passes this file as TSan's single -# suppressions= path through TSAN_OPTIONS in .evergreen/scripts/setup_sanitizer.py. -# -# Add an entry below only for a race that has been investigated and judged -# benign, with a comment saying why: either a race in PyMongo's own C -# extensions, or a CPython-internal race (both stacks within CPython) that -# the toolchain interpreter's own suppression set does not yet cover. +# Add an entry only for a race judged benign after investigation, with a +# comment saying why: a PyMongo C-extension race, or a CPython-internal race +# the toolchain's own suppressions do not cover. # # Reference: https://github.com/google/sanitizers/wiki/ThreadSanitizerSuppressions -# CPython-internal: under free-threading the GC's delete_garbage path -# (memory_clear) and a worker thread's deferred refcount merge -# (memory_dealloc) can both enter _memory_release for the same -# memoryview. Both stacks are entirely within CPython; pymongo only -# creates and releases the memoryviews concurrently. +# CPython-internal: under free-threading the GC path (memory_clear) and a +# worker's deferred refcount merge (memory_dealloc) can both enter +# _memory_release for the same memoryview; both stacks are within CPython. race_top:_memory_release diff --git a/pymongo/asynchronous/monitor.py b/pymongo/asynchronous/monitor.py index ae24680f8e..76e9f8e654 100644 --- a/pymongo/asynchronous/monitor.py +++ b/pymongo/asynchronous/monitor.py @@ -118,10 +118,8 @@ async def join(self, timeout: float | None = None) -> None: await self._executor.join(timeout) async def _wake_and_join_executor(self) -> None: - # Wait briefly for the executor to stop before resetting the pool, so - # we don't race with a connection it has checked out. The timeout only - # bounds the wait: if the executor is still running, the reset closes - # its socket once the connection is checked in. + # Join before resetting so we don't race a checked-out connection; a + # straggler's socket closes when the reset returns its connection. self._executor.wake() await self._executor.join(_EXECUTOR_JOIN_TIMEOUT) diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index 034e3bc430..86a10f4535 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -187,7 +187,6 @@ async def select_servers( else: server_timeout = server_selection_timeout - # Join any monitors closed under the topology lock. if self._monitor_tasks: await self.cleanup_monitors() @@ -536,7 +535,6 @@ async def close(self) -> None: self._opened = False self._closed = True - # Join the monitors we just closed, now that the lock is released. await self.cleanup_monitors() # Publish only after releasing the lock. diff --git a/pymongo/synchronous/monitor.py b/pymongo/synchronous/monitor.py index d886131685..9a70f37c88 100644 --- a/pymongo/synchronous/monitor.py +++ b/pymongo/synchronous/monitor.py @@ -118,10 +118,8 @@ def join(self, timeout: float | None = None) -> None: self._executor.join(timeout) def _wake_and_join_executor(self) -> None: - # Wait briefly for the executor to stop before resetting the pool, so - # we don't race with a connection it has checked out. The timeout only - # bounds the wait: if the executor is still running, the reset closes - # its socket once the connection is checked in. + # Join before resetting so we don't race a checked-out connection; a + # straggler's socket closes when the reset returns its connection. self._executor.wake() self._executor.join(_EXECUTOR_JOIN_TIMEOUT) diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index 94310af0cb..c167256941 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -187,7 +187,6 @@ def select_servers( else: server_timeout = server_selection_timeout - # Join any monitors closed under the topology lock. if self._monitor_tasks: self.cleanup_monitors() @@ -534,7 +533,6 @@ def close(self) -> None: self._opened = False self._closed = True - # Join the monitors we just closed, now that the lock is released. self.cleanup_monitors() # Publish only after releasing the lock. diff --git a/test/asynchronous/test_monitor.py b/test/asynchronous/test_monitor.py index ed85a0144f..a8906c7adb 100644 --- a/test/asynchronous/test_monitor.py +++ b/test/asynchronous/test_monitor.py @@ -131,7 +131,6 @@ def thread_alive(executor): client.close() - # close() drains the deferred-join queue after releasing the lock. self.assertEqual(client._topology._monitor_tasks, []) self.assertFalse(thread_alive(monitor._executor)) self.assertFalse(thread_alive(monitor._rtt_monitor._executor)) @@ -180,8 +179,7 @@ def __init__(self, delay: float) -> None: self._delay = delay async def join(self, timeout: float | None = None) -> None: - # Blocks with time.sleep on purpose: the sync mirror of this test - # needs the same delay, and unasync does not translate asyncio.sleep. + # time.sleep on purpose: synchro does not translate asyncio.sleep. self._sleep() def _sleep(self) -> None: diff --git a/test/test_monitor.py b/test/test_monitor.py index 36145b568e..21f795716b 100644 --- a/test/test_monitor.py +++ b/test/test_monitor.py @@ -127,7 +127,6 @@ def thread_alive(executor): client.close() - # close() drains the deferred-join queue after releasing the lock. self.assertEqual(client._topology._monitor_tasks, []) self.assertFalse(thread_alive(monitor._executor)) self.assertFalse(thread_alive(monitor._rtt_monitor._executor)) @@ -176,8 +175,7 @@ def __init__(self, delay: float) -> None: self._delay = delay def join(self, timeout: float | None = None) -> None: - # Blocks with time.sleep on purpose: the sync mirror of this test - # needs the same delay, and unasync does not translate asyncio.sleep. + # time.sleep on purpose: synchro does not translate asyncio.sleep. self._sleep() def _sleep(self) -> None: diff --git a/test/test_raw_bson_shared.py b/test/test_raw_bson_shared.py index 4cede89714..4b258a8692 100644 --- a/test/test_raw_bson_shared.py +++ b/test/test_raw_bson_shared.py @@ -349,8 +349,6 @@ def test_concurrent_reads_on_shared_document(self): doc_bytes = _make_shared_doc_bytes() shared_doc = RawBSONDocument(doc_bytes) - # Confirm we're actually exercising the zero-copy memoryview path, - # not accidentally testing a byte-copy fallback. big_check = shared_doc["big"] self.assertIsInstance(big_check.raw, memoryview) self.assertTrue(big_check.raw.readonly) @@ -374,8 +372,7 @@ def worker() -> None: small = shared_doc["small"] self.assertEqual(small["n"], 1) - # Re-encodes a view-backed subdocument while other - # threads may be reading the same underlying buffer. + # Re-encode while other threads still read the same buffer. reencoded = encode({"again": big}) self.assertIsInstance(reencoded, bytes) @@ -397,8 +394,6 @@ def worker() -> None: self.assertEqual(errors, []) def test_buffer_survives_after_source_bytes_are_dropped(self): - # Slice a bytearray, wrap it in a RawBSONDocument, then mutate and - # drop the original buffer to check for a dangling view. encoded = _make_shared_doc_bytes() for _ in range(50): buf = bytearray(encoded) + b"\x00" * 10 From 6f18a97471b131e9b15783f7754b9fb42b92e3c2 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 10:15:04 -0600 Subject: [PATCH 10/26] Load the toolchain's TSan suppressions --- .evergreen/scripts/setup_sanitizer.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.evergreen/scripts/setup_sanitizer.py b/.evergreen/scripts/setup_sanitizer.py index 8b3f43ba9d..2af2d6d637 100644 --- a/.evergreen/scripts/setup_sanitizer.py +++ b/.evergreen/scripts/setup_sanitizer.py @@ -92,9 +92,17 @@ def configure_env(sub_test_name: str, test_args: str) -> str: "its dynamic symbols). Rebuild the toolchain (PYTHON-6067)." ) suppressions = ROOT / ".evergreen" / "tsan-suppressions.txt" + # TSan takes one suppressions file: combine CPython's free-threading + # suppressions (shipped with the interpreter) with ours. + toolchain_suppressions = Path(TSAN_PYTHON).parent.parent / "suppressions_free_threading.txt" + combined = ROOT / ".evergreen" / "tsan-suppressions-combined.txt" + with combined.open("w", encoding="utf-8") as fid: + if toolchain_suppressions.is_file(): + fid.write(toolchain_suppressions.read_text(encoding="utf-8")) + fid.write(suppressions.read_text(encoding="utf-8")) write_env( "TSAN_OPTIONS", - f"halt_on_error=1:handle_segv=0:suppressions={suppressions}", + f"halt_on_error=1:handle_segv=0:suppressions={combined}", ) else: # -fno-sanitize=function: guard against compiler drift (PYTHON-6167). From 7a0a4eaff3f42ede9aca10133d4ec1ad14fb9f54 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 10:24:38 -0600 Subject: [PATCH 11/26] Defer monitor joins outside the topology lock --- pymongo/asynchronous/monitor.py | 13 +++++++++++++ pymongo/asynchronous/server.py | 10 ++++++++++ pymongo/asynchronous/topology.py | 26 +++++++++++++++----------- pymongo/periodic_executor.py | 4 +++- pymongo/synchronous/monitor.py | 13 +++++++++++++ pymongo/synchronous/server.py | 10 ++++++++++ pymongo/synchronous/topology.py | 26 +++++++++++++++----------- test/asynchronous/test_monitor.py | 5 ++++- test/test_monitor.py | 5 ++++- test/test_raw_bson_shared.py | 3 +++ 10 files changed, 90 insertions(+), 25 deletions(-) diff --git a/pymongo/asynchronous/monitor.py b/pymongo/asynchronous/monitor.py index 76e9f8e654..88f71a8604 100644 --- a/pymongo/asynchronous/monitor.py +++ b/pymongo/asynchronous/monitor.py @@ -102,6 +102,14 @@ def gc_safe_close(self) -> None: """GC safe close.""" self._executor.close() + def signal_close(self) -> None: + """Stop the executors without joining them. + + Joining blocks on on_change(), which needs the topology lock: call + close() with the lock released to join and reset the pool. + """ + self.gc_safe_close() + async def close(self) -> None: """Close and stop monitoring. @@ -170,6 +178,11 @@ def __init__( else: self._stream = not _is_faas() + def signal_close(self) -> None: + """Stop the heartbeat and RTT executors without joining them.""" + super().signal_close() + self._rtt_monitor.gc_safe_close() + def cancel_check(self) -> None: """Cancel any concurrent hello check. diff --git a/pymongo/asynchronous/server.py b/pymongo/asynchronous/server.py index 32138704ec..ccc55c5ef2 100644 --- a/pymongo/asynchronous/server.py +++ b/pymongo/asynchronous/server.py @@ -79,6 +79,16 @@ async def close(self) -> None: # interrupts the monitor close (PYTHON-6226). await self._pool.close() + async def signal_close(self) -> None: + """Stop the monitor and clear the pool without joining it. + + Joining blocks on on_change(), which needs the topology lock: the + topology defers close() to its unlocked cleanup phase. + """ + self._sdam.server_closed(self._description.address) + self._monitor.signal_close() + await self._pool.close() + def request_check(self) -> None: """Check the server's state soon.""" self._monitor.request_check() diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index 86a10f4535..301c92c9ef 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -30,7 +30,7 @@ _ServerSelectionTelemetry, log_server_selection_succeeded, ) -from pymongo.asynchronous.monitor import _EXECUTOR_JOIN_TIMEOUT, MonitorBase, SrvMonitor +from pymongo.asynchronous.monitor import MonitorBase, SrvMonitor from pymongo.asynchronous.pool import Pool from pymongo.asynchronous.server import Server from pymongo.errors import ( @@ -518,7 +518,10 @@ async def close(self) -> None: async with self._lock: old_td = self._description for server in self._servers.values(): - await server.close() + # Signal the executors; joining them here would block on + # on_change(), which needs this lock. cleanup_monitors below + # joins and resets with the lock released. + await server.signal_close() self._monitor_tasks.append(server._monitor) # Mark all servers Unknown. @@ -529,7 +532,7 @@ async def close(self) -> None: # Stop SRV polling thread. if self._srv_monitor: - await self._srv_monitor.close() + self._srv_monitor.signal_close() self._monitor_tasks.append(self._srv_monitor) self._opened = False @@ -708,25 +711,26 @@ async def _update_servers(self) -> None: # 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). + await server.signal_close() self._monitor_tasks.append(server._monitor) self._servers.pop(address) - await server.close() async def cleanup_monitors(self) -> None: - """Join monitors closed earlier while the topology lock was held. + """Close monitors signaled earlier while the topology lock was held. - Always call this with the lock released: a monitor being joined may - itself be blocked acquiring the lock. + Close joins each monitor and resets its pool. Always call this with + the lock released: a monitor being joined may itself be blocked + acquiring the lock. """ - tasks = [] + monitors = [] try: while self._monitor_tasks: - tasks.append(self._monitor_tasks.pop()) + monitors.append(self._monitor_tasks.pop()) except IndexError: pass - for t in tasks: + for monitor in monitors: try: - await t.join(_EXECUTOR_JOIN_TIMEOUT) + await monitor.close() except Exception: # noqa: S110 # One monitor failing to stop must not block the rest. pass diff --git a/pymongo/periodic_executor.py b/pymongo/periodic_executor.py index 41f9f23178..147c4dc4ef 100644 --- a/pymongo/periodic_executor.py +++ b/pymongo/periodic_executor.py @@ -88,7 +88,9 @@ def close(self, dummy: Any = None) -> None: self._task.cancel() async def join(self, timeout: float | None = None) -> None: - if self._task is not None: + # Waiting on our own task cannot complete: returning lets the caller + # finish its shutdown and the executor see the stop signal. + if self._task is not None and self._task is not asyncio.current_task(): await asyncio.wait([self._task], timeout=timeout) # type-ignore: [arg-type] def wake(self) -> None: diff --git a/pymongo/synchronous/monitor.py b/pymongo/synchronous/monitor.py index 9a70f37c88..d3a29237b9 100644 --- a/pymongo/synchronous/monitor.py +++ b/pymongo/synchronous/monitor.py @@ -102,6 +102,14 @@ def gc_safe_close(self) -> None: """GC safe close.""" self._executor.close() + def signal_close(self) -> None: + """Stop the executors without joining them. + + Joining blocks on on_change(), which needs the topology lock: call + close() with the lock released to join and reset the pool. + """ + self.gc_safe_close() + def close(self) -> None: """Close and stop monitoring. @@ -170,6 +178,11 @@ def __init__( else: self._stream = not _is_faas() + def signal_close(self) -> None: + """Stop the heartbeat and RTT executors without joining them.""" + super().signal_close() + self._rtt_monitor.gc_safe_close() + def cancel_check(self) -> None: """Cancel any concurrent hello check. diff --git a/pymongo/synchronous/server.py b/pymongo/synchronous/server.py index 803cb0093c..efa4b716ed 100644 --- a/pymongo/synchronous/server.py +++ b/pymongo/synchronous/server.py @@ -79,6 +79,16 @@ def close(self) -> None: # interrupts the monitor close (PYTHON-6226). self._pool.close() + def signal_close(self) -> None: + """Stop the monitor and clear the pool without joining it. + + Joining blocks on on_change(), which needs the topology lock: the + topology defers close() to its unlocked cleanup phase. + """ + self._sdam.server_closed(self._description.address) + self._monitor.signal_close() + self._pool.close() + def request_check(self) -> None: """Check the server's state soon.""" self._monitor.request_check() diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index c167256941..1ee7f215f9 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -52,7 +52,7 @@ secondary_server_selector, writable_server_selector, ) -from pymongo.synchronous.monitor import _EXECUTOR_JOIN_TIMEOUT, MonitorBase, SrvMonitor +from pymongo.synchronous.monitor import MonitorBase, SrvMonitor from pymongo.synchronous.pool import Pool from pymongo.synchronous.server import Server from pymongo.topology_description import ( @@ -516,7 +516,10 @@ def close(self) -> None: with self._lock: old_td = self._description for server in self._servers.values(): - server.close() + # Signal the executors; joining them here would block on + # on_change(), which needs this lock. cleanup_monitors below + # joins and resets with the lock released. + server.signal_close() self._monitor_tasks.append(server._monitor) # Mark all servers Unknown. @@ -527,7 +530,7 @@ def close(self) -> None: # Stop SRV polling thread. if self._srv_monitor: - self._srv_monitor.close() + self._srv_monitor.signal_close() self._monitor_tasks.append(self._srv_monitor) self._opened = False @@ -706,25 +709,26 @@ def _update_servers(self) -> None: # 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). + server.signal_close() self._monitor_tasks.append(server._monitor) self._servers.pop(address) - server.close() def cleanup_monitors(self) -> None: - """Join monitors closed earlier while the topology lock was held. + """Close monitors signaled earlier while the topology lock was held. - Always call this with the lock released: a monitor being joined may - itself be blocked acquiring the lock. + Close joins each monitor and resets its pool. Always call this with + the lock released: a monitor being joined may itself be blocked + acquiring the lock. """ - tasks = [] + monitors = [] try: while self._monitor_tasks: - tasks.append(self._monitor_tasks.pop()) + monitors.append(self._monitor_tasks.pop()) except IndexError: pass - for t in tasks: + for monitor in monitors: try: - t.join(_EXECUTOR_JOIN_TIMEOUT) + monitor.close() except Exception: # noqa: S110 # One monitor failing to stop must not block the rest. pass diff --git a/test/asynchronous/test_monitor.py b/test/asynchronous/test_monitor.py index a8906c7adb..ec3513a683 100644 --- a/test/asynchronous/test_monitor.py +++ b/test/asynchronous/test_monitor.py @@ -149,7 +149,10 @@ async def test_close_stops_monitor_task(self): self.assertEqual(client._topology._monitor_tasks, []) self.assertTrue(monitor._executor._task.done()) - self.assertTrue(monitor._rtt_monitor._executor._task.done()) + # The RTT executor may never start (polling RTT in FaaS environments). + rtt_task = monitor._rtt_monitor._executor._task + if rtt_task is not None: + self.assertTrue(rtt_task.done()) @async_client_context.require_sync def test_no_thread_start_runtime_err_on_shutdown(self): diff --git a/test/test_monitor.py b/test/test_monitor.py index 21f795716b..8e553da514 100644 --- a/test/test_monitor.py +++ b/test/test_monitor.py @@ -145,7 +145,10 @@ def test_close_stops_monitor_task(self): self.assertEqual(client._topology._monitor_tasks, []) self.assertTrue(monitor._executor._task.done()) - self.assertTrue(monitor._rtt_monitor._executor._task.done()) + # The RTT executor may never start (polling RTT in FaaS environments). + rtt_task = monitor._rtt_monitor._executor._task + if rtt_task is not None: + self.assertTrue(rtt_task.done()) @client_context.require_sync def test_no_thread_start_runtime_err_on_shutdown(self): diff --git a/test/test_raw_bson_shared.py b/test/test_raw_bson_shared.py index 4b258a8692..8f38506d1b 100644 --- a/test/test_raw_bson_shared.py +++ b/test/test_raw_bson_shared.py @@ -409,6 +409,9 @@ def test_buffer_survives_after_source_bytes_are_dropped(self): del buf gc.collect() self.assertEqual(copied["small"]["n"], 1) + # The still-lazy views must decode from their kept buffer copies. + self.assertEqual(copied["big"]["payload"], BIG_PAYLOAD) + self.assertEqual([doc["idx"] for doc in copied["arr"]], [0, 1, 2]) class _FakeBulkWriteContext: From fef42a5d991a22323e412e06c3e327fbcb0bbdd4 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 10:27:56 -0600 Subject: [PATCH 12/26] Add a self-join regression test --- test/asynchronous/test_periodic_executor.py | 19 +++++++++++++++++++ test/test_periodic_executor.py | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index ff70125334..8b65939491 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -180,6 +180,25 @@ async def target(): await executor.join(timeout=2) self.assertEqual(runs, 2, "executor did not restart after a self-close") + async def test_join_from_own_task_does_not_stall(self): + # A heartbeat removing its own server joins its own task; waiting on + # the current task cannot complete and would stall for the full + # timeout (PYTHON-6168). + elapsed = None + + async def target(): + nonlocal elapsed + start = time.monotonic() + await executor.join(timeout=2) + elapsed = time.monotonic() - start + return False + + executor = self._make_executor(target=target) + executor.open() + await executor.join(timeout=2) + assert elapsed is not None + self.assertLess(elapsed, 1.0, "join() from the executor's own task stalled") + async def test_close_from_thread_without_event_loop(self): # close() can run off the event loop as a weakref callback, where # asyncio.current_task() raises RuntimeError. diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index 10306fc06a..1fdd084b86 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -179,6 +179,25 @@ def target(): executor.join(timeout=2) self.assertEqual(runs, 2, "executor did not restart after a self-close") + def test_join_from_own_task_does_not_stall(self): + # A heartbeat removing its own server joins its own task; waiting on + # the current task cannot complete and would stall for the full + # timeout (PYTHON-6168). + elapsed = None + + def target(): + nonlocal elapsed + start = time.monotonic() + executor.join(timeout=2) + elapsed = time.monotonic() - start + return False + + executor = self._make_executor(target=target) + executor.open() + executor.join(timeout=2) + assert elapsed is not None + self.assertLess(elapsed, 1.0, "join() from the executor's own task stalled") + def test_close_from_thread_without_event_loop(self): # close() can run off the event loop as a weakref callback, where # asyncio.current_task() raises RuntimeError. From bbed14c1c2d3cc7aa87b8f1037558a34e0fd93b2 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 10:38:15 -0600 Subject: [PATCH 13/26] Harden the deferred monitor shutdown --- pymongo/asynchronous/monitor.py | 8 ++++++++ pymongo/asynchronous/topology.py | 17 ++++++++++++----- pymongo/synchronous/monitor.py | 8 ++++++++ pymongo/synchronous/topology.py | 17 ++++++++++++----- test/asynchronous/pymongo_mocks.py | 3 +++ .../test_discovery_and_monitoring.py | 2 +- test/pymongo_mocks.py | 3 +++ test/test_discovery_and_monitoring.py | 2 +- 8 files changed, 48 insertions(+), 12 deletions(-) diff --git a/pymongo/asynchronous/monitor.py b/pymongo/asynchronous/monitor.py index 88f71a8604..d3fd429c7e 100644 --- a/pymongo/asynchronous/monitor.py +++ b/pymongo/asynchronous/monitor.py @@ -382,6 +382,14 @@ def __init__(self, topology: Topology, topology_settings: TopologySettings): self._fqdn: str = self._settings.fqdn self._startup_time = time.monotonic() + async def close(self) -> None: + """Stop DNS polling and join the executor. + + Must be called with the topology lock released. + """ + self.gc_safe_close() + await self._wake_and_join_executor() + async def _run(self) -> None: # Don't poll right after creation, wait 60 seconds first if time.monotonic() < self._startup_time + common.MIN_SRV_RESCAN_INTERVAL: diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index 301c92c9ef..d846e3c694 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -425,6 +425,9 @@ async def on_change( # that didn't include this server. if self._opened and self._description.has_server(server_description.address): await self._process_change(server_description, reset_pool, interrupt_connections) + # Drains the monitors of servers removed in this change; the join must + # not hold the lock (PYTHON-6168). + await self.cleanup_monitors() # Clear the pool from a failed heartbeat, done outside the lock to avoid blocking on # connection close. if reset_pool: @@ -448,6 +451,9 @@ async def on_srv_update(self, seedlist: list[tuple[str, Any]]) -> None: async with self._lock: if self._opened: await self._process_srv_update(seedlist) + # Drains the monitors of servers removed in this change; the join must + # not hold the lock (PYTHON-6168). + await self.cleanup_monitors() async def get_primary(self) -> _Address | None: """Return primary's address or None.""" @@ -521,8 +527,8 @@ async def close(self) -> None: # Signal the executors; joining them here would block on # on_change(), which needs this lock. cleanup_monitors below # joins and resets with the lock released. - await server.signal_close() self._monitor_tasks.append(server._monitor) + await server.signal_close() # Mark all servers Unknown. self._description = self._description.reset() @@ -708,12 +714,13 @@ async def _update_servers(self) -> None: for address, server in list(self._servers.items()): if not self._description.has_server(address): - # 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). - await server.signal_close() + # Record the monitor and remove the server before signaling: + # signal_close() awaits the pool close, which the calling task + # may cancel (PYTHON-6226). Joins happen in cleanup_monitors(), + # outside the lock (on_change() needs it). self._monitor_tasks.append(server._monitor) self._servers.pop(address) + await server.signal_close() async def cleanup_monitors(self) -> None: """Close monitors signaled earlier while the topology lock was held. diff --git a/pymongo/synchronous/monitor.py b/pymongo/synchronous/monitor.py index d3a29237b9..fe14e48198 100644 --- a/pymongo/synchronous/monitor.py +++ b/pymongo/synchronous/monitor.py @@ -382,6 +382,14 @@ def __init__(self, topology: Topology, topology_settings: TopologySettings): self._fqdn: str = self._settings.fqdn self._startup_time = time.monotonic() + def close(self) -> None: + """Stop DNS polling and join the executor. + + Must be called with the topology lock released. + """ + self.gc_safe_close() + self._wake_and_join_executor() + def _run(self) -> None: # Don't poll right after creation, wait 60 seconds first if time.monotonic() < self._startup_time + common.MIN_SRV_RESCAN_INTERVAL: diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index 1ee7f215f9..5e9e6b3b34 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -425,6 +425,9 @@ def on_change( # that didn't include this server. if self._opened and self._description.has_server(server_description.address): self._process_change(server_description, reset_pool, interrupt_connections) + # Drains the monitors of servers removed in this change; the join must + # not hold the lock (PYTHON-6168). + self.cleanup_monitors() # Clear the pool from a failed heartbeat, done outside the lock to avoid blocking on # connection close. if reset_pool: @@ -448,6 +451,9 @@ def on_srv_update(self, seedlist: list[tuple[str, Any]]) -> None: with self._lock: if self._opened: self._process_srv_update(seedlist) + # Drains the monitors of servers removed in this change; the join must + # not hold the lock (PYTHON-6168). + self.cleanup_monitors() def get_primary(self) -> _Address | None: """Return primary's address or None.""" @@ -519,8 +525,8 @@ def close(self) -> None: # Signal the executors; joining them here would block on # on_change(), which needs this lock. cleanup_monitors below # joins and resets with the lock released. - server.signal_close() self._monitor_tasks.append(server._monitor) + server.signal_close() # Mark all servers Unknown. self._description = self._description.reset() @@ -706,12 +712,13 @@ def _update_servers(self) -> None: for address, server in list(self._servers.items()): if not self._description.has_server(address): - # 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). - server.signal_close() + # Record the monitor and remove the server before signaling: + # signal_close() awaits the pool close, which the calling task + # may cancel (PYTHON-6226). Joins happen in cleanup_monitors(), + # outside the lock (on_change() needs it). self._monitor_tasks.append(server._monitor) self._servers.pop(address) + server.signal_close() def cleanup_monitors(self) -> None: """Close monitors signaled earlier while the topology lock was held. diff --git a/test/asynchronous/pymongo_mocks.py b/test/asynchronous/pymongo_mocks.py index 5b27f30727..02ba116e3d 100644 --- a/test/asynchronous/pymongo_mocks.py +++ b/test/asynchronous/pymongo_mocks.py @@ -70,6 +70,9 @@ def cancel_check(self): async def join(self): pass + def signal_close(self): + self.opened = False + def open(self): self.opened = True diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index 502d925c96..a231fa9b19 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -797,7 +797,7 @@ async def cancelling_close(): async def remove_victim(): async with topology._lock: - with patch.object(victim, "close", cancelling_close): + with patch.object(victim, "signal_close", cancelling_close): await topology._update_servers() task = asyncio.create_task(remove_victim()) diff --git a/test/pymongo_mocks.py b/test/pymongo_mocks.py index 8d6e54e1ce..ec7ccab22a 100644 --- a/test/pymongo_mocks.py +++ b/test/pymongo_mocks.py @@ -69,6 +69,9 @@ def cancel_check(self): def join(self): pass + def signal_close(self): + self.opened = False + def open(self): self.opened = True diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index 6880eba11b..cbeda1225b 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -793,7 +793,7 @@ def cancelling_close(): def remove_victim(): with topology._lock: - with patch.object(victim, "close", cancelling_close): + with patch.object(victim, "signal_close", cancelling_close): topology._update_servers() task = asyncio.create_task(remove_victim()) From 78cb1dd36ebd9ce9344fd70151e1e8fd2fc49aab Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 10:55:20 -0600 Subject: [PATCH 14/26] Serialize monitor cleanup --- pymongo/asynchronous/topology.py | 34 ++++++----- pymongo/synchronous/topology.py | 34 ++++++----- .../test_discovery_and_monitoring.py | 58 +++++++++++++++++++ test/test_discovery_and_monitoring.py | 57 ++++++++++++++++++ 4 files changed, 153 insertions(+), 30 deletions(-) diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index d846e3c694..c07e6c7b7e 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -16,6 +16,7 @@ from __future__ import annotations +import asyncio import os import random import sys @@ -92,6 +93,7 @@ class Topology(_AgnosticTopologyBase[Pool, Server]): def __init__(self, topology_settings: TopologySettings): super().__init__(topology_settings) self._lock = _async_create_lock() + self._cleanup_lock = asyncio.Lock() self._condition = _async_create_condition( self._lock, self._settings.condition_class if _IS_SYNC else None ) @@ -400,7 +402,9 @@ async def _process_change( td_old.topology_type == TOPOLOGY_TYPE.Unknown and self._description.topology_type not in SRV_POLLING_TOPOLOGIES ): - await self._srv_monitor.close() + # Signal only: close() joins, and on_srv_update() needs this lock. + # cleanup_monitors() joins after the lock is released. + self._srv_monitor.signal_close() self._monitor_tasks.append(self._srv_monitor) # Wake anything waiting in select_servers(). @@ -725,19 +729,19 @@ async def _update_servers(self) -> None: async def cleanup_monitors(self) -> None: """Close monitors signaled earlier while the topology lock was held. - Close joins each monitor and resets its pool. Always call this with - the lock released: a monitor being joined may itself be blocked - acquiring the lock. + Close joins each monitor and resets its pool, and runs until the queue + is empty. Always call this with the topology lock released: a monitor + being joined may itself be blocked acquiring the lock. """ - monitors = [] - try: + async with self._cleanup_lock: while self._monitor_tasks: - monitors.append(self._monitor_tasks.pop()) - except IndexError: - pass - for monitor in monitors: - try: - await monitor.close() - except Exception: # noqa: S110 - # One monitor failing to stop must not block the rest. - pass + monitor = self._monitor_tasks.pop() + try: + await monitor.close() + except asyncio.CancelledError: + # Preserve the monitor for a later cleanup. + self._monitor_tasks.append(monitor) + raise + except Exception: # noqa: S110 + # One monitor failing to stop must not block the rest. + pass diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index 5e9e6b3b34..ab0d3ad85f 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -16,6 +16,7 @@ from __future__ import annotations +import asyncio import os import random import sys @@ -92,6 +93,7 @@ class Topology(_AgnosticTopologyBase[Pool, Server]): def __init__(self, topology_settings: TopologySettings): super().__init__(topology_settings) self._lock = _create_lock() + self._cleanup_lock = asyncio.Lock() self._condition = _create_condition( self._lock, self._settings.condition_class if _IS_SYNC else None ) @@ -400,7 +402,9 @@ def _process_change( td_old.topology_type == TOPOLOGY_TYPE.Unknown and self._description.topology_type not in SRV_POLLING_TOPOLOGIES ): - self._srv_monitor.close() + # Signal only: close() joins, and on_srv_update() needs this lock. + # cleanup_monitors() joins after the lock is released. + self._srv_monitor.signal_close() self._monitor_tasks.append(self._srv_monitor) # Wake anything waiting in select_servers(). @@ -723,19 +727,19 @@ def _update_servers(self) -> None: def cleanup_monitors(self) -> None: """Close monitors signaled earlier while the topology lock was held. - Close joins each monitor and resets its pool. Always call this with - the lock released: a monitor being joined may itself be blocked - acquiring the lock. + Close joins each monitor and resets its pool, and runs until the queue + is empty. Always call this with the topology lock released: a monitor + being joined may itself be blocked acquiring the lock. """ - monitors = [] - try: + with self._cleanup_lock: while self._monitor_tasks: - monitors.append(self._monitor_tasks.pop()) - except IndexError: - pass - for monitor in monitors: - try: - monitor.close() - except Exception: # noqa: S110 - # One monitor failing to stop must not block the rest. - pass + monitor = self._monitor_tasks.pop() + try: + monitor.close() + except asyncio.CancelledError: + # Preserve the monitor for a later cleanup. + self._monitor_tasks.append(monitor) + raise + except Exception: # noqa: S110 + # One monitor failing to stop must not block the rest. + pass diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index a231fa9b19..58b8293a6e 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -829,6 +829,64 @@ async def close_victim(): self.assertTrue(victim.pool.closed) +@unittest.skipUnless(not _IS_SYNC, "PYTHON-6168: task interleaving is async-only") +class TestMonitorCleanup(AsyncUnitTest): + async def test_cleanup_cancellation_requeues_monitor(self): + # A cancelled cleanup must requeue the monitor it was closing, so a + # later cleanup (including client shutdown) can finish joining it. + topology = await create_mock_topology("mongodb://a:27017,b:27017") + victim = topology._servers[("a", 27017)]._monitor + other = topology._servers[("b", 27017)]._monitor + + async def cancelling_close(): + asyncio.current_task().cancel() + await asyncio.sleep(0) + + with patch.object(victim, "close", cancelling_close): + topology._monitor_tasks.append(victim) + topology._monitor_tasks.append(other) + task = asyncio.create_task(topology.cleanup_monitors()) + with self.assertRaises(asyncio.CancelledError): + await task + + self.assertIn(victim, topology._monitor_tasks) + self.assertNotIn(other, topology._monitor_tasks) + + # A later cleanup finishes the job. + await topology.cleanup_monitors() + self.assertEqual(topology._monitor_tasks, []) + + async def test_cleanup_drains_monitors_appended_in_flight(self): + # The drain runs until the queue is empty, even when a server is + # signaled while an earlier close is still joining. + topology = await create_mock_topology("mongodb://a:27017,b:27017") + first = topology._servers[("a", 27017)]._monitor + second = topology._servers[("b", 27017)]._monitor + in_flight = asyncio.Event() + first_done = asyncio.Event() + second_done = asyncio.Event() + + async def slow_close(): + in_flight.set() + await asyncio.sleep(0.2) + first_done.set() + + async def fast_close(): + second_done.set() + + with patch.object(first, "close", slow_close), patch.object(second, "close", fast_close): + topology._monitor_tasks.append(first) + drain = asyncio.create_task(topology.cleanup_monitors()) + # Signal the second monitor while the first close is in flight. + await in_flight.wait() + topology._monitor_tasks.append(second) + await drain + + self.assertTrue(first_done.is_set()) + self.assertTrue(second_done.is_set()) + self.assertEqual(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 cbeda1225b..300fe8312d 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -824,6 +824,63 @@ def close_victim(): self.assertTrue(victim.pool.closed) +@unittest.skipUnless(not _IS_SYNC, "PYTHON-6168: task interleaving is async-only") +class TestMonitorCleanup(UnitTest): + def test_cleanup_cancellation_requeues_monitor(self): + # A cancelled cleanup must requeue the monitor it was closing, so a + # later cleanup (including client shutdown) can finish joining it. + topology = create_mock_topology("mongodb://a:27017,b:27017") + victim = topology._servers[("a", 27017)]._monitor + other = topology._servers[("b", 27017)]._monitor + + def cancelling_close(): + asyncio.current_task().cancel() + + with patch.object(victim, "close", cancelling_close): + topology._monitor_tasks.append(victim) + topology._monitor_tasks.append(other) + task = asyncio.create_task(topology.cleanup_monitors()) + with self.assertRaises(asyncio.CancelledError): + task + + self.assertIn(victim, topology._monitor_tasks) + self.assertNotIn(other, topology._monitor_tasks) + + # A later cleanup finishes the job. + topology.cleanup_monitors() + self.assertEqual(topology._monitor_tasks, []) + + def test_cleanup_drains_monitors_appended_in_flight(self): + # The drain runs until the queue is empty, even when a server is + # signaled while an earlier close is still joining. + topology = create_mock_topology("mongodb://a:27017,b:27017") + first = topology._servers[("a", 27017)]._monitor + second = topology._servers[("b", 27017)]._monitor + in_flight = asyncio.Event() + first_done = asyncio.Event() + second_done = asyncio.Event() + + def slow_close(): + in_flight.set() + time.sleep(0.2) + first_done.set() + + def fast_close(): + second_done.set() + + with patch.object(first, "close", slow_close), patch.object(second, "close", fast_close): + topology._monitor_tasks.append(first) + drain = asyncio.create_task(topology.cleanup_monitors()) + # Signal the second monitor while the first close is in flight. + in_flight.wait() + topology._monitor_tasks.append(second) + drain + + self.assertTrue(first_done.is_set()) + self.assertTrue(second_done.is_set()) + self.assertEqual(topology._monitor_tasks, []) + + # Generate unified tests. globals().update(generate_test_classes(os.path.join(SDAM_PATH, "unified"), module=__name__)) From 0166766351b6c64f1a142c3d5607f1501efb4788 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 11:13:27 -0600 Subject: [PATCH 15/26] Fix the sync cleanup lock --- pymongo/asynchronous/topology.py | 2 +- pymongo/synchronous/topology.py | 2 +- test/asynchronous/test_discovery_and_monitoring.py | 2 +- test/test_discovery_and_monitoring.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index c07e6c7b7e..a6c661d8de 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -93,7 +93,7 @@ class Topology(_AgnosticTopologyBase[Pool, Server]): def __init__(self, topology_settings: TopologySettings): super().__init__(topology_settings) self._lock = _async_create_lock() - self._cleanup_lock = asyncio.Lock() + self._cleanup_lock = _async_create_lock() self._condition = _async_create_condition( self._lock, self._settings.condition_class if _IS_SYNC else None ) diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index ab0d3ad85f..1156506221 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -93,7 +93,7 @@ class Topology(_AgnosticTopologyBase[Pool, Server]): def __init__(self, topology_settings: TopologySettings): super().__init__(topology_settings) self._lock = _create_lock() - self._cleanup_lock = asyncio.Lock() + self._cleanup_lock = _create_lock() self._condition = _create_condition( self._lock, self._settings.condition_class if _IS_SYNC else None ) diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index 58b8293a6e..1402739b79 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -829,8 +829,8 @@ async def close_victim(): self.assertTrue(victim.pool.closed) -@unittest.skipUnless(not _IS_SYNC, "PYTHON-6168: task interleaving is async-only") class TestMonitorCleanup(AsyncUnitTest): + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6168: task cancellation is async-only") async def test_cleanup_cancellation_requeues_monitor(self): # A cancelled cleanup must requeue the monitor it was closing, so a # later cleanup (including client shutdown) can finish joining it. diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index 300fe8312d..4489c417d4 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -824,8 +824,8 @@ def close_victim(): self.assertTrue(victim.pool.closed) -@unittest.skipUnless(not _IS_SYNC, "PYTHON-6168: task interleaving is async-only") class TestMonitorCleanup(UnitTest): + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6168: task cancellation is async-only") def test_cleanup_cancellation_requeues_monitor(self): # A cancelled cleanup must requeue the monitor it was closing, so a # later cleanup (including client shutdown) can finish joining it. From d6e164b6e7fae6c5796119105c5d8ab1977a7146 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 12:56:25 -0600 Subject: [PATCH 16/26] fix tests --- .../test_discovery_and_monitoring.py | 45 +++++++++++++------ test/test_discovery_and_monitoring.py | 45 +++++++++++++------ 2 files changed, 64 insertions(+), 26 deletions(-) diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index 1402739b79..8447468207 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -862,27 +862,46 @@ async def test_cleanup_drains_monitors_appended_in_flight(self): topology = await create_mock_topology("mongodb://a:27017,b:27017") first = topology._servers[("a", 27017)]._monitor second = topology._servers[("b", 27017)]._monitor - in_flight = asyncio.Event() - first_done = asyncio.Event() - second_done = asyncio.Event() + if _IS_SYNC: + in_flight = threading.Event() + second_appended = threading.Event() + second_done = threading.Event() + + def slow_close(): + in_flight.set() + second_appended.wait(timeout=5) + second_done.set() + else: + in_flight = asyncio.Event() + second_done = asyncio.Event() - async def slow_close(): - in_flight.set() - await asyncio.sleep(0.2) - first_done.set() + async def slow_close(): + in_flight.set() + await asyncio.sleep(0.2) + second_done.set() - async def fast_close(): - second_done.set() + async def fast_close(): + second_done.set() with patch.object(first, "close", slow_close), patch.object(second, "close", fast_close): topology._monitor_tasks.append(first) - drain = asyncio.create_task(topology.cleanup_monitors()) + if _IS_SYNC: + drain = threading.Thread(target=topology.cleanup_monitors) + drain.start() + else: + drain = asyncio.create_task(topology.cleanup_monitors()) # Signal the second monitor while the first close is in flight. - await in_flight.wait() + if _IS_SYNC: + in_flight.wait() + else: + await in_flight.wait() topology._monitor_tasks.append(second) - await drain + if _IS_SYNC: + second_appended.set() + drain.join(timeout=5) + else: + await drain - self.assertTrue(first_done.is_set()) self.assertTrue(second_done.is_set()) self.assertEqual(topology._monitor_tasks, []) diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index 4489c417d4..2ea596c14f 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -856,27 +856,46 @@ def test_cleanup_drains_monitors_appended_in_flight(self): topology = create_mock_topology("mongodb://a:27017,b:27017") first = topology._servers[("a", 27017)]._monitor second = topology._servers[("b", 27017)]._monitor - in_flight = asyncio.Event() - first_done = asyncio.Event() - second_done = asyncio.Event() + if _IS_SYNC: + in_flight = threading.Event() + second_appended = threading.Event() + second_done = threading.Event() + + def slow_close(): + in_flight.set() + second_appended.wait(timeout=5) + second_done.set() + else: + in_flight = asyncio.Event() + second_done = asyncio.Event() - def slow_close(): - in_flight.set() - time.sleep(0.2) - first_done.set() + def slow_close(): + in_flight.set() + time.sleep(0.2) + second_done.set() - def fast_close(): - second_done.set() + def fast_close(): + second_done.set() with patch.object(first, "close", slow_close), patch.object(second, "close", fast_close): topology._monitor_tasks.append(first) - drain = asyncio.create_task(topology.cleanup_monitors()) + if _IS_SYNC: + drain = threading.Thread(target=topology.cleanup_monitors) + drain.start() + else: + drain = asyncio.create_task(topology.cleanup_monitors()) # Signal the second monitor while the first close is in flight. - in_flight.wait() + if _IS_SYNC: + in_flight.wait() + else: + in_flight.wait() topology._monitor_tasks.append(second) - drain + if _IS_SYNC: + second_appended.set() + drain.join(timeout=5) + else: + drain - self.assertTrue(first_done.is_set()) self.assertTrue(second_done.is_set()) self.assertEqual(topology._monitor_tasks, []) From faea677547aaf8d63c92215cba98851d9ae2ce5d Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 13:14:59 -0600 Subject: [PATCH 17/26] fix tests --- test/asynchronous/test_discovery_and_monitoring.py | 3 +++ test/test_discovery_and_monitoring.py | 3 +++ 2 files changed, 6 insertions(+) diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index 8447468207..fd9e5e569c 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -871,6 +871,9 @@ def slow_close(): in_flight.set() second_appended.wait(timeout=5) second_done.set() + + def fast_close(): + second_done.set() else: in_flight = asyncio.Event() second_done = asyncio.Event() diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index 2ea596c14f..b761cb0ec8 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -865,6 +865,9 @@ def slow_close(): in_flight.set() second_appended.wait(timeout=5) second_done.set() + + def fast_close(): + second_done.set() else: in_flight = asyncio.Event() second_done = asyncio.Event() From 76df144408a742e966bb43d9c59f54b2a9d33d45 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 13:39:30 -0600 Subject: [PATCH 18/26] address review with regression test --- pymongo/asynchronous/topology.py | 55 ++++++++++--------- pymongo/periodic_executor.py | 4 +- pymongo/synchronous/topology.py | 55 ++++++++++--------- .../test_discovery_and_monitoring.py | 36 ++++++++++++ test/test_discovery_and_monitoring.py | 36 ++++++++++++ 5 files changed, 134 insertions(+), 52 deletions(-) diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index a6c661d8de..45ecbf1ffc 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -429,8 +429,8 @@ async def on_change( # that didn't include this server. if self._opened and self._description.has_server(server_description.address): await self._process_change(server_description, reset_pool, interrupt_connections) - # Drains the monitors of servers removed in this change; the join must - # not hold the lock (PYTHON-6168). + # Drain the monitors removed in this change; the join must not hold + # the lock (PYTHON-6168). await self.cleanup_monitors() # Clear the pool from a failed heartbeat, done outside the lock to avoid blocking on # connection close. @@ -455,8 +455,8 @@ async def on_srv_update(self, seedlist: list[tuple[str, Any]]) -> None: async with self._lock: if self._opened: await self._process_srv_update(seedlist) - # Drains the monitors of servers removed in this change; the join must - # not hold the lock (PYTHON-6168). + # Drain the monitors removed in this change; the join must not hold + # the lock (PYTHON-6168). await self.cleanup_monitors() async def get_primary(self) -> _Address | None: @@ -529,8 +529,7 @@ async def close(self) -> None: old_td = self._description for server in self._servers.values(): # Signal the executors; joining them here would block on - # on_change(), which needs this lock. cleanup_monitors below - # joins and resets with the lock released. + # on_change(), which needs this lock. self._monitor_tasks.append(server._monitor) await server.signal_close() @@ -548,7 +547,9 @@ async def close(self) -> None: self._opened = False self._closed = True - await self.cleanup_monitors() + # Wait for any in-flight cleanup, then close every signaled monitor. + async with self._cleanup_lock: + await self._drain_monitors() # Publish only after releasing the lock. if self._sdam._publish_tp: @@ -718,10 +719,8 @@ async def _update_servers(self) -> None: for address, server in list(self._servers.items()): if not self._description.has_server(address): - # Record the monitor and remove the server before signaling: - # signal_close() awaits the pool close, which the calling task - # may cancel (PYTHON-6226). Joins happen in cleanup_monitors(), - # outside the lock (on_change() needs it). + # Record before signaling: signal_close() may be cancelled + # mid-await (PYTHON-6226). Joins happen in cleanup_monitors(). self._monitor_tasks.append(server._monitor) self._servers.pop(address) await server.signal_close() @@ -729,19 +728,25 @@ async def _update_servers(self) -> None: async def cleanup_monitors(self) -> None: """Close monitors signaled earlier while the topology lock was held. - Close joins each monitor and resets its pool, and runs until the queue - is empty. Always call this with the topology lock released: a monitor - being joined may itself be blocked acquiring the lock. + Concurrent callers return immediately: a running cleanup drains the + queue before releasing the lock. Always call this with the topology + lock released: a monitor being joined may itself be blocked acquiring + the lock. """ + if self._cleanup_lock.locked(): + return async with self._cleanup_lock: - while self._monitor_tasks: - monitor = self._monitor_tasks.pop() - try: - await monitor.close() - except asyncio.CancelledError: - # Preserve the monitor for a later cleanup. - self._monitor_tasks.append(monitor) - raise - except Exception: # noqa: S110 - # One monitor failing to stop must not block the rest. - pass + await self._drain_monitors() + + async def _drain_monitors(self) -> None: + while self._monitor_tasks: + monitor = self._monitor_tasks.pop() + try: + await monitor.close() + except asyncio.CancelledError: + # Preserve the monitor for a later cleanup. + self._monitor_tasks.append(monitor) + raise + except Exception: # noqa: S110 + # One monitor failing to stop must not block the rest. + pass diff --git a/pymongo/periodic_executor.py b/pymongo/periodic_executor.py index 147c4dc4ef..852c5821cd 100644 --- a/pymongo/periodic_executor.py +++ b/pymongo/periodic_executor.py @@ -88,8 +88,8 @@ def close(self, dummy: Any = None) -> None: self._task.cancel() async def join(self, timeout: float | None = None) -> None: - # Waiting on our own task cannot complete: returning lets the caller - # finish its shutdown and the executor see the stop signal. + # Waiting on our own task cannot complete; returning lets the caller + # finish its shutdown. if self._task is not None and self._task is not asyncio.current_task(): await asyncio.wait([self._task], timeout=timeout) # type-ignore: [arg-type] diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index 1156506221..56d6c2cea8 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -429,8 +429,8 @@ def on_change( # that didn't include this server. if self._opened and self._description.has_server(server_description.address): self._process_change(server_description, reset_pool, interrupt_connections) - # Drains the monitors of servers removed in this change; the join must - # not hold the lock (PYTHON-6168). + # Drain the monitors removed in this change; the join must not hold + # the lock (PYTHON-6168). self.cleanup_monitors() # Clear the pool from a failed heartbeat, done outside the lock to avoid blocking on # connection close. @@ -455,8 +455,8 @@ def on_srv_update(self, seedlist: list[tuple[str, Any]]) -> None: with self._lock: if self._opened: self._process_srv_update(seedlist) - # Drains the monitors of servers removed in this change; the join must - # not hold the lock (PYTHON-6168). + # Drain the monitors removed in this change; the join must not hold + # the lock (PYTHON-6168). self.cleanup_monitors() def get_primary(self) -> _Address | None: @@ -527,8 +527,7 @@ def close(self) -> None: old_td = self._description for server in self._servers.values(): # Signal the executors; joining them here would block on - # on_change(), which needs this lock. cleanup_monitors below - # joins and resets with the lock released. + # on_change(), which needs this lock. self._monitor_tasks.append(server._monitor) server.signal_close() @@ -546,7 +545,9 @@ def close(self) -> None: self._opened = False self._closed = True - self.cleanup_monitors() + # Wait for any in-flight cleanup, then close every signaled monitor. + with self._cleanup_lock: + self._drain_monitors() # Publish only after releasing the lock. if self._sdam._publish_tp: @@ -716,10 +717,8 @@ def _update_servers(self) -> None: for address, server in list(self._servers.items()): if not self._description.has_server(address): - # Record the monitor and remove the server before signaling: - # signal_close() awaits the pool close, which the calling task - # may cancel (PYTHON-6226). Joins happen in cleanup_monitors(), - # outside the lock (on_change() needs it). + # Record before signaling: signal_close() may be cancelled + # mid-(PYTHON-6226). Joins happen in cleanup_monitors(). self._monitor_tasks.append(server._monitor) self._servers.pop(address) server.signal_close() @@ -727,19 +726,25 @@ def _update_servers(self) -> None: def cleanup_monitors(self) -> None: """Close monitors signaled earlier while the topology lock was held. - Close joins each monitor and resets its pool, and runs until the queue - is empty. Always call this with the topology lock released: a monitor - being joined may itself be blocked acquiring the lock. + Concurrent callers return immediately: a running cleanup drains the + queue before releasing the lock. Always call this with the topology + lock released: a monitor being joined may itself be blocked acquiring + the lock. """ + if self._cleanup_lock.locked(): + return with self._cleanup_lock: - while self._monitor_tasks: - monitor = self._monitor_tasks.pop() - try: - monitor.close() - except asyncio.CancelledError: - # Preserve the monitor for a later cleanup. - self._monitor_tasks.append(monitor) - raise - except Exception: # noqa: S110 - # One monitor failing to stop must not block the rest. - pass + self._drain_monitors() + + def _drain_monitors(self) -> None: + while self._monitor_tasks: + monitor = self._monitor_tasks.pop() + try: + monitor.close() + except asyncio.CancelledError: + # Preserve the monitor for a later cleanup. + self._monitor_tasks.append(monitor) + raise + except Exception: # noqa: S110 + # One monitor failing to stop must not block the rest. + pass diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index fd9e5e569c..7a2f39ad74 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -856,6 +856,42 @@ async def cancelling_close(): await topology.cleanup_monitors() self.assertEqual(topology._monitor_tasks, []) + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6168: task interleaving is async-only") + async def test_cleanup_concurrent_caller_skips_in_flight_cleanup(self): + # A concurrent cleanup returns immediately: the running cleanup owns + # the queue. + topology = await create_mock_topology("mongodb://a:27017,b:27017") + first = topology._servers[("a", 27017)]._monitor + second = topology._servers[("b", 27017)]._monitor + in_flight = asyncio.Event() + release = asyncio.Event() + first_done = asyncio.Event() + second_done = asyncio.Event() + + async def slow_close(): + in_flight.set() + await release.wait() + first_done.set() + + async def fast_close(): + second_done.set() + + with patch.object(first, "close", slow_close), patch.object(second, "close", fast_close): + topology._monitor_tasks.append(first) + cleanup = asyncio.create_task(topology.cleanup_monitors()) + await in_flight.wait() + + # The concurrent caller returns before the second close runs. + await topology.cleanup_monitors() + self.assertFalse(second_done.is_set()) + + topology._monitor_tasks.append(second) + release.set() + await cleanup + self.assertTrue(first_done.is_set()) + self.assertTrue(second_done.is_set()) + self.assertEqual(topology._monitor_tasks, []) + async def test_cleanup_drains_monitors_appended_in_flight(self): # The drain runs until the queue is empty, even when a server is # signaled while an earlier close is still joining. diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index b761cb0ec8..e55c6e2bd3 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -850,6 +850,42 @@ def cancelling_close(): topology.cleanup_monitors() self.assertEqual(topology._monitor_tasks, []) + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6168: task interleaving is async-only") + def test_cleanup_concurrent_caller_skips_in_flight_cleanup(self): + # A concurrent cleanup returns immediately: the running cleanup owns + # the queue. + topology = create_mock_topology("mongodb://a:27017,b:27017") + first = topology._servers[("a", 27017)]._monitor + second = topology._servers[("b", 27017)]._monitor + in_flight = asyncio.Event() + release = asyncio.Event() + first_done = asyncio.Event() + second_done = asyncio.Event() + + def slow_close(): + in_flight.set() + release.wait() + first_done.set() + + def fast_close(): + second_done.set() + + with patch.object(first, "close", slow_close), patch.object(second, "close", fast_close): + topology._monitor_tasks.append(first) + cleanup = asyncio.create_task(topology.cleanup_monitors()) + in_flight.wait() + + # The concurrent caller returns before the second close runs. + topology.cleanup_monitors() + self.assertFalse(second_done.is_set()) + + topology._monitor_tasks.append(second) + release.set() + cleanup + self.assertTrue(first_done.is_set()) + self.assertTrue(second_done.is_set()) + self.assertEqual(topology._monitor_tasks, []) + def test_cleanup_drains_monitors_appended_in_flight(self): # The drain runs until the queue is empty, even when a server is # signaled while an earlier close is still joining. From bab201f1e363cd08c07a9b6db279d5bb82a823ed Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 14:39:05 -0600 Subject: [PATCH 19/26] Make the sync cleanup acquire atomic --- pymongo/asynchronous/topology.py | 21 ++++++++++---- pymongo/synchronous/topology.py | 21 ++++++++++---- .../test_discovery_and_monitoring.py | 28 +++++++++++++++++++ test/test_discovery_and_monitoring.py | 28 +++++++++++++++++++ 4 files changed, 88 insertions(+), 10 deletions(-) diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index 45ecbf1ffc..cf4b9da9f8 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -720,7 +720,7 @@ async def _update_servers(self) -> None: for address, server in list(self._servers.items()): if not self._description.has_server(address): # Record before signaling: signal_close() may be cancelled - # mid-await (PYTHON-6226). Joins happen in cleanup_monitors(). + # before returning (PYTHON-6226). Joins happen in cleanup_monitors(). self._monitor_tasks.append(server._monitor) self._servers.pop(address) await server.signal_close() @@ -733,10 +733,21 @@ async def cleanup_monitors(self) -> None: lock released: a monitor being joined may itself be blocked acquiring the lock. """ - if self._cleanup_lock.locked(): - return - async with self._cleanup_lock: - await self._drain_monitors() + if _IS_SYNC: + # locked() plus acquire is not atomic across threads: a monitor + # can pass the check, then block while close's cleanup joins it. + if not self._cleanup_lock.acquire(blocking=False): # type: ignore[call-arg] + return + try: + await self._drain_monitors() + finally: + self._cleanup_lock.release() + else: + # locked() plus acquire is atomic within a single event loop. + if self._cleanup_lock.locked(): + return + async with self._cleanup_lock: + await self._drain_monitors() async def _drain_monitors(self) -> None: while self._monitor_tasks: diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index 56d6c2cea8..d6ea5f1606 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -718,7 +718,7 @@ def _update_servers(self) -> None: for address, server in list(self._servers.items()): if not self._description.has_server(address): # Record before signaling: signal_close() may be cancelled - # mid-(PYTHON-6226). Joins happen in cleanup_monitors(). + # before returning (PYTHON-6226). Joins happen in cleanup_monitors(). self._monitor_tasks.append(server._monitor) self._servers.pop(address) server.signal_close() @@ -731,10 +731,21 @@ def cleanup_monitors(self) -> None: lock released: a monitor being joined may itself be blocked acquiring the lock. """ - if self._cleanup_lock.locked(): - return - with self._cleanup_lock: - self._drain_monitors() + if _IS_SYNC: + # locked() plus acquire is not atomic across threads: a monitor + # can pass the check, then block while close's cleanup joins it. + if not self._cleanup_lock.acquire(blocking=False): # type: ignore[call-arg] + return + try: + self._drain_monitors() + finally: + self._cleanup_lock.release() + else: + # locked() plus acquire is atomic within a single event loop. + if self._cleanup_lock.locked(): + return + with self._cleanup_lock: + self._drain_monitors() def _drain_monitors(self) -> None: while self._monitor_tasks: diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index 7a2f39ad74..92078b9049 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -892,6 +892,34 @@ async def fast_close(): self.assertTrue(second_done.is_set()) self.assertEqual(topology._monitor_tasks, []) + async def test_cleanup_skips_when_cleanup_lock_held(self): + # A caller returns immediately when another cleanup holds the lock, + # leaving its monitors queued for the running cleanup to drain. + topology = await create_mock_topology("mongodb://a:27017,b:27017") + monitor = topology._servers[("a", 27017)]._monitor + topology._monitor_tasks.append(monitor) + if _IS_SYNC: + topology._cleanup_lock.acquire() + else: + await topology._cleanup_lock.acquire() + await topology.cleanup_monitors() + self.assertIn(monitor, topology._monitor_tasks) + topology._cleanup_lock.release() + await topology.cleanup_monitors() + self.assertEqual(topology._monitor_tasks, []) + + async def test_cleanup_releases_cleanup_lock(self): + # The cleanup lock must be released when cleanup_monitors returns, + # including on the nonblocking acquire path in the sync driver. + topology = await create_mock_topology("mongodb://a:27017,b:27017") + monitor = topology._servers[("a", 27017)]._monitor + topology._monitor_tasks.append(monitor) + await topology.cleanup_monitors() + self.assertFalse(topology._cleanup_lock.locked()) + await topology.cleanup_monitors() + self.assertFalse(topology._cleanup_lock.locked()) + self.assertEqual(topology._monitor_tasks, []) + async def test_cleanup_drains_monitors_appended_in_flight(self): # The drain runs until the queue is empty, even when a server is # signaled while an earlier close is still joining. diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index e55c6e2bd3..86abe6e344 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -886,6 +886,34 @@ def fast_close(): self.assertTrue(second_done.is_set()) self.assertEqual(topology._monitor_tasks, []) + def test_cleanup_skips_when_cleanup_lock_held(self): + # A caller returns immediately when another cleanup holds the lock, + # leaving its monitors queued for the running cleanup to drain. + topology = create_mock_topology("mongodb://a:27017,b:27017") + monitor = topology._servers[("a", 27017)]._monitor + topology._monitor_tasks.append(monitor) + if _IS_SYNC: + topology._cleanup_lock.acquire() + else: + topology._cleanup_lock.acquire() + topology.cleanup_monitors() + self.assertIn(monitor, topology._monitor_tasks) + topology._cleanup_lock.release() + topology.cleanup_monitors() + self.assertEqual(topology._monitor_tasks, []) + + def test_cleanup_releases_cleanup_lock(self): + # The cleanup lock must be released when cleanup_monitors returns, + # including on the nonblocking acquire path in the sync driver. + topology = create_mock_topology("mongodb://a:27017,b:27017") + monitor = topology._servers[("a", 27017)]._monitor + topology._monitor_tasks.append(monitor) + topology.cleanup_monitors() + self.assertFalse(topology._cleanup_lock.locked()) + topology.cleanup_monitors() + self.assertFalse(topology._cleanup_lock.locked()) + self.assertEqual(topology._monitor_tasks, []) + def test_cleanup_drains_monitors_appended_in_flight(self): # The drain runs until the queue is empty, even when a server is # signaled while an earlier close is still joining. From 70f4345b8e7456d43dc5ae6f90b7c909a4c1a729 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 19:03:22 -0600 Subject: [PATCH 20/26] Make the sync executor wakeable and reads cancellable promptly --- pymongo/network_layer.py | 4 ++- pymongo/periodic_executor.py | 8 ++++- test/asynchronous/test_periodic_executor.py | 35 +++++++++++++++++++++ test/test_periodic_executor.py | 35 +++++++++++++++++++++ 4 files changed, 80 insertions(+), 2 deletions(-) diff --git a/pymongo/network_layer.py b/pymongo/network_layer.py index e6f14a7e5e..6b6815ef59 100644 --- a/pymongo/network_layer.py +++ b/pymongo/network_layer.py @@ -65,7 +65,9 @@ _UNPACK_HEADER = struct.Struct(" str: return f"<{self.__class__.__name__}(name={self._name}) object at 0x{id(self):x}>" @@ -212,6 +215,7 @@ def open(self) -> None: pass if not started: + self._stop_event.clear() thread = threading.Thread(target=self._run, name=self._name) try: # Subinterpreters do not allow daemon threads, so fall back @@ -247,6 +251,7 @@ def close(self, dummy: Any = None) -> None: callback; see monitor.py. """ self._stopped = True + self._stop_event.set() def join(self, timeout: float | None = None) -> None: if self._thread is not None: @@ -292,7 +297,8 @@ def _run(self) -> None: else: deadline = time.monotonic() + self._interval while not self._stopped and time.monotonic() < deadline: - time.sleep(self._min_interval) + if self._stop_event.wait(self._min_interval): + break # Closed. if self._event: break # Early wake. diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index 8b65939491..38e88119bb 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -199,6 +199,41 @@ async def target(): assert elapsed is not None self.assertLess(elapsed, 1.0, "join() from the executor's own task stalled") + async def test_close_interrupts_wait(self): + # close() must end the executor's wait immediately: shutdown paths + # join the executor, and a wait that only ends at the next tick burns + # up to min_interval of the join budget on every close. + min_interval = 10.0 + if _IS_SYNC: + started = threading.Event() + else: + started = asyncio.Event() + + async def target(): + started.set() + return True + + executor = self._make_executor(interval=60.0, min_interval=min_interval, target=target) + executor.open() + if _IS_SYNC: + started.wait(timeout=2) + settle = threading.Event() + settle.wait(0.1) # Let the executor enter its wait. + else: + assert isinstance(started, asyncio.Event) + await asyncio.wait_for(started.wait(), timeout=2) + await asyncio.sleep(0.1) + + start = time.monotonic() + executor.close() + await executor.join(timeout=15) + elapsed = time.monotonic() - start + self.assertLess( + elapsed, + min_interval / 2, + "close() did not interrupt the executor's wait", + ) + async def test_close_from_thread_without_event_loop(self): # close() can run off the event loop as a weakref callback, where # asyncio.current_task() raises RuntimeError. diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index 1fdd084b86..0770b47429 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -198,6 +198,41 @@ def target(): assert elapsed is not None self.assertLess(elapsed, 1.0, "join() from the executor's own task stalled") + def test_close_interrupts_wait(self): + # close() must end the executor's wait immediately: shutdown paths + # join the executor, and a wait that only ends at the next tick burns + # up to min_interval of the join budget on every close. + min_interval = 10.0 + if _IS_SYNC: + started = threading.Event() + else: + started = asyncio.Event() + + def target(): + started.set() + return True + + executor = self._make_executor(interval=60.0, min_interval=min_interval, target=target) + executor.open() + if _IS_SYNC: + started.wait(timeout=2) + settle = threading.Event() + settle.wait(0.1) # Let the executor enter its wait. + else: + assert isinstance(started, asyncio.Event) + asyncio.wait_for(started.wait(), timeout=2) + time.sleep(0.1) + + start = time.monotonic() + executor.close() + executor.join(timeout=15) + elapsed = time.monotonic() - start + self.assertLess( + elapsed, + min_interval / 2, + "close() did not interrupt the executor's wait", + ) + def test_close_from_thread_without_event_loop(self): # close() can run off the event loop as a weakref callback, where # asyncio.current_task() raises RuntimeError. From c276f301381e580858bb8ced31b057de7179ed0d Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 20 Nov 2026 06:30:06 -0600 Subject: [PATCH 21/26] Harden the executor stop signal. --- pymongo/lock.py | 5 ++ pymongo/periodic_executor.py | 49 +++++++++--- test/asynchronous/test_periodic_executor.py | 85 +++++++++++++++++++++ test/test_periodic_executor.py | 85 +++++++++++++++++++++ 4 files changed, 213 insertions(+), 11 deletions(-) diff --git a/pymongo/lock.py b/pymongo/lock.py index 36df97c5af..acdf42d8c4 100644 --- a/pymongo/lock.py +++ b/pymongo/lock.py @@ -80,6 +80,11 @@ def _release_locks() -> None: lock.release() +if _HAS_REGISTER_AT_FORK: + # Threads do not survive a fork: release the tracked locks they held. + os.register_at_fork(after_in_child=_release_locks) + + async def _async_cond_wait(condition: Condition, timeout: float | None) -> bool: try: return await wait_for(condition.wait(), timeout) diff --git a/pymongo/periodic_executor.py b/pymongo/periodic_executor.py index 140d2a238e..a649351e31 100644 --- a/pymongo/periodic_executor.py +++ b/pymongo/periodic_executor.py @@ -24,7 +24,7 @@ from typing import Any from pymongo import _csot, _op_id -from pymongo.lock import _create_lock +from pymongo.lock import _create_condition, _create_lock _IS_SYNC = False @@ -181,9 +181,11 @@ def __init__( self._skip_sleep = False self._thread_will_exit = False self._lock = _create_lock() - # Set by close() to end the run loop's wait immediately; a plain - # time.sleep would delay the thread's exit by up to min_interval. - self._stop_event = threading.Event() + # Wakes the run loop immediately on close(); the lock is fork-tracked. + self._stop_condition = _create_condition(_create_lock()) + self._stop_flag = False + # The run-loop thread's ident, to detect a re-entrant close(). + self._run_loop_ident: int | None = None def __repr__(self) -> str: return f"<{self.__class__.__name__}(name={self._name}) object at 0x{id(self):x}>" @@ -207,6 +209,8 @@ def open(self) -> None: pass self._thread_will_exit = False self._stopped = False + # Reset even when reusing a live thread: a set flag would spin it. + self._stop_flag = False started: Any = False try: started = self._thread and self._thread.is_alive() @@ -215,7 +219,6 @@ def open(self) -> None: pass if not started: - self._stop_event.clear() thread = threading.Thread(target=self._run, name=self._name) try: # Subinterpreters do not allow daemon threads, so fall back @@ -251,7 +254,25 @@ def close(self, dummy: Any = None) -> None: callback; see monitor.py. """ self._stopped = True - self._stop_event.set() + self._wake_waiter() + + def _wake_waiter(self) -> None: + """Wake a thread waiting in _run() on _stop_condition. + + close() also runs as a weakref callback during garbage collection, so + this never blocks: the notify is skipped when the lock is held or the + callback re-enters the waiter's thread, and the waiter notices the + flag at its next poll. + """ + if self._run_loop_ident == threading.get_ident(): + self._stop_flag = True + return + if self._stop_condition.acquire(False): + try: + self._stop_flag = True + self._stop_condition.notify_all() + finally: + self._stop_condition.release() def join(self, timeout: float | None = None) -> None: if self._thread is not None: @@ -296,11 +317,17 @@ def _run(self) -> None: self._skip_sleep = False else: deadline = time.monotonic() + self._interval - while not self._stopped and time.monotonic() < deadline: - if self._stop_event.wait(self._min_interval): - break # Closed. - if self._event: - break # Early wake. + self._run_loop_ident = threading.get_ident() + try: + while not self._stopped and time.monotonic() < deadline: + with self._stop_condition: + if self._stop_flag: + break # Closed. + self._stop_condition.wait(self._min_interval) + if self._event: + break # Early wake. + finally: + self._run_loop_ident = None self._event = False diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index 38e88119bb..76c5880474 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -234,6 +234,91 @@ async def target(): "close() did not interrupt the executor's wait", ) + async def test_close_then_reopen_live_thread_respects_interval(self): + # A live-thread reopen must reset the stop signal, or the target spins. + if _IS_SYNC: + entered = threading.Event() + release = threading.Event() + else: + entered = asyncio.Event() + release = asyncio.Event() + calls = 0 + + async def target(): + nonlocal calls + calls += 1 + if calls == 1: + entered.set() + if _IS_SYNC: + release.wait(timeout=5) + else: + assert isinstance(release, asyncio.Event) + await asyncio.wait_for(release.wait(), timeout=5) + return calls < 3 + + executor = self._make_executor(interval=60.0, min_interval=0.05, target=target) + executor.open() + if _IS_SYNC: + entered.wait(timeout=2) + else: + assert isinstance(entered, asyncio.Event) + await asyncio.wait_for(entered.wait(), timeout=2) + # Close and reopen while the target is blocked: the thread is reused. + executor.close() + executor.open() + if _IS_SYNC: + release.set() + else: + release.set() + await executor.join(timeout=3) + self.assertEqual( + calls, + 1, + "the target did not respect its interval after a live reopen", + ) + + @unittest.skipUnless(_IS_SYNC, "fork semantics apply to the threaded executor") + def test_close_after_fork_while_notification_lock_held(self): + # A fork while the notification lock is held inherits it locked in the + # child: the fork reset frees it and close() must not block. + from pymongo.lock import _forkable_locks + + executor = self._make_executor(interval=60.0, min_interval=0.05) + executor.open() + # The condition's lock participates in the fork reset. + self.assertIn(executor._stop_condition._lock, _forkable_locks) + executor._stop_condition.acquire() # Simulate the lock held at fork. + done = threading.Event() + + def child_close(): + executor.close() # Must not block on the inherited lock. + done.set() + + closer = threading.Thread(target=child_close, daemon=True) + closer.start() + closer.join(timeout=2) + self.assertTrue(done.is_set(), "close() blocked on the notification lock") + executor._stop_condition.release() + executor.join(timeout=2) + self.assertTrue(executor._stopped) + + @unittest.skipUnless(_IS_SYNC, "fork semantics apply to the threaded executor") + def test_close_reentrant_on_notification_lock(self): + # A GC callback can re-enter close() on the run-loop's own thread + # while the notification lock is held: it must not block. + executor = self._make_executor(interval=60.0, min_interval=0.05) + executor.open() + time.sleep(0.2) # Let the executor's thread enter its wait. + # Simulate the callback: the run-loop ident, the lock held. + executor._run_loop_ident = threading.get_ident() + start = time.monotonic() + with executor._stop_condition: + executor.close() + elapsed = time.monotonic() - start + self.assertLess(elapsed, 2.0, "close() blocked on the notification lock") + executor.join(timeout=2) + self.assertTrue(executor._stopped) + async def test_close_from_thread_without_event_loop(self): # close() can run off the event loop as a weakref callback, where # asyncio.current_task() raises RuntimeError. diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index 0770b47429..4e038406f1 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -233,6 +233,91 @@ def target(): "close() did not interrupt the executor's wait", ) + def test_close_then_reopen_live_thread_respects_interval(self): + # A live-thread reopen must reset the stop signal, or the target spins. + if _IS_SYNC: + entered = threading.Event() + release = threading.Event() + else: + entered = asyncio.Event() + release = asyncio.Event() + calls = 0 + + def target(): + nonlocal calls + calls += 1 + if calls == 1: + entered.set() + if _IS_SYNC: + release.wait(timeout=5) + else: + assert isinstance(release, asyncio.Event) + asyncio.wait_for(release.wait(), timeout=5) + return calls < 3 + + executor = self._make_executor(interval=60.0, min_interval=0.05, target=target) + executor.open() + if _IS_SYNC: + entered.wait(timeout=2) + else: + assert isinstance(entered, asyncio.Event) + asyncio.wait_for(entered.wait(), timeout=2) + # Close and reopen while the target is blocked: the thread is reused. + executor.close() + executor.open() + if _IS_SYNC: + release.set() + else: + release.set() + executor.join(timeout=3) + self.assertEqual( + calls, + 1, + "the target did not respect its interval after a live reopen", + ) + + @unittest.skipUnless(_IS_SYNC, "fork semantics apply to the threaded executor") + def test_close_after_fork_while_notification_lock_held(self): + # A fork while the notification lock is held inherits it locked in the + # child: the fork reset frees it and close() must not block. + from pymongo.lock import _forkable_locks + + executor = self._make_executor(interval=60.0, min_interval=0.05) + executor.open() + # The condition's lock participates in the fork reset. + self.assertIn(executor._stop_condition._lock, _forkable_locks) + executor._stop_condition.acquire() # Simulate the lock held at fork. + done = threading.Event() + + def child_close(): + executor.close() # Must not block on the inherited lock. + done.set() + + closer = threading.Thread(target=child_close, daemon=True) + closer.start() + closer.join(timeout=2) + self.assertTrue(done.is_set(), "close() blocked on the notification lock") + executor._stop_condition.release() + executor.join(timeout=2) + self.assertTrue(executor._stopped) + + @unittest.skipUnless(_IS_SYNC, "fork semantics apply to the threaded executor") + def test_close_reentrant_on_notification_lock(self): + # A GC callback can re-enter close() on the run-loop's own thread + # while the notification lock is held: it must not block. + executor = self._make_executor(interval=60.0, min_interval=0.05) + executor.open() + time.sleep(0.2) # Let the executor's thread enter its wait. + # Simulate the callback: the run-loop ident, the lock held. + executor._run_loop_ident = threading.get_ident() + start = time.monotonic() + with executor._stop_condition: + executor.close() + elapsed = time.monotonic() - start + self.assertLess(elapsed, 2.0, "close() blocked on the notification lock") + executor.join(timeout=2) + self.assertTrue(executor._stopped) + def test_close_from_thread_without_event_loop(self): # close() can run off the event loop as a weakref callback, where # asyncio.current_task() raises RuntimeError. From d05da11a14d512b9f19a65222999a96a45e43737 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 20 Nov 2026 06:50:40 -0600 Subject: [PATCH 22/26] Skip the fork-tracking test without at-fork support --- test/asynchronous/test_periodic_executor.py | 5 ++++- test/test_periodic_executor.py | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index 76c5880474..79ce82c0a9 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -277,7 +277,10 @@ async def target(): "the target did not respect its interval after a live reopen", ) - @unittest.skipUnless(_IS_SYNC, "fork semantics apply to the threaded executor") + @unittest.skipUnless( + _IS_SYNC and hasattr(os, "register_at_fork"), + "fork lock tracking requires the threaded executor and os.register_at_fork", + ) def test_close_after_fork_while_notification_lock_held(self): # A fork while the notification lock is held inherits it locked in the # child: the fork reset frees it and close() must not block. diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index 4e038406f1..6b00780c6c 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -276,7 +276,10 @@ def target(): "the target did not respect its interval after a live reopen", ) - @unittest.skipUnless(_IS_SYNC, "fork semantics apply to the threaded executor") + @unittest.skipUnless( + _IS_SYNC and hasattr(os, "register_at_fork"), + "fork lock tracking requires the threaded executor and os.register_at_fork", + ) def test_close_after_fork_while_notification_lock_held(self): # A fork while the notification lock is held inherits it locked in the # child: the fork reset frees it and close() must not block. From 9eb1b592cf4c02deb2d833e13e06a46e496ed142 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 20 Nov 2026 08:03:46 -0600 Subject: [PATCH 23/26] Shield the pool close from cancelled callers --- pymongo/asynchronous/pool.py | 20 +++++++---- pymongo/synchronous/pool.py | 20 +++++++---- test/asynchronous/test_periodic_executor.py | 6 ++-- test/asynchronous/test_pooling.py | 37 ++++++++++++++++++++- test/test_periodic_executor.py | 6 ++-- test/test_pooling.py | 37 ++++++++++++++++++++- 6 files changed, 108 insertions(+), 18 deletions(-) diff --git a/pymongo/asynchronous/pool.py b/pymongo/asynchronous/pool.py index 6e3fba6f5a..2f8702cc30 100644 --- a/pymongo/asynchronous/pool.py +++ b/pymongo/asynchronous/pool.py @@ -513,18 +513,26 @@ async def _reset( # publishing the PoolClearedEvent. if close: if not _IS_SYNC: - await asyncio.gather( - *[conn.close_conn(ConnectionClosedReason.POOL_CLOSED) for conn in sockets], # type: ignore[func-returns-value] - return_exceptions=True, + # Shield the gather from a cancelled caller: the sockets are + # already detached from the pool, so a cancelled close would + # leak them. + await asyncio.shield( + asyncio.gather( + *[conn.close_conn(ConnectionClosedReason.POOL_CLOSED) for conn in sockets], + return_exceptions=True, + ) ) else: for conn in sockets: await conn.close_conn(ConnectionClosedReason.POOL_CLOSED) self._telemetry.pool_closed() elif not _IS_SYNC: - await asyncio.gather( - *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], # type: ignore[func-returns-value] - return_exceptions=True, + # Shielded as above: a cancelled reset would leak the sockets. + await asyncio.shield( + asyncio.gather( + *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], + return_exceptions=True, + ) ) else: for conn in sockets: diff --git a/pymongo/synchronous/pool.py b/pymongo/synchronous/pool.py index 28a8811b03..43c32d4864 100644 --- a/pymongo/synchronous/pool.py +++ b/pymongo/synchronous/pool.py @@ -513,18 +513,26 @@ def _reset( # publishing the PoolClearedEvent. if close: if not _IS_SYNC: - asyncio.gather( - *[conn.close_conn(ConnectionClosedReason.POOL_CLOSED) for conn in sockets], # type: ignore[func-returns-value] - return_exceptions=True, + # Shield the gather from a cancelled caller: the sockets are + # already detached from the pool, so a cancelled close would + # leak them. + asyncio.shield( + asyncio.gather( + *[conn.close_conn(ConnectionClosedReason.POOL_CLOSED) for conn in sockets], + return_exceptions=True, + ) ) else: for conn in sockets: conn.close_conn(ConnectionClosedReason.POOL_CLOSED) self._telemetry.pool_closed() elif not _IS_SYNC: - asyncio.gather( - *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], # type: ignore[func-returns-value] - return_exceptions=True, + # Shielded as above: a cancelled reset would leak the sockets. + asyncio.shield( + asyncio.gather( + *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], + return_exceptions=True, + ) ) else: for conn in sockets: diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index 79ce82c0a9..5236505eaa 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -284,13 +284,16 @@ async def target(): def test_close_after_fork_while_notification_lock_held(self): # A fork while the notification lock is held inherits it locked in the # child: the fork reset frees it and close() must not block. - from pymongo.lock import _forkable_locks + from pymongo.lock import _forkable_locks, _release_locks executor = self._make_executor(interval=60.0, min_interval=0.05) executor.open() # The condition's lock participates in the fork reset. self.assertIn(executor._stop_condition._lock, _forkable_locks) executor._stop_condition.acquire() # Simulate the lock held at fork. + _release_locks() # The after_in_child hook: the reset frees the lock. + self.assertTrue(executor._stop_condition.acquire(False)) + executor._stop_condition.release() done = threading.Event() def child_close(): @@ -301,7 +304,6 @@ def child_close(): closer.start() closer.join(timeout=2) self.assertTrue(done.is_set(), "close() blocked on the notification lock") - executor._stop_condition.release() executor.join(timeout=2) self.assertTrue(executor._stopped) diff --git a/test/asynchronous/test_pooling.py b/test/asynchronous/test_pooling.py index 54746d7b44..5dd799b3fc 100644 --- a/test/asynchronous/test_pooling.py +++ b/test/asynchronous/test_pooling.py @@ -33,7 +33,7 @@ from pymongo.errors import AutoReconnect, ConnectionFailure, DuplicateKeyError from pymongo.hello import HelloCompat from pymongo.lock import _async_create_lock -from pymongo.monitoring import _EventListeners +from pymongo.monitoring import ConnectionClosedReason, _EventListeners from pymongo.pool_shared import _async_wrap_socket_tls from test.asynchronous.utils import async_get_pool, async_joinall, flaky @@ -958,5 +958,40 @@ async def test_wrap_socket_tls_without_ssl_context_returns_same_socket(self): self.assertEqual(result.gettimeout(), 7.5) +class TestPoolCloseCancellation(unittest.IsolatedAsyncioTestCase): + # The close gathers must be shielded from a cancelled caller: the sockets + # are detached from the pool first, so a cancelled close would leak them. + @unittest.skipUnless(not _IS_SYNC, "cancellation is async-only") + async def test_close_completes_despite_cancellation(self): + pool = Pool(("localhost", 27017), PoolOptions()) + reasons: list[list[str]] = [[], []] + started = asyncio.Event() + proceed = asyncio.Event() + closed = asyncio.Event() + + class FakeConn: + def __init__(self, n): + self.n = n + + async def close_conn(self, reason): + if self.n == 0: + started.set() + await proceed.wait() + reasons[self.n].append(reason) + if all(reasons): + closed.set() + + pool.conns = [FakeConn(0), FakeConn(1)] + task = asyncio.create_task(pool.close()) + await started.wait() + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await task + proceed.set() + await asyncio.wait_for(closed.wait(), timeout=2) + self.assertEqual(reasons[0], [ConnectionClosedReason.POOL_CLOSED]) + self.assertEqual(reasons[1], [ConnectionClosedReason.POOL_CLOSED]) + + if __name__ == "__main__": unittest.main() diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index 6b00780c6c..7e090fedb0 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -283,13 +283,16 @@ def target(): def test_close_after_fork_while_notification_lock_held(self): # A fork while the notification lock is held inherits it locked in the # child: the fork reset frees it and close() must not block. - from pymongo.lock import _forkable_locks + from pymongo.lock import _forkable_locks, _release_locks executor = self._make_executor(interval=60.0, min_interval=0.05) executor.open() # The condition's lock participates in the fork reset. self.assertIn(executor._stop_condition._lock, _forkable_locks) executor._stop_condition.acquire() # Simulate the lock held at fork. + _release_locks() # The after_in_child hook: the reset frees the lock. + self.assertTrue(executor._stop_condition.acquire(False)) + executor._stop_condition.release() done = threading.Event() def child_close(): @@ -300,7 +303,6 @@ def child_close(): closer.start() closer.join(timeout=2) self.assertTrue(done.is_set(), "close() blocked on the notification lock") - executor._stop_condition.release() executor.join(timeout=2) self.assertTrue(executor._stopped) diff --git a/test/test_pooling.py b/test/test_pooling.py index 6da69cc41b..518e902843 100644 --- a/test/test_pooling.py +++ b/test/test_pooling.py @@ -33,7 +33,7 @@ from pymongo.errors import AutoReconnect, ConnectionFailure, DuplicateKeyError from pymongo.hello import HelloCompat from pymongo.lock import _create_lock -from pymongo.monitoring import _EventListeners +from pymongo.monitoring import ConnectionClosedReason, _EventListeners from pymongo.pool_shared import _wrap_socket_tls from test.utils import flaky, get_pool, joinall @@ -956,5 +956,40 @@ def test_wrap_socket_tls_without_ssl_context_returns_same_socket(self): self.assertEqual(result.gettimeout(), 7.5) +class TestPoolCloseCancellation(unittest.TestCase): + # The close gathers must be shielded from a cancelled caller: the sockets + # are detached from the pool first, so a cancelled close would leak them. + @unittest.skipUnless(not _IS_SYNC, "cancellation is async-only") + def test_close_completes_despite_cancellation(self): + pool = Pool(("localhost", 27017), PoolOptions()) + reasons: list[list[str]] = [[], []] + started = asyncio.Event() + proceed = asyncio.Event() + closed = asyncio.Event() + + class FakeConn: + def __init__(self, n): + self.n = n + + def close_conn(self, reason): + if self.n == 0: + started.set() + proceed.wait() + reasons[self.n].append(reason) + if all(reasons): + closed.set() + + pool.conns = [FakeConn(0), FakeConn(1)] + task = asyncio.create_task(pool.close()) + started.wait() + task.cancel() + with self.assertRaises(asyncio.CancelledError): + task + proceed.set() + asyncio.wait_for(closed.wait(), timeout=2) + self.assertEqual(reasons[0], [ConnectionClosedReason.POOL_CLOSED]) + self.assertEqual(reasons[1], [ConnectionClosedReason.POOL_CLOSED]) + + if __name__ == "__main__": unittest.main() From 6417e48ec21035e038ec4fd3f6410bd002577786 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 20 Nov 2026 08:08:27 -0600 Subject: [PATCH 24/26] clean up prose --- .evergreen/scripts/setup_sanitizer.py | 10 +++++----- .evergreen/scripts/utils.py | 6 +++--- .evergreen/tsan-suppressions.txt | 2 +- CONTRIBUTING.md | 2 +- pymongo/asynchronous/monitor.py | 14 +++++++------- pymongo/asynchronous/pool.py | 2 +- pymongo/asynchronous/server.py | 2 +- pymongo/asynchronous/topology.py | 12 ++++++------ pymongo/periodic_executor.py | 8 ++++---- pymongo/synchronous/monitor.py | 14 +++++++------- pymongo/synchronous/pool.py | 2 +- pymongo/synchronous/server.py | 2 +- pymongo/synchronous/topology.py | 12 ++++++------ test/asynchronous/test_monitor.py | 2 +- test/asynchronous/test_periodic_executor.py | 2 +- test/test_monitor.py | 2 +- test/test_periodic_executor.py | 2 +- 17 files changed, 48 insertions(+), 48 deletions(-) diff --git a/.evergreen/scripts/setup_sanitizer.py b/.evergreen/scripts/setup_sanitizer.py index 2af2d6d637..741282197a 100644 --- a/.evergreen/scripts/setup_sanitizer.py +++ b/.evergreen/scripts/setup_sanitizer.py @@ -34,7 +34,7 @@ def tsan_interface_exported(python_binary: str) -> bool: """Check the interpreter's dynamic symbols for the TSan interface. Instrumented extensions resolve __tsan_func_entry and friends against - the interpreter's dynamic exports; an interpreter built without the + the interpreter's dynamic exports. An interpreter built without the sanitizer exports none of them. """ nm = shutil.which("nm") @@ -61,8 +61,8 @@ def configure_env(sub_test_name: str, test_args: str) -> str: raise RuntimeError("The sanitizer tests require the Linux Python toolchain.") if not Path(python).is_file(): raise RuntimeError( - f"Sanitizer interpreter not found at {python}; the task must run " - "on a host with the sanitizer toolchain Python." + f"Sanitizer interpreter not found at {python}. Run the task on a " + "host with the sanitizer toolchain Python." ) if not Path(CLANG).is_file(): raise RuntimeError( @@ -79,7 +79,7 @@ def configure_env(sub_test_name: str, test_args: str) -> str: write_env("CXX", CLANGXX) write_env("UV_PYTHON", python) write_env("PYMONGO_C_EXT_MUST_BUILD") - # Env-var flags sit outside uv's cache key; skip the cache so wheels + # Env-var flags sit outside uv's cache key. Skip the cache so wheels # rebuild instrumented. write_env("UV_NO_CACHE", "1") if tsan: @@ -113,7 +113,7 @@ def configure_env(sub_test_name: str, test_args: str) -> str: write_env("LDFLAGS", "-fsanitize=address,undefined") # CPython's pymalloc trips LeakSanitizer with false positives. write_env("ASAN_OPTIONS", "detect_leaks=0") - # UBSan only warns by default; make undefined behavior fail the task. + # UBSan only warns by default, so make undefined behavior fail the task. write_env("UBSAN_OPTIONS", "halt_on_error=1:print_stacktrace=1") # No LD_PRELOAD: the interpreter self-initializes its runtimes, and a # mismatched preloaded runtime mixes sanitizers in one process. diff --git a/.evergreen/scripts/utils.py b/.evergreen/scripts/utils.py index 8561bfde5a..50fc872dc4 100644 --- a/.evergreen/scripts/utils.py +++ b/.evergreen/scripts/utils.py @@ -321,8 +321,8 @@ def read_env(path: Path | str) -> dict[str, str]: def shell_escape(value: str) -> str: """Escape a value for a double-quoted shell context. - The inverse of read_env's unescaping. Backslashes are escaped first; - otherwise a backslash-prefixed substitution re-arms when the file is + The inverse of read_env's unescaping. Backslashes are escaped first. + Otherwise a backslash-prefixed substitution re-arms when the file is sourced (PYTHON-6167). """ return value.replace("\\", "\\\\").replace("$", "\\$").replace("`", "\\`").replace('"', '\\"') @@ -331,7 +331,7 @@ def shell_escape(value: str) -> str: def write_env(name: str, value: Any = "1", escape: bool = True) -> None: """Append an export line for the value to the test environment file. - The value persists literally; pass escape=False to keep live expansions, + The value persists literally. Pass escape=False to keep live expansions, like a trailing `$PATH` (PYTHON-6167). """ with ENV_FILE.open("a", newline="\n") as fid: diff --git a/.evergreen/tsan-suppressions.txt b/.evergreen/tsan-suppressions.txt index 632df008de..a8f2442a4a 100644 --- a/.evergreen/tsan-suppressions.txt +++ b/.evergreen/tsan-suppressions.txt @@ -8,5 +8,5 @@ # CPython-internal: under free-threading the GC path (memory_clear) and a # worker's deferred refcount merge (memory_dealloc) can both enter -# _memory_release for the same memoryview; both stacks are within CPython. +# _memory_release for the same memoryview. Both stacks are within CPython. race_top:_memory_release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2a3235519d..b9522e8f80 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -417,7 +417,7 @@ the same for local checkouts with `just install`). ### Using a local checkout instead -Set `DRIVERS_TOOLS` to the path of a local clone — the environment variable wins over the +Set `DRIVERS_TOOLS` to the path of a local clone. The environment variable wins over the submodule default: ```bash diff --git a/pymongo/asynchronous/monitor.py b/pymongo/asynchronous/monitor.py index d3fd429c7e..23199bec02 100644 --- a/pymongo/asynchronous/monitor.py +++ b/pymongo/asynchronous/monitor.py @@ -105,7 +105,7 @@ def gc_safe_close(self) -> None: def signal_close(self) -> None: """Stop the executors without joining them. - Joining blocks on on_change(), which needs the topology lock: call + Joining blocks on on_change(), which needs the topology lock. Call close() with the lock released to join and reset the pool. """ self.gc_safe_close() @@ -120,13 +120,13 @@ async def close(self) -> None: async def join(self, timeout: float | None = None) -> None: """Wait for the monitor to stop. - :param timeout: Maximum time in seconds to wait; ``None`` waits - indefinitely. + :param timeout: Maximum time in seconds to wait, or ``None`` to + wait indefinitely. """ await self._executor.join(timeout) async def _wake_and_join_executor(self) -> None: - # Join before resetting so we don't race a checked-out connection; a + # Join before resetting so we don't race a checked-out connection. A # straggler's socket closes when the reset returns its connection. self._executor.wake() await self._executor.join(_EXECUTOR_JOIN_TIMEOUT) @@ -213,11 +213,11 @@ def gc_safe_close(self) -> None: async def join(self, timeout: float | None = None) -> None: """Wait for the monitor to stop. - The timeout budgets both executors: the RTT monitor gets whatever + The timeout budgets both executors. The RTT monitor gets whatever remains after the heartbeat executor stops. - :param timeout: Maximum time in seconds to wait; ``None`` waits - indefinitely. + :param timeout: Maximum time in seconds to wait, or ``None`` to + wait indefinitely. """ start = time.monotonic() await self._executor.join(timeout) diff --git a/pymongo/asynchronous/pool.py b/pymongo/asynchronous/pool.py index 2f8702cc30..849c9d76d2 100644 --- a/pymongo/asynchronous/pool.py +++ b/pymongo/asynchronous/pool.py @@ -866,7 +866,7 @@ async def _restore_counters(self, applied: int) -> None: finally: # Always reacquired: `applied` keeps restore-only flags # `notified` never tracks, so skipping needs a mask synced - # to the notify sites; uncontended acquires don't yield (PYTHON-6136). + # to the notify sites. Uncontended acquires don't yield (PYTHON-6136). async with self.size_cond: if not accounted: self._restore_applied(applied) diff --git a/pymongo/asynchronous/server.py b/pymongo/asynchronous/server.py index ccc55c5ef2..cc7c1a0815 100644 --- a/pymongo/asynchronous/server.py +++ b/pymongo/asynchronous/server.py @@ -82,7 +82,7 @@ async def close(self) -> None: async def signal_close(self) -> None: """Stop the monitor and clear the pool without joining it. - Joining blocks on on_change(), which needs the topology lock: the + Joining blocks on on_change(), which needs the topology lock, so the topology defers close() to its unlocked cleanup phase. """ self._sdam.server_closed(self._description.address) diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index cf4b9da9f8..1431053f41 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -429,7 +429,7 @@ async def on_change( # that didn't include this server. if self._opened and self._description.has_server(server_description.address): await self._process_change(server_description, reset_pool, interrupt_connections) - # Drain the monitors removed in this change; the join must not hold + # Drain the monitors removed in this change. The join must not hold # the lock (PYTHON-6168). await self.cleanup_monitors() # Clear the pool from a failed heartbeat, done outside the lock to avoid blocking on @@ -455,7 +455,7 @@ async def on_srv_update(self, seedlist: list[tuple[str, Any]]) -> None: async with self._lock: if self._opened: await self._process_srv_update(seedlist) - # Drain the monitors removed in this change; the join must not hold + # Drain the monitors removed in this change. The join must not hold # the lock (PYTHON-6168). await self.cleanup_monitors() @@ -528,7 +528,7 @@ async def close(self) -> None: async with self._lock: old_td = self._description for server in self._servers.values(): - # Signal the executors; joining them here would block on + # Signal the executors. Joining them here would block on # on_change(), which needs this lock. self._monitor_tasks.append(server._monitor) await server.signal_close() @@ -728,9 +728,9 @@ async def _update_servers(self) -> None: async def cleanup_monitors(self) -> None: """Close monitors signaled earlier while the topology lock was held. - Concurrent callers return immediately: a running cleanup drains the - queue before releasing the lock. Always call this with the topology - lock released: a monitor being joined may itself be blocked acquiring + Concurrent callers return immediately because a running cleanup drains + the queue before releasing the lock. Always call this with the topology + lock released. A monitor being joined may itself be blocked acquiring the lock. """ if _IS_SYNC: diff --git a/pymongo/periodic_executor.py b/pymongo/periodic_executor.py index a649351e31..1c67cdd3d6 100644 --- a/pymongo/periodic_executor.py +++ b/pymongo/periodic_executor.py @@ -88,7 +88,7 @@ def close(self, dummy: Any = None) -> None: self._task.cancel() async def join(self, timeout: float | None = None) -> None: - # Waiting on our own task cannot complete; returning lets the caller + # Waiting on our own task cannot complete. Returning lets the caller # finish its shutdown. if self._task is not None and self._task is not asyncio.current_task(): await asyncio.wait([self._task], timeout=timeout) # type-ignore: [arg-type] @@ -136,7 +136,7 @@ def _daemon_threads_allowed() -> bool: """Whether daemon threads are allowed in the current interpreter. Subinterpreters do not allow daemon threads, so a PeriodicExecutor - there runs on a non-daemon thread instead: _shutdown_executors stops + there runs on a non-daemon thread instead. _shutdown_executors stops and joins it during interpreter shutdown. """ # Python 3.12+ exposes the same check CPython itself uses to enforce @@ -181,7 +181,7 @@ def __init__( self._skip_sleep = False self._thread_will_exit = False self._lock = _create_lock() - # Wakes the run loop immediately on close(); the lock is fork-tracked. + # Wakes the run loop immediately on close(). The lock is fork-tracked. self._stop_condition = _create_condition(_create_lock()) self._stop_flag = False # The run-loop thread's ident, to detect a re-entrant close(). @@ -260,7 +260,7 @@ def _wake_waiter(self) -> None: """Wake a thread waiting in _run() on _stop_condition. close() also runs as a weakref callback during garbage collection, so - this never blocks: the notify is skipped when the lock is held or the + this never blocks. The notify is skipped when the lock is held or the callback re-enters the waiter's thread, and the waiter notices the flag at its next poll. """ diff --git a/pymongo/synchronous/monitor.py b/pymongo/synchronous/monitor.py index fe14e48198..e39ef30ea4 100644 --- a/pymongo/synchronous/monitor.py +++ b/pymongo/synchronous/monitor.py @@ -105,7 +105,7 @@ def gc_safe_close(self) -> None: def signal_close(self) -> None: """Stop the executors without joining them. - Joining blocks on on_change(), which needs the topology lock: call + Joining blocks on on_change(), which needs the topology lock. Call close() with the lock released to join and reset the pool. """ self.gc_safe_close() @@ -120,13 +120,13 @@ def close(self) -> None: def join(self, timeout: float | None = None) -> None: """Wait for the monitor to stop. - :param timeout: Maximum time in seconds to wait; ``None`` waits - indefinitely. + :param timeout: Maximum time in seconds to wait, or ``None`` to + wait indefinitely. """ self._executor.join(timeout) def _wake_and_join_executor(self) -> None: - # Join before resetting so we don't race a checked-out connection; a + # Join before resetting so we don't race a checked-out connection. A # straggler's socket closes when the reset returns its connection. self._executor.wake() self._executor.join(_EXECUTOR_JOIN_TIMEOUT) @@ -213,11 +213,11 @@ def gc_safe_close(self) -> None: def join(self, timeout: float | None = None) -> None: """Wait for the monitor to stop. - The timeout budgets both executors: the RTT monitor gets whatever + The timeout budgets both executors. The RTT monitor gets whatever remains after the heartbeat executor stops. - :param timeout: Maximum time in seconds to wait; ``None`` waits - indefinitely. + :param timeout: Maximum time in seconds to wait, or ``None`` to + wait indefinitely. """ start = time.monotonic() self._executor.join(timeout) diff --git a/pymongo/synchronous/pool.py b/pymongo/synchronous/pool.py index 43c32d4864..aa258cf80f 100644 --- a/pymongo/synchronous/pool.py +++ b/pymongo/synchronous/pool.py @@ -864,7 +864,7 @@ def _restore_counters(self, applied: int) -> None: finally: # Always reacquired: `applied` keeps restore-only flags # `notified` never tracks, so skipping needs a mask synced - # to the notify sites; uncontended acquires don't yield (PYTHON-6136). + # to the notify sites. Uncontended acquires don't yield (PYTHON-6136). with self.size_cond: if not accounted: self._restore_applied(applied) diff --git a/pymongo/synchronous/server.py b/pymongo/synchronous/server.py index efa4b716ed..82723ea7f5 100644 --- a/pymongo/synchronous/server.py +++ b/pymongo/synchronous/server.py @@ -82,7 +82,7 @@ def close(self) -> None: def signal_close(self) -> None: """Stop the monitor and clear the pool without joining it. - Joining blocks on on_change(), which needs the topology lock: the + Joining blocks on on_change(), which needs the topology lock, so the topology defers close() to its unlocked cleanup phase. """ self._sdam.server_closed(self._description.address) diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index d6ea5f1606..7a25ee9773 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -429,7 +429,7 @@ def on_change( # that didn't include this server. if self._opened and self._description.has_server(server_description.address): self._process_change(server_description, reset_pool, interrupt_connections) - # Drain the monitors removed in this change; the join must not hold + # Drain the monitors removed in this change. The join must not hold # the lock (PYTHON-6168). self.cleanup_monitors() # Clear the pool from a failed heartbeat, done outside the lock to avoid blocking on @@ -455,7 +455,7 @@ def on_srv_update(self, seedlist: list[tuple[str, Any]]) -> None: with self._lock: if self._opened: self._process_srv_update(seedlist) - # Drain the monitors removed in this change; the join must not hold + # Drain the monitors removed in this change. The join must not hold # the lock (PYTHON-6168). self.cleanup_monitors() @@ -526,7 +526,7 @@ def close(self) -> None: with self._lock: old_td = self._description for server in self._servers.values(): - # Signal the executors; joining them here would block on + # Signal the executors. Joining them here would block on # on_change(), which needs this lock. self._monitor_tasks.append(server._monitor) server.signal_close() @@ -726,9 +726,9 @@ def _update_servers(self) -> None: def cleanup_monitors(self) -> None: """Close monitors signaled earlier while the topology lock was held. - Concurrent callers return immediately: a running cleanup drains the - queue before releasing the lock. Always call this with the topology - lock released: a monitor being joined may itself be blocked acquiring + Concurrent callers return immediately because a running cleanup drains + the queue before releasing the lock. Always call this with the topology + lock released. A monitor being joined may itself be blocked acquiring the lock. """ if _IS_SYNC: diff --git a/test/asynchronous/test_monitor.py b/test/asynchronous/test_monitor.py index ec3513a683..f96a4c4dc9 100644 --- a/test/asynchronous/test_monitor.py +++ b/test/asynchronous/test_monitor.py @@ -212,7 +212,7 @@ async def test_rtt_join_gets_unspent_budget(self): await monitor.join(1) rtt_timeout = rtt.timeouts[0] - # Narrowing only; the verified assertion is assertLess below. + # Narrowing only. The verified assertion is assertLess below. assert isinstance(rtt_timeout, float) self.assertLess(rtt_timeout, 0.95) diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index 5236505eaa..dab87f1efa 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -181,7 +181,7 @@ async def target(): self.assertEqual(runs, 2, "executor did not restart after a self-close") async def test_join_from_own_task_does_not_stall(self): - # A heartbeat removing its own server joins its own task; waiting on + # A heartbeat removing its own server joins its own task. Waiting on # the current task cannot complete and would stall for the full # timeout (PYTHON-6168). elapsed = None diff --git a/test/test_monitor.py b/test/test_monitor.py index 8e553da514..5f932c0747 100644 --- a/test/test_monitor.py +++ b/test/test_monitor.py @@ -208,7 +208,7 @@ def test_rtt_join_gets_unspent_budget(self): monitor.join(1) rtt_timeout = rtt.timeouts[0] - # Narrowing only; the verified assertion is assertLess below. + # Narrowing only. The verified assertion is assertLess below. assert isinstance(rtt_timeout, float) self.assertLess(rtt_timeout, 0.95) diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index 7e090fedb0..99fce4d8c7 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -180,7 +180,7 @@ def target(): self.assertEqual(runs, 2, "executor did not restart after a self-close") def test_join_from_own_task_does_not_stall(self): - # A heartbeat removing its own server joins its own task; waiting on + # A heartbeat removing its own server joins its own task. Waiting on # the current task cannot complete and would stall for the full # timeout (PYTHON-6168). elapsed = None From 9bdf1b1539d8140030e9caf8921f723c2ad8c47b Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 20 Nov 2026 09:40:54 -0600 Subject: [PATCH 25/26] Restore pool type ignores and isolate the fork test --- pymongo/asynchronous/pool.py | 4 +- pymongo/synchronous/pool.py | 4 +- test/asynchronous/test_periodic_executor.py | 50 ++++++++++++++------- test/test_periodic_executor.py | 50 ++++++++++++++------- 4 files changed, 74 insertions(+), 34 deletions(-) diff --git a/pymongo/asynchronous/pool.py b/pymongo/asynchronous/pool.py index 849c9d76d2..5fa528edf0 100644 --- a/pymongo/asynchronous/pool.py +++ b/pymongo/asynchronous/pool.py @@ -518,7 +518,7 @@ async def _reset( # leak them. await asyncio.shield( asyncio.gather( - *[conn.close_conn(ConnectionClosedReason.POOL_CLOSED) for conn in sockets], + *[conn.close_conn(ConnectionClosedReason.POOL_CLOSED) for conn in sockets], # type: ignore[func-returns-value] return_exceptions=True, ) ) @@ -530,7 +530,7 @@ async def _reset( # Shielded as above: a cancelled reset would leak the sockets. await asyncio.shield( asyncio.gather( - *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], + *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], # type: ignore[func-returns-value] return_exceptions=True, ) ) diff --git a/pymongo/synchronous/pool.py b/pymongo/synchronous/pool.py index aa258cf80f..de0dce74c4 100644 --- a/pymongo/synchronous/pool.py +++ b/pymongo/synchronous/pool.py @@ -518,7 +518,7 @@ def _reset( # leak them. asyncio.shield( asyncio.gather( - *[conn.close_conn(ConnectionClosedReason.POOL_CLOSED) for conn in sockets], + *[conn.close_conn(ConnectionClosedReason.POOL_CLOSED) for conn in sockets], # type: ignore[func-returns-value] return_exceptions=True, ) ) @@ -530,7 +530,7 @@ def _reset( # Shielded as above: a cancelled reset would leak the sockets. asyncio.shield( asyncio.gather( - *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], + *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], # type: ignore[func-returns-value] return_exceptions=True, ) ) diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index dab87f1efa..9d74c7e62a 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -19,6 +19,8 @@ import asyncio import importlib import os +import select +import signal import sys import textwrap import threading @@ -283,27 +285,45 @@ async def target(): ) def test_close_after_fork_while_notification_lock_held(self): # A fork while the notification lock is held inherits it locked in the - # child: the fork reset frees it and close() must not block. + # child: the fork reset frees it and close() must not block. The reset + # runs in the forked child itself: it releases every tracked lock, + # which is only safe where no other thread survives. from pymongo.lock import _forkable_locks, _release_locks executor = self._make_executor(interval=60.0, min_interval=0.05) executor.open() # The condition's lock participates in the fork reset. self.assertIn(executor._stop_condition._lock, _forkable_locks) - executor._stop_condition.acquire() # Simulate the lock held at fork. - _release_locks() # The after_in_child hook: the reset frees the lock. - self.assertTrue(executor._stop_condition.acquire(False)) - executor._stop_condition.release() - done = threading.Event() - - def child_close(): - executor.close() # Must not block on the inherited lock. - done.set() - - closer = threading.Thread(target=child_close, daemon=True) - closer.start() - closer.join(timeout=2) - self.assertTrue(done.is_set(), "close() blocked on the notification lock") + executor._stop_condition.acquire() # Held across the fork. + read_fd, write_fd = os.pipe() + pid = os.fork() + if pid == 0: + # The child runs the real hook: no other thread survives the + # fork, the state the reset is designed for. + outcome = b"ok" + try: + _release_locks() # The after_in_child hook. + if not executor._stop_condition.acquire(False): + outcome = b"locked" + else: + executor._stop_condition.release() + executor.close() # Must not block on the inherited lock. + except BaseException: + outcome = b"error" + os.write(write_fd, outcome) + os._exit(0) + try: + ready, _, _ = select.select([read_fd], [], [], 5) + if not ready: + os.kill(pid, signal.SIGKILL) + self.fail("forked child hung: the reset or close blocked") + self.assertEqual(os.read(read_fd, 8), b"ok", "the reset did not free the lock") + finally: + os.close(read_fd) + os.close(write_fd) + os.waitpid(pid, 0) + executor._stop_condition.release() + executor.close() executor.join(timeout=2) self.assertTrue(executor._stopped) diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index 99fce4d8c7..a6a74ab2b9 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -19,6 +19,8 @@ import asyncio import importlib import os +import select +import signal import sys import textwrap import threading @@ -282,27 +284,45 @@ def target(): ) def test_close_after_fork_while_notification_lock_held(self): # A fork while the notification lock is held inherits it locked in the - # child: the fork reset frees it and close() must not block. + # child: the fork reset frees it and close() must not block. The reset + # runs in the forked child itself: it releases every tracked lock, + # which is only safe where no other thread survives. from pymongo.lock import _forkable_locks, _release_locks executor = self._make_executor(interval=60.0, min_interval=0.05) executor.open() # The condition's lock participates in the fork reset. self.assertIn(executor._stop_condition._lock, _forkable_locks) - executor._stop_condition.acquire() # Simulate the lock held at fork. - _release_locks() # The after_in_child hook: the reset frees the lock. - self.assertTrue(executor._stop_condition.acquire(False)) - executor._stop_condition.release() - done = threading.Event() - - def child_close(): - executor.close() # Must not block on the inherited lock. - done.set() - - closer = threading.Thread(target=child_close, daemon=True) - closer.start() - closer.join(timeout=2) - self.assertTrue(done.is_set(), "close() blocked on the notification lock") + executor._stop_condition.acquire() # Held across the fork. + read_fd, write_fd = os.pipe() + pid = os.fork() + if pid == 0: + # The child runs the real hook: no other thread survives the + # fork, the state the reset is designed for. + outcome = b"ok" + try: + _release_locks() # The after_in_child hook. + if not executor._stop_condition.acquire(False): + outcome = b"locked" + else: + executor._stop_condition.release() + executor.close() # Must not block on the inherited lock. + except BaseException: + outcome = b"error" + os.write(write_fd, outcome) + os._exit(0) + try: + ready, _, _ = select.select([read_fd], [], [], 5) + if not ready: + os.kill(pid, signal.SIGKILL) + self.fail("forked child hung: the reset or close blocked") + self.assertEqual(os.read(read_fd, 8), b"ok", "the reset did not free the lock") + finally: + os.close(read_fd) + os.close(write_fd) + os.waitpid(pid, 0) + executor._stop_condition.release() + executor.close() executor.join(timeout=2) self.assertTrue(executor._stopped) From 0c4667209ce49e00d7e38f21dfbf5be4cab28b73 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 20 Nov 2026 10:36:52 -0600 Subject: [PATCH 26/26] Fix shutdown and fork-test failures on newer Pythons --- pymongo/network_layer.py | 2 +- pymongo/periodic_executor.py | 5 ++++- test/asynchronous/test_periodic_executor.py | 7 ++++++- test/asynchronous/test_pooling.py | 2 +- test/test_periodic_executor.py | 7 ++++++- test/test_pooling.py | 2 +- 6 files changed, 19 insertions(+), 6 deletions(-) diff --git a/pymongo/network_layer.py b/pymongo/network_layer.py index 6b6815ef59..6d44946d2a 100644 --- a/pymongo/network_layer.py +++ b/pymongo/network_layer.py @@ -282,7 +282,7 @@ def wait_for_read(conn: Connection, deadline: float | None) -> None: if hasattr(sock, "pending") and sock.pending() > 0: readable = True else: - # Wait up to 500ms for the socket to become readable and then + # Wait up to 50ms for the socket to become readable and then # check for cancellation. if deadline: remaining = deadline - time.monotonic() diff --git a/pymongo/periodic_executor.py b/pymongo/periodic_executor.py index 1c67cdd3d6..8126fdaac7 100644 --- a/pymongo/periodic_executor.py +++ b/pymongo/periodic_executor.py @@ -264,7 +264,10 @@ def _wake_waiter(self) -> None: callback re-enters the waiter's thread, and the waiter notices the flag at its next poll. """ - if self._run_loop_ident == threading.get_ident(): + # A GC callback can run once the interpreter is finalizing, when the + # threading module's globals are already None: set the flag lock-free. + ident = threading.get_ident() if threading else None + if ident is None or self._run_loop_ident == ident: self._stop_flag = True return if self._stop_condition.acquire(False): diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index 9d74c7e62a..bd500b0d7c 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -25,6 +25,7 @@ import textwrap import threading import time +import warnings from typing import Any, Optional from unittest import mock @@ -296,7 +297,11 @@ def test_close_after_fork_while_notification_lock_held(self): self.assertIn(executor._stop_condition._lock, _forkable_locks) executor._stop_condition.acquire() # Held across the fork. read_fd, write_fd = os.pipe() - pid = os.fork() + with warnings.catch_warnings(): + # The test forks a multi-threaded process on purpose: the reset + # exists for production forks of exactly this shape. + warnings.simplefilter("ignore", DeprecationWarning) + pid = os.fork() if pid == 0: # The child runs the real hook: no other thread survives the # fork, the state the reset is designed for. diff --git a/test/asynchronous/test_pooling.py b/test/asynchronous/test_pooling.py index 5dd799b3fc..679d76f531 100644 --- a/test/asynchronous/test_pooling.py +++ b/test/asynchronous/test_pooling.py @@ -982,7 +982,7 @@ async def close_conn(self, reason): closed.set() pool.conns = [FakeConn(0), FakeConn(1)] - task = asyncio.create_task(pool.close()) + task = asyncio.create_task(pool.close()) # type: ignore[func-returns-value] await started.wait() task.cancel() with self.assertRaises(asyncio.CancelledError): diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index a6a74ab2b9..f22f09c0e7 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -25,6 +25,7 @@ import textwrap import threading import time +import warnings from typing import Any, Optional from unittest import mock @@ -295,7 +296,11 @@ def test_close_after_fork_while_notification_lock_held(self): self.assertIn(executor._stop_condition._lock, _forkable_locks) executor._stop_condition.acquire() # Held across the fork. read_fd, write_fd = os.pipe() - pid = os.fork() + with warnings.catch_warnings(): + # The test forks a multi-threaded process on purpose: the reset + # exists for production forks of exactly this shape. + warnings.simplefilter("ignore", DeprecationWarning) + pid = os.fork() if pid == 0: # The child runs the real hook: no other thread survives the # fork, the state the reset is designed for. diff --git a/test/test_pooling.py b/test/test_pooling.py index 518e902843..8319bc1431 100644 --- a/test/test_pooling.py +++ b/test/test_pooling.py @@ -980,7 +980,7 @@ def close_conn(self, reason): closed.set() pool.conns = [FakeConn(0), FakeConn(1)] - task = asyncio.create_task(pool.close()) + task = asyncio.create_task(pool.close()) # type: ignore[func-returns-value] started.wait() task.cancel() with self.assertRaises(asyncio.CancelledError):