Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
c30acd5
PYTHON-1634 Join monitor threads on MongoClient close
blink1073 Nov 17, 2026
b593991
PYTHON-6168 Add a thread sanitizer test
blink1073 Nov 17, 2026
9eae0c9
Merge remote-tracking branch 'upstream/main' into PYTHON-6168
blink1073 Nov 18, 2026
3bd1f1f
code cleanup
blink1073 Nov 18, 2026
70cf9f0
Refactor sanitizer setup into setup_sanitizer.py
blink1073 Nov 18, 2026
da0d6f9
Fix the sanitizer extension builds
blink1073 Nov 19, 2026
a86a563
Merge remote-tracking branch 'upstream/main' into PYTHON-6168
blink1073 Nov 19, 2026
3cbb36c
Remove sanitizer setup tests and apply coding-standards audit fixes
blink1073 Nov 19, 2026
9e1e604
Clean up dash separators and via in PR prose
blink1073 Nov 19, 2026
335e28f
Pin the sanitizer compiler and run on rhel87-large
blink1073 Nov 19, 2026
daf8f91
Trim comment prose
blink1073 Nov 19, 2026
6f18a97
Load the toolchain's TSan suppressions
blink1073 Nov 19, 2026
7a0a4ea
Defer monitor joins outside the topology lock
blink1073 Nov 19, 2026
fef42a5
Add a self-join regression test
blink1073 Nov 19, 2026
bbed14c
Harden the deferred monitor shutdown
blink1073 Nov 19, 2026
78cb1dd
Serialize monitor cleanup
blink1073 Nov 19, 2026
0166766
Fix the sync cleanup lock
blink1073 Nov 19, 2026
85e709f
Merge remote-tracking branch 'upstream/main' into PYTHON-6168
blink1073 Nov 19, 2026
d6e164b
fix tests
blink1073 Nov 19, 2026
faea677
fix tests
blink1073 Nov 19, 2026
76df144
address review with regression test
blink1073 Nov 19, 2026
bab201f
Make the sync cleanup acquire atomic
blink1073 Nov 19, 2026
70f4345
Make the sync executor wakeable and reads cancellable promptly
blink1073 Nov 20, 2026
d0ac308
Merge remote-tracking branch 'upstream/main' into PYTHON-6168
blink1073 Nov 20, 2026
c276f30
Harden the executor stop signal.
blink1073 Nov 20, 2026
d05da11
Skip the fork-tracking test without at-fork support
blink1073 Nov 20, 2026
9eb1b59
Shield the pool close from cancelled callers
blink1073 Nov 20, 2026
6417e48
clean up prose
blink1073 Nov 20, 2026
9bdf1b1
Restore pool type ignores and isolate the fork test
blink1073 Nov 20, 2026
0c46672
Fix shutdown and fork-test failures on newer Pythons
blink1073 Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion .evergreen/generated_configs/tasks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2866,7 +2866,7 @@ tasks:
tags: [perf]

# Sanitizer tests
- name: test-sanitizer
- name: test-sanitizer-asan
commands:
- func: run server
vars:
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion .evergreen/generated_configs/variants.yml
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ buildvariants:
- name: .sanitizer
display_name: Sanitizer RHEL8
run_on:
- rhel8.10-large
- rhel87-large
expansions:
VERSION: "9.0"
tags: [pr]
Expand Down
27 changes: 15 additions & 12 deletions .evergreen/scripts/generate_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
)
Expand Down Expand Up @@ -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():
Expand Down
121 changes: 121 additions & 0 deletions .evergreen/scripts/setup_sanitizer.py
Original file line number Diff line number Diff line change
@@ -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
53 changes: 2 additions & 51 deletions .evergreen/scripts/setup_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from pathlib import Path
from urllib import request

import setup_sanitizer
from utils import (
DRIVERS_TOOLS,
ENV_FILE,
Expand All @@ -20,7 +21,6 @@
PERF_PYTHON_VERSION,
PLATFORM,
ROOT,
SANITIZER_PYTHON,
TEST_SUITE_MAP,
Distro,
check_drivers_tools,
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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:
Expand Down
44 changes: 25 additions & 19 deletions .evergreen/scripts/test_generate_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
10 changes: 7 additions & 3 deletions .evergreen/scripts/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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('"', '\\"')
Expand All @@ -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:
Expand Down
12 changes: 12 additions & 0 deletions .evergreen/tsan-suppressions.txt
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading