litellm/.github/scripts/ci/select_changed_tests.py
yuneng-jiang dc0a852de9
ci: fit the pull request gate into five minutes (#52660)
* ci(unit): upload per-test durations as JUnit XML from each shard

Each unit shard now writes junit.xml and uploads it, so per-test timings can drive shard balancing and the choice of PR core tests.

* ci: fit the pull request gate into five minutes

Lint no longer compiles Rust. The basedpyright env skips installing the
project (same per-rule counts as main's published artifact, 93220) and runs
with four threads, and the python job installs only the dev tools. Import
safety and the OpenAPI gate move to a lint-runtime job in the unit workflow
that reuses the one shared bridge build.

The unit workflow drops coverage, schedules core shards with worksteal so
one big file no longer runs alone at the end, splits the router tests across
two 16-core shards, adds the frequent out-of-core catchers, and adds a
changed-tests job that runs the PR's changed unit tests plus the tests
mirroring its changed source files. The bridge build skips the gateway
wheel on core-mode pull requests, and merge smoke builds the bridge once
instead of once per job on a cache miss.

rust-test, rust-wheel, image-scan and CodeQL move to the integration
cadence, with a rust-tests label to run the Rust jobs on a pull request.
CodSpeed runs on main only.

* ci: build the Rust bridge on a 16-core runner (temporary cache-miss probe)

* ci: reuse the Rust bridge on cost-map-only pull requests

The bridge embeds the cost map, so a pull request that only edits the cost
map JSON used to rebuild Rust in both unit and smoke, about 7 minutes end to
end. The bridge cache key now splits the Rust inputs from the cost map, and a
cost-map-only pull request falls back to a bridge built from the same Rust
inputs with an older embedded map. cost-map-guard still loads the new JSON
through the Rust catalog, and main rebuilds the bridge on every cost map
change.

Unit's bridge job runs on a 16-core runner, which cut a measured cache miss
from 3.5 to 2.0 minutes for pull requests that do change Rust.

* ci: build smoke's Rust bridge on a 16-core runner
2026-11-18 14:41:04 -08:00

92 lines
4.1 KiB
Python

#!/usr/bin/env python3
"""Print the unit test files a pull request's changed files point at, one per line.
Reads the changed paths on stdin. A changed `tests/unit/**/test_*.py` file is selected,
and so is every `tests/unit/<dir>/test_<module>.py` or `test_<module>_*.py` mirroring a
changed `litellm/<dir>/<module>.py`. Files the unit-core shards already run are left out,
as are files whose full-matrix shard needs settings this lane does not have: serial
execution or another Python version.
"""
from __future__ import annotations
import argparse
import itertools
import sys
from collections.abc import Iterable, Iterator, Mapping
from pathlib import Path, PurePosixPath
from typing import Final
import yaml
UNIT_ROOT: Final = PurePosixPath("tests/unit")
SOURCE_ROOT: Final = PurePosixPath("litellm")
def _shard_paths(shard: Mapping[str, object]) -> tuple[PurePosixPath, ...]:
tokens: Final = str(shard.get("test-path", "")).split()
return tuple(PurePosixPath(token) for token in tokens if not token.startswith("-"))
def _shards(workflow: Mapping[str, object], job: str) -> tuple[Mapping[str, object], ...]:
jobs: Final = workflow.get("jobs")
spec: Final = jobs.get(job) if isinstance(jobs, dict) else None
strategy: Final = spec.get("strategy") if isinstance(spec, dict) else None
matrix: Final = strategy.get("matrix") if isinstance(strategy, dict) else None
include: Final = matrix.get("include") if isinstance(matrix, dict) else None
return tuple(shard for shard in include if isinstance(shard, dict)) if isinstance(include, list) else ()
def _incompatible(shard: Mapping[str, object], python: str) -> bool:
return str(shard.get("workers")) == "0" or str(shard.get("python-version")) != python
def exclusions(workflow: Mapping[str, object], python: str) -> tuple[PurePosixPath, ...]:
core: Final = _shards(workflow, "unit-core")
special: Final = (shard for shard in _shards(workflow, "unit") if _incompatible(shard, python))
return tuple(itertools.chain.from_iterable(_shard_paths(shard) for shard in itertools.chain(core, special)))
def _is_unit_test(path: PurePosixPath) -> bool:
return path.suffix == ".py" and path.name.startswith("test_") and path.is_relative_to(UNIT_ROOT)
def _mirror_patterns(path: PurePosixPath) -> tuple[str, ...]:
if path.suffix != ".py" or path.name == "__init__.py" or not path.is_relative_to(SOURCE_ROOT):
return ()
directory: Final = UNIT_ROOT / path.parent.relative_to(SOURCE_ROOT)
return (f"{directory}/test_{path.stem}.py", f"{directory}/test_{path.stem}_*.py")
def _mirrors(path: PurePosixPath, root: Path) -> Iterator[PurePosixPath]:
for pattern in _mirror_patterns(path):
yield from (PurePosixPath(match.relative_to(root).as_posix()) for match in root.glob(pattern))
def _excluded(path: PurePosixPath, excluded: tuple[PurePosixPath, ...]) -> bool:
return any(path == entry or path.is_relative_to(entry) for entry in excluded)
def select(changed: Iterable[str], excluded: tuple[PurePosixPath, ...], root: Path) -> tuple[str, ...]:
paths: Final = tuple(PurePosixPath(line.strip()) for line in changed if line.strip())
direct: Final = (path for path in paths if _is_unit_test(path))
mirrored: Final = itertools.chain.from_iterable(_mirrors(path, root) for path in paths)
candidates: Final = frozenset(itertools.chain(direct, mirrored))
return tuple(
sorted(path.as_posix() for path in candidates if (root / path).is_file() and not _excluded(path, excluded))
)
def main() -> None:
parser: Final = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--workflow", type=Path, default=Path(".github/workflows/test-unit.yml"))
parser.add_argument("--python", default="3.12")
parser.add_argument("--root", type=Path, default=Path("."))
args: Final = parser.parse_args()
workflow: Final = yaml.safe_load(args.workflow.read_text(encoding="utf-8"))
selected: Final = select(sys.stdin, exclusions(workflow, args.python), args.root)
sys.stdout.write("".join(f"{path}\n" for path in selected))
if __name__ == "__main__":
main()