diff --git a/.ci/sai/README.md b/.ci/sai/README.md index 85109e7..8965a7d 100644 --- a/.ci/sai/README.md +++ b/.ci/sai/README.md @@ -1,47 +1,74 @@ # SAI GPU validation -The manual `SAI CUDA validation` workflow runs an approved LibDDLA commit on +`SAI CUDA validation` tests an approved LibDDLA commit on SAI `16V100` with CUDA 12.9.1, GCC 13.3.0, Open MPI 5.0.10 and NCCL 2.29.3. It builds with `sm_70` and runs the full CUDA-enabled CTest suite with four MPI ranks, then reuses the same binaries for six-rank `pgeadd_indexed` and `pgemm_branches` tests on a `1x6` process grid. The partition assigns host memory; neither stage requests explicit Slurm memory. -## Runner setup - -SAI administrators provide a dedicated `sai-libddla` runner and install the -[site controller](https://github.com/Stardust0831/LibDDLA/tree/66b2c419de961618671c9fbd99298dc6c4b2d255/.ci/sai) -separately. On the VM, place `relay.py`, `endpoint.py` and `report.py` together in -`/home/libddla-runner/ci/bin/`, owned by the administrator and read-only to the -runner. The dedicated SSH configuration is -`/home/libddla-runner/ci/ssh/config`. Install the controller and enforced SSH -command restriction on SAI before enabling the workflow. - -The relay accepts `--source-sha`, `--run-id`, `--ssh-config`, `--work`, and -`--results`; `--cancel-only` cancels this attempt's recorded Slurm jobs. It -validates the administrator-approved full source SHA, transfers Git objects, -submits fixed four-/six-rank jobs and collects results. Compilation and tests -run inside Slurm allocations. Missing, skipped, failed or incomplete tests and -unsuccessful Slurm states must return a nonzero exit status. Results include -JUnit, raw logs, dependency/GPU details and Slurm accounting. - -The repository owner registers the runner and configures Environment -`sai-libddla` with required reviewers and deployment branches `main`/`develop`. -The job needs only `contents: read`; no SSH key or repository-write token is -stored in this repository. Dedicated accounts, resource limits and controller -installation remain site administration responsibilities. Native builds run -as the SAI account, so approve trusted source only. - -## Running - -Once the workflow is on the default branch, select **Run workflow** from `main` -or `develop`, enter the exact 40-character commit SHA approved by the SAI -administrator, and approve the Environment. Each run uses a separate attempt -directory and uploads its evidence even when tests fail. The relay limits total -elapsed time, including queueing, to 165 minutes. - -The workflow tests the selected commit as-is. Keep initial runs manual and -outside required merge checks while the two CUDA 12.9 Cholesky error-code -failures and deployment acceptance remain outstanding. Before activation, -verify the installed account restrictions, a complete Actions run with artifact -collection, and cancellation of that run's Slurm jobs. +## What gets tested + +| Event | Source sent to SAI | Approval | +| --- | --- | --- | +| Push or merge to protected `develop` or `main` | Pushed commit | Automatic once enabled | +| PR opened, reopened or updated against either branch | Current PR head, including for forks | A maintainer approves that run; a new commit needs new approval | +| Manual run on either protected branch | Supplied full commit SHA | A maintainer approves that run | + +Push and PR checks work on `develop` as soon as it contains the workflow. Bring +the workflow to `main` to cover pushes there and expose **Run workflow** in +Actions. A skipped job means no GPU test was run. Failed or incomplete suites +remain failures; the job uploads available JUnit, logs and Slurm evidence. + +## Repository owner + +1. Protect `develop` and `main` with required review, including workflow changes; + restrict direct and force pushes. Under **Settings > Actions > General**, + require approval for fork workflows from **all outside collaborators**. +2. Under **Settings > Environments**, keep required maintainer reviewers on + `sai-libddla` and allow the branch patterns `main`, `develop` and + `refs/pull/*/merge`. Review the source SHA in the run title before approving: + native builds run as the SAI account. Create `sai-libddla-push` with only + `main` and `develop` allowed and no required reviewer. Neither needs secrets. +3. Under **Settings > Actions > Runners**, privately give SAI a short-lived + **repository runner registration token** for the initial setup. Agree on + renewal for disposable runners and reviewer logins with SAI. Provide the site + publisher read access to Actions, Contents, Pull requests and Variables for + this repository. No repository-write token or SAI SSH key is needed by a job. +4. Once SAI confirms isolation, set the repository Actions variable + `SAI_CI_ENABLED=true` for a supervised first run on `develop`. Keep it on + after verifying reporting and cancellation; removing it disables new + automatic runs. Leave this check out of required merge checks initially. + +## SAI administrators + +- Register clean, disposable Linux x64 runners labeled `sai-libddla-results`, + with Bash and jq and one concurrent job to match site capacity. Give jobs + **only read-only access to published results** at + `/srv/sai-libddla/results`: no site credentials, SSH agent, controller socket, + private storage or cluster network access. Retire any credential-bearing + runner accessible to this public repository before accepting PR workflows. + A label or an Environment cannot stop a fork from changing workflow steps. +- On the trusted side, install a reviewed copy of [publish.py](publish.py) and the + existing [site controller](https://github.com/Stardust0831/LibDDLA/tree/66b2c419de961618671c9fbd99298dc6c4b2d255/.ci/sai). + Keep SSH, the restricted endpoint and Slurm quotas there. Run one publisher + at a time on a short timer (e.g. every 20 seconds) with Python 3.10+ and an + authenticated `gh` bound to github.com. It polls GitHub directly; it does not + accept commands or source files from the runner. +- Configure the publisher's `SAI_RELAY` and `SAI_SSH_CONFIG` paths, a private + `SAI_WORK` directory, the site-writable `SAI_RESULTS` directory exported + read-only to jobs, and comma-separated trusted `SAI_REVIEWERS` GitHub logins. + The existing endpoint requires the exact SHA during both prepare and submit. + For automatic admission, provide a site-owned `SAI_AUTHORIZE` executable: + it receives `event branch sha run_id` after verification and must authorize + only that SHA or exit nonzero. Without it only already-allowlisted SHAs run. +- Each attempt has its own results directory. On cancellation, supersession or + PR closure the publisher interrupts that attempt's relay to cancel its Slurm + jobs. An interrupted publisher does not replay an old attempt; reconcile it + with Slurm, then re-run with a new attempt. Retain public evidence per site + policy and keep partial or absent results from counting as a pass. + +Before enabling routine runs, verify the credential boundary from an actual job, +check that an unapproved SHA is refused, and exercise artifact upload and +cancellation through Actions. Keep the check informational while deployment and +the two CUDA 12.9 Cholesky error-code failures are outstanding. diff --git a/.ci/sai/publish.py b/.ci/sai/publish.py new file mode 100644 index 0000000..dea07a5 --- /dev/null +++ b/.ci/sai/publish.py @@ -0,0 +1,135 @@ +"""Poll once from the trusted site account. Never install this on the Actions runner.""" +import json +import os +from pathlib import Path +import re +import shutil +import signal +import subprocess +import sys + + +REPO = "userchba/LibDDLA" +WORKFLOW = ".github/workflows/sai-validation.yml" +BRANCHES = {"main", "develop"} +REVIEW_ENV = "sai-libddla" +RESULT_LABEL = "sai-libddla-results" + + +def api(path): + return json.loads(subprocess.check_output(["gh", "api", "--hostname", "github.com", f"repos/{REPO}/{path}"], + timeout=45)) + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def admission(run, reviewers): + event = run["event"] + match = re.fullmatch(r"SAI CUDA / (0|[1-9][0-9]*) / ([a-f0-9]{40})", run["display_title"]) + require(run["path"] == WORKFLOW and run["repository"]["full_name"] == REPO and match, + "Unknown workflow or invalid request") + pr, sha = match.groups() + if event != "workflow_dispatch": + require(api("actions/variables/SAI_CI_ENABLED")["value"] == "true", "Automatic CI is off") + branch = run["head_branch"] + if event == "pull_request": + pull = api(f"pulls/{pr}") + require(pull["state"] == "open" and pull["base"]["repo"]["full_name"] == REPO + and pull["head"]["sha"] == sha == run["head_sha"] + and pull["head"]["repo"]["id"] == run["head_repository"]["id"], + "This is not the current PR head") + branch = pull["base"]["ref"] + else: + require(event in {"push", "workflow_dispatch"} and pr == "0" + and run["head_repository"]["full_name"] == REPO, "Unexpected event or repository") + require(branch in BRANCHES and api(f"branches/{branch}")["protected"], "Unprotected base") + if event == "push": + require(sha == run["head_sha"] and + api(f"compare/{sha}...{branch}")["status"] in {"ahead", "identical"}, + "Push SHA is not on the protected branch") + else: + decisions = [a for a in api(f"actions/runs/{run['id']}/approvals") + if any(e["name"] == REVIEW_ENV for e in a["environments"])] + require(not any(a["state"] == "rejected" for a in decisions) and + any(a["state"] == "approved" and a["user"]["login"].lower() in reviewers + for a in decisions), + "No trusted Environment approval for this run") + return branch, sha, pr + + +def publish(run, reviewers): + number, attempt = int(run["id"]), int(run["run_attempt"]) + key = f"gh-{number}-{attempt}" + result = Path(os.environ["SAI_RESULTS"]) / key + if result.exists(): + return + jobs = api(f"actions/runs/{number}/attempts/{attempt}/jobs")["jobs"] + if not any(j["status"] == "in_progress" and RESULT_LABEL in j["labels"] for j in jobs): + return # A queued job can still be waiting for its Environment reviewer. + # Never replay a partially published attempt after a service restart. + try: + result.mkdir() + except FileExistsError: + return + work = Path(os.environ["SAI_WORK"]) / key + sha, code = None, 1 + try: + current = api(f"actions/runs/{number}") + require(current["run_attempt"] == attempt and current["status"] == "in_progress", + "Attempt is no longer active") + branch, sha, pr = admission(current, reviewers) + # Site policy may authorize this exact SHA; the endpoint still checks it on prepare and submit. + if hook := os.environ.get("SAI_AUTHORIZE"): + subprocess.run([hook, current["event"], branch, sha, key], check=True, timeout=60) + cmd = [sys.executable, os.environ["SAI_RELAY"], "--source-sha", sha, "--run-id", key, + "--ssh-config", os.environ["SAI_SSH_CONFIG"], "--work", str(work), + "--results", str(result)] + with subprocess.Popen(cmd) as relay: + try: + while True: + try: + code = relay.wait(timeout=20) + break + except subprocess.TimeoutExpired: + active = api(f"actions/runs/{number}") + require(active["run_attempt"] == attempt and active["status"] == "in_progress", + "Attempt ended or was superseded") + if pr != "0": + pull = api(f"pulls/{pr}") + require(pull["state"] == "open" and pull["head"]["sha"] == sha + and pull["base"]["ref"] == branch, "PR changed or closed") + finally: + if relay.poll() is None: + relay.send_signal(signal.SIGINT) # The installed relay cancels its own Slurm jobs. + relay.wait() + except (KeyError, OSError, ValueError, subprocess.SubprocessError) as error: + print(f"{key}: {error}", file=sys.stderr, flush=True) + finally: + receipt = result / "completion.tmp" + receipt.write_text(json.dumps({"run_id": key, "source_sha": sha, "exit_code": code}) + "\n") + receipt.replace(result / "completion.json") + if work.is_dir(): + shutil.rmtree(work) + + +def main(): + private, public = (Path(os.environ[k]).resolve(strict=True) for k in ("SAI_WORK", "SAI_RESULTS")) + require(private.is_dir() and public.is_dir() and not private.is_relative_to(public) + and not public.is_relative_to(private), "Private work and public results must be separate directories") + reviewers = {login.strip().lower() for login in os.environ["SAI_REVIEWERS"].split(",") if login.strip()} + page = 1 + while True: + runs = api(f"actions/runs?status=in_progress&per_page=100&page={page}")["workflow_runs"] + for run in runs: + if run["path"] == WORKFLOW: + publish(run, reviewers) + if len(runs) < 100: + return + page += 1 + + +if __name__ == "__main__": + main() diff --git a/.ci/sai/test_publish.py b/.ci/sai/test_publish.py new file mode 100644 index 0000000..18ab53e --- /dev/null +++ b/.ci/sai/test_publish.py @@ -0,0 +1,97 @@ +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import Mock, patch + +import publish as site + + +class AdmissionTest(unittest.TestCase): + def setUp(self): + self.sha = "a" * 40 + self.repo = {"id": 1, "full_name": site.REPO} + fork = {"id": 2, "full_name": "contributor/LibDDLA"} + self.run = dict(id=17, run_attempt=1, status="in_progress", event="pull_request", + path=site.WORKFLOW, repository=self.repo, head_repository=fork, + head_branch="topic", head_sha=self.sha, display_title=f"SAI CUDA / 3 / {self.sha}") + self.pull = dict(state="open", head=dict(sha=self.sha, repo=fork), + base=dict(ref="develop", repo=self.repo)) + self.routes = { + "actions/runs/17": self.run, "pulls/3": self.pull, + "branches/develop": {"protected": True}, "branches/main": {"protected": True}, + "actions/variables/SAI_CI_ENABLED": {"value": "true"}, + "actions/runs/17/approvals": [{"state": "approved", "user": {"login": "owner"}, + "environments": [{"name": site.REVIEW_ENV}]}], + "actions/runs/17/attempts/1/jobs": {"jobs": [{"status": "in_progress", + "labels": [site.RESULT_LABEL]}]}, + } + mock = patch.object(site, "api", side_effect=self.routes.__getitem__) + self.api = mock.start() + self.addCleanup(mock.stop) + + def test_pr_needs_current_head_and_its_own_approval(self): + self.assertEqual(site.admission(self.run, {"owner"}), ("develop", self.sha, "3")) + with self.assertRaises(ValueError): + site.admission(self.run, {"other"}) + self.pull["head"]["sha"] = "b" * 40 + with self.assertRaises(ValueError): + site.admission(self.run, {"owner"}) + self.run.update(id=18, head_sha="b" * 40, display_title=f"SAI CUDA / 3 / {'b' * 40}") + self.routes["actions/runs/18/approvals"] = [] + with self.assertRaises(ValueError): + site.admission(self.run, {"owner"}) + + def test_push_and_manual_sources(self): + self.run.update(event="push", head_repository=self.repo, head_branch="main", + display_title=f"SAI CUDA / 0 / {self.sha}") + self.routes[f"compare/{self.sha}...main"] = {"status": "ahead"} + self.assertEqual(site.admission(self.run, set()), ("main", self.sha, "0")) + for path, bad in [("actions/variables/SAI_CI_ENABLED", {"value": "false"}), + ("branches/main", {"protected": False}), + (f"compare/{self.sha}...main", {"status": "diverged"})]: + with self.subTest(path=path), patch.dict(self.routes, {path: bad}), self.assertRaises(ValueError): + site.admission(self.run, set()) + self.run.update(event="workflow_dispatch", display_title=f"SAI CUDA / 0 / {'b' * 40}") + self.assertEqual(site.admission(self.run, {"owner"}), ("main", "b" * 40, "0")) + self.pull["base"]["ref"] = "topic" + self.run.update(event="pull_request", head_repository=self.pull["head"]["repo"], + display_title=f"SAI CUDA / 3 / {self.sha}") + with self.assertRaises(ValueError): + site.admission(self.run, {"owner"}) + + def test_receipt_and_cancellation(self): + for exit_status in (0, 1, "cancel"): + with self.subTest(exit_status=exit_status), tempfile.TemporaryDirectory() as tmp: + env = dict(SAI_RESULTS=tmp, SAI_WORK=tmp + "/work", SAI_RELAY="/relay", + SAI_SSH_CONFIG="/config", SAI_AUTHORIZE="") + relay = Mock() + if exit_status == "cancel": + relay.wait.side_effect = [subprocess.TimeoutExpired("relay", 20), 1] + relay.poll.return_value = None + self.pull["state"] = "open" + def change_state(*args, **kwargs): + self.pull["state"] = "closed" + return relay + else: + relay.wait.return_value = exit_status + relay.poll.return_value = exit_status + change_state = lambda *args, **kwargs: relay + with patch.dict(os.environ, env), patch.object(site.subprocess, "Popen") as start: + start.return_value.__enter__.side_effect = change_state + site.publish(self.run, {"owner"}) + site.publish(self.run, {"owner"}) + self.assertEqual(start.call_count, 1) + args = start.call_args.args[0] + self.assertIn(self.sha, args) + receipt = json.loads((Path(tmp) / "gh-17-1/completion.json").read_text()) + self.assertEqual(receipt, {"run_id": "gh-17-1", "source_sha": self.sha, + "exit_code": 0 if exit_status == 0 else 1}) + if exit_status == "cancel": + relay.send_signal.assert_called_once_with(site.signal.SIGINT) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/sai-validation.yml b/.github/workflows/sai-validation.yml index d69e9df..be104d8 100644 --- a/.github/workflows/sai-validation.yml +++ b/.github/workflows/sai-validation.yml @@ -1,10 +1,16 @@ name: SAI CUDA validation +run-name: SAI CUDA / ${{ github.event.pull_request.number || 0 }} / ${{ github.event.pull_request.head.sha || inputs.source_sha || github.sha }} on: + push: + branches: [main, develop] + pull_request: + branches: [main, develop] + types: [opened, reopened, synchronize] workflow_dispatch: inputs: source_sha: - description: Full 40-character commit SHA approved by the SAI administrator + description: Full 40-character commit SHA approved for the manual run required: true type: string @@ -12,52 +18,45 @@ permissions: contents: read concurrency: - group: libddla-sai-cuda129 - cancel-in-progress: false + group: sai-cuda-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: cuda: if: >- github.repository == 'userchba/LibDDLA' && - github.event_name == 'workflow_dispatch' && - (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop') + ((github.event_name == 'workflow_dispatch' && github.ref_protected && + (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop')) || + (vars.SAI_CI_ENABLED == 'true' && + (github.event_name == 'pull_request' || + (github.event_name == 'push' && github.ref_protected && !github.event.deleted)))) name: SAI V100, full CUDA suite and six-rank matrix tests - runs-on: [self-hosted, Linux, X64, sai-libddla] - environment: sai-libddla + runs-on: [self-hosted, Linux, X64, sai-libddla-results] + environment: ${{ github.event_name == 'push' && 'sai-libddla-push' || 'sai-libddla' }} timeout-minutes: 180 env: - DDLA_SOURCE_SHA: ${{ inputs.source_sha }} + DDLA_SOURCE_SHA: ${{ github.event.pull_request.head.sha || inputs.source_sha || github.sha }} DDLA_RUN_ID: gh-${{ github.run_id }}-${{ github.run_attempt }} - DDLA_SSH_CONFIG: /home/libddla-runner/ci/ssh/config steps: - - name: Prepare, submit and collect SAI validation + - name: Read this attempt's result from SAI + timeout-minutes: 175 run: | set -euo pipefail - python3 /home/libddla-runner/ci/bin/relay.py \ - --source-sha "$DDLA_SOURCE_SHA" --run-id "$DDLA_RUN_ID" \ - --ssh-config "$DDLA_SSH_CONFIG" \ - --work "$RUNNER_TEMP/libddla-sai-$DDLA_RUN_ID" \ - --results "$RUNNER_TEMP/libddla-sai-results-$DDLA_RUN_ID" - - - name: Request cancellation of this run's remaining Slurm jobs - if: cancelled() - run: | - python3 /home/libddla-runner/ci/bin/relay.py \ - --source-sha "$DDLA_SOURCE_SHA" --run-id "$DDLA_RUN_ID" \ - --ssh-config "$DDLA_SSH_CONFIG" --cancel-only \ - --work "$RUNNER_TEMP/libddla-sai-$DDLA_RUN_ID" \ - --results "$RUNNER_TEMP/libddla-sai-results-$DDLA_RUN_ID" + result="/srv/sai-libddla/results/$DDLA_RUN_ID" + [[ "$DDLA_SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] + until [[ -f "$result/completion.json" ]]; do sleep 10; done + if [[ -s "$result/remote/summary.md" ]]; then + cat "$result/remote/summary.md" >> "$GITHUB_STEP_SUMMARY" + fi + jq -e --arg id "$DDLA_RUN_ID" --arg sha "$DDLA_SOURCE_SHA" \ + '.run_id == $id and .source_sha == $sha and .exit_code == 0' "$result/completion.json" + jq -e '.success == true' "$result/remote/summary.json" - name: Upload JUnit, logs, toolchain and Slurm evidence if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: libddla-sai-${{ github.run_id }}-${{ github.run_attempt }} - path: ${{ runner.temp }}/libddla-sai-results-${{ env.DDLA_RUN_ID }}/ + path: /srv/sai-libddla/results/${{ env.DDLA_RUN_ID }}/ if-no-files-found: error retention-days: 30 - - - name: Remove this attempt's temporary source objects - if: always() - run: | - rm -rf -- "$RUNNER_TEMP/libddla-sai-$DDLA_RUN_ID"