From 924ecb993e3da347a7a4cfc94cce07ca7ed397b4 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 19 Nov 2026 12:24:26 -0600 Subject: [PATCH 01/11] PYTHON-6266 Make the synchro pre-commit hook atomic and write only real changes (#3230) --- .gitignore | 3 + CONTRIBUTING.md | 9 +- tools/synchro.py | 311 +++++++++++++++++++---- tools/test_synchro.py | 570 +++++++++++++++++++++++++++++++++++++++++- 4 files changed, 836 insertions(+), 57 deletions(-) diff --git a/.gitignore b/.gitignore index c113d3ec21..9463ba5ab0 100644 --- a/.gitignore +++ b/.gitignore @@ -31,6 +31,9 @@ expansion.yml specifications/ results.json .synchro-modified +.synchro-staging/ +*.synchro-backup +*.synchro-tmp .evergreen/atlas_x509_dev_client_certificate.pem .evergreen/atlas_x509_sfp_client_certificate.pem diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c457931d38..43790a3299 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -620,10 +620,11 @@ To prevent the `synchro` hook from accidentally overwriting code, it first check of a file is changing and not its async counterpart, and will fail. In the unlikely scenario that you want to override this behavior, first export `OVERRIDE_SYNCHRO_CHECK=1`. -Sometimes, the `synchro` hook will fail and introduce changes many previously unmodified files. This is due to static -Python errors, such as missing imports, incorrect syntax, or other fatal typos. To resolve these issues, -run `pre-commit run --all-files --hook-stage manual ruff` and fix all reported errors before running the `synchro` -hook again. +The `synchro` hook stages the generated files and copies into the working tree only those whose content changed, so +a failed run leaves the working tree unchanged and stages nothing. If the hook reports a ruff failure on the +generated output, fix the error in the corresponding `pymongo/asynchronous` source file and run the hook again. If +it refuses to run because a `.synchro-backup` file holds an unrecovered original from a failed run, inspect and +remove that file manually, then run the hook again. ## CPU profiling diff --git a/tools/synchro.py b/tools/synchro.py index 65f86866cd..7dd2b60cb0 100644 --- a/tools/synchro.py +++ b/tools/synchro.py @@ -22,6 +22,7 @@ import os import re +import shutil import subprocess import sys from pathlib import Path @@ -29,6 +30,7 @@ from unasync import Rule, unasync_files # type: ignore[import-untyped,import-not-found] MANIFEST = ".synchro-modified" +STAGING = ".synchro-staging" replacements = { "AsyncCollection": "Collection", @@ -350,6 +352,204 @@ def process_ignores(lines: list[str]) -> list[str]: return lines +def git_tracked_files(dests: list[Path]) -> set[Path] | None: + """Return the subset of dests git tracks, or None when git is unusable. + + A ``None`` result makes callers treat every destination as tracked, + which skips unchanged files as before. + """ + if not dests: + return set() + command = ["git", "ls-files", "--", *(str(dest) for dest in dests)] + try: + result = subprocess.run( # noqa: S603 + command, + capture_output=True, + text=True, + check=True, + ) + except (OSError, subprocess.CalledProcessError): + return None + return {Path(line) for line in result.stdout.splitlines()} + + +def clear_manifest(manifest: Path) -> None: + """Remove the staging manifest so nothing is staged for this run.""" + try: + manifest.unlink(missing_ok=True) + except OSError as unlink_error: + print(f"Synchro: could not remove {manifest}: {unlink_error!r}", file=sys.stderr) + + +def copy_changed_files( + pairs: list[tuple[Path, Path]], + manifest: Path | None = None, + tracked: set[Path] | None = None, +) -> list[Path]: + """Copy staged files into the working tree when their content differs. + + Each destination is backed up, written through a temporary sibling, + and atomically replaced, so a failed write never truncates it. If a + later step fails or is interrupted, what was already written is + restored and the manifest is removed, leaving the working tree + unchanged. An unchanged destination that ``tracked`` does not contain + is listed in the manifest without being rewritten, so a newly + generated module reaches the staging hook on its first commit. + """ + written: list[tuple[Path, bytes | None, Path | None]] = [] + replaced: list[Path] = [] + included: list[Path] = [] + try: + for staged, dest in pairs: + new = staged.read_bytes() + old = dest.read_bytes() if dest.is_file() else None + if old == new: + if tracked is not None and dest not in tracked: + included.append(dest) + continue + dest.parent.mkdir(parents=True, exist_ok=True) + backup: Path | None = None + if old is not None: + backup = dest.with_name(dest.name + ".synchro-backup") + if backup.exists() and not backup.samefile(dest): + # A failed run left this backup holding the only copy of + # the original; refuse to overwrite it. Kept outside the + # try below so the refusal is not swallowed. + raise OSError( + f"Synchro: {backup} holds the unrecovered original of " + f"{dest}; inspect and remove it manually, then re-run " + "the hook." + ) + try: + backup.unlink(missing_ok=True) + os.link(dest, backup) + except OSError: + # No hard-link support: try a full copy before giving up + # on an on-disk backup. + try: + shutil.copyfile(dest, backup) + except OSError: + # Remove a partial copy so no garbage stray remains. + backup.unlink(missing_ok=True) + backup = None + # Track before replacing so an interrupt cannot skip the rollback. + written.append((dest, old, backup)) + tmp = dest.with_name(dest.name + ".synchro-tmp") + try: + tmp.write_bytes(new) + tmp.replace(dest) + except BaseException: + try: + landed = dest.read_bytes() == new + except OSError: + landed = True # cannot verify; keep the entry and attempt the restore + if not landed: + # The rename is atomic: nothing was published, so the + # destination still holds its original and the rollback + # must not rewrite it. + written.pop() + if backup is not None: + backup.unlink(missing_ok=True) + raise + finally: + tmp.unlink(missing_ok=True) + replaced.append(dest) + included.append(dest) + if manifest is not None: + names = [f"./{dest.as_posix()}" for dest in included] + tmp_manifest = manifest.with_name(manifest.name + ".synchro-tmp") + try: + tmp_manifest.write_text("\n".join(names) + ("\n" if names else "")) + tmp_manifest.replace(manifest) + finally: + tmp_manifest.unlink(missing_ok=True) + except BaseException: + # A failed run claims nothing to stage, whatever happens next. + if manifest is not None: + clear_manifest(manifest) + # Restore in reverse so each restore releases space for the next. + # Any exception, including Ctrl-C, must restore the tree, and a + # failing restore must not strand the others. + for dest, old, backup in reversed(written): + try: + if backup is not None: + backup.replace(dest) + elif old is None: + dest.unlink(missing_ok=True) + else: + # No backup: rewrite through the temporary sibling, so a + # failing restore leaves the published content in place. + tmp_restore = dest.with_name(dest.name + ".synchro-tmp") + try: + tmp_restore.write_bytes(old) + tmp_restore.replace(dest) + finally: + tmp_restore.unlink(missing_ok=True) + except BaseException as restore_error: + print( + f"Synchro: could not restore {dest}: {restore_error!r}", + file=sys.stderr, + ) + raise + # Publication succeeded, so the backups are obsolete. A backup left + # behind by a failed unlink or a failed restore holds the only copy + # of an original; the next run's guard refuses to overwrite it and + # asks for it to be removed manually. + for _, _, backup in written: + if backup is not None: + try: + backup.unlink(missing_ok=True) + except OSError as unlink_error: + # A backup left behind makes the next run refuse publication + # with recovery guidance; a completed publication must not + # fail over the cleanup. + print( + f"Synchro: could not remove {backup}: {unlink_error!r}", + file=sys.stderr, + ) + return replaced + + +def prepare_staging() -> None: + """Recreate the out-of-tree staging area used to generate sync files. + + A copy of pyproject.toml at the staging root keeps ruff's + per-file-ignores (e.g. ``test/*.py``) and first-party import + classification identical to a run against the repo root. + """ + shutil.rmtree(STAGING, ignore_errors=True) + for base in (_pymongo_dest_base, _gridfs_dest_base, _test_dest_base): + Path(STAGING, base[2:]).mkdir(parents=True, exist_ok=True) + shutil.copyfile("pyproject.toml", f"{STAGING}/pyproject.toml") + config = Path(STAGING, "pyproject.toml") + lines = config.read_text().splitlines(keepends=True) + for i, line in enumerate(lines): + if line.startswith("isort.required-imports"): + lines.insert(i + 1, 'isort.known-first-party = ["pymongo", "gridfs", "bson", "test"]\n') + break + else: + print( + "Synchro: no isort.required-imports line in pyproject.toml, so " + "isort.known-first-party was not added to the staged ruff config and " + "import classification may differ from the repo root.", + file=sys.stderr, + ) + config.write_text("".join(lines)) + + +def mirrored_test_files(filtered_tests: list[str]) -> list[str]: + """Return the generated test paths for the given async test files. + + A test file is mirrored only when its synchronous counterpart already + exists in ``test/``. + """ + return [ + _test_dest_base + Path(f).name + for f in filtered_tests + if (Path(_test_dest_base) / Path(f).name).is_file() + ] + + def unasync_directory(files: list[str], src: str, dest: str, replacements: dict[str, str]) -> None: unasync_files( files, @@ -365,6 +565,10 @@ def unasync_directory(files: list[str], src: str, dest: str, replacements: dict[ def main() -> None: is_ci = bool(os.environ.get("CI")) + # Any run that fails before publication must claim nothing to stage, so + # the previous run's manifest is dropped up front; a successful run + # publishes a fresh one below. + clear_manifest(Path(MANIFEST)) modified_files = [f"./{f}" for f in sys.argv[1:]] errored = False for fname in async_files + gridfs_files + test_files: @@ -387,68 +591,77 @@ def main() -> None: filtered_gridfs = [f for f in gridfs_files if not modified_set or f in modified_set] filtered_tests = [f for f in test_files if not modified_set or f in modified_set] - ruff_extra = [] if is_ci else ["--silent"] - # Check async source files for problems before generating sync output. async_sources = filtered_async + filtered_gridfs + filtered_tests if async_sources: subprocess.run( # noqa: S603 - [sys.executable, "-m", "ruff", "check", *async_sources, *ruff_extra], + [sys.executable, "-m", "ruff", "check", *async_sources], check=True, ) - unasync_directory(filtered_async, _pymongo_base, _pymongo_dest_base, replacements) - unasync_directory(filtered_gridfs, _gridfs_base, _gridfs_dest_base, replacements) - unasync_directory(filtered_tests, _test_base, _test_dest_base, replacements) - - # Derive generated output paths directly from filtered source paths. - generated_pymongo = [_pymongo_dest_base + Path(f).name for f in filtered_async] - generated_gridfs = [_gridfs_dest_base + Path(f).name for f in filtered_gridfs] - generated_tests = [ - _test_dest_base + Path(f).name - for f in filtered_tests - if (Path(_test_dest_base) / Path(f).name).is_file() - ] - - docstring_translate_files = generated_pymongo + generated_gridfs + generated_tests - - process_files( - generated_pymongo + generated_gridfs + generated_tests, - docstring_translate_files, - generated_tests, - ) - - generated_files = generated_pymongo + generated_gridfs + generated_tests - - if is_ci and generated_files: - print(f"Synchro generated {len(generated_files)} file(s):") - for f in generated_files: - print(f" {f}") - - if generated_files: - subprocess.run( # noqa: S603 - [sys.executable, "-m", "ruff", "check", *generated_files, "--fix", *ruff_extra], - check=is_ci, + try: + prepare_staging() + generated_pymongo = [_pymongo_dest_base + Path(f).name for f in filtered_async] + generated_gridfs = [_gridfs_dest_base + Path(f).name for f in filtered_gridfs] + generated_tests = mirrored_test_files(filtered_tests) + generated_names = generated_pymongo + generated_gridfs + generated_tests + staged_pymongo = [f"{STAGING}/{name[2:]}" for name in generated_pymongo] + staged_gridfs = [f"{STAGING}/{name[2:]}" for name in generated_gridfs] + staged_tests = [f"{STAGING}/{name[2:]}" for name in generated_tests] + staged_names = staged_pymongo + staged_gridfs + staged_tests + + unasync_directory( + filtered_async, _pymongo_base, f"{STAGING}/{_pymongo_dest_base[2:]}", replacements ) - subprocess.run( # noqa: S603 - [sys.executable, "-m", "ruff", "format", *generated_files, *ruff_extra], - check=is_ci, + unasync_directory( + filtered_gridfs, _gridfs_base, f"{STAGING}/{_gridfs_dest_base[2:]}", replacements + ) + unasync_directory( + filtered_tests, _test_base, f"{STAGING}/{_test_dest_base[2:]}", replacements ) - if is_ci and generated_files: - result = subprocess.run( # noqa: S603 - ["git", "diff", "--name-only", "--", *generated_files], # noqa: S607 - capture_output=True, - text=True, - check=True, + process_files(staged_names, staged_names, staged_tests) + + if staged_names: + try: + subprocess.run( # noqa: S603 + [sys.executable, "-m", "ruff", "check", *staged_names, "--fix"], + check=True, + ) + subprocess.run( # noqa: S603 + [sys.executable, "-m", "ruff", "format", *staged_names], + check=True, + ) + except subprocess.CalledProcessError: + print( + "Synchro: ruff failed on the generated sync output. Fix the error in " + "the corresponding async source file and run the synchro hook again; " + "the working tree was left unchanged.", + file=sys.stderr, + ) + sys.exit(1) + + pairs = [ + (Path(staged), Path(name)) + for staged, name in zip(staged_names, generated_names, strict=True) + ] + # In CI the drift itself is the report, so neither the manifest nor + # untracked detection runs and the copied drift is left in place. + changed = copy_changed_files( + pairs, + manifest=None if is_ci else Path(MANIFEST), + tracked=None if is_ci else git_tracked_files([dest for _, dest in pairs]), ) - if result.stdout.strip(): - print("Sync files are out of date. Run `just lint --all-files synchro` to regenerate:") - for f in result.stdout.strip().splitlines(): + changed_names = [f"./{dest.as_posix()}" for dest in changed] + + if is_ci and changed_names: + print(f"Synchro generated {len(changed_names)} file(s):") + for f in changed_names: print(f" {f}") + print("Sync files are out of date. Run `just lint --all-files synchro` to regenerate:") sys.exit(1) - - Path(MANIFEST).write_text("\n".join(generated_files) + ("\n" if generated_files else "")) + finally: + shutil.rmtree(STAGING, ignore_errors=True) if __name__ == "__main__": diff --git a/tools/test_synchro.py b/tools/test_synchro.py index e6a1cc3b8f..85c3ed9ef2 100644 --- a/tools/test_synchro.py +++ b/tools/test_synchro.py @@ -1,17 +1,18 @@ -"""Smoke test for tools/synchro.py.""" +"""Tests for tools/synchro.py.""" from __future__ import annotations +import subprocess import sys from pathlib import Path -from typing import TYPE_CHECKING from unittest.mock import patch -if TYPE_CHECKING: - import pytest +import pytest sys.path.insert(0, str(Path(__file__).parent)) +import synchro + def test_synchro(monkeypatch: pytest.MonkeyPatch) -> None: """Synchro processes only the async files passed as arguments. @@ -31,6 +32,8 @@ def capture(files: list[str], *args: object, **kwargs: object) -> None: with ( patch("synchro.unasync_directory", side_effect=capture), patch("synchro.process_files"), + patch("synchro.prepare_staging"), + patch("synchro.copy_changed_files", return_value=[]), patch("subprocess.run"), patch("pathlib.Path.write_text"), ): @@ -40,3 +43,562 @@ def capture(files: list[str], *args: object, **kwargs: object) -> None: assert "./pymongo/asynchronous/mongo_client.py" in processed assert "./pymongo/asynchronous/collection.py" not in processed + + +def test_copy_changed_files_skips_identical(tmp_path: Path) -> None: + """A destination whose content already matches is neither rewritten nor reported.""" + staged = tmp_path / "staged.py" + dest = tmp_path / "dest.py" + staged.write_bytes(b"same") + dest.write_bytes(b"same") + before = dest.stat().st_mtime_ns + + changed = synchro.copy_changed_files([(staged, dest)]) + + assert changed == [] + assert dest.read_bytes() == b"same" + assert dest.stat().st_mtime_ns == before + + +def test_copy_changed_files_updates_differing(tmp_path: Path) -> None: + """A destination whose content differs is overwritten and reported.""" + staged = tmp_path / "staged.py" + dest = tmp_path / "dest.py" + staged.write_bytes(b"new") + dest.write_bytes(b"old") + + changed = synchro.copy_changed_files([(staged, dest)]) + + assert changed == [dest] + assert dest.read_bytes() == b"new" + # The backup is dropped once publication succeeds. + assert sorted(p.name for p in tmp_path.iterdir()) == ["dest.py", "staged.py"] + + +def test_copy_changed_files_creates_missing_dest(tmp_path: Path) -> None: + """A missing destination is created (with parents) and reported.""" + staged = tmp_path / "staged.py" + dest = tmp_path / "subdir" / "dest.py" + staged.write_bytes(b"new") + + changed = synchro.copy_changed_files([(staged, dest)]) + + assert changed == [dest] + assert dest.read_bytes() == b"new" + + +def test_copy_changed_files_rolls_back_on_failure(tmp_path: Path) -> None: + """A failed write restores destinations that were already written.""" + staged_a = tmp_path / "a_staged.py" + dest_a = tmp_path / "a_dest.py" + staged_a.write_bytes(b"new-a") + dest_a.write_bytes(b"old-a") + staged_b = tmp_path / "b_staged.py" + dest_b = tmp_path / "blocking-dir" / "b_dest.py" + staged_b.write_bytes(b"new-b") + # A file occupies b_dest.py's parent directory, so the mkdir fails. + (tmp_path / "blocking-dir").write_bytes(b"not a directory") + manifest = tmp_path / "manifest.txt" + manifest.write_text("stale\n") + + with pytest.raises(FileExistsError): + synchro.copy_changed_files([(staged_a, dest_a), (staged_b, dest_b)], manifest=manifest) + + assert dest_a.read_bytes() == b"old-a" + # A failed run claims nothing to stage. + assert not manifest.exists() + + +def test_copy_changed_files_rollback_restores_in_reverse_order(tmp_path: Path) -> None: + """Rollback frees later allocations first so earlier restores fit.""" + staged_a = tmp_path / "a_staged.py" + dest_a = tmp_path / "a_dest.py" + staged_a.write_bytes(b"new-a") + dest_a.write_bytes(b"old-a") + staged_b = tmp_path / "b_staged.py" + dest_b = tmp_path / "b_dest.py" + staged_b.write_bytes(b"new-b") + dest_b.write_bytes(b"old-b") + staged_c = tmp_path / "c_staged.py" + dest_c = tmp_path / "blocking-dir" / "c_dest.py" + staged_c.write_bytes(b"new-c") + # A file occupies c_dest.py's parent directory, so the mkdir fails. + (tmp_path / "blocking-dir").write_bytes(b"not a directory") + + real_write = Path.write_bytes + restored: list[bytes] = [] + + def tracking_write(self: Path, data: bytes) -> None: + if data == b"old-a" and b"old-b" not in restored: + # Simulate ENOSPC: old-a does not fit until b's larger staged + # content has been released by its own restore. + raise OSError(28, "No space left on device") + real_write(self, data) + if data.startswith(b"old"): + restored.append(data) + + # No on-disk backup at all: restores rewrite the files, so the + # space-releasing order above is what the restores depend on. + with ( + patch("os.link", side_effect=OSError(1, "link not supported")), + patch("shutil.copyfile", side_effect=OSError(1, "copy not supported")), + patch.object(Path, "write_bytes", tracking_write), + ): + with pytest.raises(FileExistsError): + synchro.copy_changed_files([(staged_a, dest_a), (staged_b, dest_b), (staged_c, dest_c)]) + + assert restored == [b"old-b", b"old-a"] + assert dest_a.read_bytes() == b"old-a" + assert dest_b.read_bytes() == b"old-b" + + +def test_copy_changed_files_failing_write_leaves_dest_unchanged(tmp_path: Path) -> None: + """A write that fails midway leaves the failing destination unchanged.""" + staged_a = tmp_path / "a_staged.py" + dest_a = tmp_path / "a_dest.py" + staged_a.write_bytes(b"new-a") + dest_a.write_bytes(b"old-a") + staged_b = tmp_path / "b_staged.py" + dest_b = tmp_path / "b_dest.py" + staged_b.write_bytes(b"new-b") + dest_b.write_bytes(b"old-b") + + real_write = Path.write_bytes + + def failing_write(self: Path, data: bytes) -> None: + if self.name.startswith(dest_b.name): + # Simulate persistent ENOSPC: every write under dest_b's name, + # including a rollback restore, lands partial bytes then fails. + real_write(self, b"ne") + raise OSError(28, "No space left on device") + real_write(self, data) + + with patch.object(Path, "write_bytes", failing_write): + with pytest.raises(OSError, match="No space left on device"): + synchro.copy_changed_files([(staged_a, dest_a), (staged_b, dest_b)]) + + assert dest_a.read_bytes() == b"old-a" + assert dest_b.read_bytes() == b"old-b" + # No temporary or backup files are left behind. + assert sorted(p.name for p in tmp_path.iterdir()) == [ + "a_dest.py", + "a_staged.py", + "b_dest.py", + "b_staged.py", + ] + + +def test_copy_changed_files_manifests_untracked_unchanged( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """An unchanged untracked destination is listed in the manifest, not rewritten.""" + monkeypatch.chdir(tmp_path) + staged = tmp_path / "staged.py" + dest = tmp_path / "dest.py" + staged.write_bytes(b"same") + dest.write_bytes(b"same") + manifest = tmp_path / "manifest.txt" + before = dest.stat().st_mtime_ns + + changed = synchro.copy_changed_files( + [(staged, Path("dest.py"))], manifest=manifest, tracked=set() + ) + + assert changed == [] + assert manifest.read_text() == "./dest.py\n" + assert dest.read_bytes() == b"same" + assert dest.stat().st_mtime_ns == before + + +def test_copy_changed_files_manifest_failure_rolls_back(tmp_path: Path) -> None: + """A manifest write failure restores destinations and claims nothing to stage.""" + staged_a = tmp_path / "a_staged.py" + dest_a = tmp_path / "a_dest.py" + staged_a.write_bytes(b"new-a") + dest_a.write_bytes(b"old-a") + manifest = tmp_path / "manifest.txt" + manifest.write_text("stale\n") + + real_write_text = Path.write_text + + def failing_write_text( + self: Path, + data: str, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> int: + if self.name.startswith(manifest.name): + # Simulate ENOSPC: partial bytes land before the write fails. + real_write_text(self, data[:4], encoding, errors, newline) + raise OSError(28, "No space left on device") + return real_write_text(self, data, encoding, errors, newline) + + with patch.object(Path, "write_text", failing_write_text): + with pytest.raises(OSError, match="No space left on device"): + synchro.copy_changed_files([(staged_a, dest_a)], manifest=manifest) + + assert dest_a.read_bytes() == b"old-a" + # A failed run claims nothing to stage. + assert not manifest.exists() + # No temporary files are left behind. + assert sorted(p.name for p in tmp_path.iterdir()) == [ + "a_dest.py", + "a_staged.py", + ] + + +def test_copy_changed_files_interrupt_after_replace_rolls_back(tmp_path: Path) -> None: + """An interrupt just after a replacement still rolls that destination back.""" + staged_a = tmp_path / "a_staged.py" + dest_a = tmp_path / "a_dest.py" + staged_a.write_bytes(b"new-a") + dest_a.write_bytes(b"old-a") + staged_b = tmp_path / "b_staged.py" + dest_b = tmp_path / "b_dest.py" + staged_b.write_bytes(b"new-b") + dest_b.write_bytes(b"old-b") + + real_replace = Path.replace + + def replacing_interrupt(self: Path, target: Path) -> Path: + real_replace(self, target) + if target == dest_b: + raise KeyboardInterrupt + return target + + with patch.object(Path, "replace", replacing_interrupt): + with pytest.raises(KeyboardInterrupt): + synchro.copy_changed_files([(staged_a, dest_a), (staged_b, dest_b)]) + + assert dest_a.read_bytes() == b"old-a" + assert dest_b.read_bytes() == b"old-b" + + +def test_copy_changed_files_failed_restore_keeps_backup(tmp_path: Path) -> None: + """A restore that fails keeps its backup as the recoverable copy.""" + staged_a = tmp_path / "a_staged.py" + dest_a = tmp_path / "a_dest.py" + staged_a.write_bytes(b"new-a") + dest_a.write_bytes(b"old-a") + staged_b = tmp_path / "b_staged.py" + dest_b = tmp_path / "b_dest.py" + staged_b.write_bytes(b"new-b") + dest_b.write_bytes(b"old-b") + manifest = tmp_path / "manifest.txt" + manifest.write_text("stale\n") + + real_replace = Path.replace + real_write_text = Path.write_text + + def failing_restore(self: Path, target: Path) -> Path: + if self.name.endswith(".synchro-backup") and target == dest_b: + raise OSError(13, "Permission denied") + return real_replace(self, target) + + def failing_write_text( + self: Path, + data: str, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> int: + if self.name.startswith(manifest.name): + raise OSError(28, "No space left on device") + return real_write_text(self, data, encoding, errors, newline) + + with ( + patch.object(Path, "replace", failing_restore), + patch.object(Path, "write_text", failing_write_text), + ): + with pytest.raises(OSError, match="No space left on device"): + synchro.copy_changed_files([(staged_a, dest_a), (staged_b, dest_b)], manifest=manifest) + + assert dest_a.read_bytes() == b"old-a" + assert dest_b.read_bytes() == b"new-b" + # The failed restore's backup survives as the only copy of the original. + backup_b = tmp_path / "b_dest.py.synchro-backup" + assert backup_b.read_bytes() == b"old-b" + assert not manifest.exists() + + +def test_copy_changed_files_unrecovered_backup_blocks_publication(tmp_path: Path) -> None: + """An existing backup holding an unrecovered original refuses publication.""" + staged = tmp_path / "staged.py" + dest = tmp_path / "dest.py" + staged.write_bytes(b"new") + dest.write_bytes(b"current") + # A failed run left this backup holding the only copy of the original. + (tmp_path / "dest.py.synchro-backup").write_bytes(b"original") + + with pytest.raises(OSError, match="unrecovered original"): + synchro.copy_changed_files([(staged, dest)]) + + assert dest.read_bytes() == b"current" + assert (tmp_path / "dest.py.synchro-backup").read_bytes() == b"original" + + +def test_copy_changed_files_backup_cleanup_failure_is_not_fatal( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """A backup that cannot be swept after publication does not fail the run.""" + monkeypatch.chdir(tmp_path) + staged = tmp_path / "staged.py" + dest = Path("dest.py") + staged.write_bytes(b"new") + dest.write_bytes(b"old") + manifest = tmp_path / "manifest.txt" + + real_unlink = Path.unlink + backup_unlinks = 0 + + def failing_unlink(self: Path, missing_ok: bool = False) -> None: + nonlocal backup_unlinks + if self.name.endswith(".synchro-backup"): + backup_unlinks += 1 + if backup_unlinks > 1: + # The first unlink is the stale-backup clear at creation; + # the second is the success sweep. + raise OSError(13, "Permission denied") + real_unlink(self, missing_ok=missing_ok) + + with patch.object(Path, "unlink", failing_unlink): + changed = synchro.copy_changed_files([(staged, dest)], manifest=manifest) + + assert changed == [dest] + assert dest.read_bytes() == b"new" + assert manifest.read_text() == "./dest.py\n" + # The backup remains, with a warning on stderr. + assert (tmp_path / "dest.py.synchro-backup").exists() + assert "could not remove" in capsys.readouterr().err + + +def test_copy_changed_files_failed_fallback_restore_is_clean(tmp_path: Path) -> None: + """A fallback restore that fails leaves the published content in place.""" + staged_a = tmp_path / "a_staged.py" + dest_a = tmp_path / "a_dest.py" + staged_a.write_bytes(b"new-a") + dest_a.write_bytes(b"old-a") + staged_b = tmp_path / "b_staged.py" + dest_b = tmp_path / "b_dest.py" + staged_b.write_bytes(b"new-b") + dest_b.write_bytes(b"old-b") + staged_c = tmp_path / "c_staged.py" + dest_c = tmp_path / "blocking-dir" / "c_dest.py" + staged_c.write_bytes(b"new-c") + # A file occupies c_dest.py's parent directory, so the mkdir fails. + (tmp_path / "blocking-dir").write_bytes(b"not a directory") + + real_write = Path.write_bytes + + def failing_restore(self: Path, data: bytes) -> None: + if data == b"old-b": + # Simulate persistent ENOSPC: the restore lands partial bytes + # then fails. + real_write(self, b"ol") + raise OSError(28, "No space left on device") + real_write(self, data) + + # No on-disk backup at all: the failed restore cannot truncate the + # destination, which keeps its published content. + with ( + patch("os.link", side_effect=OSError(1, "link not supported")), + patch("shutil.copyfile", side_effect=OSError(1, "copy not supported")), + patch.object(Path, "write_bytes", failing_restore), + ): + with pytest.raises(FileExistsError): + synchro.copy_changed_files([(staged_a, dest_a), (staged_b, dest_b), (staged_c, dest_c)]) + + assert dest_a.read_bytes() == b"old-a" + # The failed restore leaves the published content, uncorrupted. + assert dest_b.read_bytes() == b"new-b" + # No temporary or backup files are left behind. + assert sorted(p.name for p in tmp_path.iterdir()) == [ + "a_dest.py", + "a_staged.py", + "b_dest.py", + "b_staged.py", + "blocking-dir", + "c_staged.py", + ] + + +ASYNC_SOURCE = "_IS_SYNC = False\n\n\ndef f() -> None:\n pass\n" +SYNC_SOURCE = "_IS_SYNC = True\n\n\ndef f() -> None:\n pass\n" + + +def setup_tree(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Create a minimal repo-like tree and point synchro at it.""" + (tmp_path / "pymongo" / "asynchronous").mkdir(parents=True) + (tmp_path / "pymongo" / "synchronous").mkdir(parents=True) + (tmp_path / "test" / "asynchronous").mkdir(parents=True) + (tmp_path / "pyproject.toml").write_text("") + (tmp_path / "pymongo" / "asynchronous" / "foo.py").write_text(ASYNC_SOURCE) + monkeypatch.setattr(sys, "argv", ["synchro.py"]) + monkeypatch.setattr(synchro, "async_files", ["./pymongo/asynchronous/foo.py"]) + monkeypatch.setattr(synchro, "gridfs_files", []) + monkeypatch.setattr(synchro, "test_files", []) + monkeypatch.delenv("CI", raising=False) + monkeypatch.chdir(tmp_path) + return tmp_path / "pymongo" / "synchronous" / "foo.py" + + +def test_noop_run_leaves_tree_unchanged(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A run with nothing to regenerate writes no files and stages nothing.""" + dest = setup_tree(tmp_path, monkeypatch) + dest.write_text(SYNC_SOURCE) + before = dest.stat().st_mtime_ns + + with ( + patch("subprocess.run"), + patch("synchro.git_tracked_files", return_value=None), + ): + synchro.main() + + assert dest.read_text() == SYNC_SOURCE + assert dest.stat().st_mtime_ns == before + assert (tmp_path / ".synchro-modified").read_text() == "" + assert not (tmp_path / ".synchro-staging").exists() + + +def test_regenerated_file_is_copied_and_manifested( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Only files whose content changed are copied and listed in the manifest.""" + dest = setup_tree(tmp_path, monkeypatch) + dest.write_text("_IS_SYNC = True\n# stale\n") + + with ( + patch("subprocess.run"), + patch("synchro.git_tracked_files", return_value=None), + ): + synchro.main() + + assert dest.read_text() == SYNC_SOURCE + assert (tmp_path / ".synchro-modified").read_text() == "./pymongo/synchronous/foo.py\n" + assert not (tmp_path / ".synchro-staging").exists() + + +def test_async_test_without_counterpart_is_not_mirrored( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """An async test file is mirrored only when test/.py already exists.""" + setup_tree(tmp_path, monkeypatch) + (tmp_path / "test" / "asynchronous" / "test_bar.py").write_text(ASYNC_SOURCE) + monkeypatch.setattr(synchro, "test_files", ["./test/asynchronous/test_bar.py"]) + + with ( + patch("subprocess.run"), + patch("synchro.git_tracked_files", return_value=None), + ): + synchro.main() + + assert not (tmp_path / "test" / "test_bar.py").exists() + + +def test_ruff_failure_leaves_tree_unchanged( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A ruff failure on generated output exits nonzero without touching the tree.""" + dest = setup_tree(tmp_path, monkeypatch) + dest.write_text("_IS_SYNC = True\n# stale\n") + (tmp_path / ".synchro-modified").write_text("./pymongo/synchronous/foo.py\n") + + def failing_ruff( + cmd: list[str], *args: object, **kwargs: object + ) -> subprocess.CompletedProcess[str]: + if "--fix" in cmd: + raise subprocess.CalledProcessError(1, cmd) + return subprocess.CompletedProcess(cmd, 0) + + with patch("subprocess.run", side_effect=failing_ruff): + with pytest.raises(SystemExit) as excinfo: + synchro.main() + + assert excinfo.value.code == 1 + assert dest.read_text() == "_IS_SYNC = True\n# stale\n" + assert not (tmp_path / ".synchro-modified").exists() + assert not (tmp_path / ".synchro-staging").exists() + + +def test_ruff_commands_keep_diagnostics_visible( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Ruff runs without --silent so fatal failures show their diagnostics.""" + setup_tree(tmp_path, monkeypatch) + + commands: list[list[str]] = [] + + def capture(cmd: list[str], *args: object, **kwargs: object) -> None: + commands.append(cmd) + + with ( + patch("subprocess.run", side_effect=capture), + patch("synchro.git_tracked_files", return_value=None), + ): + synchro.main() + + ruff_cmds = [cmd for cmd in commands if "ruff" in cmd] + assert ruff_cmds + for cmd in ruff_cmds: + assert "--silent" not in cmd + + +def test_ci_reports_drift(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """In CI, changed generated files are copied so the drift is visible, then fail.""" + dest = setup_tree(tmp_path, monkeypatch) + dest.write_text("_IS_SYNC = True\n# stale\n") + monkeypatch.setenv("CI", "true") + + with patch("subprocess.run"): + with pytest.raises(SystemExit) as excinfo: + synchro.main() + + assert excinfo.value.code == 1 + assert dest.read_text() == SYNC_SOURCE + + +def test_mirrored_test_files_requires_sync_counterpart( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Async tests are mirrored only when the sync counterpart exists.""" + async_dir = tmp_path / "test" / "asynchronous" + async_dir.mkdir(parents=True) + (async_dir / "test_a.py").write_text("") + (async_dir / "test_b.py").write_text("") + (tmp_path / "test" / "test_a.py").write_text("") + monkeypatch.setattr(synchro, "_test_dest_base", f"{tmp_path / 'test'}/") + + filtered = [str(async_dir / "test_a.py"), str(async_dir / "test_b.py")] + + assert synchro.mirrored_test_files(filtered) == [f"{tmp_path / 'test' / 'test_a.py'}"] + + +def test_prepare_staging_pins_first_party_packages( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The staged pyproject copy pins the first-party packages for isort.""" + (tmp_path / "pyproject.toml").write_text( + '[tool.ruff.lint]\nisort.required-imports = ["from __future__ import annotations"]\n' + ) + monkeypatch.chdir(tmp_path) + + synchro.prepare_staging() + + staged = (tmp_path / synchro.STAGING / "pyproject.toml").read_text() + assert 'isort.known-first-party = ["pymongo", "gridfs", "bson", "test"]' in staged + assert "isort.required-imports" in staged + + +def test_prepare_staging_warns_when_anchor_missing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """A pyproject without the isort anchor gets no insert and a stderr warning.""" + (tmp_path / "pyproject.toml").write_text("") + monkeypatch.chdir(tmp_path) + + synchro.prepare_staging() + + staged = (tmp_path / synchro.STAGING / "pyproject.toml").read_text() + assert "known-first-party" not in staged + assert "known-first-party" in capsys.readouterr().err From e87343422488876f616d01d87f6425434c44ecde Mon Sep 17 00:00:00 2001 From: Iris <58442094+sleepyStick@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:43:55 -0800 Subject: [PATCH 02/11] update 4.20.1 changelog to include CVE links (#3242) Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- doc/changelog.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/changelog.rst b/doc/changelog.rst index 0ebcbe8912..18b0160103 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -16,13 +16,13 @@ Bug fixes ``CommandStartedEvent`` (and its "Command started" log message) without a correlating ``CommandFailedEvent``. A cancellation now publishes the failure before the ``CancelledError`` propagates (`PYTHON-6187`_). -- Sanitize parsing error messages. (`PYTHON-6058`_) -- Improved credential validation. (`PYTHON-6073`_) +- Sanitize parsing error messages. (`CVE-2026-129927`_) +- Improved credential validation. (`CVE-2026-129926`_). .. _PYTHON-6262: https://jira.mongodb.org/browse/PYTHON-6262 .. _PYTHON-6187: https://jira.mongodb.org/browse/PYTHON-6187 -.. _PYTHON-6058: https://jira.mongodb.org/browse/PYTHON-6058 -.. _PYTHON-6073: https://jira.mongodb.org/browse/PYTHON-6073 +.. _CVE-2026-129927: https://www.cve.org/CVERecord?id=CVE-2026-129927 +.. _CVE-2026-129926: https://www.cve.org/CVERecord?id=CVE-2026-129926 Changes in Version 4.20.0 (2026/11/12) -------------------------------------- From ed207912d053158a779b730d44d596027db9eec6 Mon Sep 17 00:00:00 2001 From: Jeffrey 'Alex' Clark Date: Thu, 19 Nov 2026 18:20:33 -0500 Subject: [PATCH 03/11] PYTHON-6183 Reject non-string filename in GridFS get_version (#3237) --- doc/changelog.rst | 13 +++++++++++++ gridfs/asynchronous/grid_file.py | 13 ++++++++++++- gridfs/synchronous/grid_file.py | 13 ++++++++++++- test/asynchronous/test_gridfs.py | 7 +++++++ test/test_gridfs.py | 7 +++++++ 5 files changed, 51 insertions(+), 2 deletions(-) diff --git a/doc/changelog.rst b/doc/changelog.rst index 18b0160103..49141a8a18 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,19 @@ Changelog ========= +Changes in Version 4.20.2 (unreleased) +-------------------------------------- + +Bug fixes +......... + +- Fixed a bug where :meth:`~gridfs.GridFS.get_version` and + :meth:`~gridfs.GridFS.get_last_version` accepted a non-string ``filename`` + and treated a dict as query criteria. They now raise :exc:`TypeError` + (`PYTHON-6183`_). + +.. _PYTHON-6183: https://jira.mongodb.org/browse/PYTHON-6183 + Changes in Version 4.20.1 (2026/11/19) -------------------------------------- diff --git a/gridfs/asynchronous/grid_file.py b/gridfs/asynchronous/grid_file.py index 748092ffd3..095c50f7d3 100644 --- a/gridfs/asynchronous/grid_file.py +++ b/gridfs/asynchronous/grid_file.py @@ -47,7 +47,7 @@ from pymongo.asynchronous.cursor import AsyncCursor from pymongo.asynchronous.database import AsyncDatabase from pymongo.asynchronous.helpers import anext -from pymongo.common import validate_string +from pymongo.common import validate_string, validate_string_or_none from pymongo.errors import ( BulkWriteError, ConfigurationError, @@ -205,6 +205,8 @@ async def get_version( ``-3``, version ``1`` is the same as version ``-2``, and version ``2`` is the same as version ``-1``. + Raises :class:`TypeError` if `filename` is not a string or `None`. + Raises :class:`~gridfs.errors.NoFile` if no such version of that file exists. @@ -215,12 +217,16 @@ async def get_version( :class:`~pymongo.client_session.AsyncClientSession` :param kwargs: find files by custom metadata. + .. versionchanged:: 4.20.2 + Raise :class:`TypeError` if `filename` is not a string or `None`. + .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.1 ``get_version`` no longer ensures indexes. """ + validate_string_or_none("filename", filename) query = kwargs if filename is not None: query["filename"] = filename @@ -252,11 +258,16 @@ async def get_last_version( Equivalent to calling :meth:`get_version` with the default `version` (``-1``). + Raises :class:`TypeError` if `filename` is not a string or `None`. + :param filename: ``"filename"`` of the file to get, or `None` :param session: a :class:`~pymongo.client_session.AsyncClientSession` :param kwargs: find files by custom metadata. + .. versionchanged:: 4.20.2 + Raise :class:`TypeError` if `filename` is not a string or `None`. + .. versionchanged:: 3.6 Added ``session`` parameter. """ diff --git a/gridfs/synchronous/grid_file.py b/gridfs/synchronous/grid_file.py index e3d57fb0af..6d106fda36 100644 --- a/gridfs/synchronous/grid_file.py +++ b/gridfs/synchronous/grid_file.py @@ -43,7 +43,7 @@ _grid_out_property, ) from pymongo import ASCENDING, DESCENDING, WriteConcern, _csot -from pymongo.common import validate_string +from pymongo.common import validate_string, validate_string_or_none from pymongo.errors import ( BulkWriteError, ConfigurationError, @@ -205,6 +205,8 @@ def get_version( ``-3``, version ``1`` is the same as version ``-2``, and version ``2`` is the same as version ``-1``. + Raises :class:`TypeError` if `filename` is not a string or `None`. + Raises :class:`~gridfs.errors.NoFile` if no such version of that file exists. @@ -215,12 +217,16 @@ def get_version( :class:`~pymongo.client_session.ClientSession` :param kwargs: find files by custom metadata. + .. versionchanged:: 4.20.2 + Raise :class:`TypeError` if `filename` is not a string or `None`. + .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.1 ``get_version`` no longer ensures indexes. """ + validate_string_or_none("filename", filename) query = kwargs if filename is not None: query["filename"] = filename @@ -252,11 +258,16 @@ def get_last_version( Equivalent to calling :meth:`get_version` with the default `version` (``-1``). + Raises :class:`TypeError` if `filename` is not a string or `None`. + :param filename: ``"filename"`` of the file to get, or `None` :param session: a :class:`~pymongo.client_session.ClientSession` :param kwargs: find files by custom metadata. + .. versionchanged:: 4.20.2 + Raise :class:`TypeError` if `filename` is not a string or `None`. + .. versionchanged:: 3.6 Added ``session`` parameter. """ diff --git a/test/asynchronous/test_gridfs.py b/test/asynchronous/test_gridfs.py index 6b1c1c9460..e21d7a93a3 100644 --- a/test/asynchronous/test_gridfs.py +++ b/test/asynchronous/test_gridfs.py @@ -363,6 +363,13 @@ async def test_get_version_with_metadata(self): await self.fs.delete(two) await self.fs.delete(three) + async def test_get_version_invalid_filename(self): + msg = "Wrong type for filename" + with self.assertRaisesRegex(TypeError, msg): + await self.fs.get_version({"filename": "test"}) # type: ignore[arg-type] + with self.assertRaisesRegex(TypeError, msg): + await self.fs.get_last_version(filename=["test"]) # type: ignore[arg-type] + async def test_put_filelike(self): oid = await self.fs.put(BytesIO(b"hello world"), chunk_size=1) self.assertEqual(11, await self.db.fs.chunks.count_documents({})) diff --git a/test/test_gridfs.py b/test/test_gridfs.py index 6371fd2019..7173ee60f7 100644 --- a/test/test_gridfs.py +++ b/test/test_gridfs.py @@ -357,6 +357,13 @@ def test_get_version_with_metadata(self): self.fs.delete(two) self.fs.delete(three) + def test_get_version_invalid_filename(self): + msg = "Wrong type for filename" + with self.assertRaisesRegex(TypeError, msg): + self.fs.get_version({"filename": "test"}) # type: ignore[arg-type] + with self.assertRaisesRegex(TypeError, msg): + self.fs.get_last_version(filename=["test"]) # type: ignore[arg-type] + def test_put_filelike(self): oid = self.fs.put(BytesIO(b"hello world"), chunk_size=1) self.assertEqual(11, self.db.fs.chunks.count_documents({})) From acd5566b78e91460a44bf3b73b700970f27df8e8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:11:17 -0800 Subject: [PATCH 04/11] Bump peter-evans/create-pull-request from 8.1.2 to 8.1.3 in the actions group (#3243) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/sbom.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sbom.yml b/.github/workflows/sbom.yml index 7ce512e656..2f433291a1 100644 --- a/.github/workflows/sbom.yml +++ b/.github/workflows/sbom.yml @@ -75,7 +75,7 @@ jobs: if-no-files-found: error - name: Create Pull Request - uses: peter-evans/create-pull-request@15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8 # v8.1.2 + uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3 with: token: ${{ secrets.GITHUB_TOKEN }} commit-message: 'chore: Update SBOM after dependency changes' From 05ad7e86e29fe51c25ba499f0463b06a5bd0cb72 Mon Sep 17 00:00:00 2001 From: "mongodb-drivers-pr-bot[bot]" <147046816+mongodb-drivers-pr-bot[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:57:19 -0600 Subject: [PATCH 05/11] [Spec Resync] 11-23-2026 (#3244) Co-authored-by: mongodb-drivers-pr-bot[bot] <147046816+mongodb-drivers-pr-bot[bot]@users.noreply.github.com> Co-authored-by: Steven Silvester --- .evergreen/spec-patch/PYTHON-6058.patch | 419 ++++++++++++++++++ .../rediscover-quickly-after-step-down.json | 3 +- test/transactions/unified/commit.json | 7 +- .../invalid/runOnRequirement-dsc-enum.json | 15 + .../invalid/runOnRequirement-dsc-type.json | 15 + 5 files changed, 457 insertions(+), 2 deletions(-) create mode 100644 .evergreen/spec-patch/PYTHON-6058.patch create mode 100644 test/unified-test-format/invalid/runOnRequirement-dsc-enum.json create mode 100644 test/unified-test-format/invalid/runOnRequirement-dsc-type.json diff --git a/.evergreen/spec-patch/PYTHON-6058.patch b/.evergreen/spec-patch/PYTHON-6058.patch new file mode 100644 index 0000000000..e119640db2 --- /dev/null +++ b/.evergreen/spec-patch/PYTHON-6058.patch @@ -0,0 +1,419 @@ +NEEDED UNTIL DRIVERS-3623 ADDS THE CREDENTIAL-DISCLOSURE CORPUS TO THE SPEC REPO +diff --git a/test/connection_string/test/credential-disclosure.json b/test/connection_string/test/credential-disclosure.json +deleted file mode 100644 +index de88a82..0000000 +--- a/test/connection_string/test/credential-disclosure.json ++++ /dev/null +@@ -1,412 +0,0 @@ +-{ +- "tests": [ +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-bare-1", +- "uri": "mongodb://testuser:SENTINELpassword1234:27017" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-bare-2", +- "uri": "mongodb://testuser:SENTINELpassword1234" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-bare-pctenc", +- "uri": "mongodb://testuser:%53%45%4E%54%49%4E%45%4C%70%61%73%73%77%6F%72%64%31%32%33%34" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-ipv6", +- "uri": "mongodb://testuser:[SENTINELpassword1234]" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-seedlist-first", +- "uri": "mongodb://testuser:SENTINELpassword1234,localhost:27017" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-seedlist-first-withdb", +- "uri": "mongodb://testuser:SENTINELpassword1234,localhost:27017/admin" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-seedlist-later", +- "uri": "mongodb://localhost:27017,testuser:SENTINELpassword1234" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-seedlist-later-withdb", +- "uri": "mongodb://localhost:27017,testuser:SENTINELpassword1234/admin" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-srv-withdb", +- "uri": "mongodb+srv://testuser:SENTINELpassword1234/admin" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-srv-withdb-pctenc", +- "uri": "mongodb+srv://testuser:%53%45%4E%54%49%4E%45%4C%70%61%73%73%77%6F%72%64%31%32%33%34/admin" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-withdb", +- "uri": "mongodb://testuser:SENTINELpassword1234/admin" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-withdb-pctenc", +- "uri": "mongodb://testuser:%53%45%4E%54%49%4E%45%4C%70%61%73%73%77%6F%72%64%31%32%33%34/admin" +- }, +- { +- "description": "credential present with no at-sign to delimit it from the host information: noat-withdb-withopts", +- "uri": "mongodb://testuser:SENTINELpassword1234/admin?tls=true" +- }, +- { +- "description": "unencoded at-sign in the password: pw-at-after-1", +- "uri": "mongodb://testuser:a@b/SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "unencoded at-sign in the password: pw-at-after-2", +- "uri": "mongodb://testuser:x@@SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "unencoded at-sign in the password: pw-at-after-3", +- "uri": "mongodb://testuser:x@SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "unencoded at-sign in the password: pw-at-after-badport", +- "uri": "mongodb://testuser:a@b#SENTINELpassword1234@localhost:notaport/admin" +- }, +- { +- "description": "unencoded at-sign in the password: pw-at-after-badport-pctenc", +- "uri": "mongodb://testuser:a@b#%53%45%4E%54%49%4E%45%4C%70%61%73%73%77%6F%72%64%31%32%33%34@localhost:notaport/admin" +- }, +- { +- "description": "unencoded at-sign in the password: pw-at-after-pctenc-1", +- "uri": "mongodb://testuser:x@%53%45%4E%54%49%4E%45%4C%70%61%73%73%77%6F%72%64%31%32%33%34@localhost:27017/admin" +- }, +- { +- "description": "unencoded at-sign in the password: pw-at-after-pctenc-2", +- "uri": "mongodb://testuser:a@b/%53%45%4E%54%49%4E%45%4C%70%61%73%73%77%6F%72%64%31%32%33%34@localhost:27017/admin" +- }, +- { +- "description": "unencoded at-sign in the password: pw-at-before-1", +- "uri": "mongodb://testuser:SENTINELpassword1234@@localhost:27017/admin" +- }, +- { +- "description": "unencoded at-sign in the password: pw-at-before-2", +- "uri": "mongodb://testuser:SENTINELpassword1234@x@localhost:27017/admin" +- }, +- { +- "description": "unencoded at-sign in the password: pw-at-before-3", +- "uri": "mongodb://testuser:SENTINELpassword1234@localhost:notaport@x/admin" +- }, +- { +- "description": "unencoded at-sign in the password: pw-at-before-4", +- "uri": "mongodb://testuser:SENTINELpassword1234@extra@localhost:27017/admin" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-after", +- "uri": "mongodb://testuser:localhost/SENTINELpassword1234@localhost" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-after-badoptvalue", +- "uri": "mongodb://testuser:x/SENTINELpassword1234@localhost:27017/admin?connectTimeoutMS=notanumber" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-after-badport", +- "uri": "mongodb://testuser:x/SENTINELpassword1234@localhost:notaport/" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-after-empty-head", +- "uri": "mongodb://testuser:/SENTINELpassword1234@localhost" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-after-empty-head-badscheme", +- "uri": "mongodb:/testuser:SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-after-emptyhost-unixsocket", +- "uri": "mongodb://testuser:x/SENTINELpassword1234@/tmp/mongodb.sock/admin" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-after-numeric-head", +- "uri": "mongodb://testuser:12345/SENTINELpassword1234@localhost" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-after-numeric-head-srv", +- "uri": "mongodb+srv://testuser:12345/SENTINELpassword1234@localhost/admin" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-after-opt", +- "uri": "mongodb://testuser:x/SENTINELpassword1234@localhost:27017/admin?readPreference=notapref" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-after-srv", +- "uri": "mongodb+srv://testuser:x/SENTINELpassword1234@localhost/admin" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-before", +- "uri": "mongodb://testuser:SENTINELpassword1234/x@localhost:27017" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-before-ipv6", +- "uri": "mongodb://testuser:SENTINELpassword1234/x@[::1]:27017/admin" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-before-opt", +- "uri": "mongodb://testuser:SENTINELpassword1234/x@localhost:27017/admin?authSource=%" +- }, +- { +- "description": "unencoded slash in the password: pw-slash-before-srv", +- "uri": "mongodb+srv://testuser:SENTINELpassword1234/x@localhost/admin" +- }, +- { +- "description": "unencoded question mark in the password: pw-question-after", +- "uri": "mongodb://testuser:x?readPreference=SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "unencoded question mark in the password: pw-question-after-badoptvalue", +- "uri": "mongodb://testuser:x?SENTINELpassword1234@localhost:27017/admin?connectTimeoutMS=notanumber" +- }, +- { +- "description": "unencoded question mark in the password: pw-question-after-badport", +- "uri": "mongodb://testuser:x?SENTINELpassword1234@localhost:notaport/admin" +- }, +- { +- "description": "unencoded question mark in the password: pw-question-after-empty-head", +- "uri": "mongodb://testuser:?SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "unencoded question mark in the password: pw-question-after-numeric-head", +- "uri": "mongodb://testuser:12345?SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "unencoded question mark in the password: pw-question-after-numeric-head-srv", +- "uri": "mongodb+srv://testuser:12345?SENTINELpassword1234=1@localhost/admin" +- }, +- { +- "description": "unencoded question mark in the password: pw-question-after-opt", +- "uri": "mongodb://testuser:x?SENTINELpassword1234@localhost:27017?w=1" +- }, +- { +- "description": "unencoded question mark in the password: pw-question-after-srv", +- "uri": "mongodb+srv://testuser:x?SENTINELpassword1234@my.example.test:27017/admin" +- }, +- { +- "description": "unencoded question mark in the password: pw-question-after-unknownopt", +- "uri": "mongodb://testuser:x?SENTINELpassword1234@localhost:27017/admin?justakey" +- }, +- { +- "description": "unencoded question mark in the password: pw-question-before", +- "uri": "mongodb://testuser:SENTINELpassword1234?x@localhost:27017/admin" +- }, +- { +- "description": "invalid percent-escape in the password: pw-percent-after", +- "uri": "mongodb://testuser:x%SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "invalid percent-escape in the password: pw-percent-after-badport", +- "uri": "mongodb://testuser:mongodb%3A%2F%2FSENTINELpassword1234@localhost:notaport/admin" +- }, +- { +- "description": "invalid percent-escape in the password: pw-percent-after-empty-head", +- "uri": "mongodb://testuser:%zzSENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "invalid percent-escape in the password: pw-percent-after-empty-head-badport", +- "uri": "mongodb://testuser:%12345SENTINELpassword1234@localhost:notaport/admin" +- }, +- { +- "description": "invalid percent-escape in the password: pw-percent-after-empty-head-opt", +- "uri": "mongodb://testuser:%12345%12345%12345SENTINELpassword1234%12345F@localhost:27017/admin?bogus=1" +- }, +- { +- "description": "invalid percent-escape in the password: pw-percent-after-opt", +- "uri": "mongodb://testuser:mongodb%3A%2F%2FSENTINELpassword1234@localhost:27017/admin?zzz=1" +- }, +- { +- "description": "invalid percent-escape in the password: pw-percent-after-unknownopt", +- "uri": "mongodb://testuser:x%12345FSENTINELpassword1234@localhost:27017/admin?bogusOption=1" +- }, +- { +- "description": "invalid percent-escape in the password: pw-percent-before", +- "uri": "mongodb://testuser:SENTINELpassword1234%2Fx@localhost:27017/admin" +- }, +- { +- "description": "invalid percent-escape in the password: pw-percent-before-badport", +- "uri": "mongodb://testuser:SENTINELpassword1234%3A%2F%2Fhost@localhost:notaport/admin" +- }, +- { +- "description": "invalid percent-escape in the password: pw-percent-before-unknownopt", +- "uri": "mongodb://testuser:SENTINELpassword1234%2Fx@localhost:27017/admin?bogusOption=1" +- }, +- { +- "description": "unencoded delimiter in the password: pw-amp-after", +- "uri": "mongodb://testuser:x&SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "unencoded delimiter in the password: pw-amp-before", +- "uri": "mongodb://testuser:SENTINELpassword1234&x@localhost:27017/admin" +- }, +- { +- "description": "unencoded delimiter in the password: pw-colon-after", +- "uri": "mongodb://testuser:[::1]/SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "unencoded delimiter in the password: pw-colon-before", +- "uri": "mongodb://testuser:SENTINELpassword1234:x@localhost:27017/admin" +- }, +- { +- "description": "unencoded delimiter in the password: pw-comma-after", +- "uri": "mongodb://testuser:x,SENTINELpassword1234@localhost:notaport/admin" +- }, +- { +- "description": "unencoded delimiter in the password: pw-comma-before", +- "uri": "mongodb://testuser:SENTINELpassword1234,x@localhost:notaport/admin" +- }, +- { +- "description": "unencoded delimiter in the password: pw-equals-after", +- "uri": "mongodb://testuser:x=SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "unencoded delimiter in the password: pw-equals-before", +- "uri": "mongodb://testuser:SENTINELpassword1234=x@localhost:27017/admin" +- }, +- { +- "description": "unencoded delimiter in the password: pw-hash-after", +- "uri": "mongodb://testuser:x#SENTINELpassword1234@localhost:notaport/admin" +- }, +- { +- "description": "unencoded delimiter in the password: pw-hash-before", +- "uri": "mongodb://testuser:SENTINELpassword1234#x@localhost:notaport/admin" +- }, +- { +- "description": "unencoded delimiter in the password: pw-plus-after", +- "uri": "mongodb://testuser:x+SENTINELpassword1234@localhost:27017/admin?connectTimeoutMS=x" +- }, +- { +- "description": "unencoded delimiter in the password: pw-plus-before", +- "uri": "mongodb://testuser:SENTINELpassword1234+x@localhost:notaport/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean", +- "uri": "mongodb://testuser:SENTINELpassword1234@localhost:999999/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-badoptvalue", +- "uri": "mongodb://testuser:SENTINELpassword1234@LoCaLhOsT:27017/admin?connectTimeoutMS=notanumber" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-badoptvalue-unknownopt", +- "uri": "mongodb://testuser:SENTINELpassword1234@localhost:27017/admin?bogusOption=1&connectTimeoutMS=notanumber" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-badport", +- "uri": "mongodb://testuser:SENTINELpassword1234@localhost:notaport/admin?tls=notabool" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-badscheme", +- "uri": "mongod://testuser:SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-dbbadchar", +- "uri": "mongodb://testuser:SENTINELpassword1234@localhost:27017/ad min.db" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-dbbadchar-emptyhost-unixsocket", +- "uri": "mongodb://testuser:SENTINELpassword1234@/tmp/mongodb.sock/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-dbbadchar-unixsocket", +- "uri": "mongodb://testuser:SENTINELpassword1234@%2Ftmp%2Fmongo.sock/x/y.sock/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-emptyhost", +- "uri": "mongodb://testuser:SENTINELpassword1234@/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-emptyuser", +- "uri": "mongodb://:SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-ipv6", +- "uri": "mongodb://testuser:SENTINELpassword1234@[::1]:notaport/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-long", +- "uri": "mongodb://testuser:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-opt", +- "uri": "mongodb://testuser:SENTINELpassword1234@localhost:27017/admin?appname=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-portzero", +- "uri": "mongodb://testuser:SENTINELpassword1234@localhost:0/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-seedlist-other-badport", +- "uri": "mongodb://testuser:SENTINELpassword1234@localhost:27017,/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-seedlist-other-opt", +- "uri": "mongodb://testuser:SENTINELpassword1234@a.example.com,b.example.com/admin?directConnection=true" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-srv-badoptvalue", +- "uri": "mongodb+srv://testuser:SENTINELpassword1234@a.example.com/admin?connectTimeoutMS=notanumber" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-srv", +- "uri": "mongodb+srv://testuser:SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-srv-emptyhost", +- "uri": "mongodb+srv://testuser:SENTINELpassword1234@/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-srv-opt", +- "uri": "mongodb+srv://testuser:SENTINELpassword1234@a.example/admin?directConnection=true" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-srv-seedlist-other", +- "uri": "mongodb+srv://testuser:SENTINELpassword1234@a.example.com,b.example.com/admin" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-unixsocket-opt", +- "uri": "mongodb://testuser:SENTINELpassword1234@%2Ftmp%2Fmongodb.sock/admin?bogus=1" +- }, +- { +- "description": "correctly encoded password with an unrelated error elsewhere: pw-clean-unknownopt", +- "uri": "mongodb://testuser:SENTINELpassword1234@localhost:27017/admin?bogusOption=1" +- }, +- { +- "description": "sentinel carried in the username component of the userinfo: sentinel-in-username-1", +- "uri": "mongodb://testuser?SENTINELpassword1234@localhost:27017/admin" +- }, +- { +- "description": "sentinel carried in the username component of the userinfo: sentinel-in-username-2", +- "uri": "mongodb://SENTINELpassword1234%ZZ:pw@localhost:27017/admin" +- }, +- { +- "description": "sentinel carried in the username component of the userinfo: sentinel-in-username-3", +- "uri": "mongodb://SENTINELpassword1234/x@localhost:27017/admin" +- }, +- { +- "description": "sentinel carried in the username component of the userinfo: sentinel-in-username-srv", +- "uri": "mongodb+srv://testuser?SENTINELpassword1234@localhost/admin" +- }, +- { +- "description": "credential as the argument of an unrecognized option: optarg-unrecognized", +- "uri": "mongodb://localhost:27017/?notARealOption=SENTINELpassword1234" +- }, +- { +- "description": "credential as the argument of a sensitive option: optarg-sensitive", +- "uri": "mongodb://localhost:27017/?proxyPassword=SENTINELpassword1234" +- }, +- { +- "description": "credential merged into an option key by a missing equals sign: optkey-merged", +- "uri": "mongodb://localhost:27017/?proxyPasswordSENTINELpassword1234" +- }, +- { +- "description": "credential as the argument of a known integer option, where it fails integer conversion: optarg-known-integer-unparsable", +- "uri": "mongodb://localhost:27017/?connectTimeoutMS=SENTINELpassword1234" +- }, +- { +- "description": "credential as the argument of authMechanism, naming no mechanism the driver knows: optarg-unknown-mechanism", +- "uri": "mongodb://localhost:27017/?authMechanism=SENTINELpassword1234" +- } +- ] +-} diff --git a/test/discovery_and_monitoring/unified/rediscover-quickly-after-step-down.json b/test/discovery_and_monitoring/unified/rediscover-quickly-after-step-down.json index 3147a07a1e..8420e2fc6c 100644 --- a/test/discovery_and_monitoring/unified/rediscover-quickly-after-step-down.json +++ b/test/discovery_and_monitoring/unified/rediscover-quickly-after-step-down.json @@ -1,10 +1,11 @@ { "description": "rediscover-quickly-after-step-down", - "schemaVersion": "1.4", + "schemaVersion": "1.30", "runOnRequirements": [ { "minServerVersion": "4.4", "serverless": "forbid", + "dsc": "forbid", "topologies": [ "replicaset" ] diff --git a/test/transactions/unified/commit.json b/test/transactions/unified/commit.json index de3be30470..6233af695b 100644 --- a/test/transactions/unified/commit.json +++ b/test/transactions/unified/commit.json @@ -1,6 +1,6 @@ { "description": "commit", - "schemaVersion": "1.3", + "schemaVersion": "1.30", "runOnRequirements": [ { "minServerVersion": "4.0", @@ -536,6 +536,11 @@ }, { "description": "write concern error on commit", + "runOnRequirements": [ + { + "dsc": "forbid" + } + ], "operations": [ { "object": "session0", diff --git a/test/unified-test-format/invalid/runOnRequirement-dsc-enum.json b/test/unified-test-format/invalid/runOnRequirement-dsc-enum.json new file mode 100644 index 0000000000..7292da33ad --- /dev/null +++ b/test/unified-test-format/invalid/runOnRequirement-dsc-enum.json @@ -0,0 +1,15 @@ +{ + "description": "runOnRequirement-dsc-enum", + "schemaVersion": "1.30", + "runOnRequirements": [ + { + "dsc": "foo" + } + ], + "tests": [ + { + "description": "foo", + "operations": [] + } + ] +} diff --git a/test/unified-test-format/invalid/runOnRequirement-dsc-type.json b/test/unified-test-format/invalid/runOnRequirement-dsc-type.json new file mode 100644 index 0000000000..05071f31ff --- /dev/null +++ b/test/unified-test-format/invalid/runOnRequirement-dsc-type.json @@ -0,0 +1,15 @@ +{ + "description": "runOnRequirement-dsc-type", + "schemaVersion": "1.30", + "runOnRequirements": [ + { + "dsc": 1234 + } + ], + "tests": [ + { + "description": "foo", + "operations": [] + } + ] +} From 85b512a8035c9f16cb6c839d1be1012545687396 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Mon, 23 Nov 2026 14:27:09 -0600 Subject: [PATCH 06/11] PYTHON-6290 Fix fuzz corpus capture replay (#3245) --- .evergreen/scripts/capture-fuzz-corpus.sh | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.evergreen/scripts/capture-fuzz-corpus.sh b/.evergreen/scripts/capture-fuzz-corpus.sh index 438c7f6754..1b3512e4b0 100755 --- a/.evergreen/scripts/capture-fuzz-corpus.sh +++ b/.evergreen/scripts/capture-fuzz-corpus.sh @@ -15,12 +15,11 @@ if [ -z "$(ls -A fuzz-scratch/capture 2>/dev/null || true)" ]; then exit 0 fi -# A unit found by a later target never ran through the earlier ones, so -# replay every unit through all targets before publishing. +# The replay runs the atheris targets, so it must request the fuzz group. 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 --no-sync python "fuzz/${target}.py" "${replay[@]}" \ + if ! uv run --group fuzz python "fuzz/${target}.py" "${replay[@]}" \ -artifact_prefix="$PWD/fuzz-scratch/" -atheris_runs="${#replay[@]}" then echo "Captured unit fails ${target}; no corpus PR." >&2 From e825c41545061bafcdba7265a83cc9d1011bb7b7 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Mon, 23 Nov 2026 14:28:16 -0600 Subject: [PATCH 07/11] PYTHON-6286 Fix system bootstrap for older system Pythons (#3246) --- .evergreen/scripts/setup_uv.py | 5 ++--- .evergreen/scripts/test_setup_uv.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.evergreen/scripts/setup_uv.py b/.evergreen/scripts/setup_uv.py index a7d3832a7a..277ee52b86 100755 --- a/.evergreen/scripts/setup_uv.py +++ b/.evergreen/scripts/setup_uv.py @@ -10,11 +10,10 @@ elsewhere on PATH may be invisible to later steps, so setup never accepts it as-is. -This runs under the host's system python3, which may be older than our minimum supported version. +This runs under the host's system python3, which may be as old as Python 3.6 (RHEL 8). +Keep it free of __future__ imports and other 3.7+ syntax. test_setup_uv.py checks this. """ -from __future__ import annotations - import os import re import shlex diff --git a/.evergreen/scripts/test_setup_uv.py b/.evergreen/scripts/test_setup_uv.py index d16052e481..47fafd1a92 100644 --- a/.evergreen/scripts/test_setup_uv.py +++ b/.evergreen/scripts/test_setup_uv.py @@ -10,6 +10,7 @@ from __future__ import annotations +import ast import importlib.util import os import shutil @@ -521,3 +522,17 @@ def test_main_pinned_self_overwrite_runs_from_copy(tmp_path, project): assert proc.returncode == 0, proc.stderr assert (bin_dir / "uv").exists() assert f"installed-from=uv{PIN}\n" in log.read_text() + + +def test_setup_uv_supports_python_36(): + """setup_uv.py runs under the host's system python3, 3.6 on RHEL8 (PYTHON-6286).""" + # feature_version checks grammar only; it does not validate __future__ + # feature names, so scan for those imports explicitly. + tree = ast.parse(SETUP_UV.read_text(), filename=str(SETUP_UV), feature_version=(3, 6)) + futures = [ + alias.name + for node in ast.walk(tree) + if isinstance(node, ast.ImportFrom) and node.module == "__future__" + for alias in node.names + ] + assert not futures, f"Python 3.6 rejects these __future__ imports: {futures}" From 65d894b75ead08a24be96ed5d1d2cd6fb991a3fc Mon Sep 17 00:00:00 2001 From: ayuubhagi Date: Mon, 23 Nov 2026 17:08:21 -0500 Subject: [PATCH 08/11] PYTHON-5939 Fix typo in MONGODB_LOG_MAX_DOCUMENT_LENGTH environment variable name (#3238) Co-authored-by: Iris Co-authored-by: Iris <58442094+sleepyStick@users.noreply.github.com> --- doc/changelog.rst | 5 +++++ pymongo/logger.py | 8 ++++++- test/asynchronous/test_logger.py | 36 +++++++++++++++++++++++++++++--- test/helpers_shared.py | 2 +- test/test_logger.py | 36 +++++++++++++++++++++++++++++--- 5 files changed, 79 insertions(+), 8 deletions(-) diff --git a/doc/changelog.rst b/doc/changelog.rst index 49141a8a18..6e8a8de0b8 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -11,8 +11,13 @@ Bug fixes :meth:`~gridfs.GridFS.get_last_version` accepted a non-string ``filename`` and treated a dict as query criteria. They now raise :exc:`TypeError` (`PYTHON-6183`_). +- Fixed a bug where the ``MONGODB_LOG_MAX_DOCUMENT_LENGTH`` environment + variable was ignored because PyMongo read the misspelled + ``MONGOB_LOG_MAX_DOCUMENT_LENGTH`` instead. The misspelled name is still + read when ``MONGODB_LOG_MAX_DOCUMENT_LENGTH`` is not set (`PYTHON-5939`_). .. _PYTHON-6183: https://jira.mongodb.org/browse/PYTHON-6183 +.. _PYTHON-5939: https://jira.mongodb.org/browse/PYTHON-5939 Changes in Version 4.20.1 (2026/11/19) -------------------------------------- diff --git a/pymongo/logger.py b/pymongo/logger.py index c19557a659..fd0ff44f5b 100644 --- a/pymongo/logger.py +++ b/pymongo/logger.py @@ -168,7 +168,13 @@ def _redact(self) -> None: self._kwargs["durationMS"] = self._kwargs["durationMS"].total_seconds() * 1000 if "serviceId" in self._kwargs: self._kwargs["serviceId"] = str(self._kwargs["serviceId"]) - document_length = int(os.getenv("MONGOB_LOG_MAX_DOCUMENT_LENGTH", _DEFAULT_DOCUMENT_LENGTH)) + document_length = int( + os.getenv( + "MONGODB_LOG_MAX_DOCUMENT_LENGTH", + # Fall back to the misspelled name that older versions read. + os.getenv("MONGOB_LOG_MAX_DOCUMENT_LENGTH", _DEFAULT_DOCUMENT_LENGTH), + ) + ) if document_length < 0: document_length = _DEFAULT_DOCUMENT_LENGTH is_server_side_error = self._kwargs.pop("isServerSideError", False) diff --git a/test/asynchronous/test_logger.py b/test/asynchronous/test_logger.py index 3291169b07..c060a4e8bf 100644 --- a/test/asynchronous/test_logger.py +++ b/test/asynchronous/test_logger.py @@ -18,7 +18,7 @@ from bson import json_util from pymongo.errors import OperationFailure -from pymongo.logger import _DEFAULT_DOCUMENT_LENGTH, _CommandStatusMessage +from pymongo.logger import _DEFAULT_DOCUMENT_LENGTH, LogMessage, _CommandStatusMessage from test import unittest from test.asynchronous import AsyncIntegrationTest, async_client_context @@ -46,6 +46,7 @@ async def test_default_truncation_limit(self): with patch.dict("os.environ"): os.environ.pop("MONGOB_LOG_MAX_DOCUMENT_LENGTH", None) + os.environ.pop("MONGODB_LOG_MAX_DOCUMENT_LENGTH", None) with self.assertLogs("pymongo.command", level="DEBUG") as cm: await db.coll.insert_many(docs) @@ -69,7 +70,7 @@ async def test_default_truncation_limit(self): async def test_configured_truncation_limit(self): cmd = {"hello": True} db = self.db - with patch.dict("os.environ", {"MONGOB_LOG_MAX_DOCUMENT_LENGTH": "5"}): + with patch.dict("os.environ", {"MONGODB_LOG_MAX_DOCUMENT_LENGTH": "5"}): with self.assertLogs("pymongo.command", level="DEBUG") as cm: await db.command(cmd) @@ -99,7 +100,7 @@ async def test_truncation_multi_byte_codepoints(self): multi_byte_char_str += str_to_repeat for length in document_lengths: - with patch.dict("os.environ", {"MONGOB_LOG_MAX_DOCUMENT_LENGTH": length}): + with patch.dict("os.environ", {"MONGODB_LOG_MAX_DOCUMENT_LENGTH": length}): with self.assertLogs("pymongo.command", level="DEBUG") as cm: await self.db.coll.insert_one({"x": multi_byte_char_str}) cmd_started_log = self._get_command_log( @@ -168,5 +169,34 @@ async def test_logging_retry_write_attempts(self): self.assertEqual(len(retry_messages), 1) +class TestLogMessageTruncation(unittest.TestCase): + def _command_log(self): + msg = LogMessage( + message=_CommandStatusMessage.STARTED, + commandName="insert", + command={"insert": "coll", "documents": [{"x": "y" * 50}]}, + ) + return json_util.loads(str(msg))["command"] + + def test_max_document_length_env_var(self): + with patch.dict("os.environ", {"MONGODB_LOG_MAX_DOCUMENT_LENGTH": "10"}): + os.environ.pop("MONGOB_LOG_MAX_DOCUMENT_LENGTH", None) + self.assertEqual(len(self._command_log()), 10 + 3) + + def test_max_document_length_env_var_takes_precedence(self): + env = { + "MONGODB_LOG_MAX_DOCUMENT_LENGTH": "10", + "MONGOB_LOG_MAX_DOCUMENT_LENGTH": "20", + } + with patch.dict("os.environ", env): + self.assertEqual(len(self._command_log()), 10 + 3) + + def test_misspelled_max_document_length_env_var(self): + # The misspelled name was the only one read before PYTHON-5939. + with patch.dict("os.environ", {"MONGOB_LOG_MAX_DOCUMENT_LENGTH": "10"}): + os.environ.pop("MONGODB_LOG_MAX_DOCUMENT_LENGTH", None) + self.assertEqual(len(self._command_log()), 10 + 3) + + if __name__ == "__main__": unittest.main() diff --git a/test/helpers_shared.py b/test/helpers_shared.py index 0e2d567422..0ccbd0ff14 100644 --- a/test/helpers_shared.py +++ b/test/helpers_shared.py @@ -121,7 +121,7 @@ DEFAULT_KMS_TLS = dict(kmip=dict(tlsCAFile=CA_PEM, tlsCertificateKeyFile=CLIENT_PEM)) # Ensure Evergreen metadata doesn't result in truncation -os.environ.setdefault("MONGOB_LOG_MAX_DOCUMENT_LENGTH", "2000") +os.environ.setdefault("MONGODB_LOG_MAX_DOCUMENT_LENGTH", "2000") def is_server_resolvable(): diff --git a/test/test_logger.py b/test/test_logger.py index a1ae3291f7..d466b93cf1 100644 --- a/test/test_logger.py +++ b/test/test_logger.py @@ -18,7 +18,7 @@ from bson import json_util from pymongo.errors import OperationFailure -from pymongo.logger import _DEFAULT_DOCUMENT_LENGTH, _CommandStatusMessage +from pymongo.logger import _DEFAULT_DOCUMENT_LENGTH, LogMessage, _CommandStatusMessage from test import IntegrationTest, client_context, unittest _IS_SYNC = True @@ -45,6 +45,7 @@ def test_default_truncation_limit(self): with patch.dict("os.environ"): os.environ.pop("MONGOB_LOG_MAX_DOCUMENT_LENGTH", None) + os.environ.pop("MONGODB_LOG_MAX_DOCUMENT_LENGTH", None) with self.assertLogs("pymongo.command", level="DEBUG") as cm: db.coll.insert_many(docs) @@ -68,7 +69,7 @@ def test_default_truncation_limit(self): def test_configured_truncation_limit(self): cmd = {"hello": True} db = self.db - with patch.dict("os.environ", {"MONGOB_LOG_MAX_DOCUMENT_LENGTH": "5"}): + with patch.dict("os.environ", {"MONGODB_LOG_MAX_DOCUMENT_LENGTH": "5"}): with self.assertLogs("pymongo.command", level="DEBUG") as cm: db.command(cmd) @@ -98,7 +99,7 @@ def test_truncation_multi_byte_codepoints(self): multi_byte_char_str += str_to_repeat for length in document_lengths: - with patch.dict("os.environ", {"MONGOB_LOG_MAX_DOCUMENT_LENGTH": length}): + with patch.dict("os.environ", {"MONGODB_LOG_MAX_DOCUMENT_LENGTH": length}): with self.assertLogs("pymongo.command", level="DEBUG") as cm: self.db.coll.insert_one({"x": multi_byte_char_str}) cmd_started_log = self._get_command_log( @@ -167,5 +168,34 @@ def test_logging_retry_write_attempts(self): self.assertEqual(len(retry_messages), 1) +class TestLogMessageTruncation(unittest.TestCase): + def _command_log(self): + msg = LogMessage( + message=_CommandStatusMessage.STARTED, + commandName="insert", + command={"insert": "coll", "documents": [{"x": "y" * 50}]}, + ) + return json_util.loads(str(msg))["command"] + + def test_max_document_length_env_var(self): + with patch.dict("os.environ", {"MONGODB_LOG_MAX_DOCUMENT_LENGTH": "10"}): + os.environ.pop("MONGOB_LOG_MAX_DOCUMENT_LENGTH", None) + self.assertEqual(len(self._command_log()), 10 + 3) + + def test_max_document_length_env_var_takes_precedence(self): + env = { + "MONGODB_LOG_MAX_DOCUMENT_LENGTH": "10", + "MONGOB_LOG_MAX_DOCUMENT_LENGTH": "20", + } + with patch.dict("os.environ", env): + self.assertEqual(len(self._command_log()), 10 + 3) + + def test_misspelled_max_document_length_env_var(self): + # The misspelled name was the only one read before PYTHON-5939. + with patch.dict("os.environ", {"MONGOB_LOG_MAX_DOCUMENT_LENGTH": "10"}): + os.environ.pop("MONGODB_LOG_MAX_DOCUMENT_LENGTH", None) + self.assertEqual(len(self._command_log()), 10 + 3) + + if __name__ == "__main__": unittest.main() From 1bd6dfc3a77c5e60a04c8559bb7682fff39c5e15 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 24 Nov 2026 08:21:13 -0600 Subject: [PATCH 09/11] PYTHON-6287 Fix pytest usage on FIPS hosts (#3247) --- .evergreen/scripts/setup_tests.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.evergreen/scripts/setup_tests.py b/.evergreen/scripts/setup_tests.py index bd0efc550a..fecb6c9efc 100644 --- a/.evergreen/scripts/setup_tests.py +++ b/.evergreen/scripts/setup_tests.py @@ -679,6 +679,11 @@ def handle_test_env() -> None: elif opts.sync == "sync": TEST_ARGS = f"--ignore=test/asynchronous {TEST_ARGS}" + # pytest>=9.2 caches rewritten modules as hash-based pycs; importlib + # rejects them on FIPS hosts (PYTHON-6287). + if is_set("REQUIRE_FIPS"): + TEST_ARGS = f"--assert=plain {TEST_ARGS}" + write_env("TEST_ARGS", TEST_ARGS) write_env("UV_ARGS", " ".join(UV_ARGS)) From 0134933ea9298902d8e35fc2a2b6d77526943a53 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 24 Nov 2026 12:59:48 -0600 Subject: [PATCH 10/11] PYTHON-6293 Bump unified test runner to schema version 1.30 (#3250) --- test/asynchronous/test_unified_format.py | 80 ++++++++++++++++++++++++ test/asynchronous/unified_format.py | 2 +- test/test_unified_format.py | 80 ++++++++++++++++++++++++ test/unified_format.py | 2 +- test/unified_format_shared.py | 11 +++- 5 files changed, 171 insertions(+), 4 deletions(-) diff --git a/test/asynchronous/test_unified_format.py b/test/asynchronous/test_unified_format.py index e03ca1cc0e..6c652e5167 100644 --- a/test/asynchronous/test_unified_format.py +++ b/test/asynchronous/test_unified_format.py @@ -13,6 +13,7 @@ # limitations under the License. from __future__ import annotations +import json import os import sys from pathlib import Path @@ -24,9 +25,11 @@ from test import UnitTest, unittest from test.asynchronous.unified_format import ( MatchEvaluatorUtil, + UnifiedSpecTestMixinV1, generate_test_classes, get_test_path, ) +from test.version import Version _IS_SYNC = False @@ -55,6 +58,41 @@ ) +class TestSchemaVersionCoverage(UnitTest): + def test_all_spec_files_are_supported(self): + # PYTHON-6293: a spec resync that bumps a file's schemaVersion past + # the runner's SCHEMA_VERSION otherwise only surfaces as a runtime + # failure in asyncSetUp. Every consumed spec file must declare a + # schema version the runner supports. + # test/unified-test-format/invalid/ is not consumed by the runner and + # valid-fail/ files (including schemaVersion-unsupported.json) are + # deliberately invalid, so both are skipped. + runner_version = UnifiedSpecTestMixinV1.SCHEMA_VERSION + root = get_test_path() + skipped = ( + os.path.join("unified-test-format", "invalid"), + os.path.join("unified-test-format", "valid-fail"), + ) + unsupported = [] + for dirpath, dirnames, filenames in os.walk(root): + rel = os.path.relpath(dirpath, root) + if any(rel == prefix or rel.startswith(prefix + os.sep) for prefix in skipped): + continue + for filename in sorted(filenames): + if not filename.endswith(".json"): + continue + with open(os.path.join(dirpath, filename)) as fpath: + spec = json.load(fpath) + version = spec.get("schemaVersion") if isinstance(spec, dict) else None + if not isinstance(version, str): + continue + parsed = Version.from_string(version) + if parsed[0] != runner_version[0] or parsed > runner_version: + unsupported.append((os.path.join(rel, filename), version)) + + self.assertEqual(unsupported, []) + + class TestMatchEvaluatorUtil(UnitTest): def setUp(self): self.match_evaluator = MatchEvaluatorUtil(self) @@ -88,6 +126,48 @@ def test_type(self): }, ) + def test_lte(self): + # Added in schema version 1.9. + self.match_evaluator.match_result({"x": {"$$lte": 5}}, {"x": 5}) + self.match_evaluator.match_result({"x": {"$$lte": 5}}, {"x": 3}) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"x": {"$$lte": 5}}, {"x": 6}) + # An empty field name is a valid field key, not whole-result matching. + self.match_evaluator.match_result({"": {"$$lte": 5}}, {"": 5}) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"": {"$$lte": 5}}, {"": 6}) + + def test_lte_whole_result(self): + # A special operator can match an entire operation result or an + # array element, in which case there is no field key to compare. + self.match_evaluator.match_result({"$$lte": 5}, 5) + self.match_evaluator.match_result([{"$$lte": 5}], [5]) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"$$lte": 5}, 6) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result([{"$$lte": 5}], [6]) + + def test_gte(self): + # Added in schema version 1.29. + self.match_evaluator.match_result({"x": {"$$gte": 5}}, {"x": 5}) + self.match_evaluator.match_result({"x": {"$$gte": 5}}, {"x": 6}) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"x": {"$$gte": 5}}, {"x": 3}) + # An empty field name is a valid field key, not whole-result matching. + self.match_evaluator.match_result({"": {"$$gte": 5}}, {"": 5}) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"": {"$$gte": 5}}, {"": 3}) + + def test_gte_whole_result(self): + # A special operator can match an entire operation result or an + # array element, in which case there is no field key to compare. + self.match_evaluator.match_result({"$$gte": 5}, 5) + self.match_evaluator.match_result([{"$$gte": 5}], [5]) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"$$gte": 5}, 3) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result([{"$$gte": 5}], [3]) + if __name__ == "__main__": unittest.main() diff --git a/test/asynchronous/unified_format.py b/test/asynchronous/unified_format.py index 9e5afb6d98..e1c43d3c32 100644 --- a/test/asynchronous/unified_format.py +++ b/test/asynchronous/unified_format.py @@ -491,7 +491,7 @@ class UnifiedSpecTestMixinV1(AsyncIntegrationTest): a class attribute ``TEST_SPEC``. """ - SCHEMA_VERSION = Version.from_string("1.28") + SCHEMA_VERSION = Version.from_string("1.30") RUN_ON_LOAD_BALANCER = True TEST_SPEC: Any TEST_PATH = "" # This gets filled in by generate_test_classes diff --git a/test/test_unified_format.py b/test/test_unified_format.py index a02df1c560..190746bddf 100644 --- a/test/test_unified_format.py +++ b/test/test_unified_format.py @@ -13,6 +13,7 @@ # limitations under the License. from __future__ import annotations +import json import os import sys from pathlib import Path @@ -24,9 +25,11 @@ from test import UnitTest, unittest from test.unified_format import ( MatchEvaluatorUtil, + UnifiedSpecTestMixinV1, generate_test_classes, get_test_path, ) +from test.version import Version _IS_SYNC = True @@ -55,6 +58,41 @@ ) +class TestSchemaVersionCoverage(UnitTest): + def test_all_spec_files_are_supported(self): + # PYTHON-6293: a spec resync that bumps a file's schemaVersion past + # the runner's SCHEMA_VERSION otherwise only surfaces as a runtime + # failure in setUp. Every consumed spec file must declare a + # schema version the runner supports. + # test/unified-test-format/invalid/ is not consumed by the runner and + # valid-fail/ files (including schemaVersion-unsupported.json) are + # deliberately invalid, so both are skipped. + runner_version = UnifiedSpecTestMixinV1.SCHEMA_VERSION + root = get_test_path() + skipped = ( + os.path.join("unified-test-format", "invalid"), + os.path.join("unified-test-format", "valid-fail"), + ) + unsupported = [] + for dirpath, dirnames, filenames in os.walk(root): + rel = os.path.relpath(dirpath, root) + if any(rel == prefix or rel.startswith(prefix + os.sep) for prefix in skipped): + continue + for filename in sorted(filenames): + if not filename.endswith(".json"): + continue + with open(os.path.join(dirpath, filename)) as fpath: + spec = json.load(fpath) + version = spec.get("schemaVersion") if isinstance(spec, dict) else None + if not isinstance(version, str): + continue + parsed = Version.from_string(version) + if parsed[0] != runner_version[0] or parsed > runner_version: + unsupported.append((os.path.join(rel, filename), version)) + + self.assertEqual(unsupported, []) + + class TestMatchEvaluatorUtil(UnitTest): def setUp(self): self.match_evaluator = MatchEvaluatorUtil(self) @@ -88,6 +126,48 @@ def test_type(self): }, ) + def test_lte(self): + # Added in schema version 1.9. + self.match_evaluator.match_result({"x": {"$$lte": 5}}, {"x": 5}) + self.match_evaluator.match_result({"x": {"$$lte": 5}}, {"x": 3}) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"x": {"$$lte": 5}}, {"x": 6}) + # An empty field name is a valid field key, not whole-result matching. + self.match_evaluator.match_result({"": {"$$lte": 5}}, {"": 5}) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"": {"$$lte": 5}}, {"": 6}) + + def test_lte_whole_result(self): + # A special operator can match an entire operation result or an + # array element, in which case there is no field key to compare. + self.match_evaluator.match_result({"$$lte": 5}, 5) + self.match_evaluator.match_result([{"$$lte": 5}], [5]) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"$$lte": 5}, 6) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result([{"$$lte": 5}], [6]) + + def test_gte(self): + # Added in schema version 1.29. + self.match_evaluator.match_result({"x": {"$$gte": 5}}, {"x": 5}) + self.match_evaluator.match_result({"x": {"$$gte": 5}}, {"x": 6}) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"x": {"$$gte": 5}}, {"x": 3}) + # An empty field name is a valid field key, not whole-result matching. + self.match_evaluator.match_result({"": {"$$gte": 5}}, {"": 5}) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"": {"$$gte": 5}}, {"": 3}) + + def test_gte_whole_result(self): + # A special operator can match an entire operation result or an + # array element, in which case there is no field key to compare. + self.match_evaluator.match_result({"$$gte": 5}, 5) + self.match_evaluator.match_result([{"$$gte": 5}], [5]) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result({"$$gte": 5}, 3) + with self.assertRaises(AssertionError): + self.match_evaluator.match_result([{"$$gte": 5}], [3]) + if __name__ == "__main__": unittest.main() diff --git a/test/unified_format.py b/test/unified_format.py index 244d58514c..c4542de403 100644 --- a/test/unified_format.py +++ b/test/unified_format.py @@ -489,7 +489,7 @@ class UnifiedSpecTestMixinV1(IntegrationTest): a class attribute ``TEST_SPEC``. """ - SCHEMA_VERSION = Version.from_string("1.28") + SCHEMA_VERSION = Version.from_string("1.30") RUN_ON_LOAD_BALANCER = True TEST_SPEC: Any TEST_PATH = "" # This gets filled in by generate_test_classes diff --git a/test/unified_format_shared.py b/test/unified_format_shared.py index d860d345fc..e72611d6f0 100644 --- a/test/unified_format_shared.py +++ b/test/unified_format_shared.py @@ -449,9 +449,16 @@ def _operation_sessionLsid(self, spec, actual, key_to_compare): self.test.assertEqual(expected_lsid, actual[key_to_compare]) def _operation_lte(self, spec, actual, key_to_compare): - if key_to_compare not in actual: + if key_to_compare is not None and key_to_compare not in actual: + self.test.fail(f"Actual command is missing the {key_to_compare} field: {spec}") + value = actual[key_to_compare] if key_to_compare is not None else actual + self.test.assertLessEqual(value, spec) + + def _operation_gte(self, spec, actual, key_to_compare): + if key_to_compare is not None and key_to_compare not in actual: self.test.fail(f"Actual command is missing the {key_to_compare} field: {spec}") - self.test.assertLessEqual(actual[key_to_compare], spec) + value = actual[key_to_compare] if key_to_compare is not None else actual + self.test.assertGreaterEqual(value, spec) def _operation_matchAsDocument(self, spec, actual, key_to_compare): self._match_document(spec, json_util.loads(actual[key_to_compare]), False, test=True) From 04693b98ecd3fc5c1dba0f871e8f6d94971fee28 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Tue, 24 Nov 2026 14:55:42 -0600 Subject: [PATCH 11/11] PYTHON-6295 Capture the BSON fuzz corpus weekly instead of nightly (#3253) --- .evergreen/generated_configs/tasks.yml | 10 ++++++- .evergreen/generated_configs/variants.yml | 7 +++++ .evergreen/scripts/capture-fuzz-corpus.sh | 5 ++-- .evergreen/scripts/generate_config.py | 31 ++++++++++++++++------ .evergreen/scripts/setup_tests.py | 7 ++--- .evergreen/scripts/test_generate_config.py | 29 +++++++++++++------- CONTRIBUTING.md | 11 ++++---- fuzz/README.md | 22 ++++++++------- fuzz/capture_corpus.py | 2 +- 9 files changed, 85 insertions(+), 39 deletions(-) diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index 738609fc0e..00ac5416da 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -215,6 +215,14 @@ tasks: UV_PYTHON: "3.13" tags: [fuzz, fuzz-regression, pr] - name: fuzz + commands: + - func: run tests + vars: + TEST_NAME: fuzz + SUB_TEST_NAME: fuzz + UV_PYTHON: "3.13" + tags: [fuzz, fuzz-nightly] + - name: fuzz-capture commands: - func: run tests vars: @@ -234,7 +242,7 @@ tasks: - AWS_SECRET_ACCESS_KEY - AWS_SESSION_TOKEN type: test - tags: [fuzz, fuzz-nightly] + tags: [fuzz, fuzz-weekly] # Getdata tests - name: getdata diff --git a/.evergreen/generated_configs/variants.yml b/.evergreen/generated_configs/variants.yml index 5e1094ac9e..f624b89e6e 100644 --- a/.evergreen/generated_configs/variants.yml +++ b/.evergreen/generated_configs/variants.yml @@ -215,6 +215,13 @@ buildvariants: run_on: - rhel8.10-small batchtime: 1440 + - name: fuzz-capture-rhel8 + tasks: + - name: .fuzz-weekly + display_name: Fuzz Capture RHEL8 + run_on: + - rhel8.10-small + 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 1b3512e4b0..ad829e0c48 100755 --- a/.evergreen/scripts/capture-fuzz-corpus.sh +++ b/.evergreen/scripts/capture-fuzz-corpus.sh @@ -1,8 +1,9 @@ #!/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 -# nightly "fuzz" task, while the scratch corpus exists; manual -# `evergreen patch --variant fuzz-rhel8 --task fuzz` runs capture too. +# weekly "fuzz-capture" task, while the scratch corpus exists; manual +# `evergreen patch --variant fuzz-capture-rhel8 --task fuzz-capture` runs +# capture too. set -eu # Same environment as just.sh: venv on PATH for a modern Python. diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index afbe9ae55a..061f9bc0a6 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -389,12 +389,13 @@ def create_doctests_variants(): def create_fuzz_variants(): - # Two variants for the two fuzz flows: the regression reproducers run - # on every PR, the time-boxed fuzzing runs nightly. The nightly variant - # carries no "pr" tag, so PR patch builds never select it, while its - # default patchability keeps it manually runnable - # (`evergreen patch --variant fuzz-rhel8 --task fuzz`). The host needs - # CPython, which the rhel8 toolchain provides. + # 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. host = HOSTS["rhel8"] return [ create_variant( @@ -403,6 +404,12 @@ def create_fuzz_variants(): create_variant( [".fuzz-nightly"], get_variant_name("Fuzz", host), host=host, batchtime=BATCHTIME_DAY ), + create_variant( + [".fuzz-weekly"], + get_variant_name("Fuzz Capture", host), + host=host, + batchtime=BATCHTIME_WEEK, + ), ] @@ -722,10 +729,18 @@ def create_fuzz_tasks(): test_func = FunctionCall(func="run tests", vars=test_vars) tasks = [EvgTask(name="fuzz-regression", tags=tags, commands=[test_func])] - # Time-boxed fuzzing against the generated seed corpus. + # Time-boxed fuzzing against the generated seed corpus, for crash + # discovery; corpus capture moved to the weekly fuzz-capture task. tags = ["fuzz", "fuzz-nightly"] 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])) + + # 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 @@ -743,7 +758,7 @@ def create_fuzz_tasks(): "AWS_SESSION_TOKEN", ], ) - tasks.append(EvgTask(name="fuzz", tags=tags, commands=[test_func, capture_cmd])) + tasks.append(EvgTask(name="fuzz-capture", tags=tags, commands=[test_func, capture_cmd])) return tasks diff --git a/.evergreen/scripts/setup_tests.py b/.evergreen/scripts/setup_tests.py index fecb6c9efc..cb0fb59c1e 100644 --- a/.evergreen/scripts/setup_tests.py +++ b/.evergreen/scripts/setup_tests.py @@ -600,9 +600,10 @@ 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 builds 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 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. 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 8e431f1a3f..602e84e3e5 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -443,32 +443,43 @@ def test_non_standard_cov_tasks_have_no_cov_companions(): def test_fuzz_task_wiring(): """Test the fuzz task wiring. - Two fuzz variants: the pr-tagged regression variant runs the reproducers on - every PR; the nightly variant (which also captures the corpus) carries no - "pr" tag, so PR patch builds never select it, while its default patchability - keeps it manually runnable (`evergreen patch --variant fuzz-rhel8 --task fuzz`). + 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`). """ 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 [])] == ["fuzz"] + assert [task.name for task in tasks if "pr" not in (task.tags or [])] == [ + "fuzz", + "fuzz-capture", + ] variants = generate_config.create_fuzz_variants() - assert len(variants) == 2 - regression, nightly = variants + assert len(variants) == 3 + regression, nightly, capture_variant = variants assert variant_selects(regression, tasks[0]) assert "pr" in (regression.tags or []) assert variant_selects(nightly, tasks[1]) assert nightly.batchtime == generate_config_utils.BATCHTIME_DAY + assert variant_selects(capture_variant, tasks[2]) + assert capture_variant.batchtime == generate_config_utils.BATCHTIME_WEEK # 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" # 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[1].commands[-1] + capture = tasks[2].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 nightly variant never runs in a PR build. + # capture too, and the weekly variant never runs in a PR build. assert "is_patch" not in env_vars diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 43790a3299..d16f95e5db 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -452,13 +452,14 @@ wheels (CPython 3.12-3.14). - Regression test (runs on every PR): `just setup-tests fuzz regression` then `just run-tests`. -- Time-boxed fuzzing (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. -- Nightly fuzzing captures coverage-increasing inputs into `fuzz/corpus/` +- 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). To run that flow on demand, patch the task: - `evergreen patch --variant fuzz-rhel8 --task fuzz`. + `evergreen patch --variant fuzz-capture-rhel8 --task fuzz-capture`. ## Testing time-dependent operations diff --git a/fuzz/README.md b/fuzz/README.md index 464601ac06..979f4a7065 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -77,7 +77,9 @@ default mutation cap of 4096 bytes would keep the nightly 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: +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): ```bash just setup-tests fuzz fuzz @@ -95,15 +97,15 @@ 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). -### Captured corpus (nightly) +### Captured corpus (weekly) -The nightly run seeds from the spec seed corpus plus every unit in +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` 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 nights +finish, the `fuzz-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 build on prior discoveries instead of restarting from the spec seeds. Growth is bounded by per-unit and per-run caps, overridable on Evergreen: @@ -115,7 +117,7 @@ Growth is bounded by per-unit and per-run caps, overridable on Evergreen: Units over a cap are discarded, not deferred: they are never persisted, so the fuzzer may re-derive them on later nights. A run that finds nothing new opens no PR. The capture deduplicates against `main` only, so while a -`[Fuzz Corpus]` PR is open, later nights can re-capture its still-pending +`[Fuzz Corpus]` PR is open, later weeks can re-capture its still-pending units and the PRs overlap until one merges (digest-named files keep that conflict-free). Crashing inputs are excluded: they land in `fuzz-scratch/` as `crash-*` artifacts and follow the @@ -141,11 +143,11 @@ gives atheris a graceful exit so coverage.py can flush its report. ``` build_corpus.py Seed corpus builder (mirrors the Go driver's build-oss-fuzz-corpus) -capture_corpus.py Nightly capture of new coverage-increasing inputs (PYTHON-6178) +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 -corpus/ Captured coverage-increasing inputs; grown by automated nightly PRs +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/capture_corpus.py b/fuzz/capture_corpus.py index 94ad5945a4..7268b75e88 100755 --- a/fuzz/capture_corpus.py +++ b/fuzz/capture_corpus.py @@ -8,7 +8,7 @@ units into an output directory named by their SHA-256 digests, and writes a Markdown summary for the automated corpus PR body. -Pure stdlib: this runs on the Evergreen nightly host after the fuzz +Pure stdlib: this runs on the Evergreen weekly capture host after the fuzz targets finish, and its unit tests must run everywhere (no atheris, no bson).