diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index 7af1cb25a4..2bcc195224 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -2844,6 +2844,22 @@ tasks: - func: send dashboard data tags: [perf] + # Sanitizer tests + - name: test-sanitizer + commands: + - func: run server + vars: + AUTH: noauth + SSL: nossl + TOPOLOGY: standalone + - func: run tests + vars: + AUTH: noauth + SSL: nossl + TOPOLOGY: standalone + TEST_NAME: sanitizer + tags: [sanitizer, pr] + # Search index tests - name: test-search-index-helpers commands: diff --git a/.evergreen/generated_configs/variants.yml b/.evergreen/generated_configs/variants.yml index 2e5a496a13..d2b382a28b 100644 --- a/.evergreen/generated_configs/variants.yml +++ b/.evergreen/generated_configs/variants.yml @@ -530,6 +530,17 @@ buildvariants: SUB_TEST_NAME: pyopenssl tags: [pr] + # Sanitizer tests + - name: sanitizer-rhel8 + tasks: + - name: .sanitizer + display_name: Sanitizer RHEL8 + run_on: + - rhel8.10-large + expansions: + VERSION: "9.0" + tags: [pr] + # Search index tests - name: search-index-helpers-rhel8 tasks: diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index c072c32721..3b45e52971 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -527,6 +527,24 @@ def create_fuzz_variants(): return [pr_variant, nightly] +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. + host = DEFAULT_HOST + return [ + create_variant( + [".sanitizer"], + get_variant_name("Sanitizer", host), + host=host, + run_on="rhel8.10-large", + version=MAX_VERSION, + tags=["pr"], + ) + ] + + def create_atlas_connect_variants(): host = DEFAULT_HOST return [ @@ -943,6 +961,19 @@ def create_fuzz_tasks(): return 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. + 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])] + + def create_kms_tasks(): tasks = [] for kms_type in ["gcp", "azure"]: diff --git a/.evergreen/scripts/setup_tests.py b/.evergreen/scripts/setup_tests.py index 44d4d77d2a..2bd101bf36 100644 --- a/.evergreen/scripts/setup_tests.py +++ b/.evergreen/scripts/setup_tests.py @@ -18,6 +18,7 @@ PERF_PYTHON_VERSION, PLATFORM, ROOT, + SANITIZER_PYTHON, TEST_SUITE_MAP, Distro, check_drivers_tools, @@ -56,6 +57,18 @@ # Map the test name to test group. GROUP_MAP = dict(fuzz="fuzz", mockupdb="mockupdb", perf="perf") +# The test files run under ASan/UBSan (PYTHON-6048). They exercise the +# buffer-protocol acquisition path in bson/_cbsonmodule.c +# (_get_buffer/_prepare_input_buffer) and the wire-message builders in +# pymongo/_cmessagemodule.c (_op_msg, _batched_op_msg, +# _encode_batched_write_command). +SANITIZER_FILES = [ + "test/test_bson.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). @@ -536,6 +549,38 @@ def handle_test_env() -> None: zip_path.unlink() 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") + write_env("CFLAGS", "-fsanitize=address,undefined -fno-omit-frame-pointer -g -O1") + write_env("LDFLAGS", "-fsanitize=address,undefined") + # CPython's pymalloc trips LeakSanitizer with false positives. + write_env("ASAN_OPTIONS", "detect_leaks=0") + # UBSan only warns by default; make undefined behavior fail the task. + write_env("UBSAN_OPTIONS", "halt_on_error=1:print_stacktrace=1") + # The toolchain interpreter self-initializes the sanitizer runtimes, + # so no LD_PRELOAD: gcc's libasan.so is a linker script that ld.so + # cannot preload, and preloading a mismatched runtime would mix two + # sanitizers in one process. + # -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 + # Add coverage if requested. if opts.cov: # Keep in sync with combine-coverage.sh. diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index f078f2f305..51b67da1d5 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -112,17 +112,21 @@ def test_pr_tasks_effectively_pin_max_version(): def test_server_version_pr_tasks_selected_once(): - """The mongodb-* variants differ only in server version, so a pr task - must be selected only by the variant running the server version it pins.""" + """A pr server-version task must be selected only by the variant running + the server version it pins. The expected family comes from + create_server_version_variants(), not from the selections: a variant + missing its PR selector would otherwise drop from both sides and the + comparison would pass. Variants outside the family must not select these + tasks (the sanitizer variant pins MAX_VERSION for its own mongod).""" + sv_tasks = [task for task in pr_tasks() if "server-version" in (task.tags or [])] + sv_variants = generate_config.create_server_version_variants() offenders = {} - for task in pr_tasks(): - if "server-version" not in (task.tags or []): - continue + for task in sv_tasks: own = task_vars(task).get("VERSION") selecting = [variant.name for variant in all_variants() if variant_selects(variant, task)] matching = [ variant.name - for variant in all_variants() + for variant in sv_variants if (variant.expansions or {}).get("VERSION") == own ] if selecting != matching: @@ -276,3 +280,26 @@ def test_non_standard_cov_tasks_have_no_cov_companions(): elif "cov" in (task.tags or []) and "test-non-standard" in (task.tags or []): companion = task.name.removesuffix("-cov") assert companion in no_cov, f"missing no-cov companion for {task.name}" + + +def test_sanitizer_task_wiring(): + """PYTHON-6048: one pr-tagged sanitizer task, selected by exactly one + variant that pins MAX_VERSION and runs on a large host for ASan's memory + headroom. VERSION stays off the task so it is exempt + from the pr COVERAGE rule (coverage under ASan is not useful).""" + 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 diff --git a/.evergreen/scripts/utils.py b/.evergreen/scripts/utils.py index 5b7da0f5a3..285ade7892 100644 --- a/.evergreen/scripts/utils.py +++ b/.evergreen/scripts/utils.py @@ -48,6 +48,7 @@ class Distro: "mockupdb": "mockupdb", "ocsp": "ocsp", "perf": "perf", + "sanitizer": "", "sfp": "sfp", "numpy": "", } @@ -89,6 +90,10 @@ class Distro: # The managed Python version used for perf tests (PYTHON-6135). PERF_PYTHON_VERSION = "3.11.9" +# The ASan/UBSan-instrumented toolchain CPython used by the sanitizer task +# (PYTHON-6048), built by mongo-python-toolchain (PYTHON-6067). Linux only. +SANITIZER_PYTHON = "/opt/python/3.14-asan-ubsan/bin/python3" + # Tests that do not use run-mongodb directly. NO_RUN_ORCHESTRATION = [ "auth_oidc", diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e683cbc5d1..6bf693bdef 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -500,6 +500,20 @@ CPython version whose toolchain dir exists, `UV_PYTHON_SEARCH_PATH` points uv at diff to confirm the `pr` tags. - Make sure to add instructions for running the test suite to `CONTRIBUTING.md`. +### Sanitizer tests + +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 +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: + + just run-server + just setup-tests sanitizer + 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/bson/buffer.c b/bson/buffer.c index 68a8fe3590..c7df462980 100644 --- a/bson/buffer.c +++ b/bson/buffer.c @@ -85,11 +85,16 @@ static int buffer_grow(buffer_t buffer, int min_length) { } while (size < min_length) { old_size = size; - size *= 2; - if (size <= old_size) { - /* Size did not increase. Could be an overflow - * or size < 1. Just go with min_length. */ - size = min_length; + if (size > INT_MAX / 2) { + /* Doubling `size` would overflow `int`; grow to exactly + * min_length instead. */ + size = min_length; + } else { + size *= 2; + if (size <= old_size) { + /* Size did not increase. Could be size < 1. */ + size = min_length; + } } } buffer->buffer = (char*)realloc(buffer->buffer, sizeof(char) * size); diff --git a/doc/changelog.rst b/doc/changelog.rst index 8a21b8b4e8..6985dca50f 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -49,6 +49,9 @@ Bug fixes member removed itself from the topology with its own ``hello`` response (for example, during a node restart): the monitor's executor cancelled its own task, so the monitor never ran again (`PYTHON-6226`_). +- Fixed undefined behavior in the C extension's BSON buffer growth: growing + an encode buffer past 1GiB doubled a signed integer past its limit. + Over-limit encodes still raise ``ValueError`` (`PYTHON-6252`_). .. _PYTHON-5929: https://jira.mongodb.org/browse/PYTHON-5929 .. _PYTHON-5959: https://jira.mongodb.org/browse/PYTHON-5959 @@ -58,6 +61,7 @@ Bug fixes .. _PYTHON-6145: https://jira.mongodb.org/browse/PYTHON-6145 .. _PYTHON-6182: https://jira.mongodb.org/browse/PYTHON-6182 .. _PYTHON-6226: https://jira.mongodb.org/browse/PYTHON-6226 +.. _PYTHON-6252: https://jira.mongodb.org/browse/PYTHON-6252 Changes in Version 4.19.0 (2026/10/14) -------------------------------------- diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index bfa0c2275a..896dbba15c 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -200,7 +200,7 @@ async def target(): assert isinstance(started, asyncio.Event) await asyncio.wait_for(started.wait(), timeout=2) - close_error: Optional[BaseException] = None + close_error: BaseException | None = None def close_off_loop(): nonlocal close_error diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index e1eaf0e9e8..9523ceaeda 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -199,7 +199,7 @@ def target(): assert isinstance(started, asyncio.Event) asyncio.wait_for(started.wait(), timeout=2) - close_error: Optional[BaseException] = None + close_error: BaseException | None = None def close_off_loop(): nonlocal close_error