Files
TorchNPU/.github/workflows/_precise_test.yml
T

258 lines
11 KiB
YAML

name: Precise Test
on:
workflow_call:
inputs:
event_type:
required: false
type: string
default: ''
description: Event type from repository_dispatch (pull_request)
payload:
required: false
type: string
default: ''
description: Full client_payload as a JSON string
jobs:
prepare:
name: Resolve the PR to compare
runs-on: ubuntu-latest
outputs:
github_pr: ${{ steps.parse.outputs.github_pr }}
defaults:
run:
shell: bash
steps:
- name: Parse the dispatch payload
id: parse
env:
EVENT_TYPE: ${{ inputs.event_type }}
PAYLOAD_JSON: ${{ inputs.payload }}
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
if [ "${EVENT_TYPE}" = "pull_request" ]; then
PR_NUMBER=$(echo "$PAYLOAD_JSON" | jq -r '.payload.pull_request.number // empty')
UPSTREAM_REPO=$(echo "$PAYLOAD_JSON" | jq -r '.payload.repository.full_name // empty')
if [ -z "${PR_NUMBER}" ] || [ -z "${UPSTREAM_REPO}" ]; then
echo "ERROR: cannot read the PR number / upstream repo from the payload" >&2
exit 1
fi
ACTION=$(echo "$PAYLOAD_JSON" | jq -r '.payload.action // empty')
HAS_MERGED=$(echo "$PAYLOAD_JSON" | jq -r '.payload.pull_request.labels // [] | map(.name) | index("Merged") // ""')
if [ "${ACTION}" = "closed" ] && [ -z "${HAS_MERGED}" ]; then
LABELS_CODE=$(curl -sS -o /tmp/pr-labels.json -w '%{http_code}' --max-time 30 \
-H "Authorization: Bearer ${GH_TOKEN}" \
"https://api.github.com/repos/${UPSTREAM_REPO}/issues/${PR_NUMBER}/labels" || echo 000)
if [ "${LABELS_CODE}" != "200" ]; then
echo "::error::cannot fetch the labels of ${UPSTREAM_REPO}#${PR_NUMBER} (http_code=${LABELS_CODE}); the merged state cannot be verified" >&2
exit 1
fi
HAS_MERGED=$(jq -r '[.[].name] | index("Merged") // ""' /tmp/pr-labels.json 2>/dev/null || true)
fi
if [ "${ACTION}" != "closed" ] || [ -z "${HAS_MERGED}" ]; then
echo "::notice::PR ${UPSTREAM_REPO}#${PR_NUMBER} is not a landed PR (action='${ACTION}', Merged label='${HAS_MERGED:-none}'), the precise selection is skipped"
{
echo "## Precise test selection"
echo ""
echo "- PR: \`${UPSTREAM_REPO}#${PR_NUMBER}\`"
echo "- Skipped: not a landed PR (action='${ACTION}', Merged label='${HAS_MERGED:-none}'), no precise selection needed"
} >> "$GITHUB_STEP_SUMMARY"
exit 0
fi
echo "github_pr=${UPSTREAM_REPO}#${PR_NUMBER}" >> "$GITHUB_OUTPUT"
echo "=== pull request ==="
echo "github_pr: ${UPSTREAM_REPO}#${PR_NUMBER}"
exit 0
fi
echo "::notice::event_type='${EVENT_TYPE}' is not pull_request, the precise selection is skipped"
precision-test:
needs: [prepare]
if: ${{ needs.prepare.outputs.github_pr }}
name: Precise test case selection
runs-on: linux-aarch64-cpu-24
timeout-minutes: 60
defaults:
run:
shell: bash
container:
image: swr.cn-north-4.myhuaweicloud.com/frameworkptadapter/pytorch:torch-npu-test-aarch64-cann-a3-py3.10-torch-master-cann9.2.0-20260910200430-202609230923-00b993fc
options: --network host
env:
github_pr: ${{ needs.prepare.outputs.github_pr }}
PIP_INDEX_URL: https://mirrors.huaweicloud.com/repository/pypi/simple
steps:
- name: Download the coverage data from OBS
if: ${{ env.github_pr != '' }}
run: |
set -euo pipefail
obsutil config -i=${{ secrets.ACCESSKEY }} -k=${{ secrets.SECRETACCESSKEY }} -e=obs.ap-southeast-1.myhuaweicloud.com
PREFIX="obs://pytorch-ci-cache/coverage/pytorch"
ARCHIVE="${PREFIX}/latest/release.tar.gz"
echo "release: ${ARCHIVE}"
DOWNLOADED=""
for attempt in 1 2 3; do
echo "=== Download attempt ${attempt} ==="
rm -rf coverage && mkdir -p coverage
if obsutil cp "${ARCHIVE}" /tmp/release.tar.gz -f -vlength && tar -xzf /tmp/release.tar.gz -C coverage; then
DOWNLOADED=1
break
fi
echo "download failed (attempt ${attempt})"
sleep 10
done
if [ -z "${DOWNLOADED}" ]; then
echo "ERROR: cannot download the coverage release from ${ARCHIVE}" >&2
exit 1
fi
echo "=== OBS layout ==="
find coverage -maxdepth 3 -type d | sort | head -20
python3 - <<'PYEOF'
import json
import sys
from pathlib import Path
root = Path("coverage")
cov_dir = root / "pytorch@latest"
if not (cov_dir / "coverage.xml").is_file():
sys.exit("ERROR: coverage.xml not found under the OBS download")
source_dir = root / "covstub"
if not (source_dir / "torch" / "__init__.py").is_file():
sys.exit("ERROR: no source snapshot (covstub/torch) found under the OBS download")
cases = len(list((cov_dir / "test").glob("**/covdata")))
manifest_file = cov_dir / "manifest.json"
if not manifest_file.is_file():
sys.exit(f"ERROR: no manifest.json in {cov_dir}, the coverage data was not published by the coverage pipeline")
manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
print("manifest:")
for key in ("workflow", "run_id", "event", "pytorch_short", "generated_at", "test_groups", "total_cases"):
print(f" {key}: {manifest.get(key)}")
print(f"coverage dir: {cov_dir}")
print(f"source dir: {source_dir} (package: torch/)")
print(f"test cases: {cases}")
print(f"coverage.xml: {(cov_dir / 'coverage.xml').stat().st_size} bytes")
if not cases:
sys.exit(f"ERROR: no per-test coverage data under {cov_dir}/test")
if manifest.get("test_groups") != cases:
sys.exit(f"ERROR: coverage data is incomplete: manifest reports {manifest.get('test_groups')} test group(s), found {cases} under {cov_dir}/test")
map_file = cov_dir / "test_case_map.json"
if map_file.is_file():
print("test_case_map: published")
else:
print("::warning::no test_case_map.json in the coverage release; the selector builds the map on the spot")
Path("/tmp/precise.env").write_text(f"TASK_DIR={cov_dir}\nSOURCE_DIR={source_dir}\nMAP_FILE={map_file if map_file.is_file() else ''}\n")
PYEOF
cat /tmp/precise.env >> "$GITHUB_ENV"
cat /tmp/precise.env
- name: generate-select-tests-case
id: select
if: ${{ env.github_pr != '' }}
continue-on-error: true
uses: lb-actions/precision-test@v1.0.4
with:
repo: pytorch
github-pr: ${{ env.github_pr }}
source-dir: ${{ env.SOURCE_DIR }}
coverage-dir: ${{ env.TASK_DIR }}
map-file: ${{ env.MAP_FILE }}
dedup: true
env:
GITHUB_TOKEN: ${{ github.token }}
PYTHON_EXEC_TIMEOUT_SECONDS: "900"
- name: Show the selection result
if: ${{ env.github_pr != '' }}
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
SUMMARY="$GITHUB_STEP_SUMMARY"
{
echo "## Precise test selection"
echo ""
echo "- PR: \`${github_pr}\`"
} >> "$SUMMARY"
SELECT_OUTCOME="${{ steps.select.outcome }}"
if [ "${SELECT_OUTCOME}" != "success" ]; then
echo "::error::the selector step failed (${SELECT_OUTCOME}) for ${github_pr}; check the generate-select-tests-case log (PR diff fetch / adapter errors)"
echo "- Selector failed (\`${SELECT_OUTCOME}\`): see the \`generate-select-tests-case\` step log" >> "$SUMMARY"
exit 0
fi
if [ ! -s recommended_pytest_paths.txt ]; then
echo "::warning::the selector recommended 0 test file(s) for ${github_pr} (no mapped coverage for the changed lines)"
echo "- Recommended test files: 0" >> "$SUMMARY"
exit 0
fi
REPO="${github_pr%%#*}"
NUM="${github_pr##*#}"
CHANGED_TESTS=/tmp/pr-changed-tests.txt
: > "${CHANGED_TESTS}"
API_OK=0
for page in 1 2 3 4; do
CODE="$(curl -sS -o /tmp/pr-files.json -w '%{http_code}' --max-time 30 \
-H "Authorization: Bearer ${GH_TOKEN}" \
"https://api.github.com/repos/${REPO}/pulls/${NUM}/files?per_page=100&page=${page}" || echo 000)"
[ "${CODE}" = "200" ] || break
API_OK=1
python3 - <<'PYEOF' >> "${CHANGED_TESTS}" 2>/dev/null || true
import json
from pathlib import PurePosixPath
for item in json.load(open("/tmp/pr-files.json", encoding="utf-8")):
name = item.get("filename", "")
if item.get("status") == "removed" or not name.startswith("test/"):
continue
if PurePosixPath(name).name.startswith("test_") and name.endswith(".py"):
print(name)
PYEOF
[ "$(jq 'length' /tmp/pr-files.json 2>/dev/null || echo 0)" -ge 100 ] || break
done
sort -u -o "${CHANGED_TESTS}" "${CHANGED_TESTS}"
if [ "${API_OK}" = "1" ]; then
echo "PR changed-files API: http_code=${CODE}, test file(s) changed by the PR: $(wc -l < "${CHANGED_TESTS}")"
else
echo "::notice::the PR changed-files API returned ${CODE}; the reasons are not annotated"
fi
COUNT="$(wc -l < recommended_pytest_paths.txt)"
echo "selection ok: ${COUNT} test file(s) recommended"
{
echo "- Recommended test files: ${COUNT}"
echo ""
echo "| test file | reason |"
echo "| --- | --- |"
while IFS= read -r test_path; do
if [ "${API_OK}" != "1" ]; then
echo "| \`${test_path}\` | 原因未标注(未能获取 PR 改动清单) |"
elif grep -Fxq "${test_path}" "${CHANGED_TESTS}"; then
echo "| \`${test_path}\` | PR 变更的测试文件(选测器直接加入,不查覆盖率映射) |"
else
echo "| \`${test_path}\` | 覆盖率映射命中(覆盖了改动行/函数) |"
fi
done < recommended_pytest_paths.txt
} >> "$SUMMARY"