Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 9 additions & 29 deletions .github/workflows/ci-maintenance.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,36 +21,16 @@ jobs:
contents: read
pull-requests: read
steps:
- uses: actions/github-script@v8
- uses: actions/checkout@v7
with:
script: |
const repo = context.repo;
const pull_number = context.payload.number;
const expected = context.payload.pull_request;
const readPR = async () => (await github.rest.pulls.get({...repo, pull_number})).data;
const pr = await readPR();
const sameIdentity = current => current.state === 'open' &&
current.head.sha === expected.head.sha && current.head.ref === expected.head.ref &&
current.head.repo?.id === expected.head.repo?.id &&
current.base.ref === expected.base.ref && current.base.repo?.id === expected.base.repo?.id;
if (!sameIdentity(pr) || !pr.head.repo?.id || !pr.base.repo?.id) {
return core.info('PR identity changed; stop diff inspection.');
}
const readTarget = async () => (await github.rest.repos.getBranch(
{...repo, branch: pr.base.ref})).data.commit.sha;
const target = await readTarget();
if (pr.base.sha === target) return core.info('PR base snapshot is current.');
// A changed target tip alone does not prove a wrong comparison.
// REST base updates have no target compare-and-swap: a final GET
// cannot prevent overwriting a concurrent maintainer retarget.
const before = await readPR();
if (!sameIdentity(before) || before.base.sha !== pr.base.sha) {
return core.info('PR changed during inspection; inspect the newer revision.');
}
core.info(`Comparison inspection for #${pull_number}: PR base ${pr.base.sha}, ` +
`target ${pr.base.ref} at ${target}, head ${pr.head.sha}. ` +
'Verify the published inventory against the exact three-dot Git diff before repair. ' +
'This observation is read-only and does not prove an incorrect diff.');
ref: ${{ github.workflow_sha }}
fetch-depth: 1
sparse-checkout: scripts/ci
persist-credentials: false
- name: Verify the published pull request files
env:
GH_TOKEN: ${{ github.token }}
run: python3 scripts/ci/review_gate.py inspect-pr-diff

