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
83 changes: 83 additions & 0 deletions scripts/telemetry-cost-contract/tests/test_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,89 @@ def get(path, *, paginate=False):
self.assertEqual(github.statuses, [("abc123", "failure", github.statuses[0][2], True)])


class MergeRaceBeforeValidate(unittest.TestCase):
"""Regression for the merge-queue race: the signal workflow runs on a PR that merges
(closing it) before this workflow_run executes, so the open-PR lookup finds zero — not
because the result is ambiguous, but because it is moot. Observed live on
ComfyUI_frontend's 2026-11-24 merge of PR #24114: run 45391308799 hard-failed with
'Expected exactly one open PR ... found 0' even though SOFT_FAIL=true."""

def test_already_merged_pr_skips_cleanly_without_publishing_a_status(self):
github = FakeGitHub()
github.pr["state"] = "closed"
github.pr["merged_at"] = "2026-11-24T09:06:53Z"

self.assertEqual(validator(github).run(event()), 0)
self.assertEqual(github.statuses, [])
self.assertEqual(github.upserted_comments, [])
self.assertEqual(github.deleted_comments, [])

def test_already_merged_pr_via_fork_fallback_also_skips_cleanly(self):
github = FakeGitHub()
github.pr["state"] = "closed"
github.pr["merged_at"] = "2026-11-24T09:06:53Z"

def get(path, *, paginate=False):
if path.endswith("/commits/abc123/pulls"):
return [{"number": 17, "base": {"repo": {"full_name": github.repo}}}]
if path.endswith("/pulls/17"):
return dict(github.pr)
raise AssertionError(f"unexpected GitHub request: {path}")

github.get = get
fork_event = {"workflow_run": {"event": "pull_request", "head_sha": "abc123",
"pull_requests": []}}

self.assertEqual(validator(github).run(fork_event), 0)
self.assertEqual(github.statuses, [])

def test_closed_without_merging_still_fails_closed(self):
# A closed-but-not-merged PR is genuine ambiguity (abandoned PR, not a merge race):
# there is no "the result is moot, it already merged" justification to skip silently.
github = FakeGitHub()
github.pr["state"] = "closed"
github.pr["merged_at"] = None

self.assertEqual(validator(github).run(event()), 1)
self.assertEqual([s[1] for s in github.statuses], ["failure"])

def test_two_merged_candidates_is_still_ambiguous_and_fails_closed(self):
github = FakeGitHub()
github.pr["state"] = "closed"
github.pr["merged_at"] = "2026-11-24T09:06:53Z"

def get(path, *, paginate=False):
if path.endswith("/pulls/17") or path.endswith("/pulls/18"):
return dict(github.pr)
raise AssertionError(f"unexpected GitHub request: {path}")

github.get = get
two_candidates = event()
two_candidates["workflow_run"]["pull_requests"] = [{"number": 17}, {"number": 18}]

self.assertEqual(validator(github).run(two_candidates), 1)
self.assertEqual([s[1] for s in github.statuses], ["failure"])

def test_merged_candidate_with_failed_lookup_still_fails_closed(self):
github = FakeGitHub()
github.pr["state"] = "closed"
github.pr["merged_at"] = "2026-11-24T09:06:53Z"

def get(path, *, paginate=False):
if path.endswith("/pulls/17"):
return dict(github.pr)
if path.endswith("/pulls/18"):
return None
raise AssertionError(f"unexpected GitHub request: {path}")

github.get = get
two_candidates = event()
two_candidates["workflow_run"]["pull_requests"] = [{"number": 17}, {"number": 18}]

self.assertEqual(validator(github).run(two_candidates), 1)
self.assertEqual([s[1] for s in github.statuses], ["failure"])


