Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -177,14 +177,17 @@ jobs:
if: steps.changes.outputs.outside_plan == 'false' && matrix.shard == 1
run: uv run devops ci test tests/invariants

# The combined data file of the shard, which the gate keeps (#1743). The path starts with a
# dot, so the action needs `include-hidden-files`.
- name: Upload Coverage Data
# The combined data file of the shard, which the gate keeps (#1743), and the JUnit XML report
# with the time of each test of the shard, for the split by measured time (#4673). The
# coverage path starts with a dot, so the action needs `include-hidden-files`.
- name: Upload Coverage Data and Test Report
if: steps.changes.outputs.outside_plan != 'false'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: coverage-shard-${{ matrix.shard }}
path: .data/.coverage
path: |
.data/.coverage
.data/junit.xml
include-hidden-files: true
if-no-files-found: error
retention-days: 7
Expand Down
2 changes: 1 addition & 1 deletion docs/SDLC.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ CI is the authoritative gate ([ADR 0004](adr/0004-ci-is-the-authoritative-gate.m
- Every CI job runs in the devcontainer and on a stock GitHub-hosted runner, with no package install and no host change on the runner. A test that needs a capability of the host skips where the host does not have it ([docs/TESTING.md](TESTING.md#hosts-sockets-and-the-shared-container)).

#### The Test Shards (`ci.yml`, `test-shard` and `test`)
The suite has about 18,000 tests, and on one runner it took 355 s to 528 s, depending on the speed of the runner that GitHub gave. AGENTS.md rule 5 sets the bound at 300 s. The test row therefore runs in four shards on four runners, the jobs `Tests & Coverage (shard <n> of 4)`. Each runs `uv run devops ci --check --no-cache --only test --shard <n> --shards 4`, which passes the paths of about one quarter of the test files to pytest, so a shard collects only its own files. A shard checks no coverage floor, since it measures a part of the tree. It uploads its coverage data as an artifact.
The suite has about 18,000 tests, and on one runner it took 355 s to 528 s, depending on the speed of the runner that GitHub gave. AGENTS.md rule 5 sets the bound at 300 s. The test row therefore runs in four shards on four runners, the jobs `Tests & Coverage (shard <n> of 4)`. Each runs `uv run devops ci --check --no-cache --only test --shard <n> --shards 4`, which passes the paths of about one quarter of the test files to pytest, so a shard collects only its own files. A shard checks no coverage floor, since it measures a part of the tree. Its log gives the reason of each skipped test (`-rfEs`). It uploads its coverage data and a JUnit XML report with the time of each of its tests (`.data/junit.xml`) as one artifact, for the split by measured time (#4250).

The required check `Tests & Coverage` is the job that waits for the shards. It fails when a shard did not succeed, because a skipped job would pass a required check. It downloads the data, runs `coverage combine` and `coverage report`, which applies `fail_under` of `pyproject.toml` to the lines and branches of the whole tree (`[tool.coverage.run]` sets `branch = true`), and then runs the step `Changed-Line Coverage`. Beside the step that writes it, the job keeps `.data/coverage.xml` as an artifact with a 7-day retention. The ruleset binds to this job, never to a shard ([ADR 0004](adr/0004-ci-is-the-authoritative-gate.md)). To add a shard, add a number to the matrix `shard` of `test-shard`: the name, `--shards` and the split follow the count.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-12
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Design

## Decisions
- Only a shard run writes the report and the skip summary. CI runs only shards, and #4250 reads the CI artifacts. A local unsharded run keeps its output as before.
- The report path is `.data/junit.xml`, relative to the checkout, beside the coverage `data_file` of `pyproject.toml`. Each shard runs on its own runner, so one fixed name does not collide. The download of the job `Tests & Coverage` puts each artifact in its own folder.
- The constants `CONST_CI_SHARD_JUNIT_PATH` and `CONST_CI_SHARD_SUMMARY_CHARS` hold the path and the summary characters. The test reads the path from the planned shard command and compares it with the upload step of `ci.yml`, so a change of one side fails the test.
- The report keeps the default `junit_duration_report = total`: the time of setup, call and teardown, which is the cost of the test for a shard split.
- The upload stays in the artifact `coverage-shard-<n>`, so the download pattern of the job `Tests & Coverage` does not change.

## Rejected alternatives
- `PYTEST_ADDOPTS`: `build_subprocess_env` refuses the key (#2747).
- `-rs` alone: it replaces the default `fE`, and the summary of a failed shard would not name the failed tests.
- `addopts` in `pyproject.toml`: each local run, each `devops ci test` and each mutation run would then write a report. Only the shards need it.
- A separate artifact for the report: it adds one upload and one name per shard for no gain, and the issue asks for the report in the coverage artifact.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Proposal: #4673

## Why
The test shards of CI print only their 10 slowest tests and write no JUnit XML report. Thus each CI saving outside those 10 rows is an estimate. The shard logs show skips with no reason, because the shard row does not ask pytest for `-rs`. The split by measured time (#4250) and a tighter per-test bound in CI need the time of each test. Closes #4673.

## What Changes
- The test row of `devops ci --shard <n> --shards <total>` adds `-rfEs` and `--junitxml=.data/junit.xml` to its pytest command. The log of a shard gives the reason of each skip. The report holds each test of the shard with its time.
- `-r` of pytest replaces its default `fE`, so the row asks again for the failed (`f`) and error (`E`) tests. With `-rs` alone, the summary of a failed shard would not name the failed tests.
- The job `test-shard` of `ci.yml` uploads `.data/junit.xml` in the artifact `coverage-shard-<n>`, beside `.data/.coverage`. The step name is now `Upload Coverage Data and Test Report`.
- An unsharded run, such as a local `uv run devops ci`, writes no report and keeps the default summary.
- The command of a `devops ci` option changes, so the change carries a delta of `ci-test-shards`.

## Capabilities
- `ci-test-shards`: ADDED requirement "A shard reports the time of each test and the reason of each skip".

## Impact
- `src/devops_cli/commands/ci.py`, `src/devops_cli/config/constants.py`, `.github/workflows/ci.yml`, `tests/commands/test_ci_shard.py`, `docs/SDLC.md`.
- Each shard artifact grows by one XML file. The job `Tests & Coverage` downloads each artifact to its own folder and combines only `.data/shards/*/.coverage`, so the extra file does not change the coverage step.
- No new dependency. No change to a required check name.

## Feasibility
- `PYTEST_ADDOPTS` cannot carry the options: `build_subprocess_env` refuses it (ARCHITECTURE.md, File-write child environment, #2747). The options go on the command line of the row, which `_resolve_pytest_cmd` builds.
- `-r` is a store option with the default `fE` (`_REPORTCHARS_DEFAULT` of `_pytest/terminal.py` in the installed pytest). A value of `s` replaces the default, so the row passes `fEs`.
- pytest makes the parent folder of the `--junitxml` path, and pytest-xdist sends the report of each worker to the controller, which writes one file.
- `devops ci --only test` runs one row and does not capture its output (`capture_output = len(selected_specs) != 1`), so the `-r` summary goes to the job log.
- `actions/upload-artifact` takes more than one path and keeps the paths under their least common folder `.data/`. Thus the artifact root holds `.coverage` as before, and `junit.xml`.

## Existing Tool Considered
The built-in `--junitxml` and `-r` options of pytest and the multi-path input of `actions/upload-artifact`. No new tool and no new code beyond the options.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
## ADDED Requirements

### Requirement: A shard reports the time of each test and the reason of each skip
The command of a shard SHALL hold `-rfEs` and `--junitxml=.data/junit.xml`, so that its log gives the reason of each skip and still names the failed and error tests, and the report holds each test of the shard with its time. The job `test-shard` of `ci.yml` SHALL upload the report in the artifact that holds `.data/.coverage`.

#### Scenario: A shard runs a pass, a skip and a failure
- **WHEN** the report options of the command of shard 2 of 4 run on a suite with one pass, one skip and one failure
- **THEN** the report holds the three tests, and the summary gives the reason of the skip and names the failed test

#### Scenario: The upload step is read
- **WHEN** the upload step of the job `test-shard` of `ci.yml` is read
- **THEN** its paths are the `data_file` of `[tool.coverage.run]` in `pyproject.toml` and the report path of the shard command
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Tasks

## 1. Behavior

- [x] 1.1 Write failing tests: the shard row writes each test to a JUnit XML report, gives the reason of each skip and keeps the failure summary, and the shard job uploads that report with its coverage data
- Verification: `$ uv run devops ci test tests/commands/test_ci_shard.py`
- [x] 1.2 Add `-rfEs` and `--junitxml=.data/junit.xml` to the shard row, and upload the report in the artifact of each shard
- Verification: `$ uv run devops ci test tests/commands/test_ci_shard.py`

## 2. Workflows

- [x] 2.1 Lint the changed workflow
- Verification: `$ uv run devops ci --only actionlint,zizmor`

## 3. Documents

- [x] 3.1 Say in docs/SDLC.md that each shard uploads its JUnit XML report and gives the reason of each skip
- Verification: `$ uv run devops ci docs`
11 changes: 11 additions & 0 deletions openspec/specs/ci-test-shards/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,14 @@ The shards SHALL partition the test modules of `tests/`: each module SHALL be in
#### Scenario: The split has no stored input
- **WHEN** the modules of a tree are dealt to two shards
- **THEN** the lists come from the line counts of the files alone, the heaviest file going first to the shard with the fewest lines so far

### Requirement: A shard reports the time of each test and the reason of each skip
The command of a shard SHALL hold `-rfEs` and `--junitxml=.data/junit.xml`, so that its log gives the reason of each skip and still names the failed and error tests, and the report holds each test of the shard with its time. The job `test-shard` of `ci.yml` SHALL upload the report in the artifact that holds `.data/.coverage`.

#### Scenario: A shard runs a pass, a skip and a failure
- **WHEN** the report options of the command of shard 2 of 4 run on a suite with one pass, one skip and one failure
- **THEN** the report holds the three tests, and the summary gives the reason of the skip and names the failed test

#### Scenario: The upload step is read
- **WHEN** the upload step of the job `test-shard` of `ci.yml` is read
- **THEN** its paths are the `data_file` of `[tool.coverage.run]` in `pyproject.toml` and the report path of the shard command
8 changes: 7 additions & 1 deletion src/devops_cli/commands/ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
CONST_AST_GREP_SCAN_ARGS,
CONST_BANDIT_INI_NAME,
CONST_CI_RUN_STOP_SIGNAL_NAMES,
CONST_CI_SHARD_JUNIT_PATH,
CONST_CI_SHARD_SUMMARY_CHARS,
CONST_CI_SLOWEST_TESTS_SHOWN,
CONST_CI_SUBCOMMAND_SHOWS_HELP_META_KEY,
CONST_CI_TEST_BUDGET_SECONDS,
Expand Down Expand Up @@ -633,7 +635,9 @@ def _resolve_pytest_cmd(*, shard: int = 1, shards: int = 1) -> list[str]:
that deselects after collection makes every xdist worker collect the whole suite (#2371). A
shard measures a part of the tree: it checks no floor and prints no report, and the job that
combines the data of every shard does both. A shard also warns on, and does not fail on, an
unused snapshot: the snapshots of the tests in the other shards are unused in it.
unused snapshot: the snapshots of the tests in the other shards are unused in it. A shard writes
the time of each test to a JUnit XML report, which CI uploads with the coverage data, and its
log gives the reason of each skip (#4673).
"""
from devops_cli.core.test_selection import shard_test_files

Expand All @@ -651,6 +655,8 @@ def _resolve_pytest_cmd(*, shard: int = 1, shards: int = 1) -> list[str]:
"--cov-report=",
"--cov-fail-under=0",
"--snapshot-warn-unused",
f"-r{CONST_CI_SHARD_SUMMARY_CHARS}",
f"--junitxml={CONST_CI_SHARD_JUNIT_PATH}",
*shard_test_files(shard, shards, _get_project_root()),
]

Expand Down
7 changes: 7 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,13 @@
# of this many entries.
CONST_CI_TEST_BUDGET_SECONDS: Final[float] = 300.0
CONST_CI_SLOWEST_TESTS_SHOWN: Final[int] = 10
# A test shard of CI writes the time of each of its tests to this JUnit XML report, beside the
# coverage data (`data_file` of pyproject.toml), and `ci.yml` uploads both as the artifact of the
# shard (#4673). The split by measured time reads it (#4250). The path is relative to the checkout.
CONST_CI_SHARD_JUNIT_PATH: Final[str] = ".data/junit.xml"
# The `-r` summary of a test shard: the reason of each skip (s) in the log (#4673). `-r` replaces
# the default `fE` of pytest, so the shard asks again for the failed (f) and error (E) tests.
CONST_CI_SHARD_SUMMARY_CHARS: Final[str] = "fEs"
# The job of `ci.yml` that joins the shards of the test row: `devops ci job-time` reads the time of
# this check from its last runs (#2699), so the budget above is checked on the runs of the runner
# and not on the one run of a pull request. The shard jobs are named `<this name> (shard n of N)`.
Expand Down
82 changes: 82 additions & 0 deletions tests/commands/test_ci_shard.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@
from __future__ import annotations

import re
import tomllib
from pathlib import Path

import pytest
import yaml
from typer.testing import CliRunner

from devops_cli.ci.cache import resolve_ci_cache_path
from devops_cli.ci.fail_to_pass import parse_junit_xml
from devops_cli.commands.ci import app, get_check_spec
from devops_cli.core.test_selection import directory_modules, shard_test_files
from devops_cli.dry_run import set_dry_run
Expand All @@ -24,6 +27,25 @@
runner = CliRunner()

_SPLIT_OPTIONS = ("--splits", "--group", "--splitting-algorithm")
_JUNIT_OPTION = "--junitxml="

# One test of each outcome whose reason the log of a shard must give.
_SHARD_SUITE = """
import pytest


def test_passes() -> None:
assert True


@pytest.mark.skip(reason="promtool is not installed")
def test_skips() -> None:
pass


def test_fails() -> None:
assert False
"""


def _said(output: str) -> str:
Expand All @@ -39,6 +61,13 @@ def _planned_test_row(*options: str) -> list[str]:
return words[words.index("1.") + 1 :]


def _report_path(row: list[str]) -> str | None:
"""The path of the JUnit XML report that the test row `row` writes, or None when it writes none."""
return next(
(word.removeprefix(_JUNIT_OPTION) for word in row if word.startswith(_JUNIT_OPTION)), None
)


def test_the_unsharded_test_row_has_no_split_option_and_prints_the_term_report() -> None:
"""With no shard, the row is the row of every run before sharding existed."""
cmd = get_check_spec("test").cmd
Expand Down Expand Up @@ -76,6 +105,59 @@ def test_a_shard_runs_its_own_test_files_and_checks_no_floor() -> None:
) == (own_files, [False, False, False], True, True, True, False, True)


def test_a_shard_reports_each_test_id_and_the_reason_of_each_skip_and_failure(
pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch
) -> None:
"""The split by measured time (#4250) needs the time of each test of a shard, and the log of a
shard must give the reason of each skip (#4673). The report options of the shard row, on a
suite with a pass, a skip and a failure, write the three tests to the JUnit XML report and
print the reason of the skip. The option `-r` of pytest replaces its default `fE`, so the row
asks again for the failures and errors, and the failure stays in the summary."""
# The inner run loads no installed plugin: autoloading each plugin costs seconds.
monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1")
pytester.makepyprojecttoml('[tool.pytest.ini_options]\naddopts = "-p no:randomly --tb=no"\n')
pytester.makepyfile(test_shard=_SHARD_SUITE)
row = _planned_test_row("--shard", "2", "--shards", "4")
report_path = _report_path(row)
assert report_path is not None, "the shard row writes no JUnit XML report"

result = pytester.runpytest(
*[word for word in row if word.startswith(("-r", _JUNIT_OPTION))], "test_shard.py"
)

report = parse_junit_xml((pytester.path / report_path).read_text(encoding="utf-8"))
output = _said(result.stdout.str())
assert (
sorted(f"{case.classname}::{case.name}" for case in report),
re.search(r"SKIPPED \[1\] test_shard\.py:\d+: promtool is not installed", output)
is not None,
"FAILED test_shard.py::test_fails" in output,
) == (
["test_shard::test_fails", "test_shard::test_passes", "test_shard::test_skips"],
True,
True,
)


def test_each_shard_job_uploads_the_report_of_its_row_with_its_coverage_data() -> None:
"""Each shard job of CI uploads the JUnit XML report that its test row writes, in the artifact
that holds its coverage data, so that the split by measured time can read the time of each
test of the suite from the artifacts of a run (#4250, #4673)."""
workflow = yaml.safe_load((REPO_ROOT / ".github/workflows/ci.yml").read_text(encoding="utf-8"))
upload = next(
step
for step in workflow["jobs"]["test-shard"]["steps"]
if step.get("uses", "").startswith("actions/upload-artifact@")
)
pyproject = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8"))
coverage_data = pyproject["tool"]["coverage"]["run"]["data_file"]

assert upload["with"]["path"].split() == [
coverage_data,
_report_path(_planned_test_row("--shard", "2", "--shards", "4")),
]


@pytest.mark.parametrize("shards", [2, 3, 4])
def test_the_shards_cover_every_test_module_once(shards: int) -> None:
"""Each test module is in exactly one shard, and no shard is empty."""
Expand Down