Skip to content

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

ci: try to improve test performance (#917)

Johannes Grumböck9a4167771a20
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1b8aaab3..b6ed32f7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,9 +6,39 @@ on:
pull_request:
branches: [main, master]
+env:
+ PARALLEL_SHARDS: 3
+ SERIAL_SHARDS: 1
+
jobs:
+ setup:
+ name: plan shards
+ runs-on: ubuntu-latest
+ outputs:
+ matrix: ${{ steps.plan.outputs.matrix }}
+ files: ${{ steps.plan.outputs.files }}
+ steps:
+ - uses: actions/checkout@v6
+
+ - name: Set up Python
+ uses: actions/setup-python@v6
+ with:
+ python-version: "3.12"
+ cache: "pip"
+
+ - name: Install dependencies
+ run: pip install -e . && pip install -r requirements.txt boto3 pytest pytest-xdist duckdb docker cbor2 pyyaml cryptography
+
+ - name: Plan test shards
+ id: plan
+ run: python scripts/plan_test_shards.py
+
test:
+ needs: setup
runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix: ${{ fromJson(needs.setup.outputs.matrix) }}
services:
redis:
@@ -16,16 +46,13 @@ jobs:
ports:
- 6379:6379
options: >-
- --health-cmd "redis-cli ping"
- --health-interval 5s
- --health-timeout 3s
- --health-retries 5
+ --health-cmd "redis-cli ping" --health-interval 5s --health-timeout 3s --health-retries 5
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- name: Set up Python
- uses: actions/setup-python@v5
+ uses: actions/setup-python@v6
with:
python-version: "3.12"
cache: "pip"
@@ -36,18 +63,48 @@ jobs:
- name: Start MiniStack
run: |
REDIS_HOST=localhost python -m hypercorn ministack.app:app --bind 0.0.0.0:4566 --keep-alive 75 > ministack.log 2>&1 &
- sleep 3
+ for i in $(seq 1 15); do
+ curl -sf http://localhost:4566/_ministack/health && break
+ echo "Waiting for MiniStack... ($i/15)"
+ sleep 2
+ done
curl -sf http://localhost:4566/_ministack/health
- - name: Run tests (parallel safe set)
- run: pytest tests/ -v -n 3 --dist=loadfile -m "not serial"
+ - name: Resolve shard files
+ id: shard
+ env:
+ FILES_MAP: ${{ needs.setup.outputs.files }}
+ run: |
+ FILES=$(python3 -c "
+ import json, os
+ m = json.loads(os.environ['FILES_MAP'])
+ print(m.get('${{ matrix.mode }}_${{ matrix.shard_index }}', ''))
+ ")
+ echo "files=$FILES" >> $GITHUB_OUTPUT
- - name: Run tests (serial global-state set)
- run: pytest tests/ -v --tb=short -m "serial"
+ - name: Run tests (${{ matrix.mode }} shard ${{ matrix.shard_index }})
+ run: |
+ if [ -z "${{ steps.shard.outputs.files }}" ]; then
+ echo "No tests for this shard"
+ exit 0
+ fi
+ if [ "${{ matrix.mode }}" = "serial" ]; then
+ pytest ${{ steps.shard.outputs.files }} -v --tb=short -m "serial" --durations=10
+ else
+ pytest ${{ steps.shard.outputs.files }} -v -n 3 --dist=loadfile -m "not serial" --durations=25
+ fi
- name: Upload MiniStack log
if: always()
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v7
with:
- name: ministack.log
+ name: ministack-${{ matrix.mode }}-shard-${{ matrix.shard_index }}.log
path: ministack.log
+
+ test-result:
+ name: test
+ needs: test
+ if: always()
+ runs-on: ubuntu-latest
+ steps:
+ - run: '[ "${{ needs.test.result }}" = "success" ]'
diff --git a/scripts/plan_test_shards.py b/scripts/plan_test_shards.py
new file mode 100644
index 00000000..2940dbe0
--- /dev/null
+++ b/scripts/plan_test_shards.py
@@ -0,0 +1,106 @@
+#!/usr/bin/env python3
+"""
+Compute the full test sharding plan and emit a GitHub Actions matrix.
+
+Shard counts are read from env vars (set at workflow level):
+ PARALLEL_SHARDS (default: 3)
+ SERIAL_SHARDS (default: 1)
+
+Writes the matrix JSON to $GITHUB_OUTPUT when running in CI,
+or prints it to stdout when run locally.
+"""
+
+import json
+import os
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parent))
+from select_test_shard import build_shards, collect_by_file
+
+
+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")
+
+ total_parallel = sum(parallel_files.values())
+ total_serial = sum(serial_files.values())
+ # files can appear in both modes; count unique files across both
+ all_files = set(parallel_files) | set(serial_files)
+
+ parallel_sharded = build_shards(parallel_files, parallel_shards)
+ serial_sharded = build_shards(serial_files, serial_shards)
+
+ # ── human-readable plan ───────────────────────────────────────────────────
+
+ w = 60
+ print("=" * w)
+ print(
+ f" Test plan: {total_parallel + total_serial} tests"
+ f" ({total_parallel} parallel + {total_serial} serial)"
+ f" across {len(all_files)} file(s)"
+ )
+ print("=" * w)
+
+ for label, sharded, file_counts in (
+ (f"Parallel — {parallel_shards} shard(s)", parallel_sharded, parallel_files),
+ (f"Serial — {serial_shards} shard(s)", serial_sharded, serial_files),
+ ):
+ print(f"\n{label}")
+ for i, shard_files in enumerate(sharded):
+ count = sum(file_counts[f] for f in shard_files)
+ print(f" shard {i}: {count:>3} tests {len(shard_files):>2} file(s)")
+ for f in sorted(shard_files):
+ print(f" {file_counts[f]:>3} {f}")
+
+ print()
+
+ # ── build matrix ─────────────────────────────────────────────────────────
+
+ includes = []
+
+ for i, shard_files in enumerate(parallel_sharded):
+ includes.append({
+ "mode": "parallel",
+ "shard_index": i,
+ "shard_count": parallel_shards,
+ "files": " ".join(sorted(shard_files)),
+ "test_count": sum(parallel_files[f] for f in shard_files),
+ })
+
+ for i, shard_files in enumerate(serial_sharded):
+ includes.append({
+ "mode": "serial",
+ "shard_index": i,
+ "shard_count": serial_shards,
+ "files": " ".join(sorted(shard_files)),
+ "test_count": sum(serial_files[f] for f in shard_files),
+ })
+
+ # files map: "parallel_0" -> "tests/a.py tests/b.py", used by test jobs
+ files_map = {f"{e['mode']}_{e['shard_index']}": e.pop("files") for e in includes}
+ for e in includes:
+ e.pop("test_count", None) # not needed in matrix, already printed above
+
+ matrix = {"include": includes}
+
+ # ── emit ──────────────────────────────────────────────────────────────────
+
+ github_output = os.environ.get("GITHUB_OUTPUT")
+ if github_output:
+ with open(github_output, "a") as fh:
+ fh.write(f"matrix={json.dumps(matrix)}\n")
+ fh.write(f"files={json.dumps(files_map)}\n")
+ print("matrix + files written to $GITHUB_OUTPUT")
+ else:
+ print("Matrix JSON (GITHUB_OUTPUT not set, dry run):")
+ print(json.dumps(matrix, indent=2))
+ print("\nFiles map:")
+ print(json.dumps(files_map, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/select_test_shard.py b/scripts/select_test_shard.py
new file mode 100644
index 00000000..917cd828
--- /dev/null
+++ b/scripts/select_test_shard.py
@@ -0,0 +1,67 @@
+import argparse
+import subprocess
+import sys
+from collections import defaultdict
+
+
+def collect_by_file(mode: str) -> dict[str, int]:
+ marker = "serial" if mode == "serial" else "not serial"
+ result = subprocess.run(
+ [sys.executable, "-m", "pytest", "--collect-only", "-q", "--no-header",
+ "-m", marker, "tests/"],
+ capture_output=True, text=True,
+ )
+ # 0 = ok, 5 = no tests collected (valid for a mode with no matching tests)
+ if result.returncode not in (0, 5):
+ 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"
+ )
+
+ 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)
+
+
+def build_shards(counts: dict[str, int], n: int) -> list[list[str]]:
+ shards, totals = [[] for _ in range(n)], [0] * n
+ for f in sorted(counts, key=counts.__getitem__, reverse=True):
+ i = min(range(n), key=totals.__getitem__)
+ shards[i].append(f)
+ totals[i] += counts[f]
+ return shards
+
+
+def main() -> None:
+ p = argparse.ArgumentParser()
+ p.add_argument("--shard-index", type=int, required=True)
+ p.add_argument("--shard-count", type=int, required=True)
+ p.add_argument("--mode", choices=["parallel", "serial"], required=True)
+ p.add_argument("--exclude", action="append", default=[])
+ p.add_argument("--format", choices=["shell", "json"], default="shell")
+ args = p.parse_args()
+
+ if args.shard_count <= 0:
+ raise SystemExit("--shard-count must be greater than 0")
+ if not 0 <= args.shard_index < args.shard_count:
+ raise SystemExit("--shard-index must be in range [0, --shard-count)")
+
+ counts = collect_by_file(args.mode)
+ counts = {f: c for f, c in counts.items() if f not in args.exclude}
+ shards = build_shards(counts, args.shard_count)
+ selected = shards[args.shard_index]
+
+ if args.format == "json":
+ import json
+ print(json.dumps(selected))
+ else:
+ print(" ".join(selected))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/conftest.py b/tests/conftest.py
index a4d408c6..1d91d440 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -64,6 +64,7 @@ _SERIAL_TESTS = {
"tests/test_ses.py::test_ses_messages_endpoint_account_filter",
"tests/test_stepfunctions.py::test_sfn_mock_config_return",
"tests/test_stepfunctions.py::test_sfn_mock_config_throw",
+ "tests/test_stepfunctions.py::test_sfn_mock_config_jsonata_assign_applied",
"tests/test_stepfunctions.py::test_sfn_mock_config_throw_routes_to_catch",
"tests/test_stepfunctions.py::test_sfn_mock_config_jsonata_assign_applied",
"tests/test_stepfunctions.py::test_sfn_wait_scale_zero_does_not_timeout_lambda_tasks",
@@ -99,6 +100,8 @@ _SERIAL_TESTS = {
"tests/test_appsync.py::test_appsync_lambda_authorizer_rejection_returns_unauthorized",
"tests/test_appsync.py::test_appsync_lambda_missing_authorizer_returns_unauthorized",
"tests/test_appsync.py::test_appsync_lambda_failing_authorizer_returns_unauthorized",
+ # AppSync Events service mutations; shared state racing under xdist.
+ "tests/test_appsync_events.py::test_publish_with_appsync_sigv4_scope_on_events_vhost",
# Credential report reflects all users in the account; run serially to avoid
# parallel-test interference on the account-global CSV snapshot.
"tests/test_iam.py::test_iam_credential_report_mfa_and_password",