Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(release): reject superseded package artifacts after reruns (#6973)

LearningCircuite0a4d505f6b8
diff --git a/.github/scripts/release_package.py b/.github/scripts/release_package.py
index aa5127fa36..2bf4c4c3dc 100644
--- a/.github/scripts/release_package.py
+++ b/.github/scripts/release_package.py
@@ -187,8 +187,70 @@ def api(endpoint):
return json.loads(result.stdout)
-def validate_source(repo, payload, fetch=api):
- """Validate immutable artifact ownership and the successful release gates."""
+def job_attempt(job):
+ return int(
+ fullmatch(
+ r"[1-9][0-9]*",
+ str(job.get("run_attempt")),
+ "source job run attempt",
+ )
+ )
+
+
+def executed_attempt(job, history):
+ """Return the run attempt whose runner actually executed ``job``.
+
+ "Re-run failed jobs" carries every already-successful job into the new
+ attempt as a new job record (higher ID, the new ``run_attempt``) that
+ keeps the original runner and timestamps; it does not run again and
+ uploads nothing. The artifacts API does not report which attempt
+ uploaded an artifact, so identify carried-over copies by their
+ unchanged execution record. A record missing that data counts as a
+ fresh execution of its own attempt. For the package job that fails
+ closed by demanding a newer artifact; for a check job it can only
+ overstate the check's attempt, and since every check needs pip Install
+ Verification it cannot have run before a fresher package build.
+ """
+
+ def execution(row):
+ key = tuple(
+ row.get(field)
+ for field in (
+ "started_at",
+ "completed_at",
+ "runner_id",
+ "runner_name",
+ )
+ )
+ if not all(isinstance(value, str) and value for value in key[:2]):
+ return None
+ if not isinstance(key[2], int) or isinstance(key[2], bool):
+ return None
+ if not isinstance(key[3], str) or not key[3]:
+ return None
+ return key
+
+ attempt = job_attempt(job)
+ key = execution(job)
+ if key is None:
+ return attempt
+ return min(
+ [attempt]
+ + [
+ job_attempt(row)
+ for row in history
+ if row is not job and execution(row) == key
+ ]
+ )
+
+
+def validate_source(repo, payload, fetch=api, expected_attempt=None):
+ """Validate immutable artifact ownership and the successful release gates.
+
+ ``expected_attempt`` is set when the publish job revalidates live run
+ state after approval: the result must still name the package build that
+ build-package verified before the approval wait.
+ """
sha = fullmatch(r"[0-9a-f]{40}", payload["sha"], "release SHA")
run_id = fullmatch(r"[1-9][0-9]*", str(payload["run_id"]), "release run ID")
artifact_id = fullmatch(
@@ -210,9 +272,14 @@ def validate_source(repo, payload, fetch=api):
raise ValueError(
"Source is not a release workflow run for the requested commit"
)
+ current_attempt = int(
+ fullmatch(
+ r"[1-9][0-9]*", str(run.get("run_attempt")), "source run attempt"
+ )
+ )
# The parent is still in progress while waiting for this publisher.
# Verify its completed gates instead of requiring run-level success.
- jobs = {}
+ records = {}
for page in range(1, 101):
response = fetch(
f"{root}/actions/runs/{run_id}/jobs?filter=all&per_page=100&page={page}"
@@ -221,20 +288,48 @@ def validate_source(repo, payload, fetch=api):
if not isinstance(rows, list):
raise ValueError("Invalid source job response")
for job in rows:
- previous = jobs.get(job["name"])
- if previous is None or job["id"] > previous["id"]:
- jobs[job["name"]] = job
+ records.setdefault(job["name"], []).append(job)
if len(rows) < 100:
break
else:
raise ValueError("Source job pagination exceeded its limit")
- for name in ("release-gate / Release Gate Summary", "build"):
- job = jobs.get(name, {})
+ package_job = "release-gate / pip Install Verification"
+ # Keep these names aligned with release-gate.yml's package install matrix.
+ # A partial rerun may retain a successful producer from an earlier attempt;
+ # after a rebuild, however, older successful checks cover different bytes.
+ required_jobs = (
+ package_job,
+ "release-gate / Package install (3.13, wheel)",
+ "release-gate / Package install (3.14, wheel)",
+ "release-gate / Package install (3.12, sdist)",
+ "release-gate / Release Gate Summary",
+ "build",
+ )
+ attempts = {}
+ for name in required_jobs:
+ history = records.get(name, [])
+ job = max(history, key=lambda row: row["id"], default={})
if (
job.get("status") != "completed"
or job.get("conclusion") != "success"
):
raise ValueError(f"Required source job did not succeed: {name}")
+ if job_attempt(job) > current_attempt:
+ raise ValueError(f"Source job belongs to a future attempt: {name}")
+ attempts[name] = executed_attempt(job, history)
+ # The jobs API omits jobs still waiting on ``needs``. After "Re-run all
+ # jobs", the newest listed package record can therefore be the previous
+ # attempt's while this attempt has yet to rebuild. "Re-run failed jobs"
+ # lists its carried-over copies from the start of the attempt, so the
+ # package job must have a record (fresh or carried) in the current one.
+ package_record = max(records[package_job], key=lambda row: row["id"])
+ if job_attempt(package_record) != current_attempt:
+ raise ValueError(
+ "Package job has no record in the current source run attempt"
+ )
+ package_attempt = attempts[package_job]
+ if any(attempt < package_attempt for attempt in attempts.values()):
+ raise ValueError("Required source checks predate the package build")
if fetch(f"{root}/compare/{sha}...heads/main")["status"] not in {
"ahead",
"identical",
@@ -254,6 +349,33 @@ def validate_source(repo, payload, fetch=api):
raise ValueError(
"Artifact is expired or does not belong to the verified release run"
)
+ if int(match[1]) != package_attempt:
+ raise ValueError(
+ "Artifact is not from the latest successful package build"
+ )
+ # Defence in depth: no attempt may have uploaded a newer package build.
+ for page in range(1, 101):
+ rows = fetch(
+ f"{root}/actions/runs/{run_id}/artifacts?per_page=100&page={page}"
+ )["artifacts"]
+ if not isinstance(rows, list):
+ raise ValueError("Invalid source artifact response")
+ for row in rows:
+ other = re.fullmatch(
+ r"verified-python-dist-([1-9][0-9]*)", row["name"]
+ )
+ if other and int(other[1]) > package_attempt:
+ raise ValueError(
+ "Artifact is superseded by a newer package build"
+ )
+ if len(rows) < 100:
+ break
+ else:
+ raise ValueError("Source artifact pagination exceeded its limit")
+ if expected_attempt is not None and expected_attempt != match[1]:
+ raise ValueError(
+ "Source package build changed after artifact verification"
+ )
return match[1]
@@ -346,7 +468,9 @@ def main():
)
)
attempt = validate_source(
- os.environ["GITHUB_REPOSITORY"], event["client_payload"]
+ os.environ["GITHUB_REPOSITORY"],
+ event["client_payload"],
+ expected_attempt=os.environ.get("EXPECTED_ARTIFACT_ATTEMPT"),
)
output("artifact_attempt", attempt)
elif args.command == "create":
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 933d0020df..3733cff21b 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -20,6 +20,7 @@ jobs:
actions: read
outputs:
file_hashes: ${{ steps.verify.outputs.file_hashes }}
+ artifact_attempt: ${{ steps.source.outputs.artifact_attempt }}
artifact_id: ${{ steps.publisher-upload.outputs.artifact-id }}
steps:
- name: Harden runner
@@ -67,18 +68,38 @@ jobs:
if-no-files-found: error
retention-days: 14
- # No checkout, installation or package execution in the OIDC-enabled job.
+ # No package installation or execution in the OIDC-enabled job. It checks
+ # out only the trusted default-branch source policy script.
publish:
needs: build-package
runs-on: ubuntu-latest
environment: release
permissions:
+ contents: read
+ actions: read
id-token: write
steps:
- name: Harden runner
uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1
with:
egress-policy: audit
+ - name: Checkout source policy
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ path: source-policy
+ sparse-checkout: .github/scripts/release_package.py
+ sparse-checkout-cone-mode: false
+ # build-package validated the source run before the environment
+ # approval wait, and re-running only this job reuses its outputs.
+ # Revalidate the live release run now, after approval and immediately
+ # before upload, so a package rebuilt by a later release attempt in
+ # the meantime rejects this older dispatch.
+ - name: Revalidate source release run after approval
+ env:
+ GH_TOKEN: ${{ github.token }}
+ EXPECTED_ARTIFACT_ATTEMPT: ${{ needs.build-package.outputs.artifact_attempt }}
+ run: python3 source-policy/.github/scripts/release_package.py source
- name: Download verified package
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 75133f39d3..f5eea3db63 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1742,6 +1742,7 @@ jobs:
+ ' Re-run failed publisher jobs to preserve the original tested artifact and dispatch payload.'
+ ' If no publisher run exists, re-run the failed release jobs to dispatch it.'
+ ' Expired artifacts require a fresh release gate run; do not rebuild in the publisher.'
+ + ' A dispatch is rejected once a later release attempt rebuilt the package; publish the dispatch from that newer attempt instead.'
+ ' See docs/RELEASE_GUIDE.md "Recovery from PyPI failure".';
const body = `## PyPI publish failed for ${tag}\n\nResult: \`${pypi}\`\n\nNote: At this point in the atomicity flow, Docker promote (publish-docker job) has already succeeded — the Docker release tags exist and are signed. Only PyPI and the GitHub Release are missing.\n\n${action}`;
diff --git a/changelog.d/+release-artifact-attempt.bugfix.md b/changelog.d/+release-artifact-attempt.bugfix.md
new file mode 100644
index 0000000000..05dc9a1dd4
--- /dev/null
+++ b/changelog.d/+release-artifact-attempt.bugfix.md
@@ -0,0 +1 @@
+Reject superseded Python package artifacts during release publication, including when only the approved PyPI upload job is re-run, and require package-install checks and release gates to cover the latest package build, while preserving reruns that carry the original successful package build over.
diff --git a/docs/RELEASE_GUIDE.md b/docs/RELEASE_GUIDE.md
index 05c2dd6bf0..38bb8f4e12 100644
--- a/docs/RELEASE_GUIDE.md
+++ b/docs/RELEASE_GUIDE.md
@@ -116,6 +116,18 @@ succeeded, PyPI failed. At this point Docker `:1.6.9` / `:1.6` /
to build and verify new artifacts before dispatching again. The publisher
deliberately has no build step. A dispatch containing only a tag and SHA
is insufficient: the run ID, artifact ID and manifest SHA256 are required.
+ Both the publisher's verification job and, after the `release`
+ approval, its upload job recheck the live `release.yml` run, so a
+ re-run of either job also rechecks it. If a later `release.yml` attempt
+ rebuilt the package (re-ran `pip Install Verification`), the old
+ dispatch is rejected even when only the upload job is re-run; publish
+ the new build from the dispatch sent by that attempt's `trigger-pypi`
+ job (re-run that attempt's failed jobs if it did not get that far).
+ The publisher also requires the package install checks, release gate
+ summary and `build` job to have succeeded on that build, not an older
+ one. Reruns that leave `pip Install Verification` as a carried-over
+ success, such as "Re-run failed jobs" after a later job failed, keep
+ the original build, so its original artifact can still be published.
3. Once PyPI publishes successfully, manually create the GitHub Release
from the existing tag (the SBOM/sig/provenance artifacts are still
uploaded as workflow artifacts on the failed `release.yml` run; you
diff --git a/tests/ci/standalone/test_release_package.py b/tests/ci/standalone/test_release_package.py
index 595d813d98..b8c22c0379 100644
--- a/tests/ci/standalone/test_release_package.py
+++ b/tests/ci/standalone/test_release_package.py
@@ -354,6 +354,7 @@ class SourceTests(unittest.TestCase):
"event": "push",
"head_branch": "main",
"status": "in_progress",
+ "run_attempt": 1,
}
self.jobs = [
{
@@ -361,9 +362,19 @@ class SourceTests(unittest.TestCase):
"name": name,
"status": "completed",
"conclusion": "success",
+ "run_attempt": 1,
+ **self.execution(i),
}
for i, name in enumerate(
- ("release-gate / Release Gate Summary", "build"), 1
+ (
+ "release-gate / Release Gate Summary",
+ "build",
+ "release-gate / pip Install Verification",
+ "release-gate / Package install (3.13, wheel)",
+ "release-gate / Package install (3.14, wheel)",
+ "release-gate / Package install (3.12, sdist)",
+ ),
+ 1,
)
]
self.artifact = {
@@ -372,13 +383,27 @@ class SourceTests(unittest.TestCase):
"expired": False,
"workflow_run": {"id": 123, "head_sha": SHA},
}
+ self.run_artifacts = [{"name": "verified-python-dist-1"}]
self.ancestry = "ahead"
self.calls = []
+ @staticmethod
+ def execution(runner):
+ """A job record's execution fields; distinct per runner."""
+ return {
+ "started_at": f"2026-08-07T23:{runner:02d}:00Z",
+ "completed_at": f"2026-08-07T23:{runner:02d}:30Z",
+ "runner_id": 1000418800 + runner,
+ "runner_name": f"GitHub Actions {1000418800 + runner}",
+ }
+
def fetch(self, endpoint):
self.calls.append(endpoint)
if "/jobs?" in endpoint:
- return {"jobs": self.jobs}
+ page = int(endpoint.rsplit("page=", 1)[1])
+ return {"jobs": self.jobs[(page - 1) * 100 : page * 100]}
+ if "/artifacts?" in endpoint:
+ return {"artifacts": self.run_artifacts}
if "/artifacts/" in endpoint:
return self.artifact
if "/compare/" in endpoint:
@@ -388,12 +413,386 @@ class SourceTests(unittest.TestCase):
def validate(self):
return POLICY.validate_source("owner/repo", self.payload, self.fetch)
+ def rerun(self, *names, attempt=2):
+ """Model a GitHub rerun: named jobs run again on new runners; every
+ other job is carried into the new attempt as a new record that keeps
+ its original runner and timestamps (as observed in release run
+ 31226451323 and publish run 23679807987)."""
+ self.run["run_attempt"] = attempt
+ previous = {job["name"]: job for job in self.jobs}
+ carried = [name for name in previous if name not in names]
+ for name in carried + list(names):
+ fresh = {}
+ if name in names:
+ fresh = {
+ "status": "completed",
+ "conclusion": "success",
+ **self.execution(len(self.jobs) + 1),
+ }
+ self.jobs.append(
+ {
+ **previous[name],
+ "id": max(job["id"] for job in self.jobs) + 1,
+ "run_attempt": attempt,
+ **fresh,
+ }
+ )
+
def test_in_progress_release_with_successful_gates_is_valid(self):
self.assertEqual(self.validate(), "1")
self.assertTrue(
any("/artifacts/456" in endpoint for endpoint in self.calls)
)
+ def test_full_rerun_rejects_the_superseded_artifact(self):
+ self.rerun(*(job["name"] for job in self.jobs))
+ with self.assertRaises(ValueError):
+ self.validate()
+ self.artifact["name"] = "verified-python-dist-2"
+ self.run_artifacts.append({"name": "verified-python-dist-2"})
+ self.assertEqual(self.validate(), "2")
+
+ def test_rerun_failed_jobs_keeps_the_carried_over_package_build(self):
+ # Only the failed downstream job runs again; GitHub copies the
+ # successful package build into attempt 2 with run_attempt 2 but
+ # uploads no new artifact.
+ self.jobs[1]["conclusion"] = "failure"
+ self.rerun("build")
+ self.assertTrue(
+ any(
+ job["name"] == "release-gate / pip Install Verification"
+ and job["run_attempt"] == 2
+ for job in self.jobs
+ )
+ )
+ self.assertEqual(self.validate(), "1")
+ # A copy cannot vouch for an artifact its attempt never built.
+ self.artifact["name"] = "verified-python-dist-2"
+ with self.assertRaises(ValueError):
+ self.validate()
+
+ def test_full_rerun_before_the_package_job_is_listed_rejects(self):
+ # The jobs API omits jobs still waiting on ``needs`` (release run
+ # 37041154628 listed 3 jobs while its dependants were pending), so
+ # right after "Re-run all jobs" only attempt-1 records are visible.
+ self.run["run_attempt"] = 2
+ with self.assertRaises(ValueError) as caught:
+ self.validate()
+ self.assertIn("current source run attempt", str(caught.exception))
+ # Once the new package record is listed it must still rebuild.
+ self.rerun("release-gate / pip Install Verification")
+ with self.assertRaises(ValueError):
+ self.validate()
+
+ def test_rerun_failed_jobs_with_a_carried_package_copy_is_valid(self):
+ # "Re-run failed jobs" lists the carried copies at the start of the
+ # new attempt, so the package job has a current-attempt record.
+ self.jobs[0]["conclusion"] = "failure"
+ self.rerun("release-gate / Release Gate Summary", attempt=2)
+ self.assertEqual(self.validate(), "1")
+ self.rerun("release-gate / Release Gate Summary", attempt=3)
+ self.assertEqual(self.validate(), "1")
+
+ def test_real_rerun_failed_jobs_records_are_carried_over(self):
+ # Job records from release.yml run 31226451323, whose attempt 2
+ # re-ran failed jobs only (GET runs/31226451323/jobs?filter=all).
+ def record(job_id, attempt, name, started, completed, runner):
+ return {
+ "id": job_id,
+ "name": f"release-gate / {name}",
+ "status": "completed",
+ "conclusion": "success",
+ "run_attempt": attempt,
+ "started_at": started,
+ "completed_at": completed,
+ "runner_id": runner,
+ "runner_name": f"GitHub Actions {runner}",
+ }
+
+ pip = ("pip Install Verification", "2026-08-07T23:38:50Z")
+ pip += ("2026-08-07T23:42:10Z", 1000418864)
+ gate = ("Release Gate Summary", "2026-08-08T00:09:32Z")
+ gate += ("2026-08-08T00:09:42Z", 1000418969)
+ real = [
+ record(93023115290, 1, *pip),
+ record(93029267734, 1, *gate),
+ record(93059343189, 2, *pip),
+ record(93059344806, 2, *gate),
+ ]
+ self.jobs = [
+ job
+ for job in self.jobs
+ if job["name"]
+ not in {
+ "release-gate / pip Install Verification",
+ "release-gate / Release Gate Summary",
+ }
+ ] + real
+ self.run["run_attempt"] = 2
+ self.assertEqual(self.validate(), "1")
+ self.assertEqual(
+ POLICY.executed_attempt(real[2], real[::2]),
+ 1,
+ )
+
+ def test_rebuild_on_the_same_name_with_new_execution_supersedes(self):
+ for field, value in (
+ ("started_at", "2026-08-08T04:50:37Z"),
+ ("completed_at", "2026-08-08T04:54:00Z"),
+ ("runner_id", 1000419999),
+ ("runner_name", "GitHub Actions 1000419999"),
+ ):
+ self.setUp()
+ self.rerun()
+ pip = next(
+ job
+ for job in reversed(self.jobs)
+ if job["name"] == "release-gate / pip Install Verification"
+ )
+ pip[field] = value
+ with self.subTest(field=field), self.assertRaises(ValueError):
+ self.validate()
+
+ def test_carried_copy_without_execution_metadata_fails_closed(self):
+ for field in ("started_at", "completed_at", "runner_id", "runner_name"):
+ for value in (None, "", True):
+ self.setUp()
+ self.rerun()
+ for job in self.jobs:
+ if job["name"] == "release-gate / pip Install Verification":
+ job[field] = value
+ with (
+ self.subTest(field=field, value=value),
+ self.assertRaises(ValueError),
+ ):
+ self.validate()
+
+ def test_newer_package_artifact_in_the_run_rejects_the_old_one(self):
+ for name in ("verified-python-dist-2", "verified-python-dist-10"):
+ self.run_artifacts = [
+ {"name": "verified-python-dist-1"},
+ {"name": "python-dist-7"},
+ {"name": name},
+ ]
+ with self.subTest(name=name), self.assertRaises(ValueError):
+ self.validate()
+ self.run_artifacts = [{"name": "python-dist-7"}]
+ self.assertEqual(self.validate(), "1")
+
+ def test_newer_package_artifact_on_a_later_page_rejects(self):
+ self.run_artifacts = [{"name": f"sbom-{i}"} for i in range(100)]
+
+ def fetch(endpoint):
+ if "/artifacts?" in endpoint and endpoint.endswith("page=2"):
+ return {"artifacts": [{"name": "verified-python-dist-2"}]}
+ return self.fetch(endpoint)
+
+ with self.assertRaises(ValueError):
+ POLICY.validate_source("owner/repo", self.payload, fetch)
+
+ def test_publish_recheck_rejects_a_changed_package_build(self):
+ real = POLICY.validate_source
+
+ def validate(repo, payload, **kwargs):
+ return real(repo, payload, self.fetch, **kwargs)
+
+ with tempfile.TemporaryDirectory() as directory:
+ event = Path(directory, "event.json")
+ event.write_text(
+ json.dumps({"client_payload": self.payload}), encoding="utf-8"
+ )
+ output = Path(directory, "output")
+ output.touch()
+ for expected, result in ((None, 0), ("1", 0), ("2", 1)):
+ env = {
+ "GITHUB_EVENT_PATH": str(event),
+ "GITHUB_OUTPUT": str(output),
+ "GITHUB_REPOSITORY": "owner/repo",
+ }
+ if expected is not None:
+ env["EXPECTED_ARTIFACT_ATTEMPT"] = expected
+ with (
+ self.subTest(expected=expected),
+ unittest.mock.patch.dict("os.environ", env),
+ unittest.mock.patch.object(
+ POLICY, "validate_source", validate
+ ),
+ unittest.mock.patch(
+ "sys.argv", ["release_package", "source"]
+ ),
+ unittest.mock.patch("sys.stdout", io.StringIO()),
+ ):
+ self.assertEqual(POLICY.main(), result)
+
+ def test_publish_retry_rechecks_cached_dispatch_after_source_rebuild(self):
+ """A publish-only retry retains its dispatch and verified attempt,
+ but must reject those outputs once the source rebuilds the package."""
+ cached_attempt = self.validate()
+ names = tuple(dict.fromkeys(job["name"] for job in self.jobs))
+ real = POLICY.validate_source
+
+ def validate(repo, payload, **kwargs):
+ return real(repo, payload, self.fetch, **kwargs)
+
+ with tempfile.TemporaryDirectory() as directory:
+ event = Path(directory, "event.json")
+ event.write_text(
+ json.dumps({"client_payload": self.payload}), encoding="utf-8"
+ )
+ output = Path(directory, "output")
+ env = {
+ "GITHUB_EVENT_PATH": str(event),
+ "GITHUB_OUTPUT": str(output),
+ "GITHUB_REPOSITORY": "owner/repo",
+ "EXPECTED_ARTIFACT_ATTEMPT": cached_attempt,
+ }
+ phases = (
+ ("original", (), None, 0),
+ ("partial rerun", ("build",), 2, 0),
+ ("rebuilt package", names, 3, 1),
+ )
+ for phase, rerun, attempt, result in phases:
+ if attempt is not None:
+ self.rerun(*rerun, attempt=attempt)
+ output.write_text("", encoding="utf-8")
+ log = io.StringIO()
+ with (
+ self.subTest(phase=phase),
+ unittest.mock.patch.dict("os.environ", env),
+ unittest.mock.patch.object(
+ POLICY, "validate_source", validate
+ ),
+ unittest.mock.patch(
+ "sys.argv", ["release_package", "source"]
+ ),
+ unittest.mock.patch("sys.stdout", log),
+ ):
+ self.assertEqual(POLICY.main(), result)
+ if result:
+ self.assertEqual(output.read_text(), "")
+ self.assertIn(
+ "Artifact is not from the latest successful package build",
+ log.getvalue(),
+ )
+ else:
+ self.assertEqual(
+ output.read_text(), "artifact_attempt=1\n"
+ )
+
+ def test_partial_reruns_preserve_the_package_build_attempt(self):
+ self.rerun("release-gate / Release Gate Summary", "build")
+ self.assertEqual(self.validate(), "1")
+ self.rerun(
+ "release-gate / Package install (3.13, wheel)",
+ "release-gate / Release Gate Summary",
+ "build",
+ attempt=3,
+ )
+ self.assertEqual(self.validate(), "1")
+
+ def test_rebuilt_package_requires_fresh_install_and_release_gates(self):
+ self.run["run_attempt"] = 2
+ self.artifact["name"] = "verified-python-dist-2"
+ for job in self.jobs:
+ job["run_attempt"] = 2
+ for job in self.jobs:
+ if job["name"] == "release-gate / pip Install Verification":
+ continue
+ job["run_attempt"] = 1
+ with self.subTest(name=job["name"]), self.assertRaises(ValueError):
+ self.validate()
+ job["run_attempt"] = 2
+ self.assertEqual(self.validate(), "2")
+
+ def test_failed_pending_and_missing_package_checks_reject(self):
+ original = copy.deepcopy(self.jobs)
+ for name in (job["name"] for job in original[2:]):
+ for state in ("failure", None, "missing"):
+ self.jobs = copy.deepcopy(original)
+ if state == "missing":
+ self.jobs = [j for j in self.jobs if j["name"] != name]
+ else:
+ job = next(j for j in self.jobs if j["name"] == name)
+ job["conclusion"] = state
+ if state is None:
+ job["status"] = "in_progress"
+ with (
+ self.subTest(name=name, state=state),
+ self.assertRaises(ValueError),
+ ):
+ self.validate()
+
+ def test_failed_rebuild_cannot_reuse_an_older_success(self):
+ self.rerun("release-gate / pip Install Verification")
+ self.jobs[-1]["conclusion"] = "failure"
+ with self.assertRaises(ValueError):
+ self.validate()
+
+ def test_invalid_or_future_attempt_metadata_rejects(self):
+ for target in (self.run, *self.jobs):
+ for attempt in (None, 0, -1, "1\n", True):
+ target["run_attempt"] = attempt
+ with (
+ self.subTest(name=target.get("name"), attempt=attempt),
+ self.assertRaises(ValueError),
+ ):
+ self.validate()
+ target["run_attempt"] = 1
+ for job in self.jobs:
+ job["run_attempt"] = 2
+ with self.subTest(name=job["name"]), self.assertRaises(ValueError):
+ self.validate()
+ job["run_attempt"] = 1
+ self.artifact["name"] = "verified-python-dist-2"
+ with self.assertRaises(ValueError):
+ self.validate()
+
+ def paginate_jobs(self, page_one):
+ """Pad the job list so its first ``page_one`` records end page 1 of
+ the jobs API (100 per page) and the rest land on page 2, as in
+ release run 31226451323 (180 job records); IDs follow list order."""
+ self.jobs[page_one:page_one] = [
+ {"name": f"unrelated-{i}", "status": "completed"}
+ for i in range(100 - page_one)
+ ]
+ for job_id, job in enumerate(self.jobs, 1):
+ job["id"] = job_id
+ self.assertGreater(len(self.jobs), 100)
+
+ def test_failed_rerun_on_a_later_job_page_rejects(self):
+ # Re-running the summary carries the package job into attempt 2 on
+ # page 1; the fresh summary record, which failed, is on page 2.
+ self.rerun("release-gate / Release Gate Summary")
+ self.jobs[-1]["conclusion"] = "failure"
+ self.paginate_jobs(len(self.jobs) - 1)
+ page_one = self.fetch(
+ "repos/owner/repo/actions/runs/123/jobs?filter=all&page=1"
+ )["jobs"]
+ self.assertTrue(
+ any(
+ job["name"] == "release-gate / pip Install Verification"
+ and job["run_attempt"] == 2
+ for job in page_one
+ )
+ )
+ with self.assertRaises(ValueError) as caught:
+ self.validate()
+ self.assertIn("Release Gate Summary", str(caught.exception))
+ self.jobs[-1]["conclusion"] = "success"
+ self.assertEqual(self.validate(), "1")
+
+ def test_newer_build_on_later_job_page_supersedes_the_old_artifact(self):
+ # A full rerun's fresh records, including the rebuilt package job,
+ # are all on page 2; page 1 holds only attempt 1.
+ attempt_one = len(self.jobs)
+ self.rerun(*(job["name"] for job in self.jobs))
+ self.paginate_jobs(attempt_one)
+ with self.assertRaises(ValueError):
+ self.validate()
+ self.artifact["name"] = "verified-python-dist-2"
+ self.run_artifacts.append({"name": "verified-python-dist-2"})
+ self.assertEqual(self.validate(), "2")
+
def test_wrong_workflow_commit_event_and_repository_fail(self):
original = copy.deepcopy(self.run)
for changes in (
diff --git a/tests/ci/test_package_artifact_policy.py b/tests/ci/test_package_artifact_policy.py
index cafe38e2f6..9337a8d78b 100644
--- a/tests/ci/test_package_artifact_policy.py
+++ b/tests/ci/test_package_artifact_policy.py
@@ -1,12 +1,12 @@
"""Regression tests for the release artifact size and content gate."""
-# allow: no-sut-import — this test invokes the release gate script as a
-# subprocess (it runs standalone in CI before the package is installed),
-# so it never imports local_deep_research directly.
+# allow: no-sut-import — tests invoke or load standalone CI scripts before
+# the package is installed, without importing local_deep_research directly.
from __future__ import annotations
import copy
+import importlib.util
import io
import re
import stat
@@ -250,6 +250,127 @@ def test_real_release_builds_enforce_the_artifact_policy(
RELEASE_WORKFLOW = REPO_ROOT / ".github" / "workflows" / "release.yml"
+def test_publisher_requires_the_package_jobs_named_by_the_workflows():
+ """Use real workflow names rather than copying the validator's names."""
+ release = yaml.safe_load(RELEASE_WORKFLOW.read_text(encoding="utf-8"))
+ gate = yaml.safe_load(RELEASE_GATE.read_text(encoding="utf-8"))
+ caller_id, caller = next(
+ (job_id, job)
+ for job_id, job in release["jobs"].items()
+ if job.get("uses", "").endswith("/release-gate.yml")
+ )
+ prefix = caller.get("name", caller_id)
+ names = [
+ f"{prefix} / {gate['jobs'][job_id]['name']}"
+ for job_id in ("pip-install-check", "release-gate-summary")
+ ]
+ install = gate["jobs"]["package-install-matrix"]
+ for row in install["strategy"]["matrix"]["include"]:
+ name = install["name"]
+ for key, value in row.items():
+ name = name.replace("${{ matrix." + key + " }}", str(value))
+ assert "${{" not in name, "unresolved matrix job name"
+ names.append(f"{prefix} / {name}")
+ names.append(release["jobs"]["build"].get("name", "build"))
+ jobs = [
+ {
+ "id": i,
+ "name": name,
+ "run_attempt": 1,
+ "status": "completed",
+ "conclusion": "success",
+ }
+ for i, name in enumerate(names, 1)
+ ]
+ sha = "a" * 40
+ root = "repos/owner/repo"
+ responses = {
+ f"{root}/actions/runs/123": {
+ "repository": {"full_name": "owner/repo"},
+ "path": ".github/workflows/release.yml",
+ "head_sha": sha,
+ "head_branch": "main",
+ "event": "push",
+ "run_attempt": 1,
+ },
+ f"{root}/actions/runs/123/jobs?filter=all&per_page=100&page=1": {
+ "jobs": jobs
+ },
+ f"{root}/compare/{sha}...heads/main": {"status": "ahead"},
+ f"{root}/actions/runs/123/artifacts?per_page=100&page=1": {
+ "artifacts": [{"name": "verified-python-dist-1"}]
+ },
+ f"{root}/actions/artifacts/456": {
+ "id": 456,
+ "name": "verified-python-dist-1",
+ "expired": False,
+ "workflow_run": {"id": 123, "head_sha": sha},
+ },
+ }
+ payload = {
+ "sha": sha,
+ "run_id": "123",
+ "artifact_id": "456",
+ "manifest_sha256": "b" * 64,
+ "tag": "v1.2.3",
+ }
+ spec = importlib.util.spec_from_file_location(
+ "release_package", REPO_ROOT / ".github/scripts/release_package.py"
+ )
+ policy = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(policy)
+ assert (
+ policy.validate_source("owner/repo", payload, responses.__getitem__)
+ == "1"
+ )
+ for job in jobs:
+ job["conclusion"] = "failure"
+ with pytest.raises(
+ ValueError, match="Required source job did not succeed"
+ ):
+ policy.validate_source("owner/repo", payload, responses.__getitem__)
+ job["conclusion"] = "success"
+
+
+def test_publish_job_revalidates_the_source_after_approval():
+ """Re-running only ``publish`` reuses build-package's pre-approval outputs,
+ so the OIDC job itself must recheck the live source run before upload."""
+ publish = yaml.safe_load(PUBLISH_WORKFLOW.read_text(encoding="utf-8"))
+ job = publish["jobs"]["publish"]
+ assert job["environment"] == "release"
+ steps = job["steps"]
+ source = [
+ i
+ for i, step in enumerate(steps)
+ if "release_package.py source" in step.get("run", "")
+ ]
+ uploads = [
+ i
+ for i, step in enumerate(steps)
+ if step.get("uses", "").startswith("pypa/gh-action-pypi-publish@")
+ ]
+ assert len(source) == 1 and uploads
+ assert source[0] < min(uploads)
+ step = steps[source[0]]
+ assert step["env"]["EXPECTED_ARTIFACT_ATTEMPT"] == (
+ "${{ needs.build-package.outputs.artifact_attempt }}"
+ )
+ assert publish["jobs"]["build-package"]["outputs"]["artifact_attempt"] == (
+ "${{ steps.source.outputs.artifact_attempt }}"
+ )
+ assert job["permissions"]["actions"] == "read"
+ checkout = next(
+ s for s in steps if s.get("uses", "").startswith("actions/checkout@")
+ )
+ assert checkout["with"]["persist-credentials"] is False
+ assert checkout["with"]["sparse-checkout"] == (
+ ".github/scripts/release_package.py"
+ )
+ # No step in the OIDC job installs or runs the downloaded package.
+ for step in steps:
+ assert "pip install" not in step.get("run", "")
+
+
def _console_scripts():
config = tomllib.loads(PYPROJECT.read_text(encoding="utf-8"))
return tuple(sorted(config["project"].get("scripts", {})))