From 9fd924b2b0ba2552771ddcaf0f4d1a7aff70b269 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:06:36 +0000 Subject: [PATCH 1/2] ci(tests): Let filtered pytest-selected runs opt into the per-file plan Co-Authored-By: Joshua Li <14209781+joshuarli@users.noreply.github.com> --- .github/workflows/scripts/pytest-selected.py | 32 ++++++--- .../workflows/scripts/test_pytest_selected.py | 67 ++++++++++++++++++- tests/sentry/testutils/pytest/test_sentry.py | 33 ++++++++- 3 files changed, 120 insertions(+), 12 deletions(-) diff --git a/.github/workflows/scripts/pytest-selected.py b/.github/workflows/scripts/pytest-selected.py index cdac282758cc..7f218b8a6fa9 100644 --- a/.github/workflows/scripts/pytest-selected.py +++ b/.github/workflows/scripts/pytest-selected.py @@ -17,6 +17,11 @@ durations file, each shard gets whole selected files, balanced by the per-file test counts in `selected-tests.counts.json`, and a file too big for one shard gets several shards, which split it by test. +- Full runs filtered with `-m`/`-k`: every shard collects everything and keeps + its hash share, unless PYTEST_SELECTED_FILTERED_PLAN=1. Then they get the + full-run plan too: every file is still assigned to a shard, and pytest + applies the filter to the files it collects. A shard whose files have no + selected tests passes. """ from __future__ import annotations @@ -164,16 +169,22 @@ def file_weights(files: list[str]) -> dict[str, float]: return estimate_file_seconds(files, DURATIONS_FILE) +def is_filtered(args: list[str]) -> bool: + """Whether `-m`/`-k` filter the tests after collection.""" + every_arg = [*args, *shlex.split(os.environ.get("PYTEST_ADDOPTS", ""))] + return any(arg.startswith(("-m", "-k")) and not arg.startswith("--") for arg in every_arg) + + def per_file_plan_applies(args: list[str], files: list[str]) -> bool: """Whether planning by file gives each shard the tests pytest would run. `-m`/`-k` filter after the plan, so most shards could end up with no - selected tests (e.g. `-m snuba_ci` in Snuba's CI). The sentry plugin - matches the planned paths relative to the rootdir, which - pytest_shard_plugin checks is the working directory. + selected tests (e.g. `-m snuba_ci` in Snuba's CI). Callers that accept + that set PYTEST_SELECTED_FILTERED_PLAN=1. The sentry plugin matches the + planned paths relative to the rootdir, which pytest_shard_plugin checks + is the working directory. """ - every_arg = [*args, *shlex.split(os.environ.get("PYTEST_ADDOPTS", ""))] - if any(arg.startswith(("-m", "-k")) and not arg.startswith("--") for arg in every_arg): + if is_filtered(args) and os.environ.get("PYTEST_SELECTED_FILTERED_PLAN") != "1": return False return not any(os.path.isabs(f) or f.startswith(os.pardir + os.sep) for f in files) @@ -195,8 +206,9 @@ def run_full_shard(args: list[str], total: int, group: int) -> int: # As before per-file sharding: every shard collects everything and the # sentry plugin keeps its hash share of the items. print( - "pytest-selected: -m/-k or paths outside the working directory, so " - "every shard collects everything and keeps its hash share", + "pytest-selected: -m/-k without PYTEST_SELECTED_FILTERED_PLAN=1, or " + "paths outside the working directory, so every shard collects " + "everything and keeps its hash share", file=sys.stderr, ) return int(pytest.main(args)) @@ -205,9 +217,13 @@ def run_full_shard(args: list[str], total: int, group: int) -> int: return int(pytest.main(args)) artifacts = Path(".artifacts") artifacts.mkdir(exist_ok=True) - return run_planned_shard( + exit_code = run_planned_shard( args, plan, group, len(files), artifacts / f"full-tests.shard-{group}.txt" ) + # A filter can select none of this shard's files. + if exit_code == pytest.ExitCode.NO_TESTS_COLLECTED and is_filtered(args): + return 0 + return exit_code def run_planned_shard( diff --git a/.github/workflows/scripts/test_pytest_selected.py b/.github/workflows/scripts/test_pytest_selected.py index f64500e66fd1..f428e4d249b9 100644 --- a/.github/workflows/scripts/test_pytest_selected.py +++ b/.github/workflows/scripts/test_pytest_selected.py @@ -261,6 +261,8 @@ def run_full_main( total: int, group: int, addopts: str = "", + extra_env: dict[str, str] | None = None, + exit_code: pytest.ExitCode = pytest.ExitCode.OK, ) -> tuple[int, list[tuple[object, ...]]]: write_files(tmp_path, files) durations_file = tmp_path / "durations.json" @@ -271,13 +273,15 @@ def run_full_main( def fake_main(args: list[str]) -> pytest.ExitCode: env = ("SELECTED_TESTS_FILE", "TOTAL_TEST_GROUPS", "TEST_GROUP", "PYTEST_SHARD_PARTS") calls.append((args, *(os.environ.get(k) for k in env))) - return pytest.ExitCode.OK + return exit_code env = { "SELECTED_TESTS_FILE": "", "TOTAL_TEST_GROUPS": str(total), "TEST_GROUP": str(group), "PYTEST_ADDOPTS": addopts, + "PYTEST_SELECTED_FILTERED_PLAN": "", + **(extra_env or {}), } with ( contextlib.chdir(tmp_path), @@ -336,6 +340,51 @@ def test_filtered_run_falls_back_to_hash_sharding(self, tmp_path: Path) -> None: ) assert calls == [(["tests", "-q"], "", "16", "12", None)] + def test_opted_in_filtered_run_runs_only_this_shards_files(self, tmp_path: Path) -> None: + durations = {"seconds_per_test": 1.0, "files": {}} + with pieces_per_shard(1): + exit_code, calls = run_full_main( + tmp_path, + ["tests/test_a.py", "tests/test_b.py"], + durations, + 2, + 1, + "-k 'not __In' -m snuba_ci", + {"PYTEST_SELECTED_FILTERED_PLAN": "1"}, + ) + shard_file = ".artifacts/full-tests.shard-1.txt" + assert exit_code == 0 + assert calls == [ + (["tests", "-q"], shard_file, "1", "0", ".artifacts/full-tests.shard-1.json") + ] + assert (tmp_path / shard_file).read_text() == "tests/test_b.py\n" + + def test_opted_in_filtered_shard_with_no_selected_tests_passes(self, tmp_path: Path) -> None: + durations = {"seconds_per_test": 1.0, "files": {}} + exit_code, _ = run_full_main( + tmp_path, + ["tests/test_a.py", "tests/test_b.py"], + durations, + 2, + 0, + "-m snuba_ci", + {"PYTEST_SELECTED_FILTERED_PLAN": "1"}, + pytest.ExitCode.NO_TESTS_COLLECTED, + ) + assert exit_code == 0 + + def test_unfiltered_shard_with_no_tests_still_fails(self, tmp_path: Path) -> None: + durations = {"seconds_per_test": 1.0, "files": {}} + exit_code, _ = run_full_main( + tmp_path, + ["tests/test_a.py", "tests/test_b.py"], + durations, + 2, + 0, + exit_code=pytest.ExitCode.NO_TESTS_COLLECTED, + ) + assert exit_code == pytest.ExitCode.NO_TESTS_COLLECTED + @pytest.mark.parametrize( ("args", "addopts", "files", "applies"), @@ -355,3 +404,19 @@ def test_per_file_plan_applies( ) -> None: with mock.patch.dict(os.environ, {"PYTEST_ADDOPTS": addopts}): assert _mod.per_file_plan_applies(args, files) is applies + + +@pytest.mark.parametrize( + ("args", "addopts", "files", "applies"), + [ + (["tests", "-m", "snuba_ci"], "", ["tests/a.py"], True), + (["tests"], "-k 'not __In' -m 'snuba_ci or snuba'", ["tests/a.py"], True), + (["/abs/tests", "-m", "snuba_ci"], "", ["/abs/tests/a.py"], False), + ], +) +def test_per_file_plan_applies_to_opted_in_filtered_runs( + args: list[str], addopts: str, files: list[str], applies: bool +) -> None: + env = {"PYTEST_ADDOPTS": addopts, "PYTEST_SELECTED_FILTERED_PLAN": "1"} + with mock.patch.dict(os.environ, env): + assert _mod.per_file_plan_applies(args, files) is applies diff --git a/tests/sentry/testutils/pytest/test_sentry.py b/tests/sentry/testutils/pytest/test_sentry.py index eed53b7489e7..d3fed6301da1 100644 --- a/tests/sentry/testutils/pytest/test_sentry.py +++ b/tests/sentry/testutils/pytest/test_sentry.py @@ -41,6 +41,15 @@ def test_marked(n): def test_unmarked(): pass + + @pytest.mark.snuba_ci + class Base: + def test_inherited(self): + pass + + class TestChild(Base): + def test_own(self): + pass """ ) @@ -72,11 +81,25 @@ def _collect(project: Path, command: list[str], env: dict[str, str]) -> Counter[ return Counter(line for line in proc.stdout.splitlines() if "::" in line) -def test_filtered_run_spreads_selected_tests_over_every_shard(tmp_path: Path) -> None: +@pytest.mark.parametrize( + "plan_env", + [ + # Every shard collects everything and keeps its hash share. + {}, + # Every shard collects only its planned files, and test_marked0.py is + # heavy enough to be split across shards. + {"PYTEST_SELECTED_FILTERED_PLAN": "1"}, + ], +) +def test_filtered_run_spreads_selected_tests_over_every_shard( + tmp_path: Path, plan_env: dict[str, str] +) -> None: files = { "conftest.py": "from sentry.testutils.pytest.sentry import pytest_collection_modifyitems, pytest_ignore_collect # noqa: F401\n", "pytest.ini": "[pytest]\nmarkers =\n snuba_ci\n", - "durations.json": json.dumps({"seconds_per_test": 0.1, "files": {}}), + "durations.json": json.dumps( + {"seconds_per_test": 0.1, "files": {"tests/test_marked0.py": 10.0}} + ), **{f"tests/test_marked{i}.py": MARKED for i in range(2)}, **{f"tests/test_plain{i}.py": "def test_p():\n pass\n" for i in range(12)}, } @@ -94,9 +117,13 @@ def test_filtered_run_spreads_selected_tests_over_every_shard(tmp_path: Path) -> "TOTAL_TEST_GROUPS": str(SHARDS), "TEST_GROUP": str(group), "TEST_GROUP_STRATEGY": "roundrobin", + **plan_env, }, ) - assert len(unsharded) == 20 + planned = (tmp_path / ".artifacts" / f"full-tests.shard-{group}.txt").is_file() + assert planned == bool(plan_env) + # 10 parametrized and 2 inherited marked tests in each of 2 files. + assert len(unsharded) == 24 assert sharded == unsharded From 42f7adb80145b1814def0fc3f47bc12ab1d1fc9c Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:36:58 +0000 Subject: [PATCH 2/2] ref(ci): Let run_planned_shard own the empty-shard exit code Co-Authored-By: Joshua Li <14209781+joshuarli@users.noreply.github.com> --- .github/workflows/scripts/pytest-selected.py | 28 +++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/.github/workflows/scripts/pytest-selected.py b/.github/workflows/scripts/pytest-selected.py index 7f218b8a6fa9..219124dc3e2e 100644 --- a/.github/workflows/scripts/pytest-selected.py +++ b/.github/workflows/scripts/pytest-selected.py @@ -217,19 +217,21 @@ def run_full_shard(args: list[str], total: int, group: int) -> int: return int(pytest.main(args)) artifacts = Path(".artifacts") artifacts.mkdir(exist_ok=True) - exit_code = run_planned_shard( - args, plan, group, len(files), artifacts / f"full-tests.shard-{group}.txt" - ) + shard_file = artifacts / f"full-tests.shard-{group}.txt" # A filter can select none of this shard's files. - if exit_code == pytest.ExitCode.NO_TESTS_COLLECTED and is_filtered(args): - return 0 - return exit_code + return run_planned_shard(args, plan, group, len(files), shard_file, is_filtered(args)) def run_planned_shard( - args: list[str], plan: list[Shard], group: int, file_count: int, shard_file: Path + args: list[str], + plan: list[Shard], + group: int, + file_count: int, + shard_file: Path, + empty_ok: bool, ) -> int: - """Run this shard of a plan_full_shards plan.""" + """Run this shard of a plan_full_shards plan. With empty_ok, a shard that + collects no tests passes.""" shard = plan[group] print( f"pytest-selected: shard {group + 1}/{len(plan)} runs {len(shard.files)} of " @@ -253,7 +255,10 @@ def run_planned_shard( filter(None, [os.environ.get("PYTEST_PLUGINS"), "pytest_shard_plugin"]) ) start_assert_rewrite_prewarm(shard_file) - return int(pytest.main(args)) + exit_code = pytest.main(args) + if empty_ok and exit_code == pytest.ExitCode.NO_TESTS_COLLECTED: + return 0 + return int(exit_code) def main(args: list[str]) -> int: @@ -273,11 +278,8 @@ def main(args: list[str]) -> int: plan = plan_full_shards(file_weights(selected), total, SELECTED_PIECES_PER_SHARD) if plan is not None: shard_file = Path(selected_file).with_suffix(f".shard-{group}.txt") - exit_code = run_planned_shard(args, plan, group, len(selected), shard_file) # Durations are estimates, so a shard can end up with no tests. - if exit_code == pytest.ExitCode.NO_TESTS_COLLECTED: - return 0 - return exit_code + return run_planned_shard(args, plan, group, len(selected), shard_file, True) counts_file = Path(selected_file).with_suffix(".counts.json") counts = json.loads(counts_file.read_text()) if counts_file.is_file() else {}