Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

perf(ci): install with uv and collect test shards in one pass (#1672)

Johannes Grumböck971af5ef44c2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ed64993d..7cdcbae8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,6 +6,13 @@ on:
pull_request:
branches: [main, master]
+# A new push to the same PR makes the in-flight run's result irrelevant — stop
+# it competing for runners with the one that supersedes it. Runs on main are
+# never cancelled: they gate the post-merge state.
+concurrency:
+ group: ci-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
env:
PARALLEL_SHARDS: 3
SERIAL_SHARDS: 1
@@ -24,10 +31,15 @@ jobs:
uses: actions/setup-python@v6
with:
python-version: "3.13"
- cache: "pip"
+
+ # Pinned to a full version: setup-uv stopped publishing floating major
+ # tags after v7, so there is no `@v10` to track.
+ - uses: astral-sh/[email protected]
+ with:
+ enable-cache: true
- name: Install dependencies
- run: pip install -e . && pip install -r requirements.txt boto3 pytest pytest-xdist duckdb docker cbor2 pyyaml cryptography aws-sam-translator websockets
+ run: uv pip install --system -e ".[test]" -r requirements.txt
- name: Plan test shards
id: plan
@@ -55,10 +67,15 @@ jobs:
uses: actions/setup-python@v6
with:
python-version: "3.13"
- cache: "pip"
+
+ # Pinned to a full version: setup-uv stopped publishing floating major
+ # tags after v7, so there is no `@v10` to track.
+ - uses: astral-sh/[email protected]
+ with:
+ enable-cache: true
- name: Install dependencies
- run: pip install -e . && pip install -r requirements.txt boto3 pytest pytest-xdist duckdb docker cbor2 pyyaml cryptography aws-sam-translator websockets
+ run: uv pip install --system -e ".[test]" -r requirements.txt
- name: Start MiniStack
run: |
diff --git a/.gitignore b/.gitignore
index 7e7d8101..b825819f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -51,3 +51,6 @@ data/
# Logs
*.log
+
+# Shard-planning scratch output (scripts/select_test_shard.py)
+.pytest_collect_plan.json
diff --git a/pyproject.toml b/pyproject.toml
index 4147bdf8..a0bfce51 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -53,6 +53,21 @@ full = [
"asyncssh>=2.14",
"aws-sam-translator>=1.90",
]
+# Exactly what CI installs to run the test suite — kept separate from `dev`
+# (which also carries linters, type stubs and the DB drivers the container-backed
+# RDS tests skip without) so the workflow has one name to install instead of an
+# inline package list that drifts from this file.
+test = [
+ "boto3>=1.34",
+ "pytest>=8.0",
+ "pytest-xdist>=3.6",
+ "duckdb>=0.10.0",
+ "docker>=7.0.0",
+ "cbor2>=5.4.0",
+ "cryptography>=41.0",
+ "aws-sam-translator>=1.90",
+ "websockets>=12.0",
+]
dev = [
"boto3>=1.34",
"pytest>=8.0",
diff --git a/scripts/_collect_plan_plugin.py b/scripts/_collect_plan_plugin.py
new file mode 100644
index 00000000..3fecd8fc
--- /dev/null
+++ b/scripts/_collect_plan_plugin.py
@@ -0,0 +1,32 @@
+"""pytest plugin: dump per-file test counts, split by run mode, to JSON.
+
+Loaded with ``-p _collect_plan_plugin`` by scripts/select_test_shard.py so a
+single ``--collect-only`` pass yields both the ``serial`` and ``parallel``
+counts. Collecting twice (once per ``-m`` filter) doubled the cost of the
+shard-planning job for data one pass already has.
+
+Writes ``{"tests/test_x.py": {"parallel": 12, "serial": 3}, ...}`` to the path
+in $MINISTACK_COLLECT_OUT.
+"""
+
+import json
+import os
+
+
+def pytest_collection_finish(session):
+ out = os.environ.get("MINISTACK_COLLECT_OUT")
+ if not out:
+ return
+
+ rootpath = session.config.rootpath
+ counts: dict[str, dict[str, int]] = {}
+ for item in session.items:
+ try:
+ path = item.path.relative_to(rootpath).as_posix()
+ except ValueError:
+ path = item.path.as_posix()
+ mode = "serial" if item.get_closest_marker("serial") else "parallel"
+ counts.setdefault(path, {"parallel": 0, "serial": 0})[mode] += 1
+
+ with open(out, "w") as fh:
+ json.dump(dict(sorted(counts.items())), fh)
diff --git a/scripts/plan_test_shards.py b/scripts/plan_test_shards.py
index 2940dbe0..c8eb7963 100644
--- a/scripts/plan_test_shards.py
+++ b/scripts/plan_test_shards.py
@@ -23,8 +23,11 @@ def main() -> None:
parallel_shards = int(os.environ.get("PARALLEL_SHARDS", 3))
serial_shards = int(os.environ.get("SERIAL_SHARDS", 1))
- parallel_files = collect_by_file("parallel")
- serial_files = collect_by_file("serial")
+ # One collection pass yields both modes; collecting twice doubled the cost
+ # of this job for data the single pass already has.
+ collected = collect_by_file()
+ parallel_files = {f: c["parallel"] for f, c in collected.items() if c["parallel"]}
+ serial_files = {f: c["serial"] for f, c in collected.items() if c["serial"]}
total_parallel = sum(parallel_files.values())
total_serial = sum(serial_files.values())
diff --git a/scripts/select_test_shard.py b/scripts/select_test_shard.py
index 917cd828..337de382 100644
--- a/scripts/select_test_shard.py
+++ b/scripts/select_test_shard.py
@@ -1,31 +1,48 @@
import argparse
+import json
+import os
import subprocess
import sys
-from collections import defaultdict
+from pathlib import Path
+REPO_ROOT = Path(__file__).resolve().parent.parent
-def collect_by_file(mode: str) -> dict[str, int]:
- marker = "serial" if mode == "serial" else "not serial"
+
+def collect_by_file(mode: str | None = None) -> dict[str, dict[str, int]] | dict[str, int]:
+ """Collect test counts per file, split by mode, in a single pytest pass.
+
+ Returns ``{file: {"parallel": n, "serial": n}}``. When ``mode`` is given,
+ returns the flat ``{file: n}`` for that mode only (files with 0 omitted),
+ which is the shape the sharding helpers consume.
+
+ One pass rather than one per ``-m`` filter: collection dominates the
+ shard-planning job, and both counts come out of the same collected set.
+ """
+ out_path = REPO_ROOT / ".pytest_collect_plan.json"
+ env = {**os.environ, "MINISTACK_COLLECT_OUT": str(out_path)}
+ env["PYTHONPATH"] = os.pathsep.join(
+ p for p in (str(Path(__file__).resolve().parent), env.get("PYTHONPATH", "")) if p
+ )
result = subprocess.run(
[sys.executable, "-m", "pytest", "--collect-only", "-q", "--no-header",
- "-m", marker, "tests/"],
- capture_output=True, text=True,
+ "-p", "_collect_plan_plugin", "tests/"],
+ capture_output=True, text=True, env=env, cwd=REPO_ROOT,
)
- # 0 = ok, 5 = no tests collected (valid for a mode with no matching tests)
- if result.returncode not in (0, 5):
+ # 0 = ok, 5 = no tests collected (valid for a suite with no matching tests)
+ if result.returncode not in (0, 5) or not out_path.exists():
print(result.stdout[-2000:] if result.stdout else "", file=sys.stderr)
print(result.stderr[-2000:] if result.stderr else "", file=sys.stderr)
raise SystemExit(
f"pytest --collect-only failed (exit {result.returncode}) "
- f"for mode '{mode}' — aborting to avoid silently skipping tests"
+ f"— aborting to avoid silently skipping tests"
)
- counts: dict[str, int] = defaultdict(int)
- for line in result.stdout.splitlines():
- line = line.strip()
- if "::" in line:
- counts[line.split("::")[0]] += 1
- return dict(counts)
+ counts: dict[str, dict[str, int]] = json.loads(out_path.read_text())
+ out_path.unlink(missing_ok=True)
+
+ if mode is None:
+ return counts
+ return {f: c[mode] for f, c in counts.items() if c.get(mode)}
def build_shards(counts: dict[str, int], n: int) -> list[list[str]]:
@@ -57,7 +74,6 @@ def main() -> None:
selected = shards[args.shard_index]
if args.format == "json":
- import json
print(json.dumps(selected))
else:
print(" ".join(selected))