diff --git a/.github/workflows/ci_xpu.yml b/.github/workflows/ci_xpu.yml index 8aa7c8c65b6..ed6bcaac8ce 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,14 +38,15 @@ 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" 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. @@ -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: | @@ -84,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 @@ -103,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 \ @@ -132,18 +137,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/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 - name: Apply wheel version override if: inputs.version_override != '' @@ -174,7 +171,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 +191,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..29f3820bfb4 100644 --- a/.github/workflows/e2e-ci.yml +++ b/.github/workflows/e2e-ci.yml @@ -28,6 +28,29 @@ concurrency: cancel-in-progress: true jobs: + build-wheel-xpu: + if: > + github.event_name == 'workflow_dispatch' || + github.event.label.name == 'run-e2e-ci' + permissions: + contents: read + uses: ./.github/workflows/ci_xpu.yml + with: + checkout_ref: ${{ inputs.pr_sha || github.event.pull_request.head.sha || github.sha }} + + xpu-integration-test: + needs: build-wheel-xpu + permissions: + contents: read + actions: read + uses: ./.github/workflows/integration-test-xpu.yml + with: + 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 }} + artifact_attempt: ${{ needs.build-wheel-xpu.outputs.artifact_attempt }} + ascend-test: if: > github.event_name == 'workflow_dispatch' || @@ -93,6 +116,8 @@ jobs: - integration-test - rocm-integration-test - integration-test-tent + - build-wheel-xpu + - xpu-integration-test runs-on: ubuntu-latest steps: - name: Check E2E results diff --git a/.github/workflows/integration-test-xpu.yml b/.github/workflows/integration-test-xpu.yml new file mode 100644 index 00000000000..3cfd2be4e72 --- /dev/null +++ b/.github/workflows/integration-test-xpu.yml @@ -0,0 +1,104 @@ +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 + artifact_attempt: + 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" + + - name: Download exact build artifact + shell: bash + env: + 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 }} + run: | + set -euo pipefail + [[ "$ARTIFACT_ID" =~ ^[0-9]+$ ]] || { echo "::error::Invalid artifact ID"; 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" + python3 xpu-control/scripts/e2e/python/verify_xpu_ci.py unpack \ + "$RUN_DIRECTORY" "$CHECKOUT_SHA" "$ARTIFACT_ID" "$ARTIFACT_DIGEST" + + - name: Check out 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: | + bash xpu-control/scripts/xpu/run_core.sh run + + - name: Recheck current-run container cleanup + if: always() && steps.run.outputs.directory != '' + shell: bash + env: + RUN_DIRECTORY: ${{ steps.run.outputs.directory }} + run: | + bash xpu-control/scripts/xpu/run_core.sh cleanup + + - 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/tests/test_xpu_ci.py b/scripts/ci/tests/test_xpu_ci.py index 2cdc2bc7cec..a2fa854bf19 100644 --- a/scripts/ci/tests/test_xpu_ci.py +++ b/scripts/ci/tests/test_xpu_ci.py @@ -1,20 +1,28 @@ -"""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 ROOT = Path(__file__).resolve().parents[3] +CORE_SCRIPT = ROOT / "scripts/xpu/run_core.sh" def load_script(name, path): @@ -26,6 +34,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 +48,73 @@ 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, + def test_workflow_uses_xpu_report_validation(self): + script = workflow_step("Run host-side unit tests") + 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"', ), - ): - 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, + 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, - timeout=10, - ).returncode, - 0, - ) + 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): @@ -251,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"] @@ -301,6 +342,227 @@ 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.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.assertNotIn("needs", jobs["build-wheel-xpu"]) + self.assertEqual( + jobs["build-wheel-xpu"]["with"]["checkout_ref"], + "${{ inputs.pr_sha || github.event.pull_request.head.sha || github.sha }}", + ) + self.assertEqual( + jobs["xpu-integration-test"]["needs"], + "build-wheel-xpu", + ) + self.assertEqual( + jobs["xpu-integration-test"]["with"]["checkout_sha"], + "${{ inputs.pr_sha || github.event.pull_request.head.sha || github.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"]), + { + "ascend-test", + "build-wheel-rocm", + "integration-test", + "rocm-integration-test", + "integration-test-tent", + "build-wheel-xpu", + "xpu-integration-test", + }, + ) + self.assertIn("always()", jobs["e2e-gate"]["if"]) + 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( + (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 test_shared_gate_still_checks_other_platforms(self): + steps = E2E_WORKFLOW["jobs"]["e2e-gate"]["steps"] + 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"): + 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_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"]), + 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 +675,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 +762,951 @@ 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": "3", + "XPU_BUILD_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): + 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) + 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") + 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"}) + + 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", + "XPU_BUILD_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"], 152) + 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), + ): + 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()), 152 + ) + 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_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"]): + 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"), + ) + 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" + 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): + with 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, + capture_output=True, + text=True, + timeout=10, + ) + 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", + "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) + 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_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), + ("2,3", True), + ("4,5", True), + ("6,7", True), + ("0,0", False), + ("00,0", False), + ("0", False), + ("0.0,0.1", False), + ("", False), + ): + 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.pop(key, None) + environment["ZE_AFFINITY_MASK"] = mask + result = subprocess.run( + ["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.assertEqual( + (Path(environment["RUN_DIRECTORY"]) / "docker.arguments").exists(), + valid, + ) + + 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", str(CORE_SCRIPT), "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): + 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) + environment = self.prepare_host(root) + run_directory = Path(environment["RUN_DIRECTORY"]) + result = subprocess.run( + ["bash", str(CORE_SCRIPT), "run"], + cwd=root, + env={ + **environment, + "SUITE_STATUS": str(suite_status), + "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" + ) + 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)): + 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", str(CORE_SCRIPT), "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) + environment = self.prepare_host(root) + result = subprocess.run( + ["bash", str(CORE_SCRIPT), "run"], + cwd=root, + env={**environment, "MOCK_UID": "0"}, + capture_output=True, + text=True, + timeout=10, + ) + 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): + 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..55b234a9d2c --- /dev/null +++ b/scripts/e2e/python/verify_xpu_ci.py @@ -0,0 +1,733 @@ +"""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 + + +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: + 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()) + 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( + 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 MappingClosedWhenPeerExits", + 2, +) | case_names( + "SelectionModes/XpuIpcFallbackTest", + "DeviceToPeerDeviceFallsBackToStaging HostToPeerDeviceFallsBackToStaging", + 2, +) + + +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. + 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( + [ + 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])) + 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}") + + +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/XPU_CI.md b/scripts/xpu/XPU_CI.md new file mode 100644 index 00000000000..a1e2f199b17 --- /dev/null +++ b/scripts/xpu/XPU_CI.md @@ -0,0 +1,173 @@ +# XPU CI + +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 + +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 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 +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`, 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. 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 +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. +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. + +## 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. +- 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. +- 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 **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 +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 -v +``` + +XPU CI regressions share one test module and common workflow/module loaders; +they validate packaging and orchestration contracts, not actual B60 behavior. +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. Shared CTest and +TENT CI retain their existing report and exit-code behavior. + +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 +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/`. + +Enable hardware only after provisioning and successfully running the exact +core workflow; record real queue/runtime measurements during rollout. diff --git a/scripts/xpu/run_core.sh b/scripts/xpu/run_core.sh new file mode 100644 index 00000000000..9a01fa766e3 --- /dev/null +++ b/scripts/xpu/run_core.sh @@ -0,0 +1,156 @@ +#!/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 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" \ + --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 + 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 + ') + 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