From 50bccf8632b0e5cc4c5dfd856f0895206184a9d0 Mon Sep 17 00:00:00 2001 From: VincyZhang Date: Wed, 11 Nov 2026 15:29:59 +0000 Subject: [PATCH 1/6] [CI/Build] Add maintainer-authorized XPU Stage 2 hardware CI Integrate fixed-pair XPU hardware validation into the shared E2E workflow with authorized execution, verified artifact handoff, isolated networking, and shared test-report checks. Build on the merged Stage 1 implementation and include the latest concurrent-copy and peer-exit IPC tests in the required hardware inventory. Signed-off-by: VincyZhang --- .github/actions/run-ctest/action.yml | 4 +- .github/actions/run-ctest/run.sh | 11 +- .github/workflows/ci.yml | 3 + .github/workflows/ci_xpu.yml | 29 +- .github/workflows/e2e-ci.yml | 129 ++ .github/workflows/integration-test-xpu.yml | 216 ++++ .pre-commit-config.yaml | 2 +- scripts/ci/check_test_reports.py | 66 ++ scripts/ci/tests/test_run_ctest.py | 46 +- scripts/ci/tests/test_xpu_ci.py | 1235 +++++++++++++++++++- scripts/e2e/python/verify_xpu_ci.py | 699 +++++++++++ scripts/e2e/python/verify_xpu_wheel.py | 87 -- scripts/xpu/README.md | 168 +++ 13 files changed, 2522 insertions(+), 173 deletions(-) create mode 100644 .github/workflows/integration-test-xpu.yml create mode 100644 scripts/ci/check_test_reports.py create mode 100644 scripts/e2e/python/verify_xpu_ci.py delete mode 100644 scripts/e2e/python/verify_xpu_wheel.py create mode 100644 scripts/xpu/README.md diff --git a/.github/actions/run-ctest/action.yml b/.github/actions/run-ctest/action.yml index 03be26af779..2c01865b34e 100644 --- a/.github/actions/run-ctest/action.yml +++ b/.github/actions/run-ctest/action.yml @@ -1,11 +1,11 @@ name: Run Mooncake CTest suite -description: Run the source-build CTest suite with shared runtime settings +description: Run and validate the source-build CTest suite with shared runtime settings inputs: reserve-rpc-port: description: Reserve the Mooncake client RPC port from ephemeral allocation default: 'true' junit-report: - description: Optional repository-relative JUnit output path + description: Repository-relative JUnit output path (defaults to build/test-results/ctest.xml) default: '' label-exclude: description: Optional CTest label regex to exclude diff --git a/.github/actions/run-ctest/run.sh b/.github/actions/run-ctest/run.sh index 5efd41a4cdf..33aad45d735 100644 --- a/.github/actions/run-ctest/run.sh +++ b/.github/actions/run-ctest/run.sh @@ -9,13 +9,14 @@ args=(--parallel "$(nproc)" --output-on-failure) if [ -n "${CTEST_LABEL_EXCLUDE:-}" ]; then args+=(--label-exclude "$CTEST_LABEL_EXCLUDE") fi -if [ -n "$JUNIT_REPORT" ]; then - report="$GITHUB_WORKSPACE/$JUNIT_REPORT" - mkdir -p "$(dirname "$report")" - args+=(--output-junit "$report") -fi +report="$GITHUB_WORKSPACE/${JUNIT_REPORT:-build/test-results/ctest.xml}" +mkdir -p "$(dirname "$report")" +rm -f "$report" +args+=(--output-junit "$report") cd build export LD_LIBRARY_PATH=${LD_LIBRARY_PATH:-}:/usr/local/lib MC_METADATA_SERVER=http://127.0.0.1:8080/metadata \ DEFAULT_KV_LEASE_TTL=500 \ ctest "${args[@]}" +python3 "$GITHUB_ACTION_PATH/../../../scripts/ci/check_test_reports.py" \ + --allow-skipped "$report" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b59ae484586..1600191d842 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -847,6 +847,9 @@ jobs: --output-on-failure \ --output-junit "$GITHUB_WORKSPACE/build-tent/test-results/ctest.xml" \ "${ctest_args[@]}" + cd "$GITHUB_WORKSPACE" + python3 scripts/ci/check_test_reports.py --allow-skipped \ + build-tent/test-results/ctest.xml shell: bash - name: Preserve TENT CTest diagnostics diff --git a/.github/workflows/ci_xpu.yml b/.github/workflows/ci_xpu.yml index 8aa7c8c65b6..179a7a5758b 100644 --- a/.github/workflows/ci_xpu.yml +++ b/.github/workflows/ci_xpu.yml @@ -132,18 +132,10 @@ jobs: --gtest_output=xml:xpu-ci-output/reports/ep.xml "$BUILD_DIR/mooncake-store/tests/crc32c_test" \ --gtest_output=xml:xpu-ci-output/reports/crc32c.xml - python - <<'PY' - import xml.etree.ElementTree as ET - for name in ("config", "ep", "crc32c"): - cases = ET.parse(f"xpu-ci-output/reports/{name}.xml").findall(".//testcase") - if not cases: - raise RuntimeError(f"{name}: no tests executed") - for case in cases: - if (case.get("status"), case.get("result")) != ("run", "completed") or any( - case.find(tag) is not None for tag in ("failure", "error", "skipped") - ): - raise RuntimeError(f"{name}: test did not pass: {case.attrib}") - PY + python scripts/ci/check_test_reports.py --require-gtest-status \ + xpu-ci-output/reports/config.xml \ + xpu-ci-output/reports/ep.xml \ + xpu-ci-output/reports/crc32c.xml - name: Apply wheel version override if: inputs.version_override != '' @@ -174,7 +166,17 @@ jobs: "$smoke_venv/bin/python" -m pip install xpu-ci-output/*.whl # Do not expose build libraries or the source package to the check. cd "$RUNNER_TEMP" - "$smoke_venv/bin/python" "$GITHUB_WORKSPACE/scripts/e2e/python/verify_xpu_wheel.py" + "$smoke_venv/bin/python" "$GITHUB_WORKSPACE/scripts/e2e/python/verify_xpu_ci.py" + + - name: Package Python dependencies for hardware + run: | + set -euo pipefail + out=xpu-ci-output/python-deps + mkdir -p "$out" + for wheel in xpu-ci-output/*.whl; do + python -m pip download --only-binary=:all: --dest "$out" "$wheel" + rm "$out/$(basename "$wheel")" + done - name: Package native tests run: | @@ -184,6 +186,7 @@ jobs: export LD_LIBRARY_PATH="$library_dirs:${LD_LIBRARY_PATH:-}" out=xpu-ci-output/native-tests mkdir -p "$out/lib" + cp -R xpu-ci-output/python-deps "$out/" cp xpu-ci-output/provenance.txt "$out/" for binary in \ "$BUILD_DIR"/mooncake-transfer-engine/tent/tests/tent_xpu_{platform,transport,engine,ipc_process}_test \ diff --git a/.github/workflows/e2e-ci.yml b/.github/workflows/e2e-ci.yml index b436ff695dd..2a02ee029f0 100644 --- a/.github/workflows/e2e-ci.yml +++ b/.github/workflows/e2e-ci.yml @@ -28,6 +28,92 @@ concurrency: cancel-in-progress: true jobs: + xpu-authorize: + if: > + github.event_name == 'workflow_dispatch' || + github.event.label.name == 'run-e2e-ci' + runs-on: ubuntu-24.04 + permissions: + contents: read + pull-requests: read + checks: write + outputs: + sha: ${{ steps.select.outputs.sha }} + pr: ${{ steps.select.outputs.pr }} + check_id: ${{ steps.select.outputs.check_id }} + steps: + - name: Authorize exact XPU revision + id: select + uses: actions/github-script@v7 + env: + PR_NUMBER: ${{ inputs.pr_number }} + CHECKOUT_SHA: ${{ inputs.pr_sha }} + with: + script: | + const repo = context.repo; + if (context.eventName === 'workflow_dispatch' && + context.ref !== 'refs/heads/main') { + throw new Error('Dispatch the trusted main workflow, not a PR branch'); + } + const {data: actor} = await github.rest.repos.getCollaboratorPermissionLevel({ + ...repo, username: context.actor + }); + if (!['admin', 'maintain', 'write'].includes(actor.permission)) { + throw new Error('XPU hardware execution requires maintainer authorization'); + } + const rawPr = context.payload.pull_request?.number || process.env.PR_NUMBER; + if (rawPr && !/^[1-9][0-9]*$/.test(String(rawPr))) { + throw new Error('Invalid PR number'); + } + const pr = rawPr ? Number(rawPr) : null; + let sha = process.env.CHECKOUT_SHA; + if (pr) { + const {data: pull} = await github.rest.pulls.get({...repo, pull_number: pr}); + if (pull.state !== 'open' || pull.base.ref !== 'main') { + throw new Error('Expected an open PR targeting main'); + } + const authorized = context.payload.pull_request?.head.sha || sha || pull.head.sha; + if (authorized !== pull.head.sha) { + throw new Error('PR head changed; authorize the new SHA again'); + } + sha = authorized; + } else if (!sha) { + sha = context.sha; + } + if (!/^[0-9a-f]{40}$/.test(sha)) { + throw new Error('A full 40-character commit SHA is required'); + } + const {data: commit} = await github.rest.repos.getCommit({...repo, ref: sha}); + if (commit.sha !== sha) throw new Error('Commit identity mismatch'); + const {data: check} = await github.rest.checks.create({ + ...repo, name: 'XPU Core', head_sha: sha, status: 'in_progress', + details_url: `${context.serverUrl}/${repo.owner}/${repo.repo}/actions/runs/${context.runId}` + }); + core.setOutput('sha', sha); + core.setOutput('pr', pr || ''); + core.setOutput('check_id', String(check.id)); + await core.summary.addRaw(`Authorized XPU core revision: ${sha}\n`).write(); + + build-wheel-xpu: + needs: xpu-authorize + permissions: + contents: read + uses: ./.github/workflows/ci_xpu.yml + with: + checkout_ref: ${{ needs.xpu-authorize.outputs.sha }} + + xpu-integration-test: + needs: [xpu-authorize, build-wheel-xpu] + permissions: + contents: read + actions: read + uses: ./.github/workflows/integration-test-xpu.yml + with: + checkout_sha: ${{ needs.xpu-authorize.outputs.sha }} + source_sha: ${{ needs.build-wheel-xpu.outputs.source_sha }} + artifact_id: ${{ needs.build-wheel-xpu.outputs.artifact_id }} + artifact_digest: ${{ needs.build-wheel-xpu.outputs.artifact_digest }} + ascend-test: if: > github.event_name == 'workflow_dispatch' || @@ -93,8 +179,51 @@ jobs: - integration-test - rocm-integration-test - integration-test-tent + - xpu-authorize + - build-wheel-xpu + - xpu-integration-test runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + checks: write steps: + - name: Check XPU results on the authorized head + uses: actions/github-script@v7 + env: + NEEDS_JSON: ${{ toJSON(needs) }} + with: + script: | + const needs = JSON.parse(process.env.NEEDS_JSON); + const authorization = needs['xpu-authorize']; + if (authorization?.result !== 'success') { + core.setFailed('XPU authorization did not succeed'); + return; + } + const selected = authorization.outputs; + const required = ['xpu-authorize', 'build-wheel-xpu', 'xpu-integration-test']; + const failed = required + .filter(name => needs[name]?.result !== 'success') + .map(name => `${name}: ${needs[name]?.result || 'missing'}`); + if (needs['build-wheel-xpu']?.outputs?.source_sha !== selected.sha) { + failed.push('XPU build SHA differs from authorized SHA'); + } + if (selected.pr) { + const {data: pr} = await github.rest.pulls.get({ + ...context.repo, pull_number: Number(selected.pr) + }); + if (pr.head.sha !== selected.sha) failed.push('PR head changed; retrigger required'); + } + const summary = failed.length ? failed.join('\n') : + `C++ non-RDMA, Store Python and native two-rank EP passed on ${selected.sha}`; + await github.rest.checks.update({ + ...context.repo, check_run_id: Number(selected.check_id), + status: 'completed', conclusion: failed.length ? 'failure' : 'success', + output: {title: 'XPU Core', summary} + }); + await core.summary.addRaw(summary).write(); + if (failed.length) core.setFailed(summary); + - name: Check E2E results run: | echo "PR: #${{ inputs.pr_number || github.event.pull_request.number }}" diff --git a/.github/workflows/integration-test-xpu.yml b/.github/workflows/integration-test-xpu.yml new file mode 100644 index 00000000000..724b39a3eb7 --- /dev/null +++ b/.github/workflows/integration-test-xpu.yml @@ -0,0 +1,216 @@ +name: Integration test (XPU core) + +on: + workflow_call: + inputs: + checkout_sha: + type: string + required: true + source_sha: + type: string + required: true + artifact_id: + type: string + required: true + artifact_digest: + type: string + required: true + +permissions: + contents: read + actions: read + +jobs: + core: + runs-on: xpu + timeout-minutes: 90 + env: + XPU_IMAGE: intel/pytorch:xpu-2.13.0-ubuntu24.04-20260907@sha256:7366f264bd7aaa7f0df7d1bfba43be7c84c126df21ba448ae5445a34c2def4f9 + steps: + - name: Check out trusted harness + uses: actions/checkout@v4 + with: + ref: ${{ github.workflow_sha }} + path: xpu-control + persist-credentials: false + + - name: Allocate run directory + id: run + shell: bash + run: | + set -euo pipefail + directory=$(mktemp -d "$RUNNER_TEMP/xpu-core.XXXXXX") + echo "directory=$directory" >> "$GITHUB_OUTPUT" + cat > "$directory/cleanup.sh" <<'SH' + fail() { echo "::error::$*" >&2; exit 1; } + + cleanup_container() { + local status=0 + docker stop --time 10 "$container_id" || status=1 + docker inspect "$container_id" > "$run_directory/output/container-final.json" || status=1 + if [ "$(docker inspect --format '{{.State.Running}}' "$container_id")" != false ]; then + echo "Container processes were not released" >&2 + status=1 + fi + docker rm "$container_id" || status=1 + docker info >/dev/null || status=1 + if docker inspect "$container_id" >/dev/null 2>&1; then + echo "Current run container was not removed" >&2 + status=1 + fi + return "$status" + } + SH + + - name: Download exact build artifact + shell: bash + env: + GH_TOKEN: ${{ github.token }} + ARTIFACT_ID: ${{ inputs.artifact_id }} + ARTIFACT_DIGEST: ${{ inputs.artifact_digest }} + SOURCE_SHA: ${{ inputs.source_sha }} + CHECKOUT_SHA: ${{ inputs.checkout_sha }} + RUN_DIRECTORY: ${{ steps.run.outputs.directory }} + run: | + set -euo pipefail + [[ "$ARTIFACT_ID" =~ ^[0-9]+$ ]] || { echo "::error::Invalid artifact ID"; exit 1; } + [[ "$CHECKOUT_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "::error::Invalid source SHA"; exit 1; } + [ "$SOURCE_SHA" = "$CHECKOUT_SHA" ] || { echo "::error::Build SHA differs from authorized SHA"; exit 1; } + gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID" > "$RUN_DIRECTORY/artifact.json" + gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID/zip" > "$RUN_DIRECTORY/artifact.zip" + python3 xpu-control/scripts/e2e/python/verify_xpu_ci.py unpack \ + "$RUN_DIRECTORY" "$CHECKOUT_SHA" "$ARTIFACT_ID" "$ARTIFACT_DIGEST" + + - name: Check out authorized test source + uses: actions/checkout@v4 + with: + ref: ${{ inputs.checkout_sha }} + path: xpu-tested-source + persist-credentials: false + + - name: Execute isolated two-B60 core + shell: bash + env: + RUN_DIRECTORY: ${{ steps.run.outputs.directory }} + CHECKOUT_SHA: ${{ inputs.checkout_sha }} + run: | + set -euo pipefail + [ "$(git -C xpu-tested-source rev-parse HEAD)" = "$CHECKOUT_SHA" ] || { + echo "::error::Checked out source differs from authorized SHA"; exit 1; + } + run_directory=$(realpath "$RUN_DIRECTORY") + source_directory=$(realpath "$GITHUB_WORKSPACE/xpu-tested-source") + control_directory=$(realpath "$GITHUB_WORKSPACE/xpu-control/scripts") + source "$run_directory/cleanup.sh" + mkdir -p "$run_directory/output" + exec > >(tee "$run_directory/output/runner.log") 2>&1 + + [ "$(id -u)" -ne 0 ] || { echo "XPU runner must not run as root" >&2; exit 1; } + : "${ZE_AFFINITY_MASK:?Set a host-owned two-GPU ZE_AFFINITY_MASK}" + : "${XPU_IMAGE:?Missing pinned runtime image}" + : "${CHECKOUT_SHA:?Missing authorized SHA}" + [[ "$ZE_AFFINITY_MASK" =~ ^(0|[1-9][0-9]*),(0|[1-9][0-9]*)$ ]] || { + echo "ZE_AFFINITY_MASK must select two whole devices, not subdevices" >&2; exit 1; + } + [ "${BASH_REMATCH[1]}" != "${BASH_REMATCH[2]}" ] || fail "Affinity must select distinct GPUs" + [[ "$XPU_IMAGE" =~ @sha256:[0-9a-f]{64}$ ]] || fail "Runtime image must be digest-pinned" + for command in docker python3 timeout; do + command -v "$command" >/dev/null || fail "Missing runner command: $command" + done + + # Preserve host GPU ordinals for fixed masks; the mask is not security isolation. + shopt -s nullglob + devices=(/dev/dri/renderD*) + [ "${#devices[@]}" -ge 2 ] || fail "At least two GPU render nodes are required" + device_args=() + for device in "${devices[@]}"; do + [[ "$device" =~ ^/dev/dri/renderD[0-9]+$ ]] && [ -c "$device" ] \ + || fail "Not a GPU render character device: $device" + device_args+=(--device "$device" --group-add "$(stat -c %g "$device")") + done + python3 "$control_directory/e2e/python/verify_xpu_ci.py" seccomp "$run_directory/output/seccomp.json" + + container_id= + cleanup() { + local status=$? cleanup_status=0 + trap - EXIT INT TERM + if [ -n "$container_id" ]; then + cleanup_container || cleanup_status=1 + fi + printf '{"cleanup_status":%d,"suite_status":%d}\n' "$cleanup_status" "$status" \ + > "$run_directory/output/cleanup.json" + if [ "$cleanup_status" -ne 0 ]; then exit 1; fi + exit "$status" + } + trap cleanup EXIT + trap 'exit 130' INT + trap 'exit 143' TERM + + docker pull "$XPU_IMAGE" + docker image inspect "$XPU_IMAGE" > "$run_directory/output/image.json" + container_id=$(docker create \ + --label "mooncake.xpu.run=$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" \ + --user "$(id -u):$(id -g)" --cap-drop ALL \ + --security-opt no-new-privileges \ + --security-opt "seccomp=$run_directory/output/seccomp.json" \ + --network none --ipc private --shm-size 2g \ + --pids-limit 1024 --ulimit core=0 \ + "${device_args[@]}" \ + --mount "type=bind,src=$run_directory/bundle,dst=/bundle,readonly" \ + --mount "type=bind,src=$source_directory,dst=/source,readonly" \ + --mount "type=bind,src=$control_directory,dst=/control,readonly" \ + --mount "type=bind,src=$run_directory/output,dst=/output" \ + --env "ZE_AFFINITY_MASK=$ZE_AFFINITY_MASK" \ + --env ONEAPI_DEVICE_SELECTOR=level_zero:gpu \ + --env ZE_FLAT_DEVICE_HIERARCHY=FLAT \ + --env MC_USE_TENT=1 --env MOONCAKE_STORE_BACKEND=cpp \ + --env PROTOCOL=tcp --env MC_METADATA_SERVER=P2PHANDSHAKE \ + --env LOCAL_HOSTNAME=127.0.0.1 --env MASTER_SERVER=127.0.0.1:50051 \ + --env MOONCAKE_LOCAL_HOSTNAME=127.0.0.1 \ + --env CCL_KVS_IFACE=lo --env GLOO_SOCKET_IFNAME=lo \ + --env PYTHONOPTIMIZE=0 --env PYTHONDONTWRITEBYTECODE=1 \ + --env TEST_TMPDIR=/output \ + --env "XPU_SOURCE_SHA=$CHECKOUT_SHA" --env "XPU_IMAGE=$XPU_IMAGE" \ + --env HOME=/tmp/home --workdir /tmp \ + --entrypoint /bin/bash "$XPU_IMAGE" -c ' + set -eo pipefail + mkdir -p "$HOME" + python3 /control/e2e/python/verify_xpu_ci.py run /bundle /source /output + ') + timeout --signal=TERM --kill-after=30s 70m docker start --attach "$container_id" + + - name: Recheck current-run container cleanup + if: always() && steps.run.outputs.directory != '' + shell: bash + env: + RUN_DIRECTORY: ${{ steps.run.outputs.directory }} + run: | + set -euo pipefail + run_directory=$(realpath "$RUN_DIRECTORY") + source "$run_directory/cleanup.sh" + mkdir -p "$run_directory/output" + remaining=$(docker ps -aq --no-trunc \ + --filter "label=mooncake.xpu.run=$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT") + docker info >/dev/null + if [ -n "$remaining" ]; then + while read -r container_id; do + [[ "$container_id" =~ ^[0-9a-f]{64}$ ]] || fail "Invalid current-run container ID" + cleanup_container + done <<< "$remaining" + fi + echo '{"cleanup_recheck":"passed"}' > "$run_directory/output/cleanup-recheck.json" + + - name: Preserve hardware diagnostics + if: always() && steps.run.outputs.directory != '' + uses: actions/upload-artifact@v4 + with: + name: xpu-core-${{ inputs.checkout_sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + ${{ steps.run.outputs.directory }}/output/*.json + ${{ steps.run.outputs.directory }}/output/*.xml + ${{ steps.run.outputs.directory }}/output/*.log + ${{ steps.run.outputs.directory }}/output/*.list + ${{ steps.run.outputs.directory }}/output/*.ldd + ${{ steps.run.outputs.directory }}/artifact.json + if-no-files-found: error + retention-days: 14 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8a1007334c7..eb70013c82a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -75,7 +75,7 @@ repos: hooks: - id: codespell exclude: '^(extern/|FAST25-release/)' - args: ['--ignore-words-list=te,mooncake,KVCache,cann,hsa,crate,coo'] + args: ['--ignore-words-list=te,mooncake,KVCache,cann,hsa,crate,coo,renderd'] - repo: https://github.com/cheshirekow/cmake-format-precommit rev: v0.6.13 diff --git a/scripts/ci/check_test_reports.py b/scripts/ci/check_test_reports.py new file mode 100644 index 00000000000..a1216ab5253 --- /dev/null +++ b/scripts/ci/check_test_reports.py @@ -0,0 +1,66 @@ +"""Check JUnit/GoogleTest reports, optionally checking exact case identities.""" + +import argparse +from pathlib import Path +import xml.etree.ElementTree as ET + + +def validate_report( + path: str | Path, + expected: set[str] | None = None, + require_gtest_status: bool = False, + allow_skipped: bool = False, +) -> None: + report = Path(path) + cases = ET.parse(report).findall(".//testcase") + if not cases: + raise RuntimeError(f"{report}: no tests executed") + if expected is not None: + identities = [f"{case.get('classname')}.{case.get('name')}" for case in cases] + if len(identities) != len(expected) or set(identities) != expected: + raise RuntimeError(f"{report}: test identity mismatch: {identities}") + for case in cases: + status = case.get("status") + result = case.get("result") + skipped = case.find("skipped") is not None or (status, result) in { + ("run", "skipped"), + ("notrun", "suppressed"), + } + if any(case.find(tag) is not None for tag in ("failure", "error")): + raise RuntimeError(f"{report}: test did not pass: {case.attrib}") + if skipped: + if not allow_skipped or require_gtest_status: + raise RuntimeError(f"{report}: test was skipped: {case.attrib}") + continue + if require_gtest_status: + completed = (status, result) == ("run", "completed") + else: + completed = status in (None, "run") and result in (None, "completed") + if not completed: + raise RuntimeError(f"{report}: test did not pass: {case.attrib}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--require-gtest-status", + action="store_true", + help="Require GoogleTest's run/completed testcase attributes", + ) + parser.add_argument( + "--allow-skipped", + action="store_true", + help="Permit skipped testcases in CTest reports", + ) + parser.add_argument("reports", nargs="+", type=Path) + args = parser.parse_args() + for report in args.reports: + validate_report( + report, + require_gtest_status=args.require_gtest_status, + allow_skipped=args.allow_skipped, + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/ci/tests/test_run_ctest.py b/scripts/ci/tests/test_run_ctest.py index 21b16b82e1e..aa2fddcd994 100644 --- a/scripts/ci/tests/test_run_ctest.py +++ b/scripts/ci/tests/test_run_ctest.py @@ -15,10 +15,17 @@ def setUp(self): self.root = Path(self.directory.name).resolve() (self.root / "build").mkdir() - def run_suite(self, **overrides): + def run_suite(self, report="passed", **overrides): + body = { + "passed": '', + "empty": "", + "failure": '', + "skipped": '', + }[report] env = { **os.environ, "SCRIPT": str(SCRIPT), + "GITHUB_ACTION_PATH": str(SCRIPT.parent), "SUITE_TMP": str(self.root), "GITHUB_WORKSPACE": str(self.root), "RESERVE_RPC_PORT": "false", @@ -26,6 +33,7 @@ def run_suite(self, **overrides): "LD_LIBRARY_PATH": "/test/lib", "EXISTING_PORTS": "", "CTEST_STATUS": "0", + "CTEST_REPORT_XML": f"{body}", } # An inherited workflow setting must not affect the unset-value case. env.pop("CTEST_LABEL_EXCLUDE", None) @@ -48,6 +56,13 @@ def run_suite(self, **overrides): printf '%s\\0' "$@" > "$SUITE_TMP/ctest.args" printf '%s\\0' "$PWD" "$LD_LIBRARY_PATH" "$MC_METADATA_SERVER" \\ "$DEFAULT_KV_LEASE_TTL" > "$SUITE_TMP/ctest.env" + while [ "$#" -gt 0 ]; do + if [ "$1" = --output-junit ]; then + printf '%s' "$CTEST_REPORT_XML" > "$2" + break + fi + shift + done return "$CTEST_STATUS" } source "$SCRIPT" @@ -70,7 +85,13 @@ def test_unset_or_empty_filter_preserves_default_sweep(self): self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual( self.recorded("ctest.args"), - ["--parallel", "6", "--output-on-failure"], + [ + "--parallel", + "6", + "--output-on-failure", + "--output-junit", + str(self.root / "build/test-results/ctest.xml"), + ], ) self.assertEqual( self.recorded("ctest.env"), @@ -90,7 +111,15 @@ def test_label_regex_is_one_literal_argument(self): self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual( self.recorded("ctest.args"), - ["--parallel", "6", "--output-on-failure", "--label-exclude", regex], + [ + "--parallel", + "6", + "--output-on-failure", + "--label-exclude", + regex, + "--output-junit", + str(self.root / "build/test-results/ctest.xml"), + ], ) def test_junit_report_and_filter_coexist(self): @@ -106,6 +135,17 @@ def test_junit_report_and_filter_coexist(self): self.assertEqual(args[args.index("--label-exclude") + 1], "^nvlink_gpu$") self.assertTrue((self.root / report).parent.is_dir()) + def test_ctest_report_must_contain_successful_cases(self): + for report in ("empty", "failure"): + with self.subTest(report=report): + result = self.run_suite(report=report) + self.assertNotEqual(result.returncode, 0) + self.assertIn("ctest.xml", result.stderr) + + def test_ctest_report_allows_skipped_cases(self): + result = self.run_suite(report="skipped") + self.assertEqual(result.returncode, 0, result.stderr) + def test_port_reservation_preserves_existing_ports(self): for existing in ("", "12345,23456-23460"): with self.subTest(existing=existing): diff --git a/scripts/ci/tests/test_xpu_ci.py b/scripts/ci/tests/test_xpu_ci.py index 2cdc2bc7cec..382ee5eeb5d 100644 --- a/scripts/ci/tests/test_xpu_ci.py +++ b/scripts/ci/tests/test_xpu_ci.py @@ -1,15 +1,22 @@ -"""Host-only regression checks for XPU CI gates and packaging.""" +"""CPU-only regressions for XPU packaging and hardware CI orchestration.""" +import hashlib import importlib.util +import io +import json import os from pathlib import Path +import re import subprocess import sys +import tarfile import tempfile from types import SimpleNamespace import unittest from unittest.mock import patch from importlib import metadata +import xml.etree.ElementTree as ET +import zipfile import yaml @@ -26,6 +33,10 @@ def load_script(name, path): WORKFLOW = yaml.safe_load((ROOT / ".github/workflows/ci_xpu.yml").read_text()) +E2E_WORKFLOW = yaml.safe_load((ROOT / ".github/workflows/e2e-ci.yml").read_text()) +INTEGRATION = yaml.safe_load( + (ROOT / ".github/workflows/integration-test-xpu.yml").read_text() +) def workflow_step(name): @@ -36,72 +47,28 @@ def workflow_step(name): )["run"] +def hardware_step(name): + return next( + step + for step in INTEGRATION["jobs"]["core"]["steps"] + if step.get("name") == name + )["run"] + + ROCM = load_script("verify_rocm_wheel", "scripts/e2e/python/verify_rocm_wheel.py") with patch.dict(sys.modules, {"verify_rocm_wheel": ROCM}): - VERIFY = load_script("verify_xpu_wheel", "scripts/e2e/python/verify_xpu_wheel.py") + VERIFY = load_script("verify_xpu_ci", "scripts/e2e/python/verify_xpu_ci.py") class HostReportTest(unittest.TestCase): - def test_requires_nonempty_completed_non_skipped_cases(self): - with tempfile.TemporaryDirectory() as directory: - reports = Path(directory) / "xpu-ci-output/reports" - reports.mkdir(parents=True) - code = ( - workflow_step("Run host-side unit tests") - .split("python - <<'PY'\n", 1)[1] - .rsplit("\nPY", 1)[0] - ) - passed = '' - for body, count, valid in ( - (passed, 1, True), - (passed, 20, True), - ("", 1, False), - ('', 1, False), - ( - '', - 1, - False, - ), - ( - '', - 1, - False, - ), - ( - '', - 1, - False, - ), - ( - passed - + '', - 1, - False, - ), - ): - with self.subTest(body=body, count=count): - for name in ("config", "ep", "crc32c"): - (reports / f"{name}.xml").write_text( - f"{body * count}" - ) - result = subprocess.run( - [sys.executable, "-c", code], - cwd=directory, - capture_output=True, - text=True, - timeout=10, - ) - self.assertEqual(result.returncode == 0, valid, result.stderr) - (reports / "ep.xml").unlink() - self.assertNotEqual( - subprocess.run( - [sys.executable, "-c", code], - cwd=directory, - capture_output=True, - timeout=10, - ).returncode, - 0, - ) + def test_workflow_uses_strict_shared_report_validation(self): + script = workflow_step("Run host-side unit tests") + self.assertIn( + "python scripts/ci/check_test_reports.py --require-gtest-status", script + ) + self.assertNotIn("--allow-skipped", script) + for name in ("config", "ep", "crc32c"): + self.assertIn(f"xpu-ci-output/reports/{name}.xml", script) class BuildDirectoryTest(unittest.TestCase): @@ -301,6 +268,351 @@ def test_uses_container_and_shared_wheel_builder(self): [step.get("name") for step in job["steps"]].index("Check out source"), ) + def test_hosted_wheelhouse_is_hashed_inside_the_native_bundle(self): + script = workflow_step("Package Python dependencies for hardware") + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + payload = root / "xpu-ci-output" + payload.mkdir() + wheel = payload / "fixture.whl" + wheel.write_bytes(b"wheel") + python = root / "python" + python.write_text("""#!/bin/bash +set -eu +[ "$*" = "-m pip download --only-binary=:all: --dest xpu-ci-output/python-deps xpu-ci-output/fixture.whl" ] +cp xpu-ci-output/fixture.whl xpu-ci-output/python-deps/ +echo dependency > xpu-ci-output/python-deps/dependency.whl +""") + python.chmod(0o755) + result = subprocess.run( + ["bash", "-ec", script], + cwd=root, + env={**os.environ, "PATH": f"{root}:{os.environ['PATH']}"}, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + [path.name for path in (payload / "python-deps").iterdir()], + ["dependency.whl"], + ) + self.assertIn( + 'cp -R xpu-ci-output/python-deps "$out/"', + workflow_step("Package native tests"), + ) + + def test_unified_trigger_and_matching_artifact_handoff(self): + jobs = E2E_WORKFLOW["jobs"] + event = E2E_WORKFLOW.get("on", E2E_WORKFLOW.get(True)) + self.assertEqual(event["pull_request_target"]["types"], ["labeled"]) + self.assertNotIn("synchronize", event["pull_request_target"]["types"]) + self.assertIn("run-e2e-ci", jobs["xpu-authorize"]["if"]) + self.assertIn("workflow_dispatch", jobs["xpu-authorize"]["if"]) + self.assertTrue(E2E_WORKFLOW["concurrency"]["cancel-in-progress"]) + self.assertFalse((ROOT / ".github/workflows/xpu-core.yml").exists()) + self.assertEqual( + jobs["xpu-authorize"]["steps"][0]["env"], + { + "PR_NUMBER": "${{ inputs.pr_number }}", + "CHECKOUT_SHA": "${{ inputs.pr_sha }}", + }, + ) + self.assertEqual(jobs["build-wheel-xpu"]["needs"], "xpu-authorize") + self.assertEqual( + jobs["build-wheel-xpu"]["with"]["checkout_ref"], + "${{ needs.xpu-authorize.outputs.sha }}", + ) + self.assertEqual( + jobs["xpu-integration-test"]["needs"], + ["xpu-authorize", "build-wheel-xpu"], + ) + self.assertEqual( + jobs["xpu-integration-test"]["with"]["checkout_sha"], + "${{ needs.xpu-authorize.outputs.sha }}", + ) + for name in ("artifact_id", "artifact_digest", "source_sha"): + self.assertEqual( + jobs["xpu-integration-test"]["with"][name], + "${{ needs.build-wheel-xpu.outputs." + name + " }}", + ) + self.assertEqual( + set(jobs["e2e-gate"]["needs"]), + { + "ascend-test", + "build-wheel-rocm", + "integration-test", + "rocm-integration-test", + "integration-test-tent", + "xpu-authorize", + "build-wheel-xpu", + "xpu-integration-test", + }, + ) + self.assertIn("always()", jobs["e2e-gate"]["if"]) + self.assertEqual( + jobs["e2e-gate"]["permissions"]["checks"], + "write", + ) + self.assertNotIn("continue-on-error", jobs["e2e-gate"]["steps"][0]) + self.assertEqual(jobs["cleanup-label"]["needs"], ["e2e-gate"]) + integration = yaml.safe_load( + (ROOT / ".github/workflows/integration-test-xpu.yml").read_text() + ) + job = integration["jobs"]["core"] + self.assertEqual(job["runs-on"], "xpu") + build = yaml.safe_load((ROOT / ".github/workflows/ci_xpu.yml").read_text()) + self.assertEqual( + job["env"]["XPU_IMAGE"], build["jobs"]["build-wheel-xpu"]["container"] + ) + self.assertIn("github.workflow_sha", job["steps"][0]["with"]["ref"]) + self.assertTrue( + all( + not step.get("with", {}).get("persist-credentials", False) + for step in job["steps"] + ) + ) + + def run_javascript(self, job, environment, state): + script = next( + step["with"]["script"] + for step in E2E_WORKFLOW["jobs"][job]["steps"] + if "script" in step.get("with", {}) + ) + harness = r""" + const state = JSON.parse(process.env.TEST_STATE); + const context = { + repo: {owner: 'owner', repo: 'repo'}, actor: 'maintainer', + ref: state.ref || 'refs/heads/main', eventName: state.event || 'workflow_dispatch', + sha: state.sha || 'c'.repeat(40), + payload: state.payload || {}, serverUrl: 'https://github.com', runId: 123 + }; + const outputs = {}; + const core = { + setOutput: (key, value) => outputs[key] = value, + setFailed: message => { throw new Error(message); }, + summary: {addRaw() {return this;}, async write() {}} + }; + const github = {rest: { + repos: { + getCollaboratorPermissionLevel: async () => ({data: {permission: state.permission || 'write'}}), + getCommit: async ({ref}) => ({data: {sha: state.commit || ref}}) + }, + pulls: {get: async () => ({data: { + state: state.pullState || 'open', base: {ref: state.base || 'main'}, + head: {sha: state.head} + }})}, + checks: { + create: async request => { outputs.created = request; return {data: {id: 456}}; }, + update: async request => { outputs.check = request; } + } + }}; + (async () => { + SCRIPT + })().then(() => console.log(JSON.stringify(outputs))) + .catch(error => { + console.log(JSON.stringify(outputs)); + console.error(error.message); + process.exitCode = 1; + }); + """ + return subprocess.run( + ["node", "-e", harness.replace("SCRIPT", script)], + env={**os.environ, **environment, "TEST_STATE": json.dumps(state)}, + capture_output=True, + text=True, + timeout=10, + ) + + def test_authorization_and_stale_head(self): + sha = "a" * 40 + environment = {"PR_NUMBER": "1", "CHECKOUT_SHA": sha} + for state, valid in ( + ({"head": sha}, True), + ({"head": sha, "permission": "maintain"}, True), + ({"head": sha, "permission": "admin"}, True), + ({"head": sha, "permission": "read"}, False), + ({"head": "b" * 40}, False), + ({"head": sha, "ref": "refs/heads/untrusted"}, False), + ({"head": sha, "pullState": "closed"}, False), + ({"head": sha, "base": "release"}, False), + ({"head": sha, "commit": "b" * 40}, False), + ( + { + "head": sha, + "event": "pull_request_target", + "payload": {"pull_request": {"number": 1, "head": {"sha": sha}}}, + }, + True, + ), + ( + { + "head": sha, + "event": "pull_request_target", + "payload": { + "pull_request": {"number": 1, "head": {"sha": "b" * 40}} + }, + }, + False, + ), + ): + with self.subTest(state=state): + result = self.run_javascript("xpu-authorize", environment, state) + self.assertEqual(result.returncode == 0, valid, result.stderr) + if valid: + outputs = json.loads(result.stdout) + self.assertEqual(outputs["sha"], sha) + self.assertEqual(outputs["created"]["head_sha"], sha) + + def test_dispatch_revision_selection(self): + sha = "a" * 40 + for environment, state, expected in ( + ({"PR_NUMBER": "", "CHECKOUT_SHA": ""}, {"sha": sha}, sha), + ({"PR_NUMBER": "", "CHECKOUT_SHA": sha}, {}, sha), + ({"PR_NUMBER": "1", "CHECKOUT_SHA": ""}, {"head": sha}, sha), + ({"PR_NUMBER": "", "CHECKOUT_SHA": "main"}, {}, None), + ({"PR_NUMBER": "01", "CHECKOUT_SHA": sha}, {}, None), + ( + {"PR_NUMBER": "", "CHECKOUT_SHA": ""}, + {"ref": "refs/heads/untrusted", "sha": sha}, + None, + ), + ): + with self.subTest(environment=environment, state=state): + result = self.run_javascript("xpu-authorize", environment, state) + self.assertEqual( + result.returncode == 0, expected is not None, result.stderr + ) + if expected is not None: + self.assertEqual(json.loads(result.stdout)["sha"], expected) + + def test_gate_requires_success_and_current_head(self): + sha = "a" * 40 + for job in ("xpu-authorize", "build-wheel-xpu", "xpu-integration-test"): + for status in ("success", "failure", "cancelled", "skipped", "missing"): + needs = { + "xpu-authorize": { + "result": "success", + "outputs": {"sha": sha, "pr": "1", "check_id": "456"}, + }, + "build-wheel-xpu": { + "result": "success", + "outputs": {"source_sha": sha}, + }, + "xpu-integration-test": {"result": "success"}, + } + if status == "missing": + del needs[job] + else: + needs[job]["result"] = status + for head in (sha, "b" * 40): + with self.subTest(job=job, status=status, head=head): + completed = self.run_javascript( + "e2e-gate", + {"NEEDS_JSON": json.dumps(needs)}, + {"head": head}, + ) + valid = status == "success" and head == sha + self.assertEqual( + completed.returncode == 0, valid, completed.stderr + ) + if job != "xpu-authorize" or status == "success": + check = json.loads(completed.stdout)["check"] + self.assertEqual( + check["conclusion"], "success" if valid else "failure" + ) + + def test_gate_rejects_mismatched_or_missing_build_sha(self): + sha = "a" * 40 + for build_outputs in ({}, {"source_sha": "b" * 40}): + needs = { + "xpu-authorize": { + "result": "success", + "outputs": {"sha": sha, "pr": "1", "check_id": "456"}, + }, + "build-wheel-xpu": {"result": "success", "outputs": build_outputs}, + "xpu-integration-test": {"result": "success"}, + } + with self.subTest(build_outputs=build_outputs): + result = self.run_javascript( + "e2e-gate", {"NEEDS_JSON": json.dumps(needs)}, {"head": sha} + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("build SHA differs", result.stderr) + + def test_shared_gate_still_checks_other_platforms(self): + steps = E2E_WORKFLOW["jobs"]["e2e-gate"]["steps"] + self.assertEqual(steps[0]["uses"], "actions/github-script@v7") + step = next(step for step in steps if step["name"] == "Check E2E results") + script = re.sub(r"\$\{\{.*?\}\}", "fixture", step["run"]) + for status in ("success", "failure", "cancelled", "skipped"): + with self.subTest(status=status): + result = subprocess.run( + ["bash", "-ec", script], + env={ + **os.environ, + "NEEDS_JSON": json.dumps( + { + "rocm-integration-test": {"result": status}, + "xpu-integration-test": {"result": "success"}, + } + ), + }, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual( + result.returncode == 0, + status in ("success", "skipped"), + result.stderr, + ) + + +class CommandLineTest(unittest.TestCase): + def test_no_arguments_preserve_host_only_wheel_checks(self): + with ( + patch.object(sys, "argv", ["verify_xpu_ci.py"]), + patch.object(VERIFY, "main") as verify, + ): + VERIFY.cli() + verify.assert_called_once_with() + + def test_hardware_subcommands_and_unknown_command(self): + for arguments, callback, expected in ( + ( + ["unpack", "dir", "sha", "42", "digest"], + "unpack", + [Path("dir"), "sha", "42", "digest"], + ), + ( + ["run", "bundle", "source", "output"], + "run", + [Path("bundle"), Path("source"), Path("output")], + ), + ( + ["suite", "native", "source", "output"], + "suite", + [Path("native"), Path("source"), Path("output")], + ), + ( + ["store", "source", "report"], + "store_test", + [Path("source"), Path("report")], + ), + (["seccomp", "profile"], "prepare_seccomp", [Path("profile")]), + ): + with ( + self.subTest(arguments=arguments), + patch.object(sys, "argv", ["verify_xpu_ci.py", *arguments]), + patch.object(VERIFY, callback) as command, + ): + VERIFY.cli() + command.assert_called_once_with(*expected) + with patch.object(sys, "argv", ["verify_xpu_ci.py", "unknown"]): + with self.assertRaisesRegex(RuntimeError, "Unknown XPU verification"): + VERIFY.cli() + class InstalledWheelTest(unittest.TestCase): def setUp(self): @@ -413,6 +725,8 @@ def setUp(self): self.out.parent.mkdir() (self.out.parent / "provenance.txt").write_text("source_sha=test\n") (self.out.parent / "fixture.whl").write_bytes(b"wheel artifact") + (self.out.parent / "python-deps").mkdir() + (self.out.parent / "python-deps" / "fixture-dep.whl").write_bytes(b"dependency") self.build.mkdir() (self.build / "CMakeCache.txt").write_text("USE_XPU:BOOL=ON\n") self.library = self.root / "libfixture.so" @@ -498,5 +812,802 @@ def test_rejects_zero_test_inventory(self): self.assertIn("Empty GoogleTest inventory", result.stderr) +def write_sums(root, excluded=()): + (root / "SHA256SUMS").write_text( + "".join( + f"{VERIFY.digest(path)} ./{path.relative_to(root)}\n" + for path in sorted(root.rglob("*")) + if path.is_file() and path.name not in (*excluded, "SHA256SUMS") + ) + ) + + +class ArtifactTest(unittest.TestCase): + def test_exact_artifact_identity_digest_sha_and_complete_manifest(self): + sha = "a" * 40 + image = "intel/pytorch@sha256:" + "b" * 64 + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + provenance = f"source_sha={sha}\nimage={image}\nci_run=123/2\n" + wheel = "mooncake_transfer_engine_xpu-0.0.0-cp312-cp312-linux_x86_64.whl" + payload = {wheel: b"wheel", "native-tests.tar.gz": b"native"} + sums = "".join( + f"{hashlib.sha256(data).hexdigest()} ./{name}\n" + for name, data in payload.items() + ) + payload.update( + {"provenance.txt": provenance.encode(), "SHA256SUMS": sums.encode()} + ) + with zipfile.ZipFile(root / "artifact.zip", "w") as archive: + for name, data in payload.items(): + archive.writestr(name, data) + checksum = VERIFY.digest(root / "artifact.zip") + original = { + "id": 42, + "name": f"mooncake-xpu-ci-py312-{sha}-123-2", + "expired": False, + "workflow_run": {"id": 123}, + "digest": f"sha256:{checksum}", + } + environment = { + "GITHUB_RUN_ID": "123", + "GITHUB_RUN_ATTEMPT": "2", + "XPU_IMAGE": image, + } + for change in ( + {"id": 43}, + {"name": "latest"}, + {"expired": True}, + {"workflow_run": {"id": 122}}, + {"digest": "sha256:" + "0" * 64}, + ): + with self.subTest(change=change), patch.dict(os.environ, environment): + (root / "artifact.json").write_text( + json.dumps({**original, **change}) + ) + with self.assertRaises(RuntimeError): + VERIFY.unpack(root, sha, "42", checksum) + (root / "artifact.json").write_text(json.dumps(original)) + with patch.dict(os.environ, environment): + with self.assertRaises(RuntimeError): + VERIFY.unpack(root, sha, "42", "0" * 64) + VERIFY.unpack(root, sha, "42", checksum) + bundle = root / "bundle" + with self.assertRaises(RuntimeError): + VERIFY.verify_provenance(bundle, "c" * 40, image, "123/2") + with self.assertRaises(RuntimeError): + VERIFY.verify_provenance(bundle, sha, image + "changed", "123/2") + (bundle / wheel).write_bytes(b"corrupted") + with self.assertRaises(RuntimeError): + VERIFY.verify_hashes(bundle, {"provenance.txt"}) + + def test_zip_rejects_traversal_and_duplicate_entries(self): + for names in ( + ["../escape", "a", "b", "c"], + ["/escape", "a", "b", "c"], + ["nested/file", "a", "b", "c"], + ): + with self.subTest(names=names), tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + with zipfile.ZipFile(root / "artifact.zip", "w") as archive: + for name in names: + archive.writestr(name, b"data") + checksum = VERIFY.digest(root / "artifact.zip") + (root / "artifact.json").write_text( + json.dumps( + { + "id": 1, + "name": f"mooncake-xpu-ci-py312-{'a' * 40}-1-1", + "expired": False, + "workflow_run": {"id": 1}, + "digest": f"sha256:{checksum}", + } + ) + ) + with patch.dict( + os.environ, {"GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"} + ): + with self.assertRaises(RuntimeError): + VERIFY.unpack(root, "a" * 40, "1", checksum) + + def test_hash_inventory_rejects_unhashed_missing_duplicate_and_unsafe_files(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + (root / "a").write_bytes(b"a") + write_sums(root) + valid = (root / "SHA256SUMS").read_text() + VERIFY.verify_hashes(root) + for content in ( + "", + valid * 2, + valid.replace("./a", "../a"), + valid + "invalid\n", + ): + with self.subTest(content=content): + (root / "SHA256SUMS").write_text(content) + with self.assertRaises(RuntimeError): + VERIFY.verify_hashes(root) + (root / "SHA256SUMS").write_text(valid) + (root / "unhashed").write_text("extra") + with self.assertRaises(RuntimeError): + VERIFY.verify_hashes(root) + + def test_native_tar_roundtrip_and_rejection_of_links_and_traversal(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + native = root / "native-tests" + native.mkdir() + (native / "provenance.txt").write_text("source provenance") + (native / "test").write_bytes(b"executable") + (native / "test").chmod(0o755) + write_sums(native) + (root / "provenance.txt").write_bytes( + (native / "provenance.txt").read_bytes() + ) + with tarfile.open(root / "native-tests.tar.gz", "w:gz") as archive: + archive.add(native, arcname="native-tests") + output = root / "valid" + output.mkdir() + extracted = VERIFY.extract_native(root, output) + self.assertEqual((extracted / "test").stat().st_mode & 0o777, 0o755) + for index, (name, kind) in enumerate( + ( + ("../escape", tarfile.REGTYPE), + ("native-tests/link", tarfile.SYMTYPE), + ("native-tests/link", tarfile.LNKTYPE), + ("native-tests/device", tarfile.CHRTYPE), + ) + ): + with self.subTest(name=name, kind=kind): + entry = tarfile.TarInfo(name) + entry.type = kind + with tarfile.open(root / "native-tests.tar.gz", "w:gz") as archive: + archive.addfile(entry, io.BytesIO()) + output = root / str(index) + output.mkdir() + with self.assertRaises(RuntimeError): + VERIFY.extract_native(root, output) + + +class ReportTest(unittest.TestCase): + def test_suite_requires_store_report_and_ep_completion_before_success(self): + import importlib.metadata + + def write_report(path, identities): + root = ET.Element("testsuites") + suite = ET.SubElement(root, "testsuite") + for identity in identities: + classname, name = identity.split(".", 1) + ET.SubElement( + suite, + "testcase", + classname=classname, + name=name, + status="run", + result="completed", + ) + ET.ElementTree(root).write(path) + + def inventory_text(identities): + return "".join( + f"{identity.split('.', 1)[0]}.\n {identity.split('.', 1)[1]}\n" + for identity in sorted(identities) + ) + + for store_report, ep_complete, valid in ( + (True, True, True), + (False, True, False), + (True, False, False), + ): + with self.subTest(store_report=store_report, ep_complete=ep_complete): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + for name, (inventory, _) in VERIFY.SUITES.items(): + (root / f"{name}.list").write_text(inventory_text(inventory)) + + def run_command(args, log, timeout=600): + if log.name == "wheel.log": + self.assertEqual(args, [sys.executable, VERIFY.__file__]) + self.assertTrue(Path(args[1]).is_file()) + if "--gtest_list_tests" in args: + return inventory_text(VERIFY.SUITES[Path(args[0]).name][0]) + for argument in args: + if argument.startswith("--gtest_output=xml:"): + write_report( + Path(argument.split("xml:", 1)[1]), + VERIFY.SUITES[Path(args[0]).name][1], + ) + if len(args) > 2 and args[2] == "store" and store_report: + write_report( + Path(args[4]), {"StorePython.test_xpu_local_copy_paths"} + ) + if "test_mooncake_ep_xpu.py" in args[1]: + if not ep_complete: + return "" + return "".join( + f"round {i}: tokens=0 ok\n" for i in range(8) + ) + ( + "PASSED: 8 rounds + 2 empty-rank rounds + 4 two-batch rounds" + " + duplicate experts + reused src_info + rejected handle" + " + cross-stream + fallback agreement" + " on 2 ranks (hidden=1024, experts=8, topk=2)\n" + ) + return "" + + with ( + patch.object(VERIFY, "preflight"), + patch.object(VERIFY, "command", side_effect=run_command), + patch.object( + VERIFY, "validate_report", wraps=VERIFY.validate_report + ) as validate, + patch.object(VERIFY.socket, "create_connection"), + patch.object(VERIFY.subprocess, "Popen") as process, + patch.object( + importlib.metadata, "distribution" + ) as distribution, + patch.dict(os.environ, {"XPU_SOURCE_SHA": "a" * 40}), + ): + distribution.return_value.locate_file.return_value = root + process.return_value.__enter__.return_value.poll.return_value = None + if valid: + VERIFY.suite(root, ROOT, root) + self.assertTrue(validate.called) + for call in validate.call_args_list: + self.assertTrue(call.kwargs["require_gtest_status"]) + self.assertTrue(call.args[1]) + result = json.loads((root / "result.json").read_text()) + self.assertEqual(result["cpp_cases"], 151) + self.assertEqual(result["ep_rounds"], 8) + else: + with self.assertRaises((RuntimeError, FileNotFoundError)): + VERIFY.suite(root, ROOT, root) + self.assertFalse((root / "result.json").exists()) + + def test_inventory_parser(self): + self.assertEqual( + VERIFY.parse_inventory( + "noise\nModes/Suite.\n Case/0 # GetParam() = false\n Case/1\n" + ), + {"Modes/Suite.Case/0", "Modes/Suite.Case/1"}, + ) + for text in ("", "noise\n", " Case\n", "Suite.\n Case\n Case\n"): + with self.subTest(text=text), self.assertRaises(RuntimeError): + VERIFY.parse_inventory(text) + + def test_required_inventory_matches_cpp_sources(self): + tent = ROOT / "mooncake-transfer-engine/tent/tests/xpu" + for filename, names in ( + ("xpu_platform_test.cpp", VERIFY.PLATFORM), + ("xpu_transport_test.cpp", VERIFY.TRANSPORT), + ("xpu_engine_test.cpp", VERIFY.ENGINE | VERIFY.RDMA), + ("xpu_ipc_process_test.cpp", VERIFY.IPC), + ): + declared = set( + re.findall( + r"TEST_[FP]\(\s*(\w+),\s*(\w+)\s*\)", (tent / filename).read_text() + ) + ) + selected = { + ( + identity.split(".")[0].split("/")[-1], + identity.split(".")[1].split("/")[0], + ) + for identity in names + } + self.assertEqual(selected, declared, filename) + self.assertEqual(len(VERIFY.ENGINE), 124) + self.assertEqual(len(VERIFY.INAPPLICABLE), 10) + self.assertEqual( + sum(len(selected) for _, selected in VERIFY.SUITES.values()), 151 + ) + selected_engine = VERIFY.SUITES["tent_xpu_engine_test"][1] + self.assertFalse(selected_engine & VERIFY.RDMA) + self.assertFalse(selected_engine & VERIFY.INAPPLICABLE.keys()) + + def test_command_exit_and_timeout_propagate(self): + with tempfile.TemporaryDirectory() as temporary: + log = Path(temporary) / "command.log" + diagnostics = io.StringIO() + with ( + patch.object(VERIFY.sys, "stderr", diagnostics), + self.assertRaises(subprocess.CalledProcessError), + ): + VERIFY.command(["bash", "-c", "echo failed; exit 2"], log) + self.assertIn("failed", log.read_text()) + self.assertIn(str(log), diagnostics.getvalue()) + self.assertIn("failed", diagnostics.getvalue()) + diagnostics = io.StringIO() + with ( + patch.object(VERIFY.sys, "stderr", diagnostics), + self.assertRaises(subprocess.TimeoutExpired), + ): + VERIFY.command(["sleep", "2"], log, timeout=0.01) + self.assertIn(str(log), diagnostics.getvalue()) + + def test_command_failure_diagnostics_are_bounded(self): + with tempfile.TemporaryDirectory() as temporary: + log = Path(temporary) / "command.log" + diagnostics = io.StringIO() + with ( + patch.object(VERIFY.sys, "stderr", diagnostics), + self.assertRaises(subprocess.CalledProcessError), + ): + VERIFY.command(["bash", "-c", "seq 1 100; exit 2"], log) + lines = diagnostics.getvalue().splitlines() + self.assertEqual(len(lines), 41) + self.assertEqual(lines[1:], [str(i) for i in range(61, 101)]) + + def test_device_preflight_rejects_missing_wrong_and_unexecuted_devices(self): + from types import SimpleNamespace + + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) + for count, name, total, valid in ( + (0, "Intel Arc Pro B60", 2080, False), + (1, "Intel Arc Pro B60", 2080, False), + (2, "CPU fallback", 2080, False), + (2, "Intel Arc Pro B60", 0, False), + (2, "Intel Arc Pro B60", 2080, True), + ): + tensor = unittest.mock.MagicMock() + tensor.__add__.return_value.sum.return_value.cpu.return_value = total + torch = SimpleNamespace( + __version__="2.13.0+xpu", + xpu=SimpleNamespace( + is_available=lambda: count > 0, + device_count=lambda: count, + get_device_properties=lambda index: SimpleNamespace( + name=name, total_memory=24 << 30 + ), + synchronize=lambda index: None, + ), + arange=lambda *args, **kwargs: tensor, + ) + read_text = Path.read_text + + def runtime_text(path, *args, **kwargs): + if str(path) == "/proc/self/status": + return "CapEff:\t00000000\n" + if str(path) == "/proc/sys/kernel/yama/ptrace_scope": + return "1" + return read_text(path, *args, **kwargs) + + with ( + self.subTest(count=count, name=name, total=total), + patch.dict("sys.modules", {"torch": torch}), + patch.dict( + os.environ, + { + "ONEAPI_DEVICE_SELECTOR": "level_zero:gpu", + "ZE_AFFINITY_MASK": "0,1", + "XPU_IMAGE": "image", + "XPU_SOURCE_SHA": "a" * 40, + }, + ), + patch.object(Path, "read_text", runtime_text), + ): + if valid: + VERIFY.preflight(output) + else: + with self.assertRaises(RuntimeError): + VERIFY.preflight(output) + + +class ShellLifecycleTest(unittest.TestCase): + def test_inline_hardware_shell_syntax_and_removed_launchers(self): + for step in INTEGRATION["jobs"]["core"]["steps"]: + if "run" in step: + with self.subTest(step=step["name"]): + result = subprocess.run( + ["bash", "-n"], + input=step["run"], + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stderr) + for name in ("run_xpu_core.sh", "xpu_core.py"): + self.assertFalse((ROOT / "scripts/ci" / name).exists()) + self.assertIn( + "scripts/e2e/python/verify_xpu_ci.py unpack", + hardware_step("Download exact build artifact"), + ) + + def prepare_run(self, root): + output = root / "github-output" + subprocess.run( + ["bash", "-ec", hardware_step("Allocate run directory")], + env={ + **os.environ, + "RUNNER_TEMP": str(root), + "GITHUB_OUTPUT": str(output), + }, + check=True, + capture_output=True, + text=True, + timeout=10, + ) + return Path(output.read_text().strip().removeprefix("directory=")) + + def test_network_isolation_sets_store_and_ep_loopback_interfaces(self): + script = hardware_step("Execute isolated two-B60 core") + start = script.index("container_id=$(docker create") + stop = script.index("timeout --signal=TERM", start) + docker_command = script[start:stop] + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + docker = root / "docker" + docker.write_text("""#!/bin/bash +set -eu +printf '%s\\n' "$@" > "$DOCKER_ARGUMENTS" +echo container-id +""") + docker.chmod(0o755) + arguments = root / "arguments" + result = subprocess.run( + ["bash", "-ec", "device_args=()\n" + docker_command], + env={ + **os.environ, + "PATH": f"{root}:{os.environ['PATH']}", + "DOCKER_ARGUMENTS": str(arguments), + "GITHUB_RUN_ID": "123", + "GITHUB_RUN_ATTEMPT": "1", + "XPU_IMAGE": "image", + "ZE_AFFINITY_MASK": "4,5", + "CHECKOUT_SHA": "a" * 40, + "run_directory": str(root), + "source_directory": str(ROOT), + "control_directory": str(ROOT / "scripts"), + }, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stderr) + args = arguments.read_text().splitlines() + self.assertEqual(args[args.index("--network") + 1], "none") + for variable in ( + "MOONCAKE_LOCAL_HOSTNAME=127.0.0.1", + "CCL_KVS_IFACE=lo", + "GLOO_SOCKET_IFNAME=lo", + "LOCAL_HOSTNAME=127.0.0.1", + "MASTER_SERVER=127.0.0.1:50051", + "ZE_AFFINITY_MASK=4,5", + ): + self.assertIn(variable, args) + self.assertEqual(args[args.index(variable) - 1], "--env") + self.assertNotIn("--privileged", args) + self.assertIn( + "python3 /control/e2e/python/verify_xpu_ci.py run /bundle /source /output", + "\n".join(args), + ) + + def test_fixed_runner_masks_need_no_lock_or_profile_variables(self): + script = hardware_step("Execute isolated two-B60 core") + start = script.index(': "${ZE_AFFINITY_MASK:') + stop = script.index("# Preserve host GPU ordinals") + for mask, valid in ( + ("0,1", True), + ("2,3", True), + ("4,5", True), + ("6,7", True), + ("0,0", False), + ("00,0", False), + ("0", False), + ("0.0,0.1", False), + ("", False), + ): + environment = { + key: value + for key, value in os.environ.items() + if key + not in { + "XPU_LOCK_DIRECTORY", + "XPU_SECCOMP_PROFILE", + "XPU_RENDER_DEVICES", + } + } + environment.update( + { + "ZE_AFFINITY_MASK": mask, + "XPU_IMAGE": "image@sha256:" + "a" * 64, + "CHECKOUT_SHA": "b" * 40, + } + ) + with self.subTest(mask=mask): + result = subprocess.run( + [ + "bash", + "-ec", + 'fail() { echo "$*" >&2; exit 1; }\n' + script[start:stop], + ], + env=environment, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode == 0, valid, result.stderr) + self.assertNotIn("XPU_LOCK_DIRECTORY", script) + self.assertNotIn("XPU_SECCOMP_PROFILE", script) + self.assertNotIn("XPU_RENDER_DEVICES", script) + self.assertNotIn("flock", script) + self.assertIn("devices=(/dev/dri/renderD*)", script) + self.assertIn('--env "ZE_AFFINITY_MASK=$ZE_AFFINITY_MASK"', script) + self.assertIn( + '--security-opt "seccomp=$run_directory/output/seccomp.json"', script + ) + + def test_cleanup_recheck_propagates_docker_query_failure(self): + for query_status in (0, 2): + with self.subTest( + query_status=query_status + ), tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + run_directory = self.prepare_run(root) + docker = root / "docker" + docker.write_text("""#!/bin/bash +set -eu +case "$1" in + ps) exit "$QUERY_STATUS" ;; + info) exit 0 ;; + *) exit 99 ;; +esac +""") + docker.chmod(0o755) + result = subprocess.run( + [ + "bash", + "-ec", + hardware_step("Recheck current-run container cleanup"), + ], + env={ + **os.environ, + "PATH": f"{root}:{os.environ['PATH']}", + "GITHUB_RUN_ID": "123", + "GITHUB_RUN_ATTEMPT": "1", + "QUERY_STATUS": str(query_status), + "RUN_DIRECTORY": str(run_directory), + }, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode, query_status, result.stderr) + self.assertEqual( + (run_directory / "output/cleanup-recheck.json").exists(), + query_status == 0, + ) + + def test_owned_container_cleanup_and_failures_propagate(self): + script = hardware_step("Execute isolated two-B60 core") + cleanup = ( + 'source "$RUN_DIRECTORY/cleanup.sh"\n' + + script[ + script.index("container_id=\n") : script.index( + 'docker pull "$XPU_IMAGE"' + ) + ] + ) + for suite_status, cleanup_failure, expected in ( + (0, "no", 0), + (2, "no", 2), + (0, "yes", 1), + ): + with self.subTest( + suite_status=suite_status, cleanup_failure=cleanup_failure + ): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + run_directory = self.prepare_run(root) + (run_directory / "output").mkdir() + docker = root / "docker" + docker.write_text("""#!/bin/bash +set -eu +echo "$*" >> "$RUN_DIRECTORY/docker.commands" +case "$1" in + info) echo daemon-ready ;; + stop) echo owned-container ;; + inspect) + [ ! -e "$RUN_DIRECTORY/removed" ] || exit 1 + if [ "${2:-}" = --format ]; then echo false; else echo '{}'; fi ;; + rm) + [ "$CLEANUP_FAILURE" = no ] || exit 1 + touch "$RUN_DIRECTORY/removed" ;; + *) exit 99 ;; +esac +""") + docker.chmod(0o755) + result = subprocess.run( + [ + "bash", + "-ec", + f"{cleanup}\ncontainer_id=owned-container\nexit {suite_status}", + ], + env={ + **os.environ, + "PATH": f"{root}:{os.environ['PATH']}", + "run_directory": str(run_directory), + "RUN_DIRECTORY": str(run_directory), + "CLEANUP_FAILURE": cleanup_failure, + }, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual( + result.returncode, expected, result.stdout + result.stderr + ) + commands = (run_directory / "docker.commands").read_text() + self.assertIn("stop --time 10 owned-container", commands) + self.assertIn("rm owned-container", commands) + self.assertNotIn("prune", commands) + report = json.loads( + (run_directory / "output/cleanup.json").read_text() + ) + self.assertEqual( + report["cleanup_status"] == 0, cleanup_failure == "no" + ) + + def test_cleanup_recheck_removes_only_current_run_container(self): + for container_id, valid in (("a" * 64, True), ("invalid-id", False)): + with self.subTest( + container_id=container_id + ), tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + run_directory = self.prepare_run(root) + docker = root / "docker" + docker.write_text("""#!/bin/bash +set -eu +echo "$*" >> "$RUN_DIRECTORY/docker.commands" +case "$1" in + ps) echo "$OWNED_CONTAINER" ;; + info|stop) exit 0 ;; + inspect) + [ ! -e "$RUN_DIRECTORY/removed" ] || exit 1 + if [ "${2:-}" = --format ]; then echo false; else echo '{}'; fi ;; + rm) touch "$RUN_DIRECTORY/removed" ;; + *) exit 99 ;; +esac +""") + docker.chmod(0o755) + result = subprocess.run( + [ + "bash", + "-ec", + hardware_step("Recheck current-run container cleanup"), + ], + env={ + **os.environ, + "PATH": f"{root}:{os.environ['PATH']}", + "RUN_DIRECTORY": str(run_directory), + "OWNED_CONTAINER": container_id, + "GITHUB_RUN_ID": "123", + "GITHUB_RUN_ATTEMPT": "1", + }, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode == 0, valid, result.stderr) + commands = (run_directory / "docker.commands").read_text() + self.assertIn("--filter label=mooncake.xpu.run=123-1", commands) + self.assertEqual((run_directory / "removed").exists(), valid) + self.assertEqual( + (run_directory / "output/cleanup-recheck.json").exists(), valid + ) + if valid: + self.assertIn(f"rm {container_id}", commands) + else: + self.assertNotIn("stop ", commands) + self.assertNotIn("rm ", commands) + self.assertNotIn("prune", commands) + + def test_host_preflight_rejects_root(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + (root / "output").mkdir() + fake_id = root / "id" + fake_id.write_text("#!/bin/sh\necho 0\n") + fake_id.chmod(0o755) + script = hardware_step("Execute isolated two-B60 core") + result = subprocess.run( + [ + "bash", + "-ec", + script[script.index("exec >") :], + ], + env={ + **os.environ, + "PATH": f"{root}:{os.environ['PATH']}", + "run_directory": str(root), + }, + capture_output=True, + text=True, + timeout=10, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("must not run as root", result.stdout + result.stderr) + + +class SeccompTest(unittest.TestCase): + def test_only_required_syscalls_are_unconditionally_allowed(self): + original = { + "defaultAction": "SCMP_ACT_ERRNO", + "defaultErrnoRet": 1, + "archMap": [{"architecture": "SCMP_ARCH_X86_64", "subArchitectures": []}], + "syscalls": [ + {"names": ["read", "write", "pidfd_open"], "action": "SCMP_ACT_ALLOW"}, + { + "names": ["pidfd_getfd", "ptrace"], + "action": "SCMP_ACT_ALLOW", + "includes": {"caps": ["CAP_SYS_PTRACE"]}, + }, + { + "names": ["io_uring_setup"], + "action": "SCMP_ACT_ERRNO", + "errnoRet": 1, + }, + { + "names": ["mount"], + "action": "SCMP_ACT_ALLOW", + "includes": {"caps": ["CAP_SYS_ADMIN"]}, + }, + ], + } + content = json.dumps(original).encode() + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "seccomp.json" + with ( + patch.object(VERIFY.urllib.request, "urlopen") as download, + patch.object( + VERIFY, "SECCOMP_SHA256", hashlib.sha256(content).hexdigest() + ), + ): + download.return_value.__enter__.return_value.read.return_value = content + VERIFY.prepare_seccomp(output) + download.assert_called_once_with(VERIFY.SECCOMP_URL, timeout=30) + actual = json.loads(output.read_text()) + self.assertEqual(actual["defaultAction"], original["defaultAction"]) + self.assertEqual(actual["archMap"], original["archMap"]) + self.assertEqual( + actual["syscalls"][-1], + { + "names": sorted(VERIFY.XPU_SYSCALLS), + "action": "SCMP_ACT_ALLOW", + }, + ) + remaining = [] + for rule in original["syscalls"]: + names = [ + name for name in rule["names"] if name not in VERIFY.XPU_SYSCALLS + ] + if names: + remaining.append({**rule, "names": names}) + self.assertEqual(actual["syscalls"][:-1], remaining) + + def test_download_checksum_and_default_action_failures_abort(self): + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "seccomp.json" + with patch.object( + VERIFY.urllib.request, "urlopen", side_effect=OSError("download failed") + ): + with self.assertRaisesRegex(OSError, "download failed"): + VERIFY.prepare_seccomp(output) + with patch.object(VERIFY.urllib.request, "urlopen") as download: + download.return_value.__enter__.return_value.read.return_value = ( + b"corrupted" + ) + with self.assertRaisesRegex(RuntimeError, "checksum mismatch"): + VERIFY.prepare_seccomp(output) + content = b'{"defaultAction":"SCMP_ACT_ALLOW"}' + download.return_value.__enter__.return_value.read.return_value = content + with patch.object( + VERIFY, "SECCOMP_SHA256", hashlib.sha256(content).hexdigest() + ): + with self.assertRaisesRegex(RuntimeError, "deny-by-default"): + VERIFY.prepare_seccomp(output) + self.assertFalse(output.exists()) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/e2e/python/verify_xpu_ci.py b/scripts/e2e/python/verify_xpu_ci.py new file mode 100644 index 00000000000..03a7b2b1ed8 --- /dev/null +++ b/scripts/e2e/python/verify_xpu_ci.py @@ -0,0 +1,699 @@ +"""Verify XPU CI artifacts and hardware suites; no arguments check the wheel.""" + +from collections import deque +import hashlib +import importlib +import importlib.util +from importlib import metadata +import json +import os +from pathlib import Path, PurePosixPath +import re +import shutil +import socket +import stat +import subprocess +import sys +import tarfile +import time +import unittest +import urllib.request +import xml.etree.ElementTree as ET +import zipfile + +from verify_rocm_wheel import find_extension_record, record_digest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "ci")) +validate_report = importlib.import_module("check_test_reports").validate_report + + +def main() -> None: + os.environ["MC_USE_TENT"] = "1" + os.environ["MOONCAKE_STORE_BACKEND"] = "cpp" + distribution = metadata.distribution("mooncake-transfer-engine-xpu") + package = importlib.import_module("mooncake") + package_dir = Path(package.__file__).resolve().parent + records = {str(item): item for item in distribution.files or ()} + for stem in ("engine.", "_store.", "_ep."): + relative = find_extension_record(records, stem) + record = records[relative] + installed = Path(distribution.locate_file(record)).resolve() + if installed != package_dir / Path(relative).name: + raise RuntimeError( + f"Extension resolves outside installed package: {installed}" + ) + if ( + record.hash is None + or record_digest(installed, record.hash.mode) != record.hash.value + ): + raise RuntimeError(f"Wheel RECORD mismatch: {installed}") + module = importlib.import_module(f"mooncake.{stem.rstrip('.')}") + if Path(module.__file__).resolve() != installed: + raise RuntimeError(f"Extension loaded outside wheel: {module.__file__}") + + engine = importlib.import_module("mooncake.engine") + if not engine.SUPPORT_XPU or not engine.SUPPORT_TENT or engine.SUPPORT_CUDA: + raise RuntimeError("Wheel must provide native XPU/TENT, not CUDA") + ep = importlib.import_module("mooncake.ep") + if ep.DEVICE_TYPE != "xpu": + raise RuntimeError("Wheel did not load the native XPU EP implementation") + store = importlib.import_module("mooncake.store") + private_store = importlib.import_module("mooncake._store") + if ( + store._BACKEND != "cpp" + or store.MooncakeDistributedStore is not private_store.MooncakeDistributedStore + ): + raise RuntimeError("Store facade did not select the installed C++ extension") + + master = package_dir / "mooncake_master" + record = records.get("mooncake/mooncake_master") + if ( + record is None + or record.hash is None + or record_digest(master, record.hash.mode) != record.hash.value + ): + raise RuntimeError("Packaged master does not match wheel RECORD") + subprocess.run([str(master), "--version"], check=True, timeout=15) + with subprocess.Popen([str(master), "--port=50051"]) as process: + try: + for _ in range(100): + if process.poll() is not None: + raise RuntimeError(f"Packaged master exited: {process.returncode}") + try: + with socket.create_connection(("127.0.0.1", 50051), timeout=0.1): + break + except OSError: + time.sleep(0.1) + else: + raise RuntimeError("Packaged master did not start within 10 seconds") + finally: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + raise + print( + f"Verified mooncake-transfer-engine-xpu {distribution.version}; host-only coverage" + ) + + +SECCOMP_URL = ( + "https://raw.githubusercontent.com/moby/profiles/" + "4b8214fc4971e06172938a1f1554ccff6647ee80/seccomp/default.json" +) + + +SECCOMP_SHA256 = "6416b47770785a41ac59073cdc77d9fe98517df2799dc83ef207e622de3053f6" + + +XPU_SYSCALLS = { + "pidfd_open", + "pidfd_getfd", + "io_uring_setup", + "io_uring_enter", + "io_uring_register", +} + + +def prepare_seccomp(output: Path) -> None: + with urllib.request.urlopen(SECCOMP_URL, timeout=30) as response: + content = response.read() + require( + hashlib.sha256(content).hexdigest() == SECCOMP_SHA256, + "Docker default seccomp profile checksum mismatch", + ) + profile = json.loads(content) + require( + profile["defaultAction"] == "SCMP_ACT_ERRNO", "Expected deny-by-default seccomp" + ) + rules = [] + for rule in profile["syscalls"]: + names = [name for name in rule["names"] if name not in XPU_SYSCALLS] + if names: + rules.append({**rule, "names": names}) + rules.append({"names": sorted(XPU_SYSCALLS), "action": "SCMP_ACT_ALLOW"}) + profile["syscalls"] = rules + output.write_text(json.dumps(profile, indent=2)) + + +def require(condition: bool, message: str) -> None: + if not condition: + raise RuntimeError(message) + + +def digest(path: Path) -> str: + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def relative_path(name: str) -> Path: + path = PurePosixPath(name) + require(not path.is_absolute() and ".." not in path.parts, f"Unsafe path: {name}") + require(bool(path.parts), f"Empty path: {name}") + return Path(*path.parts) + + +def verify_hashes( + root: Path, excluded: set[str] | frozenset[str] = frozenset() +) -> None: + expected = set() + for line in (root / "SHA256SUMS").read_text().splitlines(): + match = re.fullmatch(r"([0-9a-f]{64}) [ *](.+)", line) + if match is None: + raise RuntimeError(f"Invalid checksum entry: {line}") + checksum, name = match.groups() + path = relative_path(name) + require( + path not in expected and path != Path("SHA256SUMS"), f"Duplicate: {name}" + ) + expected.add(path) + require(digest(root / path) == checksum, f"Checksum mismatch: {name}") + actual = { + path.relative_to(root) + for path in root.rglob("*") + if path.is_file() and path.name not in excluded and path != root / "SHA256SUMS" + } + require(bool(expected) and actual == expected, "Checksum inventory mismatch") + + +def verify_provenance(root: Path, sha: str, image: str, run: str) -> None: + lines = (root / "provenance.txt").read_text().splitlines() + for item in (f"source_sha={sha}", f"image={image}", f"ci_run={run}"): + require(lines.count(item) == 1, f"Missing or mismatched provenance: {item}") + + +def unpack(directory: Path, sha: str, artifact_id: str, checksum: str) -> None: + info = json.loads((directory / "artifact.json").read_text()) + run = f"{os.environ['GITHUB_RUN_ID']}/{os.environ['GITHUB_RUN_ATTEMPT']}" + expected_name = f"mooncake-xpu-ci-py312-{sha}-{run.replace('/', '-')}" + checksum = checksum.removeprefix("sha256:") + require( + re.fullmatch(r"[0-9a-f]{64}", checksum) is not None, "Invalid artifact digest" + ) + require(str(info["id"]) == artifact_id, "Artifact ID mismatch") + require( + info["name"] == expected_name and not info["expired"], + "Artifact identity mismatch", + ) + require( + str(info["workflow_run"]["id"]) == run.split("/")[0], "Artifact run mismatch" + ) + require(info["digest"] == f"sha256:{checksum}", "Artifact metadata digest mismatch") + require( + digest(directory / "artifact.zip") == checksum, "Artifact ZIP digest mismatch" + ) + bundle = directory / "bundle" + bundle.mkdir() + with zipfile.ZipFile(directory / "artifact.zip") as archive: + names = archive.namelist() + require( + len(names) == len(set(names)) == 4, "Expected exactly four artifact files" + ) + for member in archive.infolist(): + path = relative_path(member.filename) + require( + len(path.parts) == 1 and not member.is_dir(), "Artifact must be flat" + ) + require( + not stat.S_ISLNK(member.external_attr >> 16), + "Artifact contains a symlink", + ) + with archive.open(member) as source, (bundle / path).open("wb") as target: + shutil.copyfileobj(source, target) + require( + {path.name for path in bundle.iterdir() if path.suffix != ".whl"} + == {"native-tests.tar.gz", "provenance.txt", "SHA256SUMS"}, + "Unexpected artifact payload", + ) + wheels = list(bundle.glob("mooncake_transfer_engine_xpu-*-cp312-cp312-*.whl")) + require(len(wheels) == 1, "Expected one CPython 3.12 XPU wheel") + verify_hashes(bundle, {"provenance.txt"}) + verify_provenance(bundle, sha, os.environ["XPU_IMAGE"], run) + + +def extract_native(bundle: Path, output: Path) -> Path: + destination = output / "native" + destination.mkdir() + seen = set() + with tarfile.open(bundle / "native-tests.tar.gz", "r:gz") as archive: + for member in archive: + path = relative_path(member.name) + require(path.parts[0] == "native-tests", "Unexpected native archive root") + require(path not in seen, f"Duplicate native entry: {path}") + seen.add(path) + target = destination / path + if member.isdir(): + target.mkdir(parents=True, exist_ok=True) + else: + require( + member.isfile(), + f"Native archive contains a link or special file: {path}", + ) + target.parent.mkdir(parents=True, exist_ok=True) + source = archive.extractfile(member) + if source is None: + raise RuntimeError(f"Native archive file has no data: {path}") + with source, target.open("wb") as stream: + shutil.copyfileobj(source, stream) + target.chmod(member.mode & 0o777) + native = destination / "native-tests" + verify_hashes(native) + require( + (native / "provenance.txt").read_bytes() + == (bundle / "provenance.txt").read_bytes(), + "Native and wheel provenance differ", + ) + return native + + +def case_names(suite: str, names: str, count: int = 0) -> set[str]: + return { + f"{suite}.{name}" + (f"/{index}" if count else "") + for name in names.split() + for index in range(count or 1) + } + + +PLATFORM = case_names( + "XpuPlatformTest", + """TypeString ProbeRegistersOneMemEntryPerDevice ProbeDoesNotDuplicateGpusAcrossAdapters + DeviceAllocCopyFreeRoundTrip HostPointerClassifiesAsCpu ForeignUsmClassifiesAsXpuAndCopies + InteriorPointerClassifiesAsXpu BareXpuLocationAllocatesDeviceZero MalformedXpuOrdinalIsRejected + HostPointerIsNotExportable DeviceAllocationExportsAsDmabuf SeparateAllocationsExportDistinctDmabufs + DeviceToDeviceCopyOnSameDevice DeviceToDeviceCopyAcrossDevices CopyRejectsRangePastAllocationEnd + IpcImportOnSameDevice IpcImportOnPeerDevice HostPointerIsNotIpcExportable ImportRejectsBadArguments + ConcurrentHostDeviceCopiesKeepTheirData""", +) + + +TRANSPORT = case_names( + "XpuTransportTest", + """LocalStageCopiesFromInteriorDeviceOffset RemoteStageCopiesToInteriorDeviceOffset + ReadStageCopiesHostToDevice FailsWhenNeitherSideIsDeviceMemory CopiesDeviceToDevice + RejectsUnmappedNonLocalTarget ReRegistrationPublishesDistinctIpcAttribute""", +) + + +ENGINE = ( + case_names( + "NetworkAndDispatchModes/XpuEngineTest", + """DefaultRegistrationSelectsLocalXpuCopy StagesDeviceToDeviceReadAndWrite + StagesOneDeviceSideReadAndWrite RetryKeepsHostTransportBehindStaging + RejectsXpuHintForPeerSegment UnstagedHostSourceMustCarryHostTransport + DisabledXpuTransportRoutesByCapability""", + 8, + ) + | case_names( + "NetworkAndDispatchModes/XpuLocalDeviceCopyTest", "SameDevice AcrossDevices", 8 + ) + | case_names( + "DispatchModes/XpuIpcEngineTest", + """DeviceToPeerDeviceReadAndWrite HostToPeerDeviceReadAndWrite XpuHintForPeerSegmentIsHonoured + ImportsArePerLocalDevice FailoverRouteIsStaged PolicyWithoutXpuStaysStaged + StaleSnapshotKeepsNewerImports ClosingSegmentReleasesImports UnpublishedPeerBufferIsReleased + InteriorOffsetsRelocateInsideMapping PeerHostBufferStaysStaged PeerWithoutIpcStaysStaged""", + 4, + ) + | case_names( + "SelectionModes/XpuIoUringFileTest", + "DeviceWriteReachesFile DeviceReadReturnsFileContents", + 2, + ) +) + + +RDMA = case_names( + "SelectionModes/XpuDirectRdmaTest", + """DeviceToDeviceReadAndWrite OneDeviceSideReadAndWrite HostTransportHintKeepsStaging + HostOnlyPolicyKeepsStaging""", + 2, +) + + +INAPPLICABLE = { + **{ + f"NetworkAndDispatchModes/XpuEngineTest.RetryKeepsHostTransportBehindStaging/{i}": "TCP recovers inside the device stage" + for i in range(4) + }, + **{ + f"NetworkAndDispatchModes/XpuEngineTest.DisabledXpuTransportRoutesByCapability/{i}": "HP TCP alone cannot register device memory" + for i in range(4, 8) + }, + **{ + f"DispatchModes/XpuIpcEngineTest.PolicyWithoutXpuStaysStaged/{i}": "Policies apply to selector mode only" + for i in (2, 3) + }, +} + + +IPC = ( + case_names( + "SelectionModes/XpuIpcProcessTest", + "DeviceToPeerDeviceReadAndWrite HostToPeerDeviceReadAndWrite", + 2, + ) + | case_names( + "SelectionModes/XpuIpcFallbackTest", + "DeviceToPeerDeviceFallsBackToStaging HostToPeerDeviceFallsBackToStaging", + 2, + ) + | case_names("XpuIpcProcessTest", "MappingClosedWhenPeerExits") +) + + +STORE = {"RealClientTest.XpuDeviceBufferPutGetRoundTrips"} + + +SUITES = { + "tent_xpu_platform_test": (PLATFORM, PLATFORM), + "tent_xpu_transport_test": (TRANSPORT, TRANSPORT), + "tent_xpu_engine_test": (ENGINE | RDMA, ENGINE - INAPPLICABLE.keys()), + "tent_xpu_ipc_process_test": (IPC, IPC), + "pybind_client_test": (STORE, STORE), +} + + +def parse_inventory(text: str) -> set[str]: + suite = "" + names = [] + for line in text.splitlines(): + value = line.split("#", 1)[0].strip() + if not value: + continue + if not line.startswith(" ") and value.endswith("."): + suite = value + elif line.startswith(" ") and re.fullmatch(r"[A-Za-z0-9_/]+", value): + require(bool(suite), "Test without suite") + names.append(suite + value) + require( + bool(names) and len(names) == len(set(names)), + "Empty or duplicate test inventory", + ) + return set(names) + + +def command(args: list[str], log: Path, timeout: int = 600) -> str: + try: + with log.open("w") as stream: + subprocess.run( + args, + stdout=stream, + stderr=subprocess.STDOUT, + check=True, + timeout=timeout, + ) + except (subprocess.CalledProcessError, subprocess.TimeoutExpired): + print(f"XPU command failed; last 40 lines of {log}:", file=sys.stderr) + with log.open() as stream: + for line in deque(stream, maxlen=40): + print(line, end="", file=sys.stderr) + raise + return log.read_text() + + +def preflight(output: Path) -> None: + import torch + + require(sys.version_info[:2] == (3, 12), "Runtime must use CPython 3.12") + require(torch.__version__.split("+")[0] == "2.13.0", "Unexpected PyTorch runtime") + require( + os.environ["ONEAPI_DEVICE_SELECTOR"] == "level_zero:gpu", + "Level Zero GPU backend required", + ) + available = torch.xpu.is_available() + count = torch.xpu.device_count() + properties = [torch.xpu.get_device_properties(index) for index in range(count)] + devices = [ + {"index": index, "name": props.name, "memory": props.total_memory} + for index, props in enumerate(properties) + ] + inventory = { + "devices": devices, + "available": available, + "count": count, + "torch": torch.__version__, + "python": sys.version, + "affinity": os.environ["ZE_AFFINITY_MASK"], + "image": os.environ["XPU_IMAGE"], + "source_sha": os.environ["XPU_SOURCE_SHA"], + "verified": False, + } + (output / "devices.json").write_text(json.dumps(inventory, indent=2)) + require( + available and count == 2, f"Exactly two XPU devices required; found {count}" + ) + for index, props in enumerate(properties): + require("B60" in props.name, f"Expected B60, found {props.name}") + tensor = torch.arange(64, device=f"xpu:{index}") + require(int((tensor + 1).sum().cpu()) == 2080, "XPU execution failed") + torch.xpu.synchronize(index) + status = Path("/proc/self/status").read_text() + match = re.search(r"^CapEff:\s+([0-9a-f]+)$", status, re.MULTILINE) + if match is None: + raise RuntimeError("Cannot verify process capabilities") + caps = int(match.group(1), 16) + require( + not caps & (1 << 19), + "CAP_SYS_PTRACE invalidates permission-denied IPC coverage", + ) + scope = Path("/proc/sys/kernel/yama/ptrace_scope") + require( + not scope.exists() or int(scope.read_text()) <= 1, + "IPC requires ptrace_scope <= 1", + ) + inventory["verified"] = True + (output / "devices.json").write_text(json.dumps(inventory, indent=2)) + + +def store_test(source: Path, report: Path) -> None: + spec = importlib.util.spec_from_file_location( + "xpu_store_tensor_test", source / "mooncake-wheel/tests/test_put_get_tensor.py" + ) + if spec is None or spec.loader is None: + raise RuntimeError("Store test module has no loader") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + test = module.TestDistributedObjectStore("test_xpu_local_copy_paths") + result = unittest.TextTestRunner(verbosity=2).run(unittest.TestSuite([test])) + root = ET.Element("testsuites") + suite = ET.SubElement(root, "testsuite", name="StorePython") + case = ET.SubElement( + suite, + "testcase", + classname="StorePython", + name="test_xpu_local_copy_paths", + status="run", + result="completed", + ) + if not result.wasSuccessful() or result.skipped or result.testsRun != 1: + ET.SubElement(case, "failure").text = repr(result.__dict__) + ET.ElementTree(root).write(report) + validate_report( + report, {"StorePython.test_xpu_local_copy_paths"}, require_gtest_status=True + ) + + +def run(bundle: Path, source: Path, output: Path) -> None: + verify_hashes(bundle, {"provenance.txt"}) + native = extract_native(bundle, output) + # Intel PyTorch ships SYCL/UR in its interpreter prefix, not ldconfig. + os.environ["LD_LIBRARY_PATH"] = ( + f"{native / 'lib'}:{Path(sys.prefix) / 'lib'}:{os.environ.get('LD_LIBRARY_PATH', '')}" + ) + python = sys.executable + wheel = next(bundle.glob("*.whl")) + command( + [ + python, + "-m", + "pip", + "install", + "--no-index", + "--ignore-installed", + "--find-links", + str(native / "python-deps"), + "--target", + "/tmp/xpu-installed", + str(wheel), + ], + output / "install.log", + ) + os.environ["PYTHONPATH"] = "/tmp/xpu-installed" + command( + [python, __file__, "suite", str(native), str(source), str(output)], + output / "suite.log", + timeout=4000, + ) + + +def suite(native: Path, source: Path, output: Path) -> None: + started = time.monotonic() + python = sys.executable + preflight(output) + command([python, "-m", "pip", "freeze"], output / "runtime-packages.log") + command([python, __file__], output / "wheel.log") + (output / "selection.json").write_text( + json.dumps( + { + "required": { + name: sorted(selected) for name, (_, selected) in SUITES.items() + }, + "excluded": { + **dict.fromkeys(sorted(RDMA), "No RDMA hardware"), + **INAPPLICABLE, + }, + "outside_scope": [ + "GDS", + "multi-node", + "EP > 2 ranks", + "vLLM", + "nightly E2E", + ], + }, + indent=2, + ) + ) + for name, (inventory, selected) in SUITES.items(): + binary = str(native / name) + libraries = command(["ldd", binary], output / f"{name}.ldd") + require("not found" not in libraries, f"Missing native dependencies: {name}") + discovered = parse_inventory( + command([binary, "--gtest_list_tests"], output / f"{name}.list") + ) + require( + discovered == parse_inventory((native / f"{name}.list").read_text()), + f"Build/runtime inventory differs: {name}", + ) + require( + inventory <= discovered + if name == "pybind_client_test" + else inventory == discovered, + f"Unexpected test inventory: {name}", + ) + report = output / f"{name}.xml" + command( + [ + binary, + f"--gtest_filter={':'.join(sorted(selected))}", + f"--gtest_output=xml:{report}", + ], + output / f"{name}.log", + timeout=1200, + ) + validate_report(report, selected, require_gtest_status=True) + + package = Path( + metadata.distribution("mooncake-transfer-engine-xpu").locate_file("mooncake") + ) + master_log = (output / "master.log").open("w") + with master_log, subprocess.Popen( + [str(package / "mooncake_master"), "--port=50051"], + stdout=master_log, + stderr=subprocess.STDOUT, + ) as master: + try: + for _ in range(100): + require(master.poll() is None, "Store master exited before readiness") + try: + with socket.create_connection(("127.0.0.1", 50051), timeout=0.1): + break + except OSError: + time.sleep(0.1) + else: + raise RuntimeError("Store master did not start") + command( + [ + python, + __file__, + "store", + str(source), + str(output / "store-python.xml"), + ], + output / "store-python.log", + ) + validate_report( + output / "store-python.xml", + {"StorePython.test_xpu_local_copy_paths"}, + require_gtest_status=True, + ) + finally: + master.terminate() + try: + master.wait(timeout=10) + except subprocess.TimeoutExpired: + master.kill() + master.wait() + raise + ep = command( + [ + python, + str(source / "python/tests/ep/test_mooncake_ep_xpu.py"), + "--num-ranks", + "2", + "--max-tokens", + "32", + "--hidden", + "1024", + "--num-experts", + "8", + "--num-topk", + "2", + "--rounds", + "5", + ], + output / "ep.log", + timeout=1200, + ) + require( + re.findall(r"^round (\d+): .* ok$", ep, re.MULTILINE) + == [str(i) for i in range(8)], + "Missing EP correctness rounds", + ) + expected = ( + "PASSED: 8 rounds + 2 empty-rank rounds + 4 two-batch rounds + duplicate experts" + " + reused src_info + rejected handle + cross-stream + fallback agreement" + " on 2 ranks (hidden=1024, experts=8, topk=2)" + ) + require( + ep.splitlines().count(expected) == 1, "Missing native two-rank EP completion" + ) + (output / "result.json").write_text( + json.dumps( + { + "source_sha": os.environ["XPU_SOURCE_SHA"], + "status": "passed", + "cpp_cases": sum(len(selected) for _, selected in SUITES.values()), + "store_python_cases": 1, + "ep_ranks": 2, + "ep_rounds": 8, + "elapsed_seconds": time.monotonic() - started, + }, + indent=2, + ) + ) + + +def cli() -> None: + if len(sys.argv) == 1: + main() + return + mode, *args = sys.argv[1:] + if mode == "unpack": + directory, sha, artifact_id, checksum = args + unpack(Path(directory), sha, artifact_id, checksum) + elif mode == "run": + run(*(Path(arg) for arg in args)) + elif mode == "suite": + suite(*(Path(arg) for arg in args)) + elif mode == "store": + store_test(*(Path(arg) for arg in args)) + elif mode == "seccomp": + prepare_seccomp(Path(args[0])) + else: + raise RuntimeError(f"Unknown XPU verification command: {mode}") + + +if __name__ == "__main__": + cli() diff --git a/scripts/e2e/python/verify_xpu_wheel.py b/scripts/e2e/python/verify_xpu_wheel.py deleted file mode 100644 index 4f7cabee977..00000000000 --- a/scripts/e2e/python/verify_xpu_wheel.py +++ /dev/null @@ -1,87 +0,0 @@ -"""Check an installed XPU wheel without a GPU or a source-tree native build.""" - -import importlib -from importlib import metadata -import os -from pathlib import Path -import socket -import subprocess -import time - -from verify_rocm_wheel import find_extension_record, record_digest - - -def main() -> None: - os.environ["MC_USE_TENT"] = "1" - os.environ["MOONCAKE_STORE_BACKEND"] = "cpp" - distribution = metadata.distribution("mooncake-transfer-engine-xpu") - package = importlib.import_module("mooncake") - package_dir = Path(package.__file__).resolve().parent - records = {str(item): item for item in distribution.files or ()} - for stem in ("engine.", "_store.", "_ep."): - relative = find_extension_record(records, stem) - record = records[relative] - installed = Path(distribution.locate_file(record)).resolve() - if installed != package_dir / Path(relative).name: - raise RuntimeError( - f"Extension resolves outside installed package: {installed}" - ) - if ( - record.hash is None - or record_digest(installed, record.hash.mode) != record.hash.value - ): - raise RuntimeError(f"Wheel RECORD mismatch: {installed}") - module = importlib.import_module(f"mooncake.{stem.rstrip('.')}") - if Path(module.__file__).resolve() != installed: - raise RuntimeError(f"Extension loaded outside wheel: {module.__file__}") - - engine = importlib.import_module("mooncake.engine") - if not engine.SUPPORT_XPU or not engine.SUPPORT_TENT or engine.SUPPORT_CUDA: - raise RuntimeError("Wheel must provide native XPU/TENT, not CUDA") - ep = importlib.import_module("mooncake.ep") - if ep.DEVICE_TYPE != "xpu": - raise RuntimeError("Wheel did not load the native XPU EP implementation") - store = importlib.import_module("mooncake.store") - private_store = importlib.import_module("mooncake._store") - if ( - store._BACKEND != "cpp" - or store.MooncakeDistributedStore is not private_store.MooncakeDistributedStore - ): - raise RuntimeError("Store facade did not select the installed C++ extension") - - master = package_dir / "mooncake_master" - record = records.get("mooncake/mooncake_master") - if ( - record is None - or record.hash is None - or record_digest(master, record.hash.mode) != record.hash.value - ): - raise RuntimeError("Packaged master does not match wheel RECORD") - subprocess.run([str(master), "--version"], check=True, timeout=15) - with subprocess.Popen([str(master), "--port=50051"]) as process: - try: - for _ in range(100): - if process.poll() is not None: - raise RuntimeError(f"Packaged master exited: {process.returncode}") - try: - with socket.create_connection(("127.0.0.1", 50051), timeout=0.1): - break - except OSError: - time.sleep(0.1) - else: - raise RuntimeError("Packaged master did not start within 10 seconds") - finally: - process.terminate() - try: - process.wait(timeout=10) - except subprocess.TimeoutExpired: - process.kill() - process.wait() - raise - print( - f"Verified mooncake-transfer-engine-xpu {distribution.version}; host-only coverage" - ) - - -if __name__ == "__main__": - main() diff --git a/scripts/xpu/README.md b/scripts/xpu/README.md new file mode 100644 index 00000000000..87f213e865f --- /dev/null +++ b/scripts/xpu/README.md @@ -0,0 +1,168 @@ +# XPU hardware core (Stage 2) + +Stage 1 builds a CPython 3.12 wheel and matching native tests on hosted CPU +runners. Stage 2 consumes that exact artifact on a fixed two-B60 allocation. +It does not build while holding GPUs, use models, publish wheels, or enable +nightly hardware/application coverage (Stage 3). + +## Runner contract + +Register dedicated, isolated, **non-root, ephemeral** runners with the `xpu` +label (`runs-on: xpu`). PR code executes inside the runtime container; +do not place credentials, other tenants, or persistent trusted workloads on +these runners. Destroy/reimage the runner after each job. Docker access is +host administration capability: container flags are not a substitute for this +runner isolation. + +Each eight-GPU host runs four runners, each owning a fixed, non-overlapping +pair. GitHub runs one job at a time per runner; no additional allocation lock +or lock-directory configuration is needed. No other workload may use those +assigned devices. + +Install Docker, `gh`, Python 3.12, and `timeout`. The only required GPU +configuration is the runner's existing **host-owned** environment variable: + +```sh +ZE_AFFINITY_MASK=0,1 +``` + +For example, the four masks can be `0,1`, `2,3`, `4,5`, and `6,7`, using the +host's Level Zero whole-device ordinals. All render nodes are passed into the +container to preserve device enumeration; the mask selects the assigned pair. +Preflight requires exactly two visible B60s and real GPU arithmetic. +**The mask is not a security boundary:** this setup trusts the fixed runner +allocation and test code not to use other devices. It is not suitable for +untrusted multi-tenant code. No privileged mode, host network/PID/IPC namespace, +Docker socket, publishing token, or `CAP_SYS_PTRACE` is passed to the container. + +CI automatically downloads a commit-pinned Moby default seccomp profile, +verifies its SHA256, and writes a per-run profile allowing `pidfd_open`, +`pidfd_getfd`, `io_uring_setup`, `io_uring_enter`, and `io_uring_register`. +All other default rules remain unchanged. No `XPU_SECCOMP_PROFILE`, +`XPU_LOCK_DIRECTORY`, or `XPU_RENDER_DEVICES` setting is required or consumed. +The host needs HTTPS access to `raw.githubusercontent.com`; download or +checksum failure aborts the job, never falls back to `seccomp=unconfined`. +The generated profile is retained in the diagnostic artifact. +Host Yama `ptrace_scope` must be 0 or 1, +Level Zero IPC/P2P must work, and the run's output filesystem must support +`O_DIRECT` and io_uring. Missing permissions/capabilities fail core, not skip it. + +The container keeps `--network none`: Store and EP peers communicate only +inside its private loopback network. CI sets both the Python Store's +`LOCAL_HOSTNAME` and TENT's distinct `MOONCAKE_LOCAL_HOSTNAME` to `127.0.0.1`. +TENT's automatic address discovery skips loopback, so the latter must be +explicit even when Store setup already supplies a local segment name. +EP's oneCCL KVS also excludes loopback during automatic discovery, so CI sets +`CCL_KVS_IFACE=lo`; the EP test's CPU process group uses +`GLOO_SOCKET_IFNAME=lo`. These are container-local interface selections, not +additional runner-service settings. XCCL and the native Level Zero IPC fast +path remain enabled; no network access or fallback-only coverage is introduced. + +The runtime uses the same digest-pinned Intel PyTorch image as Stage 1. +Provision compatible Intel GPU drivers and matching SYCL/Level Zero runtimes; +dependency loading, wheel RECORD/native capabilities, and real GPU arithmetic +are checked before the suites. The hosted builder also downloads the wheel's +Python dependencies into the hashed native bundle. The offline container +installs only this wheel and those dependencies (`--no-index --find-links`) +into a fresh temporary import directory, retaining the pinned image's PyTorch. +Intel's native runtime is resolved from that image's Python prefix; no SYCL or +Level Zero runtime is added to the Mooncake wheel. + +## Trigger and revision binding + +After these workflows are available on upstream `main`, a maintainer with +write/maintain/admin permission can add `run-e2e-ci` to an open PR targeting +`main`. The shared **E2E CI** entry point runs XPU alongside the existing ROCm, +Ascend and other integration jobs; XPU is required, not an optional selection. +The existing E2E label cleanup removes the label after the gate; add it again +to rerun. A new PR head needs new authorization; leaving the label attached +does not authorize later pushes. + +Alternatively dispatch **E2E CI** on trusted `main`, supplying `pr_number` +(current head) and optionally `pr_sha` (must match), or a full 40-character +`pr_sha` without a PR. With neither input, XPU tests the dispatch's `main` +commit. No branch names or implicit latest artifacts are accepted. +Fork PR heads are supported through their commit SHA. + +The hosted builder receives that exact SHA. Hardware downloads its artifact +by ID in the same run and verifies the API identity, run/attempt, ZIP digest, +payload/native hashes, source/image provenance, and build/runtime inventories. +The host runs the trusted workflow-revision harness, not PR host scripts. + +The shared `E2E Gate` requires XPU authorization, build, hardware tests and +cleanup to succeed. Its hosted-only XPU step publishes the `XPU Core` check +on the authorized commit, rechecking the PR head and build SHA before success. +Failed, cancelled, skipped, missing or stale required XPU results cannot pass. +The existing E2E concurrency policy cancels older runs for the same PR; +an interrupted controller can leave an in-progress check, never a successful +check. Other platforms retain their existing jobs and gate policy. +The normal Stage 1 hosted build remains independent and required by the +existing PR CI gate. Nightly still builds only the XPU artifact, without +running XPU hardware tests. + +## Required coverage and diagnostics + +Core executes sequentially: + +- 19 platform cases, including foreign/interior USM, dma-buf export, and + same-/cross-device IPC and copies. +- 7 XPU transport cases. +- 114 engine cases: local copies, TCP/HP-TCP staging (tests explicitly disable + IPC for those paths), retry/routing, IPC lifetime/policies, and io_uring. +- 8 real cross-process IPC/fallback cases, including permission-denied peers. +- 1 C++ Store foreign-USM roundtrip with an in-process master. +- 1 existing Python Store tensor/registered-buffer roundtrip with a packaged + local master. +- Native EP on two ranks: eight fixed-seed rounds covering BF16/FP8, + event/hook completion and dispatch weights, plus empty-rank, overlap, + duplicate-expert, handle, cross-stream, and fallback-agreement checks. + The existing script asserts native selection and must print its exact final + completion record; missing rounds or zero-test execution fail. + +The **151 C++ cases** require exact GoogleTest identities and completed XML +results. Ten parameter combinations that unconditionally skip because they +are inapplicable are excluded *before* execution, with reasons in +`selection.json`. No runtime skips are allowed. The eight direct-RDMA +parameterizations are explicitly excluded; dma-buf export itself needs no NIC. +GDS, multi-node, more than two EP ranks, and vLLM are not claimed as coverage. + +Artifacts retain runner/container cleanup state, device/runtime identity, +selection, XML, logs, inventories, dependency diagnostics, artifact metadata, +source SHA, and elapsed suite time, including on failure. A failed/timed-out +command's final 40 log lines are also printed so nested test errors appear in +the Actions step; full logs remain in the artifact. Only the current container +is stopped/removed; its PID namespace owns all test descendants. +Cleanup failure fails the hardware job. Runner reimaging remains mandatory +after failure or cancellation. + +CPU-only regression validation: + +```sh +python3 -m unittest scripts.ci.tests.test_xpu_ci \ + scripts.ci.tests.test_run_ctest -v +``` + +XPU CI regressions share one test module and common workflow/module loaders; +they validate packaging and orchestration contracts, not actual B60 behavior. +Shared XML report validation lives in `scripts/ci/check_test_reports.py`. +Both the hosted XPU tests and hardware suites require GoogleTest's explicit +`run`/`completed` status and reject skipped cases. Hardware suites additionally +pass their expected case identities to the same validator. The shared CTest +action and TENT CI also use it for JUnit reports, preserving CTest's existing +skip policy via `--allow-skipped`. Targeted CTest steps without XML reports +retain their native exit-code and `--no-tests=error` checks. + +Docker launch, device mapping, traps and cleanup are inline in +`.github/workflows/integration-test-xpu.yml`. A temporary cleanup helper is +created from that trusted workflow in the host run directory and shared by +the exit trap and the `always()` cleanup recheck; it is not mounted into the +test container. + +`scripts/e2e/python/verify_xpu_ci.py` is the single verification entry point: +no arguments retain the hosted wheel smoke checks; `unpack` verifies the +downloaded artifact, `seccomp` prepares the pinned profile, and `run` installs +the wheel offline and launches the `suite`/`store` hardware checks. There are +no separate XPU runtime scripts under `scripts/ci/`. + +Enable hardware only after provisioning and successfully running the exact +core workflow; record real queue/runtime measurements during rollout. From ee741e8617f399f792f33970c79baa38989c4b0a Mon Sep 17 00:00:00 2001 From: VincyZhang Date: Thu, 12 Nov 2026 03:19:55 +0000 Subject: [PATCH 2/6] [CI/Build] Preserve XPU artifact identity across partial reruns Pass the producing build attempt through the artifact handoff instead of validating against the consumer attempt. Keep strict artifact and provenance checks, and cover partial reruns and mismatched attempts in regressions. Signed-off-by: VincyZhang --- .github/workflows/ci_xpu.yml | 4 ++ .github/workflows/e2e-ci.yml | 1 + .github/workflows/integration-test-xpu.yml | 4 ++ scripts/ci/tests/test_xpu_ci.py | 51 ++++++++++++++++++++-- scripts/e2e/python/verify_xpu_ci.py | 4 +- 5 files changed, 60 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci_xpu.yml b/.github/workflows/ci_xpu.yml index 179a7a5758b..75db37101e9 100644 --- a/.github/workflows/ci_xpu.yml +++ b/.github/workflows/ci_xpu.yml @@ -18,6 +18,8 @@ on: value: ${{ jobs.build-wheel-xpu.outputs.artifact_id }} artifact_digest: value: ${{ jobs.build-wheel-xpu.outputs.artifact_digest }} + artifact_attempt: + value: ${{ jobs.build-wheel-xpu.outputs.artifact_attempt }} workflow_dispatch: permissions: @@ -36,6 +38,7 @@ jobs: source_sha: ${{ steps.source.outputs.sha }} artifact_id: ${{ steps.artifact.outputs.artifact-id }} artifact_digest: ${{ steps.artifact.outputs.artifact-digest }} + artifact_attempt: ${{ steps.source.outputs.attempt }} env: XPU_BUILD: "1" PYTHON_VERSION: "3.12" @@ -64,6 +67,7 @@ jobs: run: | git config --global --add safe.directory "$GITHUB_WORKSPACE" echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + echo "attempt=$GITHUB_RUN_ATTEMPT" >> "$GITHUB_OUTPUT" - name: Install toolchain and dependencies run: | diff --git a/.github/workflows/e2e-ci.yml b/.github/workflows/e2e-ci.yml index 2a02ee029f0..8780fb79a5c 100644 --- a/.github/workflows/e2e-ci.yml +++ b/.github/workflows/e2e-ci.yml @@ -113,6 +113,7 @@ jobs: source_sha: ${{ needs.build-wheel-xpu.outputs.source_sha }} artifact_id: ${{ needs.build-wheel-xpu.outputs.artifact_id }} artifact_digest: ${{ needs.build-wheel-xpu.outputs.artifact_digest }} + artifact_attempt: ${{ needs.build-wheel-xpu.outputs.artifact_attempt }} ascend-test: if: > diff --git a/.github/workflows/integration-test-xpu.yml b/.github/workflows/integration-test-xpu.yml index 724b39a3eb7..d7e356d9778 100644 --- a/.github/workflows/integration-test-xpu.yml +++ b/.github/workflows/integration-test-xpu.yml @@ -15,6 +15,9 @@ on: artifact_digest: type: string required: true + artifact_attempt: + type: string + required: true permissions: contents: read @@ -68,6 +71,7 @@ jobs: GH_TOKEN: ${{ github.token }} ARTIFACT_ID: ${{ inputs.artifact_id }} ARTIFACT_DIGEST: ${{ inputs.artifact_digest }} + XPU_BUILD_ATTEMPT: ${{ inputs.artifact_attempt }} SOURCE_SHA: ${{ inputs.source_sha }} CHECKOUT_SHA: ${{ inputs.checkout_sha }} RUN_DIRECTORY: ${{ steps.run.outputs.directory }} diff --git a/scripts/ci/tests/test_xpu_ci.py b/scripts/ci/tests/test_xpu_ci.py index 382ee5eeb5d..bb8391772db 100644 --- a/scripts/ci/tests/test_xpu_ci.py +++ b/scripts/ci/tests/test_xpu_ci.py @@ -331,11 +331,42 @@ def test_unified_trigger_and_matching_artifact_handoff(self): jobs["xpu-integration-test"]["with"]["checkout_sha"], "${{ needs.xpu-authorize.outputs.sha }}", ) - for name in ("artifact_id", "artifact_digest", "source_sha"): + for name in ( + "artifact_id", + "artifact_digest", + "artifact_attempt", + "source_sha", + ): self.assertEqual( jobs["xpu-integration-test"]["with"][name], "${{ needs.build-wheel-xpu.outputs." + name + " }}", ) + build_event = WORKFLOW.get("on", WORKFLOW.get(True)) + self.assertEqual( + build_event["workflow_call"]["outputs"]["artifact_attempt"]["value"], + "${{ jobs.build-wheel-xpu.outputs.artifact_attempt }}", + ) + self.assertEqual( + WORKFLOW["jobs"]["build-wheel-xpu"]["outputs"]["artifact_attempt"], + "${{ steps.source.outputs.attempt }}", + ) + self.assertIn( + 'echo "attempt=$GITHUB_RUN_ATTEMPT" >> "$GITHUB_OUTPUT"', + workflow_step("Record selected source"), + ) + hardware_event = INTEGRATION.get("on", INTEGRATION.get(True)) + self.assertEqual( + hardware_event["workflow_call"]["inputs"]["artifact_attempt"], + {"type": "string", "required": True}, + ) + download = next( + step + for step in INTEGRATION["jobs"]["core"]["steps"] + if step.get("name") == "Download exact build artifact" + ) + self.assertEqual( + download["env"]["XPU_BUILD_ATTEMPT"], "${{ inputs.artifact_attempt }}" + ) self.assertEqual( set(jobs["e2e-gate"]["needs"]), { @@ -851,7 +882,8 @@ def test_exact_artifact_identity_digest_sha_and_complete_manifest(self): } environment = { "GITHUB_RUN_ID": "123", - "GITHUB_RUN_ATTEMPT": "2", + "GITHUB_RUN_ATTEMPT": "3", + "XPU_BUILD_ATTEMPT": "2", "XPU_IMAGE": image, } for change in ( @@ -869,6 +901,12 @@ def test_exact_artifact_identity_digest_sha_and_complete_manifest(self): VERIFY.unpack(root, sha, "42", checksum) (root / "artifact.json").write_text(json.dumps(original)) with patch.dict(os.environ, environment): + for attempt in ("", "0", "-1", "2/3", "3"): + with self.subTest(attempt=attempt), patch.dict( + os.environ, {"XPU_BUILD_ATTEMPT": attempt} + ): + with self.assertRaises(RuntimeError): + VERIFY.unpack(root, sha, "42", checksum) with self.assertRaises(RuntimeError): VERIFY.unpack(root, sha, "42", "0" * 64) VERIFY.unpack(root, sha, "42", checksum) @@ -877,6 +915,8 @@ def test_exact_artifact_identity_digest_sha_and_complete_manifest(self): VERIFY.verify_provenance(bundle, "c" * 40, image, "123/2") with self.assertRaises(RuntimeError): VERIFY.verify_provenance(bundle, sha, image + "changed", "123/2") + with self.assertRaises(RuntimeError): + VERIFY.verify_provenance(bundle, sha, image, "123/3") (bundle / wheel).write_bytes(b"corrupted") with self.assertRaises(RuntimeError): VERIFY.verify_hashes(bundle, {"provenance.txt"}) @@ -905,7 +945,12 @@ def test_zip_rejects_traversal_and_duplicate_entries(self): ) ) with patch.dict( - os.environ, {"GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"} + os.environ, + { + "GITHUB_RUN_ID": "1", + "GITHUB_RUN_ATTEMPT": "1", + "XPU_BUILD_ATTEMPT": "1", + }, ): with self.assertRaises(RuntimeError): VERIFY.unpack(root, "a" * 40, "1", checksum) diff --git a/scripts/e2e/python/verify_xpu_ci.py b/scripts/e2e/python/verify_xpu_ci.py index 03a7b2b1ed8..2839470efcf 100644 --- a/scripts/e2e/python/verify_xpu_ci.py +++ b/scripts/e2e/python/verify_xpu_ci.py @@ -186,7 +186,9 @@ def verify_provenance(root: Path, sha: str, image: str, run: str) -> None: def unpack(directory: Path, sha: str, artifact_id: str, checksum: str) -> None: info = json.loads((directory / "artifact.json").read_text()) - run = f"{os.environ['GITHUB_RUN_ID']}/{os.environ['GITHUB_RUN_ATTEMPT']}" + attempt = os.environ["XPU_BUILD_ATTEMPT"] + require(re.fullmatch(r"[1-9][0-9]*", attempt) is not None, "Invalid build attempt") + run = f"{os.environ['GITHUB_RUN_ID']}/{attempt}" expected_name = f"mooncake-xpu-ci-py312-{sha}-{run.replace('/', '-')}" checksum = checksum.removeprefix("sha256:") require( From 3406a6c2b40ff875442d7d0be3db064436468f4a Mon Sep 17 00:00:00 2001 From: VincyZhang Date: Thu, 12 Nov 2026 06:22:43 +0000 Subject: [PATCH 3/6] [CI/Build] Keep XPU Stage 2 changes scoped to hardware CI Remove custom XPU authorization and check publication, using GitHub revision context and the existing E2E gate. Restore shared CTest and TENT behavior and update XPU tests and documentation while preserving artifact verification and partial-rerun support. Signed-off-by: VincyZhang --- .github/actions/run-ctest/action.yml | 4 +- .github/actions/run-ctest/run.sh | 11 +- .github/workflows/ci.yml | 3 - .github/workflows/ci_xpu.yml | 2 +- .github/workflows/e2e-ci.yml | 113 +--------- .github/workflows/integration-test-xpu.yml | 8 +- scripts/ci/check_test_reports.py | 66 ------ scripts/ci/tests/test_run_ctest.py | 46 +--- scripts/ci/tests/test_xpu_ci.py | 248 +++++---------------- scripts/e2e/python/verify_xpu_ci.py | 37 ++- scripts/xpu/{README.md => XPU_CI.md} | 62 +++--- 11 files changed, 142 insertions(+), 458 deletions(-) delete mode 100644 scripts/ci/check_test_reports.py rename scripts/xpu/{README.md => XPU_CI.md} (77%) diff --git a/.github/actions/run-ctest/action.yml b/.github/actions/run-ctest/action.yml index 2c01865b34e..03be26af779 100644 --- a/.github/actions/run-ctest/action.yml +++ b/.github/actions/run-ctest/action.yml @@ -1,11 +1,11 @@ name: Run Mooncake CTest suite -description: Run and validate the source-build CTest suite with shared runtime settings +description: Run the source-build CTest suite with shared runtime settings inputs: reserve-rpc-port: description: Reserve the Mooncake client RPC port from ephemeral allocation default: 'true' junit-report: - description: Repository-relative JUnit output path (defaults to build/test-results/ctest.xml) + description: Optional repository-relative JUnit output path default: '' label-exclude: description: Optional CTest label regex to exclude diff --git a/.github/actions/run-ctest/run.sh b/.github/actions/run-ctest/run.sh index 33aad45d735..5efd41a4cdf 100644 --- a/.github/actions/run-ctest/run.sh +++ b/.github/actions/run-ctest/run.sh @@ -9,14 +9,13 @@ args=(--parallel "$(nproc)" --output-on-failure) if [ -n "${CTEST_LABEL_EXCLUDE:-}" ]; then args+=(--label-exclude "$CTEST_LABEL_EXCLUDE") fi -report="$GITHUB_WORKSPACE/${JUNIT_REPORT:-build/test-results/ctest.xml}" -mkdir -p "$(dirname "$report")" -rm -f "$report" -args+=(--output-junit "$report") +if [ -n "$JUNIT_REPORT" ]; then + report="$GITHUB_WORKSPACE/$JUNIT_REPORT" + mkdir -p "$(dirname "$report")" + args+=(--output-junit "$report") +fi cd build export LD_LIBRARY_PATH=${LD_LIBRARY_PATH:-}:/usr/local/lib MC_METADATA_SERVER=http://127.0.0.1:8080/metadata \ DEFAULT_KV_LEASE_TTL=500 \ ctest "${args[@]}" -python3 "$GITHUB_ACTION_PATH/../../../scripts/ci/check_test_reports.py" \ - --allow-skipped "$report" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1600191d842..b59ae484586 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -847,9 +847,6 @@ jobs: --output-on-failure \ --output-junit "$GITHUB_WORKSPACE/build-tent/test-results/ctest.xml" \ "${ctest_args[@]}" - cd "$GITHUB_WORKSPACE" - python3 scripts/ci/check_test_reports.py --allow-skipped \ - build-tent/test-results/ctest.xml shell: bash - name: Preserve TENT CTest diagnostics diff --git a/.github/workflows/ci_xpu.yml b/.github/workflows/ci_xpu.yml index 75db37101e9..7c781fc7e68 100644 --- a/.github/workflows/ci_xpu.yml +++ b/.github/workflows/ci_xpu.yml @@ -136,7 +136,7 @@ jobs: --gtest_output=xml:xpu-ci-output/reports/ep.xml "$BUILD_DIR/mooncake-store/tests/crc32c_test" \ --gtest_output=xml:xpu-ci-output/reports/crc32c.xml - python scripts/ci/check_test_reports.py --require-gtest-status \ + python scripts/e2e/python/verify_xpu_ci.py reports \ xpu-ci-output/reports/config.xml \ xpu-ci-output/reports/ep.xml \ xpu-ci-output/reports/crc32c.xml diff --git a/.github/workflows/e2e-ci.yml b/.github/workflows/e2e-ci.yml index 8780fb79a5c..29f3820bfb4 100644 --- a/.github/workflows/e2e-ci.yml +++ b/.github/workflows/e2e-ci.yml @@ -28,88 +28,24 @@ concurrency: cancel-in-progress: true jobs: - xpu-authorize: + build-wheel-xpu: if: > github.event_name == 'workflow_dispatch' || github.event.label.name == 'run-e2e-ci' - runs-on: ubuntu-24.04 - permissions: - contents: read - pull-requests: read - checks: write - outputs: - sha: ${{ steps.select.outputs.sha }} - pr: ${{ steps.select.outputs.pr }} - check_id: ${{ steps.select.outputs.check_id }} - steps: - - name: Authorize exact XPU revision - id: select - uses: actions/github-script@v7 - env: - PR_NUMBER: ${{ inputs.pr_number }} - CHECKOUT_SHA: ${{ inputs.pr_sha }} - with: - script: | - const repo = context.repo; - if (context.eventName === 'workflow_dispatch' && - context.ref !== 'refs/heads/main') { - throw new Error('Dispatch the trusted main workflow, not a PR branch'); - } - const {data: actor} = await github.rest.repos.getCollaboratorPermissionLevel({ - ...repo, username: context.actor - }); - if (!['admin', 'maintain', 'write'].includes(actor.permission)) { - throw new Error('XPU hardware execution requires maintainer authorization'); - } - const rawPr = context.payload.pull_request?.number || process.env.PR_NUMBER; - if (rawPr && !/^[1-9][0-9]*$/.test(String(rawPr))) { - throw new Error('Invalid PR number'); - } - const pr = rawPr ? Number(rawPr) : null; - let sha = process.env.CHECKOUT_SHA; - if (pr) { - const {data: pull} = await github.rest.pulls.get({...repo, pull_number: pr}); - if (pull.state !== 'open' || pull.base.ref !== 'main') { - throw new Error('Expected an open PR targeting main'); - } - const authorized = context.payload.pull_request?.head.sha || sha || pull.head.sha; - if (authorized !== pull.head.sha) { - throw new Error('PR head changed; authorize the new SHA again'); - } - sha = authorized; - } else if (!sha) { - sha = context.sha; - } - if (!/^[0-9a-f]{40}$/.test(sha)) { - throw new Error('A full 40-character commit SHA is required'); - } - const {data: commit} = await github.rest.repos.getCommit({...repo, ref: sha}); - if (commit.sha !== sha) throw new Error('Commit identity mismatch'); - const {data: check} = await github.rest.checks.create({ - ...repo, name: 'XPU Core', head_sha: sha, status: 'in_progress', - details_url: `${context.serverUrl}/${repo.owner}/${repo.repo}/actions/runs/${context.runId}` - }); - core.setOutput('sha', sha); - core.setOutput('pr', pr || ''); - core.setOutput('check_id', String(check.id)); - await core.summary.addRaw(`Authorized XPU core revision: ${sha}\n`).write(); - - build-wheel-xpu: - needs: xpu-authorize permissions: contents: read uses: ./.github/workflows/ci_xpu.yml with: - checkout_ref: ${{ needs.xpu-authorize.outputs.sha }} + checkout_ref: ${{ inputs.pr_sha || github.event.pull_request.head.sha || github.sha }} xpu-integration-test: - needs: [xpu-authorize, build-wheel-xpu] + needs: build-wheel-xpu permissions: contents: read actions: read uses: ./.github/workflows/integration-test-xpu.yml with: - checkout_sha: ${{ needs.xpu-authorize.outputs.sha }} + checkout_sha: ${{ inputs.pr_sha || github.event.pull_request.head.sha || github.sha }} source_sha: ${{ needs.build-wheel-xpu.outputs.source_sha }} artifact_id: ${{ needs.build-wheel-xpu.outputs.artifact_id }} artifact_digest: ${{ needs.build-wheel-xpu.outputs.artifact_digest }} @@ -180,51 +116,10 @@ jobs: - integration-test - rocm-integration-test - integration-test-tent - - xpu-authorize - build-wheel-xpu - xpu-integration-test runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: read - checks: write steps: - - name: Check XPU results on the authorized head - uses: actions/github-script@v7 - env: - NEEDS_JSON: ${{ toJSON(needs) }} - with: - script: | - const needs = JSON.parse(process.env.NEEDS_JSON); - const authorization = needs['xpu-authorize']; - if (authorization?.result !== 'success') { - core.setFailed('XPU authorization did not succeed'); - return; - } - const selected = authorization.outputs; - const required = ['xpu-authorize', 'build-wheel-xpu', 'xpu-integration-test']; - const failed = required - .filter(name => needs[name]?.result !== 'success') - .map(name => `${name}: ${needs[name]?.result || 'missing'}`); - if (needs['build-wheel-xpu']?.outputs?.source_sha !== selected.sha) { - failed.push('XPU build SHA differs from authorized SHA'); - } - if (selected.pr) { - const {data: pr} = await github.rest.pulls.get({ - ...context.repo, pull_number: Number(selected.pr) - }); - if (pr.head.sha !== selected.sha) failed.push('PR head changed; retrigger required'); - } - const summary = failed.length ? failed.join('\n') : - `C++ non-RDMA, Store Python and native two-rank EP passed on ${selected.sha}`; - await github.rest.checks.update({ - ...context.repo, check_run_id: Number(selected.check_id), - status: 'completed', conclusion: failed.length ? 'failure' : 'success', - output: {title: 'XPU Core', summary} - }); - await core.summary.addRaw(summary).write(); - if (failed.length) core.setFailed(summary); - - name: Check E2E results run: | echo "PR: #${{ inputs.pr_number || github.event.pull_request.number }}" diff --git a/.github/workflows/integration-test-xpu.yml b/.github/workflows/integration-test-xpu.yml index d7e356d9778..a15857943b9 100644 --- a/.github/workflows/integration-test-xpu.yml +++ b/.github/workflows/integration-test-xpu.yml @@ -79,13 +79,13 @@ jobs: set -euo pipefail [[ "$ARTIFACT_ID" =~ ^[0-9]+$ ]] || { echo "::error::Invalid artifact ID"; exit 1; } [[ "$CHECKOUT_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "::error::Invalid source SHA"; exit 1; } - [ "$SOURCE_SHA" = "$CHECKOUT_SHA" ] || { echo "::error::Build SHA differs from authorized SHA"; exit 1; } + [ "$SOURCE_SHA" = "$CHECKOUT_SHA" ] || { echo "::error::Build SHA differs from requested SHA"; exit 1; } gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID" > "$RUN_DIRECTORY/artifact.json" gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID/zip" > "$RUN_DIRECTORY/artifact.zip" python3 xpu-control/scripts/e2e/python/verify_xpu_ci.py unpack \ "$RUN_DIRECTORY" "$CHECKOUT_SHA" "$ARTIFACT_ID" "$ARTIFACT_DIGEST" - - name: Check out authorized test source + - name: Check out test source uses: actions/checkout@v4 with: ref: ${{ inputs.checkout_sha }} @@ -100,7 +100,7 @@ jobs: run: | set -euo pipefail [ "$(git -C xpu-tested-source rev-parse HEAD)" = "$CHECKOUT_SHA" ] || { - echo "::error::Checked out source differs from authorized SHA"; exit 1; + echo "::error::Checked out source differs from requested SHA"; exit 1; } run_directory=$(realpath "$RUN_DIRECTORY") source_directory=$(realpath "$GITHUB_WORKSPACE/xpu-tested-source") @@ -112,7 +112,7 @@ jobs: [ "$(id -u)" -ne 0 ] || { echo "XPU runner must not run as root" >&2; exit 1; } : "${ZE_AFFINITY_MASK:?Set a host-owned two-GPU ZE_AFFINITY_MASK}" : "${XPU_IMAGE:?Missing pinned runtime image}" - : "${CHECKOUT_SHA:?Missing authorized SHA}" + : "${CHECKOUT_SHA:?Missing requested SHA}" [[ "$ZE_AFFINITY_MASK" =~ ^(0|[1-9][0-9]*),(0|[1-9][0-9]*)$ ]] || { echo "ZE_AFFINITY_MASK must select two whole devices, not subdevices" >&2; exit 1; } diff --git a/scripts/ci/check_test_reports.py b/scripts/ci/check_test_reports.py deleted file mode 100644 index a1216ab5253..00000000000 --- a/scripts/ci/check_test_reports.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Check JUnit/GoogleTest reports, optionally checking exact case identities.""" - -import argparse -from pathlib import Path -import xml.etree.ElementTree as ET - - -def validate_report( - path: str | Path, - expected: set[str] | None = None, - require_gtest_status: bool = False, - allow_skipped: bool = False, -) -> None: - report = Path(path) - cases = ET.parse(report).findall(".//testcase") - if not cases: - raise RuntimeError(f"{report}: no tests executed") - if expected is not None: - identities = [f"{case.get('classname')}.{case.get('name')}" for case in cases] - if len(identities) != len(expected) or set(identities) != expected: - raise RuntimeError(f"{report}: test identity mismatch: {identities}") - for case in cases: - status = case.get("status") - result = case.get("result") - skipped = case.find("skipped") is not None or (status, result) in { - ("run", "skipped"), - ("notrun", "suppressed"), - } - if any(case.find(tag) is not None for tag in ("failure", "error")): - raise RuntimeError(f"{report}: test did not pass: {case.attrib}") - if skipped: - if not allow_skipped or require_gtest_status: - raise RuntimeError(f"{report}: test was skipped: {case.attrib}") - continue - if require_gtest_status: - completed = (status, result) == ("run", "completed") - else: - completed = status in (None, "run") and result in (None, "completed") - if not completed: - raise RuntimeError(f"{report}: test did not pass: {case.attrib}") - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument( - "--require-gtest-status", - action="store_true", - help="Require GoogleTest's run/completed testcase attributes", - ) - parser.add_argument( - "--allow-skipped", - action="store_true", - help="Permit skipped testcases in CTest reports", - ) - parser.add_argument("reports", nargs="+", type=Path) - args = parser.parse_args() - for report in args.reports: - validate_report( - report, - require_gtest_status=args.require_gtest_status, - allow_skipped=args.allow_skipped, - ) - - -if __name__ == "__main__": - main() diff --git a/scripts/ci/tests/test_run_ctest.py b/scripts/ci/tests/test_run_ctest.py index aa2fddcd994..21b16b82e1e 100644 --- a/scripts/ci/tests/test_run_ctest.py +++ b/scripts/ci/tests/test_run_ctest.py @@ -15,17 +15,10 @@ def setUp(self): self.root = Path(self.directory.name).resolve() (self.root / "build").mkdir() - def run_suite(self, report="passed", **overrides): - body = { - "passed": '', - "empty": "", - "failure": '', - "skipped": '', - }[report] + def run_suite(self, **overrides): env = { **os.environ, "SCRIPT": str(SCRIPT), - "GITHUB_ACTION_PATH": str(SCRIPT.parent), "SUITE_TMP": str(self.root), "GITHUB_WORKSPACE": str(self.root), "RESERVE_RPC_PORT": "false", @@ -33,7 +26,6 @@ def run_suite(self, report="passed", **overrides): "LD_LIBRARY_PATH": "/test/lib", "EXISTING_PORTS": "", "CTEST_STATUS": "0", - "CTEST_REPORT_XML": f"{body}", } # An inherited workflow setting must not affect the unset-value case. env.pop("CTEST_LABEL_EXCLUDE", None) @@ -56,13 +48,6 @@ def run_suite(self, report="passed", **overrides): printf '%s\\0' "$@" > "$SUITE_TMP/ctest.args" printf '%s\\0' "$PWD" "$LD_LIBRARY_PATH" "$MC_METADATA_SERVER" \\ "$DEFAULT_KV_LEASE_TTL" > "$SUITE_TMP/ctest.env" - while [ "$#" -gt 0 ]; do - if [ "$1" = --output-junit ]; then - printf '%s' "$CTEST_REPORT_XML" > "$2" - break - fi - shift - done return "$CTEST_STATUS" } source "$SCRIPT" @@ -85,13 +70,7 @@ def test_unset_or_empty_filter_preserves_default_sweep(self): self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual( self.recorded("ctest.args"), - [ - "--parallel", - "6", - "--output-on-failure", - "--output-junit", - str(self.root / "build/test-results/ctest.xml"), - ], + ["--parallel", "6", "--output-on-failure"], ) self.assertEqual( self.recorded("ctest.env"), @@ -111,15 +90,7 @@ def test_label_regex_is_one_literal_argument(self): self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual( self.recorded("ctest.args"), - [ - "--parallel", - "6", - "--output-on-failure", - "--label-exclude", - regex, - "--output-junit", - str(self.root / "build/test-results/ctest.xml"), - ], + ["--parallel", "6", "--output-on-failure", "--label-exclude", regex], ) def test_junit_report_and_filter_coexist(self): @@ -135,17 +106,6 @@ def test_junit_report_and_filter_coexist(self): self.assertEqual(args[args.index("--label-exclude") + 1], "^nvlink_gpu$") self.assertTrue((self.root / report).parent.is_dir()) - def test_ctest_report_must_contain_successful_cases(self): - for report in ("empty", "failure"): - with self.subTest(report=report): - result = self.run_suite(report=report) - self.assertNotEqual(result.returncode, 0) - self.assertIn("ctest.xml", result.stderr) - - def test_ctest_report_allows_skipped_cases(self): - result = self.run_suite(report="skipped") - self.assertEqual(result.returncode, 0, result.stderr) - def test_port_reservation_preserves_existing_ports(self): for existing in ("", "12345,23456-23460"): with self.subTest(existing=existing): diff --git a/scripts/ci/tests/test_xpu_ci.py b/scripts/ci/tests/test_xpu_ci.py index bb8391772db..f8413f8049e 100644 --- a/scripts/ci/tests/test_xpu_ci.py +++ b/scripts/ci/tests/test_xpu_ci.py @@ -61,15 +61,60 @@ def hardware_step(name): class HostReportTest(unittest.TestCase): - def test_workflow_uses_strict_shared_report_validation(self): + def test_workflow_uses_xpu_report_validation(self): script = workflow_step("Run host-side unit tests") - self.assertIn( - "python scripts/ci/check_test_reports.py --require-gtest-status", script - ) + self.assertIn("python scripts/e2e/python/verify_xpu_ci.py reports", script) self.assertNotIn("--allow-skipped", script) for name in ("config", "ep", "crc32c"): self.assertIn(f"xpu-ci-output/reports/{name}.xml", script) + def test_reports_command(self): + completed = ( + '' + ) + for case, success in ( + (completed, True), + ("", False), + ('', False), + (completed.replace("/>", ">"), False), + (completed.replace("/>", ">"), False), + (completed.replace("/>", ">"), False), + (completed.replace('result="completed"', 'result="skipped"'), False), + ( + completed.replace( + 'status="run" result="completed"', + 'status="notrun" result="suppressed"', + ), + False, + ), + ): + with self.subTest(case=case), tempfile.TemporaryDirectory() as directory: + valid = Path(directory) / "valid.xml" + report = Path(directory) / "report.xml" + valid.write_text( + f"{completed}" + ) + report.write_text( + f"{case}" + ) + result = subprocess.run( + [ + sys.executable, + str(Path(VERIFY.__file__)), + "reports", + str(valid), + str(report), + ], + capture_output=True, + text=True, + ) + self.assertEqual(result.returncode == 0, success, result.stderr) + + def test_reports_command_requires_reports(self): + with patch.object(sys, "argv", [VERIFY.__file__, "reports"]): + with self.assertRaisesRegex(RuntimeError, "at least one test report"): + VERIFY.cli() + class BuildDirectoryTest(unittest.TestCase): def test_cleanup_defaults_and_explicit_override(self): @@ -307,29 +352,23 @@ def test_unified_trigger_and_matching_artifact_handoff(self): event = E2E_WORKFLOW.get("on", E2E_WORKFLOW.get(True)) self.assertEqual(event["pull_request_target"]["types"], ["labeled"]) self.assertNotIn("synchronize", event["pull_request_target"]["types"]) - self.assertIn("run-e2e-ci", jobs["xpu-authorize"]["if"]) - self.assertIn("workflow_dispatch", jobs["xpu-authorize"]["if"]) + self.assertNotIn("xpu-authorize", jobs) + self.assertIn("run-e2e-ci", jobs["build-wheel-xpu"]["if"]) + self.assertIn("workflow_dispatch", jobs["build-wheel-xpu"]["if"]) self.assertTrue(E2E_WORKFLOW["concurrency"]["cancel-in-progress"]) self.assertFalse((ROOT / ".github/workflows/xpu-core.yml").exists()) - self.assertEqual( - jobs["xpu-authorize"]["steps"][0]["env"], - { - "PR_NUMBER": "${{ inputs.pr_number }}", - "CHECKOUT_SHA": "${{ inputs.pr_sha }}", - }, - ) - self.assertEqual(jobs["build-wheel-xpu"]["needs"], "xpu-authorize") + self.assertNotIn("needs", jobs["build-wheel-xpu"]) self.assertEqual( jobs["build-wheel-xpu"]["with"]["checkout_ref"], - "${{ needs.xpu-authorize.outputs.sha }}", + "${{ inputs.pr_sha || github.event.pull_request.head.sha || github.sha }}", ) self.assertEqual( jobs["xpu-integration-test"]["needs"], - ["xpu-authorize", "build-wheel-xpu"], + "build-wheel-xpu", ) self.assertEqual( jobs["xpu-integration-test"]["with"]["checkout_sha"], - "${{ needs.xpu-authorize.outputs.sha }}", + "${{ inputs.pr_sha || github.event.pull_request.head.sha || github.sha }}", ) for name in ( "artifact_id", @@ -375,16 +414,12 @@ def test_unified_trigger_and_matching_artifact_handoff(self): "integration-test", "rocm-integration-test", "integration-test-tent", - "xpu-authorize", "build-wheel-xpu", "xpu-integration-test", }, ) self.assertIn("always()", jobs["e2e-gate"]["if"]) - self.assertEqual( - jobs["e2e-gate"]["permissions"]["checks"], - "write", - ) + self.assertNotIn("permissions", jobs["e2e-gate"]) self.assertNotIn("continue-on-error", jobs["e2e-gate"]["steps"][0]) self.assertEqual(jobs["cleanup-label"]["needs"], ["e2e-gate"]) integration = yaml.safe_load( @@ -404,176 +439,9 @@ def test_unified_trigger_and_matching_artifact_handoff(self): ) ) - def run_javascript(self, job, environment, state): - script = next( - step["with"]["script"] - for step in E2E_WORKFLOW["jobs"][job]["steps"] - if "script" in step.get("with", {}) - ) - harness = r""" - const state = JSON.parse(process.env.TEST_STATE); - const context = { - repo: {owner: 'owner', repo: 'repo'}, actor: 'maintainer', - ref: state.ref || 'refs/heads/main', eventName: state.event || 'workflow_dispatch', - sha: state.sha || 'c'.repeat(40), - payload: state.payload || {}, serverUrl: 'https://github.com', runId: 123 - }; - const outputs = {}; - const core = { - setOutput: (key, value) => outputs[key] = value, - setFailed: message => { throw new Error(message); }, - summary: {addRaw() {return this;}, async write() {}} - }; - const github = {rest: { - repos: { - getCollaboratorPermissionLevel: async () => ({data: {permission: state.permission || 'write'}}), - getCommit: async ({ref}) => ({data: {sha: state.commit || ref}}) - }, - pulls: {get: async () => ({data: { - state: state.pullState || 'open', base: {ref: state.base || 'main'}, - head: {sha: state.head} - }})}, - checks: { - create: async request => { outputs.created = request; return {data: {id: 456}}; }, - update: async request => { outputs.check = request; } - } - }}; - (async () => { - SCRIPT - })().then(() => console.log(JSON.stringify(outputs))) - .catch(error => { - console.log(JSON.stringify(outputs)); - console.error(error.message); - process.exitCode = 1; - }); - """ - return subprocess.run( - ["node", "-e", harness.replace("SCRIPT", script)], - env={**os.environ, **environment, "TEST_STATE": json.dumps(state)}, - capture_output=True, - text=True, - timeout=10, - ) - - def test_authorization_and_stale_head(self): - sha = "a" * 40 - environment = {"PR_NUMBER": "1", "CHECKOUT_SHA": sha} - for state, valid in ( - ({"head": sha}, True), - ({"head": sha, "permission": "maintain"}, True), - ({"head": sha, "permission": "admin"}, True), - ({"head": sha, "permission": "read"}, False), - ({"head": "b" * 40}, False), - ({"head": sha, "ref": "refs/heads/untrusted"}, False), - ({"head": sha, "pullState": "closed"}, False), - ({"head": sha, "base": "release"}, False), - ({"head": sha, "commit": "b" * 40}, False), - ( - { - "head": sha, - "event": "pull_request_target", - "payload": {"pull_request": {"number": 1, "head": {"sha": sha}}}, - }, - True, - ), - ( - { - "head": sha, - "event": "pull_request_target", - "payload": { - "pull_request": {"number": 1, "head": {"sha": "b" * 40}} - }, - }, - False, - ), - ): - with self.subTest(state=state): - result = self.run_javascript("xpu-authorize", environment, state) - self.assertEqual(result.returncode == 0, valid, result.stderr) - if valid: - outputs = json.loads(result.stdout) - self.assertEqual(outputs["sha"], sha) - self.assertEqual(outputs["created"]["head_sha"], sha) - - def test_dispatch_revision_selection(self): - sha = "a" * 40 - for environment, state, expected in ( - ({"PR_NUMBER": "", "CHECKOUT_SHA": ""}, {"sha": sha}, sha), - ({"PR_NUMBER": "", "CHECKOUT_SHA": sha}, {}, sha), - ({"PR_NUMBER": "1", "CHECKOUT_SHA": ""}, {"head": sha}, sha), - ({"PR_NUMBER": "", "CHECKOUT_SHA": "main"}, {}, None), - ({"PR_NUMBER": "01", "CHECKOUT_SHA": sha}, {}, None), - ( - {"PR_NUMBER": "", "CHECKOUT_SHA": ""}, - {"ref": "refs/heads/untrusted", "sha": sha}, - None, - ), - ): - with self.subTest(environment=environment, state=state): - result = self.run_javascript("xpu-authorize", environment, state) - self.assertEqual( - result.returncode == 0, expected is not None, result.stderr - ) - if expected is not None: - self.assertEqual(json.loads(result.stdout)["sha"], expected) - - def test_gate_requires_success_and_current_head(self): - sha = "a" * 40 - for job in ("xpu-authorize", "build-wheel-xpu", "xpu-integration-test"): - for status in ("success", "failure", "cancelled", "skipped", "missing"): - needs = { - "xpu-authorize": { - "result": "success", - "outputs": {"sha": sha, "pr": "1", "check_id": "456"}, - }, - "build-wheel-xpu": { - "result": "success", - "outputs": {"source_sha": sha}, - }, - "xpu-integration-test": {"result": "success"}, - } - if status == "missing": - del needs[job] - else: - needs[job]["result"] = status - for head in (sha, "b" * 40): - with self.subTest(job=job, status=status, head=head): - completed = self.run_javascript( - "e2e-gate", - {"NEEDS_JSON": json.dumps(needs)}, - {"head": head}, - ) - valid = status == "success" and head == sha - self.assertEqual( - completed.returncode == 0, valid, completed.stderr - ) - if job != "xpu-authorize" or status == "success": - check = json.loads(completed.stdout)["check"] - self.assertEqual( - check["conclusion"], "success" if valid else "failure" - ) - - def test_gate_rejects_mismatched_or_missing_build_sha(self): - sha = "a" * 40 - for build_outputs in ({}, {"source_sha": "b" * 40}): - needs = { - "xpu-authorize": { - "result": "success", - "outputs": {"sha": sha, "pr": "1", "check_id": "456"}, - }, - "build-wheel-xpu": {"result": "success", "outputs": build_outputs}, - "xpu-integration-test": {"result": "success"}, - } - with self.subTest(build_outputs=build_outputs): - result = self.run_javascript( - "e2e-gate", {"NEEDS_JSON": json.dumps(needs)}, {"head": sha} - ) - self.assertNotEqual(result.returncode, 0) - self.assertIn("build SHA differs", result.stderr) - def test_shared_gate_still_checks_other_platforms(self): steps = E2E_WORKFLOW["jobs"]["e2e-gate"]["steps"] - self.assertEqual(steps[0]["uses"], "actions/github-script@v7") + self.assertEqual(len(steps), 1) step = next(step for step in steps if step["name"] == "Check E2E results") script = re.sub(r"\$\{\{.*?\}\}", "fixture", step["run"]) for status in ("success", "failure", "cancelled", "skipped"): diff --git a/scripts/e2e/python/verify_xpu_ci.py b/scripts/e2e/python/verify_xpu_ci.py index 2839470efcf..106d60e32c0 100644 --- a/scripts/e2e/python/verify_xpu_ci.py +++ b/scripts/e2e/python/verify_xpu_ci.py @@ -23,8 +23,37 @@ from verify_rocm_wheel import find_extension_record, record_digest -sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "ci")) -validate_report = importlib.import_module("check_test_reports").validate_report + +def validate_report( + path: str | Path, + expected: set[str] | None = None, + require_gtest_status: bool = False, +) -> None: + report = Path(path) + cases = ET.parse(report).findall(".//testcase") + if not cases: + raise RuntimeError(f"{report}: no tests executed") + if expected is not None: + identities = [f"{case.get('classname')}.{case.get('name')}" for case in cases] + if len(identities) != len(expected) or set(identities) != expected: + raise RuntimeError(f"{report}: test identity mismatch: {identities}") + for case in cases: + status = case.get("status") + result = case.get("result") + skipped = case.find("skipped") is not None or (status, result) in { + ("run", "skipped"), + ("notrun", "suppressed"), + } + if any(case.find(tag) is not None for tag in ("failure", "error")): + raise RuntimeError(f"{report}: test did not pass: {case.attrib}") + if skipped: + raise RuntimeError(f"{report}: test was skipped: {case.attrib}") + if require_gtest_status: + completed = (status, result) == ("run", "completed") + else: + completed = status in (None, "run") and result in (None, "completed") + if not completed: + raise RuntimeError(f"{report}: test did not pass: {case.attrib}") def main() -> None: @@ -693,6 +722,10 @@ def cli() -> None: store_test(*(Path(arg) for arg in args)) elif mode == "seccomp": prepare_seccomp(Path(args[0])) + elif mode == "reports": + require(bool(args), "Expected at least one test report") + for report in args: + validate_report(report, require_gtest_status=True) else: raise RuntimeError(f"Unknown XPU verification command: {mode}") diff --git a/scripts/xpu/README.md b/scripts/xpu/XPU_CI.md similarity index 77% rename from scripts/xpu/README.md rename to scripts/xpu/XPU_CI.md index 87f213e865f..2216d19e1bb 100644 --- a/scripts/xpu/README.md +++ b/scripts/xpu/XPU_CI.md @@ -1,9 +1,9 @@ -# XPU hardware core (Stage 2) +# XPU CI -Stage 1 builds a CPython 3.12 wheel and matching native tests on hosted CPU -runners. Stage 2 consumes that exact artifact on a fixed two-B60 allocation. -It does not build while holding GPUs, use models, publish wheels, or enable -nightly hardware/application coverage (Stage 3). +The hosted build creates a CPython 3.12 wheel and matching native tests on CPU +runners. The hardware job consumes that exact artifact on a fixed two-B60 +allocation. It does not build while holding GPUs, use models, publish wheels, +or run nightly hardware/application tests. ## Runner contract @@ -58,7 +58,7 @@ EP's oneCCL KVS also excludes loopback during automatic discovery, so CI sets additional runner-service settings. XCCL and the native Level Zero IPC fast path remain enabled; no network access or fallback-only coverage is introduced. -The runtime uses the same digest-pinned Intel PyTorch image as Stage 1. +The runtime uses the same digest-pinned Intel PyTorch image as the hosted build. Provision compatible Intel GPU drivers and matching SYCL/Level Zero runtimes; dependency loading, wheel RECORD/native capabilities, and real GPU arithmetic are checked before the suites. The hosted builder also downloads the wheel's @@ -70,18 +70,19 @@ Level Zero runtime is added to the Mooncake wheel. ## Trigger and revision binding -After these workflows are available on upstream `main`, a maintainer with -write/maintain/admin permission can add `run-e2e-ci` to an open PR targeting -`main`. The shared **E2E CI** entry point runs XPU alongside the existing ROCm, +After these workflows are available on upstream `main`, adding `run-e2e-ci` +to a PR targeting `main` triggers the shared **E2E CI** entry point. +It runs XPU alongside the existing ROCm, Ascend and other integration jobs; XPU is required, not an optional selection. The existing E2E label cleanup removes the label after the gate; add it again -to rerun. A new PR head needs new authorization; leaving the label attached -does not authorize later pushes. - -Alternatively dispatch **E2E CI** on trusted `main`, supplying `pr_number` -(current head) and optionally `pr_sha` (must match), or a full 40-character -`pr_sha` without a PR. With neither input, XPU tests the dispatch's `main` -commit. No branch names or implicit latest artifacts are accepted. +to rerun. Leaving the label attached does not trigger runs on later pushes. +Execution permissions and hardware access are managed through GitHub settings, +not custom workflow authorization logic. + +Alternatively dispatch **E2E CI**, supplying a full 40-character `pr_sha` +to test a specific revision. `pr_number` alone does not select a PR revision. +Without `pr_sha`, XPU tests the dispatch's commit. Label-triggered runs use +the PR head SHA from the GitHub event. Fork PR heads are supported through their commit SHA. The hosted builder receives that exact SHA. Hardware downloads its artifact @@ -89,14 +90,13 @@ by ID in the same run and verifies the API identity, run/attempt, ZIP digest, payload/native hashes, source/image provenance, and build/runtime inventories. The host runs the trusted workflow-revision harness, not PR host scripts. -The shared `E2E Gate` requires XPU authorization, build, hardware tests and -cleanup to succeed. Its hosted-only XPU step publishes the `XPU Core` check -on the authorized commit, rechecking the PR head and build SHA before success. -Failed, cancelled, skipped, missing or stale required XPU results cannot pass. -The existing E2E concurrency policy cancels older runs for the same PR; -an interrupted controller can leave an in-progress check, never a successful -check. Other platforms retain their existing jobs and gate policy. -The normal Stage 1 hosted build remains independent and required by the +The shared `E2E Gate` includes the XPU build and hardware job results using +the existing gate policy. Cleanup failure fails the hardware job. +Results are reported through the standard GitHub Actions job checks; there +is no separately published `XPU Core` check or PR-head API lookup. +The existing E2E concurrency policy cancels older runs for the same PR. +Other platforms retain their existing jobs and gate policy. +The normal hosted build remains independent and required by the existing PR CI gate. Nightly still builds only the XPU artifact, without running XPU hardware tests. @@ -138,19 +138,16 @@ after failure or cancellation. CPU-only regression validation: ```sh -python3 -m unittest scripts.ci.tests.test_xpu_ci \ - scripts.ci.tests.test_run_ctest -v +python3 -m unittest scripts.ci.tests.test_xpu_ci -v ``` XPU CI regressions share one test module and common workflow/module loaders; they validate packaging and orchestration contracts, not actual B60 behavior. -Shared XML report validation lives in `scripts/ci/check_test_reports.py`. +XPU XML report validation lives in `scripts/e2e/python/verify_xpu_ci.py`. Both the hosted XPU tests and hardware suites require GoogleTest's explicit `run`/`completed` status and reject skipped cases. Hardware suites additionally -pass their expected case identities to the same validator. The shared CTest -action and TENT CI also use it for JUnit reports, preserving CTest's existing -skip policy via `--allow-skipped`. Targeted CTest steps without XML reports -retain their native exit-code and `--no-tests=error` checks. +pass their expected case identities to the same validator. Shared CTest and +TENT CI retain their existing report and exit-code behavior. Docker launch, device mapping, traps and cleanup are inline in `.github/workflows/integration-test-xpu.yml`. A temporary cleanup helper is @@ -159,7 +156,8 @@ the exit trap and the `always()` cleanup recheck; it is not mounted into the test container. `scripts/e2e/python/verify_xpu_ci.py` is the single verification entry point: -no arguments retain the hosted wheel smoke checks; `unpack` verifies the +no arguments retain the hosted wheel smoke checks; `reports ` validates +host-side GoogleTest reports with strict status checks, `unpack` verifies the downloaded artifact, `seccomp` prepares the pinned profile, and `run` installs the wheel offline and launches the `suite`/`store` hardware checks. There are no separate XPU runtime scripts under `scripts/ci/`. From fe71fab4c27a54e2c0a08c493f9b7b6ef35de0f9 Mon Sep 17 00:00:00 2001 From: VincyZhang Date: Fri, 13 Nov 2026 03:12:34 +0000 Subject: [PATCH 4/6] [CI/Build] Harden XPU library paths and clarify SHA validation Signed-off-by: VincyZhang --- .github/workflows/integration-test-xpu.yml | 2 +- scripts/ci/tests/test_xpu_ci.py | 22 ++++++++++++++++++++++ scripts/e2e/python/verify_xpu_ci.py | 9 ++++++--- 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/.github/workflows/integration-test-xpu.yml b/.github/workflows/integration-test-xpu.yml index a15857943b9..62df61b8d90 100644 --- a/.github/workflows/integration-test-xpu.yml +++ b/.github/workflows/integration-test-xpu.yml @@ -78,7 +78,7 @@ jobs: run: | set -euo pipefail [[ "$ARTIFACT_ID" =~ ^[0-9]+$ ]] || { echo "::error::Invalid artifact ID"; exit 1; } - [[ "$CHECKOUT_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "::error::Invalid source SHA"; exit 1; } + [[ "$CHECKOUT_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "::error::Invalid checkout SHA"; exit 1; } [ "$SOURCE_SHA" = "$CHECKOUT_SHA" ] || { echo "::error::Build SHA differs from requested SHA"; exit 1; } gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID" > "$RUN_DIRECTORY/artifact.json" gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID/zip" > "$RUN_DIRECTORY/artifact.zip" diff --git a/scripts/ci/tests/test_xpu_ci.py b/scripts/ci/tests/test_xpu_ci.py index f8413f8049e..72f8aaf299f 100644 --- a/scripts/ci/tests/test_xpu_ci.py +++ b/scripts/ci/tests/test_xpu_ci.py @@ -469,6 +469,28 @@ def test_shared_gate_still_checks_other_platforms(self): class CommandLineTest(unittest.TestCase): + def test_run_library_path_excludes_empty_components(self): + for previous in (None, "", "/existing/lib", "/first::/second:"): + with ( + self.subTest(previous=previous), + tempfile.TemporaryDirectory() as directory, + patch.dict(os.environ), + patch.object(VERIFY, "verify_hashes"), + patch.object(VERIFY, "extract_native") as extract, + patch.object(VERIFY, "command"), + ): + root = Path(directory) + (root / "test.whl").touch() + extract.return_value = root / "native" + if previous is None: + os.environ.pop("LD_LIBRARY_PATH", None) + else: + os.environ["LD_LIBRARY_PATH"] = previous + VERIFY.run(root, root / "source", root / "output") + expected = [str(root / "native/lib"), str(Path(sys.prefix) / "lib")] + expected.extend(path for path in (previous or "").split(":") if path) + self.assertEqual(os.environ["LD_LIBRARY_PATH"].split(":"), expected) + def test_no_arguments_preserve_host_only_wheel_checks(self): with ( patch.object(sys, "argv", ["verify_xpu_ci.py"]), diff --git a/scripts/e2e/python/verify_xpu_ci.py b/scripts/e2e/python/verify_xpu_ci.py index 106d60e32c0..bbccf05ae0e 100644 --- a/scripts/e2e/python/verify_xpu_ci.py +++ b/scripts/e2e/python/verify_xpu_ci.py @@ -530,9 +530,12 @@ def run(bundle: Path, source: Path, output: Path) -> None: verify_hashes(bundle, {"provenance.txt"}) native = extract_native(bundle, output) # Intel PyTorch ships SYCL/UR in its interpreter prefix, not ldconfig. - os.environ["LD_LIBRARY_PATH"] = ( - f"{native / 'lib'}:{Path(sys.prefix) / 'lib'}:{os.environ.get('LD_LIBRARY_PATH', '')}" - ) + library_paths = [ + str(native / "lib"), + str(Path(sys.prefix) / "lib"), + *os.environ.get("LD_LIBRARY_PATH", "").split(":"), + ] + os.environ["LD_LIBRARY_PATH"] = ":".join(path for path in library_paths if path) python = sys.executable wheel = next(bundle.glob("*.whl")) command( From d9707694f0ac3848ea2439a35964e403ca77e4a2 Mon Sep 17 00:00:00 2001 From: VincyZhang Date: Mon, 16 Nov 2026 05:56:02 +0000 Subject: [PATCH 5/6] [CI/Build] Extract trusted XPU core runner and address review feedback Move host preflight, Docker execution, exit traps and cleanup rechecks into the trusted run_core.sh entry points, with mocked-command lifecycle regressions. Restrict compiler-cache credential setup to push/schedule builds without an external revision. Correct IPC parameterized identities and document the 152-case native inventory. Signed-off-by: VincyZhang --- .github/workflows/ci_xpu.yml | 7 +- .github/workflows/integration-test-xpu.yml | 120 +------ scripts/ci/tests/test_xpu_ci.py | 379 +++++++++++++-------- scripts/e2e/python/verify_xpu_ci.py | 20 +- scripts/xpu/XPU_CI.md | 21 +- scripts/xpu/run_core.sh | 127 +++++++ 6 files changed, 397 insertions(+), 277 deletions(-) create mode 100644 scripts/xpu/run_core.sh diff --git a/.github/workflows/ci_xpu.yml b/.github/workflows/ci_xpu.yml index 7c781fc7e68..ed6bcaac8ce 100644 --- a/.github/workflows/ci_xpu.yml +++ b/.github/workflows/ci_xpu.yml @@ -45,8 +45,8 @@ jobs: BUILD_DIR: build-xpu-ci OUTPUT_DIR: dist-xpu-ci DEBIAN_FRONTEND: noninteractive - SCCACHE_GHA_ENABLED: "true" - # Match the other wheel builders: PRs read shared entries but do not evict them. + SCCACHE_GHA_ENABLED: ${{ inputs.checkout_ref == '' && (github.event_name == 'push' || github.event_name == 'schedule') }} + ENABLE_SCCACHE: ${{ inputs.checkout_ref == '' && (github.event_name == 'push' || github.event_name == 'schedule') && 'ON' || 'OFF' }} SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' || github.event_name == 'schedule') && 'READ_WRITE' || 'READ_ONLY' }} steps: # As in ROCm CI, git must exist before checkout to avoid a source tarball. @@ -88,6 +88,7 @@ jobs: "$RUNNER_TEMP/xpu-build-env/bin/python" -m pip install numpy==2.5.4 - name: Set up compiler cache + if: inputs.checkout_ref == '' && (github.event_name == 'push' || github.event_name == 'schedule') uses: ./.github/actions/setup-sccache - name: Configure and build project @@ -107,7 +108,7 @@ jobs: cmake -G Ninja -S . -B "$BUILD_DIR" \ -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx \ -DPython3_EXECUTABLE="$(command -v python)" \ - -DCMAKE_BUILD_TYPE=Release -DENABLE_DEBUG_SYMBOLS=OFF -DENABLE_SCCACHE=ON \ + -DCMAKE_BUILD_TYPE=Release -DENABLE_DEBUG_SYMBOLS=OFF -DENABLE_SCCACHE="$ENABLE_SCCACHE" \ -DUSE_XPU=ON -DUSE_TENT=ON -DUSE_CUDA=OFF -DUSE_XPU_GDS=OFF \ -DWITH_EP=ON -DMOONCAKE_EP_XPU_AOT_DEVICES=bmg \ -DWITH_STORE=ON -DWITH_STORE_RUST=OFF -DWITH_STORE_RS=OFF \ diff --git a/.github/workflows/integration-test-xpu.yml b/.github/workflows/integration-test-xpu.yml index 62df61b8d90..3cfd2be4e72 100644 --- a/.github/workflows/integration-test-xpu.yml +++ b/.github/workflows/integration-test-xpu.yml @@ -44,26 +44,6 @@ jobs: set -euo pipefail directory=$(mktemp -d "$RUNNER_TEMP/xpu-core.XXXXXX") echo "directory=$directory" >> "$GITHUB_OUTPUT" - cat > "$directory/cleanup.sh" <<'SH' - fail() { echo "::error::$*" >&2; exit 1; } - - cleanup_container() { - local status=0 - docker stop --time 10 "$container_id" || status=1 - docker inspect "$container_id" > "$run_directory/output/container-final.json" || status=1 - if [ "$(docker inspect --format '{{.State.Running}}' "$container_id")" != false ]; then - echo "Container processes were not released" >&2 - status=1 - fi - docker rm "$container_id" || status=1 - docker info >/dev/null || status=1 - if docker inspect "$container_id" >/dev/null 2>&1; then - echo "Current run container was not removed" >&2 - status=1 - fi - return "$status" - } - SH - name: Download exact build artifact shell: bash @@ -98,90 +78,7 @@ jobs: RUN_DIRECTORY: ${{ steps.run.outputs.directory }} CHECKOUT_SHA: ${{ inputs.checkout_sha }} run: | - set -euo pipefail - [ "$(git -C xpu-tested-source rev-parse HEAD)" = "$CHECKOUT_SHA" ] || { - echo "::error::Checked out source differs from requested SHA"; exit 1; - } - run_directory=$(realpath "$RUN_DIRECTORY") - source_directory=$(realpath "$GITHUB_WORKSPACE/xpu-tested-source") - control_directory=$(realpath "$GITHUB_WORKSPACE/xpu-control/scripts") - source "$run_directory/cleanup.sh" - mkdir -p "$run_directory/output" - exec > >(tee "$run_directory/output/runner.log") 2>&1 - - [ "$(id -u)" -ne 0 ] || { echo "XPU runner must not run as root" >&2; exit 1; } - : "${ZE_AFFINITY_MASK:?Set a host-owned two-GPU ZE_AFFINITY_MASK}" - : "${XPU_IMAGE:?Missing pinned runtime image}" - : "${CHECKOUT_SHA:?Missing requested SHA}" - [[ "$ZE_AFFINITY_MASK" =~ ^(0|[1-9][0-9]*),(0|[1-9][0-9]*)$ ]] || { - echo "ZE_AFFINITY_MASK must select two whole devices, not subdevices" >&2; exit 1; - } - [ "${BASH_REMATCH[1]}" != "${BASH_REMATCH[2]}" ] || fail "Affinity must select distinct GPUs" - [[ "$XPU_IMAGE" =~ @sha256:[0-9a-f]{64}$ ]] || fail "Runtime image must be digest-pinned" - for command in docker python3 timeout; do - command -v "$command" >/dev/null || fail "Missing runner command: $command" - done - - # Preserve host GPU ordinals for fixed masks; the mask is not security isolation. - shopt -s nullglob - devices=(/dev/dri/renderD*) - [ "${#devices[@]}" -ge 2 ] || fail "At least two GPU render nodes are required" - device_args=() - for device in "${devices[@]}"; do - [[ "$device" =~ ^/dev/dri/renderD[0-9]+$ ]] && [ -c "$device" ] \ - || fail "Not a GPU render character device: $device" - device_args+=(--device "$device" --group-add "$(stat -c %g "$device")") - done - python3 "$control_directory/e2e/python/verify_xpu_ci.py" seccomp "$run_directory/output/seccomp.json" - - container_id= - cleanup() { - local status=$? cleanup_status=0 - trap - EXIT INT TERM - if [ -n "$container_id" ]; then - cleanup_container || cleanup_status=1 - fi - printf '{"cleanup_status":%d,"suite_status":%d}\n' "$cleanup_status" "$status" \ - > "$run_directory/output/cleanup.json" - if [ "$cleanup_status" -ne 0 ]; then exit 1; fi - exit "$status" - } - trap cleanup EXIT - trap 'exit 130' INT - trap 'exit 143' TERM - - docker pull "$XPU_IMAGE" - docker image inspect "$XPU_IMAGE" > "$run_directory/output/image.json" - container_id=$(docker create \ - --label "mooncake.xpu.run=$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" \ - --user "$(id -u):$(id -g)" --cap-drop ALL \ - --security-opt no-new-privileges \ - --security-opt "seccomp=$run_directory/output/seccomp.json" \ - --network none --ipc private --shm-size 2g \ - --pids-limit 1024 --ulimit core=0 \ - "${device_args[@]}" \ - --mount "type=bind,src=$run_directory/bundle,dst=/bundle,readonly" \ - --mount "type=bind,src=$source_directory,dst=/source,readonly" \ - --mount "type=bind,src=$control_directory,dst=/control,readonly" \ - --mount "type=bind,src=$run_directory/output,dst=/output" \ - --env "ZE_AFFINITY_MASK=$ZE_AFFINITY_MASK" \ - --env ONEAPI_DEVICE_SELECTOR=level_zero:gpu \ - --env ZE_FLAT_DEVICE_HIERARCHY=FLAT \ - --env MC_USE_TENT=1 --env MOONCAKE_STORE_BACKEND=cpp \ - --env PROTOCOL=tcp --env MC_METADATA_SERVER=P2PHANDSHAKE \ - --env LOCAL_HOSTNAME=127.0.0.1 --env MASTER_SERVER=127.0.0.1:50051 \ - --env MOONCAKE_LOCAL_HOSTNAME=127.0.0.1 \ - --env CCL_KVS_IFACE=lo --env GLOO_SOCKET_IFNAME=lo \ - --env PYTHONOPTIMIZE=0 --env PYTHONDONTWRITEBYTECODE=1 \ - --env TEST_TMPDIR=/output \ - --env "XPU_SOURCE_SHA=$CHECKOUT_SHA" --env "XPU_IMAGE=$XPU_IMAGE" \ - --env HOME=/tmp/home --workdir /tmp \ - --entrypoint /bin/bash "$XPU_IMAGE" -c ' - set -eo pipefail - mkdir -p "$HOME" - python3 /control/e2e/python/verify_xpu_ci.py run /bundle /source /output - ') - timeout --signal=TERM --kill-after=30s 70m docker start --attach "$container_id" + bash xpu-control/scripts/xpu/run_core.sh run - name: Recheck current-run container cleanup if: always() && steps.run.outputs.directory != '' @@ -189,20 +86,7 @@ jobs: env: RUN_DIRECTORY: ${{ steps.run.outputs.directory }} run: | - set -euo pipefail - run_directory=$(realpath "$RUN_DIRECTORY") - source "$run_directory/cleanup.sh" - mkdir -p "$run_directory/output" - remaining=$(docker ps -aq --no-trunc \ - --filter "label=mooncake.xpu.run=$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT") - docker info >/dev/null - if [ -n "$remaining" ]; then - while read -r container_id; do - [[ "$container_id" =~ ^[0-9a-f]{64}$ ]] || fail "Invalid current-run container ID" - cleanup_container - done <<< "$remaining" - fi - echo '{"cleanup_recheck":"passed"}' > "$run_directory/output/cleanup-recheck.json" + bash xpu-control/scripts/xpu/run_core.sh cleanup - name: Preserve hardware diagnostics if: always() && steps.run.outputs.directory != '' diff --git a/scripts/ci/tests/test_xpu_ci.py b/scripts/ci/tests/test_xpu_ci.py index 72f8aaf299f..3f552a6f039 100644 --- a/scripts/ci/tests/test_xpu_ci.py +++ b/scripts/ci/tests/test_xpu_ci.py @@ -22,6 +22,7 @@ ROOT = Path(__file__).resolve().parents[3] +CORE_SCRIPT = ROOT / "scripts/xpu/run_core.sh" def load_script(name, path): @@ -263,6 +264,34 @@ def test_xpu_metadata_and_mutual_exclusion(self): class WorkflowTest(unittest.TestCase): + def test_external_revisions_do_not_receive_shared_cache_credentials(self): + job = WORKFLOW["jobs"]["build-wheel-xpu"] + cache_step = next( + step for step in job["steps"] if step.get("name") == "Set up compiler cache" + ) + trusted = ( + "inputs.checkout_ref == '' && " + "(github.event_name == 'push' || github.event_name == 'schedule')" + ) + self.assertEqual(cache_step["if"], trusted) + self.assertEqual(job["env"]["SCCACHE_GHA_ENABLED"], "${{ " + trusted + " }}") + self.assertEqual( + job["env"]["ENABLE_SCCACHE"], + "${{ " + trusted + " && 'ON' || 'OFF' }}", + ) + self.assertIn( + '-DENABLE_SCCACHE="$ENABLE_SCCACHE"', + workflow_step("Configure and build project"), + ) + self.assertEqual( + [ + step["uses"] + for step in job["steps"] + if step.get("uses", "").startswith("./") + ], + [cache_step["uses"]], + ) + def test_xpu_selection_and_strict_gate_are_wired(self): workflow = yaml.safe_load((ROOT / ".github/workflows/ci.yml").read_text()) jobs = workflow["jobs"] @@ -991,7 +1020,7 @@ def run_command(args, log, timeout=600): self.assertTrue(call.kwargs["require_gtest_status"]) self.assertTrue(call.args[1]) result = json.loads((root / "result.json").read_text()) - self.assertEqual(result["cpp_cases"], 151) + self.assertEqual(result["cpp_cases"], 152) self.assertEqual(result["ep_rounds"], 8) else: with self.assertRaises((RuntimeError, FileNotFoundError)): @@ -1017,23 +1046,34 @@ def test_required_inventory_matches_cpp_sources(self): ("xpu_engine_test.cpp", VERIFY.ENGINE | VERIFY.RDMA), ("xpu_ipc_process_test.cpp", VERIFY.IPC), ): - declared = set( - re.findall( - r"TEST_[FP]\(\s*(\w+),\s*(\w+)\s*\)", (tent / filename).read_text() - ) - ) - selected = { - ( - identity.split(".")[0].split("/")[-1], - identity.split(".")[1].split("/")[0], - ) - for identity in names - } - self.assertEqual(selected, declared, filename) + source = (tent / filename).read_text() + instances = {} + for prefix, suite, generator in re.findall( + r"INSTANTIATE_TEST_SUITE_P\(\s*(\w+),\s*(\w+),\s*" r"(.*?)\);", + source, + re.DOTALL, + ): + booleans = len(re.findall(r"::testing::Bool\(\)", generator)) + self.assertGreater(booleans, 0, generator) + instances.setdefault(suite, []).append((prefix, 2**booleans)) + declared = set() + for kind, suite, name in re.findall( + r"TEST_([FP])\(\s*(\w+),\s*(\w+)\s*\)", source + ): + if kind == "P": + self.assertIn(suite, instances, filename) + for prefix, count in instances[suite]: + declared.update( + VERIFY.case_names(f"{prefix}/{suite}", name, count) + ) + else: + declared.add(f"{suite}.{name}") + self.assertEqual(names, declared, filename) self.assertEqual(len(VERIFY.ENGINE), 124) + self.assertEqual(len(VERIFY.IPC), 10) self.assertEqual(len(VERIFY.INAPPLICABLE), 10) self.assertEqual( - sum(len(selected) for _, selected in VERIFY.SUITES.values()), 151 + sum(len(selected) for _, selected in VERIFY.SUITES.values()), 152 ) selected_engine = VERIFY.SUITES["tent_xpu_engine_test"][1] self.assertFalse(selected_engine & VERIFY.RDMA) @@ -1129,7 +1169,11 @@ def runtime_text(path, *args, **kwargs): class ShellLifecycleTest(unittest.TestCase): - def test_inline_hardware_shell_syntax_and_removed_launchers(self): + def test_hardware_shell_syntax_and_trusted_entry_points(self): + result = subprocess.run( + ["bash", "-n", str(CORE_SCRIPT)], capture_output=True, timeout=10 + ) + self.assertEqual(result.returncode, 0, result.stderr) for step in INTEGRATION["jobs"]["core"]["steps"]: if "run" in step: with self.subTest(step=step["name"]): @@ -1147,6 +1191,83 @@ def test_inline_hardware_shell_syntax_and_removed_launchers(self): "scripts/e2e/python/verify_xpu_ci.py unpack", hardware_step("Download exact build artifact"), ) + for name, command in ( + ("Execute isolated two-B60 core", "run"), + ("Recheck current-run container cleanup", "cleanup"), + ): + self.assertEqual( + hardware_step(name).strip(), + f"bash xpu-control/scripts/xpu/run_core.sh {command}", + ) + cleanup_step = next( + step + for step in INTEGRATION["jobs"]["core"]["steps"] + if step.get("name") == "Recheck current-run container cleanup" + ) + self.assertIn("always()", cleanup_step["if"]) + self.assertNotIn("cleanup.sh", hardware_step("Allocate run directory")) + + def prepare_host(self, root): + run_directory = self.prepare_run(root) + (root / "xpu-tested-source").mkdir() + startup = root / "host-mocks.sh" + startup.write_text( + "compgen() {\n" + ' if [ "${MOCK_DEVICES:-two}" = two ]; then\n' + " printf '/dev/dri/renderD128\\n/dev/dri/renderD129\\n'\n" + " fi\n" + "}\n" + "function [() {\n" + ' if [[ "$1" = -c && "$2" = /dev/dri/renderD* ]]; then\n' + " return 0\n" + " fi\n" + ' builtin [ "$@"\n' + "}\n" + 'id() { echo "${MOCK_UID:-1000}"; }\n' + 'git() { echo "${MOCK_SHA:-$CHECKOUT_SHA}"; }\n' + "stat() { echo 109; }\n" + 'python3() { printf "%s\\n" "$@" > "$RUN_DIRECTORY/python.arguments"; }\n' + "timeout() {\n" + ' printf "%s\\n" "$@" > "$RUN_DIRECTORY/timeout.arguments"\n' + ' if [[ -n "${SUITE_SIGNAL:-}" ]]; then kill -s "$SUITE_SIGNAL" "$BASHPID"; fi\n' + " shift 3\n" + ' "$@"\n' + "}\n" + ) + docker = root / "docker" + docker.write_text( + "#!/bin/bash\n" + "set -eu\n" + 'echo "$*" >> "$RUN_DIRECTORY/docker.commands"\n' + 'case "$1" in\n' + " pull|image|info|stop) exit 0 ;;\n" + " create)\n" + ' printf "%s\\n" "$@" > "$RUN_DIRECTORY/docker.arguments"\n' + " echo owned-container ;;\n" + ' start) exit "${SUITE_STATUS:-0}" ;;\n' + " inspect)\n" + ' [ ! -e "$RUN_DIRECTORY/removed" ] || exit 1\n' + ' [ "${CLEANUP_FAILURE:-no}" != inspect ] || exit 1\n' + ' if [ "${2:-}" = --format ]; then echo false; else echo "{}"; fi ;;\n' + " rm)\n" + ' [ "${CLEANUP_FAILURE:-no}" != yes ] || exit 1\n' + ' touch "$RUN_DIRECTORY/removed" ;;\n' + " *) exit 99 ;;\n" + "esac\n" + ) + docker.chmod(0o755) + return { + **os.environ, + "BASH_ENV": str(startup), + "PATH": f"{root}:{os.environ['PATH']}", + "GITHUB_WORKSPACE": str(root), + "GITHUB_RUN_ID": "123", + "GITHUB_RUN_ATTEMPT": "1", + "XPU_IMAGE": "image@sha256:" + "a" * 64, + "ZE_AFFINITY_MASK": "4,5", + "CHECKOUT_SHA": "b" * 40, + "RUN_DIRECTORY": str(run_directory), + } def prepare_run(self, root): output = root / "github-output" @@ -1165,41 +1286,20 @@ def prepare_run(self, root): return Path(output.read_text().strip().removeprefix("directory=")) def test_network_isolation_sets_store_and_ep_loopback_interfaces(self): - script = hardware_step("Execute isolated two-B60 core") - start = script.index("container_id=$(docker create") - stop = script.index("timeout --signal=TERM", start) - docker_command = script[start:stop] with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) - docker = root / "docker" - docker.write_text("""#!/bin/bash -set -eu -printf '%s\\n' "$@" > "$DOCKER_ARGUMENTS" -echo container-id -""") - docker.chmod(0o755) - arguments = root / "arguments" + environment = self.prepare_host(root) + run_directory = Path(environment["RUN_DIRECTORY"]) result = subprocess.run( - ["bash", "-ec", "device_args=()\n" + docker_command], - env={ - **os.environ, - "PATH": f"{root}:{os.environ['PATH']}", - "DOCKER_ARGUMENTS": str(arguments), - "GITHUB_RUN_ID": "123", - "GITHUB_RUN_ATTEMPT": "1", - "XPU_IMAGE": "image", - "ZE_AFFINITY_MASK": "4,5", - "CHECKOUT_SHA": "a" * 40, - "run_directory": str(root), - "source_directory": str(ROOT), - "control_directory": str(ROOT / "scripts"), - }, + ["bash", str(CORE_SCRIPT), "run"], + cwd=root, + env=environment, capture_output=True, text=True, timeout=10, ) self.assertEqual(result.returncode, 0, result.stderr) - args = arguments.read_text().splitlines() + args = (run_directory / "docker.arguments").read_text().splitlines() self.assertEqual(args[args.index("--network") + 1], "none") for variable in ( "MOONCAKE_LOCAL_HOSTNAME=127.0.0.1", @@ -1212,15 +1312,34 @@ def test_network_isolation_sets_store_and_ep_loopback_interfaces(self): self.assertIn(variable, args) self.assertEqual(args[args.index(variable) - 1], "--env") self.assertNotIn("--privileged", args) + for device in ("/dev/dri/renderD128", "/dev/dri/renderD129"): + self.assertEqual(args[args.index(device) - 1], "--device") + for mount in ( + f"type=bind,src={ROOT / 'scripts'},dst=/control,readonly", + f"type=bind,src={root / 'xpu-tested-source'},dst=/source,readonly", + ): + self.assertIn(mount, args) + self.assertIn("no-new-privileges", args) + self.assertIn("ALL", args) + self.assertIn(f"seccomp={run_directory}/output/seccomp.json", args) + self.assertEqual( + (run_directory / "timeout.arguments").read_text().splitlines(), + [ + "--signal=TERM", + "--kill-after=30s", + "70m", + "docker", + "start", + "--attach", + "owned-container", + ], + ) self.assertIn( "python3 /control/e2e/python/verify_xpu_ci.py run /bundle /source /output", "\n".join(args), ) def test_fixed_runner_masks_need_no_lock_or_profile_variables(self): - script = hardware_step("Execute isolated two-B60 core") - start = script.index(': "${ZE_AFFINITY_MASK:') - stop = script.index("# Preserve host GPU ordinals") for mask, valid in ( ("0,1", True), ("2,3", True), @@ -1232,45 +1351,29 @@ def test_fixed_runner_masks_need_no_lock_or_profile_variables(self): ("0.0,0.1", False), ("", False), ): - environment = { - key: value - for key, value in os.environ.items() - if key - not in { + with self.subTest(mask=mask), tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + environment = self.prepare_host(root) + for key in ( "XPU_LOCK_DIRECTORY", "XPU_SECCOMP_PROFILE", "XPU_RENDER_DEVICES", - } - } - environment.update( - { - "ZE_AFFINITY_MASK": mask, - "XPU_IMAGE": "image@sha256:" + "a" * 64, - "CHECKOUT_SHA": "b" * 40, - } - ) - with self.subTest(mask=mask): + ): + environment.pop(key, None) + environment["ZE_AFFINITY_MASK"] = mask result = subprocess.run( - [ - "bash", - "-ec", - 'fail() { echo "$*" >&2; exit 1; }\n' + script[start:stop], - ], + ["bash", str(CORE_SCRIPT), "run"], + cwd=root, env=environment, capture_output=True, text=True, timeout=10, ) self.assertEqual(result.returncode == 0, valid, result.stderr) - self.assertNotIn("XPU_LOCK_DIRECTORY", script) - self.assertNotIn("XPU_SECCOMP_PROFILE", script) - self.assertNotIn("XPU_RENDER_DEVICES", script) - self.assertNotIn("flock", script) - self.assertIn("devices=(/dev/dri/renderD*)", script) - self.assertIn('--env "ZE_AFFINITY_MASK=$ZE_AFFINITY_MASK"', script) - self.assertIn( - '--security-opt "seccomp=$run_directory/output/seccomp.json"', script - ) + self.assertEqual( + (Path(environment["RUN_DIRECTORY"]) / "docker.arguments").exists(), + valid, + ) def test_cleanup_recheck_propagates_docker_query_failure(self): for query_status in (0, 2): @@ -1290,11 +1393,7 @@ def test_cleanup_recheck_propagates_docker_query_failure(self): """) docker.chmod(0o755) result = subprocess.run( - [ - "bash", - "-ec", - hardware_step("Recheck current-run container cleanup"), - ], + ["bash", str(CORE_SCRIPT), "cleanup"], env={ **os.environ, "PATH": f"{root}:{os.environ['PATH']}", @@ -1314,55 +1413,25 @@ def test_cleanup_recheck_propagates_docker_query_failure(self): ) def test_owned_container_cleanup_and_failures_propagate(self): - script = hardware_step("Execute isolated two-B60 core") - cleanup = ( - 'source "$RUN_DIRECTORY/cleanup.sh"\n' - + script[ - script.index("container_id=\n") : script.index( - 'docker pull "$XPU_IMAGE"' - ) - ] - ) for suite_status, cleanup_failure, expected in ( (0, "no", 0), (2, "no", 2), (0, "yes", 1), + (0, "inspect", 1), ): with self.subTest( suite_status=suite_status, cleanup_failure=cleanup_failure ): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) - run_directory = self.prepare_run(root) - (run_directory / "output").mkdir() - docker = root / "docker" - docker.write_text("""#!/bin/bash -set -eu -echo "$*" >> "$RUN_DIRECTORY/docker.commands" -case "$1" in - info) echo daemon-ready ;; - stop) echo owned-container ;; - inspect) - [ ! -e "$RUN_DIRECTORY/removed" ] || exit 1 - if [ "${2:-}" = --format ]; then echo false; else echo '{}'; fi ;; - rm) - [ "$CLEANUP_FAILURE" = no ] || exit 1 - touch "$RUN_DIRECTORY/removed" ;; - *) exit 99 ;; -esac -""") - docker.chmod(0o755) + environment = self.prepare_host(root) + run_directory = Path(environment["RUN_DIRECTORY"]) result = subprocess.run( - [ - "bash", - "-ec", - f"{cleanup}\ncontainer_id=owned-container\nexit {suite_status}", - ], + ["bash", str(CORE_SCRIPT), "run"], + cwd=root, env={ - **os.environ, - "PATH": f"{root}:{os.environ['PATH']}", - "run_directory": str(run_directory), - "RUN_DIRECTORY": str(run_directory), + **environment, + "SUITE_STATUS": str(suite_status), "CLEANUP_FAILURE": cleanup_failure, }, capture_output=True, @@ -1382,6 +1451,7 @@ def test_owned_container_cleanup_and_failures_propagate(self): self.assertEqual( report["cleanup_status"] == 0, cleanup_failure == "no" ) + self.assertEqual(report["suite_status"], suite_status) def test_cleanup_recheck_removes_only_current_run_container(self): for container_id, valid in (("a" * 64, True), ("invalid-id", False)): @@ -1406,11 +1476,7 @@ def test_cleanup_recheck_removes_only_current_run_container(self): """) docker.chmod(0o755) result = subprocess.run( - [ - "bash", - "-ec", - hardware_step("Recheck current-run container cleanup"), - ], + ["bash", str(CORE_SCRIPT), "cleanup"], env={ **os.environ, "PATH": f"{root}:{os.environ['PATH']}", @@ -1440,22 +1506,11 @@ def test_cleanup_recheck_removes_only_current_run_container(self): def test_host_preflight_rejects_root(self): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) - (root / "output").mkdir() - fake_id = root / "id" - fake_id.write_text("#!/bin/sh\necho 0\n") - fake_id.chmod(0o755) - script = hardware_step("Execute isolated two-B60 core") + environment = self.prepare_host(root) result = subprocess.run( - [ - "bash", - "-ec", - script[script.index("exec >") :], - ], - env={ - **os.environ, - "PATH": f"{root}:{os.environ['PATH']}", - "run_directory": str(root), - }, + ["bash", str(CORE_SCRIPT), "run"], + cwd=root, + env={**environment, "MOCK_UID": "0"}, capture_output=True, text=True, timeout=10, @@ -1463,6 +1518,56 @@ def test_host_preflight_rejects_root(self): self.assertNotEqual(result.returncode, 0) self.assertIn("must not run as root", result.stdout + result.stderr) + def test_preflight_failures_do_not_launch_containers(self): + for overrides, message in ( + ({"MOCK_SHA": "c" * 40}, "source differs"), + ({"XPU_IMAGE": "unpinned:latest"}, "digest-pinned"), + ({"MOCK_DEVICES": "none"}, "At least two GPU"), + ): + with self.subTest( + overrides=overrides + ), tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + environment = self.prepare_host(root) + result = subprocess.run( + ["bash", str(CORE_SCRIPT), "run"], + cwd=root, + env={**environment, **overrides}, + capture_output=True, + text=True, + timeout=10, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn(message, result.stdout + result.stderr) + self.assertFalse( + (Path(environment["RUN_DIRECTORY"]) / "docker.commands").exists() + ) + + def test_signals_preserve_failure_status_and_cleanup(self): + for signal_name, status in (("INT", 130), ("TERM", 143)): + with self.subTest( + signal=signal_name + ), tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + environment = self.prepare_host(root) + run_directory = Path(environment["RUN_DIRECTORY"]) + result = subprocess.run( + ["bash", str(CORE_SCRIPT), "run"], + cwd=root, + env={**environment, "SUITE_SIGNAL": signal_name}, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual( + result.returncode, status, result.stdout + result.stderr + ) + self.assertTrue((run_directory / "removed").exists()) + self.assertEqual( + json.loads((run_directory / "output/cleanup.json").read_text()), + {"cleanup_status": 0, "suite_status": status}, + ) + class SeccompTest(unittest.TestCase): def test_only_required_syscalls_are_unconditionally_allowed(self): diff --git a/scripts/e2e/python/verify_xpu_ci.py b/scripts/e2e/python/verify_xpu_ci.py index bbccf05ae0e..55b234a9d2c 100644 --- a/scripts/e2e/python/verify_xpu_ci.py +++ b/scripts/e2e/python/verify_xpu_ci.py @@ -379,18 +379,14 @@ def case_names(suite: str, names: str, count: int = 0) -> set[str]: } -IPC = ( - case_names( - "SelectionModes/XpuIpcProcessTest", - "DeviceToPeerDeviceReadAndWrite HostToPeerDeviceReadAndWrite", - 2, - ) - | case_names( - "SelectionModes/XpuIpcFallbackTest", - "DeviceToPeerDeviceFallsBackToStaging HostToPeerDeviceFallsBackToStaging", - 2, - ) - | case_names("XpuIpcProcessTest", "MappingClosedWhenPeerExits") +IPC = case_names( + "SelectionModes/XpuIpcProcessTest", + "DeviceToPeerDeviceReadAndWrite HostToPeerDeviceReadAndWrite MappingClosedWhenPeerExits", + 2, +) | case_names( + "SelectionModes/XpuIpcFallbackTest", + "DeviceToPeerDeviceFallsBackToStaging HostToPeerDeviceFallsBackToStaging", + 2, ) diff --git a/scripts/xpu/XPU_CI.md b/scripts/xpu/XPU_CI.md index 2216d19e1bb..a1e2f199b17 100644 --- a/scripts/xpu/XPU_CI.md +++ b/scripts/xpu/XPU_CI.md @@ -89,6 +89,10 @@ The hosted builder receives that exact SHA. Hardware downloads its artifact by ID in the same run and verifies the API identity, run/attempt, ZIP digest, payload/native hashes, source/image provenance, and build/runtime inventories. The host runs the trusted workflow-revision harness, not PR host scripts. +Exact-revision E2E builds do not run the local compiler-cache action or enable +sccache. Cache credentials are exported only for push/schedule builds without +an external checkout revision; a read-only sccache setting is not a credential +boundary for PR-controlled build code. The shared `E2E Gate` includes the XPU build and hardware job results using the existing gate policy. Cleanup failure fails the hardware job. @@ -109,7 +113,8 @@ Core executes sequentially: - 7 XPU transport cases. - 114 engine cases: local copies, TCP/HP-TCP staging (tests explicitly disable IPC for those paths), retry/routing, IPC lifetime/policies, and io_uring. -- 8 real cross-process IPC/fallback cases, including permission-denied peers. +- 10 real cross-process IPC/fallback cases, including permission-denied peers + and mapping cleanup after peer exit in both selection modes. - 1 C++ Store foreign-USM roundtrip with an in-process master. - 1 existing Python Store tensor/registered-buffer roundtrip with a packaged local master. @@ -119,7 +124,7 @@ Core executes sequentially: The existing script asserts native selection and must print its exact final completion record; missing rounds or zero-test execution fail. -The **151 C++ cases** require exact GoogleTest identities and completed XML +The **152 C++ cases** require exact GoogleTest identities and completed XML results. Ten parameter combinations that unconditionally skip because they are inapplicable are excluded *before* execution, with reasons in `selection.json`. No runtime skips are allowed. The eight direct-RDMA @@ -149,11 +154,13 @@ Both the hosted XPU tests and hardware suites require GoogleTest's explicit pass their expected case identities to the same validator. Shared CTest and TENT CI retain their existing report and exit-code behavior. -Docker launch, device mapping, traps and cleanup are inline in -`.github/workflows/integration-test-xpu.yml`. A temporary cleanup helper is -created from that trusted workflow in the host run directory and shared by -the exit trap and the `always()` cleanup recheck; it is not mounted into the -test container. +Host GPU preflight, Docker launch, device mapping, traps and cleanup live in +`scripts/xpu/run_core.sh`, with `run` and `cleanup` subcommands. The workflow +invokes both from `xpu-control`, checked out at `github.workflow_sha`, never +from `xpu-tested-source`. The `run` exit trap cleans its container; the separate +`always()` workflow step calls `cleanup` to recheck containers labeled for the +current run/attempt. No temporary cleanup script is generated. CPU-only +regressions exercise these entry points with mocked host commands. `scripts/e2e/python/verify_xpu_ci.py` is the single verification entry point: no arguments retain the hosted wheel smoke checks; `reports ` validates diff --git a/scripts/xpu/run_core.sh b/scripts/xpu/run_core.sh new file mode 100644 index 00000000000..c24527d753a --- /dev/null +++ b/scripts/xpu/run_core.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +set -euo pipefail + +fail() { echo "::error::$*" >&2; exit 1; } + +cleanup_container() { + local status=0 + docker stop --time 10 "$container_id" || status=1 + docker inspect "$container_id" > "$run_directory/output/container-final.json" || status=1 + if [ "$(docker inspect --format '{{.State.Running}}' "$container_id")" != false ]; then + echo "Container processes were not released" >&2 + status=1 + fi + docker rm "$container_id" || status=1 + docker info >/dev/null || status=1 + if docker inspect "$container_id" >/dev/null 2>&1; then + echo "Current run container was not removed" >&2 + status=1 + fi + return "$status" +} + +cleanup() { + local status=$? cleanup_status=0 + trap - EXIT INT TERM + if [ -n "$container_id" ]; then + cleanup_container || cleanup_status=1 + fi + printf '{"cleanup_status":%d,"suite_status":%d}\n' "$cleanup_status" "$status" \ + > "$run_directory/output/cleanup.json" + if [ "$cleanup_status" -ne 0 ]; then exit 1; fi + exit "$status" +} + +run() { + [ "$(git -C xpu-tested-source rev-parse HEAD)" = "$CHECKOUT_SHA" ] || \ + fail "Checked out source differs from requested SHA" + local source_directory control_directory + source_directory=$(realpath "$GITHUB_WORKSPACE/xpu-tested-source") + control_directory=$(realpath "$(dirname "${BASH_SOURCE[0]}")/..") + exec > >(tee "$run_directory/output/runner.log") 2>&1 + + [ "$(id -u)" -ne 0 ] || fail "XPU runner must not run as root" + : "${ZE_AFFINITY_MASK:?Set a host-owned two-GPU ZE_AFFINITY_MASK}" + : "${XPU_IMAGE:?Missing pinned runtime image}" + : "${CHECKOUT_SHA:?Missing requested SHA}" + [[ "$ZE_AFFINITY_MASK" =~ ^(0|[1-9][0-9]*),(0|[1-9][0-9]*)$ ]] || \ + fail "ZE_AFFINITY_MASK must select two whole devices, not subdevices" + [ "${BASH_REMATCH[1]}" != "${BASH_REMATCH[2]}" ] || fail "Affinity must select distinct GPUs" + [[ "$XPU_IMAGE" =~ @sha256:[0-9a-f]{64}$ ]] || fail "Runtime image must be digest-pinned" + for command in docker python3 timeout; do + command -v "$command" >/dev/null || fail "Missing runner command: $command" + done + + local devices device_args=() device + mapfile -t devices < <(compgen -G '/dev/dri/renderD*' || true) + [ "${#devices[@]}" -ge 2 ] || fail "At least two GPU render nodes are required" + for device in "${devices[@]}"; do + [[ "$device" =~ ^/dev/dri/renderD[0-9]+$ ]] && [ -c "$device" ] \ + || fail "Not a GPU render character device: $device" + device_args+=(--device "$device" --group-add "$(stat -c %g "$device")") + done + python3 "$control_directory/e2e/python/verify_xpu_ci.py" seccomp "$run_directory/output/seccomp.json" + + container_id= + trap cleanup EXIT + trap 'exit 130' INT + trap 'exit 143' TERM + + docker pull "$XPU_IMAGE" + docker image inspect "$XPU_IMAGE" > "$run_directory/output/image.json" + container_id=$(docker create \ + --label "mooncake.xpu.run=$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" \ + --user "$(id -u):$(id -g)" --cap-drop ALL \ + --security-opt no-new-privileges \ + --security-opt "seccomp=$run_directory/output/seccomp.json" \ + --network none --ipc private --shm-size 2g \ + --pids-limit 1024 --ulimit core=0 \ + "${device_args[@]}" \ + --mount "type=bind,src=$run_directory/bundle,dst=/bundle,readonly" \ + --mount "type=bind,src=$source_directory,dst=/source,readonly" \ + --mount "type=bind,src=$control_directory,dst=/control,readonly" \ + --mount "type=bind,src=$run_directory/output,dst=/output" \ + --env "ZE_AFFINITY_MASK=$ZE_AFFINITY_MASK" \ + --env ONEAPI_DEVICE_SELECTOR=level_zero:gpu \ + --env ZE_FLAT_DEVICE_HIERARCHY=FLAT \ + --env MC_USE_TENT=1 --env MOONCAKE_STORE_BACKEND=cpp \ + --env PROTOCOL=tcp --env MC_METADATA_SERVER=P2PHANDSHAKE \ + --env LOCAL_HOSTNAME=127.0.0.1 --env MASTER_SERVER=127.0.0.1:50051 \ + --env MOONCAKE_LOCAL_HOSTNAME=127.0.0.1 \ + --env CCL_KVS_IFACE=lo --env GLOO_SOCKET_IFNAME=lo \ + --env PYTHONOPTIMIZE=0 --env PYTHONDONTWRITEBYTECODE=1 \ + --env TEST_TMPDIR=/output \ + --env "XPU_SOURCE_SHA=$CHECKOUT_SHA" --env "XPU_IMAGE=$XPU_IMAGE" \ + --env HOME=/tmp/home --workdir /tmp \ + --entrypoint /bin/bash "$XPU_IMAGE" -c ' + set -eo pipefail + mkdir -p "$HOME" + python3 /control/e2e/python/verify_xpu_ci.py run /bundle /source /output + ') + timeout --signal=TERM --kill-after=30s 70m docker start --attach "$container_id" +} + +recheck_cleanup() { + local remaining + remaining=$(docker ps -aq --no-trunc \ + --filter "label=mooncake.xpu.run=$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT") + docker info >/dev/null + if [ -n "$remaining" ]; then + while read -r container_id; do + [[ "$container_id" =~ ^[0-9a-f]{64}$ ]] || fail "Invalid current-run container ID" + cleanup_container + done <<< "$remaining" + fi + echo '{"cleanup_recheck":"passed"}' > "$run_directory/output/cleanup-recheck.json" +} + +case "${1:-}" in + run|cleanup) ;; + *) fail "Usage: $0 {run|cleanup}" ;; +esac +run_directory=$(realpath "$RUN_DIRECTORY") +mkdir -p "$run_directory/output" +case "$1" in + run) run ;; + cleanup) recheck_cleanup ;; +esac From 069db9f193be40f4fb0b57da0a3c00905b894aef Mon Sep 17 00:00:00 2001 From: VincyZhang Date: Tue, 17 Nov 2026 13:08:37 +0000 Subject: [PATCH 6/6] [CI/Build] Raise XPU PID limit and capture cgroup diagnostics Signed-off-by: VincyZhang --- scripts/ci/tests/test_xpu_ci.py | 59 +++++++++++++++++++++++++++++++++ scripts/xpu/run_core.sh | 31 ++++++++++++++++- 2 files changed, 89 insertions(+), 1 deletion(-) diff --git a/scripts/ci/tests/test_xpu_ci.py b/scripts/ci/tests/test_xpu_ci.py index 3f552a6f039..a2fa854bf19 100644 --- a/scripts/ci/tests/test_xpu_ci.py +++ b/scripts/ci/tests/test_xpu_ci.py @@ -1301,6 +1301,7 @@ def test_network_isolation_sets_store_and_ep_loopback_interfaces(self): self.assertEqual(result.returncode, 0, result.stderr) args = (run_directory / "docker.arguments").read_text().splitlines() self.assertEqual(args[args.index("--network") + 1], "none") + self.assertEqual(args[args.index("--pids-limit") + 1], "2048") for variable in ( "MOONCAKE_LOCAL_HOSTNAME=127.0.0.1", "CCL_KVS_IFACE=lo", @@ -1339,6 +1340,64 @@ def test_network_isolation_sets_store_and_ep_loopback_interfaces(self): "\n".join(args), ) + def test_pid_diagnostics_preserve_suite_status(self): + for layout in ("v2", "v1", "missing"): + for suite_status in (0, 7): + with ( + self.subTest(layout=layout, suite_status=suite_status), + tempfile.TemporaryDirectory() as temporary, + ): + root = Path(temporary) + environment = self.prepare_host(root) + run_directory = Path(environment["RUN_DIRECTORY"]) + subprocess.run( + ["bash", str(CORE_SCRIPT), "run"], + cwd=root, + env=environment, + check=True, + capture_output=True, + timeout=10, + ) + arguments = (run_directory / "docker.arguments").read_text() + entrypoint = arguments.split("\n-c\n", 1)[1] + cgroup = root / "cgroup" + counters = cgroup / "pids" if layout == "v1" else cgroup + counters.mkdir(parents=True) + if layout != "missing": + for name, value in ( + ("pids.current", "2"), + ("pids.peak", "1134"), + ("pids.events", "max 0"), + ("pids.max", "2048"), + ): + (counters / name).write_text(value + "\n") + output = run_directory / "output" + entrypoint = entrypoint.replace("/sys/fs/cgroup", str(cgroup)) + entrypoint = entrypoint.replace( + "/output/pids.log", str(output / "pids.log") + ) + entrypoint = entrypoint.replace( + "python3 /control/e2e/python/verify_xpu_ci.py run /bundle /source /output", + f"exit {suite_status}", + ) + result = subprocess.run( + ["bash", "-c", entrypoint], + env={**os.environ, "HOME": str(root / "home")}, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode, suite_status, result.stderr) + report = (output / "pids.log").read_text() + self.assertIn("logical_cpus=", report) + self.assertIn("process_limit=", report) + if layout == "missing": + self.assertEqual(report.count("unavailable"), 4) + else: + self.assertIn("pids.peak:\n1134\n", report) + self.assertIn("pids.events:\nmax 0\n", report) + self.assertIn("pids.max:\n2048\n", report) + def test_fixed_runner_masks_need_no_lock_or_profile_variables(self): for mask, valid in ( ("0,1", True), diff --git a/scripts/xpu/run_core.sh b/scripts/xpu/run_core.sh index c24527d753a..9a01fa766e3 100644 --- a/scripts/xpu/run_core.sh +++ b/scripts/xpu/run_core.sh @@ -75,7 +75,7 @@ run() { --security-opt no-new-privileges \ --security-opt "seccomp=$run_directory/output/seccomp.json" \ --network none --ipc private --shm-size 2g \ - --pids-limit 1024 --ulimit core=0 \ + --pids-limit 2048 --ulimit core=0 \ "${device_args[@]}" \ --mount "type=bind,src=$run_directory/bundle,dst=/bundle,readonly" \ --mount "type=bind,src=$source_directory,dst=/source,readonly" \ @@ -95,6 +95,35 @@ run() { --env HOME=/tmp/home --workdir /tmp \ --entrypoint /bin/bash "$XPU_IMAGE" -c ' set -eo pipefail + collect_pid_diagnostics() { + local counter path line + { + printf "logical_cpus=" + getconf _NPROCESSORS_ONLN || true + printf "process_limit=" + ulimit -u + for counter in pids.current pids.peak pids.events pids.max; do + path="/sys/fs/cgroup/$counter" + if [[ ! -r "$path" ]]; then + path="/sys/fs/cgroup/pids/$counter" + fi + printf "%s:\n" "$counter" + if [[ -r "$path" ]]; then + while IFS= read -r line || [[ -n "$line" ]]; do + printf "%s\n" "$line" + done < "$path" + else + printf "unavailable\n" + fi + done + } > /output/pids.log + } + finish() { + local status=$? + collect_pid_diagnostics || true + exit "$status" + } + trap finish EXIT mkdir -p "$HOME" python3 /control/e2e/python/verify_xpu_ci.py run /bundle /source /output ')