From d4f7bddb457c4821890ab764baf320459615ea2f Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 10:51:16 -0600 Subject: [PATCH 01/16] PYTHON-6169 Add native ASan-instrumented BSON fuzzing --- .evergreen/generated_configs/tasks.yml | 19 +++ .evergreen/generated_configs/variants.yml | 8 +- .evergreen/scripts/generate_config.py | 42 ++++-- .evergreen/scripts/test_generate_config.py | 70 +++++++-- AGENTS.md | 2 +- fuzz/README.md | 31 +++- fuzz/build_native.sh | 94 ++++++++++++ fuzz/fuzz_decode.py | 92 ++++++------ fuzz/fuzz_decode_all.py | 82 ++++++----- fuzz/fuzz_is_valid.py | 46 +++--- fuzz/fuzz_shared.py | 24 ++- fuzz/run_native.sh | 73 ++++++++++ test/test_fuzz_shared.py | 162 +++++++++++++++++++++ 13 files changed, 617 insertions(+), 128 deletions(-) create mode 100755 fuzz/build_native.sh create mode 100755 fuzz/run_native.sh create mode 100644 test/test_fuzz_shared.py diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index 00ac5416da..b5abdae70e 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -205,6 +205,25 @@ tasks: depends_on: [{ name: .server-version, variant: .coverage_tag, status: "*", patch_optional: true }] tags: [coverage, pr] + # Fuzz native tests + - name: fuzz-native + commands: + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/build_native.sh + working_dir: src + type: test + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/run_native.sh + working_dir: src + type: test + tags: [fuzz, fuzz-native] + # Fuzz tests - name: fuzz-regression commands: diff --git a/.evergreen/generated_configs/variants.yml b/.evergreen/generated_configs/variants.yml index f624b89e6e..bdf0a8f734 100644 --- a/.evergreen/generated_configs/variants.yml +++ b/.evergreen/generated_configs/variants.yml @@ -206,21 +206,23 @@ buildvariants: - name: .fuzz-regression display_name: Fuzz Regression RHEL8 run_on: - - rhel8.10-small + - rhel8.7-large tags: [pr] - name: fuzz-rhel8 tasks: - name: .fuzz-nightly + - name: .fuzz-regression + - name: .fuzz-native display_name: Fuzz RHEL8 run_on: - - rhel8.10-small + - rhel8.7-large batchtime: 1440 - name: fuzz-capture-rhel8 tasks: - name: .fuzz-weekly display_name: Fuzz Capture RHEL8 run_on: - - rhel8.10-small + - rhel8.7-large batchtime: 10080 # Green framework tests diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index 061f9bc0a6..18019586b4 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -389,25 +389,37 @@ def create_doctests_variants(): def create_fuzz_variants(): - # Three variants for the three fuzz flows: the regression reproducers run - # on every PR, the time-boxed fuzzing for crash discovery runs nightly, - # and the weekly variant also captures the corpus (opens the automated - # [Fuzz Corpus] PR). The non-pr variants carry no "pr" tag, so PR patch - # builds never select them, while their default patchability keeps them - # manually runnable (`evergreen patch --variant fuzz-rhel8 --task fuzz`). - # The host needs CPython, which the rhel8 toolchain provides. + # Three variants for the fuzz flows: the regression reproducers run + # on every PR, the daily variant fuzzes for crash discovery and runs + # the native ASan fuzzing (PYTHON-6169), and the weekly variant also + # captures the corpus (opens the automated [Fuzz Corpus] PR). The + # non-pr variants carry no "pr" tag, so PR patch builds never select + # them, while their default patchability keeps them manually runnable + # (`evergreen patch --variant fuzz-rhel8 --task fuzz`). The host needs + # CPython, which the rhel8 toolchain provides; the large rhel8.7 distro + # matches the other drivers' fuzz jobs and fits libFuzzer's growing + # corpus. host = HOSTS["rhel8"] return [ create_variant( - [".fuzz-regression"], get_variant_name("Fuzz Regression", host), host=host, tags=["pr"] + [".fuzz-regression"], + get_variant_name("Fuzz Regression", host), + host=host, + run_on="rhel8.7-large", + tags=["pr"], ), create_variant( - [".fuzz-nightly"], get_variant_name("Fuzz", host), host=host, batchtime=BATCHTIME_DAY + [".fuzz-nightly", ".fuzz-regression", ".fuzz-native"], + get_variant_name("Fuzz", host), + host=host, + run_on="rhel8.7-large", + batchtime=BATCHTIME_DAY, ), create_variant( [".fuzz-weekly"], get_variant_name("Fuzz Capture", host), host=host, + run_on="rhel8.7-large", batchtime=BATCHTIME_WEEK, ), ] @@ -762,6 +774,18 @@ def create_fuzz_tasks(): return tasks +def create_fuzz_native_tasks(): + # Native ASan-instrumented fuzzing (PYTHON-6169). Plain subprocess.exec: + # the "run tests" function would reinstall pymongo without sanitizer + # flags and clobber the instrumented build. + tags = ["fuzz", "fuzz-native"] + commands = [ + get_subprocess_exec(args=["fuzz/build_native.sh"]), + get_subprocess_exec(args=["fuzz/run_native.sh"]), + ] + return [EvgTask(name="fuzz-native", tags=tags, commands=commands)] + + 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. diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 602e84e3e5..36a0d29af0 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -444,37 +444,49 @@ def test_fuzz_task_wiring(): """Test the fuzz task wiring. Three fuzz flows: the pr-tagged regression variant runs the reproducers - on every PR; the nightly variant fuzzes for crash discovery; the weekly - variant also captures the corpus. The non-pr variants carry no "pr" tag, - so PR patch builds never select them, while their default patchability - keeps them manually runnable - (`evergreen patch --variant fuzz-rhel8 --task fuzz`). + on every PR; the nightly variant fuzzes for crash discovery and runs + the native ASan fuzzing (PYTHON-6169); the weekly variant also captures + the corpus. The non-pr variants carry no "pr" tag, so PR patch builds + never select them, while their default patchability keeps them manually + runnable (`evergreen patch --variant fuzz-rhel8 --task fuzz`). """ - tasks = [task for task in all_tasks() if "fuzz" in (task.tags or [])] - assert [task.name for task in tasks if "pr" in (task.tags or [])] == ["fuzz-regression"] - assert [task.name for task in tasks if "pr" not in (task.tags or [])] == [ + tasks = {task.name: task for task in all_tasks() if "fuzz" in (task.tags or [])} + assert sorted(task.name for task in tasks.values() if "pr" in (task.tags or [])) == [ + "fuzz-regression" + ] + assert sorted(task.name for task in tasks.values() if "pr" not in (task.tags or [])) == [ "fuzz", "fuzz-capture", + "fuzz-native", ] variants = generate_config.create_fuzz_variants() assert len(variants) == 3 regression, nightly, capture_variant = variants - assert variant_selects(regression, tasks[0]) + assert variant_selects(regression, tasks["fuzz-regression"]) assert "pr" in (regression.tags or []) - assert variant_selects(nightly, tasks[1]) + # The nightly variant runs the whole daily fuzz family, so one patch + # build covers it: crash-discovery fuzzing, the regression replay, and + # the native ASan fuzzing (PYTHON-6169). + assert variant_selects(nightly, tasks["fuzz"]) + assert variant_selects(nightly, tasks["fuzz-native"]) + assert not variant_selects(nightly, tasks["fuzz-capture"]) assert nightly.batchtime == generate_config_utils.BATCHTIME_DAY - assert variant_selects(capture_variant, tasks[2]) + assert variant_selects(capture_variant, tasks["fuzz-capture"]) assert capture_variant.batchtime == generate_config_utils.BATCHTIME_WEEK + # The fuzz family runs on the large rhel8.7 distro, like the other + # drivers' fuzz jobs. + for variant in (regression, nightly, capture_variant): + assert variant.run_on == ["rhel8.7-large"] # Webhook PR patch builds only select pr-tagged variants. assert not nightly.tags assert not capture_variant.tags # The nightly fuzz task is crash discovery only: its last command is # the "run tests" FunctionCall, with no capture command. - assert tasks[1].commands[-1].func == "run tests" + assert tasks["fuzz"].commands[-1].func == "run tests" # The capture subprocess bootstraps the comment-bot github app, whose # secrets live in AWS Secrets Manager: it needs the assumed-role # credentials (as resync_specs and backport-pr also pass them). - capture = tasks[2].commands[-1] + capture = tasks["fuzz-capture"].commands[-1] env_vars = capture.params["include_expansions_in_env"] for var in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"): assert var in env_vars, f"capture subprocess missing {var}" @@ -789,3 +801,35 @@ def test_sanitizer_task_wiring(): assert len(variants) == 1 assert variants[0].run_on == ["rhel8.10-large"] assert (variants[0].expansions or {}).get("VERSION") == generate_config_utils.MAX_VERSION + + +def test_fuzz_native_task_wiring(): + """Run the daily fuzz-native task's scripts with plain subprocess.exec. + + The "run tests" function would reinstall pymongo without sanitizer + flags and clobber the instrumented build. The task runs in the nightly + Fuzz RHEL8 variant alongside the other fuzz tasks. + """ + tasks = [task for task in all_tasks() if "fuzz-native" in (task.tags or [])] + assert len(tasks) == 1 + task = tasks[0] + assert "pr" not in task.tags + # Plain subprocess.exec only: no FunctionCall ("run tests") anywhere. + assert all(getattr(cmd, "func", None) is None for cmd in task.commands) + args = [cmd.params["args"] for cmd in task.commands] + assert args == [["fuzz/build_native.sh"], ["fuzz/run_native.sh"]] + # The get_subprocess_exec defaults: bash, from the src dir. + assert all(cmd.params["binary"] == "bash" for cmd in task.commands) + assert all(cmd.params["working_dir"] == "src" for cmd in task.commands) + variants = [v for v in all_variants() if variant_selects(v, task)] + assert len(variants) == 1 + variant = variants[0] + assert variant.batchtime == generate_config_utils.BATCHTIME_DAY + assert variant.run_on == ["rhel8.7-large"] + # All the fuzz tasks share one nightly variant, so one patch build + # covers the whole family. + assert [ref.name for ref in variant.tasks] == [ + ".fuzz-nightly", + ".fuzz-regression", + ".fuzz-native", + ] diff --git a/AGENTS.md b/AGENTS.md index b11b8c09da..cd101b41ba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ Official Python driver for MongoDB. - `test/asynchronous/` — async test suite - `test/` — sync test suite (generated from `test/asynchronous/` by `just synchro`) and shared test suite - `test/unified_format/` — cross-driver spec tests (Unified Test Format) -- `fuzz/` — BSON fuzz tests (not pytest; see `fuzz/README.md`) +- `fuzz/` — BSON fuzz tests, including native ASan fuzzing (not pytest; see `fuzz/README.md`) Do not edit files in `pymongo/synchronous/` or mirrored files in `test/` directly: they are generated by `just synchro` from `pymongo/asynchronous/` and `test/asynchronous/`. A file in `test/` is mirrored if a file of the same name exists in `test/asynchronous/`. diff --git a/fuzz/README.md b/fuzz/README.md index 979f4a7065..76b11be34d 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -95,7 +95,7 @@ uv run --group fuzz python fuzz/fuzz_decode.py /tmp/fuzz-corpus -max_total_time= Pass any [libFuzzer flags](https://llvm.org/docs/LibFuzzer.html#options) after the corpus directory. The `Failed to find function __sanitizer_*` startup warnings are benign libFuzzer symbol probes on uninstrumented runs; -native ASan-instrumented fuzzing is tracked separately (PYTHON-6169). +for instrumented native runs see "Native ASan fuzzing" below. ### Captured corpus (weekly) @@ -139,15 +139,44 @@ The run count equals the file count: replaying individual files (not a corpus directory) performs no empty-input warmup, and letting the budget reach zero gives atheris a graceful exit so coverage.py can flush its report. +## Native ASan fuzzing (PYTHON-6169) + +Atheris instruments only Python code, so memory-safety bugs in +`bson/_cbsonmodule.c` are invisible to it. Rebuild the C extensions with +ASan and run the same three targets under libFuzzer. Requires Linux x86_64 +with a preinstalled clang (atheris ships Linux x86_64 wheels only); no +packages are installed: + +```bash +bash fuzz/build_native.sh # instrumented build into the project venv +FUZZ_MAX_TIME=60 bash fuzz/run_native.sh # time-boxed run over the seed corpus +``` + +The runner sets `FUZZ_NATIVE=1` (the targets skip atheris's own +libFuzzer), `LD_PRELOAD`s atheris's `asan_with_fuzzer.so`, and sets +`PYTHONMALLOC=malloc` so ASan has per-object redzones. Inputs are also +decoded through a sentinel-free `array.array`: `bytes` ends in CPython's +hidden NUL sentinel, which hides over-reads from ASan (the PYTHON-6110 +masking). Leak detection is off (`ASAN_OPTIONS=detect_leaks=0`), the +same as the sanitizer tests (PYTHON-6048). Like the weekly capture run, +the corpus seeds from the spec seed corpus plus the committed `corpus/` +units. + +The `fuzz-native` Evergreen task runs both scripts daily on RHEL8 with +pinned CPython 3.13; it runs in the nightly `Fuzz RHEL8` variant alongside +the other fuzz tasks. + ## Files ``` build_corpus.py Seed corpus builder (mirrors the Go driver's build-oss-fuzz-corpus) +build_native.sh Rebuild the C extensions with ASan + libFuzzer instrumentation capture_corpus.py Weekly capture of new coverage-increasing inputs (PYTHON-6178) fuzz_decode.py Fuzz target: bson.decode() fuzz_decode_all.py Fuzz target: bson.decode_all() fuzz_is_valid.py Fuzz target: bson.is_valid() fuzz_shared.py Code shared by the fuzz targets +run_native.sh Run the targets against an instrumented build under libFuzzer corpus/ Captured coverage-increasing inputs; grown by automated weekly PRs regression/ Known bug reproducers; run with the seed corpus on PRs ``` diff --git a/fuzz/build_native.sh b/fuzz/build_native.sh new file mode 100755 index 0000000000..c1077f797d --- /dev/null +++ b/fuzz/build_native.sh @@ -0,0 +1,94 @@ +#!/bin/bash +# Rebuild the C extensions with ASan + libFuzzer instrumentation and install +# the instrumented package into the project venv (PYTHON-6169). +# +# Requires Linux x86_64 (atheris wheel constraint) and a preinstalled clang. +# This script does not install packages. Run from the repository root: +# bash fuzz/build_native.sh +set -euo pipefail + +ROOT=$(git rev-parse --show-toplevel) +cd "$ROOT" + +PYVER="${FUZZ_NATIVE_PYTHON:-3.13}" + +if [ "$(uname -s)" != "Linux" ] || [ "$(uname -m)" != "x86_64" ]; then + echo "ERROR: native fuzzing requires Linux x86_64 (atheris wheel constraint)." >&2 + exit 1 +fi + +CC="${CC:-clang}" +if ! command -v "$CC" > /dev/null 2>&1; then + echo "ERROR: clang not found ('$CC'). Native fuzzing needs a clang toolchain." >&2 + echo "Install clang on the host or image. This script does not install packages." >&2 + exit 1 +fi + +if ! command -v uv > /dev/null 2>&1; then + echo "ERROR: uv not found. Install uv or add its bin dir (PYMONGO_BIN_DIR," >&2 + echo '$HOME/.local/bin on Evergreen hosts) to PATH.' >&2 + exit 1 +fi + +# Sync the venv: atheris plus a regular (non-instrumented) pymongo install. +uv sync --group fuzz --python "$PYVER" + +# setuptools for the direct build_ext invocation below (uv venvs omit it). +uv pip install --python ".venv/bin/python" setuptools + +# Clear stale C artifacts: build_ext reuses them by mtime, and a plain +# same-version CPython build shares the ABI tag (as in PYTHON-6048). +rm -rf build +rm -f bson/*.so pymongo/*.so + +# Compile the extensions instrumented, directly and visibly: uv builds +# directory sources from a cached copy of the tree that contains the .so +# files built during `uv sync`, so a `uv pip install` can package the +# non-instrumented extensions without invoking the compiler (PYTHON-6169). +# Build failures and flag mismatches are then visible in the log. +export CC +export CFLAGS="-fsanitize=address,fuzzer-no-link -fno-omit-frame-pointer -g -O1" +export LDFLAGS="-fsanitize=address,fuzzer-no-link" +export LDSHARED="$CC -shared" +export PYMONGO_C_EXT_MUST_BUILD=1 +.venv/bin/python _setup.py build_ext -i + +# Overwrite the venv's C extensions with the instrumented ones, bypassing +# uv's wheel build and its cached, non-instrumented copy. +SITE_PACKAGES=$(ls -d .venv/lib/python3.*/site-packages) +cp -f bson/*.so "$SITE_PACKAGES/bson/" +cp -f pymongo/*.so "$SITE_PACKAGES/pymongo/" + +# Verify the instrumented build landed. The smoke import below (under the +# preloaded runtime) is the authoritative check. The nm symbol check is a +# diagnostic only. clang's -shared -fsanitize=address embeds the ASan +# runtime, which can hide __asan symbols from nm output depending on linker +# mode (PYTHON-6169). +SO=$(ls "$SITE_PACKAGES"/bson/_cbson*.so) + +ATHERIS_DIR=$(.venv/bin/python -c 'import atheris; print(atheris.path())') +if [ ! -f "$ATHERIS_DIR/asan_with_fuzzer.so" ]; then + echo "ERROR: $ATHERIS_DIR/asan_with_fuzzer.so is missing. atheris could not provide the runtime." >&2 + exit 1 +fi + +# Smoke: the instrumented extension must import under the preloaded runtime. +if ! FUZZ_NATIVE=1 LD_PRELOAD="$ATHERIS_DIR/asan_with_fuzzer.so" \ + ASAN_OPTIONS="detect_leaks=0" \ + .venv/bin/python -c "import bson; assert bson.has_c()"; then + echo "ERROR: the instrumented extension failed to import under the ASan runtime." >&2 + exit 1 +fi + +if ! nm "$SO" 2>/dev/null | grep -E "__asan|__sanitizer_cov|check_load_add|check_store_add" > /dev/null; then + echo "WARNING: $SO shows no ASan/sancov symbols with nm. The smoke import" >&2 + echo "passed, so the extension works, but instrumentation is unproven." >&2 + echo "--- diagnostics:" >&2 + file "$SO" >&2 || true + sha256sum "$SO" bson/_cbson*.so >&2 || true + nm "$SO" 2>&1 | head -40 >&2 || true + readelf -d "$SO" 2>&1 | head -15 >&2 || true +fi + +echo "Instrumented build installed: $SO" +echo "Preload runtime: $ATHERIS_DIR/asan_with_fuzzer.so" diff --git a/fuzz/fuzz_decode.py b/fuzz/fuzz_decode.py index 261059b349..cdc0f6187b 100755 --- a/fuzz/fuzz_decode.py +++ b/fuzz/fuzz_decode.py @@ -8,8 +8,13 @@ from __future__ import annotations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import array + import atheris -from fuzz_shared import OTHER_ERRORS, load_pure_python_bson, main, normalize +from fuzz_shared import OTHER_ERRORS, input_views, load_pure_python_bson, main, normalize with atheris.instrument_imports(): # Load both implementations while import instrumentation is active so the @@ -23,7 +28,7 @@ _BOTH_IMPLS = _bson_c.has_c() -def _decode_with(bson_mod, data: bytes) -> dict | None: +def _decode_with(bson_mod, data: bytes | array.array) -> dict | None: """Run bson_mod.decode(data), returning the document or None on expected errors.""" try: return bson_mod.decode(data) @@ -33,45 +38,50 @@ def _decode_with(bson_mod, data: bytes) -> dict | None: @atheris.instrument_func def TestOneInput(data: bytes) -> None: - doc_c = _decode_with(_bson_c, data) - - # A successful decode must round-trip through encode(). - if doc_c is not None: - try: - _bson_c.encode(doc_c) - except Exception as exc: - raise AssertionError( - f"bson.encode() failed after bson.decode() succeeded: {exc!r}\n" - f"decoded document: {doc_c!r}" - ) from exc - - doc_pure = _decode_with(_bson_pure, data) - - if doc_pure is not None: - try: - _bson_pure.encode(doc_pure) - except Exception as exc: - raise AssertionError( - f"pure-Python bson.encode() failed after bson.decode() succeeded: {exc!r}\n" - f"decoded document: {doc_pure!r}" - ) from exc - - # Consistency check. - if _BOTH_IMPLS: - c_succeeded = doc_c is not None - pure_succeeded = doc_pure is not None - if c_succeeded != pure_succeeded: - raise AssertionError( - f"C extension and pure-Python bson.decode() disagree: " - f"C={'success' if c_succeeded else 'failure'}, " - f"pure={'success' if pure_succeeded else 'failure'} " - f"for input: {data!r}" - ) - if doc_c is not None and doc_pure is not None and normalize(doc_c) != normalize(doc_pure): - raise AssertionError( - f"C extension and pure-Python bson.decode() produced different " - f"documents: C={doc_c!r}, pure={doc_pure!r}, input: {data!r}" - ) + for view in input_views(data): + doc_c = _decode_with(_bson_c, view) + + # A successful decode must round-trip through encode(). + if doc_c is not None: + try: + _bson_c.encode(doc_c) + except Exception as exc: + raise AssertionError( + f"bson.encode() failed after bson.decode() succeeded: {exc!r}\n" + f"decoded document: {doc_c!r}" + ) from exc + + doc_pure = _decode_with(_bson_pure, view) + + if doc_pure is not None: + try: + _bson_pure.encode(doc_pure) + except Exception as exc: + raise AssertionError( + f"pure-Python bson.encode() failed after bson.decode() succeeded: {exc!r}\n" + f"decoded document: {doc_pure!r}" + ) from exc + + # Consistency check. + if _BOTH_IMPLS: + c_succeeded = doc_c is not None + pure_succeeded = doc_pure is not None + if c_succeeded != pure_succeeded: + raise AssertionError( + f"C extension and pure-Python bson.decode() disagree: " + f"C={'success' if c_succeeded else 'failure'}, " + f"pure={'success' if pure_succeeded else 'failure'} " + f"for input: {data!r}" + ) + if ( + doc_c is not None + and doc_pure is not None + and normalize(doc_c) != normalize(doc_pure) + ): + raise AssertionError( + f"C extension and pure-Python bson.decode() produced different " + f"documents: C={doc_c!r}, pure={doc_pure!r}, input: {data!r}" + ) if __name__ == "__main__": diff --git a/fuzz/fuzz_decode_all.py b/fuzz/fuzz_decode_all.py index e8a9812fc6..1a672e811b 100755 --- a/fuzz/fuzz_decode_all.py +++ b/fuzz/fuzz_decode_all.py @@ -8,8 +8,13 @@ from __future__ import annotations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import array + import atheris -from fuzz_shared import OTHER_ERRORS, load_pure_python_bson, main, normalize +from fuzz_shared import OTHER_ERRORS, input_views, load_pure_python_bson, main, normalize with atheris.instrument_imports(): # Load both implementations while import instrumentation is active so the @@ -23,7 +28,7 @@ _BOTH_IMPLS = _bson_c.has_c() -def _decode_all_with(bson_mod, data: bytes) -> list | None: +def _decode_all_with(bson_mod, data: bytes | array.array) -> list | None: """Run bson_mod.decode_all(data), returning the documents or None on expected errors.""" try: return bson_mod.decode_all(data) @@ -45,42 +50,43 @@ def _encode_all_with(bson_mod, docs) -> None: @atheris.instrument_func def TestOneInput(data: bytes) -> None: - docs_c = _decode_all_with(_bson_c, data) - if docs_c is not None: - _encode_all_with(_bson_c, docs_c) - - docs_pure = _decode_all_with(_bson_pure, data) - if docs_pure is not None: - _encode_all_with(_bson_pure, docs_pure) - - # Consistency checks. - if _BOTH_IMPLS: - c_succeeded = docs_c is not None - pure_succeeded = docs_pure is not None - - if c_succeeded != pure_succeeded: - raise AssertionError( - f"C extension and pure-Python bson.decode_all() disagree: " - f"C={'success' if c_succeeded else 'failure'}, " - f"pure={'success' if pure_succeeded else 'failure'} " - f"for input: {data!r}" - ) - - if docs_c is not None and docs_pure is not None and len(docs_c) != len(docs_pure): - raise AssertionError( - f"C extension decoded {len(docs_c)} document(s) but pure Python " - f"decoded {len(docs_pure)} document(s) for input: {data!r}" - ) - - if ( - docs_c is not None - and docs_pure is not None - and normalize(docs_c) != normalize(docs_pure) - ): - raise AssertionError( - f"C extension and pure-Python bson.decode_all() produced different " - f"documents for input: {data!r}" - ) + for view in input_views(data): + docs_c = _decode_all_with(_bson_c, view) + if docs_c is not None: + _encode_all_with(_bson_c, docs_c) + + docs_pure = _decode_all_with(_bson_pure, view) + if docs_pure is not None: + _encode_all_with(_bson_pure, docs_pure) + + # Consistency checks. + if _BOTH_IMPLS: + c_succeeded = docs_c is not None + pure_succeeded = docs_pure is not None + + if c_succeeded != pure_succeeded: + raise AssertionError( + f"C extension and pure-Python bson.decode_all() disagree: " + f"C={'success' if c_succeeded else 'failure'}, " + f"pure={'success' if pure_succeeded else 'failure'} " + f"for input: {data!r}" + ) + + if docs_c is not None and docs_pure is not None and len(docs_c) != len(docs_pure): + raise AssertionError( + f"C extension decoded {len(docs_c)} document(s) but pure Python " + f"decoded {len(docs_pure)} document(s) for input: {data!r}" + ) + + if ( + docs_c is not None + and docs_pure is not None + and normalize(docs_c) != normalize(docs_pure) + ): + raise AssertionError( + f"C extension and pure-Python bson.decode_all() produced different " + f"documents for input: {data!r}" + ) if __name__ == "__main__": diff --git a/fuzz/fuzz_is_valid.py b/fuzz/fuzz_is_valid.py index 5281c7e49e..4d9819e81f 100755 --- a/fuzz/fuzz_is_valid.py +++ b/fuzz/fuzz_is_valid.py @@ -9,7 +9,7 @@ from __future__ import annotations import atheris -from fuzz_shared import load_pure_python_bson, main +from fuzz_shared import input_views, load_pure_python_bson, main with atheris.instrument_imports(): # Load both implementations while import instrumentation is active so the @@ -25,29 +25,33 @@ @atheris.instrument_func def TestOneInput(data: bytes) -> None: + # is_valid() requires bytes (other buffers raise TypeError) and is a + # pure content predicate, so it runs on the raw input. decode() + # exercises every view, including the sentinel-free array.array copy + # that lets ASan see over-reads in native mode (PYTHON-6169). valid_c = _bson_c.is_valid(data) - - if valid_c: - try: - _bson_c.decode(data) - except Exception as exc: - # is_valid() performs a full decode and swallows every exception, - # so a True result guarantees decode() raises none. - raise AssertionError( - f"bson.is_valid() returned True but bson.decode() raised " - f"{type(exc).__name__}: {exc!r}\ninput: {data!r}" - ) from exc - valid_pure = _bson_pure.is_valid(data) - if valid_pure: - try: - _bson_pure.decode(data) - except Exception as exc: - raise AssertionError( - f"pure-Python bson.is_valid() returned True but bson.decode() " - f"raised {type(exc).__name__}: {exc!r}\ninput: {data!r}" - ) from exc + for view in input_views(data): + if valid_c: + try: + _bson_c.decode(view) + except Exception as exc: + # is_valid() performs a full decode and swallows every exception, + # so a True result guarantees decode() raises none. + raise AssertionError( + f"bson.is_valid() returned True but bson.decode() raised " + f"{type(exc).__name__}: {exc!r}\ninput: {data!r}" + ) from exc + + if valid_pure: + try: + _bson_pure.decode(view) + except Exception as exc: + raise AssertionError( + f"pure-Python bson.is_valid() returned True but bson.decode() " + f"raised {type(exc).__name__}: {exc!r}\ninput: {data!r}" + ) from exc if _BOTH_IMPLS and valid_c != valid_pure: raise AssertionError( diff --git a/fuzz/fuzz_shared.py b/fuzz/fuzz_shared.py index f4cde8aaae..406513d3a5 100755 --- a/fuzz/fuzz_shared.py +++ b/fuzz/fuzz_shared.py @@ -3,12 +3,15 @@ from __future__ import annotations +import array import math import os import struct import sys +from typing import TYPE_CHECKING -import atheris +if TYPE_CHECKING: + from collections.abc import Iterator def load_pure_python_bson(): @@ -64,8 +67,27 @@ def normalize(obj: object) -> object: return f"{type(obj).__name__}:{obj!r}" +def input_views(data: bytes) -> Iterator[object]: + """Yield the buffer views to decode for one fuzz input. + + Always yields the raw bytes. With FUZZ_NATIVE=1 (native ASan fuzzing, + PYTHON-6169) it also yields a sentinel-free array.array copy: bytes + ends in CPython's hidden NUL sentinel, which hides an over-read past + the buffer from ASan (the PYTHON-6110 masking). The array copy has no + sentinel, so the same over-read triggers ASan's redzone check. + """ + yield data + if os.environ.get("FUZZ_NATIVE") == "1": + yield array.array("B", data) + + def main(test_one_input) -> None: """Set up atheris for a fuzz target and start fuzzing.""" + # Imported here so fuzz_shared remains importable without atheris, which + # test/test_fuzz_shared.py relies on. The fuzz targets import atheris + # themselves before calling main(). + import atheris + # FUZZ_NATIVE=1: libFuzzer is preloaded externally; skip atheris's own. internal_libfuzzer = os.environ.get("FUZZ_NATIVE") != "1" atheris.Setup(sys.argv, test_one_input, internal_libfuzzer=internal_libfuzzer) diff --git a/fuzz/run_native.sh b/fuzz/run_native.sh new file mode 100755 index 0000000000..7ea5da96e5 --- /dev/null +++ b/fuzz/run_native.sh @@ -0,0 +1,73 @@ +#!/bin/bash +# Run the BSON fuzz targets against an ASan-instrumented build under +# libFuzzer (PYTHON-6169). Expects fuzz/build_native.sh to have run. +# +# Time-boxed per target (FUZZ_MAX_TIME seconds, default 300) against the +# generated seed corpus plus the committed fuzz/corpus/ units. Run from +# the repository root: +# bash fuzz/run_native.sh +set -euo pipefail + +ROOT=$(git rev-parse --show-toplevel) +cd "$ROOT" + +PYTHON=".venv/bin/python" +SCRATCH="$ROOT/fuzz-scratch" +CORPUS="$SCRATCH/native-corpus" +MAX_TIME="${FUZZ_MAX_TIME:-300}" + +if [ ! -x "$PYTHON" ]; then + echo "ERROR: $PYTHON not found. Run fuzz/build_native.sh first." >&2 + exit 1 +fi + +# The venv's pymongo must be the instrumented one. The symbol pattern covers +# both instrumentation shapes: undefined/embedded __asan references and the +# .check_load_add/.check_store_add local labels clang emits for inline ASan +# checks (PYTHON-6169). grep without -q: with pipefail, grep -q's early exit +# SIGPIPEs nm on a large symbol table and the pipeline fails even on a match. +SO=$(ls .venv/lib/python3.*/site-packages/bson/_cbson*.so) +if ! nm "$SO" 2>/dev/null | grep -E "__asan|__sanitizer_cov|check_load_add|check_store_add" > /dev/null; then + echo "ERROR: $SO is not ASan-instrumented. Run fuzz/build_native.sh first." >&2 + exit 1 +fi + +# Build the seed corpus from the vendored spec data. build_corpus.py forces +# the pure-Python implementation, so it is safe under an instrumented venv. +rm -rf "$CORPUS" +mkdir -p "$CORPUS" +ZIP="$SCRATCH/native-corpus-seed.zip" +"$PYTHON" fuzz/build_corpus.py "$ZIP" --data-dir test/bson_corpus +"$PYTHON" -m zipfile -e "$ZIP" "$CORPUS" +rm "$ZIP" +# Seed from the committed corpus of previously captured inputs too, so +# native fuzzing starts from the spec seeds plus prior discoveries +# (setup_tests.py seeds the nightly and weekly runs the same way). +for unit in "$ROOT"/fuzz/corpus/*; do + if [ -f "$unit" ]; then + cp "$unit" "$CORPUS/" + fi +done +if [ -z "$(ls -A "$CORPUS")" ]; then + echo "ERROR: no seed corpus built in $CORPUS." >&2 + exit 1 +fi + +# FUZZ_NATIVE=1: the targets read it and skip atheris's own libFuzzer, +# which comes preloaded below. PYTHONMALLOC=malloc: ASan needs per-object +# redzones and pymalloc has none, so the array.array over-reads are +# invisible under pymalloc. detect_leaks=0: LSan reports the targets' +# live objects as leaks (PYTHON-6048). +export FUZZ_NATIVE=1 +export PYTHONMALLOC=malloc +export ASAN_OPTIONS="detect_leaks=0" +ATHERIS_RUNTIME="$($PYTHON -c 'import atheris; print(atheris.path())')/asan_with_fuzzer.so" +export LD_PRELOAD="$ATHERIS_RUNTIME" + +# Write libFuzzer crash artifacts under the scratch dir, which exists after +# the corpus extraction. +for target in fuzz_decode fuzz_decode_all fuzz_is_valid; do + "$PYTHON" "fuzz/$target.py" "$CORPUS" \ + "-artifact_prefix=$SCRATCH/" \ + "-max_total_time=$MAX_TIME" -max_len=1048576 -print_final_stats=1 +done diff --git a/test/test_fuzz_shared.py b/test/test_fuzz_shared.py new file mode 100644 index 0000000000..7f89ff4985 --- /dev/null +++ b/test/test_fuzz_shared.py @@ -0,0 +1,162 @@ +"""Tests for the BSON fuzz target helpers (PYTHON-6169).""" + +from __future__ import annotations + +import array +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).parent.parent / "fuzz")) + +import fuzz_shared # type: ignore[import-not-found] + +# The PYTHON-6110 reproducer: a truncated Regex element whose flags string +# starts one byte past the document. +OVERREAD_INPUT = b"\x08\x00\x00\x00\x0b\x61\x00\x00" + + +# Explicit "default" markers: the repo's collection hook only auto-marks +# items with no markers, and @pytest.mark.parametrize is a marker, so the +# parametrized tests would otherwise be deselected by the default +# "-m default or default_async" filter. +@pytest.mark.default +@pytest.mark.parametrize("data", [b"", b"\x08\x00\x00\x00\x00", OVERREAD_INPUT]) +def test_input_views_bytes_by_default(monkeypatch, data): + """Without FUZZ_NATIVE, the only view is the raw bytes.""" + monkeypatch.delenv("FUZZ_NATIVE", raising=False) + views = list(fuzz_shared.input_views(data)) + assert len(views) == 1 + assert type(views[0]) is bytes + assert views[0] == data + + +@pytest.mark.default +@pytest.mark.parametrize("data", [b"", b"\x08\x00\x00\x00\x00", OVERREAD_INPUT]) +def test_input_views_native_adds_sentinel_free_array(monkeypatch, data): + """Also decode through a sentinel-free array under FUZZ_NATIVE=1. + + bytes ends in CPython's hidden NUL sentinel, which hides over-reads + from ASan (the PYTHON-6110 masking). The array copy has none. + """ + monkeypatch.setenv("FUZZ_NATIVE", "1") + views = list(fuzz_shared.input_views(data)) + assert len(views) == 2 + assert type(views[0]) is bytes + assert type(views[1]) is array.array + assert views[1].typecode == "B" + assert views[1].tobytes() == data + + +def test_array_view_decodes_like_bytes(): + """Test that bson.decode() accepts an array view like bytes. + + The decoded result must equal the bytes result. + """ + import bson + + doc = bson.encode({"a": "bc", "b": 123}) + assert bson.decode(array.array("B", doc)) == bson.decode(doc) + + +def test_overread_input_rejected_for_both_views(): + """Reject the PYTHON-6110 reproducer identically through both views. + + The C extension's regex decoder is bounds-checked (PYTHON-6110), so the + over-read is rejected rather than masked by bytes' hidden NUL sentinel. + The sentinel-free array view decodes exactly like bytes. + """ + import bson + + for view in (OVERREAD_INPUT, array.array("B", OVERREAD_INPUT)): + with pytest.raises(bson.InvalidBSON): + bson.decode(view) + + +@pytest.fixture +def fuzz_targets(monkeypatch): + """Import the fuzz target modules with a no-op atheris shim. + + The targets require atheris at import time, but atheris ships Linux + x86_64 wheels only, so the real package is unavailable on other + platforms and interpreters. bson itself is imported normally. + """ + import contextlib + import types + + fake_atheris = types.ModuleType("atheris") + fake_atheris.instrument_imports = contextlib.nullcontext + fake_atheris.instrument_func = lambda func: func + monkeypatch.setitem(sys.modules, "atheris", fake_atheris) + + import fuzz_decode # type: ignore[import-not-found] + import fuzz_decode_all # type: ignore[import-not-found] + import fuzz_is_valid # type: ignore[import-not-found] + + return fuzz_decode, fuzz_decode_all, fuzz_is_valid + + +@pytest.mark.default +@pytest.mark.parametrize( + "data", + [ + b"", + b"\x05\x00\x00\x00\x00", # empty document + OVERREAD_INPUT, + bytes(bytearray(range(256))), # every byte value, all invalid + ], +) +def test_targets_handle_every_view(fuzz_targets, monkeypatch, data): + """Run every target's TestOneInput over both views. + + Under FUZZ_NATIVE=1 each input is decoded through the raw bytes and + the sentinel-free array copy. is_valid() raises TypeError for the + array view, which aborts the target in native mode. + """ + monkeypatch.setenv("FUZZ_NATIVE", "1") + fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets + + fuzz_decode.TestOneInput(data) + fuzz_decode_all.TestOneInput(data) + fuzz_is_valid.TestOneInput(data) + + +def test_targets_accept_valid_documents_in_native_mode(fuzz_targets, monkeypatch): + """Round-trip a valid document through every view in native mode. + + The targets' consistency assertions must not fail. + """ + monkeypatch.setenv("FUZZ_NATIVE", "1") + fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets + + import bson + + data = bson.encode({"a": "bc", "b": 123, "c": [1, 2, 3]}) + fuzz_decode.TestOneInput(data) + fuzz_decode_all.TestOneInput(data) + fuzz_is_valid.TestOneInput(data) + + +def test_regression_files_replay_cleanly(fuzz_targets, monkeypatch): + """Replay every committed reproducer in fuzz/regression/decode__*. + + Each must replay cleanly through both implementations over every input + view: the C extension and pure-Python must agree, and no exception may + escape the targets' expected-error handling. Includes the PYTHON-6256 + reproducers for the array-decoding heap-buffer-overflow reads found by + PYTHON-6169's native ASan fuzzer (the sanitizer replay is covered by + the fuzz-native task). + """ + monkeypatch.setenv("FUZZ_NATIVE", "1") + fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets + + regression = Path(__file__).parent.parent / "fuzz" / "regression" + paths = sorted(regression.glob("decode__*")) + assert paths, "no regression reproducers found" + + for path in paths: + data = path.read_bytes() + fuzz_decode.TestOneInput(data) + fuzz_decode_all.TestOneInput(data) + fuzz_is_valid.TestOneInput(data) From 740549a3b34ff87885e571ad87c0383a77a28883 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 13:44:26 -0600 Subject: [PATCH 02/16] trim comments --- fuzz/build_native.sh | 14 +++++++++----- test/test_fuzz_shared.py | 6 +++--- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/fuzz/build_native.sh b/fuzz/build_native.sh index c1077f797d..519c14b566 100755 --- a/fuzz/build_native.sh +++ b/fuzz/build_native.sh @@ -59,11 +59,10 @@ SITE_PACKAGES=$(ls -d .venv/lib/python3.*/site-packages) cp -f bson/*.so "$SITE_PACKAGES/bson/" cp -f pymongo/*.so "$SITE_PACKAGES/pymongo/" -# Verify the instrumented build landed. The smoke import below (under the -# preloaded runtime) is the authoritative check. The nm symbol check is a -# diagnostic only. clang's -shared -fsanitize=address embeds the ASan -# runtime, which can hide __asan symbols from nm output depending on linker -# mode (PYTHON-6169). +# The smoke import only proves the extension loads under the preloaded +# runtime; the nm symbol check is the instrumentation proof, demoted to a +# warning because -shared -fsanitize=address can hide __asan symbols from +# nm depending on linker mode. run_native.sh hard-fails on the same grep. SO=$(ls "$SITE_PACKAGES"/bson/_cbson*.so) ATHERIS_DIR=$(.venv/bin/python -c 'import atheris; print(atheris.path())') @@ -90,5 +89,10 @@ if ! nm "$SO" 2>/dev/null | grep -E "__asan|__sanitizer_cov|check_load_add|check readelf -d "$SO" 2>&1 | head -15 >&2 || true fi +# Remove the in-tree copies: an instrumented extension here would break a +# plain `import bson` from the repo root (the targets load the site-packages +# copies). Left in place on an early exit above, where they help debugging. +rm -f bson/*.so pymongo/*.so + echo "Instrumented build installed: $SO" echo "Preload runtime: $ATHERIS_DIR/asan_with_fuzzer.so" diff --git a/test/test_fuzz_shared.py b/test/test_fuzz_shared.py index 7f89ff4985..4a7b0e3db8 100644 --- a/test/test_fuzz_shared.py +++ b/test/test_fuzz_shared.py @@ -110,9 +110,9 @@ def fuzz_targets(monkeypatch): def test_targets_handle_every_view(fuzz_targets, monkeypatch, data): """Run every target's TestOneInput over both views. - Under FUZZ_NATIVE=1 each input is decoded through the raw bytes and - the sentinel-free array copy. is_valid() raises TypeError for the - array view, which aborts the target in native mode. + decode and decode_all see both views; fuzz_is_valid keeps is_valid() + on the raw bytes (it raises TypeError for other buffers) and runs + only decode() over both views. """ monkeypatch.setenv("FUZZ_NATIVE", "1") fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets From 82bb0f94e16e62c12e4cee765fbe6a41e9c9c598 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 14:25:46 -0600 Subject: [PATCH 03/16] Fix silent pure-Python fallback in native fuzzing --- .evergreen/config.yml | 1 + .evergreen/generated_configs/functions.yml | 26 +++++++++++++++ .evergreen/generated_configs/tasks.yml | 7 ++++ .evergreen/scripts/generate_config.py | 24 +++++++++++++- .evergreen/scripts/test_generate_config.py | 38 ++++++++++++++++++++-- fuzz/README.md | 14 +++++--- fuzz/build_native.sh | 21 ++++++++++-- fuzz/run_native.sh | 8 ++--- 8 files changed, 124 insertions(+), 15 deletions(-) diff --git a/.evergreen/config.yml b/.evergreen/config.yml index 791dd332f0..8e219617c6 100644 --- a/.evergreen/config.yml +++ b/.evergreen/config.yml @@ -42,6 +42,7 @@ post: - func: "upload coverage" - func: "upload mo artifacts" - func: "upload test results" + - func: "upload fuzz artifacts" - func: "cleanup" tasks: diff --git a/.evergreen/generated_configs/functions.yml b/.evergreen/generated_configs/functions.yml index f27d11892b..eaa6a84ffb 100644 --- a/.evergreen/generated_configs/functions.yml +++ b/.evergreen/generated_configs/functions.yml @@ -301,6 +301,32 @@ functions: optional: "true" type: setup + # Upload fuzz artifacts + upload fuzz artifacts: + - command: ec2.assume_role + params: + role_arn: ${assume_role_arn} + type: setup + - command: archive.targz_pack + params: + target: fuzz-native-artifacts.tgz + source_dir: ./ + include: + - ./src/fuzz-scratch/** + - command: s3.put + params: + remote_file: ${build_variant}/${revision}/${version_id}/${build_id}/fuzz/${task_id}-${execution}-fuzz-native-artifacts.tar.gz + aws_key: ${AWS_ACCESS_KEY_ID} + aws_secret: ${AWS_SECRET_ACCESS_KEY} + aws_session_token: ${AWS_SESSION_TOKEN} + bucket: ${bucket_name} + local_file: fuzz-native-artifacts.tgz + permissions: public-read + content_type: ${content_type|application/x-gzip} + display_name: Fuzz Artifacts - Execution + optional: "true" + type: setup + # Upload mo artifacts upload mo artifacts: - command: ec2.assume_role diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index b5abdae70e..88e0645b36 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -208,6 +208,13 @@ tasks: # Fuzz native tests - name: fuzz-native commands: + - command: subprocess.exec + params: + binary: bash + args: + - .evergreen/scripts/install-dependencies.sh + working_dir: src + type: test - command: subprocess.exec params: binary: bash diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index 18019586b4..9ea00eba33 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -777,9 +777,11 @@ def create_fuzz_tasks(): def create_fuzz_native_tasks(): # Native ASan-instrumented fuzzing (PYTHON-6169). Plain subprocess.exec: # the "run tests" function would reinstall pymongo without sanitizer - # flags and clobber the instrumented build. + # flags and clobber the instrumented build. install-dependencies.sh + # bootstraps uv for the fresh command shell without installing the project. tags = ["fuzz", "fuzz-native"] commands = [ + get_subprocess_exec(args=[".evergreen/scripts/install-dependencies.sh"]), get_subprocess_exec(args=["fuzz/build_native.sh"]), get_subprocess_exec(args=["fuzz/run_native.sh"]), ] @@ -1205,6 +1207,26 @@ def create_upload_mo_artifacts_func(): return "upload mo artifacts", cmds +def create_upload_fuzz_artifacts_func(): + # Retain libFuzzer crash-* reproducers (PYTHON-6169): they land in + # src/fuzz-scratch/ and no other post-task upload collects them. Outside + # fuzz tasks the include matches nothing, so optional keeps the upload + # a no-op. + archive_cmd = archive_targz_pack( + target="fuzz-native-artifacts.tgz", source_dir="./", include=["./src/fuzz-scratch/**"] + ) + display_name = "Fuzz Artifacts - Execution" + remote_file = ( + "${build_variant}/${revision}/${version_id}/${build_id}/fuzz/" + "${task_id}-${execution}-fuzz-native-artifacts.tar.gz" + ) + s3_artifacts = get_s3_put( + local_file="fuzz-native-artifacts.tgz", remote_file=remote_file, display_name=display_name + ) + cmds = [get_assume_role(), archive_cmd, s3_artifacts] + return "upload fuzz artifacts", cmds + + def create_fetch_source_func(): # Executes clone and applies the submitted patch, if any. cmd = git_get_project(directory="src") diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 36a0d29af0..7489b3646d 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -807,8 +807,8 @@ def test_fuzz_native_task_wiring(): """Run the daily fuzz-native task's scripts with plain subprocess.exec. The "run tests" function would reinstall pymongo without sanitizer - flags and clobber the instrumented build. The task runs in the nightly - Fuzz RHEL8 variant alongside the other fuzz tasks. + flags and clobber the instrumented build. install-dependencies.sh + bootstraps uv, which a fresh command shell does not inherit. """ tasks = [task for task in all_tasks() if "fuzz-native" in (task.tags or [])] assert len(tasks) == 1 @@ -817,7 +817,11 @@ def test_fuzz_native_task_wiring(): # Plain subprocess.exec only: no FunctionCall ("run tests") anywhere. assert all(getattr(cmd, "func", None) is None for cmd in task.commands) args = [cmd.params["args"] for cmd in task.commands] - assert args == [["fuzz/build_native.sh"], ["fuzz/run_native.sh"]] + assert args == [ + [".evergreen/scripts/install-dependencies.sh"], + ["fuzz/build_native.sh"], + ["fuzz/run_native.sh"], + ] # The get_subprocess_exec defaults: bash, from the src dir. assert all(cmd.params["binary"] == "bash" for cmd in task.commands) assert all(cmd.params["working_dir"] == "src" for cmd in task.commands) @@ -833,3 +837,31 @@ def test_fuzz_native_task_wiring(): ".fuzz-regression", ".fuzz-native", ] + + +def test_upload_fuzz_artifacts_func(): + """The fuzz artifacts upload archives crash reproducers and is optional. + + crash-* artifacts land in src/fuzz-scratch/ and no other post-task + upload collects them (PYTHON-6169). + """ + name, cmds = generate_config.create_upload_fuzz_artifacts_func() + assert name == "upload fuzz artifacts" + archive = [cmd for cmd in cmds if cmd.command == "archive.targz_pack"] + assert len(archive) == 1 + assert archive[0].params["include"] == ["./src/fuzz-scratch/**"] + puts = [cmd for cmd in cmds if cmd.command == "s3.put"] + assert len(puts) == 1 + assert puts[0].params["optional"] == "true" + assert puts[0].params["local_file"] == "fuzz-native-artifacts.tgz" + # Wired into post hooks before cleanup, so it runs on task failure too. + config = Path(__file__).parents[2].joinpath(".evergreen/config.yml").read_text() + post = config.split("post:", 1)[1].split("tasks:", 1)[0] + assert '- func: "upload fuzz artifacts"' in post + assert post.index("upload fuzz artifacts") < post.index("cleanup") + + +def test_run_native_seeds_regression(): + """The native runner replays fuzz/regression/ reproducers under ASan.""" + script = Path(__file__).parents[2].joinpath("fuzz/run_native.sh").read_text() + assert "fuzz/regression" in script diff --git a/fuzz/README.md b/fuzz/README.md index 76b11be34d..1a9823f1eb 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -160,11 +160,15 @@ hidden NUL sentinel, which hides over-reads from ASan (the PYTHON-6110 masking). Leak detection is off (`ASAN_OPTIONS=detect_leaks=0`), the same as the sanitizer tests (PYTHON-6048). Like the weekly capture run, the corpus seeds from the spec seed corpus plus the committed `corpus/` -units. - -The `fuzz-native` Evergreen task runs both scripts daily on RHEL8 with -pinned CPython 3.13; it runs in the nightly `Fuzz RHEL8` variant alongside -the other fuzz tasks. +and `regression/` units, replaying every known reproducer under ASan. + +The `fuzz-native` Evergreen task bootstraps the environment and runs both +scripts daily in the nightly `Fuzz RHEL8` variant with pinned CPython +3.13. Crash artifacts under `fuzz-scratch/` upload as task artifacts, so +an ASan finding keeps its reproducer. `build_native.sh` installs pymongo +non-editably so the targets load the instrumented venv copy after the +in-tree cleanup. A developer's `.venv` stays non-editable until the next +plain `uv sync`. ## Files diff --git a/fuzz/build_native.sh b/fuzz/build_native.sh index 519c14b566..ce335d1ca9 100755 --- a/fuzz/build_native.sh +++ b/fuzz/build_native.sh @@ -12,6 +12,12 @@ cd "$ROOT" PYVER="${FUZZ_NATIVE_PYTHON:-3.13}" +# Task commands run in fresh shells: source the bootstrap's env.sh to find +# uv. Guarded: a local run without Evergreen setup skips it. +if [ -f .evergreen/scripts/env.sh ]; then + . .evergreen/scripts/env.sh +fi + if [ "$(uname -s)" != "Linux" ] || [ "$(uname -m)" != "x86_64" ]; then echo "ERROR: native fuzzing requires Linux x86_64 (atheris wheel constraint)." >&2 exit 1 @@ -30,8 +36,10 @@ if ! command -v uv > /dev/null 2>&1; then exit 1 fi -# Sync the venv: atheris plus a regular (non-instrumented) pymongo install. -uv sync --group fuzz --python "$PYVER" +# Sync the venv: atheris plus a non-editable pymongo install. Non-editable +# keeps the cleanup below from leaving the targets on the pure-Python +# fallback (PYTHON-6169). +uv sync --no-editable --group fuzz --python "$PYVER" # setuptools for the direct build_ext invocation below (uv venvs omit it). uv pip install --python ".venv/bin/python" setuptools @@ -94,5 +102,14 @@ fi # copies). Left in place on an early exit above, where they help debugging. rm -f bson/*.so pymongo/*.so +# Smoke from a neutral cwd: with the in-tree copies gone, only the venv's +# site-packages copy can satisfy `bson.has_c()` (PYTHON-6169). +if ! (cd /tmp && FUZZ_NATIVE=1 LD_PRELOAD="$ATHERIS_DIR/asan_with_fuzzer.so" \ + ASAN_OPTIONS="detect_leaks=0" \ + "$ROOT/.venv/bin/python" -c "import bson; assert bson.has_c()"); then + echo "ERROR: post-cleanup import did not load the instrumented extension." >&2 + exit 1 +fi + echo "Instrumented build installed: $SO" echo "Preload runtime: $ATHERIS_DIR/asan_with_fuzzer.so" diff --git a/fuzz/run_native.sh b/fuzz/run_native.sh index 7ea5da96e5..f5de96b8fb 100755 --- a/fuzz/run_native.sh +++ b/fuzz/run_native.sh @@ -40,10 +40,10 @@ ZIP="$SCRATCH/native-corpus-seed.zip" "$PYTHON" fuzz/build_corpus.py "$ZIP" --data-dir test/bson_corpus "$PYTHON" -m zipfile -e "$ZIP" "$CORPUS" rm "$ZIP" -# Seed from the committed corpus of previously captured inputs too, so -# native fuzzing starts from the spec seeds plus prior discoveries -# (setup_tests.py seeds the nightly and weekly runs the same way). -for unit in "$ROOT"/fuzz/corpus/*; do +# Seed from the committed corpus and the regression reproducers too: the +# spec seeds, prior discoveries, and a deterministic ASan replay of every +# known bug (setup_tests.py seeds the other runs the same way). +for unit in "$ROOT"/fuzz/corpus/* "$ROOT"/fuzz/regression/*; do if [ -f "$unit" ]; then cp "$unit" "$CORPUS/" fi From a1649cab9ee3ede4aa23a434cb5612b0913909b3 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 14:39:58 -0600 Subject: [PATCH 04/16] Fix silent pure-Python fallback in native fuzzing --- fuzz/fuzz_shared.py | 8 ++++++-- test/test_fuzz_shared.py | 8 +++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/fuzz/fuzz_shared.py b/fuzz/fuzz_shared.py index 406513d3a5..afeec190a8 100755 --- a/fuzz/fuzz_shared.py +++ b/fuzz/fuzz_shared.py @@ -74,11 +74,15 @@ def input_views(data: bytes) -> Iterator[object]: PYTHON-6169) it also yields a sentinel-free array.array copy: bytes ends in CPython's hidden NUL sentinel, which hides an over-read past the buffer from ASan (the PYTHON-6110 masking). The array copy has no - sentinel, so the same over-read triggers ASan's redzone check. + sentinel and is exact-sized (a bare array.array(bytes) overallocates), + so the same over-read triggers ASan's redzone check. """ yield data if os.environ.get("FUZZ_NATIVE") == "1": - yield array.array("B", data) + # array.array(bytes) overallocates its buffer, leaving short + # over-reads inside addressable memory. A full slice of it + # allocates exactly len(data), putting the redzone right after. + yield array.array("B", data)[:] def main(test_one_input) -> None: diff --git a/test/test_fuzz_shared.py b/test/test_fuzz_shared.py index 4a7b0e3db8..692e4f58bd 100644 --- a/test/test_fuzz_shared.py +++ b/test/test_fuzz_shared.py @@ -38,7 +38,9 @@ def test_input_views_native_adds_sentinel_free_array(monkeypatch, data): """Also decode through a sentinel-free array under FUZZ_NATIVE=1. bytes ends in CPython's hidden NUL sentinel, which hides over-reads - from ASan (the PYTHON-6110 masking). The array copy has none. + from ASan (the PYTHON-6110 masking). The array copy has none and is + exact-sized: an overallocating buffer would leave short over-reads + inside addressable memory, invisible to ASan. """ monkeypatch.setenv("FUZZ_NATIVE", "1") views = list(fuzz_shared.input_views(data)) @@ -47,6 +49,10 @@ def test_input_views_native_adds_sentinel_free_array(monkeypatch, data): assert type(views[1]) is array.array assert views[1].typecode == "B" assert views[1].tobytes() == data + # Exact allocation: array.array(bytes) overallocates its buffer, which + # masks short over-reads from ASan. + empty = sys.getsizeof(array.array("B")) + assert sys.getsizeof(views[1]) == empty + len(data) def test_array_view_decodes_like_bytes(): From 760453129b42ce9465ad66f40aad785e94fe2721 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 17:06:16 -0600 Subject: [PATCH 05/16] consolidate the tasks --- .evergreen/generated_configs/tasks.yml | 85 ++++++++++---- .evergreen/generated_configs/variants.yml | 27 ++--- .evergreen/scripts/capture-fuzz-corpus.sh | 25 ++-- .evergreen/scripts/generate_config.py | 127 ++++++++++++--------- .evergreen/scripts/setup_tests.py | 7 +- .evergreen/scripts/test_generate_config.py | 127 +++++++++++---------- fuzz/README.md | 36 +++--- fuzz/run_native.sh | 47 ++++++-- 8 files changed, 281 insertions(+), 200 deletions(-) diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index 88e0645b36..a34068114a 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -205,8 +205,16 @@ tasks: depends_on: [{ name: .server-version, variant: .coverage_tag, status: "*", patch_optional: true }] tags: [coverage, pr] - # Fuzz native tests - - name: fuzz-native + # Fuzz tests + - name: fuzz-python-regression + commands: + - func: run tests + vars: + TEST_NAME: fuzz + SUB_TEST_NAME: regression + UV_PYTHON: "3.13" + tags: [fuzz, fuzz-python, pr] + - name: fuzz-native-regression commands: - command: subprocess.exec params: @@ -228,33 +236,66 @@ tasks: args: - fuzz/run_native.sh working_dir: src + env: + FUZZ_MAX_TIME: "0" type: test - tags: [fuzz, fuzz-native] - - # Fuzz tests - - name: fuzz-regression - commands: - - func: run tests - vars: - TEST_NAME: fuzz - SUB_TEST_NAME: regression - UV_PYTHON: "3.13" - tags: [fuzz, fuzz-regression, pr] - - name: fuzz + tags: [fuzz, fuzz-native, pr] + - name: fuzz-python-full commands: - func: run tests vars: TEST_NAME: fuzz SUB_TEST_NAME: fuzz UV_PYTHON: "3.13" - tags: [fuzz, fuzz-nightly] - - name: fuzz-capture + tags: [fuzz, fuzz-python] + - name: fuzz-native-full commands: - - func: run tests - vars: - TEST_NAME: fuzz - SUB_TEST_NAME: fuzz - UV_PYTHON: "3.13" + - command: subprocess.exec + params: + binary: bash + args: + - .evergreen/scripts/install-dependencies.sh + working_dir: src + type: test + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/build_native.sh + working_dir: src + type: test + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/run_native.sh + working_dir: src + type: test + tags: [fuzz, fuzz-native] + - name: fuzz-corpus-capture + commands: + - command: subprocess.exec + params: + binary: bash + args: + - .evergreen/scripts/install-dependencies.sh + working_dir: src + type: test + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/build_native.sh + working_dir: src + type: test + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/run_native.sh + - fuzz-scratch/corpus + working_dir: src + type: test - command: subprocess.exec params: binary: bash @@ -268,7 +309,7 @@ tasks: - AWS_SECRET_ACCESS_KEY - AWS_SESSION_TOKEN type: test - tags: [fuzz, fuzz-weekly] + tags: [fuzz, fuzz-corpus-capture] # Getdata tests - name: getdata diff --git a/.evergreen/generated_configs/variants.yml b/.evergreen/generated_configs/variants.yml index bdf0a8f734..2418038fd5 100644 --- a/.evergreen/generated_configs/variants.yml +++ b/.evergreen/generated_configs/variants.yml @@ -201,29 +201,18 @@ buildvariants: AUTH: auth # Fuzz tests - - name: fuzz-regression-rhel8 + - name: fuzzing-rhel8 tasks: - - name: .fuzz-regression - display_name: Fuzz Regression RHEL8 - run_on: - - rhel8.7-large - tags: [pr] - - name: fuzz-rhel8 - tasks: - - name: .fuzz-nightly - - name: .fuzz-regression - - name: .fuzz-native - display_name: Fuzz RHEL8 + - name: fuzz-python-regression + - name: fuzz-native-regression + - name: fuzz-python-full + - name: fuzz-native-full + - name: fuzz-corpus-capture + batchtime: 10080 + display_name: Fuzzing RHEL8 run_on: - rhel8.7-large batchtime: 1440 - - name: fuzz-capture-rhel8 - tasks: - - name: .fuzz-weekly - display_name: Fuzz Capture RHEL8 - run_on: - - rhel8.7-large - batchtime: 10080 # Green framework tests - name: green-gevent-rhel8 diff --git a/.evergreen/scripts/capture-fuzz-corpus.sh b/.evergreen/scripts/capture-fuzz-corpus.sh index ad829e0c48..1e4b33692f 100755 --- a/.evergreen/scripts/capture-fuzz-corpus.sh +++ b/.evergreen/scripts/capture-fuzz-corpus.sh @@ -1,27 +1,32 @@ #!/bin/bash # PYTHON-6178: capture coverage-increasing inputs from a fuzz run and open # an automated PR growing fuzz/corpus/. Runs as the last command of the -# weekly "fuzz-capture" task, while the scratch corpus exists; manual -# `evergreen patch --variant fuzz-capture-rhel8 --task fuzz-capture` runs -# capture too. +# weekly fuzz-corpus-capture task, whose fuzzing run is native +# (PYTHON-6169). Manual `evergreen patch --variant fuzzing-capture-rhel8 +# --task fuzz-corpus-capture` runs capture too. set -eu -# Same environment as just.sh: venv on PATH for a modern Python. -. "$(dirname "${BASH_SOURCE:-$0}")/setup-dev-env.sh" - # No new units means no PR, and the github secrets flow is never touched. -uv run --no-sync python fuzz/capture_corpus.py +# The venv python directly: `uv run` re-syncs, which would clobber the +# instrumented extensions the replay validates against. capture_corpus.py +# is stdlib-only, so the venv needs nothing extra. +.venv/bin/python fuzz/capture_corpus.py if [ -z "$(ls -A fuzz-scratch/capture 2>/dev/null || true)" ]; then echo "No new fuzz corpus units; nothing to do." exit 0 fi -# The replay runs the atheris targets, so it must request the fuzz group. +# Replay the captured units natively: each unit as a file argument, so +# libFuzzer runs each exactly once under ASan. Same environment as +# run_native.sh. +ATHERIS_RUNTIME=$(.venv/bin/python -c 'import atheris; print(atheris.path())')/asan_with_fuzzer.so replay=(fuzz-scratch/capture/*) for target in fuzz_decode fuzz_decode_all fuzz_is_valid; do echo "Replaying captured units against ${target}..." - if ! uv run --group fuzz python "fuzz/${target}.py" "${replay[@]}" \ - -artifact_prefix="$PWD/fuzz-scratch/" -atheris_runs="${#replay[@]}" + if ! FUZZ_NATIVE=1 PYTHONMALLOC=malloc ASAN_OPTIONS="detect_leaks=0" \ + LD_PRELOAD="$ATHERIS_RUNTIME" \ + .venv/bin/python "fuzz/${target}.py" "${replay[@]}" \ + -artifact_prefix="$PWD/fuzz-scratch/" then echo "Captured unit fails ${target}; no corpus PR." >&2 exit 1 diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index 9ea00eba33..251d17a444 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -389,39 +389,28 @@ def create_doctests_variants(): def create_fuzz_variants(): - # Three variants for the fuzz flows: the regression reproducers run - # on every PR, the daily variant fuzzes for crash discovery and runs - # the native ASan fuzzing (PYTHON-6169), and the weekly variant also - # captures the corpus (opens the automated [Fuzz Corpus] PR). The - # non-pr variants carry no "pr" tag, so PR patch builds never select - # them, while their default patchability keeps them manually runnable - # (`evergreen patch --variant fuzz-rhel8 --task fuzz`). The host needs - # CPython, which the rhel8 toolchain provides; the large rhel8.7 distro - # matches the other drivers' fuzz jobs and fits libFuzzer's growing - # corpus. + # One variant hosts all the fuzz flows (PYTHON-6169). A task's "pr" + # tag keeps it out of mainline builds and selects it into PR patch + # builds. The capture ref carries its own weekly batchtime, which + # overrides the variant's daily one (the kms tasks do the same). The + # host needs CPython, which the rhel8 toolchain provides. The large + # rhel8.7 distro matches the other drivers' fuzz jobs and fits + # libFuzzer's growing corpus. host = HOSTS["rhel8"] return [ create_variant( - [".fuzz-regression"], - get_variant_name("Fuzz Regression", host), - host=host, - run_on="rhel8.7-large", - tags=["pr"], - ), - create_variant( - [".fuzz-nightly", ".fuzz-regression", ".fuzz-native"], - get_variant_name("Fuzz", host), + [ + "fuzz-python-regression", + "fuzz-native-regression", + "fuzz-python-full", + "fuzz-native-full", + EvgTaskRef(name="fuzz-corpus-capture", batchtime=BATCHTIME_WEEK), + ], + get_variant_name("Fuzzing", host), host=host, run_on="rhel8.7-large", batchtime=BATCHTIME_DAY, ), - create_variant( - [".fuzz-weekly"], - get_variant_name("Fuzz Capture", host), - host=host, - run_on="rhel8.7-large", - batchtime=BATCHTIME_WEEK, - ), ] @@ -735,28 +724,55 @@ def create_no_orchestration_tasks(): def create_fuzz_tasks(): - # Deterministic regression test over the committed known-bug reproducers. - tags = ["fuzz", "fuzz-regression", "pr"] + # Deterministic replay of the committed reproducers through the atheris + # targets (PYTHON-4232). + tags = ["fuzz", "fuzz-python", "pr"] test_vars = dict(TEST_NAME="fuzz", SUB_TEST_NAME="regression", UV_PYTHON="3.13") test_func = FunctionCall(func="run tests", vars=test_vars) - tasks = [EvgTask(name="fuzz-regression", tags=tags, commands=[test_func])] + tasks = [EvgTask(name="fuzz-python-regression", tags=tags, commands=[test_func])] + + # Native replay of the whole corpus (PYTHON-6169): FUZZ_MAX_TIME=0 + # makes libFuzzer run each unit once and exit. + build_cmd = get_subprocess_exec(args=["fuzz/build_native.sh"]) + install_cmd = get_subprocess_exec(args=[".evergreen/scripts/install-dependencies.sh"]) + tasks.append( + EvgTask( + name="fuzz-native-regression", + tags=["fuzz", "fuzz-native", "pr"], + commands=[ + install_cmd, + build_cmd, + get_subprocess_exec(args=["fuzz/run_native.sh"], env=dict(FUZZ_MAX_TIME="0")), + ], + ) + ) - # Time-boxed fuzzing against the generated seed corpus, for crash - # discovery; corpus capture moved to the weekly fuzz-capture task. - tags = ["fuzz", "fuzz-nightly"] + # Time-boxed atheris fuzzing on mainline, for crash discovery. + tags = ["fuzz", "fuzz-python"] test_vars = dict(TEST_NAME="fuzz", SUB_TEST_NAME="fuzz", UV_PYTHON="3.13") test_func = FunctionCall(func="run tests", vars=test_vars) - tasks.append(EvgTask(name="fuzz", tags=tags, commands=[test_func])) + tasks.append(EvgTask(name="fuzz-python-full", tags=tags, commands=[test_func])) + + # Time-boxed native fuzzing (PYTHON-6169). Plain subprocess.exec: the + # "run tests" function would reinstall pymongo without sanitizer flags + # and clobber the instrumented build. + tasks.append( + EvgTask( + name="fuzz-native-full", + tags=["fuzz", "fuzz-native"], + commands=[ + install_cmd, + build_cmd, + get_subprocess_exec(args=["fuzz/run_native.sh"]), + ], + ) + ) - # The weekly capture task fuzzes too (the capture reads the task-local - # fuzz-scratch/ corpus, so it must stay attached to a fuzzing run). - tags = ["fuzz", "fuzz-weekly"] - test_vars = dict(TEST_NAME="fuzz", SUB_TEST_NAME="fuzz", UV_PYTHON="3.13") - test_func = FunctionCall(func="run tests", vars=test_vars) - # PYTHON-6178: while the scratch corpus still exists, capture the new - # coverage-increasing inputs, replay them through every target so a - # unit that fails one is never published, and open an automated PR - # growing fuzz/corpus/. + # The capture fuzzes natively (PYTHON-6169): the instrumented build + # discovers C-extension coverage, and captured units are + # ASan-validated before publication. The run targets + # fuzz-scratch/corpus, where capture_corpus.py harvests (PYTHON-6178). + tags = ["fuzz", "fuzz-corpus-capture"] capture_cmd = get_subprocess_exec( args=[".evergreen/scripts/capture-fuzz-corpus.sh"], include_expansions_in_env=[ @@ -770,24 +786,21 @@ def create_fuzz_tasks(): "AWS_SESSION_TOKEN", ], ) - tasks.append(EvgTask(name="fuzz-capture", tags=tags, commands=[test_func, capture_cmd])) + tasks.append( + EvgTask( + name="fuzz-corpus-capture", + tags=tags, + commands=[ + install_cmd, + build_cmd, + get_subprocess_exec(args=["fuzz/run_native.sh", "fuzz-scratch/corpus"]), + capture_cmd, + ], + ) + ) return tasks -def create_fuzz_native_tasks(): - # Native ASan-instrumented fuzzing (PYTHON-6169). Plain subprocess.exec: - # the "run tests" function would reinstall pymongo without sanitizer - # flags and clobber the instrumented build. install-dependencies.sh - # bootstraps uv for the fresh command shell without installing the project. - tags = ["fuzz", "fuzz-native"] - commands = [ - get_subprocess_exec(args=[".evergreen/scripts/install-dependencies.sh"]), - get_subprocess_exec(args=["fuzz/build_native.sh"]), - get_subprocess_exec(args=["fuzz/run_native.sh"]), - ] - return [EvgTask(name="fuzz-native", tags=tags, commands=commands)] - - 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. diff --git a/.evergreen/scripts/setup_tests.py b/.evergreen/scripts/setup_tests.py index cb0fb59c1e..de31ca4b9c 100644 --- a/.evergreen/scripts/setup_tests.py +++ b/.evergreen/scripts/setup_tests.py @@ -600,10 +600,9 @@ def handle_test_env() -> None: zip_path.unlink() if sub_test_name == "fuzz": # PYTHON-6178 Also seed from the committed corpus of previously - # captured inputs, so the nightly and weekly runs build on prior - # discoveries instead of the spec seeds alone. Regression runs - # (PRs) keep running only the reproducers and the spec seed - # corpus. + # captured inputs, so the full run builds on prior discoveries + # instead of the spec seeds alone. Regression runs (PRs) keep + # running only the reproducers and the spec seed corpus. committed_dir = ROOT / "fuzz" / "corpus" if committed_dir.is_dir(): for path in sorted(committed_dir.iterdir()): diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 7489b3646d..1a7a5742ae 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -443,56 +443,69 @@ def test_non_standard_cov_tasks_have_no_cov_companions(): def test_fuzz_task_wiring(): """Test the fuzz task wiring. - Three fuzz flows: the pr-tagged regression variant runs the reproducers - on every PR; the nightly variant fuzzes for crash discovery and runs - the native ASan fuzzing (PYTHON-6169); the weekly variant also captures - the corpus. The non-pr variants carry no "pr" tag, so PR patch builds - never select them, while their default patchability keeps them manually - runnable (`evergreen patch --variant fuzz-rhel8 --task fuzz`). + Five flows in one Fuzzing variant. A task's "pr" tag keeps it out of + mainline builds and selects it into PR patch builds, so the replays + gate PRs and the full flows run only on mainline. """ tasks = {task.name: task for task in all_tasks() if "fuzz" in (task.tags or [])} - assert sorted(task.name for task in tasks.values() if "pr" in (task.tags or [])) == [ - "fuzz-regression" + assert sorted(tasks) == [ + "fuzz-corpus-capture", + "fuzz-native-full", + "fuzz-native-regression", + "fuzz-python-full", + "fuzz-python-regression", ] - assert sorted(task.name for task in tasks.values() if "pr" not in (task.tags or [])) == [ - "fuzz", - "fuzz-capture", - "fuzz-native", + assert sorted(task.name for task in tasks.values() if "pr" in (task.tags or [])) == [ + "fuzz-native-regression", + "fuzz-python-regression", ] variants = generate_config.create_fuzz_variants() - assert len(variants) == 3 - regression, nightly, capture_variant = variants - assert variant_selects(regression, tasks["fuzz-regression"]) - assert "pr" in (regression.tags or []) - # The nightly variant runs the whole daily fuzz family, so one patch - # build covers it: crash-discovery fuzzing, the regression replay, and - # the native ASan fuzzing (PYTHON-6169). - assert variant_selects(nightly, tasks["fuzz"]) - assert variant_selects(nightly, tasks["fuzz-native"]) - assert not variant_selects(nightly, tasks["fuzz-capture"]) - assert nightly.batchtime == generate_config_utils.BATCHTIME_DAY - assert variant_selects(capture_variant, tasks["fuzz-capture"]) - assert capture_variant.batchtime == generate_config_utils.BATCHTIME_WEEK + assert len(variants) == 1 + fuzzing = variants[0] + assert not fuzzing.tags + assert fuzzing.batchtime == generate_config_utils.BATCHTIME_DAY + # All five flows share the variant. The capture ref carries its own + # weekly batchtime, which overrides the variant's daily one. + assert [ref.name for ref in fuzzing.tasks] == [ + "fuzz-python-regression", + "fuzz-native-regression", + "fuzz-python-full", + "fuzz-native-full", + "fuzz-corpus-capture", + ] + capture_ref = fuzzing.tasks[-1] + assert capture_ref.batchtime == generate_config_utils.BATCHTIME_WEEK + for name, task in tasks.items(): + assert variant_selects(fuzzing, task), name # The fuzz family runs on the large rhel8.7 distro, like the other # drivers' fuzz jobs. - for variant in (regression, nightly, capture_variant): - assert variant.run_on == ["rhel8.7-large"] - # Webhook PR patch builds only select pr-tagged variants. - assert not nightly.tags - assert not capture_variant.tags - # The nightly fuzz task is crash discovery only: its last command is - # the "run tests" FunctionCall, with no capture command. - assert tasks["fuzz"].commands[-1].func == "run tests" + assert fuzzing.run_on == ["rhel8.7-large"] + # The python flows go through the "run tests" function: the regression + # replay for PRs, time-boxed discovery for mainline. + assert tasks["fuzz-python-regression"].commands[-1].func == "run tests" + assert tasks["fuzz-python-full"].commands[-1].func == "run tests" + native_regression_run = tasks["fuzz-native-regression"].commands[-1] + assert native_regression_run.params["args"] == ["fuzz/run_native.sh"] + assert native_regression_run.params["env"] == {"FUZZ_MAX_TIME": "0"} + native_full_run = tasks["fuzz-native-full"].commands[-1] + assert native_full_run.params["args"] == ["fuzz/run_native.sh"] + assert "env" not in native_full_run.params # The capture subprocess bootstraps the comment-bot github app, whose # secrets live in AWS Secrets Manager: it needs the assumed-role # credentials (as resync_specs and backport-pr also pass them). - capture = tasks["fuzz-capture"].commands[-1] + capture = tasks["fuzz-corpus-capture"].commands[-1] env_vars = capture.params["include_expansions_in_env"] for var in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"): assert var in env_vars, f"capture subprocess missing {var}" # The capture no longer keys off is_patch: manual patch runs must # capture too, and the weekly variant never runs in a PR build. assert "is_patch" not in env_vars + # The capture fuzzes natively into the corpus capture_corpus.py harvests. + capture_commands = tasks["fuzz-corpus-capture"].commands + assert capture_commands[0].params["args"] == [".evergreen/scripts/install-dependencies.sh"] + assert capture_commands[1].params["args"] == ["fuzz/build_native.sh"] + assert capture_commands[2].params["args"] == ["fuzz/run_native.sh", "fuzz-scratch/corpus"] + assert capture_commands[3] is capture def test_load_balancer_marker_selection(monkeypatch): @@ -804,39 +817,29 @@ def test_sanitizer_task_wiring(): def test_fuzz_native_task_wiring(): - """Run the daily fuzz-native task's scripts with plain subprocess.exec. + """Run the native fuzz tasks' scripts with plain subprocess.exec. The "run tests" function would reinstall pymongo without sanitizer flags and clobber the instrumented build. install-dependencies.sh bootstraps uv, which a fresh command shell does not inherit. """ - tasks = [task for task in all_tasks() if "fuzz-native" in (task.tags or [])] - assert len(tasks) == 1 - task = tasks[0] - assert "pr" not in task.tags - # Plain subprocess.exec only: no FunctionCall ("run tests") anywhere. - assert all(getattr(cmd, "func", None) is None for cmd in task.commands) - args = [cmd.params["args"] for cmd in task.commands] - assert args == [ - [".evergreen/scripts/install-dependencies.sh"], - ["fuzz/build_native.sh"], - ["fuzz/run_native.sh"], - ] - # The get_subprocess_exec defaults: bash, from the src dir. - assert all(cmd.params["binary"] == "bash" for cmd in task.commands) - assert all(cmd.params["working_dir"] == "src" for cmd in task.commands) - variants = [v for v in all_variants() if variant_selects(v, task)] - assert len(variants) == 1 - variant = variants[0] - assert variant.batchtime == generate_config_utils.BATCHTIME_DAY - assert variant.run_on == ["rhel8.7-large"] - # All the fuzz tasks share one nightly variant, so one patch build - # covers the whole family. - assert [ref.name for ref in variant.tasks] == [ - ".fuzz-nightly", - ".fuzz-regression", - ".fuzz-native", - ] + tasks = {task.name: task for task in all_tasks() if "fuzz-native" in (task.tags or [])} + assert sorted(tasks) == ["fuzz-native-full", "fuzz-native-regression"] + for name, task in tasks.items(): + # Plain subprocess.exec only: no FunctionCall ("run tests") anywhere. + assert all(getattr(cmd, "func", None) is None for cmd in task.commands), name + args = [cmd.params["args"] for cmd in task.commands] + assert args == [ + [".evergreen/scripts/install-dependencies.sh"], + ["fuzz/build_native.sh"], + ["fuzz/run_native.sh"], + ], name + # The get_subprocess_exec defaults: bash, from the src dir. + assert all(cmd.params["binary"] == "bash" for cmd in task.commands), name + assert all(cmd.params["working_dir"] == "src" for cmd in task.commands), name + # The pr tag keeps the replay off mainline and in PR patch builds. + assert "pr" in tasks["fuzz-native-regression"].tags + assert "pr" not in tasks["fuzz-native-full"].tags def test_upload_fuzz_artifacts_func(): diff --git a/fuzz/README.md b/fuzz/README.md index 1a9823f1eb..076f72202f 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -39,18 +39,9 @@ The Evergreen fuzz tasks pin Linux CPython 3.13 and are unaffected. ### Regression inputs (deterministic) -`regression/` holds reproducers for known bugs. Running the targets -over them runs on Evergreen as the `fuzz-regression` sub-test on every PR: - -```bash -just setup-tests fuzz regression -just run-tests -``` - -On every PR, the `fuzz-regression` task runs the committed reproducers and the full generated seed -corpus. - -Or without the justfile: +`regression/` holds reproducers for known bugs. The native runs seed +them into the corpus, so every PR and daily run replays them under ASan. +A local replay against the uninstrumented targets is: ```bash uv run --group fuzz python fuzz/fuzz_decode.py fuzz/regression/* -atheris_runs=3 @@ -150,6 +141,7 @@ packages are installed: ```bash bash fuzz/build_native.sh # instrumented build into the project venv FUZZ_MAX_TIME=60 bash fuzz/run_native.sh # time-boxed run over the seed corpus +FUZZ_MAX_TIME=0 bash fuzz/run_native.sh fuzz-scratch/corpus # replay a corpus, no mutation ``` The runner sets `FUZZ_NATIVE=1` (the targets skip atheris's own @@ -162,13 +154,19 @@ same as the sanitizer tests (PYTHON-6048). Like the weekly capture run, the corpus seeds from the spec seed corpus plus the committed `corpus/` and `regression/` units, replaying every known reproducer under ASan. -The `fuzz-native` Evergreen task bootstraps the environment and runs both -scripts daily in the nightly `Fuzz RHEL8` variant with pinned CPython -3.13. Crash artifacts under `fuzz-scratch/` upload as task artifacts, so -an ASan finding keeps its reproducer. `build_native.sh` installs pymongo -non-editably so the targets load the instrumented venv copy after the -in-tree cleanup. A developer's `.venv` stays non-editable until the next -plain `uv sync`. +Five Evergreen tasks run these scripts in one Fuzzing variant. On every +PR it replays the reproducers through the atheris targets +(`fuzz-python-regression`) and the whole corpus natively +(`fuzz-native-regression`, `FUZZ_MAX_TIME=0`: each unit runs once, +without mutation). On mainline it runs the full time-boxed flows daily +(`fuzz-python-full`, `fuzz-native-full`). The `fuzz-corpus-capture` +task runs weekly, fuzzing natively into `fuzz-scratch/corpus` and +replaying the coverage-increasing inputs under ASan before opening the +automated [Fuzz Corpus] PR. Crash artifacts under `fuzz-scratch/` upload +as task artifacts, so an ASan finding keeps its reproducer. +`build_native.sh` installs pymongo non-editably so the targets load the +instrumented venv copy after the in-tree cleanup. A developer's `.venv` +stays non-editable until the next plain `uv sync`. ## Files diff --git a/fuzz/run_native.sh b/fuzz/run_native.sh index f5de96b8fb..5b10ec4e1e 100755 --- a/fuzz/run_native.sh +++ b/fuzz/run_native.sh @@ -2,9 +2,12 @@ # Run the BSON fuzz targets against an ASan-instrumented build under # libFuzzer (PYTHON-6169). Expects fuzz/build_native.sh to have run. # -# Time-boxed per target (FUZZ_MAX_TIME seconds, default 300) against the -# generated seed corpus plus the committed fuzz/corpus/ units. Run from -# the repository root: +# Optional argument: the corpus directory (default fuzz-scratch/ +# native-corpus; the weekly capture passes fuzz-scratch/corpus, which +# capture_corpus.py harvests). +# +# FUZZ_MAX_TIME seconds per target, default 300. 0 replays every corpus +# unit once without mutating (the PR flow). Run from the repository root: # bash fuzz/run_native.sh set -euo pipefail @@ -13,9 +16,23 @@ cd "$ROOT" PYTHON=".venv/bin/python" SCRATCH="$ROOT/fuzz-scratch" -CORPUS="$SCRATCH/native-corpus" +CORPUS="${1:-$SCRATCH/native-corpus}" MAX_TIME="${FUZZ_MAX_TIME:-300}" +# Relative arguments resolve against the repository root, the script's cwd. +case "$CORPUS" in + /*) ;; + *) CORPUS="$ROOT/$CORPUS" ;; +esac +# rm -rf below requires the corpus to stay inside the repository. +case "$CORPUS" in + "$ROOT"/*) ;; + *) + echo "ERROR: corpus directory must live inside the repository." >&2 + exit 1 + ;; +esac + if [ ! -x "$PYTHON" ]; then echo "ERROR: $PYTHON not found. Run fuzz/build_native.sh first." >&2 exit 1 @@ -53,6 +70,14 @@ if [ -z "$(ls -A "$CORPUS")" ]; then exit 1 fi +# Baseline manifest: capture_corpus.py treats these digests as +# already-known, so only units discovered during the run get captured +# (setup_tests.py writes the same manifest for the atheris runs). +MANIFEST="$(dirname "$CORPUS")/baseline.txt" +for unit in "$CORPUS"/*; do + sha256sum "$unit" +done | awk '{print $1}' > "$MANIFEST" + # FUZZ_NATIVE=1: the targets read it and skip atheris's own libFuzzer, # which comes preloaded below. PYTHONMALLOC=malloc: ASan needs per-object # redzones and pymalloc has none, so the array.array over-reads are @@ -67,7 +92,15 @@ export LD_PRELOAD="$ATHERIS_RUNTIME" # Write libFuzzer crash artifacts under the scratch dir, which exists after # the corpus extraction. for target in fuzz_decode fuzz_decode_all fuzz_is_valid; do - "$PYTHON" "fuzz/$target.py" "$CORPUS" \ - "-artifact_prefix=$SCRATCH/" \ - "-max_total_time=$MAX_TIME" -max_len=1048576 -print_final_stats=1 + if [ "$MAX_TIME" -gt 0 ]; then + "$PYTHON" "fuzz/$target.py" "$CORPUS" \ + "-artifact_prefix=$SCRATCH/" \ + "-max_total_time=$MAX_TIME" -max_len=1048576 -print_final_stats=1 + else + # Replay-only (FUZZ_MAX_TIME=0, the PR flow): pass every corpus + # unit as a file argument, so libFuzzer runs each exactly once + # and exits. + "$PYTHON" "fuzz/$target.py" "$CORPUS"/* \ + "-artifact_prefix=$SCRATCH/" + fi done From ed99902c0b82ffe1490127b5a61e127418f898f6 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 17:10:03 -0600 Subject: [PATCH 06/16] Drop stale daily-run mentions from the fuzz docs --- fuzz/README.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/fuzz/README.md b/fuzz/README.md index 076f72202f..a671b2c41b 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -40,7 +40,7 @@ The Evergreen fuzz tasks pin Linux CPython 3.13 and are unaffected. ### Regression inputs (deterministic) `regression/` holds reproducers for known bugs. The native runs seed -them into the corpus, so every PR and daily run replays them under ASan. +them into the corpus, so every PR and mainline run replays them under ASan. A local replay against the uninstrumented targets is: ```bash @@ -64,13 +64,12 @@ uv run python -m zipfile -e /tmp/fuzz-seed.zip /tmp/fuzz-corpus The builder also synthesizes seeds the spec corpus lacks: boundary-value documents and a ~500 KB stress document. Without a large seed, libFuzzer's -default mutation cap of 4096 bytes would keep the nightly away from +default mutation cap of 4096 bytes would keep the fuzzer away from long-string and many-field code paths. -Run the targets against the corpus. Time-boxed runs suit CI; this runs on -Evergreen as the `fuzz` sub-test, daily. The nightly `fuzz` task is crash -discovery only; the weekly `fuzz-capture` task fuzzes and captures the -corpus (below): +Run the targets against the corpus. Time-boxed runs suit CI; on Evergreen +this is the `fuzz-python-full` task, crash discovery only; the weekly +`fuzz-corpus-capture` task fuzzes and captures the corpus (below): ```bash just setup-tests fuzz fuzz @@ -158,7 +157,7 @@ Five Evergreen tasks run these scripts in one Fuzzing variant. On every PR it replays the reproducers through the atheris targets (`fuzz-python-regression`) and the whole corpus natively (`fuzz-native-regression`, `FUZZ_MAX_TIME=0`: each unit runs once, -without mutation). On mainline it runs the full time-boxed flows daily +without mutation). On mainline it runs the full time-boxed flows (`fuzz-python-full`, `fuzz-native-full`). The `fuzz-corpus-capture` task runs weekly, fuzzing natively into `fuzz-scratch/corpus` and replaying the coverage-increasing inputs under ASan before opening the From 94cd290895c60aa05d4e3cd5e571f819bb277366 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 17:23:53 -0600 Subject: [PATCH 07/16] consolidate the tasks --- .evergreen/generated_configs/tasks.yml | 8 ------- .evergreen/generated_configs/variants.yml | 1 - .evergreen/scripts/generate_config.py | 16 ++++--------- .evergreen/scripts/run_tests.py | 27 ---------------------- .evergreen/scripts/setup_tests.py | 20 ++++++++-------- .evergreen/scripts/test_generate_config.py | 16 +++++-------- fuzz/README.md | 18 +++++++-------- 7 files changed, 28 insertions(+), 78 deletions(-) diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index a34068114a..cc0544ec2f 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -206,14 +206,6 @@ tasks: tags: [coverage, pr] # Fuzz tests - - name: fuzz-python-regression - commands: - - func: run tests - vars: - TEST_NAME: fuzz - SUB_TEST_NAME: regression - UV_PYTHON: "3.13" - tags: [fuzz, fuzz-python, pr] - name: fuzz-native-regression commands: - command: subprocess.exec diff --git a/.evergreen/generated_configs/variants.yml b/.evergreen/generated_configs/variants.yml index 2418038fd5..e1eebb1225 100644 --- a/.evergreen/generated_configs/variants.yml +++ b/.evergreen/generated_configs/variants.yml @@ -203,7 +203,6 @@ buildvariants: # Fuzz tests - name: fuzzing-rhel8 tasks: - - name: fuzz-python-regression - name: fuzz-native-regression - name: fuzz-python-full - name: fuzz-native-full diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index 251d17a444..ccfa205d5c 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -400,7 +400,6 @@ def create_fuzz_variants(): return [ create_variant( [ - "fuzz-python-regression", "fuzz-native-regression", "fuzz-python-full", "fuzz-native-full", @@ -724,18 +723,11 @@ def create_no_orchestration_tasks(): def create_fuzz_tasks(): - # Deterministic replay of the committed reproducers through the atheris - # targets (PYTHON-4232). - tags = ["fuzz", "fuzz-python", "pr"] - test_vars = dict(TEST_NAME="fuzz", SUB_TEST_NAME="regression", UV_PYTHON="3.13") - test_func = FunctionCall(func="run tests", vars=test_vars) - tasks = [EvgTask(name="fuzz-python-regression", tags=tags, commands=[test_func])] - - # Native replay of the whole corpus (PYTHON-6169): FUZZ_MAX_TIME=0 - # makes libFuzzer run each unit once and exit. + # Native replay of the whole corpus on every PR (PYTHON-6169): + # FUZZ_MAX_TIME=0 makes libFuzzer run each unit once and exit. build_cmd = get_subprocess_exec(args=["fuzz/build_native.sh"]) install_cmd = get_subprocess_exec(args=[".evergreen/scripts/install-dependencies.sh"]) - tasks.append( + tasks = [ EvgTask( name="fuzz-native-regression", tags=["fuzz", "fuzz-native", "pr"], @@ -745,7 +737,7 @@ def create_fuzz_tasks(): get_subprocess_exec(args=["fuzz/run_native.sh"], env=dict(FUZZ_MAX_TIME="0")), ], ) - ) + ] # Time-boxed atheris fuzzing on mainline, for crash discovery. tags = ["fuzz", "fuzz-python"] diff --git a/.evergreen/scripts/run_tests.py b/.evergreen/scripts/run_tests.py index 8f9802ffcb..9106b40924 100644 --- a/.evergreen/scripts/run_tests.py +++ b/.evergreen/scripts/run_tests.py @@ -149,33 +149,6 @@ def handle_fuzz() -> None: """Run the BSON fuzz targets (PYTHON-4232). Not pytest-based.""" targets = ["fuzz_decode", "fuzz_decode_all", "fuzz_is_valid"] - if SUB_TEST_NAME == "regression": - # Run the committed reproducers plus the seed corpus. - # Skip dotfiles (pathlib globbing matches them). - inputs = sorted( - str(p) for p in (ROOT / "fuzz" / "regression").glob("*") if not p.name.startswith(".") - ) - if not inputs: - raise RuntimeError("No fuzz regression inputs found in fuzz/regression/") - corpus_dir = os.environ.get("FUZZ_CORPUS_DIR", str(ROOT / "fuzz-scratch" / "corpus")) - # Fail fast on a missing or empty corpus; libFuzzer would silently skip it. - corpus_files = sorted( - str(p) for p in Path(corpus_dir).glob("*") if not p.name.startswith(".") - ) - if not corpus_files: - raise RuntimeError( - f"No fuzz seed corpus found in {corpus_dir}; was setup_tests.py run?" - ) - inputs.extend(corpus_files) - # Each input runs once: -atheris_runs equals the file count, so - # atheris exits cleanly after the last one. - runs = len(inputs) - for target in targets: - run_command( - f"{sys.executable} fuzz/{target}.py {' '.join(inputs)} -atheris_runs={runs}" - ) - return - # Time-boxed fuzzing against the generated seed corpus. corpus_dir = os.environ.get("FUZZ_CORPUS_DIR", str(ROOT / "fuzz-scratch" / "corpus")) # Fail fast: libFuzzer would burn the whole budget without the seeds. diff --git a/.evergreen/scripts/setup_tests.py b/.evergreen/scripts/setup_tests.py index de31ca4b9c..9771e5d5a5 100644 --- a/.evergreen/scripts/setup_tests.py +++ b/.evergreen/scripts/setup_tests.py @@ -598,17 +598,15 @@ def handle_test_env() -> None: with zipfile.ZipFile(zip_path) as zf: zf.extractall(corpus_dir) zip_path.unlink() - if sub_test_name == "fuzz": - # PYTHON-6178 Also seed from the committed corpus of previously - # captured inputs, so the full run builds on prior discoveries - # instead of the spec seeds alone. Regression runs (PRs) keep - # running only the reproducers and the spec seed corpus. - committed_dir = ROOT / "fuzz" / "corpus" - if committed_dir.is_dir(): - for path in sorted(committed_dir.iterdir()): - if path.name.startswith("."): - continue - shutil.copyfile(path, corpus_dir / path.name) + # PYTHON-6178 Also seed from the committed corpus of previously + # captured inputs, so the run builds on prior discoveries instead + # of the spec seeds alone. + committed_dir = ROOT / "fuzz" / "corpus" + if committed_dir.is_dir(): + for path in sorted(committed_dir.iterdir()): + if path.name.startswith("."): + continue + shutil.copyfile(path, corpus_dir / path.name) # Manifest of every input this run starts from; capture_corpus.py # treats these digests as already-known, so only units the fuzzer # discovered during the run get captured. diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 1a7a5742ae..845343a871 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -443,9 +443,9 @@ def test_non_standard_cov_tasks_have_no_cov_companions(): def test_fuzz_task_wiring(): """Test the fuzz task wiring. - Five flows in one Fuzzing variant. A task's "pr" tag keeps it out of - mainline builds and selects it into PR patch builds, so the replays - gate PRs and the full flows run only on mainline. + Four flows in one Fuzzing variant. A task's "pr" tag keeps it out of + mainline builds and selects it into PR patch builds, so the native + replay gates PRs and the full flows run only on mainline. """ tasks = {task.name: task for task in all_tasks() if "fuzz" in (task.tags or [])} assert sorted(tasks) == [ @@ -453,21 +453,18 @@ def test_fuzz_task_wiring(): "fuzz-native-full", "fuzz-native-regression", "fuzz-python-full", - "fuzz-python-regression", ] assert sorted(task.name for task in tasks.values() if "pr" in (task.tags or [])) == [ "fuzz-native-regression", - "fuzz-python-regression", ] variants = generate_config.create_fuzz_variants() assert len(variants) == 1 fuzzing = variants[0] assert not fuzzing.tags assert fuzzing.batchtime == generate_config_utils.BATCHTIME_DAY - # All five flows share the variant. The capture ref carries its own + # All four flows share the variant. The capture ref carries its own # weekly batchtime, which overrides the variant's daily one. assert [ref.name for ref in fuzzing.tasks] == [ - "fuzz-python-regression", "fuzz-native-regression", "fuzz-python-full", "fuzz-native-full", @@ -480,9 +477,8 @@ def test_fuzz_task_wiring(): # The fuzz family runs on the large rhel8.7 distro, like the other # drivers' fuzz jobs. assert fuzzing.run_on == ["rhel8.7-large"] - # The python flows go through the "run tests" function: the regression - # replay for PRs, time-boxed discovery for mainline. - assert tasks["fuzz-python-regression"].commands[-1].func == "run tests" + # The python flow goes through the "run tests" function: time-boxed + # discovery on mainline. assert tasks["fuzz-python-full"].commands[-1].func == "run tests" native_regression_run = tasks["fuzz-native-regression"].commands[-1] assert native_regression_run.params["args"] == ["fuzz/run_native.sh"] diff --git a/fuzz/README.md b/fuzz/README.md index a671b2c41b..12b81b76cf 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -44,9 +44,10 @@ them into the corpus, so every PR and mainline run replays them under ASan. A local replay against the uninstrumented targets is: ```bash -uv run --group fuzz python fuzz/fuzz_decode.py fuzz/regression/* -atheris_runs=3 -uv run --group fuzz python fuzz/fuzz_decode_all.py fuzz/regression/* -atheris_runs=3 -uv run --group fuzz python fuzz/fuzz_is_valid.py fuzz/regression/* -atheris_runs=3 +runs="$(ls fuzz/regression | wc -l)" +uv run --group fuzz python fuzz/fuzz_decode.py fuzz/regression/* -atheris_runs="$runs" +uv run --group fuzz python fuzz/fuzz_decode_all.py fuzz/regression/* -atheris_runs="$runs" +uv run --group fuzz python fuzz/fuzz_is_valid.py fuzz/regression/* -atheris_runs="$runs" ``` When a target finds a bug, create a new ticket, add the reproducer as a new @@ -153,12 +154,11 @@ same as the sanitizer tests (PYTHON-6048). Like the weekly capture run, the corpus seeds from the spec seed corpus plus the committed `corpus/` and `regression/` units, replaying every known reproducer under ASan. -Five Evergreen tasks run these scripts in one Fuzzing variant. On every -PR it replays the reproducers through the atheris targets -(`fuzz-python-regression`) and the whole corpus natively -(`fuzz-native-regression`, `FUZZ_MAX_TIME=0`: each unit runs once, -without mutation). On mainline it runs the full time-boxed flows -(`fuzz-python-full`, `fuzz-native-full`). The `fuzz-corpus-capture` +Four Evergreen tasks run these scripts in one Fuzzing variant. On every +PR it replays the whole corpus natively (`fuzz-native-regression`, +`FUZZ_MAX_TIME=0`: each unit runs once, without mutation). On mainline +it runs the full time-boxed flows (`fuzz-python-full`, +`fuzz-native-full`). The `fuzz-corpus-capture` task runs weekly, fuzzing natively into `fuzz-scratch/corpus` and replaying the coverage-increasing inputs under ASan before opening the automated [Fuzz Corpus] PR. Crash artifacts under `fuzz-scratch/` upload From 5cb1cb297696a64b2d3f2f4b3d71ca7c692eb120 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 17:32:22 -0600 Subject: [PATCH 08/16] address copilot review --- fuzz/run_native.sh | 49 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/fuzz/run_native.sh b/fuzz/run_native.sh index 5b10ec4e1e..d6b3f5527e 100755 --- a/fuzz/run_native.sh +++ b/fuzz/run_native.sh @@ -3,15 +3,18 @@ # libFuzzer (PYTHON-6169). Expects fuzz/build_native.sh to have run. # # Optional argument: the corpus directory (default fuzz-scratch/ -# native-corpus; the weekly capture passes fuzz-scratch/corpus, which -# capture_corpus.py harvests). +# native-corpus, rebuilt from seeds each run; an explicit directory is +# kept, with the seeds added to it). The weekly capture passes +# fuzz-scratch/corpus, which capture_corpus.py harvests. # # FUZZ_MAX_TIME seconds per target, default 300. 0 replays every corpus # unit once without mutating (the PR flow). Run from the repository root: # bash fuzz/run_native.sh set -euo pipefail -ROOT=$(git rev-parse --show-toplevel) +# Canonical root: the containment check below compares real paths, so a +# symlinked checkout must resolve first. +ROOT=$(cd "$(git rev-parse --show-toplevel)" && pwd -P) cd "$ROOT" PYTHON=".venv/bin/python" @@ -24,14 +27,6 @@ case "$CORPUS" in /*) ;; *) CORPUS="$ROOT/$CORPUS" ;; esac -# rm -rf below requires the corpus to stay inside the repository. -case "$CORPUS" in - "$ROOT"/*) ;; - *) - echo "ERROR: corpus directory must live inside the repository." >&2 - exit 1 - ;; -esac if [ ! -x "$PYTHON" ]; then echo "ERROR: $PYTHON not found. Run fuzz/build_native.sh first." >&2 @@ -49,10 +44,35 @@ if ! nm "$SO" 2>/dev/null | grep -E "__asan|__sanitizer_cov|check_load_add|check exit 1 fi +# Canonicalize the corpus path (symlinks and ..) before any deletion: the +# containment check must see where the path really resolves (PYTHON-6169). +CORPUS=$("$PYTHON" -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$CORPUS") +case "$CORPUS" in + "$ROOT"/*) ;; + *) + echo "ERROR: corpus directory must live inside the repository." >&2 + exit 1 + ;; +esac +# Managed seed sources: copying the seeds into them would collide with +# themselves. +case "$CORPUS" in + "$ROOT"/fuzz/corpus | "$ROOT"/fuzz/regression) + echo "ERROR: pass a corpus directory, not a seed source." >&2 + exit 1 + ;; +esac + # Build the seed corpus from the vendored spec data. build_corpus.py forces # the pure-Python implementation, so it is safe under an instrumented venv. -rm -rf "$CORPUS" -mkdir -p "$CORPUS" +# The default corpus is rebuilt from seeds every run; an explicit corpus is +# preserved, with the seeds added to it, so replaying never deletes locally +# discovered inputs. +mkdir -p "$CORPUS" "$SCRATCH" +if [ "$#" -eq 0 ]; then + rm -rf "$CORPUS" + mkdir -p "$CORPUS" +fi ZIP="$SCRATCH/native-corpus-seed.zip" "$PYTHON" fuzz/build_corpus.py "$ZIP" --data-dir test/bson_corpus "$PYTHON" -m zipfile -e "$ZIP" "$CORPUS" @@ -89,8 +109,7 @@ export ASAN_OPTIONS="detect_leaks=0" ATHERIS_RUNTIME="$($PYTHON -c 'import atheris; print(atheris.path())')/asan_with_fuzzer.so" export LD_PRELOAD="$ATHERIS_RUNTIME" -# Write libFuzzer crash artifacts under the scratch dir, which exists after -# the corpus extraction. +# Write libFuzzer crash artifacts under the scratch dir. for target in fuzz_decode fuzz_decode_all fuzz_is_valid; do if [ "$MAX_TIME" -gt 0 ]; then "$PYTHON" "fuzz/$target.py" "$CORPUS" \ From 82f5de783d6341a22b560f45b062fe0ee3acf9ed Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 19:37:23 -0600 Subject: [PATCH 09/16] Update the fuzz docs for the consolidated tasks --- CONTRIBUTING.md | 13 +++++++------ fuzz/README.md | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d16f95e5db..5adbccd59c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -450,16 +450,17 @@ The `fuzz/` directory holds coverage-guided fuzz tests for `bson` tests can only be run on Linux x86_64, the only platform with atheris wheels (CPython 3.12-3.14). -- Regression test (runs on every PR): - `just setup-tests fuzz regression` then `just run-tests`. +- Replay the committed corpus under ASan (runs on every PR): the + `fuzz-native-regression` task. Local replays are covered in + [fuzz/README.md](fuzz/README.md). - Time-boxed fuzzing for crash discovery (runs daily on Evergreen): `just setup-tests fuzz fuzz` then `just run-tests`. Set `FUZZ_MAX_TIME` (seconds, default 300) to change the per-target budget. -- Weekly capture (runs weekly on Evergreen): the `fuzz-capture` task also - fuzzes, then captures coverage-increasing inputs into `fuzz/corpus/` - via an automated PR (PYTHON-6178); see [fuzz/README.md](fuzz/README.md). +- Weekly capture (runs weekly on Evergreen): the `fuzz-corpus-capture` + task also fuzzes, then captures coverage-increasing inputs into + `fuzz/corpus/` via an automated PR (PYTHON-6178); see [fuzz/README.md](fuzz/README.md). To run that flow on demand, patch the task: - `evergreen patch --variant fuzz-capture-rhel8 --task fuzz-capture`. + `evergreen patch --variant fuzzing-rhel8 --task fuzz-corpus-capture`. ## Testing time-dependent operations diff --git a/fuzz/README.md b/fuzz/README.md index 12b81b76cf..1d2858e8a5 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -93,7 +93,7 @@ for instrumented native runs see "Native ASan fuzzing" below. The weekly capture run seeds from the spec seed corpus plus every unit in `corpus/`, and libFuzzer writes each coverage-increasing ("interesting") input it discovers back into its corpus directory. After the targets -finish, the `fuzz-capture` task captures those new units, replays them +finish, the `fuzz-corpus-capture` task captures those new units, replays them through every target once so a unit that fails any target is never published (it stays in `fuzz-scratch/` for triage), and opens an automated "[Fuzz Corpus]" PR against main (PYTHON-6178). Later weeks From df87f2e883be68d865853dd1a16ac084999f632d Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 19:49:32 -0600 Subject: [PATCH 10/16] Trim docstrings in the fuzz scripts and tests --- .evergreen/scripts/test_generate_config.py | 11 ++++------- test/test_fuzz_shared.py | 22 +++++----------------- 2 files changed, 9 insertions(+), 24 deletions(-) diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 845343a871..9ece456a52 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -1,7 +1,5 @@ """Sanity checks for the Evergreen config generation. -Also regression tests for the .evergreen script fixes in PYTHON-6167. - Run: pytest .evergreen/scripts/test_generate_config.py -m "" (-m "" clears the repo-wide marker filter.) Requires the generate-config hook's dependencies: pytest, pytest-asyncio, shrub.py, pyyaml. @@ -204,11 +202,10 @@ def test_pr_tasks_effectively_pin_max_version(): def test_server_version_pr_tasks_selected_once(): """A pr server-version task must be selected only by its matching variant. - The variant must run the server version the task 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 + 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 [])] diff --git a/test/test_fuzz_shared.py b/test/test_fuzz_shared.py index 692e4f58bd..29926dba61 100644 --- a/test/test_fuzz_shared.py +++ b/test/test_fuzz_shared.py @@ -56,10 +56,7 @@ def test_input_views_native_adds_sentinel_free_array(monkeypatch, data): def test_array_view_decodes_like_bytes(): - """Test that bson.decode() accepts an array view like bytes. - - The decoded result must equal the bytes result. - """ + """Test that bson.decode() accepts an array view like bytes.""" import bson doc = bson.encode({"a": "bc", "b": 123}) @@ -71,7 +68,6 @@ def test_overread_input_rejected_for_both_views(): The C extension's regex decoder is bounds-checked (PYTHON-6110), so the over-read is rejected rather than masked by bytes' hidden NUL sentinel. - The sentinel-free array view decodes exactly like bytes. """ import bson @@ -116,9 +112,8 @@ def fuzz_targets(monkeypatch): def test_targets_handle_every_view(fuzz_targets, monkeypatch, data): """Run every target's TestOneInput over both views. - decode and decode_all see both views; fuzz_is_valid keeps is_valid() - on the raw bytes (it raises TypeError for other buffers) and runs - only decode() over both views. + fuzz_is_valid keeps is_valid() on the raw bytes (it raises TypeError + for other buffers) and runs only decode() over both views. """ monkeypatch.setenv("FUZZ_NATIVE", "1") fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets @@ -129,10 +124,7 @@ def test_targets_handle_every_view(fuzz_targets, monkeypatch, data): def test_targets_accept_valid_documents_in_native_mode(fuzz_targets, monkeypatch): - """Round-trip a valid document through every view in native mode. - - The targets' consistency assertions must not fail. - """ + """Round-trip a valid document through every view in native mode.""" monkeypatch.setenv("FUZZ_NATIVE", "1") fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets @@ -148,11 +140,7 @@ def test_regression_files_replay_cleanly(fuzz_targets, monkeypatch): """Replay every committed reproducer in fuzz/regression/decode__*. Each must replay cleanly through both implementations over every input - view: the C extension and pure-Python must agree, and no exception may - escape the targets' expected-error handling. Includes the PYTHON-6256 - reproducers for the array-decoding heap-buffer-overflow reads found by - PYTHON-6169's native ASan fuzzer (the sanitizer replay is covered by - the fuzz-native task). + view: no exception may escape the targets' expected-error handling. """ monkeypatch.setenv("FUZZ_NATIVE", "1") fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets From 76bb1f85292853b82b19f82817ee3541001d7bfd Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 19:54:15 -0600 Subject: [PATCH 11/16] address coding standards --- fuzz/build_native.sh | 6 ++++-- fuzz/fuzz_shared.py | 5 ++++- fuzz/run_native.sh | 3 ++- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/fuzz/build_native.sh b/fuzz/build_native.sh index ce335d1ca9..7c17e71071 100755 --- a/fuzz/build_native.sh +++ b/fuzz/build_native.sh @@ -75,7 +75,8 @@ SO=$(ls "$SITE_PACKAGES"/bson/_cbson*.so) ATHERIS_DIR=$(.venv/bin/python -c 'import atheris; print(atheris.path())') if [ ! -f "$ATHERIS_DIR/asan_with_fuzzer.so" ]; then - echo "ERROR: $ATHERIS_DIR/asan_with_fuzzer.so is missing. atheris could not provide the runtime." >&2 + echo "ERROR: $ATHERIS_DIR/asan_with_fuzzer.so is missing. atheris could" >&2 + echo "not provide the runtime." >&2 exit 1 fi @@ -87,7 +88,8 @@ if ! FUZZ_NATIVE=1 LD_PRELOAD="$ATHERIS_DIR/asan_with_fuzzer.so" \ exit 1 fi -if ! nm "$SO" 2>/dev/null | grep -E "__asan|__sanitizer_cov|check_load_add|check_store_add" > /dev/null; then +PATTERN="__asan|__sanitizer_cov|check_load_add|check_store_add" +if ! nm "$SO" 2>/dev/null | grep -E "$PATTERN" > /dev/null; then echo "WARNING: $SO shows no ASan/sancov symbols with nm. The smoke import" >&2 echo "passed, so the extension works, but instrumentation is unproven." >&2 echo "--- diagnostics:" >&2 diff --git a/fuzz/fuzz_shared.py b/fuzz/fuzz_shared.py index afeec190a8..4d659ae87c 100755 --- a/fuzz/fuzz_shared.py +++ b/fuzz/fuzz_shared.py @@ -15,7 +15,10 @@ def load_pure_python_bson(): - """Re-import bson with the C extension blocked, then restore sys.modules.""" + """Re-import bson with the C extension blocked, then restore sys.modules. + + Raises RuntimeError if the pure-Python implementation cannot be loaded. + """ saved = { k: sys.modules.pop(k) for k in list(sys.modules) if k == "bson" or k.startswith("bson.") } diff --git a/fuzz/run_native.sh b/fuzz/run_native.sh index d6b3f5527e..734cb81fef 100755 --- a/fuzz/run_native.sh +++ b/fuzz/run_native.sh @@ -39,7 +39,8 @@ fi # checks (PYTHON-6169). grep without -q: with pipefail, grep -q's early exit # SIGPIPEs nm on a large symbol table and the pipeline fails even on a match. SO=$(ls .venv/lib/python3.*/site-packages/bson/_cbson*.so) -if ! nm "$SO" 2>/dev/null | grep -E "__asan|__sanitizer_cov|check_load_add|check_store_add" > /dev/null; then +PATTERN="__asan|__sanitizer_cov|check_load_add|check_store_add" +if ! nm "$SO" 2>/dev/null | grep -E "$PATTERN" > /dev/null; then echo "ERROR: $SO is not ASan-instrumented. Run fuzz/build_native.sh first." >&2 exit 1 fi From 627fbfeda6a979fdea39dd189383945977055386 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 20:01:07 -0600 Subject: [PATCH 12/16] trim comments --- .evergreen/scripts/test_generate_config.py | 14 +++++++------- test/test_fuzz_shared.py | 7 +++---- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 9ece456a52..4e4950c6d0 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -459,8 +459,8 @@ def test_fuzz_task_wiring(): fuzzing = variants[0] assert not fuzzing.tags assert fuzzing.batchtime == generate_config_utils.BATCHTIME_DAY - # All four flows share the variant. The capture ref carries its own - # weekly batchtime, which overrides the variant's daily one. + # All four flows share the variant, with the capture ref's weekly + # batchtime overriding the variant's daily one. assert [ref.name for ref in fuzzing.tasks] == [ "fuzz-native-regression", "fuzz-python-full", @@ -553,11 +553,11 @@ def test_ensure_openssl3_escapes_persisted_values(monkeypatch, tmp_path): setup_tests.ensure_openssl3() - # The payload must not have executed at write time... + # The payload must not have executed at write time. assert not (Path.cwd() / "pwned.txt").exists() assert not (tmp_path / "pwned.txt").exists() - # ...nor when the persisted environment is sourced: the values round-trip - # literally. + # The exported values must round-trip literally through the persisted + # environment file. env = subprocess.run( # noqa: S603 ["/bin/bash", "-c", '. "$1" >/dev/null && env', "bash", str(env_file)], capture_output=True, @@ -733,8 +733,8 @@ def test_crypt_shared_escapes_backslashes(monkeypatch, tmp_path): env_file = tmp_path / "test-env.sh" monkeypatch.setattr(utils, "ENV_FILE", env_file) monkeypatch.setattr(setup_tests, "ENV_FILE", env_file) - # The secrets service writes the path bash-escaped; read_env sees the - # literal, so persist its escaping. + # The secrets service writes the path bash-escaped, so persist its + # escaping for read_env to see the literal. escaped_payload = "\\$(touch cs-pwned.txt)" literal_payload = "$(touch cs-pwned.txt)" drivers_tools = tmp_path / "drivers-tools" diff --git a/test/test_fuzz_shared.py b/test/test_fuzz_shared.py index 29926dba61..5731bac28c 100644 --- a/test/test_fuzz_shared.py +++ b/test/test_fuzz_shared.py @@ -17,10 +17,9 @@ OVERREAD_INPUT = b"\x08\x00\x00\x00\x0b\x61\x00\x00" -# Explicit "default" markers: the repo's collection hook only auto-marks -# items with no markers, and @pytest.mark.parametrize is a marker, so the -# parametrized tests would otherwise be deselected by the default -# "-m default or default_async" filter. +# Explicit "default" markers: the collection hook auto-marks only unmarked +# modules, so parametrized tests would be deselected by the repo's +# default-marker filter. @pytest.mark.default @pytest.mark.parametrize("data", [b"", b"\x08\x00\x00\x00\x00", OVERREAD_INPUT]) def test_input_views_bytes_by_default(monkeypatch, data): From 77ae0ba121676e261508ef977f066f95b3459507 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 20:08:07 -0600 Subject: [PATCH 13/16] Trim test docstrings to one sentence --- .evergreen/scripts/test_generate_config.py | 157 ++++----------------- test/test_fuzz_shared.py | 33 +---- 2 files changed, 30 insertions(+), 160 deletions(-) diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 4e4950c6d0..85b9d15be2 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -103,12 +103,7 @@ def test_generation_sanity(): def test_variants_select_tasks(): - """Check every variant selects at least one task. - - Every suite-family task is selected by at least one variant: a family - restructured without variant wiring would silently never run - (PYTHON-6167). - """ + """Check every variant selects at least one task.""" tasks = all_tasks() for variant in all_variants(): assert any(variant_selects(variant, task) for task in tasks), ( @@ -122,11 +117,7 @@ def test_variants_select_tasks(): def test_suite_families(): - """Check each per-suite family identifies its suite. - - The name and TEST_NAME identify the suite, and no family task mixes - min-deps with coverage (PYTHON-6167). - """ + """Check each per-suite family identifies its suite.""" for family, suite in SUITE_FAMILIES.items(): for task in [t for t in all_tasks() if family in (t.tags or [])]: where = f"{family} {task.name}" @@ -139,12 +130,7 @@ def test_suite_families(): def test_pr_tasks_pin_max_version(): - """Task-level pins: pr tasks pin MAX_VERSION. - - The "latest" nightly is unstable; the explicit 4.4 min-deps pin is the - exception. Variant-merged pins are checked by - test_pr_tasks_effectively_pin_max_version. - """ + """Task-level pins: pr tasks pin MAX_VERSION, except the 4.4 min-deps pin.""" offenders = [ (task.name, task_vars(task).get("VERSION")) for task in pr_tasks() @@ -157,11 +143,7 @@ def test_pr_tasks_pin_max_version(): def test_suite_families_have_pr_pins(): - """Run every suite family at least once on PR patches, with coverage. - - A restructure cannot then silently drop a family from the patch build - or the codecov report (PYTHON-6167). - """ + """Run every suite family at least once on PR patches, with coverage.""" for family in SUITE_FAMILIES: pinned = [ task @@ -174,12 +156,7 @@ def test_suite_families_have_pr_pins(): def test_pr_tasks_effectively_pin_max_version(): - """Effective pins: every pr task that runs a server resolves to MAX_VERSION. - - A pr task without its own VERSION var inherits the selecting variant's - version once variant expansions merge in. The explicit 4.4 min-deps - pin is the exception. - """ + """Effective pins: pr server tasks resolve to MAX_VERSION, except the 4.4 pin.""" tasks = [task for task in all_tasks() if "pr" in (task.tags or [])] offenders = [] for variant in all_variants(): @@ -200,14 +177,7 @@ def test_pr_tasks_effectively_pin_max_version(): def test_server_version_pr_tasks_selected_once(): - """A pr server-version task must be selected only by its matching variant. - - 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). - """ + """A pr server-version task must be selected only by its matching variant.""" sv_tasks = [task for task in pr_tasks() if "server-version" in (task.tags or [])] sv_variants = generate_config.create_server_version_variants() offenders = {} @@ -227,11 +197,7 @@ def test_server_version_pr_tasks_selected_once(): def test_pr_tasks_cover_version_boundaries(): - """PRs test the server version boundaries. - - The newest numbered server runs with every Python boundary, the min - server with its min-Python floor. - """ + """PRs test the server version boundaries.""" for version, pythons in ( ( generate_config_utils.MAX_VERSION, @@ -252,11 +218,7 @@ def test_pr_tasks_cover_version_boundaries(): def test_amazon2023_no_toolchain_variant_runs_on_prs(): - """Keep the no-toolchain variant on PR patches. - - The Amazon Linux host has no Python toolchain, so its no-toolchain - variant must keep running on PR patches (PYTHON-6167). - """ + """Keep the no-toolchain variant on PR patches.""" (variant,) = [v for v in all_variants() if "amazon2023" in v.name] assert "pr" in (variant.tags or []) selected = [task for task in all_tasks() if variant_selects(variant, task)] @@ -265,10 +227,7 @@ def test_amazon2023_no_toolchain_variant_runs_on_prs(): def test_server_version_rotated_tasks_keep_coverage(): - """Per-commit coverage for this family rides the rotated boundary-Python tasks. - - Not the pr tasks, which run only on MAX_VERSION. - """ + """Per-commit coverage for this family rides the rotated boundary-Python tasks.""" family = [task for task in all_tasks() if "server-version" in (task.tags or [])] cov = [task for task in family if task_vars(task).get("COVERAGE") == "1"] assert any("pr" not in (task.tags or []) for task in cov), ( @@ -291,11 +250,7 @@ def test_server_version_rotated_tasks_keep_coverage(): def test_numpy_win32_tasks_run_on_windows_only(): - """Keep the win32 numpy tasks on the windows variant. - - They use the 32-bit toolchain (IS_WIN32) and must be selected only by - the windows variant (PYTHON-6167). - """ + """Keep the win32 numpy tasks on the windows variant.""" win32_tasks = [task for task in all_tasks() if "test-numpy-win32" in (task.tags or [])] assert win32_tasks, "no win32 numpy tasks" for task in win32_tasks: @@ -314,11 +269,7 @@ def test_numpy_win32_tasks_run_on_windows_only(): def test_run_tests_env_carries_crypt_shared(): - """Check the run tests setup env carries TEST_CRYPT_SHARED. - - setup_tests.py reads it to wire the crypt_shared lib directory - (PYTHON-6167). - """ + """Check the run tests setup env carries TEST_CRYPT_SHARED.""" _, cmds = generate_config.create_run_tests_func() setup_cmd = cmds[0] includes = setup_cmd.params["include_expansions_in_env"] @@ -336,11 +287,7 @@ def test_pr_min_deps_tasks_also_run_coverage(): def test_standard_family_pr_budget(): - """Patch-build PR budget for test-standard pr tasks. - - At most 5 (the pre-pin baseline), at most 3 on Python 3.14+ (the - ubuntu22 compression filter). - """ + """Patch-build PR budget for test-standard pr tasks: at most 5, at most 3 on 3.14+.""" tasks = [task for task in pr_tasks() if "test-standard" in (task.tags or [])] assert len(tasks) <= 5, f"too many test-standard PR tasks: {[t.name for t in tasks]}" newer = [ @@ -355,12 +302,7 @@ def test_standard_family_pr_budget(): def test_pr_tasks_run_coverage(): - """Pr tasks that pin a server version run with COVERAGE=1. - - No-cov companions, infrastructure tasks (no VERSION), and the - encryption tasks (their suites exceed the coverage timeout on - macOS/Win64, PYTHON-6167) are exempt. - """ + """Pr tasks that pin a server version run with COVERAGE=1.""" offenders = [ task.name for task in pr_tasks() @@ -373,11 +315,7 @@ def test_pr_tasks_run_coverage(): def test_rotated_tasks_keep_nightly_coverage(): - """Batch coverage rides the rotation independently of the pr tasks. - - Rotated "latest" tasks and max-Python auth-aws tasks keep COVERAGE=1 - (min-deps excepted). - """ + """Batch coverage rides the rotation independently of the pr tasks.""" offenders = [] for task in all_tasks(): tags = task.tags or [] @@ -423,11 +361,7 @@ def test_rotated_tasks_keep_nightly_coverage(): def test_non_standard_cov_tasks_have_no_cov_companions(): - """Each non-standard coverage task also emits a no-cov companion. - - The macOS/Win64 encryption variants (which filter .cov) have a task to - activate in patch builds. - """ + """Each non-standard coverage task also emits a no-cov companion.""" no_cov = {task.name for task in all_tasks() if "test-non-standard-no-cov" in (task.tags or [])} for task in all_tasks(): if "test-non-standard-no-cov" in (task.tags or []): @@ -502,11 +436,7 @@ def test_fuzz_task_wiring(): def test_load_balancer_marker_selection(monkeypatch): - """The load balancer tasks select the load_balancer marker explicitly. - - pytest_conf.py only grants the implicit default markers to unmarked - tests (PYTHON-6167). - """ + """The load balancer tasks select the load_balancer marker explicitly.""" import run_tests monkeypatch.setattr(run_tests, "TEST_NAME", "load_balancer") @@ -520,11 +450,7 @@ def test_load_balancer_marker_selection(monkeypatch): def test_ensure_openssl3_escapes_persisted_values(monkeypatch, tmp_path): - """Reject DRIVERS_TOOLS paths carrying command substitution. - - A hostile path must not execute at write time or when the persisted - env.sh is sourced (PYTHON-6167). - """ + """Reject DRIVERS_TOOLS paths carrying command substitution.""" import subprocess import setup_tests @@ -571,11 +497,7 @@ def test_ensure_openssl3_escapes_persisted_values(monkeypatch, tmp_path): def test_crypt_shared_persisted_to_env(monkeypatch, tmp_path): - """Check the crypt_shared setup persists TEST_CRYPT_SHARED. - - The encryption tests use it to decide whether to run their crypt_shared - cases (PYTHON-6167). - """ + """Check the crypt_shared setup persists TEST_CRYPT_SHARED.""" import setup_tests import utils @@ -605,11 +527,7 @@ def test_crypt_shared_persisted_to_env(monkeypatch, tmp_path): def test_write_env_escapes_backslashes(monkeypatch, tmp_path): - """Check write_env escapes backslashes first. - - Substitution payloads and trailing backslashes must round-trip - literally when the file is sourced (PYTHON-6167). - """ + """Check write_env escapes backslashes first.""" import subprocess import utils @@ -642,11 +560,7 @@ def test_write_env_escapes_backslashes(monkeypatch, tmp_path): def test_read_env_unescapes_double_quoted_escapes(monkeypatch, tmp_path): - """Check read_env yields the value bash sourcing would. - - Double-quoted escapes unescape, single-quoted values stay literal - (PYTHON-6167). - """ + """Check read_env yields the value bash sourcing would.""" import subprocess import utils @@ -681,11 +595,7 @@ def test_read_env_unescapes_double_quoted_escapes(monkeypatch, tmp_path): def test_write_env_escapes_embedded_quotes(monkeypatch, tmp_path): - """Check write_env escapes embedded double quotes. - - Dropping them would lose data: a value read with read_env must - round-trip when persisted (PYTHON-6167). - """ + """Check write_env escapes embedded double quotes.""" import subprocess import utils @@ -718,10 +628,7 @@ def test_write_env_escapes_embedded_quotes(monkeypatch, tmp_path): def test_crypt_shared_escapes_backslashes(monkeypatch, tmp_path): - """Check the crypt_shared lib path persists literally. - - The trailing LD_LIBRARY_PATH expansion stays live (PYTHON-6167). - """ + """Check the crypt_shared lib path persists literally.""" import subprocess import setup_tests @@ -785,12 +692,7 @@ def test_sync_option_env_override(monkeypatch): def test_sanitizer_task_wiring(): - """PYTHON-6048: one pr-tagged sanitizer task, selected by exactly 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). - """ + """One pr-tagged sanitizer task, selected by exactly one variant (PYTHON-6048).""" tasks = [task for task in all_tasks() if "sanitizer" in (task.tags or [])] assert len(tasks) == 1 task = tasks[0] @@ -810,12 +712,7 @@ def test_sanitizer_task_wiring(): def test_fuzz_native_task_wiring(): - """Run the native fuzz tasks' scripts with plain subprocess.exec. - - The "run tests" function would reinstall pymongo without sanitizer - flags and clobber the instrumented build. install-dependencies.sh - bootstraps uv, which a fresh command shell does not inherit. - """ + """Run the native fuzz tasks' scripts with plain subprocess.exec.""" tasks = {task.name: task for task in all_tasks() if "fuzz-native" in (task.tags or [])} assert sorted(tasks) == ["fuzz-native-full", "fuzz-native-regression"] for name, task in tasks.items(): @@ -836,11 +733,7 @@ def test_fuzz_native_task_wiring(): def test_upload_fuzz_artifacts_func(): - """The fuzz artifacts upload archives crash reproducers and is optional. - - crash-* artifacts land in src/fuzz-scratch/ and no other post-task - upload collects them (PYTHON-6169). - """ + """The fuzz artifacts upload archives crash reproducers and is optional.""" name, cmds = generate_config.create_upload_fuzz_artifacts_func() assert name == "upload fuzz artifacts" archive = [cmd for cmd in cmds if cmd.command == "archive.targz_pack"] diff --git a/test/test_fuzz_shared.py b/test/test_fuzz_shared.py index 5731bac28c..4c5a5b94bf 100644 --- a/test/test_fuzz_shared.py +++ b/test/test_fuzz_shared.py @@ -34,13 +34,7 @@ def test_input_views_bytes_by_default(monkeypatch, data): @pytest.mark.default @pytest.mark.parametrize("data", [b"", b"\x08\x00\x00\x00\x00", OVERREAD_INPUT]) def test_input_views_native_adds_sentinel_free_array(monkeypatch, data): - """Also decode through a sentinel-free array under FUZZ_NATIVE=1. - - bytes ends in CPython's hidden NUL sentinel, which hides over-reads - from ASan (the PYTHON-6110 masking). The array copy has none and is - exact-sized: an overallocating buffer would leave short over-reads - inside addressable memory, invisible to ASan. - """ + """Also decode through a sentinel-free, exact-sized array under FUZZ_NATIVE=1.""" monkeypatch.setenv("FUZZ_NATIVE", "1") views = list(fuzz_shared.input_views(data)) assert len(views) == 2 @@ -63,11 +57,7 @@ def test_array_view_decodes_like_bytes(): def test_overread_input_rejected_for_both_views(): - """Reject the PYTHON-6110 reproducer identically through both views. - - The C extension's regex decoder is bounds-checked (PYTHON-6110), so the - over-read is rejected rather than masked by bytes' hidden NUL sentinel. - """ + """Reject the PYTHON-6110 reproducer identically through both views.""" import bson for view in (OVERREAD_INPUT, array.array("B", OVERREAD_INPUT)): @@ -77,12 +67,7 @@ def test_overread_input_rejected_for_both_views(): @pytest.fixture def fuzz_targets(monkeypatch): - """Import the fuzz target modules with a no-op atheris shim. - - The targets require atheris at import time, but atheris ships Linux - x86_64 wheels only, so the real package is unavailable on other - platforms and interpreters. bson itself is imported normally. - """ + """Import the fuzz target modules with a no-op atheris shim.""" import contextlib import types @@ -109,11 +94,7 @@ def fuzz_targets(monkeypatch): ], ) def test_targets_handle_every_view(fuzz_targets, monkeypatch, data): - """Run every target's TestOneInput over both views. - - fuzz_is_valid keeps is_valid() on the raw bytes (it raises TypeError - for other buffers) and runs only decode() over both views. - """ + """Run every target's TestOneInput over both views.""" monkeypatch.setenv("FUZZ_NATIVE", "1") fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets @@ -136,11 +117,7 @@ def test_targets_accept_valid_documents_in_native_mode(fuzz_targets, monkeypatch def test_regression_files_replay_cleanly(fuzz_targets, monkeypatch): - """Replay every committed reproducer in fuzz/regression/decode__*. - - Each must replay cleanly through both implementations over every input - view: no exception may escape the targets' expected-error handling. - """ + """Replay every committed reproducer in fuzz/regression/decode__*.""" monkeypatch.setenv("FUZZ_NATIVE", "1") fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets From f9d4276fe9c9913df363d605decb2c6d37fc4cb9 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 1 Dec 2026 20:38:40 -0600 Subject: [PATCH 14/16] Pass FUZZ_MAX_TIME to the discovery and capture runners --- .evergreen/generated_configs/tasks.yml | 4 ++++ .evergreen/scripts/generate_config.py | 9 +++++++-- .evergreen/scripts/test_generate_config.py | 4 ++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index cc0544ec2f..0a217b0108 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -262,6 +262,8 @@ tasks: args: - fuzz/run_native.sh working_dir: src + include_expansions_in_env: + - FUZZ_MAX_TIME type: test tags: [fuzz, fuzz-native] - name: fuzz-corpus-capture @@ -287,6 +289,8 @@ tasks: - fuzz/run_native.sh - fuzz-scratch/corpus working_dir: src + include_expansions_in_env: + - FUZZ_MAX_TIME type: test - command: subprocess.exec params: diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index ccfa205d5c..226a713d53 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -755,7 +755,9 @@ def create_fuzz_tasks(): commands=[ install_cmd, build_cmd, - get_subprocess_exec(args=["fuzz/run_native.sh"]), + get_subprocess_exec( + args=["fuzz/run_native.sh"], include_expansions_in_env=["FUZZ_MAX_TIME"] + ), ], ) ) @@ -785,7 +787,10 @@ def create_fuzz_tasks(): commands=[ install_cmd, build_cmd, - get_subprocess_exec(args=["fuzz/run_native.sh", "fuzz-scratch/corpus"]), + get_subprocess_exec( + args=["fuzz/run_native.sh", "fuzz-scratch/corpus"], + include_expansions_in_env=["FUZZ_MAX_TIME"], + ), capture_cmd, ], ) diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 85b9d15be2..5a0692f515 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -416,6 +416,9 @@ def test_fuzz_task_wiring(): assert native_regression_run.params["env"] == {"FUZZ_MAX_TIME": "0"} native_full_run = tasks["fuzz-native-full"].commands[-1] assert native_full_run.params["args"] == ["fuzz/run_native.sh"] + # The full flow reads the FUZZ_MAX_TIME expansion so a configured + # budget reaches it. + assert "FUZZ_MAX_TIME" in native_full_run.params["include_expansions_in_env"] assert "env" not in native_full_run.params # The capture subprocess bootstraps the comment-bot github app, whose # secrets live in AWS Secrets Manager: it needs the assumed-role @@ -432,6 +435,7 @@ def test_fuzz_task_wiring(): assert capture_commands[0].params["args"] == [".evergreen/scripts/install-dependencies.sh"] assert capture_commands[1].params["args"] == ["fuzz/build_native.sh"] assert capture_commands[2].params["args"] == ["fuzz/run_native.sh", "fuzz-scratch/corpus"] + assert "FUZZ_MAX_TIME" in capture_commands[2].params["include_expansions_in_env"] assert capture_commands[3] is capture From 925a2dd7a59eb73d421f9083172c04693fda6186 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 2 Dec 2026 06:46:35 -0600 Subject: [PATCH 15/16] Scope the native corpus reset to the scratch area --- fuzz/run_native.sh | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/fuzz/run_native.sh b/fuzz/run_native.sh index 734cb81fef..10d4d06bab 100755 --- a/fuzz/run_native.sh +++ b/fuzz/run_native.sh @@ -71,7 +71,17 @@ esac # discovered inputs. mkdir -p "$CORPUS" "$SCRATCH" if [ "$#" -eq 0 ]; then - rm -rf "$CORPUS" + # The reset is scoped to the scratch area: a symlink at the default + # corpus path must not redirect the deletion into tracked sources + # (PYTHON-6169). + case "$CORPUS" in + "$SCRATCH"/*) rm -rf "$CORPUS" ;; + *) + echo "ERROR: the default corpus path resolved outside fuzz-scratch." >&2 + echo "Remove the symlink or pass the corpus directory explicitly." >&2 + exit 1 + ;; + esac mkdir -p "$CORPUS" fi ZIP="$SCRATCH/native-corpus-seed.zip" From f841e52d8d8f6601cfc6bea9ef9b0449ec761fc6 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 2 Dec 2026 08:17:08 -0600 Subject: [PATCH 16/16] Combine python and native replay in the regression task --- .evergreen/generated_configs/tasks.yml | 19 +++++- .evergreen/generated_configs/variants.yml | 2 +- .evergreen/scripts/generate_config.py | 27 +++++++-- .evergreen/scripts/test_generate_config.py | 69 +++++++++++----------- CONTRIBUTING.md | 6 +- fuzz/README.md | 5 +- 6 files changed, 81 insertions(+), 47 deletions(-) diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index 0a217b0108..afa7dbf29f 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -206,7 +206,7 @@ tasks: tags: [coverage, pr] # Fuzz tests - - name: fuzz-native-regression + - name: fuzz-regression commands: - command: subprocess.exec params: @@ -215,6 +215,21 @@ tasks: - .evergreen/scripts/install-dependencies.sh working_dir: src type: test + - command: subprocess.exec + params: + binary: uv + args: + - run + - --extra + - test + - python + - -m + - pytest + - test/test_fuzz_shared.py + - -m + - default + working_dir: src + type: test - command: subprocess.exec params: binary: bash @@ -231,7 +246,7 @@ tasks: env: FUZZ_MAX_TIME: "0" type: test - tags: [fuzz, fuzz-native, pr] + tags: [fuzz, fuzz-regression, pr] - name: fuzz-python-full commands: - func: run tests diff --git a/.evergreen/generated_configs/variants.yml b/.evergreen/generated_configs/variants.yml index e1eebb1225..f14c4ab0d0 100644 --- a/.evergreen/generated_configs/variants.yml +++ b/.evergreen/generated_configs/variants.yml @@ -203,7 +203,7 @@ buildvariants: # Fuzz tests - name: fuzzing-rhel8 tasks: - - name: fuzz-native-regression + - name: fuzz-regression - name: fuzz-python-full - name: fuzz-native-full - name: fuzz-corpus-capture diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index 226a713d53..27116bbad1 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -400,7 +400,7 @@ def create_fuzz_variants(): return [ create_variant( [ - "fuzz-native-regression", + "fuzz-regression", "fuzz-python-full", "fuzz-native-full", EvgTaskRef(name="fuzz-corpus-capture", batchtime=BATCHTIME_WEEK), @@ -723,16 +723,33 @@ def create_no_orchestration_tasks(): def create_fuzz_tasks(): - # Native replay of the whole corpus on every PR (PYTHON-6169): - # FUZZ_MAX_TIME=0 makes libFuzzer run each unit once and exit. + # The PR regression gate covers both oracles (PYTHON-6169): the + # python-side helper suite replays the reproducers through both bson + # implementations on the regular build, and the native replay runs the + # whole corpus under ASan. The pytest step runs before the instrumented + # build so the regular venv is still in place. build_cmd = get_subprocess_exec(args=["fuzz/build_native.sh"]) install_cmd = get_subprocess_exec(args=[".evergreen/scripts/install-dependencies.sh"]) tasks = [ EvgTask( - name="fuzz-native-regression", - tags=["fuzz", "fuzz-native", "pr"], + name="fuzz-regression", + tags=["fuzz", "fuzz-regression", "pr"], commands=[ install_cmd, + get_subprocess_exec( + binary="uv", + args=[ + "run", + "--extra", + "test", + "python", + "-m", + "pytest", + "test/test_fuzz_shared.py", + "-m", + "default", + ], + ), build_cmd, get_subprocess_exec(args=["fuzz/run_native.sh"], env=dict(FUZZ_MAX_TIME="0")), ], diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 5a0692f515..679d0b498c 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -375,18 +375,18 @@ def test_fuzz_task_wiring(): """Test the fuzz task wiring. Four flows in one Fuzzing variant. A task's "pr" tag keeps it out of - mainline builds and selects it into PR patch builds, so the native - replay gates PRs and the full flows run only on mainline. + mainline builds and selects it into PR patch builds, so the regression + task gates PRs and the full flows run only on mainline. """ tasks = {task.name: task for task in all_tasks() if "fuzz" in (task.tags or [])} assert sorted(tasks) == [ "fuzz-corpus-capture", "fuzz-native-full", - "fuzz-native-regression", "fuzz-python-full", + "fuzz-regression", ] assert sorted(task.name for task in tasks.values() if "pr" in (task.tags or [])) == [ - "fuzz-native-regression", + "fuzz-regression", ] variants = generate_config.create_fuzz_variants() assert len(variants) == 1 @@ -396,7 +396,7 @@ def test_fuzz_task_wiring(): # All four flows share the variant, with the capture ref's weekly # batchtime overriding the variant's daily one. assert [ref.name for ref in fuzzing.tasks] == [ - "fuzz-native-regression", + "fuzz-regression", "fuzz-python-full", "fuzz-native-full", "fuzz-corpus-capture", @@ -405,19 +405,41 @@ def test_fuzz_task_wiring(): assert capture_ref.batchtime == generate_config_utils.BATCHTIME_WEEK for name, task in tasks.items(): assert variant_selects(fuzzing, task), name - # The fuzz family runs on the large rhel8.7 distro, like the other - # drivers' fuzz jobs. assert fuzzing.run_on == ["rhel8.7-large"] # The python flow goes through the "run tests" function: time-boxed # discovery on mainline. assert tasks["fuzz-python-full"].commands[-1].func == "run tests" - native_regression_run = tasks["fuzz-native-regression"].commands[-1] - assert native_regression_run.params["args"] == ["fuzz/run_native.sh"] - assert native_regression_run.params["env"] == {"FUZZ_MAX_TIME": "0"} - native_full_run = tasks["fuzz-native-full"].commands[-1] - assert native_full_run.params["args"] == ["fuzz/run_native.sh"] - # The full flow reads the FUZZ_MAX_TIME expansion so a configured + # The regression task covers both oracles: the python-side helper suite + # on the regular build, then the whole corpus replayed under ASan. + regression = tasks["fuzz-regression"].commands + assert regression[0].params["args"] == [".evergreen/scripts/install-dependencies.sh"] + assert regression[1].params["binary"] == "uv" + assert regression[1].params["args"] == [ + "run", + "--extra", + "test", + "python", + "-m", + "pytest", + "test/test_fuzz_shared.py", + "-m", + "default", + ] + assert regression[2].params["args"] == ["fuzz/build_native.sh"] + regression_run = regression[3] + assert regression_run.params["args"] == ["fuzz/run_native.sh"] + assert regression_run.params["env"] == {"FUZZ_MAX_TIME": "0"} + # Script commands run bash from the src dir. + for cmd in (regression[0], regression[2], regression_run): + assert cmd.params["binary"] == "bash" + assert cmd.params["working_dir"] == "src" + # The native full flow reads the FUZZ_MAX_TIME expansion so a configured # budget reaches it. + native_full = tasks["fuzz-native-full"].commands + assert native_full[0].params["args"] == [".evergreen/scripts/install-dependencies.sh"] + assert native_full[1].params["args"] == ["fuzz/build_native.sh"] + native_full_run = native_full[2] + assert native_full_run.params["args"] == ["fuzz/run_native.sh"] assert "FUZZ_MAX_TIME" in native_full_run.params["include_expansions_in_env"] assert "env" not in native_full_run.params # The capture subprocess bootstraps the comment-bot github app, whose @@ -715,27 +737,6 @@ def test_sanitizer_task_wiring(): assert (variants[0].expansions or {}).get("VERSION") == generate_config_utils.MAX_VERSION -def test_fuzz_native_task_wiring(): - """Run the native fuzz tasks' scripts with plain subprocess.exec.""" - tasks = {task.name: task for task in all_tasks() if "fuzz-native" in (task.tags or [])} - assert sorted(tasks) == ["fuzz-native-full", "fuzz-native-regression"] - for name, task in tasks.items(): - # Plain subprocess.exec only: no FunctionCall ("run tests") anywhere. - assert all(getattr(cmd, "func", None) is None for cmd in task.commands), name - args = [cmd.params["args"] for cmd in task.commands] - assert args == [ - [".evergreen/scripts/install-dependencies.sh"], - ["fuzz/build_native.sh"], - ["fuzz/run_native.sh"], - ], name - # The get_subprocess_exec defaults: bash, from the src dir. - assert all(cmd.params["binary"] == "bash" for cmd in task.commands), name - assert all(cmd.params["working_dir"] == "src" for cmd in task.commands), name - # The pr tag keeps the replay off mainline and in PR patch builds. - assert "pr" in tasks["fuzz-native-regression"].tags - assert "pr" not in tasks["fuzz-native-full"].tags - - def test_upload_fuzz_artifacts_func(): """The fuzz artifacts upload archives crash reproducers and is optional.""" name, cmds = generate_config.create_upload_fuzz_artifacts_func() diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5adbccd59c..15d5c64572 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -450,9 +450,9 @@ The `fuzz/` directory holds coverage-guided fuzz tests for `bson` tests can only be run on Linux x86_64, the only platform with atheris wheels (CPython 3.12-3.14). -- Replay the committed corpus under ASan (runs on every PR): the - `fuzz-native-regression` task. Local replays are covered in - [fuzz/README.md](fuzz/README.md). +- Regression (runs on every PR): the `fuzz-regression` task runs the + python-side fuzz test suite and replays the whole corpus under ASan. + Local replays are covered in [fuzz/README.md](fuzz/README.md). - Time-boxed fuzzing for crash discovery (runs daily on Evergreen): `just setup-tests fuzz fuzz` then `just run-tests`. Set `FUZZ_MAX_TIME` (seconds, default 300) to change the per-target budget. diff --git a/fuzz/README.md b/fuzz/README.md index 1d2858e8a5..74f15641d5 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -155,8 +155,9 @@ the corpus seeds from the spec seed corpus plus the committed `corpus/` and `regression/` units, replaying every known reproducer under ASan. Four Evergreen tasks run these scripts in one Fuzzing variant. On every -PR it replays the whole corpus natively (`fuzz-native-regression`, -`FUZZ_MAX_TIME=0`: each unit runs once, without mutation). On mainline +PR it runs the python-side regression suite and replays the whole corpus +natively (`fuzz-regression`, `FUZZ_MAX_TIME=0`: each unit runs once, +without mutation). On mainline it runs the full time-boxed flows (`fuzz-python-full`, `fuzz-native-full`). The `fuzz-corpus-capture` task runs weekly, fuzzing natively into `fuzz-scratch/corpus` and