diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index 738609fc0e..7e61e2177b 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -2866,7 +2866,7 @@ tasks: tags: [perf] # Sanitizer tests - - name: test-sanitizer + - name: test-sanitizer-asan commands: - func: run server vars: @@ -2879,6 +2879,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/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 afbe9ae55a..207dd53056 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -407,17 +407,16 @@ 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 - # large distro gives 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( [".sanitizer"], get_variant_name("Sanitizer", host), host=host, - run_on="rhel8.10-large", + run_on="rhel87-large", version=MAX_VERSION, tags=["pr"], ) @@ -748,16 +747,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. + # 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) - 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_sanitizer.py b/.evergreen/scripts/setup_sanitizer.py new file mode 100644 index 0000000000..741282197a --- /dev/null +++ b/.evergreen/scripts/setup_sanitizer.py @@ -0,0 +1,121 @@ +"""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 + +# 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", + "test/test_raw_bson.py", + "test/test_raw_bson_shared.py", + "test/test_client.py", +] + +# 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++" + + +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}. Run the task 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 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"): + ext.unlink() + write_env("CC", CLANG) + 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 + # 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") + 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" + # 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={combined}", + ) + else: + # -fno-sanitize=function: guard against compiler drift (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") + # 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. + # -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/setup_tests.py b/.evergreen/scripts/setup_tests.py index bd0efc550a..a8bc490106 100644 --- a/.evergreen/scripts/setup_tests.py +++ b/.evergreen/scripts/setup_tests.py @@ -12,6 +12,7 @@ from pathlib import Path from urllib import request +import setup_sanitizer from utils import ( DRIVERS_TOOLS, ENV_FILE, @@ -20,7 +21,6 @@ PERF_PYTHON_VERSION, PLATFORM, ROOT, - SANITIZER_PYTHON, TEST_SUITE_MAP, Distro, check_drivers_tools, @@ -60,20 +60,6 @@ # 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, 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), and the hostile-input and boundary tests -# driving the decoder and builders directly. -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 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). @@ -619,42 +605,7 @@ def handle_test_env() -> None: write_env("FUZZ_CORPUS_DIR", str(corpus_dir)) if test_name == "sanitizer": - if PLATFORM != "linux": - raise RuntimeError("The sanitizer tests require the Linux Python toolchain.") - if not Path(SANITIZER_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." - ) - # 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 ASan/UBSan-instrumented toolchain CPython, - # and fail loudly rather than silently skip the C extension build. - write_env("UV_PYTHON", SANITIZER_PYTHON) - write_env("PYMONGO_C_EXT_MUST_BUILD") - # -fno-sanitize=function: the toolchain interpreter's UBSan runtime - # predates the image's clang, whose function check references a - # handler the runtime does not provide (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") - # 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. - # -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_generate_config.py b/.evergreen/scripts/test_generate_config.py index 8e431f1a3f..348a8fc02f 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -756,25 +756,31 @@ def test_sync_option_env_override(monkeypatch): def test_sanitizer_task_wiring(): - """PYTHON-6048: one pr-tagged sanitizer task, selected by exactly one variant. + """PYTHON-6048/PYTHON-6168: pr-tagged sanitizer tasks, selected by one variant. - The variant 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). + Each task is selected by exactly one variant that pins MAX_VERSION and + 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 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 == ["rhel87-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 17fe71906b..50fc872dc4 100644 --- a/.evergreen/scripts/utils.py +++ b/.evergreen/scripts/utils.py @@ -96,6 +96,10 @@ 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 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. NO_RUN_ORCHESTRATION = [ "auth_oidc", @@ -317,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('"', '\\"') @@ -327,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 new file mode 100644 index 0000000000..a8f2442a4a --- /dev/null +++ b/.evergreen/tsan-suppressions.txt @@ -0,0 +1,12 @@ +# PyMongo-specific ThreadSanitizer suppressions. +# +# 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 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/CONTRIBUTING.md b/CONTRIBUTING.md index 43790a3299..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 @@ -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: @@ -518,6 +518,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 +with 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/doc/changelog.rst b/doc/changelog.rst index 49141a8a18..b147d92fb0 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -7,11 +7,17 @@ Changes in Version 4.20.2 (unreleased) Bug fixes ......... +- 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 (`PYTHON-1634`_). - Fixed a bug where :meth:`~gridfs.GridFS.get_version` and :meth:`~gridfs.GridFS.get_last_version` accepted a non-string ``filename`` and treated a dict as query criteria. They now raise :exc:`TypeError` (`PYTHON-6183`_). +.. _PYTHON-1634: https://jira.mongodb.org/browse/PYTHON-1634 .. _PYTHON-6183: https://jira.mongodb.org/browse/PYTHON-6183 Changes in Version 4.20.1 (2026/11/19) diff --git a/pymongo/asynchronous/monitor.py b/pymongo/asynchronous/monitor.py index 7448109fa2..23199bec02 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 @@ -46,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.""" @@ -100,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. @@ -107,9 +117,19 @@ async def close(self) -> None: """ self.gc_safe_close() - async def join(self) -> None: - """Wait for the monitor to stop.""" - await self._executor.join() + async def join(self, timeout: float | None = None) -> None: + """Wait for the monitor to stop. + + :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 + # straggler's socket closes when the reset returns its connection. + self._executor.wake() + await self._executor.join(_EXECUTOR_JOIN_TIMEOUT) def request_check(self) -> None: """If the monitor is sleeping, wake it soon.""" @@ -158,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. @@ -185,14 +210,25 @@ 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: 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, or ``None`` to + wait indefinitely. + """ + start = time.monotonic() + await self._executor.join(timeout) + if timeout is not None: + 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() + 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() @@ -346,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: @@ -409,6 +453,7 @@ def __init__(self, topology: Topology, topology_settings: TopologySettings, pool async def close(self) -> None: self.gc_safe_close() + 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/asynchronous/pool.py b/pymongo/asynchronous/pool.py index 6e3fba6f5a..5fa528edf0 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], # type: ignore[func-returns-value] + 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], # type: ignore[func-returns-value] + return_exceptions=True, + ) ) else: for conn in sockets: @@ -858,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 32138704ec..cc7c1a0815 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, so 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 50100db0c0..1431053f41 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -93,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 = _async_create_lock() self._condition = _async_create_condition( self._lock, self._settings.condition_class if _IS_SYNC else None ) @@ -188,8 +189,7 @@ async def select_servers( else: server_timeout = server_selection_timeout - # Cleanup any completed monitor tasks safely - if not _IS_SYNC and self._monitor_tasks: + if self._monitor_tasks: await self.cleanup_monitors() async with self._lock: @@ -402,9 +402,10 @@ 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() - if not _IS_SYNC: - self._monitor_tasks.append(self._srv_monitor) + # 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(). self._condition.notify_all() @@ -428,6 +429,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) + # 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. if reset_pool: @@ -451,6 +455,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) + # 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: """Return primary's address or None.""" @@ -521,9 +528,10 @@ async def close(self) -> None: async with self._lock: old_td = self._description for server in self._servers.values(): - await server.close() - if not _IS_SYNC: - self._monitor_tasks.append(server._monitor) + # 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() # Mark all servers Unknown. self._description = self._description.reset() @@ -533,13 +541,16 @@ 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._srv_monitor.signal_close() + self._monitor_tasks.append(self._srv_monitor) self._opened = False self._closed = True + # 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: self._description = TopologyDescription( @@ -708,19 +719,45 @@ 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). - if not _IS_SYNC: - self._monitor_tasks.append(server._monitor) + # Record before signaling: signal_close() may be cancelled + # before returning (PYTHON-6226). Joins happen in cleanup_monitors(). + self._monitor_tasks.append(server._monitor) self._servers.pop(address) - await server.close() + await server.signal_close() async def cleanup_monitors(self) -> None: - 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] + """Close monitors signaled earlier while the topology lock was held. + + 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: + # 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: + 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/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/network_layer.py b/pymongo/network_layer.py index e6f14a7e5e..6d44946d2a 100644 --- a/pymongo/network_layer.py +++ b/pymongo/network_layer.py @@ -65,7 +65,9 @@ _UNPACK_HEADER = struct.Struct(" 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 83e574814a..8126fdaac7 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 @@ -87,8 +87,10 @@ 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: - if self._task is not None: + async def join(self, timeout: float | None = None) -> None: + # 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] def wake(self) -> None: @@ -134,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 @@ -179,6 +181,11 @@ 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. + 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}>" @@ -202,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() @@ -245,8 +254,30 @@ def close(self, dummy: Any = None) -> None: callback; see monitor.py. """ self._stopped = True + self._wake_waiter() - def join(self, timeout: int | None = None) -> None: + 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. + """ + # 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): + 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: try: self._thread.join(timeout) @@ -289,10 +320,17 @@ def _run(self) -> None: self._skip_sleep = False else: deadline = time.monotonic() + self._interval - while not self._stopped and time.monotonic() < deadline: - time.sleep(self._min_interval) - 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/pymongo/synchronous/monitor.py b/pymongo/synchronous/monitor.py index aca19b1395..e39ef30ea4 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 @@ -46,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.""" @@ -100,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. @@ -107,9 +117,19 @@ def close(self) -> None: """ self.gc_safe_close() - def join(self) -> None: - """Wait for the monitor to stop.""" - self._executor.join() + def join(self, timeout: float | None = None) -> None: + """Wait for the monitor to stop. + + :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 + # straggler's socket closes when the reset returns its connection. + self._executor.wake() + self._executor.join(_EXECUTOR_JOIN_TIMEOUT) def request_check(self) -> None: """If the monitor is sleeping, wake it soon.""" @@ -158,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. @@ -185,12 +210,25 @@ 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: 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, or ``None`` to + wait indefinitely. + """ + start = time.monotonic() + self._executor.join(timeout) + if timeout is not None: + 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() + 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() @@ -344,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: @@ -407,6 +453,7 @@ def __init__(self, topology: Topology, topology_settings: TopologySettings, pool def close(self) -> None: self.gc_safe_close() + 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/pymongo/synchronous/pool.py b/pymongo/synchronous/pool.py index 28a8811b03..de0dce74c4 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], # type: ignore[func-returns-value] + 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], # type: ignore[func-returns-value] + return_exceptions=True, + ) ) else: for conn in sockets: @@ -856,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 803cb0093c..82723ea7f5 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, so 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 5719bb148d..7a25ee9773 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -93,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 = _create_lock() self._condition = _create_condition( self._lock, self._settings.condition_class if _IS_SYNC else None ) @@ -188,8 +189,7 @@ def select_servers( else: server_timeout = server_selection_timeout - # Cleanup any completed monitor tasks safely - if not _IS_SYNC and self._monitor_tasks: + if self._monitor_tasks: self.cleanup_monitors() with self._lock: @@ -402,9 +402,10 @@ def _process_change( td_old.topology_type == TOPOLOGY_TYPE.Unknown 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) + # 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(). self._condition.notify_all() @@ -428,6 +429,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) + # 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. if reset_pool: @@ -451,6 +455,9 @@ 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 + # the lock (PYTHON-6168). + self.cleanup_monitors() def get_primary(self) -> _Address | None: """Return primary's address or None.""" @@ -519,9 +526,10 @@ def close(self) -> None: with self._lock: old_td = self._description for server in self._servers.values(): - server.close() - if not _IS_SYNC: - self._monitor_tasks.append(server._monitor) + # Signal the executors. Joining them here would block on + # on_change(), which needs this lock. + self._monitor_tasks.append(server._monitor) + server.signal_close() # Mark all servers Unknown. self._description = self._description.reset() @@ -531,13 +539,16 @@ 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._srv_monitor.signal_close() + self._monitor_tasks.append(self._srv_monitor) self._opened = False self._closed = True + # 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: self._description = TopologyDescription( @@ -706,19 +717,45 @@ 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). - if not _IS_SYNC: - self._monitor_tasks.append(server._monitor) + # Record before signaling: signal_close() may be cancelled + # before returning (PYTHON-6226). Joins happen in cleanup_monitors(). + self._monitor_tasks.append(server._monitor) self._servers.pop(address) - server.close() + server.signal_close() def cleanup_monitors(self) -> None: - 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] + """Close monitors signaled earlier while the topology lock was held. + + 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: + # 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: + 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/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..92078b9049 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()) @@ -829,6 +829,150 @@ async def close_victim(): self.assertTrue(victim.pool.closed) +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. + 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, []) + + @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_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. + topology = await create_mock_topology("mongodb://a:27017,b:27017") + first = topology._servers[("a", 27017)]._monitor + second = topology._servers[("b", 27017)]._monitor + 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() + + def fast_close(): + second_done.set() + else: + in_flight = asyncio.Event() + second_done = asyncio.Event() + + async def slow_close(): + in_flight.set() + await asyncio.sleep(0.2) + 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) + 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. + if _IS_SYNC: + in_flight.wait() + else: + await in_flight.wait() + topology._monitor_tasks.append(second) + if _IS_SYNC: + second_appended.set() + drain.join(timeout=5) + else: + await drain + + 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/asynchronous/test_monitor.py b/test/asynchronous/test_monitor.py index 7648ddcacc..f96a4c4dc9 100644 --- a/test/asynchronous/test_monitor.py +++ b/test/asynchronous/test_monitor.py @@ -20,16 +20,19 @@ import gc import subprocess import sys +import time import warnings from functools import partial 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, @@ -108,6 +111,49 @@ 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. + + 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 + + sync_wait_until(lambda: thread_alive(monitor._executor), "monitor thread never started") + + client.close() + + 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()) + # 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): """Test we silence noisy runtime errors. @@ -129,5 +175,56 @@ 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: + # time.sleep on purpose: synchro 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/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index ff70125334..bd500b0d7c 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -19,10 +19,13 @@ import asyncio import importlib import os +import select +import signal import sys import textwrap import threading import time +import warnings from typing import Any, Optional from unittest import mock @@ -180,6 +183,172 @@ 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_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_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 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. 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() # Held across the fork. + read_fd, write_fd = os.pipe() + 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. + 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) + + @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/asynchronous/test_pooling.py b/test/asynchronous/test_pooling.py index 54746d7b44..679d76f531 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()) # type: ignore[func-returns-value] + 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/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..86abe6e344 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()) @@ -824,6 +824,149 @@ def close_victim(): self.assertTrue(victim.pool.closed) +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. + 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, []) + + @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_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. + topology = create_mock_topology("mongodb://a:27017,b:27017") + first = topology._servers[("a", 27017)]._monitor + second = topology._servers[("b", 27017)]._monitor + 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() + + def fast_close(): + second_done.set() + else: + in_flight = asyncio.Event() + second_done = asyncio.Event() + + def slow_close(): + in_flight.set() + time.sleep(0.2) + 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) + 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. + if _IS_SYNC: + in_flight.wait() + else: + in_flight.wait() + topology._monitor_tasks.append(second) + if _IS_SYNC: + second_appended.set() + drain.join(timeout=5) + else: + drain + + 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_monitor.py b/test/test_monitor.py index c06833020e..5f932c0747 100644 --- a/test/test_monitor.py +++ b/test/test_monitor.py @@ -20,16 +20,19 @@ import gc import subprocess import sys +import time import warnings from functools import partial 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, @@ -104,6 +107,49 @@ 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. + + 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 + + sync_wait_until(lambda: thread_alive(monitor._executor), "monitor thread never started") + + client.close() + + 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()) + # 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): """Test we silence noisy runtime errors. @@ -125,5 +171,56 @@ 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: + # time.sleep on purpose: synchro 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_periodic_executor.py b/test/test_periodic_executor.py index 10306fc06a..f22f09c0e7 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -19,10 +19,13 @@ import asyncio import importlib import os +import select +import signal import sys import textwrap import threading import time +import warnings from typing import Any, Optional from unittest import mock @@ -179,6 +182,172 @@ 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_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_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 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. 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() # Held across the fork. + read_fd, write_fd = os.pipe() + 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. + 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) + + @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. diff --git a/test/test_pooling.py b/test/test_pooling.py index 6da69cc41b..8319bc1431 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()) # type: ignore[func-returns-value] + 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() diff --git a/test/test_raw_bson_shared.py b/test/test_raw_bson_shared.py index d2006919f0..8f38506d1b 100644 --- a/test/test_raw_bson_shared.py +++ b/test/test_raw_bson_shared.py @@ -17,6 +17,7 @@ import gc import pickle import sys +import threading import unittest import uuid @@ -40,6 +41,20 @@ b"\x00\x00\x00\x02street\x00\r\x00\x00\x00Baker Street\x00\x00\x00\x00" ) +N_THREADS = 16 +N_ITERS = 200 +BIG_PAYLOAD = "x" * 8000 + + +def _make_shared_doc_bytes() -> 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. @@ -323,5 +338,140 @@ 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. + + These tests also run under the sanitizer CI tasks (see SANITIZER_FILES in + .evergreen/scripts/setup_sanitizer.py). + """ + + def test_concurrent_reads_on_shared_document(self): + doc_bytes = _make_shared_doc_bytes() + shared_doc = RawBSONDocument(doc_bytes) + + 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"] + 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): + self.assertEqual(item["idx"], j) + self.assertEqual(item["payload"], BIG_PAYLOAD) + + small = shared_doc["small"] + self.assertEqual(small["n"], 1) + + # Re-encode while other threads still read the same buffer. + reencoded = encode({"again": big}) + self.assertIsInstance(reencoded, bytes) + + multi = decode_all(doc_bytes * 2, DEFAULT_RAW_BSON_OPTIONS) + self.assertEqual(len(multi), 2) + for d in multi: + self.assertIsInstance(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): + 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) + # 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: + """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()