class PendingStatusWriteFailure(unittest.TestCase):
def test_failed_pending_write_is_treated_as_critical_and_short_circuits(self):
github = FakeGitHub(pending_publish_ok=False)
Expand Down
58 changes: 44 additions & 14 deletions scripts/telemetry-cost-contract/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@ class ChangedFilesUnavailable(Exception):
to be complete. Always fails the check closed (``changed_files_unavailable``)."""


class _AlreadyMerged:
"""Sentinel type for _resolve_pr: the commit's only associated PR merged in the window
between the signal workflow uploading and this workflow_run executing. The verdict is
moot post-merge (nothing left to publish a status against that could still block
anything), so this is distinct from genuine ambiguity, which still fails closed."""


_ALREADY_MERGED = _AlreadyMerged()


def log(msg: str) -> None:
print(msg, file=sys.stderr, flush=True)

Expand Down Expand Up @@ -336,11 +346,16 @@ def run(self, event: dict) -> int:
f"Triggering workflow_run event was '{wr_event}', not 'pull_request'. The "
"signal workflow must run on pull_request; refusing to validate.")

self.pr_number = self._resolve_pr(event, head_sha)
if self.pr_number is None:
resolved = self._resolve_pr(event, head_sha)
if isinstance(resolved, _AlreadyMerged):
log(f"The PR for {head_sha} merged before this validate run could execute; the "
"verdict is moot post-merge. Skipping without publishing a status.")
return 0
if resolved is None:
return self._fail_closed_pre_pr(
head_sha, "Could not resolve exactly one open PR for this commit; refusing "
"to publish an ambiguous result.", log_message=False)
self.pr_number = resolved

pr = self.gh.get(f"/repos/{self.gh.repo}/pulls/{self.pr_number}")
if not pr:
Expand Down Expand Up @@ -414,31 +429,46 @@ def run(self, event: dict) -> int:
"missing_cost_impact",
f"Matched pattern `{pattern_text}` against an added line in {md_code(filename)}.")

def _resolve_pr(self, event: dict, head_sha: str) -> int | None:
"""Exactly one open PR. Same-repo runs carry workflow_run.pull_requests; fork runs do
not, so fall back to the commit->PR association (GitHub-owned data either way)."""
def _resolve_pr(self, event: dict, head_sha: str) -> int | _AlreadyMerged | None:
"""Exactly one open PR, ``_ALREADY_MERGED`` if the commit's one associated PR merged
before this run could execute, or ``None`` if genuinely ambiguous (zero or multiple
candidates with none merged). Same-repo runs carry workflow_run.pull_requests; fork
runs do not, so fall back to the commit->PR association (GitHub-owned data either
way)."""
wr = event.get("workflow_run") or {}
candidates = [pr.get("number") for pr in (wr.get("pull_requests") or []) if pr.get("number")]
if not candidates:
assoc = self.gh.get(f"/repos/{self.gh.repo}/commits/{head_sha}/pulls") or []
candidates = [
pr.get("number") for pr in assoc
if pr.get("state") == "open"
and (pr.get("base") or {}).get("repo", {}).get("full_name") == self.gh.repo
if (pr.get("base") or {}).get("repo", {}).get("full_name") == self.gh.repo
]

open_prs: list[int] = []
merged_prs: list[int] = []
lookup_failed = False
for number in dict.fromkeys(candidates):
data = self.gh.get(f"/repos/{self.gh.repo}/pulls/{number}")
if data and data.get("state") == "open":
if not data:
lookup_failed = True
continue
Comment thread
christian-byrne marked this conversation as resolved.
Resolved
if data.get("state") == "open":
open_prs.append(number)
elif data.get("merged_at"):
merged_prs.append(number)

if len(open_prs) != 1:
error(f"Expected exactly one open PR associated with {head_sha}, found "
f"{len(open_prs)} (event={wr.get('event')}). Refusing to publish an "
"ambiguous result.")
return None
return open_prs[0]
if len(open_prs) == 1:
return open_prs[0]

if not lookup_failed and not open_prs and len(merged_prs) == 1:
log(f"PR #{merged_prs[0]} associated with {head_sha} already merged before this "
"validate run executed.")
return _ALREADY_MERGED

error(f"Expected exactly one open PR associated with {head_sha}, found "
f"{len(open_prs)} (event={wr.get('event')}). Refusing to publish an "
"ambiguous result.")
return None


def main() -> int:
Expand Down
Loading