From 5474c5718f38566cb8bb691eedb276d7b3671a21 Mon Sep 17 00:00:00 2001 From: William Godbe Date: Wed, 28 Oct 2026 14:54:48 -0700 Subject: [PATCH 1/2] Fix test-quarantine evidence collection reliability Verify original Case B tracking issues before activation and collect complete Part 2 pipeline evidence deterministically. Require bound eligibility receipts when validating unquarantine patches. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../scripts/test-quarantine/README.md | 26 +- .../collect_case_a_eligibility.py | 70 +++- .../collect_unquarantine_eligibility.py | 351 ++++++++++++++++++ .../test_collect_case_a_eligibility.py | 4 + .../test_collect_unquarantine_eligibility.py | 313 ++++++++++++++++ .../test_validate_pull_request_outputs.py | 33 ++ .../test-quarantine/test_workflow_policy.py | 2 +- .../validate_pull_request_outputs.py | 30 +- .github/workflows/test-quarantine.lock.yml | 34 +- .github/workflows/test-quarantine.md | 49 ++- 10 files changed, 893 insertions(+), 19 deletions(-) create mode 100644 .github/workflows/scripts/test-quarantine/collect_unquarantine_eligibility.py create mode 100644 .github/workflows/scripts/test-quarantine/test_collect_unquarantine_eligibility.py diff --git a/.github/workflows/scripts/test-quarantine/README.md b/.github/workflows/scripts/test-quarantine/README.md index 5f20147e4779..00adde9e2ef6 100644 --- a/.github/workflows/scripts/test-quarantine/README.md +++ b/.github/workflows/scripts/test-quarantine/README.md @@ -24,7 +24,12 @@ issue. These correspond to Case A and Case B in history cutoff commit, exact evidence identity, and the `origin/main` history commit used for the decision. The receipt also identifies Case B tests with at least one post-cutoff failure whose source snapshot contains - the unquarantine commit. Assembly history is + the unquarantine commit. An authenticated, cached lookup verifies that the + original Case B tracking number is an issue (open or closed), not a PR. + `case_b_issue_verified` is required at the safe-output boundary; the agent + need not repeat the lookup through integrity-filtered tools. Lookup errors + abort collection, while a definitive missing issue is ineligible. + Assembly history is reconstructed across the resolved test project, including deleted quarantine files. Same-project partial declarations are also evaluated as a logical type for type-level quarantine history, so sibling declaration @@ -48,8 +53,20 @@ issue. These correspond to Case A and Case B in method and partial type moves between files preserve their logical history, and issue-URL-only replacements are not remove/add transitions. Automated unquarantine requires an exact - `first-quarantine` match and fails closed otherwise. -4. The pre-activation job uploads all three files as the one-day + `first-quarantine` match and fails closed otherwise. `introduced_utc` records + the exact target's introduction, rather than a later issue-URL replacement. +4. `collect_unquarantine_eligibility.py` fully paginates 30 days of main builds + and results for pipelines 84 and 87 before activation. It preserves exact + result names and per-pipeline denominators, maps rows through the shared + source resolver, and requires zero failures, real passes, 66% build + appearance, 60-day age, first-quarantine history, and no human suppression or + re-quarantine blocklist match. Unresolved rows fail closed. Ambiguous + re-quarantine PR ownership conservatively excludes targets sharing the issue + in that file; a truncated diff excludes the whole file. + The compact receipt records complete collection, pipeline counts, eligible + source targets, and the history receipt's SHA-256. Missing pages or malformed + responses abort pre-activation; they never become an empty candidate list. + The pre-activation job uploads all four files as the one-day `test-quarantine-evidence-` artifact. 5. The agent may choose a new-quarantine or re-quarantine candidate only from the corresponding deterministic eligible-test list injected into its @@ -72,7 +89,7 @@ issue. These correspond to Case A and Case B in target changes. It rejects unrelated edits, mixed additions/removals, duplicate targets, stale project source, additions that do not match an eligible Case A or Case B receipt, and removals whose exact current history - is not `first-quarantine`. + is not `first-quarantine` or lacks bound deterministic Part 2 eligibility. Agent-provided log excerpts and URLs are for human display only. They are not accepted as validation evidence. @@ -210,6 +227,7 @@ Run the deterministic collector fixtures: ```bash python3 -B .github/workflows/scripts/test-quarantine/test_collect_case_a_eligibility.py +python3 -B .github/workflows/scripts/test-quarantine/test_collect_unquarantine_eligibility.py ``` Run the pull-request action-boundary fixtures: diff --git a/.github/workflows/scripts/test-quarantine/collect_case_a_eligibility.py b/.github/workflows/scripts/test-quarantine/collect_case_a_eligibility.py index 45e83f7d95d2..ec13665b248d 100644 --- a/.github/workflows/scripts/test-quarantine/collect_case_a_eligibility.py +++ b/.github/workflows/scripts/test-quarantine/collect_case_a_eligibility.py @@ -579,6 +579,13 @@ def build_source_index(root): "type": type_name, "method": method, "method_line": method_line + 1, + "is_test": any( + re.search( + r"\[\s*(?:global::)?(?:\w+\.)*\w*(?:Fact|Theory)(?:Attribute)?\b", + sanitize_csharp(attribute), + ) is not None + for attribute in logical_attributes(attributes) + ), "project_root": project_root, "method_quarantined": bool(parsed_attributes["method"]), "method_operating_systems": ( @@ -2545,6 +2552,10 @@ def collect_requarantine_history( "type": declaration["type"], "method": declaration["method"], "issue": issue, + "introduced_utc": next(( + event.get("utc") for event in events + if event["status"] == "added" + ), None), "status": ( classify_current_quarantine_history(events) if issue is not None else "ambiguous" @@ -2615,6 +2626,10 @@ def collect_requarantine_history( "method": declaration["method"], "data": data_attribute["data"], "issue": issue, + "introduced_utc": next(( + event.get("utc") for event in events + if event["status"] == "added" + ), None), "status": ( classify_current_quarantine_history(events) if issue is not None else "ambiguous" @@ -2672,6 +2687,10 @@ def collect_requarantine_history( "type": declaration["type"], "method": None, "issue": issue, + "introduced_utc": next(( + event.get("utc") for event in events + if event["status"] == "added" + ), None), "status": ( classify_current_quarantine_history(events) if issue is not None else "ambiguous" @@ -2716,6 +2735,10 @@ def collect_requarantine_history( "scope": "assembly", "path": assembly["path"], "issue": assembly["issue"], + "introduced_utc": next(( + event.get("utc") for event in events + if event["status"] == "added" + ), None), "type": None, "method": None, "status": ( @@ -2982,6 +3005,38 @@ def github_commit_contains(repository, ancestor, descendant, token): raise ValueError(f"Unexpected GitHub comparison status: {status!r}") +def github_issue_exists(repository, issue, token): + if not token: + raise ValueError("A GitHub token is required to verify tracking issues") + request = urllib.request.Request( + f"https://api.github.com/repos/{repository}/issues/{issue}", + headers={ + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "User-Agent": "aspnetcore-test-quarantine", + }, + ) + for attempt in range(3): + try: + with urllib.request.urlopen(request, timeout=30) as response: + data = json.load(response) + return ( + data.get("number") == issue + and data.get("url") == f"https://api.github.com/repos/{repository}/issues/{issue}" + and "pull_request" not in data + and data.get("state") in ("open", "closed") + ) + except urllib.error.HTTPError as error: + if error.code == 404: + return False + if attempt == 2 or error.code not in (403, 429) and error.code < 500: + raise + except OSError: + if attempt == 2: + raise + time.sleep(2 * (attempt + 1)) + + def commit_contains(root, repository, ancestor, descendant, token): if not ancestor or not descendant: raise ValueError("Both ancestor and descendant commits are required") @@ -3054,6 +3109,7 @@ def collect( pr_files_provider=None, commit_contains_provider=None, history_ref="HEAD", + issue_exists_provider=None, ): root = pathlib.Path(root) token = os.environ.get("GH_TOKEN", "") @@ -3069,6 +3125,9 @@ def collect( token, ) ) + issue_exists_provider = issue_exists_provider or ( + lambda issue: github_issue_exists(repository, issue, token) + ) source_index = build_source_index(root) history_commit = git(root, "rev-parse", "--verify", history_ref) history_order = first_parent_order(root, history_ref) @@ -3080,6 +3139,7 @@ def collect( receipts = {} pr_files_cache = {} ancestry_cache = {} + issue_cache = {} project_history_cache = {} assembly_history_cache = {} method_history_cache = {} @@ -3112,6 +3172,7 @@ def collect( "eligible_failure_builds": [], "case_b_eligible": False, "case_b_issue": None, + "case_b_issue_verified": False, "quarantine_operating_systems": None, "evidence": None, "reasons": reasons, @@ -3386,7 +3447,14 @@ def collect( if case_b: receipt["status"] = "ineligible" if included: - receipt["case_b_eligible"] = True + issue = receipt["case_b_issue"] + if issue not in issue_cache: + issue_cache[issue] = issue_exists_provider(issue) is True + receipt["case_b_issue_verified"] = issue_cache[issue] + if receipt["case_b_issue_verified"]: + receipt["case_b_eligible"] = True + else: + reasons.append("original-quarantine-issue-unverified") else: reasons.append("no-post-cutoff-failures") continue diff --git a/.github/workflows/scripts/test-quarantine/collect_unquarantine_eligibility.py b/.github/workflows/scripts/test-quarantine/collect_unquarantine_eligibility.py new file mode 100644 index 000000000000..8e2eb6d46ce3 --- /dev/null +++ b/.github/workflows/scripts/test-quarantine/collect_unquarantine_eligibility.py @@ -0,0 +1,351 @@ +#!/usr/bin/env python3 + +import argparse +import collections +import datetime +import hashlib +import json +import os +import pathlib +import re +import time +import urllib.error +import urllib.parse +import urllib.request + +from collect_requarantine_history import MODULE as SOURCE + + +ADO = "https://dev.azure.com/dnceng-public/public/_apis" +VSTMR = "https://vstmr.dev.azure.com/dnceng-public/public/_apis" +PIPELINES = (84, 87) +IIS_PREFIX = re.compile( + r"^Microsoft\.AspNetCore\.Server\.IIS\." + r"(?:(?:IISExpress|NewHandler|NewShim)\.)?FunctionalTests\." +) + + +def fetch(url): + for attempt in range(3): + try: + request = urllib.request.Request( + url, headers={"User-Agent": "aspnetcore-test-quarantine"} + ) + with urllib.request.urlopen(request, timeout=120) as response: + return json.load(response), response.headers + except urllib.error.HTTPError as error: + if attempt == 2 or error.code < 500 and error.code != 429: + raise + except OSError: + if attempt == 2: + raise + time.sleep(2 * (attempt + 1)) + + +def pages(endpoint, parameters, provider): + token = None + seen = set() + while True: + query = dict(parameters) + if token: + query["continuationToken"] = token + data, headers = provider(f"{endpoint}?{urllib.parse.urlencode(query)}") + if not isinstance(data, dict) or not isinstance(data.get("value"), list): + raise ValueError("Azure DevOps returned an invalid result page") + yield from data["value"] + token = headers.get("x-ms-continuationtoken") or data.get("continuationToken") + if not token: + break + if token in seen: + raise ValueError("Azure DevOps repeated a continuation token") + seen.add(token) + + +def collect_results(now, provider=fetch): + pipelines = {} + start = now - datetime.timedelta(days=30) + for pipeline in PIPELINES: + builds = list(pages(f"{ADO}/build/builds", { + "definitions": pipeline, + "branchName": "refs/heads/main", + "statusFilter": "completed", + "minTime": start.isoformat(), + "$top": 100, + "api-version": "7.1", + }, provider)) + build_ids = set() + tests = {} + for build in builds: + build_id = build["id"] + if build_id in build_ids: + raise ValueError("Azure DevOps returned a duplicate build") + if ( + build.get("sourceBranch") != "refs/heads/main" + or build.get("status") != "completed" + or build.get("definition", {}).get("id") != pipeline + ): + raise ValueError("Azure DevOps returned a build outside the query") + build_ids.add(build_id) + for result in pages(f"{VSTMR}/testresults/resultsbyBuild", { + "buildId": build_id, + "$top": 10000, + "api-version": "7.1-preview.1", + }, provider): + name = result.get("automatedTestName") + if not isinstance(name, str) or not name: + raise ValueError("A test result lacks its exact automatedTestName") + if name.endswith(".WorkItemExecution"): + continue + counts = tests.setdefault(name, { + "passed": 0, "failed": 0, "other": 0, "builds": set(), + }) + outcome = result.get("outcome") + if not isinstance(outcome, str): + raise ValueError("A test result lacks its outcome") + key = {"Passed": "passed", "Failed": "failed"}.get(outcome, "other") + counts[key] += 1 + counts["builds"].add(build_id) + pipelines[str(pipeline)] = {"build_count": len(build_ids), "tests": tests} + return pipelines + + +def target_key(target): + return tuple(target.get(key) for key in ("scope", "path", "type", "method", "data")) + + +def resolve(root, name, index): + source = SOURCE.resolve_source(root, name, index) + if source["status"] == "missing" and IIS_PREFIX.match(name): + test_name, _ = SOURCE.split_test_name(name) + runtime_type = test_name.rsplit(".", 1)[0] + suffix = IIS_PREFIX.sub("", runtime_type) + candidates = [ + type_name for type_name in index["types"] + if IIS_PREFIX.match(type_name) + and IIS_PREFIX.sub("", type_name) == suffix + ] + if len(candidates) == 1: + source = SOURCE.resolve_source( + root, candidates[0] + name[len(runtime_type):], index + ) + if not source.get("path", "").startswith("src/Servers/IIS/"): + return {"status": "ambiguous"} + return source + + +def matches(target, source): + if source.get("status") != "exact": + return False + scope = target["scope"] + if scope == "assembly": + return target["project_root"] == source["assembly_project_root"] + if scope == "type": + return any( + item["type"] == target["type"] + and item["project_root"] == target["project_root"] + for item in source["type_history_locations"] + ) + if ( + target["path"] != source["path"] + or target["type"] != source["declaring_type"] + or target["method"] != source["method"] + ): + return False + if scope == "data": + row = source.get("data_quarantine") + return isinstance(row, dict) and row["data"] == target["data"] + return scope == "method" + + +def expected_methods(root, target, index): + if target["scope"] in ("method", "data"): + return {(target["type"], target["method"])} + owners = set() + if target["scope"] == "type": + current_type = target["type"] + while current_type not in owners: + owners.add(current_type) + logical = SOURCE.logical_type(index, current_type, target["project_root"]) + if logical["status"] != "exact": + return set() + if not logical["base"]: + break + base = SOURCE.resolve_base_type( + index, current_type, logical["base"], target["project_root"], + ) + if base["status"] != "exact": + return set() + current_type = base["type"] + else: + return set() + methods = set() + for name, declarations in index["methods"].items(): + methods.update( + (item["type"], name) for item in declarations + if item["project_root"] == target["project_root"] and item["is_test"] + and (target["scope"] == "assembly" or item["type"] in owners) + ) + return methods + + +def suppressed(target, names, closed_prs, now): + identifiers = set(names) + if target["scope"] == "method": + identifiers.update(SOURCE.split_test_name(name)[0] for name in names) + if target["scope"] == "type": + identifiers.add(target["type"]) + for pr in closed_prs: + text = f"{pr.get('title', '')}\n{pr.get('body', '')}" + if not any(identifier in text for identifier in identifiers): + continue + if pr.get("trusted_closed") is True and pr.get("closed_at"): + return True + timestamp = pr.get("unquarantine_label_added_at") + if timestamp and now < SOURCE.parse_utc(timestamp) + datetime.timedelta(days=30): + return True + return False + + +def collect(root, history, history_bytes, closed_prs, blocked_issues, requarantine_prs, + now, provider=fetch): + root = pathlib.Path(root) + if SOURCE.git(root, "rev-parse", "HEAD") != history["history_commit"]: + raise ValueError("Source checkout differs from the history receipt") + index = SOURCE.build_source_index(root) + current = {target_key(target): target for target in SOURCE.current_quarantine_targets(index)} + pipelines = collect_results(now, provider) + resolved = { + name: resolve(root, name, index) + for pipeline in pipelines.values() for name in pipeline["tests"] + } + candidates = [] + exclusions = collections.Counter() + for historical in history["targets"]: + target = current.get(target_key(historical)) + if target is None: + raise ValueError("History receipt contains a missing current target") + reasons = [] + introduced = historical.get("introduced_utc") + if ( + historical["status"] != "first-quarantine" + or not isinstance(historical.get("issue"), int) + or not introduced + or now - SOURCE.parse_utc(introduced) < datetime.timedelta(days=60) + ): + exclusions["history-or-age-unproven"] += 1 + continue + if historical["issue"] in blocked_issues: + reasons.append("re-quarantine-issue") + if any( + entry["filename"] == target["path"] + and ( + entry["patch_truncated"] + or any( + SOURCE.quarantine_issue(line) == historical["issue"] + for line in entry["added_lines"] + ) + ) + for pr in requarantine_prs for entry in pr["quarantine_entries"] + ): + # Added attribute lines do not prove their owner. Block a shared issue + # conservatively; only a truncated diff can implicate the whole file. + reasons.append("re-quarantine-file") + if "src/SignalR/server/Specification.Tests/" in target["path"]: + reasons.append("excluded-source") + expected = expected_methods(root, target, index) + names = [name for name, source in resolved.items() if matches(target, source)] + if suppressed(target, names, closed_prs, now): + reasons.append("human-suppression") + if any("AlwaysTestTests.SuccessfulTests.GuaranteedQuarantinedTest" in name for name in names): + reasons.append("always-quarantined") + if any( + source["status"] != "exact" + and SOURCE.split_test_name(name)[0].rsplit(".", 1)[-1] in { + method for _, method in expected + } + for name, source in resolved.items() + ): + reasons.append("unresolved-test-source") + evidence = {} + for pipeline_id, pipeline in pipelines.items(): + groups = {} + for name in names: + counts = pipeline["tests"].get(name) + if counts is None: + continue + source = resolved[name] + method = (source["declaring_type"], source["method"]) + group = groups.setdefault(method, { + "passed": 0, "failed": 0, "other": 0, "builds": set(), + }) + for key in ("passed", "failed", "other"): + group[key] += counts[key] + group["builds"].update(counts["builds"]) + if not groups: + continue + if any(group["failed"] for group in groups.values()): + reasons.append("failed-results") + healthy = bool(expected) and expected == set(groups) and all( + group["passed"] > 0 + and group["failed"] == 0 + and len(group["builds"]) * 100 >= pipeline["build_count"] * 66 + for group in groups.values() + ) + if not healthy: + reasons.append("insufficient-run-evidence") + evidence[pipeline_id] = { + "passed": sum(group["passed"] for group in groups.values()), + "failed": sum(group["failed"] for group in groups.values()), + "other": sum(group["other"] for group in groups.values()), + "methods": len(groups), + "build_count": pipeline["build_count"], + } + if not evidence: + reasons.append("no-run-evidence") + if reasons: + exclusions.update(set(reasons)) + continue + candidates.append({**historical, "eligible": True, "pipelines": evidence}) + return { + **{key: history[key] for key in ( + "schema_version", "repository", "ref", "commit", "history_ref", "history_commit", + )}, + "history_sha256": hashlib.sha256(history_bytes).hexdigest(), + "complete": True, + "generated_utc": now.isoformat(), + "window_start": (now - datetime.timedelta(days=30)).isoformat(), + "pipelines": { + key: {"build_count": value["build_count"], "test_count": len(value["tests"])} + for key, value in pipelines.items() + }, + "excluded": dict(exclusions), + "targets": candidates, + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--history", required=True) + parser.add_argument("--closed-prs", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--repo-root", default=".") + args = parser.parse_args() + history_bytes = pathlib.Path(args.history).read_bytes() + receipt = collect( + args.repo_root, json.loads(history_bytes), history_bytes, + json.loads(pathlib.Path(args.closed_prs).read_text(encoding="utf-8")), + json.loads(os.environ["REQUARANTINE_ISSUES"]), + json.loads(os.environ["REQUARANTINE_PRS"]), + datetime.datetime.now(datetime.timezone.utc), + ) + compact = json.dumps(receipt, separators=(",", ":"), sort_keys=True) + if len(compact.encode("utf-8")) > 120000: + raise ValueError("Unquarantine evidence exceeds the safe job-output limit") + pathlib.Path(args.output).write_text(compact, encoding="utf-8") + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + output.write(f"unquarantine_eligibility={compact}\n") + print(f"Part 2 complete: {len(receipt['targets'])} eligible targets; {receipt['pipelines']}") + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/scripts/test-quarantine/test_collect_case_a_eligibility.py b/.github/workflows/scripts/test-quarantine/test_collect_case_a_eligibility.py index dc6f28723630..189a0fc220ec 100644 --- a/.github/workflows/scripts/test-quarantine/test_collect_case_a_eligibility.py +++ b/.github/workflows/scripts/test-quarantine/test_collect_case_a_eligibility.py @@ -204,6 +204,7 @@ def collect( pr_files_provider=lambda _: set(), commit_contains_provider=lambda _ancestor, _descendant: True, module=None, + issue_exists_provider=lambda _: True, ): module = module or MODULE serialized = json.dumps(data, separators=(",", ":")).encode() @@ -217,6 +218,7 @@ def collect( subprocess.check_output(["git", "-C", root, "rev-parse", "HEAD"], text=True).strip(), pr_files_provider=pr_files_provider, commit_contains_provider=commit_contains_provider, + issue_exists_provider=issue_exists_provider, ) @@ -772,6 +774,7 @@ def test_theory_data_quarantine_support(): "method": "ReturnsExpectedResponse", "data": "HttpProtocols.Http3", "issue": 1, + "introduced_utc": "2026-08-04T00:00:00Z", "status": "re-quarantined", }], history @@ -1148,6 +1151,7 @@ def test_requarantine_history(): "type": "Microsoft.AspNetCore.Tests.SampleTests", "method": "ReturnsExpectedResponse", "issue": 1, + "introduced_utc": "2026-08-02T00:00:00Z", "status": "first-quarantine", }], first diff --git a/.github/workflows/scripts/test-quarantine/test_collect_unquarantine_eligibility.py b/.github/workflows/scripts/test-quarantine/test_collect_unquarantine_eligibility.py new file mode 100644 index 000000000000..781d933387fa --- /dev/null +++ b/.github/workflows/scripts/test-quarantine/test_collect_unquarantine_eligibility.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 + +import datetime +import json +import pathlib +import tempfile +import unittest +import urllib.parse +from unittest import mock + +import collect_unquarantine_eligibility as MODULE +import test_collect_case_a_eligibility as FIXTURES +import test_validate_pull_request_outputs as PATCHES + + +NOW = datetime.datetime(2026, 10, 28, tzinfo=datetime.timezone.utc) +NAME = FIXTURES.TEST_NAME + + +class Provider: + def __init__(self, results=None, builds=None): + self.results = results if results is not None else { + 1: [(NAME, "Passed")], 2: [(NAME, "Passed")], + } + self.builds = builds if builds is not None else {84: [1, 2], 87: []} + self.calls = [] + self.fail_build = None + + def __call__(self, url): + self.calls.append(url) + query = urllib.parse.parse_qs(urllib.parse.urlparse(url).query) + page = int(query.get("continuationToken", ["0"])[0]) + if "/build/builds?" in url: + pipeline = int(query["definitions"][0]) + if query["branchName"] != ["refs/heads/main"]: + raise AssertionError("The collector must request main builds") + values = [{ + "id": build, "definition": {"id": pipeline}, + "sourceBranch": "refs/heads/main", "status": "completed", + } for build in self.builds[pipeline]] + else: + build = int(query["buildId"][0]) + if build == self.fail_build: + raise OSError("result page unavailable") + values = [ + {"automatedTestName": name, "outcome": outcome} + for name, outcome in self.results.get(build, []) + ] + headers = {"x-ms-continuationtoken": str(page + 1)} if page + 1 < len(values) else {} + return {"value": values[page:page + 1]}, headers + + +class UnquarantineTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = pathlib.Path(self.directory.name) + FIXTURES.initialize_repository(self.root) + self.path = self.root / FIXTURES.TEST_PATH + self.path.write_text(FIXTURES.source(), encoding="utf-8") + FIXTURES.commit(self.root, "Initial test", "2026-01-01T00:00:00Z") + self.set_source(FIXTURES.source(FIXTURES.QUARANTINE_ATTRIBUTE)) + + def set_source(self, source, timestamp="2026-07-01T00:00:00Z"): + self.path.write_text(source, encoding="utf-8") + FIXTURES.commit(self.root, "Quarantine", timestamp) + self.history = MODULE.SOURCE.collect_requarantine_history( + self.root, "HEAD", "dotnet/aspnetcore", "refs/heads/main", "a" * 40, + ) + + def collect(self, provider=None, closed=None, blocked=None, requarantine_prs=None): + encoded = json.dumps(self.history).encode() + return MODULE.collect( + self.root, self.history, encoded, closed or [], blocked or [], requarantine_prs or [], + NOW, provider or Provider(), + ) + + def fresh_source(self, baseline, quarantined, relative_path=FIXTURES.TEST_PATH): + self.root = self.root / "fresh" + self.root.mkdir() + FIXTURES.initialize_git_repository(self.root) + self.path = self.root / relative_path + self.path.parent.mkdir(parents=True) + (self.path.parent / "Sample.Tests.csproj").write_text("", encoding="utf-8") + self.path.write_text(baseline, encoding="utf-8") + FIXTURES.commit(self.root, "Initial source", "2026-01-01T00:00:00Z") + self.set_source(quarantined) + + def test_paginated_collection_finishes_before_candidates(self): + provider = Provider({1: [(NAME, "Passed"), (NAME, "NotExecuted")], + 2: [(NAME, "Passed")]}) + receipt = self.collect(provider) + self.assertTrue(receipt["complete"]) + self.assertEqual(set(receipt["pipelines"]), {"84", "87"}) + self.assertEqual(receipt["pipelines"]["84"]["build_count"], 2) + self.assertEqual(len(receipt["targets"]), 1, receipt) + evidence = receipt["targets"][0] + self.assertEqual(evidence["introduced_utc"], "2026-07-01T00:00:00Z") + self.assertEqual(evidence["pipelines"]["84"]["passed"], 2) + self.assertTrue(any("continuationToken=" in url for url in provider.calls)) + + def test_both_pipelines_are_collected_even_without_candidates(self): + self.history["targets"][0]["status"] = "re-quarantined" + receipt = self.collect() + self.assertEqual(set(receipt["pipelines"]), {"84", "87"}) + self.assertEqual(receipt["targets"], []) + + def test_missing_page_aborts_instead_of_emitting_empty_candidates(self): + provider = Provider() + provider.fail_build = 2 + with self.assertRaisesRegex(OSError, "page unavailable"): + self.collect(provider) + + def test_bad_pages_and_repeated_continuation_fail_closed(self): + for data, headers in (({}, {}), ({"value": []}, {"x-ms-continuationtoken": "same"})): + with self.subTest(data=data, headers=headers): + with self.assertRaises(ValueError): + list(MODULE.pages("https://example.test", {}, lambda _: (data, headers))) + + def test_skips_failures_age_and_appearance_fail_closed(self): + for label, results, builds in ( + ("skips", {1: [(NAME, "NotExecuted")], 2: [(NAME, "NotExecuted")]}, None), + ("failure", {1: [(NAME, "Passed")], 2: [(NAME, "Failed")]}, None), + ("sparse", {1: [(NAME, "Passed")]}, {84: [1, 2, 3], 87: []}), + ): + with self.subTest(label=label): + self.assertEqual(self.collect(Provider(results, builds))["targets"], []) + self.history["targets"][0]["introduced_utc"] = "2026-10-01T00:00:00Z" + self.assertEqual(self.collect()["targets"], []) + + def test_pipeline_denominators_are_separate(self): + receipt = self.collect(Provider(builds={84: [1, 2], 87: list(range(3, 10))})) + self.assertEqual(len(receipt["targets"]), 1, receipt) + provider = Provider({1: [(NAME, "Passed")], 2: [(NAME, "Failed")]}, + {84: [1], 87: [2]}) + self.assertEqual(self.collect(provider)["targets"], []) + + def test_unrelated_class_cannot_supply_run_evidence(self): + unrelated = NAME.replace("SampleTests", "UnrelatedTests") + self.assertEqual(self.collect(Provider({1: [(unrelated, "Passed")]}))["targets"], []) + + def test_method_uses_all_rows_but_data_target_only_its_row(self): + self.set_source(FIXTURES.theory_source( + "[InlineData(HttpProtocols.Http3)]", "[InlineData(HttpProtocols.Http2)]", + method_quarantine=FIXTURES.QUARANTINE_ATTRIBUTE, + )) + http3 = FIXTURES.THEORY_TEST_NAME + http2 = http3.replace("Http3", "Http2") + provider = Provider({1: [(http3, "Passed"), (http2, "Failed")], + 2: [(http3, "Passed")]}) + self.assertEqual(self.collect(provider)["targets"], []) + self.root = self.root / "data-target" + self.root.mkdir() + FIXTURES.initialize_repository(self.root) + self.path = self.root / FIXTURES.TEST_PATH + self.path.write_text(FIXTURES.theory_source( + "[InlineData(HttpProtocols.Http3)]", "[InlineData(HttpProtocols.Http2)]", + ), encoding="utf-8") + FIXTURES.commit(self.root, "Initial theory rows", "2026-01-01T00:00:00Z") + self.set_source(FIXTURES.theory_source( + '[QuarantinedTestData("https://github.com/dotnet/aspnetcore/issues/1", ' + 'OperatingSystems.Linux, HttpProtocols.Http3)]', + "[InlineData(HttpProtocols.Http2)]", + )) + self.assertEqual(len(self.collect(provider)["targets"]), 1) + + def test_human_suppression_and_issue_blocklist(self): + for pr in ( + {"title": NAME, "trusted_closed": True, "closed_at": "2026-10-01T00:00:00Z"}, + {"title": NAME, "unquarantine_label_added_at": "2026-10-15T00:00:00Z"}, + ): + self.assertEqual(self.collect(closed=[pr])["targets"], []) + self.assertEqual(self.collect(blocked=[1])["targets"], []) + receipt = self.collect(closed=[{ + "title": NAME, "quarantine_label_added_at": "2026-10-15T00:00:00Z", + }]) + self.assertEqual(len(receipt["targets"]), 1) + for signals in ( + {"trusted_closed": True, "closed_at": "2026-10-01T00:00:00Z"}, + {"unquarantine_label_added_at": "2026-10-15T00:00:00Z"}, + ): + with self.subTest(signals=signals): + receipt = self.collect(closed=[{ + "title": NAME.replace("SampleTests", "UnrelatedTests"), **signals, + }]) + self.assertEqual(len(receipt["targets"]), 1, receipt) + + def test_type_and_assembly_require_every_test_method(self): + baseline = FIXTURES.class_source( + "Microsoft.AspNetCore.Tests", "SampleTests", + members=["[Fact]\n" + FIXTURES.method_member("One"), + '[Trait("Category", "Sample"), Fact]\n' + FIXTURES.method_member("Two")], + ) + for scope in ("type", "assembly"): + with self.subTest(scope=scope): + quarantined = ( + baseline.replace("public class", FIXTURES.QUARANTINE_ATTRIBUTE + "\npublic class") + if scope == "type" + else FIXTURES.QUARANTINE_ATTRIBUTE.replace("[QuarantinedTest", "[assembly: QuarantinedTest") + + "\n" + baseline + ) + self.fresh_source(baseline, quarantined) + one = NAME.rsplit(".", 1)[0] + ".One" + two = NAME.rsplit(".", 1)[0] + ".Two" + self.assertEqual(self.collect(Provider({1: [(one, "Passed")], 2: [(one, "Passed")]}))["targets"], []) + receipt = self.collect(Provider({ + 1: [(one, "Passed"), (two, "Passed")], + 2: [(one, "Passed"), (two, "Passed")], + })) + self.assertEqual(len(receipt["targets"]), 1, receipt) + + def test_iis_variants_cannot_hide_a_failure_or_merge_unrelated_classes(self): + namespace = "Microsoft.AspNetCore.Server.IIS.FunctionalTests" + baseline = FIXTURES.source().replace("Microsoft.AspNetCore.Tests", namespace) + self.fresh_source( + baseline, baseline.replace("public void", FIXTURES.QUARANTINE_ATTRIBUTE + "\n public void"), + "src/Servers/IIS/IIS/test/Common.LongTests/SampleTests.cs", + ) + normal = NAME.replace("Microsoft.AspNetCore.Tests", namespace) + variant = normal.replace(".IIS.FunctionalTests", ".IIS.NewHandler.FunctionalTests") + receipt = self.collect(Provider({1: [(normal, "Passed"), (variant, "NotExecuted")], + 2: [(normal, "Passed"), (variant, "Passed")]})) + self.assertEqual(len(receipt["targets"]), 1, receipt) + receipt = self.collect(Provider({1: [(normal, "Passed"), (variant, "Failed")], + 2: [(normal, "Passed")]})) + self.assertEqual(receipt["targets"], []) + unrelated = normal.replace(".SampleTests.", ".UnrelatedTests.") + receipt = self.collect(Provider({1: [(unrelated, "Passed")], 2: [(unrelated, "Passed")]})) + self.assertEqual(receipt["targets"], []) + + def test_case_b_collector_does_not_authorize_an_unverified_issue(self): + self.path.write_text(FIXTURES.source(), encoding="utf-8") + FIXTURES.commit(self.root, "Unquarantine", "2026-07-02T00:00:00Z") + for verified in (False, True): + with self.subTest(verified=verified): + receipt = FIXTURES.collect( + self.root, FIXTURES.evidence(), + issue_exists_provider=lambda _: verified, + ) + record = receipt["tests"][NAME] + self.assertEqual(record["originating_case"], "case-b") + self.assertIs(record["case_b_issue_verified"], verified) + self.assertIs(record["case_b_eligible"], verified) + + def test_requarantine_pr_does_not_block_an_unrelated_issue_in_the_same_file(self): + for issue, truncated, expected_count in ((2, False, 1), (1, False, 0), (2, True, 0)): + with self.subTest(issue=issue, truncated=truncated): + receipt = self.collect(requarantine_prs=[{ + "quarantine_entries": [{ + "filename": FIXTURES.TEST_PATH, + "patch_truncated": truncated, + "added_lines": [ + FIXTURES.QUARANTINE_ATTRIBUTE.replace("/issues/1", f"/issues/{issue}") + ], + }], + }]) + self.assertEqual(len(receipt["targets"]), expected_count, receipt) + + def test_validator_rejects_missing_ineligible_and_unbound_evidence(self): + target = self.collect()["targets"][0] + key = PATCHES.MODULE.target_key(target) + removed = {key: {**target, "reference": "1"}} + PATCHES.MODULE.validate_removals(removed, {key: target}, {key: target}) + for evidence in ({}, {key: {**target, "eligible": False}}, + {key: {**target, "issue": 2}}): + with self.assertRaisesRegex(PATCHES.MODULE.ValidationError, "Part 2 eligibility"): + PATCHES.MODULE.validate_removals(removed, {key: target}, evidence) + + +class TrackingIssueTests(unittest.TestCase): + def test_open_and_closed_issues_are_verified_but_prs_are_not(self): + for state, extra, expected in ( + ("open", {}, True), ("closed", {}, True), + ("open", {"pull_request": {}}, False), ("unknown", {}, False), + ): + with self.subTest(state=state, extra=extra): + response = FIXTURES.FakeResponse({ + "number": 68223, "state": state, **extra, + "url": "https://api.github.com/repos/dotnet/aspnetcore/issues/68223", + }) + with mock.patch.object(MODULE.SOURCE.urllib.request, "urlopen", + return_value=response) as urlopen: + self.assertIs(MODULE.SOURCE.github_issue_exists( + "dotnet/aspnetcore", 68223, "test-token"), expected) + self.assertEqual(urlopen.call_args.args[0].full_url, + "https://api.github.com/repos/dotnet/aspnetcore/issues/68223") + + def test_missing_issue_is_not_verified_and_transient_errors_are_retried(self): + error = MODULE.urllib.error.HTTPError("url", 404, "missing", {}, None) + with mock.patch.object(MODULE.SOURCE.urllib.request, "urlopen", side_effect=error): + self.assertFalse(MODULE.SOURCE.github_issue_exists("dotnet/aspnetcore", 1, "token")) + error.close() + with mock.patch.object(MODULE.SOURCE.time, "sleep"), mock.patch.object( + MODULE.SOURCE.urllib.request, "urlopen", side_effect=OSError("unavailable"), + ) as urlopen: + with self.assertRaisesRegex(OSError, "unavailable"): + MODULE.SOURCE.github_issue_exists("dotnet/aspnetcore", 1, "token") + self.assertEqual(urlopen.call_count, 3) + + def test_validator_requires_case_b_verification(self): + record = PATCHES.case_b_record() + target = {"scope": "method", "path": PATCHES.TEST_PATH, "type": PATCHES.TYPE_NAME, + "method": "ReturnsExpectedResponse", "reference": "1", + "operating_systems": record["quarantine_operating_systems"]} + for verified in (False, None): + with self.subTest(verified=verified): + record["case_b_issue_verified"] = verified + with self.assertRaisesRegex(PATCHES.MODULE.ValidationError, "Case B addition"): + PATCHES.MODULE.validate_addition(target, {"tests": {NAME: record}}, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/scripts/test-quarantine/test_validate_pull_request_outputs.py b/.github/workflows/scripts/test-quarantine/test_validate_pull_request_outputs.py index af3eb57ed03b..dadbd40e7a83 100644 --- a/.github/workflows/scripts/test-quarantine/test_validate_pull_request_outputs.py +++ b/.github/workflows/scripts/test-quarantine/test_validate_pull_request_outputs.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import importlib.util +import hashlib import json import os import pathlib @@ -171,6 +172,7 @@ def case_b_record(issue=1, operating_systems=None): "originating_case": "case-b", "case_b_eligible": True, "case_b_issue": issue, + "case_b_issue_verified": True, "source_resolution": { "status": "exact", "path": TEST_PATH, @@ -274,6 +276,7 @@ def validate( agent_output, transport, current_main=None, + unquarantine=None, ): evidence = root / "evidence" evidence.mkdir(exist_ok=True) @@ -282,6 +285,20 @@ def validate( output_path = evidence / "agent-output.json" write_json(eligibility_path, eligibility) write_json(history_path, history) + unquarantine_path = evidence / "unquarantine.json" + if unquarantine is None: + unquarantine = { + **history, + "history_sha256": hashlib.sha256(history_path.read_bytes()).hexdigest(), + "complete": True, + "pipelines": {"84": {"build_count": 1}, "87": {"build_count": 0}}, + "targets": [ + {**target, "eligible": True} + for target in history["targets"] + if target.get("status") == "first-quarantine" + ], + } + write_json(unquarantine_path, unquarantine) write_json(output_path, agent_output) return MODULE.validate_outputs( root, @@ -293,6 +310,7 @@ def validate( REF, commit, current_main=current_main or commit, + unquarantine_path=unquarantine_path, ) @@ -734,6 +752,21 @@ def main(): transport, ) assert result[0]["operation"] == "unquarantine", result + evidence = json.loads((root / "evidence" / "unquarantine.json").read_text()) + for changed, message in ( + ({**evidence, "targets": []}, "Part 2 eligibility"), + ({**evidence, "complete": False}, "incomplete or unbound"), + ({**evidence, "history_sha256": "0" * 64}, "incomplete or unbound"), + ({**evidence, "pipelines": {"84": {}}}, "incomplete or unbound"), + ): + assert_rejected( + lambda changed=changed: validate( + root, commit, eligibility, history, + {"items": [pull_request(branch)]}, transport, + unquarantine=changed, + ), + message, + ) with tempfile.TemporaryDirectory() as directory: root = pathlib.Path(directory) diff --git a/.github/workflows/scripts/test-quarantine/test_workflow_policy.py b/.github/workflows/scripts/test-quarantine/test_workflow_policy.py index 1c62279e792d..ecd3f0079f3f 100644 --- a/.github/workflows/scripts/test-quarantine/test_workflow_policy.py +++ b/.github/workflows/scripts/test-quarantine/test_workflow_policy.py @@ -24,7 +24,7 @@ def test_part_two_analysis_is_mandatory(self): def test_incomplete_analysis_cannot_report_noop(self): expected_clauses = ( - "still query pipelines 84 and 87 and complete the Part 2 candidate analysis before reporting `noop`.", + "still inspect the deterministic collection for pipelines 84 and 87 and complete the Part 2 candidate analysis before reporting `noop`.", "A `noop` message must explicitly summarize the Part 1 Case A and Case B candidate counts", "and the Part 2 pipeline 84 and pipeline 87 analysis results.", "Never use `noop` to disclose that a required phase was skipped.", diff --git a/.github/workflows/scripts/test-quarantine/validate_pull_request_outputs.py b/.github/workflows/scripts/test-quarantine/validate_pull_request_outputs.py index 183c8784017e..511792f8c485 100644 --- a/.github/workflows/scripts/test-quarantine/validate_pull_request_outputs.py +++ b/.github/workflows/scripts/test-quarantine/validate_pull_request_outputs.py @@ -2,6 +2,7 @@ import argparse import collections +import hashlib import importlib.util import json import os @@ -414,6 +415,7 @@ def validate_addition(target, eligibility, issue_items): isinstance(record, dict) and record.get("originating_case") == "case-b" and record.get("case_b_eligible") is True + and record.get("case_b_issue_verified") is True and record.get("case_b_issue") == issue and record.get("current_quarantine_state") == "not-quarantined" and record.get("latest_quarantine_transition") == "removed" @@ -443,7 +445,7 @@ def history_target_map(history): return result -def validate_removals(removed, history_targets): +def validate_removals(removed, history_targets, unquarantine_targets): issues = set() for key, target in removed.items(): reference = target["reference"] @@ -461,6 +463,16 @@ def validate_removals(removed, history_targets): raise ValidationError( f"Unquarantine target is not an exact first quarantine: {key}" ) + evidence = unquarantine_targets.get(key) + if ( + not isinstance(evidence, dict) + or evidence.get("eligible") is not True + or evidence.get("issue") != issue + or evidence.get("introduced_utc") != history_target.get("introduced_utc") + ): + raise ValidationError( + f"Unquarantine target lacks deterministic Part 2 eligibility: {key}" + ) issues.add(issue) if len(issues) != 1: raise ValidationError( @@ -572,6 +584,7 @@ def validate_outputs( ref, commit, current_main=None, + unquarantine_path=None, ): repo_root = pathlib.Path(repo_root).resolve() payload = load_json(agent_output_path) @@ -584,6 +597,18 @@ def validate_outputs( ref, commit, ) + if unquarantine_path is None: + raise ValidationError("Required deterministic Part 2 receipt is missing") + unquarantine = load_json(unquarantine_path) + validate_receipts(unquarantine, history, repository, ref, commit) + if ( + unquarantine.get("complete") is not True + or unquarantine.get("history_sha256") + != hashlib.sha256(pathlib.Path(history_path).read_bytes()).hexdigest() + or set(unquarantine.get("pipelines", {})) != {"84", "87"} + ): + raise ValidationError("Deterministic Part 2 collection is incomplete or unbound") + unquarantine_targets = history_target_map(unquarantine) pull_requests = items(payload, "create_pull_request") issue_items = items(payload, "create_quarantine_issue") if not pull_requests: @@ -843,7 +868,7 @@ def validate_outputs( "Unquarantine pull request attribute lines do not " "match its derived targets" ) - validate_removals(removed, history_targets) + validate_removals(removed, history_targets, unquarantine_targets) summaries.append({ "branch": item["branch"], "operation": "unquarantine", @@ -904,6 +929,7 @@ def main(): args.repository, args.ref, args.commit, + unquarantine_path=evidence_directory / "test-quarantine-unquarantine-eligibility.json", ) except ValidationError as error: raise SystemExit(f"FATAL: {error}") from error diff --git a/.github/workflows/test-quarantine.lock.yml b/.github/workflows/test-quarantine.lock.yml index cc9bb271b9ee..938d33b26ea9 100644 --- a/.github/workflows/test-quarantine.lock.yml +++ b/.github/workflows/test-quarantine.lock.yml @@ -1,4 +1,4 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"3026c5ff93d56002b7c8cf339bba3f73f73fe24e3969b1241728fba4896c0d25","body_hash":"a4a9334057f8f67afbd5657339d4b688985328f9f13211c64cd0c9c7e7d50a31","compiler_version":"v0.92.0","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.96"}} +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"3540216fc5f4b8c31f2e13d437026a70122e1e34f5e533a1638041c2e8d43284","body_hash":"7d5b88284b2435992a26819a60980f8c169ca20f50a3c733cc9979ac59bb6306","compiler_version":"v0.92.0","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.96"}} # gh-aw-manifest: {"version":1,"secrets":["COPILOT_PAT_0","COPILOT_PAT_1","COPILOT_PAT_2","COPILOT_PAT_3","COPILOT_PAT_4","COPILOT_PAT_5","COPILOT_PAT_6","COPILOT_PAT_7","COPILOT_PAT_8","COPILOT_PAT_9","GH_AW_CI_TRIGGER_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"458b269006dcf88e3b5496b6fbecabe4b9a0f954","version":"v0.92.0"}],"skills":[".github/skills/create-kbe"],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.28.57","digest":"sha256:a9861b2fad1d29c586bbbf98840a61056e30e2720d8d9ec2c0def9049566bd8a","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.28.57@sha256:a9861b2fad1d29c586bbbf98840a61056e30e2720d8d9ec2c0def9049566bd8a"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.57","digest":"sha256:f2925ff32dc972a5d8b90a7785b6ca68052efd2575fe896556ac457e22e86dcc","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.57@sha256:f2925ff32dc972a5d8b90a7785b6ca68052efd2575fe896556ac457e22e86dcc"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.28.57","digest":"sha256:be808c16b535ebabd070eebe086fe6bffd5bb86b2e5fe8e5cdad30068eb9c0ac","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.28.57@sha256:be808c16b535ebabd070eebe086fe6bffd5bb86b2e5fe8e5cdad30068eb9c0ac"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.31","digest":"sha256:dbec0f2ddef6adf83b7764019323096e3e5cc0f3886255f6320555b7fe2a7caf","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.31@sha256:dbec0f2ddef6adf83b7764019323096e3e5cc0f3886255f6320555b7fe2a7caf"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:0daa8971fa4732b647150cb6524a6b0804b68d5d24f6f58b5dd1af23bd63fb23","pinned_image":"ghcr.io/github/gh-aw-node@sha256:0daa8971fa4732b647150cb6524a6b0804b68d5d24f6f58b5dd1af23bd63fb23"},{"image":"ghcr.io/github/github-mcp-server:v2.0.2","digest":"sha256:ffced0d76e77428532a2ced185516992d77fd146d69eec2f244e6237d1a97796","pinned_image":"ghcr.io/github/github-mcp-server:v2.0.2@sha256:ffced0d76e77428532a2ced185516992d77fd146d69eec2f244e6237d1a97796"}],"mcp_servers":[{"name":"github","tools":["get_commit","get_file_contents","get_latest_release","get_pull_request","get_pull_request_comments","get_pull_request_diff","get_pull_request_files","get_pull_request_review_comments","get_pull_request_reviews","get_pull_request_status","get_release_by_tag","get_tag","issue_read","list_branches","list_commits","list_issue_types","list_issues","list_pull_requests","list_releases","list_starred_repositories","list_tags","pull_request_read","search_code","search_issues","search_pull_requests","search_repositories"]},{"name":"safeoutputs","tools":["add_comment","add_labels","create_pull_request","create_quarantine_issue","missing_data","missing_tool","noop","report_incomplete"]}],"threat_detection":{"mode":"enabled"}} # This file was automatically generated by gh-aw (v0.92.0). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # @@ -1393,6 +1393,17 @@ on: # f"{eligible_operating_systems_json}\n" # ) # SCRIPT + # - env: + # REQUARANTINE_ISSUES: ${{ steps.requarantine_issues.outputs.requarantine_issue_numbers }} + # REQUARANTINE_PRS: ${{ steps.requarantine_prs.outputs.requarantine_data }} + # id: unquarantine_eligibility + # name: Collect deterministic unquarantine eligibility + # run: | + # python3 .github/workflows/scripts/test-quarantine/collect_unquarantine_eligibility.py \ + # --history "${RUNNER_TEMP}/test-quarantine-requarantine-history.json" \ + # --closed-prs "${RUNNER_TEMP}/test-quarantine-closed-prs.json" \ + # --output "${RUNNER_TEMP}/test-quarantine-unquarantine-eligibility.json" \ + # --repo-root "${GITHUB_WORKSPACE}" # - name: Upload deterministic evidence for safe output validation # uses: actions/upload-artifact@v7.0.2 # with: @@ -1402,6 +1413,7 @@ on: # ${{ runner.temp }}/test-quarantine-part1.json # ${{ runner.temp }}/test-quarantine-case-a-eligibility.json # ${{ runner.temp }}/test-quarantine-requarantine-history.json + # ${{ runner.temp }}/test-quarantine-unquarantine-eligibility.json # retention-days: 1 workflow_dispatch: inputs: @@ -1689,6 +1701,7 @@ jobs: GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_DATA: ${{ needs.pre_activation.outputs.requarantine_data }} GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_HISTORY: ${{ needs.pre_activation.outputs.requarantine_history }} GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_ISSUE_NUMBERS: ${{ needs.pre_activation.outputs.requarantine_issue_numbers }} + GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_UNQUARANTINE_ELIGIBILITY: ${{ needs.pre_activation.outputs.unquarantine_eligibility }} GH_AW_PROMPT_CONTENT_0000: "\n" GH_AW_PROMPT_CONTENT_0001: "\nTools: add_comment(max:10), create_pull_request(max:10), add_labels, missing_tool, missing_data, noop(max:2), create_quarantine_issue\n" GH_AW_PROMPT_CONTENT_0002: "\n" @@ -1733,6 +1746,7 @@ jobs: GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_DATA: ${{ needs.pre_activation.outputs.requarantine_data }} GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_HISTORY: ${{ needs.pre_activation.outputs.requarantine_history }} GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_ISSUE_NUMBERS: ${{ needs.pre_activation.outputs.requarantine_issue_numbers }} + GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_UNQUARANTINE_ELIGIBILITY: ${{ needs.pre_activation.outputs.unquarantine_eligibility }} with: script: | const path = require('path'); @@ -1779,6 +1793,7 @@ jobs: GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_DATA: ${{ needs.pre_activation.outputs.requarantine_data }} GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_HISTORY: ${{ needs.pre_activation.outputs.requarantine_history }} GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_ISSUE_NUMBERS: ${{ needs.pre_activation.outputs.requarantine_issue_numbers }} + GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_UNQUARANTINE_ELIGIBILITY: ${{ needs.pre_activation.outputs.unquarantine_eligibility }} with: script: | const path = require('path'); @@ -1825,7 +1840,8 @@ jobs: GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_PART1_DATA_9: process.env.GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_PART1_DATA_9, GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_DATA: process.env.GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_DATA, GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_HISTORY: process.env.GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_HISTORY, - GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_ISSUE_NUMBERS: process.env.GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_ISSUE_NUMBERS + GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_ISSUE_NUMBERS: process.env.GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_REQUARANTINE_ISSUE_NUMBERS, + GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_UNQUARANTINE_ELIGIBILITY: process.env.GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_UNQUARANTINE_ELIGIBILITY } }); - name: Validate prompt placeholders @@ -3617,6 +3633,8 @@ jobs: setup-trace-id: ${{ steps.setup.outputs.trace-id }} source_b_build_ids: ${{ steps.source_b_prs.outputs.source_b_build_ids }} source_b_prs_result: ${{ steps.source_b_prs.outcome }} + unquarantine_eligibility: ${{ steps.unquarantine_eligibility.outputs.unquarantine_eligibility }} + unquarantine_eligibility_result: ${{ steps.unquarantine_eligibility.outcome }} steps: - name: Setup Scripts id: setup @@ -4970,6 +4988,17 @@ jobs: env: CLOSED_QUARANTINE_PRS: ${{ steps.closed_quarantine_prs.outputs.closed_quarantine_prs }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Collect deterministic unquarantine eligibility + id: unquarantine_eligibility + run: | + python3 .github/workflows/scripts/test-quarantine/collect_unquarantine_eligibility.py \ + --history "${RUNNER_TEMP}/test-quarantine-requarantine-history.json" \ + --closed-prs "${RUNNER_TEMP}/test-quarantine-closed-prs.json" \ + --output "${RUNNER_TEMP}/test-quarantine-unquarantine-eligibility.json" \ + --repo-root "${GITHUB_WORKSPACE}" + env: + REQUARANTINE_ISSUES: ${{ steps.requarantine_issues.outputs.requarantine_issue_numbers }} + REQUARANTINE_PRS: ${{ steps.requarantine_prs.outputs.requarantine_data }} - name: Upload deterministic evidence for safe output validation uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: @@ -4979,6 +5008,7 @@ jobs: ${{ runner.temp }}/test-quarantine-part1.json ${{ runner.temp }}/test-quarantine-case-a-eligibility.json ${{ runner.temp }}/test-quarantine-requarantine-history.json + ${{ runner.temp }}/test-quarantine-unquarantine-eligibility.json retention-days: ${{ vars.GH_AW_DEFAULT_ARTIFACT_RETENTION_DAYS || '1' }} safe_outputs: diff --git a/.github/workflows/test-quarantine.md b/.github/workflows/test-quarantine.md index bb25c0a0960f..2d9de5c4f164 100644 --- a/.github/workflows/test-quarantine.md +++ b/.github/workflows/test-quarantine.md @@ -1342,6 +1342,18 @@ on: ) SCRIPT + - name: Collect deterministic unquarantine eligibility + id: unquarantine_eligibility + env: + REQUARANTINE_ISSUES: ${{ steps.requarantine_issues.outputs.requarantine_issue_numbers }} + REQUARANTINE_PRS: ${{ steps.requarantine_prs.outputs.requarantine_data }} + run: | + python3 .github/workflows/scripts/test-quarantine/collect_unquarantine_eligibility.py \ + --history "${RUNNER_TEMP}/test-quarantine-requarantine-history.json" \ + --closed-prs "${RUNNER_TEMP}/test-quarantine-closed-prs.json" \ + --output "${RUNNER_TEMP}/test-quarantine-unquarantine-eligibility.json" \ + --repo-root "${GITHUB_WORKSPACE}" + - name: Upload deterministic evidence for safe output validation uses: actions/upload-artifact@v7.0.2 with: @@ -1350,6 +1362,7 @@ on: ${{ runner.temp }}/test-quarantine-part1.json ${{ runner.temp }}/test-quarantine-case-a-eligibility.json ${{ runner.temp }}/test-quarantine-requarantine-history.json + ${{ runner.temp }}/test-quarantine-unquarantine-eligibility.json retention-days: 1 if-no-files-found: error @@ -1364,6 +1377,7 @@ jobs: eligible_test_names: ${{ steps.case_a_eligibility.outputs.eligible_test_names }} eligible_case_b_test_names: ${{ steps.case_a_eligibility.outputs.eligible_case_b_test_names }} eligible_operating_systems: ${{ steps.case_a_eligibility.outputs.eligible_operating_systems }} + unquarantine_eligibility: ${{ steps.unquarantine_eligibility.outputs.unquarantine_eligibility }} # part1_data is chunked across fixed outputs to stay under the 131072-byte MAX_ARG_STRLEN # per-env-var limit (see write_part1_chunks above); the prompt concatenates them back. part1_data_0: ${{ steps.part1_aggregate.outputs.part1_data_0 }} @@ -2141,7 +2155,7 @@ You are an automated workflow that manages flaky test quarantine in the dotnet/a **Both tasks are mandatory analysis phases on every run.** An empty Case A/Case B eligibility list completes only Part 1; it does not make Part 2 optional. You must -still query pipelines 84 and 87 and complete the Part 2 candidate analysis before +still inspect the deterministic collection for pipelines 84 and 87 and complete the Part 2 candidate analysis before reporting `noop`. Priority and budget rules may defer an identified unquarantine write after the analysis is complete, but they never permit skipping Part 2. If required data, tools, time, or turn budget prevent either analysis phase from @@ -2288,7 +2302,7 @@ All of the following are true: The `refs/remotes/origin/main --first-parent` walk makes this the actual main-branch landing commit and timestamp, not an earlier topic-branch commit. The fully qualified ref avoids ambiguity with a local branch named `origin/main`. The `-p` flag prints each commit's patch inline using the file's **historical** path at that commit, so it works correctly across renames — do **not** issue a separate `git show -- `, which would return an empty diff for any commit from before a rename. Walk the matching commits from **newest to oldest**, inspecting the inline patch of each, and stop at the most recent commit whose patch **adds or removes the exact `[QuarantinedTest]` method/class/assembly target or `[QuarantinedTestData]` row target** (ignore commits that only touch other targets in the same file). If that commit removed the exact target, Case B applies; if it added the target, the test case is currently/most-recently quarantined and Case B does not apply. - It has **at least one distinct-build failure incident remaining after the mandatory evidence cutoff above**. The history-derived cutoff includes the unquarantine landing time and any later relevant fix, and the final cutoff also includes any later trusted prior-attempt decision. Failures from before that cutoff do not count — they are stale evidence from before the test was repaired/unquarantined or before a maintainer rejected an earlier attempt. If no incidents remain, do not re-quarantine and do not evaluate the test under Case A. - **Respect any prior-attempt cutoff (see the "Check for recently closed (not merged) PRs" rule).** If a trusted contributor already closed a recent re-quarantine attempt for this same test, only failures whose build `startedUtc` is strictly after that PR's `closed_at` count toward re-quarantining. If no failure post-dates that cutoff, do **not** re-quarantine this run — defer until there is fresh flakiness after the maintainer's decision. -- **Reuse the original tracking issue — do not create a new one.** Determine the issue **directly from the exact `[QuarantinedTest]` or `[QuarantinedTestData]` line removed by the unquarantine commit's patch**. Its numeric issue URL names the original tracking issue to reuse in Step 3.1. Do **not** rely only on issue-title searches. Confirm the issue exists (it may be open or closed) before reusing it. If the removed attribute has no valid numeric issue URL, fail closed and skip automated re-quarantine for this test case. +- **Reuse the original tracking issue — do not create a new one.** Determine the issue **directly from the exact `[QuarantinedTest]` or `[QuarantinedTestData]` line removed by the unquarantine commit's patch**. Its numeric issue URL names the original tracking issue to reuse in Step 3.1. Do **not** rely only on issue-title searches. The trusted pre-activation collector confirms that this exact number is an existing issue, not a PR, using the authenticated GitHub API; it sets `case_b_issue_verified` before including the test in the Case B eligible list. This receipt is this run's existence confirmation, including for closed issues. Do not repeat the lookup through integrity-filtered MCP tools or agent HTTP. The safe-output validator requires the verified receipt. If the removed attribute has no valid numeric issue URL or verification fails, the test is not eligible. **Case A identity boundary** @@ -2307,15 +2321,32 @@ candidates for later — they will be actioned in Part 3 after budget planning. ### Step 2.1 — Gather passing test data from the quarantined pipeline and components-e2e pipeline +**This collection is already complete before the agent starts.** The trusted +`collect_unquarantine_eligibility.py` step fully paginates both pipelines and +their test results, resolves exact current source targets, and applies the +age, history, run-evidence, and suppression gates below. Read this compact +receipt instead of making Azure DevOps HTTP calls: + +```json +${{ needs.pre_activation.outputs.unquarantine_eligibility }} +``` + +Require `complete: true` and entries for both pipelines `84` and `87`; missing or +malformed evidence requires `report_incomplete`, never `noop`. An empty `targets` +array with complete collection is a valid result, not a skipped phase. Summarize +both pipelines' build/test counts and the candidate count. Only receipt targets +with `eligible: true` may be removed; agent checks can disqualify but cannot add +candidates. The safe-output validator enforces the receipt's run identity, +history hash, and exact target/issue binding for removals. + +The following describes the collector's data contract, not additional agent work. + Query two pipelines in the `dnceng-public` Azure DevOps organization, `public` project: - **aspnetcore-quarantined-tests** (definition ID **84**) — runs only quarantined tests - **components-e2e** (definition ID **87**) — runs both quarantined and non-quarantined tests -Follow the **Critical HTTP access rule** above. Use standalone -`python3`/`urllib.request` tool calls for these requests. If a tool call is -denied before execution, correct the command and retry; do not treat the -denial as evidence that Azure DevOps is unavailable. +These requests run in trusted pre-activation code; do not repeat them in the agent. For each pipeline, query only builds on the **main branch**: @@ -2343,7 +2374,7 @@ A test is a candidate for unquarantining if ALL of the following are true: - It does **not** have a suspiciously low total count — it appeared in at least 66% of the builds **for the pipeline that actually runs it**. Since a quarantined test only runs in one of the two pipelines (84 or 87), compare its build count against the total builds for that specific pipeline, not the combined total across both pipelines. - It is **not** `AlwaysTestTests.SuccessfulTests.GuaranteedQuarantinedTest` (this test must always stay quarantined) - It is an **individual test case**, not a work item (exclude names ending in `.WorkItemExecution`) -- The exact `[QuarantinedTest]` or `[QuarantinedTestData]` target has been present for **at least 60 days**. To check this, use `git log -G` with a regex matching the issue URL from the attribute to find the commit that introduced it (pass `--follow` so renames of the file are traversed): +- The exact `[QuarantinedTest]` or `[QuarantinedTestData]` target has been present for **at least 60 days**. The receipt's `introduced_utc` comes from exact-target first-parent history, including file moves and issue-URL-only changes. Optional source inspection may disqualify a target but cannot replace that proof: ``` git log --follow --format="%H %ai" -1 -G 'QuarantinedTest.*{ISSUE_NUMBER}' -- {FILE_PATH} ``` @@ -2458,7 +2489,7 @@ Group the unquarantine candidates by their associated GitHub issue number. Extra - **`[QuarantinedTest]` and `[QuarantinedTestData]` attributes must reference a GitHub issue URL that *ultimately resolves* to a numeric issue number** (e.g., `https://github.com/dotnet/aspnetcore/issues/12345`). For a newly created issue (Case A) you write the `#{temporary_id}` token while editing; the framework resolves it before the PR is opened. Never write placeholder strings, descriptive text, or any other non-numeric identifier — the only permitted non-numeric value is the required `#{temporary_id}` token. - **For a newly created quarantine issue (Case A), you MUST write the `#{temporary_id}` reference — never a literal numeric issue number.** Here `#{temporary_id}` means a literal `#` immediately followed by the **exact** `temporary_id` string you passed to the corresponding `create_quarantine_issue` call (do **not** add any extra `aw_` prefix — the `temporary_id` already includes it). The issue's real number is assigned by the framework *after* the agent finishes, so it is impossible for you to know it while editing code. For example, if you called `create_quarantine_issue(temporary_id: "aw_http2ign", ...)`, write `[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/#aw_http2ign")]`. The framework resolves `#aw_http2ign` to the real numeric URL before opening the PR, so the final committed code will contain the numeric URL. - **The `temporary_id` must be exactly the literal prefix `aw_` followed by a *slug* of 3 to 12 characters from `[A-Za-z0-9_]`** — i.e. it must match `^aw_[A-Za-z0-9_]{3,12}$` (the framework's exact rule is "'aw_' followed by 3 to 12 alphanumeric or underscore characters"). The **3–12 count applies only to the slug portion after `aw_`**, so the full token is 6–15 characters long (e.g. `aw_http2ign` = slug `http2ign`, 8 chars). This limit is enforced by the framework. If you pass a `temporary_id` whose slug is too long or otherwise malformed, the framework **silently discards it, auto-generates a *different* id, and registers your new issue under that auto-generated id** — so the `#{temporary_id}` token you wrote into the code no longer matches any registered id, is treated as a malformed reference, and is **committed verbatim as a broken placeholder**. Keep the slug short and abbreviate. The identical `temporary_id` must be used for the `create_quarantine_issue` call, the `add_comment` `item_number`, the `#{temporary_id}` in the attribute, and the `Associated issue: #{temporary_id}` in the PR body. - - **A literal numeric issue URL is allowed ONLY when reusing an already-existing tracking issue (Case B re-quarantine), and only after you have confirmed in this run that the issue exists and is the original tracking issue for this test.** The authoritative way to identify it is the issue number in the `[QuarantinedTest("…/issues/N")]` line removed by the unquarantine commit (see Case B in Step 1.2); that issue is correct to reuse whether it is labeled `test-failure`, `Known Build Error`, or otherwise. The reused issue may be **closed** — a prior unquarantine PR (Step 3.2) can auto-close the tracking issue on merge, and re-quarantine still reuses that original issue. Never write a literal number for an issue you created (or will create) in this run. + - **A literal numeric issue URL is allowed ONLY when reusing an already-existing tracking issue (Case B re-quarantine), and only after the trusted pre-activation receipt confirms in this run that the issue exists and is the original tracking issue for this test.** The authoritative way to identify it is the issue number in the `[QuarantinedTest("…/issues/N")]` line removed by the unquarantine commit (see Case B in Step 1.2); that issue is correct to reuse whether it is labeled `test-failure`, `Known Build Error`, or otherwise. The reused issue may be **closed** — a prior unquarantine PR (Step 3.2) can auto-close the tracking issue on merge, and re-quarantine still reuses that original issue. Never write a literal number for an issue you created (or will create) in this run. - **Never** use placeholder text like `TODO`, `TBD`, or descriptive strings. - **Never guess, predict, probe for, or reverse-engineer a GitHub issue number.** Do not try to discover "what number my new issue will get" by listing issues, incrementing the latest issue/PR number, or probing candidate issue numbers via the issue/PR APIs to find an "unused" one. New-issue numbers are assigned asynchronously by the framework and are unknowable while you are editing code — the only correct way to reference a newly created issue is the `#{temporary_id}` token (see above). (Looking up a **known, specific** issue number to confirm the original tracking issue for Case B reuse — identified from the unquarantine commit's removed `[QuarantinedTest]` attribute, whether labeled `test-failure` or `Known Build Error` — is fine — what is forbidden is probing for, or guessing, the number of an issue you are creating in this run.) - **Treat any "not found", "filtered", "lower integrity", "not accessible", "integrity policy", or permission-denied response from an issue or PR lookup as access-denied — NOT as evidence that an issue number is free, unused, or available.** Such responses tell you nothing about whether a number is allocated. Never conclude that a probed number is "available", and never write a probed or inferred number into code. @@ -2600,7 +2631,7 @@ For each quarantine/re-quarantine candidate, in priority order (Case B re-quaran Before you call `create_pull_request` for any quarantine or re-quarantine, re-read the exact diff you are about to submit and verify **every** added `[QuarantinedTest(...)]` and `[QuarantinedTestData(...)]` line: 1. If `` is for an issue you created in this run, it **must** be `#{temporary_id}` — a literal `#` followed by the *exact* `temporary_id` you passed to a `create_quarantine_issue` call in this same run (e.g., `#aw_http2ign`; do not add an extra `aw_` prefix). A bare number here is a bug — fix it before submitting. -2. If `` is a literal number, it **must** be the original tracking issue for this test, confirmed in this run (Case B reuse only; identified from the issue URL removed by the unquarantine commit, and it may be labeled `test-failure` or `Known Build Error`; the issue may be closed). If you cannot confirm that, do not submit the PR. +2. If `` is a literal number, it **must** be the original tracking issue for this test, confirmed in this run by the trusted `case_b_issue_verified` receipt (Case B reuse only; identified from the issue URL removed by the unquarantine commit, and it may be labeled `test-failure` or `Known Build Error`; the issue may be closed). The deterministic eligible Case B list includes only verified issues; use that confirmation without another MCP or agent HTTP lookup. If the receipt does not confirm it, do not submit the PR. 3. `` must never be a guessed, probed, or inferred number — for example a number guessed by incrementing the latest issue/PR, probed for to find an "unused" one, or inferred from a "not found"/"filtered"/access-denied lookup response — nor a `TODO`/`TBD`/placeholder. Factual lookups *are* allowed: confirming that a **known, specific** issue exists (Case B reuse — e.g. the issue named in the removed `[QuarantinedTest]` attribute), or discovering the original tracking issue from the unquarantine commit's diff, is fine. What is forbidden is treating any lookup result as license to invent, pick, or guess a number. If any added attribute fails these checks, **do not create the PR** — correct the reference first, or skip the candidate entirely. It is far better to skip a quarantine than to commit a wrong issue link. From 9434661d5c42d908715ee99e28130acc723263d9 Mon Sep 17 00:00:00 2001 From: William Godbe Date: Wed, 28 Oct 2026 15:16:40 -0700 Subject: [PATCH 2/2] Fix inherited unquarantine eligibility and suppression matching Resolve inherited test overrides to effective method identities and exclude abstract assembly runners. Honor method-wide and declaring-method suppressions without conflating distinct theory rows. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../scripts/test-quarantine/README.md | 4 + .../collect_case_a_eligibility.py | 4 + .../collect_unquarantine_eligibility.py | 71 +++++++-- .../test_collect_unquarantine_eligibility.py | 135 ++++++++++++++++++ 4 files changed, 200 insertions(+), 14 deletions(-) diff --git a/.github/workflows/scripts/test-quarantine/README.md b/.github/workflows/scripts/test-quarantine/README.md index 00adde9e2ef6..1d83ca6f4320 100644 --- a/.github/workflows/scripts/test-quarantine/README.md +++ b/.github/workflows/scripts/test-quarantine/README.md @@ -63,6 +63,10 @@ issue. These correspond to Case A and Case B in re-quarantine blocklist match. Unresolved rows fail closed. Ambiguous re-quarantine PR ownership conservatively excludes targets sharing the issue in that file; a truncated diff excludes the whole file. + Class/assembly coverage uses effective resolved overrides, including inherited + test attributes; abstract types are not independent assembly runners. + Suppressions recognize runtime and declaring method identities, and method-wide + references block data rows without matching a different argument row. The compact receipt records complete collection, pipeline counts, eligible source targets, and the history receipt's SHA-256. Missing pages or malformed responses abort pre-activation; they never become an empty candidate list. diff --git a/.github/workflows/scripts/test-quarantine/collect_case_a_eligibility.py b/.github/workflows/scripts/test-quarantine/collect_case_a_eligibility.py index ec13665b248d..63e2cdd77989 100644 --- a/.github/workflows/scripts/test-quarantine/collect_case_a_eligibility.py +++ b/.github/workflows/scripts/test-quarantine/collect_case_a_eligibility.py @@ -536,12 +536,16 @@ def build_source_index(root): ) declaration_line = clean.count("\n", 0, position) attributes = attribute_block(lines, declaration_line) + prefix_start = max( + clean.rfind(delimiter, 0, position) for delimiter in (";", "{", "}", "]") + ) + 1 quarantined = has_quarantine_attribute(attributes) if quarantined: type_quarantines[(str(project_root), type_name)] = True type_index.setdefault(type_name, []).append({ "type": type_name, "base": entry[5], + "is_abstract": re.search(r"\babstract\b", clean[prefix_start:position]) is not None, "path": relative_path, "project_root": str(project_root), "quarantined": quarantined, diff --git a/.github/workflows/scripts/test-quarantine/collect_unquarantine_eligibility.py b/.github/workflows/scripts/test-quarantine/collect_unquarantine_eligibility.py index 8e2eb6d46ce3..b2c18c82ff64 100644 --- a/.github/workflows/scripts/test-quarantine/collect_unquarantine_eligibility.py +++ b/.github/workflows/scripts/test-quarantine/collect_unquarantine_eligibility.py @@ -160,43 +160,86 @@ def matches(target, source): def expected_methods(root, target, index): if target["scope"] in ("method", "data"): return {(target["type"], target["method"])} - owners = set() if target["scope"] == "type": - current_type = target["type"] + runners = {target["type"]} + else: + runners = { + name for name, declarations in index["types"].items() + if any(item["project_root"] == target["project_root"] for item in declarations) + and not any( + item["project_root"] == target["project_root"] and item["is_abstract"] + for item in declarations + ) + } + methods = set() + for runner in runners: + owners = set() + current_type = runner + proven = True while current_type not in owners: owners.add(current_type) logical = SOURCE.logical_type(index, current_type, target["project_root"]) if logical["status"] != "exact": - return set() + proven = False + break if not logical["base"]: break base = SOURCE.resolve_base_type( index, current_type, logical["base"], target["project_root"], ) if base["status"] != "exact": - return set() + proven = False + break current_type = base["type"] else: + proven = False + names = { + name for name, declarations in index["methods"].items() + if any( + item["project_root"] == target["project_root"] + and item["is_test"] and item["type"] in owners + for item in declarations + ) + } + if not names: + continue + if not proven: return set() - methods = set() - for name, declarations in index["methods"].items(): - methods.update( - (item["type"], name) for item in declarations - if item["project_root"] == target["project_root"] and item["is_test"] - and (target["scope"] == "assembly" or item["type"] in owners) - ) + for name in names: + source = SOURCE.resolve_source(root, f"{runner}.{name}", index) + if source["status"] == "unmatched-data-row" and len(source["matches"]) == 1: + # Enumerating a theory's method does not select a parameter row. + source = source["matches"][0] + elif source["status"] != "exact": + return set() + methods.add((source.get("declaring_type") or source["type"], source["method"])) return methods def suppressed(target, names, closed_prs, now): identifiers = set(names) - if target["scope"] == "method": - identifiers.update(SOURCE.split_test_name(name)[0] for name in names) + method_patterns = [] + if target["scope"] in ("method", "data"): + declaring_method = f"{target['type']}.{target['method']}" + methods = {SOURCE.split_test_name(name)[0] for name in names} | {declaring_method} + if target["scope"] == "data": + identifiers.update( + declaring_method + name[len(SOURCE.split_test_name(name)[0]):] + for name in names + ) + for method in methods: + pattern = rf"(?