cancel-obsolete-pr:
if: github.event_name == 'pull_request_target' && (github.event.action == 'closed' || github.event.action == 'synchronize')
Expand Down
13 changes: 10 additions & 3 deletions .github/workflows/python-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ jobs:
if: github.event_name != 'pull_request_target' && (github.event_name != 'pull_request' || github.event.action != 'closed')
runs-on: ubuntu-latest
timeout-minutes: 3
permissions:
contents: read
pull-requests: read
outputs:
core_tests: ${{ steps.classify.outputs.core_tests }}
backend_tests: ${{ steps.classify.outputs.backend_tests }}
Expand All @@ -61,6 +64,7 @@ jobs:
- uses: actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-python@v6
with:
python-version: "3.11"
Expand All @@ -81,13 +85,14 @@ jobs:
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
CHECKOUT_SHA: ${{ github.sha }}
FORCE_FULL: ${{ contains(github.event.pull_request.labels.*.name, 'ci:full') }}
GH_TOKEN: ${{ github.token }}
shell: bash
run: |
set -euo pipefail
extra=()
if [[ "$FORCE_FULL" == true ]]; then extra+=(--force-full); fi
set --
if [[ "$FORCE_FULL" == true ]]; then set -- --force-full; fi
if [[ "$EVENT_NAME" == pull_request ]]; then
python scripts/ci/review_gate.py classify --base "$BASE_SHA" --head "$HEAD_SHA" --plan impact-plan.json "${extra[@]}" >> "$GITHUB_OUTPUT"
python scripts/ci/review_gate.py classify --base "$BASE_SHA" --head "$HEAD_SHA" --verify-pr-diff --plan impact-plan.json "$@" >> "$GITHUB_OUTPUT"
else
python scripts/ci/review_gate.py classify --base "$CHECKOUT_SHA" --head "$CHECKOUT_SHA" --non-pr --plan impact-plan.json >> "$GITHUB_OUTPUT"
fi
Expand All @@ -99,6 +104,8 @@ jobs:
summary.write("## CI job exemptions\n\n")
summary.write(f"Change kind: **{plan['change_kind']}**; Python shards: **{plan['python_shards']}**.\n\n")
summary.write(plan['reason'] + ".\n\n")
if plan.get("published_diff", {}).get("verified"):
summary.write(f"Published files match Git comparison `{plan['merge_base_sha']}...{plan['head_sha']}`.\n\n")
summary.write(
f"Backend: {plan['backend_tests']}; Frontend browser: {plan['frontend_tests']}; "
f"Compat: {plan['compat_tests']}; Python: {plan['python_tests']}; "
Expand Down
15 changes: 15 additions & 0 deletions docs/development/ci-impact-selection.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,21 @@ and runs heavyweight cross-OS, full 6-shard Python/coverage, Node compatibility,
Stage 2C, and release/package dry-run matrices on Nightly `schedule`, `push` to
`main`, `merge_group`, `workflow_dispatch`, CI-policy/manifest changes, and `ci:full`.

For open PRs, `changes` verifies the complete published PR file inventory
against the Git comparison before granting exemptions. It rechecks PR identity
after reading all pages and allows base-branch advances that keep the same merge
base. A confirmed difference or comparison change fails classification and
therefore `merge-gate`. Unavailable or capped file data selects full
qualification and records why. CI Maintenance runs the same verification from
its pinned trusted workflow checkout using read-only GitHub access. Fork
commits are fetched as Git objects for comparison.

开放 PR 的 `changes` 先核对已发布的完整文件清单与 Git 比较,再决定能否免跑。
分页结束后重新确认 PR 身份,目标分支推进但 merge base 一致时继续。确认清单
或比较范围不一致会使分类失败,并阻止 `merge-gate`。文件数据不可用或达到 API
上限时执行全量检查并记录原因。CI Maintenance 在固定的可信 workflow checkout
运行同一核对,GitHub 权限仅为只读。Fork 提交以 Git 对象的形式用于比较。

| Whole PR / Event (`change_kind`) | Backend static/TS/contracts (`backend_tests`) | Browser / UI (`frontend_tests`, `presentation_tests`) | Node compat (`compat_tests`) | 6-shard Python / Windows (`python_tests`) | Stage 2C (`stage2c_tests`) |
| --- | --- | --- | --- | --- | --- |
| Allowlisted root Markdown or `docs/**/*.md` (`docs`) | Skip | Skip | Skip | Skip | Skip |
Expand Down
89 changes: 82 additions & 7 deletions loopx/cli_commands/canary.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import argparse
import os
import subprocess
import sys
from collections.abc import Callable
Expand Down Expand Up @@ -87,7 +88,8 @@ def _run_git_name_only(repo_root: Path, args: list[str]) -> dict[str, Any]:
# `core.quotePath` escapes non-ASCII pathnames, and a repository may turn
# that off, at which point a path can carry U+0085/U+2028/U+2029 raw and
# `str.splitlines()` splits one path into two.
command = ["git", "-C", str(repo_root), *args, "-z"]
subcommand, *arguments = args
command = ["git", "-C", str(repo_root), subcommand, "-z", *arguments, "--"]
completed = subprocess.run(
command,
check=False,
Expand Down Expand Up @@ -133,6 +135,69 @@ def _resolve_git_repo_root(candidate: Path) -> Path:
return candidate.resolve()


def _run_git_text(repo_root: Path, args: list[str]) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["git", "--no-replace-objects", "-C", str(repo_root), *args],
check=False,
env={**os.environ, "GIT_NO_LAZY_FETCH": "1", "GIT_OPTIONAL_LOCKS": "0"},
text=True,
encoding="utf-8",
errors="replace",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)


def _failed_base_source(
completed: subprocess.CompletedProcess[str],
*,
returncode: int | None = None,
path_error: str | None = None,
) -> dict[str, Any]:
return {
"ok": False,
"returncode": completed.returncode if returncode is None else returncode,
"command": list(completed.args),
"changed_files": [],
"undecodable_path_count": 0,
"path_error": path_error,
"stderr_tail": completed.stderr[-800:],
}


def _resolve_base_diff_source(
repo_root: Path, base_ref: str
) -> tuple[dict[str, Any], str | None]:
base_rev = _run_git_text(
repo_root, ["rev-parse", "--verify", "--end-of-options", f"{base_ref}^{{commit}}"]
)
if base_rev.returncode != 0:
return _failed_base_source(base_rev), None
head_rev = _run_git_text(
repo_root, ["rev-parse", "--verify", "--end-of-options", "HEAD^{commit}"]
)
if head_rev.returncode != 0:
return _failed_base_source(head_rev), None
base_sha = base_rev.stdout.strip()
head_sha = head_rev.stdout.strip()
merge_bases = _run_git_text(repo_root, ["merge-base", "--all", base_sha, head_sha])
bases = [line.strip() for line in merge_bases.stdout.splitlines() if line.strip()]
if merge_bases.returncode != 0 or not bases:
return _failed_base_source(merge_bases, returncode=merge_bases.returncode or 1), None
if len(bases) > 1:
detail = (
f"Git comparison of {base_ref!r} and HEAD requires one unambiguous merge base "
f"(found {len(bases)}); specify an explicit --git-diff-base with a single common ancestor."
)
return _failed_base_source(merge_bases, returncode=1, path_error=detail), detail
return (
_run_git_name_only(
repo_root, ["diff", "--name-only", "--end-of-options", f"{bases[0]}..{head_sha}"]
),
None,
)


def collect_git_diff_changed_files(
*,
repo_root: Path,
Expand All @@ -141,8 +206,9 @@ def collect_git_diff_changed_files(
"""Collect committed, staged, unstaged, and untracked paths for canary selection."""

base_ref = (base_ref or "origin/main").strip() or "origin/main"
base_source, base_error = _resolve_base_diff_source(repo_root, base_ref)
sources = {
"base": _run_git_name_only(repo_root, ["diff", "--name-only", f"{base_ref}...HEAD"]),
"base": base_source,
"staged": _run_git_name_only(repo_root, ["diff", "--name-only", "--cached"]),
"unstaged": _run_git_name_only(repo_root, ["diff", "--name-only"]),
"untracked": _run_git_name_only(repo_root, ["ls-files", "--others", "--exclude-standard"]),
Expand Down Expand Up @@ -173,21 +239,30 @@ def collect_git_diff_changed_files(
int(source.get("undecodable_path_count") or 0)
for source in sources.values()
)
path_error = (
error = (
"Git returned changed pathnames that are not valid UTF-8; canary "
"cannot preserve their identity in the selector output"
if undecodable_path_count
else None
)
if error is None and not sources["base"]["ok"]:
error = base_error or (
f"Git could not compare {base_ref!r} with HEAD. Fetch the target branch "
"or set --git-diff-base to a revision with shared history."
)
elif error is None and warnings:
failed = ", ".join(warning["source"] for warning in warnings)
error = f"Git could not read changed paths from {failed}; selection is incomplete."
selected = changed_files if error is None else []
return {
"ok": bool(successful_sources) and path_error is None,
"ok": error is None,
"base_ref": base_ref,
"repo_root": str(repo_root),
"changed_files": [] if path_error is not None else changed_files,
"changed_file_count": len(changed_files),
"changed_files": selected,
"changed_file_count": len(selected),
"successful_sources": successful_sources,
"undecodable_path_count": undecodable_path_count,
**({"error": path_error} if path_error else {}),
**({"error": error} if error else {}),
"warnings": warnings,
}

Expand Down
68 changes: 56 additions & 12 deletions scripts/ci/impact_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

from collections.abc import Callable
from dataclasses import dataclass
import json
import os
Expand All @@ -10,7 +11,10 @@

SCHEMA = "loopx_ci_job_plan_v1"
ROOT_DOCS = {"README.md", "README.zh-CN.md", "README.ja.md", "CHANGELOG.md", "CONTRIBUTING.md"}
POLICY_PATHS = ("scripts/ci/impact_plan.py", "scripts/ci/review_gate.py", ".github/workflows/python-tests.yml")
POLICY_PATHS = (
"scripts/ci/impact_plan.py", "scripts/ci/pull_request_diff.py",
"scripts/ci/review_gate.py", ".github/workflows/python-tests.yml",
)
OUTPUTS = (
"core_tests",
"backend_tests",
Expand Down Expand Up @@ -95,6 +99,14 @@ class Change:
path: str


@dataclass(frozen=True)
class Comparison:
base_sha: str
head_sha: str
merge_base_sha: str
changes: list[Change]


def is_document(path: str) -> bool:
return path in ROOT_DOCS or (path.startswith("docs/") and PurePosixPath(path).suffix == ".md")

Expand Down Expand Up @@ -157,20 +169,40 @@ def job_flags(kind: str, *, presentation: bool = False) -> dict[str, bool]:


def git(*args: str) -> bytes:
return subprocess.check_output(["git", *args])
return subprocess.check_output(
["git", "--no-replace-objects", *args],
env={**os.environ, "GIT_NO_LAZY_FETCH": "1", "GIT_OPTIONAL_LOCKS": "0"},
stderr=subprocess.PIPE, timeout=30,
)


def revision(ref: str) -> str:
return git("rev-parse", "--verify", "--end-of-options", f"{ref}^{{commit}}").decode().strip()


def diff_changes(base: str, head: str) -> list[Change]:
raw = git("diff", "--name-status", "--no-renames", "-z", base, head, "--").split(b"\0")
raw = git(
"diff", "--no-ext-diff", "--no-textconv", "--name-status", "--no-renames",
"-z", base, head, "--",
).split(b"\0")
if raw[-1] != b"" or (len(raw) - 1) % 2:
raise ValueError("malformed NUL-delimited Git changes")
return [Change(os.fsdecode(raw[i]), os.fsdecode(raw[i + 1])) for i in range(0, len(raw) - 1, 2)]


def merge_base(base: str, head: str) -> str:
bases = git("merge-base", "--all", base, head).decode("ascii").splitlines()
if len(bases) != 1:
raise ValueError("Git comparison requires one unambiguous merge base")
return bases[0]


def compare(base: str, head: str) -> Comparison:
base_sha, head_sha = revision(base), revision(head)
ancestor = merge_base(base_sha, head_sha)
return Comparison(base_sha, head_sha, ancestor, diff_changes(ancestor, head_sha))


def trusted_policy(base: str, head: str) -> bool:
# A PR cannot introduce its own exemption. No manifest or per-test inventory.
for path in POLICY_PATHS:
Expand Down Expand Up @@ -203,20 +235,29 @@ def declared_python_shards(checkout_sha: str) -> int:
return len(shards)


def plan(base: str, head: str, *, pull_request: bool = True, force_full: bool = False) -> dict:
base_sha, head_sha = revision(base), revision(head)
merge_base = git("merge-base", base_sha, head_sha).decode().strip()
changes = diff_changes(merge_base, head_sha)
def plan(
base: str,
head: str,
*,
pull_request: bool = True,
force_full: bool = False,
verify_pr_diff: Callable[[Comparison], str | None] | None = None,
) -> dict:
comparison = compare(base, head)
base_sha, head_sha, changes = comparison.base_sha, comparison.head_sha, comparison.changes
unverified = verify_pr_diff(comparison) if verify_pr_diff is not None else None
kind, reason = candidate(changes, pull_request=pull_request)
presentation = kind in {"presentation", "mixed"}
policy_change = any(item.path.startswith("scripts/ci/") or item.path == POLICY_PATHS[-1] for item in changes)
if kind != "full":
if kind != "full" and unverified is None:
for item in changes:
for sha in (merge_base, head_sha):
for sha in (comparison.merge_base_sha, head_sha):
mode = git("ls-tree", "--format=%(objectmode)", sha, "--", item.path).decode().strip()
if mode and mode not in {"100644", "100755"}:
kind, reason = "full", "symlinks and nonregular Git objects cannot grant an exemption"
if force_full:
if unverified is not None:
kind, reason = "full", f"{unverified}; run full qualification"
elif force_full:
kind, reason = "full", "explicit force-full override"
elif kind in {"presentation", "backend", "mixed"} and not trusted_policy(base_sha, head_sha):
kind, reason = "full", "CI exemption policy is not already trusted on the target branch"
Expand All @@ -229,12 +270,15 @@ def plan(base: str, head: str, *, pull_request: bool = True, force_full: bool =
if flags["backend_tests"]
else "no Python coverage claim"
)
return {"schema_version": SCHEMA, "base_sha": base_sha, "head_sha": head_sha,
"merge_base_sha": merge_base, "checkout_sha": checkout_sha, "change_kind": kind,
packet = {"schema_version": SCHEMA, "base_sha": base_sha, "head_sha": head_sha,
"merge_base_sha": comparison.merge_base_sha, "checkout_sha": checkout_sha, "change_kind": kind,
"force_full": force_full, "reason": reason, **flags,
"changes": [{"status": item.status, "path": item.path} for item in changes],
"coverage_scope": coverage_scope,
"python_shards": declared_python_shards(checkout_sha) if flags["python_tests"] else 0}
if verify_pr_diff is not None:
packet["published_diff"] = {"verified": unverified is None, "unavailable_reason": unverified}
return packet


def write_plan(packet: dict, output: str) -> None:
Expand Down
Loading
Loading