diff --git a/.claude/commands/recover-failed-ingest.md b/.claude/commands/recover-failed-ingest.md index 91baa7dfb0..bcba156303 100644 --- a/.claude/commands/recover-failed-ingest.md +++ b/.claude/commands/recover-failed-ingest.md @@ -29,7 +29,7 @@ gh api --paginate "repos/SemiAnalysisAI/InferenceX/actions/runs/$RUN_ID/artifact | --- | --- | | `results_bmk/agg_bmk.json` | JSON array; filter the intended model, hardware, topology, scenario, and concurrency. The collector parses JSON but does not validate or deduplicate rows. | | `eval_results_all/agg_eval_all.json` and `eval_*` | Aggregate rows must match task, concurrency, score, and `n_eff`; retain per-config `meta_env.json`, results, and samples where needed. Collection may keep completed points from failed batches; reuse requires valid coverage. | -| `bmk_agentic_` and `agentic_` | Pair exact suffixes, including `_concN`; raw `profile_export.jsonl` is required. Preserve dataset identity, request accounting, and relevant `server_logs_*`. | +| `bmk_agentic_` and `agentic_` | Pair exact suffixes, including `_concN`; raw `profile_export.jsonl` is required. Preserve dataset identity, request accounting, and relevant `server_logs_*`. `num_requests_successful` counts profiled records only, while `num_requests_total` also counts warmup drops, so their ratio is not an error rate. Read `request_accounting.records_error_dropped` and `error_categories` instead. | | Power audits | Retained diagnostics or `power_valid` alone do not prove successful requests, answer quality, or publishable power. Inspect the outcome and each required window's validity. | Download only unexpired artifacts into a fresh `mktemp -d` directory. Check shape @@ -84,8 +84,11 @@ For PR-number input, use `gh pr view "$ORIGINAL_PR" --json mergeCommit` and with `-R SemiAnalysisAI/InferenceX`; select the exact target, not the newest unrelated run. Find completed `pull_request` runs of `run-sweep.yml` on the original PR branch. -Skip no-op reuse-gate runs without results. Require success unless the user explicitly -pinned the exact failed/cancelled source; only its completed, valid points can be recovered. +Skip no-op reuse-gate runs without results (zero artifacts, about 30 seconds long). +Require success unless the user explicitly pinned the exact failed/cancelled source; +only its completed, valid points can be recovered. Do not just take the run cited in +a sign-off. Later commits can change the recipe, so choose the newest run whose +execution inputs match the final PR head. ```bash SOURCE_JSON=$(gh api "repos/SemiAnalysisAI/InferenceX/actions/runs/$SOURCE_RUN_ID") @@ -104,6 +107,15 @@ uv run --project inferencex-e2e --extra workflows python -m infx.workflows.recov git diff "${ORIGINAL_MERGE_SHA}^" "$ORIGINAL_MERGE_SHA" -- inferencex-e2e/perf-changelog.yaml ``` +If the original PR merged `main`, a whole-tree diff mostly shows `main`'s changes. +Restrict the comparison to the files the original merge commit changed: + +```bash +git diff --name-only "${ORIGINAL_MERGE_SHA}^" "$ORIGINAL_MERGE_SHA" | + grep -v perf-changelog.yaml | xargs git diff --stat "$SOURCE_HEAD_SHA" \ + "refs/remotes/origin/source-pr-$ORIGINAL_PR" -- +``` + Compare the recovered config and its image, model, recipe, runner, launcher, arguments, and environment at the source SHA and final original PR head. Stop if execution semantics changed. Unrelated edits and generator/eval-selection @@ -116,9 +128,6 @@ intended entries from the original PR diff or stop on ambiguity. Create an empty bootstrap branch/commit from current `origin/main`, then open the PR before changing the changelog. Use a bilingual title/body and the required AI disclosure; set `BRANCH` and `RECOVERY_PR` to its branch and number. -An authorized `OWNER`, `MEMBER`, or `COLLABORATOR` must pin the source -with `/use ` (legacy `/reuse-sweep-run ` is also accepted). -Verify acknowledgement before pushing the changelog change. Reuse needs no sweep label. If a primary label is present, allow only one. Never use `evals-only` or `agentx-fast` on the recovery PR, or select a source @@ -144,44 +153,42 @@ Commit the append, set `RECOVERY_COMMIT=$(git rev-parse HEAD)`, and validate: ``` Require only the intended recovery scope; current matrix row counts may differ -from the source. With no uncommitted or untracked work, attach source ancestry -without changing the recovery tree: +from the source. Push the append, which starts no GPU jobs while the PR has no +primary sweep label: ```bash -test -z "$(git status --porcelain)" || exit 1 -TARGET_PARENT=$(git rev-parse HEAD) -TARGET_TREE=$(git rev-parse HEAD^{tree}) -ATTACH_SHA=$(printf 'chore: attach reusable sweep run %s\n' "$SOURCE_RUN_ID" | - git commit-tree "$TARGET_TREE" -p "$TARGET_PARENT" -p "$SOURCE_HEAD_SHA") -git reset --hard "$ATTACH_SHA" -test "$(git rev-parse HEAD^1)" = "$TARGET_PARENT" || exit 1 -test "$(git rev-parse HEAD^2)" = "$SOURCE_HEAD_SHA" || exit 1 -test "$(git rev-parse HEAD^{tree})" = "$(git rev-parse HEAD^1^{tree})" || exit 1 test "$(git diff --name-only origin/main...HEAD)" = "inferencex-e2e/perf-changelog.yaml" || exit 1 git diff --check origin/main...HEAD || exit 1 git push origin "$BRANCH" ``` -Never rebase, locally squash, amend, or force-push after attaching the source. -If `main` advances or conflicts, update from it and recreate the final two-parent -carrier; preserve the verified first-parent tree. Do not silently drop ancestry. +An authorized `OWNER`, `MEMBER`, or `COLLABORATOR` then pins the source with +`/use $SOURCE_RUN_ID` (legacy `/reuse-sweep-run ` is also accepted). The +source commit belongs to the original PR, not the recovery PR, so expect the bot to +react 👍 and post an outside-PR warning comment. Require the 👍 before merging. +A 👎 explains itself only in the matching `reuse-sweep-comment.yml` run log +(`Reuse rejected / 复用请求未接受: ...`). ## Verify reuse and merge ```bash -gh api --paginate "repos/SemiAnalysisAI/InferenceX/pulls/$RECOVERY_PR/commits" \ - --jq '.[].sha' | grep -Fx "$SOURCE_HEAD_SHA" test "$(gh pr diff "$RECOVERY_PR" -R SemiAnalysisAI/InferenceX --name-only)" = \ "inferencex-e2e/perf-changelog.yaml" gh pr checks "$RECOVERY_PR" -R SemiAnalysisAI/InferenceX --watch --fail-fast ``` -Wait for the `run-sweep.yml` run at `ATTACH_SHA`, not just early comment checks. +Wait for the `run-sweep.yml` run at the PR head, not just early comment checks. Require passing `check-changelog` and `reuse-sweep-gate`, with `setup` and GPU jobs -skipped. Keep `ATTACH_SHA` as the PR head. Merge only with explicit authorization; -never bypass failed or pending checks. Admin merge is allowed only when passing -checks leave repository policy as the sole blocker. GitHub squash merge is safe -because it does not rewrite the PR branch's recorded ancestry. +skipped. Merge only with explicit authorization; never bypass failed or pending +checks. Admin merge is allowed only when passing checks leave repository policy as +the sole blocker. Do not use `merge_with_reuse` here. It posts its own +`/reuse-sweep-run` chosen from the recovery PR's commits, which supersedes the pinned +source and finds no sweep. Merge directly: + +```bash +gh pr merge "$RECOVERY_PR" -R SemiAnalysisAI/InferenceX --squash --admin \ + --match-head-commit "$(git rev-parse HEAD)" +``` ## Verify the exact publication diff --git a/.github/codeowner-signoff-verify-prompt.md b/.github/codeowner-signoff-verify-prompt.md index a8734f1b7a..decb219c58 100644 --- a/.github/codeowner-signoff-verify-prompt.md +++ b/.github/codeowner-signoff-verify-prompt.md @@ -69,12 +69,12 @@ Then decide: Name the path and its real owners in one line. ## Check 1 — A passing sweep + evals ran on a commit IN this PR -The merge standard (and InferenceX's own reuse gate) requires a green full sweep, -including evals, on a commit that is CURRENTLY part of this PR. A sweep that ran on a -commit later rebased/force-pushed out does NOT count: at merge, `merge_with_reuse.py` -→ `validate_reusable_run` (in `inferencex-e2e/infx/workflows/reuse.py`) rejects any source -whose `head_sha` is not in `GET /pulls//commits`. So the whole question collapses -to one fact: does a commit still in this PR carry green, executed sweep/eval checks? +The merge standard requires a green full sweep, including evals, on a commit that is +CURRENTLY part of this PR. A sweep that ran on a commit later rebased/force-pushed out +does NOT count. The reuse tooling no longer enforces this: a pinned `/use ` may +name any run, and the acknowledgement bot only posts a warning comment when its commit is outside the +PR. This check is therefore the enforcement point, and the whole question collapses to +one fact: does a commit still in this PR carry green, executed sweep/eval checks? The cleanest way to answer is the check-runs attached to each in-PR commit. You do NOT need to list `run-sweep.yml` runs or parse reuse logs. diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 37f1fd399c..0ef456826a 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -258,8 +258,8 @@ a primary sweep label on the PR, although staging its results requires one: ``` Keep the command and required run ID on one line. This pins an eligible completed -`run-sweep.yml` PR run whose commit remains in the PR, including failed or cancelled -runs with usable results. +`run-sweep.yml` PR run, including failed or cancelled runs with usable results. The +run may come from any PR; its commit need not be part of this one. The legacy `/reuse-sweep-run ` remains equivalent. Bare `/reuse-sweep-run` selects the latest successful eligible run automatically; bare `/use` is rejected. @@ -271,9 +271,10 @@ certify a green full sweep. Verify coverage and pin the run ID when a full sweep is required by the review process. The latest matching comment across both names by an `OWNER`, `MEMBER`, or `COLLABORATOR` wins. -The bot reacts with 👍 after validating the request, or 👎 on rejection; details -are in the Actions run summary. Edits replace the bot's old reaction. The reuse -check posts no comment, but `/use ` also triggers `stage-results.yml`. +The bot reacts with 👍 after validating the request, or 👎 on rejection. When the +pinned run's commit is not part of the PR, it also posts one warning comment for +that request and run; reuse still proceeds. Details are in the Actions run summary. +Edits replace the bot's old reaction. `/use ` also triggers `stage-results.yml`. Staging requires a primary sweep label on the PR and a source run created while one was applied. It posts a staging comment, or a rejection comment when the PR has no primary label. Comments do not trigger or cancel GPU sweeps. Later commits diff --git a/.github/workflows/merge-ingest.yml b/.github/workflows/merge-ingest.yml index 55dcdefbb1..04a21de17c 100644 --- a/.github/workflows/merge-ingest.yml +++ b/.github/workflows/merge-ingest.yml @@ -66,7 +66,7 @@ jobs: with: script: | await core.summary.addTable([ - ['Source PR', `#${process.env.SOURCE_PR}`], + ['Source PR', process.env.SOURCE_PR ? `#${process.env.SOURCE_PR}` : 'unknown'], ['Source run', process.env.SOURCE_RUN_URL], ['Reused benchmark source', process.env.SOURCE_SHA], ]).write(); diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7c28a4475c..fcf90a5b7b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -160,11 +160,11 @@ The verdict records only the commit actually assessed; it does not carry approva A full benchmark sweep is expensive GPU time, and the runners are shared by every open PR, so an approved PR's sweep runs only once, for PR validation. `main` never reruns it after merge; the reuse path publishes that PR sweep instead: -- After your PR has an eligible green full sweep, an authorized maintainer (`OWNER`/`MEMBER`/`COLLABORATOR`) comments `/use ` on the PR to select that run. Keep the command and run ID on the same line. +- After your PR has an eligible green full sweep, an authorized maintainer (`OWNER`/`MEMBER`/`COLLABORATOR`) comments `/use ` on the PR to select that run. Keep the command and run ID on the same line. The pinned run may come from any PR; if its commit is not part of this PR, reuse is still accepted but flagged as a warning. - `/reuse-sweep-run ` remains supported with identical behavior. Bare `/reuse-sweep-run` selects automatically; bare `/use` is rejected. - The merge-to-`main` run then validates and ingests the PR sweep's artifacts; `main` never re-runs the sweep itself. - **Reuse is mandatory.** A green sweep alone is not enough. The reuse command must be on record (the sign-off verification checks for it), otherwise the `main` run fails and the PR's results are never ingested. -- Reuse does not require retaining a primary label, but it is rejected while the PR carries `evals-only` or `agentx-fast`, and `merge_with_reuse` refuses a PR with more than one primary label. The bot reacts to the command with 👍 when accepted or 👎 when rejected, with details in the Actions run summary; source artifacts are revalidated at merge. +- Reuse does not require retaining a primary label, but it is rejected while the PR carries `evals-only` or `agentx-fast`, and `merge_with_reuse` refuses a PR with more than one primary label. The bot reacts to the command with 👍 when accepted or 👎 when rejected, with details in the Actions run summary, and posts a warning comment when the pinned run's commit is outside the PR; source artifacts are revalidated at merge. - A missing authorized reuse command produces a Check 4 **WARN**, not a rejection. The warning stays visible in the sign-off verdict; posting an authorized command is still required to reuse artifacts. - From the repository root, `uv run --project inferencex-e2e --extra workflows python -m infx.workflows.merge_with_reuse ` is the supported merge path. It posts the command, syncs the branch with `main`, waits for checks, and squash-merges. See the [workflows README](.github/workflows/README.md#reusing-an-approved-pr-full-sweep) for eligibility details. diff --git a/inferencex-e2e/infx/tests/workflows/test_acknowledge_sweep_reuse.py b/inferencex-e2e/infx/tests/workflows/test_acknowledge_sweep_reuse.py index 8e8ac3d689..1203e02e73 100644 --- a/inferencex-e2e/infx/tests/workflows/test_acknowledge_sweep_reuse.py +++ b/inferencex-e2e/infx/tests/workflows/test_acknowledge_sweep_reuse.py @@ -29,7 +29,7 @@ def make_request_case(monkeypatch) -> dict: "head_sha": "tested-sha"}, "commits": [{"sha": "tested-sha"}], "artifacts": [{"name": "results_bmk", "expired": False}], - "reactions": [], "writes": [], + "reactions": [], "writes": [], "posted": [], } def api(repo, path, token, params=None, *, method="GET", data=None): @@ -37,6 +37,14 @@ def api(repo, path, token, params=None, *, method="GET", data=None): assert token == "test-token" if case.get("fail_path") == path: raise RuntimeError("GitHub unavailable") + if method == "POST" and path == "/issues/7/comments": + if case.get("fail_warning"): + raise RuntimeError("comment write failed") + posted = {"id": 900 + len(case["posted"]), "body": data["body"], + "user": {"login": "github-actions[bot]"}} + case["posted"].append(posted) + case["comments"].append(posted) + return posted if method == "POST": assert path == "/issues/comments/41/reactions" case["writes"].append(data["content"]) @@ -59,6 +67,8 @@ def api(repo, path, token, params=None, *, method="GET", data=None): return case["pr"] if path == "/pulls/7/commits": return case["commits"] + if path == "/commits/tested-sha/pulls": + return case.get("source_pulls", []) if path == "/actions/runs/123": return case["run"] if path == "/actions/workflows/run-sweep.yml/runs": @@ -111,13 +121,40 @@ def test_explicit_partial_source_keeps_existing_acceptance(request_case, conclus assert bot_status(request_case) == ["+1"] +def test_source_outside_pr_is_accepted_then_warned_once(request_case, capsys): + request_case["commits"] = [{"sha": "different-sha"}] + request_case["run"]["head_branch"] = "other-branch" + request_case["source_pulls"] = [ + {"number": 6, "head": {"ref": "unrelated"}}, + {"number": 5, "head": {"ref": "other-branch"}}, + ] + event = event_for(request_case) + for _ in range(2): + assert acknowledgment.acknowledge("example/project", event, "test-token") == 0 + assert bot_status(request_case) == ["+1"] + assert len(request_case["posted"]) == 1 + assert "(from PR #5, commit `tested-sha`)" in request_case["posted"][0]["body"] + assert "::warning::Reuse source run 123 head tested-sha is not part of PR #7" in capsys.readouterr().out + + +def test_warning_comment_failure_keeps_acceptance(request_case): + request_case["commits"] = [{"sha": "different-sha"}] + request_case["fail_warning"] = True + assert acknowledgment.acknowledge("example/project", event_for(request_case), "test-token") == 0 + assert bot_status(request_case) == ["+1"] + + +def test_source_in_pr_posts_no_warning(request_case): + assert acknowledgment.acknowledge("example/project", event_for(request_case), "test-token") == 0 + assert request_case["posted"] == [] + + @pytest.mark.parametrize("problem,reason", [ ("unauthorized", "OWNER, MEMBER, or COLLABORATOR"), ("syntax", "Usage:"), ("closed", "not open"), ("workflow", "expected .github/workflows/run-sweep.yml"), ("running", "not completed"), - ("orphan", "not in PR #7's commit list"), ("empty", "no benchmark, eval, or agentic result artifact"), ("expired", "no benchmark, eval, or agentic result artifact"), ("modifier", "reuse-incompatible"), @@ -136,8 +173,6 @@ def test_rejects_invalid_requests_without_approving(request_case, capsys, proble case["run"]["path"] = ".github/workflows/other.yml" elif problem == "running": case["run"]["status"] = "in_progress" - elif problem == "orphan": - case["commits"] = [{"sha": "different-sha"}] elif problem == "empty": case["artifacts"] = [{"name": "run-stats"}] elif problem == "expired": diff --git a/inferencex-e2e/infx/tests/workflows/test_find_reusable_sweep_run.py b/inferencex-e2e/infx/tests/workflows/test_find_reusable_sweep_run.py index ea9d2e8a6b..c7c9202f53 100644 --- a/inferencex-e2e/infx/tests/workflows/test_find_reusable_sweep_run.py +++ b/inferencex-e2e/infx/tests/workflows/test_find_reusable_sweep_run.py @@ -336,7 +336,6 @@ def test_validate_reusable_run_rejects_non_success_run_by_default(conclusion) -> reuse.validate_reusable_run( "SemiAnalysisAI/InferenceX", "run-sweep.yml", - 1321, { "id": 25763404168, "event": "pull_request", @@ -430,6 +429,47 @@ def fake_paginated_github_api(repo, path, token, item_key, params=None): assert outputs["reuse-source-head-sha"] == "abc123" +def test_main_reports_outside_run_source_pr(monkeypatch, tmp_path) -> None: + run = { + "id": 77, "event": "pull_request", "status": "completed", "conclusion": "success", + "path": ".github/workflows/run-sweep.yml", "pull_requests": [], + "head_sha": "other-sha", "head_branch": "other-branch", + } + + def fake_github_api(repo, path, token, params=None): + return { + "/commits/merge-sha/pulls": [{"number": 1321}], + "/pulls/1321": {"merged_at": "2026-05-13T00:01:00Z", "labels": []}, + "/actions/runs/77": run, + "/commits/other-sha/pulls": [{"number": 900, "head": {"ref": "other-branch"}}], + }[path] + + def fake_paginated_github_api(repo, path, token, item_key, params=None): + return { + "/issues/1321/comments": [{ + "created_at": "2026-05-13T00:00:00Z", "author_association": "OWNER", + "body": "/use 77", + }], + "/pulls/1321/commits": [{"sha": "abc123"}], + "/actions/runs/77/artifacts": [{"name": "results_bmk"}], + }[path] + + output_path = tmp_path / "outputs" + monkeypatch.setenv("GITHUB_TOKEN", "token") + monkeypatch.setattr(reuse.github, "api", fake_github_api) + monkeypatch.setattr(reuse.github, "paginate", fake_paginated_github_api) + monkeypatch.setattr(reuse.sys, "argv", [ + "find_reusable_sweep_run.py", "--repo", "SemiAnalysisAI/InferenceX", + "--commit-sha", "merge-sha", "--event-name", "push", "--ref", "refs/heads/main", + "--github-output", str(output_path), + ]) + + assert reuse.main() == 0 + outputs = dict(line.split("=", 1) for line in output_path.read_text().splitlines()) + assert outputs["reuse-source-run-id"] == "77" + assert outputs["reuse-source-pr-number"] == "900" + + def test_main_enables_explicitly_pinned_failed_run(monkeypatch, tmp_path) -> None: comments = [ { diff --git a/inferencex-e2e/infx/workflows/reuse.py b/inferencex-e2e/infx/workflows/reuse.py index 7d23f1554d..599933cb1a 100644 --- a/inferencex-e2e/infx/workflows/reuse.py +++ b/inferencex-e2e/infx/workflows/reuse.py @@ -5,7 +5,8 @@ commit maps unambiguously to one pull request and a maintainer has left a ``/use `` or legacy ``/reuse-sweep-run`` comment. The legacy command may omit the source run ID; without one, the latest successful -``pull_request`` ``run-sweep.yml`` run for the PR head is used. +``pull_request`` ``run-sweep.yml`` run for the PR head is used. A pinned run ID may +come from any PR; its commit need not be part of the PR being merged. """ from __future__ import annotations @@ -25,6 +26,7 @@ completed_pr_runs, has_reusable_result_artifacts as has_reusable_result_artifacts, pr_commit_shas as pr_commit_shas, + run_pr_number as run_pr_number, ) DEFAULT_ALLOWED_AUTHOR_ASSOCIATIONS = ("OWNER", "MEMBER", "COLLABORATOR") @@ -164,7 +166,6 @@ def workflow_path(workflow_id: str) -> str: def validate_reusable_run( repo: str, workflow_id: str, - pr_number: int, run: dict[str, Any], token: str, allow_failed: bool = False, @@ -191,12 +192,6 @@ def validate_reusable_run( run_head_sha = str(run.get("head_sha") or "") if not run_head_sha: raise RuntimeError(f"Reusable source run {run_id} has no head_sha.") - pr_shas = pr_commit_shas(repo, pr_number, token) - if run_head_sha not in pr_shas: - raise RuntimeError( - f"Reusable source run {run_id} head {run_head_sha} is not in PR #{pr_number}'s " - f"commit list; pin a run whose commit is still part of the PR." - ) names = artifact_names(repo, run_id, token) if not has_reusable_result_artifacts(names): @@ -247,7 +242,6 @@ def resolve_reusable_run( validate_reusable_run( repo, workflow_id, - pr_number, run, token, allow_failed=pinned_run_id is not None, @@ -404,6 +398,11 @@ def main() -> int: ) run_id = int(run["id"]) reason = f"PR #{pr_number} approved sweep reuse from run {run_id}" + head_sha = str(run.get("head_sha") or "") + if head_sha in pr_commit_shas(args.repo, pr_number, token): + source_pr: int | None = pr_number + else: + source_pr = run_pr_number(args.repo, run, token) outputs = result( enabled=True, @@ -411,8 +410,8 @@ def main() -> int: source_run_id=str(run_id), source_run_attempt=str(run.get("run_attempt") or "1"), source_run_url=str(run.get("html_url") or ""), - source_pr_number=str(pr_number), - source_head_sha=str(run.get("head_sha") or ""), + source_pr_number=str(source_pr or ""), + source_head_sha=head_sha, ) write_outputs(args.github_output, outputs) print(json.dumps(outputs, indent=2)) diff --git a/inferencex-e2e/infx/workflows/reuse_comment.py b/inferencex-e2e/infx/workflows/reuse_comment.py index 71c0872bdb..f0a7bab6b0 100644 --- a/inferencex-e2e/infx/workflows/reuse_comment.py +++ b/inferencex-e2e/infx/workflows/reuse_comment.py @@ -1,4 +1,8 @@ -"""Acknowledge reuse requests with reactions; never post a separate comment.""" +"""Acknowledge reuse requests with reactions. + +An accepted request gets 👍. If its source run's commit is not part of the PR, +the bot also posts one warning comment per request and run; reuse still proceeds. +""" from __future__ import annotations @@ -13,6 +17,36 @@ from . import reuse +BOT_STATUS = ("+1", "-1") + + +def warn_outside_pr( + repo: str, pr_number: int, comment: dict[str, Any], run: dict[str, Any], token: str +) -> None: + """Post a warning comment once for a reuse source outside the PR.""" + marker = f"" + comments = github.paginate(repo, f"/issues/{pr_number}/comments", token, "") + if any( + c.get("user", {}).get("login") == "github-actions[bot]" and marker in str(c.get("body")) + for c in comments + ): + return + head_sha = str(run.get("head_sha") or "") + source_pr = reuse.run_pr_number(repo, run, token) + origin_en = f"from PR #{source_pr}, " if source_pr else "" + origin_zh = f"来自 PR #{source_pr}," if source_pr else "" + body = ( + f"{marker}\n" + f"⚠️ Reuse source run [{run['id']}]({run.get('html_url', '')}) " + f"({origin_en}commit `{head_sha[:12]}`) is not part of this PR. Its results will " + f"publish under this PR's changelog entry at merge.\n\n" + f"
\n中文\n\n" + f"⚠️ 复用的来源运行 [{run['id']}]({run.get('html_url', '')}),{origin_zh}" + f"提交 `{head_sha[:12]}`,不属于本 PR,合并后其结果将以本 PR 的 changelog 条目发布。\n\n" + f"
" + ) + github.api(repo, f"/issues/{pr_number}/comments", token, method="POST", data={"body": body}) + def acknowledge(repo: str, event: dict[str, Any], token: str) -> int: if event.get("action") not in {"created", "edited"} or not event.get("issue", {}).get( @@ -29,7 +63,7 @@ def acknowledge(repo: str, event: dict[str, Any], token: str) -> int: comment = github.api(repo, comment_path, token) if any(comment.get(key) != event["comment"].get(key) for key in ("body", "updated_at")): return 0 - github.set_comment_reaction(repo, comment_id, token, None, replace=("+1", "-1")) + github.set_comment_reaction(repo, comment_id, token, None, replace=BOT_STATUS) body = str(comment.get("body") or "") if not command_pattern.search(body): return 0 @@ -48,6 +82,8 @@ def acknowledge(repo: str, event: dict[str, Any], token: str) -> int: if pr.get("state") != "open": raise RuntimeError(f"PR #{pr_number} is not open.") run = reuse.resolve_reusable_run(repo, "run-sweep.yml", pr_number, pr, token, pinned_run_id) + head_sha = str(run.get("head_sha") or "") + outside_pr = head_sha not in reuse.pr_commit_shas(repo, pr_number, token) latest = github.api(repo, comment_path, token) selected, _ = reuse.find_reuse_request(repo, pr_number, token, "/reuse-sweep-run", allowed) @@ -57,16 +93,25 @@ def acknowledge(repo: str, event: dict[str, Any], token: str) -> int: or selected.get("id") != comment_id or any(selected.get(key) != comment.get(key) for key in ("body", "updated_at")) ): - github.set_comment_reaction(repo, comment_id, token, None, replace=("+1", "-1")) + github.set_comment_reaction(repo, comment_id, token, None, replace=BOT_STATUS) return 0 - github.set_comment_reaction(repo, comment_id, token, "+1", replace=("+1", "-1")) + github.set_comment_reaction(repo, comment_id, token, "+1", replace=BOT_STATUS) message = f"Reuse accepted / 复用请求已接受: PR #{pr_number}, run {run['id']} ({run['conclusion']})." + if outside_pr: + try: + warn_outside_pr(repo, pr_number, comment, run, token) + except Exception as exc: # noqa: BLE001 + print(f"::warning::Could not post outside-PR warning comment: {exc}") + print( + f"::warning::Reuse source run {run['id']} head {head_sha} is not part of " + f"PR #{pr_number}; its results will publish under this PR's changelog." + ) code = 0 except Exception as exc: # noqa: BLE001 latest = github.api(repo, comment_path, token) if any(latest.get(key) != comment.get(key) for key in ("body", "updated_at")): return 0 - github.set_comment_reaction(repo, comment_id, token, "-1", replace=("+1", "-1")) + github.set_comment_reaction(repo, comment_id, token, "-1", replace=BOT_STATUS) message = f"Reuse rejected / 复用请求未接受: {exc}" code = 1 print(message) diff --git a/inferencex-e2e/infx/workflows/sweep_runs.py b/inferencex-e2e/infx/workflows/sweep_runs.py index 99684c99e0..1c916e41ea 100644 --- a/inferencex-e2e/infx/workflows/sweep_runs.py +++ b/inferencex-e2e/infx/workflows/sweep_runs.py @@ -45,6 +45,21 @@ def pr_commit_shas(repo: str, pr_number: int, token: str) -> set[str]: } +def run_pr_number(repo: str, run: dict[str, Any], token: str) -> int | None: + """Return the run's PR; ``run.pull_requests`` is empty once that PR's head moves.""" + for pull in run.get("pull_requests") or []: + if pull.get("number"): + return int(pull["number"]) + head_sha = str(run.get("head_sha") or "") + if not head_sha: + return None + pulls = github.api(repo, f"/commits/{head_sha}/pulls", token) + for pull in pulls if isinstance(pulls, list) else []: + if pull.get("head", {}).get("ref") == run.get("head_branch") and pull.get("number"): + return int(pull["number"]) + return None + + def has_reusable_result_artifacts(names: set[str]) -> bool: """Return whether a run produced ingest-relevant result artifacts.""" return bool(names & REUSABLE_AGGREGATE_ARTIFACTS) or any(