diff --git a/.github/actions/devkit-overlay-package/action.yml b/.github/actions/devkit-overlay-package/action.yml index 83f645ed8..23900be5c 100644 --- a/.github/actions/devkit-overlay-package/action.yml +++ b/.github/actions/devkit-overlay-package/action.yml @@ -45,6 +45,13 @@ inputs: description: Comma-separated families whose engines to overlay (changes.py devkit-families; every family overlays every engine). required: false default: "" + engines: + description: > + engines.json choosing the engines to overlay, relative to the + workspace; empty for the checkout's flm-dev-kit/FLM_DLL/engines.json. + A dispatch benching an earlier run passes that run's commit's. + required: false + default: "" new-models: description: Comma-separated models the change adds (changes.py new-models), for the test selection outputs. required: false @@ -171,6 +178,7 @@ runs: DEVKIT_XCLBIN_MODELS: ${{ inputs.xclbin-models || '[]' }} FAMILIES: ${{ inputs.families }} NEW_MODELS: ${{ inputs.new-models }} + ENGINES: ${{ inputs.engines }} TARGET_OS: ${{ inputs.os }} RUNTIME: ${{ inputs.runtime }} run: | @@ -184,6 +192,7 @@ runs: --github-output) [ -n "${LIBS}" ] && args+=(--libs "${GITHUB_WORKSPACE}/devkit-libs") [ -n "${XCLBINS}" ] && args+=(--xclbins "${GITHUB_WORKSPACE}/devkit-xclbins") + [ -n "${ENGINES}" ] && args+=(--engines "${ENGINES}") python3 .github/script/ci/devkit_overlay.py "${args[@]}" echo "root=${root}" >> "$GITHUB_OUTPUT" @@ -199,6 +208,7 @@ runs: DEVKIT_XCLBIN_MODELS: ${{ inputs.xclbin-models || '[]' }} FAMILIES: ${{ inputs.families }} NEW_MODELS: ${{ inputs.new-models }} + ENGINES: ${{ inputs.engines }} TARGET_OS: ${{ inputs.os }} RUNTIME: ${{ inputs.runtime }} run: | @@ -213,6 +223,7 @@ runs: "--families=$env:FAMILIES", "--new-models=$env:NEW_MODELS", '--github-output') if ($env:LIBS) { $cmdArgs += "--libs=$(Join-Path $env:GITHUB_WORKSPACE 'devkit-libs')" } if ($env:XCLBINS) { $cmdArgs += "--xclbins=$(Join-Path $env:GITHUB_WORKSPACE 'devkit-xclbins')" } + if ($env:ENGINES) { $cmdArgs += "--engines=$env:ENGINES" } $env:PYTHONUTF8 = '1' & python $cmdArgs if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/.github/script/ci/devkit_swap.py b/.github/script/ci/devkit_swap.py index 447e72fd6..2fd1c6a61 100644 --- a/.github/script/ci/devkit_swap.py +++ b/.github/script/ci/devkit_swap.py @@ -38,7 +38,8 @@ every system and runtime the run staged files into passed, that the pull request is not from a fork, and that main gained no commit touching the dev-kit engine or kernel sources or the prebuilt binaries since the run's -base (else merge main and let CI run again). Then it downloads the manifests +base (documentation there does not count, see main_moved; else merge main +and let CI run again). Then it downloads the manifests and the artifacts holding the files that differ from the branch, checks every file's size and SHA-256 against the manifests, writes them under src/lib and src/xclbins, and makes ONE commit (no push) whose message ends @@ -59,10 +60,10 @@ build of an engine, part of the kernels), the recorded run passes the checks fetch makes (read with the job's token, actions: read: only the small manifests are downloaded), main gained no dev-kit source or binary -change between the run's base and the pull request's base, and the pull -request changes none of SWAP_CI_PATHS (the code that stages, writes and -checks the manifests: it runs from the pull request's merge commit, so a -swap must not come with changes to it). The bytes are compared by git blob +change (documentation does not count) between the run's base and the pull +request's base, and the pull request changes none of SWAP_CI_PATHS (the +code that stages, writes and checks the manifests: it runs from the pull +request's merge commit, so a swap must not come with changes to it). The bytes are compared by git blob id (the manifest records it beside the SHA-256; both hash exactly the bytes), read from the trees alone, so the changes job's blob:none clone downloads no binary. Prints the reasons and writes swap-verified=true|false @@ -171,8 +172,25 @@ BINARY_ROOTS = ("src/lib/", "src/xclbins/") # What a change on main since the run's base must not touch: the dev-kit -# engine and kernel sources and build inputs, and the binaries themselves. +# engine and kernel sources and build inputs, and the binaries themselves +# (main_moved: documentation under them, NON_CODE, does not count; anything +# under BINARY_ROOTS does). SOURCE_PATHS = ("flm-dev-kit/FLM_DLL/", "flm-dev-kit/FLM_Xclbin/", "src/lib/", "src/xclbins/") +# changes.py's NON_CODE, copied rather than imported: verify runs the pull +# request's code, and changes.py is not in SWAP_CI_PATHS, so a pull request +# widening its NON_CODE would otherwise hide source commits on main from +# main_moved. test_devkit_swap pins the two equal. +NON_CODE = re.compile( + r"^(docs/" + r"|assets/" # README images and the like, at the repo root + r"|src/tb_files/" + r"|src/iceCream\.jpg$" + r"|\.github/ISSUE_TEMPLATE/" + r"|\.github/(PULL_REQUEST_TEMPLATE[^/]*|CODEOWNERS|FUNDING\.yml)$" + r"|(.*/)?\.gitignore$|\.mailmap$" + r"|.*\.md$" + r"|.*~$)", # editor backups such as src/home_install.sh~ + re.IGNORECASE) THIRD_PARTY = {k: v for k, v in devkit_check.CATALOG_ALLOW.items() if k.startswith("src/lib/")} @@ -767,16 +785,33 @@ def check_recorded_run(api, repo: str, run_id: str, tested: str, pr: Pr, tmp: Pa return RunCheck(run, manifests, entries, notes, errors) +def counts_for_swap(path: str) -> bool: + """Whether a change to path (under SOURCE_PATHS) on main makes a run's + swap stale: every binary does, and every source or build input but + documentation (NON_CODE, changes.py's, so that the two agree).""" + return path.startswith(BINARY_ROOTS) or not NON_CODE.match(path) + + def main_moved(git: Git, since: str, until: str) -> list[str]: - """Commits on until since since that touch SOURCE_PATHS (a SwapError - when since is unknown here, or is no commit of until's history: a - run's base is a commit of main).""" + """Commits on until since since that change a SOURCE_PATHS file that + counts_for_swap (a commit changing only documentation there does not + count; a SwapError when since is unknown here, or is no commit of + until's history: a run's base is a commit of main). Trees only (no + blob is read): a blob:none clone fetches nothing.""" if not git.rev(since): raise SwapError(f"the run's base {since[:10]} is not in this clone: fetch main") if not git.is_ancestor(since, until): raise SwapError(f"the run's base {since[:10]} is not a commit of {until}") - out = git.run("rev-list", f"{since}..{until}", "--", *SOURCE_PATHS) - return out.split() + moved = [] + for commit in git.run("rev-list", f"{since}..{until}", "--", *SOURCE_PATHS).split(): + # -c: a merge lists the files it changed against every parent (what + # a side brought in is listed by the side's own commits); --root: + # a root commit lists its files. + out = git.run("diff-tree", "-r", "-c", "--root", "--no-commit-id", "--name-only", "-z", + commit, "--", *SOURCE_PATHS) + if any(counts_for_swap(p) for p in out.split("\0") if p): + moved.append(commit) + return moved # ── verify ─────────────────────────────────────────────────────────────────── @@ -790,6 +825,8 @@ def main_moved(git: Git, since: str, until: str) -> list[str]: # run from the pull request's merge commit). changes.py is not here: a new # model family needs its engine table (ENGINES) and comes with its swap; # what it decides runs from the pull request's code whatever this says. +# verify does not depend on it: main_moved uses this file's copy of its +# NON_CODE. # npu_test's pr-tier table (plan.py PR_CHAT) needs no entry for a new # family (it gets its smallest model), so a new model needs no harness edit. SWAP_CI_PATHS = ( diff --git a/.github/script/ci/test_devkit_assemble_xclbins.py b/.github/script/ci/test_devkit_assemble_xclbins.py index 592cdf775..c4bd88267 100644 --- a/.github/script/ci/test_devkit_assemble_xclbins.py +++ b/.github/script/ci/test_devkit_assemble_xclbins.py @@ -69,7 +69,7 @@ def test_assemble(self): # No xclbin built (m:9b), and ambiguous (m:amb): nothing for them. self.assertFalse((out / "M-9B").exists()) self.assertFalse((out / "M-AMB").exists()) - self.assertEqual(sorted(str(p.relative_to(out)) for p in out.rglob("*") if p.is_file()), [ + self.assertEqual(sorted(p.relative_to(out).as_posix() for p in out.rglob("*") if p.is_file()), [ "M-1B/dequant.xclbin", "M-1B/layer.xclbin", "M-3B/dequant.xclbin", "M-3B/vision_mm_a.xclbin", "M-3B/vision_mm_b.xclbin"]) diff --git a/.github/script/ci/test_devkit_bench.py b/.github/script/ci/test_devkit_bench.py index 46303d779..74cfd3475 100644 --- a/.github/script/ci/test_devkit_bench.py +++ b/.github/script/ci/test_devkit_bench.py @@ -14,6 +14,7 @@ import io import json import os +import subprocess import sys import tempfile import unittest @@ -573,27 +574,30 @@ def job(name, conclusion): self.assertEqual(resolve.engines_result(ok + [job("devkit-engines / x", None)]), "failure") self.assertEqual(resolve.engines_result([job("devkit-engines-other", "failure")] + ok), "success") - def find_build(self, *, run_obj, artifacts, jobs, run_id="5"): - """cmd_find_build with the GitHub API stubbed; (rc, outputs, plan or None).""" - saved = resolve.api_get, resolve.list_artifacts, resolve.list_jobs + def find_build(self, *, run_obj, artifacts, jobs, run_id="5", ref="refs/heads/feature", + ancestors=(SHA_B,)): + """cmd_find_build with the GitHub API and git stubbed (ancestors: the + commits before SHA_A, the dispatched one); (rc, outputs, plan or None).""" + saved = resolve.api_get, resolve.list_artifacts, resolve.list_jobs, resolve.is_ancestor resolve.api_get = lambda path, params=None: (run_obj if path.endswith(f"/runs/{run_id}") else {"workflow_runs": [run_obj]}) resolve.list_artifacts = lambda repo, rid: artifacts resolve.list_jobs = lambda repo, rid: jobs + resolve.is_ancestor = lambda root, a, b: b == SHA_A and (a == SHA_A or a in ancestors) try: with tempfile.TemporaryDirectory() as d: out, plan = os.path.join(d, "out"), os.path.join(d, "plan.json") os.environ["GITHUB_OUTPUT"] = out try: rc = quiet(resolve.main, ["find-build", "--repo", self.REPO, "--head-sha", SHA_A, - "--run-id", run_id, "--wait-minutes", "0", "--poll-seconds", "0", + "--ref", ref, "--run-id", run_id, "--wait-minutes", "0", "--poll-seconds", "0", "--plan-out", plan, "--artifacts-out", os.path.join(d, "a.json")]) finally: del os.environ["GITHUB_OUTPUT"] values = dict(line.split("=", 1) for line in Path(out).read_text(encoding="utf-8").splitlines()) written = json.loads(Path(plan).read_text(encoding="utf-8")) if Path(plan).exists() else None finally: - resolve.api_get, resolve.list_artifacts, resolve.list_jobs = saved + resolve.api_get, resolve.list_artifacts, resolve.list_jobs, resolve.is_ancestor = saved return rc, values, written def test_find_build(self): @@ -622,7 +626,75 @@ def test_find_build(self): rc, out, plan = self.find_build(run_obj=run(status="in_progress"), artifacts=arts, jobs=built) self.assertEqual((out["ok"], plan), ("false", None)) - def plan_cli(self, plan, *extra, changed=False): + def test_find_build_earlier_push_run_on_main(self): + # main moved on (SHA_B, then SHA_A dispatched): SHA_B's push run. + arts = [{"id": 1, "name": "portable"}, {"id": 2, "name": "devkit-libs-lin-xrt"}, + {"id": 3, "name": f"fastflowlm-windows-{SHA_B}"}, {"id": 4, "name": "devkit-xclbins"}] + built = [{"name": "devkit-engines / Build", "conclusion": "success"}] + main_run = run(event="push", head_branch="main", head_sha=SHA_B) + for conclusion in ("success", "failure"): + with self.subTest(conclusion=conclusion): + rc, out, plan = self.find_build(run_obj={**main_run, "conclusion": conclusion}, artifacts=arts, + jobs=built, ref="refs/heads/main") + self.assertEqual((rc, out["ok"], out["run-id"], out["head-sha"]), (0, "true", "5", SHA_B)) + self.assertIn(SHA_B[:10], out["reason"]) + # The plan names the run's commit, not the dispatched one. + plan = resolve.parse_plan(plan) + self.assertEqual(plan["head_sha"], SHA_B) + self.assertEqual(plan["builds"]["win-xrt"]["package"], f"fastflowlm-windows-{SHA_B}") + # Its own commit's push run on main is fine too. + rc, out, plan = self.find_build(run_obj={**main_run, "head_sha": SHA_A}, artifacts=arts, jobs=built, + ref="refs/heads/main") + self.assertEqual((out["ok"], out["head-sha"]), ("true", SHA_A)) + refused = { + # The same run, dispatched on another branch: exactly this commit only. + "another branch": dict(run_obj=main_run, ref="refs/heads/feature"), + # Not an ancestor of the dispatched commit (a later or unrelated one). + "not an ancestor": dict(run_obj=main_run, ref="refs/heads/main", ancestors=()), + # Not a push run on main: a pull request's, a branch's push, a dispatch's. + "pull request": dict(run_obj={**main_run, "event": "pull_request"}, ref="refs/heads/main"), + "branch push": dict(run_obj={**main_run, "head_branch": "feature"}, ref="refs/heads/main"), + "dispatch": dict(run_obj={**main_run, "event": "workflow_dispatch"}, ref="refs/heads/main"), + "fork": dict(run_obj={**main_run, "head_repository": {"full_name": "fork/FastFlowLM"}}, + ref="refs/heads/main"), + "other workflow": dict(run_obj={**main_run, "path": ".github/workflows/evil.yml"}, + ref="refs/heads/main"), + } + for why, kw in refused.items(): + with self.subTest(why=why): + rc, out, plan = self.find_build(artifacts=arts, jobs=built, **kw) + self.assertEqual((rc, out["ok"], plan), (0, "false", None)) + self.assertIn("is not this repository's Build and Test run", out["reason"]) + # Still strict about how the run ended and what it holds. + rc, out, plan = self.find_build(run_obj={**main_run, "conclusion": "cancelled"}, artifacts=arts, + jobs=built, ref="refs/heads/main") + self.assertEqual((out["ok"], plan), ("false", None)) + rc, out, plan = self.find_build(run_obj=main_run, artifacts=arts[:1], ref="refs/heads/main", + jobs=[{"name": "devkit-engines", "conclusion": "skipped"}]) + self.assertEqual((out["ok"], plan), ("false", None)) + self.assertIn("no dev-kit engines or kernels", out["reason"]) + # Without a run id only a run of exactly this commit is taken. + rc, out, plan = self.find_build(run_obj=main_run, artifacts=arts, jobs=built, run_id="", + ref="refs/heads/main") + self.assertEqual((out["ok"], plan), ("false", None)) + + def test_is_ancestor(self): + with tempfile.TemporaryDirectory() as d: + def git(*args): + return subprocess.run(["git", "-C", d, "-c", "user.name=t", "-c", "user.email=t@example.com", + "-c", "commit.gpgsign=false", *args], + capture_output=True, text=True, check=True).stdout.strip() + git("init", "-q", "-b", "main") + git("commit", "-q", "--allow-empty", "-m", "a") + first = git("rev-parse", "HEAD") + git("commit", "-q", "--allow-empty", "-m", "b") + second = git("rev-parse", "HEAD") + self.assertTrue(resolve.is_ancestor(Path(d), first, second)) + self.assertTrue(resolve.is_ancestor(Path(d), second, second)) + self.assertFalse(resolve.is_ancestor(Path(d), second, first)) + self.assertFalse(resolve.is_ancestor(Path(d), SHA_B, second)) + + def plan_cli(self, plan, *extra, changed=False, rc=0): """cmd_plan with source_changed stubbed; its outputs.""" saved = resolve.source_changed calls = [] @@ -636,7 +708,7 @@ def plan_cli(self, plan, *extra, changed=False): os.environ["GITHUB_OUTPUT"] = out try: self.assertEqual(quiet(resolve.main, ["plan", "--plan", path, "--runtimes", "lin-xrt", - "--baseline", base, *extra]), 0) + "--baseline", base, *extra]), rc) finally: del os.environ["GITHUB_OUTPUT"] values = dict(line.split("=", 1) for line in Path(out).read_text(encoding="utf-8").splitlines()) @@ -646,6 +718,15 @@ def plan_cli(self, plan, *extra, changed=False): return values def test_plan_baseline_gate(self): + # A dispatch reads the benched commit's maps; SHA_A's are this checkout's here. + real = resolve.load_maps + resolve.load_maps = lambda root, ref="": real(root) + try: + self.check_plan_baseline_gate() + finally: + resolve.load_maps = real + + def check_plan_baseline_gate(self): index = resolve.artifact_index([{"id": 1, "name": "portable"}, {"id": 2, "name": "devkit-libs-lin-xrt"}]) plan = resolve.plan_from_artifacts(index, SHA_A, "success") nightly = resolve.write_plan(head_sha=SHA_A, package_sha=SHA_A, engines="success", @@ -733,6 +814,70 @@ def stub(root, ref=""): finally: resolve.load_maps = real + def test_dispatch_selects_from_the_benched_runs_maps(self): + # On main a dispatch may bench an earlier push run (SHA_A) while the + # checkout is the dispatched commit, whose maps differ: the selection + # and the engines overlaid are the benched commit's. + index = resolve.artifact_index([{"id": 1, "name": "portable"}, {"id": 2, "name": "devkit-libs-lin-xrt"}]) + plan = resolve.plan_from_artifacts(index, SHA_A, "success") + real, refs = resolve.load_maps, [] + head = self.head_maps_with_new_model() + + def stub(root, ref=""): + refs.append(ref) + return head if ref == SHA_A else real(root) + resolve.load_maps = stub + try: + v = self.plan_cli(plan, "--mode", "dispatch", "--models", "nova:1b") + finally: + resolve.load_maps = real + self.assertEqual(refs, [SHA_A]) + self.assertEqual(v["head-sha"], SHA_A) + self.assertEqual({e["model"] for e in json.loads(v["matrix"])}, {"nova:1b"}) + + def test_dispatch_never_selects_from_another_commits_maps(self): + index = resolve.artifact_index([{"id": 1, "name": "portable"}, {"id": 2, "name": "devkit-libs-lin-xrt"}]) + plan = resolve.plan_from_artifacts(index, SHA_A, "success") + real, refs = resolve.load_maps, [] + + def stub(root, ref=""): + refs.append(ref) + if ref: + raise OSError("not fetched") + return real(root) + resolve.load_maps = stub + try: + v = self.plan_cli(plan, "--mode", "dispatch", rc=1) + finally: + resolve.load_maps = real + self.assertEqual(refs, [SHA_A]) + self.assertEqual(v["bench"], "false") + self.assertIn(SHA_A[:10], v["reason"]) + + def test_bench_overlays_the_benched_runs_engines(self): + # The overlay's engines.json is the benched commit's on a dispatch: + # resolve reads it with git show and uploads it, and the bench job + # downloads it. No bench job checks out a computed commit (a checkout + # of needs.resolve.outputs.head-sha there is what code scanning flags + # as cache poisoning). + text = workflow("devkit-bench.yml") + resolve_job = text.split("\n resolve:\n", 1)[1].split("\n npu-gate:\n", 1)[0] + read = resolve_job.split("- name: Engine map of the benched commit\n", 1)[1].split("\n\n")[0] + self.assertIn("git show \"${HEAD_SHA}:flm-dev-kit/FLM_DLL/engines.json\"", read) + self.assertIn("HEAD_SHA: ${{ steps.plan.outputs.head-sha }}", read) + self.assertIn("name: devkit-bench-engines", resolve_job) + bench = text.split("\n bench:\n", 1)[1].split("\n report:\n", 1)[0] + download = bench.split("- name: Download the benched commit's engine map\n", 1)[1].split("\n\n")[0] + self.assertIn("name: devkit-bench-engines", download) + self.assertIn("if: ${{ !inputs.mode }}", download) + self.assertNotIn("needs.resolve.outputs.head-sha", bench.replace( + "head-sha: ${{ needs.resolve.outputs.head-sha }}", "")) + overlay = bench.split("- name: Overlay\n", 1)[1].split("\n\n")[0] + self.assertIn("engines: ${{ !inputs.mode && 'bench-run/engines.json' || '' }}", overlay) + action = (REPO / ".github/actions/devkit-overlay-package/action.yml").read_text(encoding="utf-8") + self.assertIn('args+=(--engines "${ENGINES}")', action) + self.assertIn('$cmdArgs += "--engines=$env:ENGINES"', action) + def test_unreadable_head_maps_fall_back_to_the_base(self): plan = resolve.write_plan(head_sha=SHA_A, package_sha=SHA_B, engines="success", families="qwen3", builds={"lin-xrt": "success"}) @@ -929,6 +1074,13 @@ def test_only_the_hard_gate_fails_summary(self): block = bench.split(f"- name: {step}\n", 1)[1].split("\n\n")[0] self.assertIn("overwrite: true", block, step) + def test_dispatch_ancestor_check_has_the_history(self): + # find-build on main checks ancestry in the resolve job's checkout. + job = workflow("devkit-bench.yml").split("\n resolve:\n", 1)[1].split("\n npu-gate:\n", 1)[0] + self.assertIn('--ref "${GITHUB_REF}"', job) + checkout = job.split("- name: Checkout\n", 1)[1].split("\n\n")[0] + self.assertIn("fetch-depth: 0", checkout) + def test_bench_workflow_has_no_secrets_or_writes(self): text = workflow("devkit-bench.yml") self.assertNotIn("secrets.", text) diff --git a/.github/script/ci/test_devkit_check.py b/.github/script/ci/test_devkit_check.py index 96aef056f..f16d29a33 100644 --- a/.github/script/ci/test_devkit_check.py +++ b/.github/script/ci/test_devkit_check.py @@ -9,6 +9,7 @@ import json import os import shutil +import stat import subprocess import sys import tempfile @@ -49,6 +50,17 @@ """ +def rmtree(path: Path) -> None: + """shutil.rmtree that also removes read-only files (git objects on Windows).""" + def fix(func, p, _exc): + os.chmod(p, stat.S_IWRITE) + func(p) + if sys.version_info >= (3, 12): + shutil.rmtree(path, onexc=fix) + else: + shutil.rmtree(path, onerror=fix) + + class Tree: """A minimal repository with every file devkit_check reads.""" @@ -120,7 +132,7 @@ def setUp(self): self.addCleanup(patcher.stop) def tearDown(self): - shutil.rmtree(self.tmp) + rmtree(self.tmp) def assertError(self, *fragments: str) -> None: errors = self.tree.errors() diff --git a/.github/script/ci/test_devkit_rtp_lock.py b/.github/script/ci/test_devkit_rtp_lock.py index ad420b16e..e139b64ad 100644 --- a/.github/script/ci/test_devkit_rtp_lock.py +++ b/.github/script/ci/test_devkit_rtp_lock.py @@ -44,8 +44,8 @@ def setUp(self): self.write("devkit-xclbins-shard-1/xclbins-Unused/layer.xclbin", "x") self.write("devkit-xclbins-shard-1/xclbins-Unused/rtp_addresses.txt", "R 7\n") self.lock = self.tmp / "lock.txt" - (self.tmp / "a.json").write_text(json.dumps(ASSIGNMENT)) - (self.tmp / "e.json").write_text(json.dumps(ENGINES)) + (self.tmp / "a.json").write_text(json.dumps(ASSIGNMENT), encoding="utf-8") + (self.tmp / "e.json").write_text(json.dumps(ENGINES), encoding="utf-8") def tearDown(self): shutil.rmtree(self.tmp) @@ -53,7 +53,7 @@ def tearDown(self): def write(self, rel: str, text: str) -> None: p = self.shards / rel p.parent.mkdir(parents=True, exist_ok=True) - p.write_text(text) + p.write_text(text, encoding="utf-8") def run_cli(self, *args: str) -> tuple[int, str]: out = io.StringIO() @@ -73,7 +73,7 @@ def check(self) -> tuple[int, str]: class Format(Fixture): def test_generate_is_sorted_and_normalized(self): self.assertEqual(self.generate("--note", "from run 1"), 0) - text = self.lock.read_text() + text = self.lock.read_text(encoding="utf-8") self.assertTrue(text.startswith("# Copyright © Advanced Micro Devices")) self.assertIn("# from run 1\n", text) body = text[text.index("\n["):] @@ -85,7 +85,7 @@ def test_generate_is_sorted_and_normalized(self): self.assertIn("from run 1", header) # Generating again gives the same bytes. self.generate("--note", "from run 1") - self.assertEqual(self.lock.read_text(), text) + self.assertEqual(self.lock.read_text(encoding="utf-8"), text) def test_parse_errors(self): for text, fragment in (("RTP_A 1\n", "expected [/]"), @@ -111,9 +111,9 @@ def test_changed_artifacts(self): def test_update_keeps_artifacts_not_built(self): self.lock.write_text("[xclbins-Smol/rtp_addresses.txt]\nR 5\n\n" "[xclbins-Other/rtp_addresses.txt]\nR 5\n\n" - "[xclbins-G_decoding_E4B/old_rtp_addresses.txt]\nR 6\n") + "[xclbins-G_decoding_E4B/old_rtp_addresses.txt]\nR 6\n", encoding="utf-8") self.generate("--update") - entries, _ = rl.parse_lock(self.lock.read_text()) + entries, _ = rl.parse_lock(self.lock.read_text(encoding="utf-8")) # Smol kept; Other dropped (no model uses it); E4B was built, so its # stanzas are this run's only. self.assertIn(("xclbins-Smol", "rtp_addresses.txt"), entries) @@ -125,16 +125,16 @@ def test_update_keeps_header_notes(self): self.generate("--note", "Generated from run 1, all builds.") shutil.rmtree(self.shards / "devkit-xclbins-shard-0") self.generate("--update", "--note", "E4B from run 2.") - entries, header = rl.parse_lock(self.lock.read_text()) + entries, header = rl.parse_lock(self.lock.read_text(encoding="utf-8")) self.assertEqual(rl.header_notes(header), ["Generated from run 1, all builds.", "E4B from run 2."]) self.assertIn(("xclbins-G_decoding_E2B", "rtp_addresses.txt"), entries) # Without --update, the notes are only those given. self.generate("--note", "run 3") - self.assertEqual(rl.header_notes(rl.parse_lock(self.lock.read_text())[1]), ["run 3"]) + self.assertEqual(rl.header_notes(rl.parse_lock(self.lock.read_text(encoding="utf-8"))[1]), ["run 3"]) def test_artifacts_no_model_uses_are_left_out(self): self.generate() - entries, _ = rl.parse_lock(self.lock.read_text()) + entries, _ = rl.parse_lock(self.lock.read_text(encoding="utf-8")) self.assertFalse(any(a == "xclbins-Unused" for a, _ in entries)) @@ -182,7 +182,7 @@ def test_errors_name_their_source(self): rc, out = self.check() self.assertEqual(rc, 1) self.assertIn(f"::error::{self.shards}: xclbins-Dequant appears twice", out) - self.lock.write_text("[xclbins-A/r.txt]\n# c\nR 1\n") + self.lock.write_text("[xclbins-A/r.txt]\n# c\nR 1\n", encoding="utf-8") rc, out = self.check() self.assertEqual(rc, 1) self.assertIn(f"::error::{self.lock}: line 2", out) @@ -198,7 +198,7 @@ def test_summary(self): del os.environ["GITHUB_STEP_SUMMARY"] self.assertEqual(rc, 1) self.assertIn("| `xclbins-G_decoding_E4B` | `rtp_addresses.txt` | differs from the lock | g:4b, v:1b |", - summary.read_text()) + summary.read_text(encoding="utf-8")) class RealLock(unittest.TestCase): diff --git a/.github/script/ci/test_devkit_swap.py b/.github/script/ci/test_devkit_swap.py index d87d24f9a..0369921a6 100644 --- a/.github/script/ci/test_devkit_swap.py +++ b/.github/script/ci/test_devkit_swap.py @@ -1004,6 +1004,81 @@ def test_symlinked_directory_is_refused(self): ds.safe_target(tmp / "repo", "src/xclbins/M/a.xclbin") +class MainMoved(unittest.TestCase): + """main_moved: which commits on main since a run's base make its swap + stale (documentation under SOURCE_PATHS does not; code, build inputs and + binaries do).""" + + def setUp(self): + tmp = Path(tempfile.mkdtemp()) + self.addCleanup(rmtree, tmp) + self.repo = Repo(tmp) + self.base = self.repo.commit({**DEVKIT_DATA, **OLD}, "base") + self.git = ds.Git(self.repo.path) + + def moved(self, files: dict[str, bytes]) -> list[str]: + commit = self.repo.commit(files) + moved = ds.main_moved(self.git, self.base, "main") + self.assertIn(moved, ([], [commit])) + return moved + + def test_docs_only_does_not_count(self): + # Like a pull request editing only the Markdown under FLM_DLL. + self.assertEqual(self.moved({"flm-dev-kit/FLM_DLL/README.md": b"# x\n", + "flm-dev-kit/FLM_DLL/detail/foo_npu/NOTES.md": b"x\n", + "flm-dev-kit/FLM_Xclbin/.gitignore": b"build/\n"}), []) + + def test_elsewhere_does_not_count(self): + self.assertEqual(self.moved({"src/server/x.cpp": b"//\n", "flm-dev-kit/FLM_Pybind/x.cpp": b"//\n"}), []) + + def test_code_counts(self): + for path in ("flm-dev-kit/FLM_DLL/detail/foo_npu/foo.cpp", "flm-dev-kit/FLM_DLL/detail/foo_npu/Makefile", + "flm-dev-kit/FLM_Xclbin/x/gen.py"): + with self.subTest(path=path): + self.assertEqual(len(self.moved({path: path.encode()})), 1) + self.base = self.repo.git("rev-parse", "HEAD") + + def test_docs_beside_code_counts(self): + self.assertEqual(len(self.moved({"flm-dev-kit/FLM_DLL/README.md": b"# y\n", + "flm-dev-kit/FLM_DLL/detail/foo_npu/foo.cpp": b"//\n"})), 1) + + def test_binaries_count(self): + # Anything under src/lib and src/xclbins, even a Markdown file. + for path, data in ((KERNEL, blob("main-k")), (XRT_LIN, blob("main-so")), + ("src/xclbins/M-NPU2/README.md", b"# x\n"), ("src/lib/xrt/notes.md", b"x\n")): + with self.subTest(path=path): + self.assertEqual(len(self.moved({path: data})), 1) + self.base = self.repo.git("rev-parse", "HEAD") + + def test_merged_side_branch(self): + self.repo.git("checkout", "-q", "-b", "side") + code = self.repo.commit({"flm-dev-kit/FLM_DLL/detail/foo_npu/foo.cpp": b"//\n"}) + docs = self.repo.commit({"flm-dev-kit/FLM_DLL/README.md": b"# x\n"}) + self.repo.git("checkout", "-q", "main") + self.repo.commit({"src/server/x.cpp": b"//\n"}) + self.repo.git("merge", "-q", "--no-ff", "-m", "merge", "side") + moved = ds.main_moved(self.git, self.base, "main") + self.assertIn(code, moved) + self.assertNotIn(docs, moved) + + def test_unknown_or_unrelated_base(self): + with self.assertRaisesRegex(ds.SwapError, "not in this clone"): + ds.main_moved(self.git, "0" * 40, "main") + self.repo.git("checkout", "-q", "--orphan", "other") + other = self.repo.commit({"x.txt": b"x\n"}) + with self.assertRaisesRegex(ds.SwapError, "is not a commit of main"): + ds.main_moved(self.git, other, "main") + + def test_non_code_is_changes_pys(self): + # verify runs the pull request's code, and changes.py is not in + # SWAP_CI_PATHS: main_moved keeps its own copy of NON_CODE, which + # must stay equal to changes.py's. + import changes + self.assertEqual((ds.NON_CODE.pattern, ds.NON_CODE.flags), + (changes.NON_CODE.pattern, changes.NON_CODE.flags)) + self.assertNotIn("changes", vars(ds)) + + class Wiring(unittest.TestCase): """devkit_check.py's swap wiring rule, on this tree and on a broken copy.""" diff --git a/.github/script/ci/test_devkit_xclbin_compare.py b/.github/script/ci/test_devkit_xclbin_compare.py index 5408cbbf8..8f0b21703 100644 --- a/.github/script/ci/test_devkit_xclbin_compare.py +++ b/.github/script/ci/test_devkit_xclbin_compare.py @@ -175,7 +175,11 @@ def test_unreadable_files_are_rows(self): self.put("devkit/A-NPU2/attn.xclbin", base) self.put("shipped/A-NPU2/attn.xclbin", base) self.put("shipped/A-NPU2/mm.xclbin", base) - (self.tmp / "devkit/A-NPU2/mm.xclbin").symlink_to(self.tmp / "gone.xclbin") + try: + (self.tmp / "devkit/A-NPU2/mm.xclbin").symlink_to(self.tmp / "gone.xclbin") + except (OSError, NotImplementedError): + # Windows without Developer Mode or the privilege to create one. + self.skipTest("cannot create a symbolic link here") rc, out = self.run_main("--devkit", str(self.tmp / "devkit"), "--shipped", str(self.tmp / "shipped"), "--json", str(self.tmp / "out.json")) self.assertEqual(rc, 0) diff --git a/.github/script/devkit-bench/resolve.py b/.github/script/devkit-bench/resolve.py index e76e730aa..d523284a8 100644 --- a/.github/script/devkit-bench/resolve.py +++ b/.github/script/devkit-bench/resolve.py @@ -9,7 +9,7 @@ --engines success|failure|skipped [--families a,b] [--xclbin-models JSON] [--bench-models JSON] [--xclbins devkit-xclbins] - resolve.py find-build --repo R --head-sha S [--run-id N] + resolve.py find-build --repo R --head-sha S [--run-id N] [--ref R] [--wait-minutes 200] --plan-out plan.json [--artifacts-out artifacts.json] resolve.py find-baseline --repo R @@ -27,7 +27,14 @@ run): it finds that run and waits (polling) for it to complete. The run must be of .github/workflows/build-and-test.yml in this repository, for exactly this head commit (a run id given is checked the same way), the newest such -run, completed with success or failure. Its plan is derived from the +run, completed with success or failure. On main (--ref refs/heads/main), +which moves often, a run id given may also be this repository's Build and +Test push run on main for an earlier commit: one whose head is an ancestor +of the dispatched commit (git merge-base --is-ancestor in --repo-root, which +needs the history: devkit-bench.yml checks out with fetch-depth 0). The +plan, and so everything that names the benched commit, then has the run's +head, not the dispatched commit: the packages and dev-kit builds benched +are that run's. Its plan is derived from the artifacts it uploaded and its devkit-engines job's result (plan_from_artifacts), with write-plan's rules: a runtime benches when its package is there and the engines built (then with that runtime's dev-kit @@ -87,6 +94,7 @@ # artifacts last 90 days). BASELINE_WORKFLOWS = (BUILD_WORKFLOW, BENCH_WORKFLOW) BASELINE_ARTIFACT = "devkit-bench-baseline" +MAIN_REF = "refs/heads/main" SHA = re.compile(r"^[0-9a-f]{40}$") REPO = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") ARTIFACT = re.compile(r"^[A-Za-z0-9._-]{1,128}$") @@ -164,6 +172,33 @@ def run_matches(run: dict, *, repo: str, head_sha: str) -> bool: and run.get("head_sha") == head_sha) +def main_push_run(run: dict, *, repo: str) -> bool: + """Whether a run is this repository's Build and Test push run on main + (whatever its commit: see find_build_ok).""" + return (run.get("path") == BUILD_WORKFLOW and _full_name(run.get("repository")) == repo + and _full_name(run.get("head_repository")) == repo and run.get("event") == "push" + and run.get("head_branch") == "main" and SHA.match(str(run.get("head_sha") or "")) is not None) + + +def is_ancestor(repo_root: Path, ancestor: str, commit: str) -> bool: + """Whether ancestor is commit or one of its ancestors, in repo_root's + history (False when either is not there).""" + proc = subprocess.run(["git", "-C", str(repo_root), "merge-base", "--is-ancestor", ancestor, commit], + capture_output=True) + return proc.returncode == 0 + + +def find_build_ok(run: dict, *, repo: str, head_sha: str, ref: str, repo_root: Path) -> bool: + """Whether a dispatch may bench a run it names: this repository's Build + and Test for exactly the dispatched commit (run_matches), or, for a + dispatch on main only, its push run on main for that commit or an + ancestor of it (main moves on while a run builds and tests).""" + if run_matches(run, repo=repo, head_sha=head_sha): + return True + return (ref == MAIN_REF and main_push_run(run, repo=repo) + and is_ancestor(repo_root, run["head_sha"], head_sha)) + + def pick_build_run(runs: list[dict], **match) -> Optional[dict]: hits = [r for r in runs if run_matches(r, **match)] return max(hits, key=lambda r: (r.get("run_number", 0), r.get("run_attempt", 0))) if hits else None @@ -430,10 +465,13 @@ def cmd_find_build(args) -> int: while True: if args.run_id: candidate = api_get(f"repos/{args.repo}/actions/runs/{int(args.run_id)}") - run = candidate if run_matches(candidate, repo=args.repo, head_sha=args.head_sha) else None + run = candidate if find_build_ok(candidate, repo=args.repo, head_sha=args.head_sha, ref=args.ref, + repo_root=Path(args.repo_root)) else None if run is None: - write_outputs({"ok": "false", "run-id": "", "reason": "run is not this repository's " - "Build and Test run for this commit"}) + reason = "run is not this repository's Build and Test run for this commit" + if args.ref == MAIN_REF: + reason += " nor its push run on main for an earlier commit of main" + write_outputs({"ok": "false", "run-id": "", "reason": reason}) return 0 else: runs = api_get(f"repos/{args.repo}/actions/workflows/build-and-test.yml/runs", @@ -465,8 +503,11 @@ def cmd_find_build(args) -> int: "reason": f"Build and Test run {run['id']} built no dev-kit engines or kernels"}) return 0 Path(args.plan_out).write_text(json.dumps(plan, indent=1), encoding="utf-8") + # The run's head, which on main may be an earlier commit than the + # dispatched one: its packages and dev-kit builds are what is benched. + earlier = f" of {run['head_sha'][:10]}" if run["head_sha"] != args.head_sha else "" write_outputs({"ok": "true", "run-id": str(run["id"]), "head-sha": run["head_sha"], - "reason": f"Build and Test run {run['id']}"}) + "reason": f"Build and Test run {run['id']}{earlier}"}) return 0 @@ -531,11 +572,21 @@ def cmd_plan(args) -> int: # --data-from-head: a model the pull request adds is only in its catalog # and engines.json, and is benched like the NPU tests test it. Without # that commit (a fork's head is not fetched) the base's data is used. + # A dispatch always selects from the benched commit's data: on main it + # may bench an earlier push run, whose packages hold that commit's + # models and engines, not the dispatched commit's. Its checkout has the + # whole history (find-build checked the ancestry in it), so a map it + # cannot read there fails the plan rather than select from another + # commit's. catalog = None - if args.data_from_head: + if args.data_from_head or args.mode == "dispatch": try: catalog, engines, assignment = load_maps(repo_root, plan["head_sha"]) except (OSError, ValueError) as exc: + if args.mode == "dispatch": + write_outputs({**no, "reason": f"cannot read the catalog or dev-kit maps of the benched " + f"{plan['head_sha'][:10]}: {exc}"}) + return 1 notes.append(f"the catalog and dev-kit maps of {plan['head_sha'][:10]} are not readable " f"({exc}): selecting from the base's") if catalog is None: @@ -602,6 +653,9 @@ def main(argv=None) -> int: p.add_argument("--repo", required=True) p.add_argument("--head-sha", required=True) p.add_argument("--run-id", default="") + p.add_argument("--ref", default="", help="the dispatch's github.ref: on main, --run-id may be the " + "push run of an ancestor of --head-sha") + p.add_argument("--repo-root", default=str(HERE.parents[2]), help="a checkout with --head-sha's history") p.add_argument("--wait-minutes", type=float, default=200) p.add_argument("--poll-seconds", type=float, default=60) p.add_argument("--plan-out", required=True) diff --git a/.github/workflows/devkit-bench.yml b/.github/workflows/devkit-bench.yml index 1315e649a..ab9ea3337 100644 --- a/.github/workflows/devkit-bench.yml +++ b/.github/workflows/devkit-bench.yml @@ -83,7 +83,10 @@ name: Dev-kit Bench # Dispatch (re-benches an earlier Build and Test run, or exercises a change # to the bench CI itself, for which Build and Test calls nothing): build-run # names the Build and Test run to bench (default the newest for this -# commit), whose artifacts are looked up and checked across runs, with the +# commit; on main, which moves on while a run builds, also a push run on main +# of an earlier commit, whose commit is then the one benched and reported, and +# whose catalog and dev-kit maps select the models and the engines overlaid), +# whose artifacts are looked up and checked across runs, with the # rules the call uses (a runtime whose dev-kit engines failed or whose # libraries are gone is left out; a run that built no dev-kit engines or # kernels benches nothing); models replaces the selection, which otherwise is @@ -141,7 +144,7 @@ on: workflow_dispatch: inputs: build-run: - description: Build and Test run id whose artifacts to bench (default the newest for this commit) + description: Build and Test run id whose artifacts to bench (default the newest for this commit; on main, also a push run on main of an earlier commit) type: string default: '' models: @@ -198,7 +201,8 @@ jobs: esac # The pull request's base: its scripts, catalog and dev-kit maps. - # Full history for the nightly's changes.py diff. + # Full history for the nightly's changes.py diff and a dispatch's + # ancestor check (find-build --ref on main). - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -238,7 +242,10 @@ jobs: --xclbins "${XCLBINS}" # Dispatch: an earlier Build and Test run, checked (this repository, - # this commit, completed) and its artifacts listed; waits for it. + # this commit, completed) and its artifacts listed; waits for it. On + # main, build-run may also be a push run on main of an ancestor of + # this commit (checked with git in the checkout above: fetch-depth 0); + # the plan then benches and names that run's commit. - name: Find Build and Test's run id: build if: steps.ready.outputs.ready == 'true' && steps.mode.outputs.mode == 'dispatch' @@ -247,7 +254,7 @@ jobs: RUN_ID: ${{ inputs.build-run }} run: | python3 .github/script/devkit-bench/resolve.py find-build --repo "${GITHUB_REPOSITORY}" \ - --head-sha "${GITHUB_SHA}" --run-id "${RUN_ID}" --wait-minutes 200 \ + --head-sha "${GITHUB_SHA}" --ref "${GITHUB_REF}" --run-id "${RUN_ID}" --wait-minutes 200 \ --plan-out "${RUNNER_TEMP}/plan.json" --artifacts-out "${RUNNER_TEMP}/artifacts.json" - name: Note why nothing is benched @@ -310,6 +317,33 @@ jobs: fi python3 .github/script/devkit-bench/resolve.py "${args[@]}" + # A dispatch may bench an earlier run of main: the engines its overlay + # replaces are those that run's commit's engines.json names (the + # libraries were built from it), not the dispatched commit's. Read it + # here, as data, from this full-history checkout and hand it to the + # bench jobs as an artifact, so no bench job checks out a computed + # commit. + - name: Engine map of the benched commit + id: engines + if: ${{ !inputs.mode && steps.plan.outputs.bench == 'true' }} + env: + HEAD_SHA: ${{ steps.plan.outputs.head-sha }} + run: | + [[ "${HEAD_SHA}" =~ ^[0-9a-f]{40}$ ]] || { echo "::error::head-sha is not a commit sha"; exit 1; } + mkdir -p "${RUNNER_TEMP}/bench-engines" + git show "${HEAD_SHA}:flm-dev-kit/FLM_DLL/engines.json" > "${RUNNER_TEMP}/bench-engines/engines.json" + python3 -c 'import json, sys; json.load(open(sys.argv[1], encoding="utf-8"))' \ + "${RUNNER_TEMP}/bench-engines/engines.json" + + - name: Upload the engine map + if: steps.engines.outcome == 'success' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: devkit-bench-engines + path: ${{ runner.temp }}/bench-engines/engines.json + retention-days: 1 + overwrite: true + # ── NPU approval gate, dispatch only ───────────────────────────────────── # Called, Build and Test's npu-gate / npu-approve already gate the call # (the same rules; see there). A dispatch on main is ungated; one on any @@ -451,6 +485,18 @@ jobs: sparse-checkout: .github/script filter: blob:none + # A dispatch on main may bench an earlier push run: the engines it + # overlays are those its commit's engines.json names (the libraries + # were built from it), not the dispatched commit's. resolve read it + # (git show, data only) and uploaded it: nothing here checks out a + # computed commit. + - name: Download the benched commit's engine map + if: ${{ !inputs.mode }} + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: devkit-bench-engines + path: bench-run + # A pull request's and the full refresh's packages already hold the # staged dev-kit files: nothing to overlay. Nightly and a dispatch # overlay the dev-kit builds. No unmodified base copy is kept: no A/B @@ -465,6 +511,7 @@ jobs: libs: ${{ (inputs.mode == 'nightly' || !inputs.mode) && matrix.libs || '' }} xclbins: ${{ (inputs.mode == 'nightly' || !inputs.mode) && matrix.xclbins || '' }} families: ${{ (inputs.mode == 'nightly' || !inputs.mode) && matrix.families || '' }} + engines: ${{ !inputs.mode && 'bench-run/engines.json' || '' }} # Dispatch: the earlier Build and Test run's; called: this run's. run-id: ${{ needs.resolve.outputs.build-run-id }} github-token: ${{ needs.resolve.outputs.build-run-id != '' && github.token || '' }} diff --git a/flm-dev-kit/AGENTS.md b/flm-dev-kit/AGENTS.md index 0e20314e4..369557ddc 100644 --- a/flm-dev-kit/AGENTS.md +++ b/flm-dev-kit/AGENTS.md @@ -151,7 +151,10 @@ accuracy. Do not invent a `make test` or claim tests pass. comment; any bench failure other than the accuracy hard gate (perf, a pull, a timeout, infrastructure) warns; only a model failing that gate (acc_common: no predictions, or too many unanswered) fails the required check, which therefore waits for the benches. A manual dispatch of - that workflow re-benches an earlier Build and Test run: it benches by default (force), and without + that workflow re-benches an earlier Build and Test run (`build-run`, of the dispatched commit; a + dispatch on main may also name the push run on main of an earlier commit of main, whose commit is + then the one benched and reported, and whose catalog, `engines.json` and `kernel_assignment.json` + select the models and the engines overlaid): it benches by default (force), and without `models` takes the nightly's rotation, so name the models to re-bench a pull request's. The full refresh benches every benchable model on the four runtimes and reports only its own numbers. @@ -176,7 +179,9 @@ as a *swap commit*. allowed being the *Dev-kit swap pending* step; a failed bench job does not count unless a model failed the accuracy hard gate, which fails `summary`'s *Dev-kit checks*; the product test job of every system and runtime it staged files into passed; and no commit on main since the run's base touches `FLM_DLL/`, `FLM_Xclbin/`, `../src/lib/` or - `../src/xclbins/`: otherwise merge main and let CI run again), downloads the staged files, checks + `../src/xclbins/` (documentation under `FLM_DLL/` and `FLM_Xclbin/`, what `changes.py` + `NON_CODE` calls non-code such as `*.md`, does not count; `devkit_swap.py` keeps a copy pinned equal + by its tests, so a pull request's `changes.py` cannot widen it): otherwise merge main and let CI run again), downloads the staged files, checks every SHA-256 against the manifests, writes them and makes one commit with the trailers `Devkit-Swap-Run: ` and `Devkit-Swap-Tested: `. It does not push. The dev-kit artifacts are kept 7 days: once they expire, re-run the workflow.